diff --git a/AUTHORS b/AUTHORS index e84bf8d..9f1e5d6 100644 --- a/AUTHORS +++ b/AUTHORS
@@ -15,6 +15,7 @@ Aaryaman Vasishta <jem456.vasishta@gmail.com> Abhijeet Kandalkar <abhijeet.k@samsung.com> Abhishek Agarwal <abhishek.a21@samsung.com> +Abhishek Kanike <abhishek.ka@samsung.com> Abhishek Singh <abhi.rathore@samsung.com> Adam Bonner <abonner-chromium@solscope.com> Adam Roben <adam@github.com> @@ -23,13 +24,13 @@ Adenilson Cavalcanti <a.cavalcanti@samsung.com> Aditya Bhargava <heuristicist@gmail.com> Adrian Belgun <adrian.belgun@intel.com> -Abhishek Kanike <abhishek.ka@samsung.com> Ahmet Emir Ercin <ahmetemiremir@gmail.com> -Ajay Berwal <ajay.berwal@samsung.com> Ajay Berwal <a.berwal@samsung.com> +Ajay Berwal <ajay.berwal@samsung.com> Ajith Kumar V <ajith.v@samsung.com> Aku Kotkavuo <a.kotkavuo@partner.samsung.com> Aldo Culquicondor <alculquicondor@gmail.com> +Aleksandar Stojiljkovic <aleksandar.stojiljkovic@intel.com> Alex Gabriel <minilogo@gmail.com> Alex Gartrell <agartrell@cmu.edu> Alex Henrie <alexhenrie24@gmail.com> @@ -57,8 +58,10 @@ Amruth Raj <ckqr36@motorola.com> Anand Ratn <anand.ratn@samsung.com> Anastasios Cassiotis <tom.cassiotis@gmail.com> +anatoly techtonik <techtonik@gmail.com> Ancil George <ancilgeorge@samsung.com> Andra Paraschiv <andra.paraschiv@intel.com> +Andrei Borza <andrei.borza@gmail.com> Andrei Parvu <andrei.prv@gmail.com> Andrei Parvu <parvu@adobe.com> Andrew Boyarshin <andrew.boyarshin@gmail.com> @@ -126,6 +129,7 @@ Calvin Mei <calvimei@amazon.com> Cameron Gutman <aicommander@gmail.com> Catalin Badea <badea@adobe.com> +Cathie Chen <cathiechen@tencent.com> Cem Kocagil <cem.kocagil@gmail.com> Chakshu Ahuja <chakshu.a@samsung.com> Chamal De Silva <chamalsl@yahoo.com> @@ -133,20 +137,22 @@ Chandra Shekar Vallala <brk376@motorola.com> Chandramouli Sanchi <cm.sanchi@samsung.com> Chang Shu <c.shu@samsung.com> -ChangSeok Oh <shivamidow@gmail.com> Changbin Shao <changbin.shao@intel.com> Changjun Yang <changjun.yang@intel.com> +ChangSeok Oh <shivamidow@gmail.com> Changwan Hong <cwhong893@gmail.com> Changyeon Kim <cyzero.kim@samsung.com> +Chanho Park <parkch98@gmail.com> Chansik Yun <chansik.yun@gmail.com> Chaobin Zhang <zhchbin@gmail.com> +Charles Vaughn <cvaughn@gmail.com> Choongwoo Han <cwhan.tunz@gmail.com> Chris Greene <cwgreene@amazon.com> Chris Harrelson <chrishtr@gmail.com> Chris Nardi <hichris123@gmail.com> +Chris Szurgot <szurgotc@amazon.com> Chris Tserng <tserng@amazon.com> Chris Vasselli <clindsay@gmail.com> -Chris Szurgot <szurgotc@amazon.com> Christophe Dumez <ch.dumez@samsung.com> Christopher Dale <chrelad@gmail.com> Claudio DeSouza <claudiomdsjr@gmail.com> @@ -186,6 +192,7 @@ David Spellman <dspell@amazon.com> Dax Kelson <dkelson@gurulabs.com> Debashish Samantaray <d.samantaray@samsung.com> +Debug Wang <debugwang@tencent.com> Deepak Dilip Borade <deepak.db@samsung.com> Deepak Mittal <deepak.m1@samsung.com> Deepak Singla <deepak.s@samsung.com> @@ -210,12 +217,13 @@ Douglas F. Turner <doug.turner@gmail.com> Dustin Doloff <doloffd@amazon.com> Ebrahim Byagowi <ebraminio@gmail.com> +Eden Wang <nedenwang@tencent.com> Eduardo Lima (Etrunko) <eblima@gmail.com> Eduardo Lima (Etrunko) <eduardo.lima@intel.com> Edward Baker <edward.baker@intel.com> Edward Crossman <tedoc2000@gmail.com> -Eero Häkkinen <eero.hakkinen@intel.com> Eero Häkkinen <e.hakkinen@samsung.com> +Eero Häkkinen <eero.hakkinen@intel.com> Egor Starkov <egor.starkov@samsung.com> Ehsan Akhgari <ehsan.akhgari@gmail.com> Elan Ruusamäe <elan.ruusamae@gmail.com> @@ -224,6 +232,7 @@ Erik Hill <erikghill@gmail.com> Erik Sjölund <erik.sjolund@gmail.com> Eriq Augustine <eriq.augustine@gmail.com> +Ernesto Mudu <ernesto.mudu@gmail.com> Etienne Laurin <etienne@atnnn.com> Evan Peterson <evan.peterson.ep@gmail.com> Evan Wallace <evan.exe@gmail.com> @@ -253,6 +262,7 @@ Gergely Nagy <ngg@ngg.hu> Getulio Sánchez <valentin2507@gmail.com> Gideon Pyzer <gjpyzer@gmail.com> +Girish Kumar M <mck.giri@samsung.com> Gitanshu Mehndiratta <g.mehndiratt@samsung.com> Giuseppe Iuculano <giuseppe@iuculano.it> Glenn Adams <glenn@chromium.org> @@ -260,8 +270,8 @@ Gordana Cmiljanovic <gordana.cmiljanovic@imgtec.com> Goutham Jagannatha <wrm364@motorola.com> Graham Yoakum <gyoakum@skobalt.com> -Gregory Davis <gpdavis.chromium@gmail.com> Greg Visser <gregvis@gmail.com> +Gregory Davis <gpdavis.chromium@gmail.com> Grzegorz Czajkowski <g.czajkowski@samsung.com> Guangzhen Li <guangzhen.li@intel.com> Gurpreet Kaur <k.gurpreet@samsung.com> @@ -297,11 +307,11 @@ Hwanseung Lee <hs1217.lee@gmail.com> Hwanseung Lee <hs1217.lee@samsung.com> Hyemi Shin <hyemi.sin@samsung.com> +Hyungchan Kim <inlinechan@gmail.com> +Hyungwook Lee <hyungwook.lee@navercorp.com> +Hyungwook Lee <withlhw@gmail.com> Hyunjune Kim <hyunjune.kim@samsung.com> Hyunki Baik <hyunki.baik@samsung.com> -Hyungchan Kim <inlinechan@gmail.com> -Hyungwook Lee <withlhw@gmail.com> -Hyungwook Lee <hyungwook.lee@navercorp.com> Ian Cullinan <cullinan@amazon.com> Ian Scott <ian.scott@arteris.com> Ibrar Ahmed <ibrar.ahmad@gmail.com> @@ -333,6 +343,7 @@ James Vega <vega.james@gmail.com> James Wei <james.wei@intel.com> James Willcox <jwillcox@litl.com> +Jan Rucka <ruckajan10@gmail.com> Jan Sauer <jan@jansauer.de> Janwar Dinata <j.dinata@gmail.com> Jared Shumway <jaredshumway94@gmail.com> @@ -357,8 +368,8 @@ Jianneng Zhong <muzuiget@gmail.com> Jiawei Shao <jiawei.shao@intel.com> Jie Chen <jie.a.chen@intel.com> -Jihoon Chung <jihoon@gmail.com> Jihoon Chung <j.c@navercorp.com> +Jihoon Chung <jihoon@gmail.com> Jihun Brent Kim <devgrapher@gmail.com> Jin Yang <jin.a.yang@intel.com> Jincheol Jo <jincheol.jo@navercorp.com> @@ -368,9 +379,10 @@ Jinkyu Seong <jinkyu.seong@lge.com> Jinsong Fan <fanjinsong@sogou-inc.com> Jinwoo Song <jinwoo7.song@samsung.com> +Jinyoung Hur <hurims@gmail.com> Jitendra Kumar Sahoo <jitendra.ks@samsung.com> -Joachim Bauch <mail@joachim-bauch.de> Joachim Bauch <jbauch@webrtc.org> +Joachim Bauch <mail@joachim-bauch.de> Joe Knoll <joe.knoll@workday.com> Joe Thomas <mhx348@motorola.com> Joel Stanley <joel@jms.id.au> @@ -388,8 +400,8 @@ Jorge Villatoro <jorge@tomatocannon.com> Joseph Gentle <josephg@gmail.com> Joseph Lolak <joseph.lolak@samsung.com> -Josh Triplett <josh@joshtriplett.org> Josh Triplett <josh.triplett@intel.com> +Josh Triplett <josh@joshtriplett.org> Joshua Lock <joshua.lock@intel.com> Joshua Roesslein <jroesslein@gmail.com> Josué Ratelle <jorat1346@gmail.com> @@ -417,12 +429,13 @@ Karan Thakkar <karanjthakkar@gmail.com> Kartikey Bhatt <kartikey@amazon.com> Kaspar Brand <googlecontrib@velox.ch> -Kaustubh Atrawalkar <kaustubh.ra@gmail.com> Kaustubh Atrawalkar <kaustubh.a@samsung.com> +Kaustubh Atrawalkar <kaustubh.ra@gmail.com> Ke He <ke.he@intel.com> Keene Pan <keenepan@linpus.com> Keith Chen <keitchen@amazon.com> Kenneth Rohde Christiansen <kenneth.r.christiansen@intel.com> +Kenneth Strickland <ken.strickland@gmail.com> Kenneth Zhou <knthzh@gmail.com> Keonho Kim <keonho07.kim@samsung.com> Ketan Goyal <ketan.goyal@samsung.com> @@ -431,12 +444,12 @@ Kevin M. McCormick <mckev@amazon.com> Khasim Syed Mohammed <khasim.mohammed@linaro.org> Kihong Kwon <kihong.kwon@samsung.com> +Kihwang Kim <pwangkk@gmail.com> Kim Christensen <kimworking@gmail.com> Kingshuk Jana <kingshuk.j@samsung.com> Kirill Bobyrev <kirillbobyrev@gmail.com> Kirill Ovchinnikov <kirill.ovchinn@gmail.com> Kirk Shoop <kirk.shoop@microsoft.com> -Kihwang Kim <pwangkk@gmail.com> Klemen Forstnerič <klemen.forstneric@gmail.com> Kodam Nagaraju <k2.nagaraju@samsung.com> Konrad Dzwinel <kdzwinel@gmail.com> @@ -448,9 +461,12 @@ Kushal Pisavadia <kushi.p@gmail.com> Kwangho Shin <k_h.shin@samsung.com> Kyle Nahrgang <kpn24@drexel.edu> +Kyle Plumadore <kyle.plumadore@amd.com> Kyounga Ra <kyounga.ra@gmail.com> -Kyungtae Kim <ktf.kim@samsung.com> +Kyoungdeok Kwon <kkd927@gmail.com> Kyung Yeol Kim <chitacan@gmail.com> +Kyungtae Kim <ktf.kim@samsung.com> +Kyungyoung Heo <bbvch13531@gmail.com> Laszlo Gombos <l.gombos@samsung.com> Laszlo Radanyi <bekkra@gmail.com> Lauren Yeun Kim <lauren.yeun.kim@gmail.com> @@ -487,10 +503,11 @@ Manuel Braun <thembrown@gmail.com> Mao Yujie <maojie0924@gmail.com> Mao Yujie <yujie.mao@intel.com> +Marc des Garets <marc.desgarets@googlemail.com> +Marcin Wiacek <marcin@mwiacek.com> Marco Rodrigues <gothicx@gmail.com> Mario Pistrich <m.pistrich@gmail.com> Mario Sanchez Prada <mario.prada@samsung.com> -Marcin Wiacek <marcin@mwiacek.com> Mariusz Mlynski <marius.mlynski@gmail.com> Mark Hahnenberg <mhahnenb@andrew.cmu.edu> Mark Seaborn <mrs@mythic-beasts.com> @@ -536,11 +553,12 @@ Milton Chiang <milton.chiang@mediatek.com> Minggang Wang <minggang.wang@intel.com> Mingmin Xie <melvinxie@gmail.com> +Minjeong Lee <apenr1234@gmail.com> Minseok Koo <kei98301@gmail.com> Minsoo Max Koo <msu.koo@samsung.com> Miran Karic <miran.karic@imgtec.com> -Mirela Budaes <mbudaes@gmail.com> Mirela Budaes <mbudaes@adobe.com> +Mirela Budaes <mbudaes@gmail.com> Mitchell Rosen <mitchellwrosen@chromium.org> Miyoung Shin <myid.shin@samsung.com> Mohamed I. Hammad <ibraaaa@gmail.com> @@ -551,6 +569,7 @@ Mohit Bhalla <bhallam@amazon.com> Mrunal Kapade <mrunal.kapade@intel.com> Myles C. Maxfield <mymax@amazon.com> +Myung-jong Kim <mjkim610@gmail.com> Nagarajan Narayanan <nagarajan.n@samsung.com> Nagarjuna Atluri <nagarjuna.a@samsung.com> Naiem Shaik <naiem.shaik@gmail.com> @@ -568,13 +587,14 @@ Nikita Ofitserov <himikof@gmail.com> Niklas Schulze <me@jns.io> Nikola Kovacs <nikola.kovacs@gmail.com> -Nils Schneider <nils@nilsschneider.net> Nils Schneider <nils.schneider@gmail.com> +Nils Schneider <nils@nilsschneider.net> Ningxin Hu <ningxin.hu@intel.com> Nitish Mehrotra <nitish.m@samsung.com> Noj Vek <nojvek@gmail.com> Nolan Cao <nolan.robin.cao@gmail.com> Oleksii Kadurin <ovkadurin@gmail.com> +Olli Raula (Old name Olli Syrjälä) <olli.raula@intel.com> Omar Sandoval <osandov@osandov.com> Pan Deng <pan.deng@intel.com> Parag Radke <nrqv63@motorola.com> @@ -595,8 +615,10 @@ Paul Wicks <pwicks86@gmail.com> Pavan Kumar Emani <pavan.e@samsung.com> Pavel Ivanov <paivanof@gmail.com> -Paweł Hajdan jr <phajdan.jr@gmail.com> Pawel Forysiuk <p.forysiuk@samsung.com> +Paweł Hajdan jr <phajdan.jr@gmail.com> +Payal Pandey <payal.pandey@samsung.com> +Peng Hu <penghu@tencent.com> Peng Jiang <leiyi.jp@gmail.com> Peng Xinchao <pxinchao@gmail.com> Petar Jovanovic <petarj@mips.com> @@ -611,6 +633,7 @@ Philipp Hancke <philipp.hancke@googlemail.com> Philippe Beauchamp <philippe.beauchamp@gmail.com> Philippe Beaudoin <philippe.beaudoin@gmail.com> +Pierre Neter <pierreneter@gmail.com> Pierre-Antoine LaFayette <pierre.lafayette@gmail.com> Po-Chun Chang <pochang0403@gmail.com> Pramod Begur Srinath <pramod.bs@samsung.com> @@ -622,13 +645,14 @@ Preeti Nayak <preeti.nayak@samsung.com> Pritam Nikam <pritam.nikam@samsung.com> Puttaraju R <puttaraju.r@samsung.com> +Qi Yang <qi1988.yang@samsung.com> Qiankun Miao <qiankun.miao@intel.com> Qing Zhang <qing.zhang@intel.com> -Qi Yang <qi1988.yang@samsung.com> Radu Stavila <stavila@adobe.com> Radu Velea <radu.velea@intel.com> Rafael Antognolli <rafael.antognolli@intel.com> Raghavendra Ghatage <r.ghatage@samsung.com> +Raghu Ram Nagaraj <r.nagaraj@samsung.com> Rahul Gupta <rahul.g@samsung.com> Rajneesh Rana <rajneesh.r@samsung.com> Raman Tenneti <raman.tenneti@gmail.com> @@ -704,10 +728,10 @@ Seshadri Mahalingam <seshadri.mahalingam@gmail.com> Sevan Janiyan <venture37@geeklan.co.uk> Shahriar Rostami <shahriar.rostami@gmail.com> +Shail Singhal <shail.s@samsung.com> Shane Hansen <shanemhansen@gmail.com> ShankarGanesh K <blr.bmlab@gmail.com> Shanmuga Pandi M <shanmuga.m@samsung.com> -Shail Singhal <shail.s@samsung.com> Shaobo Yan <shaobo.yan@intel.com> Shashi Kumar <sk.kumar@samsung.com> Sherry Mou <wenjinm@amazon.com> @@ -716,18 +740,20 @@ Shiliu Wang <aofdwsl@gmail.com> Shiliu Wang <shiliu.wang@intel.com> Shilpa Shri <shilpa.shri@samsung.com> -Shivakumar JM <shiva.jm@samsung.com> Shiva Kumar <shiva.k1@samsung.com> +Shivakumar JM <shiva.jm@samsung.com> Shouqun Liu <liushouqun@xiaomi.com> Shouqun Liu <shouqun.liu@intel.com> Shreeram Kushwaha <shreeram.k@samsung.com> Shreyas Gopal <shreyas.g@samsung.com> Shreyas VA <v.a.shreyas@gmail.com> Siba Samal <siba.samal@samsung.com> +Siddharth Bagai <b.siddharth@samsung.com> +Siddharth Shankar <funkysidd@gmail.com> Simon Arlott <simon.arlott@gmail.com> Siva Kumar Gunturi <siva.gunturi@samsung.com> -Sohan Jyoti Ghosh <sohan.jyoti@samsung.com> Sohan Jyoti Ghosh <sohan.jyoti@huawei.com> +Sohan Jyoti Ghosh <sohan.jyoti@samsung.com> Song YeWen <ffmpeg@gmail.com> Sooho Park <sooho1000@gmail.com> Soorya R <soorya.r@samsung.com> @@ -743,15 +769,16 @@ Sudarshan Parthasarathy <sudarshan.p@samsung.com> Sujae Jo <sujae33.jo@gmail.com> Sujith S S <sujiths.s@samsung.com> +Sunchang Li <johnstonli@tencent.com> Suneel Kota <suneel.kota@samsung.com> Sungguk Lim <limasdf@gmail.com> Sunghoon Kim <shoon.kim@lge.com> Sungmann Cho <sungmann.cho@gmail.com> Sungmann Cho <sungmann.cho@navercorp.com> -Sunitha Srivatsa <srivats@amazon.com> -Suyash Sengar <suyash.s@samsung.com> Sunil Ratnu <sunil.ratnu@samsung.com> +Sunitha Srivatsa <srivats@amazon.com> Suvanjan Mukherjee <suvanjanmukherjee@gmail.com> +Suyash Sengar <suyash.s@samsung.com> Swarali Raut <swarali.sr@samsung.com> Swati Jaiswal <swa.jaiswal@samsung.com> Sylvain Zimmer <sylvinus@gmail.com> @@ -777,10 +804,11 @@ Tim Ansell <mithro@mithis.com> Tim Niederhausen <tim@rnc-ag.de> Timo Reimann <ttr314@googlemail.com> +Timo Witte <timo.witte@gmail.com> Tom Callaway <tcallawa@redhat.com> Tom Harwood <tfh@skip.org> -Torsten Kurbad <google@tk-webart.de> Tomas Popela <tomas.popela@gmail.com> +Torsten Kurbad <google@tk-webart.de> Trevor Perrin <unsafe@trevp.net> Tripta Gupta <tripta.g@samsung.com> U. Artie Eoff <ullysses.a.eoff@intel.com> @@ -800,11 +828,13 @@ Vinay Anantharaman <vinaya@adobe.com> Vipul Bhasin <vipul.bhasin@gmail.com> Visa Putkinen <v.putkinen@partner.samsung.com> +Vishal Bhatnagar <vishal.b@samsung.com> Vivek Galatage <vivek.vg@samsung.com> Volker Sorge <volker.sorge@gmail.com> Waihung Fu <fufranci@amazon.com> Wanchang Ryu <wanchang.ryu@lge.com> Wang Qing <wangqing-hf@loongson.cn> +WenSheng He <wensheng.he@samsung.com> Wesley Lancel <wesleylancel@gmail.com> Wesley Wigham <t-weswig@microsoft.com> Wesley Wigham <wwigham@gmail.com> @@ -830,14 +860,18 @@ Yair Yogev <progame@chromium.org> Yan Wang <yan0422.wang@samsung.com> Yang Gu <yang.gu@intel.com> +Yannic Bonenberger <contact@yannic-bonenberger.com> Yarin Kaul <yarin.kaul@gmail.com> Ye Liu <cbakgly@gmail.com> +Yeol Park <peary2@gmail.com> Yi Shen <yi.shen@samsung.com> Yi Sun <ratsunny@gmail.com> Yizhou Jiang <yizhou.jiang@intel.com> Yoav Weiss <yoav@yoav.ws> Yoav Zilberberg <yoav.zilberberg@gmail.com> Yong Shin <sy3620@gmail.com> +Yong Wang <ccyongwang@tencent.com> +Yongha Lee <yongha78.lee@samsung.com> Yongsheng Zhu <yongsheng.zhu@intel.com> Yoonjae Cho <yoonjae.cho92@gmail.com> Yoshinori Sano <yoshinori.sano@gmail.com> @@ -849,88 +883,55 @@ Youngsun Suh <zard17@gmail.com> Yumikiyo Osanai <yumios.art@gmail.com> Yunchao He <yunchao.he@intel.com> +Yunsik Jang <yunsik.jang@lge.com> +Yupei Wang <perryuwang@tencent.com> Yuri Gorobets <yuri.gorobets@gmail.com> Yuriy Taraday <yorik.sar@gmail.com> Zeno Albisser <zeno.albisser@digia.com> +Zeqin Chen <talonchen@tencent.com> Zhaoze Zhou <zhaoze.zhou@partner.samsung.com> +Zheda Chen <zheda.chen@intel.com> Zheng Chuang <zhengchuangscu@gmail.com> Zhenyu Liang <zhenyu.liang@intel.com> Zhenyu Shan <zhenyu.shan@intel.com> -Zheda Chen <zheda.chen@intel.com> +Zhifei Fang <facetothefate@gmail.com> Zhuoyu Qian <zhuoyu.qian@samsung.com> Ziran Sun <ziran.sun@samsung.com> Zoltan Herczeg <zherczeg.u-szeged@partner.samsung.com> Zoltan Kuscsik <zoltan.kuscsik@linaro.org> Zsolt Borbely <zsborbely.u-szeged@partner.samsung.com> -Yongha Lee <yongha78.lee@samsung.com> 方觉 (Fang Jue) <fangjue23303@gmail.com> -Yupei Wang <perryuwang@tencent.com> -Peng Hu <penghu@tencent.com> -WenSheng He <wensheng.he@samsung.com> -Raghu Ram Nagaraj <r.nagaraj@samsung.com> -Chanho Park <parkch98@gmail.com> -Payal Pandey <payal.pandey@samsung.com> -Kenneth Strickland <ken.strickland@gmail.com> -Olli Raula (Old name Olli Syrjälä) <olli.raula@intel.com> -Vishal Bhatnagar <vishal.b@samsung.com> -Yunsik Jang <yunsik.jang@lge.com> -Siddharth Bagai <b.siddharth@samsung.com> -Andrei Borza <andrei.borza@gmail.com> -anatoly techtonik <techtonik@gmail.com> -Aleksandar Stojiljkovic <aleksandar.stojiljkovic@intel.com> -Marc des Garets <marc.desgarets@googlemail.com> -Siddharth Shankar <funkysidd@gmail.com> -Eden Wang <nedenwang@tencent.com> -Cathie Chen <cathiechen@tencent.com> -Kyle Plumadore <kyle.plumadore@amd.com> -Sunchang Li <johnstonli@tencent.com> -Yeol Park <peary2@gmail.com> -Debug Wang <debugwang@tencent.com> -Zeqin Chen <talonchen@tencent.com> -Yong Wang <ccyongwang@tencent.com> -Charles Vaughn <cvaughn@gmail.com> -Ernesto Mudu <ernesto.mudu@gmail.com> -Zhifei Fang <facetothefate@gmail.com> -Timo Witte <timo.witte@gmail.com> -Pierre Neter <pierreneter@gmail.com> -Jan Rucka <ruckajan10@gmail.com> -Yannic Bonenberger <contact@yannic-bonenberger.com> -Kyoungdeok Kwon <kkd927@gmail.com> -Kyungyoung Heo <bbvch13531@gmail.com> -Jinyoung Hur <hurims@gmail.com> -Minjeong Lee <apenr1234@gmail.com> -Myung-jong Kim <mjkim610@gmail.com> ACCESS CO., LTD. <*@access-company.com> +Akamai Inc. <*@akamai.com> +ARM Holdings <*@arm.com> BlackBerry Limited <*@blackberry.com> +Canonical Limited <*@canonical.com> Code Aurora Forum <*@codeaurora.org> Comodo CA Limited Endless Mobile, Inc. <*@endlessm.com> +Facebook, Inc. <*@fb.com> +Facebook, Inc. <*@oculus.com> Google Inc. <*@google.com> Hewlett-Packard Development Company, L.P. <*@hp.com> +IBM Inc. <*@*.ibm.com> Igalia S.L. <*@igalia.com> -NIKE, Inc. <*@nike.com> +Impossible Dreams Network <*@impossibledreams.net> +LG Electronics, Inc. <*@lge.com> Loongson Technology Corporation Limited. <*@loongson.cn> +Macadamian <*@macadamian.com> MIPS Technologies, Inc. <*@mips.com> -NVIDIA Corporation <*@nvidia.com> Neverware Inc. <*@neverware.com> +NIKE, Inc. <*@nike.com> +NVIDIA Corporation <*@nvidia.com> Opera Software ASA <*@opera.com> +Seznam.cz, a.s. <*@firma.seznam.cz> Spotify AB <*@spotify.com> +Tableau Software <*@tableau.com> TeamSpeak Systems GmbH <*@teamspeak.com> The Chromium Authors <*@chromium.org> The MathWorks, Inc. <binod.pant@mathworks.com> Torchmobile Inc. Venture 3 Systems LLC <*@venture3systems.com> -Yandex LLC <*@yandex-team.ru> -ARM Holdings <*@arm.com> -Macadamian <*@macadamian.com> -IBM Inc. <*@*.ibm.com> -Tableau Software <*@tableau.com> -Akamai Inc. <*@akamai.com> -Impossible Dreams Network <*@impossibledreams.net> -Facebook, Inc. <*@fb.com> -Facebook, Inc. <*@oculus.com> -Canonical Limited <*@canonical.com> -Seznam.cz, a.s. <*@firma.seznam.cz> -LG Electronics, Inc. <*@lge.com> Vewd Software AS <*@vewd.com> +Yandex LLC <*@yandex-team.ru>
diff --git a/DEPS b/DEPS index 587e793..f97e9878 100644 --- a/DEPS +++ b/DEPS
@@ -74,11 +74,11 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling Skia # and whatever else without interference from each other. - 'skia_revision': '9f553932a4a4e986db323d8f4da2f78d9a729254', + 'skia_revision': '3cc8092947882a59f7ded61c3ca44a569ae95b38', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling V8 # and whatever else without interference from each other. - 'v8_revision': 'e1591d9c0d5d5930b3692438be4bf891140ecfbd', + 'v8_revision': 'b5d27a6af1d1fd5a15c5bbabcd910d101b22756f', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling swarming_client # and whatever else without interference from each other. @@ -86,7 +86,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ANGLE # and whatever else without interference from each other. - 'angle_revision': '0b684ce3c9f59fe9ba2e7adb19086e72f73e8605', + 'angle_revision': 'f13cadd8bd5fa1f4f4ab78b594812117c26a4b95', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling build tools # and whatever else without interference from each other. @@ -98,7 +98,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling PDFium # and whatever else without interference from each other. - 'pdfium_revision': 'fee749f0a1419e300a49ef657106f580c43842c4', + 'pdfium_revision': '1ff9b7ffa653de1d25c5e013d731054815b13e86', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling openmax_dl # and whatever else without interference from each other. @@ -130,7 +130,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling catapult # and whatever else without interference from each other. - 'catapult_revision': '230a61040fc82beb17c9ea7fee9a462bc0311b85', + 'catapult_revision': 'b0b1ce2c6e9001363a35c0ec943dc873d0b24d4a', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libFuzzer # and whatever else without interference from each other. @@ -244,7 +244,7 @@ }, 'src/third_party/android_tools': { - 'url': Var('chromium_git') + '/android_tools.git' + '@' + '9914c5704717424998c69e837be3631914d787cc', + 'url': Var('chromium_git') + '/android_tools.git' + '@' + 'a2e9bc7c1b41d983577907df51d339fb1e0fd02f', 'condition': 'checkout_android', }, @@ -308,7 +308,7 @@ }, 'src/third_party/depot_tools': - Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + '1b30125fbc42e1a3c2c89c26eee813384f42d22c', + Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + '9e51906ffb13222de7215293dac7a8031d538c0e', # DevTools node modules. Used on Linux buildbots only. 'src/third_party/devtools-node-modules': { @@ -330,7 +330,7 @@ }, 'src/third_party/ffmpeg': - Var('chromium_git') + '/chromium/third_party/ffmpeg.git' + '@' + '9cb03e5705c1bcff7cdaace0e8f55d79374e24b6', + Var('chromium_git') + '/chromium/third_party/ffmpeg.git' + '@' + '18c815f81428e3b41e6f4efc6cb0cbe5b846d1c2', 'src/third_party/findbugs': { 'url': Var('chromium_git') + '/chromium/deps/findbugs.git' + '@' + '4275d9ac8610db6b1bc9a5e887f97e41b33fac67', @@ -624,7 +624,7 @@ Var('chromium_git') + '/external/khronosgroup/webgl.git' + '@' + 'e4919fa03c74bd561dcabf3e61668fa3c7e54353', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + 'e9619f8f81de6ec91b920a0468a6f2c8431bb2f4', # commit position 20628 + Var('webrtc_git') + '/src.git' + '@' + '4e70a72571dd26b85c2385e9c618e343428df5d3', # commit position 20628 'src/third_party/xdg-utils': { 'url': Var('chromium_git') + '/chromium/deps/xdg-utils.git' + '@' + 'd80274d5869b17b8c9067a1022e4416ee7ed5e0d', @@ -647,7 +647,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@ac0ab16a9d31c45421b58eb89d76d15a6659d7a4', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@d638a44a623a5b63de31f3217fb5ecb40413f037', 'condition': 'checkout_src_internal', }, }
diff --git a/WATCHLISTS b/WATCHLISTS index 1105112..5351d4a 100644 --- a/WATCHLISTS +++ b/WATCHLISTS
@@ -907,13 +907,6 @@ 'filepath': 'chrome/browser/resources/(md_)?history|'\ 'chrome/browser/ui/webui/.*history', }, - 'hotword': { - 'filepath': 'chrome/browser/extensions/api/hotword_private/'\ - '|chrome/browser/resources/hotword_helper/'\ - '|chrome/browser/resources/hotword/'\ - '|chrome/browser/search/hotword*'\ - '|chrome/test/data/extensions/api_test/hotword_private/', - }, 'i18n': { 'filepath': 'base/i18n/|base/string|l10n|icu|'\ 'locale_settings|encoding', @@ -2049,7 +2042,6 @@ 'gpu_passthrough_cmd_decoder': ['cwallez+watch@chromium.org', 'geofflang+watch@chromium.org'], 'history_ui': ['pam+watch@chromium.org'], - 'hotword': ['rlp+watch@chromium.org'], 'i18n': ['jshin+watch@chromium.org'], 'importer': ['tfarina@chromium.org'], 'incident_reporting': ['grt+watch@chromium.org'],
diff --git a/android_webview/browser/aw_content_browser_client.cc b/android_webview/browser/aw_content_browser_client.cc index 407bbbd..a5a5673 100644 --- a/android_webview/browser/aw_content_browser_client.cc +++ b/android_webview/browser/aw_content_browser_client.cc
@@ -552,7 +552,7 @@ void AwContentBrowserClient::ExposeInterfacesToRenderer( service_manager::BinderRegistry* registry, - content::AssociatedInterfaceRegistry* associated_registry, + blink::AssociatedInterfaceRegistry* associated_registry, content::RenderProcessHost* render_process_host) { if (base::FeatureList::IsEnabled(features::kNetworkService)) { registry->AddInterface(
diff --git a/android_webview/browser/aw_content_browser_client.h b/android_webview/browser/aw_content_browser_client.h index 50831667..877d338 100644 --- a/android_webview/browser/aw_content_browser_client.h +++ b/android_webview/browser/aw_content_browser_client.h
@@ -143,7 +143,7 @@ mojo::ScopedMessagePipeHandle interface_pipe) override; void ExposeInterfacesToRenderer( service_manager::BinderRegistry* registry, - content::AssociatedInterfaceRegistry* associated_registry, + blink::AssociatedInterfaceRegistry* associated_registry, content::RenderProcessHost* render_process_host) override; std::vector<std::unique_ptr<content::URLLoaderThrottle>> CreateURLLoaderThrottles(
diff --git a/android_webview/browser/aw_javascript_dialog_manager.cc b/android_webview/browser/aw_javascript_dialog_manager.cc index 673649a..3e4a3be1 100644 --- a/android_webview/browser/aw_javascript_dialog_manager.cc +++ b/android_webview/browser/aw_javascript_dialog_manager.cc
@@ -37,6 +37,7 @@ void AwJavaScriptDialogManager::RunBeforeUnloadDialog( content::WebContents* web_contents, + content::RenderFrameHost* render_frame_host, bool is_reload, DialogClosedCallback callback) { AwContentsClientBridge* bridge =
diff --git a/android_webview/browser/aw_javascript_dialog_manager.h b/android_webview/browser/aw_javascript_dialog_manager.h index 19f41a9..e31c967 100644 --- a/android_webview/browser/aw_javascript_dialog_manager.h +++ b/android_webview/browser/aw_javascript_dialog_manager.h
@@ -24,6 +24,7 @@ DialogClosedCallback callback, bool* did_suppress_message) override; void RunBeforeUnloadDialog(content::WebContents* web_contents, + content::RenderFrameHost* render_frame_host, bool is_reload, DialogClosedCallback callback) override; void CancelDialogs(content::WebContents* web_contents,
diff --git a/android_webview/common/crash_reporter/crash_keys.cc b/android_webview/common/crash_reporter/crash_keys.cc index c388e99..01c1aad 100644 --- a/android_webview/common/crash_reporter/crash_keys.cc +++ b/android_webview/common/crash_reporter/crash_keys.cc
@@ -95,6 +95,9 @@ // Temporary for https://crbug.com/685996. {"user-cloud-policy-manager-connect-trace", kMediumSize}, + // TODO(sunnyps): Remove after fixing crbug.com/724999. + {"gl-context-set-current-stack-trace", kMediumSize}, + // Accessibility keys. Temporary for http://crbug.com/765490. {"ax_tree_error", kSmallSize}, {"ax_tree_update", kMediumSize},
diff --git a/android_webview/java/src/org/chromium/android_webview/AwContents.java b/android_webview/java/src/org/chromium/android_webview/AwContents.java index 329c25e..94094ee 100644 --- a/android_webview/java/src/org/chromium/android_webview/AwContents.java +++ b/android_webview/java/src/org/chromium/android_webview/AwContents.java
@@ -3282,7 +3282,9 @@ @Override public boolean onDragEvent(DragEvent event) { - return mWebContents.getEventForwarder().onDragEvent(event, mContainerView); + return isDestroyedOrNoOperation(NO_WARN) + ? false + : mWebContents.getEventForwarder().onDragEvent(event, mContainerView); } @Override
diff --git a/android_webview/lib/aw_main_delegate.cc b/android_webview/lib/aw_main_delegate.cc index 29595d53..d9227cf4 100644 --- a/android_webview/lib/aw_main_delegate.cc +++ b/android_webview/lib/aw_main_delegate.cc
@@ -154,6 +154,8 @@ CommandLineHelper::AddEnabledFeature(*cl, features::kLoadingWithMojo.name); + CommandLineHelper::AddDisabledFeature(*cl, features::kMojoInputMessages.name); + android_webview::RegisterPathProvider(); safe_browsing_api_handler_.reset(
diff --git a/ash/accelerators/accelerator_controller.cc b/ash/accelerators/accelerator_controller.cc index ff80953..0cdd9291 100644 --- a/ash/accelerators/accelerator_controller.cc +++ b/ash/accelerators/accelerator_controller.cc
@@ -11,7 +11,6 @@ #include "ash/accelerators/accelerator_controller_delegate.h" #include "ash/accelerators/debug_commands.h" #include "ash/accessibility/accessibility_controller.h" -#include "ash/accessibility/accessibility_delegate.h" #include "ash/display/display_configuration_controller.h" #include "ash/display/display_move_window_util.h" #include "ash/focus_cycler.h" @@ -505,7 +504,7 @@ // When spoken feedback is enabled, we should neither toggle the list nor // consume the key since Search+Shift is one of the shortcuts the a11y // feature uses. crbug.com/132296 - if (Shell::Get()->accessibility_delegate()->IsSpokenFeedbackEnabled()) + if (Shell::Get()->accessibility_controller()->IsSpokenFeedbackEnabled()) return false; } return true; @@ -827,8 +826,10 @@ void HandleToggleSpokenFeedback() { base::RecordAction(UserMetricsAction("Accel_Toggle_Spoken_Feedback")); - Shell::Get()->accessibility_delegate()->ToggleSpokenFeedback( - A11Y_NOTIFICATION_SHOW); + AccessibilityController* controller = + Shell::Get()->accessibility_controller(); + controller->SetSpokenFeedbackEnabled(!controller->IsSpokenFeedbackEnabled(), + A11Y_NOTIFICATION_SHOW); } void HandleVolumeDown(mojom::VolumeController* volume_controller,
diff --git a/ash/accelerators/accelerator_controller_unittest.cc b/ash/accelerators/accelerator_controller_unittest.cc index 0cb5deb5..3c3eac5 100644 --- a/ash/accelerators/accelerator_controller_unittest.cc +++ b/ash/accelerators/accelerator_controller_unittest.cc
@@ -6,7 +6,6 @@ #include "ash/accelerators/accelerator_table.h" #include "ash/accessibility/accessibility_controller.h" -#include "ash/accessibility/accessibility_delegate.h" #include "ash/accessibility/test_accessibility_controller_client.h" #include "ash/ime/ime_controller.h" #include "ash/media_controller.h" @@ -823,7 +822,8 @@ app_list::test::TestAppListPresenter test_app_list_presenter; Shell::Get()->app_list()->SetAppListPresenter( test_app_list_presenter.CreateInterfacePtrAndBind()); - AccessibilityDelegate* delegate = Shell::Get()->accessibility_delegate(); + AccessibilityController* controller = + Shell::Get()->accessibility_controller(); // The press event should not toggle the AppList, the release should instead. EXPECT_FALSE( @@ -839,12 +839,14 @@ EXPECT_EQ(ui::VKEY_LWIN, GetPreviousAccelerator().key_code()); // When spoken feedback is on, the AppList should not toggle. - delegate->ToggleSpokenFeedback(A11Y_NOTIFICATION_NONE); + controller->SetSpokenFeedbackEnabled(true, A11Y_NOTIFICATION_NONE); + EXPECT_TRUE(controller->IsSpokenFeedbackEnabled()); EXPECT_FALSE( ProcessInController(ui::Accelerator(ui::VKEY_LWIN, ui::EF_NONE))); EXPECT_FALSE(ProcessInController( CreateReleaseAccelerator(ui::VKEY_LWIN, ui::EF_NONE))); - delegate->ToggleSpokenFeedback(A11Y_NOTIFICATION_NONE); + controller->SetSpokenFeedbackEnabled(false, A11Y_NOTIFICATION_NONE); + EXPECT_FALSE(controller->IsSpokenFeedbackEnabled()); RunAllPendingInMessageLoop(); EXPECT_EQ(1u, test_app_list_presenter.toggle_count());
diff --git a/ash/accelerators/spoken_feedback_toggler.cc b/ash/accelerators/spoken_feedback_toggler.cc index 4a3b243..5a5ac3d 100644 --- a/ash/accelerators/spoken_feedback_toggler.cc +++ b/ash/accelerators/spoken_feedback_toggler.cc
@@ -7,7 +7,7 @@ #include <utility> #include "ash/accelerators/key_hold_detector.h" -#include "ash/accessibility/accessibility_delegate.h" +#include "ash/accessibility/accessibility_controller.h" #include "ash/public/cpp/accessibility_types.h" #include "ash/shell.h" #include "ui/events/event.h" @@ -53,8 +53,10 @@ void SpokenFeedbackToggler::OnKeyHold(const ui::KeyEvent* event) { if (!toggled_) { toggled_ = true; - Shell::Get()->accessibility_delegate()->ToggleSpokenFeedback( - A11Y_NOTIFICATION_SHOW); + AccessibilityController* controller = + Shell::Get()->accessibility_controller(); + controller->SetSpokenFeedbackEnabled(!controller->IsSpokenFeedbackEnabled(), + A11Y_NOTIFICATION_SHOW); } }
diff --git a/ash/accelerators/spoken_feedback_toggler_unittest.cc b/ash/accelerators/spoken_feedback_toggler_unittest.cc index 543cd52..9efc979 100644 --- a/ash/accelerators/spoken_feedback_toggler_unittest.cc +++ b/ash/accelerators/spoken_feedback_toggler_unittest.cc
@@ -3,7 +3,7 @@ // found in the LICENSE file. #include "ash/accelerators/spoken_feedback_toggler.h" -#include "ash/accessibility/accessibility_delegate.h" +#include "ash/accessibility/accessibility_controller.h" #include "ash/shell.h" #include "ash/test/ash_test_base.h" #include "ash/wm/window_util.h" @@ -17,34 +17,35 @@ TEST_F(SpokenFeedbackTogglerTest, Basic) { SpokenFeedbackToggler::ScopedEnablerForTest scoped; - AccessibilityDelegate* delegate = Shell::Get()->accessibility_delegate(); + AccessibilityController* controller = + Shell::Get()->accessibility_controller(); ui::test::EventGenerator& generator = GetEventGenerator(); - EXPECT_FALSE(delegate->IsSpokenFeedbackEnabled()); + EXPECT_FALSE(controller->IsSpokenFeedbackEnabled()); generator.PressKey(ui::VKEY_F6, ui::EF_SHIFT_DOWN); - EXPECT_FALSE(delegate->IsSpokenFeedbackEnabled()); + EXPECT_FALSE(controller->IsSpokenFeedbackEnabled()); generator.ReleaseKey(ui::VKEY_F6, 0); - EXPECT_FALSE(delegate->IsSpokenFeedbackEnabled()); + EXPECT_FALSE(controller->IsSpokenFeedbackEnabled()); // Click and hold toggles the spoken feedback. generator.PressKey(ui::VKEY_F6, ui::EF_SHIFT_DOWN); - EXPECT_FALSE(delegate->IsSpokenFeedbackEnabled()); + EXPECT_FALSE(controller->IsSpokenFeedbackEnabled()); generator.PressKey(ui::VKEY_F6, ui::EF_SHIFT_DOWN); - EXPECT_TRUE(delegate->IsSpokenFeedbackEnabled()); + EXPECT_TRUE(controller->IsSpokenFeedbackEnabled()); generator.PressKey(ui::VKEY_F6, ui::EF_SHIFT_DOWN); - EXPECT_TRUE(delegate->IsSpokenFeedbackEnabled()); + EXPECT_TRUE(controller->IsSpokenFeedbackEnabled()); generator.ReleaseKey(ui::VKEY_F6, 0); - EXPECT_TRUE(delegate->IsSpokenFeedbackEnabled()); + EXPECT_TRUE(controller->IsSpokenFeedbackEnabled()); // toggle again generator.PressKey(ui::VKEY_F6, ui::EF_SHIFT_DOWN); - EXPECT_TRUE(delegate->IsSpokenFeedbackEnabled()); + EXPECT_TRUE(controller->IsSpokenFeedbackEnabled()); generator.PressKey(ui::VKEY_F6, ui::EF_SHIFT_DOWN); - EXPECT_FALSE(delegate->IsSpokenFeedbackEnabled()); + EXPECT_FALSE(controller->IsSpokenFeedbackEnabled()); generator.PressKey(ui::VKEY_F6, ui::EF_SHIFT_DOWN); - EXPECT_FALSE(delegate->IsSpokenFeedbackEnabled()); + EXPECT_FALSE(controller->IsSpokenFeedbackEnabled()); generator.ReleaseKey(ui::VKEY_F6, 0); - EXPECT_FALSE(delegate->IsSpokenFeedbackEnabled()); + EXPECT_FALSE(controller->IsSpokenFeedbackEnabled()); } TEST_F(SpokenFeedbackTogglerTest, PassThroughEvents) {
diff --git a/ash/accessibility/accessibility_controller.cc b/ash/accessibility/accessibility_controller.cc index 8da5d7f..70010e9c 100644 --- a/ash/accessibility/accessibility_controller.cc +++ b/ash/accessibility/accessibility_controller.cc
@@ -29,13 +29,10 @@ namespace ash { namespace { -void NotifyAccessibilityStatusChanged() { +void NotifyAccessibilityStatusChanged( + AccessibilityNotificationVisibility notification_visibility) { Shell::Get()->system_tray_notifier()->NotifyAccessibilityStatusChanged( - A11Y_NOTIFICATION_NONE); -} - -PrefService* GetActivePrefService() { - return Shell::Get()->session_controller()->GetActivePrefService(); + notification_visibility); } } // namespace @@ -64,6 +61,8 @@ registry->RegisterBooleanPref(prefs::kAccessibilityMonoAudioEnabled, false); registry->RegisterBooleanPref(prefs::kAccessibilityScreenMagnifierEnabled, false); + registry->RegisterBooleanPref(prefs::kAccessibilitySpokenFeedbackEnabled, + false); return; } @@ -74,6 +73,7 @@ registry->RegisterForeignPref(prefs::kAccessibilityLargeCursorDipSize); registry->RegisterForeignPref(prefs::kAccessibilityMonoAudioEnabled); registry->RegisterForeignPref(prefs::kAccessibilityScreenMagnifierEnabled); + registry->RegisterForeignPref(prefs::kAccessibilitySpokenFeedbackEnabled); } void AccessibilityController::BindRequest( @@ -117,6 +117,22 @@ return mono_audio_enabled_; } +void AccessibilityController::SetSpokenFeedbackEnabled( + bool enabled, + AccessibilityNotificationVisibility notify) { + PrefService* prefs = GetActivePrefService(); + if (!prefs) + return; + spoken_feedback_notification_ = notify; + prefs->SetBoolean(prefs::kAccessibilitySpokenFeedbackEnabled, enabled); + prefs->CommitPendingWrite(); + spoken_feedback_notification_ = A11Y_NOTIFICATION_NONE; +} + +bool AccessibilityController::IsSpokenFeedbackEnabled() const { + return spoken_feedback_enabled_; +} + void AccessibilityController::TriggerAccessibilityAlert( mojom::AccessibilityAlert alert) { if (client_) @@ -138,6 +154,11 @@ ObservePrefs(prefs); } +void AccessibilityController::SetPrefServiceForTest(PrefService* prefs) { + pref_service_for_test_ = prefs; + ObservePrefs(prefs); +} + void AccessibilityController::FlushMojoForTest() { client_.FlushForTesting(); } @@ -162,11 +183,22 @@ prefs::kAccessibilityMonoAudioEnabled, base::Bind(&AccessibilityController::UpdateMonoAudioFromPref, base::Unretained(this))); + pref_change_registrar_->Add( + prefs::kAccessibilitySpokenFeedbackEnabled, + base::Bind(&AccessibilityController::UpdateSpokenFeedbackFromPref, + base::Unretained(this))); // Load current state. UpdateHighContrastFromPref(); UpdateLargeCursorFromPref(); UpdateMonoAudioFromPref(); + UpdateSpokenFeedbackFromPref(); +} + +PrefService* AccessibilityController::GetActivePrefService() const { + if (pref_service_for_test_) + return pref_service_for_test_; + return Shell::Get()->session_controller()->GetActivePrefService(); } void AccessibilityController::UpdateHighContrastFromPref() { @@ -179,7 +211,7 @@ high_contrast_enabled_ = enabled; - NotifyAccessibilityStatusChanged(); + NotifyAccessibilityStatusChanged(A11Y_NOTIFICATION_NONE); // Under mash the UI service (window server) handles high contrast mode. if (Shell::GetAshConfig() == Config::MASH) { @@ -211,7 +243,7 @@ large_cursor_enabled_ = enabled; large_cursor_size_in_dip_ = size; - NotifyAccessibilityStatusChanged(); + NotifyAccessibilityStatusChanged(A11Y_NOTIFICATION_NONE); ShellPort::Get()->SetCursorSize( large_cursor_enabled_ ? ui::CursorSize::kLarge : ui::CursorSize::kNormal); @@ -228,8 +260,24 @@ mono_audio_enabled_ = enabled; - NotifyAccessibilityStatusChanged(); + NotifyAccessibilityStatusChanged(A11Y_NOTIFICATION_NONE); chromeos::CrasAudioHandler::Get()->SetOutputMonoEnabled(enabled); } +void AccessibilityController::UpdateSpokenFeedbackFromPref() { + PrefService* prefs = GetActivePrefService(); + const bool enabled = + prefs->GetBoolean(prefs::kAccessibilitySpokenFeedbackEnabled); + + if (spoken_feedback_enabled_ == enabled) + return; + + spoken_feedback_enabled_ = enabled; + + NotifyAccessibilityStatusChanged(spoken_feedback_notification_); + // TODO(warx): Chrome observes prefs change and turns on/off spoken feedback. + // Define a mojo call to control toggling spoken feedback (ChromeVox) once + // prefs ownership and registration is moved to ash. +} + } // namespace ash
diff --git a/ash/accessibility/accessibility_controller.h b/ash/accessibility/accessibility_controller.h index be6c88b2..9c14335 100644 --- a/ash/accessibility/accessibility_controller.h +++ b/ash/accessibility/accessibility_controller.h
@@ -9,6 +9,7 @@ #include "ash/ash_constants.h" #include "ash/ash_export.h" +#include "ash/public/cpp/accessibility_types.h" #include "ash/public/interfaces/accessibility_controller.mojom.h" #include "ash/session/session_observer.h" #include "base/macros.h" @@ -49,6 +50,10 @@ void SetMonoAudioEnabled(bool enabled); bool IsMonoAudioEnabled() const; + void SetSpokenFeedbackEnabled(bool enabled, + AccessibilityNotificationVisibility notify); + bool IsSpokenFeedbackEnabled() const; + // Triggers an accessibility alert to give the user feedback. void TriggerAccessibilityAlert(mojom::AccessibilityAlert alert); @@ -59,6 +64,9 @@ void OnSigninScreenPrefServiceInitialized(PrefService* prefs) override; void OnActiveUserPrefServiceChanged(PrefService* prefs) override; + // TODO(warx): remove this method for browser tests (crbug.com/789285). + void SetPrefServiceForTest(PrefService* prefs); + // Test helpers: void FlushMojoForTest(); @@ -67,9 +75,14 @@ // initial settings. void ObservePrefs(PrefService* prefs); + // Returns |pref_service_for_test_| if not null, otherwise return + // SessionController::GetActivePrefService(). + PrefService* GetActivePrefService() const; + void UpdateHighContrastFromPref(); void UpdateLargeCursorFromPref(); void UpdateMonoAudioFromPref(); + void UpdateSpokenFeedbackFromPref(); service_manager::Connector* connector_ = nullptr; std::unique_ptr<PrefChangeRegistrar> pref_change_registrar_; @@ -84,6 +97,12 @@ bool large_cursor_enabled_ = false; int large_cursor_size_in_dip_ = kDefaultLargeCursorSize; bool mono_audio_enabled_ = false; + bool spoken_feedback_enabled_ = false; + + AccessibilityNotificationVisibility spoken_feedback_notification_ = + A11Y_NOTIFICATION_NONE; + + PrefService* pref_service_for_test_ = nullptr; DISALLOW_COPY_AND_ASSIGN(AccessibilityController); };
diff --git a/ash/accessibility/accessibility_controller_unittest.cc b/ash/accessibility/accessibility_controller_unittest.cc index b441e91..5f1e64e 100644 --- a/ash/accessibility/accessibility_controller_unittest.cc +++ b/ash/accessibility/accessibility_controller_unittest.cc
@@ -23,10 +23,15 @@ // AccessibilityObserver: void OnAccessibilityStatusChanged( AccessibilityNotificationVisibility notify) override { - changed_++; + if (notify == A11Y_NOTIFICATION_NONE) { + ++notification_none_changed_; + } else if (notify == A11Y_NOTIFICATION_SHOW) { + ++notification_show_changed_; + } } - int changed_ = 0; + int notification_none_changed_ = 0; + int notification_show_changed_ = 0; private: DISALLOW_COPY_AND_ASSIGN(TestAccessibilityObserver); @@ -43,6 +48,8 @@ EXPECT_TRUE(prefs->FindPreference(prefs::kAccessibilityMonoAudioEnabled)); EXPECT_TRUE( prefs->FindPreference(prefs::kAccessibilityScreenMagnifierEnabled)); + EXPECT_TRUE( + prefs->FindPreference(prefs::kAccessibilitySpokenFeedbackEnabled)); } TEST_F(AccessibilityControllerTest, SetHighContrastEnabled) { @@ -52,15 +59,15 @@ TestAccessibilityObserver observer; Shell::Get()->system_tray_notifier()->AddAccessibilityObserver(&observer); - EXPECT_EQ(0, observer.changed_); + EXPECT_EQ(0, observer.notification_none_changed_); controller->SetHighContrastEnabled(true); EXPECT_TRUE(controller->IsHighContrastEnabled()); - EXPECT_EQ(1, observer.changed_); + EXPECT_EQ(1, observer.notification_none_changed_); controller->SetHighContrastEnabled(false); EXPECT_FALSE(controller->IsHighContrastEnabled()); - EXPECT_EQ(2, observer.changed_); + EXPECT_EQ(2, observer.notification_none_changed_); Shell::Get()->system_tray_notifier()->RemoveAccessibilityObserver(&observer); } @@ -72,15 +79,15 @@ TestAccessibilityObserver observer; Shell::Get()->system_tray_notifier()->AddAccessibilityObserver(&observer); - EXPECT_EQ(0, observer.changed_); + EXPECT_EQ(0, observer.notification_none_changed_); controller->SetLargeCursorEnabled(true); EXPECT_TRUE(controller->IsLargeCursorEnabled()); - EXPECT_EQ(1, observer.changed_); + EXPECT_EQ(1, observer.notification_none_changed_); controller->SetLargeCursorEnabled(false); EXPECT_FALSE(controller->IsLargeCursorEnabled()); - EXPECT_EQ(2, observer.changed_); + EXPECT_EQ(2, observer.notification_none_changed_); Shell::Get()->system_tray_notifier()->RemoveAccessibilityObserver(&observer); } @@ -109,15 +116,38 @@ TestAccessibilityObserver observer; Shell::Get()->system_tray_notifier()->AddAccessibilityObserver(&observer); - EXPECT_EQ(0, observer.changed_); + EXPECT_EQ(0, observer.notification_none_changed_); controller->SetMonoAudioEnabled(true); EXPECT_TRUE(controller->IsMonoAudioEnabled()); - EXPECT_EQ(1, observer.changed_); + EXPECT_EQ(1, observer.notification_none_changed_); controller->SetMonoAudioEnabled(false); EXPECT_FALSE(controller->IsMonoAudioEnabled()); - EXPECT_EQ(2, observer.changed_); + EXPECT_EQ(2, observer.notification_none_changed_); + + Shell::Get()->system_tray_notifier()->RemoveAccessibilityObserver(&observer); +} + +TEST_F(AccessibilityControllerTest, SetSpokenFeedbackEnabled) { + AccessibilityController* controller = + Shell::Get()->accessibility_controller(); + EXPECT_FALSE(controller->IsSpokenFeedbackEnabled()); + + TestAccessibilityObserver observer; + Shell::Get()->system_tray_notifier()->AddAccessibilityObserver(&observer); + EXPECT_EQ(0, observer.notification_none_changed_); + EXPECT_EQ(0, observer.notification_show_changed_); + + controller->SetSpokenFeedbackEnabled(true, A11Y_NOTIFICATION_SHOW); + EXPECT_TRUE(controller->IsSpokenFeedbackEnabled()); + EXPECT_EQ(0, observer.notification_none_changed_); + EXPECT_EQ(1, observer.notification_show_changed_); + + controller->SetSpokenFeedbackEnabled(false, A11Y_NOTIFICATION_NONE); + EXPECT_FALSE(controller->IsSpokenFeedbackEnabled()); + EXPECT_EQ(1, observer.notification_none_changed_); + EXPECT_EQ(1, observer.notification_show_changed_); Shell::Get()->system_tray_notifier()->RemoveAccessibilityObserver(&observer); }
diff --git a/ash/accessibility/accessibility_delegate.h b/ash/accessibility/accessibility_delegate.h index 15870f0b..8e8deb0 100644 --- a/ash/accessibility/accessibility_delegate.h +++ b/ash/accessibility/accessibility_delegate.h
@@ -21,13 +21,6 @@ public: virtual ~AccessibilityDelegate() {} - // Invoked to toggle spoken feedback for accessibility - virtual void ToggleSpokenFeedback( - AccessibilityNotificationVisibility notify) = 0; - - // Returns true if spoken feedback is enabled. - virtual bool IsSpokenFeedbackEnabled() const = 0; - // Invoked to enable the screen magnifier. virtual void SetMagnifierEnabled(bool enabled) = 0;
diff --git a/ash/accessibility/default_accessibility_delegate.cc b/ash/accessibility/default_accessibility_delegate.cc index f3e6183..2da9584 100644 --- a/ash/accessibility/default_accessibility_delegate.cc +++ b/ash/accessibility/default_accessibility_delegate.cc
@@ -15,10 +15,6 @@ DefaultAccessibilityDelegate::~DefaultAccessibilityDelegate() = default; -bool DefaultAccessibilityDelegate::IsSpokenFeedbackEnabled() const { - return spoken_feedback_enabled_; -} - void DefaultAccessibilityDelegate::SetMagnifierEnabled(bool enabled) { screen_magnifier_enabled_ = enabled; } @@ -102,7 +98,7 @@ bool DefaultAccessibilityDelegate::ShouldShowAccessibilityMenu() const { AccessibilityController* controller = Shell::Get()->accessibility_controller(); - return spoken_feedback_enabled_ || screen_magnifier_enabled_ || + return controller->IsSpokenFeedbackEnabled() || screen_magnifier_enabled_ || autoclick_enabled_ || virtual_keyboard_enabled_ || controller->IsMonoAudioEnabled() || controller->IsLargeCursorEnabled() || @@ -115,11 +111,6 @@ void DefaultAccessibilityDelegate::SilenceSpokenFeedback() const {} -void DefaultAccessibilityDelegate::ToggleSpokenFeedback( - AccessibilityNotificationVisibility notify) { - spoken_feedback_enabled_ = !spoken_feedback_enabled_; -} - void DefaultAccessibilityDelegate::SaveScreenMagnifierScale(double scale) {} double DefaultAccessibilityDelegate::GetSavedScreenMagnifierScale() {
diff --git a/ash/accessibility/default_accessibility_delegate.h b/ash/accessibility/default_accessibility_delegate.h index 74ca6f1..71fe6946 100644 --- a/ash/accessibility/default_accessibility_delegate.h +++ b/ash/accessibility/default_accessibility_delegate.h
@@ -17,7 +17,6 @@ DefaultAccessibilityDelegate(); ~DefaultAccessibilityDelegate() override; - bool IsSpokenFeedbackEnabled() const override; void SetMagnifierEnabled(bool enabled) override; bool IsMagnifierEnabled() const override; void SetAutoclickEnabled(bool enabled) override; @@ -41,8 +40,6 @@ bool ShouldShowAccessibilityMenu() const override; bool IsBrailleDisplayConnected() const override; void SilenceSpokenFeedback() const override; - void ToggleSpokenFeedback( - AccessibilityNotificationVisibility notify) override; void SaveScreenMagnifierScale(double scale) override; double GetSavedScreenMagnifierScale() override; bool ShouldToggleSpokenFeedbackViaTouch() override; @@ -52,7 +49,6 @@ void HandleAccessibilityGesture(ui::AXGesture gesture) override; private: - bool spoken_feedback_enabled_ = false; bool screen_magnifier_enabled_ = false; bool autoclick_enabled_ = false; bool virtual_keyboard_enabled_ = false;
diff --git a/ash/app_list/app_list_presenter_delegate.cc b/ash/app_list/app_list_presenter_delegate.cc index e17b59c..aa2b08b 100644 --- a/ash/app_list/app_list_presenter_delegate.cc +++ b/ash/app_list/app_list_presenter_delegate.cc
@@ -48,8 +48,8 @@ // until after this function is called.) keyboard::KeyboardController* keyboard_controller = keyboard::KeyboardController::GetInstance(); - if (keyboard_controller && keyboard_controller->keyboard_visible()) - bounds.Subtract(keyboard_controller->current_keyboard_bounds()); + if (keyboard_controller) + bounds.Subtract(keyboard_controller->GetWorkspaceObscuringBounds()); // Apply the |minimum_height|. if (bounds.height() < minimum_height)
diff --git a/ash/app_list/model/search_box_model.cc b/ash/app_list/model/search_box_model.cc index d94c542d..e91012b 100644 --- a/ash/app_list/model/search_box_model.cc +++ b/ash/app_list/model/search_box_model.cc
@@ -12,16 +12,10 @@ namespace app_list { SearchBoxModel::SpeechButtonProperty::SpeechButtonProperty( - const gfx::ImageSkia& on_icon, - const base::string16& on_tooltip, - const gfx::ImageSkia& off_icon, - const base::string16& off_tooltip, + const gfx::ImageSkia& icon, + const base::string16& tooltip, const base::string16& accessible_name) - : on_icon(on_icon), - on_tooltip(on_tooltip), - off_icon(off_icon), - off_tooltip(off_tooltip), - accessible_name(accessible_name) {} + : icon(icon), tooltip(tooltip), accessible_name(accessible_name) {} SearchBoxModel::SpeechButtonProperty::~SpeechButtonProperty() = default;
diff --git a/ash/app_list/model/search_box_model.h b/ash/app_list/model/search_box_model.h index 450698a..f20f74b 100644 --- a/ash/app_list/model/search_box_model.h +++ b/ash/app_list/model/search_box_model.h
@@ -5,6 +5,8 @@ #ifndef ASH_APP_LIST_MODEL_SEARCH_BOX_MODEL_H_ #define ASH_APP_LIST_MODEL_SEARCH_BOX_MODEL_H_ +#include <memory> + #include "ash/app_list/model/app_list_model_export.h" #include "base/macros.h" #include "base/observer_list.h" @@ -25,20 +27,13 @@ public: // The properties of the speech button. struct APP_LIST_MODEL_EXPORT SpeechButtonProperty { - SpeechButtonProperty(const gfx::ImageSkia& on_icon, - const base::string16& on_tooltip, - const gfx::ImageSkia& off_icon, - const base::string16& off_tooltip, + SpeechButtonProperty(const gfx::ImageSkia& icon, + const base::string16& tooltip, const base::string16& accessible_name); ~SpeechButtonProperty(); - // The icon/tooltip when the hotword is on. - gfx::ImageSkia on_icon; - base::string16 on_tooltip; - - // The icon/tooltip when the hotword is off. - gfx::ImageSkia off_icon; - base::string16 off_tooltip; + gfx::ImageSkia icon; + base::string16 tooltip; // The accessibility name of the button. base::string16 accessible_name;
diff --git a/ash/ash_touch_exploration_manager_chromeos.cc b/ash/ash_touch_exploration_manager_chromeos.cc index a453885..c090a49b 100644 --- a/ash/ash_touch_exploration_manager_chromeos.cc +++ b/ash/ash_touch_exploration_manager_chromeos.cc
@@ -7,6 +7,7 @@ #include <memory> #include <vector> +#include "ash/accessibility/accessibility_controller.h" #include "ash/accessibility/accessibility_delegate.h" #include "ash/accessibility/accessibility_focus_ring_controller.h" #include "ash/keyboard/keyboard_observer_register.h" @@ -67,7 +68,7 @@ } void AshTouchExplorationManager::SilenceSpokenFeedback() { - if (Shell::Get()->accessibility_delegate()->IsSpokenFeedbackEnabled()) + if (Shell::Get()->accessibility_controller()->IsSpokenFeedbackEnabled()) Shell::Get()->accessibility_delegate()->SilenceSpokenFeedback(); } @@ -135,8 +136,12 @@ void AshTouchExplorationManager::ToggleSpokenFeedback() { AccessibilityDelegate* delegate = Shell::Get()->accessibility_delegate(); - if (delegate->ShouldToggleSpokenFeedbackViaTouch()) - delegate->ToggleSpokenFeedback(ash::A11Y_NOTIFICATION_SHOW); + if (delegate->ShouldToggleSpokenFeedbackViaTouch()) { + AccessibilityController* controller = + Shell::Get()->accessibility_controller(); + controller->SetSpokenFeedbackEnabled(!controller->IsSpokenFeedbackEnabled(), + ash::A11Y_NOTIFICATION_SHOW); + } } void AshTouchExplorationManager::OnWindowActivated( @@ -180,7 +185,7 @@ aura::client::kAccessibilityTouchExplorationPassThrough); const bool spoken_feedback_enabled = - Shell::Get()->accessibility_delegate()->IsSpokenFeedbackEnabled(); + Shell::Get()->accessibility_controller()->IsSpokenFeedbackEnabled(); if (!touch_accessibility_enabler_) { // Always enable gesture to toggle spoken feedback.
diff --git a/ash/frame/caption_buttons/frame_caption_button.cc b/ash/frame/caption_buttons/frame_caption_button.cc index 11036a7..70c909a 100644 --- a/ash/frame/caption_buttons/frame_caption_button.cc +++ b/ash/frame/caption_buttons/frame_caption_button.cc
@@ -51,12 +51,16 @@ FrameCaptionButton::~FrameCaptionButton() = default; +// static +SkColor FrameCaptionButton::GetButtonColor(bool use_light_images) { + return use_light_images ? SK_ColorWHITE : gfx::kChromeIconGrey; +} + void FrameCaptionButton::SetImage(CaptionButtonIcon icon, Animate animate, const gfx::VectorIcon& icon_definition) { - gfx::ImageSkia new_icon_image = gfx::CreateVectorIcon( - icon_definition, - use_light_images_ ? SK_ColorWHITE : gfx::kChromeIconGrey); + gfx::ImageSkia new_icon_image = + gfx::CreateVectorIcon(icon_definition, GetButtonColor(use_light_images_)); // The early return is dependent on |animate| because callers use SetImage() // with ANIMATE_NO to progress the crossfade animation to the end.
diff --git a/ash/frame/caption_buttons/frame_caption_button.h b/ash/frame/caption_buttons/frame_caption_button.h index bf90e9a..adb7cac 100644 --- a/ash/frame/caption_buttons/frame_caption_button.h +++ b/ash/frame/caption_buttons/frame_caption_button.h
@@ -31,6 +31,9 @@ FrameCaptionButton(views::ButtonListener* listener, CaptionButtonIcon icon); ~FrameCaptionButton() override; + // Gets the color to use for a frame caption button. + static SkColor GetButtonColor(bool use_light_images); + // Sets the image to use to paint the button. If |animate| is ANIMATE_YES, // the button crossfades to the new visuals. If the image matches the one // currently used by the button and |animate| is ANIMATE_NO, the crossfade
diff --git a/ash/frame/default_frame_header.cc b/ash/frame/default_frame_header.cc index e6e6010d..016cc9d 100644 --- a/ash/frame/default_frame_header.cc +++ b/ash/frame/default_frame_header.cc
@@ -240,14 +240,6 @@ : active_frame_color_); } -// static -const gfx::FontList& DefaultFrameHeader::GetTitleFontList() { - static const gfx::FontList* title_font_list = - new gfx::FontList(views::NativeWidgetAura::GetWindowTitleFontList()); - ANNOTATE_LEAKING_OBJECT_PTR(title_font_list); - return *title_font_list; -} - void DefaultFrameHeader::UpdateLeftHeaderView(views::View* left_header_view) { left_header_view_ = left_header_view; } @@ -299,7 +291,8 @@ gfx::Rect title_bounds = GetAvailableTitleBounds(); title_bounds.set_x(view_->GetMirroredXForRect(title_bounds)); canvas->DrawStringRect(frame_->widget_delegate()->GetWindowTitle(), - GetTitleFontList(), GetTitleColor(), title_bounds); + views::NativeWidgetAura::GetWindowTitleFontList(), + GetTitleColor(), title_bounds); } void DefaultFrameHeader::PaintHeaderContentSeparator(gfx::Canvas* canvas) { @@ -344,7 +337,8 @@ gfx::Rect DefaultFrameHeader::GetAvailableTitleBounds() const { views::View* left_view = left_header_view_ ? left_header_view_ : back_button_; return FrameHeaderUtil::GetAvailableTitleBounds( - left_view, caption_button_container_, GetTitleFontList()); + left_view, caption_button_container_, + views::NativeWidgetAura::GetWindowTitleFontList()); } bool DefaultFrameHeader::UsesCustomFrameColors() const {
diff --git a/ash/frame/default_frame_header.h b/ash/frame/default_frame_header.h index dc901493..3f873017 100644 --- a/ash/frame/default_frame_header.h +++ b/ash/frame/default_frame_header.h
@@ -17,7 +17,6 @@ #include "ui/gfx/animation/animation_delegate.h" namespace gfx { -class FontList; class Rect; class SlideAnimation; } // namespace gfx @@ -75,9 +74,6 @@ bool ShouldUseLightImages() const; protected: - // Returns the FontList to use for the title. - static const gfx::FontList& GetTitleFontList(); - // Paints the title bar, primarily the title string. virtual void PaintTitleBar(gfx::Canvas* canvas);
diff --git a/ash/frame/detached_title_area_renderer.cc b/ash/frame/detached_title_area_renderer.cc index b889a98..1ee73f8a 100644 --- a/ash/frame/detached_title_area_renderer.cc +++ b/ash/frame/detached_title_area_renderer.cc
@@ -99,6 +99,8 @@ CreateInitParams("DetachedTitleAreaRendererForClient"); views::NativeWidgetAura* native_widget = new views::NativeWidgetAura(widget_, true); + native_widget->GetNativeView()->SetProperty( + aura::client::kEmbedType, aura::client::WindowEmbedType::TOP_LEVEL_IN_WM); aura::SetWindowType(native_widget->GetNativeWindow(), ui::mojom::WindowType::POPUP); ApplyProperties(native_widget->GetNativeWindow(),
diff --git a/ash/message_center/message_center_view.cc b/ash/message_center/message_center_view.cc index 189543d..b9320369 100644 --- a/ash/message_center/message_center_view.cc +++ b/ash/message_center/message_center_view.cc
@@ -459,11 +459,6 @@ message_center_->RemoveNotification(notification_id, by_user); } -std::unique_ptr<ui::MenuModel> MessageCenterView::CreateMenuModel( - const message_center::Notification& notification) { - return ui_controller_->CreateNotificationMenuModel(notification); -} - void MessageCenterView::ClickOnNotificationButton( const std::string& notification_id, int button_index) {
diff --git a/ash/message_center/message_center_view.h b/ash/message_center/message_center_view.h index b357d49..bf3f7cd 100644 --- a/ash/message_center/message_center_view.h +++ b/ash/message_center/message_center_view.h
@@ -103,8 +103,6 @@ void ClickOnNotification(const std::string& notification_id) override; void RemoveNotification(const std::string& notification_id, bool by_user) override; - std::unique_ptr<ui::MenuModel> CreateMenuModel( - const message_center::Notification& notification) override; void ClickOnNotificationButton(const std::string& notification_id, int button_index) override; void ClickOnNotificationButtonWithReply(const std::string& notification_id, @@ -190,8 +188,7 @@ // Current view mode. During animation, it is the target mode. Mode mode_ = Mode::NO_NOTIFICATIONS; - message_center::MessageViewContextMenuController context_menu_controller_{ - this}; + message_center::MessageViewContextMenuController context_menu_controller_; views::FocusManager* focus_manager_ = nullptr;
diff --git a/ash/message_center/message_center_view_unittest.cc b/ash/message_center/message_center_view_unittest.cc index aff6be5..368b676 100644 --- a/ash/message_center/message_center_view_unittest.cc +++ b/ash/message_center/message_center_view_unittest.cc
@@ -195,8 +195,6 @@ void ClickOnNotification(const std::string& notification_id) override; void RemoveNotification(const std::string& notification_id, bool by_user) override; - std::unique_ptr<ui::MenuModel> CreateMenuModel( - const Notification& notification) override; void ClickOnNotificationButton(const std::string& notification_id, int button_index) override; void ClickOnNotificationButtonWithReply(const std::string& notification_id, @@ -380,13 +378,6 @@ message_center_view_->OnNotificationRemoved(notification_id, by_user); } -std::unique_ptr<ui::MenuModel> MessageCenterViewTest::CreateMenuModel( - const Notification& notification) { - // For this test, this method should not be invoked. - NOTREACHED(); - return nullptr; -} - void MessageCenterViewTest::ClickOnNotificationButton( const std::string& notification_id, int button_index) {
diff --git a/ash/message_center/message_list_view_unittest.cc b/ash/message_center/message_list_view_unittest.cc index 5b7383e..dc3b0ada 100644 --- a/ash/message_center/message_list_view_unittest.cc +++ b/ash/message_center/message_list_view_unittest.cc
@@ -180,11 +180,6 @@ void ClickOnNotification(const std::string& notification_id) override {} void RemoveNotification(const std::string& notification_id, bool by_user) override {} - std::unique_ptr<ui::MenuModel> CreateMenuModel( - const Notification& notification) override { - NOTREACHED(); - return nullptr; - } void ClickOnNotificationButton(const std::string& notification_id, int button_index) override {} void ClickOnNotificationButtonWithReply(
diff --git a/ash/mus/window_manager_unittest.cc b/ash/mus/window_manager_unittest.cc new file mode 100644 index 0000000..96ecc6d --- /dev/null +++ b/ash/mus/window_manager_unittest.cc
@@ -0,0 +1,167 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include <map> +#include <memory> +#include <vector> + +#include "ash/mus/window_manager.h" +#include "ash/mus/window_manager_service.h" +#include "ash/public/cpp/window_properties.h" +#include "ash/public/interfaces/constants.mojom.h" +#include "ash/public/interfaces/window_properties.mojom.h" +#include "ash/session/test_session_controller_client.h" +#include "ash/shell.h" +#include "ash/test/ash_test_base.h" +#include "ash/test/ash_test_helper.h" +#include "base/bind.h" +#include "base/macros.h" +#include "base/run_loop.h" +#include "components/session_manager/session_manager_types.h" +#include "services/service_manager/public/cpp/service_test.h" +#include "services/ui/public/cpp/property_type_converters.h" +#include "services/ui/public/interfaces/window_manager_constants.mojom.h" +#include "services/ui/public/interfaces/window_tree.mojom.h" +#include "ui/aura/env.h" +#include "ui/aura/mus/property_converter.h" +#include "ui/aura/mus/window_tree_client.h" +#include "ui/aura/mus/window_tree_client_delegate.h" +#include "ui/aura/mus/window_tree_host_mus.h" +#include "ui/aura/mus/window_tree_host_mus_init_params.h" +#include "ui/aura/test/env_test_helper.h" +#include "ui/aura/window.h" +#include "ui/display/display.h" +#include "ui/display/display_list.h" +#include "ui/display/screen_base.h" +#include "ui/wm/core/capture_controller.h" +#include "ui/wm/core/wm_state.h" + +namespace ash { + +class WindowTreeClientDelegate : public aura::WindowTreeClientDelegate { + public: + WindowTreeClientDelegate() {} + ~WindowTreeClientDelegate() override {} + + void WaitForEmbed() { run_loop_.Run(); } + + void DestroyWindowTreeHost() { window_tree_host_.reset(); } + + private: + // aura::WindowTreeClientDelegate: + void OnEmbed( + std::unique_ptr<aura::WindowTreeHostMus> window_tree_host) override { + window_tree_host_ = std::move(window_tree_host); + run_loop_.Quit(); + } + void OnEmbedRootDestroyed( + aura::WindowTreeHostMus* window_tree_host) override {} + void OnLostConnection(aura::WindowTreeClient* client) override {} + void OnPointerEventObserved(const ui::PointerEvent& event, + aura::Window* target) override {} + aura::PropertyConverter* GetPropertyConverter() override { + return &property_converter_; + } + + base::RunLoop run_loop_; + ::wm::WMState wm_state_; + aura::PropertyConverter property_converter_; + std::unique_ptr<aura::WindowTreeHostMus> window_tree_host_; + + DISALLOW_COPY_AND_ASSIGN(WindowTreeClientDelegate); +}; + +class WindowManagerServiceTest : public service_manager::test::ServiceTest { + public: + WindowManagerServiceTest() + : service_manager::test::ServiceTest("mash_unittests") {} + ~WindowManagerServiceTest() override {} + + void TearDown() override { + // Unset the screen installed by the test. + display::Screen::SetScreenInstance(nullptr); + service_manager::test::ServiceTest::TearDown(); + } + + private: + DISALLOW_COPY_AND_ASSIGN(WindowManagerServiceTest); +}; + +void OnEmbed(bool success) { + ASSERT_TRUE(success); +} + +TEST_F(WindowManagerServiceTest, OpenWindow) { + display::ScreenBase screen; + screen.display_list().AddDisplay( + display::Display(1, gfx::Rect(0, 0, 200, 200)), + display::DisplayList::Type::PRIMARY); + display::Screen::SetScreenInstance(&screen); + + WindowTreeClientDelegate window_tree_delegate; + + connector()->StartService(mojom::kServiceName); + + // Connect to mus and create a new top level window. The request goes to + // |ash|, but is async. + aura::WindowTreeClient client(connector(), &window_tree_delegate, nullptr, + nullptr, nullptr, false); + client.ConnectViaWindowTreeFactory(); + aura::test::EnvWindowTreeClientSetter env_window_tree_client_setter(&client); + std::map<std::string, std::vector<uint8_t>> properties; + properties[ui::mojom::WindowManager::kWindowType_InitProperty] = + mojo::ConvertTo<std::vector<uint8_t>>( + static_cast<int32_t>(ui::mojom::WindowType::WINDOW)); + aura::WindowTreeHostMus window_tree_host_mus( + aura::CreateInitParamsForTopLevel(&client, std::move(properties))); + window_tree_host_mus.InitHost(); + aura::Window* child_window = new aura::Window(nullptr); + child_window->Init(ui::LAYER_NOT_DRAWN); + window_tree_host_mus.window()->AddChild(child_window); + + // Create another WindowTreeClient by way of embedding in + // |child_window|. This blocks until it succeeds. + ui::mojom::WindowTreeClientPtr tree_client; + auto tree_client_request = MakeRequest(&tree_client); + client.Embed(child_window, std::move(tree_client), 0u, base::Bind(&OnEmbed)); + aura::WindowTreeClient child_client(connector(), &window_tree_delegate, + nullptr, std::move(tree_client_request), + nullptr, false); + window_tree_delegate.WaitForEmbed(); + ASSERT_TRUE(!child_client.GetRoots().empty()); + window_tree_delegate.DestroyWindowTreeHost(); +} + +using WindowManagerTest = AshTestBase; + +TEST_F(WindowManagerTest, SystemModalLockIsntReparented) { + ash_test_helper()->test_session_controller_client()->SetSessionState( + session_manager::SessionState::LOCKED); + std::unique_ptr<aura::Window> window = CreateTestWindow(); + aura::Window* system_modal_container = Shell::GetContainer( + Shell::GetPrimaryRootWindow(), kShellWindowId_LockSystemModalContainer); + system_modal_container->AddChild(window.get()); + aura::WindowManagerDelegate* window_manager_delegate = + ash_test_helper()->window_manager_service()->window_manager(); + window_manager_delegate->OnWmSetModalType(window.get(), + ui::MODAL_TYPE_SYSTEM); + ASSERT_TRUE(window->parent()); + // Setting to system modal should not reparent. + EXPECT_EQ(kShellWindowId_LockSystemModalContainer, window->parent()->id()); +} + +TEST_F(WindowManagerTest, CanConsumeSystemKeysFromContentBrowser) { + std::map<std::string, std::vector<uint8_t>> properties; + properties[ash::mojom::kCanConsumeSystemKeys_Property] = + mojo::ConvertTo<std::vector<uint8_t>>(static_cast<int64_t>(true)); + + aura::WindowManagerDelegate* window_manager_delegate = + ash_test_helper()->window_manager_service()->window_manager(); + aura::Window* window = window_manager_delegate->OnWmCreateTopLevelWindow( + ui::mojom::WindowType::WINDOW, &properties); + + EXPECT_EQ(true, window->GetProperty(kCanConsumeSystemKeysKey)); +} + +} // namespace ash
diff --git a/ash/system/ime_menu/ime_menu_tray.cc b/ash/system/ime_menu/ime_menu_tray.cc index a6946d5..72d58e9 100644 --- a/ash/system/ime_menu/ime_menu_tray.cc +++ b/ash/system/ime_menu/ime_menu_tray.cc
@@ -4,6 +4,7 @@ #include "ash/system/ime_menu/ime_menu_tray.h" +#include "ash/accessibility/accessibility_controller.h" #include "ash/accessibility/accessibility_delegate.h" #include "ash/ash_constants.h" #include "ash/ime/ime_controller.h" @@ -508,7 +509,7 @@ } bool ImeMenuTray::ShouldEnableExtraKeyboardAccessibility() { - return Shell::Get()->accessibility_delegate()->IsSpokenFeedbackEnabled(); + return Shell::Get()->accessibility_controller()->IsSpokenFeedbackEnabled(); } void ImeMenuTray::HideBubble(const views::TrayBubbleView* bubble_view) {
diff --git a/ash/system/network/tray_network.cc b/ash/system/network/tray_network.cc index 8e1a9f9..cf8ea9f57 100644 --- a/ash/system/network/tray_network.cc +++ b/ash/system/network/tray_network.cc
@@ -78,6 +78,7 @@ : TrayItemView(network_tray) { CreateImageView(); UpdateNetworkStateHandlerIcon(); + UpdateConnectionStatus(GetConnectedNetwork(), true /* notify_a11y */); } ~NetworkTrayView() override { @@ -98,8 +99,6 @@ network_icon::NetworkIconAnimation::GetInstance()->AddObserver(this); else network_icon::NetworkIconAnimation::GetInstance()->RemoveObserver(this); - - UpdateConnectionStatus(GetConnectedNetwork()); } // views::View: @@ -109,11 +108,14 @@ } // network_icon::AnimationObserver: - void NetworkIconChanged() override { UpdateNetworkStateHandlerIcon(); } + void NetworkIconChanged() override { + UpdateNetworkStateHandlerIcon(); + UpdateConnectionStatus(GetConnectedNetwork(), false /* notify_a11y */); + } - private: // Updates connection status and notifies accessibility event when necessary. - void UpdateConnectionStatus(const NetworkState* connected_network) { + void UpdateConnectionStatus(const NetworkState* connected_network, + bool notify_a11y) { using SignalStrength = network_icon::SignalStrength; base::string16 new_connection_status_string; @@ -154,11 +156,12 @@ } if (new_connection_status_string != connection_status_string_) { connection_status_string_ = new_connection_status_string; - if (!connection_status_string_.empty()) + if (notify_a11y && !connection_status_string_.empty()) NotifyAccessibilityEvent(ui::AX_EVENT_ALERT, true); } } + private: void UpdateIcon(bool tray_icon_visible, const gfx::ImageSkia& image) { image_view()->SetImage(image); SetVisible(tray_icon_visible); @@ -306,12 +309,14 @@ } void TrayNetwork::OnCaptivePortalDetected(const std::string& /* guid */) { - NetworkStateChanged(); + NetworkStateChanged(true /* notify_a11y */); } -void TrayNetwork::NetworkStateChanged() { - if (tray_) +void TrayNetwork::NetworkStateChanged(bool notify_a11y) { + if (tray_) { tray_->UpdateNetworkStateHandlerIcon(); + tray_->UpdateConnectionStatus(tray::GetConnectedNetwork(), notify_a11y); + } if (default_) default_->Update(); if (detailed_)
diff --git a/ash/system/network/tray_network.h b/ash/system/network/tray_network.h index 93c68d69..3eecb71 100644 --- a/ash/system/network/tray_network.h +++ b/ash/system/network/tray_network.h
@@ -47,7 +47,7 @@ void OnCaptivePortalDetected(const std::string& guid) override; // TrayNetworkStateObserver::Delegate - void NetworkStateChanged() override; + void NetworkStateChanged(bool notify_a11y) override; private: tray::NetworkTrayView* tray_;
diff --git a/ash/system/network/tray_network_state_observer.cc b/ash/system/network/tray_network_state_observer.cc index 60e05c4..f2ea186 100644 --- a/ash/system/network/tray_network_state_observer.cc +++ b/ash/system/network/tray_network_state_observer.cc
@@ -48,18 +48,18 @@ void TrayNetworkStateObserver::NetworkListChanged() { purge_icons_ = true; - SignalUpdate(); + SignalUpdate(false /* notify_a11y */); } void TrayNetworkStateObserver::DeviceListChanged() { - SignalUpdate(); + SignalUpdate(false /* notify_a11y */); } // Any change to the Default (primary connected) network, including Strength // changes, should trigger a NetworkStateChanged update. void TrayNetworkStateObserver::DefaultNetworkChanged( const chromeos::NetworkState* network) { - SignalUpdate(); + SignalUpdate(true /* notify_a11y */); } // Any change to the Connection State should trigger a NetworkStateChanged @@ -67,7 +67,7 @@ // connected. void TrayNetworkStateObserver::NetworkConnectionStateChanged( const chromeos::NetworkState* network) { - SignalUpdate(); + SignalUpdate(true /* notify_a11y */); } // This tracks Strength and other property changes for all networks. It will @@ -75,18 +75,19 @@ // changes. void TrayNetworkStateObserver::NetworkPropertiesUpdated( const chromeos::NetworkState* network) { - SignalUpdate(); + SignalUpdate(false /* notify_a11y */); } -void TrayNetworkStateObserver::SignalUpdate() { +void TrayNetworkStateObserver::SignalUpdate(bool notify_a11y) { if (timer_.IsRunning()) return; timer_.Start(FROM_HERE, base::TimeDelta::FromMilliseconds(update_frequency_), - this, &TrayNetworkStateObserver::SendNetworkStateChanged); + base::Bind(&TrayNetworkStateObserver::SendNetworkStateChanged, + base::Unretained(this), notify_a11y)); } -void TrayNetworkStateObserver::SendNetworkStateChanged() { - delegate_->NetworkStateChanged(); +void TrayNetworkStateObserver::SendNetworkStateChanged(bool notify_a11y) { + delegate_->NetworkStateChanged(notify_a11y); if (purge_icons_) { network_icon::PurgeNetworkIconCache(); purge_icons_ = false;
diff --git a/ash/system/network/tray_network_state_observer.h b/ash/system/network/tray_network_state_observer.h index 9e6e8ed..ead056d 100644 --- a/ash/system/network/tray_network_state_observer.h +++ b/ash/system/network/tray_network_state_observer.h
@@ -17,7 +17,7 @@ public: // Called when any interesting network changes occur. The frequency of this // event is limited to kUpdateFrequencyMs. - virtual void NetworkStateChanged() = 0; + virtual void NetworkStateChanged(bool notify_a11y) = 0; protected: virtual ~Delegate() {} @@ -36,8 +36,8 @@ void NetworkPropertiesUpdated(const chromeos::NetworkState* network) override; private: - void SignalUpdate(); - void SendNetworkStateChanged(); + void SignalUpdate(bool notify_a11y); + void SendNetworkStateChanged(bool notify_a11y); // Unowned Delegate pointer (must outlive this instance). Delegate* delegate_;
diff --git a/ash/system/network/tray_vpn.cc b/ash/system/network/tray_vpn.cc index 802a252..53d3e2a3 100644 --- a/ash/system/network/tray_vpn.cc +++ b/ash/system/network/tray_vpn.cc
@@ -186,7 +186,7 @@ detailed_ = nullptr; } -void TrayVPN::NetworkStateChanged() { +void TrayVPN::NetworkStateChanged(bool /* notify_a11y */) { if (default_) default_->Update(); if (detailed_)
diff --git a/ash/system/network/tray_vpn.h b/ash/system/network/tray_vpn.h index cda9c84..01047c6 100644 --- a/ash/system/network/tray_vpn.h +++ b/ash/system/network/tray_vpn.h
@@ -32,7 +32,7 @@ void OnDetailedViewDestroyed() override; // TrayNetworkStateObserver::Delegate - void NetworkStateChanged() override; + void NetworkStateChanged(bool notify_a11y) override; private: tray::VpnDefaultView* default_;
diff --git a/ash/system/palette/palette_tray.cc b/ash/system/palette/palette_tray.cc index 8924a37af..aeb5bba5 100644 --- a/ash/system/palette/palette_tray.cc +++ b/ash/system/palette/palette_tray.cc
@@ -6,7 +6,7 @@ #include <memory> -#include "ash/accessibility/accessibility_delegate.h" +#include "ash/accessibility/accessibility_controller.h" #include "ash/public/cpp/ash_pref_names.h" #include "ash/public/cpp/config.h" #include "ash/public/cpp/stylus_utils.h" @@ -332,7 +332,7 @@ } bool PaletteTray::ShouldEnableExtraKeyboardAccessibility() { - return Shell::Get()->accessibility_delegate()->IsSpokenFeedbackEnabled(); + return Shell::Get()->accessibility_controller()->IsSpokenFeedbackEnabled(); } void PaletteTray::HideBubble(const views::TrayBubbleView* bubble_view) {
diff --git a/ash/system/power/peripheral_battery_notifier_unittest.cc b/ash/system/power/peripheral_battery_notifier_unittest.cc index 7aeb48f..0b5c913b 100644 --- a/ash/system/power/peripheral_battery_notifier_unittest.cc +++ b/ash/system/power/peripheral_battery_notifier_unittest.cc
@@ -167,7 +167,8 @@ EXPECT_TRUE(non_bluetooth_device_info.bluetooth_address.empty()); } -TEST_F(PeripheralBatteryNotifierTest, DeviceRemove) { +// TODO(crbug.com/765794): Flaky on ash_unittests --mus. +TEST_F(PeripheralBatteryNotifierTest, DISABLED_DeviceRemove) { message_center::MessageCenter* message_center = message_center::MessageCenter::Get();
diff --git a/ash/system/toast/toast_manager_unittest.cc b/ash/system/toast/toast_manager_unittest.cc index 604134d8..c08b6a6 100644 --- a/ash/system/toast/toast_manager_unittest.cc +++ b/ash/system/toast/toast_manager_unittest.cc
@@ -190,9 +190,10 @@ gfx::Rect shelf_bounds = shelf->GetIdealBounds(); EXPECT_FALSE(toast_bounds.Intersects(shelf_bounds)); - EXPECT_EQ(shelf_bounds.y() - 5, toast_bounds.bottom()); - EXPECT_EQ(root_bounds.bottom() - shelf_bounds.height() - 5, - toast_bounds.bottom()); + EXPECT_EQ(shelf_bounds.y() - ToastOverlay::kOffset, toast_bounds.bottom()); + EXPECT_EQ( + root_bounds.bottom() - shelf_bounds.height() - ToastOverlay::kOffset, + toast_bounds.bottom()); } TEST_F(ToastManagerTest, PositionWithAutoHiddenBottomShelf) { @@ -213,7 +214,7 @@ EXPECT_TRUE(toast_bounds.Intersects(shelf->GetUserWorkAreaBounds())); EXPECT_NEAR(root_bounds.CenterPoint().x(), toast_bounds.CenterPoint().x(), 1); - EXPECT_EQ(root_bounds.bottom() - kShelfAutoHideSize - 5, + EXPECT_EQ(root_bounds.bottom() - kShelfAutoHideSize - ToastOverlay::kOffset, toast_bounds.bottom()); } @@ -232,7 +233,8 @@ EXPECT_TRUE(toast_bounds.Intersects(shelf->GetUserWorkAreaBounds())); EXPECT_NEAR(root_bounds.CenterPoint().x(), toast_bounds.CenterPoint().x(), 1); - EXPECT_EQ(root_bounds.bottom() - 5, toast_bounds.bottom()); + EXPECT_EQ(root_bounds.bottom() - ToastOverlay::kOffset, + toast_bounds.bottom()); } TEST_F(ToastManagerTest, PositionWithVisibleLeftShelf) { @@ -249,7 +251,8 @@ ScreenUtil::GetDisplayBoundsWithShelf(shelf->GetWindow()); EXPECT_TRUE(toast_bounds.Intersects(shelf->GetUserWorkAreaBounds())); - EXPECT_EQ(root_bounds.bottom() - 5, toast_bounds.bottom()); + EXPECT_EQ(root_bounds.bottom() - ToastOverlay::kOffset, + toast_bounds.bottom()); gfx::Rect shelf_bounds = shelf->GetIdealBounds(); EXPECT_FALSE(toast_bounds.Intersects(shelf_bounds)); @@ -279,9 +282,10 @@ gfx::Rect shelf_bounds = shelf->GetIdealBounds(); EXPECT_FALSE(toast_bounds.Intersects(shelf_bounds)); - EXPECT_EQ(shelf_bounds.y() - 5, toast_bounds.bottom()); - EXPECT_EQ(root_bounds.bottom() - shelf_bounds.height() - 5, - toast_bounds.bottom()); + EXPECT_EQ(shelf_bounds.y() - ToastOverlay::kOffset, toast_bounds.bottom()); + EXPECT_EQ( + root_bounds.bottom() - shelf_bounds.height() - ToastOverlay::kOffset, + toast_bounds.bottom()); } TEST_F(ToastManagerTest, CancelToast) {
diff --git a/ash/system/toast/toast_overlay.cc b/ash/system/toast/toast_overlay.cc index 22bded7..a1f6dbe 100644 --- a/ash/system/toast/toast_overlay.cc +++ b/ash/system/toast/toast_overlay.cc
@@ -18,6 +18,7 @@ #include "ui/gfx/canvas.h" #include "ui/gfx/font_list.h" #include "ui/gfx/geometry/insets.h" +#include "ui/views/animation/ink_drop_mask.h" #include "ui/views/border.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/label.h" @@ -31,21 +32,21 @@ namespace { -// Offset of the overlay from the edge of the work area. -const int kOffset = 5; - // Duration of slide animation when overlay is shown or hidden. -const int kSlideAnimationDurationMs = 100; +constexpr int kSlideAnimationDurationMs = 100; // Colors for the dismiss button. -const SkColor kButtonBackgroundColor = SkColorSetARGB(0xFF, 0x32, 0x32, 0x32); -const SkColor kButtonTextColor = SkColorSetARGB(0xFF, 0x7B, 0xAA, 0xF7); +constexpr SkColor kButtonBackgroundColor = + SkColorSetARGB(0xCC, 0x00, 0x00, 0x00); +constexpr SkColor kButtonTextColor = SkColorSetARGB(0xFF, 0xD2, 0xE3, 0xFC); // These values are in DIP. -const int kToastHorizontalSpacing = 16; -const int kToastVerticalSpacing = 16; -const int kToastMaximumWidth = 568; -const int kToastMinimumWidth = 288; +constexpr int kToastCornerRounding = 16; +constexpr int kToastHeight = 32; +constexpr int kToastHorizontalSpacing = 16; +constexpr int kToastMaximumWidth = 512; +constexpr int kToastMinimumWidth = 288; +constexpr int kToastButtonMaximumWidth = 160; // Returns the work area bounds for the root window where new windows are added // (including new toasts). @@ -58,61 +59,64 @@ // ToastOverlayLabel class ToastOverlayLabel : public views::Label { public: - explicit ToastOverlayLabel(const base::string16& label); - ~ToastOverlayLabel() override; + explicit ToastOverlayLabel(const base::string16& label) + : Label(label, CONTEXT_TOAST_OVERLAY) { + SetHorizontalAlignment(gfx::ALIGN_LEFT); + SetAutoColorReadabilityEnabled(false); + SetMultiLine(true); + SetMaxLines(2); + SetEnabledColor(SK_ColorWHITE); + SetSubpixelRenderingEnabled(false); + + int vertical_spacing = + std::max((kToastHeight - GetPreferredSize().height()) / 2, 0); + SetBorder(views::CreateEmptyBorder( + gfx::Insets(vertical_spacing, kToastHorizontalSpacing))); + } + + ~ToastOverlayLabel() override = default; private: DISALLOW_COPY_AND_ASSIGN(ToastOverlayLabel); }; -ToastOverlayLabel::ToastOverlayLabel(const base::string16& label) - : Label(label, CONTEXT_TOAST_OVERLAY) { - SetHorizontalAlignment(gfx::ALIGN_LEFT); - SetAutoColorReadabilityEnabled(false); - SetMultiLine(true); - SetEnabledColor(SK_ColorWHITE); - SetSubpixelRenderingEnabled(false); - - int verticalSpacing = - kToastVerticalSpacing - (GetPreferredSize().height() - GetBaseline()); - SetBorder(views::CreateEmptyBorder(verticalSpacing, kToastHorizontalSpacing, - verticalSpacing, kToastHorizontalSpacing)); -} - -ToastOverlayLabel::~ToastOverlayLabel() = default; - } // namespace /////////////////////////////////////////////////////////////////////////////// // ToastOverlayButton class ToastOverlayButton : public views::LabelButton { public: - explicit ToastOverlayButton(views::ButtonListener* listener, - const base::string16& label); + ToastOverlayButton(views::ButtonListener* listener, + const base::string16& text) + : views::LabelButton(listener, text, CONTEXT_TOAST_OVERLAY) { + SetInkDropMode(InkDropMode::ON); + set_has_ink_drop_action_on_click(true); + set_ink_drop_base_color(SK_ColorWHITE); + + SetEnabledTextColors(kButtonTextColor); + + // Treat the space below the baseline as a margin. + int vertical_spacing = + std::max((kToastHeight - GetPreferredSize().height()) / 2, 0); + SetBorder(views::CreateEmptyBorder( + gfx::Insets(vertical_spacing, kToastHorizontalSpacing))); + } + ~ToastOverlayButton() override = default; + protected: + // views::LabelButton: + std::unique_ptr<views::InkDropMask> CreateInkDropMask() const override { + return std::make_unique<views::RoundRectInkDropMask>(size(), gfx::Insets(), + kToastCornerRounding); + } + private: friend class ToastOverlay; // for ToastOverlay::ClickDismissButtonForTesting. DISALLOW_COPY_AND_ASSIGN(ToastOverlayButton); }; -ToastOverlayButton::ToastOverlayButton(views::ButtonListener* listener, - const base::string16& text) - : views::LabelButton(listener, text, CONTEXT_TOAST_OVERLAY) { - SetInkDropMode(InkDropMode::ON); - set_has_ink_drop_action_on_click(true); - set_ink_drop_base_color(SK_ColorWHITE); - - SetEnabledTextColors(kButtonTextColor); - - // Treat the space below the baseline as a margin. - int verticalSpacing = kToastVerticalSpacing - - (GetPreferredSize().height() - label()->GetBaseline()); - SetBorder(views::CreateEmptyBorder(verticalSpacing, kToastHorizontalSpacing, - verticalSpacing, kToastHorizontalSpacing)); -} - /////////////////////////////////////////////////////////////////////////////// // ToastOverlayView class ToastOverlayView : public views::View, public views::ButtonListener { @@ -120,21 +124,63 @@ // This object is not owned by the views hierarchy or by the widget. ToastOverlayView(ToastOverlay* overlay, const base::string16& text, - const base::Optional<base::string16>& dismiss_text); - ~ToastOverlayView() override; + const base::Optional<base::string16>& dismiss_text) + : overlay_(overlay) { + auto* layout = new views::BoxLayout(views::BoxLayout::kHorizontal); + SetLayoutManager(layout); - // views::View overrides: - void OnPaint(gfx::Canvas* canvas) override; + if (dismiss_text.has_value()) { + button_ = new ToastOverlayButton( + this, dismiss_text.value().empty() + ? l10n_util::GetStringUTF16(IDS_ASH_TOAST_DISMISS_BUTTON) + : dismiss_text.value()); + } + + auto* label = new ToastOverlayLabel(text); + AddChildView(label); + label->SetMaximumWidth(GetMaximumSize().width()); + layout->SetFlexForView(label, 1); + + if (button_) { + int button_width = std::min(button_->GetPreferredSize().width(), + kToastButtonMaximumWidth); + button_->SetMaxSize(gfx::Size(button_width, GetMaximumSize().height())); + label->SetMaximumWidth(GetMaximumSize().width() - button_width - + kToastHorizontalSpacing * 2 - + kToastHorizontalSpacing * 2); + AddChildView(button_); + } + } + + ~ToastOverlayView() override = default; ToastOverlayButton* button() { return button_; } - private: - // views::View overrides: - gfx::Size GetMaximumSize() const override; - gfx::Size GetMinimumSize() const override; + // views::View: + void OnPaint(gfx::Canvas* canvas) override { + cc::PaintFlags flags; + flags.setStyle(cc::PaintFlags::kFill_Style); + flags.setColor(kButtonBackgroundColor); + canvas->DrawRoundRect(GetLocalBounds(), kToastCornerRounding, flags); + views::View::OnPaint(canvas); + } - // views::ButtonListener overrides: - void ButtonPressed(views::Button* sender, const ui::Event& event) override; + private: + // views::View: + gfx::Size GetMinimumSize() const override { + return gfx::Size(kToastMinimumWidth, kToastHeight); + } + + gfx::Size GetMaximumSize() const override { + return gfx::Size(kToastMaximumWidth, GetUserWorkAreaBounds().height() - + ToastOverlay::kOffset * 2); + } + + // views::ButtonListener: + void ButtonPressed(views::Button* sender, const ui::Event& event) override { + DCHECK_EQ(button_, sender); + overlay_->Show(false); + } ToastOverlay* overlay_ = nullptr; // weak ToastOverlayButton* button_ = nullptr; // weak @@ -142,58 +188,6 @@ DISALLOW_COPY_AND_ASSIGN(ToastOverlayView); }; -ToastOverlayView::ToastOverlayView( - ToastOverlay* overlay, - const base::string16& text, - const base::Optional<base::string16>& dismiss_text) - : overlay_(overlay) { - auto* layout = new views::BoxLayout(views::BoxLayout::kHorizontal); - SetLayoutManager(layout); - - if (dismiss_text.has_value()) { - button_ = new ToastOverlayButton( - this, dismiss_text.value().empty() - ? l10n_util::GetStringUTF16(IDS_ASH_TOAST_DISMISS_BUTTON) - : dismiss_text.value()); - } - - ToastOverlayLabel* label = new ToastOverlayLabel(text); - AddChildView(label); - layout->SetFlexForView(label, 1); - - if (button_) { - label->SetMaximumWidth( - GetMaximumSize().width() - button_->GetPreferredSize().width() - - kToastHorizontalSpacing * 2 - kToastHorizontalSpacing * 2); - AddChildView(button_); - } -} - -ToastOverlayView::~ToastOverlayView() = default; - -void ToastOverlayView::OnPaint(gfx::Canvas* canvas) { - cc::PaintFlags flags; - flags.setStyle(cc::PaintFlags::kFill_Style); - flags.setColor(kButtonBackgroundColor); - canvas->DrawRoundRect(GetLocalBounds(), 2, flags); - views::View::OnPaint(canvas); -} - -gfx::Size ToastOverlayView::GetMinimumSize() const { - return gfx::Size(kToastMinimumWidth, 0); -} - -gfx::Size ToastOverlayView::GetMaximumSize() const { - gfx::Rect work_area_bounds = GetUserWorkAreaBounds(); - return gfx::Size(kToastMaximumWidth, work_area_bounds.height() - kOffset * 2); -} - -void ToastOverlayView::ButtonPressed(views::Button* sender, - const ui::Event& event) { - DCHECK_EQ(button_, sender); - overlay_->Show(false); -} - /////////////////////////////////////////////////////////////////////////////// // ToastOverlay ToastOverlay::ToastOverlay(Delegate* delegate, @@ -250,8 +244,8 @@ base::TimeDelta original_duration = animator->GetTransitionDuration(); ui::ScopedLayerAnimationSettings animation_settings(animator); - // ScopedLayerAnimationSettings ctor chanes the transition duration, so change - // back it to the original value (should be zero). + // ScopedLayerAnimationSettings ctor changes the transition duration, so + // change it back to the original value (should be zero). animation_settings.SetTransitionDuration(original_duration); animation_settings.AddObserver(this); @@ -268,7 +262,8 @@ gfx::Rect ToastOverlay::CalculateOverlayBounds() { gfx::Rect bounds = GetUserWorkAreaBounds(); - int target_y = bounds.bottom() - widget_size_.height() - kOffset; + int target_y = + bounds.bottom() - widget_size_.height() - ToastOverlay::kOffset; bounds.ClampToCenteredSize(widget_size_); bounds.set_y(target_y); return bounds;
diff --git a/ash/system/toast/toast_overlay.h b/ash/system/toast/toast_overlay.h index 034eb880..4f20b01b 100644 --- a/ash/system/toast/toast_overlay.h +++ b/ash/system/toast/toast_overlay.h
@@ -37,6 +37,9 @@ virtual void OnClosed() = 0; }; + // Offset of the overlay from the edge of the work area. + static constexpr int kOffset = 16; + // Creates the Toast overlay UI. |text| is the message to be shown, and // |dismiss_text| is the message for the button to dismiss the toast message. // If |dismiss_text| is null, no dismiss button will be shown. If
diff --git a/ash/system/tray/system_tray.cc b/ash/system/tray/system_tray.cc index df22319b..62f1e1a 100644 --- a/ash/system/tray/system_tray.cc +++ b/ash/system/tray/system_tray.cc
@@ -9,6 +9,7 @@ #include <memory> #include <vector> +#include "ash/accessibility/accessibility_controller.h" #include "ash/login_status.h" #include "ash/metrics/user_metrics_recorder.h" #include "ash/public/cpp/ash_switches.h" @@ -621,7 +622,7 @@ // e.g. volume slider. Persistent system bubble is a bubble which is not // closed even if user clicks outside of the bubble. return system_bubble_ && !system_bubble_->is_persistent() && - Shell::Get()->accessibility_delegate()->IsSpokenFeedbackEnabled(); + Shell::Get()->accessibility_controller()->IsSpokenFeedbackEnabled(); } void SystemTray::HideBubble(const TrayBubbleView* bubble_view) {
diff --git a/ash/system/tray_accessibility.cc b/ash/system/tray_accessibility.cc index 4ca6c379..bf37398 100644 --- a/ash/system/tray_accessibility.cc +++ b/ash/system/tray_accessibility.cc
@@ -63,7 +63,7 @@ AccessibilityController* controller = Shell::Get()->accessibility_controller(); uint32_t state = A11Y_NONE; - if (delegate->IsSpokenFeedbackEnabled()) + if (controller->IsSpokenFeedbackEnabled()) state |= A11Y_SPOKEN_FEEDBACK; if (controller->IsHighContrastEnabled()) state |= A11Y_HIGH_CONTRAST; @@ -157,7 +157,7 @@ AccessibilityController* controller = Shell::Get()->accessibility_controller(); - spoken_feedback_enabled_ = delegate->IsSpokenFeedbackEnabled(); + spoken_feedback_enabled_ = controller->IsSpokenFeedbackEnabled(); TrayPopupUtils::UpdateCheckMarkVisibility(spoken_feedback_view_, spoken_feedback_enabled_); @@ -215,7 +215,7 @@ AccessibilityController* controller = Shell::Get()->accessibility_controller(); - spoken_feedback_enabled_ = delegate->IsSpokenFeedbackEnabled(); + spoken_feedback_enabled_ = controller->IsSpokenFeedbackEnabled(); spoken_feedback_view_ = AddScrollListCheckableItem( kSystemMenuAccessibilityChromevoxIcon, l10n_util::GetStringUTF16( @@ -304,10 +304,11 @@ using base::RecordAction; using base::UserMetricsAction; if (view == spoken_feedback_view_) { - RecordAction(delegate->IsSpokenFeedbackEnabled() - ? UserMetricsAction("StatusArea_SpokenFeedbackDisabled") - : UserMetricsAction("StatusArea_SpokenFeedbackEnabled")); - delegate->ToggleSpokenFeedback(A11Y_NOTIFICATION_NONE); + bool new_state = !controller->IsSpokenFeedbackEnabled(); + RecordAction(new_state + ? UserMetricsAction("StatusArea_SpokenFeedbackEnabled") + : UserMetricsAction("StatusArea_SpokenFeedbackDisabled")); + controller->SetSpokenFeedbackEnabled(new_state, A11Y_NOTIFICATION_NONE); } else if (view == high_contrast_view_) { bool new_state = !controller->IsHighContrastEnabled(); RecordAction(new_state
diff --git a/ash/system/tray_accessibility_unittest.cc b/ash/system/tray_accessibility_unittest.cc index 26f1347..2940a63 100644 --- a/ash/system/tray_accessibility_unittest.cc +++ b/ash/system/tray_accessibility_unittest.cc
@@ -12,7 +12,11 @@ #include "ash/system/tray/system_tray_notifier.h" #include "ash/system/tray/system_tray_test_api.h" #include "ash/test/ash_test_base.h" +#include "base/strings/utf_string_conversions.h" #include "components/prefs/pref_service.h" +#include "ui/message_center/message_center.h" + +using message_center::MessageCenter; namespace ash { namespace { @@ -66,5 +70,27 @@ EXPECT_FALSE(tray_item->tray_view()->visible()); } +TEST_F(TrayAccessibilityTest, ShowNotificationOnSpokenFeedback) { + const base::string16 kChromeVoxEnabledTitle = + base::ASCIIToUTF16("ChromeVox enabled"); + const base::string16 kChromeVoxEnabled = + base::ASCIIToUTF16("Press Ctrl + Alt + Z to disable spoken feedback."); + AccessibilityController* controller = + Shell::Get()->accessibility_controller(); + + // Enabling spoken feedback should show the notification. + controller->SetSpokenFeedbackEnabled(true, A11Y_NOTIFICATION_SHOW); + message_center::NotificationList::Notifications notifications = + MessageCenter::Get()->GetVisibleNotifications(); + EXPECT_EQ(1u, notifications.size()); + EXPECT_EQ(kChromeVoxEnabledTitle, (*notifications.begin())->title()); + EXPECT_EQ(kChromeVoxEnabled, (*notifications.begin())->message()); + + // Disabling spoken feedback should not show any notification. + controller->SetSpokenFeedbackEnabled(false, A11Y_NOTIFICATION_SHOW); + notifications = MessageCenter::Get()->GetVisibleNotifications(); + EXPECT_EQ(0u, notifications.size()); +} + } // namespace } // namespace ash
diff --git a/ash/system/user/button_from_view.cc b/ash/system/user/button_from_view.cc index cc399c0f..cbcdf04 100644 --- a/ash/system/user/button_from_view.cc +++ b/ash/system/user/button_from_view.cc
@@ -17,6 +17,7 @@ #include "ui/views/animation/ink_drop_highlight.h" #include "ui/views/animation/ink_drop_impl.h" #include "ui/views/animation/ink_drop_mask.h" +#include "ui/views/background.h" #include "ui/views/layout/fill_layout.h" #include "ui/views/painter.h" @@ -43,6 +44,9 @@ SetFocusForPlatform(); SetFocusPainter(TrayPopupUtils::CreateFocusPainter()); + + SetBackground(views::CreateThemedSolidBackground( + this, ui::NativeTheme::kColorId_BubbleBackground)); } ButtonFromView::~ButtonFromView() = default;
diff --git a/ash/system/user/user_view.cc b/ash/system/user/user_view.cc index 085294f..f34f542 100644 --- a/ash/system/user/user_view.cc +++ b/ash/system/user/user_view.cc
@@ -357,9 +357,8 @@ color_utils::GetResultingPaintColor(kMenuSeparatorColor, bg_color)); const int separator_horizontal_padding = (kTrayPopupItemMinStartWidth - kTrayItemSize) / 2; - separator->SetBorder( - views::CreateSolidSidedBorder(0, separator_horizontal_padding, 0, - separator_horizontal_padding, bg_color)); + separator->SetBorder(views::CreateEmptyBorder( + 0, separator_horizontal_padding, 0, separator_horizontal_padding)); user_dropdown_padding->AddChildView(separator); // Add other logged in users.
diff --git a/ash/system/web_notification/web_notification_tray.cc b/ash/system/web_notification/web_notification_tray.cc index 8a9d85b..a244fb9 100644 --- a/ash/system/web_notification/web_notification_tray.cc +++ b/ash/system/web_notification/web_notification_tray.cc
@@ -6,7 +6,7 @@ #include <memory> -#include "ash/accessibility/accessibility_delegate.h" +#include "ash/accessibility/accessibility_controller.h" #include "ash/message_center/message_center_bubble.h" #include "ash/resources/vector_icons/vector_icons.h" #include "ash/root_window_controller.h" @@ -461,7 +461,7 @@ } bool WebNotificationTray::ShouldEnableExtraKeyboardAccessibility() { - return Shell::Get()->accessibility_delegate()->IsSpokenFeedbackEnabled(); + return Shell::Get()->accessibility_controller()->IsSpokenFeedbackEnabled(); } void WebNotificationTray::HideBubble(const views::TrayBubbleView* bubble_view) {
diff --git a/ash/test/ash_test_helper.cc b/ash/test/ash_test_helper.cc index 0cf6936..8200cd0 100644 --- a/ash/test/ash_test_helper.cc +++ b/ash/test/ash_test_helper.cc
@@ -95,7 +95,9 @@ switches::kAshDisableSmoothScreenRotation); } - if (config_ == Config::MUS) + // Allow for other code to have created InputDeviceManager (such as the + // test-suite). + if (config_ == Config::MUS && !ui::InputDeviceManager::HasInstance()) input_device_client_ = std::make_unique<ui::InputDeviceClient>(); display::ResetDisplayIdForTest(); @@ -231,6 +233,7 @@ command_line_.reset(); display::Display::ResetForceDeviceScaleFactorForTesting(); + env_window_tree_client_setter_.reset(); // WindowManager owns the CaptureController for mus/mash. CHECK(config_ != Config::CLASSIC || !::wm::CaptureController::Get()); @@ -267,8 +270,9 @@ window_tree_client_setup_.InitForWindowManager( window_manager_service_->window_manager_.get(), window_manager_service_->window_manager_.get()); - aura::test::EnvTestHelper().SetWindowTreeClient( - window_tree_client_setup_.window_tree_client()); + env_window_tree_client_setter_ = + std::make_unique<aura::test::EnvWindowTreeClientSetter>( + window_tree_client_setup_.window_tree_client()); // Classic ash does not start the NetworkHandler in tests, so don't start it // for mash either. The NetworkHandler may cause subtle side effects (such as // additional tray items) that can make for flaky tests.
diff --git a/ash/test/ash_test_helper.h b/ash/test/ash_test_helper.h index 38afb974..1ed288e 100644 --- a/ash/test/ash_test_helper.h +++ b/ash/test/ash_test_helper.h
@@ -21,6 +21,9 @@ namespace aura { class Window; class WindowTreeClientPrivate; +namespace test { +class EnvWindowTreeClientSetter; +} } namespace display { @@ -129,6 +132,8 @@ static Config config_; + std::unique_ptr<aura::test::EnvWindowTreeClientSetter> + env_window_tree_client_setter_; AshTestEnvironment* ash_test_environment_; // Not owned. TestShellDelegate* test_shell_delegate_; // Owned by ash::Shell. std::unique_ptr<ui::ScopedAnimationDurationScaleMode> zero_duration_mode_;
diff --git a/ash/test/ash_test_suite.cc b/ash/test/ash_test_suite.cc index ccf694a7..e3bb96c 100644 --- a/ash/test/ash_test_suite.cc +++ b/ash/test/ash_test_suite.cc
@@ -4,9 +4,6 @@ #include "ash/test/ash_test_suite.h" -#include <memory> -#include <set> - #include "ash/public/cpp/config.h" #include "ash/test/ash_test_environment.h" #include "ash/test/ash_test_helper.h" @@ -16,80 +13,15 @@ #include "base/metrics/statistics_recorder.h" #include "base/path_service.h" #include "build/build_config.h" -#include "cc/test/fake_output_surface.h" -#include "cc/test/test_context_provider.h" -#include "components/viz/test/test_layer_tree_frame_sink.h" #include "testing/gtest/include/gtest/gtest.h" +#include "ui/aura/test/aura_test_context_factory.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/ui_base_paths.h" -#include "ui/compositor/test/fake_context_factory.h" +#include "ui/base/ui_base_switches.h" #include "ui/gfx/gfx_paths.h" #include "ui/gl/test/gl_surface_test_support.h" namespace ash { -namespace { - -class FrameSinkClient : public viz::TestLayerTreeFrameSinkClient { - public: - explicit FrameSinkClient( - scoped_refptr<viz::ContextProvider> display_context_provider) - : display_context_provider_(std::move(display_context_provider)) {} - - std::unique_ptr<viz::OutputSurface> CreateDisplayOutputSurface( - scoped_refptr<viz::ContextProvider> compositor_context_provider) - override { - return cc::FakeOutputSurface::Create3d( - std::move(display_context_provider_)); - } - - void DisplayReceivedLocalSurfaceId( - const viz::LocalSurfaceId& local_surface_id) override {} - void DisplayReceivedCompositorFrame( - const viz::CompositorFrame& frame) override {} - void DisplayWillDrawAndSwap( - bool will_draw_and_swap, - const viz::RenderPassList& render_passes) override {} - void DisplayDidDrawAndSwap() override {} - - private: - scoped_refptr<viz::ContextProvider> display_context_provider_; - - DISALLOW_COPY_AND_ASSIGN(FrameSinkClient); -}; - -class AshTestContextFactory : public ui::FakeContextFactory { - public: - AshTestContextFactory() = default; - ~AshTestContextFactory() override = default; - - // ui::FakeContextFactory - void CreateLayerTreeFrameSink( - base::WeakPtr<ui::Compositor> compositor) override { - scoped_refptr<cc::TestContextProvider> context_provider = - cc::TestContextProvider::Create(); - std::unique_ptr<FrameSinkClient> frame_sink_client = - std::make_unique<FrameSinkClient>(context_provider); - constexpr bool synchronous_composite = false; - constexpr bool disable_display_vsync = false; - const double refresh_rate = GetRefreshRate(); - auto frame_sink = std::make_unique<viz::TestLayerTreeFrameSink>( - context_provider, cc::TestContextProvider::CreateWorker(), nullptr, - GetGpuMemoryBufferManager(), renderer_settings(), - base::ThreadTaskRunnerHandle::Get().get(), synchronous_composite, - disable_display_vsync, refresh_rate); - frame_sink->SetClient(frame_sink_client.get()); - compositor->SetLayerTreeFrameSink(std::move(frame_sink)); - frame_sink_clients_.insert(std::move(frame_sink_client)); - } - - private: - std::set<std::unique_ptr<viz::TestLayerTreeFrameSinkClient>> - frame_sink_clients_; - - DISALLOW_COPY_AND_ASSIGN(AshTestContextFactory); -}; - -} // namespace AshTestSuite::AshTestSuite(int argc, char** argv) : TestSuite(argc, argv) {} @@ -139,9 +71,12 @@ : aura::Env::Mode::LOCAL); if (is_mus || is_mash) { - context_factory_ = std::make_unique<AshTestContextFactory>(); + context_factory_ = std::make_unique<aura::test::AuraTestContextFactory>(); env_->set_context_factory(context_factory_.get()); env_->set_context_factory_private(nullptr); + // mus needs to host viz, because ash by itself cannot. + base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( + switches::kMus, switches::kMusHostVizValue); } }
diff --git a/ash/window_manager_unittest.cc b/ash/window_manager_unittest.cc index 8991b5b..00b1bbc9 100644 --- a/ash/window_manager_unittest.cc +++ b/ash/window_manager_unittest.cc
@@ -108,7 +108,7 @@ aura::WindowTreeClient client(connector(), &window_tree_delegate, nullptr, nullptr, nullptr, false); client.ConnectViaWindowTreeFactory(); - aura::test::EnvTestHelper().SetWindowTreeClient(&client); + aura::test::EnvWindowTreeClientSetter env_window_tree_client_setter(&client); std::map<std::string, std::vector<uint8_t>> properties; properties[ui::mojom::WindowManager::kWindowType_InitProperty] = mojo::ConvertTo<std::vector<uint8_t>>(
diff --git a/ash/wm/workspace/backdrop_controller.cc b/ash/wm/workspace/backdrop_controller.cc index 87785864c..39b8418 100644 --- a/ash/wm/workspace/backdrop_controller.cc +++ b/ash/wm/workspace/backdrop_controller.cc
@@ -6,6 +6,7 @@ #include <memory> +#include "ash/accessibility/accessibility_controller.h" #include "ash/accessibility/accessibility_delegate.h" #include "ash/public/cpp/app_types.h" #include "ash/public/cpp/shell_window_ids.h" @@ -190,7 +191,7 @@ return; bool enabled = - Shell::Get()->accessibility_delegate()->IsSpokenFeedbackEnabled(); + Shell::Get()->accessibility_controller()->IsSpokenFeedbackEnabled(); if (enabled) { if (!backdrop_event_handler_) { backdrop_event_handler_ = std::make_unique<BackdropEventHandler>(); @@ -228,7 +229,7 @@ if (window->GetProperty(aura::client::kAppType) == static_cast<int>(AppType::ARC_APP) && wm::IsActiveWindow(window) && - Shell::Get()->accessibility_delegate()->IsSpokenFeedbackEnabled()) { + Shell::Get()->accessibility_controller()->IsSpokenFeedbackEnabled()) { return true; }
diff --git a/ash/wm/workspace/workspace_layout_manager_unittest.cc b/ash/wm/workspace/workspace_layout_manager_unittest.cc index a2d2763..9b1b30f 100644 --- a/ash/wm/workspace/workspace_layout_manager_unittest.cc +++ b/ash/wm/workspace/workspace_layout_manager_unittest.cc
@@ -7,6 +7,7 @@ #include <string> #include <utility> +#include "ash/accessibility/accessibility_controller.h" #include "ash/accessibility/test_accessibility_delegate.h" #include "ash/app_list/test_app_list_presenter_impl.h" #include "ash/frame/custom_frame_view_ash.h" @@ -24,7 +25,6 @@ #include "ash/shell.h" #include "ash/shell_observer.h" #include "ash/shell_test_api.h" -#include "ash/system/tray/system_tray_notifier.h" #include "ash/test/ash_test_base.h" #include "ash/wm/fullscreen_window_finder.h" #include "ash/wm/overview/window_selector_controller.h" @@ -1325,12 +1325,10 @@ EXPECT_EQ(kNoSoundKey, accessibility_delegate->GetPlayedEarconAndReset()); // Enable spoken feedback. - Shell::Get()->accessibility_delegate()->ToggleSpokenFeedback( - ash::A11Y_NOTIFICATION_NONE); - Shell::Get()->system_tray_notifier()->NotifyAccessibilityStatusChanged( - ash::A11Y_NOTIFICATION_NONE); - EXPECT_TRUE( - Shell::Get()->accessibility_delegate()->IsSpokenFeedbackEnabled()); + AccessibilityController* controller = + Shell::Get()->accessibility_controller(); + controller->SetSpokenFeedbackEnabled(true, A11Y_NOTIFICATION_NONE); + EXPECT_TRUE(controller->IsSpokenFeedbackEnabled()); generator.MoveMouseTo(300, 300); generator.ClickLeftButton(); @@ -1342,12 +1340,8 @@ EXPECT_EQ(kNoSoundKey, accessibility_delegate->GetPlayedEarconAndReset()); // Disable spoken feedback. Shadow underlay is restored. - Shell::Get()->accessibility_delegate()->ToggleSpokenFeedback( - A11Y_NOTIFICATION_NONE); - Shell::Get()->system_tray_notifier()->NotifyAccessibilityStatusChanged( - A11Y_NOTIFICATION_NONE); - EXPECT_FALSE( - Shell::Get()->accessibility_delegate()->IsSpokenFeedbackEnabled()); + controller->SetSpokenFeedbackEnabled(false, A11Y_NOTIFICATION_NONE); + EXPECT_FALSE(controller->IsSpokenFeedbackEnabled()); generator.MoveMouseTo(300, 300); generator.ClickLeftButton(); @@ -1441,11 +1435,11 @@ TestAccessibilityDelegate* accessibility_delegate = static_cast<TestAccessibilityDelegate*>( Shell::Get()->accessibility_delegate()); + AccessibilityController* controller = + Shell::Get()->accessibility_controller(); - accessibility_delegate->ToggleSpokenFeedback(A11Y_NOTIFICATION_NONE); - Shell::Get()->system_tray_notifier()->NotifyAccessibilityStatusChanged( - A11Y_NOTIFICATION_NONE); - EXPECT_TRUE(accessibility_delegate->IsSpokenFeedbackEnabled()); + controller->SetSpokenFeedbackEnabled(true, A11Y_NOTIFICATION_NONE); + EXPECT_TRUE(controller->IsSpokenFeedbackEnabled()); aura::test::TestWindowDelegate delegate; std::unique_ptr<aura::Window> window_arc(CreateTestWindowInShellWithDelegate(
diff --git a/base/BUILD.gn b/base/BUILD.gn index 2400e40..cd240f9 100644 --- a/base/BUILD.gn +++ b/base/BUILD.gn
@@ -1277,6 +1277,8 @@ "files/file_path_watcher_fuchsia.cc", "fuchsia/default_job.cc", "fuchsia/default_job.h", + "fuchsia/fuchsia_logging.cc", + "fuchsia/fuchsia_logging.h", "fuchsia/scoped_zx_handle.h", "memory/shared_memory_fuchsia.cc", "memory/shared_memory_handle_fuchsia.cc", @@ -2848,6 +2850,7 @@ "android/library_loader/library_load_from_apk_status_codes.h", "android/library_loader/library_loader_hooks.h", "memory/memory_pressure_listener.h", + "metrics/histogram_base.h", ] }
diff --git a/base/allocator/partition_allocator/partition_alloc_unittest.cc b/base/allocator/partition_allocator/partition_alloc_unittest.cc index a9da138..5bd790e 100644 --- a/base/allocator/partition_allocator/partition_alloc_unittest.cc +++ b/base/allocator/partition_allocator/partition_alloc_unittest.cc
@@ -103,9 +103,9 @@ class PartitionAllocTest : public testing::Test { protected: - PartitionAllocTest() {} + PartitionAllocTest() = default; - ~PartitionAllocTest() override {} + ~PartitionAllocTest() override = default; void SetUp() override { allocator.init();
diff --git a/base/android/java/src/org/chromium/base/BuildInfo.java b/base/android/java/src/org/chromium/base/BuildInfo.java index 874c3b2..f88d7deb 100644 --- a/base/android/java/src/org/chromium/base/BuildInfo.java +++ b/base/android/java/src/org/chromium/base/BuildInfo.java
@@ -8,6 +8,7 @@ import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Build; +import android.os.Build.VERSION; import android.text.TextUtils; import org.chromium.base.annotations.CalledByNative; @@ -124,6 +125,9 @@ return "eng".equals(Build.TYPE) || "userdebug".equals(Build.TYPE); } + // The markers Begin:BuildCompat and End:BuildCompat delimit code + // that is autogenerated from Android sources. + // Begin:BuildCompat O,OMR1,P /** * @return Whether the current device is running Android O release or newer. * @@ -131,6 +135,7 @@ */ @Deprecated public static boolean isAtLeastO() { - return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O; + return VERSION.SDK_INT >= Build.VERSION_CODES.O; } + // End:BuildCompat }
diff --git a/base/android/java/src/org/chromium/base/LocaleUtils.java b/base/android/java/src/org/chromium/base/LocaleUtils.java index 2f51455..85a62b98 100644 --- a/base/android/java/src/org/chromium/base/LocaleUtils.java +++ b/base/android/java/src/org/chromium/base/LocaleUtils.java
@@ -32,7 +32,7 @@ static { // A variation of this mapping also exists in: - // build/android/gyp/package_resources.py + // build/android/gyp/process_resources.py HashMap<String, String> mapForChromium = new HashMap<>(); mapForChromium.put("iw", "he"); // Hebrew mapForChromium.put("ji", "yi"); // Yiddish
diff --git a/base/android/java/src/org/chromium/base/metrics/StatisticsRecorderAndroid.java b/base/android/java/src/org/chromium/base/metrics/StatisticsRecorderAndroid.java index 62a37949..bff3fae7 100644 --- a/base/android/java/src/org/chromium/base/metrics/StatisticsRecorderAndroid.java +++ b/base/android/java/src/org/chromium/base/metrics/StatisticsRecorderAndroid.java
@@ -15,11 +15,13 @@ private StatisticsRecorderAndroid() {} /** - * @return All the registered histograms as JSON text. - */ - public static String toJson() { - return nativeToJson(); + * @param verbosityLevel controls the information that should be included when dumping each of + * the histogram. + * @return All the registered histograms as JSON text. + */ + public static String toJson(@JSONVerbosityLevel int verbosityLevel) { + return nativeToJson(verbosityLevel); } - private static native String nativeToJson(); + private static native String nativeToJson(@JSONVerbosityLevel int verbosityLevel); } \ No newline at end of file
diff --git a/base/android/statistics_recorder_android.cc b/base/android/statistics_recorder_android.cc index 509ea19c..346a7c7 100644 --- a/base/android/statistics_recorder_android.cc +++ b/base/android/statistics_recorder_android.cc
@@ -5,7 +5,9 @@ #include <string> #include "base/android/jni_string.h" +#include "base/metrics/histogram_base.h" #include "base/metrics/statistics_recorder.h" +#include "base/sys_info.h" #include "jni/StatisticsRecorderAndroid_jni.h" using base::android::JavaParamRef; @@ -16,9 +18,11 @@ static ScopedJavaLocalRef<jstring> JNI_StatisticsRecorderAndroid_ToJson( JNIEnv* env, - const JavaParamRef<jclass>& clazz) { + const JavaParamRef<jclass>& clazz, + jint verbosityLevel) { return ConvertUTF8ToJavaString( - env, base::StatisticsRecorder::ToJSON(std::string())); + env, base::StatisticsRecorder::ToJSON( + static_cast<JSONVerbosityLevel>(verbosityLevel))); } } // namespace android
diff --git a/base/bind_unittest.cc b/base/bind_unittest.cc index ef948c1..7deba47 100644 --- a/base/bind_unittest.cc +++ b/base/bind_unittest.cc
@@ -31,7 +31,7 @@ class NoRef { public: - NoRef() {} + NoRef() = default; MOCK_METHOD0(VoidMethod0, void()); MOCK_CONST_METHOD0(VoidConstMethod0, void()); @@ -49,7 +49,7 @@ class HasRef : public NoRef { public: - HasRef() {} + HasRef() = default; MOCK_CONST_METHOD0(AddRef, void()); MOCK_CONST_METHOD0(Release, bool()); @@ -61,7 +61,7 @@ class HasRefPrivateDtor : public HasRef { private: - ~HasRefPrivateDtor() {} + ~HasRefPrivateDtor() = default; }; static const int kParentValue = 1; @@ -196,11 +196,8 @@ public: CopyCounter(int* copies, int* assigns) : counter_(copies, assigns, nullptr, nullptr) {} - CopyCounter(const CopyCounter& other) : counter_(other.counter_) {} - CopyCounter& operator=(const CopyCounter& other) { - counter_ = other.counter_; - return *this; - } + CopyCounter(const CopyCounter& other) = default; + CopyCounter& operator=(const CopyCounter& other) = default; explicit CopyCounter(const DerivedCopyMoveCounter& other) : counter_(other) {} @@ -321,8 +318,7 @@ static_func_mock_ptr = &static_func_mock_; } - virtual ~BindTest() { - } + virtual ~BindTest() = default; static void VoidFunc0() { static_func_mock_ptr->VoidMethod0();
diff --git a/base/callback_helpers.cc b/base/callback_helpers.cc index 1f87a6c..9086731 100644 --- a/base/callback_helpers.cc +++ b/base/callback_helpers.cc
@@ -6,7 +6,7 @@ namespace base { -ScopedClosureRunner::ScopedClosureRunner() {} +ScopedClosureRunner::ScopedClosureRunner() = default; ScopedClosureRunner::ScopedClosureRunner(OnceClosure closure) : closure_(std::move(closure)) {}
diff --git a/base/callback_internal.cc b/base/callback_internal.cc index 864c1a0..0179bb7 100644 --- a/base/callback_internal.cc +++ b/base/callback_internal.cc
@@ -71,7 +71,7 @@ DCHECK(!bind_state_.get() || bind_state_->HasOneRef()); } -CallbackBase::~CallbackBase() {} +CallbackBase::~CallbackBase() = default; CallbackBaseCopyable::CallbackBaseCopyable(const CallbackBaseCopyable& c) : CallbackBase(nullptr) {
diff --git a/base/callback_unittest.cc b/base/callback_unittest.cc index f76adbc..c07d3ee 100644 --- a/base/callback_unittest.cc +++ b/base/callback_unittest.cc
@@ -25,7 +25,7 @@ FakeBindState() : BindStateBase(&NopInvokeFunc, &Destroy, &IsCancelled) {} private: - ~FakeBindState() {} + ~FakeBindState() = default; static void Destroy(const internal::BindStateBase* self) { delete static_cast<const FakeBindState*>(self); } @@ -41,7 +41,7 @@ CallbackTest() : callback_a_(new FakeBindState()), callback_b_(new FakeBindState()) {} - ~CallbackTest() override {} + ~CallbackTest() override = default; protected: Callback<void()> callback_a_;
diff --git a/base/cancelable_callback_unittest.cc b/base/cancelable_callback_unittest.cc index e793a83..373498c 100644 --- a/base/cancelable_callback_unittest.cc +++ b/base/cancelable_callback_unittest.cc
@@ -23,7 +23,8 @@ class TestRefCounted : public RefCountedThreadSafe<TestRefCounted> { private: friend class RefCountedThreadSafe<TestRefCounted>; - ~TestRefCounted() {}; + ~TestRefCounted() = default; + ; }; void Increment(int* count) { (*count)++; }
diff --git a/base/command_line.cc b/base/command_line.cc index 69c5fb1..3a5d089b 100644 --- a/base/command_line.cc +++ b/base/command_line.cc
@@ -174,21 +174,11 @@ InitFromArgv(argv); } -CommandLine::CommandLine(const CommandLine& other) - : argv_(other.argv_), - switches_(other.switches_), - begin_args_(other.begin_args_) { -} +CommandLine::CommandLine(const CommandLine& other) = default; -CommandLine& CommandLine::operator=(const CommandLine& other) { - argv_ = other.argv_; - switches_ = other.switches_; - begin_args_ = other.begin_args_; - return *this; -} +CommandLine& CommandLine::operator=(const CommandLine& other) = default; -CommandLine::~CommandLine() { -} +CommandLine::~CommandLine() = default; #if defined(OS_WIN) // static
diff --git a/base/containers/linked_list_unittest.cc b/base/containers/linked_list_unittest.cc index 4b40fbf..3470c86b 100644 --- a/base/containers/linked_list_unittest.cc +++ b/base/containers/linked_list_unittest.cc
@@ -28,7 +28,7 @@ class MultipleInheritanceNode : public MultipleInheritanceNodeBase, public LinkNode<MultipleInheritanceNode> { public: - MultipleInheritanceNode() {} + MultipleInheritanceNode() = default; }; // Checks that when iterating |list| (either from head to tail, or from
diff --git a/base/containers/small_map_unittest.cc b/base/containers/small_map_unittest.cc index d33549f..6561851 100644 --- a/base/containers/small_map_unittest.cc +++ b/base/containers/small_map_unittest.cc
@@ -443,7 +443,7 @@ class unordered_map_add_item : public std::unordered_map<int, int> { public: - unordered_map_add_item() {} + unordered_map_add_item() = default; explicit unordered_map_add_item(const std::pair<int, int>& item) { insert(item); }
diff --git a/base/containers/stack_container_unittest.cc b/base/containers/stack_container_unittest.cc index 2090705..b6bb9b6 100644 --- a/base/containers/stack_container_unittest.cc +++ b/base/containers/stack_container_unittest.cc
@@ -107,7 +107,7 @@ class AlignedData { public: AlignedData() { memset(data_, 0, alignment); } - ~AlignedData() {} + ~AlignedData() = default; alignas(alignment) char data_[alignment]; };
diff --git a/base/cpu.cc b/base/cpu.cc index 132a6964..cd9066f5 100644 --- a/base/cpu.cc +++ b/base/cpu.cc
@@ -107,17 +107,14 @@ std::string contents; ReadFileToString(FilePath("/proc/cpuinfo"), &contents); DCHECK(!contents.empty()); - if (contents.empty()) { - return new std::string(); - } std::istringstream iss(contents); std::string line; while (std::getline(iss, line)) { - if ((line.compare(0, strlen(kModelNamePrefix), kModelNamePrefix) == 0 || - line.compare(0, strlen(kProcessorPrefix), kProcessorPrefix) == 0)) { + if (line.compare(0, strlen(kModelNamePrefix), kModelNamePrefix) == 0) return new std::string(line.substr(strlen(kModelNamePrefix))); - } + if (line.compare(0, strlen(kProcessorPrefix), kProcessorPrefix) == 0) + return new std::string(line.substr(strlen(kProcessorPrefix))); } return new std::string();
diff --git a/base/debug/activity_analyzer.cc b/base/debug/activity_analyzer.cc index 5cb7b71d..d787829 100644 --- a/base/debug/activity_analyzer.cc +++ b/base/debug/activity_analyzer.cc
@@ -41,8 +41,8 @@ } // namespace -ThreadActivityAnalyzer::Snapshot::Snapshot() {} -ThreadActivityAnalyzer::Snapshot::~Snapshot() {} +ThreadActivityAnalyzer::Snapshot::Snapshot() = default; +ThreadActivityAnalyzer::Snapshot::~Snapshot() = default; ThreadActivityAnalyzer::ThreadActivityAnalyzer( const ThreadActivityTracker& tracker) @@ -60,7 +60,7 @@ PersistentMemoryAllocator::kSizeAny), allocator->GetAllocSize(reference)) {} -ThreadActivityAnalyzer::~ThreadActivityAnalyzer() {} +ThreadActivityAnalyzer::~ThreadActivityAnalyzer() = default; void ThreadActivityAnalyzer::AddGlobalInformation( GlobalActivityAnalyzer* global) { @@ -87,7 +87,7 @@ DCHECK(allocator_); } -GlobalActivityAnalyzer::~GlobalActivityAnalyzer() {} +GlobalActivityAnalyzer::~GlobalActivityAnalyzer() = default; // static std::unique_ptr<GlobalActivityAnalyzer> @@ -298,12 +298,12 @@ return !allocator_->IsFull(); } -GlobalActivityAnalyzer::UserDataSnapshot::UserDataSnapshot() {} +GlobalActivityAnalyzer::UserDataSnapshot::UserDataSnapshot() = default; GlobalActivityAnalyzer::UserDataSnapshot::UserDataSnapshot( const UserDataSnapshot& rhs) = default; GlobalActivityAnalyzer::UserDataSnapshot::UserDataSnapshot( UserDataSnapshot&& rhs) = default; -GlobalActivityAnalyzer::UserDataSnapshot::~UserDataSnapshot() {} +GlobalActivityAnalyzer::UserDataSnapshot::~UserDataSnapshot() = default; void GlobalActivityAnalyzer::PrepareAllAnalyzers() { // Record the time when analysis started.
diff --git a/base/debug/activity_analyzer_unittest.cc b/base/debug/activity_analyzer_unittest.cc index 78a8e19..e08b43a 100644 --- a/base/debug/activity_analyzer_unittest.cc +++ b/base/debug/activity_analyzer_unittest.cc
@@ -37,7 +37,7 @@ : ThreadActivityTracker(memset(memory.get(), 0, mem_size), mem_size), mem_segment_(std::move(memory)) {} - ~TestActivityTracker() override {} + ~TestActivityTracker() override = default; private: std::unique_ptr<char[]> mem_segment_; @@ -51,7 +51,7 @@ const int kMemorySize = 1 << 20; // 1MiB const int kStackSize = 1 << 10; // 1KiB - ActivityAnalyzerTest() {} + ActivityAnalyzerTest() = default; ~ActivityAnalyzerTest() override { GlobalActivityTracker* global_tracker = GlobalActivityTracker::Get(); @@ -119,7 +119,7 @@ exit_(false), exit_condition_(&lock_) {} - ~SimpleActivityThread() override {} + ~SimpleActivityThread() override = default; void Run() override { ThreadActivityTracker::ActivityId id =
diff --git a/base/debug/activity_tracker.cc b/base/debug/activity_tracker.cc index 264ad6b5..1b3aaeec 100644 --- a/base/debug/activity_tracker.cc +++ b/base/debug/activity_tracker.cc
@@ -120,8 +120,8 @@ } // namespace -OwningProcess::OwningProcess() {} -OwningProcess::~OwningProcess() {} +OwningProcess::OwningProcess() = default; +OwningProcess::~OwningProcess() = default; void OwningProcess::Release_Initialize(int64_t pid) { uint32_t old_id = data_id.load(std::memory_order_acquire); @@ -185,7 +185,7 @@ DCHECK(allocator); } -ActivityTrackerMemoryAllocator::~ActivityTrackerMemoryAllocator() {} +ActivityTrackerMemoryAllocator::~ActivityTrackerMemoryAllocator() = default; ActivityTrackerMemoryAllocator::Reference ActivityTrackerMemoryAllocator::GetObjectReference() { @@ -276,9 +276,9 @@ #endif } -ActivityUserData::TypedValue::TypedValue() {} +ActivityUserData::TypedValue::TypedValue() = default; ActivityUserData::TypedValue::TypedValue(const TypedValue& other) = default; -ActivityUserData::TypedValue::~TypedValue() {} +ActivityUserData::TypedValue::~TypedValue() = default; StringPiece ActivityUserData::TypedValue::Get() const { DCHECK_EQ(RAW_VALUE, type_); @@ -323,13 +323,13 @@ // These are required because std::atomic is (currently) not a POD type and // thus clang requires explicit out-of-line constructors and destructors even // when they do nothing. -ActivityUserData::ValueInfo::ValueInfo() {} +ActivityUserData::ValueInfo::ValueInfo() = default; ActivityUserData::ValueInfo::ValueInfo(ValueInfo&&) = default; -ActivityUserData::ValueInfo::~ValueInfo() {} -ActivityUserData::MemoryHeader::MemoryHeader() {} -ActivityUserData::MemoryHeader::~MemoryHeader() {} -ActivityUserData::FieldHeader::FieldHeader() {} -ActivityUserData::FieldHeader::~FieldHeader() {} +ActivityUserData::ValueInfo::~ValueInfo() = default; +ActivityUserData::MemoryHeader::MemoryHeader() = default; +ActivityUserData::MemoryHeader::~MemoryHeader() = default; +ActivityUserData::FieldHeader::FieldHeader() = default; +ActivityUserData::FieldHeader::~FieldHeader() = default; ActivityUserData::ActivityUserData() : ActivityUserData(nullptr, 0, -1) {} @@ -362,7 +362,7 @@ ImportExistingData(); } -ActivityUserData::~ActivityUserData() {} +ActivityUserData::~ActivityUserData() = default; bool ActivityUserData::CreateSnapshot(Snapshot* output_snapshot) const { DCHECK(output_snapshot); @@ -655,8 +655,8 @@ char thread_name[32]; }; -ThreadActivityTracker::Snapshot::Snapshot() {} -ThreadActivityTracker::Snapshot::~Snapshot() {} +ThreadActivityTracker::Snapshot::Snapshot() = default; +ThreadActivityTracker::Snapshot::~Snapshot() = default; ThreadActivityTracker::ScopedActivity::ScopedActivity( ThreadActivityTracker* tracker, @@ -758,7 +758,7 @@ } } -ThreadActivityTracker::~ThreadActivityTracker() {} +ThreadActivityTracker::~ThreadActivityTracker() = default; ThreadActivityTracker::ActivityId ThreadActivityTracker::PushActivity( const void* program_counter, @@ -1082,18 +1082,18 @@ // of std::atomic because the latter can create global ctors and dtors. subtle::AtomicWord GlobalActivityTracker::g_tracker_ = 0; -GlobalActivityTracker::ModuleInfo::ModuleInfo() {} +GlobalActivityTracker::ModuleInfo::ModuleInfo() = default; GlobalActivityTracker::ModuleInfo::ModuleInfo(ModuleInfo&& rhs) = default; GlobalActivityTracker::ModuleInfo::ModuleInfo(const ModuleInfo& rhs) = default; -GlobalActivityTracker::ModuleInfo::~ModuleInfo() {} +GlobalActivityTracker::ModuleInfo::~ModuleInfo() = default; GlobalActivityTracker::ModuleInfo& GlobalActivityTracker::ModuleInfo::operator=( ModuleInfo&& rhs) = default; GlobalActivityTracker::ModuleInfo& GlobalActivityTracker::ModuleInfo::operator=( const ModuleInfo& rhs) = default; -GlobalActivityTracker::ModuleInfoRecord::ModuleInfoRecord() {} -GlobalActivityTracker::ModuleInfoRecord::~ModuleInfoRecord() {} +GlobalActivityTracker::ModuleInfoRecord::ModuleInfoRecord() = default; +GlobalActivityTracker::ModuleInfoRecord::~ModuleInfoRecord() = default; bool GlobalActivityTracker::ModuleInfoRecord::DecodeTo( GlobalActivityTracker::ModuleInfo* info, @@ -1225,7 +1225,7 @@ int64_t pid) : ActivityUserData(memory, size, pid) {} -GlobalActivityTracker::ThreadSafeUserData::~ThreadSafeUserData() {} +GlobalActivityTracker::ThreadSafeUserData::~ThreadSafeUserData() = default; void GlobalActivityTracker::ThreadSafeUserData::Set(StringPiece name, ValueType type,
diff --git a/base/debug/activity_tracker_unittest.cc b/base/debug/activity_tracker_unittest.cc index 1c7ed7acc..79d19db 100644 --- a/base/debug/activity_tracker_unittest.cc +++ b/base/debug/activity_tracker_unittest.cc
@@ -33,7 +33,7 @@ : ThreadActivityTracker(memset(memory.get(), 0, mem_size), mem_size), mem_segment_(std::move(memory)) {} - ~TestActivityTracker() override {} + ~TestActivityTracker() override = default; private: std::unique_ptr<char[]> mem_segment_; @@ -49,7 +49,7 @@ using ActivityId = ThreadActivityTracker::ActivityId; - ActivityTrackerTest() {} + ActivityTrackerTest() = default; ~ActivityTrackerTest() override { GlobalActivityTracker* global_tracker = GlobalActivityTracker::Get(); @@ -260,7 +260,7 @@ data_changed_(false), is_running_(false) {} - ~SimpleLockThread() override {} + ~SimpleLockThread() override = default; void Run() override { ThreadActivityTracker* tracker = @@ -401,7 +401,7 @@ exit_(false), exit_condition_(&lock_) {} - ~SimpleActivityThread() override {} + ~SimpleActivityThread() override = default; void Run() override { ThreadActivityTracker::ActivityId id =
diff --git a/base/debug/stack_trace_posix.cc b/base/debug/stack_trace_posix.cc index fdaff1c..1d7df1f6 100644 --- a/base/debug/stack_trace_posix.cc +++ b/base/debug/stack_trace_posix.cc
@@ -129,7 +129,7 @@ virtual void HandleOutput(const char* output) = 0; protected: - virtual ~BacktraceOutputHandler() {} + virtual ~BacktraceOutputHandler() = default; }; #if !defined(__UCLIBC__) && !defined(_AIX) @@ -415,7 +415,7 @@ class PrintBacktraceOutputHandler : public BacktraceOutputHandler { public: - PrintBacktraceOutputHandler() {} + PrintBacktraceOutputHandler() = default; void HandleOutput(const char* output) override { // NOTE: This code MUST be async-signal safe (it's used by in-process
diff --git a/base/debug/task_annotator.cc b/base/debug/task_annotator.cc index 31f11be..b9ff7f7 100644 --- a/base/debug/task_annotator.cc +++ b/base/debug/task_annotator.cc
@@ -14,11 +14,9 @@ namespace base { namespace debug { -TaskAnnotator::TaskAnnotator() { -} +TaskAnnotator::TaskAnnotator() = default; -TaskAnnotator::~TaskAnnotator() { -} +TaskAnnotator::~TaskAnnotator() = default; void TaskAnnotator::DidQueueTask(const char* queue_function, const PendingTask& pending_task) {
diff --git a/base/deferred_sequenced_task_runner.cc b/base/deferred_sequenced_task_runner.cc index 21cb99a6..9830402 100644 --- a/base/deferred_sequenced_task_runner.cc +++ b/base/deferred_sequenced_task_runner.cc
@@ -18,8 +18,7 @@ DeferredSequencedTaskRunner::DeferredTask::DeferredTask(DeferredTask&& other) = default; -DeferredSequencedTaskRunner::DeferredTask::~DeferredTask() { -} +DeferredSequencedTaskRunner::DeferredTask::~DeferredTask() = default; DeferredSequencedTaskRunner::DeferredTask& DeferredSequencedTaskRunner::DeferredTask::operator=(DeferredTask&& other) = @@ -29,8 +28,7 @@ scoped_refptr<SequencedTaskRunner> target_task_runner) : started_(false), target_task_runner_(std::move(target_task_runner)) {} -DeferredSequencedTaskRunner::~DeferredSequencedTaskRunner() { -} +DeferredSequencedTaskRunner::~DeferredSequencedTaskRunner() = default; bool DeferredSequencedTaskRunner::PostDelayedTask(const Location& from_here, OnceClosure task,
diff --git a/base/environment.cc b/base/environment.cc index 6c13f5f2..f6655d9 100644 --- a/base/environment.cc +++ b/base/environment.cc
@@ -132,7 +132,7 @@ } // namespace env_vars -Environment::~Environment() {} +Environment::~Environment() = default; // static std::unique_ptr<Environment> Environment::Create() {
diff --git a/base/feature_list.cc b/base/feature_list.cc index 7d984f1..e9aa54b 100644 --- a/base/feature_list.cc +++ b/base/feature_list.cc
@@ -81,9 +81,9 @@ base::FEATURE_DISABLED_BY_DEFAULT}; #endif // defined(SYZYASAN) -FeatureList::FeatureList() {} +FeatureList::FeatureList() = default; -FeatureList::~FeatureList() {} +FeatureList::~FeatureList() = default; void FeatureList::InitializeFromCommandLine( const std::string& enable_features,
diff --git a/base/file_descriptor_store.cc b/base/file_descriptor_store.cc index 34f3381..71cf2b3 100644 --- a/base/file_descriptor_store.cc +++ b/base/file_descriptor_store.cc
@@ -26,7 +26,7 @@ FileDescriptorStore::Descriptor&& other) : key(other.key), fd(std::move(other.fd)), region(other.region) {} -FileDescriptorStore::Descriptor::~Descriptor() {} +FileDescriptorStore::Descriptor::~Descriptor() = default; // static FileDescriptorStore& FileDescriptorStore::GetInstance() { @@ -66,8 +66,8 @@ descriptors_.insert(std::make_pair(key, std::move(descriptor))); } -FileDescriptorStore::FileDescriptorStore() {} +FileDescriptorStore::FileDescriptorStore() = default; -FileDescriptorStore::~FileDescriptorStore() {} +FileDescriptorStore::~FileDescriptorStore() = default; } // namespace base
diff --git a/base/files/file.cc b/base/files/file.cc index 6729500..50b4370d 100644 --- a/base/files/file.cc +++ b/base/files/file.cc
@@ -17,8 +17,7 @@ is_symbolic_link(false) { } -File::Info::~Info() { -} +File::Info::~Info() = default; File::File() : error_details_(FILE_ERROR_FAILED),
diff --git a/base/files/file_enumerator.cc b/base/files/file_enumerator.cc index dfa277a..9dfb2ba 100644 --- a/base/files/file_enumerator.cc +++ b/base/files/file_enumerator.cc
@@ -8,8 +8,7 @@ namespace base { -FileEnumerator::FileInfo::~FileInfo() { -} +FileEnumerator::FileInfo::~FileInfo() = default; bool FileEnumerator::ShouldSkip(const FilePath& path) { FilePath::StringType basename = path.BaseName().value();
diff --git a/base/files/file_enumerator_posix.cc b/base/files/file_enumerator_posix.cc index 71c0c3f..4b429c6 100644 --- a/base/files/file_enumerator_posix.cc +++ b/base/files/file_enumerator_posix.cc
@@ -92,8 +92,7 @@ pending_paths_.push(root_path); } -FileEnumerator::~FileEnumerator() { -} +FileEnumerator::~FileEnumerator() = default; FilePath FileEnumerator::Next() { AssertBlockingAllowed();
diff --git a/base/files/file_locking_unittest.cc b/base/files/file_locking_unittest.cc index 067ff57..e158b7d 100644 --- a/base/files/file_locking_unittest.cc +++ b/base/files/file_locking_unittest.cc
@@ -121,7 +121,7 @@ class FileLockingTest : public testing::Test { public: - FileLockingTest() {} + FileLockingTest() = default; protected: void SetUp() override {
diff --git a/base/files/file_path.cc b/base/files/file_path.cc index 3f83dfa9..29a0b40 100644 --- a/base/files/file_path.cc +++ b/base/files/file_path.cc
@@ -169,11 +169,9 @@ } // namespace -FilePath::FilePath() { -} +FilePath::FilePath() = default; -FilePath::FilePath(const FilePath& that) : path_(that.path_) { -} +FilePath::FilePath(const FilePath& that) = default; FilePath::FilePath(FilePath&& that) noexcept = default; FilePath::FilePath(StringPieceType path) { @@ -183,13 +181,9 @@ path_.erase(nul_pos, StringType::npos); } -FilePath::~FilePath() { -} +FilePath::~FilePath() = default; -FilePath& FilePath::operator=(const FilePath& that) { - path_ = that.path_; - return *this; -} +FilePath& FilePath::operator=(const FilePath& that) = default; FilePath& FilePath::operator=(FilePath&& that) = default;
diff --git a/base/files/file_path_watcher_unittest.cc b/base/files/file_path_watcher_unittest.cc index 3895d52..1ae5dc1 100644 --- a/base/files/file_path_watcher_unittest.cc +++ b/base/files/file_path_watcher_unittest.cc
@@ -75,7 +75,7 @@ private: friend class base::RefCountedThreadSafe<NotificationCollector>; - ~NotificationCollector() {} + ~NotificationCollector() = default; void RecordChange(TestDelegate* delegate) { // Warning: |delegate| is Unretained. Do not dereference. @@ -100,8 +100,8 @@ class TestDelegateBase : public SupportsWeakPtr<TestDelegateBase> { public: - TestDelegateBase() {} - virtual ~TestDelegateBase() {} + TestDelegateBase() = default; + virtual ~TestDelegateBase() = default; virtual void OnFileChanged(const FilePath& path, bool error) = 0; @@ -120,7 +120,7 @@ : collector_(collector) { collector_->Register(this); } - ~TestDelegate() override {} + ~TestDelegate() override = default; void OnFileChanged(const FilePath& path, bool error) override { if (error) @@ -144,7 +144,7 @@ { } - ~FilePathWatcherTest() override {} + ~FilePathWatcherTest() override = default; protected: void SetUp() override { @@ -275,7 +275,7 @@ : watcher_(watcher), loop_(loop) { } - ~Deleter() override {} + ~Deleter() override = default; void OnFileChanged(const FilePath&, bool) override { watcher_.reset();
diff --git a/base/files/important_file_writer_unittest.cc b/base/files/important_file_writer_unittest.cc index f48343a..0f97945 100644 --- a/base/files/important_file_writer_unittest.cc +++ b/base/files/important_file_writer_unittest.cc
@@ -114,7 +114,7 @@ class ImportantFileWriterTest : public testing::Test { public: - ImportantFileWriterTest() { } + ImportantFileWriterTest() = default; void SetUp() override { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); file_ = temp_dir_.GetPath().AppendASCII("test-file");
diff --git a/base/files/scoped_temp_dir.cc b/base/files/scoped_temp_dir.cc index a04e825..01ec0f0 100644 --- a/base/files/scoped_temp_dir.cc +++ b/base/files/scoped_temp_dir.cc
@@ -16,8 +16,7 @@ } // namespace -ScopedTempDir::ScopedTempDir() { -} +ScopedTempDir::ScopedTempDir() = default; ScopedTempDir::~ScopedTempDir() { if (!path_.empty() && !Delete())
diff --git a/base/fuchsia/fuchsia_logging.cc b/base/fuchsia/fuchsia_logging.cc new file mode 100644 index 0000000..31a8dd5 --- /dev/null +++ b/base/fuchsia/fuchsia_logging.cc
@@ -0,0 +1,26 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/fuchsia/fuchsia_logging.h" + +#include <zircon/status.h> + +#include <iomanip> + +namespace logging { + +ZxLogMessage::ZxLogMessage(const char* file_path, + int line, + LogSeverity severity, + zx_status_t zx_err) + : LogMessage(file_path, line, severity), zx_err_(zx_err) {} + +ZxLogMessage::~ZxLogMessage() { + // zx_status_t error values are negative, so log the numeric version as + // decimal rather than hex. This is also useful to match zircon/errors.h for + // grepping. + stream() << ": " << zx_status_get_string(zx_err_) << " (" << zx_err_ << ")"; +} + +} // namespace logging
diff --git a/base/fuchsia/fuchsia_logging.h b/base/fuchsia/fuchsia_logging.h new file mode 100644 index 0000000..728b0bb --- /dev/null +++ b/base/fuchsia/fuchsia_logging.h
@@ -0,0 +1,60 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef BASE_FUCHSIA_FUCHSIA_LOGGING_H_ +#define BASE_FUCHSIA_FUCHSIA_LOGGING_H_ + +#include <zircon/types.h> + +#include "base/base_export.h" +#include "base/logging.h" +#include "base/macros.h" +#include "build/build_config.h" + +// Use the ZX_LOG family of macros along with a zx_status_t containing a Zircon +// error. The error value will be decoded so that logged messages explain the +// error. + +namespace logging { + +class BASE_EXPORT ZxLogMessage : public logging::LogMessage { + public: + ZxLogMessage(const char* file_path, + int line, + LogSeverity severity, + zx_status_t zx_err); + ~ZxLogMessage(); + + private: + zx_status_t zx_err_; + + DISALLOW_COPY_AND_ASSIGN(ZxLogMessage); +}; + +} // namespace logging + +#define ZX_LOG_STREAM(severity, zx_err) \ + COMPACT_GOOGLE_LOG_EX_##severity(ZxLogMessage, zx_err).stream() + +#define ZX_LOG(severity, zx_err) \ + LAZY_STREAM(ZX_LOG_STREAM(severity, zx_err), LOG_IS_ON(severity)) +#define ZX_LOG_IF(severity, condition, zx_err) \ + LAZY_STREAM(ZX_LOG_STREAM(severity, zx_err), \ + LOG_IS_ON(severity) && (condition)) + +#define ZX_CHECK(condition, zx_err) \ + LAZY_STREAM(ZX_LOG_STREAM(FATAL, zx_err), !(condition)) \ + << "Check failed: " #condition << ". " + +#define ZX_DLOG(severity, zx_err) \ + LAZY_STREAM(ZX_LOG_STREAM(severity, zx_err), DLOG_IS_ON(severity)) +#define ZX_DLOG_IF(severity, condition, zx_err) \ + LAZY_STREAM(ZX_LOG_STREAM(severity, zx_err), \ + DLOG_IS_ON(severity) && (condition)) + +#define ZX_DCHECK(condition, zx_err) \ + LAZY_STREAM(ZX_LOG_STREAM(FATAL, zx_err), DCHECK_IS_ON() && !(condition)) \ + << "Check failed: " #condition << ". " + +#endif // BASE_FUCHSIA_FUCHSIA_LOGGING_H_
diff --git a/base/gmock_unittest.cc b/base/gmock_unittest.cc index da8dd94e..5c16728 100644 --- a/base/gmock_unittest.cc +++ b/base/gmock_unittest.cc
@@ -23,8 +23,8 @@ // for easy mocking. class SampleClass { public: - SampleClass() {} - virtual ~SampleClass() {} + SampleClass() = default; + virtual ~SampleClass() = default; virtual int ReturnSomething() { return -1;
diff --git a/base/i18n/bidi_line_iterator_unittest.cc b/base/i18n/bidi_line_iterator_unittest.cc index 5851664..d531313 100644 --- a/base/i18n/bidi_line_iterator_unittest.cc +++ b/base/i18n/bidi_line_iterator_unittest.cc
@@ -14,7 +14,7 @@ class BiDiLineIteratorTest : public testing::TestWithParam<TextDirection> { public: - BiDiLineIteratorTest() {} + BiDiLineIteratorTest() = default; BiDiLineIterator* iterator() { return &iterator_; }
diff --git a/base/i18n/char_iterator.cc b/base/i18n/char_iterator.cc index 25efc51..d80b8b6 100644 --- a/base/i18n/char_iterator.cc +++ b/base/i18n/char_iterator.cc
@@ -21,8 +21,7 @@ U8_NEXT(str_, next_pos_, len_, char_); } -UTF8CharIterator::~UTF8CharIterator() { -} +UTF8CharIterator::~UTF8CharIterator() = default; bool UTF8CharIterator::Advance() { if (array_pos_ >= len_) @@ -58,8 +57,7 @@ ReadChar(); } -UTF16CharIterator::~UTF16CharIterator() { -} +UTF16CharIterator::~UTF16CharIterator() = default; bool UTF16CharIterator::Advance() { if (array_pos_ >= len_)
diff --git a/base/i18n/file_util_icu.cc b/base/i18n/file_util_icu.cc index e0cf3d52..c154204 100644 --- a/base/i18n/file_util_icu.cc +++ b/base/i18n/file_util_icu.cc
@@ -54,7 +54,7 @@ friend struct DefaultSingletonTraits<IllegalCharacters>; IllegalCharacters(); - ~IllegalCharacters() { } + ~IllegalCharacters() = default; // set of characters considered invalid anywhere inside a filename. std::unique_ptr<icu::UnicodeSet> illegal_anywhere_;
diff --git a/base/i18n/message_formatter.cc b/base/i18n/message_formatter.cc index 6962a282..c69dd07 100644 --- a/base/i18n/message_formatter.cc +++ b/base/i18n/message_formatter.cc
@@ -48,7 +48,7 @@ MessageArg::MessageArg(const Time& t) : formattable(new icu::Formattable(static_cast<UDate>(t.ToJsTime()))) {} -MessageArg::~MessageArg() {} +MessageArg::~MessageArg() = default; // Tests if this argument has a value, and if so increments *count. bool MessageArg::has_value(int *count) const {
diff --git a/base/json/json_file_value_serializer.cc b/base/json/json_file_value_serializer.cc index cd836fc..a7c68c5 100644 --- a/base/json/json_file_value_serializer.cc +++ b/base/json/json_file_value_serializer.cc
@@ -21,8 +21,7 @@ : json_file_path_(json_file_path) { } -JSONFileValueSerializer::~JSONFileValueSerializer() { -} +JSONFileValueSerializer::~JSONFileValueSerializer() = default; bool JSONFileValueSerializer::Serialize(const base::Value& root) { return SerializeInternal(root, false); @@ -57,8 +56,7 @@ int options) : json_file_path_(json_file_path), options_(options), last_read_size_(0U) {} -JSONFileValueDeserializer::~JSONFileValueDeserializer() { -} +JSONFileValueDeserializer::~JSONFileValueDeserializer() = default; int JSONFileValueDeserializer::ReadFileToString(std::string* json_string) { DCHECK(json_string);
diff --git a/base/json/json_parser.cc b/base/json/json_parser.cc index 7b26c20..ceb64a6 100644 --- a/base/json/json_parser.cc +++ b/base/json/json_parser.cc
@@ -70,8 +70,7 @@ error_column_(0) { } -JSONParser::~JSONParser() { -} +JSONParser::~JSONParser() = default; std::unique_ptr<Value> JSONParser::Parse(StringPiece input) { start_pos_ = input.data(); @@ -135,8 +134,7 @@ JSONParser::StringBuilder::StringBuilder(const char* pos) : pos_(pos), length_(0) {} -JSONParser::StringBuilder::~StringBuilder() { -} +JSONParser::StringBuilder::~StringBuilder() = default; JSONParser::StringBuilder& JSONParser::StringBuilder::operator=( StringBuilder&& other) = default;
diff --git a/base/json/json_reader.cc b/base/json/json_reader.cc index 4ff7496b..e18f4a5 100644 --- a/base/json/json_reader.cc +++ b/base/json/json_reader.cc
@@ -39,8 +39,7 @@ : parser_(new internal::JSONParser(options)) { } -JSONReader::~JSONReader() { -} +JSONReader::~JSONReader() = default; // static std::unique_ptr<Value> JSONReader::Read(StringPiece json) {
diff --git a/base/json/json_string_value_serializer.cc b/base/json/json_string_value_serializer.cc index 2e46ab38..f9c45a40 100644 --- a/base/json/json_string_value_serializer.cc +++ b/base/json/json_string_value_serializer.cc
@@ -15,7 +15,7 @@ pretty_print_(false) { } -JSONStringValueSerializer::~JSONStringValueSerializer() {} +JSONStringValueSerializer::~JSONStringValueSerializer() = default; bool JSONStringValueSerializer::Serialize(const Value& root) { return SerializeInternal(root, false); @@ -45,7 +45,7 @@ int options) : json_string_(json_string), options_(options) {} -JSONStringValueDeserializer::~JSONStringValueDeserializer() {} +JSONStringValueDeserializer::~JSONStringValueDeserializer() = default; std::unique_ptr<Value> JSONStringValueDeserializer::Deserialize( int* error_code,
diff --git a/base/lazy_instance_unittest.cc b/base/lazy_instance_unittest.cc index 55ea45bf..cfa48f23 100644 --- a/base/lazy_instance_unittest.cc +++ b/base/lazy_instance_unittest.cc
@@ -150,8 +150,8 @@ template <size_t alignment> class AlignedData { public: - AlignedData() {} - ~AlignedData() {} + AlignedData() = default; + ~AlignedData() = default; alignas(alignment) char data_[alignment]; };
diff --git a/base/linux_util.cc b/base/linux_util.cc index d58fb79..ddf848ee 100644 --- a/base/linux_util.cc +++ b/base/linux_util.cc
@@ -48,7 +48,7 @@ // The simple state machine goes from: // STATE_DID_NOT_CHECK -> STATE_CHECK_STARTED -> STATE_CHECK_FINISHED. LinuxDistroHelper() : state_(STATE_DID_NOT_CHECK) {} - ~LinuxDistroHelper() {} + ~LinuxDistroHelper() = default; // Retrieve the current state, if we're in STATE_DID_NOT_CHECK, // we automatically move to STATE_CHECK_STARTED so nobody else will
diff --git a/base/logging_unittest.cc b/base/logging_unittest.cc index db4aa3c..0e32b68 100644 --- a/base/logging_unittest.cc +++ b/base/logging_unittest.cc
@@ -9,6 +9,7 @@ #include "base/macros.h" #include "base/strings/string_piece.h" #include "base/test/scoped_feature_list.h" +#include "build/build_config.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -28,6 +29,10 @@ #include <windows.h> #endif // OS_WIN +#if defined(OS_FUCHSIA) +#include "base/fuchsia/fuchsia_logging.h" +#endif + namespace logging { namespace { @@ -635,6 +640,26 @@ } #endif // DCHECK_IS_ON() && defined(SYZYASAN) +#if defined(OS_FUCHSIA) +TEST_F(LoggingTest, FuchsiaLogging) { + MockLogSource mock_log_source; + EXPECT_CALL(mock_log_source, Log()) + .Times(DCHECK_IS_ON() ? 2 : 1) + .WillRepeatedly(Return("log message")); + + SetMinLogLevel(LOG_INFO); + + EXPECT_TRUE(LOG_IS_ON(INFO)); + EXPECT_TRUE((DCHECK_IS_ON() != 0) == DLOG_IS_ON(INFO)); + + ZX_LOG(INFO, ZX_ERR_INTERNAL) << mock_log_source.Log(); + ZX_DLOG(INFO, ZX_ERR_INTERNAL) << mock_log_source.Log(); + + ZX_CHECK(true, ZX_ERR_INTERNAL); + ZX_DCHECK(true, ZX_ERR_INTERNAL); +} +#endif // defined(OS_FUCHSIA) + } // namespace } // namespace logging
diff --git a/base/memory/discardable_memory.cc b/base/memory/discardable_memory.cc index d50f185..f0730aa4 100644 --- a/base/memory/discardable_memory.cc +++ b/base/memory/discardable_memory.cc
@@ -6,10 +6,8 @@ namespace base { -DiscardableMemory::DiscardableMemory() { -} +DiscardableMemory::DiscardableMemory() = default; -DiscardableMemory::~DiscardableMemory() { -} +DiscardableMemory::~DiscardableMemory() = default; } // namespace base
diff --git a/base/memory/discardable_shared_memory.cc b/base/memory/discardable_shared_memory.cc index 2b7f738..7aeddab 100644 --- a/base/memory/discardable_shared_memory.cc +++ b/base/memory/discardable_shared_memory.cc
@@ -152,8 +152,7 @@ locked_page_count_(0) { } -DiscardableSharedMemory::~DiscardableSharedMemory() { -} +DiscardableSharedMemory::~DiscardableSharedMemory() = default; bool DiscardableSharedMemory::CreateAndMap(size_t size) { CheckedNumeric<size_t> checked_size = size;
diff --git a/base/memory/discardable_shared_memory_unittest.cc b/base/memory/discardable_shared_memory_unittest.cc index 2858f50..caf7eaf0 100644 --- a/base/memory/discardable_shared_memory_unittest.cc +++ b/base/memory/discardable_shared_memory_unittest.cc
@@ -19,7 +19,7 @@ class TestDiscardableSharedMemory : public DiscardableSharedMemory { public: - TestDiscardableSharedMemory() {} + TestDiscardableSharedMemory() = default; explicit TestDiscardableSharedMemory(SharedMemoryHandle handle) : DiscardableSharedMemory(handle) {}
diff --git a/base/memory/memory_coordinator_client_registry.cc b/base/memory/memory_coordinator_client_registry.cc index 6706458..45b4a7f 100644 --- a/base/memory/memory_coordinator_client_registry.cc +++ b/base/memory/memory_coordinator_client_registry.cc
@@ -17,7 +17,7 @@ MemoryCoordinatorClientRegistry::MemoryCoordinatorClientRegistry() : clients_(new ClientList) {} -MemoryCoordinatorClientRegistry::~MemoryCoordinatorClientRegistry() {} +MemoryCoordinatorClientRegistry::~MemoryCoordinatorClientRegistry() = default; void MemoryCoordinatorClientRegistry::Register( MemoryCoordinatorClient* client) {
diff --git a/base/memory/memory_coordinator_proxy.cc b/base/memory/memory_coordinator_proxy.cc index f82e928..4e22fe04 100644 --- a/base/memory/memory_coordinator_proxy.cc +++ b/base/memory/memory_coordinator_proxy.cc
@@ -12,11 +12,9 @@ } // namespace -MemoryCoordinatorProxy::MemoryCoordinatorProxy() { -} +MemoryCoordinatorProxy::MemoryCoordinatorProxy() = default; -MemoryCoordinatorProxy::~MemoryCoordinatorProxy() { -} +MemoryCoordinatorProxy::~MemoryCoordinatorProxy() = default; // static MemoryCoordinatorProxy* MemoryCoordinatorProxy::GetInstance() {
diff --git a/base/memory/memory_pressure_monitor_chromeos_unittest.cc b/base/memory/memory_pressure_monitor_chromeos_unittest.cc index 23b037c..d203afb 100644 --- a/base/memory/memory_pressure_monitor_chromeos_unittest.cc +++ b/base/memory/memory_pressure_monitor_chromeos_unittest.cc
@@ -52,7 +52,7 @@ // function. StopObserving(); } - ~TestMemoryPressureMonitor() override {} + ~TestMemoryPressureMonitor() override = default; void SetMemoryInPercentOverride(int percent) { memory_in_percent_override_ = percent;
diff --git a/base/memory/ref_counted_memory.cc b/base/memory/ref_counted_memory.cc index 00f2293..7eaaf03 100644 --- a/base/memory/ref_counted_memory.cc +++ b/base/memory/ref_counted_memory.cc
@@ -15,9 +15,9 @@ (memcmp(front(), other->front(), size()) == 0); } -RefCountedMemory::RefCountedMemory() {} +RefCountedMemory::RefCountedMemory() = default; -RefCountedMemory::~RefCountedMemory() {} +RefCountedMemory::~RefCountedMemory() = default; const unsigned char* RefCountedStaticMemory::front() const { return data_; @@ -27,9 +27,9 @@ return length_; } -RefCountedStaticMemory::~RefCountedStaticMemory() {} +RefCountedStaticMemory::~RefCountedStaticMemory() = default; -RefCountedBytes::RefCountedBytes() {} +RefCountedBytes::RefCountedBytes() = default; RefCountedBytes::RefCountedBytes(const std::vector<unsigned char>& initializer) : data_(initializer) { @@ -55,11 +55,11 @@ return data_.size(); } -RefCountedBytes::~RefCountedBytes() {} +RefCountedBytes::~RefCountedBytes() = default; -RefCountedString::RefCountedString() {} +RefCountedString::RefCountedString() = default; -RefCountedString::~RefCountedString() {} +RefCountedString::~RefCountedString() = default; // static scoped_refptr<RefCountedString> RefCountedString::TakeString(
diff --git a/base/memory/ref_counted_unittest.cc b/base/memory/ref_counted_unittest.cc index afaebdb..96f588e6 100644 --- a/base/memory/ref_counted_unittest.cc +++ b/base/memory/ref_counted_unittest.cc
@@ -14,7 +14,7 @@ class SelfAssign : public base::RefCounted<SelfAssign> { protected: - virtual ~SelfAssign() {} + virtual ~SelfAssign() = default; private: friend class base::RefCounted<SelfAssign>; @@ -22,7 +22,7 @@ class Derived : public SelfAssign { protected: - ~Derived() override {} + ~Derived() override = default; private: friend class base::RefCounted<Derived>; @@ -112,7 +112,7 @@ private: friend class base::RefCounted<Other>; - ~Other() {} + ~Other() = default; }; class HasPrivateDestructorWithDeleter; @@ -124,11 +124,11 @@ class HasPrivateDestructorWithDeleter : public base::RefCounted<HasPrivateDestructorWithDeleter, Deleter> { public: - HasPrivateDestructorWithDeleter() {} + HasPrivateDestructorWithDeleter() = default; private: friend struct Deleter; - ~HasPrivateDestructorWithDeleter() {} + ~HasPrivateDestructorWithDeleter() = default; }; void Deleter::Destruct(const HasPrivateDestructorWithDeleter* x) { @@ -147,11 +147,11 @@ public: REQUIRE_ADOPTION_FOR_REFCOUNTED_TYPE(); - InitialRefCountIsOne() {} + InitialRefCountIsOne() = default; private: friend class base::RefCounted<InitialRefCountIsOne>; - ~InitialRefCountIsOne() {} + ~InitialRefCountIsOne() = default; }; } // end namespace
diff --git a/base/memory/shared_memory_posix.cc b/base/memory/shared_memory_posix.cc index bf840e2..5b5d002d 100644 --- a/base/memory/shared_memory_posix.cc +++ b/base/memory/shared_memory_posix.cc
@@ -33,7 +33,7 @@ namespace base { -SharedMemory::SharedMemory() {} +SharedMemory::SharedMemory() = default; SharedMemory::SharedMemory(const SharedMemoryHandle& handle, bool read_only) : shm_(handle), read_only_(read_only) {}
diff --git a/base/memory/shared_memory_unittest.cc b/base/memory/shared_memory_unittest.cc index ceafb99..7567eb4 100644 --- a/base/memory/shared_memory_unittest.cc +++ b/base/memory/shared_memory_unittest.cc
@@ -55,7 +55,7 @@ class MultipleThreadMain : public PlatformThread::Delegate { public: explicit MultipleThreadMain(int16_t id) : id_(id) {} - ~MultipleThreadMain() override {} + ~MultipleThreadMain() override = default; static void CleanUp() { SharedMemory memory;
diff --git a/base/memory/singleton_unittest.cc b/base/memory/singleton_unittest.cc index 1a4d901..50b862d 100644 --- a/base/memory/singleton_unittest.cc +++ b/base/memory/singleton_unittest.cc
@@ -19,8 +19,8 @@ template <size_t alignment> class AlignedData { public: - AlignedData() {} - ~AlignedData() {} + AlignedData() = default; + ~AlignedData() = default; alignas(alignment) char data_[alignment]; }; @@ -123,8 +123,8 @@ template <class Type> class AlignedTestSingleton { public: - AlignedTestSingleton() {} - ~AlignedTestSingleton() {} + AlignedTestSingleton() = default; + ~AlignedTestSingleton() = default; static AlignedTestSingleton* GetInstance() { return Singleton<AlignedTestSingleton, StaticMemorySingletonTraits<AlignedTestSingleton>>::get(); @@ -162,7 +162,7 @@ class SingletonTest : public testing::Test { public: - SingletonTest() {} + SingletonTest() = default; void SetUp() override { non_leak_called_ = false;
diff --git a/base/memory/weak_ptr.cc b/base/memory/weak_ptr.cc index 2130d67..1c3208f 100644 --- a/base/memory/weak_ptr.cc +++ b/base/memory/weak_ptr.cc
@@ -28,17 +28,14 @@ return is_valid_; } -WeakReference::Flag::~Flag() { -} +WeakReference::Flag::~Flag() = default; -WeakReference::WeakReference() { -} +WeakReference::WeakReference() = default; WeakReference::WeakReference(const Flag* flag) : flag_(flag) { } -WeakReference::~WeakReference() { -} +WeakReference::~WeakReference() = default; WeakReference::WeakReference(WeakReference&& other) = default; @@ -46,8 +43,7 @@ bool WeakReference::is_valid() const { return flag_.get() && flag_->IsValid(); } -WeakReferenceOwner::WeakReferenceOwner() { -} +WeakReferenceOwner::WeakReferenceOwner() = default; WeakReferenceOwner::~WeakReferenceOwner() { Invalidate(); @@ -70,7 +66,7 @@ WeakPtrBase::WeakPtrBase() : ptr_(0) {} -WeakPtrBase::~WeakPtrBase() {} +WeakPtrBase::~WeakPtrBase() = default; WeakPtrBase::WeakPtrBase(const WeakReference& ref, uintptr_t ptr) : ref_(ref), ptr_(ptr) {}
diff --git a/base/memory/weak_ptr_unittest.cc b/base/memory/weak_ptr_unittest.cc index 93c4105..f8dfb7c0 100644 --- a/base/memory/weak_ptr_unittest.cc +++ b/base/memory/weak_ptr_unittest.cc
@@ -51,7 +51,7 @@ struct TargetBase {}; struct Target : public TargetBase, public SupportsWeakPtr<Target> { - virtual ~Target() {} + virtual ~Target() = default; }; struct DerivedTarget : public Target {}; @@ -64,7 +64,7 @@ // A struct with a virtual destructor. struct VirtualDestructor { - virtual ~VirtualDestructor() {} + virtual ~VirtualDestructor() = default; }; // A class inheriting from Target where Target is not the first base, and where
diff --git a/base/message_loop/message_loop.cc b/base/message_loop/message_loop.cc index 9cddbe89..2c8899bf 100644 --- a/base/message_loop/message_loop.cc +++ b/base/message_loop/message_loop.cc
@@ -71,14 +71,11 @@ //------------------------------------------------------------------------------ -MessageLoop::TaskObserver::TaskObserver() { -} +MessageLoop::TaskObserver::TaskObserver() = default; -MessageLoop::TaskObserver::~TaskObserver() { -} +MessageLoop::TaskObserver::~TaskObserver() = default; -MessageLoop::DestructionObserver::~DestructionObserver() { -} +MessageLoop::DestructionObserver::~DestructionObserver() = default; //------------------------------------------------------------------------------
diff --git a/base/message_loop/message_loop_io_posix_unittest.cc b/base/message_loop/message_loop_io_posix_unittest.cc index 5038bea7..f98d4668 100644 --- a/base/message_loop/message_loop_io_posix_unittest.cc +++ b/base/message_loop/message_loop_io_posix_unittest.cc
@@ -25,7 +25,7 @@ class MessageLoopForIoPosixTest : public testing::Test { public: - MessageLoopForIoPosixTest() {} + MessageLoopForIoPosixTest() = default; // testing::Test interface. void SetUp() override {
diff --git a/base/message_loop/message_loop_task_runner.cc b/base/message_loop/message_loop_task_runner.cc index 5d41986..f251e3b 100644 --- a/base/message_loop/message_loop_task_runner.cc +++ b/base/message_loop/message_loop_task_runner.cc
@@ -46,8 +46,7 @@ return valid_thread_id_ == PlatformThread::CurrentId(); } -MessageLoopTaskRunner::~MessageLoopTaskRunner() { -} +MessageLoopTaskRunner::~MessageLoopTaskRunner() = default; } // namespace internal
diff --git a/base/message_loop/message_loop_unittest.cc b/base/message_loop/message_loop_unittest.cc index 742436e..39953cc5 100644 --- a/base/message_loop/message_loop_unittest.cc +++ b/base/message_loop/message_loop_unittest.cc
@@ -86,7 +86,7 @@ private: friend class RefCounted<Foo>; - ~Foo() {} + ~Foo() = default; int test_count_; std::string result_; @@ -202,7 +202,7 @@ num_tasks_processed_(0), num_tasks_(num_tasks) {} - ~DummyTaskObserver() override {} + ~DummyTaskObserver() override = default; void WillProcessTask(const PendingTask& pending_task) override { num_tasks_started_++;
diff --git a/base/message_loop/message_pump.cc b/base/message_loop/message_pump.cc index 3d85b9b..9076176 100644 --- a/base/message_loop/message_pump.cc +++ b/base/message_loop/message_pump.cc
@@ -6,11 +6,9 @@ namespace base { -MessagePump::MessagePump() { -} +MessagePump::MessagePump() = default; -MessagePump::~MessagePump() { -} +MessagePump::~MessagePump() = default; void MessagePump::SetTimerSlack(TimerSlack) { }
diff --git a/base/message_loop/message_pump_default.cc b/base/message_loop/message_pump_default.cc index 50dbc6f..dba0f5b 100644 --- a/base/message_loop/message_pump_default.cc +++ b/base/message_loop/message_pump_default.cc
@@ -24,7 +24,7 @@ event_(WaitableEvent::ResetPolicy::AUTOMATIC, WaitableEvent::InitialState::NOT_SIGNALED) {} -MessagePumpDefault::~MessagePumpDefault() {} +MessagePumpDefault::~MessagePumpDefault() = default; void MessagePumpDefault::Run(Delegate* delegate) { AutoReset<bool> auto_reset_keep_running(&keep_running_, true);
diff --git a/base/message_loop/message_pump_libevent_unittest.cc b/base/message_loop/message_pump_libevent_unittest.cc index c0282a12..da7c06e 100644 --- a/base/message_loop/message_pump_libevent_unittest.cc +++ b/base/message_loop/message_pump_libevent_unittest.cc
@@ -33,7 +33,7 @@ MessagePumpLibeventTest() : ui_loop_(new MessageLoop(MessageLoop::TYPE_UI)), io_thread_("MessagePumpLibeventTestIOThread") {} - ~MessagePumpLibeventTest() override {} + ~MessagePumpLibeventTest() override = default; void SetUp() override { Thread::Options options(MessageLoop::TYPE_IO, 0); @@ -77,7 +77,7 @@ // nothing useful. class StupidWatcher : public MessagePumpLibevent::Watcher { public: - ~StupidWatcher() override {} + ~StupidWatcher() override = default; // base:MessagePumpLibevent::Watcher interface void OnFileCanReadWithoutBlocking(int fd) override {} @@ -111,7 +111,7 @@ : controller_(controller) { DCHECK(controller_); } - ~BaseWatcher() override {} + ~BaseWatcher() override = default; // base:MessagePumpLibevent::Watcher interface void OnFileCanReadWithoutBlocking(int /* fd */) override { NOTREACHED(); } @@ -155,7 +155,7 @@ MessagePumpLibevent::FileDescriptorWatcher* controller) : BaseWatcher(controller) {} - ~StopWatcher() override {} + ~StopWatcher() override = default; void OnFileCanWriteWithoutBlocking(int /* fd */) override { controller_->StopWatchingFileDescriptor(); @@ -183,8 +183,8 @@ class NestedPumpWatcher : public MessagePumpLibevent::Watcher { public: - NestedPumpWatcher() {} - ~NestedPumpWatcher() override {} + NestedPumpWatcher() = default; + ~NestedPumpWatcher() override = default; void OnFileCanReadWithoutBlocking(int /* fd */) override { RunLoop runloop;
diff --git a/base/message_loop/message_pump_perftest.cc b/base/message_loop/message_pump_perftest.cc index 4b45341d..90680f07 100644 --- a/base/message_loop/message_pump_perftest.cc +++ b/base/message_loop/message_pump_perftest.cc
@@ -240,8 +240,8 @@ class FakeMessagePump : public MessagePump { public: - FakeMessagePump() {} - ~FakeMessagePump() override {} + FakeMessagePump() = default; + ~FakeMessagePump() override = default; void Run(Delegate* delegate) override {}
diff --git a/base/metrics/bucket_ranges.cc b/base/metrics/bucket_ranges.cc index f995d7c..0404393 100644 --- a/base/metrics/bucket_ranges.cc +++ b/base/metrics/bucket_ranges.cc
@@ -107,7 +107,7 @@ : ranges_(num_ranges, 0), checksum_(0) {} -BucketRanges::~BucketRanges() {} +BucketRanges::~BucketRanges() = default; uint32_t BucketRanges::CalculateChecksum() const { // Seed checksum.
diff --git a/base/metrics/field_trial.cc b/base/metrics/field_trial.cc index 221253f..72f25a901 100644 --- a/base/metrics/field_trial.cc +++ b/base/metrics/field_trial.cc
@@ -243,14 +243,13 @@ //------------------------------------------------------------------------------ // FieldTrial methods and members. -FieldTrial::EntropyProvider::~EntropyProvider() { -} +FieldTrial::EntropyProvider::~EntropyProvider() = default; -FieldTrial::State::State() {} +FieldTrial::State::State() = default; FieldTrial::State::State(const State& other) = default; -FieldTrial::State::~State() {} +FieldTrial::State::~State() = default; bool FieldTrial::FieldTrialEntry::GetTrialAndGroupName( StringPiece* trial_name, @@ -413,7 +412,7 @@ << "Trial " << trial_name << " is missing a default group name."; } -FieldTrial::~FieldTrial() {} +FieldTrial::~FieldTrial() = default; void FieldTrial::SetTrialRegistered() { DCHECK_EQ(kNotFinalized, group_); @@ -486,8 +485,7 @@ // static bool FieldTrialList::used_without_global_ = false; -FieldTrialList::Observer::~Observer() { -} +FieldTrialList::Observer::~Observer() = default; FieldTrialList::FieldTrialList( std::unique_ptr<const FieldTrial::EntropyProvider> entropy_provider)
diff --git a/base/metrics/field_trial_param_associator.cc b/base/metrics/field_trial_param_associator.cc index 9c93f34..af76eaf 100644 --- a/base/metrics/field_trial_param_associator.cc +++ b/base/metrics/field_trial_param_associator.cc
@@ -8,8 +8,8 @@ namespace base { -FieldTrialParamAssociator::FieldTrialParamAssociator() {} -FieldTrialParamAssociator::~FieldTrialParamAssociator() {} +FieldTrialParamAssociator::FieldTrialParamAssociator() = default; +FieldTrialParamAssociator::~FieldTrialParamAssociator() = default; // static FieldTrialParamAssociator* FieldTrialParamAssociator::GetInstance() {
diff --git a/base/metrics/histogram.cc b/base/metrics/histogram.cc index 2941190b..40e7bcc 100644 --- a/base/metrics/histogram.cc +++ b/base/metrics/histogram.cc
@@ -622,8 +622,7 @@ unlogged_samples_->id(), ranges, logged_meta, logged_counts)); } -Histogram::~Histogram() { -} +Histogram::~Histogram() = default; bool Histogram::PrintEmptyBucket(uint32_t index) const { return true; @@ -878,7 +877,7 @@ DISALLOW_COPY_AND_ASSIGN(Factory); }; -LinearHistogram::~LinearHistogram() {} +LinearHistogram::~LinearHistogram() = default; HistogramBase* LinearHistogram::FactoryGet(const std::string& name, Sample minimum,
diff --git a/base/metrics/histogram_base.cc b/base/metrics/histogram_base.cc index e0a5047..405a80f2 100644 --- a/base/metrics/histogram_base.cc +++ b/base/metrics/histogram_base.cc
@@ -69,7 +69,7 @@ HistogramBase::HistogramBase(const char* name) : histogram_name_(name), flags_(kNoFlags) {} -HistogramBase::~HistogramBase() {} +HistogramBase::~HistogramBase() = default; void HistogramBase::CheckName(const StringPiece& name) const { DCHECK_EQ(StringPiece(histogram_name()), name); @@ -108,7 +108,8 @@ return true; } -void HistogramBase::WriteJSON(std::string* output) const { +void HistogramBase::WriteJSON(std::string* output, + JSONVerbosityLevel verbosity_level) const { Count count; int64_t sum; std::unique_ptr<ListValue> buckets(new ListValue()); @@ -123,7 +124,8 @@ root.SetDouble("sum", static_cast<double>(sum)); root.SetInteger("flags", flags()); root.Set("params", std::move(parameters)); - root.Set("buckets", std::move(buckets)); + if (verbosity_level != JSON_VERBOSITY_LEVEL_OMIT_BUCKETS) + root.Set("buckets", std::move(buckets)); root.SetInteger("pid", GetUniqueIdForProcess()); serializer.Serialize(root); }
diff --git a/base/metrics/histogram_base.h b/base/metrics/histogram_base.h index 7e1d67e..b6928f1f 100644 --- a/base/metrics/histogram_base.h +++ b/base/metrics/histogram_base.h
@@ -41,6 +41,16 @@ SPARSE_HISTOGRAM, }; +// Controls the verbosity of the information when the histogram is serialized to +// a JSON. +// GENERATED_JAVA_ENUM_PACKAGE: org.chromium.base.metrics +enum JSONVerbosityLevel { + // The histogram is completely serialized. + JSON_VERBOSITY_LEVEL_FULL, + // The bucket information is not serialized. + JSON_VERBOSITY_LEVEL_OMIT_BUCKETS, +}; + std::string HistogramTypeToString(HistogramType type); // This enum is used for reporting how many histograms and of what types and @@ -216,10 +226,11 @@ virtual bool ValidateHistogramContents(bool crash_if_invalid, int corrupted_count) const; - // Produce a JSON representation of the histogram. This is implemented with - // the help of GetParameters and GetCountAndBucketData; overwrite them to - // customize the output. - void WriteJSON(std::string* output) const; + // Produce a JSON representation of the histogram with |verbosity_level| as + // the serialization verbosity. This is implemented with the help of + // GetParameters and GetCountAndBucketData; overwrite them to customize the + // output. + void WriteJSON(std::string* output, JSONVerbosityLevel verbosity_level) const; protected: enum ReportActivity { HISTOGRAM_CREATED, HISTOGRAM_LOOKUP };
diff --git a/base/metrics/histogram_base_unittest.cc b/base/metrics/histogram_base_unittest.cc index 3894857..5850c67 100644 --- a/base/metrics/histogram_base_unittest.cc +++ b/base/metrics/histogram_base_unittest.cc
@@ -21,8 +21,7 @@ ResetStatisticsRecorder(); } - ~HistogramBaseTest() override { - } + ~HistogramBaseTest() override = default; void ResetStatisticsRecorder() { // It is necessary to fully destruct any existing StatisticsRecorder
diff --git a/base/metrics/histogram_delta_serialization.cc b/base/metrics/histogram_delta_serialization.cc index b0b9d724..a74b87f 100644 --- a/base/metrics/histogram_delta_serialization.cc +++ b/base/metrics/histogram_delta_serialization.cc
@@ -37,8 +37,7 @@ const std::string& caller_name) : histogram_snapshot_manager_(this), serialized_deltas_(nullptr) {} -HistogramDeltaSerialization::~HistogramDeltaSerialization() { -} +HistogramDeltaSerialization::~HistogramDeltaSerialization() = default; void HistogramDeltaSerialization::PrepareAndSerializeDeltas( std::vector<std::string>* serialized_deltas,
diff --git a/base/metrics/histogram_samples.cc b/base/metrics/histogram_samples.cc index 10243bb..7703580 100644 --- a/base/metrics/histogram_samples.cc +++ b/base/metrics/histogram_samples.cc
@@ -186,7 +186,7 @@ // This mustn't do anything with |meta_|. It was passed to the ctor and may // be invalid by the time this dtor gets called. -HistogramSamples::~HistogramSamples() {} +HistogramSamples::~HistogramSamples() = default; void HistogramSamples::Add(const HistogramSamples& other) { IncreaseSumAndCount(other.sum(), other.redundant_count()); @@ -262,7 +262,7 @@ static_cast<int32_t>(id())); } -SampleCountIterator::~SampleCountIterator() {} +SampleCountIterator::~SampleCountIterator() = default; bool SampleCountIterator::GetBucketIndex(size_t* index) const { DCHECK(!Done()); @@ -280,7 +280,7 @@ size_t bucket_index) : min_(min), max_(max), bucket_index_(bucket_index), count_(count) {} -SingleSampleIterator::~SingleSampleIterator() {} +SingleSampleIterator::~SingleSampleIterator() = default; bool SingleSampleIterator::Done() const { return count_ == 0;
diff --git a/base/metrics/histogram_snapshot_manager.cc b/base/metrics/histogram_snapshot_manager.cc index a4166dbf..7b3cff8 100644 --- a/base/metrics/histogram_snapshot_manager.cc +++ b/base/metrics/histogram_snapshot_manager.cc
@@ -41,8 +41,7 @@ is_active_.store(false, std::memory_order_relaxed); } -HistogramSnapshotManager::~HistogramSnapshotManager() { -} +HistogramSnapshotManager::~HistogramSnapshotManager() = default; void HistogramSnapshotManager::PrepareDelta(HistogramBase* histogram) { if (!histogram->ValidateHistogramContents(true, 0)) @@ -79,23 +78,16 @@ // Extract fields useful during debug. const BucketRanges* ranges = static_cast<const Histogram*>(histogram)->bucket_ranges(); - std::vector<HistogramBase::Sample> ranges_copy; - for (size_t i = 0; i < ranges->size(); ++i) - ranges_copy.push_back(ranges->range(i)); - HistogramBase::Sample* ranges_ptr = &ranges_copy[0]; uint32_t ranges_checksum = ranges->checksum(); uint32_t ranges_calc_checksum = ranges->CalculateChecksum(); - const char* histogram_name = histogram->histogram_name(); int32_t flags = histogram->flags(); // The checksum should have caught this, so crash separately if it didn't. CHECK_NE(0U, HistogramBase::RANGE_CHECKSUM_ERROR & corruption); CHECK(false); // Crash for the bucket order corruption. // Ensure that compiler keeps around pointers to |histogram| and its // internal |bucket_ranges_| for any minidumps. - base::debug::Alias(&ranges_ptr); base::debug::Alias(&ranges_checksum); base::debug::Alias(&ranges_calc_checksum); - base::debug::Alias(&histogram_name); base::debug::Alias(&flags); } // Checksum corruption might not have caused order corruption.
diff --git a/base/metrics/histogram_snapshot_manager_unittest.cc b/base/metrics/histogram_snapshot_manager_unittest.cc index ca95eaa..1e2c599 100644 --- a/base/metrics/histogram_snapshot_manager_unittest.cc +++ b/base/metrics/histogram_snapshot_manager_unittest.cc
@@ -19,7 +19,7 @@ class HistogramFlattenerDeltaRecorder : public HistogramFlattener { public: - HistogramFlattenerDeltaRecorder() {} + HistogramFlattenerDeltaRecorder() = default; void RecordDelta(const HistogramBase& histogram, const HistogramSamples& snapshot) override { @@ -59,7 +59,7 @@ : statistics_recorder_(StatisticsRecorder::CreateTemporaryForTesting()), histogram_snapshot_manager_(&histogram_flattener_delta_recorder_) {} - ~HistogramSnapshotManagerTest() override {} + ~HistogramSnapshotManagerTest() override = default; std::unique_ptr<StatisticsRecorder> statistics_recorder_; HistogramFlattenerDeltaRecorder histogram_flattener_delta_recorder_;
diff --git a/base/metrics/persistent_histogram_allocator.cc b/base/metrics/persistent_histogram_allocator.cc index 1d908fae..79a903e 100644 --- a/base/metrics/persistent_histogram_allocator.cc +++ b/base/metrics/persistent_histogram_allocator.cc
@@ -106,7 +106,8 @@ PersistentMemoryAllocator* allocator) : allocator_(allocator), record_iterator_(allocator) {} -PersistentSparseHistogramDataManager::~PersistentSparseHistogramDataManager() {} +PersistentSparseHistogramDataManager::~PersistentSparseHistogramDataManager() = + default; PersistentSampleMapRecords* PersistentSparseHistogramDataManager::UseSampleMapRecords(uint64_t id, @@ -189,7 +190,7 @@ uint64_t sample_map_id) : data_manager_(data_manager), sample_map_id_(sample_map_id) {} -PersistentSampleMapRecords::~PersistentSampleMapRecords() {} +PersistentSampleMapRecords::~PersistentSampleMapRecords() = default; PersistentSampleMapRecords* PersistentSampleMapRecords::Acquire( const void* user) { @@ -276,7 +277,7 @@ : memory_allocator_(std::move(memory)), sparse_histogram_data_manager_(memory_allocator_.get()) {} -PersistentHistogramAllocator::~PersistentHistogramAllocator() {} +PersistentHistogramAllocator::~PersistentHistogramAllocator() = default; std::unique_ptr<HistogramBase> PersistentHistogramAllocator::GetHistogram( Reference ref) { @@ -747,7 +748,7 @@ result_histogram->Add(result); } -GlobalHistogramAllocator::~GlobalHistogramAllocator() {} +GlobalHistogramAllocator::~GlobalHistogramAllocator() = default; // static void GlobalHistogramAllocator::CreateWithPersistentMemory(
diff --git a/base/metrics/persistent_memory_allocator.cc b/base/metrics/persistent_memory_allocator.cc index e49ea47..be107c3 100644 --- a/base/metrics/persistent_memory_allocator.cc +++ b/base/metrics/persistent_memory_allocator.cc
@@ -1029,7 +1029,7 @@ read_only), shared_memory_(std::move(memory)) {} -SharedPersistentMemoryAllocator::~SharedPersistentMemoryAllocator() {} +SharedPersistentMemoryAllocator::~SharedPersistentMemoryAllocator() = default; // static bool SharedPersistentMemoryAllocator::IsSharedMemoryAcceptable( @@ -1056,7 +1056,7 @@ read_only), mapped_file_(std::move(file)) {} -FilePersistentMemoryAllocator::~FilePersistentMemoryAllocator() {} +FilePersistentMemoryAllocator::~FilePersistentMemoryAllocator() = default; // static bool FilePersistentMemoryAllocator::IsFileAcceptable( @@ -1159,7 +1159,7 @@ DCHECK(reference_); } -DelayedPersistentAllocation::~DelayedPersistentAllocation() {} +DelayedPersistentAllocation::~DelayedPersistentAllocation() = default; void* DelayedPersistentAllocation::Get() const { // Relaxed operations are acceptable here because it's not protecting the
diff --git a/base/metrics/persistent_sample_map.cc b/base/metrics/persistent_sample_map.cc index 817702f..f38b9d1 100644 --- a/base/metrics/persistent_sample_map.cc +++ b/base/metrics/persistent_sample_map.cc
@@ -50,7 +50,7 @@ SkipEmptyBuckets(); } -PersistentSampleMapIterator::~PersistentSampleMapIterator() {} +PersistentSampleMapIterator::~PersistentSampleMapIterator() = default; bool PersistentSampleMapIterator::Done() const { return iter_ == end_;
diff --git a/base/metrics/sample_map.cc b/base/metrics/sample_map.cc index 08fe032..c6dce293 100644 --- a/base/metrics/sample_map.cc +++ b/base/metrics/sample_map.cc
@@ -47,7 +47,7 @@ SkipEmptyBuckets(); } -SampleMapIterator::~SampleMapIterator() {} +SampleMapIterator::~SampleMapIterator() = default; bool SampleMapIterator::Done() const { return iter_ == end_;
diff --git a/base/metrics/sample_vector.cc b/base/metrics/sample_vector.cc index 749b2d8f..cf8634e 100644 --- a/base/metrics/sample_vector.cc +++ b/base/metrics/sample_vector.cc
@@ -30,7 +30,7 @@ CHECK_GE(bucket_ranges_->bucket_count(), 1u); } -SampleVectorBase::~SampleVectorBase() {} +SampleVectorBase::~SampleVectorBase() = default; void SampleVectorBase::Accumulate(Sample value, Count count) { const size_t bucket_index = GetBucketIndex(value); @@ -327,7 +327,7 @@ } } -PersistentSampleVector::~PersistentSampleVector() {} +PersistentSampleVector::~PersistentSampleVector() = default; bool PersistentSampleVector::MountExistingCountsStorage() const { // There is no early exit if counts is not yet mounted because, given that @@ -384,7 +384,7 @@ SkipEmptyBuckets(); } -SampleVectorIterator::~SampleVectorIterator() {} +SampleVectorIterator::~SampleVectorIterator() = default; bool SampleVectorIterator::Done() const { return index_ >= counts_size_;
diff --git a/base/metrics/single_sample_metrics_unittest.cc b/base/metrics/single_sample_metrics_unittest.cc index e3c1cf0..c1a8b96 100644 --- a/base/metrics/single_sample_metrics_unittest.cc +++ b/base/metrics/single_sample_metrics_unittest.cc
@@ -20,7 +20,7 @@ class SingleSampleMetricsTest : public testing::Test { public: - SingleSampleMetricsTest() {} + SingleSampleMetricsTest() = default; ~SingleSampleMetricsTest() override { // Ensure we cleanup after ourselves.
diff --git a/base/metrics/sparse_histogram.cc b/base/metrics/sparse_histogram.cc index 35a2b59..e33fd3c8 100644 --- a/base/metrics/sparse_histogram.cc +++ b/base/metrics/sparse_histogram.cc
@@ -78,7 +78,7 @@ new SparseHistogram(allocator, name, meta, logged_meta)); } -SparseHistogram::~SparseHistogram() {} +SparseHistogram::~SparseHistogram() = default; uint64_t SparseHistogram::name_hash() const { return unlogged_samples_->id();
diff --git a/base/metrics/statistics_recorder.cc b/base/metrics/statistics_recorder.cc index 7372d507..a21adc0 100644 --- a/base/metrics/statistics_recorder.cc +++ b/base/metrics/statistics_recorder.cc
@@ -204,19 +204,13 @@ } // static -std::string StatisticsRecorder::ToJSON(const std::string& query) { +std::string StatisticsRecorder::ToJSON(JSONVerbosityLevel verbosity_level) { if (!IsActive()) return std::string(); std::string output("{"); - if (!query.empty()) { - output += "\"query\":"; - EscapeJSONString(query, true, &output); - output += ","; - } - Histograms snapshot; - GetSnapshot(query, &snapshot); + GetSnapshot(std::string(), &snapshot); output += "\"histograms\":["; bool first_histogram = true; for (const HistogramBase* histogram : snapshot) { @@ -225,7 +219,7 @@ else output += ","; std::string json; - histogram->WriteJSON(&json); + histogram->WriteJSON(&json, verbosity_level); output += json; } output += "]}";
diff --git a/base/metrics/statistics_recorder.h b/base/metrics/statistics_recorder.h index cdec67ae..49ccaf5 100644 --- a/base/metrics/statistics_recorder.h +++ b/base/metrics/statistics_recorder.h
@@ -110,9 +110,9 @@ static void WriteHTMLGraph(const std::string& query, std::string* output); static void WriteGraph(const std::string& query, std::string* output); - // Returns the histograms with |query| as a substring as JSON text (an empty - // |query| will process all registered histograms). - static std::string ToJSON(const std::string& query); + // Returns the histograms with |verbosity_level| as the serialization + // verbosity. + static std::string ToJSON(JSONVerbosityLevel verbosity_level); // Method for extracting histograms which were marked for use by UMA. static void GetHistograms(Histograms* output);
diff --git a/base/metrics/statistics_recorder_unittest.cc b/base/metrics/statistics_recorder_unittest.cc index f0bb50c..92d1bba6 100644 --- a/base/metrics/statistics_recorder_unittest.cc +++ b/base/metrics/statistics_recorder_unittest.cc
@@ -14,6 +14,7 @@ #include "base/json/json_reader.h" #include "base/logging.h" #include "base/memory/weak_ptr.h" +#include "base/metrics/histogram_base.h" #include "base/metrics/histogram_macros.h" #include "base/metrics/persistent_histogram_allocator.h" #include "base/metrics/record_histogram_checker.h" @@ -42,7 +43,7 @@ // Test implementation of RecordHistogramChecker interface. class OddRecordHistogramChecker : public base::RecordHistogramChecker { public: - ~OddRecordHistogramChecker() override {} + ~OddRecordHistogramChecker() override = default; // base::RecordHistogramChecker: bool ShouldRecord(uint64_t histogram_hash) const override { @@ -371,7 +372,7 @@ Histogram::FactoryGet("TestHistogram2", 1, 1000, 50, HistogramBase::kNoFlags) ->Add(40); - std::string json(StatisticsRecorder::ToJSON(std::string())); + std::string json(StatisticsRecorder::ToJSON(JSON_VERBOSITY_LEVEL_FULL)); // Check for valid JSON. std::unique_ptr<Value> root = JSONReader::Read(json); @@ -395,33 +396,27 @@ ASSERT_TRUE(histogram_dict->GetInteger("count", &sample_count)); EXPECT_EQ(2, sample_count); - // Test the query filter. - std::string query("TestHistogram2"); - json = StatisticsRecorder::ToJSON(query); + ListValue* buckets_list = nullptr; + ASSERT_TRUE(histogram_dict->GetList("buckets", &buckets_list)); + EXPECT_EQ(2u, buckets_list->GetList().size()); + // Check the serialized JSON with a different verbosity level. + json = StatisticsRecorder::ToJSON(JSON_VERBOSITY_LEVEL_OMIT_BUCKETS); root = JSONReader::Read(json); ASSERT_TRUE(root.get()); + root_dict = nullptr; ASSERT_TRUE(root->GetAsDictionary(&root_dict)); - - std::string query_value; - ASSERT_TRUE(root_dict->GetString("query", &query_value)); - EXPECT_EQ(query, query_value); - + histogram_list = nullptr; ASSERT_TRUE(root_dict->GetList("histograms", &histogram_list)); - ASSERT_EQ(1u, histogram_list->GetSize()); - + ASSERT_EQ(2u, histogram_list->GetSize()); + histogram_dict = nullptr; ASSERT_TRUE(histogram_list->GetDictionary(0, &histogram_dict)); - - std::string histogram_name; - ASSERT_TRUE(histogram_dict->GetString("name", &histogram_name)); - EXPECT_EQ("TestHistogram2", histogram_name); - - json.clear(); - UninitializeStatisticsRecorder(); - - // No data should be returned. - json = StatisticsRecorder::ToJSON(query); - EXPECT_TRUE(json.empty()); + sample_count = 0; + ASSERT_TRUE(histogram_dict->GetInteger("count", &sample_count)); + EXPECT_EQ(2, sample_count); + buckets_list = nullptr; + // Bucket information should be omitted. + ASSERT_FALSE(histogram_dict->GetList("buckets", &buckets_list)); } TEST_P(StatisticsRecorderTest, IterationTest) {
diff --git a/base/observer_list_unittest.cc b/base/observer_list_unittest.cc index fa6ab78..fd88a2d 100644 --- a/base/observer_list_unittest.cc +++ b/base/observer_list_unittest.cc
@@ -31,14 +31,14 @@ class Foo { public: virtual void Observe(int x) = 0; - virtual ~Foo() {} + virtual ~Foo() = default; virtual int GetValue() const { return 0; } }; class Adder : public Foo { public: explicit Adder(int scaler) : total(0), scaler_(scaler) {} - ~Adder() override {} + ~Adder() override = default; void Observe(int x) override { total += x * scaler_; } int GetValue() const override { return total; } @@ -58,7 +58,7 @@ Disrupter(ObserverList<Foo>* list, bool remove_self) : Disrupter(list, nullptr, remove_self) {} - ~Disrupter() override {} + ~Disrupter() override = default; void Observe(int x) override { if (remove_self_) @@ -116,7 +116,7 @@ ready_(ready), weak_factory_(this) {} - ~AddRemoveThread() override {} + ~AddRemoveThread() override = default; void ThreadMain() override { loop_ = new MessageLoop(); // Fire up a message loop. @@ -528,7 +528,7 @@ class FooRemover : public Foo { public: explicit FooRemover(ObserverListThreadSafe<Foo>* list) : list_(list) {} - ~FooRemover() override {} + ~FooRemover() override = default; void AddFooToRemove(Foo* foo) { foos_.push_back(foo); @@ -875,7 +875,7 @@ class ListDestructor : public Foo { public: explicit ListDestructor(ObserverList<Foo>* list) : list_(list) {} - ~ListDestructor() override {} + ~ListDestructor() override = default; void Observe(int x) override { delete list_; }
diff --git a/base/pending_task.cc b/base/pending_task.cc index 64dc1da..31f2d2d 100644 --- a/base/pending_task.cc +++ b/base/pending_task.cc
@@ -33,8 +33,7 @@ PendingTask::PendingTask(PendingTask&& other) = default; -PendingTask::~PendingTask() { -} +PendingTask::~PendingTask() = default; PendingTask& PendingTask::operator=(PendingTask&& other) = default;
diff --git a/base/pickle.cc b/base/pickle.cc index cfd4c7a..c2189c8f 100644 --- a/base/pickle.cc +++ b/base/pickle.cc
@@ -207,9 +207,9 @@ return true; } -Pickle::Attachment::Attachment() {} +Pickle::Attachment::Attachment() = default; -Pickle::Attachment::~Attachment() {} +Pickle::Attachment::~Attachment() = default; // Payload is uint32_t aligned.
diff --git a/base/pickle_unittest.cc b/base/pickle_unittest.cc index faf88cfc..6c30257 100644 --- a/base/pickle_unittest.cc +++ b/base/pickle_unittest.cc
@@ -529,7 +529,7 @@ // Publicly exposes the ClaimBytes interface for testing. class TestingPickle : public Pickle { public: - TestingPickle() {} + TestingPickle() = default; void* ClaimBytes(size_t num_bytes) { return Pickle::ClaimBytes(num_bytes); } };
diff --git a/base/posix/global_descriptors.cc b/base/posix/global_descriptors.cc index 9cc75531..738d14e3 100644 --- a/base/posix/global_descriptors.cc +++ b/base/posix/global_descriptors.cc
@@ -94,8 +94,8 @@ descriptors_ = mapping; } -GlobalDescriptors::GlobalDescriptors() {} +GlobalDescriptors::GlobalDescriptors() = default; -GlobalDescriptors::~GlobalDescriptors() {} +GlobalDescriptors::~GlobalDescriptors() = default; } // namespace base
diff --git a/base/power_monitor/power_monitor_source.cc b/base/power_monitor/power_monitor_source.cc index 5d27a0e..d4757b0 100644 --- a/base/power_monitor/power_monitor_source.cc +++ b/base/power_monitor/power_monitor_source.cc
@@ -9,8 +9,8 @@ namespace base { -PowerMonitorSource::PowerMonitorSource() {} -PowerMonitorSource::~PowerMonitorSource() {} +PowerMonitorSource::PowerMonitorSource() = default; +PowerMonitorSource::~PowerMonitorSource() = default; bool PowerMonitorSource::IsOnBatteryPower() { AutoLock auto_lock(battery_lock_);
diff --git a/base/power_monitor/power_monitor_unittest.cc b/base/power_monitor/power_monitor_unittest.cc index f1c2459..7f2a84b7 100644 --- a/base/power_monitor/power_monitor_unittest.cc +++ b/base/power_monitor/power_monitor_unittest.cc
@@ -17,7 +17,7 @@ power_monitor_.reset(new PowerMonitor( std::unique_ptr<PowerMonitorSource>(power_monitor_source_))); } - ~PowerMonitorTest() override {} + ~PowerMonitorTest() override = default; PowerMonitorTestSource* source() { return power_monitor_source_; } PowerMonitor* monitor() { return power_monitor_.get(); }
diff --git a/base/process/launch_posix.cc b/base/process/launch_posix.cc index 570cdbf..148ad4f 100644 --- a/base/process/launch_posix.cc +++ b/base/process/launch_posix.cc
@@ -693,10 +693,6 @@ #if defined(OS_LINUX) || defined(OS_NACL_NONSFI) || defined(OS_AIX) namespace { -bool IsRunningOnValgrind() { - return RUNNING_ON_VALGRIND; -} - // This function runs on the stack specified on the clone call. It uses longjmp // to switch back to the original stack so the child can return from sys_clone. int CloneHelper(void* arg) { @@ -759,7 +755,7 @@ // without CLONE_VM, so we cannot use libc's clone wrapper when running under // Valgrind. As a result, the libc pid cache may be incorrect under Valgrind. // See crbug.com/442817 for more details. - if (IsRunningOnValgrind()) { + if (RunningOnValgrind()) { // See kernel/fork.c in Linux. There is different ordering of sys_clone // parameters depending on CONFIG_CLONE_BACKWARDS* configuration options. #if defined(ARCH_CPU_X86_64)
diff --git a/base/process/process_iterator.cc b/base/process/process_iterator.cc index 920c8d0..013017f 100644 --- a/base/process/process_iterator.cc +++ b/base/process/process_iterator.cc
@@ -10,7 +10,7 @@ #if defined(OS_POSIX) ProcessEntry::ProcessEntry() : pid_(0), ppid_(0), gid_(0) {} ProcessEntry::ProcessEntry(const ProcessEntry& other) = default; -ProcessEntry::~ProcessEntry() {} +ProcessEntry::~ProcessEntry() = default; #endif const ProcessEntry* ProcessIterator::NextProcessEntry() { @@ -52,8 +52,7 @@ #endif } -NamedProcessIterator::~NamedProcessIterator() { -} +NamedProcessIterator::~NamedProcessIterator() = default; int GetProcessCount(const FilePath::StringType& executable_name, const ProcessFilter* filter) {
diff --git a/base/process/process_metrics_posix.cc b/base/process/process_metrics_posix.cc index 0eb5c1f9..73a52d621 100644 --- a/base/process/process_metrics_posix.cc +++ b/base/process/process_metrics_posix.cc
@@ -29,7 +29,7 @@ return ret; } -ProcessMetrics::~ProcessMetrics() { } +ProcessMetrics::~ProcessMetrics() = default; #if defined(OS_LINUX) static const rlim_t kSystemDefaultMaxFds = 8192;
diff --git a/base/process/process_metrics_unittest.cc b/base/process/process_metrics_unittest.cc index be08bb9..fdf9c96a 100644 --- a/base/process/process_metrics_unittest.cc +++ b/base/process/process_metrics_unittest.cc
@@ -51,7 +51,7 @@ // Exists as a class so it can be a friend of SystemMetrics. class SystemMetricsTest : public testing::Test { public: - SystemMetricsTest() {} + SystemMetricsTest() = default; private: DISALLOW_COPY_AND_ASSIGN(SystemMetricsTest);
diff --git a/base/process/process_posix.cc b/base/process/process_posix.cc index a7772b7a..2481e26 100644 --- a/base/process/process_posix.cc +++ b/base/process/process_posix.cc
@@ -225,8 +225,7 @@ Process::Process(ProcessHandle handle) : process_(handle) { } -Process::~Process() { -} +Process::~Process() = default; Process::Process(Process&& other) : process_(other.process_) { other.Close();
diff --git a/base/process/process_util_unittest.cc b/base/process/process_util_unittest.cc index f6f3a83..43f2898 100644 --- a/base/process/process_util_unittest.cc +++ b/base/process/process_util_unittest.cc
@@ -1038,7 +1038,7 @@ class ReadFromPipeDelegate : public base::LaunchOptions::PreExecDelegate { public: explicit ReadFromPipeDelegate(int fd) : fd_(fd) {} - ~ReadFromPipeDelegate() override {} + ~ReadFromPipeDelegate() override = default; void RunAsyncSafe() override { char c; RAW_CHECK(HANDLE_EINTR(read(fd_, &c, 1)) == 1);
diff --git a/base/process/process_win.cc b/base/process/process_win.cc index 3c27d98..005a68e 100644 --- a/base/process/process_win.cc +++ b/base/process/process_win.cc
@@ -84,6 +84,9 @@ // static void Process::TerminateCurrentProcessImmediately(int exit_code) { ::TerminateProcess(GetCurrentProcess(), exit_code); + // There is some ambiguity over whether the call above can return. Rather than + // hitting confusing crashes later on we should crash right here. + CHECK(false); } bool Process::IsValid() const {
diff --git a/base/profiler/native_stack_sampler.cc b/base/profiler/native_stack_sampler.cc index 6fa9cfa..6eed54f 100644 --- a/base/profiler/native_stack_sampler.cc +++ b/base/profiler/native_stack_sampler.cc
@@ -13,11 +13,11 @@ sizeof(uintptr_t)]), size_(buffer_size) {} -NativeStackSampler::StackBuffer::~StackBuffer() {} +NativeStackSampler::StackBuffer::~StackBuffer() = default; -NativeStackSampler::NativeStackSampler() {} +NativeStackSampler::NativeStackSampler() = default; -NativeStackSampler::~NativeStackSampler() {} +NativeStackSampler::~NativeStackSampler() = default; std::unique_ptr<NativeStackSampler::StackBuffer> NativeStackSampler::CreateStackBuffer() { @@ -27,8 +27,8 @@ return std::make_unique<StackBuffer>(size); } -NativeStackSamplerTestDelegate::~NativeStackSamplerTestDelegate() {} +NativeStackSamplerTestDelegate::~NativeStackSamplerTestDelegate() = default; -NativeStackSamplerTestDelegate::NativeStackSamplerTestDelegate() {} +NativeStackSamplerTestDelegate::NativeStackSamplerTestDelegate() = default; } // namespace base
diff --git a/base/profiler/stack_sampling_profiler.cc b/base/profiler/stack_sampling_profiler.cc index bacde01..35e60581 100644 --- a/base/profiler/stack_sampling_profiler.cc +++ b/base/profiler/stack_sampling_profiler.cc
@@ -59,7 +59,7 @@ const FilePath& filename) : base_address(base_address), id(id), filename(filename) {} -StackSamplingProfiler::Module::~Module() {} +StackSamplingProfiler::Module::~Module() = default; // StackSamplingProfiler::Frame ----------------------------------------------- @@ -67,7 +67,7 @@ size_t module_index) : instruction_pointer(instruction_pointer), module_index(module_index) {} -StackSamplingProfiler::Frame::~Frame() {} +StackSamplingProfiler::Frame::~Frame() = default; StackSamplingProfiler::Frame::Frame() : instruction_pointer(0), module_index(kUnknownModuleIndex) { @@ -75,11 +75,11 @@ // StackSamplingProfiler::Sample ---------------------------------------------- -StackSamplingProfiler::Sample::Sample() {} +StackSamplingProfiler::Sample::Sample() = default; StackSamplingProfiler::Sample::Sample(const Sample& sample) = default; -StackSamplingProfiler::Sample::~Sample() {} +StackSamplingProfiler::Sample::~Sample() = default; StackSamplingProfiler::Sample::Sample(const Frame& frame) { frames.push_back(std::move(frame)); @@ -90,12 +90,12 @@ // StackSamplingProfiler::CallStackProfile ------------------------------------ -StackSamplingProfiler::CallStackProfile::CallStackProfile() {} +StackSamplingProfiler::CallStackProfile::CallStackProfile() = default; StackSamplingProfiler::CallStackProfile::CallStackProfile( CallStackProfile&& other) = default; -StackSamplingProfiler::CallStackProfile::~CallStackProfile() {} +StackSamplingProfiler::CallStackProfile::~CallStackProfile() = default; StackSamplingProfiler::CallStackProfile& StackSamplingProfiler::CallStackProfile::operator=(CallStackProfile&& other) = @@ -151,7 +151,7 @@ callback(callback), finished(finished), native_sampler(std::move(sampler)) {} - ~CollectionContext() {} + ~CollectionContext() = default; // An identifier for the profiler associated with this collection, used to // uniquely identify the collection to outside interests.
diff --git a/base/profiler/stack_sampling_profiler_unittest.cc b/base/profiler/stack_sampling_profiler_unittest.cc index 94c3d34..94b8a6e 100644 --- a/base/profiler/stack_sampling_profiler_unittest.cc +++ b/base/profiler/stack_sampling_profiler_unittest.cc
@@ -863,7 +863,7 @@ // Test delegate that counts samples. class SampleRecordedCounter : public NativeStackSamplerTestDelegate { public: - SampleRecordedCounter() {} + SampleRecordedCounter() = default; void OnPreStackWalk() override { AutoLock lock(lock_);
diff --git a/base/sequenced_task_runner.cc b/base/sequenced_task_runner.cc index 4f36dc4..86771c67 100644 --- a/base/sequenced_task_runner.cc +++ b/base/sequenced_task_runner.cc
@@ -28,8 +28,7 @@ : task_runner_(std::move(task_runner)) { } -OnTaskRunnerDeleter::~OnTaskRunnerDeleter() { -} +OnTaskRunnerDeleter::~OnTaskRunnerDeleter() = default; OnTaskRunnerDeleter::OnTaskRunnerDeleter(OnTaskRunnerDeleter&&) = default;
diff --git a/base/strings/string_util.cc b/base/strings/string_util.cc index d538567..2112f230 100644 --- a/base/strings/string_util.cc +++ b/base/strings/string_util.cc
@@ -36,7 +36,7 @@ // prevents other code that might accidentally use Singleton<string> from // getting our internal one. struct EmptyStrings { - EmptyStrings() {} + EmptyStrings() = default; const std::string s; const string16 s16;
diff --git a/base/sync_socket_posix.cc b/base/sync_socket_posix.cc index cc44e58a..ff1e0e6c 100644 --- a/base/sync_socket_posix.cc +++ b/base/sync_socket_posix.cc
@@ -212,7 +212,7 @@ return r; } -CancelableSyncSocket::CancelableSyncSocket() {} +CancelableSyncSocket::CancelableSyncSocket() = default; CancelableSyncSocket::CancelableSyncSocket(Handle handle) : SyncSocket(handle) { }
diff --git a/base/sync_socket_unittest.cc b/base/sync_socket_unittest.cc index 202aa2c7..fdcd9a1 100644 --- a/base/sync_socket_unittest.cc +++ b/base/sync_socket_unittest.cc
@@ -30,7 +30,7 @@ thread_.Start(); } - ~HangingReceiveThread() override {} + ~HangingReceiveThread() override = default; void Run() override { int data = 0;
diff --git a/base/synchronization/waitable_event_watcher_posix.cc b/base/synchronization/waitable_event_watcher_posix.cc index 80f142d..21368a8 100644 --- a/base/synchronization/waitable_event_watcher_posix.cc +++ b/base/synchronization/waitable_event_watcher_posix.cc
@@ -46,7 +46,7 @@ private: friend class RefCountedThreadSafe<Flag>; - ~Flag() {} + ~Flag() = default; mutable Lock lock_; bool flag_;
diff --git a/base/task_runner.cc b/base/task_runner.cc index bbba7028..aae9f9ec 100644 --- a/base/task_runner.cc +++ b/base/task_runner.cc
@@ -51,9 +51,9 @@ from_here, std::move(task), std::move(reply)); } -TaskRunner::TaskRunner() {} +TaskRunner::TaskRunner() = default; -TaskRunner::~TaskRunner() {} +TaskRunner::~TaskRunner() = default; void TaskRunner::OnDestruct() const { delete this;
diff --git a/base/test/fuzzed_data_provider.cc b/base/test/fuzzed_data_provider.cc index 14ffb12a..b2d443a9 100644 --- a/base/test/fuzzed_data_provider.cc +++ b/base/test/fuzzed_data_provider.cc
@@ -14,7 +14,7 @@ FuzzedDataProvider::FuzzedDataProvider(const uint8_t* data, size_t size) : remaining_data_(reinterpret_cast<const char*>(data), size) {} -FuzzedDataProvider::~FuzzedDataProvider() {} +FuzzedDataProvider::~FuzzedDataProvider() = default; std::string FuzzedDataProvider::ConsumeBytes(size_t num_bytes) { num_bytes = std::min(num_bytes, remaining_data_.length());
diff --git a/base/test/gtest_util.cc b/base/test/gtest_util.cc index 1552c1a..e5d38f4 100644 --- a/base/test/gtest_util.cc +++ b/base/test/gtest_util.cc
@@ -16,8 +16,7 @@ namespace base { -TestIdentifier::TestIdentifier() { -} +TestIdentifier::TestIdentifier() = default; TestIdentifier::TestIdentifier(const TestIdentifier& other) = default;
diff --git a/base/test/histogram_tester.cc b/base/test/histogram_tester.cc index 485f30f..64b4ca2 100644 --- a/base/test/histogram_tester.cc +++ b/base/test/histogram_tester.cc
@@ -29,8 +29,7 @@ } } -HistogramTester::~HistogramTester() { -} +HistogramTester::~HistogramTester() = default; void HistogramTester::ExpectUniqueSample( const std::string& name,
diff --git a/base/test/launcher/test_launcher.cc b/base/test/launcher/test_launcher.cc index 2cd90aaa..52055e5 100644 --- a/base/test/launcher/test_launcher.cc +++ b/base/test/launcher/test_launcher.cc
@@ -6,7 +6,9 @@ #include <stdio.h> -#include <memory> +#include <algorithm> +#include <map> +#include <utility> #include "base/at_exit.h" #include "base/bind.h" @@ -199,11 +201,9 @@ bool UnsetEnvironmentVariableIfExists(const std::string& name) { std::unique_ptr<Environment> env(Environment::Create()); std::string str_val; - - if (!env->GetVar(name.c_str(), &str_val)) + if (!env->GetVar(name, &str_val)) return true; - - return env->UnSetVar(name.c_str()); + return env->UnSetVar(name); } // Returns true if bot mode has been requested, i.e. defaults optimized @@ -493,7 +493,7 @@ const char kGTestRunDisabledTestsFlag[] = "gtest_also_run_disabled_tests"; const char kGTestOutputFlag[] = "gtest_output"; -TestLauncherDelegate::~TestLauncherDelegate() {} +TestLauncherDelegate::~TestLauncherDelegate() = default; TestLauncher::LaunchOptions::LaunchOptions() = default; TestLauncher::LaunchOptions::LaunchOptions(const LaunchOptions& other) = @@ -521,7 +521,7 @@ &TestLauncher::OnOutputTimeout), parallel_jobs_(parallel_jobs) {} -TestLauncher::~TestLauncher() {} +TestLauncher::~TestLauncher() = default; bool TestLauncher::Run() { if (!Init()) @@ -1025,13 +1025,13 @@ void TestLauncher::RunTests() { std::vector<std::string> test_names; - for (size_t i = 0; i < tests_.size(); i++) { + const CommandLine* command_line = CommandLine::ForCurrentProcess(); + for (const TestIdentifier& test_id : tests_) { std::string test_name = - FormatFullTestName(tests_[i].test_case_name, tests_[i].test_name); + FormatFullTestName(test_id.test_case_name, test_id.test_name); results_tracker_.AddTest(test_name); - const CommandLine* command_line = CommandLine::ForCurrentProcess(); if (test_name.find("DISABLED") != std::string::npos) { results_tracker_.AddDisabledTest(test_name); @@ -1040,8 +1040,8 @@ continue; } - if (!launcher_delegate_->ShouldRunTest(tests_[i].test_case_name, - tests_[i].test_name)) { + if (!launcher_delegate_->ShouldRunTest(test_id.test_case_name, + test_id.test_name)) { continue; } @@ -1084,7 +1084,7 @@ // Report test locations after applying all filters, so that we report test // locations only for those tests that were run as part of this shard. - results_tracker_.AddTestLocation(test_name, tests_[i].file, tests_[i].line); + results_tracker_.AddTestLocation(test_name, test_id.file, test_id.line); test_names.push_back(test_name); }
diff --git a/base/test/launcher/test_launcher.h b/base/test/launcher/test_launcher.h index eed9f069..7ca6026 100644 --- a/base/test/launcher/test_launcher.h +++ b/base/test/launcher/test_launcher.h
@@ -8,8 +8,10 @@ #include <stddef.h> #include <stdint.h> +#include <memory> #include <set> #include <string> +#include <vector> #include "base/compiler_specific.h" #include "base/macros.h"
diff --git a/base/test/launcher/test_launcher_nacl_nonsfi.cc b/base/test/launcher/test_launcher_nacl_nonsfi.cc index d456ba2..2199e5a 100644 --- a/base/test/launcher/test_launcher_nacl_nonsfi.cc +++ b/base/test/launcher/test_launcher_nacl_nonsfi.cc
@@ -66,8 +66,7 @@ class NonSfiUnitTestPlatformDelegate : public base::UnitTestPlatformDelegate { public: - NonSfiUnitTestPlatformDelegate() { - } + NonSfiUnitTestPlatformDelegate() = default; bool Init(const std::string& test_binary) { base::FilePath dir_exe;
diff --git a/base/test/launcher/test_launcher_tracer.cc b/base/test/launcher/test_launcher_tracer.cc index 4ffa8de3..d525df752 100644 --- a/base/test/launcher/test_launcher_tracer.cc +++ b/base/test/launcher/test_launcher_tracer.cc
@@ -13,7 +13,7 @@ TestLauncherTracer::TestLauncherTracer() : trace_start_time_(TimeTicks::Now()) {} -TestLauncherTracer::~TestLauncherTracer() {} +TestLauncherTracer::~TestLauncherTracer() = default; void TestLauncherTracer::RecordProcessExecution(TimeTicks start_time, TimeDelta duration) {
diff --git a/base/test/launcher/test_result.cc b/base/test/launcher/test_result.cc index ce4776a..9f37a2b9 100644 --- a/base/test/launcher/test_result.cc +++ b/base/test/launcher/test_result.cc
@@ -49,8 +49,7 @@ TestResult::TestResult() : status(TEST_UNKNOWN) { } -TestResult::~TestResult() { -} +TestResult::~TestResult() = default; TestResult::TestResult(const TestResult& other) = default; TestResult::TestResult(TestResult&& other) = default;
diff --git a/base/test/launcher/test_results_tracker.cc b/base/test/launcher/test_results_tracker.cc index dc84bece..16587a1 100644 --- a/base/test/launcher/test_results_tracker.cc +++ b/base/test/launcher/test_results_tracker.cc
@@ -6,6 +6,7 @@ #include <stddef.h> +#include <memory> #include <utility> #include "base/base64.h" @@ -20,6 +21,7 @@ #include "base/strings/stringprintf.h" #include "base/test/gtest_util.h" #include "base/test/launcher/test_launcher.h" +#include "base/time/time.h" #include "base/values.h" namespace base { @@ -34,8 +36,8 @@ // 8601 format, without the timezone information. // TODO(xyzzyz): Find a good place in Chromium to put it and refactor all uses // to point to it. -std::string FormatTimeAsIso8601(base::Time time) { - base::Time::Exploded exploded; +std::string FormatTimeAsIso8601(Time time) { + Time::Exploded exploded; time.UTCExplode(&exploded); return StringPrintf("%04d-%02d-%02dT%02d:%02d:%02d", exploded.year, @@ -78,7 +80,7 @@ int disabled; int errors; - base::TimeDelta elapsed_time; + TimeDelta elapsed_time; }; } // namespace @@ -105,14 +107,13 @@ } fprintf(out_, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); - fprintf(out_, "<testsuites name=\"AllTests\" tests=\"%d\" failures=\"%d\"" + fprintf(out_, + "<testsuites name=\"AllTests\" tests=\"%d\" failures=\"%d\"" " disabled=\"%d\" errors=\"%d\" time=\"%.3f\" timestamp=\"%s\">\n", - all_tests_aggregator.tests, - all_tests_aggregator.failures, - all_tests_aggregator.disabled, - all_tests_aggregator.errors, + all_tests_aggregator.tests, all_tests_aggregator.failures, + all_tests_aggregator.disabled, all_tests_aggregator.errors, all_tests_aggregator.elapsed_time.InSecondsF(), - FormatTimeAsIso8601(base::Time::Now()).c_str()); + FormatTimeAsIso8601(Time::Now()).c_str()); for (const TestCaseMap::value_type& i : test_case_map) { const std::string testsuite_name = i.first; @@ -122,14 +123,14 @@ for (const TestResult& result : results) { aggregator.Add(result); } - fprintf(out_, " <testsuite name=\"%s\" tests=\"%d\" " + fprintf(out_, + " <testsuite name=\"%s\" tests=\"%d\" " "failures=\"%d\" disabled=\"%d\" errors=\"%d\" time=\"%.3f\" " "timestamp=\"%s\">\n", - testsuite_name.c_str(), - aggregator.tests, aggregator.failures, + testsuite_name.c_str(), aggregator.tests, aggregator.failures, aggregator.disabled, aggregator.errors, aggregator.elapsed_time.InSecondsF(), - FormatTimeAsIso8601(base::Time::Now()).c_str()); + FormatTimeAsIso8601(Time::Now()).c_str()); for (const TestResult& result : results) { fprintf(out_, " <testcase name=\"%s\" status=\"run\" time=\"%.3f\"" @@ -188,7 +189,7 @@ LOG(WARNING) << "The output directory does not exist. " << "Creating the directory: " << dir_name.value(); // Create the directory if necessary (because the gtest does the same). - if (!base::CreateDirectory(dir_name)) { + if (!CreateDirectory(dir_name)) { LOG(ERROR) << "Failed to created directory " << dir_name.value(); return false; } @@ -482,33 +483,29 @@ count, count != 1 ? "s" : "", description.c_str()); - for (InputIterator i = first; i != last; ++i) { - fprintf(stdout, - " %s (%s:%d)\n", - (*i).c_str(), - test_locations_.at(*i).file.c_str(), - test_locations_.at(*i).line); + for (InputIterator it = first; it != last; ++it) { + const std::string& test_name = *it; + const auto location_it = test_locations_.find(test_name); + DCHECK(location_it != test_locations_.end()) << test_name; + const CodeLocation& location = location_it->second; + fprintf(stdout, " %s (%s:%d)\n", test_name.c_str(), + location.file.c_str(), location.line); } fflush(stdout); } - -TestResultsTracker::AggregateTestResult::AggregateTestResult() { -} +TestResultsTracker::AggregateTestResult::AggregateTestResult() = default; TestResultsTracker::AggregateTestResult::AggregateTestResult( const AggregateTestResult& other) = default; -TestResultsTracker::AggregateTestResult::~AggregateTestResult() { -} +TestResultsTracker::AggregateTestResult::~AggregateTestResult() = default; -TestResultsTracker::PerIterationData::PerIterationData() { -} +TestResultsTracker::PerIterationData::PerIterationData() = default; TestResultsTracker::PerIterationData::PerIterationData( const PerIterationData& other) = default; -TestResultsTracker::PerIterationData::~PerIterationData() { -} +TestResultsTracker::PerIterationData::~PerIterationData() = default; } // namespace base
diff --git a/base/test/launcher/unit_test_launcher.cc b/base/test/launcher/unit_test_launcher.cc index cdbc65c7..17be529 100644 --- a/base/test/launcher/unit_test_launcher.cc +++ b/base/test/launcher/unit_test_launcher.cc
@@ -4,6 +4,10 @@ #include "base/test/launcher/unit_test_launcher.h" +#include <map> +#include <memory> +#include <utility> + #include "base/base_switches.h" #include "base/bind.h" #include "base/callback_helpers.h" @@ -108,8 +112,7 @@ class DefaultUnitTestPlatformDelegate : public UnitTestPlatformDelegate { public: - DefaultUnitTestPlatformDelegate() { - } + DefaultUnitTestPlatformDelegate() = default; private: // UnitTestPlatformDelegate: @@ -223,7 +226,7 @@ return 0; } - base::TimeTicks start_time(base::TimeTicks::Now()); + TimeTicks start_time(TimeTicks::Now()); gtest_init.Run(); TestTimeouts::Initialize(); @@ -247,11 +250,11 @@ DefaultUnitTestPlatformDelegate platform_delegate; UnitTestLauncherDelegate delegate( &platform_delegate, batch_limit, use_job_objects); - base::TestLauncher launcher(&delegate, parallel_jobs); + TestLauncher launcher(&delegate, parallel_jobs); bool success = launcher.Run(); fprintf(stdout, "Tests took %" PRId64 " seconds.\n", - (base::TimeTicks::Now() - start_time).InSeconds()); + (TimeTicks::Now() - start_time).InSeconds()); fflush(stdout); return (success ? 0 : 1); @@ -605,7 +608,7 @@ // Create a dedicated temporary directory to store the xml result data // per run to ensure clean state and make it possible to launch multiple // processes in parallel. - base::FilePath output_file; + FilePath output_file; CHECK(platform_delegate->CreateTemporaryFile(&output_file)); auto observer = std::make_unique<SerialUnitTestProcessLifetimeObserver>( @@ -635,7 +638,7 @@ // Create a dedicated temporary directory to store the xml result data // per run to ensure clean state and make it possible to launch multiple // processes in parallel. - base::FilePath output_file; + FilePath output_file; CHECK(platform_delegate->CreateTemporaryFile(&output_file)); auto observer = std::make_unique<ParallelUnitTestProcessLifetimeObserver>( @@ -650,8 +653,7 @@ // depending on how many tests ran and how many remain. // Note: do NOT parse child's stdout to do that, it's known to be // unreliable (e.g. buffering issues can mix up the output). - base::TimeDelta timeout = - test_names.size() * TestTimeouts::test_launcher_timeout(); + TimeDelta timeout = test_names.size() * TestTimeouts::test_launcher_timeout(); TestLauncher::LaunchOptions options; options.flags = launch_flags;
diff --git a/base/test/launcher/unit_test_launcher.h b/base/test/launcher/unit_test_launcher.h index 91abcfb..cb5bde9 100644 --- a/base/test/launcher/unit_test_launcher.h +++ b/base/test/launcher/unit_test_launcher.h
@@ -7,6 +7,9 @@ #include <stddef.h> +#include <string> +#include <vector> + #include "base/callback.h" #include "base/files/file_path.h" #include "base/macros.h" @@ -16,7 +19,7 @@ namespace base { // Callback that runs a test suite and returns exit code. -typedef base::Callback<int(void)> RunTestSuiteCallback; +using RunTestSuiteCallback = Callback<int(void)>; // Launches unit tests in given test suite. Returns exit code. int LaunchUnitTests(int argc,
diff --git a/base/test/mock_devices_changed_observer.cc b/base/test/mock_devices_changed_observer.cc index c05f26a6..9fc57cd 100644 --- a/base/test/mock_devices_changed_observer.cc +++ b/base/test/mock_devices_changed_observer.cc
@@ -6,10 +6,8 @@ namespace base { -MockDevicesChangedObserver::MockDevicesChangedObserver() { -} +MockDevicesChangedObserver::MockDevicesChangedObserver() = default; -MockDevicesChangedObserver::~MockDevicesChangedObserver() { -} +MockDevicesChangedObserver::~MockDevicesChangedObserver() = default; } // namespace base
diff --git a/base/test/mock_entropy_provider.cc b/base/test/mock_entropy_provider.cc index 5ebf19a..f3fd2a4 100644 --- a/base/test/mock_entropy_provider.cc +++ b/base/test/mock_entropy_provider.cc
@@ -9,7 +9,7 @@ MockEntropyProvider::MockEntropyProvider() : entropy_value_(0.5) {} MockEntropyProvider::MockEntropyProvider(double entropy_value) : entropy_value_(entropy_value) {} -MockEntropyProvider::~MockEntropyProvider() {} +MockEntropyProvider::~MockEntropyProvider() = default; double MockEntropyProvider::GetEntropyForTrial( const std::string& trial_name,
diff --git a/base/test/multiprocess_test.cc b/base/test/multiprocess_test.cc index 68f7604..46556f75 100644 --- a/base/test/multiprocess_test.cc +++ b/base/test/multiprocess_test.cc
@@ -50,8 +50,7 @@ // MultiProcessTest ------------------------------------------------------------ -MultiProcessTest::MultiProcessTest() { -} +MultiProcessTest::MultiProcessTest() = default; Process MultiProcessTest::SpawnChild(const std::string& procname) { LaunchOptions options;
diff --git a/base/test/null_task_runner.cc b/base/test/null_task_runner.cc index 44a41a1..dfa26fa 100644 --- a/base/test/null_task_runner.cc +++ b/base/test/null_task_runner.cc
@@ -6,9 +6,9 @@ namespace base { -NullTaskRunner::NullTaskRunner() {} +NullTaskRunner::NullTaskRunner() = default; -NullTaskRunner::~NullTaskRunner() {} +NullTaskRunner::~NullTaskRunner() = default; bool NullTaskRunner::PostDelayedTask(const Location& from_here, OnceClosure task,
diff --git a/base/test/power_monitor_test_base.cc b/base/test/power_monitor_test_base.cc index 9eba874..f662b535 100644 --- a/base/test/power_monitor_test_base.cc +++ b/base/test/power_monitor_test_base.cc
@@ -17,8 +17,7 @@ << "PowerMonitorTestSource requires a MessageLoop."; } -PowerMonitorTestSource::~PowerMonitorTestSource() { -} +PowerMonitorTestSource::~PowerMonitorTestSource() = default; void PowerMonitorTestSource::GeneratePowerStateEvent(bool on_battery_power) { test_on_battery_power_ = on_battery_power; @@ -47,8 +46,7 @@ resumes_(0) { } -PowerMonitorTestObserver::~PowerMonitorTestObserver() { -} +PowerMonitorTestObserver::~PowerMonitorTestObserver() = default; // PowerObserver callbacks. void PowerMonitorTestObserver::OnPowerStateChange(bool on_battery_power) {
diff --git a/base/test/scoped_feature_list.cc b/base/test/scoped_feature_list.cc index 170500d..bd3e3a4 100644 --- a/base/test/scoped_feature_list.cc +++ b/base/test/scoped_feature_list.cc
@@ -81,7 +81,7 @@ } // namespace -ScopedFeatureList::ScopedFeatureList() {} +ScopedFeatureList::ScopedFeatureList() = default; ScopedFeatureList::~ScopedFeatureList() { if (field_trial_override_)
diff --git a/base/test/sequenced_task_runner_test_template.cc b/base/test/sequenced_task_runner_test_template.cc index 0022aac..de68492 100644 --- a/base/test/sequenced_task_runner_test_template.cc +++ b/base/test/sequenced_task_runner_test_template.cc
@@ -99,8 +99,7 @@ task_end_cv_.Wait(); } -SequencedTaskTracker::~SequencedTaskTracker() { -} +SequencedTaskTracker::~SequencedTaskTracker() = default; void PrintTo(const TaskEvent& event, std::ostream* os) { *os << "(i=" << event.i << ", type=";
diff --git a/base/test/simple_test_clock.cc b/base/test/simple_test_clock.cc index a2bdc2a..cf95065f 100644 --- a/base/test/simple_test_clock.cc +++ b/base/test/simple_test_clock.cc
@@ -6,9 +6,9 @@ namespace base { -SimpleTestClock::SimpleTestClock() {} +SimpleTestClock::SimpleTestClock() = default; -SimpleTestClock::~SimpleTestClock() {} +SimpleTestClock::~SimpleTestClock() = default; Time SimpleTestClock::Now() { AutoLock lock(lock_);
diff --git a/base/test/simple_test_tick_clock.cc b/base/test/simple_test_tick_clock.cc index c6375bd..d454646 100644 --- a/base/test/simple_test_tick_clock.cc +++ b/base/test/simple_test_tick_clock.cc
@@ -8,9 +8,9 @@ namespace base { -SimpleTestTickClock::SimpleTestTickClock() {} +SimpleTestTickClock::SimpleTestTickClock() = default; -SimpleTestTickClock::~SimpleTestTickClock() {} +SimpleTestTickClock::~SimpleTestTickClock() = default; TimeTicks SimpleTestTickClock::NowTicks() { AutoLock lock(lock_);
diff --git a/base/test/task_runner_test_template.cc b/base/test/task_runner_test_template.cc index 5a72d31a..fe702472 100644 --- a/base/test/task_runner_test_template.cc +++ b/base/test/task_runner_test_template.cc
@@ -10,7 +10,7 @@ TaskTracker::TaskTracker() : task_runs_(0), task_runs_cv_(&lock_) {} -TaskTracker::~TaskTracker() {} +TaskTracker::~TaskTracker() = default; Closure TaskTracker::WrapTask(const Closure& task, int i) { return Bind(&TaskTracker::RunTask, this, task, i);
diff --git a/base/test/test_discardable_memory_allocator.cc b/base/test/test_discardable_memory_allocator.cc index 23aac68c7..37397d8 100644 --- a/base/test/test_discardable_memory_allocator.cc +++ b/base/test/test_discardable_memory_allocator.cc
@@ -53,11 +53,9 @@ } // namespace -TestDiscardableMemoryAllocator::TestDiscardableMemoryAllocator() { -} +TestDiscardableMemoryAllocator::TestDiscardableMemoryAllocator() = default; -TestDiscardableMemoryAllocator::~TestDiscardableMemoryAllocator() { -} +TestDiscardableMemoryAllocator::~TestDiscardableMemoryAllocator() = default; std::unique_ptr<DiscardableMemory> TestDiscardableMemoryAllocator::AllocateLockedDiscardableMemory(size_t size) {
diff --git a/base/test/test_message_loop.cc b/base/test/test_message_loop.cc index 7283a879..bd3610f 100644 --- a/base/test/test_message_loop.cc +++ b/base/test/test_message_loop.cc
@@ -7,7 +7,7 @@ namespace base { -TestMessageLoop::TestMessageLoop() {} +TestMessageLoop::TestMessageLoop() = default; TestMessageLoop::TestMessageLoop(MessageLoop::Type type) : loop_(type) {}
diff --git a/base/test/test_mock_time_task_runner.cc b/base/test/test_mock_time_task_runner.cc index 86cebb0b..d97e35a9 100644 --- a/base/test/test_mock_time_task_runner.cc +++ b/base/test/test_mock_time_task_runner.cc
@@ -162,8 +162,8 @@ nestability), ordinal(ordinal) {} -TestMockTimeTaskRunner::TestOrderedPendingTask::~TestOrderedPendingTask() { -} +TestMockTimeTaskRunner::TestOrderedPendingTask::~TestOrderedPendingTask() = + default; TestMockTimeTaskRunner::TestOrderedPendingTask& TestMockTimeTaskRunner::TestOrderedPendingTask::operator=( @@ -203,8 +203,7 @@ } } -TestMockTimeTaskRunner::~TestMockTimeTaskRunner() { -} +TestMockTimeTaskRunner::~TestMockTimeTaskRunner() = default; void TestMockTimeTaskRunner::FastForwardBy(TimeDelta delta) { DCHECK(thread_checker_.CalledOnValidThread());
diff --git a/base/test/test_pending_task.cc b/base/test/test_pending_task.cc index 999de7e..f9cfa8e 100644 --- a/base/test/test_pending_task.cc +++ b/base/test/test_pending_task.cc
@@ -36,7 +36,7 @@ return GetTimeToRun() < other.GetTimeToRun(); } -TestPendingTask::~TestPendingTask() {} +TestPendingTask::~TestPendingTask() = default; void TestPendingTask::AsValueInto(base::trace_event::TracedValue* state) const { state->SetInteger("run_at", GetTimeToRun().ToInternalValue());
diff --git a/base/test/thread_test_helper.cc b/base/test/thread_test_helper.cc index 037de2b..f3ca7807 100644 --- a/base/test/thread_test_helper.cc +++ b/base/test/thread_test_helper.cc
@@ -31,7 +31,7 @@ void ThreadTestHelper::RunTest() { set_test_result(true); } -ThreadTestHelper::~ThreadTestHelper() {} +ThreadTestHelper::~ThreadTestHelper() = default; void ThreadTestHelper::RunOnSequence() { RunTest();
diff --git a/base/test/trace_event_analyzer.cc b/base/test/trace_event_analyzer.cc index 0431bcc..5d6d081 100644 --- a/base/test/trace_event_analyzer.cc +++ b/base/test/trace_event_analyzer.cc
@@ -27,8 +27,7 @@ TraceEvent::TraceEvent(TraceEvent&& other) = default; -TraceEvent::~TraceEvent() { -} +TraceEvent::~TraceEvent() = default; TraceEvent& TraceEvent::operator=(TraceEvent&& rhs) = default; @@ -205,8 +204,7 @@ QueryNode::QueryNode(const Query& query) : query_(query) { } -QueryNode::~QueryNode() { -} +QueryNode::~QueryNode() = default; // Query @@ -227,19 +225,9 @@ is_pattern_(false) { } -Query::Query(const Query& query) - : type_(query.type_), - operator_(query.operator_), - left_(query.left_), - right_(query.right_), - member_(query.member_), - number_(query.number_), - string_(query.string_), - is_pattern_(query.is_pattern_) { -} +Query::Query(const Query& query) = default; -Query::~Query() { -} +Query::~Query() = default; Query Query::String(const std::string& str) { return Query(str); @@ -728,8 +716,7 @@ TraceAnalyzer::TraceAnalyzer() : ignore_metadata_events_(false), allow_association_changes_(true) {} -TraceAnalyzer::~TraceAnalyzer() { -} +TraceAnalyzer::~TraceAnalyzer() = default; // static TraceAnalyzer* TraceAnalyzer::Create(const std::string& json_events) {
diff --git a/base/threading/sequenced_worker_pool.cc b/base/threading/sequenced_worker_pool.cc index 8dc2b6fa..4a2fdfda 100644 --- a/base/threading/sequenced_worker_pool.cc +++ b/base/threading/sequenced_worker_pool.cc
@@ -80,7 +80,7 @@ sequence_task_number(0), shutdown_behavior(SequencedWorkerPool::BLOCK_SHUTDOWN) {} - ~SequencedTask() {} + ~SequencedTask() = default; SequencedTask(SequencedTask&&) = default; SequencedTask& operator=(SequencedTask&&) = default; @@ -151,8 +151,7 @@ SequencedWorkerPool::WorkerShutdown shutdown_behavior) : pool_(std::move(pool)), shutdown_behavior_(shutdown_behavior) {} -SequencedWorkerPoolTaskRunner::~SequencedWorkerPoolTaskRunner() { -} +SequencedWorkerPoolTaskRunner::~SequencedWorkerPoolTaskRunner() = default; bool SequencedWorkerPoolTaskRunner::PostDelayedTask(const Location& from_here, OnceClosure task, @@ -578,8 +577,7 @@ Start(); } -SequencedWorkerPool::Worker::~Worker() { -} +SequencedWorkerPool::Worker::~Worker() = default; void SequencedWorkerPool::Worker::Run() { DCHECK_EQ(AllPoolsState::USE_WORKER_POOL, g_all_pools_state); @@ -1474,7 +1472,7 @@ task_priority, observer)) {} -SequencedWorkerPool::~SequencedWorkerPool() {} +SequencedWorkerPool::~SequencedWorkerPool() = default; void SequencedWorkerPool::OnDestruct() const { // Avoid deleting ourselves on a worker thread (which would deadlock).
diff --git a/base/threading/sequenced_worker_pool_unittest.cc b/base/threading/sequenced_worker_pool_unittest.cc index 8afd5a1..32ed912 100644 --- a/base/threading/sequenced_worker_pool_unittest.cc +++ b/base/threading/sequenced_worker_pool_unittest.cc
@@ -210,7 +210,7 @@ private: friend class base::RefCountedThreadSafe<TestTracker>; - ~TestTracker() {} + ~TestTracker() = default; void SignalWorkerDone(int id) { { @@ -1105,9 +1105,9 @@ class SequencedWorkerPoolTaskRunnerTestDelegate { public: - SequencedWorkerPoolTaskRunnerTestDelegate() {} + SequencedWorkerPoolTaskRunnerTestDelegate() = default; - ~SequencedWorkerPoolTaskRunnerTestDelegate() {} + ~SequencedWorkerPoolTaskRunnerTestDelegate() = default; void StartTaskRunner() { pool_owner_.reset( @@ -1140,10 +1140,9 @@ class SequencedWorkerPoolTaskRunnerWithShutdownBehaviorTestDelegate { public: - SequencedWorkerPoolTaskRunnerWithShutdownBehaviorTestDelegate() {} + SequencedWorkerPoolTaskRunnerWithShutdownBehaviorTestDelegate() = default; - ~SequencedWorkerPoolTaskRunnerWithShutdownBehaviorTestDelegate() { - } + ~SequencedWorkerPoolTaskRunnerWithShutdownBehaviorTestDelegate() = default; void StartTaskRunner() { pool_owner_.reset( @@ -1180,10 +1179,9 @@ class SequencedWorkerPoolSequencedTaskRunnerTestDelegate { public: - SequencedWorkerPoolSequencedTaskRunnerTestDelegate() {} + SequencedWorkerPoolSequencedTaskRunnerTestDelegate() = default; - ~SequencedWorkerPoolSequencedTaskRunnerTestDelegate() { - } + ~SequencedWorkerPoolSequencedTaskRunnerTestDelegate() = default; void StartTaskRunner() { pool_owner_.reset(new SequencedWorkerPoolOwner(
diff --git a/base/threading/simple_thread_unittest.cc b/base/threading/simple_thread_unittest.cc index 0e52500..4e618f9 100644 --- a/base/threading/simple_thread_unittest.cc +++ b/base/threading/simple_thread_unittest.cc
@@ -19,7 +19,7 @@ class SetIntRunner : public DelegateSimpleThread::Delegate { public: SetIntRunner(int* ptr, int val) : ptr_(ptr), val_(val) { } - ~SetIntRunner() override {} + ~SetIntRunner() override = default; private: void Run() override { *ptr_ = val_; } @@ -69,7 +69,7 @@ class WaitEventRunner : public DelegateSimpleThread::Delegate { public: explicit WaitEventRunner(WaitableEvent* event) : event_(event) { } - ~WaitEventRunner() override {} + ~WaitEventRunner() override = default; private: void Run() override {
diff --git a/base/threading/thread_collision_warner_unittest.cc b/base/threading/thread_collision_warner_unittest.cc index 71447ef..cd56768 100644 --- a/base/threading/thread_collision_warner_unittest.cc +++ b/base/threading/thread_collision_warner_unittest.cc
@@ -46,7 +46,7 @@ void warn() override { failed_ = true; } - ~AssertReporter() override {} + ~AssertReporter() override = default; bool fail_state() const { return failed_; } void reset() { failed_ = false; }
diff --git a/base/threading/thread_id_name_manager.cc b/base/threading/thread_id_name_manager.cc index 03c1eee2..74a42c7d 100644 --- a/base/threading/thread_id_name_manager.cc +++ b/base/threading/thread_id_name_manager.cc
@@ -28,8 +28,7 @@ name_to_interned_name_[kDefaultName] = g_default_name; } -ThreadIdNameManager::~ThreadIdNameManager() { -} +ThreadIdNameManager::~ThreadIdNameManager() = default; ThreadIdNameManager* ThreadIdNameManager::GetInstance() { return Singleton<ThreadIdNameManager,
diff --git a/base/threading/thread_local_storage_unittest.cc b/base/threading/thread_local_storage_unittest.cc index 335252b..a577e76 100644 --- a/base/threading/thread_local_storage_unittest.cc +++ b/base/threading/thread_local_storage_unittest.cc
@@ -35,7 +35,7 @@ explicit ThreadLocalStorageRunner(int* tls_value_ptr) : tls_value_ptr_(tls_value_ptr) {} - ~ThreadLocalStorageRunner() override {} + ~ThreadLocalStorageRunner() override = default; void Run() override { *tls_value_ptr_ = kInitialTlsValue;
diff --git a/base/threading/thread_local_unittest.cc b/base/threading/thread_local_unittest.cc index 8517683..54f2ad2 100644 --- a/base/threading/thread_local_unittest.cc +++ b/base/threading/thread_local_unittest.cc
@@ -20,7 +20,7 @@ : tlp_(tlp), done_(done) { } - ~ThreadLocalTesterBase() override {} + ~ThreadLocalTesterBase() override = default; protected: TLPType* tlp_; @@ -31,7 +31,7 @@ public: SetThreadLocal(TLPType* tlp, base::WaitableEvent* done) : ThreadLocalTesterBase(tlp, done), val_(nullptr) {} - ~SetThreadLocal() override {} + ~SetThreadLocal() override = default; void set_value(char* val) { val_ = val; } @@ -49,7 +49,7 @@ public: GetThreadLocal(TLPType* tlp, base::WaitableEvent* done) : ThreadLocalTesterBase(tlp, done), ptr_(nullptr) {} - ~GetThreadLocal() override {} + ~GetThreadLocal() override = default; void set_ptr(char** ptr) { ptr_ = ptr; }
diff --git a/base/threading/watchdog_unittest.cc b/base/threading/watchdog_unittest.cc index 473f3ec..f534a863 100644 --- a/base/threading/watchdog_unittest.cc +++ b/base/threading/watchdog_unittest.cc
@@ -27,7 +27,7 @@ alarm_counter_(0) { } - ~WatchdogCounter() override {} + ~WatchdogCounter() override = default; void Alarm() override { alarm_counter_++;
diff --git a/base/time/clock.cc b/base/time/clock.cc index 34dc37e..9e3f2712 100644 --- a/base/time/clock.cc +++ b/base/time/clock.cc
@@ -6,6 +6,6 @@ namespace base { -Clock::~Clock() {} +Clock::~Clock() = default; } // namespace base
diff --git a/base/time/default_clock.cc b/base/time/default_clock.cc index 2f90dad5..284e12d 100644 --- a/base/time/default_clock.cc +++ b/base/time/default_clock.cc
@@ -8,7 +8,7 @@ namespace base { -DefaultClock::~DefaultClock() {} +DefaultClock::~DefaultClock() = default; Time DefaultClock::Now() { return Time::Now();
diff --git a/base/time/default_tick_clock.cc b/base/time/default_tick_clock.cc index ce394de5..96d4d86 100644 --- a/base/time/default_tick_clock.cc +++ b/base/time/default_tick_clock.cc
@@ -8,7 +8,7 @@ namespace base { -DefaultTickClock::~DefaultTickClock() {} +DefaultTickClock::~DefaultTickClock() = default; TimeTicks DefaultTickClock::NowTicks() { return TimeTicks::Now();
diff --git a/base/time/tick_clock.cc b/base/time/tick_clock.cc index 495805c..79e396d 100644 --- a/base/time/tick_clock.cc +++ b/base/time/tick_clock.cc
@@ -6,6 +6,6 @@ namespace base { -TickClock::~TickClock() {} +TickClock::~TickClock() = default; } // namespace base
diff --git a/base/timer/hi_res_timer_manager_posix.cc b/base/timer/hi_res_timer_manager_posix.cc index 89012b9..d2a3aa5 100644 --- a/base/timer/hi_res_timer_manager_posix.cc +++ b/base/timer/hi_res_timer_manager_posix.cc
@@ -12,8 +12,7 @@ : hi_res_clock_available_(false) { } -HighResolutionTimerManager::~HighResolutionTimerManager() { -} +HighResolutionTimerManager::~HighResolutionTimerManager() = default; void HighResolutionTimerManager::OnPowerStateChange(bool on_battery_power) { }
diff --git a/base/timer/mock_timer.cc b/base/timer/mock_timer.cc index b53c0065..ca0893b 100644 --- a/base/timer/mock_timer.cc +++ b/base/timer/mock_timer.cc
@@ -17,8 +17,7 @@ bool is_repeating) : Timer(true, is_repeating), delay_(delay), is_running_(false) {} -MockTimer::~MockTimer() { -} +MockTimer::~MockTimer() = default; bool MockTimer::IsRunning() const { return is_running_;
diff --git a/base/timer/mock_timer_unittest.cc b/base/timer/mock_timer_unittest.cc index a389815..ed05f39 100644 --- a/base/timer/mock_timer_unittest.cc +++ b/base/timer/mock_timer_unittest.cc
@@ -56,8 +56,8 @@ class HasWeakPtr : public base::SupportsWeakPtr<HasWeakPtr> { public: - HasWeakPtr() {} - virtual ~HasWeakPtr() {} + HasWeakPtr() = default; + virtual ~HasWeakPtr() = default; private: DISALLOW_COPY_AND_ASSIGN(HasWeakPtr);
diff --git a/base/tools_sanity_unittest.cc b/base/tools_sanity_unittest.cc index af2081d3..5c41bd7 100644 --- a/base/tools_sanity_unittest.cc +++ b/base/tools_sanity_unittest.cc
@@ -254,7 +254,7 @@ class TOOLS_SANITY_TEST_CONCURRENT_THREAD : public PlatformThread::Delegate { public: explicit TOOLS_SANITY_TEST_CONCURRENT_THREAD(bool *value) : value_(value) {} - ~TOOLS_SANITY_TEST_CONCURRENT_THREAD() override {} + ~TOOLS_SANITY_TEST_CONCURRENT_THREAD() override = default; void ThreadMain() override { *value_ = true; @@ -270,7 +270,7 @@ class ReleaseStoreThread : public PlatformThread::Delegate { public: explicit ReleaseStoreThread(base::subtle::Atomic32 *value) : value_(value) {} - ~ReleaseStoreThread() override {} + ~ReleaseStoreThread() override = default; void ThreadMain() override { base::subtle::Release_Store(value_, kMagicValue); @@ -286,7 +286,7 @@ class AcquireLoadThread : public PlatformThread::Delegate { public: explicit AcquireLoadThread(base::subtle::Atomic32 *value) : value_(value) {} - ~AcquireLoadThread() override {} + ~AcquireLoadThread() override = default; void ThreadMain() override { // Wait for the other thread to make Release_Store PlatformThread::Sleep(TimeDelta::FromMilliseconds(100));
diff --git a/base/trace_event/event_name_filter.cc b/base/trace_event/event_name_filter.cc index 8d0058c..7bf932e 100644 --- a/base/trace_event/event_name_filter.cc +++ b/base/trace_event/event_name_filter.cc
@@ -16,7 +16,7 @@ std::unique_ptr<EventNamesWhitelist> event_names_whitelist) : event_names_whitelist_(std::move(event_names_whitelist)) {} -EventNameFilter::~EventNameFilter() {} +EventNameFilter::~EventNameFilter() = default; bool EventNameFilter::FilterTraceEvent(const TraceEvent& trace_event) const { return event_names_whitelist_->count(trace_event.name()) != 0;
diff --git a/base/trace_event/heap_profiler_allocation_context_tracker.cc b/base/trace_event/heap_profiler_allocation_context_tracker.cc index f1fff8b..e9466a8 100644 --- a/base/trace_event/heap_profiler_allocation_context_tracker.cc +++ b/base/trace_event/heap_profiler_allocation_context_tracker.cc
@@ -87,7 +87,7 @@ tracked_stack_.reserve(kMaxStackDepth); task_contexts_.reserve(kMaxTaskDepth); } -AllocationContextTracker::~AllocationContextTracker() {} +AllocationContextTracker::~AllocationContextTracker() = default; // static void AllocationContextTracker::SetCurrentThreadName(const char* name) {
diff --git a/base/trace_event/heap_profiler_allocation_register.cc b/base/trace_event/heap_profiler_allocation_register.cc index 22b1788..44f34423 100644 --- a/base/trace_event/heap_profiler_allocation_register.cc +++ b/base/trace_event/heap_profiler_allocation_register.cc
@@ -91,7 +91,7 @@ DCHECK_EQ(index_and_flag.first, kOutOfStorageBacktraceIndex); } -AllocationRegister::~AllocationRegister() {} +AllocationRegister::~AllocationRegister() = default; bool AllocationRegister::Insert(const void* address, size_t size,
diff --git a/base/trace_event/heap_profiler_event_filter.cc b/base/trace_event/heap_profiler_event_filter.cc index 67125ff2..937072ca 100644 --- a/base/trace_event/heap_profiler_event_filter.cc +++ b/base/trace_event/heap_profiler_event_filter.cc
@@ -32,8 +32,8 @@ // static const char HeapProfilerEventFilter::kName[] = "heap_profiler_predicate"; -HeapProfilerEventFilter::HeapProfilerEventFilter() {} -HeapProfilerEventFilter::~HeapProfilerEventFilter() {} +HeapProfilerEventFilter::HeapProfilerEventFilter() = default; +HeapProfilerEventFilter::~HeapProfilerEventFilter() = default; bool HeapProfilerEventFilter::FilterTraceEvent( const TraceEvent& trace_event) const {
diff --git a/base/trace_event/heap_profiler_heap_dump_writer.cc b/base/trace_event/heap_profiler_heap_dump_writer.cc index 9f64f6e..71c3d97f 100644 --- a/base/trace_event/heap_profiler_heap_dump_writer.cc +++ b/base/trace_event/heap_profiler_heap_dump_writer.cc
@@ -186,7 +186,7 @@ type_name_deduplicator_(type_name_deduplicator), breakdown_threshold_bytes_(breakdown_threshold_bytes) {} -HeapDumpWriter::~HeapDumpWriter() {} +HeapDumpWriter::~HeapDumpWriter() = default; bool HeapDumpWriter::AddEntryForBucket(const Bucket& bucket) { // The contexts in the bucket are all different, but the [begin, cursor) range
diff --git a/base/trace_event/heap_profiler_serialization_state.cc b/base/trace_event/heap_profiler_serialization_state.cc index d332d43c..b1866e72 100644 --- a/base/trace_event/heap_profiler_serialization_state.cc +++ b/base/trace_event/heap_profiler_serialization_state.cc
@@ -9,7 +9,7 @@ HeapProfilerSerializationState::HeapProfilerSerializationState() : heap_profiler_breakdown_threshold_bytes_(0) {} -HeapProfilerSerializationState::~HeapProfilerSerializationState() {} +HeapProfilerSerializationState::~HeapProfilerSerializationState() = default; void HeapProfilerSerializationState::SetStackFrameDeduplicator( std::unique_ptr<StackFrameDeduplicator> stack_frame_deduplicator) {
diff --git a/base/trace_event/heap_profiler_stack_frame_deduplicator.cc b/base/trace_event/heap_profiler_stack_frame_deduplicator.cc index 351117f1..c05cd0a2 100644 --- a/base/trace_event/heap_profiler_stack_frame_deduplicator.cc +++ b/base/trace_event/heap_profiler_stack_frame_deduplicator.cc
@@ -39,14 +39,14 @@ int parent_frame_index) : frame(frame), parent_frame_index(parent_frame_index) {} StackFrameDeduplicator::FrameNode::FrameNode(const FrameNode& other) = default; -StackFrameDeduplicator::FrameNode::~FrameNode() {} +StackFrameDeduplicator::FrameNode::~FrameNode() = default; size_t StackFrameDeduplicator::FrameNode::EstimateMemoryUsage() const { return base::trace_event::EstimateMemoryUsage(children); } -StackFrameDeduplicator::StackFrameDeduplicator() {} -StackFrameDeduplicator::~StackFrameDeduplicator() {} +StackFrameDeduplicator::StackFrameDeduplicator() = default; +StackFrameDeduplicator::~StackFrameDeduplicator() = default; bool StackFrameDeduplicator::Match(int frame_index, const StackFrame* begin_frame,
diff --git a/base/trace_event/heap_profiler_type_name_deduplicator.cc b/base/trace_event/heap_profiler_type_name_deduplicator.cc index 8fb81a2e..360f239b 100644 --- a/base/trace_event/heap_profiler_type_name_deduplicator.cc +++ b/base/trace_event/heap_profiler_type_name_deduplicator.cc
@@ -24,7 +24,7 @@ type_ids_.insert(std::make_pair(nullptr, 0)); } -TypeNameDeduplicator::~TypeNameDeduplicator() {} +TypeNameDeduplicator::~TypeNameDeduplicator() = default; int TypeNameDeduplicator::Insert(const char* type_name) { auto result = type_ids_.insert(std::make_pair(type_name, 0));
diff --git a/base/trace_event/malloc_dump_provider.cc b/base/trace_event/malloc_dump_provider.cc index b7fdae8..ffd51913 100644 --- a/base/trace_event/malloc_dump_provider.cc +++ b/base/trace_event/malloc_dump_provider.cc
@@ -191,7 +191,7 @@ MallocDumpProvider::MallocDumpProvider() : tid_dumping_heap_(kInvalidThreadId) {} -MallocDumpProvider::~MallocDumpProvider() {} +MallocDumpProvider::~MallocDumpProvider() = default; // Called at trace dump point time. Creates a snapshot the memory counters for // the current process.
diff --git a/base/trace_event/memory_allocator_dump.cc b/base/trace_event/memory_allocator_dump.cc index 6566cad..5260a73 100644 --- a/base/trace_event/memory_allocator_dump.cc +++ b/base/trace_event/memory_allocator_dump.cc
@@ -41,8 +41,7 @@ DCHECK(absolute_name[0] != '/' && *absolute_name.rbegin() != '/'); } -MemoryAllocatorDump::~MemoryAllocatorDump() { -} +MemoryAllocatorDump::~MemoryAllocatorDump() = default; void MemoryAllocatorDump::AddScalar(const char* name, const char* units,
diff --git a/base/trace_event/memory_dump_manager.cc b/base/trace_event/memory_dump_manager.cc index 3b39806..14fe7e93 100644 --- a/base/trace_event/memory_dump_manager.cc +++ b/base/trace_event/memory_dump_manager.cc
@@ -930,8 +930,8 @@ MakeUnique<ProcessMemoryDump>(heap_profiler_serialization_state, args); } -MemoryDumpManager::ProcessMemoryDumpAsyncState::~ProcessMemoryDumpAsyncState() { -} +MemoryDumpManager::ProcessMemoryDumpAsyncState::~ProcessMemoryDumpAsyncState() = + default; } // namespace trace_event } // namespace base
diff --git a/base/trace_event/memory_dump_manager_unittest.cc b/base/trace_event/memory_dump_manager_unittest.cc index e2d4ee13..22cee6d65 100644 --- a/base/trace_event/memory_dump_manager_unittest.cc +++ b/base/trace_event/memory_dump_manager_unittest.cc
@@ -168,7 +168,7 @@ } private: - ~TestSequencedTaskRunner() override {} + ~TestSequencedTaskRunner() override = default; SequencedWorkerPoolOwner worker_pool_; const SequencedWorkerPool::SequenceToken token_;
diff --git a/base/trace_event/memory_dump_provider_info.cc b/base/trace_event/memory_dump_provider_info.cc index 34784eb..65eeadf 100644 --- a/base/trace_event/memory_dump_provider_info.cc +++ b/base/trace_event/memory_dump_provider_info.cc
@@ -27,7 +27,7 @@ consecutive_failures(0), disabled(false) {} -MemoryDumpProviderInfo::~MemoryDumpProviderInfo() {} +MemoryDumpProviderInfo::~MemoryDumpProviderInfo() = default; bool MemoryDumpProviderInfo::Comparator::operator()( const scoped_refptr<MemoryDumpProviderInfo>& a,
diff --git a/base/trace_event/memory_dump_scheduler.cc b/base/trace_event/memory_dump_scheduler.cc index 8e4baaa..0332af7 100644 --- a/base/trace_event/memory_dump_scheduler.cc +++ b/base/trace_event/memory_dump_scheduler.cc
@@ -114,8 +114,8 @@ TimeDelta::FromMilliseconds(period_ms_)); } -MemoryDumpScheduler::Config::Config() {} -MemoryDumpScheduler::Config::~Config() {} +MemoryDumpScheduler::Config::Config() = default; +MemoryDumpScheduler::Config::~Config() = default; MemoryDumpScheduler::Config::Config(const MemoryDumpScheduler::Config&) = default;
diff --git a/base/trace_event/process_memory_dump.cc b/base/trace_event/process_memory_dump.cc index f315c48a..3d068af 100644 --- a/base/trace_event/process_memory_dump.cc +++ b/base/trace_event/process_memory_dump.cc
@@ -198,7 +198,7 @@ std::move(heap_profiler_serialization_state)), dump_args_(dump_args) {} -ProcessMemoryDump::~ProcessMemoryDump() {} +ProcessMemoryDump::~ProcessMemoryDump() = default; ProcessMemoryDump::ProcessMemoryDump(ProcessMemoryDump&& other) = default; ProcessMemoryDump& ProcessMemoryDump::operator=(ProcessMemoryDump&& other) = default;
diff --git a/base/trace_event/trace_buffer.cc b/base/trace_event/trace_buffer.cc index a776fa3..8de470f 100644 --- a/base/trace_event/trace_buffer.cc +++ b/base/trace_event/trace_buffer.cc
@@ -246,7 +246,7 @@ TraceBufferChunk::TraceBufferChunk(uint32_t seq) : next_free_(0), seq_(seq) {} -TraceBufferChunk::~TraceBufferChunk() {} +TraceBufferChunk::~TraceBufferChunk() = default; void TraceBufferChunk::Reset(uint32_t new_seq) { for (size_t i = 0; i < next_free_; ++i) @@ -312,7 +312,7 @@ TraceResultBuffer::TraceResultBuffer() : append_comma_(false) {} -TraceResultBuffer::~TraceResultBuffer() {} +TraceResultBuffer::~TraceResultBuffer() = default; void TraceResultBuffer::SetOutputCallback( const OutputCallback& json_chunk_callback) {
diff --git a/base/trace_event/trace_config.cc b/base/trace_event/trace_config.cc index 38356d8..5926c954 100644 --- a/base/trace_event/trace_config.cc +++ b/base/trace_event/trace_config.cc
@@ -57,7 +57,7 @@ explicit ConvertableTraceConfigToTraceFormat(const TraceConfig& trace_config) : trace_config_(trace_config) {} - ~ConvertableTraceConfigToTraceFormat() override {} + ~ConvertableTraceConfigToTraceFormat() override = default; void AppendAsTraceFormat(std::string* out) const override { out->append(trace_config_.ToString()); @@ -91,12 +91,12 @@ memory_dump_config_ = memory_dump_config; } -TraceConfig::MemoryDumpConfig::MemoryDumpConfig() {} +TraceConfig::MemoryDumpConfig::MemoryDumpConfig() = default; TraceConfig::MemoryDumpConfig::MemoryDumpConfig( const MemoryDumpConfig& other) = default; -TraceConfig::MemoryDumpConfig::~MemoryDumpConfig() {} +TraceConfig::MemoryDumpConfig::~MemoryDumpConfig() = default; void TraceConfig::MemoryDumpConfig::Clear() { allowed_dump_modes.clear(); @@ -119,7 +119,7 @@ const std::string& predicate_name) : predicate_name_(predicate_name) {} -TraceConfig::EventFilterConfig::~EventFilterConfig() {} +TraceConfig::EventFilterConfig::~EventFilterConfig() = default; TraceConfig::EventFilterConfig::EventFilterConfig(const EventFilterConfig& tc) { *this = tc; @@ -224,16 +224,9 @@ InitializeDefault(); } -TraceConfig::TraceConfig(const TraceConfig& tc) - : record_mode_(tc.record_mode_), - enable_systrace_(tc.enable_systrace_), - enable_argument_filter_(tc.enable_argument_filter_), - category_filter_(tc.category_filter_), - memory_dump_config_(tc.memory_dump_config_), - event_filters_(tc.event_filters_) {} +TraceConfig::TraceConfig(const TraceConfig& tc) = default; -TraceConfig::~TraceConfig() { -} +TraceConfig::~TraceConfig() = default; TraceConfig& TraceConfig::operator=(const TraceConfig& rhs) { if (this == &rhs)
diff --git a/base/trace_event/trace_config_category_filter.cc b/base/trace_event/trace_config_category_filter.cc index de78c04..d188430 100644 --- a/base/trace_event/trace_config_category_filter.cc +++ b/base/trace_event/trace_config_category_filter.cc
@@ -20,23 +20,15 @@ const char kExcludedCategoriesParam[] = "excluded_categories"; } -TraceConfigCategoryFilter::TraceConfigCategoryFilter() {} +TraceConfigCategoryFilter::TraceConfigCategoryFilter() = default; TraceConfigCategoryFilter::TraceConfigCategoryFilter( - const TraceConfigCategoryFilter& other) - : included_categories_(other.included_categories_), - disabled_categories_(other.disabled_categories_), - excluded_categories_(other.excluded_categories_) {} + const TraceConfigCategoryFilter& other) = default; -TraceConfigCategoryFilter::~TraceConfigCategoryFilter() {} +TraceConfigCategoryFilter::~TraceConfigCategoryFilter() = default; TraceConfigCategoryFilter& TraceConfigCategoryFilter::operator=( - const TraceConfigCategoryFilter& rhs) { - included_categories_ = rhs.included_categories_; - disabled_categories_ = rhs.disabled_categories_; - excluded_categories_ = rhs.excluded_categories_; - return *this; -} + const TraceConfigCategoryFilter& rhs) = default; void TraceConfigCategoryFilter::InitializeFromString( const StringPiece& category_filter_string) {
diff --git a/base/trace_event/trace_event_filter.cc b/base/trace_event/trace_event_filter.cc index 6265295..d0b116e 100644 --- a/base/trace_event/trace_event_filter.cc +++ b/base/trace_event/trace_event_filter.cc
@@ -7,8 +7,8 @@ namespace base { namespace trace_event { -TraceEventFilter::TraceEventFilter() {} -TraceEventFilter::~TraceEventFilter() {} +TraceEventFilter::TraceEventFilter() = default; +TraceEventFilter::~TraceEventFilter() = default; void TraceEventFilter::EndEvent(const char* category_name, const char* event_name) const {}
diff --git a/base/trace_event/trace_event_filter_test_utils.cc b/base/trace_event/trace_event_filter_test_utils.cc index 06548b04..85b4cfa2 100644 --- a/base/trace_event/trace_event_filter_test_utils.cc +++ b/base/trace_event/trace_event_filter_test_utils.cc
@@ -26,8 +26,8 @@ return res; } -TestEventFilter::TestEventFilter() {} -TestEventFilter::~TestEventFilter() {} +TestEventFilter::TestEventFilter() = default; +TestEventFilter::~TestEventFilter() = default; bool TestEventFilter::FilterTraceEvent(const TraceEvent& trace_event) const { if (g_hits_counter)
diff --git a/base/trace_event/trace_event_impl.cc b/base/trace_event/trace_event_impl.cc index 08654cca..2b7f98a 100644 --- a/base/trace_event/trace_event_impl.cc +++ b/base/trace_event/trace_event_impl.cc
@@ -55,8 +55,7 @@ memset(arg_values_, 0, sizeof(arg_values_)); } -TraceEvent::~TraceEvent() { -} +TraceEvent::~TraceEvent() = default; void TraceEvent::MoveFrom(std::unique_ptr<TraceEvent> other) { timestamp_ = other->timestamp_;
diff --git a/base/trace_event/trace_event_memory_overhead.cc b/base/trace_event/trace_event_memory_overhead.cc index bb6edfba..d5875f8 100644 --- a/base/trace_event/trace_event_memory_overhead.cc +++ b/base/trace_event/trace_event_memory_overhead.cc
@@ -58,7 +58,7 @@ TraceEventMemoryOverhead::TraceEventMemoryOverhead() : allocated_objects_() {} -TraceEventMemoryOverhead::~TraceEventMemoryOverhead() {} +TraceEventMemoryOverhead::~TraceEventMemoryOverhead() = default; void TraceEventMemoryOverhead::AddInternal(ObjectType object_type, size_t count,
diff --git a/base/trace_event/trace_event_system_stats_monitor.cc b/base/trace_event/trace_event_system_stats_monitor.cc index 52e1cdc..7e082f3 100644 --- a/base/trace_event/trace_event_system_stats_monitor.cc +++ b/base/trace_event/trace_event_system_stats_monitor.cc
@@ -27,8 +27,8 @@ // Holds profiled system stats until the tracing system needs to serialize it. class SystemStatsHolder : public base::trace_event::ConvertableToTraceFormat { public: - SystemStatsHolder() { } - ~SystemStatsHolder() override {} + SystemStatsHolder() = default; + ~SystemStatsHolder() override = default; // Fills system_metrics_ with profiled system memory and disk stats. // Uses the previous stats to compute rates if this is not the first profile.
diff --git a/base/trace_event/trace_event_system_stats_monitor_unittest.cc b/base/trace_event/trace_event_system_stats_monitor_unittest.cc index cf9bdb7..52a05ba9 100644 --- a/base/trace_event/trace_event_system_stats_monitor_unittest.cc +++ b/base/trace_event/trace_event_system_stats_monitor_unittest.cc
@@ -22,8 +22,8 @@ // Exists as a class so it can be a friend of TraceEventSystemStatsMonitor. class TraceSystemStatsMonitorTest : public testing::Test { public: - TraceSystemStatsMonitorTest() {} - ~TraceSystemStatsMonitorTest() override {} + TraceSystemStatsMonitorTest() = default; + ~TraceSystemStatsMonitorTest() override = default; private: DISALLOW_COPY_AND_ASSIGN(TraceSystemStatsMonitorTest);
diff --git a/base/trace_event/trace_event_unittest.cc b/base/trace_event/trace_event_unittest.cc index 755dd61..625168f 100644 --- a/base/trace_event/trace_event_unittest.cc +++ b/base/trace_event/trace_event_unittest.cc
@@ -1277,8 +1277,8 @@ class AfterStateChangeEnabledStateObserver : public TraceLog::EnabledStateObserver { public: - AfterStateChangeEnabledStateObserver() {} - ~AfterStateChangeEnabledStateObserver() override {} + AfterStateChangeEnabledStateObserver() = default; + ~AfterStateChangeEnabledStateObserver() override = default; // TraceLog::EnabledStateObserver overrides: void OnTraceLogEnabled() override { @@ -1308,8 +1308,8 @@ class SelfRemovingEnabledStateObserver : public TraceLog::EnabledStateObserver { public: - SelfRemovingEnabledStateObserver() {} - ~SelfRemovingEnabledStateObserver() override {} + SelfRemovingEnabledStateObserver() = default; + ~SelfRemovingEnabledStateObserver() override = default; // TraceLog::EnabledStateObserver overrides: void OnTraceLogEnabled() override {} @@ -1406,7 +1406,7 @@ class Convertable : public ConvertableToTraceFormat { public: explicit Convertable(int* num_calls) : num_calls_(num_calls) {} - ~Convertable() override {} + ~Convertable() override = default; void AppendAsTraceFormat(std::string* out) const override { (*num_calls_)++; out->append("\"metadata_value\""); @@ -2153,8 +2153,8 @@ class MyData : public ConvertableToTraceFormat { public: - MyData() {} - ~MyData() override {} + MyData() = default; + ~MyData() override = default; void AppendAsTraceFormat(std::string* out) const override { out->append("{\"foo\":1}");
diff --git a/base/trace_event/trace_log.cc b/base/trace_event/trace_log.cc index 509adf6..92fccb9 100644 --- a/base/trace_event/trace_log.cc +++ b/base/trace_event/trace_log.cc
@@ -327,7 +327,7 @@ struct TraceLog::RegisteredAsyncObserver { explicit RegisteredAsyncObserver(WeakPtr<AsyncEnabledStateObserver> observer) : observer(observer), task_runner(ThreadTaskRunnerHandle::Get()) {} - ~RegisteredAsyncObserver() {} + ~RegisteredAsyncObserver() = default; WeakPtr<AsyncEnabledStateObserver> observer; scoped_refptr<SequencedTaskRunner> task_runner; @@ -335,7 +335,7 @@ TraceLogStatus::TraceLogStatus() : event_capacity(0), event_count(0) {} -TraceLogStatus::~TraceLogStatus() {} +TraceLogStatus::~TraceLogStatus() = default; // static TraceLog* TraceLog::GetInstance() { @@ -369,7 +369,7 @@ nullptr); } -TraceLog::~TraceLog() {} +TraceLog::~TraceLog() = default; void TraceLog::InitializeThreadLocalEventBufferIfSupported() { // A ThreadLocalEventBuffer needs the message loop
diff --git a/base/trace_event/tracing_agent.cc b/base/trace_event/tracing_agent.cc index 0af90f3c7..cfbaad9 100644 --- a/base/trace_event/tracing_agent.cc +++ b/base/trace_event/tracing_agent.cc
@@ -7,7 +7,7 @@ namespace base { namespace trace_event { -TracingAgent::~TracingAgent() {} +TracingAgent::~TracingAgent() = default; bool TracingAgent::SupportsExplicitClockSync() { return false;
diff --git a/base/tuple_unittest.cc b/base/tuple_unittest.cc index 730985c..321c549 100644 --- a/base/tuple_unittest.cc +++ b/base/tuple_unittest.cc
@@ -16,14 +16,14 @@ } struct Addy { - Addy() { } + Addy() = default; void DoAdd(int a, int b, int c, int d, int* res) { *res = a + b + c + d; } }; struct Addz { - Addz() { } + Addz() = default; void DoAdd(int a, int b, int c, int d, int e, int* res) { *res = a + b + c + d + e; } @@ -68,7 +68,7 @@ struct CopyLogger { CopyLogger() { ++TimesConstructed; } CopyLogger(const CopyLogger& tocopy) { ++TimesConstructed; ++TimesCopied; } - ~CopyLogger() { } + ~CopyLogger() = default; static int TimesCopied; static int TimesConstructed;
diff --git a/base/values.cc b/base/values.cc index f3e891f..261d9dc 100644 --- a/base/values.cc +++ b/base/values.cc
@@ -1113,7 +1113,7 @@ DictionaryValue::Iterator::Iterator(const Iterator& other) = default; -DictionaryValue::Iterator::~Iterator() {} +DictionaryValue::Iterator::~Iterator() = default; DictionaryValue* DictionaryValue::DeepCopy() const { return new DictionaryValue(dict_); @@ -1355,11 +1355,9 @@ return std::make_unique<ListValue>(list_); } -ValueSerializer::~ValueSerializer() { -} +ValueSerializer::~ValueSerializer() = default; -ValueDeserializer::~ValueDeserializer() { -} +ValueDeserializer::~ValueDeserializer() = default; std::ostream& operator<<(std::ostream& out, const Value& value) { std::string json;
diff --git a/base/version.cc b/base/version.cc index ca97a84..7e897b2 100644 --- a/base/version.cc +++ b/base/version.cc
@@ -77,13 +77,11 @@ } // namespace -Version::Version() { -} +Version::Version() = default; Version::Version(const Version& other) = default; -Version::~Version() { -} +Version::~Version() = default; Version::Version(const std::string& version_str) { std::vector<uint32_t> parsed;
diff --git a/base/vlog.cc b/base/vlog.cc index bf80820..fbe1897 100644 --- a/base/vlog.cc +++ b/base/vlog.cc
@@ -78,7 +78,7 @@ } } -VlogInfo::~VlogInfo() {} +VlogInfo::~VlogInfo() = default; namespace {
diff --git a/build/android/gyp/package_resources.py b/build/android/gyp/package_resources.py deleted file mode 100755 index 2be10bb..0000000 --- a/build/android/gyp/package_resources.py +++ /dev/null
@@ -1,449 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -# pylint: disable=C0301 -"""Package resources into an apk. - -See https://android.googlesource.com/platform/tools/base/+/master/legacy/ant-tasks/src/main/java/com/android/ant/AaptExecTask.java -and -https://android.googlesource.com/platform/sdk/+/master/files/ant/build.xml -""" -# pylint: enable=C0301 - -import multiprocessing.pool -import optparse -import os -import re -import shutil -import subprocess -import sys -import zipfile - -from util import build_utils - - -# A variation of this lists also exists in: -# //base/android/java/src/org/chromium/base/LocaleUtils.java -_CHROME_TO_ANDROID_LOCALE_MAP = { - 'en-GB': 'en-rGB', - 'en-US': 'en-rUS', - 'es-419': 'es-rUS', - 'fil': 'tl', - 'he': 'iw', - 'id': 'in', - 'pt-PT': 'pt-rPT', - 'pt-BR': 'pt-rBR', - 'yi': 'ji', - 'zh-CN': 'zh-rCN', - 'zh-TW': 'zh-rTW', -} - -# List is generated from the chrome_apk.apk_intermediates.ap_ via: -# unzip -l $FILE_AP_ | cut -c31- | grep res/draw | cut -d'/' -f 2 | sort \ -# | uniq | grep -- -tvdpi- | cut -c10- -# and then manually sorted. -# Note that we can't just do a cross-product of dimensions because the filenames -# become too big and aapt fails to create the files. -# This leaves all default drawables (mdpi) in the main apk. Android gets upset -# though if any drawables are missing from the default drawables/ directory. -DENSITY_SPLITS = { - 'hdpi': ( - 'hdpi-v4', # Order matters for output file names. - 'ldrtl-hdpi-v4', - 'sw600dp-hdpi-v13', - 'ldrtl-hdpi-v17', - 'ldrtl-sw600dp-hdpi-v17', - 'hdpi-v21', - ), - 'xhdpi': ( - 'xhdpi-v4', - 'ldrtl-xhdpi-v4', - 'sw600dp-xhdpi-v13', - 'ldrtl-xhdpi-v17', - 'ldrtl-sw600dp-xhdpi-v17', - 'xhdpi-v21', - ), - 'xxhdpi': ( - 'xxhdpi-v4', - 'ldrtl-xxhdpi-v4', - 'sw600dp-xxhdpi-v13', - 'ldrtl-xxhdpi-v17', - 'ldrtl-sw600dp-xxhdpi-v17', - 'xxhdpi-v21', - ), - 'xxxhdpi': ( - 'xxxhdpi-v4', - 'ldrtl-xxxhdpi-v4', - 'sw600dp-xxxhdpi-v13', - 'ldrtl-xxxhdpi-v17', - 'ldrtl-sw600dp-xxxhdpi-v17', - 'xxxhdpi-v21', - ), - 'tvdpi': ( - 'tvdpi-v4', - 'sw600dp-tvdpi-v13', - 'ldrtl-sw600dp-tvdpi-v17', - ), -} - - -_PNG_TO_WEBP_ARGS = [ - '-mt', '-quiet', '-m', '6', '-q', '100', '-lossless', '-o'] - - -def _ParseArgs(args): - """Parses command line options. - - Returns: - An options object as from optparse.OptionsParser.parse_args() - """ - parser = optparse.OptionParser() - build_utils.AddDepfileOption(parser) - parser.add_option('--android-sdk-jar', - help='path to the Android SDK jar.') - parser.add_option('--aapt-path', - help='path to the Android aapt tool') - parser.add_option('--debuggable', - action='store_true', - help='Whether to add android:debuggable="true"') - parser.add_option('--android-manifest', help='AndroidManifest.xml path') - parser.add_option('--version-code', help='Version code for apk.') - parser.add_option('--version-name', help='Version name for apk.') - parser.add_option( - '--shared-resources', - action='store_true', - help='Make a resource package that can be loaded by a different' - 'application at runtime to access the package\'s resources.') - parser.add_option( - '--app-as-shared-lib', - action='store_true', - help='Make a resource package that can be loaded as shared library') - parser.add_option('--resource-zips', - default='[]', - help='zip files containing resources to be packaged') - parser.add_option('--asset-dir', - help='directories containing assets to be packaged') - parser.add_option('--no-compress', help='disables compression for the ' - 'given comma separated list of extensions') - parser.add_option( - '--create-density-splits', - action='store_true', - help='Enables density splits') - parser.add_option('--language-splits', - default='[]', - help='GN list of languages to create splits for') - parser.add_option('--locale-whitelist', - default='[]', - help='GN list of languages to include. All other language ' - 'configs will be stripped out. List may include ' - 'a combination of Android locales or Chrome locales.') - parser.add_option('--apk-path', - help='Path to output (partial) apk.') - parser.add_option('--exclude-xxxhdpi', action='store_true', - help='Do not include xxxhdpi drawables.') - parser.add_option('--xxxhdpi-whitelist', - default='[]', - help='GN list of globs that say which xxxhdpi images to ' - 'include even when --exclude-xxxhdpi is set.') - parser.add_option('--png-to-webp', action='store_true', - help='Convert png files to webp format.') - parser.add_option('--webp-binary', default='', - help='Path to the cwebp binary.') - parser.add_option('--support-zh-hk', action='store_true', - help='Tell aapt to support zh-rHK.') - - options, positional_args = parser.parse_args(args) - - if positional_args: - parser.error('No positional arguments should be given.') - - # Check that required options have been provided. - required_options = ('android_sdk_jar', 'aapt_path', 'android_manifest', - 'version_code', 'version_name', 'apk_path') - - build_utils.CheckOptions(options, parser, required=required_options) - - options.resource_zips = build_utils.ParseGnList(options.resource_zips) - options.language_splits = build_utils.ParseGnList(options.language_splits) - options.locale_whitelist = build_utils.ParseGnList(options.locale_whitelist) - options.xxxhdpi_whitelist = build_utils.ParseGnList(options.xxxhdpi_whitelist) - return options - - -def _ToAaptLocales(locale_whitelist, support_zh_hk): - """Converts the list of Chrome locales to aapt config locales.""" - ret = set() - for locale in locale_whitelist: - locale = _CHROME_TO_ANDROID_LOCALE_MAP.get(locale, locale) - if locale is None or ('-' in locale and '-r' not in locale): - raise Exception('_CHROME_TO_ANDROID_LOCALE_MAP needs updating.' - ' Found: %s' % locale) - ret.add(locale) - # Always keep non-regional fall-backs. - language = locale.split('-')[0] - ret.add(language) - - # We don't actually support zh-HK in Chrome on Android, but we mimic the - # native side behavior where we use zh-TW resources when the locale is set to - # zh-HK. See https://crbug.com/780847. - if support_zh_hk: - assert not any('HK' in l for l in locale_whitelist), ( - 'Remove special logic if zh-HK is now supported (crbug.com/780847).') - ret.add('zh-rHK') - return sorted(ret) - - -def MoveImagesToNonMdpiFolders(res_root): - """Move images from drawable-*-mdpi-* folders to drawable-* folders. - - Why? http://crbug.com/289843 - """ - for src_dir_name in os.listdir(res_root): - src_components = src_dir_name.split('-') - if src_components[0] != 'drawable' or 'mdpi' not in src_components: - continue - src_dir = os.path.join(res_root, src_dir_name) - if not os.path.isdir(src_dir): - continue - dst_components = [c for c in src_components if c != 'mdpi'] - assert dst_components != src_components - dst_dir_name = '-'.join(dst_components) - dst_dir = os.path.join(res_root, dst_dir_name) - build_utils.MakeDirectory(dst_dir) - for src_file_name in os.listdir(src_dir): - if not src_file_name.endswith('.png'): - continue - src_file = os.path.join(src_dir, src_file_name) - dst_file = os.path.join(dst_dir, src_file_name) - assert not os.path.lexists(dst_file) - shutil.move(src_file, dst_file) - - -def PackageArgsForExtractedZip(d): - """Returns the aapt args for an extracted resources zip. - - A resources zip either contains the resources for a single target or for - multiple targets. If it is multiple targets merged into one, the actual - resource directories will be contained in the subdirectories 0, 1, 2, ... - """ - subdirs = [os.path.join(d, s) for s in os.listdir(d)] - subdirs = [s for s in subdirs if os.path.isdir(s)] - is_multi = any(os.path.basename(s).isdigit() for s in subdirs) - if is_multi: - res_dirs = sorted(subdirs, key=lambda p : int(os.path.basename(p))) - else: - res_dirs = [d] - package_command = [] - for d in res_dirs: - MoveImagesToNonMdpiFolders(d) - package_command += ['-S', d] - return package_command - - -def _GenerateDensitySplitPaths(apk_path): - for density, config in DENSITY_SPLITS.iteritems(): - src_path = '%s_%s' % (apk_path, '_'.join(config)) - dst_path = '%s_%s' % (apk_path, density) - yield src_path, dst_path - - -def _GenerateLanguageSplitOutputPaths(apk_path, languages): - for lang in languages: - yield '%s_%s' % (apk_path, lang) - - -def RenameDensitySplits(apk_path): - """Renames all density splits to have shorter / predictable names.""" - for src_path, dst_path in _GenerateDensitySplitPaths(apk_path): - shutil.move(src_path, dst_path) - - -def CheckForMissedConfigs(apk_path, check_density, languages): - """Raises an exception if apk_path contains any unexpected configs.""" - triggers = [] - if check_density: - triggers.extend(re.compile('-%s' % density) for density in DENSITY_SPLITS) - if languages: - triggers.extend(re.compile(r'-%s\b' % lang) for lang in languages) - with zipfile.ZipFile(apk_path) as main_apk_zip: - for name in main_apk_zip.namelist(): - for trigger in triggers: - if trigger.search(name) and not 'mipmap-' in name: - raise Exception(('Found config in main apk that should have been ' + - 'put into a split: %s\nYou need to update ' + - 'package_resources.py to include this new ' + - 'config (trigger=%s)') % (name, trigger.pattern)) - - -def _ConstructMostAaptArgs(options): - package_command = [ - options.aapt_path, - 'package', - '--version-code', options.version_code, - '--version-name', options.version_name, - '-M', options.android_manifest, - '--no-crunch', - '-f', - '--auto-add-overlay', - '--no-version-vectors', - '-I', options.android_sdk_jar, - '-F', options.apk_path, - '--ignore-assets', build_utils.AAPT_IGNORE_PATTERN, - ] - - if options.no_compress: - for ext in options.no_compress.split(','): - package_command += ['-0', ext] - - if options.shared_resources: - package_command.append('--shared-lib') - - if options.app_as_shared_lib: - package_command.append('--app-as-shared-lib') - - if options.asset_dir and os.path.exists(options.asset_dir): - package_command += ['-A', options.asset_dir] - - if options.create_density_splits: - for config in DENSITY_SPLITS.itervalues(): - package_command.extend(('--split', ','.join(config))) - - if options.language_splits: - for lang in options.language_splits: - package_command.extend(('--split', lang)) - - if options.debuggable: - package_command += ['--debug-mode'] - - if options.locale_whitelist: - aapt_locales = _ToAaptLocales( - options.locale_whitelist, options.support_zh_hk) - package_command += ['-c', ','.join(aapt_locales)] - - return package_command - - -def _ResourceNameFromPath(path): - return os.path.splitext(os.path.basename(path))[0] - - -def _CreateExtractPredicate(dep_zips, exclude_xxxhdpi, xxxhdpi_whitelist): - if not exclude_xxxhdpi: - # Do not extract dotfiles (e.g. ".gitkeep"). aapt ignores them anyways. - return lambda path: os.path.basename(path)[0] != '.' - - # Returns False only for xxxhdpi non-mipmap, non-whitelisted drawables. - naive_predicate = lambda path: ( - not re.search(r'[/-]xxxhdpi[/-]', path) or - re.search(r'[/-]mipmap[/-]', path) or - build_utils.MatchesGlob(path, xxxhdpi_whitelist)) - - # Build a set of all non-xxxhdpi drawables to ensure that we never exclude any - # xxxhdpi drawable that does not exist in other densities. - non_xxxhdpi_drawables = set() - for resource_zip_path in dep_zips: - with zipfile.ZipFile(resource_zip_path) as zip_file: - for path in zip_file.namelist(): - if re.search(r'[/-]drawable[/-]', path) and naive_predicate(path): - non_xxxhdpi_drawables.add(_ResourceNameFromPath(path)) - - return lambda path: (naive_predicate(path) or - _ResourceNameFromPath(path) not in non_xxxhdpi_drawables) - - -def _ConvertToWebP(webp_binary, png_files): - pool = multiprocessing.pool.ThreadPool(10) - def convert_image(png_path): - root = os.path.splitext(png_path)[0] - webp_path = root + '.webp' - args = [webp_binary, png_path] + _PNG_TO_WEBP_ARGS + [webp_path] - subprocess.check_call(args) - os.remove(png_path) - # Android requires pngs for 9-patch images. - pool.map(convert_image, [f for f in png_files if not f.endswith('.9.png')]) - pool.close() - pool.join() - - -def _OnStaleMd5(package_command, options): - with build_utils.TempDir() as temp_dir: - if options.resource_zips: - dep_zips = options.resource_zips - extract_predicate = _CreateExtractPredicate( - dep_zips, options.exclude_xxxhdpi, options.xxxhdpi_whitelist) - png_paths = [] - package_subdirs = [] - for z in dep_zips: - subdir = os.path.join(temp_dir, os.path.basename(z)) - if os.path.exists(subdir): - raise Exception('Resource zip name conflict: ' + os.path.basename(z)) - extracted_files = build_utils.ExtractAll( - z, path=subdir, predicate=extract_predicate) - if extracted_files: - package_subdirs.append(subdir) - png_paths.extend(f for f in extracted_files if f.endswith('.png')) - if png_paths and options.png_to_webp: - _ConvertToWebP(options.webp_binary, png_paths) - for subdir in package_subdirs: - package_command += PackageArgsForExtractedZip(subdir) - - build_utils.CheckOutput( - package_command, print_stdout=False, print_stderr=False) - - if options.create_density_splits or options.language_splits: - CheckForMissedConfigs(options.apk_path, options.create_density_splits, - options.language_splits) - - if options.create_density_splits: - RenameDensitySplits(options.apk_path) - - -def main(args): - args = build_utils.ExpandFileArgs(args) - options = _ParseArgs(args) - - package_command = _ConstructMostAaptArgs(options) - - output_paths = [options.apk_path] - - if options.create_density_splits: - for _, dst_path in _GenerateDensitySplitPaths(options.apk_path): - output_paths.append(dst_path) - output_paths.extend( - _GenerateLanguageSplitOutputPaths(options.apk_path, - options.language_splits)) - - input_paths = [options.android_manifest] + options.resource_zips - - input_strings = [options.exclude_xxxhdpi] + options.xxxhdpi_whitelist - input_strings.extend(package_command) - if options.png_to_webp: - # This is necessary to ensure conversion if the option is toggled. - input_strings.append('png_to_webp') - if options.support_zh_hk: - input_strings.append('support_zh_hk') - - # The md5_check.py doesn't count file path in md5 intentionally, - # in order to repackage resources when assets' name changed, we need - # to put assets into input_strings, as we know the assets path isn't - # changed among each build if there is no asset change. - if options.asset_dir and os.path.exists(options.asset_dir): - asset_paths = [] - for root, _, filenames in os.walk(options.asset_dir): - asset_paths.extend(os.path.join(root, f) for f in filenames) - input_paths.extend(asset_paths) - input_strings.extend(sorted(asset_paths)) - - build_utils.CallAndWriteDepfileIfStale( - lambda: _OnStaleMd5(package_command, options), - options, - input_paths=input_paths, - input_strings=input_strings, - output_paths=output_paths) - - -if __name__ == '__main__': - main(sys.argv[1:])
diff --git a/build/android/gyp/process_resources.py b/build/android/gyp/process_resources.py index 0df462e9..3baacdc 100755 --- a/build/android/gyp/process_resources.py +++ b/build/android/gyp/process_resources.py
@@ -12,10 +12,12 @@ import codecs import collections +import multiprocessing.pool import optparse import os import re import shutil +import subprocess import sys import xml.etree.ElementTree import zipfile @@ -35,6 +37,73 @@ ('java_type', 'resource_type', 'name', 'value')) +# A variation of this lists also exists in: +# //base/android/java/src/org/chromium/base/LocaleUtils.java +_CHROME_TO_ANDROID_LOCALE_MAP = { + 'en-GB': 'en-rGB', + 'en-US': 'en-rUS', + 'es-419': 'es-rUS', + 'fil': 'tl', + 'he': 'iw', + 'id': 'in', + 'pt-PT': 'pt-rPT', + 'pt-BR': 'pt-rBR', + 'yi': 'ji', + 'zh-CN': 'zh-rCN', + 'zh-TW': 'zh-rTW', +} + +# List is generated from the chrome_apk.apk_intermediates.ap_ via: +# unzip -l $FILE_AP_ | cut -c31- | grep res/draw | cut -d'/' -f 2 | sort \ +# | uniq | grep -- -tvdpi- | cut -c10- +# and then manually sorted. +# Note that we can't just do a cross-product of dimensions because the filenames +# become too big and aapt fails to create the files. +# This leaves all default drawables (mdpi) in the main apk. Android gets upset +# though if any drawables are missing from the default drawables/ directory. +_DENSITY_SPLITS = { + 'hdpi': ( + 'hdpi-v4', # Order matters for output file names. + 'ldrtl-hdpi-v4', + 'sw600dp-hdpi-v13', + 'ldrtl-hdpi-v17', + 'ldrtl-sw600dp-hdpi-v17', + 'hdpi-v21', + ), + 'xhdpi': ( + 'xhdpi-v4', + 'ldrtl-xhdpi-v4', + 'sw600dp-xhdpi-v13', + 'ldrtl-xhdpi-v17', + 'ldrtl-sw600dp-xhdpi-v17', + 'xhdpi-v21', + ), + 'xxhdpi': ( + 'xxhdpi-v4', + 'ldrtl-xxhdpi-v4', + 'sw600dp-xxhdpi-v13', + 'ldrtl-xxhdpi-v17', + 'ldrtl-sw600dp-xxhdpi-v17', + 'xxhdpi-v21', + ), + 'xxxhdpi': ( + 'xxxhdpi-v4', + 'ldrtl-xxxhdpi-v4', + 'sw600dp-xxxhdpi-v13', + 'ldrtl-xxxhdpi-v17', + 'ldrtl-sw600dp-xxxhdpi-v17', + 'xxxhdpi-v21', + ), + 'tvdpi': ( + 'tvdpi-v4', + 'sw600dp-tvdpi-v13', + 'ldrtl-sw600dp-tvdpi-v17', + ), +} + + + + def _ParseArgs(args): """Parses command line options. @@ -63,6 +132,7 @@ help='Make a resource package that can be loaded as shared library.') parser.add_option('--resource-dirs', + default='[]', help='Directories containing resources of this target.') parser.add_option('--dependencies-res-zips', help='Resources from dependents.') @@ -97,21 +167,44 @@ help='For each additional package, the R.txt file should contain a ' 'list of resources to be included in the R.java file in the format ' 'generated by aapt') - parser.add_option( - '--include-all-resources', - action='store_true', - help='Include every resource ID in every generated R.java file ' - '(ignoring R.txt).') - parser.add_option( - '--all-resources-zip-out', - help='Path for output of all resources. This includes resources in ' - 'dependencies.') parser.add_option('--support-zh-hk', action='store_true', help='Use zh-rTW resources for zh-rHK.') parser.add_option('--stamp', help='File to touch on success') + parser.add_option('--debuggable', + action='store_true', + help='Whether to add android:debuggable="true"') + parser.add_option('--version-code', help='Version code for apk.') + parser.add_option('--version-name', help='Version name for apk.') + parser.add_option('--no-compress', help='disables compression for the ' + 'given comma separated list of extensions') + parser.add_option( + '--create-density-splits', + action='store_true', + help='Enables density splits') + parser.add_option('--language-splits', + default='[]', + help='GN list of languages to create splits for') + parser.add_option('--locale-whitelist', + default='[]', + help='GN list of languages to include. All other language ' + 'configs will be stripped out. List may include ' + 'a combination of Android locales or Chrome locales.') + parser.add_option('--apk-path', + help='Path to output (partial) apk.') + parser.add_option('--exclude-xxxhdpi', action='store_true', + help='Do not include xxxhdpi drawables.') + parser.add_option('--xxxhdpi-whitelist', + default='[]', + help='GN list of globs that say which xxxhdpi images to ' + 'include even when --exclude-xxxhdpi is set.') + parser.add_option('--png-to-webp', action='store_true', + help='Convert png files to webp format.') + parser.add_option('--webp-binary', default='', + help='Path to the cwebp binary.') + options, positional_args = parser.parse_args(args) if positional_args: @@ -123,7 +216,6 @@ 'aapt_path', 'android_manifest', 'dependencies_res_zips', - 'resource_dirs', ) build_utils.CheckOptions(options, parser, required=required_options) @@ -131,6 +223,10 @@ options.dependencies_res_zips = ( build_utils.ParseGnList(options.dependencies_res_zips)) + options.language_splits = build_utils.ParseGnList(options.language_splits) + options.locale_whitelist = build_utils.ParseGnList(options.locale_whitelist) + options.xxxhdpi_whitelist = build_utils.ParseGnList(options.xxxhdpi_whitelist) + # Don't use [] as default value since some script explicitly pass "". if options.extra_res_packages: options.extra_res_packages = ( @@ -147,7 +243,7 @@ return options -def CreateRJavaFiles(srcjar_dir, main_r_txt_file, packages, r_txt_files, +def _CreateRJavaFiles(srcjar_dir, main_r_txt_file, packages, r_txt_files, shared_resources, non_constant_id): assert len(packages) == len(r_txt_files), 'Need one R.txt file per package' @@ -277,7 +373,7 @@ final=final) -def CrunchDirectory(aapt, input_dir, output_dir): +def _CrunchDirectory(aapt, input_dir, output_dir): """Crunches the images in input_dir and its subdirectories into output_dir. If an image is already optimized, crunching often increases image size. In @@ -288,8 +384,8 @@ '-C', output_dir, '-S', input_dir, '--ignore-assets', build_utils.AAPT_IGNORE_PATTERN] - build_utils.CheckOutput(aapt_cmd, stderr_filter=FilterCrunchStderr, - fail_func=DidCrunchFail) + build_utils.CheckOutput(aapt_cmd, stderr_filter=_FilterCrunchStderr, + fail_func=_DidCrunchFail) # Check for images whose size increased during crunching and replace them # with their originals (except for 9-patches, which must be crunched). @@ -307,7 +403,7 @@ shutil.copyfile(original, crunched) -def FilterCrunchStderr(stderr): +def _FilterCrunchStderr(stderr): """Filters out lines from aapt crunch's stderr that can safely be ignored.""" filtered_lines = [] for line in stderr.splitlines(True): @@ -320,7 +416,7 @@ return ''.join(filtered_lines) -def DidCrunchFail(returncode, stderr): +def _DidCrunchFail(returncode, stderr): """Determines whether aapt crunch failed from its return code and output. Because aapt's return code cannot be trusted, any output to stderr is @@ -329,7 +425,7 @@ return returncode != 0 or stderr -def ZipResources(resource_dirs, zip_path): +def _ZipResources(resource_dirs, zip_path): # Python zipfile does not provide a way to replace a file (it just writes # another file with the same name). So, first collect all the files to put # in the zip (with proper overriding), and then zip them. @@ -346,103 +442,325 @@ build_utils.DoZip(files_to_zip.iteritems(), zip_path) -def CombineZips(zip_files, output_path, support_zh_hk): - # When packaging resources, if the top-level directories in the zip file are - # of the form 0, 1, ..., then each subdirectory will be passed to aapt as a - # resources directory. While some resources just clobber others (image files, - # etc), other resources (particularly .xml files) need to be more - # intelligently merged. That merging is left up to aapt. - def path_transform(name, src_zip): - return '%d/%s' % (zip_files.index(src_zip), name) - - # We don't currently support zh-HK on Chrome for Android, but on the - # native side we resolve zh-HK resources to zh-TW. This logic is - # duplicated here by just copying the zh-TW res folders to zh-HK. - # See https://crbug.com/780847. - with build_utils.TempDir() as temp_dir: - if support_zh_hk: - zip_files = _DuplicateZhResources(zip_files, temp_dir) - build_utils.MergeZips(output_path, zip_files, path_transform=path_transform) - - -def _DuplicateZhResources(zip_files, temp_dir): - new_zip_files = [] - for i, zip_path in enumerate(zip_files): - # We use zh-TW resources for zh-HK (if we have zh-TW resources). If no - # zh-TW resources exists (ex. api specific resources), then just use the - # original zip. - if not _ZipContains(zip_path, r'zh-r(HK|TW)'): - new_zip_files.append(zip_path) - continue - - resource_dir = os.path.join(temp_dir, str(i)) - new_zip_path = os.path.join(temp_dir, str(i) + '.zip') - - # Exclude existing zh-HK resources so that we don't mess up any resource - # IDs. This can happen if the type IDs in the existing resources don't - # align with ours (since they've already been generated at this point). - build_utils.ExtractAll( - zip_path, path=resource_dir, predicate=lambda x: not 'zh-rHK' in x) +def _DuplicateZhResources(resource_dirs): + for resource_dir in resource_dirs: + # We use zh-TW resources for zh-HK (if we have zh-TW resources). for path in build_utils.IterFiles(resource_dir): if 'zh-rTW' in path: hk_path = path.replace('zh-rTW', 'zh-rHK') - build_utils.Touch(hk_path) + build_utils.MakeDirectory(os.path.dirname(hk_path)) shutil.copyfile(path, hk_path) - build_utils.ZipDir(new_zip_path, resource_dir) - new_zip_files.append(new_zip_path) - return new_zip_files - - -def _ZipContains(path, pattern): - with zipfile.ZipFile(path, 'r') as z: - return any(re.search(pattern, f) for f in z.namelist()) - - def _ExtractPackageFromManifest(manifest_path): doc = xml.etree.ElementTree.parse(manifest_path) return doc.getroot().get('package') +def _ToAaptLocales(locale_whitelist, support_zh_hk): + """Converts the list of Chrome locales to aapt config locales.""" + ret = set() + for locale in locale_whitelist: + locale = _CHROME_TO_ANDROID_LOCALE_MAP.get(locale, locale) + if locale is None or ('-' in locale and '-r' not in locale): + raise Exception('_CHROME_TO_ANDROID_LOCALE_MAP needs updating.' + ' Found: %s' % locale) + ret.add(locale) + # Always keep non-regional fall-backs. + language = locale.split('-')[0] + ret.add(language) + + # We don't actually support zh-HK in Chrome on Android, but we mimic the + # native side behavior where we use zh-TW resources when the locale is set to + # zh-HK. See https://crbug.com/780847. + if support_zh_hk: + assert not any('HK' in l for l in locale_whitelist), ( + 'Remove special logic if zh-HK is now supported (crbug.com/780847).') + ret.add('zh-rHK') + return sorted(ret) + + +def _MoveImagesToNonMdpiFolders(res_root): + """Move images from drawable-*-mdpi-* folders to drawable-* folders. + + Why? http://crbug.com/289843 + """ + for src_dir_name in os.listdir(res_root): + src_components = src_dir_name.split('-') + if src_components[0] != 'drawable' or 'mdpi' not in src_components: + continue + src_dir = os.path.join(res_root, src_dir_name) + if not os.path.isdir(src_dir): + continue + dst_components = [c for c in src_components if c != 'mdpi'] + assert dst_components != src_components + dst_dir_name = '-'.join(dst_components) + dst_dir = os.path.join(res_root, dst_dir_name) + build_utils.MakeDirectory(dst_dir) + for src_file_name in os.listdir(src_dir): + if not src_file_name.endswith('.png'): + continue + src_file = os.path.join(src_dir, src_file_name) + dst_file = os.path.join(dst_dir, src_file_name) + assert not os.path.lexists(dst_file) + shutil.move(src_file, dst_file) + + +def _GenerateDensitySplitPaths(apk_path): + for density, config in _DENSITY_SPLITS.iteritems(): + src_path = '%s_%s' % (apk_path, '_'.join(config)) + dst_path = '%s_%s' % (apk_path, density) + yield src_path, dst_path + + +def _GenerateLanguageSplitOutputPaths(apk_path, languages): + for lang in languages: + yield '%s_%s' % (apk_path, lang) + + +def _RenameDensitySplits(apk_path): + """Renames all density splits to have shorter / predictable names.""" + for src_path, dst_path in _GenerateDensitySplitPaths(apk_path): + shutil.move(src_path, dst_path) + + +def _CheckForMissedConfigs(apk_path, check_density, languages): + """Raises an exception if apk_path contains any unexpected configs.""" + triggers = [] + if check_density: + triggers.extend(re.compile('-%s' % density) for density in _DENSITY_SPLITS) + if languages: + triggers.extend(re.compile(r'-%s\b' % lang) for lang in languages) + with zipfile.ZipFile(apk_path) as main_apk_zip: + for name in main_apk_zip.namelist(): + for trigger in triggers: + if trigger.search(name) and not 'mipmap-' in name: + raise Exception(('Found config in main apk that should have been ' + + 'put into a split: %s\nYou need to update ' + + 'package_resources.py to include this new ' + + 'config (trigger=%s)') % (name, trigger.pattern)) + + +def _CreatePackageApkArgs(options): + package_command = [ + '--version-code', options.version_code, + '--version-name', options.version_name, + '-f', + '-F', options.apk_path, + ] + + if options.proguard_file: + package_command += ['-G', options.proguard_file] + if options.proguard_file_main_dex: + package_command += ['-D', options.proguard_file_main_dex] + + if options.no_compress: + for ext in options.no_compress.split(','): + package_command += ['-0', ext] + + if options.shared_resources: + package_command.append('--shared-lib') + if options.app_as_shared_lib: + package_command.append('--app-as-shared-lib') + + if options.create_density_splits: + for config in _DENSITY_SPLITS.itervalues(): + package_command.extend(('--split', ','.join(config))) + + if options.language_splits: + for lang in options.language_splits: + package_command.extend(('--split', lang)) + + if options.debuggable: + package_command += ['--debug-mode'] + + if options.locale_whitelist: + aapt_locales = _ToAaptLocales( + options.locale_whitelist, options.support_zh_hk) + package_command += ['-c', ','.join(aapt_locales)] + + return package_command + + +def _ResourceNameFromPath(path): + return os.path.splitext(os.path.basename(path))[0] + + +def _CreateKeepPredicate(resource_dirs, exclude_xxxhdpi, xxxhdpi_whitelist): + if not exclude_xxxhdpi: + # Do not extract dotfiles (e.g. ".gitkeep"). aapt ignores them anyways. + return lambda path: os.path.basename(path)[0] != '.' + + # Returns False only for xxxhdpi non-mipmap, non-whitelisted drawables. + naive_predicate = lambda path: ( + not re.search(r'[/-]xxxhdpi[/-]', path) or + re.search(r'[/-]mipmap[/-]', path) or + build_utils.MatchesGlob(path, xxxhdpi_whitelist)) + + # Build a set of all non-xxxhdpi drawables to ensure that we never exclude any + # xxxhdpi drawable that does not exist in other densities. + non_xxxhdpi_drawables = set() + for resource_dir in resource_dirs: + for path in build_utils.IterFiles(resource_dir): + if re.search(r'[/-]drawable[/-]', path) and naive_predicate(path): + non_xxxhdpi_drawables.add(_ResourceNameFromPath(path)) + + return lambda path: (naive_predicate(path) or + _ResourceNameFromPath(path) not in non_xxxhdpi_drawables) + + +def _ConvertToWebP(webp_binary, png_files): + pool = multiprocessing.pool.ThreadPool(10) + def convert_image(png_path): + root = os.path.splitext(png_path)[0] + webp_path = root + '.webp' + args = [webp_binary, png_path, '-mt', '-quiet', '-m', '6', '-q', '100', + '-lossless', '-o', webp_path] + subprocess.check_call(args) + os.remove(png_path) + # Android requires pngs for 9-patch images. + pool.map(convert_image, [f for f in png_files if not f.endswith('.9.png')]) + pool.close() + pool.join() + + +def _PackageApk(options, package_command, dep_subdirs): + _DuplicateZhResources(dep_subdirs) + + package_command += _CreatePackageApkArgs(options) + + keep_predicate = _CreateKeepPredicate( + dep_subdirs, options.exclude_xxxhdpi, options.xxxhdpi_whitelist) + png_paths = [] + for directory in dep_subdirs: + for f in build_utils.IterFiles(directory): + if not keep_predicate(f): + os.remove(f) + elif f.endswith('.png'): + png_paths.append(f) + if png_paths and options.png_to_webp: + _ConvertToWebP(options.webp_binary, png_paths) + for directory in dep_subdirs: + _MoveImagesToNonMdpiFolders(directory) + + # Creates a .zip with AndroidManifest.xml, resources.arsc, res/* + # Also creates R.txt + build_utils.CheckOutput( + package_command, print_stdout=False, print_stderr=False) + + if options.create_density_splits or options.language_splits: + _CheckForMissedConfigs(options.apk_path, options.create_density_splits, + options.language_splits) + + if options.create_density_splits: + _RenameDensitySplits(options.apk_path) + + +def _PackageLibrary(options, package_command, temp_dir): + v14_dir = os.path.join(temp_dir, 'v14') + build_utils.MakeDirectory(v14_dir) + + input_resource_dirs = options.resource_dirs + + for d in input_resource_dirs: + package_command += ['-S', d] + + if not options.v14_skip: + for resource_dir in input_resource_dirs: + generate_v14_compatible_resources.GenerateV14Resources( + resource_dir, + v14_dir) + + # This is the list of directories with resources to put in the final .zip + # file. The order of these is important so that crunched/v14 resources + # override the normal ones. + zip_resource_dirs = input_resource_dirs + [v14_dir] + + base_crunch_dir = os.path.join(temp_dir, 'crunch') + # Crunch image resources. This shrinks png files and is necessary for + # 9-patch images to display correctly. 'aapt crunch' accepts only a single + # directory at a time and deletes everything in the output directory. + for idx, input_dir in enumerate(input_resource_dirs): + crunch_dir = os.path.join(base_crunch_dir, str(idx)) + build_utils.MakeDirectory(crunch_dir) + zip_resource_dirs.append(crunch_dir) + _CrunchDirectory(options.aapt_path, input_dir, crunch_dir) + + if options.resource_zip_out: + _ZipResources(zip_resource_dirs, options.resource_zip_out) + + # Only creates an R.txt + build_utils.CheckOutput( + package_command, print_stdout=False, print_stderr=False) + + +def _CreateRTxtAndSrcJar(options, r_txt_path, srcjar_dir): + # When an empty res/ directory is passed, aapt does not write an R.txt. + if not os.path.exists(r_txt_path): + build_utils.Touch(r_txt_path) + + if options.r_text_in: + r_txt_path = options.r_text_in + + packages = list(options.extra_res_packages) + r_txt_files = list(options.extra_r_text_files) + + cur_package = options.custom_package + if not options.custom_package: + cur_package = _ExtractPackageFromManifest(options.android_manifest) + + # Don't create a .java file for the current resource target when: + # - no package name was provided (either by manifest or build rules), + # - there was already a dependent android_resources() with the same + # package (occurs mostly when an apk target and resources target share + # an AndroidManifest.xml) + if cur_package != 'org.dummy' and cur_package not in packages: + packages.append(cur_package) + r_txt_files.append(r_txt_path) + + if packages: + shared_resources = options.shared_resources or options.app_as_shared_lib + _CreateRJavaFiles(srcjar_dir, r_txt_path, packages, r_txt_files, + shared_resources, options.non_constant_id) + + if options.srcjar_out: + build_utils.ZipDir(options.srcjar_out, srcjar_dir) + + if options.r_text_out: + shutil.copyfile(r_txt_path, options.r_text_out) + + +def _ExtractDeps(dep_zips, deps_dir): + dep_subdirs = [] + for z in dep_zips: + subdir = os.path.join(deps_dir, os.path.basename(z)) + if os.path.exists(subdir): + raise Exception('Resource zip name conflict: ' + os.path.basename(z)) + build_utils.ExtractAll(z, path=subdir) + dep_subdirs.append(subdir) + return dep_subdirs + + def _OnStaleMd5(options): - aapt = options.aapt_path with build_utils.TempDir() as temp_dir: deps_dir = os.path.join(temp_dir, 'deps') build_utils.MakeDirectory(deps_dir) - v14_dir = os.path.join(temp_dir, 'v14') - build_utils.MakeDirectory(v14_dir) - gen_dir = os.path.join(temp_dir, 'gen') build_utils.MakeDirectory(gen_dir) r_txt_path = os.path.join(gen_dir, 'R.txt') srcjar_dir = os.path.join(temp_dir, 'java') - input_resource_dirs = options.resource_dirs - - if not options.v14_skip: - for resource_dir in input_resource_dirs: - generate_v14_compatible_resources.GenerateV14Resources( - resource_dir, - v14_dir) - - dep_zips = options.dependencies_res_zips - dep_subdirs = [] - for z in dep_zips: - subdir = os.path.join(deps_dir, os.path.basename(z)) - if os.path.exists(subdir): - raise Exception('Resource zip name conflict: ' + os.path.basename(z)) - build_utils.ExtractAll(z, path=subdir) - dep_subdirs.append(subdir) + dep_subdirs = _ExtractDeps(options.dependencies_res_zips, deps_dir) # Generate R.java. This R.java contains non-final constants and is used only # while compiling the library jar (e.g. chromium_content.jar). When building # an apk, a new R.java file with the correct resource -> ID mappings will be # generated by merging the resources from all libraries and the main apk # project. - package_command = [aapt, + package_command = [options.aapt_path, 'package', '-m', '-M', options.android_manifest, + '--no-crunch', '--auto-add-overlay', '--no-version-vectors', '-I', options.android_sdk_jar, @@ -450,31 +768,6 @@ '-J', gen_dir, # Required for R.txt generation. '--ignore-assets', build_utils.AAPT_IGNORE_PATTERN] - # aapt supports only the "--include-all-resources" mode, where each R.java - # file ends up with all symbols, rather than only those that it had at the - # time it was originally generated. This subtle difference makes no - # difference when compiling, but can lead to increased unused symbols in the - # resulting R.class files. - # TODO(agrieve): See if proguard makes this difference actually translate - # into a size difference. If not, we can delete all of our custom R.java - # template code above (and make include_all_resources the default). - if options.include_all_resources: - srcjar_dir = gen_dir - if options.extra_res_packages: - colon_separated = ':'.join(options.extra_res_packages) - package_command += ['--extra-packages', colon_separated] - if options.non_constant_id: - package_command.append('--non-constant-id') - if options.custom_package: - package_command += ['--custom-package', options.custom_package] - if options.shared_resources: - package_command.append('--shared-lib') - if options.app_as_shared_lib: - package_command.append('--app-as-shared-lib') - - for d in input_resource_dirs: - package_command += ['-S', d] - # Adding all dependencies as sources is necessary for @type/foo references # to symbols within dependencies to resolve. However, it has the side-effect # that all Java symbols from dependencies are copied into the new R.java. @@ -484,74 +777,12 @@ for d in dep_subdirs: package_command += ['-S', d] - if options.proguard_file: - package_command += ['-G', options.proguard_file] - if options.proguard_file_main_dex: - package_command += ['-D', options.proguard_file_main_dex] - build_utils.CheckOutput(package_command, print_stderr=False) + if options.apk_path: + _PackageApk(options, package_command, dep_subdirs) + else: + _PackageLibrary(options, package_command, temp_dir) - # When an empty res/ directory is passed, aapt does not write an R.txt. - if not os.path.exists(r_txt_path): - build_utils.Touch(r_txt_path) - - if not options.include_all_resources: - # --include-all-resources can only be specified for generating final R - # classes for APK. It makes no sense for APK to have pre-generated R.txt - # though, because aapt-generated already lists all available resources. - if options.r_text_in: - r_txt_path = options.r_text_in - - packages = list(options.extra_res_packages) - r_txt_files = list(options.extra_r_text_files) - - cur_package = options.custom_package - if not options.custom_package: - cur_package = _ExtractPackageFromManifest(options.android_manifest) - - # Don't create a .java file for the current resource target when: - # - no package name was provided (either by manifest or build rules), - # - there was already a dependent android_resources() with the same - # package (occurs mostly when an apk target and resources target share - # an AndroidManifest.xml) - if cur_package != 'org.dummy' and cur_package not in packages: - packages.append(cur_package) - r_txt_files.append(r_txt_path) - - if packages: - shared_resources = options.shared_resources or options.app_as_shared_lib - CreateRJavaFiles(srcjar_dir, r_txt_path, packages, r_txt_files, - shared_resources, options.non_constant_id) - - # This is the list of directories with resources to put in the final .zip - # file. The order of these is important so that crunched/v14 resources - # override the normal ones. - zip_resource_dirs = input_resource_dirs + [v14_dir] - - base_crunch_dir = os.path.join(temp_dir, 'crunch') - - # Crunch image resources. This shrinks png files and is necessary for - # 9-patch images to display correctly. 'aapt crunch' accepts only a single - # directory at a time and deletes everything in the output directory. - for idx, input_dir in enumerate(input_resource_dirs): - crunch_dir = os.path.join(base_crunch_dir, str(idx)) - build_utils.MakeDirectory(crunch_dir) - zip_resource_dirs.append(crunch_dir) - CrunchDirectory(aapt, input_dir, crunch_dir) - - if options.resource_zip_out: - ZipResources(zip_resource_dirs, options.resource_zip_out) - - if options.all_resources_zip_out: - all_zips = [options.resource_zip_out] if options.resource_zip_out else [] - all_zips += dep_zips - CombineZips(all_zips, - options.all_resources_zip_out, options.support_zh_hk) - - if options.srcjar_out: - build_utils.ZipDir(options.srcjar_out, srcjar_dir) - - if options.r_text_out: - shutil.copyfile(r_txt_path, options.r_text_out) + _CreateRTxtAndSrcJar(options, r_txt_path, srcjar_dir) def main(args): @@ -561,8 +792,8 @@ # Order of these must match order specified in GN so that the correct one # appears first in the depfile. possible_output_paths = [ + options.apk_path, options.resource_zip_out, - options.all_resources_zip_out, options.r_text_out, options.srcjar_out, options.proguard_file, @@ -570,18 +801,30 @@ ] output_paths = [x for x in possible_output_paths if x] + if options.apk_path and options.create_density_splits: + for _, dst_path in _GenerateDensitySplitPaths(options.apk_path): + output_paths.append(dst_path) + if options.apk_path and options.language_splits: + output_paths.extend( + _GenerateLanguageSplitOutputPaths(options.apk_path, + options.language_splits)) + # List python deps in input_strings rather than input_paths since the contents # of them does not change what gets written to the depsfile. input_strings = options.extra_res_packages + [ options.app_as_shared_lib, options.custom_package, - options.include_all_resources, options.non_constant_id, options.shared_resources, options.v14_skip, + options.exclude_xxxhdpi, + options.xxxhdpi_whitelist, + str(options.png_to_webp), + str(options.support_zh_hk), ] - if options.support_zh_hk: - input_strings.append('support_zh_hk') + + if options.apk_path: + input_strings.extend(_CreatePackageApkArgs(options)) input_paths = [ options.aapt_path,
diff --git a/build/android/lint/suppressions.xml b/build/android/lint/suppressions.xml index f40067f..ef84286 100644 --- a/build/android/lint/suppressions.xml +++ b/build/android/lint/suppressions.xml
@@ -328,6 +328,16 @@ <!-- 2 resources used by android webview glue layer, could be refactored --> <ignore regexp="android_webview/java/res/drawable-hdpi/ic_play_circle_outline_black_48dp.png"/> <ignore regexp="R.string.private_browsing_warning"/> + <!-- OMR1 SDK roll mystery. TODO(jbudorick): Remove this after rolling lint. --> + <ignore regexp="chrome/android/chrome_strings_grd.resources.zip/values/android_chrome_strings.xml"/> + <ignore regexp="chrome/android/java/res/layout/location_bar.xml"/> + <ignore regexp="chrome/android/java/res/values/colors.xml"/> + <ignore regexp="chrome/android/java/res/values/dimens.xml"/> + <ignore regexp="chrome/android/java/res/drawable-hdpi/ic_omnibox_magnifier.png"/> + <ignore regexp="chrome/android/java/res/drawable-hdpi/omnibox_https_invalid.png"/> + <ignore regexp="chrome/android/java/res/drawable-hdpi/omnibox_info.png"/> + <ignore regexp="clank/java/clank_strings_grd.resources.zip/values/android_internal_strings.xml"/> + <ignore regexp="tools/android/audio_focus_grabber/java/res/drawable-hdpi/notification_icon.png"/> </issue> <issue id="UseCompoundDrawables"> <!-- Upscaling 24dp to 48dp doesn't work as expected with a TextView compound drawable. -->
diff --git a/build/android/pylib/constants/__init__.py b/build/android/pylib/constants/__init__.py index 354254a..d7547b2 100644 --- a/build/android/pylib/constants/__init__.py +++ b/build/android/pylib/constants/__init__.py
@@ -95,8 +95,8 @@ SCREENSHOTS_DIR = os.path.join(DIR_SOURCE_ROOT, 'out_screenshots') -ANDROID_SDK_VERSION = version_codes.O -ANDROID_SDK_BUILD_TOOLS_VERSION = '26.0.2' +ANDROID_SDK_VERSION = version_codes.O_MR1 +ANDROID_SDK_BUILD_TOOLS_VERSION = '27.0.1' ANDROID_SDK_ROOT = os.path.join(DIR_SOURCE_ROOT, 'third_party', 'android_tools', 'sdk') ANDROID_SDK_TOOLS = os.path.join(ANDROID_SDK_ROOT,
diff --git a/build/config/android/config.gni b/build/config/android/config.gni index 74e77909..d8eb8db 100644 --- a/build/config/android/config.gni +++ b/build/config/android/config.gni
@@ -30,7 +30,7 @@ } else { import("//build/config/android/sdk.gni") declare_args() { - # Android SDK release. Currently, only "o" is publicly supported. + # Android SDK release. Currently, only "o_mr1" is publicly supported. android_sdk_release = default_android_sdk_release } } @@ -51,11 +51,11 @@ assert(defined(default_android_ndk_major_version)) } - if (android_sdk_release == "o") { + if (android_sdk_release == "o_mr1") { default_android_sdk_root = "//third_party/android_tools/sdk" - default_android_sdk_version = "26" - default_android_sdk_build_tools_version = "26.0.2" - default_android_sdk_tools_version_suffix = "-25.3.2" + default_android_sdk_version = "27" + default_android_sdk_build_tools_version = "27.0.1" + default_android_sdk_tools_version_suffix = "-26.0.0-dev" public_android_sdk = true }
diff --git a/build/config/android/internal_rules.gni b/build/config/android/internal_rules.gni index d3b6bad..daa081f 100644 --- a/build/config/android/internal_rules.gni +++ b/build/config/android/internal_rules.gni
@@ -770,14 +770,13 @@ lint_suppressions_file = "//build/android/lint/suppressions.xml" } + _lint_path = "$lint_android_sdk_root/tools-lint/bin/lint" _cache_dir = "$root_build_dir/android_lint_cache" _result_path = "$target_gen_dir/$target_name/result.xml" _config_path = "$target_gen_dir/$target_name/config.xml" _suppressions_file = lint_suppressions_file _platform_xml_path = "${android_sdk_root}/platform-tools/api/api-versions.xml" - _rebased_lint_android_sdk_root = - rebase_path(lint_android_sdk_root, root_build_dir) script = "//build/android/gyp/lint.py" depfile = "$target_gen_dir/$target_name.d" @@ -793,7 +792,8 @@ ] args = [ - "--lint-path=$_rebased_lint_android_sdk_root/tools-lint/bin/lint", + "--lint-path", + rebase_path(_lint_path, root_build_dir), "--cache-dir", rebase_path(_cache_dir, root_build_dir), "--platform-xml-path", @@ -1383,7 +1383,19 @@ # Runs process_resources.py template("process_resources") { - action(target_name) { + _process_resources_target_name = target_name + if (defined(invoker.output)) { + _post_process = defined(invoker.post_process_script) + _packaged_resources_path = invoker.output + if (_post_process) { + _process_resources_target_name = "${target_name}__intermediate" + _packaged_resources_path = + get_path_info(_packaged_resources_path, "dir") + "/" + + get_path_info(_packaged_resources_path, "name") + + ".intermediate.ap_" + } + } + action(_process_resources_target_name) { set_sources_assignment_filter([]) forward_variables_from(invoker, [ @@ -1426,6 +1438,7 @@ } inputs = [ + android_default_aapt_path, invoker.build_config, invoker.android_manifest, _android_aapt_path, @@ -1445,12 +1458,41 @@ rebase_path(_android_aapt_path, root_build_dir), "--android-manifest", rebase_path(invoker.android_manifest, root_build_dir), - "--resource-dirs=$_rebased_all_resource_dirs", "--dependencies-res-zips=@FileArg($_rebased_build_config:resources:dependency_zips)", "--extra-res-packages=@FileArg($_rebased_build_config:resources:extra_package_names)", "--extra-r-text-files=@FileArg($_rebased_build_config:resources:extra_r_text_files)", ] + if (_rebased_all_resource_dirs != []) { + args += [ "--resource-dirs=$_rebased_all_resource_dirs" ] + } + + if (defined(invoker.version_code)) { + args += [ + "--version-code", + invoker.version_code, + ] + } + if (defined(invoker.version_name)) { + args += [ + "--version-name", + invoker.version_name, + ] + } + if (defined(_packaged_resources_path)) { + outputs += [ _packaged_resources_path ] + args += [ + "--apk-path", + rebase_path(_packaged_resources_path, root_build_dir), + ] + } + + # Useful to have android:debuggable in the manifest even for Release + # builds. Just omit it for officai + if (debuggable_apks) { + args += [ "--debuggable" ] + } + if (defined(invoker.zip_path)) { outputs += [ invoker.zip_path ] args += [ @@ -1459,15 +1501,6 @@ ] } - if (defined(invoker.all_resources_zip_path)) { - _all_resources_zip = invoker.all_resources_zip_path - outputs += [ _all_resources_zip ] - args += [ - "--all-resources-zip-out", - rebase_path(_all_resources_zip, root_build_dir), - ] - } - if (defined(invoker.r_text_out_path)) { outputs += [ invoker.r_text_out_path ] args += [ @@ -1517,11 +1550,6 @@ args += [ "--app-as-shared-lib" ] } - if (defined(invoker.include_all_resources) && - invoker.include_all_resources) { - args += [ "--include-all-resources" ] - } - if (defined(invoker.proguard_file)) { outputs += [ invoker.proguard_file ] args += [ @@ -1538,112 +1566,6 @@ ] } - if (defined(invoker.support_zh_hk) && invoker.support_zh_hk) { - args += [ "--support-zh-hk" ] - } - - if (defined(invoker.args)) { - args += invoker.args - } - } - } - - # Runs aapt to create an .ap_ file, which is a zip file containing - # compiled xml and a resources.arsc file. - # - # Required Variables: - # output: Path to .ap_ to create. - # android_manifest: The AndroidManifest.xml for the apk. - # version_code: The verison code to use. - # version_name: The verison name to use. - # Optional Variables: - # aapt_locale_whitelist: If set, all locales not in this list will be - # stripped from resources.arsc. - # alternative_android_sdk_jar: An alternative android sdk jar. - # app_as_shared_lib: Enables --app-as-shared-lib. - # exclude_xxxhdpi: Causes all drawable-xxxhdpi images to be excluded - # (mipmaps are still included). - # png_to_webp: If true, pngs (with the exception of 9-patch) are - # converted to webp. - # post_process_script: Script to call to post-process the .ap_. - # resources_zip: Resource .zip file created by process_resources to package. - # shared_resources: Enables --shared-lib. - # density_splits: A list of densities to create apk splits for. - # language_splits: A list of language codes to create apk splits for. - # xxxhdpi_whitelist: A list of globs used when exclude_xxxhdpi=true. Files - # that match this whitelist will still be included. - template("package_resources") { - _post_process = defined(invoker.post_process_script) - _package_resources_target_name = target_name - _packaged_resources_path = invoker.output - if (_post_process) { - _package_resources_target_name = "${target_name}__intermediate" - _packaged_resources_path = - get_path_info(_packaged_resources_path, "dir") + "/" + - get_path_info(_packaged_resources_path, "name") + ".intermediate.ap_" - } - - action(_package_resources_target_name) { - forward_variables_from(invoker, - [ - "deps", - "testonly", - "visibility", - ]) - - script = "//build/android/gyp/package_resources.py" - depfile = "${target_gen_dir}/${target_name}.d" - outputs = [ - _packaged_resources_path, - ] - - _android_sdk_jar = android_sdk_jar - if (defined(invoker.alternative_android_sdk_jar)) { - _android_sdk_jar = invoker.alternative_android_sdk_jar - } - - inputs = [ - android_default_aapt_path, - _android_sdk_jar, - invoker.android_manifest, - ] - - args = [ - "--depfile", - rebase_path(depfile, root_build_dir), - "--android-sdk-jar", - rebase_path(_android_sdk_jar, root_build_dir), - "--aapt-path", - rebase_path(android_default_aapt_path, root_build_dir), - "--android-manifest", - rebase_path(invoker.android_manifest, root_build_dir), - "--version-code", - invoker.version_code, - "--version-name", - invoker.version_name, - "--apk-path", - rebase_path(_packaged_resources_path, root_build_dir), - ] - - # Useful to have android:debuggable in the manifest even for Release - # builds. Just omit it for officai - if (debuggable_apks) { - args += [ "--debuggable" ] - } - - if (defined(invoker.resources_zip)) { - inputs += [ invoker.resources_zip ] - args += [ - "--resource-zips", - rebase_path(invoker.resources_zip, root_build_dir), - ] - } - if (defined(invoker.shared_resources) && invoker.shared_resources) { - args += [ "--shared-resources" ] - } - if (defined(invoker.app_as_shared_lib) && invoker.app_as_shared_lib) { - args += [ "--app-as-shared-lib" ] - } if (defined(invoker.density_splits) && invoker.density_splits != []) { args += [ "--create-density-splits" ] foreach(_density, invoker.density_splits) { @@ -1675,12 +1597,17 @@ args += [ "--xxxhdpi-whitelist=${invoker.xxxhdpi_whitelist}" ] } } + if (defined(invoker.support_zh_hk) && invoker.support_zh_hk) { args += [ "--support-zh-hk" ] } + + if (defined(invoker.args)) { + args += invoker.args + } } - if (_post_process) { + if (defined(_packaged_resources_path) && _post_process) { action(target_name) { depfile = "${target_gen_dir}/${target_name}.d" script = invoker.post_process_script @@ -1699,7 +1626,7 @@ invoker.output, ] public_deps = [ - ":${_package_resources_target_name}", + ":${_process_resources_target_name}", ] } }
diff --git a/build/config/android/rules.gni b/build/config/android/rules.gni index 26199a12..753d974 100644 --- a/build/config/android/rules.gni +++ b/build/config/android/rules.gni
@@ -1192,7 +1192,7 @@ _deps += invoker.deps } if (defined(invoker.java_files)) { - _java_sources_file = "$target_gen_dir/target_name.sources" + _java_sources_file = "$target_gen_dir/$target_name.sources" } write_build_config(_build_config_target_name) { forward_variables_from(invoker, [ "classpath_deps" ]) @@ -1740,8 +1740,6 @@ # (optional). # apk_under_test: For an instrumentation test apk, this is the target of the # tested apk. - # include_all_resources - If true include all resource IDs in all generated - # R.java files. # testonly: Marks this target as "test-only". # write_asset_list: Adds an extra file to the assets, which contains a list of # all other asset files. @@ -1794,7 +1792,6 @@ # JUnit tests use resource zip files. These must not be put in gen/ # directory or they will not be available to tester bots. - _all_resources_zip_path = "$_base_path.resources.all.zip" _jar_path = "$_base_path.jar" _lib_dex_path = "$_base_path.dex.jar" _rebased_lib_dex_path = rebase_path(_lib_dex_path, root_build_dir) @@ -2113,19 +2110,29 @@ [ "alternative_android_sdk_jar", "app_as_shared_lib", - "include_all_resources", "shared_resources", "support_zh_hk", + "aapt_locale_whitelist", + "exclude_xxxhdpi", + "png_to_webp", + "xxxhdpi_whitelist", ]) + android_manifest = _android_manifest + version_code = _version_code + version_name = _version_name + if (defined(invoker.post_process_package_resources_script)) { + post_process_script = invoker.post_process_package_resources_script + } srcjar_path = "${target_gen_dir}/${target_name}.srcjar" r_text_out_path = "${target_gen_dir}/${target_name}_R.txt" - android_manifest = _android_manifest - all_resources_zip_path = _all_resources_zip_path generate_constant_ids = true proguard_file = _generated_proguard_config if (_enable_multidex) { proguard_file_main_dex = _generated_proguard_main_dex_config } + output = _packaged_resources_path + density_splits = _density_splits + language_splits = _language_splits build_config = _build_config deps = _deps + [ @@ -2134,34 +2141,6 @@ ] } _srcjar_deps += [ ":$_process_resources_target" ] - _package_resources_target = "${target_name}__package_resources" - package_resources(_package_resources_target) { - forward_variables_from(invoker, - [ - "aapt_locale_whitelist", - "alternative_android_sdk_jar", - "app_as_shared_lib", - "exclude_xxxhdpi", - "png_to_webp", - "shared_resources", - "support_zh_hk", - "xxxhdpi_whitelist", - ]) - deps = _deps + [ - ":$_android_manifest_target", - ":$_process_resources_target", - ] - android_manifest = _android_manifest - version_code = _version_code - version_name = _version_name - if (defined(invoker.post_process_package_resources_script)) { - post_process_script = invoker.post_process_package_resources_script - } - resources_zip = _all_resources_zip_path - output = _packaged_resources_path - density_splits = _density_splits - language_splits = _language_splits - } if (_native_libs_deps != []) { _enable_chromium_linker_tests = false @@ -2520,7 +2499,7 @@ incremental_deps = _deps + [ ":$_android_manifest_target", ":$_build_config_target", - ":$_package_resources_target", + ":$_process_resources_target", ] # This target generates the input file _all_resources_zip_path. @@ -2528,7 +2507,7 @@ ":$_android_manifest_target", ":$_build_config_target", ":$_final_dex_target_name", - ":$_package_resources_target", + ":$_process_resources_target", ] if ((_native_libs_deps != [] || @@ -2570,7 +2549,7 @@ ] } - package_resources("${_apk_rule}__process_resources") { + process_resources("${_apk_rule}__process_resources") { deps = [ ":${_apk_rule}__generate_manifest", ]
diff --git a/build/config/android/sdk.gni b/build/config/android/sdk.gni index 562d9b6..2fe0400 100644 --- a/build/config/android/sdk.gni +++ b/build/config/android/sdk.gni
@@ -4,7 +4,7 @@ # The default SDK release used by public builds. Value may differ in # internal builds. -default_android_sdk_release = "o" +default_android_sdk_release = "o_mr1" # SDK releases against which public builds are supported. -public_sdk_releases = [ "o" ] +public_sdk_releases = [ "o_mr1" ]
diff --git a/cc/layers/video_layer_impl.cc b/cc/layers/video_layer_impl.cc index b4316bb..99dd57e 100644 --- a/cc/layers/video_layer_impl.cc +++ b/cc/layers/video_layer_impl.cc
@@ -106,37 +106,7 @@ layer_tree_impl()->resource_provider(), layer_tree_impl()->settings().use_stream_video_draw_quad)); } - - VideoFrameExternalResources external_resources = - updater_->CreateExternalResourcesFromVideoFrame(frame_); - frame_resource_type_ = external_resources.type; - - if (external_resources.type == - VideoFrameExternalResources::SOFTWARE_RESOURCE) { - DCHECK_GT(external_resources.software_resource, viz::kInvalidResourceId); - software_resource_ = external_resources.software_resource; - software_release_callback_ = - std::move(external_resources.software_release_callback); - return true; - } - frame_resource_offset_ = external_resources.offset; - frame_resource_multiplier_ = external_resources.multiplier; - frame_bits_per_channel_ = external_resources.bits_per_channel; - - DCHECK_EQ(external_resources.resources.size(), - external_resources.release_callbacks.size()); - ResourceProvider::ResourceIdArray resource_ids; - resource_ids.reserve(external_resources.resources.size()); - for (size_t i = 0; i < external_resources.resources.size(); ++i) { - unsigned resource_id = resource_provider->ImportResource( - external_resources.resources[i], - viz::SingleReleaseCallback::Create( - std::move(external_resources.release_callbacks[i]))); - frame_resources_.push_back( - FrameResource(resource_id, external_resources.resources[i].size)); - resource_ids.push_back(resource_id); - } - + updater_->ObtainFrameResources(frame_); return true; } @@ -165,153 +135,20 @@ break; } - viz::SharedQuadState* shared_quad_state = - render_pass->CreateAndAppendSharedQuadState(); - gfx::Rect rotated_size_rect(rotated_size); - shared_quad_state->SetAll(transform, rotated_size_rect, visible_layer_rect(), - clip_rect(), is_clipped(), contents_opaque(), - draw_opacity(), SkBlendMode::kSrcOver, - GetSortingContextId()); - - AppendDebugBorderQuad(render_pass, rotated_size_rect, shared_quad_state, - append_quads_data); - - gfx::Rect quad_rect(rotated_size); - gfx::Rect visible_rect = frame_->visible_rect(); - bool needs_blending = !contents_opaque(); - gfx::Size coded_size = frame_->coded_size(); - Occlusion occlusion_in_video_space = draw_properties() .occlusion_in_content_space.GetOcclusionWithGivenDrawTransform( transform); gfx::Rect visible_quad_rect = - occlusion_in_video_space.GetUnoccludedContentRect(quad_rect); + occlusion_in_video_space.GetUnoccludedContentRect( + gfx::Rect(rotated_size)); if (visible_quad_rect.IsEmpty()) return; - const float tex_width_scale = - static_cast<float>(visible_rect.width()) / coded_size.width(); - const float tex_height_scale = - static_cast<float>(visible_rect.height()) / coded_size.height(); - - switch (frame_resource_type_) { - // TODO(danakj): Remove this, hide it in the hardware path. - case VideoFrameExternalResources::SOFTWARE_RESOURCE: { - DCHECK_EQ(frame_resources_.size(), 0u); - DCHECK_GT(software_resource_, viz::kInvalidResourceId); - bool premultiplied_alpha = true; - gfx::PointF uv_top_left(0.f, 0.f); - gfx::PointF uv_bottom_right(tex_width_scale, tex_height_scale); - float opacity[] = {1.0f, 1.0f, 1.0f, 1.0f}; - bool flipped = false; - bool nearest_neighbor = false; - auto* texture_quad = - render_pass->CreateAndAppendDrawQuad<viz::TextureDrawQuad>(); - texture_quad->SetNew( - shared_quad_state, quad_rect, visible_quad_rect, needs_blending, - software_resource_, premultiplied_alpha, uv_top_left, uv_bottom_right, - SK_ColorTRANSPARENT, opacity, flipped, nearest_neighbor, false); - ValidateQuadResources(texture_quad); - break; - } - case VideoFrameExternalResources::YUV_RESOURCE: { - const gfx::Size ya_tex_size = coded_size; - - int u_width = media::VideoFrame::Columns( - media::VideoFrame::kUPlane, frame_->format(), coded_size.width()); - int u_height = media::VideoFrame::Rows( - media::VideoFrame::kUPlane, frame_->format(), coded_size.height()); - gfx::Size uv_tex_size(u_width, u_height); - - if (frame_->HasTextures()) { - if (frame_->format() == media::PIXEL_FORMAT_NV12) { - DCHECK_EQ(2u, frame_resources_.size()); - } else { - DCHECK_EQ(media::PIXEL_FORMAT_I420, frame_->format()); - DCHECK_EQ(3u, - frame_resources_.size()); // Alpha is not supported yet. - } - } else { - DCHECK_GE(frame_resources_.size(), 3u); - DCHECK(frame_resources_.size() <= 3 || - ya_tex_size == media::VideoFrame::PlaneSize( - frame_->format(), media::VideoFrame::kAPlane, - coded_size)); - } - - // Compute the UV sub-sampling factor based on the ratio between - // |ya_tex_size| and |uv_tex_size|. - float uv_subsampling_factor_x = - static_cast<float>(ya_tex_size.width()) / uv_tex_size.width(); - float uv_subsampling_factor_y = - static_cast<float>(ya_tex_size.height()) / uv_tex_size.height(); - gfx::RectF ya_tex_coord_rect(visible_rect); - gfx::RectF uv_tex_coord_rect( - visible_rect.x() / uv_subsampling_factor_x, - visible_rect.y() / uv_subsampling_factor_y, - visible_rect.width() / uv_subsampling_factor_x, - visible_rect.height() / uv_subsampling_factor_y); - - auto* yuv_video_quad = - render_pass->CreateAndAppendDrawQuad<viz::YUVVideoDrawQuad>(); - yuv_video_quad->SetNew( - shared_quad_state, quad_rect, visible_quad_rect, needs_blending, - ya_tex_coord_rect, uv_tex_coord_rect, ya_tex_size, uv_tex_size, - frame_resources_[0].id, frame_resources_[1].id, - frame_resources_.size() > 2 ? frame_resources_[2].id - : frame_resources_[1].id, - frame_resources_.size() > 3 ? frame_resources_[3].id : 0, - frame_->ColorSpace(), frame_resource_offset_, - frame_resource_multiplier_, frame_bits_per_channel_); - yuv_video_quad->require_overlay = frame_->metadata()->IsTrue( - media::VideoFrameMetadata::REQUIRE_OVERLAY); - ValidateQuadResources(yuv_video_quad); - break; - } - case VideoFrameExternalResources::RGBA_RESOURCE: - case VideoFrameExternalResources::RGBA_PREMULTIPLIED_RESOURCE: - case VideoFrameExternalResources::RGB_RESOURCE: { - DCHECK_EQ(frame_resources_.size(), 1u); - if (frame_resources_.size() < 1u) - break; - bool premultiplied_alpha = - frame_resource_type_ == - VideoFrameExternalResources::RGBA_PREMULTIPLIED_RESOURCE; - gfx::PointF uv_top_left(0.f, 0.f); - gfx::PointF uv_bottom_right(tex_width_scale, tex_height_scale); - float opacity[] = {1.0f, 1.0f, 1.0f, 1.0f}; - bool flipped = false; - bool nearest_neighbor = false; - auto* texture_quad = - render_pass->CreateAndAppendDrawQuad<viz::TextureDrawQuad>(); - texture_quad->SetNew(shared_quad_state, quad_rect, visible_quad_rect, - needs_blending, frame_resources_[0].id, - premultiplied_alpha, uv_top_left, uv_bottom_right, - SK_ColorTRANSPARENT, opacity, flipped, - nearest_neighbor, false); - texture_quad->set_resource_size_in_pixels(coded_size); - ValidateQuadResources(texture_quad); - break; - } - case VideoFrameExternalResources::STREAM_TEXTURE_RESOURCE: { - DCHECK_EQ(frame_resources_.size(), 1u); - if (frame_resources_.size() < 1u) - break; - gfx::Transform scale; - scale.Scale(tex_width_scale, tex_height_scale); - auto* stream_video_quad = - render_pass->CreateAndAppendDrawQuad<viz::StreamVideoDrawQuad>(); - stream_video_quad->SetNew(shared_quad_state, quad_rect, visible_quad_rect, - needs_blending, frame_resources_[0].id, - frame_resources_[0].size_in_pixels, scale); - ValidateQuadResources(stream_video_quad); - break; - } - case VideoFrameExternalResources::NONE: - NOTIMPLEMENTED(); - break; - } + updater_->AppendQuads(render_pass, frame_, transform, rotated_size, + visible_layer_rect(), clip_rect(), is_clipped(), + contents_opaque(), draw_opacity(), + GetSortingContextId(), visible_quad_rect); } void VideoLayerImpl::DidDraw(LayerTreeResourceProvider* resource_provider) { @@ -319,17 +156,7 @@ DCHECK(frame_.get()); - if (frame_resource_type_ == - VideoFrameExternalResources::SOFTWARE_RESOURCE) { - DCHECK_GT(software_resource_, viz::kInvalidResourceId); - std::move(software_release_callback_).Run(gpu::SyncToken(), false); - software_resource_ = viz::kInvalidResourceId; - } else { - for (const FrameResource& resource : frame_resources_) - resource_provider->RemoveImportedResource(resource.id); - frame_resources_.clear(); - } - + updater_->ReleaseFrameResources(); provider_client_impl_->PutCurrentFrame(); frame_ = nullptr;
diff --git a/cc/layers/video_layer_impl.h b/cc/layers/video_layer_impl.h index 134e403..30d1055 100644 --- a/cc/layers/video_layer_impl.h +++ b/cc/layers/video_layer_impl.h
@@ -63,23 +63,6 @@ media::VideoRotation video_rotation_; std::unique_ptr<VideoResourceUpdater> updater_; - VideoFrameExternalResources::ResourceType frame_resource_type_; - float frame_resource_offset_; - float frame_resource_multiplier_; - uint32_t frame_bits_per_channel_; - - struct FrameResource { - FrameResource(viz::ResourceId id, gfx::Size size_in_pixels) - : id(id), size_in_pixels(size_in_pixels) {} - viz::ResourceId id; - gfx::Size size_in_pixels; - }; - std::vector<FrameResource> frame_resources_; - - // TODO(danakj): Remove these, use TransferableResource for software path too. - unsigned software_resource_ = viz::kInvalidResourceId; - // Called once for software_resource_. - viz::ReleaseCallback software_release_callback_; DISALLOW_COPY_AND_ASSIGN(VideoLayerImpl); };
diff --git a/cc/paint/paint_image.h b/cc/paint/paint_image.h index 1e32f87..1d4f6f14 100644 --- a/cc/paint/paint_image.h +++ b/cc/paint/paint_image.h
@@ -166,9 +166,6 @@ // Returns the total number of frames known to exist in this image. size_t FrameCount() const; - // Returns an SkImage for the frame at |index|. - sk_sp<SkImage> GetSkImageForFrame(size_t index) const; - std::string ToString() const; private: @@ -187,6 +184,9 @@ void CreateSkImage(); PaintImage MakeSubset(const gfx::Rect& subset) const; + // Returns an SkImage for the frame at |index|. + sk_sp<SkImage> GetSkImageForFrame(size_t index) const; + sk_sp<SkImage> sk_image_; sk_sp<PaintRecord> paint_record_;
diff --git a/cc/paint/paint_op_buffer.h b/cc/paint/paint_op_buffer.h index eb34cdce..eef8cc2 100644 --- a/cc/paint/paint_op_buffer.h +++ b/cc/paint/paint_op_buffer.h
@@ -855,8 +855,6 @@ ptr_ += op->skip; op_offset_ += op->skip; - // Debugging crbug.com/738182. - base::debug::Alias(op); CHECK_LE(op_offset_, buffer_->used_); return *this; }
diff --git a/cc/resources/video_resource_updater.cc b/cc/resources/video_resource_updater.cc index 6adf2f8b..8799963c 100644 --- a/cc/resources/video_resource_updater.cc +++ b/cc/resources/video_resource_updater.cc
@@ -14,8 +14,12 @@ #include "base/trace_event/trace_event.h" #include "cc/base/math_util.h" #include "cc/paint/skia_paint_canvas.h" -#include "cc/resources/resource_provider.h" +#include "cc/resources/layer_tree_resource_provider.h" #include "cc/resources/resource_util.h" +#include "components/viz/common/quads/render_pass.h" +#include "components/viz/common/quads/stream_video_draw_quad.h" +#include "components/viz/common/quads/texture_draw_quad.h" +#include "components/viz/common/quads/yuv_video_draw_quad.h" #include "gpu/GLES2/gl2extchromium.h" #include "gpu/command_buffer/client/gles2_interface.h" #include "media/base/video_frame.h" @@ -187,7 +191,7 @@ VideoResourceUpdater::VideoResourceUpdater( viz::ContextProvider* context_provider, - ResourceProvider* resource_provider, + LayerTreeResourceProvider* resource_provider, bool use_stream_video_draw_quad) : context_provider_(context_provider), resource_provider_(resource_provider), @@ -583,6 +587,209 @@ return external_resources; } +void VideoResourceUpdater::ObtainFrameResources( + scoped_refptr<media::VideoFrame> video_frame) { + VideoFrameExternalResources external_resources = + CreateExternalResourcesFromVideoFrame(video_frame); + frame_resource_type_ = external_resources.type; + + if (external_resources.type == + VideoFrameExternalResources::SOFTWARE_RESOURCE) { + DCHECK_GT(external_resources.software_resource, viz::kInvalidResourceId); + software_resource_ = external_resources.software_resource; + software_release_callback_ = + std::move(external_resources.software_release_callback); + } else { + frame_resource_offset_ = external_resources.offset; + frame_resource_multiplier_ = external_resources.multiplier; + frame_bits_per_channel_ = external_resources.bits_per_channel; + + DCHECK_EQ(external_resources.resources.size(), + external_resources.release_callbacks.size()); + ResourceProvider::ResourceIdArray resource_ids; + resource_ids.reserve(external_resources.resources.size()); + for (size_t i = 0; i < external_resources.resources.size(); ++i) { + unsigned resource_id = resource_provider_->ImportResource( + external_resources.resources[i], + viz::SingleReleaseCallback::Create( + std::move(external_resources.release_callbacks[i]))); + frame_resources_.push_back( + FrameResource(resource_id, external_resources.resources[i].size)); + resource_ids.push_back(resource_id); + } + } +} + +void VideoResourceUpdater::ReleaseFrameResources() { + if (frame_resource_type_ == VideoFrameExternalResources::SOFTWARE_RESOURCE) { + DCHECK_GT(software_resource_, viz::kInvalidResourceId); + std::move(software_release_callback_).Run(gpu::SyncToken(), false); + software_resource_ = viz::kInvalidResourceId; + } else { + for (size_t i = 0; i < frame_resources_.size(); ++i) + resource_provider_->RemoveImportedResource(frame_resources_[i].id); + frame_resources_.clear(); + } +} + +void VideoResourceUpdater::AppendQuads(viz::RenderPass* render_pass, + scoped_refptr<media::VideoFrame> frame, + gfx::Transform transform, + gfx::Size rotated_size, + gfx::Rect visible_layer_rect, + gfx::Rect clip_rect, + bool is_clipped, + bool contents_opaque, + float draw_opacity, + int sorting_context_id, + gfx::Rect visible_quad_rect) { + DCHECK(frame.get()); + + viz::SharedQuadState* shared_quad_state = + render_pass->CreateAndAppendSharedQuadState(); + gfx::Rect rotated_size_rect(rotated_size); + shared_quad_state->SetAll( + transform, rotated_size_rect, visible_layer_rect, clip_rect, is_clipped, + contents_opaque, draw_opacity, SkBlendMode::kSrcOver, sorting_context_id); + + gfx::Rect quad_rect(rotated_size); + gfx::Rect visible_rect = frame->visible_rect(); + bool needs_blending = !contents_opaque; + gfx::Size coded_size = frame->coded_size(); + + const float tex_width_scale = + static_cast<float>(visible_rect.width()) / coded_size.width(); + const float tex_height_scale = + static_cast<float>(visible_rect.height()) / coded_size.height(); + + switch (frame_resource_type_) { + // TODO(danakj): Remove this, hide it in the hardware path. + case VideoFrameExternalResources::SOFTWARE_RESOURCE: { + DCHECK_EQ(frame_resources_.size(), 0u); + DCHECK_GT(software_resource_, viz::kInvalidResourceId); + bool premultiplied_alpha = true; + gfx::PointF uv_top_left(0.f, 0.f); + gfx::PointF uv_bottom_right(tex_width_scale, tex_height_scale); + float opacity[] = {1.0f, 1.0f, 1.0f, 1.0f}; + bool flipped = false; + bool nearest_neighbor = false; + auto* texture_quad = + render_pass->CreateAndAppendDrawQuad<viz::TextureDrawQuad>(); + texture_quad->SetNew( + shared_quad_state, quad_rect, visible_quad_rect, needs_blending, + software_resource_, premultiplied_alpha, uv_top_left, uv_bottom_right, + SK_ColorTRANSPARENT, opacity, flipped, nearest_neighbor, false); + for (viz::ResourceId resource_id : texture_quad->resources) { + resource_provider_->ValidateResource(resource_id); + } + break; + } + case VideoFrameExternalResources::YUV_RESOURCE: { + const gfx::Size ya_tex_size = coded_size; + + int u_width = media::VideoFrame::Columns( + media::VideoFrame::kUPlane, frame->format(), coded_size.width()); + int u_height = media::VideoFrame::Rows( + media::VideoFrame::kUPlane, frame->format(), coded_size.height()); + gfx::Size uv_tex_size(u_width, u_height); + + if (frame->HasTextures()) { + if (frame->format() == media::PIXEL_FORMAT_NV12) { + DCHECK_EQ(2u, frame_resources_.size()); + } else { + DCHECK_EQ(media::PIXEL_FORMAT_I420, frame->format()); + DCHECK_EQ(3u, + frame_resources_.size()); // Alpha is not supported yet. + } + } else { + DCHECK_GE(frame_resources_.size(), 3u); + DCHECK(frame_resources_.size() <= 3 || + ya_tex_size == media::VideoFrame::PlaneSize( + frame->format(), media::VideoFrame::kAPlane, + coded_size)); + } + + // Compute the UV sub-sampling factor based on the ratio between + // |ya_tex_size| and |uv_tex_size|. + float uv_subsampling_factor_x = + static_cast<float>(ya_tex_size.width()) / uv_tex_size.width(); + float uv_subsampling_factor_y = + static_cast<float>(ya_tex_size.height()) / uv_tex_size.height(); + gfx::RectF ya_tex_coord_rect(visible_rect); + gfx::RectF uv_tex_coord_rect( + visible_rect.x() / uv_subsampling_factor_x, + visible_rect.y() / uv_subsampling_factor_y, + visible_rect.width() / uv_subsampling_factor_x, + visible_rect.height() / uv_subsampling_factor_y); + + auto* yuv_video_quad = + render_pass->CreateAndAppendDrawQuad<viz::YUVVideoDrawQuad>(); + yuv_video_quad->SetNew( + shared_quad_state, quad_rect, visible_quad_rect, needs_blending, + ya_tex_coord_rect, uv_tex_coord_rect, ya_tex_size, uv_tex_size, + frame_resources_[0].id, frame_resources_[1].id, + frame_resources_.size() > 2 ? frame_resources_[2].id + : frame_resources_[1].id, + frame_resources_.size() > 3 ? frame_resources_[3].id : 0, + frame->ColorSpace(), frame_resource_offset_, + frame_resource_multiplier_, frame_bits_per_channel_); + yuv_video_quad->require_overlay = frame->metadata()->IsTrue( + media::VideoFrameMetadata::REQUIRE_OVERLAY); + + for (viz::ResourceId resource_id : yuv_video_quad->resources) { + resource_provider_->ValidateResource(resource_id); + } + break; + } + case VideoFrameExternalResources::RGBA_RESOURCE: + case VideoFrameExternalResources::RGBA_PREMULTIPLIED_RESOURCE: + case VideoFrameExternalResources::RGB_RESOURCE: { + DCHECK_EQ(frame_resources_.size(), 1u); + if (frame_resources_.size() < 1u) + break; + bool premultiplied_alpha = + frame_resource_type_ == + VideoFrameExternalResources::RGBA_PREMULTIPLIED_RESOURCE; + gfx::PointF uv_top_left(0.f, 0.f); + gfx::PointF uv_bottom_right(tex_width_scale, tex_height_scale); + float opacity[] = {1.0f, 1.0f, 1.0f, 1.0f}; + bool flipped = false; + bool nearest_neighbor = false; + auto* texture_quad = + render_pass->CreateAndAppendDrawQuad<viz::TextureDrawQuad>(); + texture_quad->SetNew(shared_quad_state, quad_rect, visible_quad_rect, + needs_blending, frame_resources_[0].id, + premultiplied_alpha, uv_top_left, uv_bottom_right, + SK_ColorTRANSPARENT, opacity, flipped, + nearest_neighbor, false); + texture_quad->set_resource_size_in_pixels(coded_size); + for (viz::ResourceId resource_id : texture_quad->resources) { + resource_provider_->ValidateResource(resource_id); + } + break; + } + case VideoFrameExternalResources::STREAM_TEXTURE_RESOURCE: { + DCHECK_EQ(frame_resources_.size(), 1u); + if (frame_resources_.size() < 1u) + break; + gfx::Transform scale; + scale.Scale(tex_width_scale, tex_height_scale); + auto* stream_video_quad = + render_pass->CreateAndAppendDrawQuad<viz::StreamVideoDrawQuad>(); + stream_video_quad->SetNew(shared_quad_state, quad_rect, visible_quad_rect, + needs_blending, frame_resources_[0].id, + frame_resources_[0].size_in_pixels, scale); + for (viz::ResourceId resource_id : stream_video_quad->resources) { + resource_provider_->ValidateResource(resource_id); + } + break; + } + case VideoFrameExternalResources::NONE: + NOTIMPLEMENTED(); + break; + } +} + // static void VideoResourceUpdater::ReturnTexture( base::WeakPtr<VideoResourceUpdater> updater,
diff --git a/cc/resources/video_resource_updater.h b/cc/resources/video_resource_updater.h index 14a1e6d..8e1f6b4 100644 --- a/cc/resources/video_resource_updater.h +++ b/cc/resources/video_resource_updater.h
@@ -29,12 +29,18 @@ class VideoFrame; } +namespace gfx { +class Rect; +class Transform; +} // namespace gfx + namespace viz { class ContextProvider; +class RenderPass; } namespace cc { -class ResourceProvider; +class LayerTreeResourceProvider; class CC_EXPORT VideoFrameExternalResources { public: @@ -50,7 +56,6 @@ SOFTWARE_RESOURCE }; - ResourceType type = NONE; std::vector<viz::TransferableResource> resources; std::vector<viz::ReleaseCallback> release_callbacks; @@ -77,7 +82,7 @@ class CC_EXPORT VideoResourceUpdater { public: VideoResourceUpdater(viz::ContextProvider* context_provider, - ResourceProvider* resource_provider, + LayerTreeResourceProvider* resource_provider, bool use_stream_video_draw_quad); ~VideoResourceUpdater(); @@ -88,6 +93,20 @@ use_r16_for_testing_ = use_r16_for_testing; } + void ObtainFrameResources(scoped_refptr<media::VideoFrame> video_frame); + void ReleaseFrameResources(); + void AppendQuads(viz::RenderPass* render_pass, + scoped_refptr<media::VideoFrame> frame, + gfx::Transform transform, + gfx::Size rotated_size, + gfx::Rect visible_layer_rect, + gfx::Rect clip_rect, + bool is_clipped, + bool context_opaque, + float draw_opacity, + int sorting_context_id, + gfx::Rect visible_quad_rect); + private: class PlaneResource { public: @@ -178,12 +197,30 @@ bool lost_resource); viz::ContextProvider* context_provider_; - ResourceProvider* resource_provider_; + LayerTreeResourceProvider* resource_provider_; const bool use_stream_video_draw_quad_; std::unique_ptr<media::PaintCanvasVideoRenderer> video_renderer_; std::vector<uint8_t> upload_pixels_; bool use_r16_for_testing_ = false; + VideoFrameExternalResources::ResourceType frame_resource_type_; + // TODO(danakj): Remove these, use TransferableResource for software path too. + unsigned software_resource_ = viz::kInvalidResourceId; + // Called once for |software_resource_|. + viz::ReleaseCallback software_release_callback_; + + float frame_resource_offset_; + float frame_resource_multiplier_; + uint32_t frame_bits_per_channel_; + + struct FrameResource { + FrameResource(viz::ResourceId id, gfx::Size size_in_pixels) + : id(id), size_in_pixels(size_in_pixels) {} + viz::ResourceId id; + gfx::Size size_in_pixels; + }; + std::vector<FrameResource> frame_resources_; + // Recycle resources so that we can reduce the number of allocations and // data transfers. ResourceList all_resources_;
diff --git a/cc/resources/video_resource_updater_unittest.cc b/cc/resources/video_resource_updater_unittest.cc index 5980c2e..e37c49d 100644 --- a/cc/resources/video_resource_updater_unittest.cc +++ b/cc/resources/video_resource_updater_unittest.cc
@@ -100,11 +100,14 @@ void SetUp() override { testing::Test::SetUp(); shared_bitmap_manager_.reset(new SharedBitmapManagerAllocationCounter()); - resource_provider3d_ = FakeResourceProvider::Create( - context_provider_.get(), shared_bitmap_manager_.get(), - high_bit_for_testing_); - resource_provider_software_ = FakeResourceProvider::Create( - nullptr, shared_bitmap_manager_.get(), high_bit_for_testing_); + resource_provider3d_ = + FakeResourceProvider::CreateLayerTreeResourceProvider( + context_provider_.get(), shared_bitmap_manager_.get(), nullptr, + high_bit_for_testing_); + resource_provider_software_ = + FakeResourceProvider::CreateLayerTreeResourceProvider( + nullptr, shared_bitmap_manager_.get(), nullptr, + high_bit_for_testing_); } scoped_refptr<media::VideoFrame> CreateTestYUVVideoFrame() { @@ -242,8 +245,8 @@ WebGraphicsContext3DUploadCounter* context3d_; scoped_refptr<TestContextProvider> context_provider_; std::unique_ptr<SharedBitmapManagerAllocationCounter> shared_bitmap_manager_; - std::unique_ptr<ResourceProvider> resource_provider3d_; - std::unique_ptr<ResourceProvider> resource_provider_software_; + std::unique_ptr<LayerTreeResourceProvider> resource_provider3d_; + std::unique_ptr<LayerTreeResourceProvider> resource_provider_software_; gpu::SyncToken release_sync_token_; bool high_bit_for_testing_ = false; };
diff --git a/cc/test/fake_resource_provider.h b/cc/test/fake_resource_provider.h index 01a3c16..d5b217e 100644 --- a/cc/test/fake_resource_provider.h +++ b/cc/test/fake_resource_provider.h
@@ -36,11 +36,13 @@ CreateLayerTreeResourceProvider( viz::ContextProvider* context_provider, viz::SharedBitmapManager* shared_bitmap_manager, - gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager = nullptr) { + gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager = nullptr, + bool high_bit_for_testing = false) { viz::ResourceSettings resource_settings; resource_settings.texture_id_allocation_chunk_size = 1; resource_settings.buffer_to_texture_target_map = viz::DefaultBufferToTextureTargetMapForTesting(); + resource_settings.high_bit_for_testing = high_bit_for_testing; return std::make_unique<LayerTreeResourceProvider>( context_provider, shared_bitmap_manager, gpu_memory_buffer_manager, true, resource_settings);
diff --git a/cc/trees/layer_tree_host_impl.cc b/cc/trees/layer_tree_host_impl.cc index 8a47cc3..92a9f016 100644 --- a/cc/trees/layer_tree_host_impl.cc +++ b/cc/trees/layer_tree_host_impl.cc
@@ -166,6 +166,9 @@ "Scheduling.%s.PendingTreeDuration"); DEFINE_SCOPED_UMA_HISTOGRAM_TIMER(PendingTreeRasterDurationHistogramTimer, "Scheduling.%s.PendingTreeRasterDuration"); +DEFINE_SCOPED_UMA_HISTOGRAM_TIMER( + ImageInvalidationUpdateDurationHistogramTimer, + "Scheduling.%s.ImageInvalidationUpdateDuration"); LayerTreeHostImpl::FrameData::FrameData() : render_surface_list(nullptr), @@ -396,15 +399,19 @@ // Defer invalidating images until UpdateDrawProperties is performed since // that updates whether an image should be animated based on its visibility // and the updated data for the image from the main frame. - PaintImageIdFlatSet images_to_invalidate = - tile_manager_.TakeImagesToInvalidateOnSyncTree(); - if (image_animation_controller_.has_value()) { - const auto& animated_images = - image_animation_controller_.value().AnimateForSyncTree( - CurrentBeginFrameArgs().frame_time); - images_to_invalidate.insert(animated_images.begin(), animated_images.end()); + { + ImageInvalidationUpdateDurationHistogramTimer image_invalidation_timer; + PaintImageIdFlatSet images_to_invalidate = + tile_manager_.TakeImagesToInvalidateOnSyncTree(); + if (image_animation_controller_.has_value()) { + const auto& animated_images = + image_animation_controller_.value().AnimateForSyncTree( + CurrentBeginFrameArgs().frame_time); + images_to_invalidate.insert(animated_images.begin(), + animated_images.end()); + } + sync_tree()->InvalidateRegionForImages(images_to_invalidate); } - sync_tree()->InvalidateRegionForImages(images_to_invalidate); // Start working on newly created tiles immediately if needed. // TODO(vmpstr): Investigate always having PrepareTiles issue
diff --git a/chrome/VERSION b/chrome/VERSION index 6fa60907a..5e161b3 100644 --- a/chrome/VERSION +++ b/chrome/VERSION
@@ -1,4 +1,4 @@ MAJOR=64 MINOR=0 -BUILD=3280 +BUILD=3281 PATCH=0
diff --git a/chrome/android/channel.gni b/chrome/android/channel.gni index 397f83a..6348bb9 100644 --- a/chrome/android/channel.gni +++ b/chrome/android/channel.gni
@@ -10,5 +10,5 @@ assert(android_channel == "default" || android_channel == "canary" || android_channel == "dev" || android_channel == "beta" || - android_channel == "stable" || android_channel == "work", + android_channel == "stable", "Invalid channel: " + android_channel)
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java b/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java index 875c8a4..c179ac8a 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java
@@ -186,6 +186,7 @@ "ContentSuggestionsThumbnailDominantColor"; public static final String CONTEXTUAL_SEARCH_ML_TAP_SUPPRESSION = "ContextualSearchMlTapSuppression"; + public static final String CONTEXTUAL_SEARCH_RANKER_QUERY = "ContextualSearchRankerQuery"; public static final String CONTEXTUAL_SUGGESTIONS_CAROUSEL = "ContextualSuggestionsCarousel"; public static final String COPYLESS_PASTE = "CopylessPaste"; public static final String CUSTOM_CONTEXT_MENU = "CustomContextMenu";
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/bookmarks/BookmarkItemsAdapter.java b/chrome/android/java/src/org/chromium/chrome/browser/bookmarks/BookmarkItemsAdapter.java index a62ac51..b8a60a2 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/bookmarks/BookmarkItemsAdapter.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/bookmarks/BookmarkItemsAdapter.java
@@ -50,7 +50,6 @@ private final List<List<? extends Object>> mSections; // The promo header section will always contain 0 or 1 elements. - @ViewType private final List<Integer> mPromoHeaderSection = new ArrayList<>(); private final List<BookmarkId> mFolderSection = new ArrayList<>(); private final List<BookmarkId> mBookmarkSection = new ArrayList<>();
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/browseractions/BrowserActionsContextMenuHelper.java b/chrome/android/java/src/org/chromium/chrome/browser/browseractions/BrowserActionsContextMenuHelper.java index ab21966..5922508 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/browseractions/BrowserActionsContextMenuHelper.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/browseractions/BrowserActionsContextMenuHelper.java
@@ -8,6 +8,7 @@ import android.app.PendingIntent; import android.app.PendingIntent.CanceledException; import android.app.ProgressDialog; +import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; @@ -19,6 +20,8 @@ import android.support.customtabs.browseractions.BrowserActionItem; import android.support.customtabs.browseractions.BrowserActionsIntent; import android.support.customtabs.browseractions.BrowserActionsIntent.BrowserActionsItemId; +import android.support.v4.content.res.ResourcesCompat; +import android.support.v7.content.res.AppCompatResources; import android.util.Pair; import android.util.SparseArray; import android.view.ContextMenu; @@ -27,7 +30,6 @@ import android.view.View.OnAttachStateChangeListener; import android.view.View.OnCreateContextMenuListener; -import org.chromium.base.ApiCompatibilityUtils; import org.chromium.base.Callback; import org.chromium.base.ContextUtils; import org.chromium.base.Log; @@ -219,10 +221,19 @@ Drawable drawable = null; if (resources != null && customItems.get(i).getIconId() != 0) { try { - drawable = ApiCompatibilityUtils.getDrawable( - resources, customItems.get(i).getIconId()); - } catch (NotFoundException e) { - Log.e(TAG, "Cannot get Drawable for %s", customItems.get(i).getTitle(), e); + drawable = ResourcesCompat.getDrawable( + resources, customItems.get(i).getIconId(), null); + } catch (NotFoundException e1) { + try { + Context context = mActivity.createPackageContext(sourcePackageName, + Context.CONTEXT_IGNORE_SECURITY | Context.CONTEXT_INCLUDE_CODE); + drawable = AppCompatResources.getDrawable( + context, customItems.get(i).getIconId()); + } catch (NameNotFoundException e2) { + Log.e(TAG, "Cannot find the package name %s", sourcePackageName, e2); + } catch (NotFoundException e3) { + Log.e(TAG, "Cannot get Drawable for %s", customItems.get(i).getTitle(), e3); + } } } items.add(
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelper.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelper.java index 25a0e178..de7c23a3 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelper.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelper.java
@@ -4,8 +4,9 @@ package org.chromium.chrome.browser.compositor.overlays.strip; -import static org.chromium.chrome.browser.compositor.layouts.ChromeAnimation.AnimatableAnimation.createAnimation; - +import android.animation.Animator; +import android.animation.AnimatorListenerAdapter; +import android.animation.AnimatorSet; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.Resources; @@ -24,9 +25,7 @@ import org.chromium.base.VisibleForTesting; import org.chromium.chrome.R; -import org.chromium.chrome.browser.compositor.layouts.ChromeAnimation; -import org.chromium.chrome.browser.compositor.layouts.ChromeAnimation.Animatable; -import org.chromium.chrome.browser.compositor.layouts.ChromeAnimation.Animation; +import org.chromium.chrome.browser.compositor.animation.CompositorAnimator; import org.chromium.chrome.browser.compositor.layouts.LayoutRenderHost; import org.chromium.chrome.browser.compositor.layouts.LayoutUpdateHost; import org.chromium.chrome.browser.compositor.layouts.components.CompositorButton; @@ -110,7 +109,7 @@ private StripLayoutTab[] mStripTabsToRender = new StripLayoutTab[0]; private final StripTabEventHandler mStripTabEventHandler = new StripTabEventHandler(); private final TabLoadTrackerCallback mTabLoadTrackerHost = new TabLoadTrackerCallbackImpl(); - private ChromeAnimation<Animatable<?>> mLayoutAnimations; + private Animator mRunningAnimator; private final CompositorButton mNewTabButton; @@ -440,7 +439,16 @@ * @return Whether or not animations are done. */ public boolean updateLayout(long time, long dt) { - final boolean doneAnimating = onUpdateAnimation(time, false); + // 1. Handle any Scroller movements (flings). + updateScrollOffset(time); + + // 2. Handle reordering automatically scrolling the tab strip. + handleReorderAutoScrolling(time); + + // 3. Update tab spinners. + updateSpinners(time); + + final boolean doneAnimating = mRunningAnimator == null || !mRunningAnimator.isRunning(); updateStrip(); // If this is the first layout pass, scroll to the selected tab so that it is visible. @@ -548,7 +556,12 @@ // 2. Start an animation for the newly created tab. StripLayoutTab tab = findTabById(id); - if (tab != null) startAnimation(buildTabCreatedAnimation(tab), true); + if (tab != null) { + finishAnimation(); + mRunningAnimator = CompositorAnimator.ofFloatProperty(mUpdateHost.getAnimationHandler(), + tab, StripLayoutTab.Y_OFFSET, tab.getHeight(), 0f, ANIM_TAB_CREATED_MS); + mRunningAnimator.start(); + } // 3. Figure out which tab needs to be visible. StripLayoutTab fastExpandTab = findTabById(prevId); @@ -818,11 +831,29 @@ } @Override - public void handleCloseButtonClick(StripLayoutTab tab, long time) { + public void handleCloseButtonClick(final StripLayoutTab tab, long time) { if (tab == null || tab.isDying()) return; // 1. Start the close animation. - startAnimation(buildTabClosedAnimation(tab), true); + finishAnimation(); + mRunningAnimator = CompositorAnimator.ofFloatProperty(mUpdateHost.getAnimationHandler(), + tab, StripLayoutTab.Y_OFFSET, tab.getOffsetY(), tab.getHeight(), + ANIM_TAB_CLOSED_MS); + + mRunningAnimator.addListener(new AnimatorListenerAdapter() { + @Override + public void onAnimationEnd(Animator animation) { + // Find out if we're closing the last tab. This determines if we resize + // immediately. + boolean lastTab = mStripTabs.length == 0 + || mStripTabs[mStripTabs.length - 1].getId() == tab.getId(); + + // Resize the tabs appropriately. + resizeTabStrip(!lastTab); + } + }); + + mRunningAnimator.start(); // 2. Set the dying state of the tab. tab.setIsDying(true); @@ -830,13 +861,6 @@ // 3. Fake a selection on the next tab now. Tab nextTab = mModel.getNextTabIfClosed(tab.getId()); if (nextTab != null) tabSelected(time, nextTab.getId(), tab.getId()); - - // 4. Find out if we're closing the last tab. This determines if we resize immediately. - boolean lastTab = - mStripTabs.length == 0 || mStripTabs[mStripTabs.length - 1].getId() == tab.getId(); - - // 5. Resize the tabs appropriately. - resizeTabStrip(!lastTab); } @Override @@ -894,50 +918,13 @@ } } - private boolean onUpdateAnimation(long time, boolean jumpToEnd) { - // 1. Handle any Scroller movements (flings). - if (!jumpToEnd) updateScrollOffset(time); - - // 2. Handle reordering automatically scrolling the tab strip. - handleReorderAutoScrolling(time); - - // 3. Handle layout-wide animations. - boolean update = false; - boolean finished = true; - if (mLayoutAnimations != null) { - if (jumpToEnd) { - finished = mLayoutAnimations.finished(); - } else { - finished = mLayoutAnimations.update(time); - } - if (jumpToEnd || finished) finishAnimation(); - - update = true; - } - - // 4. Handle tab-specific content animations. - for (int i = 0; i < mStripTabs.length; i++) { - if (jumpToEnd) mStripTabs[i].finishAnimation(); - } - - // 5. Update tab spinners. - updateSpinners(time); - - // 6. Stop any flings if we're trying to stop animations. - if (jumpToEnd) mScroller.forceFinished(true); - - // 7. Request another update if anything requires it. - if (update) mUpdateHost.requestUpdate(); - - return finished; - } - /** * @return Whether or not the tabs are moving. */ @VisibleForTesting public boolean isAnimating() { - return mLayoutAnimations != null || !mScroller.isFinished(); + return (mRunningAnimator != null && mRunningAnimator.isRunning()) + || !mScroller.isFinished(); } /** @@ -945,11 +932,11 @@ * {@link TabModel}. */ public void finishAnimation() { - if (mLayoutAnimations == null) return; + if (mRunningAnimator == null) return; // 1. Force any outstanding animations to finish. - mLayoutAnimations.updateAndFinish(); - mLayoutAnimations = null; + mRunningAnimator.end(); + mRunningAnimator = null; // 2. Figure out which tabs need to be closed. ArrayList<StripLayoutTab> tabsToRemove = new ArrayList<StripLayoutTab>(); @@ -966,23 +953,6 @@ if (!tabsToRemove.isEmpty()) mUpdateHost.requestUpdate(); } - private void startAnimation(Animation<Animatable<?>> animation, boolean finishPrevious) { - if (finishPrevious) finishAnimation(); - - if (mLayoutAnimations == null) { - mLayoutAnimations = new ChromeAnimation<ChromeAnimation.Animatable<?>>(); - } - - mLayoutAnimations.add(animation); - - mUpdateHost.requestUpdate(); - } - - private void cancelAnimation(StripLayoutTab tab, StripLayoutTab.Property property) { - if (mLayoutAnimations == null) return; - mLayoutAnimations.cancel(tab, property); - } - private void updateSpinners(long time) { long diff = time - mLastSpinnerUpdate; float degrees = diff * SPINNER_DPMS; @@ -1138,20 +1108,31 @@ // 4. Calculate the realistic tab width. mCachedTabWidth = MathUtils.clamp(optimalTabWidth, mMinTabWidth, mMaxTabWidth); - // 5. Propagate the tab width to all tabs. + // 5. Prepare animations and propagate width to all tabs. + finishAnimation(); + ArrayList<Animator> resizeAnimationList = null; + if (animate && !mAnimationsDisabledForTesting) resizeAnimationList = new ArrayList<>(); + for (int i = 0; i < mStripTabs.length; i++) { StripLayoutTab tab = mStripTabs[i]; if (tab.isDying()) continue; - // 5.a. Cancel any outstanding tab width animations. - cancelAnimation(mStripTabs[i], StripLayoutTab.Property.WIDTH); - - if (animate && !mAnimationsDisabledForTesting) { - startAnimation(buildTabResizeAnimation(tab, mCachedTabWidth), false); + if (resizeAnimationList != null) { + CompositorAnimator animator = CompositorAnimator.ofFloatProperty( + mUpdateHost.getAnimationHandler(), tab, StripLayoutTab.WIDTH, + tab.getWidth(), mCachedTabWidth, ANIM_TAB_RESIZE_MS); + resizeAnimationList.add(animator); } else { mStripTabs[i].setWidth(mCachedTabWidth); } } + + if (resizeAnimationList != null) { + AnimatorSet set = new AnimatorSet(); + set.playTogether(resizeAnimationList); + mRunningAnimator = set; + mRunningAnimator.start(); + } } private void updateStrip() { @@ -1377,7 +1358,11 @@ mInReorderMode = false; // 2. Clear any drag offset. - startAnimation(buildTabMoveAnimation(mInteractingTab, mInteractingTab.getOffsetX()), true); + finishAnimation(); + mRunningAnimator = CompositorAnimator.ofFloatProperty(mUpdateHost.getAnimationHandler(), + mInteractingTab, StripLayoutTab.X_OFFSET, mInteractingTab.getOffsetX(), 0f, + ANIM_TAB_MOVE_MS); + mRunningAnimator.start(); // 3. Request an update. mUpdateHost.requestUpdate(); @@ -1471,7 +1456,11 @@ final float animationLength = MathUtils.flipSignIf(direction * flipWidth, LocalizationUtils.isLayoutRtl()); StripLayoutTab slideTab = mStripTabs[newIndex - direction]; - startAnimation(buildTabMoveAnimation(slideTab, animationLength), true); + + finishAnimation(); + mRunningAnimator = CompositorAnimator.ofFloatProperty(mUpdateHost.getAnimationHandler(), + slideTab, StripLayoutTab.X_OFFSET, animationLength, 0f, ANIM_TAB_MOVE_MS); + mRunningAnimator.start(); } } @@ -1555,29 +1544,6 @@ } } - private static Animation<Animatable<?>> buildTabCreatedAnimation(StripLayoutTab tab) { - return createAnimation(tab, StripLayoutTab.Property.Y_OFFSET, tab.getHeight(), 0.f, - ANIM_TAB_CREATED_MS, 0, false, ChromeAnimation.getLinearInterpolator()); - } - - private static Animation<Animatable<?>> buildTabClosedAnimation(StripLayoutTab tab) { - return createAnimation(tab, StripLayoutTab.Property.Y_OFFSET, tab.getOffsetY(), - tab.getHeight(), ANIM_TAB_CLOSED_MS, 0, false, - ChromeAnimation.getLinearInterpolator()); - } - - private static Animation<Animatable<?>> buildTabResizeAnimation( - StripLayoutTab tab, float width) { - return createAnimation(tab, StripLayoutTab.Property.WIDTH, tab.getWidth(), width, - ANIM_TAB_RESIZE_MS, 0, false, ChromeAnimation.getLinearInterpolator()); - } - - private static Animation<Animatable<?>> buildTabMoveAnimation( - StripLayoutTab tab, float startX) { - return createAnimation(tab, StripLayoutTab.Property.X_OFFSET, startX, 0.f, ANIM_TAB_MOVE_MS, - 0, false, ChromeAnimation.getLinearInterpolator()); - } - private static <T> void moveElement(T[] array, int oldIndex, int newIndex) { if (oldIndex <= newIndex) { moveElementUp(array, oldIndex, newIndex);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutTab.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutTab.java index 7275aa08..7d9ea65f 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutTab.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutTab.java
@@ -14,7 +14,7 @@ import org.chromium.base.VisibleForTesting; import org.chromium.chrome.R; import org.chromium.chrome.browser.compositor.animation.CompositorAnimator; -import org.chromium.chrome.browser.compositor.layouts.ChromeAnimation; +import org.chromium.chrome.browser.compositor.animation.FloatProperty; import org.chromium.chrome.browser.compositor.layouts.LayoutRenderHost; import org.chromium.chrome.browser.compositor.layouts.LayoutUpdateHost; import org.chromium.chrome.browser.compositor.layouts.components.CompositorButton; @@ -34,9 +34,7 @@ * {@link StripLayoutTab} is used to keep track of the strip position and rendering information for * a particular tab so it can draw itself onto the GL canvas. */ -public class StripLayoutTab - implements ChromeAnimation.Animatable<StripLayoutTab.Property>, VirtualView { - +public class StripLayoutTab implements VirtualView { /** An observer interface for StripLayoutTab. */ public interface Observer { /** @param visible Whether the StripLayoutTab is visible. */ @@ -61,15 +59,47 @@ void handleCloseButtonClick(StripLayoutTab tab, long time); } - /** - * Animatable properties that can be used with a {@link ChromeAnimation.Animatable} on a - * {@link StripLayoutTab}. - */ - enum Property { - X_OFFSET, - Y_OFFSET, - WIDTH, - } + /** A property for animations to use for changing the X offset of the tab. */ + public static final FloatProperty<StripLayoutTab> X_OFFSET = + new FloatProperty<StripLayoutTab>("offsetX") { + @Override + public void setValue(StripLayoutTab object, float value) { + object.setOffsetX(value); + } + + @Override + public Float get(StripLayoutTab object) { + return object.getOffsetX(); + } + }; + + /** A property for animations to use for changing the Y offset of the tab. */ + public static final FloatProperty<StripLayoutTab> Y_OFFSET = + new FloatProperty<StripLayoutTab>("offsetY") { + @Override + public void setValue(StripLayoutTab object, float value) { + object.setOffsetY(value); + } + + @Override + public Float get(StripLayoutTab object) { + return object.getOffsetY(); + } + }; + + /** A property for animations to use for changing the width of the tab. */ + public static final FloatProperty<StripLayoutTab> WIDTH = + new FloatProperty<StripLayoutTab>("width") { + @Override + public void setValue(StripLayoutTab object, float value) { + object.setWidth(value); + } + + @Override + public Float get(StripLayoutTab object) { + return object.getHeight(); + } + }; // Behavior Constants private static final float VISIBILITY_FADE_CLOSE_BUTTON_PERCENTAGE = 0.99f; @@ -514,24 +544,6 @@ if (mButtonOpacityAnimation != null) mButtonOpacityAnimation.end(); } - @Override - public void setProperty(Property prop, float val) { - switch (prop) { - case X_OFFSET: - setOffsetX(val); - break; - case Y_OFFSET: - setOffsetY(val); - break; - case WIDTH: - setWidth(val); - break; - } - } - - @Override - public void onPropertyAnimationFinished(Property prop) {} - private void resetCloseRect() { RectF closeRect = getCloseRect(); mCloseButton.setWidth(closeRect.width());
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchFieldTrial.java b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchFieldTrial.java index 1876cf9..51a382e 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchFieldTrial.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchFieldTrial.java
@@ -81,11 +81,6 @@ private static final String DISABLE_PAGE_CONTENT_NOTIFICATION = "disable_page_content_notification"; - // -------------------------------------- - // Params that also exist in native code. - // -------------------------------------- - private static final String ENABLE_RANKER_INTEGRATION = "enable_ranker_integration"; - // Cached values to avoid repeated and redundant JNI operations. // TODO(donnd): consider creating a single Map to cache these static values. private static Boolean sEnabled; @@ -105,7 +100,6 @@ private static Boolean sIsOnlineDetectionDisabled; private static Boolean sIsAmpAsSeparateTabDisabled; private static Boolean sContextualSearchMlTapSuppressionEnabled; - private static Boolean sIsRankerIntegrationEnabled; private static Boolean sIsSendHomeCountryDisabled; private static Boolean sIsPageContentNotificationDisabled; private static Boolean sIsUkmRankerLoggingDisabled; @@ -362,30 +356,6 @@ } /** - * Whether Ranker integration is enabled or not, to apply machine intelligence for Tap gestures. - * This controls whether we call the Ranker logic to produce an inference or not, and may have - * no user-visible effect. There's a similar user-visible flag for whether Tap suppression is - * enabled or not, so call {@link #isRankerIntegrationOrMlTapSuppressionEnabled} in order to - * check if either is enabled. - * @return Whether Ranker will be used or not in this session, even for internal ranking. - */ - private static boolean isRankerIntegrationEnabled() { - if (sIsRankerIntegrationEnabled == null) { - sIsRankerIntegrationEnabled = getBooleanParam(ENABLE_RANKER_INTEGRATION); - } - return sIsRankerIntegrationEnabled; - } - - /** - * Whether Ranker integration or the user-visible flag for whether ML-based Tap suppression is - * enabled or not. - * @return Whether to apply Ranker ML in this session, even if only for internal ranking. - */ - static boolean isRankerIntegrationOrMlTapSuppressionEnabled() { - return isRankerIntegrationEnabled() || isContextualSearchMlTapSuppressionEnabled(); - } - - /** * Gets an amount to delay after a Tap gesture is recognized, in case some user gesture * immediately follows that would prevent the UI from showing. * The classic example is a scroll, which might be a signal that the previous tap was @@ -435,7 +405,6 @@ sContextualSearchMlTapSuppressionEnabled = ChromeFeatureList.isEnabled( ChromeFeatureList.CONTEXTUAL_SEARCH_ML_TAP_SUPPRESSION); } - return sContextualSearchMlTapSuppressionEnabled; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchSelectionController.java b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchSelectionController.java index fc8b6237..0c499cae 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchSelectionController.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchSelectionController.java
@@ -9,6 +9,7 @@ import org.chromium.base.VisibleForTesting; import org.chromium.chrome.browser.ChromeActivity; +import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.compositor.bottombar.OverlayPanel; import org.chromium.chrome.browser.preferences.ChromePreferenceManager; import org.chromium.chrome.browser.preferences.PrefServiceBridge; @@ -378,6 +379,11 @@ mLastTapState = null; } + // Make sure Tap Suppression features are consistent. + assert !ContextualSearchFieldTrial.isContextualSearchMlTapSuppressionEnabled() + || ChromeFeatureList.isEnabled(ChromeFeatureList.CONTEXTUAL_SEARCH_RANKER_QUERY) + : "Tap Suppression requires the Ranker Query feature to be enabled!"; + // If we're suppressing based on heuristics then Ranker doesn't need to know about it. @AssistRankerPrediction int tapPrediction = AssistRankerPrediction.UNDETERMINED;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java index 47f830b..279127bf 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java
@@ -233,6 +233,10 @@ private TabModelObserver mTabModelObserver = new EmptyTabModelObserver() { @Override public void didAddTab(Tab tab, TabLaunchType type) { + // Ensure that the PageLoadMetrics observer is attached in all cases, if in + // the future we do not go through initializeMainTab. ObserverList.addObserver + // will deduplicate additions, so it is safe to add both here as well as in + // initializeMainTab(). PageLoadMetrics.addObserver(mMetricsObserver); tab.addObserver(mTabObserver); } @@ -621,6 +625,9 @@ getApplication(), mSession, mIntentDataProvider.isOpenedByChrome()); mMetricsObserver = new PageLoadMetricsObserver(mConnection, mSession, tab); + // Immediately add the observer to PageLoadMetrics to catch early events that may + // be generated in the middle of tab initialization. + PageLoadMetrics.addObserver(mMetricsObserver); tab.addObserver(mTabObserver); prepareTabBackground(tab);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/feedback/FeedbackCollector.java b/chrome/android/java/src/org/chromium/chrome/browser/feedback/FeedbackCollector.java index d0004c9..47b0812 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/feedback/FeedbackCollector.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/feedback/FeedbackCollector.java
@@ -80,6 +80,7 @@ sources.add(new HistogramFeedbackSource(profile)); sources.add(new ChromeHomeFeedbackSource(profile)); sources.add(new LowEndDeviceFeedbackSource()); + sources.add(new IMEFeedbackSource()); return sources; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/feedback/HistogramFeedbackSource.java b/chrome/android/java/src/org/chromium/chrome/browser/feedback/HistogramFeedbackSource.java index 5953733..d0d6896 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/feedback/HistogramFeedbackSource.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/feedback/HistogramFeedbackSource.java
@@ -6,6 +6,8 @@ import android.util.Pair; +import org.chromium.base.SysUtils; +import org.chromium.base.metrics.JSONVerbosityLevel; import org.chromium.base.metrics.StatisticsRecorderAndroid; import org.chromium.chrome.browser.profiles.Profile; @@ -24,6 +26,10 @@ @Override public Pair<String, String> getLogs() { if (mIsOffTheRecord) return null; - return Pair.create(HISTOGRAMS_KEY, StatisticsRecorderAndroid.toJson()); + int jsonVerbosityLevel = JSONVerbosityLevel.JSON_VERBOSITY_LEVEL_FULL; + if (SysUtils.isLowEndDevice()) { + jsonVerbosityLevel = JSONVerbosityLevel.JSON_VERBOSITY_LEVEL_OMIT_BUCKETS; + } + return Pair.create(HISTOGRAMS_KEY, StatisticsRecorderAndroid.toJson(jsonVerbosityLevel)); } } \ No newline at end of file
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/feedback/IMEFeedbackSource.java b/chrome/android/java/src/org/chromium/chrome/browser/feedback/IMEFeedbackSource.java new file mode 100644 index 0000000..6878b4e --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/feedback/IMEFeedbackSource.java
@@ -0,0 +1,28 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.feedback; + +import android.provider.Settings; +import android.text.TextUtils; +import android.util.Pair; + +import org.chromium.base.CollectionUtil; +import org.chromium.base.ContextUtils; + +import java.util.Map; + +/** Grabs feedback about the default IME input method. */ +public class IMEFeedbackSource implements FeedbackSource { + IMEFeedbackSource() {} + + @Override + public Map<String, String> getFeedback() { + String imePackage = + Settings.Secure.getString(ContextUtils.getApplicationContext().getContentResolver(), + Settings.Secure.DEFAULT_INPUT_METHOD); + if (TextUtils.isEmpty(imePackage)) return null; + return CollectionUtil.newHashMap(Pair.create("Default IME", imePackage)); + } +} \ No newline at end of file
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/infobar/IPHInfoBarSupport.java b/chrome/android/java/src/org/chromium/chrome/browser/infobar/IPHInfoBarSupport.java index 5b2b168..94ee79c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/infobar/IPHInfoBarSupport.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/infobar/IPHInfoBarSupport.java
@@ -88,6 +88,9 @@ /** The state of the currently showing in-product window or {@code null} if none is showing. */ private PopupState mCurrentState; + /** Helper for tracking invalid calls to {@link #onDismiss()}. See crbug.com/786916. */ + private Throwable mLastDismissStack; + /** Creates a new instance of an IPHInfoBarSupport class. */ IPHInfoBarSupport(IPHBubbleDelegate delegate) { mDelegate = delegate; @@ -149,6 +152,9 @@ // PopupWindow.OnDismissListener implementation. @Override public void onDismiss() { + // Helper for crbug.com/786916 to catch why we are getting two dismiss calls in a row. + if (mCurrentState == null) throw new IllegalStateException(mLastDismissStack); + mLastDismissStack = new Exception(); assert mCurrentState != null; mDelegate.onPopupDismissed(mCurrentState); mCurrentState = null;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ntp/NewTabPage.java b/chrome/android/java/src/org/chromium/chrome/browser/ntp/NewTabPage.java index 9f751ff..34069d7e 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ntp/NewTabPage.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ntp/NewTabPage.java
@@ -49,6 +49,7 @@ import org.chromium.chrome.browser.tab.TabObserver; import org.chromium.chrome.browser.tabmodel.TabModelSelector; import org.chromium.chrome.browser.util.FeatureUtilities; +import org.chromium.chrome.browser.util.UrlUtilities; import org.chromium.chrome.browser.vr_shell.VrShellDelegate; import org.chromium.content_public.browser.NavigationController; import org.chromium.content_public.browser.NavigationEntry; @@ -56,6 +57,8 @@ import org.chromium.ui.base.DeviceFormFactor; import org.chromium.ui.mojom.WindowOpenDisposition; +import java.net.URI; +import java.net.URISyntaxException; import java.util.List; import java.util.concurrent.TimeUnit; @@ -149,10 +152,25 @@ * @return Whether the passed in URL is used to render the NTP. */ public static boolean isNTPUrl(String url) { - // Also handle the legacy chrome://newtab URL since that will redirect to + // Also handle the legacy chrome://newtab and about:newtab URLs since they will redirect to // chrome-native://newtab natively. - return url != null - && (url.startsWith(UrlConstants.NTP_URL) || url.startsWith("chrome://newtab")); + if (url == null) return false; + try { + // URL().getProtocol() throws MalformedURLException if the scheme is "invalid", + // including common ones like "about:", so it's not usable for isInternalScheme(). + URI uri = new URI(url); + if (!UrlUtilities.isInternalScheme(uri)) return false; + + String host = uri.getHost(); + if (host == null) { + // "about:newtab" would lead to null host. + uri = new URI(uri.getScheme() + "://" + uri.getSchemeSpecificPart()); + host = uri.getHost(); + } + return UrlConstants.NTP_HOST.equals(host); + } catch (URISyntaxException e) { + return false; + } } private class NewTabPageManagerImpl
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ntp/snippets/SnippetArticle.java b/chrome/android/java/src/org/chromium/chrome/browser/ntp/snippets/SnippetArticle.java index 25ccda1..008b29e 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ntp/snippets/SnippetArticle.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ntp/snippets/SnippetArticle.java
@@ -3,6 +3,7 @@ // found in the LICENSE file. package org.chromium.chrome.browser.ntp.snippets; +import android.annotation.SuppressLint; import android.graphics.drawable.Drawable; import android.support.annotation.ColorInt; import android.support.annotation.Nullable; @@ -88,6 +89,7 @@ /** * Creates a SnippetArticleListItem object that will hold the data. */ + @SuppressLint("SupportAnnotationUsage") // for ColorInt on an Integer rather than int or long public SnippetArticle(int category, String idWithinCategory, String title, String publisher, String url, long publishTimestamp, float score, long fetchTimestamp, boolean isVideoSuggestion, @ColorInt Integer thumbnailDominantColor) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/partnercustomizations/PartnerBrowserCustomizations.java b/chrome/android/java/src/org/chromium/chrome/browser/partnercustomizations/PartnerBrowserCustomizations.java index e032054f..6c224b6 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/partnercustomizations/PartnerBrowserCustomizations.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/partnercustomizations/PartnerBrowserCustomizations.java
@@ -22,6 +22,7 @@ import org.chromium.chrome.browser.ChromeSwitches; import org.chromium.chrome.browser.ChromeVersionInfo; import org.chromium.chrome.browser.UrlConstants; +import org.chromium.chrome.browser.ntp.NewTabPage; import org.chromium.chrome.browser.partnerbookmarks.PartnerBookmarksReader; import org.chromium.chrome.browser.util.UrlUtilities; @@ -350,9 +351,11 @@ @VisibleForTesting static boolean isValidHomepage(String url) { if (url == null) return false; - if (!UrlUtilities.isHttpOrHttps(url) - && !UrlConstants.CHROME_SCHEME.equals(Uri.parse(url).getScheme())) { - Log.w(TAG, "The scheme in homepage URL \"%s\" is not allowed.", url); + if (!UrlUtilities.isHttpOrHttps(url) && !NewTabPage.isNTPUrl(url)) { + Log.w(TAG, + "Partner homepage must be HTTP(S) or NewTabPage. " + + "Got invalid URL \"%s\"", + url); return false; } if (url.length() > HOMEPAGE_URL_MAX_LENGTH) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/survey/ChromeHomeSurveyController.java b/chrome/android/java/src/org/chromium/chrome/browser/survey/ChromeHomeSurveyController.java index d31764a..433988f2 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/survey/ChromeHomeSurveyController.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/survey/ChromeHomeSurveyController.java
@@ -6,12 +6,13 @@ import android.content.Context; import android.content.SharedPreferences; +import android.os.AsyncTask; import android.support.annotation.VisibleForTesting; import android.text.TextUtils; import org.chromium.base.CommandLine; import org.chromium.base.ContextUtils; -import org.chromium.base.StrictModeContext; +import org.chromium.base.ThreadUtils; import org.chromium.base.metrics.RecordUserAction; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeSwitches; @@ -31,6 +32,9 @@ import org.chromium.content_public.browser.WebContentsObserver; import org.chromium.ui.base.DeviceFormFactor; +import java.util.Calendar; +import java.util.Random; + /** * Class that controls if and when to show surveys related to the Chrome Home experiment. */ @@ -40,13 +44,16 @@ public static final String PARAM_NAME = "survey_override_site_id"; private static final String TRIAL_NAME = "ChromeHome"; + private static final String MAX_NUMBER = "MaxNumber"; static final long ONE_WEEK_IN_MILLIS = 604800000L; static final String SURVEY_INFOBAR_DISMISSED_KEY = "chrome_home_survey_info_bar_dismissed"; + static final String DATE_LAST_ROLLED_KEY = "chrome_home_date_last_rolled_for_survey"; private TabModelSelector mTabModelSelector; - private ChromeHomeSurveyController() { + @VisibleForTesting + ChromeHomeSurveyController() { // Empty constructor. } @@ -57,12 +64,11 @@ * shown. */ public static void initialize(Context context, TabModelSelector tabModelSelector) { - new ChromeHomeSurveyController().startDownload(context, tabModelSelector); + new StartDownloadIfEligibleTask(new ChromeHomeSurveyController(), context, tabModelSelector) + .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } private void startDownload(Context context, TabModelSelector tabModelSelector) { - if (!doesUserQualifyForSurvey()) return; - mTabModelSelector = tabModelSelector; SurveyController surveyController = SurveyController.getInstance(); @@ -86,15 +92,14 @@ } private boolean doesUserQualifyForSurvey() { - if (CommandLine.getInstance().hasSwitch(ChromeSwitches.CHROME_HOME_FORCE_ENABLE_SURVEY)) { - return true; - } if (DeviceFormFactor.isTablet()) return false; if (!isUMAEnabled()) return false; if (AccessibilityUtil.isAccessibilityEnabled()) return false; if (hasInfoBarBeenDisplayed()) return false; if (!FeatureUtilities.isChromeHomeEnabled()) return true; - return wasChromeHomeEnabledForMinimumOneWeek(); + return wasChromeHomeEnabledForMinimumOneWeek() + || CommandLine.getInstance().hasSwitch( + ChromeSwitches.CHROME_HOME_FORCE_ENABLE_SURVEY); } private void onSurveyAvailable(String siteId) { @@ -133,35 +138,30 @@ } private boolean isUMAEnabled() { - try (StrictModeContext unused = StrictModeContext.allowDiskReads()) { - return PrivacyPreferencesManager.getInstance() - .isUsageAndCrashReportingPermittedByUser(); - } + return PrivacyPreferencesManager.getInstance().isUsageAndCrashReportingPermittedByUser(); } private void showSurveyInfoBar(WebContents webContents, String siteId) { SurveyInfoBar.showSurveyInfoBar( webContents, siteId, true, R.drawable.chrome_sync_logo, getSurveyInfoBarDelegate()); SharedPreferences sharedPreferences = ContextUtils.getAppSharedPreferences(); - sharedPreferences.edit().putBoolean(SURVEY_INFO_BAR_DISPLAYED_KEY, true).apply(); + sharedPreferences.edit() + .putLong(SURVEY_INFO_BAR_DISPLAYED_KEY, System.currentTimeMillis()) + .apply(); } @VisibleForTesting boolean hasInfoBarBeenDisplayed() { - try (StrictModeContext unused = StrictModeContext.allowDiskReads()) { - SharedPreferences sharedPreferences = ContextUtils.getAppSharedPreferences(); - return sharedPreferences.getBoolean(SURVEY_INFO_BAR_DISPLAYED_KEY, false); - } + SharedPreferences sharedPreferences = ContextUtils.getAppSharedPreferences(); + return sharedPreferences.getLong(SURVEY_INFO_BAR_DISPLAYED_KEY, -1L) != -1L; } @VisibleForTesting boolean wasChromeHomeEnabledForMinimumOneWeek() { - try (StrictModeContext unused = StrictModeContext.allowDiskReads()) { - SharedPreferences sharedPreferences = ContextUtils.getAppSharedPreferences(); - long earliestLoggedDate = sharedPreferences.getLong( - ChromePreferenceManager.CHROME_HOME_SHARED_PREFERENCES_KEY, Long.MAX_VALUE); - if (System.currentTimeMillis() - earliestLoggedDate >= ONE_WEEK_IN_MILLIS) return true; - } + SharedPreferences sharedPreferences = ContextUtils.getAppSharedPreferences(); + long earliestLoggedDate = sharedPreferences.getLong( + ChromePreferenceManager.CHROME_HOME_SHARED_PREFERENCES_KEY, Long.MAX_VALUE); + if (System.currentTimeMillis() - earliestLoggedDate >= ONE_WEEK_IN_MILLIS) return true; return false; } @@ -176,6 +176,52 @@ } /** + * Rolls a random number to see if the user was eligible for the survey + * @return Whether the user is eligible (i.e. the random number rolled was 0). + */ + @VisibleForTesting + boolean isRandomlySelectedForSurvey() { + SharedPreferences preferences = ContextUtils.getAppSharedPreferences(); + int lastDate = preferences.getInt(DATE_LAST_ROLLED_KEY, -1); + int today = getDayOfYear(); + if (lastDate == today) return false; + + int maxNumber = getMaxNumber(); + if (maxNumber == -1) return false; + + preferences.edit().putInt(DATE_LAST_ROLLED_KEY, today).apply(); + return getRandomNumberUpTo(maxNumber) == 0; + } + + /** + * @param max The max threshold for the random number generator. + * @return A random number from 0 (inclusive) to the max number (exclusive). + */ + @VisibleForTesting + int getRandomNumberUpTo(int max) { + return new Random().nextInt(max); + } + + /** @return The max number as stated in the finch config. */ + @VisibleForTesting + int getMaxNumber() { + try { + String number = VariationsAssociatedData.getVariationParamValue(TRIAL_NAME, MAX_NUMBER); + if (TextUtils.isEmpty(number)) return -1; + return Integer.parseInt(number); + } catch (NumberFormatException e) { + return -1; + } + } + + /** @return The day of the year for today. */ + @VisibleForTesting + int getDayOfYear() { + ThreadUtils.assertOnBackgroundThread(); + return Calendar.getInstance().get(Calendar.DAY_OF_YEAR); + } + + /** * @return The survey info bar delegate containing actions specific to the Chrome Home survey. */ private SurveyInfoBarDelegate getSurveyInfoBarDelegate() { @@ -199,4 +245,30 @@ } }; } + + static class StartDownloadIfEligibleTask extends AsyncTask<Void, Void, Boolean> { + final ChromeHomeSurveyController mController; + final Context mContext; + final TabModelSelector mSelector; + + public StartDownloadIfEligibleTask(ChromeHomeSurveyController controller, Context context, + TabModelSelector tabModelSelector) { + mController = controller; + mContext = context; + mSelector = tabModelSelector; + } + + @Override + protected Boolean doInBackground(Void... params) { + if (!mController.doesUserQualifyForSurvey()) return false; + return mController.isRandomlySelectedForSurvey() + || CommandLine.getInstance().hasSwitch( + ChromeSwitches.CHROME_HOME_FORCE_ENABLE_SURVEY); + } + + @Override + protected void onPostExecute(Boolean result) { + if (result) mController.startDownload(mContext, mSelector); + } + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarTablet.java b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarTablet.java index 89c49050..f249fc4 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarTablet.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarTablet.java
@@ -552,14 +552,14 @@ @Override public boolean useLightDrawables() { - return mUseLightColorAssets; + return mUseLightColorAssets != null && mUseLightColorAssets; } @Override public void showAppMenuUpdateBadge() { super.showAppMenuUpdateBadge(); if (!mIsInTabSwitcherMode) { - if (mUseLightColorAssets) { + if (mUseLightColorAssets != null && mUseLightColorAssets) { setAppMenuUpdateBadgeDrawable(mUseLightColorAssets); } setAppMenuUpdateBadgeToVisible(true);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/bottomsheet/BottomSheet.java b/chrome/android/java/src/org/chromium/chrome/browser/widget/bottomsheet/BottomSheet.java index 73677eca..51be483 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/widget/bottomsheet/BottomSheet.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/widget/bottomsheet/BottomSheet.java
@@ -1316,6 +1316,8 @@ tracker.notifyEvent(EventConstants.BOTTOM_SHEET_EXPANDED_FROM_SWIPE); } else if (reason == StateChangeReason.EXPAND_BUTTON) { tracker.notifyEvent(EventConstants.BOTTOM_SHEET_EXPANDED_FROM_BUTTON); + } else if (reason == StateChangeReason.OMNIBOX_FOCUS) { + tracker.notifyEvent(EventConstants.BOTTOM_SHEET_EXPANDED_FROM_OMNIBOX_FOCUS); } } @@ -1845,7 +1847,8 @@ if (!fromMenu && !showRefreshIph && !showColdStartIph) return; // Determine which strings to use. - boolean showExpandButtonHelpBubble = mDefaultToolbarView.isUsingExpandButton(); + boolean showExpandButtonHelpBubble = + !showRefreshIph && mDefaultToolbarView.isUsingExpandButton(); View anchorView = showExpandButtonHelpBubble ? mControlContainer.findViewById(R.id.expand_sheet_button) : mControlContainer; @@ -1853,6 +1856,9 @@ : showExpandButtonHelpBubble ? R.string.bottom_sheet_accessibility_expand_button_help_bubble_message : R.string.bottom_sheet_help_bubble_message; + int accessibilityStringId = showRefreshIph + ? R.string.bottom_sheet_pull_to_refresh_help_bubble_accessibility_message + : stringId; // Register an overview mode observer so the bubble can be dismissed if overview mode // is shown. @@ -1869,7 +1875,8 @@ mFullscreenManager.getBrowserVisibilityDelegate().showControlsPersistent(); // Create the help bubble and setup dismissal behavior. - mHelpBubble = new ViewAnchoredTextBubble(getContext(), anchorView, stringId, stringId); + mHelpBubble = new ViewAnchoredTextBubble( + getContext(), anchorView, stringId, accessibilityStringId); if (ChromeFeatureList.isEnabled(ChromeFeatureList.CHROME_HOME_PERSISTENT_IPH)) { int dismissTimeout = ChromeFeatureList.getFieldTrialParamByFeatureAsInt(
diff --git a/chrome/android/java/strings/android_chrome_strings.grd b/chrome/android/java/strings/android_chrome_strings.grd index 6ed35ae..bcc0dc7cf 100644 --- a/chrome/android/java/strings/android_chrome_strings.grd +++ b/chrome/android/java/strings/android_chrome_strings.grd
@@ -558,11 +558,11 @@ <message name="IDS_SAFE_BROWSING_SUMMARY" desc="Summary for safe browsing."> Protect you and your device from dangerous sites </message> - <message name="IDS_NETWORK_PREDICTIONS_TITLE" desc="Title of a setting in Chrome settings. Followed by a body that describes what pages are downloaded. If setting is turned on, Chrome will download certain pages to the user’s phone automatically for offline reading. “Download” is a verb, imperative. "> - Automatically download pages + <message name="IDS_NETWORK_PREDICTIONS_TITLE" desc="Title of a setting in Chrome settings. Followed by a body that describes the setting. If setting is turned on, Chrome will download certain pages to the user’s phone automatically for offline reading. 'predictions' convey the idea that Chrome is using predictive models to figure out pages likely of interest to the user."> + Use page predictions </message> - <message name="IDS_NETWORK_PREDICTIONS_SUMMARY" desc="Body text for the “Automatically download pages” setting in Chrome settings. Describes what happens if the setting is turned on. Load pages refers to how quickly website pages load. Offline reading refers to the ability to access the pages without a network connection."> - Load pages more quickly and save popular pages for offline reading + <message name="IDS_NETWORK_PREDICTIONS_SUMMARY" desc="Body text for the “Use page predictions” setting in Chrome settings. Describes what happens if the setting is turned on. 'Preload' conveys the idea that Chrome is getting pages for the user without their explicit interaction or consent."> + Preload pages for faster loading and offline reading </message> <message name="IDS_CONTEXTUAL_SEARCH_TITLE" desc="Name for the Contextual Search feature, which allows users to search for a term in a web page by tapping on it."> Touch to Search @@ -3163,8 +3163,11 @@ <message name="IDS_BOTTOM_SHEET_HELP_BUBBLE_MESSAGE" desc="Text displayed in a help bubble above the bottom navigation sheet prompting users to pull the sheet up to see their bookmarks and other content."> Pull up to see bookmarks and more </message> - <message name="IDS_BOTTOM_SHEET_PULL_TO_REFRESH_HELP_BUBBLE_MESSAGE" desc="Text displayed in a help bubble above the toolbar after the user performs a pull-to-refresh action." translateable="false"> - The address bar is now easy to reach at the bottom of your screen + <message name="IDS_BOTTOM_SHEET_PULL_TO_REFRESH_HELP_BUBBLE_MESSAGE" desc="Text displayed in a help bubble above the address bar. “access” is a verb (imperative). The intent of the string is to help users find the address bar at the bottom of the screen."> + Access the address bar here + </message> + <message name="IDS_BOTTOM_SHEET_PULL_TO_REFRESH_HELP_BUBBLE_ACCESSIBILITY_MESSAGE" desc="Text displayed in a help bubble above the address bar when TalkBack is enabled. “access” is a verb (imperative). The intent of the string is to help users find the address bar at the bottom of the screen."> + Access the address bar at the bottom of your screen </message> <message name="IDS_BOTTOM_SHEET_ACCESSIBILITY_EXPAND_BUTTON_HELP_BUBBLE_MESSAGE" desc="Text displayed in a help bubble above the toolbar expand button prompting users to tap the button to see their bookmarks and other content when accessibility is enabled."> Tap to see downloads, bookmarks, and history
diff --git a/chrome/android/java_sources.gni b/chrome/android/java_sources.gni index ddb3f422..a3dc889 100644 --- a/chrome/android/java_sources.gni +++ b/chrome/android/java_sources.gni
@@ -416,6 +416,7 @@ "java/src/org/chromium/chrome/browser/feedback/FeedbackReporter.java", "java/src/org/chromium/chrome/browser/feedback/FeedbackSource.java", "java/src/org/chromium/chrome/browser/feedback/HistogramFeedbackSource.java", + "java/src/org/chromium/chrome/browser/feedback/IMEFeedbackSource.java", "java/src/org/chromium/chrome/browser/feedback/LowEndDeviceFeedbackSource.java", "java/src/org/chromium/chrome/browser/feedback/ScreenshotSource.java", "java/src/org/chromium/chrome/browser/feedback/ScreenshotTask.java",
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/bookmarks/BookmarkPersonalizedSigninPromoTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/bookmarks/BookmarkPersonalizedSigninPromoTest.java index dffd4af..51cedb35 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/bookmarks/BookmarkPersonalizedSigninPromoTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/bookmarks/BookmarkPersonalizedSigninPromoTest.java
@@ -31,6 +31,7 @@ import org.chromium.base.ThreadUtils; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.DisableIf; +import org.chromium.base.test.util.DisabledTest; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.ChromeSwitches; @@ -84,6 +85,7 @@ @Test @LargeTest @DisableIf.Device(type = {UiDisableIf.TABLET}) // https://crbug.com/776405. + @DisabledTest(message = "Flaky. See crbug.com/789531") public void testAutoDismissPromo() throws Exception { int impressionCap = SigninPromoController.getMaxImpressionsBookmarksForTests(); for (int impression = 0; impression < impressionCap; impression++) {
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/browseractions/BrowserActionActivityTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/browseractions/BrowserActionActivityTest.java index 66ba97c..285ae4d 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/browseractions/BrowserActionActivityTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/browseractions/BrowserActionActivityTest.java
@@ -219,12 +219,7 @@ i))); } Assert.assertNotNull(contextMenuItems.get(5).getDrawable(context)); - // Vector Drawable is not supported on pre-L so the icon will be null. - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - Assert.assertNotNull(contextMenuItems.get(6).getDrawable(context)); - } else { - Assert.assertNull(contextMenuItems.get(6).getDrawable(context)); - } + Assert.assertNotNull(contextMenuItems.get(6).getDrawable(context)); Assert.assertNull(contextMenuItems.get(7).getDrawable(context)); Assert.assertNull(contextMenuItems.get(8).getDrawable(context)); }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabActivityTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabActivityTest.java index 3cfc4da6..c5e6f82 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabActivityTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabActivityTest.java
@@ -1178,16 +1178,20 @@ final AtomicReference<Long> firstContentfulPaintMs = new AtomicReference<>(-1L); final AtomicReference<Long> activityStartTimeMs = new AtomicReference<>(-1L); final AtomicReference<Long> loadEventStartMs = new AtomicReference<>(-1L); + final AtomicReference<Boolean> sawNetworkQualityEstimates = new AtomicReference<>(false); CustomTabsCallback cb = new CustomTabsCallback() { @Override public void extraCallback(String callbackName, Bundle args) { Assert.assertEquals(CustomTabsConnection.PAGE_LOAD_METRICS_CALLBACK, callbackName); + if (-1 != args.getLong(PageLoadMetrics.EFFECTIVE_CONNECTION_TYPE, -1)) { + sawNetworkQualityEstimates.set(true); + } + long navigationStart = args.getLong(PageLoadMetrics.NAVIGATION_START, -1); if (navigationStart == -1) { - // Return if the callback just had network quality information, which - // isn't tested. + // Untested metric callback. return; } long current = SystemClock.uptimeMillis(); @@ -1231,6 +1235,12 @@ return loadEventStartMs.get() > 0; } }); + CriteriaHelper.pollInstrumentationThread(new Criteria() { + @Override + public boolean isSatisfied() { + return sawNetworkQualityEstimates.get(); + } + }); } catch (InterruptedException e) { Assert.fail(); }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/download/DownloadActivityTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/download/DownloadActivityTest.java index cd2458e..9ae60bb 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/download/DownloadActivityTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/download/DownloadActivityTest.java
@@ -139,7 +139,6 @@ @Test @MediumTest - @RetryOnFailure(message = "crbug.com/751492") public void testSpaceDisplay() throws Exception { // This first check is a Criteria because initialization of the Adapter is asynchronous. CriteriaHelper.pollUiThread(new Criteria() { @@ -156,7 +155,14 @@ ThreadUtils.runOnUiThread(() -> mAdapter.onDownloadItemCreated(updateItem)); mAdapterObserver.onChangedCallback.waitForCallback(callCount, 2); mAdapterObserver.onSpaceDisplayUpdatedCallback.waitForCallback(spaceDisplayCallCount); - Assert.assertEquals("6.50 GB downloaded", mSpaceUsedDisplay.getText()); + // Use Criteria here because the text for SpaceDisplay is updated through an AsyncTask. + // Same for the checks below. + CriteriaHelper.pollUiThread(new Criteria() { + @Override + public boolean isSatisfied() { + return TextUtils.equals("6.50 GB downloaded", mSpaceUsedDisplay.getText()); + } + }); // Mark one download as deleted on disk, which should prevent it from being counted. callCount = mAdapterObserver.onChangedCallback.getCallCount(); @@ -166,7 +172,12 @@ ThreadUtils.runOnUiThread(() -> mAdapter.onDownloadItemUpdated(deletedItem)); mAdapterObserver.onChangedCallback.waitForCallback(callCount, 2); mAdapterObserver.onSpaceDisplayUpdatedCallback.waitForCallback(spaceDisplayCallCount); - Assert.assertEquals("5.50 GB downloaded", mSpaceUsedDisplay.getText()); + CriteriaHelper.pollUiThread(new Criteria() { + @Override + public boolean isSatisfied() { + return TextUtils.equals("5.50 GB downloaded", mSpaceUsedDisplay.getText()); + } + }); // Say that the offline page has been deleted. callCount = mAdapterObserver.onChangedCallback.getCallCount(); @@ -178,7 +189,12 @@ deletedPage.id)); mAdapterObserver.onChangedCallback.waitForCallback(callCount, 2); mAdapterObserver.onSpaceDisplayUpdatedCallback.waitForCallback(spaceDisplayCallCount); - Assert.assertEquals("512.00 MB downloaded", mSpaceUsedDisplay.getText()); + CriteriaHelper.pollUiThread(new Criteria() { + @Override + public boolean isSatisfied() { + return TextUtils.equals("512.00 MB downloaded", mSpaceUsedDisplay.getText()); + } + }); } /** Clicking on filters affects various things in the UI. */
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/notifications/NotificationPlatformBridgeTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/notifications/NotificationPlatformBridgeTest.java index 7bcf7d5..38d9f7b6 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/notifications/NotificationPlatformBridgeTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/notifications/NotificationPlatformBridgeTest.java
@@ -4,6 +4,8 @@ package org.chromium.chrome.browser.notifications; +import static org.junit.Assert.assertThat; + import static org.chromium.base.test.util.ScalableTimeout.scaleTimeout; import android.annotation.TargetApi; @@ -21,6 +23,7 @@ import android.support.test.filters.LargeTest; import android.support.test.filters.MediumTest; +import org.hamcrest.Matchers; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; @@ -34,6 +37,7 @@ import org.chromium.base.test.util.Feature; import org.chromium.base.test.util.MinAndroidSdkLevel; import org.chromium.base.test.util.RetryOnFailure; +import org.chromium.base.test.util.UserActionTester; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeSwitches; import org.chromium.chrome.browser.engagement.SiteEngagementService; @@ -53,6 +57,8 @@ import org.chromium.content.browser.test.util.CriteriaHelper; import java.net.URL; +import java.util.ArrayList; +import java.util.Iterator; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; @@ -343,6 +349,8 @@ mNotificationTestRule.setNotificationContentSettingForCurrentOrigin(ContentSetting.ALLOW); Context context = InstrumentationRegistry.getTargetContext(); + UserActionTester actionTester = new UserActionTester(); + // +5 engagement from notification permission and +0.5 from navigating to the test page. Assert.assertEquals(5.5, getEngagementScoreBlocking(), 0); Notification notification = mNotificationTestRule.showAndGetNotification("MyNotification", @@ -364,6 +372,11 @@ // Expect +1 engagement from interacting with the notification. waitForTitle("reply: My Reply"); Assert.assertEquals(6.5, getEngagementScoreBlocking(), 0); + + // Replies are always delivered to an action button. + assertThat(actionTester.toString(), getNotificationActions(actionTester), + Matchers.contains("Notifications.Persistent.Shown", + "Notifications.Persistent.ClickedActionButton")); } /** @@ -692,6 +705,8 @@ // +5 engagement from notification permission and +0.5 from navigating to the test page. Assert.assertEquals(5.5, getEngagementScoreBlocking(), 0); + UserActionTester actionTester = new UserActionTester(); + Notification notification = mNotificationTestRule.showAndGetNotification("MyNotification", "{}"); @@ -712,6 +727,11 @@ RecordHistogram.getHistogramTotalCountForTesting( "Notifications.Android.JobStartDelay")); } + + // Clicking on a notification should record the right user metrics. + assertThat(actionTester.toString(), getNotificationActions(actionTester), + Matchers.contains( + "Notifications.Persistent.Shown", "Notifications.Persistent.Clicked")); } /** @@ -859,4 +879,18 @@ // Expect +1 engagement from interacting with the notification. Assert.assertEquals(7.5, getEngagementScoreBlocking(), 0); } + + /** + * Get Notification related actions, filter all other actions to avoid flakes. + */ + private List<String> getNotificationActions(UserActionTester actionTester) { + List<String> actions = new ArrayList<>(actionTester.getActions()); + Iterator<String> it = actions.iterator(); + while (it.hasNext()) { + if (!it.next().startsWith("Notifications.")) { + it.remove(); + } + } + return actions; + } }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestServiceWorkerPaymentAppTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestServiceWorkerPaymentAppTest.java index cca27472..9baf5ee 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestServiceWorkerPaymentAppTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestServiceWorkerPaymentAppTest.java
@@ -13,6 +13,7 @@ import org.junit.runner.RunWith; import org.chromium.base.test.util.CommandLineFlags; +import org.chromium.base.test.util.DisabledTest; import org.chromium.base.test.util.Feature; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeFeatureList; @@ -328,6 +329,7 @@ @Test @MediumTest @Feature({"Payments"}) + @DisabledTest(message = "Flaky. See crbug.com/789532") public void testCallCanMakePayment() throws InterruptedException, ExecutionException, TimeoutException { String[] supportedMethodNames = {"https://bobpay.com", "basic-card"};
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/printing/PrintingControllerTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/printing/PrintingControllerTest.java index e953bf3c5..72f9ba5 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/printing/PrintingControllerTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/printing/PrintingControllerTest.java
@@ -4,6 +4,7 @@ package org.chromium.chrome.browser.printing; +import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.os.Build; import android.os.CancellationSignal; @@ -26,6 +27,7 @@ import org.chromium.base.test.util.CallbackHelper; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.Feature; +import org.chromium.base.test.util.MinAndroidSdkLevel; import org.chromium.base.test.util.RetryOnFailure; import org.chromium.base.test.util.TestFileUtil; import org.chromium.base.test.util.UrlUtils; @@ -54,6 +56,8 @@ */ @RunWith(ChromeJUnit4ClassRunner.class) @RetryOnFailure +@SuppressLint("NewApi") +@MinAndroidSdkLevel(Build.VERSION_CODES.KITKAT) @CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE, ChromeActivityTestRule.DISABLE_NETWORK_PREDICTION_FLAG}) public class PrintingControllerTest {
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/partnercustomizations/PartnerBrowserCustomizationsUnitTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/partnercustomizations/PartnerBrowserCustomizationsUnitTest.java index 86caf6c..8341efc 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/partnercustomizations/PartnerBrowserCustomizationsUnitTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/partnercustomizations/PartnerBrowserCustomizationsUnitTest.java
@@ -21,10 +21,26 @@ @Test @Feature({"Homepage"}) public void testIsValidHomepage() { + Assert.assertTrue(PartnerBrowserCustomizations.isValidHomepage( + "chrome-native://newtab/path#fragment")); + Assert.assertTrue(PartnerBrowserCustomizations.isValidHomepage("chrome-native://newtab/")); + Assert.assertTrue(PartnerBrowserCustomizations.isValidHomepage("chrome-native://newtab")); Assert.assertTrue(PartnerBrowserCustomizations.isValidHomepage("chrome://newtab")); + Assert.assertTrue(PartnerBrowserCustomizations.isValidHomepage("about://newtab")); + Assert.assertTrue(PartnerBrowserCustomizations.isValidHomepage("about:newtab")); + Assert.assertTrue( + PartnerBrowserCustomizations.isValidHomepage("about:newtab/path#fragment")); Assert.assertTrue(PartnerBrowserCustomizations.isValidHomepage("http://example.com")); Assert.assertTrue(PartnerBrowserCustomizations.isValidHomepage("https:example.com")); + Assert.assertFalse(PartnerBrowserCustomizations.isValidHomepage("chrome://newtab--not")); + Assert.assertFalse(PartnerBrowserCustomizations.isValidHomepage("about:newtab--not")); + Assert.assertFalse(PartnerBrowserCustomizations.isValidHomepage("chrome://history")); + Assert.assertFalse(PartnerBrowserCustomizations.isValidHomepage("chrome://")); + Assert.assertFalse(PartnerBrowserCustomizations.isValidHomepage("chrome:")); + Assert.assertFalse(PartnerBrowserCustomizations.isValidHomepage("chrome")); + Assert.assertFalse( + PartnerBrowserCustomizations.isValidHomepage("chrome-native://bookmarks")); Assert.assertFalse(PartnerBrowserCustomizations.isValidHomepage("example.com")); Assert.assertFalse(PartnerBrowserCustomizations.isValidHomepage( "content://com.android.providers.media.documents/document/video:113"));
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/survey/ChromeHomeSurveyControllerTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/survey/ChromeHomeSurveyControllerTest.java index 8e94c5d..22688ced 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/survey/ChromeHomeSurveyControllerTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/survey/ChromeHomeSurveyControllerTest.java
@@ -59,11 +59,12 @@ @Test public void testInfoBarDisplayedBefore() { - Assert.assertFalse(mController.hasInfoBarBeenDisplayed()); Assert.assertFalse(mSharedPreferences.contains( ChromeHomeSurveyController.SURVEY_INFO_BAR_DISPLAYED_KEY)); + Assert.assertFalse(mController.hasInfoBarBeenDisplayed()); mSharedPreferences.edit() - .putBoolean(ChromeHomeSurveyController.SURVEY_INFO_BAR_DISPLAYED_KEY, true) + .putLong(ChromeHomeSurveyController.SURVEY_INFO_BAR_DISPLAYED_KEY, + System.currentTimeMillis()) .apply(); Assert.assertTrue(mController.hasInfoBarBeenDisplayed()); } @@ -123,4 +124,68 @@ verify(mTab, times(1)).getWebContents(); verify(mTab, never()).isIncognito(); } + + @Test + public void testEligibilityRolledYesterday() { + mController = new RiggedSurveyController(0, 5, 10); + mSharedPreferences.edit().putInt(ChromeHomeSurveyController.DATE_LAST_ROLLED_KEY, 4); + Assert.assertTrue(mController.isRandomlySelectedForSurvey()); + } + + @Test + public void testEligibilityRollingTwiceSameDay() { + mController = new RiggedSurveyController(0, 5, 10); + mSharedPreferences.edit() + .putInt(ChromeHomeSurveyController.DATE_LAST_ROLLED_KEY, 5) + .apply(); + Assert.assertFalse(mController.isRandomlySelectedForSurvey()); + } + + @Test + public void testEligibilityFirstTimeRollingQualifies() { + mController = new RiggedSurveyController(0, 5, 10); + Assert.assertFalse( + mSharedPreferences.contains(ChromeHomeSurveyController.DATE_LAST_ROLLED_KEY)); + Assert.assertTrue(mController.isRandomlySelectedForSurvey()); + Assert.assertEquals( + 5, mSharedPreferences.getInt(ChromeHomeSurveyController.DATE_LAST_ROLLED_KEY, -1)); + } + + @Test + public void testEligibilityFirstTimeRollingDoesNotQualify() { + mController = new RiggedSurveyController(5, 1, 10); + Assert.assertFalse( + mSharedPreferences.contains(ChromeHomeSurveyController.DATE_LAST_ROLLED_KEY)); + Assert.assertFalse(mController.isRandomlySelectedForSurvey()); + Assert.assertEquals( + 1, mSharedPreferences.getInt(ChromeHomeSurveyController.DATE_LAST_ROLLED_KEY, -1)); + } + + class RiggedSurveyController extends ChromeHomeSurveyController { + int mRandomNumberToReturn; + int mDayOfYear; + int mMaxNumber; + + RiggedSurveyController(int randomNumberToReturn, int dayOfYear, int maxNumber) { + super(); + mRandomNumberToReturn = randomNumberToReturn; + mDayOfYear = dayOfYear; + mMaxNumber = maxNumber; + } + + @Override + int getRandomNumberUpTo(int max) { + return mRandomNumberToReturn; + } + + @Override + int getDayOfYear() { + return mDayOfYear; + } + + @Override + int getMaxNumber() { + return mMaxNumber; + } + } }
diff --git a/chrome/app/chrome_crash_reporter_client_win.cc b/chrome/app/chrome_crash_reporter_client_win.cc index 1d06534..79552a9 100644 --- a/chrome/app/chrome_crash_reporter_client_win.cc +++ b/chrome/app/chrome_crash_reporter_client_win.cc
@@ -159,6 +159,9 @@ // Temporary for https://crbug.com/685996. {"user-cloud-policy-manager-connect-trace", kMediumSize}, + // TODO(sunnyps): Remove after fixing crbug.com/724999. + {"gl-context-set-current-stack-trace", kMediumSize}, + // TODO(asvitkine): Remove after fixing https://crbug.com/736675 {"bad_histogram", kMediumSize},
diff --git a/chrome/app/chrome_main.cc b/chrome/app/chrome_main.cc index 9c7b71b..12eb04b 100644 --- a/chrome/app/chrome_main.cc +++ b/chrome/app/chrome_main.cc
@@ -105,11 +105,6 @@ #endif // defined(OS_LINUX) || defined(OS_MACOSX) || defined(OS_WIN) #if BUILDFLAG(ENABLE_MUS) - if (service_manager::ServiceManagerIsRemote() || - command_line->HasSwitch(switches::kMash)) { - params.create_discardable_memory = false; - params.env_mode = aura::Env::Mode::MUS; - } // In config==mus the ui service runs in process and is shut down well before // the rest of Chrome. Have Chrome create the DiscardableSharedMemoryManager // to ensure the DiscardableSharedMemoryManager is destroyed later on. Doing @@ -119,6 +114,16 @@ if (command_line->HasSwitch(switches::kMus)) { params.create_discardable_memory = true; params.env_mode = aura::Env::Mode::MUS; + // TODO(786453): Remove when mus no longer needs to host viz. + base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( + switches::kMus, switches::kMusHostVizValue); + } + if (service_manager::ServiceManagerIsRemote() || + command_line->HasSwitch(switches::kMash)) { + params.create_discardable_memory = false; + params.env_mode = aura::Env::Mode::MUS; + base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( + switches::kMus, switches::kMusHostVizValue); } #endif // BUILDFLAG(ENABLE_MUS)
diff --git a/chrome/app/chromeos_strings.grdp b/chrome/app/chromeos_strings.grdp index d47e35e..448c017 100644 --- a/chrome/app/chromeos_strings.grdp +++ b/chrome/app/chromeos_strings.grdp
@@ -307,6 +307,11 @@ <ph name="LINE_BREAKS"><br/><br/></ph> Removing your device while it is in use may cause data loss. Please wait until the operation is over, then eject the device using the Files app. </message> + <message name="IDS_FILE_BROWSER_UNMOUNT_PROVIDED_FAILED" desc="Title of the error dialog when unmount operation for a volume provided by an extension failed."> + <ph name="BEGIN_BOLD"><b></ph>Cannot unmount volume<ph name="END_BOLD"></b></ph> + <ph name="LINE_BREAKS"><br/><br/></ph> + The volume is busy. Please close all the opened files from it, then try again later. + </message> <message name="IDS_FILE_BROWSER_MOUNT_ARCHIVE" desc="Title of the action for mounting an archive file to work with its contents."> Open </message>
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd index 3851d61..adbaa60 100644 --- a/chrome/app/generated_resources.grd +++ b/chrome/app/generated_resources.grd
@@ -1165,11 +1165,17 @@ <!-- Download Shelf--> <if expr="use_titlecase"> + <message name="IDS_HIDE_DOWNLOADS" desc="Button label for screenreader users, for button at the corner of the download shelf that closes the download shelf (title case)"> + Close Downloads Bar + </message> <message name="IDS_SHOW_ALL_DOWNLOADS" desc="Button label shown at the corner of the download shelf that opens the downloads page (title case)"> Show All </message> </if> <if expr="not use_titlecase"> + <message name="IDS_HIDE_DOWNLOADS" desc="Button label for screenreader users, for button at the corner of the download shelf that closes the download shelf (sentence case)"> + Close downloads bar + </message> <message name="IDS_SHOW_ALL_DOWNLOADS" desc="Button label shown at the corner of the download shelf that opens the downloads page (sentence case)"> Show all </message> @@ -4799,15 +4805,6 @@ Set which search engine is used when searching from the <ph name="BEGIN_LINK"><a target="_blank" href="$1"></ph>omnibox<ph name="END_LINK"></a><ex></a></ex></ph>. </message> - <message name="IDS_HOTWORD_GENERIC_ERROR_MESSAGE" desc="The default error message text when no additional details are known."> - This feature is temporarily unavailable. <ph name="BEGIN_LINK"><a target="_blank" href="$1"></ph>Help<ph name="END_LINK"></a><ex></a></ex></ph> - </message> - <message name="IDS_HOTWORD_NACL_DISABLED_ERROR_MESSAGE" desc="The error message text when hotwording fails because NaCl is disabled."> - Native Client plugin needs to be enabled to use this feature. - </message> - <message name="IDS_HOTWORD_MICROPHONE_ERROR_MESSAGE" desc="The error message text when hotwording fails because the microphone isn't working."> - Microphone is currently unavailable. <ph name="BEGIN_LINK"><a target="_blank" href="chrome://settings/content#media-stream-settings"></ph>Manage microphone<ph name="END_LINK"></a><ex></a></ex></ph> - </message> <if expr="is_win"> <!-- Conflicts page --> <message name="IDS_CONFLICTS_CHECK_PAGE_TABLE_TITLE_SUFFIX_ONE" desc="What gets appended after the page title if no conflicts were found."> @@ -5079,16 +5076,6 @@ This page uses a Native Client app that doesn't work on your computer. </message> - <!-- chrome://voicesearch strings --> - <if expr="chromeos"> - <message name="IDS_VOICESEARCH_LOADING_MESSAGE" desc="Shown while loading until full list of modules is retrieved"> - Loading... - </message> - <message name="IDS_VOICESEARCH_TITLE_MESSAGE" desc="Shown while loading until full list of modules is retrieved"> - About Voice Search - </message> - </if> - <!-- About box strings --> <if expr="is_win"> <message name="IDS_ABOUT_BOX_ERROR_DURING_UPDATE_CHECK" desc="The error label for errors that occurred while checking for updates in the About box."> @@ -6979,6 +6966,9 @@ <message name="IDS_COLLECTED_COOKIES_BLOCKED_AUX_TEXT" desc="The text used to label a cookie which has been marked as blocked."> Blocked </message> + <message name="IDS_COLLECTED_COOKIES_CLEAR_ON_EXIT_AUX_TEXT" desc="The text used to label a cookie which has been marked to be cleared on exit."> + Cleared on Exit + </message> <message name="IDS_COLLECTED_COOKIES_INFOBAR_MESSAGE" desc="The string shown in the infobar after the user has changed the allowed/blocked state of a cookie, reminding them to reload the page in order for the new cookies to take effect."> New cookie settings will take effect after reloading the page. </message> @@ -9882,9 +9872,6 @@ <message name="IDS_APP_LIST_START_SPEECH_RECOGNITION" desc="Tooltip text for the button to start the speech recognition."> Click to start voice search </message> - <message name="IDS_APP_LIST_HOTWORD_LISTENING" desc="Tooltip text for the mic button when it waits for the hotword."> - Click, or say "Ok Google" to start voice search - </message> <message name="IDS_SEARCH_BOX_ACCESSIBILITY_NAME" desc="Hint text for the search box in fullscreen app list window with additional instructions to use the arrow keys in Accessibility mode."> Search your device, apps, and web. Use the arrow keys to navigate your apps. </message> @@ -9897,9 +9884,6 @@ <message name="IDS_SEARCH_BOX_HINT_FULLSCREEN" desc="Hint text for the search box in fullscreen app list window."> Search your device, apps, web... </message> - <message name="IDS_SEARCH_BOX_HOTWORD_HINT" desc="Hint text for the search box in app list window when the hotword is enabled."> - Search, or say "Ok Google" - </message> <if expr="not use_titlecase"> <message name="IDS_APP_LIST_CONTEXT_MENU_NEW_TAB" desc="Title text for the 'open new' context menu item of an app list item configured to open in a tab"> New tab @@ -10536,115 +10520,6 @@ Select </message> - <!-- Hotword Audio Verification (opt-in) App strings. --> - <message name="IDS_HOTWORD_BROWSER_NAME" desc="Name of the device when we're not running in CrOS"> - <ph name="IDS_SHORT_PRODUCT_NAME">$1<ex>Chromium</ex></ph> browser - </message> - <message name="IDS_HOTWORD_OPT_IN_CLOSE" desc="Label for the close button for the 'Ok Google' hotword opt-in dialog."> - Close - </message> - <message name="IDS_HOTWORD_OPT_IN_CANCEL" desc="Text on the cancel button for the 'Ok Google' hotword opt-in dialog."> - CANCEL - </message> - <message name="IDS_HOTWORD_OPT_IN_INTRO_TITLE" desc="Title of the intro page of the 'Ok Google' hotword opt-in dialog."> - Voice search at any time - </message> - <message name="IDS_HOTWORD_OPT_IN_INTRO_SUBTITLE" desc="Sub-title of the intro page of the 'Ok Google' hotword opt-in dialog."> - Say "Ok Google" when your screen is on and unlocked - </message> - <message name="IDS_HOTWORD_OPT_IN_INTRO_DESCRIPTION" desc="Description explaining the steps required to continue through the hotword opt-in process."> - To make this happen, you'll need to enable Voice & Audio Activity and train your <ph name="DEVICE_TYPE">$1<ex>Chromebook</ex></ph> in the following steps. - </message> - <message name="IDS_HOTWORD_OPT_IN_INTRO_DESCRIPTION_AUDIO_HISTORY_ENABLED" desc="Description explaining the steps required to continue through the hotword opt-in process."> - To make this happen, you'll need to train your <ph name="DEVICE_TYPE">$1<ex>Chromebook</ex></ph> in the following step. - </message> - <message name="IDS_HOTWORD_OPT_IN_INTRO_START" desc="Text on the start button for the 'Ok Google' hotword opt-in dialog."> - Get Started - </message> - <message name="IDS_HOTWORD_OPT_IN_AUDIO_HISTORY_TITLE" desc="Title of the Audio History page of the 'Ok Google' hotword opt-in dialog."> - Enable Voice & Audio Activity - </message> - <message name="IDS_HOTWORD_OPT_IN_AUDIO_HISTORY_DESCRIPTION_1" desc="Description of the Audio History page of the 'Ok Google' hotword opt-in dialog."> - When you use audio activation commands, such as "Ok Google" or touching a microphone icon, your private Voice & Audio Activity stores some voice and other audio to your account. A recording of the following speech/audio, plus a few seconds before, will be stored. - </message> - <message name="IDS_HOTWORD_OPT_IN_AUDIO_HISTORY_DESCRIPTION_2" desc="Description of the Audio History page of the 'Ok Google' hotword opt-in dialog."> - This helps Google recognize your voice and improve speech and audio recognition in order to give you results faster and with fewer hassles. <ph name="BEGIN_LINK"><a target="_blank" href="https://support.google.com/websearch?p=chromebook_audiohistory"></ph>Learn more<ph name="END_LINK"></a><ex></a></ex></ph> - </message> - <message name="IDS_HOTWORD_OPT_IN_AUDIO_HISTORY_DESCRIPTION_3" desc="Description of the Audio History page of the 'Ok Google' hotword opt-in dialog."> - You can change this setting or <ph name="BEGIN_LINK"><a target="_blank" href="https://history.google.com/history/audio"></ph>manage your private data<ph name="END_LINK"></a><ex></a></ex></ph> whenever you like. Please remember that when Voice & Audio Activity is on, this data may be saved from any of your signed-in devices. - </message> - <message name="IDS_HOTWORD_OPT_IN_AUDIO_HISTORY_AGREE" desc="Text on the agree button for the Audio History section of the 'Ok Google' hotword opt-in dialog."> - Enable - </message> - <message name="IDS_HOTWORD_OPT_IN_AUDIO_HISTORY_WAIT" desc="Text displayed when waiting for Audio History setting in the 'Ok Google' hotword opt-in dialog."> - Enabling Voice & Audio Activity... - </message> - <message name="IDS_HOTWORD_OPT_IN_ERROR" desc="Text displayed on error setting Audio History and training in the 'Ok Google' hotword opt-in dialog."> - Something went wrong. Please try again. - </message> - <message name="IDS_HOTWORD_OPT_IN_TRAINING_TITLE" desc="Title of the voice model training page of the 'Ok Google' hotword opt-in dialog."> - Let's train your <ph name="DEVICE_TYPE">$1<ex>Chromebook</ex></ph> - </message> - <message name="IDS_HOTWORD_OPT_IN_TRAINING_DESCRIPTION" desc="Description on the voice model training page of the 'Ok Google' hotword opt-in dialog."> - To help your <ph name="DEVICE_TYPE">$1<ex>Chromebook</ex></ph> respond to you and for reliable and easy access to voice search, you need to teach Google the sound of your voice. - </message> - <message name="IDS_HOTWORD_OPT_IN_TRAINING_SPEAK" desc="The text describing the action the user should take on the voice model training page of the 'Ok Google' hotword opt-in dialog."> - Just say "Ok Google" three times - </message> - <message name="IDS_HOTWORD_OPT_IN_TRAINING_FIRST_PROMPT" desc="The first prompt text on the voice model training page of the 'Ok Google' hotword opt-in dialog."> - Say "Ok Google" - </message> - <message name="IDS_HOTWORD_OPT_IN_TRAINING_MIDDLE_PROMPT" desc="The middle prompt text on the voice model training page of the 'Ok Google' hotword opt-in dialog."> - Say "Ok Google" again - </message> - <message name="IDS_HOTWORD_OPT_IN_TRAINING_LAST_PROMPT" desc="The last prompt text on the voice model training page of the 'Ok Google' hotword opt-in dialog."> - Say "Ok Google" one last time - </message> - <message name="IDS_HOTWORD_OPT_IN_TRAINING_RECORDED" desc="The message displayed when an 'Ok Google' utterance has been completed."> - Complete - </message> - <message name="IDS_HOTWORD_OPT_IN_TRAINING_TIMEOUT" desc="The message displayed when an 'Ok Google' training has time out."> - Training timed out - </message> - <message name="IDS_HOTWORD_OPT_IN_TRAINING_RETRY" desc="Text on the retry button of the voice model training page of the 'Ok Google' hotword opt-in dialog."> - RETRY - </message> - <message name="IDS_HOTWORD_OPT_IN_FINISHED_TITLE" desc="Title of the finished page of the 'Ok Google' hotword opt-in dialog."> - You're all set! - </message> - <message name="IDS_HOTWORD_OPT_IN_FINISHED_LIST_INTRO" desc="The text at the beginning of the list describing the Chromebook's new abilities. "> - Your <ph name="DEVICE_TYPE">$1<ex>Chromebook</ex></ph> can now: - </message> - <message name="IDS_HOTWORD_OPT_IN_FINISHED_LIST_ITEM_1" desc="The text of the first item in the list of Chromebook abilities. "> - Recognize your voice when you say "Ok Google" - </message> - <message name="IDS_HOTWORD_OPT_IN_FINISHED_LIST_ITEM_2" desc="The text of the second item in the list of Chromebook abilities. "> - Respond to "Ok Google" when the screen is on and unlocked - </message> - <message name="IDS_HOTWORD_OPT_IN_FINISHED_SETTINGS" desc="The text indicating where the user can change their Chrome settings. "> - You can change this at any time in <ph name="BEGIN_LINK"><a target="_blank" href="#" id="settings-link"></ph>Chrome Settings<ph name="END_LINK"></a><ex></a></ex></ph>. - </message> - <message name="IDS_HOTWORD_OPT_IN_FINISHED_AUDIO_HISTORY" desc="The text indicating where the user can change their account history. "> - Search queries will be tied to your Google Account. You can view and delete them in your <ph name="BEGIN_LINK"><a target="_blank" href="https://www.google.com/settings/accounthistory"></ph>Account History<ph name="END_LINK"></a><ex></a></ex></ph>. - </message> - <message name="IDS_HOTWORD_OPT_IN_FINISH" desc="Text on the finish button for the 'Ok Google' hotword opt-in dialog."> - OK - </message> - <message name="IDS_HOTWORD_OPT_IN_FINISHED_WAIT" desc="The text displayed when waiting for the voice model training to complete."> - Processing... - </message> - - <!-- Hotword Notification --> - <message name="IDS_HOTWORD_NOTIFICATION_TITLE" desc="The text displayed as the title for the hotword notification. "> - Voice search at any time - </message> - <message name="IDS_HOTWORD_NOTIFICATION_DESCRIPTION" desc="The text displayed as the description for the hotword notification. "> - Enable "Ok Google" to voice search when your screen is on and unlocked - </message> - <message name="IDS_HOTWORD_NOTIFICATION_BUTTON" desc="The text displayed on the button of the hotword notification. "> - Enable "Ok Google" - </message> - <!-- About device logs UI display strings --> <message name="IDS_DEVICE_LOG_TITLE" desc="Title of the chrome://device-log page"> Device Log
diff --git a/chrome/app/md_extensions_strings.grdp b/chrome/app/md_extensions_strings.grdp index bcc1b94..62238bfe 100644 --- a/chrome/app/md_extensions_strings.grdp +++ b/chrome/app/md_extensions_strings.grdp
@@ -133,6 +133,9 @@ <message name="IDS_MD_EXTENSIONS_NO_SEARCH_RESULTS" desc="The message shown to the user when a search on the Extensions settings page has no matching results."> No search results found </message> + <message name="IDS_MD_EXTENSIONS_NO_DESCRIPTION" desc="The message shown to the user when an extension does not have any description."> + No description provided + </message> <message name="IDS_MD_EXTENSIONS_PACK_DIALOG_TITLE" desc="The title of the dialog to pack an extension."> Pack extension </message>
diff --git a/chrome/app/settings_strings.grdp b/chrome/app/settings_strings.grdp index 11eca0f..008de717 100644 --- a/chrome/app/settings_strings.grdp +++ b/chrome/app/settings_strings.grdp
@@ -1368,6 +1368,12 @@ <message name="IDS_SETTINGS_INTERNET_ADD_THIRD_PARTY_VPN" desc="Settings > Internet > Add third party VPN label"> Add <ph name="PROVIDER_NAME">$1<ex>VPN Demo</ex></ph>... </message> + <message name="IDS_SETTINGS_INTERNET_ADD_ARC_VPN" desc="Settings > Internet > Add Arc VPN label."> + Add Android VPN... + </message> + <message name="IDS_SETTINGS_INTERNET_ADD_ARC_VPN_PROVIDER" desc="Settings > Internet > Add Arc VPN provider label"> + Add <ph name="PROVIDER_NAME">$1<ex>VPN Demo</ex></ph>... + </message> <message name="IDS_SETTINGS_INTERNET_DEVICE_ENABLING" desc="Settings > Internet > Message when a device (e.g a Cellular modem) is enabling."> Enabling </message> @@ -2243,36 +2249,6 @@ <message name="IDS_SETTINGS_SEARCH_MANAGE_SEARCH_ENGINES" desc="Label for the Manage Search Engines button."> Manage search engines </message> - <message name="IDS_SETTINGS_SEARCH_OK_GOOGLE_LABEL" desc="Label for the checkbox which enables the OK Google hotword."> - Enable "Ok Google" to start a voice search - </message> - <if expr="chromeos"> - <message name="IDS_SETTINGS_SEARCH_OK_GOOGLE_DISABLED" desc="Label to indicate to the user that the OK Google hotword has been disabled."> - "Ok Google" voice search has been removed from Chrome OS - </message> - </if> - <message name="IDS_SETTINGS_SEARCH_OK_GOOGLE_SUBTEXT_ALWAYS_ON" desc="Subtext describing when the OK Google hotword may be used."> - Say "Ok Google" when the screen is on and unlocked - </message> - <if expr="chromeos"> - <message name="IDS_SETTINGS_SEARCH_OK_GOOGLE_SUBTEXT_NO_HARDWARE" desc="Subtext describing when the OK Google hotword may be used for devices without hardware support."> - Say "Ok Google" in a new tab, google.com, and the App Launcher - </message> - </if> - <if expr="not chromeos"> - <message name="IDS_SETTINGS_SEARCH_OK_GOOGLE_SUBTEXT_NO_HARDWARE" desc="Subtext describing when the OK Google hotword may be used for devices with no hardware support."> - Say "Ok Google" in a new tab and google.com - </message> - </if> - <message name="IDS_SETTINGS_SEARCH_OK_GOOGLE_AUDIO_HISTORY_LABEL" desc="Text to display when the user has audio history enabled."> - Voice and Audio Activity for <ph name="USER_EMAIL">$1<ex>joe@gmail.com</ex></ph>. - </message> - <message name="IDS_SETTINGS_SEARCH_OK_GOOGLE_AUDIO_HISTORY_SUBTEXT" desc="Subtext describing why audio history is enabled."> - Enabled (required to use "Ok Google") - </message> - <message name="IDS_SETTINGS_SEARCH_OK_GOOGLE_RETRAIN" desc="Text for button to retrain the OK Google hotword voice model."> - Retrain - </message> <if expr="chromeos"> <message name="IDS_SETTINGS_SEARCH_GOOGLE_ASSISTANT" desc="Label for the Google Assistant button."> Google Assistant
diff --git a/chrome/app/theme/default_100_percent/common/app_list_mic_hotword_off.png b/chrome/app/theme/default_100_percent/common/app_list_mic_hotword_off.png deleted file mode 100644 index 9f7db87..0000000 --- a/chrome/app/theme/default_100_percent/common/app_list_mic_hotword_off.png +++ /dev/null Binary files differ
diff --git a/chrome/app/theme/default_100_percent/common/app_list_mic_hotword_on.png b/chrome/app/theme/default_100_percent/common/app_list_mic_hotword_on.png deleted file mode 100644 index ad216dae..0000000 --- a/chrome/app/theme/default_100_percent/common/app_list_mic_hotword_on.png +++ /dev/null Binary files differ
diff --git a/chrome/app/theme/default_100_percent/common/notification_hotword_icon.png b/chrome/app/theme/default_100_percent/common/notification_hotword_icon.png deleted file mode 100644 index 95c161bc..0000000 --- a/chrome/app/theme/default_100_percent/common/notification_hotword_icon.png +++ /dev/null Binary files differ
diff --git a/chrome/app/theme/default_200_percent/common/app_list_mic_hotword_off.png b/chrome/app/theme/default_200_percent/common/app_list_mic_hotword_off.png deleted file mode 100644 index 9d82452..0000000 --- a/chrome/app/theme/default_200_percent/common/app_list_mic_hotword_off.png +++ /dev/null Binary files differ
diff --git a/chrome/app/theme/default_200_percent/common/app_list_mic_hotword_on.png b/chrome/app/theme/default_200_percent/common/app_list_mic_hotword_on.png deleted file mode 100644 index 26510654..0000000 --- a/chrome/app/theme/default_200_percent/common/app_list_mic_hotword_on.png +++ /dev/null Binary files differ
diff --git a/chrome/app/theme/default_200_percent/common/notification_hotword_icon.png b/chrome/app/theme/default_200_percent/common/notification_hotword_icon.png deleted file mode 100644 index 914ce66..0000000 --- a/chrome/app/theme/default_200_percent/common/notification_hotword_icon.png +++ /dev/null Binary files differ
diff --git a/chrome/app/theme/theme_resources.grd b/chrome/app/theme/theme_resources.grd index 0a3d77c..f7dd5fe 100644 --- a/chrome/app/theme/theme_resources.grd +++ b/chrome/app/theme/theme_resources.grd
@@ -48,8 +48,6 @@ </if> <if expr="enable_app_list"> <structure type="chrome_scaled_image" name="IDR_APP_LIST_TAB_OVERLAY" file="common/app_list_v1_overlay.png" /> - <structure type="chrome_scaled_image" name="IDR_APP_LIST_MIC_HOTWORD_OFF" file="common/app_list_mic_hotword_off.png" /> - <structure type="chrome_scaled_image" name="IDR_APP_LIST_MIC_HOTWORD_ON" file="common/app_list_mic_hotword_on.png" /> </if> <if expr="toolkit_views and not is_macosx"> <structure type="chrome_scaled_image" name="IDR_APP_WINDOW_CLOSE" file="common/app_window_close.png" /> @@ -200,7 +198,6 @@ <structure type="chrome_scaled_image" name="IDR_HIDE_PASSWORD" file="cros/hide_password.png" /> </if> <structure type="chrome_scaled_image" name="IDR_HIDE_PASSWORD_HOVER" file="common/hide_password_hover.png" /> - <structure type="chrome_scaled_image" name="IDR_HOTWORD_NOTIFICATION_ICON" file="common/notification_hotword_icon.png" /> <if expr="is_macosx"> <structure type="chrome_scaled_image" name="IDR_ICON_PROFILES_ACCOUNT_BUTTON_ERROR" file="legacy/avatar_menu_auth_error.png" /> </if>
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index 4fdb25f..4cfa1fc 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -3366,13 +3366,6 @@ "renderer_context_menu/context_menu_content_type_platform_app.h", "renderer_host/chrome_extension_message_filter.cc", "renderer_host/chrome_extension_message_filter.h", - "search/hotword_audio_history_handler.cc", - "search/hotword_audio_history_handler.h", - "search/hotword_client.h", - "search/hotword_service.cc", - "search/hotword_service.h", - "search/hotword_service_factory.cc", - "search/hotword_service_factory.h", "signin/chrome_proximity_auth_client.cc", "signin/chrome_proximity_auth_client.h", "signin/easy_unlock_app_manager.cc", @@ -3542,10 +3535,6 @@ ] } - if (enable_hotwording) { - defines += [ "ENABLE_HOTWORDING" ] - } - if (enable_mdns) { sources += [ "local_discovery/service_discovery_client_impl.cc",
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 9472d68e..2a9e7d5 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -1948,10 +1948,6 @@ flag_descriptions::kUserConsentForExtensionScriptsDescription, kOsAll, SINGLE_VALUE_TYPE(extensions::switches::kEnableScriptsRequireAction)}, #endif // ENABLE_EXTENSIONS - {"enable-hotword-hardware", - flag_descriptions::kExperimentalHotwordHardwareName, - flag_descriptions::kExperimentalHotwordHardwareDescription, kOsCrOS, - SINGLE_VALUE_TYPE(switches::kEnableExperimentalHotwordHardware)}, #if BUILDFLAG(ENABLE_EXTENSIONS) {"enable-embedded-extension-options", flag_descriptions::kEmbeddedExtensionOptionsName, @@ -2996,9 +2992,6 @@ flag_descriptions::kEnableZeroSuggestRedirectToChromeName, flag_descriptions::kEnableZeroSuggestRedirectToChromeDescription, kOsAll, FEATURE_VALUE_TYPE(omnibox::kZeroSuggestRedirectToChrome)}, - {"new-omnibox-answer-types", flag_descriptions::kNewOmniboxAnswerTypesName, - flag_descriptions::kNewOmniboxAnswerTypesDescription, kOsAll, - FEATURE_VALUE_TYPE(omnibox::kNewOmniboxAnswerTypes)}, {"left-to-right-urls", flag_descriptions::kLeftToRightUrlsName, flag_descriptions::kLeftToRightUrlsDescription, kOsDesktop, FEATURE_VALUE_TYPE(features::kLeftToRightUrls)},
diff --git a/chrome/browser/android/chrome_feature_list.cc b/chrome/browser/android/chrome_feature_list.cc index baf51fbd..c35b8a02 100644 --- a/chrome/browser/android/chrome_feature_list.cc +++ b/chrome/browser/android/chrome_feature_list.cc
@@ -79,6 +79,7 @@ &kContentSuggestionsSettings, &kContentSuggestionsThumbnailDominantColor, &kContextualSearchMlTapSuppression, + &kContextualSearchRankerQuery, &kContextualSuggestionsCarousel, &kCustomContextMenu, &kCustomFeedbackUi, @@ -229,6 +230,9 @@ const base::Feature kContextualSearchMlTapSuppression{ "ContextualSearchMlTapSuppression", base::FEATURE_DISABLED_BY_DEFAULT}; +const base::Feature kContextualSearchRankerQuery{ + "ContextualSearchRankerQuery", base::FEATURE_DISABLED_BY_DEFAULT}; + const base::Feature kContextualSuggestionsCarousel{ "ContextualSuggestionsCarousel", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/chrome/browser/android/chrome_feature_list.h b/chrome/browser/android/chrome_feature_list.h index 3078bd6b..bf252f70 100644 --- a/chrome/browser/android/chrome_feature_list.h +++ b/chrome/browser/android/chrome_feature_list.h
@@ -39,6 +39,7 @@ extern const base::Feature kContentSuggestionsSettings; extern const base::Feature kContentSuggestionsThumbnailDominantColor; extern const base::Feature kContextualSearchMlTapSuppression; +extern const base::Feature kContextualSearchRankerQuery; extern const base::Feature kContextualSuggestionsCarousel; extern const base::Feature kCustomContextMenu; extern const base::Feature kCustomFeedbackUi;
diff --git a/chrome/browser/android/contextualsearch/contextual_search_field_trial.cc b/chrome/browser/android/contextualsearch/contextual_search_field_trial.cc index ce82482..be5a340 100644 --- a/chrome/browser/android/contextualsearch/contextual_search_field_trial.cc +++ b/chrome/browser/android/contextualsearch/contextual_search_field_trial.cc
@@ -6,8 +6,6 @@ #include "base/command_line.h" #include "base/strings/string_number_conversions.h" -#include "chrome/browser/android/chrome_feature_list.h" -#include "chrome/common/chrome_switches.h" #include "components/variations/variations_associated_data.h" namespace { @@ -23,8 +21,6 @@ const char kContextualSearchDecodeMentionsDisabledParamName[] = "disable_decode_mentions"; const char kContextualCardsVersionParamName[] = "contextual_cards_version"; -const char kContextualSearchRankerIntegrationEnabledParamName[] = - "enable_ranker_integration"; // The default size of the content surrounding the selection to gather, allowing // room for other parameters. @@ -48,9 +44,7 @@ is_decode_mentions_disabled_cached_(false), is_decode_mentions_disabled_(false), is_contextual_cards_version_cached_(false), - contextual_cards_version_(0), - is_ranker_integration_enabled_cached_(false), - is_ranker_integration_enabled_(false) {} + contextual_cards_version_(0) {} ContextualSearchFieldTrial::~ContextualSearchFieldTrial() {} @@ -96,15 +90,6 @@ &contextual_cards_version_); } -bool ContextualSearchFieldTrial:: - IsRankerIntegrationOrMlTapSuppressionEnabled() { - return base::FeatureList::IsEnabled( - chrome::android::kContextualSearchMlTapSuppression) || - GetBooleanParam(kContextualSearchRankerIntegrationEnabledParamName, - &is_ranker_integration_enabled_cached_, - &is_ranker_integration_enabled_); -} - bool ContextualSearchFieldTrial::GetBooleanParam(const std::string& name, bool* is_value_cached, bool* cached_value) {
diff --git a/chrome/browser/android/contextualsearch/contextual_search_field_trial.h b/chrome/browser/android/contextualsearch/contextual_search_field_trial.h index f37198aa..c020c15 100644 --- a/chrome/browser/android/contextualsearch/contextual_search_field_trial.h +++ b/chrome/browser/android/contextualsearch/contextual_search_field_trial.h
@@ -38,10 +38,6 @@ // not set. int GetContextualCardsVersion(); - // Gets whether either the CS Ranker integration param, or the ML Tap - // Suppression feature flag is enabled. - bool IsRankerIntegrationOrMlTapSuppressionEnabled(); - // Disables the cache. void DisableCache(); @@ -94,9 +90,6 @@ bool is_contextual_cards_version_cached_; int contextual_cards_version_; - bool is_ranker_integration_enabled_cached_; - bool is_ranker_integration_enabled_; - DISALLOW_COPY_AND_ASSIGN(ContextualSearchFieldTrial); };
diff --git a/chrome/browser/android/contextualsearch/contextual_search_ranker_logger_impl.cc b/chrome/browser/android/contextualsearch/contextual_search_ranker_logger_impl.cc index 7935d97..4ea61f4 100644 --- a/chrome/browser/android/contextualsearch/contextual_search_ranker_logger_impl.cc +++ b/chrome/browser/android/contextualsearch/contextual_search_ranker_logger_impl.cc
@@ -11,7 +11,7 @@ #include "base/metrics/histogram_functions.h" #include "base/metrics/metrics_hashes.h" #include "base/strings/stringprintf.h" -#include "chrome/browser/android/contextualsearch/contextual_search_field_trial.h" +#include "chrome/browser/android/chrome_feature_list.h" #include "chrome/browser/assist_ranker/assist_ranker_service_factory.h" #include "chrome/browser/browser_process.h" #include "components/assist_ranker/assist_ranker_service_impl.h" @@ -28,9 +28,6 @@ class BrowserContext; } -const base::Feature kContextualSearchRankerQuery{ - "ContextualSearchRankerQuery", base::FEATURE_DISABLED_BY_DEFAULT}; - namespace { const char kContextualSearchRankerModelUrlParamName[] = @@ -42,8 +39,8 @@ const char kContextualSearchRankerPrediction[] = "OutcomeRankerPrediction"; const base::FeatureParam<std::string> kModelUrl{ - &kContextualSearchRankerQuery, kContextualSearchRankerModelUrlParamName, - ""}; + &chrome::android::kContextualSearchRankerQuery, + kContextualSearchRankerModelUrlParamName, ""}; // TODO(donnd, hamelphi): move hex-hash-string to Ranker. std::string HexHashFeatureName(const std::string& feature_name) { @@ -58,15 +55,12 @@ : ukm_recorder_(nullptr), source_id_(0), builder_(nullptr), - field_trial_(nullptr), predictor_(nullptr), browser_context_(nullptr), ranker_example_(nullptr), has_predicted_decision_(false), java_object_(nullptr) { java_object_.Reset(env, obj); - // TODO(donnd): consider making a singleton CSFieldTrial instead of many? - field_trial_.reset(new ContextualSearchFieldTrial()); } ContextualSearchRankerLoggerImpl::~ContextualSearchRankerLoggerImpl() { @@ -86,7 +80,7 @@ ukm::UkmRecorder* ukm_recorder = ukm::UkmRecorder::Get(); SetUkmRecorder(ukm_recorder, page_url); - if (IsRankerEnabled()) { + if (IsRankerQueryEnabled()) { SetupRankerPredictor(web_contents); // Start building example data based on features to be gathered and logged. ranker_example_.reset(new assist_ranker::RankerExample()); @@ -110,7 +104,7 @@ void ContextualSearchRankerLoggerImpl::SetupRankerPredictor( content::WebContents* web_contents) { // Set up the Ranker predictor. - if (IsRankerEnabled()) { + if (IsRankerQueryEnabled()) { // Create one predictor for the current BrowserContext. content::BrowserContext* browser_context = web_contents->GetBrowserContext(); @@ -136,8 +130,8 @@ if (builder_) builder_->AddMetric(feature.c_str(), j_long); - // Also write to Ranker if prediction of the decision has not been made yet. - if (IsRankerEnabled() && !has_predicted_decision_) { + // Also write to Ranker if we're logging data needed to predict a decision. + if (IsRankerQueryEnabled() && !has_predicted_decision_) { std::string hex_feature_key(HexHashFeatureName(feature)); auto& features = *ranker_example_->mutable_features(); features[hex_feature_key].set_int32_value(j_long); @@ -150,7 +144,7 @@ has_predicted_decision_ = true; bool prediction = false; bool was_able_to_predict = false; - if (IsRankerEnabled()) { + if (IsRankerQueryEnabled()) { was_able_to_predict = predictor_->Predict(*ranker_example_, &prediction); // Log to UMA whether we were able to predict or not. base::UmaHistogramBoolean("Search.ContextualSearchRankerWasAbleToPredict", @@ -189,9 +183,9 @@ ranker_example_.reset(); } -bool ContextualSearchRankerLoggerImpl::IsRankerEnabled() { - return field_trial_->IsRankerIntegrationOrMlTapSuppressionEnabled() && - base::FeatureList::IsEnabled(kContextualSearchRankerQuery); +bool ContextualSearchRankerLoggerImpl::IsRankerQueryEnabled() { + return base::FeatureList::IsEnabled( + chrome::android::kContextualSearchRankerQuery); } // Java wrapper boilerplate
diff --git a/chrome/browser/android/contextualsearch/contextual_search_ranker_logger_impl.h b/chrome/browser/android/contextualsearch/contextual_search_ranker_logger_impl.h index b0efd27c..19e76f2 100644 --- a/chrome/browser/android/contextualsearch/contextual_search_ranker_logger_impl.h +++ b/chrome/browser/android/contextualsearch/contextual_search_ranker_logger_impl.h
@@ -7,13 +7,8 @@ #include "base/android/jni_android.h" -class ContextualSearchFieldTrial; class GURL; -namespace base { -struct Feature; -} - namespace content { class BrowserContext; class WebContents; @@ -38,9 +33,6 @@ ASSIST_RANKER_PREDICTION_SHOW, }; -// The Feature that queries the Contextual Search Ranker model (and has a URL). -extern const base::Feature kContextualSearchRankerQuery; - // Runs Ranker inference and logging through UKM for Ranker model development. // This is used to prediction whether a tap gesture will be useful to the user // or not. @@ -84,8 +76,8 @@ // Sets up the Ranker Predictor for the given |web_contents|. void SetupRankerPredictor(content::WebContents* web_contents); - // Whether Ranker predicting and model loading is enabled. - bool IsRankerEnabled(); + // Whether querying Ranker for model loading and prediction is enabled. + bool IsRankerQueryEnabled(); // Used to log URL-keyed metrics. This pointer will outlive |this|, and may // be nullptr. @@ -97,9 +89,6 @@ // The entry builder for the current record, or nullptr if not yet configured. std::unique_ptr<ukm::UkmEntryBuilder> builder_; - // The field trial helper instance, always set up by the constructor. - std::unique_ptr<ContextualSearchFieldTrial> field_trial_; - // The Ranker Predictor for whether a tap gesture should be suppressed or not. std::unique_ptr<assist_ranker::BinaryClassifierPredictor> predictor_;
diff --git a/chrome/browser/android/ntp/content_suggestions_notifier_service_unittest.cc b/chrome/browser/android/ntp/content_suggestions_notifier_service_unittest.cc index e2597e3..c95ec7e 100644 --- a/chrome/browser/android/ntp/content_suggestions_notifier_service_unittest.cc +++ b/chrome/browser/android/ntp/content_suggestions_notifier_service_unittest.cc
@@ -119,7 +119,7 @@ NOTIMPLEMENTED(); } - void ClearCachedSuggestions(Category category) override { NOTIMPLEMENTED(); } + void ClearCachedSuggestions() override { NOTIMPLEMENTED(); } void GetDismissedSuggestionsForDebugging( Category category,
diff --git a/chrome/browser/android/tab_android.cc b/chrome/browser/android/tab_android.cc index 42b7d62..bf59c7b 100644 --- a/chrome/browser/android/tab_android.cc +++ b/chrome/browser/android/tab_android.cc
@@ -71,7 +71,6 @@ #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" -#include "content/public/common/associated_interface_provider.h" #include "content/public/common/browser_controls_state.h" #include "content/public/common/resource_request_body.h" #include "jni/Tab_jni.h" @@ -80,6 +79,7 @@ #include "services/service_manager/public/cpp/bind_source_info.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "skia/ext/image_operations.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" #include "third_party/WebKit/public/platform/WebReferrerPolicy.h" #include "ui/android/view_android.h" #include "ui/android/window_android.h"
diff --git a/chrome/browser/android/vr_shell/vr_shell.cc b/chrome/browser/android/vr_shell/vr_shell.cc index ca135ef..c23b30c 100644 --- a/chrome/browser/android/vr_shell/vr_shell.cc +++ b/chrome/browser/android/vr_shell/vr_shell.cc
@@ -667,20 +667,26 @@ void VrShell::OnUnsupportedMode(vr::UiUnsupportedMode mode) { switch (mode) { - case vr::UiUnsupportedMode::kAndroidPermissionNeeded: { - JNIEnv* env = base::android::AttachCurrentThread(); - Java_VrShellImpl_onUnhandledPermissionPrompt(env, j_vr_shell_); - break; - } + case vr::UiUnsupportedMode::kUnhandledCodePoint: + ExitVrDueToUnsupportedMode(mode); + return; case vr::UiUnsupportedMode::kUnhandledPageInfo: { JNIEnv* env = base::android::AttachCurrentThread(); Java_VrShellImpl_onUnhandledPageInfo(env, j_vr_shell_); - break; + return; } - default: - ExitVrDueToUnsupportedMode(mode); - break; + case vr::UiUnsupportedMode::kAndroidPermissionNeeded: { + JNIEnv* env = base::android::AttachCurrentThread(); + Java_VrShellImpl_onUnhandledPermissionPrompt(env, j_vr_shell_); + return; + } + case vr::UiUnsupportedMode::kCount: + NOTREACHED(); // Should never be used as a mode. + return; } + + NOTREACHED(); + ExitVrDueToUnsupportedMode(mode); } void VrShell::OnExitVrPromptResult(vr::UiUnsupportedMode reason,
diff --git a/chrome/browser/android/vr_shell/vr_shell_gl.cc b/chrome/browser/android/vr_shell/vr_shell_gl.cc index a5c0cb1..6a0e2b0 100644 --- a/chrome/browser/android/vr_shell/vr_shell_gl.cc +++ b/chrome/browser/android/vr_shell/vr_shell_gl.cc
@@ -400,7 +400,7 @@ } // Always notify the client that we're done with the mailbox even // if we haven't drawn it, so that it's eligible for destruction. - submit_client_->OnSubmitFrameTransferred(); + submit_client_->OnSubmitFrameTransferred(true); if (!swapped) { // We dropped without drawing, report this as completed rendering // now to unblock the client. We're not going to receive it in @@ -459,9 +459,10 @@ ui_->OnWebVrFrameAvailable(); - DrawFrame(frame_index, base::TimeTicks::Now()); if (web_vr_mode_) ++webvr_frames_received_; + + DrawFrame(frame_index, base::TimeTicks::Now()); ScheduleOrCancelWebVrFrameTimeout(); } @@ -948,12 +949,15 @@ // At this point, we draw non-WebVR content that could, potentially, fill the // viewport. NB: this is not just 2d browsing stuff, we may have a splash - // screen showing in WebVR mode that must also fill the screen. - ui_->ui_renderer()->Draw(render_info_primary_); + // screen showing in WebVR mode that must also fill the screen. That said, + // while the splash screen is up ShouldDrawWebVr() will return false. + if (!ShouldDrawWebVr()) { + ui_->ui_renderer()->Draw(render_info_primary_); - // Draw keyboard. TODO(ymalik,crbug.com/780135): Keyboard should be a UI - // element and this special rendering logic should move out of here. - DrawKeyboard(); + // Draw keyboard. TODO(ymalik,crbug.com/780135): Keyboard should be a UI + // element and this special rendering logic should move out of here. + DrawKeyboard(); + } content_frame_available_ = false; acquired_frame_.Unbind();
diff --git a/chrome/browser/apps/guest_view/web_view_interactive_browsertest.cc b/chrome/browser/apps/guest_view/web_view_interactive_browsertest.cc index e4af17c..d317d6f 100644 --- a/chrome/browser/apps/guest_view/web_view_interactive_browsertest.cc +++ b/chrome/browser/apps/guest_view/web_view_interactive_browsertest.cc
@@ -1011,14 +1011,7 @@ NEEDS_TEST_SERVER); } -// Flaky on win_chromium_rel_ng. https://crbug.com/504054 -#if defined(OS_WIN) -#define MAYBE_NewWindow_Redirect DISABLED_NewWindow_Redirect -#else -#define MAYBE_NewWindow_Redirect NewWindow_Redirect -#endif -IN_PROC_BROWSER_TEST_P(WebViewNewWindowInteractiveTest, - MAYBE_NewWindow_Redirect) { +IN_PROC_BROWSER_TEST_P(WebViewNewWindowInteractiveTest, NewWindow_Redirect) { TestHelper("testNewWindowRedirect", "web_view/newwindow", NEEDS_TEST_SERVER); @@ -1264,14 +1257,7 @@ "platform_apps/web_view/common", "execute_code")) << message_; } -// Causes problems on windows: http://crbug.com/544037 -#if defined(OS_WIN) -#define MAYBE_PopupPositioningBasic DISABLED_PopupPositioningBasic -#else -#define MAYBE_PopupPositioningBasic PopupPositioningBasic -#endif -IN_PROC_BROWSER_TEST_F(WebViewPopupInteractiveTest, - MAYBE_PopupPositioningBasic) { +IN_PROC_BROWSER_TEST_F(WebViewPopupInteractiveTest, PopupPositioningBasic) { TestHelper("testBasic", "web_view/popup_positioning", NO_TEST_SERVER); ASSERT_TRUE(guest_web_contents()); PopupTestHelper(gfx::Point()); @@ -1281,8 +1267,7 @@ } // Flaky on ChromeOS and Linux: http://crbug.com/526886 -// Causes problems on windows: http://crbug.com/544998 -#if defined(OS_CHROMEOS) || defined(OS_WIN) || defined(OS_LINUX) +#if defined(OS_CHROMEOS) || defined(OS_LINUX) #define MAYBE_PopupPositioningMoved DISABLED_PopupPositioningMoved #else #define MAYBE_PopupPositioningMoved PopupPositioningMoved @@ -1333,8 +1318,15 @@ // Trips over a DCHECK in content::MouseLockDispatcher::OnLockMouseACK; see // https://crbug.com/761783. +#if defined(OS_WIN) +#define MAYBE_PointerLock_PointerLockLostWithFocus \ + PointerLock_PointerLockLostWithFocus +#else +#define MAYBE_PointerLock_PointerLockLostWithFocus \ + DISABLED_PointerLock_PointerLockLostWithFocus +#endif IN_PROC_BROWSER_TEST_P(WebViewPointerLockInteractiveTest, - DISABLED_PointerLock_PointerLockLostWithFocus) { + MAYBE_PointerLock_PointerLockLostWithFocus) { TestHelper("testPointerLockLostWithFocus", "web_view/pointerlock", NO_TEST_SERVER);
diff --git a/chrome/browser/autofill/autofill_interactive_uitest.cc b/chrome/browser/autofill/autofill_interactive_uitest.cc index 1c20f8d..89bc54c5 100644 --- a/chrome/browser/autofill/autofill_interactive_uitest.cc +++ b/chrome/browser/autofill/autofill_interactive_uitest.cc
@@ -1590,7 +1590,7 @@ #else #define MAYBE_FormFillableOnReset FormFillableOnReset #endif -IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest, FormFillableOnReset) { +IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest, MAYBE_FormFillableOnReset) { CreateTestProfile(); GURL url =
diff --git a/chrome/browser/autofill/form_structure_browsertest.cc b/chrome/browser/autofill/form_structure_browsertest.cc index 1e96ad45..4b1c89b 100644 --- a/chrome/browser/autofill/form_structure_browsertest.cc +++ b/chrome/browser/autofill/form_structure_browsertest.cc
@@ -26,6 +26,7 @@ #include "components/autofill/core/browser/autofill_manager.h" #include "components/autofill/core/browser/data_driven_test.h" #include "components/autofill/core/browser/form_structure.h" +#include "components/autofill/core/common/autofill_features.h" #include "content/public/common/content_switches.h" #include "url/gurl.h" @@ -122,8 +123,8 @@ FormStructureBrowserTest::FormStructureBrowserTest() : DataDrivenTest(GetTestDataDir()) { - feature_list_.InitAndEnableFeature( - autofill::kAutofillRationalizeFieldTypePredictions); + feature_list_.InitAndDisableFeature( + autofill::features::kAutofillEnforceMinRequiredFieldsForUpload); } FormStructureBrowserTest::~FormStructureBrowserTest() { @@ -166,7 +167,9 @@ IN_PROC_BROWSER_TEST_P(FormStructureBrowserTest, DataDrivenHeuristics) { // Prints the path of the test to be executed. LOG(INFO) << GetParam().MaybeAsASCII(); - RunOneDataDrivenTest(GetParam(), GetOutputDirectory(kTestName)); + const bool kIsExpectedToPass = true; + RunOneDataDrivenTest(GetParam(), GetOutputDirectory(kTestName), + kIsExpectedToPass); } INSTANTIATE_TEST_CASE_P(AllForms,
diff --git a/chrome/browser/banners/app_banner_manager.cc b/chrome/browser/banners/app_banner_manager.cc index 9a54a9b..e9935793 100644 --- a/chrome/browser/banners/app_banner_manager.cc +++ b/chrome/browser/banners/app_banner_manager.cc
@@ -538,7 +538,7 @@ // requires a user gesture. In contrast, showing of traditional app banners // is automatic, so we throttle it if the user has recently ignored or // blocked the banner. - if (!base::FeatureList::IsEnabled(features::kExperimentalAppBanners)) { + if (!IsExperimentalAppBannersEnabled()) { base::Time now = GetCurrentTime(); if (AppBannerSettingsHelper::WasBannerRecentlyBlocked( contents, validated_url_, GetAppIdentifier(), now)) {
diff --git a/chrome/browser/banners/app_banner_manager_desktop.cc b/chrome/browser/banners/app_banner_manager_desktop.cc index 6238b7ac..b4b1774 100644 --- a/chrome/browser/banners/app_banner_manager_desktop.cc +++ b/chrome/browser/banners/app_banner_manager_desktop.cc
@@ -31,7 +31,7 @@ return false; return base::FeatureList::IsEnabled(features::kAppBanners) || - base::FeatureList::IsEnabled(features::kExperimentalAppBanners); + IsExperimentalAppBannersEnabled(); } void AppBannerManagerDesktop::DisableTriggeringForTesting() {
diff --git a/chrome/browser/browser_resources.grd b/chrome/browser/browser_resources.grd index 3dcea99..01e3df3 100644 --- a/chrome/browser/browser_resources.grd +++ b/chrome/browser/browser_resources.grd
@@ -199,10 +199,6 @@ <!-- Hangout Services extension, included in Google Chrome builds only. --> <include name="IDR_HANGOUT_SERVICES_MANIFEST" file="resources\hangout_services\manifest.json" type="BINDATA" /> </if> - <if expr="enable_hotwording"> - <include name="IDR_HOTWORD_MANIFEST" file="resources\hotword\manifest.json" type="BINDATA" /> - <include name="IDR_HOTWORD_AUDIO_VERIFICATION_MANIFEST" file="resources\hotword_audio_verification\manifest.json" type="BINDATA" /> - </if> <if expr="not is_android"> <!-- MD Bookmarks. --> @@ -375,8 +371,6 @@ <include name="IDR_PLUGIN_DB_JSON" file="resources\plugin_metadata\plugins_mac.json" type="BINDATA" /> </if> <if expr="chromeos"> - <include name="IDR_ABOUT_VOICESEARCH_HTML" file="resources\about_voicesearch.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" /> - <include name="IDR_ABOUT_VOICESEARCH_JS" file="resources\about_voicesearch.js" type="BINDATA" /> <include name="IDR_PLUGIN_DB_JSON" file="resources\plugin_metadata\plugins_chromeos.json" type="BINDATA" /> </if> <if expr="desktop_linux or (is_android and enable_plugins)">
diff --git a/chrome/browser/browser_shutdown_browsertest.cc b/chrome/browser/browser_shutdown_browsertest.cc new file mode 100644 index 0000000..cec18f2 --- /dev/null +++ b/chrome/browser/browser_shutdown_browsertest.cc
@@ -0,0 +1,77 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/test/histogram_tester.h" +#include "chrome/app/chrome_command_ids.h" +#include "chrome/browser/browser_shutdown.h" +#include "chrome/browser/chrome_notification_types.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/browser_commands.h" +#include "chrome/browser/ui/browser_list.h" +#include "chrome/test/base/in_process_browser_test.h" +#include "chrome/test/base/ui_test_utils.h" +#include "content/public/browser/notification_service.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +using testing::_; +using testing::AtLeast; + +class BrowserShutdownBrowserTest : public InProcessBrowserTest { + public: + BrowserShutdownBrowserTest() {} + ~BrowserShutdownBrowserTest() override {} + + protected: + base::HistogramTester histogram_tester_; + + private: + DISALLOW_COPY_AND_ASSIGN(BrowserShutdownBrowserTest); +}; + +class BrowserClosingObserver : public chrome::BrowserListObserver { + public: + BrowserClosingObserver() {} + MOCK_METHOD1(OnBrowserClosing, void(Browser* browser)); + + private: + DISALLOW_COPY_AND_ASSIGN(BrowserClosingObserver); +}; + +// ChromeOS has the different shutdown flow on user initiated exit process. +// See the comment for chrome::AttemptUserExit() function declaration. +#if !defined(OS_CHROMEOS) +IN_PROC_BROWSER_TEST_F(BrowserShutdownBrowserTest, + PRE_TwoBrowsersClosingShutdownHistograms) { + ui_test_utils::NavigateToURL(browser(), GURL("browser://version")); + Browser* browser2 = CreateBrowser(browser()->profile()); + ui_test_utils::NavigateToURL(browser2, GURL("browser://help")); + + BrowserClosingObserver closing_observer; + BrowserList::AddObserver(&closing_observer); + EXPECT_CALL(closing_observer, OnBrowserClosing(_)).Times(AtLeast(1)); + + content::WindowedNotificationObserver terminate_observer( + chrome::NOTIFICATION_APP_TERMINATING, + content::NotificationService::AllSources()); + chrome::ExecuteCommand(browser(), IDC_EXIT); + terminate_observer.Wait(); + + EXPECT_TRUE(browser_shutdown::IsTryingToQuit()); + EXPECT_TRUE(BrowserList::GetInstance()->empty()); + EXPECT_EQ(browser_shutdown::GetShutdownType(), + browser_shutdown::WINDOW_CLOSE); + BrowserList::RemoveObserver(&closing_observer); +} + +IN_PROC_BROWSER_TEST_F(BrowserShutdownBrowserTest, + TwoBrowsersClosingShutdownHistograms) { + histogram_tester_.ExpectUniqueSample("Shutdown.ShutdownType", + browser_shutdown::WINDOW_CLOSE, 1); + histogram_tester_.ExpectTotalCount("Shutdown.renderers.total", 1); + histogram_tester_.ExpectTotalCount("Shutdown.window_close.time2", 1); + histogram_tester_.ExpectTotalCount("Shutdown.window_close.time_per_process", + 1); +} +#endif // !defined(OS_CHROMEOS)
diff --git a/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate_unittest.cc b/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate_unittest.cc index 791e34f..18d6b49 100644 --- a/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate_unittest.cc +++ b/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate_unittest.cc
@@ -1870,14 +1870,13 @@ EXPECT_EQ(0u, zoom_map->GetAllZoomLevels().size()); - auto test_clock = base::MakeUnique<base::SimpleTestClock>(); - base::SimpleTestClock* clock = test_clock.get(); - zoom_map->SetClockForTesting(std::move(test_clock)); + base::SimpleTestClock test_clock; + zoom_map->SetClockForTesting(&test_clock); base::Time now = base::Time::Now(); zoom_map->InitializeZoomLevelForHost(kTestRegisterableDomain1, 1.5, now - base::TimeDelta::FromHours(5)); - clock->SetNow(now - base::TimeDelta::FromHours(2)); + test_clock.SetNow(now - base::TimeDelta::FromHours(2)); zoom_map->SetZoomLevelForHost(kTestRegisterableDomain3, 2.0); EXPECT_EQ(2u, zoom_map->GetAllZoomLevels().size()); @@ -1889,7 +1888,7 @@ // Nothing should be deleted as the zoomlevels were created earlier. EXPECT_EQ(2u, zoom_map->GetAllZoomLevels().size()); - clock->SetNow(now); + test_clock.SetNow(now); zoom_map->SetZoomLevelForHost(kTestRegisterableDomain3, 2.0); // Remove everything changed during the last hour (domain3).
diff --git a/chrome/browser/chrome_content_browser_client.cc b/chrome/browser/chrome_content_browser_client.cc index 1fb9a93..4d27eec 100644 --- a/chrome/browser/chrome_content_browser_client.cc +++ b/chrome/browser/chrome_content_browser_client.cc
@@ -2995,7 +2995,7 @@ void ChromeContentBrowserClient::ExposeInterfacesToRenderer( service_manager::BinderRegistry* registry, - content::AssociatedInterfaceRegistry* associated_registry, + blink::AssociatedInterfaceRegistry* associated_registry, content::RenderProcessHost* render_process_host) { // The CacheStatsRecorder is an associated binding, instead of a // non-associated one, because the sender (in the renderer process) posts the
diff --git a/chrome/browser/chrome_content_browser_client.h b/chrome/browser/chrome_content_browser_client.h index 0c76ef9..72c9bbdd 100644 --- a/chrome/browser/chrome_content_browser_client.h +++ b/chrome/browser/chrome_content_browser_client.h
@@ -309,7 +309,7 @@ #endif void ExposeInterfacesToRenderer( service_manager::BinderRegistry* registry, - content::AssociatedInterfaceRegistry* associated_registry, + blink::AssociatedInterfaceRegistry* associated_registry, content::RenderProcessHost* render_process_host) override; void ExposeInterfacesToMediaService( service_manager::BinderRegistry* registry,
diff --git a/chrome/browser/chrome_content_browser_client_parts.h b/chrome/browser/chrome_content_browser_client_parts.h index 1713fc7..d794bff8 100644 --- a/chrome/browser/chrome_content_browser_client_parts.h +++ b/chrome/browser/chrome_content_browser_client_parts.h
@@ -16,8 +16,11 @@ class FilePath; } -namespace content { +namespace blink { class AssociatedInterfaceRegistry; +} + +namespace content { class BrowserContext; class BrowserURLHandler; class RenderProcessHost; @@ -71,7 +74,7 @@ // task runner is provided. virtual void ExposeInterfacesToRenderer( service_manager::BinderRegistry* registry, - content::AssociatedInterfaceRegistry* associated_registry, + blink::AssociatedInterfaceRegistry* associated_registry, content::RenderProcessHost* render_process_host) {} };
diff --git a/chrome/browser/chromeos/DEPS b/chrome/browser/chromeos/DEPS index e81aa0a..c0f0d58e 100644 --- a/chrome/browser/chromeos/DEPS +++ b/chrome/browser/chromeos/DEPS
@@ -24,6 +24,7 @@ "+media/mojo/interfaces", # For platform verification mojom interface. "+mojo/edk/embedder", "+services/device/public", + "+services/viz/public/interfaces", # Chromeos should not use ozone directly, it must go through mojo as ozone # does not run in process in mus. "-ui/ozone/public",
diff --git a/chrome/browser/chromeos/accessibility/accessibility_manager.cc b/chrome/browser/chromeos/accessibility/accessibility_manager.cc index eac1f79..b3467932 100644 --- a/chrome/browser/chromeos/accessibility/accessibility_manager.cc +++ b/chrome/browser/chromeos/accessibility/accessibility_manager.cc
@@ -241,7 +241,6 @@ switch_access_pref_handler_( ash::prefs::kAccessibilitySwitchAccessEnabled), sticky_keys_enabled_(false), - spoken_feedback_enabled_(false), autoclick_enabled_(false), autoclick_delay_ms_(ash::AutoclickController::GetDefaultAutoclickDelay()), virtual_keyboard_enabled_(false), @@ -445,7 +444,7 @@ spoken_feedback_notification_ = ash::A11Y_NOTIFICATION_NONE; } -void AccessibilityManager::UpdateSpokenFeedbackFromPref() { +void AccessibilityManager::OnSpokenFeedbackChanged() { if (!profile_) return; @@ -458,11 +457,6 @@ weak_ptr_factory_.GetWeakPtr())); } - if (spoken_feedback_enabled_ == enabled) - return; - - spoken_feedback_enabled_ = enabled; - AccessibilityStatusEventDetails details(ACCESSIBILITY_TOGGLE_SPOKEN_FEEDBACK, enabled, spoken_feedback_notification_); @@ -483,12 +477,8 @@ } bool AccessibilityManager::IsSpokenFeedbackEnabled() const { - return spoken_feedback_enabled_; -} - -void AccessibilityManager::ToggleSpokenFeedback( - ash::AccessibilityNotificationVisibility notify) { - EnableSpokenFeedback(!IsSpokenFeedbackEnabled(), notify); + return profile_ && profile_->GetPrefs()->GetBoolean( + ash::prefs::kAccessibilitySpokenFeedbackEnabled); } void AccessibilityManager::EnableHighContrast(bool enabled) { @@ -1046,7 +1036,7 @@ extension_ime_util::kBrailleImeEngineId); bool is_enabled = (it != preload_engines.end()); bool should_be_enabled = - (spoken_feedback_enabled_ && braille_display_connected_); + (IsSpokenFeedbackEnabled() && braille_display_connected_); if (is_enabled == should_be_enabled) return; if (should_be_enabled) @@ -1123,7 +1113,7 @@ base::Unretained(this))); pref_change_registrar_->Add( ash::prefs::kAccessibilitySpokenFeedbackEnabled, - base::Bind(&AccessibilityManager::UpdateSpokenFeedbackFromPref, + base::Bind(&AccessibilityManager::OnSpokenFeedbackChanged, base::Unretained(this))); pref_change_registrar_->Add( ash::prefs::kAccessibilityHighContrastEnabled, @@ -1211,7 +1201,6 @@ UpdateBrailleImeState(); UpdateAlwaysShowMenuFromPref(); UpdateStickyKeysFromPref(); - UpdateSpokenFeedbackFromPref(); UpdateAutoclickFromPref(); UpdateAutoclickDelayFromPref(); UpdateVirtualKeyboardFromPref(); @@ -1274,7 +1263,8 @@ if (details.notification_type != ACCESSIBILITY_MANAGER_SHUTDOWN && details.notification_type != ACCESSIBILITY_TOGGLE_HIGH_CONTRAST_MODE && details.notification_type != ACCESSIBILITY_TOGGLE_LARGE_CURSOR && - details.notification_type != ACCESSIBILITY_TOGGLE_MONO_AUDIO) { + details.notification_type != ACCESSIBILITY_TOGGLE_MONO_AUDIO && + details.notification_type != ACCESSIBILITY_TOGGLE_SPOKEN_FEEDBACK) { ash::Shell::Get()->system_tray_notifier()->NotifyAccessibilityStatusChanged( details.notify); } @@ -1376,7 +1366,13 @@ const DisplayState& display_state) { braille_display_connected_ = display_state.available; if (braille_display_connected_) { - EnableSpokenFeedback(true, ash::A11Y_NOTIFICATION_SHOW); + // TODO(crbug.com/594887): Fix for mash by moving notifying accessibility + // status change to ash for BrailleDisplayStateChanged. + if (GetAshConfig() == ash::Config::MASH) + return; + + ash::Shell::Get()->accessibility_controller()->SetSpokenFeedbackEnabled( + true, ash::A11Y_NOTIFICATION_SHOW); } UpdateBrailleImeState();
diff --git a/chrome/browser/chromeos/accessibility/accessibility_manager.h b/chrome/browser/chromeos/accessibility/accessibility_manager.h index 728c8a7..9d91757 100644 --- a/chrome/browser/chromeos/accessibility/accessibility_manager.h +++ b/chrome/browser/chromeos/accessibility/accessibility_manager.h
@@ -147,9 +147,6 @@ // Returns true if spoken feedback is enabled, or false if not. bool IsSpokenFeedbackEnabled() const; - // Toggles whether Chrome OS spoken feedback is on or off. - void ToggleSpokenFeedback(ash::AccessibilityNotificationVisibility notify); - // Enables or disables the high contrast mode for Chrome. void EnableHighContrast(bool enabled); @@ -312,7 +309,7 @@ void UpdateAlwaysShowMenuFromPref(); void OnLargeCursorChanged(); void UpdateStickyKeysFromPref(); - void UpdateSpokenFeedbackFromPref(); + void OnSpokenFeedbackChanged(); void OnHighContrastChanged(); void UpdateAutoclickFromPref(); void UpdateAutoclickDelayFromPref(); @@ -388,7 +385,6 @@ PrefHandler switch_access_pref_handler_; bool sticky_keys_enabled_; - bool spoken_feedback_enabled_; bool autoclick_enabled_; base::TimeDelta autoclick_delay_ms_; bool virtual_keyboard_enabled_;
diff --git a/chrome/browser/chromeos/accessibility/accessibility_manager_browsertest.cc b/chrome/browser/chromeos/accessibility/accessibility_manager_browsertest.cc index a7369eb..778060ba 100644 --- a/chrome/browser/chromeos/accessibility/accessibility_manager_browsertest.cc +++ b/chrome/browser/chromeos/accessibility/accessibility_manager_browsertest.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/chromeos/accessibility/accessibility_manager.h" +#include "ash/accessibility/accessibility_controller.h" #include "ash/magnifier/magnification_controller.h" #include "ash/public/cpp/accessibility_types.h" #include "ash/public/cpp/ash_pref_names.h" @@ -176,8 +177,10 @@ // Simulates how UserSessionManager starts a user session by loading user // profile and marking session as started. void StartUserSession(const AccountId& account_id) { - ProfileHelper::GetProfileByUserIdHashForTest( + Profile* profile = ProfileHelper::GetProfileByUserIdHashForTest( user_manager::UserManager::Get()->FindUser(account_id)->username_hash()); + ash::Shell::Get()->accessibility_controller()->SetPrefServiceForTest( + profile->GetPrefs()); session_manager::SessionManager::Get()->SessionStarted(); } @@ -280,8 +283,10 @@ void SetUpOnMainThread() override { // Sets the login-screen profile. - AccessibilityManager::Get()->SetProfileForTest( - ProfileHelper::GetSigninProfile()); + Profile* profile = ProfileHelper::GetSigninProfile(); + AccessibilityManager::Get()->SetProfileForTest(profile); + ash::Shell::Get()->accessibility_controller()->SetPrefServiceForTest( + profile->GetPrefs()); default_autoclick_delay_ = GetAutoclickDelay(); }
diff --git a/chrome/browser/chromeos/accessibility/touch_exploration_controller_browsertest.cc b/chrome/browser/chromeos/accessibility/touch_exploration_controller_browsertest.cc index 61cf0a2..9b1b5b6 100644 --- a/chrome/browser/chromeos/accessibility/touch_exploration_controller_browsertest.cc +++ b/chrome/browser/chromeos/accessibility/touch_exploration_controller_browsertest.cc
@@ -12,6 +12,7 @@ #include "base/test/simple_test_tick_clock.h" #include "base/time/time.h" #include "build/build_config.h" +#include "chrome/browser/chromeos/accessibility/accessibility_manager.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/test/base/in_process_browser_test.h" @@ -56,10 +57,8 @@ } void SwitchTouchExplorationMode(bool on) { - ash::AccessibilityDelegate* delegate = - ash::Shell::Get()->accessibility_delegate(); - if (on != delegate->IsSpokenFeedbackEnabled()) - delegate->ToggleSpokenFeedback(ash::A11Y_NOTIFICATION_NONE); + chromeos::AccessibilityManager::Get()->EnableSpokenFeedback( + on, ash::A11Y_NOTIFICATION_NONE); } base::TimeTicks Now() { return simulated_clock_->NowTicks(); }
diff --git a/chrome/browser/chromeos/arc/accessibility/ax_tree_source_arc.cc b/chrome/browser/chromeos/arc/accessibility/ax_tree_source_arc.cc index 70563e5..81d6ff8 100644 --- a/chrome/browser/chromeos/arc/accessibility/ax_tree_source_arc.cc +++ b/chrome/browser/chromeos/arc/accessibility/ax_tree_source_arc.cc
@@ -253,9 +253,8 @@ // These mappings were taken from accessibility utils (Android -> Chrome) and // BrowserAccessibilityAndroid. They do not completely match the above two // sources. - // The FOCUSABLE state is not mapped because Android places focusability on - // many ancestor nodes. MAP_STATE(AXBooleanProperty::EDITABLE, ui::AX_STATE_EDITABLE); + MAP_STATE(AXBooleanProperty::FOCUSABLE, ui::AX_STATE_FOCUSABLE); MAP_STATE(AXBooleanProperty::MULTI_LINE, ui::AX_STATE_MULTILINE); MAP_STATE(AXBooleanProperty::PASSWORD, ui::AX_STATE_PROTECTED); MAP_STATE(AXBooleanProperty::SELECTED, ui::AX_STATE_SELECTED);
diff --git a/chrome/browser/chromeos/arc/auth/arc_background_auth_code_fetcher.cc b/chrome/browser/chromeos/arc/auth/arc_background_auth_code_fetcher.cc index 4388346d..0e8a19d 100644 --- a/chrome/browser/chromeos/arc/auth/arc_background_auth_code_fetcher.cc +++ b/chrome/browser/chromeos/arc/auth/arc_background_auth_code_fetcher.cc
@@ -101,12 +101,39 @@ std::string request_string; base::JSONWriter::Write(request_data, &request_string); - auth_code_fetcher_ = net::URLFetcher::Create( - 0, GURL(kAuthTokenExchangeEndPoint), net::URLFetcher::POST, this); + const net::NetworkTrafficAnnotationTag traffic_annotation = + net::DefineNetworkTrafficAnnotation("arc_auth_code_fetcher", R"( + semantics { + sender: "ARC auth code fetcher" + description: + "Fetches auth code to be used for Google Play Store sign-in." + trigger: + "The user or administrator initially enables Google Play Store on " + "the device, and Google Play Store requests authorization code for " + "account setup. This is also triggered when the Google Play Store " + "detects that current credentials are revoked or invalid and " + "requests extra authorization code for the account re-sign in." + data: + "Device id and access token." + destination: GOOGLE_OWNED_SERVICE + } + policy { + cookies_allowed: NO + setting: + "There's no direct Chromium's setting to disable this, but you can " + "remove Google Play Store in Chrome's settings under the Google " + "Play Store section if this is allowed by policy." + policy_exception_justification: "Not implemented." + })"); + + auth_code_fetcher_ = + net::URLFetcher::Create(0, GURL(kAuthTokenExchangeEndPoint), + net::URLFetcher::POST, this, traffic_annotation); auth_code_fetcher_->SetRequestContext(request_context_getter_); auth_code_fetcher_->SetUploadData(kContentTypeJSON, request_string); - auth_code_fetcher_->SetLoadFlags(net::LOAD_DISABLE_CACHE | - net::LOAD_BYPASS_CACHE); + auth_code_fetcher_->SetLoadFlags( + net::LOAD_DISABLE_CACHE | net::LOAD_BYPASS_CACHE | + net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SAVE_COOKIES); auth_code_fetcher_->SetAutomaticallyRetryOnNetworkChanges( kGetAuthCodeNetworkRetry); auth_code_fetcher_->SetExtraRequestHeaders(kGetAuthCodeHeaders);
diff --git a/chrome/browser/chromeos/extensions/file_manager/private_api_strings.cc b/chrome/browser/chromeos/extensions/file_manager/private_api_strings.cc index f83c394..4a039704 100644 --- a/chrome/browser/chromeos/extensions/file_manager/private_api_strings.cc +++ b/chrome/browser/chromeos/extensions/file_manager/private_api_strings.cc
@@ -745,6 +745,8 @@ SET_STRING("UNMOUNT_DEVICE_BUTTON_LABEL", IDS_FILE_BROWSER_UNMOUNT_DEVICE_BUTTON_LABEL); SET_STRING("UNMOUNT_FAILED", IDS_FILE_BROWSER_UNMOUNT_FAILED); + SET_STRING("UNMOUNT_PROVIDED_FAILED", + IDS_FILE_BROWSER_UNMOUNT_PROVIDED_FAILED); SET_STRING("UNSUPPORTED_FILESYSTEM_WARNING", IDS_FILE_BROWSER_UNSUPPORTED_FILESYSTEM_WARNING); SET_STRING("UPLOAD_LABEL", IDS_FILE_BROWSER_UPLOAD_LABEL);
diff --git a/chrome/browser/chromeos/extensions/quick_unlock_private/quick_unlock_private_api.cc b/chrome/browser/chromeos/extensions/quick_unlock_private/quick_unlock_private_api.cc index 63bc80c..d71f8b81 100644 --- a/chrome/browser/chromeos/extensions/quick_unlock_private/quick_unlock_private_api.cc +++ b/chrome/browser/chromeos/extensions/quick_unlock_private/quick_unlock_private_api.cc
@@ -285,7 +285,10 @@ QuickUnlockPrivateSetModesFunction::QuickUnlockPrivateSetModesFunction() : chrome_details_(this) {} -QuickUnlockPrivateSetModesFunction::~QuickUnlockPrivateSetModesFunction() {} +QuickUnlockPrivateSetModesFunction::~QuickUnlockPrivateSetModesFunction() { + if (extended_authenticator_) + extended_authenticator_->SetConsumer(nullptr); +} void QuickUnlockPrivateSetModesFunction::SetAuthenticatorAllocatorForTesting( const QuickUnlockPrivateSetModesFunction::AuthenticatorAllocator& @@ -347,6 +350,7 @@ // Lazily allocate the authenticator. We do this here, instead of in the ctor, // so that tests can install a fake. + DCHECK(!extended_authenticator_); if (authenticator_allocator_.is_null()) extended_authenticator_ = chromeos::ExtendedAuthenticator::Create(this); else
diff --git a/chrome/browser/chromeos/first_run/goodies_displayer_browsertest.cc b/chrome/browser/chromeos/first_run/goodies_displayer_browsertest.cc index 2adf0b81..3a9a241 100644 --- a/chrome/browser/chromeos/first_run/goodies_displayer_browsertest.cc +++ b/chrome/browser/chromeos/first_run/goodies_displayer_browsertest.cc
@@ -85,10 +85,9 @@ // InProcessBrowserTest overrides. void SetUpDefaultCommandLine(base::CommandLine* command_line) override { base::CommandLine default_command_line(base::CommandLine::NO_PROGRAM); - if (command_line->HasSwitch(switches::kMash)) - default_command_line.AppendSwitch(switches::kMash); - else if (command_line->HasSwitch(switches::kMus)) - default_command_line.AppendSwitch(switches::kMus); + const char* kSwitchesToCopy[] = {switches::kMash, switches::kMus}; + default_command_line.CopySwitchesFrom(*command_line, kSwitchesToCopy, + arraysize(kSwitchesToCopy)); InProcessBrowserTest::SetUpDefaultCommandLine(&default_command_line); if (NoFirstRunSpecified()) { // --no-first-run is present by default. *command_line = default_command_line;
diff --git a/chrome/browser/chromeos/login/active_directory_login_browsertest.cc b/chrome/browser/chromeos/login/active_directory_login_browsertest.cc index e34f46a..6a4975a 100644 --- a/chrome/browser/chromeos/login/active_directory_login_browsertest.cc +++ b/chrome/browser/chromeos/login/active_directory_login_browsertest.cc
@@ -6,6 +6,7 @@ #include "base/command_line.h" #include "base/location.h" +#include "base/path_service.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/strings/string_util.h" @@ -20,12 +21,15 @@ #include "chrome/browser/chromeos/login/wizard_controller.h" #include "chrome/browser/chromeos/settings/stub_install_attributes.h" #include "chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h" +#include "chrome/common/chrome_paths.h" #include "chrome/grit/generated_resources.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/interactive_test_utils.h" +#include "chromeos/chromeos_paths.h" #include "chromeos/chromeos_switches.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/fake_auth_policy_client.h" +#include "chromeos/dbus/fake_cryptohome_client.h" #include "chromeos/login/auth/authpolicy_login_helper.h" #include "components/signin/core/account_id/account_id.h" #include "components/user_manager/user_names.h" @@ -43,7 +47,6 @@ constexpr char kAdOfflineAuthId[] = "offline-ad-auth"; -constexpr char kDeviceId[] = "device_id"; constexpr char kAdMachineName[] = "machine_name"; constexpr char kTestActiveDirectoryUser[] = "test-user"; constexpr char kAdMachineInput[] = "machineNameInput"; @@ -64,14 +67,15 @@ constexpr char kCloseButtonId[] = "closeButton"; // Used for the callback from FakeAuthPolicy::JoinAdDomain. -void OnJoinedDomain(authpolicy::ErrorType error) { +void OnJoinedDomain(base::OnceClosure closure, authpolicy::ErrorType error) { EXPECT_EQ(authpolicy::ERROR_NONE, error); + std::move(closure).Run(); } // Used for the callback from FakeAuthPolicy::RefreshDevicePolicy. -void OnRefreshedPolicy(const base::Closure& closure, bool status) { - EXPECT_TRUE(status); - closure.Run(); +void OnRefreshedPolicy(base::OnceClosure closure, authpolicy::ErrorType error) { + EXPECT_EQ(authpolicy::ERROR_NONE, error); + std::move(closure).Run(); } class TestAuthPolicyClient : public FakeAuthPolicyClient { @@ -105,11 +109,7 @@ : LoginManagerTest(true), // Using the same realm as supervised user domain. Should be treated as // normal realm. - test_realm_(user_manager::kSupervisedUserDomain), - install_attributes_( - ScopedStubInstallAttributes::CreateActiveDirectoryManaged( - test_realm_, - kDeviceId)) {} + test_realm_(user_manager::kSupervisedUserDomain) {} ~ActiveDirectoryLoginTest() override = default; @@ -118,6 +118,15 @@ LoginManagerTest::SetUp(); } + void SetUpInProcessBrowserTestFixture() override { + LoginManagerTest::SetUpInProcessBrowserTestFixture(); + base::FilePath user_data_dir; + ASSERT_TRUE(PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)); + chromeos::RegisterStubPathOverrides(user_data_dir); + DBusThreadManager::GetSetterForTesting()->SetCryptohomeClient( + std::make_unique<FakeCryptohomeClient>()); + } + void SetUpCommandLine(base::CommandLine* command_line) override { command_line->AppendSwitch(switches::kOobeSkipPostLogin); LoginManagerTest::SetUpCommandLine(command_line); @@ -137,14 +146,23 @@ void MarkAsActiveDirectoryEnterprise() { StartupUtils::MarkOobeCompleted(); - base::RunLoop loop; - AuthPolicyLoginHelper().JoinAdDomain( - kAdMachineName, kTestActiveDirectoryUser + ("@" + test_realm_), - "" /* password */, base::BindOnce(&OnJoinedDomain)); - - fake_auth_policy_client()->RefreshDevicePolicy( - base::BindOnce(&OnRefreshedPolicy, loop.QuitClosure())); - loop.Run(); + AuthPolicyLoginHelper helper; + { + base::RunLoop loop; + helper.JoinAdDomain(kAdMachineName, + kTestActiveDirectoryUser + ("@" + test_realm_), + "" /* password */, + base::BindOnce(&OnJoinedDomain, loop.QuitClosure())); + loop.Run(); + } + ASSERT_TRUE(AuthPolicyLoginHelper::LockDeviceActiveDirectoryForTesting( + test_realm_)); + { + base::RunLoop loop; + fake_auth_policy_client()->RefreshDevicePolicy( + base::BindOnce(&OnRefreshedPolicy, loop.QuitClosure())); + loop.Run(); + } } void TriggerPasswordChangeScreen() { @@ -318,7 +336,6 @@ const std::string test_realm_; private: - ScopedStubInstallAttributes install_attributes_; TestAuthPolicyClient* fake_auth_policy_client_; DISALLOW_COPY_AND_ASSIGN(ActiveDirectoryLoginTest);
diff --git a/chrome/browser/chromeos/login/existing_user_controller_browsertest.cc b/chrome/browser/chromeos/login/existing_user_controller_browsertest.cc index 1491409..a3e56a3e 100644 --- a/chrome/browser/chromeos/login/existing_user_controller_browsertest.cc +++ b/chrome/browser/chromeos/login/existing_user_controller_browsertest.cc
@@ -37,6 +37,7 @@ #include "chrome/test/base/testing_browser_process.h" #include "chromeos/chromeos_switches.h" #include "chromeos/dbus/fake_session_manager_client.h" +#include "chromeos/login/auth/authpolicy_login_helper.h" #include "chromeos/login/auth/key.h" #include "chromeos/login/auth/mock_url_fetchers.h" #include "chromeos/login/auth/user_context.h" @@ -760,15 +761,14 @@ ExistingUserControllerActiveDirectoryTest() = default; // Overriden from DevicePolicyCrosBrowserTest: - void MarkOwnership() override { - policy::DevicePolicyCrosTestHelper::MarkAsActiveDirectoryEnterpriseOwned( - kActiveDirectoryRealm); - } + void MarkOwnership() override {} // Overriden from ExistingUserControllerTest: void SetUpInProcessBrowserTestFixture() override { - RefreshDevicePolicy(); ExistingUserControllerTest::SetUpInProcessBrowserTestFixture(); + ASSERT_TRUE(AuthPolicyLoginHelper::LockDeviceActiveDirectoryForTesting( + kActiveDirectoryRealm)); + RefreshDevicePolicy(); } void TearDownOnMainThread() override {
diff --git a/chrome/browser/chromeos/login/lock/screen_locker.cc b/chrome/browser/chromeos/login/lock/screen_locker.cc index 86f4b0f..de71ef7 100644 --- a/chrome/browser/chromeos/login/lock/screen_locker.cc +++ b/chrome/browser/chromeos/login/lock/screen_locker.cc
@@ -573,8 +573,11 @@ VLOG(1) << "Destroying ScreenLocker " << this; DCHECK(base::MessageLoopForUI::IsCurrent()); - if (authenticator_.get()) + if (authenticator_) authenticator_->SetConsumer(nullptr); + if (extended_authenticator_) + extended_authenticator_->SetConsumer(nullptr); + ClearErrors(); screen_locker_ = nullptr;
diff --git a/chrome/browser/chromeos/login/ui/webui_login_view.cc b/chrome/browser/chromeos/login/ui/webui_login_view.cc index 7e2608a6..0d46148 100644 --- a/chrome/browser/chromeos/login/ui/webui_login_view.cc +++ b/chrome/browser/chromeos/login/ui/webui_login_view.cc
@@ -452,11 +452,11 @@ //////////////////////////////////////////////////////////////////////////////// // keyboard::KeyboardControllerObserver: -void WebUILoginView::OnKeyboardBoundsChanging(const gfx::Rect& new_bounds) { +void WebUILoginView::OnKeyboardAvailabilityChanging(const bool is_available) { if (!GetOobeUI()) return; CoreOobeView* view = GetOobeUI()->GetCoreOobeView(); - if (new_bounds.IsEmpty()) { + if (!is_available) { // Keyboard has been hidden. view->ShowControlBar(true); view->SetVirtualKeyboardShown(false); @@ -467,8 +467,6 @@ } } -void WebUILoginView::OnKeyboardClosed() {} - // WebUILoginView private: ----------------------------------------------------- bool WebUILoginView::HandleContextMenu(
diff --git a/chrome/browser/chromeos/login/ui/webui_login_view.h b/chrome/browser/chromeos/login/ui/webui_login_view.h index c837109..b4cd1d5 100644 --- a/chrome/browser/chromeos/login/ui/webui_login_view.h +++ b/chrome/browser/chromeos/login/ui/webui_login_view.h
@@ -152,8 +152,7 @@ aura::Window* root_window) override; // keyboard::KeyboardControllerObserver: - void OnKeyboardBoundsChanging(const gfx::Rect& new_bounds) override; - void OnKeyboardClosed() override; + void OnKeyboardAvailabilityChanging(bool is_available) override; // Overridden from content::WebContentsDelegate. bool HandleContextMenu(const content::ContextMenuParams& params) override;
diff --git a/chrome/browser/chromeos/policy/active_directory_policy_manager.cc b/chrome/browser/chromeos/policy/active_directory_policy_manager.cc index fc1fcbf..ca2437c 100644 --- a/chrome/browser/chromeos/policy/active_directory_policy_manager.cc +++ b/chrome/browser/chromeos/policy/active_directory_policy_manager.cc
@@ -21,6 +21,11 @@ // https://technet.microsoft.com/en-us/library/cc940895.aspx constexpr base::TimeDelta kFetchInterval = base::TimeDelta::FromMinutes(90); +void RunRefreshCallback(base::OnceCallback<void(bool success)> callback, + authpolicy::ErrorType error) { + std::move(callback).Run(error == authpolicy::ERROR_NONE); +} + } // namespace namespace policy { @@ -168,9 +173,11 @@ thread_manager->GetAuthPolicyClient(); DCHECK(auth_policy_client); if (account_id_ == EmptyAccountId()) { - auth_policy_client->RefreshDevicePolicy(std::move(callback)); + auth_policy_client->RefreshDevicePolicy( + base::BindOnce(&RunRefreshCallback, std::move(callback))); } else { - auth_policy_client->RefreshUserPolicy(account_id_, std::move(callback)); + auth_policy_client->RefreshUserPolicy( + account_id_, base::BindOnce(&RunRefreshCallback, std::move(callback))); } }
diff --git a/chrome/browser/chromeos/policy/active_directory_policy_manager_unittest.cc b/chrome/browser/chromeos/policy/active_directory_policy_manager_unittest.cc index b7afeb5..1d9aacb0 100644 --- a/chrome/browser/chromeos/policy/active_directory_policy_manager_unittest.cc +++ b/chrome/browser/chromeos/policy/active_directory_policy_manager_unittest.cc
@@ -58,7 +58,7 @@ RefreshPolicyCallback callback) override { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(std::move(callback), - refresh_user_policy_callback_success_)); + refresh_user_policy_callback_error_)); } void ConnectToSignal( @@ -68,12 +68,13 @@ NOTIMPLEMENTED(); } - void SetRefreshUserPolicyCallbackSuccess(bool success) { - refresh_user_policy_callback_success_ = success; + void SetRefreshUserPolicyCallbackError(authpolicy::ErrorType error) { + refresh_user_policy_callback_error_ = error; } private: - bool refresh_user_policy_callback_success_ = true; + authpolicy::ErrorType refresh_user_policy_callback_error_ = + authpolicy::ERROR_NONE; }; } // namespace @@ -154,7 +155,7 @@ EXPECT_FALSE(policy_manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); // Configure mock policy fetch to fail. - mock_client_->SetRefreshUserPolicyCallbackSuccess(false); + mock_client_->SetRefreshUserPolicyCallbackError(authpolicy::ERROR_UNKNOWN); // Trigger mock policy fetch from authpolicyd. policy_manager_->Init(&schema_registry_); @@ -185,7 +186,7 @@ EXPECT_FALSE(policy_manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); // Configure mock policy fetch to succeed. - mock_client_->SetRefreshUserPolicyCallbackSuccess(true); + mock_client_->SetRefreshUserPolicyCallbackError(authpolicy::ERROR_NONE); // Trigger mock policy fetch from authpolicyd. policy_manager_->Init(&schema_registry_); @@ -215,7 +216,7 @@ EXPECT_FALSE(policy_manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); // Configure mock policy fetch to succeed. - mock_client_->SetRefreshUserPolicyCallbackSuccess(true); + mock_client_->SetRefreshUserPolicyCallbackError(authpolicy::ERROR_NONE); // Trigger mock policy fetch from authpolicyd. policy_manager_->Init(&schema_registry_); @@ -252,7 +253,7 @@ EXPECT_FALSE(policy_manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); // Configure mock policy fetch to fail. - mock_client_->SetRefreshUserPolicyCallbackSuccess(false); + mock_client_->SetRefreshUserPolicyCallbackError(authpolicy::ERROR_UNKNOWN); // Trigger mock policy fetch from authpolicyd. policy_manager_->Init(&schema_registry_); @@ -287,7 +288,7 @@ EXPECT_FALSE(policy_manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); // Configure mock policy fetch to fail. - mock_client_->SetRefreshUserPolicyCallbackSuccess(false); + mock_client_->SetRefreshUserPolicyCallbackError(authpolicy::ERROR_UNKNOWN); // Trigger mock policy fetch from authpolicyd. policy_manager_->Init(&schema_registry_); @@ -321,7 +322,7 @@ EXPECT_FALSE(policy_manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); // Configure mock policy fetch to fail. - mock_client_->SetRefreshUserPolicyCallbackSuccess(false); + mock_client_->SetRefreshUserPolicyCallbackError(authpolicy::ERROR_UNKNOWN); // Trigger mock policy fetch from authpolicyd. policy_manager_->Init(&schema_registry_); @@ -347,7 +348,7 @@ EXPECT_FALSE(policy_manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); // Configure mock policy fetch to fail. - mock_client_->SetRefreshUserPolicyCallbackSuccess(false); + mock_client_->SetRefreshUserPolicyCallbackError(authpolicy::ERROR_UNKNOWN); // Trigger mock policy fetch from authpolicyd. policy_manager_->Init(&schema_registry_); @@ -382,7 +383,7 @@ EXPECT_FALSE(policy_manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); // Configure mock policy fetch to fail. - mock_client_->SetRefreshUserPolicyCallbackSuccess(false); + mock_client_->SetRefreshUserPolicyCallbackError(authpolicy::ERROR_UNKNOWN); // Trigger mock policy fetch from authpolicyd. policy_manager_->Init(&schema_registry_); @@ -416,7 +417,7 @@ EXPECT_FALSE(policy_manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME)); // Configure mock policy fetch to fail. - mock_client_->SetRefreshUserPolicyCallbackSuccess(false); + mock_client_->SetRefreshUserPolicyCallbackError(authpolicy::ERROR_UNKNOWN); // Trigger mock policy fetch from authpolicyd. policy_manager_->Init(&schema_registry_);
diff --git a/chrome/browser/chromeos/policy/device_policy_cros_browser_test.cc b/chrome/browser/chromeos/policy/device_policy_cros_browser_test.cc index 296554e..7ce2cfa2 100644 --- a/chrome/browser/chromeos/policy/device_policy_cros_browser_test.cc +++ b/chrome/browser/chromeos/policy/device_policy_cros_browser_test.cc
@@ -18,6 +18,7 @@ #include "chromeos/chromeos_paths.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/fake_session_manager_client.h" +#include "chromeos/login/auth/authpolicy_login_helper.h" #include "crypto/rsa_private_key.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -58,10 +59,9 @@ void DevicePolicyCrosTestHelper::MarkAsActiveDirectoryEnterpriseOwned( const std::string& realm) { OverridePaths(); - WriteInstallAttributesFile( - chromeos::InstallAttributes:: - GetActiveDirectoryEnterpriseOwnedInstallAttributesBlobForTesting( - realm)); + ASSERT_TRUE( + chromeos::AuthPolicyLoginHelper::LockDeviceActiveDirectoryForTesting( + realm)); } void DevicePolicyCrosTestHelper::MarkAsEnterpriseOwned() {
diff --git a/chrome/browser/chromeos/policy/enrollment_handler_chromeos.cc b/chrome/browser/chromeos/policy/enrollment_handler_chromeos.cc index 86ce060..f271848 100644 --- a/chrome/browser/chromeos/policy/enrollment_handler_chromeos.cc +++ b/chrome/browser/chromeos/policy/enrollment_handler_chromeos.cc
@@ -667,10 +667,10 @@ } void EnrollmentHandlerChromeOS::HandleActiveDirectoryPolicyRefreshed( - bool success) { + authpolicy::ErrorType error) { DCHECK_EQ(STEP_STORE_POLICY, enrollment_step_); - if (!success) { + if (error != authpolicy::ERROR_NONE) { LOG(ERROR) << "Failed to load Active Directory policy."; ReportResult(EnrollmentStatus::ForStatus( EnrollmentStatus::ACTIVE_DIRECTORY_POLICY_FETCH_FAILED));
diff --git a/chrome/browser/chromeos/policy/enrollment_handler_chromeos.h b/chrome/browser/chromeos/policy/enrollment_handler_chromeos.h index c0dea2c..0e6fd0e 100644 --- a/chrome/browser/chromeos/policy/enrollment_handler_chromeos.h +++ b/chrome/browser/chromeos/policy/enrollment_handler_chromeos.h
@@ -17,6 +17,7 @@ #include "chrome/browser/chromeos/policy/device_cloud_policy_validator.h" #include "chrome/browser/chromeos/policy/enrollment_config.h" #include "chrome/browser/chromeos/settings/install_attributes.h" +#include "chromeos/dbus/auth_policy_client.h" #include "components/policy/core/common/cloud/cloud_policy_client.h" #include "components/policy/core/common/cloud/cloud_policy_constants.h" #include "components/policy/core/common/cloud/cloud_policy_store.h" @@ -197,7 +198,7 @@ void HandleStoreRobotAuthTokenResult(bool result); // Handles result from device policy refresh via authpolicyd. - void HandleActiveDirectoryPolicyRefreshed(bool success); + void HandleActiveDirectoryPolicyRefreshed(authpolicy::ErrorType error); // Drops any ongoing actions. void Stop();
diff --git a/chrome/browser/chromeos/power/ml/idle_event_notifier.cc b/chrome/browser/chromeos/power/ml/idle_event_notifier.cc index a4b4808..65dbd827 100644 --- a/chrome/browser/chromeos/power/ml/idle_event_notifier.cc +++ b/chrome/browser/chromeos/power/ml/idle_event_notifier.cc
@@ -9,20 +9,46 @@ #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/power_manager/idle.pb.h" #include "chromeos/dbus/power_manager/suspend.pb.h" +#include "ui/base/user_activity/user_activity_detector.h" +#include "ui/events/event.h" +#include "ui/events/event_constants.h" namespace chromeos { namespace power { namespace ml { -IdleEventNotifier::IdleEventNotifier(const base::TimeDelta& idle_delay) - : idle_delay_(idle_delay), clock_(std::make_unique<base::DefaultClock>()) { - chromeos::DBusThreadManager::Get()->GetPowerManagerClient()->AddObserver( - this); +IdleEventNotifier::ActivityData::ActivityData() = default; +IdleEventNotifier::ActivityData::ActivityData(base::Time last_activity_time, + base::Time earliest_activity_time) + : last_activity_time(last_activity_time), + earliest_activity_time(earliest_activity_time) {} + +IdleEventNotifier::ActivityData::ActivityData(const ActivityData& input_data) { + last_activity_time = input_data.last_activity_time; + earliest_activity_time = input_data.earliest_activity_time; + last_user_activity_time = input_data.last_user_activity_time; + last_mouse_time = input_data.last_mouse_time; + last_key_time = input_data.last_key_time; +} + +IdleEventNotifier::IdleEventNotifier( + PowerManagerClient* power_client, + viz::mojom::VideoDetectorObserverRequest request) + : clock_(std::make_unique<base::DefaultClock>()), + power_client_(power_client), + binding_(this, std::move(request)) { + DCHECK(power_client_); + power_client_->AddObserver(this); + ui::UserActivityDetector* detector = ui::UserActivityDetector::Get(); + DCHECK(detector); + detector->AddObserver(this); } IdleEventNotifier::~IdleEventNotifier() { - chromeos::DBusThreadManager::Get()->GetPowerManagerClient()->RemoveObserver( - this); + power_client_->RemoveObserver(this); + ui::UserActivityDetector* detector = ui::UserActivityDetector::Get(); + DCHECK(detector); + detector->RemoveObserver(this); } void IdleEventNotifier::SetClockForTesting( @@ -45,7 +71,7 @@ const base::TimeTicks& /* timestamp */) { // Ignore lid-close event, as we will observe suspend signal. if (state == chromeos::PowerManagerClient::LidState::OPEN) { - last_activity_time_ = clock_->Now(); + UpdateActivityData(ActivityType::USER_OTHER); ResetIdleDelayTimer(); } } @@ -54,8 +80,7 @@ const power_manager::PowerSupplyProperties& proto) { if (external_power_ != proto.external_power()) { external_power_ = proto.external_power(); - last_activity_time_ = clock_->Now(); - // Power change is a user activity, so reset timer. + UpdateActivityData(ActivityType::USER_OTHER); ResetIdleDelayTimer(); } } @@ -63,10 +88,10 @@ void IdleEventNotifier::SuspendImminent( power_manager::SuspendImminent::Reason reason) { if (idle_delay_timer_.IsRunning()) { - // This means the user hasn't been idle for more than kModelStartDelaySec. - // Regardless of the reason of suspend, we won't be emitting any idle event - // now or following SuspendDone. - // We stop the timer to prevent it from resuming in SuspendDone. + // This means the user hasn't been idle for more than idle_delay. Regardless + // of the reason of suspend, we won't be emitting any idle event now or + // following SuspendDone. We stop the timer to prevent it from resuming in + // SuspendDone. idle_delay_timer_.Stop(); } } @@ -75,20 +100,80 @@ // TODO(jiameng): consider check sleep_duration to decide whether to log // event. DCHECK(!idle_delay_timer_.IsRunning()); - last_activity_time_ = clock_->Now(); + // SuspendDone is triggered by user opening the lid (or other user + // activities). + UpdateActivityData(ActivityType::USER_OTHER); + ResetIdleDelayTimer(); +} + +void IdleEventNotifier::OnUserActivity(const ui::Event* event) { + if (!event) + return; + // Get the type of activity first then reset timer. + ActivityType type = ActivityType::USER_OTHER; + if (event->IsKeyEvent()) { + type = ActivityType::KEY; + } else if (event->IsMouseEvent() || event->IsTouchEvent()) { + type = ActivityType::MOUSE; + } + UpdateActivityData(type); + ResetIdleDelayTimer(); +} + +void IdleEventNotifier::OnVideoActivityStarted() { + video_playing_ = true; + UpdateActivityData(ActivityType::VIDEO); +} + +void IdleEventNotifier::OnVideoActivityEnded() { + video_playing_ = false; + UpdateActivityData(ActivityType::VIDEO); ResetIdleDelayTimer(); } void IdleEventNotifier::ResetIdleDelayTimer() { + // According to the policy, if there's video playing we should never dim or + // turn off the screen (or transition to any other lower energy state). + if (video_playing_) + return; + idle_delay_timer_.Start(FROM_HERE, idle_delay_, this, &IdleEventNotifier::OnIdleDelayTimeout); } void IdleEventNotifier::OnIdleDelayTimeout() { - ActivityData activity_data; - activity_data.last_activity_time = last_activity_time_; + if (video_playing_) + return; + for (auto& observer : observers_) - observer.OnIdleEventObserved(activity_data); + observer.OnIdleEventObserved(data_); + data_ = {}; +} + +void IdleEventNotifier::UpdateActivityData(ActivityType type) { + base::Time now = clock_->Now(); + data_.last_activity_time = now; + if (data_.earliest_activity_time == base::Time()) { + data_.earliest_activity_time = now; + } + + if (type == ActivityType::VIDEO) + return; + + // All other activity is user-initiated. + data_.last_user_activity_time = now; + + switch (type) { + case ActivityType::KEY: + data_.last_key_time = now; + break; + case ActivityType::MOUSE: + data_.last_mouse_time = now; + break; + default: + // We don't track other activity types. + return; + } } } // namespace ml
diff --git a/chrome/browser/chromeos/power/ml/idle_event_notifier.h b/chrome/browser/chromeos/power/ml/idle_event_notifier.h index 8ae74781..e51a9e9 100644 --- a/chrome/browser/chromeos/power/ml/idle_event_notifier.h +++ b/chrome/browser/chromeos/power/ml/idle_event_notifier.h
@@ -14,6 +14,9 @@ #include "base/timer/timer.h" #include "chromeos/dbus/power_manager/power_supply_properties.pb.h" #include "chromeos/dbus/power_manager_client.h" +#include "mojo/public/cpp/bindings/binding.h" +#include "services/viz/public/interfaces/compositing/video_detector_observer.mojom.h" +#include "ui/base/user_activity/user_activity_observer.h" namespace base { class Clock; @@ -27,11 +30,37 @@ // event is generated. An idle event is generated when the idle period reaches // |idle_delay_|. No further idle events will be generated until user becomes // active again, followed by an idle period of |idle_delay_|. -class IdleEventNotifier : public PowerManagerClient::Observer { +class IdleEventNotifier : public PowerManagerClient::Observer, + public ui::UserActivityObserver, + public viz::mojom::VideoDetectorObserver { public: struct ActivityData { - // Last activity time. + ActivityData(); + ActivityData(base::Time last_activity_time, + base::Time earliest_activity_time); + + ActivityData(const ActivityData& input_data); + + // Last activity time. This is the activity that triggers idle event. base::Time last_activity_time; + + // Earliest activity time of a *sequence* of activities: whose idle period + // gap is smaller than |idle_delay_|. This value will be the same as + // |last_activity_time| if the earlier activity happened more than + // |idle_delay_| ago. + base::Time earliest_activity_time; + + // Last user activity time of the sequence of activities ending in the last + // activity. It could be different from |last_activity_time| if the last + // activity is not a user activity (e.g. video). It is unset (i.e. 0) if + // there is no user activity before the idle event is fired. + base::Time last_user_activity_time; + + // Last mouse/key event time of the sequence of activities ending in the + // last activity. It is unset (i.e. 0) if there is no mouse/key activity + // before the idle event. + base::Time last_mouse_time; + base::Time last_key_time; }; class Observer { @@ -43,7 +72,8 @@ virtual ~Observer() {} }; - explicit IdleEventNotifier(const base::TimeDelta& idle_delay); + IdleEventNotifier(PowerManagerClient* power_client, + viz::mojom::VideoDetectorObserverRequest request); ~IdleEventNotifier() override; // Set test clock so that we can check activity time. @@ -60,6 +90,13 @@ void SuspendImminent(power_manager::SuspendImminent::Reason reason) override; void SuspendDone(const base::TimeDelta& sleep_duration) override; + // ui::UserActivityObserver overrides: + void OnUserActivity(const ui::Event* event) override; + + // viz::mojom::VideoDetectorObserver overrides: + void OnVideoActivityStarted() override; + void OnVideoActivityEnded() override; + const base::TimeDelta& idle_delay() const { return idle_delay_; } void set_idle_delay(const base::TimeDelta& delay) { idle_delay_ = delay; } @@ -67,26 +104,40 @@ FRIEND_TEST_ALL_PREFIXES(IdleEventNotifierTest, CheckInitialValues); friend class IdleEventNotifierTest; + enum class ActivityType { + USER_OTHER, // All other user-related activities. + KEY, + MOUSE, + VIDEO, + }; + // Resets |idle_delay_timer_|, it's called when a new activity is observed. void ResetIdleDelayTimer(); + // Called when |idle_delay_timer_| expires. void OnIdleDelayTimeout(); - base::TimeDelta idle_delay_; + // Updates all activity-related timestamps. + void UpdateActivityData(ActivityType type); + + base::TimeDelta idle_delay_ = base::TimeDelta::FromSeconds(10); // It is base::DefaultClock, but will be set to a mock clock for tests. std::unique_ptr<base::Clock> clock_; base::OneShotTimer idle_delay_timer_; + PowerManagerClient* power_client_; // not owned. // Last-received external power state. Changes are treated as user activity. base::Optional<power_manager::PowerSupplyProperties_ExternalPower> external_power_; base::ObserverList<Observer> observers_; - // Time of last activity, which may be a user or non-user activity (e.g. - // video). - base::Time last_activity_time_; + ActivityData data_; + + // Whether video is playing. + bool video_playing_ = false; + mojo::Binding<viz::mojom::VideoDetectorObserver> binding_; DISALLOW_COPY_AND_ASSIGN(IdleEventNotifier); };
diff --git a/chrome/browser/chromeos/power/ml/idle_event_notifier_unittest.cc b/chrome/browser/chromeos/power/ml/idle_event_notifier_unittest.cc index 1f85e98..66edc0f 100644 --- a/chrome/browser/chromeos/power/ml/idle_event_notifier_unittest.cc +++ b/chrome/browser/chromeos/power/ml/idle_event_notifier_unittest.cc
@@ -9,11 +9,14 @@ #include "base/memory/ptr_util.h" #include "base/test/test_mock_time_task_runner.h" #include "base/time/clock.h" -#include "chromeos/dbus/dbus_thread_manager.h" +#include "chromeos/dbus/fake_power_manager_client.h" #include "chromeos/dbus/power_manager/idle.pb.h" #include "chromeos/dbus/power_manager/power_supply_properties.pb.h" #include "chromeos/dbus/power_manager/suspend.pb.h" #include "testing/gtest/include/gtest/gtest.h" +#include "ui/base/user_activity/user_activity_detector.h" +#include "ui/events/event.h" +#include "ui/events/event_constants.h" namespace chromeos { namespace power { @@ -21,11 +24,13 @@ namespace { -// TODO(jiameng): we will add more fields to ActivityData, hence we define an -// equality comparison below for tests. bool operator==(const IdleEventNotifier::ActivityData& x, const IdleEventNotifier::ActivityData& y) { - return x.last_activity_time == y.last_activity_time; + return x.last_activity_time == y.last_activity_time && + x.earliest_activity_time == y.earliest_activity_time && + x.last_user_activity_time == y.last_user_activity_time && + x.last_mouse_time == y.last_mouse_time && + x.last_key_time == y.last_key_time; } class TestObserver : public IdleEventNotifier::Observer { @@ -59,9 +64,9 @@ : task_runner_(base::MakeRefCounted<base::TestMockTimeTaskRunner>( base::TestMockTimeTaskRunner::Type::kBoundToThread)), scoped_context_(task_runner_.get()) { - chromeos::DBusThreadManager::Initialize(); - idle_event_notifier_ = - std::make_unique<IdleEventNotifier>(base::TimeDelta::FromSeconds(1)); + viz::mojom::VideoDetectorObserverPtr observer; + idle_event_notifier_ = std::make_unique<IdleEventNotifier>( + &power_client_, mojo::MakeRequest(&observer)); idle_event_notifier_->SetClockForTesting(task_runner_->GetMockClock()); idle_event_notifier_->AddObserver(&test_observer_); ac_power_.set_external_power( @@ -71,9 +76,7 @@ } ~IdleEventNotifierTest() override { - // Destroy idle event notifier before DBusThreadManager is shut down. idle_event_notifier_.reset(); - chromeos::DBusThreadManager::Shutdown(); } protected: @@ -92,6 +95,8 @@ std::unique_ptr<IdleEventNotifier> idle_event_notifier_; power_manager::PowerSupplyProperties ac_power_; power_manager::PowerSupplyProperties disconnected_power_; + FakePowerManagerClient power_client_; + ui::UserActivityDetector user_activity_detector_; private: DISALLOW_COPY_AND_ASSIGN(IdleEventNotifierTest); @@ -109,14 +114,15 @@ base::Time now = task_runner_->Now(); idle_event_notifier_->LidEventReceived( chromeos::PowerManagerClient::LidState::OPEN, base::TimeTicks::Now()); - FastForwardAndCheckResults(1, {now}); + IdleEventNotifier::ActivityData data(now, now); + data.last_user_activity_time = now; + FastForwardAndCheckResults(1, data); } // Lid-closed event will not trigger any future idle event to be generated. TEST_F(IdleEventNotifierTest, LidClosedEventReceived) { idle_event_notifier_->LidEventReceived( chromeos::PowerManagerClient::LidState::CLOSED, base::TimeTicks::Now()); - IdleEventNotifier::ActivityData expected_activity_data; FastForwardAndCheckResults(0, {}); } @@ -126,7 +132,9 @@ TEST_F(IdleEventNotifierTest, PowerChangedFirstSet) { base::Time now = task_runner_->Now(); idle_event_notifier_->PowerChanged(ac_power_); - FastForwardAndCheckResults(1, {now}); + IdleEventNotifier::ActivityData data(now, now); + data.last_user_activity_time = now; + FastForwardAndCheckResults(1, data); } // PowerChanged signal is received but source isn't changed, so it won't trigger @@ -134,9 +142,11 @@ TEST_F(IdleEventNotifierTest, PowerSourceNotChanged) { base::Time now = task_runner_->Now(); idle_event_notifier_->PowerChanged(ac_power_); - FastForwardAndCheckResults(1, {now}); + IdleEventNotifier::ActivityData data(now, now); + data.last_user_activity_time = now; + FastForwardAndCheckResults(1, data); idle_event_notifier_->PowerChanged(ac_power_); - FastForwardAndCheckResults(1, {now}); + FastForwardAndCheckResults(1, data); } // PowerChanged signal is received and source is changed, so it will trigger @@ -144,11 +154,15 @@ TEST_F(IdleEventNotifierTest, PowerSourceChanged) { base::Time now_1 = task_runner_->Now(); idle_event_notifier_->PowerChanged(ac_power_); - FastForwardAndCheckResults(1, {now_1}); + IdleEventNotifier::ActivityData data_1(now_1, now_1); + data_1.last_user_activity_time = now_1; + FastForwardAndCheckResults(1, data_1); task_runner_->FastForwardBy(base::TimeDelta::FromSeconds(100)); base::Time now_2 = task_runner_->Now(); idle_event_notifier_->PowerChanged(disconnected_power_); - FastForwardAndCheckResults(2, {now_2}); + IdleEventNotifier::ActivityData data_2(now_2, now_2); + data_2.last_user_activity_time = now_2; + FastForwardAndCheckResults(2, data_2); } // SuspendImminent will not trigger any future idle event. @@ -165,7 +179,105 @@ TEST_F(IdleEventNotifierTest, SuspendDone) { base::Time now = task_runner_->Now(); idle_event_notifier_->SuspendDone(base::TimeDelta::FromSeconds(1)); - FastForwardAndCheckResults(1, {now}); + IdleEventNotifier::ActivityData data(now, now); + data.last_user_activity_time = now; + FastForwardAndCheckResults(1, data); +} + +TEST_F(IdleEventNotifierTest, UserActivityKey) { + base::Time now = task_runner_->Now(); + ui::KeyEvent key_event(ui::ET_KEY_PRESSED, ui::VKEY_A, ui::EF_NONE); + idle_event_notifier_->OnUserActivity(&key_event); + IdleEventNotifier::ActivityData data(now, now); + data.last_user_activity_time = now; + data.last_key_time = now; + FastForwardAndCheckResults(1, data); +} + +TEST_F(IdleEventNotifierTest, UserActivityMouse) { + base::Time now = task_runner_->Now(); + ui::MouseEvent mouse_event(ui::ET_MOUSE_EXITED, gfx::Point(0, 0), + gfx::Point(0, 0), base::TimeTicks(), 0, 0); + + idle_event_notifier_->OnUserActivity(&mouse_event); + IdleEventNotifier::ActivityData data(now, now); + data.last_user_activity_time = now; + data.last_mouse_time = now; + FastForwardAndCheckResults(1, data); +} + +TEST_F(IdleEventNotifierTest, UserActivityOther) { + base::Time now = task_runner_->Now(); + ui::GestureEvent gesture_event(0, 0, 0, base::TimeTicks(), + ui::GestureEventDetails(ui::ET_GESTURE_TAP)); + + idle_event_notifier_->OnUserActivity(&gesture_event); + IdleEventNotifier::ActivityData data(now, now); + data.last_user_activity_time = now; + FastForwardAndCheckResults(1, data); +} + +// Two consecutive activities separated by 2sec only. Only 1 idle event with +// different timestamps for the two activities. +TEST_F(IdleEventNotifierTest, TwoQuickUserActivities) { + base::Time now_1 = task_runner_->Now(); + ui::MouseEvent mouse_event(ui::ET_MOUSE_EXITED, gfx::Point(0, 0), + gfx::Point(0, 0), base::TimeTicks(), 0, 0); + idle_event_notifier_->OnUserActivity(&mouse_event); + + task_runner_->FastForwardBy(base::TimeDelta::FromSeconds(2)); + base::Time now_2 = task_runner_->Now(); + ui::KeyEvent key_event(ui::ET_KEY_PRESSED, ui::VKEY_A, ui::EF_NONE); + idle_event_notifier_->OnUserActivity(&key_event); + + IdleEventNotifier::ActivityData data(now_2, now_1); + data.last_user_activity_time = now_2; + data.last_mouse_time = now_1; + data.last_key_time = now_2; + FastForwardAndCheckResults(1, data); +} + +TEST_F(IdleEventNotifierTest, ActivityWhileVideoPlaying) { + ui::MouseEvent mouse_event(ui::ET_MOUSE_EXITED, gfx::Point(0, 0), + gfx::Point(0, 0), base::TimeTicks(), 0, 0); + idle_event_notifier_->OnVideoActivityStarted(); + idle_event_notifier_->OnUserActivity(&mouse_event); + FastForwardAndCheckResults(0, {}); +} + +// Activity is observed when video isn't playing, it will start idle timer. But +// before timer expires, video starts playing. So when timer expires, no idle +// event will be generated. +TEST_F(IdleEventNotifierTest, ActivityBeforeVideoStarts) { + ui::MouseEvent mouse_event(ui::ET_MOUSE_EXITED, gfx::Point(0, 0), + gfx::Point(0, 0), base::TimeTicks(), 0, 0); + idle_event_notifier_->OnUserActivity(&mouse_event); + task_runner_->FastForwardBy(base::TimeDelta::FromSeconds(2)); + idle_event_notifier_->OnVideoActivityStarted(); + FastForwardAndCheckResults(0, {}); +} + +// An activity is observed when video is playing. No idle timer will be +// triggered but last user activity time will be recorded. Video then stops +// playing that will trigger timer to start. +TEST_F(IdleEventNotifierTest, ActivityAfterVideoStarts) { + ui::MouseEvent mouse_event(ui::ET_MOUSE_EXITED, gfx::Point(0, 0), + gfx::Point(0, 0), base::TimeTicks(), 0, 0); + base::Time now_1 = task_runner_->Now(); + idle_event_notifier_->OnVideoActivityStarted(); + + task_runner_->FastForwardBy(base::TimeDelta::FromSeconds(1)); + base::Time now_2 = task_runner_->Now(); + idle_event_notifier_->OnUserActivity(&mouse_event); + + task_runner_->FastForwardBy(base::TimeDelta::FromSeconds(2)); + base::Time now_3 = task_runner_->Now(); + idle_event_notifier_->OnVideoActivityEnded(); + + IdleEventNotifier::ActivityData data(now_3, now_1); + data.last_user_activity_time = now_2; + data.last_mouse_time = now_2; + FastForwardAndCheckResults(1, data); } } // namespace ml
diff --git a/chrome/browser/chromeos/power/ml/user_activity_event.proto b/chrome/browser/chromeos/power/ml/user_activity_event.proto index 199e9401..495ab6706 100644 --- a/chrome/browser/chromeos/power/ml/user_activity_event.proto +++ b/chrome/browser/chromeos/power/ml/user_activity_event.proto
@@ -62,6 +62,7 @@ optional int32 last_activity_time_sec = 3; optional int32 last_user_activity_time_sec = 4; + // This must match the week range in base::Time::Exploded. enum DayOfWeek { SUN = 0; MON = 1;
diff --git a/chrome/browser/chromeos/power/ml/user_activity_logger.cc b/chrome/browser/chromeos/power/ml/user_activity_logger.cc index 6c1f39d..0a562a2 100644 --- a/chrome/browser/chromeos/power/ml/user_activity_logger.cc +++ b/chrome/browser/chromeos/power/ml/user_activity_logger.cc
@@ -5,16 +5,40 @@ #include "chrome/browser/chromeos/power/ml/user_activity_logger.h" #include "base/timer/timer.h" -#include "chrome/browser/chromeos/power/ml/user_activity_event.pb.h" -#include "ui/base/user_activity/user_activity_observer.h" +#include "chromeos/dbus/power_manager/power_supply_properties.pb.h" +#include "chromeos/system/devicetype.h" namespace chromeos { namespace power { namespace ml { UserActivityLogger::UserActivityLogger( - UserActivityLoggerDelegate* const delegate) - : logger_delegate_(delegate) {} + UserActivityLoggerDelegate* delegate, + IdleEventNotifier* idle_event_notifier, + ui::UserActivityDetector* detector, + chromeos::PowerManagerClient* power_manager_client) + : logger_delegate_(delegate), + idle_event_observer_(this), + user_activity_observer_(this), + power_manager_client_observer_(this) { + DCHECK(idle_event_notifier); + idle_event_observer_.Add(idle_event_notifier); + + DCHECK(detector); + user_activity_observer_.Add(detector); + + DCHECK(power_manager_client); + power_manager_client_observer_.Add(power_manager_client); + power_manager_client->RequestStatusUpdate(); + power_manager_client->GetSwitchStates(base::BindOnce( + &UserActivityLogger::OnReceiveSwitchStates, base::Unretained(this))); + + if (chromeos::GetDeviceType() == chromeos::DeviceType::kChromebook) { + device_type_ = UserActivityEvent::Features::CHROMEBOOK; + } else { + device_type_ = UserActivityEvent::Features::UNKNOWN_DEVICE; + } +} UserActivityLogger::~UserActivityLogger() = default; @@ -28,21 +52,105 @@ event->set_type(UserActivityEvent::Event::REACTIVATE); event->set_reason(UserActivityEvent::Event::USER_ACTIVITY); - UserActivityEvent::Features* features = activity_event.mutable_features(); - features->set_last_activity_time_sec( - (activity_data_.last_activity_time - - activity_data_.last_activity_time.LocalMidnight()) - .InSeconds()); + *activity_event.mutable_features() = features_; // Log to metrics. logger_delegate_->LogActivity(activity_event); idle_event_observed_ = false; } +void UserActivityLogger::LidEventReceived( + chromeos::PowerManagerClient::LidState state, + const base::TimeTicks& /* timestamp */) { + lid_state_ = state; +} + +// TODO(renjieliu): Log power changes activity here by checking whether the +// battery status has changed. +void UserActivityLogger::PowerChanged( + const power_manager::PowerSupplyProperties& proto) { + on_battery_ = (proto.external_power() == + power_manager::PowerSupplyProperties::DISCONNECTED); + + if (proto.has_battery_percent()) { + battery_percent_ = proto.battery_percent(); + } +} + +void UserActivityLogger::TabletModeEventReceived( + chromeos::PowerManagerClient::TabletMode mode, + const base::TimeTicks& /* timestamp */) { + tablet_mode_ = mode; +} + void UserActivityLogger::OnIdleEventObserved( const IdleEventNotifier::ActivityData& activity_data) { idle_event_observed_ = true; - activity_data_ = activity_data; + ExtractFeatures(activity_data); +} + +void UserActivityLogger::OnReceiveSwitchStates( + base::Optional<chromeos::PowerManagerClient::SwitchStates> switch_states) { + if (switch_states.has_value()) { + lid_state_ = switch_states->lid_state; + tablet_mode_ = switch_states->tablet_mode; + } +} + +void UserActivityLogger::ExtractFeatures( + const IdleEventNotifier::ActivityData& activity_data) { + features_.Clear(); + + // Set time related features. + features_.set_last_activity_time_sec( + (activity_data.last_activity_time - + activity_data.last_activity_time.LocalMidnight()) + .InSeconds()); + if (activity_data.last_user_activity_time != base::Time()) { + features_.set_last_user_activity_time_sec( + (activity_data.last_user_activity_time - + activity_data.last_user_activity_time.LocalMidnight()) + .InSeconds()); + } + + base::Time::Exploded exploded; + activity_data.last_activity_time.LocalExplode(&exploded); + features_.set_last_activity_day( + static_cast<chromeos::power::ml::UserActivityEvent_Features_DayOfWeek>( + exploded.day_of_week)); + + if (activity_data.last_mouse_time != base::Time()) { + features_.set_time_since_last_mouse_sec( + (base::Time::Now() - activity_data.last_mouse_time).InSeconds()); + } + if (activity_data.last_key_time != base::Time()) { + features_.set_time_since_last_key_sec( + (base::Time::Now() - activity_data.last_key_time).InSeconds()); + } + + features_.set_recent_time_active_sec( + (activity_data.last_activity_time - activity_data.earliest_activity_time) + .InSeconds()); + + // Set device mode. + if (lid_state_ == chromeos::PowerManagerClient::LidState::CLOSED) { + features_.set_device_mode(UserActivityEvent::Features::CLOSED_LID); + } else if (lid_state_ == chromeos::PowerManagerClient::LidState::OPEN) { + if (tablet_mode_ == chromeos::PowerManagerClient::TabletMode::ON) { + features_.set_device_mode(UserActivityEvent::Features::TABLET); + } else { + features_.set_device_mode(UserActivityEvent::Features::CLAMSHELL); + } + } else { + features_.set_device_mode(UserActivityEvent::Features::UNKNOWN_MODE); + } + + features_.set_device_type(device_type_); + + if (battery_percent_.has_value()) { + features_.set_battery_percent(*battery_percent_); + } + features_.set_on_battery(on_battery_); } } // namespace ml
diff --git a/chrome/browser/chromeos/power/ml/user_activity_logger.h b/chrome/browser/chromeos/power/ml/user_activity_logger.h index 60d756ae..30a74b4 100644 --- a/chrome/browser/chromeos/power/ml/user_activity_logger.h +++ b/chrome/browser/chromeos/power/ml/user_activity_logger.h
@@ -6,8 +6,14 @@ #define CHROME_BROWSER_CHROMEOS_POWER_ML_USER_ACTIVITY_LOGGER_H_ #include "base/macros.h" +#include "base/optional.h" +#include "base/scoped_observer.h" +#include "base/time/time.h" #include "chrome/browser/chromeos/power/ml/idle_event_notifier.h" +#include "chrome/browser/chromeos/power/ml/user_activity_event.pb.h" #include "chrome/browser/chromeos/power/ml/user_activity_logger_delegate.h" +#include "chromeos/dbus/power_manager_client.h" +#include "ui/base/user_activity/user_activity_detector.h" #include "ui/base/user_activity/user_activity_observer.h" namespace chromeos { @@ -17,13 +23,21 @@ // Logs user activity after an idle event is observed. // TODO(renjieliu): Add power-related activity as well. class UserActivityLogger : public ui::UserActivityObserver, - public IdleEventNotifier::Observer { + public IdleEventNotifier::Observer, + public PowerManagerClient::Observer { public: - explicit UserActivityLogger(UserActivityLoggerDelegate* delegate); + UserActivityLogger(UserActivityLoggerDelegate* delegate, + IdleEventNotifier* idle_event_notifier, + ui::UserActivityDetector* detector, + chromeos::PowerManagerClient* power_manager_client); ~UserActivityLogger() override; - private: - friend class UserActivityLoggerTest; + // chromeos::PowerManagerClient::Observer overrides: + void LidEventReceived(chromeos::PowerManagerClient::LidState state, + const base::TimeTicks& timestamp) override; + void PowerChanged(const power_manager::PowerSupplyProperties& proto) override; + void TabletModeEventReceived(chromeos::PowerManagerClient::TabletMode mode, + const base::TimeTicks& timestamp) override; // ui::UserActivityObserver overrides. void OnUserActivity(const ui::Event* event) override; @@ -32,15 +46,49 @@ void OnIdleEventObserved( const IdleEventNotifier::ActivityData& data) override; + private: + friend class UserActivityLoggerTest; + + // Updates lid state and tablet mode from received switch states. + void OnReceiveSwitchStates( + base::Optional<chromeos::PowerManagerClient::SwitchStates> switch_states); + + // Extracts features from last known activity data and from device states. + void ExtractFeatures(const IdleEventNotifier::ActivityData& activity_data); + // Flag indicating whether an idle event has been observed. bool idle_event_observed_ = false; - // UserActivity data derived from idle event. - IdleEventNotifier::ActivityData activity_data_; + chromeos::PowerManagerClient::LidState lid_state_ = + chromeos::PowerManagerClient::LidState::NOT_PRESENT; - // Logger delegate. + chromeos::PowerManagerClient::TabletMode tablet_mode_ = + chromeos::PowerManagerClient::TabletMode::UNSUPPORTED; + + UserActivityEvent::Features::DeviceType device_type_ = + UserActivityEvent::Features::UNKNOWN_DEVICE; + + // Flag indicating whether the device is on battery. + bool on_battery_ = false; + + // Battery percent. This is in the range [0.0, 100.0]. + base::Optional<float> battery_percent_; + + // Features extracted when receives an idle event. + UserActivityEvent::Features features_; + UserActivityLoggerDelegate* const logger_delegate_; + ScopedObserver<IdleEventNotifier, IdleEventNotifier::Observer> + idle_event_observer_; + + ScopedObserver<ui::UserActivityDetector, ui::UserActivityObserver> + user_activity_observer_; + + ScopedObserver<chromeos::PowerManagerClient, + chromeos::PowerManagerClient::Observer> + power_manager_client_observer_; + DISALLOW_COPY_AND_ASSIGN(UserActivityLogger); };
diff --git a/chrome/browser/chromeos/power/ml/user_activity_logger_unittest.cc b/chrome/browser/chromeos/power/ml/user_activity_logger_unittest.cc index f731923..92c7e6d 100644 --- a/chrome/browser/chromeos/power/ml/user_activity_logger_unittest.cc +++ b/chrome/browser/chromeos/power/ml/user_activity_logger_unittest.cc
@@ -7,11 +7,17 @@ #include <memory> #include <vector> +#include "base/single_thread_task_runner.h" +#include "base/test/scoped_task_environment.h" #include "base/timer/timer.h" #include "chrome/browser/chromeos/power/ml/idle_event_notifier.h" #include "chrome/browser/chromeos/power/ml/user_activity_event.pb.h" #include "chrome/browser/chromeos/power/ml/user_activity_logger_delegate.h" +#include "chromeos/dbus/fake_power_manager_client.h" +#include "chromeos/dbus/power_manager/power_supply_properties.pb.h" +#include "chromeos/dbus/power_manager_client.h" #include "testing/gtest/include/gtest/gtest.h" +#include "ui/base/user_activity/user_activity_detector.h" namespace chromeos { namespace power { @@ -31,6 +37,7 @@ const std::vector<UserActivityEvent>& events() const { return events_; } + // UserActivityLoggerDelegate overrides: void LogActivity(const UserActivityEvent& event) override { events_.push_back(event); } @@ -43,17 +50,41 @@ class UserActivityLoggerTest : public testing::Test { public: - UserActivityLoggerTest() : activity_logger_(&delegate_) {} + UserActivityLoggerTest() : task_runner_(base::ThreadTaskRunnerHandle::Get()) { + viz::mojom::VideoDetectorObserverPtr observer; + idle_event_notifier_ = std::make_unique<IdleEventNotifier>( + &fake_power_manager_client_, mojo::MakeRequest(&observer)); + activity_logger_ = std::make_unique<UserActivityLogger>( + &delegate_, idle_event_notifier_.get(), &user_activity_detector_, + &fake_power_manager_client_); + } ~UserActivityLoggerTest() override = default; protected: void ReportUserActivity(const ui::Event* event) { - activity_logger_.OnUserActivity(event); + activity_logger_->OnUserActivity(event); } void ReportIdleEvent(const IdleEventNotifier::ActivityData& data) { - activity_logger_.OnIdleEventObserved(data); + activity_logger_->OnIdleEventObserved(data); + } + + void ReportLidEvent(chromeos::PowerManagerClient::LidState state) { + fake_power_manager_client_.SetLidState(state, base::TimeTicks::Now()); + } + + void ReportPowerChangeEvent( + power_manager::PowerSupplyProperties::ExternalPower power, + float battery_percent) { + power_manager::PowerSupplyProperties proto; + proto.set_external_power(power); + proto.set_battery_percent(battery_percent); + fake_power_manager_client_.UpdatePowerProperties(proto); + } + + void ReportTabletModeEvent(chromeos::PowerManagerClient::TabletMode mode) { + fake_power_manager_client_.SetTabletMode(mode, base::TimeTicks::Now()); } const std::vector<UserActivityEvent>& GetEvents() { @@ -61,18 +92,25 @@ } private: + base::test::ScopedTaskEnvironment scoped_task_environment_; + scoped_refptr<base::SingleThreadTaskRunner> task_runner_; + + ui::UserActivityDetector user_activity_detector_; TestingUserActivityLoggerDelegate delegate_; - UserActivityLogger activity_logger_; + std::unique_ptr<IdleEventNotifier> idle_event_notifier_; + chromeos::FakePowerManagerClient fake_power_manager_client_; + std::unique_ptr<UserActivityLogger> activity_logger_; }; // After an idle event, we have a ui::Event, we should expect one // UserActivityEvent. TEST_F(UserActivityLoggerTest, LogAfterIdleEvent) { // Trigger an idle event. - ReportIdleEvent({base::Time::Now()}); + base::Time now = base::Time::UnixEpoch(); + ReportIdleEvent({now, now}); ReportUserActivity(nullptr); - const auto& events = GetEvents(); + const std::vector<UserActivityEvent>& events = GetEvents(); ASSERT_EQ(1U, events.size()); UserActivityEvent::Event expected_event; @@ -85,7 +123,8 @@ TEST_F(UserActivityLoggerTest, LogBeforeIdleEvent) { ReportUserActivity(nullptr); // Trigger an idle event. - ReportIdleEvent({base::Time::Now()}); + base::Time now = base::Time::UnixEpoch(); + ReportIdleEvent({now, now}); EXPECT_EQ(0U, GetEvents().size()); } @@ -95,11 +134,12 @@ TEST_F(UserActivityLoggerTest, LogSecondEvent) { ReportUserActivity(nullptr); // Trigger an idle event. - ReportIdleEvent({base::Time::Now()}); + base::Time now = base::Time::UnixEpoch(); + ReportIdleEvent({now, now}); // Another user event. ReportUserActivity(nullptr); - const auto& events = GetEvents(); + const std::vector<UserActivityEvent>& events = GetEvents(); ASSERT_EQ(1U, events.size()); UserActivityEvent::Event expected_event; @@ -111,16 +151,18 @@ // Log multiple events. TEST_F(UserActivityLoggerTest, LogMultipleEvents) { // Trigger an idle event. - ReportIdleEvent({base::Time::Now()}); + base::Time now = base::Time::UnixEpoch(); + ReportIdleEvent({now, now}); // First user event. ReportUserActivity(nullptr); // Trigger an idle event. - ReportIdleEvent({base::Time::Now()}); + now = base::Time::UnixEpoch(); + ReportIdleEvent({now, now}); // Second user event. ReportUserActivity(nullptr); - const auto& events = GetEvents(); + const std::vector<UserActivityEvent>& events = GetEvents(); ASSERT_EQ(2U, events.size()); UserActivityEvent::Event expected_event; @@ -130,6 +172,24 @@ EqualEvent(expected_event, events[1].event()); } +// Test feature extraction. +TEST_F(UserActivityLoggerTest, FeatureExtraction) { + ReportLidEvent(chromeos::PowerManagerClient::LidState::OPEN); + ReportTabletModeEvent(chromeos::PowerManagerClient::TabletMode::UNSUPPORTED); + ReportPowerChangeEvent(power_manager::PowerSupplyProperties::AC, 23.0f); + + ReportIdleEvent({}); + ReportUserActivity(nullptr); + + const auto& events = GetEvents(); + ASSERT_EQ(1U, events.size()); + + const UserActivityEvent::Features& features = events[0].features(); + EXPECT_EQ(UserActivityEvent::Features::CLAMSHELL, features.device_mode()); + EXPECT_EQ(23.0f, features.battery_percent()); + EXPECT_DOUBLE_EQ(false, features.on_battery()); +} + } // namespace ml } // namespace power } // namespace chromeos
diff --git a/chrome/browser/chromeos/preferences.cc b/chrome/browser/chromeos/preferences.cc index d21804a..972c808 100644 --- a/chrome/browser/chromeos/preferences.cc +++ b/chrome/browser/chromeos/preferences.cc
@@ -203,7 +203,7 @@ ash::kDefaultLargeCursorSize, PrefRegistry::PUBLIC); registry->RegisterBooleanPref(ash::prefs::kAccessibilitySpokenFeedbackEnabled, - false); + false, PrefRegistry::PUBLIC); registry->RegisterBooleanPref( ash::prefs::kAccessibilityHighContrastEnabled, false, user_prefs::PrefRegistrySyncable::SYNCABLE_PREF | PrefRegistry::PUBLIC);
diff --git a/chrome/browser/chromeos/settings/install_attributes.cc b/chrome/browser/chromeos/settings/install_attributes.cc index fdd5a2d..faa0011 100644 --- a/chrome/browser/chromeos/settings/install_attributes.cc +++ b/chrome/browser/chromeos/settings/install_attributes.cc
@@ -73,28 +73,6 @@ return install_attrs_proto.SerializeAsString(); } -// static -std::string InstallAttributes:: - GetActiveDirectoryEnterpriseOwnedInstallAttributesBlobForTesting( - const std::string& realm) { - cryptohome::SerializedInstallAttributes install_attrs_proto; - cryptohome::SerializedInstallAttributes::Attribute* attribute = nullptr; - - attribute = install_attrs_proto.add_attributes(); - attribute->set_name(InstallAttributes::kAttrEnterpriseOwned); - attribute->set_value("true"); - - attribute = install_attrs_proto.add_attributes(); - attribute->set_name(InstallAttributes::kAttrEnterpriseMode); - attribute->set_value(InstallAttributes::kEnterpriseADDeviceMode); - - attribute = install_attrs_proto.add_attributes(); - attribute->set_name(InstallAttributes::kAttrEnterpriseRealm); - attribute->set_value(realm); - - return install_attrs_proto.SerializeAsString(); -} - InstallAttributes::InstallAttributes(CryptohomeClient* cryptohome_client) : cryptohome_client_(cryptohome_client), weak_ptr_factory_(this) {
diff --git a/chrome/browser/chromeos/settings/install_attributes.h b/chrome/browser/chromeos/settings/install_attributes.h index 6fd0311..1986396 100644 --- a/chrome/browser/chromeos/settings/install_attributes.h +++ b/chrome/browser/chromeos/settings/install_attributes.h
@@ -49,11 +49,6 @@ static std::string GetEnterpriseOwnedInstallAttributesBlobForTesting( const std::string& user_name); - // Return serialized InstallAttributes of an enterprise-owned configuration. - static std::string - GetActiveDirectoryEnterpriseOwnedInstallAttributesBlobForTesting( - const std::string& realm); - explicit InstallAttributes(CryptohomeClient* cryptohome_client); ~InstallAttributes();
diff --git a/chrome/browser/chromeos/system/tray_accessibility_browsertest.cc b/chrome/browser/chromeos/system/tray_accessibility_browsertest.cc index 03d4fc2c..d0983dd 100644 --- a/chrome/browser/chromeos/system/tray_accessibility_browsertest.cc +++ b/chrome/browser/chromeos/system/tray_accessibility_browsertest.cc
@@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "ash/accessibility/accessibility_controller.h" #include "ash/login_status.h" #include "ash/public/cpp/accessibility_types.h" #include "ash/public/cpp/ash_pref_names.h" @@ -970,8 +971,6 @@ IN_PROC_BROWSER_TEST_P(TrayAccessibilityTest, ShowNotification) { const base::string16 BRAILLE_CONNECTED = base::ASCIIToUTF16("Braille display connected."); - const base::string16 CHROMEVOX_ENABLED_TITLE = - base::ASCIIToUTF16("ChromeVox enabled"); const base::string16 CHROMEVOX_ENABLED = base::ASCIIToUTF16("Press Ctrl + Alt + Z to disable spoken feedback."); const base::string16 BRAILLE_CONNECTED_AND_CHROMEVOX_ENABLED_TITLE = @@ -979,18 +978,17 @@ EXPECT_FALSE(AccessibilityManager::Get()->IsSpokenFeedbackEnabled()); - // Enabling spoken feedback should show the notification. - EnableSpokenFeedback(true, ash::A11Y_NOTIFICATION_SHOW); - message_center::NotificationList::Notifications notifications = - MessageCenter::Get()->GetVisibleNotifications(); - EXPECT_EQ(1u, notifications.size()); - EXPECT_EQ(CHROMEVOX_ENABLED_TITLE, (*notifications.begin())->title()); - EXPECT_EQ(CHROMEVOX_ENABLED, (*notifications.begin())->message()); + ash::Shell::Get()->accessibility_controller()->SetSpokenFeedbackEnabled( + true, ash::A11Y_NOTIFICATION_SHOW); + // Spin the run loop to make sure ash see the change. + base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(AccessibilityManager::Get()->IsSpokenFeedbackEnabled()); // Connecting a braille display when spoken feedback is already enabled // should only show the message about the braille display. SetBrailleConnected(true); - notifications = MessageCenter::Get()->GetVisibleNotifications(); + message_center::NotificationList::Notifications notifications = + MessageCenter::Get()->GetVisibleNotifications(); EXPECT_EQ(1u, notifications.size()); EXPECT_EQ(base::string16(), (*notifications.begin())->title()); EXPECT_EQ(BRAILLE_CONNECTED, (*notifications.begin())->message()); @@ -1001,7 +999,10 @@ EXPECT_TRUE(AccessibilityManager::Get()->IsSpokenFeedbackEnabled()); notifications = MessageCenter::Get()->GetVisibleNotifications(); EXPECT_EQ(0u, notifications.size()); - EnableSpokenFeedback(false, ash::A11Y_NOTIFICATION_SHOW); + ash::Shell::Get()->accessibility_controller()->SetSpokenFeedbackEnabled( + false, ash::A11Y_NOTIFICATION_SHOW); + // Spin the run loop to make sure ash see the change. + base::RunLoop().RunUntilIdle(); notifications = MessageCenter::Get()->GetVisibleNotifications(); EXPECT_EQ(0u, notifications.size()); EXPECT_FALSE(AccessibilityManager::Get()->IsSpokenFeedbackEnabled()); @@ -1009,6 +1010,8 @@ // Connecting a braille display should enable spoken feedback and show // both messages. SetBrailleConnected(true); + // Spin the run loop to make sure ash see the change. + base::RunLoop().RunUntilIdle(); EXPECT_TRUE(AccessibilityManager::Get()->IsSpokenFeedbackEnabled()); notifications = MessageCenter::Get()->GetVisibleNotifications(); EXPECT_EQ(BRAILLE_CONNECTED_AND_CHROMEVOX_ENABLED_TITLE,
diff --git a/chrome/browser/chromeos/system_logs/command_line_log_source.cc b/chrome/browser/chromeos/system_logs/command_line_log_source.cc index 2903bbca..1a928f8 100644 --- a/chrome/browser/chromeos/system_logs/command_line_log_source.cc +++ b/chrome/browser/chromeos/system_logs/command_line_log_source.cc
@@ -6,6 +6,7 @@ #include <stddef.h> +#include <memory> #include <string> #include <vector> @@ -101,11 +102,12 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(!callback.is_null()); - SystemLogsResponse* response = new SystemLogsResponse; + auto response = std::make_unique<SystemLogsResponse>(); + SystemLogsResponse* response_ptr = response.get(); base::PostTaskWithTraitsAndReply( FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND}, - base::Bind(&ExecuteCommandLines, response), - base::Bind(callback, base::Owned(response))); + base::BindOnce(&ExecuteCommandLines, response_ptr), + base::BindOnce(callback, std::move(response))); } } // namespace system_logs
diff --git a/chrome/browser/chromeos/system_logs/dbus_log_source.cc b/chrome/browser/chromeos/system_logs/dbus_log_source.cc index 7f3b4fc..11a342fe 100644 --- a/chrome/browser/chromeos/system_logs/dbus_log_source.cc +++ b/chrome/browser/chromeos/system_logs/dbus_log_source.cc
@@ -4,6 +4,8 @@ #include "chrome/browser/chromeos/system_logs/dbus_log_source.h" +#include <memory> + #include "content/public/browser/browser_thread.h" #include "dbus/dbus_statistics.h" @@ -22,14 +24,14 @@ DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(!callback.is_null()); - SystemLogsResponse response; - response[kDBusLogEntryShort] = dbus::statistics::GetAsString( - dbus::statistics::SHOW_INTERFACE, - dbus::statistics::FORMAT_ALL); - response[kDBusLogEntryLong] = dbus::statistics::GetAsString( - dbus::statistics::SHOW_METHOD, - dbus::statistics::FORMAT_TOTALS); - callback.Run(&response); + auto response = std::make_unique<SystemLogsResponse>(); + response->emplace(kDBusLogEntryShort, dbus::statistics::GetAsString( + dbus::statistics::SHOW_INTERFACE, + dbus::statistics::FORMAT_ALL)); + response->emplace(kDBusLogEntryLong, dbus::statistics::GetAsString( + dbus::statistics::SHOW_METHOD, + dbus::statistics::FORMAT_TOTALS)); + callback.Run(std::move(response)); } } // namespace system_logs
diff --git a/chrome/browser/chromeos/system_logs/debug_daemon_log_source.cc b/chrome/browser/chromeos/system_logs/debug_daemon_log_source.cc index 6d706f2..f5205373d 100644 --- a/chrome/browser/chromeos/system_logs/debug_daemon_log_source.cc +++ b/chrome/browser/chromeos/system_logs/debug_daemon_log_source.cc
@@ -127,7 +127,8 @@ const KeyValueMap& user_log_files) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (succeeded) { - SystemLogsResponse* response = new SystemLogsResponse; + auto response = std::make_unique<SystemLogsResponse>(); + SystemLogsResponse* response_ptr = response.get(); const user_manager::UserList& users = user_manager::UserManager::Get()->GetLoggedInUsers(); @@ -144,13 +145,15 @@ base::PostTaskWithTraitsAndReply( FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND}, - base::Bind(&DebugDaemonLogSource::ReadUserLogFiles, user_log_files, - profile_dirs, response), - base::Bind(&DebugDaemonLogSource::MergeUserLogFilesResponse, - weak_ptr_factory_.GetWeakPtr(), base::Owned(response))); + base::BindOnce(&DebugDaemonLogSource::ReadUserLogFiles, user_log_files, + profile_dirs, response_ptr), + base::BindOnce(&DebugDaemonLogSource::MergeUserLogFilesResponse, + weak_ptr_factory_.GetWeakPtr(), std::move(response))); } else { (*response_)[kUserLogFileKeyName] = kNotAvailable; - callback_.Run(response_.get()); + auto response = std::make_unique<SystemLogsResponse>(); + std::swap(response, response_); + callback_.Run(std::move(response)); } } @@ -179,11 +182,11 @@ } void DebugDaemonLogSource::MergeUserLogFilesResponse( - SystemLogsResponse* response) { - for (SystemLogsResponse::const_iterator it = response->begin(); - it != response->end(); ++it) - response_->insert(*it); - callback_.Run(response_.get()); + std::unique_ptr<SystemLogsResponse> response) { + response_->insert(response->begin(), response->end()); + auto response_to_return = std::make_unique<SystemLogsResponse>(); + std::swap(response_to_return, response_); + callback_.Run(std::move(response_to_return)); } void DebugDaemonLogSource::RequestCompleted() {
diff --git a/chrome/browser/chromeos/system_logs/debug_daemon_log_source.h b/chrome/browser/chromeos/system_logs/debug_daemon_log_source.h index afda56e..fd9b2cd 100644 --- a/chrome/browser/chromeos/system_logs/debug_daemon_log_source.h +++ b/chrome/browser/chromeos/system_logs/debug_daemon_log_source.h
@@ -53,7 +53,7 @@ // Merge the responses from ReadUserLogFiles into the main response dict and // invoke the callback_.Run method with the assumption that all other logs // have already been collected. - void MergeUserLogFilesResponse(SystemLogsResponse* response); + void MergeUserLogFilesResponse(std::unique_ptr<SystemLogsResponse> response); // When all the requests are completed, send one last request to collect the // user logs and complete the collection by invoking the callback's Run
diff --git a/chrome/browser/chromeos/system_logs/device_event_log_source.cc b/chrome/browser/chromeos/system_logs/device_event_log_source.cc index 501bc33..d361000 100644 --- a/chrome/browser/chromeos/system_logs/device_event_log_source.cc +++ b/chrome/browser/chromeos/system_logs/device_event_log_source.cc
@@ -23,7 +23,7 @@ DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(!callback.is_null()); - std::unique_ptr<SystemLogsResponse> response(new SystemLogsResponse); + auto response = std::make_unique<SystemLogsResponse>(); const int kMaxDeviceEventsForAboutSystem = 400; (*response)[kNetworkEventLogEntry] = device_event_log::GetAsString( device_event_log::OLDEST_FIRST, "time,file,level", "network", @@ -31,7 +31,7 @@ (*response)[kDeviceEventLogEntry] = device_event_log::GetAsString( device_event_log::OLDEST_FIRST, "time,file,type,level", "non-network", device_event_log::LOG_LEVEL_DEBUG, kMaxDeviceEventsForAboutSystem); - callback.Run(response.get()); + callback.Run(std::move(response)); } } // namespace system_logs
diff --git a/chrome/browser/chromeos/system_logs/lsb_release_log_source.cc b/chrome/browser/chromeos/system_logs/lsb_release_log_source.cc index 5dfb1fe..d1103ab 100644 --- a/chrome/browser/chromeos/system_logs/lsb_release_log_source.cc +++ b/chrome/browser/chromeos/system_logs/lsb_release_log_source.cc
@@ -18,14 +18,14 @@ void LsbReleaseLogSource::Fetch(const SysLogsSourceCallback& callback) { DCHECK(!callback.is_null()); - std::unique_ptr<SystemLogsResponse> response(new SystemLogsResponse); + auto response = std::make_unique<SystemLogsResponse>(); const base::SysInfo::LsbReleaseMap& lsb_map = base::SysInfo::GetLsbReleaseMap(); for (base::SysInfo::LsbReleaseMap::const_iterator iter = lsb_map.begin(); iter != lsb_map.end(); ++iter) { (*response)[iter->first] = iter->second; } - callback.Run(response.get()); + callback.Run(std::move(response)); } } // namespace system_logs
diff --git a/chrome/browser/chromeos/system_logs/single_debug_daemon_log_source.cc b/chrome/browser/chromeos/system_logs/single_debug_daemon_log_source.cc index d938e97..445beb9 100644 --- a/chrome/browser/chromeos/system_logs/single_debug_daemon_log_source.cc +++ b/chrome/browser/chromeos/system_logs/single_debug_daemon_log_source.cc
@@ -4,6 +4,8 @@ #include "chrome/browser/chromeos/system_logs/single_debug_daemon_log_source.h" +#include <memory> + #include "base/bind.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/debug_daemon_client.h" @@ -61,13 +63,14 @@ base::Optional<std::string> result) const { // |result| and |response| are the same type, but |result| is passed in from // DebugDaemonClient, which does not use the SystemLogsResponse alias. - SystemLogsResponse response; + auto response = std::make_unique<SystemLogsResponse>(); // Return an empty result if the call to GetLog() failed. - if (result.has_value()) - response.emplace(log_name, - feedback::AnonymizerTool().Anonymize(result.value())); + if (result.has_value()) { + response->emplace(log_name, + feedback::AnonymizerTool().Anonymize(result.value())); + } - callback.Run(&response); + callback.Run(std::move(response)); } } // namespace system_logs
diff --git a/chrome/browser/chromeos/system_logs/single_debug_daemon_log_source_unittest.cc b/chrome/browser/chromeos/system_logs/single_debug_daemon_log_source_unittest.cc index 4b7b4fb43..1f7bd8b 100644 --- a/chrome/browser/chromeos/system_logs/single_debug_daemon_log_source_unittest.cc +++ b/chrome/browser/chromeos/system_logs/single_debug_daemon_log_source_unittest.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/chromeos/system_logs/single_debug_daemon_log_source.h" +#include <memory> #include <string> #include "base/bind.h" @@ -54,7 +55,7 @@ void ClearResponse() { response_.clear(); } private: - void OnFetchComplete(SystemLogsResponse* response) { + void OnFetchComplete(std::unique_ptr<SystemLogsResponse> response) { ++num_callback_calls_; response_ = *response; }
diff --git a/chrome/browser/chromeos/system_logs/single_log_file_log_source.cc b/chrome/browser/chromeos/system_logs/single_log_file_log_source.cc index 7f06a174..d59944f 100644 --- a/chrome/browser/chromeos/system_logs/single_log_file_log_source.cc +++ b/chrome/browser/chromeos/system_logs/single_log_file_log_source.cc
@@ -102,10 +102,10 @@ base::PostTaskWithTraitsAndReply( FROM_HERE, base::TaskTraits(base::MayBlock(), base::TaskPriority::BACKGROUND), - base::Bind(&SingleLogFileLogSource::ReadFile, - weak_ptr_factory_.GetWeakPtr(), - kMaxNumAllowedLogRotationsDuringFileRead, response_ptr), - base::Bind(callback, base::Owned(response.release()))); + base::BindOnce(&SingleLogFileLogSource::ReadFile, + weak_ptr_factory_.GetWeakPtr(), + kMaxNumAllowedLogRotationsDuringFileRead, response_ptr), + base::BindOnce(callback, std::move(response))); } base::FilePath SingleLogFileLogSource::GetLogFilePath() const {
diff --git a/chrome/browser/chromeos/system_logs/single_log_file_log_source_unittest.cc b/chrome/browser/chromeos/system_logs/single_log_file_log_source_unittest.cc index 14ceb0b..f6d42c1a 100644 --- a/chrome/browser/chromeos/system_logs/single_log_file_log_source_unittest.cc +++ b/chrome/browser/chromeos/system_logs/single_log_file_log_source_unittest.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/chromeos/system_logs/single_log_file_log_source.h" +#include <memory> #include <string> #include "base/bind.h" @@ -98,7 +99,7 @@ // Callback for fetching logs from |source_|. Overwrites the previous stored // value of |latest_response_|. - void OnFileRead(SystemLogsResponse* response) { + void OnFileRead(std::unique_ptr<SystemLogsResponse> response) { ++num_callback_calls_; if (response->empty()) return;
diff --git a/chrome/browser/chromeos/system_logs/touch_log_source_ozone.cc b/chrome/browser/chromeos/system_logs/touch_log_source_ozone.cc index 5767837..722ea5f 100644 --- a/chrome/browser/chromeos/system_logs/touch_log_source_ozone.cc +++ b/chrome/browser/chromeos/system_logs/touch_log_source_ozone.cc
@@ -140,15 +140,11 @@ const std::vector<base::FilePath>& log_paths) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - // We cannot eliminate these temporaries and inline these closures because the - // compiler may call release() before get(). - const base::Closure pack_closure = - base::Bind(&PackEventLog, base::Unretained(response.get()), log_paths); - const base::Closure callback_closure = - base::Bind(callback, base::Owned(response.release())); + system_logs::SystemLogsResponse* response_ptr = response.get(); base::PostTaskWithTraitsAndReply( FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND}, - pack_closure, callback_closure); + base::BindOnce(&PackEventLog, response_ptr, log_paths), + base::BindOnce(callback, std::move(response))); } // Callback for handing the outcome of GetTouchDeviceStatus(). @@ -168,7 +164,7 @@ g_browser_process->platform_part()->GetInputDeviceControllerClient(); input_device_controller_client->GetTouchEventLog( kBaseLogPath, - base::BindOnce(&OnEventLogCollected, base::Passed(&response), callback)); + base::BindOnce(&OnEventLogCollected, std::move(response), callback)); } // Collect touch HUD debug logs. This needs to be done on the UI thread. @@ -192,15 +188,14 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(!callback.is_null()); - std::unique_ptr<SystemLogsResponse> response = - base::MakeUnique<SystemLogsResponse>(); + auto response = std::make_unique<SystemLogsResponse>(); CollectTouchHudDebugLog(response.get()); // Collect touch device status logs. ui::InputDeviceControllerClient* input_device_controller_client = g_browser_process->platform_part()->GetInputDeviceControllerClient(); input_device_controller_client->GetTouchDeviceStatus( - base::BindOnce(&OnStatusLogCollected, base::Passed(&response), callback)); + base::BindOnce(&OnStatusLogCollected, std::move(response), callback)); } } // namespace system_logs
diff --git a/chrome/browser/devtools/device/android_device_info_query.cc b/chrome/browser/devtools/device/android_device_info_query.cc index e16000b..8dbbb4d 100644 --- a/chrome/browser/devtools/device/android_device_info_query.cc +++ b/chrome/browser/devtools/device/android_device_info_query.cc
@@ -74,11 +74,6 @@ kChromeDefaultName }, { - "com.chrome.work", - kChromeDefaultSocket, - "Work Chrome" - }, - { "org.chromium.android_webview.shell", "webview_devtools_remote", "WebView Test Shell"
diff --git a/chrome/browser/download/download_browsertest.cc b/chrome/browser/download/download_browsertest.cc index 386127e..aad00e1 100644 --- a/chrome/browser/download/download_browsertest.cc +++ b/chrome/browser/download/download_browsertest.cc
@@ -357,7 +357,8 @@ explicit HistoryObserver(Profile* profile) : profile_(profile), waiting_(false), - seen_stored_(false) { + seen_stored_(false), + minimum_received_bytes_(kNoMinimumReceivedBytes) { DownloadCoreServiceFactory::GetForBrowserContext(profile_) ->GetDownloadHistory() ->AddObserver(this); @@ -370,6 +371,10 @@ service->GetDownloadHistory()->RemoveObserver(this); } + void set_minimum_received_bytes(int64_t minimum_received_bytes) { + minimum_received_bytes_ = minimum_received_bytes; + } + void SetFilterCallback(const FilterCallback& callback) { callback_ = callback; } @@ -379,6 +384,11 @@ if (!callback_.is_null() && (!callback_.Run(info))) return; + if (minimum_received_bytes_ != kNoMinimumReceivedBytes && + info.received_bytes < minimum_received_bytes_) { + return; + } + seen_stored_ = true; if (waiting_) base::RunLoop::QuitCurrentWhenIdleDeprecated(); @@ -399,9 +409,11 @@ } private: + static const int64_t kNoMinimumReceivedBytes = -1; Profile* profile_; bool waiting_; bool seen_stored_; + int64_t minimum_received_bytes_; FilterCallback callback_; DISALLOW_COPY_AND_ASSIGN(HistoryObserver); @@ -1841,13 +1853,7 @@ return std::move(response); } -#if defined(OS_WIN) -// https://crbug.com/788160 -#define MAYBE_DownloadHistoryCheck DISABLED_DownloadHistoryCheck -#else -#define MAYBE_DownloadHistoryCheck DownloadHistoryCheck -#endif -IN_PROC_BROWSER_TEST_F(DownloadTest, MAYBE_DownloadHistoryCheck) { +IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadHistoryCheck) { // Rediret to the actual download URL. embedded_test_server()->RegisterRequestHandler( base::Bind(&ServerRedirectRequestHandler)); @@ -1882,6 +1888,8 @@ base::Time start(base::Time::Now()); HistoryObserver observer(browser()->profile()); observer.SetFilterCallback(base::Bind(&HasDataAndName)); + observer.set_minimum_received_bytes( + content::SlowDownloadHttpResponse::kFirstDownloadSize); ui_test_utils::NavigateToURL(browser(), redirect_url); observer.WaitForStored();
diff --git a/chrome/browser/engagement/site_engagement_helper.cc b/chrome/browser/engagement/site_engagement_helper.cc index d69a079b..e294869 100644 --- a/chrome/browser/engagement/site_engagement_helper.cc +++ b/chrome/browser/engagement/site_engagement_helper.cc
@@ -16,7 +16,7 @@ #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" -#include "content/public/common/associated_interface_provider.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" #include "url/gurl.h" #include "url/origin.h"
diff --git a/chrome/browser/engagement/site_engagement_service.cc b/chrome/browser/engagement/site_engagement_service.cc index fd99bba2..ef0c8096 100644 --- a/chrome/browser/engagement/site_engagement_service.cc +++ b/chrome/browser/engagement/site_engagement_service.cc
@@ -34,7 +34,7 @@ #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" -#include "content/public/common/associated_interface_provider.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" #include "url/gurl.h" #if defined(OS_ANDROID)
diff --git a/chrome/browser/experiments/memory_ablation_experiment.cc b/chrome/browser/experiments/memory_ablation_experiment.cc index 7eaf2b4..ef98d0ba 100644 --- a/chrome/browser/experiments/memory_ablation_experiment.cc +++ b/chrome/browser/experiments/memory_ablation_experiment.cc
@@ -91,6 +91,7 @@ for (; offset < max_offset; offset += page_size) { memory[offset] = static_cast<uint8_t>(offset); } + // Make sure compiler doesn't optimize away the writes. base::debug::Alias(memory_.get()); if (offset < memory_size_) { ScheduleTouchMemory(offset);
diff --git a/chrome/browser/extensions/BUILD.gn b/chrome/browser/extensions/BUILD.gn index 66b71f7..51854588 100644 --- a/chrome/browser/extensions/BUILD.gn +++ b/chrome/browser/extensions/BUILD.gn
@@ -201,8 +201,6 @@ "api/gcm/gcm_api.h", "api/history/history_api.cc", "api/history/history_api.h", - "api/hotword_private/hotword_private_api.cc", - "api/hotword_private/hotword_private_api.h", "api/i18n/i18n_api.cc", "api/i18n/i18n_api.h", "api/identity/extension_token_key.cc", @@ -940,6 +938,8 @@ "api/input_ime/input_ime_api_chromeos.h", "api/input_ime/input_ime_event_router_base.cc", "api/input_ime/input_ime_event_router_base.h", + "api/media_perception_private/media_perception_api_delegate_chromeos.cc", + "api/media_perception_private/media_perception_api_delegate_chromeos.h", "api/messaging/native_message_host_chromeos.cc", "api/networking_cast_private/chrome_networking_cast_private_delegate.cc", "api/networking_cast_private/chrome_networking_cast_private_delegate.h", @@ -1116,10 +1116,6 @@ ] } - if (enable_hotwording) { - defines += [ "ENABLE_HOTWORDING" ] - } - if (enable_service_discovery) { sources += [ "api/mdns/mdns_api.cc",
diff --git a/chrome/browser/extensions/api/autofill_private/autofill_private_api.cc b/chrome/browser/extensions/api/autofill_private/autofill_private_api.cc index 77c77df1..c3fbbfe0 100644 --- a/chrome/browser/extensions/api/autofill_private/autofill_private_api.cc +++ b/chrome/browser/extensions/api/autofill_private/autofill_private_api.cc
@@ -399,7 +399,7 @@ base::UTF8ToUTF16(*card->expiration_year)); } - if (!card->billing_address_id->empty()) { + if (card->billing_address_id) { credit_card.set_billing_address_id(*card->billing_address_id); }
diff --git a/chrome/browser/extensions/api/cast_streaming/performance_test.cc b/chrome/browser/extensions/api/cast_streaming/performance_test.cc index 12a6718..d505f8b 100644 --- a/chrome/browser/extensions/api/cast_streaming/performance_test.cc +++ b/chrome/browser/extensions/api/cast_streaming/performance_test.cc
@@ -18,6 +18,7 @@ #include "base/strings/stringprintf.h" #include "base/test/trace_event_analyzer.h" #include "base/time/default_tick_clock.h" +#include "build/build_config.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/tab_helper.h" @@ -703,7 +704,13 @@ } // namespace -IN_PROC_BROWSER_TEST_P(CastV2PerformanceTest, Performance) { +#if defined(OS_WIN) +#define MAYBE_Performance DISABLED_Performance +#else +#define MAYBE_Performance Performance +#endif + +IN_PROC_BROWSER_TEST_P(CastV2PerformanceTest, MAYBE_Performance) { RunTest("CastV2Performance"); }
diff --git a/chrome/browser/extensions/api/chrome_extensions_api_client.cc b/chrome/browser/extensions/api/chrome_extensions_api_client.cc index 7354bf8..3948216 100644 --- a/chrome/browser/extensions/api/chrome_extensions_api_client.cc +++ b/chrome/browser/extensions/api/chrome_extensions_api_client.cc
@@ -46,6 +46,7 @@ #if defined(OS_CHROMEOS) #include "chrome/browser/extensions/api/file_handlers/non_native_file_system_delegate_chromeos.h" +#include "chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.h" #include "chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.h" #include "chrome/browser/extensions/clipboard_extension_helper_chromeos.h" #endif @@ -212,6 +213,15 @@ } #if defined(OS_CHROMEOS) +MediaPerceptionAPIDelegate* +ChromeExtensionsAPIClient::GetMediaPerceptionAPIDelegate() { + if (!media_perception_api_delegate_) { + media_perception_api_delegate_ = + std::make_unique<MediaPerceptionAPIDelegateChromeOS>(); + } + return media_perception_api_delegate_.get(); +} + NonNativeFileSystemDelegate* ChromeExtensionsAPIClient::GetNonNativeFileSystemDelegate() { if (!non_native_file_system_delegate_) {
diff --git a/chrome/browser/extensions/api/chrome_extensions_api_client.h b/chrome/browser/extensions/api/chrome_extensions_api_client.h index 7c5e18d..bf32204 100644 --- a/chrome/browser/extensions/api/chrome_extensions_api_client.h +++ b/chrome/browser/extensions/api/chrome_extensions_api_client.h
@@ -62,6 +62,7 @@ FeedbackPrivateDelegate* GetFeedbackPrivateDelegate() override; #if defined(OS_CHROMEOS) + MediaPerceptionAPIDelegate* GetMediaPerceptionAPIDelegate() override; NonNativeFileSystemDelegate* GetNonNativeFileSystemDelegate() override; void SaveImageDataToClipboard( @@ -81,6 +82,7 @@ std::unique_ptr<FeedbackPrivateDelegate> feedback_private_delegate_; #if defined(OS_CHROMEOS) + std::unique_ptr<MediaPerceptionAPIDelegate> media_perception_api_delegate_; std::unique_ptr<NonNativeFileSystemDelegate> non_native_file_system_delegate_; std::unique_ptr<ClipboardExtensionHelper> clipboard_extension_helper_; #endif
diff --git a/chrome/browser/extensions/api/hotword_private/OWNERS b/chrome/browser/extensions/api/hotword_private/OWNERS deleted file mode 100644 index 2ae98b3a..0000000 --- a/chrome/browser/extensions/api/hotword_private/OWNERS +++ /dev/null
@@ -1,2 +0,0 @@ -kcarattini@chromium.org -mgiuca@chromium.org
diff --git a/chrome/browser/extensions/api/hotword_private/hotword_private_api.cc b/chrome/browser/extensions/api/hotword_private/hotword_private_api.cc deleted file mode 100644 index 6976c1b..0000000 --- a/chrome/browser/extensions/api/hotword_private/hotword_private_api.cc +++ /dev/null
@@ -1,540 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/extensions/api/hotword_private/hotword_private_api.h" - -#include <memory> -#include <string> -#include <utility> - -#include "base/lazy_instance.h" -#include "base/memory/ptr_util.h" -#include "base/strings/utf_string_conversions.h" -#include "build/build_config.h" -#include "chrome/browser/browser_process.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/search/hotword_audio_history_handler.h" -#include "chrome/browser/search/hotword_client.h" -#include "chrome/browser/search/hotword_service.h" -#include "chrome/browser/search/hotword_service_factory.h" -#include "chrome/browser/ui/app_list/app_list_service.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/common/pref_names.h" -#include "chrome/grit/chromium_strings.h" -#include "chrome/grit/generated_resources.h" -#include "components/prefs/pref_service.h" -#include "content/public/browser/speech_recognition_session_preamble.h" -#include "extensions/browser/event_router.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/base/webui/web_ui_util.h" - -#if defined(OS_CHROMEOS) -#include "ui/chromeos/devicetype_utils.h" -#endif - -namespace extensions { - -namespace hotword_private_constants { -const char kHotwordServiceUnavailable[] = "Hotword Service is unavailable."; -const char kHotwordEventServiceUnavailable[] = - "Hotword Private Event Service is unavailable."; -} // hotword_private_constants - -namespace OnEnabledChanged = - api::hotword_private::OnEnabledChanged; - -static base::LazyInstance< - BrowserContextKeyedAPIFactory<HotwordPrivateEventService>>::DestructorAtExit - g_hotword_private_api_factory = LAZY_INSTANCE_INITIALIZER; - -HotwordPrivateEventService::HotwordPrivateEventService( - content::BrowserContext* context) - : profile_(Profile::FromBrowserContext(context)) { - pref_change_registrar_.Init(profile_->GetPrefs()); - pref_change_registrar_.Add( - prefs::kHotwordSearchEnabled, - base::Bind(&HotwordPrivateEventService::OnEnabledChanged, - base::Unretained(this))); - pref_change_registrar_.Add( - prefs::kHotwordAlwaysOnSearchEnabled, - base::Bind(&HotwordPrivateEventService::OnEnabledChanged, - base::Unretained(this))); -} - -HotwordPrivateEventService::~HotwordPrivateEventService() { -} - -void HotwordPrivateEventService::Shutdown() { -} - -// static -BrowserContextKeyedAPIFactory<HotwordPrivateEventService>* -HotwordPrivateEventService::GetFactoryInstance() { - return g_hotword_private_api_factory.Pointer(); -} - -// static -const char* HotwordPrivateEventService::service_name() { - return "HotwordPrivateEventService"; -} - -void HotwordPrivateEventService::OnEnabledChanged( - const std::string& pref_name) { - DCHECK(pref_name == std::string(prefs::kHotwordSearchEnabled) || - pref_name == std::string(prefs::kHotwordAlwaysOnSearchEnabled) || - pref_name == std::string( - hotword_internal::kHotwordTrainingEnabled)); - SignalEvent(events::HOTWORD_PRIVATE_ON_ENABLED_CHANGED, - OnEnabledChanged::kEventName); -} - -void HotwordPrivateEventService::OnHotwordSessionRequested() { - SignalEvent(events::HOTWORD_PRIVATE_ON_HOTWORD_SESSION_REQUESTED, - api::hotword_private::OnHotwordSessionRequested::kEventName); -} - -void HotwordPrivateEventService::OnHotwordSessionStopped() { - SignalEvent(events::HOTWORD_PRIVATE_ON_HOTWORD_SESSION_STOPPED, - api::hotword_private::OnHotwordSessionStopped::kEventName); -} - -void HotwordPrivateEventService::OnFinalizeSpeakerModel() { - SignalEvent(events::HOTWORD_PRIVATE_ON_FINALIZE_SPEAKER_MODEL, - api::hotword_private::OnFinalizeSpeakerModel::kEventName); -} - -void HotwordPrivateEventService::OnSpeakerModelSaved() { - SignalEvent(events::HOTWORD_PRIVATE_ON_SPEAKER_MODEL_SAVED, - api::hotword_private::OnSpeakerModelSaved::kEventName); -} - -void HotwordPrivateEventService::OnHotwordTriggered() { - SignalEvent(events::HOTWORD_PRIVATE_ON_HOTWORD_TRIGGERED, - api::hotword_private::OnHotwordTriggered::kEventName); -} - -void HotwordPrivateEventService::OnDeleteSpeakerModel() { - SignalEvent(events::HOTWORD_PRIVATE_ON_DELETE_SPEAKER_MODEL, - api::hotword_private::OnDeleteSpeakerModel::kEventName); -} - -void HotwordPrivateEventService::OnSpeakerModelExists() { - SignalEvent(events::HOTWORD_PRIVATE_ON_SPEAKER_MODEL_EXISTS, - api::hotword_private::OnSpeakerModelExists::kEventName); -} - -void HotwordPrivateEventService::OnMicrophoneStateChanged(bool enabled) { - SignalEvent(events::HOTWORD_PRIVATE_ON_MICROPHONE_STATE_CHANGED, - api::hotword_private::OnMicrophoneStateChanged::kEventName, - api::hotword_private::OnMicrophoneStateChanged::Create(enabled)); -} - -void HotwordPrivateEventService::SignalEvent( - events::HistogramValue histogram_value, - const std::string& event_name) { - SignalEvent(histogram_value, event_name, base::MakeUnique<base::ListValue>()); -} - -void HotwordPrivateEventService::SignalEvent( - events::HistogramValue histogram_value, - const std::string& event_name, - std::unique_ptr<base::ListValue> args) { - EventRouter* router = EventRouter::Get(profile_); - if (!router || !router->HasEventListener(event_name)) - return; - - std::unique_ptr<Event> event( - new Event(histogram_value, event_name, std::move(args))); - router->BroadcastEvent(std::move(event)); -} - -ExtensionFunction::ResponseAction HotwordPrivateSetEnabledFunction::Run() { - std::unique_ptr<api::hotword_private::SetEnabled::Params> params( - api::hotword_private::SetEnabled::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - PrefService* prefs = - Profile::FromBrowserContext(browser_context())->GetPrefs(); - prefs->SetBoolean(prefs::kHotwordSearchEnabled, params->state); - return RespondNow(NoArguments()); -} - -ExtensionFunction::ResponseAction -HotwordPrivateSetAudioLoggingEnabledFunction::Run() { - std::unique_ptr<api::hotword_private::SetAudioLoggingEnabled::Params> params( - api::hotword_private::SetAudioLoggingEnabled::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - // TODO(kcarattini): Sync the chrome pref with the account-level - // Audio History setting. - PrefService* prefs = - Profile::FromBrowserContext(browser_context())->GetPrefs(); - prefs->SetBoolean(prefs::kHotwordAudioLoggingEnabled, params->state); - return RespondNow(NoArguments()); -} - -ExtensionFunction::ResponseAction -HotwordPrivateSetHotwordAlwaysOnSearchEnabledFunction::Run() { - std::unique_ptr<api::hotword_private::SetHotwordAlwaysOnSearchEnabled::Params> - params( - api::hotword_private::SetHotwordAlwaysOnSearchEnabled::Params::Create( - *args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - PrefService* prefs = - Profile::FromBrowserContext(browser_context())->GetPrefs(); - prefs->SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, params->state); - return RespondNow(NoArguments()); -} - -ExtensionFunction::ResponseAction HotwordPrivateGetStatusFunction::Run() { - std::unique_ptr<api::hotword_private::GetStatus::Params> params( - api::hotword_private::GetStatus::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - api::hotword_private::StatusDetails result; - - Profile* profile = Profile::FromBrowserContext(browser_context()); - HotwordService* hotword_service = - HotwordServiceFactory::GetForProfile(profile); - if (!hotword_service) { - result.available = false; - result.always_on_available = false; - result.enabled = false; - result.audio_logging_enabled = false; - result.always_on_enabled = false; - result.user_is_active = false; - result.hotword_hardware_available = false; - } else { - result.available = false; - result.always_on_available = false; - if (params->get_optional_fields && *params->get_optional_fields) { - result.available = hotword_service->IsServiceAvailable(); - result.always_on_available = - HotwordServiceFactory::IsAlwaysOnAvailable(); - } - result.enabled = hotword_service->IsSometimesOnEnabled(); - result.audio_logging_enabled = hotword_service->IsOptedIntoAudioLogging(); - result.training_enabled = hotword_service->IsTraining(); - result.always_on_enabled = hotword_service->IsAlwaysOnEnabled(); - result.user_is_active = hotword_service->UserIsActive(); - result.hotword_hardware_available = - HotwordService::IsHotwordHardwareAvailable(); - } - - PrefService* prefs = profile->GetPrefs(); - result.enabled_set = prefs->HasPrefPath(prefs::kHotwordSearchEnabled); - - return RespondNow(OneArgument(result.ToValue())); -} - -ExtensionFunction::ResponseAction -HotwordPrivateSetHotwordSessionStateFunction::Run() { - std::unique_ptr<api::hotword_private::SetHotwordSessionState::Params> params( - api::hotword_private::SetHotwordSessionState::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - HotwordService* hotword_service = HotwordServiceFactory::GetForProfile( - Profile::FromBrowserContext(browser_context())); - if (hotword_service && - hotword_service->client() && - !hotword_service->IsTraining()) - hotword_service->client()->OnHotwordStateChanged(params->started); - return RespondNow(NoArguments()); -} - -ExtensionFunction::ResponseAction -HotwordPrivateNotifyHotwordRecognitionFunction::Run() { - std::unique_ptr<api::hotword_private::NotifyHotwordRecognition::Params> - params(api::hotword_private::NotifyHotwordRecognition::Params::Create( - *args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - scoped_refptr<content::SpeechRecognitionSessionPreamble> preamble; - if (params->log.get() && - !params->log->buffer.empty() && - params->log->channels == 1) { - // TODO(amistry): Convert multi-channel preamble log into mono. - preamble = new content::SpeechRecognitionSessionPreamble(); - preamble->sample_rate = params->log->sample_rate; - preamble->sample_depth = params->log->bytes_per_sample; - preamble->sample_data.swap(params->log->buffer); - } - - Profile* profile = Profile::FromBrowserContext(browser_context()); - HotwordService* hotword_service = - HotwordServiceFactory::GetForProfile(profile); - if (hotword_service) { - if (hotword_service->IsTraining()) { - hotword_service->NotifyHotwordTriggered(); - } else if (hotword_service->client()) { - hotword_service->client()->OnHotwordRecognized(preamble); - } else if (hotword_service->IsAlwaysOnEnabled()) { - AppListService* app_list_service = AppListService::Get(); - CHECK(app_list_service); - app_list_service->ShowForVoiceSearch(profile, preamble); - } - } - - return RespondNow(NoArguments()); -} - -ExtensionFunction::ResponseAction HotwordPrivateGetLaunchStateFunction::Run() { - HotwordService* hotword_service = HotwordServiceFactory::GetForProfile( - Profile::FromBrowserContext(browser_context())); - if (!hotword_service) { - return RespondNow( - Error(hotword_private_constants::kHotwordServiceUnavailable)); - } - - api::hotword_private::LaunchState result; - result.launch_mode = - hotword_service->GetHotwordAudioVerificationLaunchMode(); - return RespondNow(OneArgument(result.ToValue())); -} - -ExtensionFunction::ResponseAction HotwordPrivateStartTrainingFunction::Run() { - HotwordService* hotword_service = HotwordServiceFactory::GetForProfile( - Profile::FromBrowserContext(browser_context())); - if (!hotword_service) { - return RespondNow( - Error(hotword_private_constants::kHotwordServiceUnavailable)); - } - - hotword_service->StartTraining(); - return RespondNow(NoArguments()); -} - -ExtensionFunction::ResponseAction -HotwordPrivateFinalizeSpeakerModelFunction::Run() { - HotwordService* hotword_service = HotwordServiceFactory::GetForProfile( - Profile::FromBrowserContext(browser_context())); - if (!hotword_service) { - return RespondNow( - Error(hotword_private_constants::kHotwordServiceUnavailable)); - } - - hotword_service->FinalizeSpeakerModel(); - return RespondNow(NoArguments()); -} - -ExtensionFunction::ResponseAction -HotwordPrivateNotifySpeakerModelSavedFunction::Run() { - HotwordPrivateEventService* event_service = - BrowserContextKeyedAPIFactory<HotwordPrivateEventService>::Get( - Profile::FromBrowserContext(browser_context())); - if (!event_service) { - return RespondNow( - Error(hotword_private_constants::kHotwordEventServiceUnavailable)); - } - - event_service->OnSpeakerModelSaved(); - return RespondNow(NoArguments()); -} - -ExtensionFunction::ResponseAction HotwordPrivateStopTrainingFunction::Run() { - HotwordService* hotword_service = HotwordServiceFactory::GetForProfile( - Profile::FromBrowserContext(browser_context())); - if (!hotword_service) { - return RespondNow( - Error(hotword_private_constants::kHotwordServiceUnavailable)); - } - - hotword_service->StopTraining(); - return RespondNow(NoArguments()); -} - -ExtensionFunction::ResponseAction -HotwordPrivateGetLocalizedStringsFunction::Run() { -#if defined(OS_CHROMEOS) - base::string16 device_type = ui::GetChromeOSDeviceName(); -#else - base::string16 product_name = - l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME); - base::string16 device_type = - l10n_util::GetStringFUTF16(IDS_HOTWORD_BROWSER_NAME, product_name); -#endif - - std::unique_ptr<base::DictionaryValue> localized_strings( - new base::DictionaryValue()); - - localized_strings->SetString( - "close", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_CLOSE)); - localized_strings->SetString( - "cancel", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_CANCEL)); - localized_strings->SetString( - "introTitle", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_INTRO_TITLE)); - localized_strings->SetString( - "introSubtitle", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_INTRO_SUBTITLE)); - localized_strings->SetString( - "introDescription", - l10n_util::GetStringFUTF16(IDS_HOTWORD_OPT_IN_INTRO_DESCRIPTION, - device_type)); - localized_strings->SetString( - "introDescriptionAudioHistoryEnabled", - l10n_util::GetStringFUTF16( - IDS_HOTWORD_OPT_IN_INTRO_DESCRIPTION_AUDIO_HISTORY_ENABLED, - device_type)); - localized_strings->SetString( - "introStart", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_INTRO_START)); - localized_strings->SetString( - "audioHistoryTitle", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_AUDIO_HISTORY_TITLE)); - localized_strings->SetString( - "audioHistoryDescription1", - l10n_util::GetStringUTF16( - IDS_HOTWORD_OPT_IN_AUDIO_HISTORY_DESCRIPTION_1)); - localized_strings->SetString( - "audioHistoryDescription2", - l10n_util::GetStringUTF16( - IDS_HOTWORD_OPT_IN_AUDIO_HISTORY_DESCRIPTION_2)); - localized_strings->SetString( - "audioHistoryDescription3", - l10n_util::GetStringUTF16( - IDS_HOTWORD_OPT_IN_AUDIO_HISTORY_DESCRIPTION_3)); - localized_strings->SetString( - "audioHistoryAgree", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_AUDIO_HISTORY_AGREE)); - localized_strings->SetString( - "audioHistoryWait", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_AUDIO_HISTORY_WAIT)); - localized_strings->SetString( - "error", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_ERROR)); - localized_strings->SetString( - "trainingTitle", l10n_util::GetStringFUTF16( - IDS_HOTWORD_OPT_IN_TRAINING_TITLE, device_type)); - localized_strings->SetString( - "trainingDescription", - l10n_util::GetStringFUTF16(IDS_HOTWORD_OPT_IN_TRAINING_DESCRIPTION, - device_type)); - localized_strings->SetString( - "trainingSpeak", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_TRAINING_SPEAK)); - localized_strings->SetString( - "trainingFirstPrompt", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_TRAINING_FIRST_PROMPT)); - localized_strings->SetString( - "trainingMiddlePrompt", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_TRAINING_MIDDLE_PROMPT)); - localized_strings->SetString( - "trainingLastPrompt", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_TRAINING_LAST_PROMPT)); - localized_strings->SetString( - "trainingRecorded", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_TRAINING_RECORDED)); - localized_strings->SetString( - "trainingTimeout", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_TRAINING_TIMEOUT)); - localized_strings->SetString( - "trainingRetry", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_TRAINING_RETRY)); - localized_strings->SetString( - "finishedTitle", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_FINISHED_TITLE)); - localized_strings->SetString( - "finishedListIntro", - l10n_util::GetStringFUTF16(IDS_HOTWORD_OPT_IN_FINISHED_LIST_INTRO, - device_type)); - localized_strings->SetString( - "finishedListItem1", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_FINISHED_LIST_ITEM_1)); - localized_strings->SetString( - "finishedListItem2", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_FINISHED_LIST_ITEM_2)); - localized_strings->SetString( - "finishedSettings", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_FINISHED_SETTINGS)); - localized_strings->SetString( - "finishedAudioHistory", - l10n_util::GetStringUTF16( - IDS_HOTWORD_OPT_IN_FINISHED_AUDIO_HISTORY)); - localized_strings->SetString( - "finish", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_FINISH)); - localized_strings->SetString( - "finishedWait", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_FINISHED_WAIT)); - - const std::string& app_locale = g_browser_process->GetApplicationLocale(); - webui::SetLoadTimeDataDefaults(app_locale, localized_strings.get()); - - return RespondNow(OneArgument(std::move(localized_strings))); -} - -bool HotwordPrivateSetAudioHistoryEnabledFunction::RunAsync() { - std::unique_ptr<api::hotword_private::SetAudioHistoryEnabled::Params> params( - api::hotword_private::SetAudioHistoryEnabled::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - HotwordService* hotword_service = - HotwordServiceFactory::GetForProfile(GetProfile()); - if (!hotword_service || !hotword_service->GetAudioHistoryHandler()) { - error_ = hotword_private_constants::kHotwordServiceUnavailable; - return false; - } - - hotword_service->GetAudioHistoryHandler()->SetAudioHistoryEnabled( - params->enabled, - base::Bind( - &HotwordPrivateSetAudioHistoryEnabledFunction::SetResultAndSendResponse, - this)); - return true; -} - -void HotwordPrivateSetAudioHistoryEnabledFunction::SetResultAndSendResponse( - bool success, bool new_enabled_value) { - api::hotword_private::AudioHistoryState result; - result.success = success; - result.enabled = new_enabled_value; - SetResult(result.ToValue()); - SendResponse(true); -} - -bool HotwordPrivateGetAudioHistoryEnabledFunction::RunAsync() { - HotwordService* hotword_service = - HotwordServiceFactory::GetForProfile(GetProfile()); - if (!hotword_service || !hotword_service->GetAudioHistoryHandler()) { - error_ = hotword_private_constants::kHotwordServiceUnavailable; - return false; - } - - hotword_service->GetAudioHistoryHandler()->GetAudioHistoryEnabled(base::Bind( - &HotwordPrivateGetAudioHistoryEnabledFunction::SetResultAndSendResponse, - this)); - - return true; -} - -void HotwordPrivateGetAudioHistoryEnabledFunction::SetResultAndSendResponse( - bool success, bool new_enabled_value) { - api::hotword_private::AudioHistoryState result; - result.success = success; - result.enabled = new_enabled_value; - SetResult(result.ToValue()); - SendResponse(true); -} - -ExtensionFunction::ResponseAction -HotwordPrivateSpeakerModelExistsResultFunction::Run() { - std::unique_ptr<api::hotword_private::SpeakerModelExistsResult::Params> - params(api::hotword_private::SpeakerModelExistsResult::Params::Create( - *args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - HotwordService* hotword_service = HotwordServiceFactory::GetForProfile( - Profile::FromBrowserContext(browser_context())); - if (!hotword_service) - return RespondNow(Error(kUnknownErrorDoNotUse)); - - hotword_service->SpeakerModelExistsComplete(params->exists); - return RespondNow(NoArguments()); -} - -} // namespace extensions
diff --git a/chrome/browser/extensions/api/hotword_private/hotword_private_api.h b/chrome/browser/extensions/api/hotword_private/hotword_private_api.h deleted file mode 100644 index 1f38624..0000000 --- a/chrome/browser/extensions/api/hotword_private/hotword_private_api.h +++ /dev/null
@@ -1,259 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_EXTENSIONS_API_HOTWORD_PRIVATE_HOTWORD_PRIVATE_API_H_ -#define CHROME_BROWSER_EXTENSIONS_API_HOTWORD_PRIVATE_HOTWORD_PRIVATE_API_H_ - -#include "base/values.h" -#include "chrome/browser/extensions/chrome_extension_function.h" -#include "chrome/common/extensions/api/hotword_private.h" -#include "components/prefs/pref_change_registrar.h" -#include "extensions/browser/browser_context_keyed_api_factory.h" -#include "extensions/browser/extension_event_histogram_value.h" - -class Profile; - -namespace extensions { - -// Listens for changes in disable/enabled state and forwards as an extension -// event. -class HotwordPrivateEventService : public BrowserContextKeyedAPI { - public: - explicit HotwordPrivateEventService(content::BrowserContext* context); - ~HotwordPrivateEventService() override; - - // BrowserContextKeyedAPI implementation. - void Shutdown() override; - static BrowserContextKeyedAPIFactory<HotwordPrivateEventService>* - GetFactoryInstance(); - static const char* service_name(); - - void OnEnabledChanged(const std::string& pref_name); - - void OnHotwordSessionRequested(); - - void OnHotwordSessionStopped(); - - void OnHotwordTriggered(); - - void OnFinalizeSpeakerModel(); - - void OnSpeakerModelSaved(); - - void OnDeleteSpeakerModel(); - - void OnSpeakerModelExists(); - - void OnMicrophoneStateChanged(bool enabled); - - private: - friend class BrowserContextKeyedAPIFactory<HotwordPrivateEventService>; - - void SignalEvent(events::HistogramValue histogram_value, - const std::string& event_name); - void SignalEvent(events::HistogramValue histogram_value, - const std::string& event_name, - std::unique_ptr<base::ListValue> args); - - Profile* profile_; - PrefChangeRegistrar pref_change_registrar_; -}; - -class HotwordPrivateSetEnabledFunction : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("hotwordPrivate.setEnabled", - HOTWORDPRIVATE_SETENABLED) - - protected: - ~HotwordPrivateSetEnabledFunction() override {} - - // ExtensionFunction: - ResponseAction Run() override; -}; - -class HotwordPrivateSetAudioLoggingEnabledFunction - : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("hotwordPrivate.setAudioLoggingEnabled", - HOTWORDPRIVATE_SETAUDIOLOGGINGENABLED) - - protected: - ~HotwordPrivateSetAudioLoggingEnabledFunction() override {} - - // ExtensionFunction: - ResponseAction Run() override; -}; - -class HotwordPrivateSetHotwordAlwaysOnSearchEnabledFunction - : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("hotwordPrivate.setHotwordAlwaysOnSearchEnabled", - HOTWORDPRIVATE_SETHOTWORDALWAYSONSEARCHENABLED) - - protected: - ~HotwordPrivateSetHotwordAlwaysOnSearchEnabledFunction() override {} - - // ExtensionFunction: - ResponseAction Run() override; -}; - -class HotwordPrivateGetStatusFunction : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("hotwordPrivate.getStatus", - HOTWORDPRIVATE_GETSTATUS) - - protected: - ~HotwordPrivateGetStatusFunction() override {} - - // ExtensionFunction: - ResponseAction Run() override; -}; - -class HotwordPrivateSetHotwordSessionStateFunction - : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("hotwordPrivate.setHotwordSessionState", - HOTWORDPRIVATE_SETHOTWORDSESSIONSTATE); - - protected: - ~HotwordPrivateSetHotwordSessionStateFunction() override {} - - // ExtensionFunction: - ResponseAction Run() override; -}; - -class HotwordPrivateNotifyHotwordRecognitionFunction - : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("hotwordPrivate.notifyHotwordRecognition", - HOTWORDPRIVATE_NOTIFYHOTWORDRECOGNITION); - - protected: - ~HotwordPrivateNotifyHotwordRecognitionFunction() override {} - - // ExtensionFunction: - ResponseAction Run() override; -}; - -class HotwordPrivateGetLaunchStateFunction : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("hotwordPrivate.getLaunchState", - HOTWORDPRIVATE_GETLAUNCHSTATE) - - protected: - ~HotwordPrivateGetLaunchStateFunction() override {} - - // ExtensionFunction: - ResponseAction Run() override; -}; - -class HotwordPrivateStartTrainingFunction : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("hotwordPrivate.startTraining", - HOTWORDPRIVATE_STARTTRAINING) - - protected: - ~HotwordPrivateStartTrainingFunction() override {} - - // ExtensionFunction: - ResponseAction Run() override; -}; - -class HotwordPrivateFinalizeSpeakerModelFunction - : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("hotwordPrivate.finalizeSpeakerModel", - HOTWORDPRIVATE_FINALIZESPEAKERMODEL) - - protected: - ~HotwordPrivateFinalizeSpeakerModelFunction() override {} - - // ExtensionFunction: - ResponseAction Run() override; -}; - -class HotwordPrivateNotifySpeakerModelSavedFunction - : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("hotwordPrivate.notifySpeakerModelSaved", - HOTWORDPRIVATE_NOTIFYSPEAKERMODELSAVED) - - protected: - ~HotwordPrivateNotifySpeakerModelSavedFunction() override {} - - // ExtensionFunction: - ResponseAction Run() override; -}; - -class HotwordPrivateStopTrainingFunction : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("hotwordPrivate.stopTraining", - HOTWORDPRIVATE_STOPTRAINING) - - protected: - ~HotwordPrivateStopTrainingFunction() override {} - - // ExtensionFunction: - ResponseAction Run() override; -}; - -class HotwordPrivateGetLocalizedStringsFunction - : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("hotwordPrivate.getLocalizedStrings", - HOTWORDPRIVATE_GETLOCALIZEDSTRINGS) - - protected: - ~HotwordPrivateGetLocalizedStringsFunction() override {} - - // ExtensionFunction: - ResponseAction Run() override; -}; - -class HotwordPrivateSetAudioHistoryEnabledFunction - : public ChromeAsyncExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("hotwordPrivate.setAudioHistoryEnabled", - HOTWORDPRIVATE_SETAUDIOHISTORYENABLED) - - protected: - ~HotwordPrivateSetAudioHistoryEnabledFunction() override {} - - // ExtensionFunction: - bool RunAsync() override; - - void SetResultAndSendResponse(bool success, bool new_enabled_value); -}; - -class HotwordPrivateGetAudioHistoryEnabledFunction - : public ChromeAsyncExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("hotwordPrivate.getAudioHistoryEnabled", - HOTWORDPRIVATE_GETAUDIOHISTORYENABLED) - - protected: - ~HotwordPrivateGetAudioHistoryEnabledFunction() override {} - - // ExtensionFunction: - bool RunAsync() override; - - void SetResultAndSendResponse(bool success, bool new_enabled_value); -}; - -class HotwordPrivateSpeakerModelExistsResultFunction - : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("hotwordPrivate.speakerModelExistsResult", - HOTWORDPRIVATE_SPEAKERMODELEXISTSRESULT) - - protected: - ~HotwordPrivateSpeakerModelExistsResultFunction() override {} - - // ExtensionFunction: - ResponseAction Run() override; -}; - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_API_HOTWORD_PRIVATE_HOTWORD_PRIVATE_API_H_
diff --git a/chrome/browser/extensions/api/hotword_private/hotword_private_apitest.cc b/chrome/browser/extensions/api/hotword_private/hotword_private_apitest.cc deleted file mode 100644 index 4ef4e4b..0000000 --- a/chrome/browser/extensions/api/hotword_private/hotword_private_apitest.cc +++ /dev/null
@@ -1,559 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <memory> - -#include "base/command_line.h" -#include "base/macros.h" -#include "base/memory/ptr_util.h" -#include "base/threading/thread_task_runner_handle.h" -#include "chrome/browser/extensions/api/hotword_private/hotword_private_api.h" -#include "chrome/browser/extensions/extension_apitest.h" -#include "chrome/browser/extensions/extension_service.h" -#include "chrome/browser/history/web_history_service_factory.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/search/hotword_audio_history_handler.h" -#include "chrome/browser/search/hotword_client.h" -#include "chrome/browser/search/hotword_service.h" -#include "chrome/browser/search/hotword_service_factory.h" -#include "chrome/browser/signin/profile_oauth2_token_service_factory.h" -#include "chrome/browser/signin/signin_manager_factory.h" -#include "chrome/common/chrome_switches.h" -#include "chrome/common/pref_names.h" -#include "components/history/core/browser/web_history_service.h" -#include "components/prefs/pref_service.h" -#include "components/signin/core/browser/profile_oauth2_token_service.h" -#include "components/signin/core/browser/signin_manager.h" -#include "extensions/common/switches.h" -#include "extensions/test/extension_test_message_listener.h" -#include "net/traffic_annotation/network_traffic_annotation_test_helper.h" -#include "net/url_request/url_request_context_getter.h" - -namespace { - -const char kHotwordTestExtensionId[] = "cpfhkdbjfdgdebcjlifoldbijinjfifp"; - -// Mock the web history service so that we don't make actual requests over the -// network. -class MockWebHistoryService : public history::WebHistoryService { - public: - explicit MockWebHistoryService(Profile* profile) - : WebHistoryService( - ProfileOAuth2TokenServiceFactory::GetForProfile(profile), - SigninManagerFactory::GetForProfile(profile), - profile->GetRequestContext()), - expected_success_(true), - expected_value_(false) {} - ~MockWebHistoryService() override {} - - // For both of the following functions, just call the callback to simulate - // a successful return from the url fetch. - void GetAudioHistoryEnabled(const AudioWebHistoryCallback& callback, - const net::PartialNetworkTrafficAnnotationTag& - partial_traffic_annotation) override { - callback.Run(expected_success_, expected_value_ && expected_success_); - } - - void SetAudioHistoryEnabled(bool new_enabled_value, - const AudioWebHistoryCallback& callback, - const net::PartialNetworkTrafficAnnotationTag& - partial_traffic_annotation) override { - callback.Run(expected_success_, new_enabled_value && expected_success_); - } - - void SetExpectedValue(bool expected_value) { - expected_value_ = expected_value; - } - - void SetFailureState() { - expected_success_ = false; - } - - private: - bool expected_success_; - bool expected_value_; -}; - -// Make a mock audio history handler so that the method for getting the web -// history can be overridden. -class MockAudioHistoryHandler : public HotwordAudioHistoryHandler { - public: - MockAudioHistoryHandler(content::BrowserContext* context, - history::WebHistoryService* web_history) - : HotwordAudioHistoryHandler(context, - base::ThreadTaskRunnerHandle::Get()), - web_history_(web_history) {} - ~MockAudioHistoryHandler() override {} - - history::WebHistoryService* GetWebHistory() override { - return web_history_.get(); - } - - private: - std::unique_ptr<history::WebHistoryService> web_history_; -}; - -class MockHotwordService : public HotwordService { - public: - explicit MockHotwordService(Profile* profile) - : HotwordService(profile), service_available_(true) {} - ~MockHotwordService() override {} - - bool IsServiceAvailable() override { return service_available_; } - - void setServiceAvailable(bool available) { - service_available_ = available; - } - - static std::unique_ptr<KeyedService> Build(content::BrowserContext* profile) { - return base::MakeUnique<MockHotwordService>(static_cast<Profile*>(profile)); - } - - LaunchMode GetHotwordAudioVerificationLaunchMode() override { - return launch_mode_; - } - - void SetHotwordAudioVerificationLaunchMode(const LaunchMode& launch_mode) { - launch_mode_ = launch_mode; - } - - private: - bool service_available_; - LaunchMode launch_mode_; - - DISALLOW_COPY_AND_ASSIGN(MockHotwordService); -}; - -class MockHotwordClient : public HotwordClient { - public: - MockHotwordClient() - : last_enabled_(false), - state_changed_count_(0), - recognized_count_(0) { - } - - ~MockHotwordClient() override {} - - void OnHotwordStateChanged(bool enabled) override { - last_enabled_ = enabled; - state_changed_count_++; - } - - void OnHotwordRecognized( - const scoped_refptr<content::SpeechRecognitionSessionPreamble>& preamble) - override { recognized_count_++; } - - bool last_enabled() const { return last_enabled_; } - int state_changed_count() const { return state_changed_count_; } - int recognized_count() const { return recognized_count_; } - - private: - bool last_enabled_; - int state_changed_count_; - int recognized_count_; - - DISALLOW_COPY_AND_ASSIGN(MockHotwordClient); -}; - -class HotwordPrivateApiTest : public ExtensionApiTest { - public: - HotwordPrivateApiTest() {} - ~HotwordPrivateApiTest() override {} - - void SetUpCommandLine(base::CommandLine* command_line) override { - ExtensionApiTest::SetUpCommandLine(command_line); - - // Whitelist the test extensions (which all share a common ID) to use - // private APIs. - command_line->AppendSwitchASCII( - extensions::switches::kWhitelistedExtensionID, kHotwordTestExtensionId); - } - - void SetUpOnMainThread() override { - ExtensionApiTest::SetUpOnMainThread(); - - test_data_dir_ = test_data_dir_.AppendASCII("hotword_private"); - - service_ = static_cast<MockHotwordService*>( - HotwordServiceFactory::GetInstance()->SetTestingFactoryAndUse( - profile(), MockHotwordService::Build)); - } - - MockHotwordService* service() { - return service_; - } - - private: - MockHotwordService* service_; - - DISALLOW_COPY_AND_ASSIGN(HotwordPrivateApiTest); -}; - -} // anonymous namespace - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, SetEnabled) { - EXPECT_FALSE(profile()->GetPrefs()->GetBoolean(prefs::kHotwordSearchEnabled)); - - ExtensionTestMessageListener listenerTrue("ready", false); - ASSERT_TRUE(RunComponentExtensionTest("setEnabledTrue")) << message_; - EXPECT_TRUE(listenerTrue.WaitUntilSatisfied()); - EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(prefs::kHotwordSearchEnabled)); - - ExtensionTestMessageListener listenerFalse("ready", false); - ASSERT_TRUE(RunComponentExtensionTest("setEnabledFalse")) << message_; - EXPECT_TRUE(listenerFalse.WaitUntilSatisfied()); - EXPECT_FALSE(profile()->GetPrefs()->GetBoolean(prefs::kHotwordSearchEnabled)); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, SetAudioLoggingEnabled) { - EXPECT_FALSE(service()->IsOptedIntoAudioLogging()); - EXPECT_FALSE(profile()->GetPrefs()->GetBoolean( - prefs::kHotwordAudioLoggingEnabled)); - - ExtensionTestMessageListener listenerTrue("ready", false); - ASSERT_TRUE(RunComponentExtensionTest("setAudioLoggingEnableTrue")) - << message_; - EXPECT_TRUE(listenerTrue.WaitUntilSatisfied()); - EXPECT_TRUE(profile()->GetPrefs()->GetBoolean( - prefs::kHotwordAudioLoggingEnabled)); - EXPECT_TRUE(service()->IsOptedIntoAudioLogging()); - - ExtensionTestMessageListener listenerFalse("ready", false); - ASSERT_TRUE(RunComponentExtensionTest("setAudioLoggingEnableFalse")) - << message_; - EXPECT_TRUE(listenerFalse.WaitUntilSatisfied()); - EXPECT_FALSE(profile()->GetPrefs()->GetBoolean( - prefs::kHotwordAudioLoggingEnabled)); - EXPECT_FALSE(service()->IsOptedIntoAudioLogging()); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, SetHotwordAlwaysOnSearchEnabled) { - EXPECT_FALSE(profile()->GetPrefs()->GetBoolean( - prefs::kHotwordAlwaysOnSearchEnabled)); - - ExtensionTestMessageListener listener("ready", false); - ASSERT_TRUE(RunComponentExtensionTest("setHotwordAlwaysOnSearchEnableTrue")) - << message_; - EXPECT_TRUE(listener.WaitUntilSatisfied()); - EXPECT_TRUE(profile()->GetPrefs()->GetBoolean( - prefs::kHotwordAlwaysOnSearchEnabled)); - - listener.Reset(); - ASSERT_TRUE(RunComponentExtensionTest("setHotwordAlwaysOnSearchEnableFalse")) - << message_; - EXPECT_TRUE(listener.WaitUntilSatisfied()); - EXPECT_FALSE(profile()->GetPrefs()->GetBoolean( - prefs::kHotwordAlwaysOnSearchEnabled)); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, GetStatus) { - ASSERT_TRUE(RunComponentExtensionTest("getEnabled")) << message_; -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, IsAvailableTrue) { - service()->setServiceAvailable(true); - ExtensionTestMessageListener listener("available: true", false); - ASSERT_TRUE(RunComponentExtensionTest("isAvailable")) << message_; - EXPECT_TRUE(listener.WaitUntilSatisfied()); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, IsAvailableTrue_NoGet) { - service()->setServiceAvailable(true); - ExtensionTestMessageListener listener("available: false", false); - ASSERT_TRUE(RunComponentExtensionTest("isAvailableNoGet")) << message_; - EXPECT_TRUE(listener.WaitUntilSatisfied()); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, IsAvailableFalse) { - service()->setServiceAvailable(false); - ExtensionTestMessageListener listener("available: false", false); - ASSERT_TRUE(RunComponentExtensionTest("isAvailable")) << message_; - EXPECT_TRUE(listener.WaitUntilSatisfied()); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, AlwaysOnEnabled) { - // Bypass the hotword hardware check. - base::CommandLine::ForCurrentProcess()->AppendSwitch( - switches::kEnableExperimentalHotwordHardware); - - { - ExtensionTestMessageListener listener("alwaysOnEnabled: false", - false); - ASSERT_TRUE(RunComponentExtensionTest("alwaysOnEnabled")) - << message_; - EXPECT_TRUE(listener.WaitUntilSatisfied()); - } - - profile()->GetPrefs()->SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, true); - { - ExtensionTestMessageListener listener("alwaysOnEnabled: true", - false); - ASSERT_TRUE(RunComponentExtensionTest("alwaysOnEnabled")) - << message_; - EXPECT_TRUE(listener.WaitUntilSatisfied()); - } -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, OnEnabledChanged) { - // Trigger the pref registrar. - extensions::HotwordPrivateEventService::GetFactoryInstance(); - ExtensionTestMessageListener listener("ready", false); - ASSERT_TRUE( - LoadExtensionAsComponent(test_data_dir_.AppendASCII("onEnabledChanged"))); - EXPECT_TRUE(listener.WaitUntilSatisfied()); - - ExtensionTestMessageListener listenerNotification("notification", false); - profile()->GetPrefs()->SetBoolean(prefs::kHotwordSearchEnabled, true); - EXPECT_TRUE(listenerNotification.WaitUntilSatisfied()); - - listenerNotification.Reset(); - profile()->GetPrefs()->SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, - true); - EXPECT_TRUE(listenerNotification.WaitUntilSatisfied()); - - listenerNotification.Reset(); - service()->StartTraining(); - EXPECT_TRUE(listenerNotification.WaitUntilSatisfied()); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, HotwordSession) { - extensions::HotwordPrivateEventService::GetFactoryInstance(); - ExtensionTestMessageListener listener("ready", false); - LoadExtensionAsComponent( - test_data_dir_.AppendASCII("hotwordSession")); - EXPECT_TRUE(listener.WaitUntilSatisfied()); - - ExtensionTestMessageListener listenerStopReady("stopReady", false); - ExtensionTestMessageListener listenerStopped("stopped", false); - MockHotwordClient client; - service()->RequestHotwordSession(&client); - EXPECT_TRUE(listenerStopReady.WaitUntilSatisfied()); - service()->StopHotwordSession(&client); - EXPECT_TRUE(listenerStopped.WaitUntilSatisfied()); - - EXPECT_TRUE(client.last_enabled()); - EXPECT_EQ(1, client.state_changed_count()); - EXPECT_EQ(1, client.recognized_count()); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, GetLaunchStateHotwordOnly) { - service()->SetHotwordAudioVerificationLaunchMode( - HotwordService::HOTWORD_ONLY); - ExtensionTestMessageListener listener("launchMode: 0", false); - ASSERT_TRUE(RunComponentExtensionTest("getLaunchState")) << message_; - EXPECT_TRUE(listener.WaitUntilSatisfied()); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, - GetLaunchStateHotwordAudioHistory) { - service()->SetHotwordAudioVerificationLaunchMode( - HotwordService::HOTWORD_AND_AUDIO_HISTORY); - ExtensionTestMessageListener listener("launchMode: 1", false); - ASSERT_TRUE(RunComponentExtensionTest("getLaunchState")) << message_; - EXPECT_TRUE(listener.WaitUntilSatisfied()); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, OnFinalizeSpeakerModel) { - // Trigger the pref registrar. - extensions::HotwordPrivateEventService::GetFactoryInstance(); - ExtensionTestMessageListener listener("ready", false); - ASSERT_TRUE( - LoadExtensionAsComponent(test_data_dir_.AppendASCII( - "onFinalizeSpeakerModel"))); - EXPECT_TRUE(listener.WaitUntilSatisfied()); - - ExtensionTestMessageListener listenerNotification("notification", false); - service()->FinalizeSpeakerModel(); - EXPECT_TRUE(listenerNotification.WaitUntilSatisfied()); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, OnHotwordTriggered) { - // Trigger the pref registrar. - extensions::HotwordPrivateEventService::GetFactoryInstance(); - ExtensionTestMessageListener listener("ready", false); - ASSERT_TRUE( - LoadExtensionAsComponent(test_data_dir_.AppendASCII( - "onHotwordTriggered"))); - EXPECT_TRUE(listener.WaitUntilSatisfied()); - - ExtensionTestMessageListener listenerNotification("notification", false); - service()->NotifyHotwordTriggered(); - EXPECT_TRUE(listenerNotification.WaitUntilSatisfied()); -} - -#if defined(OS_LINUX) -#define MAYBE_OnDeleteSpeakerModel DISABLED_OnDeleteSpeakerModel -#else -#define MAYBE_OnDeleteSpeakerModel OnDeleteSpeakerModel -#endif -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, MAYBE_OnDeleteSpeakerModel) { - MockWebHistoryService* web_history = new MockWebHistoryService(profile()); - MockAudioHistoryHandler* handler = - new MockAudioHistoryHandler(profile(), web_history); - service()->SetAudioHistoryHandler(handler); - web_history->SetExpectedValue(false); - profile()->GetPrefs()->SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, true); - - // Trigger the pref registrar. - extensions::HotwordPrivateEventService::GetFactoryInstance(); - ExtensionTestMessageListener listener("ready", false); - ASSERT_TRUE( - LoadExtensionAsComponent(test_data_dir_.AppendASCII( - "onDeleteSpeakerModel"))); - EXPECT_TRUE(listener.WaitUntilSatisfied()); - - ExtensionTestMessageListener listenerNotification("notification", false); - EXPECT_TRUE(listenerNotification.WaitUntilSatisfied()); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, OnSpeakerModelExists) { - extensions::HotwordPrivateEventService::GetFactoryInstance(); - ExtensionTestMessageListener listener("ready", false); - ASSERT_TRUE( - LoadExtensionAsComponent(test_data_dir_.AppendASCII( - "onSpeakerModelExists"))); - EXPECT_TRUE(listener.WaitUntilSatisfied()); - - service()->OptIntoHotwording(HotwordService::HOTWORD_ONLY); - - ExtensionTestMessageListener listenerNotification("notification", false); - EXPECT_TRUE(listenerNotification.WaitUntilSatisfied()); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, SpeakerModelExistsResult) { - EXPECT_FALSE(profile()->GetPrefs()->GetBoolean( - prefs::kHotwordAlwaysOnSearchEnabled)); - - ExtensionTestMessageListener listenerTrue("ready", false); - ASSERT_TRUE(RunComponentExtensionTest( - "speakerModelExistsResultTrue")) << message_; - EXPECT_TRUE(listenerTrue.WaitUntilSatisfied()); - EXPECT_TRUE(profile()->GetPrefs()->GetBoolean( - prefs::kHotwordAlwaysOnSearchEnabled)); - - PrefService* prefs = profile()->GetPrefs(); - prefs->SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, false); - ExtensionTestMessageListener listenerFalse("ready", false); - ASSERT_TRUE(RunComponentExtensionTest( - "speakerModelExistsResultFalse")) << message_; - EXPECT_TRUE(listenerFalse.WaitUntilSatisfied()); - EXPECT_FALSE(profile()->GetPrefs()->GetBoolean( - prefs::kHotwordAlwaysOnSearchEnabled)); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, Training) { - EXPECT_FALSE(service()->IsTraining()); - - ExtensionTestMessageListener listenerTrue("start training", false); - ASSERT_TRUE(RunComponentExtensionTest("startTraining")) << message_; - EXPECT_TRUE(listenerTrue.WaitUntilSatisfied()); - EXPECT_TRUE(service()->IsTraining()); - - ExtensionTestMessageListener listenerFalse("stop training", false); - ASSERT_TRUE(RunComponentExtensionTest("stopTraining")) << message_; - EXPECT_TRUE(listenerFalse.WaitUntilSatisfied()); - EXPECT_FALSE(service()->IsTraining()); -} - -// Flaky on ChromeOS (https://crbug.com/668335) -#if defined(OS_CHROMEOS) -#define MAYBE_OnSpeakerModelSaved DISABLED_OnSpeakerModelSaved -#else -#define MAYBE_OnSpeakerModelSaved OnSpeakerModelSaved -#endif - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, MAYBE_OnSpeakerModelSaved) { - extensions::HotwordPrivateEventService::GetFactoryInstance(); - ExtensionTestMessageListener listener("ready", false); - ASSERT_TRUE( - LoadExtensionAsComponent(test_data_dir_.AppendASCII( - "onSpeakerModelSaved"))); - EXPECT_TRUE(listener.WaitUntilSatisfied()); - - ExtensionTestMessageListener listenerNotification("notification", false); - EXPECT_TRUE(listenerNotification.WaitUntilSatisfied()); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, NotifySpeakerModelSaved) { - ExtensionTestMessageListener listener("speaker model saved", false); - ASSERT_TRUE( - RunComponentExtensionTest("notifySpeakerModelSaved")) << message_; - EXPECT_TRUE(listener.WaitUntilSatisfied()); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, AudioHistory) { - MockWebHistoryService* web_history = new MockWebHistoryService(profile()); - MockAudioHistoryHandler* handler = - new MockAudioHistoryHandler(profile(), web_history); - service()->SetAudioHistoryHandler(handler); - web_history->SetExpectedValue(true); - - ExtensionTestMessageListener setListenerT("set AH True: true success", false); - ExtensionTestMessageListener setListenerF("set AH False: false success", - false); - ExtensionTestMessageListener getListener("get AH: true success", false); - - ASSERT_TRUE(RunComponentExtensionTest("audioHistory")) << message_; - - EXPECT_TRUE(setListenerT.WaitUntilSatisfied()); - EXPECT_TRUE(setListenerF.WaitUntilSatisfied()); - EXPECT_TRUE(getListener.WaitUntilSatisfied()); - - web_history->SetExpectedValue(false); - - ExtensionTestMessageListener setListenerT2("set AH True: true success", - false); - ExtensionTestMessageListener setListenerF2("set AH False: false success", - false); - ExtensionTestMessageListener getListener2("get AH: false success", false); - - ASSERT_TRUE(RunComponentExtensionTest("audioHistory")) << message_; - - EXPECT_TRUE(setListenerT2.WaitUntilSatisfied()); - EXPECT_TRUE(setListenerF2.WaitUntilSatisfied()); - EXPECT_TRUE(getListener2.WaitUntilSatisfied()); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, AudioHistoryNoWebHistory) { - MockAudioHistoryHandler* handler = - new MockAudioHistoryHandler(profile(), nullptr); - service()->SetAudioHistoryHandler(handler); - - // Set an initial value for the audio logging pref. - PrefService* prefs = profile()->GetPrefs(); - prefs->SetBoolean(prefs::kHotwordAudioLoggingEnabled, true); - - ExtensionTestMessageListener setListenerT("set AH True: true failure", false); - ExtensionTestMessageListener setListenerF("set AH False: true failure", - false); - ExtensionTestMessageListener getListener("get AH: true failure", false); - - ASSERT_TRUE(RunComponentExtensionTest("audioHistory")) << message_; - - EXPECT_TRUE(setListenerT.WaitUntilSatisfied()); - EXPECT_TRUE(setListenerF.WaitUntilSatisfied()); - EXPECT_TRUE(getListener.WaitUntilSatisfied()); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, AudioHistoryWebHistoryFailure) { - MockWebHistoryService* web_history = new MockWebHistoryService(profile()); - MockAudioHistoryHandler* handler = - new MockAudioHistoryHandler(profile(), web_history); - service()->SetAudioHistoryHandler(handler); - web_history->SetFailureState(); - // It shouldn't matter if this is set to true. GetAudioHistoryEnabled should - // still return false. - web_history->SetExpectedValue(true); - - ExtensionTestMessageListener setListenerT("set AH True: true failure", false); - ExtensionTestMessageListener setListenerF("set AH False: false failure", - false); - ExtensionTestMessageListener getListener("get AH: false failure", false); - - ASSERT_TRUE(RunComponentExtensionTest("audioHistory")) << message_; - - EXPECT_TRUE(setListenerT.WaitUntilSatisfied()); - EXPECT_TRUE(setListenerF.WaitUntilSatisfied()); - EXPECT_TRUE(getListener.WaitUntilSatisfied()); -}
diff --git a/chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.cc b/chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.cc new file mode 100644 index 0000000..dc857e6f --- /dev/null +++ b/chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.cc
@@ -0,0 +1,47 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.h" + +#include "chrome/browser/component_updater/cros_component_installer.h" + +namespace media_perception = extensions::api::media_perception_private; + +namespace extensions { + +namespace { + +constexpr char kLightComponentName[] = "rtanalytics-light"; +constexpr char kFullComponentName[] = "rtanalytics-full"; + +std::string GetComponentNameForComponentType( + const media_perception::ComponentType& type) { + switch (type) { + case media_perception::COMPONENT_TYPE_LIGHT: + return kLightComponentName; + case media_perception::COMPONENT_TYPE_FULL: + return kFullComponentName; + case media_perception::COMPONENT_TYPE_NONE: + LOG(ERROR) << "No component type requested."; + return ""; + } + NOTREACHED() << "Reached component type not in switch."; + return ""; +} + +} // namespace + +MediaPerceptionAPIDelegateChromeOS::MediaPerceptionAPIDelegateChromeOS() = + default; + +MediaPerceptionAPIDelegateChromeOS::~MediaPerceptionAPIDelegateChromeOS() {} + +void MediaPerceptionAPIDelegateChromeOS::LoadCrOSComponent( + const media_perception::ComponentType& type, + LoadCrOSComponentCallback load_callback) { + component_updater::CrOSComponent::LoadComponent( + GetComponentNameForComponentType(type), std::move(load_callback)); +} + +} // namespace extensions
diff --git a/chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.h b/chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.h new file mode 100644 index 0000000..4457251 --- /dev/null +++ b/chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.h
@@ -0,0 +1,30 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_EXTENSIONS_API_MEDIA_PERCEPTION_PRIVATE_MEDIA_PERCEPTION_API_DELEGATE_CHROMEOS_H_ +#define CHROME_BROWSER_EXTENSIONS_API_MEDIA_PERCEPTION_PRIVATE_MEDIA_PERCEPTION_API_DELEGATE_CHROMEOS_H_ + +#include "base/callback_forward.h" +#include "extensions/browser/api/media_perception_private/media_perception_api_delegate.h" + +namespace extensions { + +class MediaPerceptionAPIDelegateChromeOS + : public extensions::MediaPerceptionAPIDelegate { + public: + MediaPerceptionAPIDelegateChromeOS(); + ~MediaPerceptionAPIDelegateChromeOS() override; + + // extensions::MediaPerceptionAPIDelegate: + void LoadCrOSComponent( + const api::media_perception_private::ComponentType& type, + LoadCrOSComponentCallback load_callback) override; + + private: + DISALLOW_COPY_AND_ASSIGN(MediaPerceptionAPIDelegateChromeOS); +}; + +} // namespace extensions + +#endif // CHROME_BROWSER_EXTENSIONS_API_MEDIA_PERCEPTION_PRIVATE_MEDIA_PERCEPTION_API_DELEGATE_CHROMEOS_H_
diff --git a/chrome/browser/extensions/api/preference/preference_api.cc b/chrome/browser/extensions/api/preference/preference_api.cc index b388308..153c8f7 100644 --- a/chrome/browser/extensions/api/preference/preference_api.cc +++ b/chrome/browser/extensions/api/preference/preference_api.cc
@@ -102,8 +102,6 @@ APIPermission::kPrivacy, APIPermission::kPrivacy}, {"hyperlinkAuditingEnabled", prefs::kEnableHyperlinkAuditing, APIPermission::kPrivacy, APIPermission::kPrivacy}, - {"hotwordSearchEnabled", prefs::kHotwordSearchEnabled, - APIPermission::kPrivacy, APIPermission::kPrivacy}, {"networkPredictionEnabled", prefs::kNetworkPredictionOptions, APIPermission::kPrivacy, APIPermission::kPrivacy}, {"passwordSavingEnabled",
diff --git a/chrome/browser/extensions/api/settings_private/prefs_util.cc b/chrome/browser/extensions/api/settings_private/prefs_util.cc index 2c0ae37..7b73936b 100644 --- a/chrome/browser/extensions/api/settings_private/prefs_util.cc +++ b/chrome/browser/extensions/api/settings_private/prefs_util.cc
@@ -426,12 +426,6 @@ settings_private::PrefType::PREF_TYPE_BOOLEAN; #endif - // Search settings. - (*s_whitelist)[::prefs::kHotwordSearchEnabled] = - settings_private::PrefType::PREF_TYPE_BOOLEAN; - (*s_whitelist)[::prefs::kHotwordAlwaysOnSearchEnabled] = - settings_private::PrefType::PREF_TYPE_BOOLEAN; - // Proxy settings. (*s_whitelist)[proxy_config::prefs::kProxy] = settings_private::PrefType::PREF_TYPE_DICTIONARY;
diff --git a/chrome/browser/extensions/browser_action_test_util.h b/chrome/browser/extensions/browser_action_test_util.h index cf90784..6ca3ac57 100644 --- a/chrome/browser/extensions/browser_action_test_util.h +++ b/chrome/browser/extensions/browser_action_test_util.h
@@ -108,7 +108,7 @@ // A private constructor to create an overflow version. BrowserActionTestUtil(Browser* browser, BrowserActionTestUtil* main_bar); - Browser* browser_; // weak + Browser* const browser_; // weak // Our test helper, which constructs and owns the views if we don't have a // real browser window, or if this is an overflow version.
diff --git a/chrome/browser/extensions/browser_context_keyed_service_factories.cc b/chrome/browser/extensions/browser_context_keyed_service_factories.cc index 2403fc0f..0ff6f15 100644 --- a/chrome/browser/extensions/browser_context_keyed_service_factories.cc +++ b/chrome/browser/extensions/browser_context_keyed_service_factories.cc
@@ -20,7 +20,6 @@ #include "chrome/browser/extensions/api/extension_action/extension_action_api.h" #include "chrome/browser/extensions/api/font_settings/font_settings_api.h" #include "chrome/browser/extensions/api/history/history_api.h" -#include "chrome/browser/extensions/api/hotword_private/hotword_private_api.h" #include "chrome/browser/extensions/api/identity/identity_api.h" #include "chrome/browser/extensions/api/language_settings_private/language_settings_private_delegate_factory.h" #include "chrome/browser/extensions/api/omnibox/omnibox_api.h" @@ -94,7 +93,6 @@ extensions::ExtensionWebUIOverrideRegistrar::GetFactoryInstance(); extensions::FontSettingsAPI::GetFactoryInstance(); extensions::HistoryAPI::GetFactoryInstance(); - extensions::HotwordPrivateEventService::GetFactoryInstance(); extensions::IdentityAPI::GetFactoryInstance(); extensions::InstallTrackerFactory::GetInstance(); extensions::InstallVerifierFactory::GetInstance();
diff --git a/chrome/browser/extensions/browser_extension_window_controller.h b/chrome/browser/extensions/browser_extension_window_controller.h index 86545fd..7f12097 100644 --- a/chrome/browser/extensions/browser_extension_window_controller.h +++ b/chrome/browser/extensions/browser_extension_window_controller.h
@@ -35,7 +35,7 @@ const extensions::Extension* extension) const override; private: - Browser* browser_; + Browser* const browser_; DISALLOW_COPY_AND_ASSIGN(BrowserExtensionWindowController); };
diff --git a/chrome/browser/extensions/chrome_extension_test_notification_observer.h b/chrome/browser/extensions/chrome_extension_test_notification_observer.h index df4995b..1c7d4f42 100644 --- a/chrome/browser/extensions/chrome_extension_test_notification_observer.h +++ b/chrome/browser/extensions/chrome_extension_test_notification_observer.h
@@ -47,7 +47,7 @@ // ExtensionActionAPI::Observer: void OnPageActionsUpdated(content::WebContents* contents) override; - Browser* browser_; + Browser* const browser_; DISALLOW_COPY_AND_ASSIGN(ChromeExtensionTestNotificationObserver); };
diff --git a/chrome/browser/extensions/component_extensions_whitelist/whitelist.cc b/chrome/browser/extensions/component_extensions_whitelist/whitelist.cc index c81399a..d8a82a2 100644 --- a/chrome/browser/extensions/component_extensions_whitelist/whitelist.cc +++ b/chrome/browser/extensions/component_extensions_whitelist/whitelist.cc
@@ -26,7 +26,6 @@ bool IsComponentExtensionWhitelisted(const std::string& extension_id) { const char* const kAllowed[] = { - extension_misc::kHotwordSharedModuleId, extension_misc::kInAppPaymentsSupportAppId, extension_misc::kMediaRouterStableExtensionId, extension_misc::kPdfExtensionId, @@ -73,10 +72,6 @@ #if BUILDFLAG(ENABLE_HANGOUT_SERVICES_EXTENSION) case IDR_HANGOUT_SERVICES_MANIFEST: #endif -#if defined(ENABLE_HOTWORDING) - case IDR_HOTWORD_AUDIO_VERIFICATION_MANIFEST: - case IDR_HOTWORD_MANIFEST: -#endif case IDR_IDENTITY_API_SCOPE_APPROVAL_MANIFEST: #if defined(OS_CHROMEOS) case IDR_IMAGE_LOADER_MANIFEST:
diff --git a/chrome/browser/extensions/component_loader.cc b/chrome/browser/extensions/component_loader.cc index d6a3a47..7b8e2be 100644 --- a/chrome/browser/extensions/component_loader.cc +++ b/chrome/browser/extensions/component_loader.cc
@@ -19,8 +19,6 @@ #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/pdf/pdf_extension_util.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/search/hotword_service.h" -#include "chrome/browser/search/hotword_service_factory.h" #include "chrome/browser/ui/webui/md_bookmarks/md_bookmarks_ui.h" #include "chrome/common/channel_info.h" #include "chrome/common/chrome_paths.h" @@ -356,24 +354,6 @@ #endif } -void ComponentLoader::AddHotwordAudioVerificationApp() { -#if defined(ENABLE_HOTWORDING) - if (HotwordServiceFactory::IsAlwaysOnAvailable()) { - Add(IDR_HOTWORD_AUDIO_VERIFICATION_MANIFEST, - base::FilePath(FILE_PATH_LITERAL("hotword_audio_verification"))); - } -#endif -} - -void ComponentLoader::AddHotwordHelperExtension() { -#if defined(ENABLE_HOTWORDING) - if (HotwordServiceFactory::IsHotwordAllowed(profile_)) { - Add(IDR_HOTWORD_MANIFEST, - base::FilePath(FILE_PATH_LITERAL("hotword"))); - } -#endif -} - void ComponentLoader::AddImageLoaderExtension() { #if defined(OS_CHROMEOS) Add(IDR_IMAGE_LOADER_MANIFEST, @@ -580,8 +560,6 @@ AddWebstoreWidgetExtension(); AddHangoutServicesExtension(); - AddHotwordAudioVerificationApp(); - AddHotwordHelperExtension(); AddImageLoaderExtension(); bool install_feedback = enable_background_extensions_during_testing;
diff --git a/chrome/browser/extensions/component_loader.h b/chrome/browser/extensions/component_loader.h index 6cb9596..3416f56 100644 --- a/chrome/browser/extensions/component_loader.h +++ b/chrome/browser/extensions/component_loader.h
@@ -168,7 +168,6 @@ void AddZipArchiverExtension(); void AddWebstoreWidgetExtension(); void AddHangoutServicesExtension(); - void AddHotwordHelperExtension(); void AddImageLoaderExtension(); void AddNetworkSpeechSynthesisExtension(); @@ -177,7 +176,6 @@ const std::string& name_string, const std::string& description_string); void AddChromeApp(); - void AddHotwordAudioVerificationApp(); void AddKeyboardApp(); void AddWebStoreApp();
diff --git a/chrome/browser/extensions/extension_context_menu_model.h b/chrome/browser/extensions/extension_context_menu_model.h index 3f7c704b..c7a8aee 100644 --- a/chrome/browser/extensions/extension_context_menu_model.h +++ b/chrome/browser/extensions/extension_context_menu_model.h
@@ -117,7 +117,7 @@ // it has one, otherwise NULL). ExtensionAction* extension_action_; - Browser* browser_; + Browser* const browser_; Profile* profile_;
diff --git a/chrome/browser/extensions/extension_message_bubble_controller.h b/chrome/browser/extensions/extension_message_bubble_controller.h index b74b5c5..5b3a9cbc 100644 --- a/chrome/browser/extensions/extension_message_bubble_controller.h +++ b/chrome/browser/extensions/extension_message_bubble_controller.h
@@ -215,7 +215,7 @@ void OnClose(); // A weak pointer to the Browser we are associated with. Not owned by us. - Browser* browser_; + Browser* const browser_; // The associated ToolbarActionsModel. Not owned. ToolbarActionsModel* model_;
diff --git a/chrome/browser/extensions/extension_service.h b/chrome/browser/extensions/extension_service.h index 90729097..30ea503f 100644 --- a/chrome/browser/extensions/extension_service.h +++ b/chrome/browser/extensions/extension_service.h
@@ -273,21 +273,20 @@ // Returns true if an uninstall was successfully triggered; this can fail if // the extension cannot be uninstalled (such as a policy force-installed // extension). - virtual bool UninstallExtension(const std::string& extension_id, - extensions::UninstallReason reason, - base::string16* error); + bool UninstallExtension(const std::string& extension_id, + extensions::UninstallReason reason, + base::string16* error); // Enables the extension. If the extension is already enabled, does // nothing. - virtual void EnableExtension(const std::string& extension_id); + void EnableExtension(const std::string& extension_id); // Disables the extension. If the extension is already disabled, just adds // the |disable_reasons| (a bitmask of disable_reason::DisableReason - there // can be multiple DisableReasons e.g. when an extension comes in disabled // from Sync). If the extension cannot be disabled (due to policy), does // nothing. - virtual void DisableExtension(const std::string& extension_id, - int disable_reasons); + void DisableExtension(const std::string& extension_id, int disable_reasons); // Disable non-default and non-managed extensions with ids not in // |except_ids|. Default extensions are those from the Web Store with
diff --git a/chrome/browser/extensions/external_component_loader.cc b/chrome/browser/extensions/external_component_loader.cc index 8768741..27b103f 100644 --- a/chrome/browser/extensions/external_component_loader.cc +++ b/chrome/browser/extensions/external_component_loader.cc
@@ -9,8 +9,6 @@ #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/component_extensions_whitelist/whitelist.h" #include "chrome/browser/media/router/media_router_feature.h" -#include "chrome/browser/search/hotword_service.h" -#include "chrome/browser/search/hotword_service_factory.h" #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/common/features.h" @@ -20,7 +18,6 @@ #include "extensions/common/manifest.h" #if defined(OS_CHROMEOS) -#include "base/command_line.h" #include "chromeos/chromeos_switches.h" #endif @@ -38,9 +35,6 @@ AddExternalExtension(extension_misc::kInAppPaymentsSupportAppId, prefs.get()); #endif // defined(GOOGLE_CHROME_BUILD) - if (HotwordServiceFactory::IsHotwordAllowed(profile_)) - AddExternalExtension(extension_misc::kHotwordSharedModuleId, prefs.get()); - #if defined(OS_CHROMEOS) { base::CommandLine* const command_line =
diff --git a/chrome/browser/extensions/hotword_browsertest.cc b/chrome/browser/extensions/hotword_browsertest.cc deleted file mode 100644 index 076a455..0000000 --- a/chrome/browser/extensions/hotword_browsertest.cc +++ /dev/null
@@ -1,85 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/files/file_path.h" -#include "base/macros.h" -#include "chrome/browser/extensions/component_loader.h" -#include "chrome/browser/extensions/error_console/error_console.h" -#include "chrome/browser/extensions/extension_browsertest.h" -#include "chrome/browser/extensions/extension_service.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/common/chrome_switches.h" -#include "chrome/common/pref_names.h" -#include "components/prefs/pref_service.h" -#include "content/public/common/content_switches.h" -#include "extensions/common/extension.h" -#include "extensions/test/extension_test_message_listener.h" -#include "testing/gtest/include/gtest/gtest.h" - - -namespace extensions { - -static const char kHotwordHelperExtensionId[] = - "dnhpdliibojhegemfjheidglijccjfmc"; - -class HotwordBrowserTest : public ExtensionBrowserTest { - public: - HotwordBrowserTest() : error_console_(NULL) { } - ~HotwordBrowserTest() override {} - - protected: - void SetUpInProcessBrowserTestFixture() override { - ExtensionBrowserTest::SetUpInProcessBrowserTestFixture(); - - // Load the hotword_helper extension. - ComponentLoader::EnableBackgroundExtensionsForTesting(); - - // We need to enable the ErrorConsole FeatureSwitch in order to collect - // errors. This should be enabled on any channel <= Dev, but let's make - // sure (in case a test is running on, e.g., a beta channel). - FeatureSwitch::error_console()->SetOverrideValue( - FeatureSwitch::OVERRIDE_ENABLED); - } - - void SetUpOnMainThread() override { - ExtensionBrowserTest::SetUpOnMainThread(); - - // Errors are only kept if we have Developer Mode enabled. - profile()->GetPrefs()->SetBoolean(prefs::kExtensionsUIDeveloperMode, true); - - error_console_ = ErrorConsole::Get(profile()); - ASSERT_TRUE(error_console_); - } - - ErrorConsole* error_console() { return error_console_; } - - private: - // Weak reference to the ErrorConsole. - ErrorConsole* error_console_; - - DISALLOW_COPY_AND_ASSIGN(HotwordBrowserTest); -}; - -// Test we silently capture an exception from a message handler's response -// callback. This happens when the caller to chrome.runtime.sendMessage() -// doesn't specify a response callback. -// NOTE(amistry): Test is disabled instead of deleted since the functionality -// may still be required to implement crbug.com/436681 -IN_PROC_BROWSER_TEST_F(HotwordBrowserTest, DISABLED_MessageSendResponseError) { - // Enable error reporting for the hotword helper extension. - error_console()->SetReportingAllForExtension(kHotwordHelperExtensionId, true); - - ExtensionTestMessageListener doneListener("done", false); - const Extension* extension = extension_service()->GetExtensionById( - kHotwordHelperExtensionId, false); - ASSERT_TRUE(extension); - const Extension* test_extension = LoadExtension( - test_data_dir_.AppendASCII("hotword")); - ASSERT_TRUE(test_extension); - - ASSERT_TRUE(doneListener.WaitUntilSatisfied()); - ASSERT_TRUE(error_console()->GetErrorsForExtension(extension->id()).empty()); -} - -} // namespace extensions
diff --git a/chrome/browser/feedback/system_logs/log_sources/chrome_internal_log_source.cc b/chrome/browser/feedback/system_logs/log_sources/chrome_internal_log_source.cc index bef5e094..ff39e3e 100644 --- a/chrome/browser/feedback/system_logs/log_sources/chrome_internal_log_source.cc +++ b/chrome/browser/feedback/system_logs/log_sources/chrome_internal_log_source.cc
@@ -115,7 +115,7 @@ DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(!callback.is_null()); - std::unique_ptr<SystemLogsResponse> response(new SystemLogsResponse()); + auto response = std::make_unique<SystemLogsResponse>(); response->emplace(kChromeVersionTag, chrome::GetVersionString()); @@ -152,14 +152,14 @@ // Get the entries that should be retrieved on the blocking pool and invoke // the callback later when done. - SystemLogsResponse* response_ptr = response.release(); + SystemLogsResponse* response_ptr = response.get(); base::PostTaskWithTraitsAndReply( FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND}, - base::Bind(&GetEntriesAsync, response_ptr), - base::Bind(callback, base::Owned(response_ptr))); + base::BindOnce(&GetEntriesAsync, response_ptr), + base::BindOnce(callback, std::move(response))); #else // On other platforms, we're done. Invoke the callback. - callback.Run(response.get()); + callback.Run(std::move(response)); #endif // defined(OS_CHROMEOS) }
diff --git a/chrome/browser/feedback/system_logs/log_sources/crash_ids_source.cc b/chrome/browser/feedback/system_logs/log_sources/crash_ids_source.cc index 747a442..43bbcd6 100644 --- a/chrome/browser/feedback/system_logs/log_sources/crash_ids_source.cc +++ b/chrome/browser/feedback/system_logs/log_sources/crash_ids_source.cc
@@ -78,11 +78,11 @@ void CrashIdsSource::RespondWithCrashIds( const SysLogsSourceCallback& callback) const { - std::unique_ptr<SystemLogsResponse> response(new SystemLogsResponse()); + auto response = std::make_unique<SystemLogsResponse>(); (*response)[feedback::FeedbackReport::kCrashReportIdsKey] = crash_ids_list_; // We must respond anyways. - callback.Run(response.get()); + callback.Run(std::move(response)); } } // namespace system_logs
diff --git a/chrome/browser/feedback/system_logs/log_sources/memory_details_log_source.cc b/chrome/browser/feedback/system_logs/log_sources/memory_details_log_source.cc index bdcfd7f..3e8f0df9 100644 --- a/chrome/browser/feedback/system_logs/log_sources/memory_details_log_source.cc +++ b/chrome/browser/feedback/system_logs/log_sources/memory_details_log_source.cc
@@ -21,9 +21,9 @@ void OnDetailsAvailable() override { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - std::unique_ptr<SystemLogsResponse> response(new SystemLogsResponse); + auto response = std::make_unique<SystemLogsResponse>(); (*response)["mem_usage"] = ToLogString(); - callback_.Run(response.get()); + callback_.Run(std::move(response)); } private:
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index 95ef64f1..2ba4686 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -580,12 +580,6 @@ "Displays experimental UI to allow mouse and touch input methods to exit " "fullscreen mode."; -const char kExperimentalHotwordHardwareName[] = - "Simulated hardware 'Ok Google' features"; -const char kExperimentalHotwordHardwareDescription[] = - "Enables an experimental version of 'Ok Google' hotword detection features " - "that have a hardware dependency."; - const char kExperimentalKeyboardLockUiName[] = "Experimental keyboard lock UI."; const char kExperimentalKeyboardLockUiDescription[] = "An experimental full screen with keyboard lock mode requiring users to " @@ -867,13 +861,6 @@ const char kNewBookmarkAppsDescription[] = "Enables the new system for creating bookmark apps."; -const char kNewOmniboxAnswerTypesName[] = - "New omnibox answers in suggest types"; -const char kNewOmniboxAnswerTypesDescription[] = - "Enables new types of answers in the omnibox suggest drop-down: currency " - "conversions, dictionary definitions, sports scores, translations, and " - "when is."; - const char kNewRemotePlaybackPipelineName[] = "Enable the new remote playback pipeline."; const char kNewRemotePlaybackPipelineDescription[] =
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index 0050a38..d5e2dbd 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -372,9 +372,6 @@ extern const char kExperimentalFullscreenExitUIName[]; extern const char kExperimentalFullscreenExitUIDescription[]; -extern const char kExperimentalHotwordHardwareName[]; -extern const char kExperimentalHotwordHardwareDescription[]; - extern const char kExperimentalKeyboardLockUiName[]; extern const char kExperimentalKeyboardLockUiDescription[]; @@ -544,9 +541,6 @@ extern const char kNewBookmarkAppsName[]; extern const char kNewBookmarkAppsDescription[]; -extern const char kNewOmniboxAnswerTypesName[]; -extern const char kNewOmniboxAnswerTypesDescription[]; - extern const char kNewRemotePlaybackPipelineName[]; extern const char kNewRemotePlaybackPipelineDescription[];
diff --git a/chrome/browser/media/media_engagement_browsertest.cc b/chrome/browser/media/media_engagement_browsertest.cc index d5304934..2a8dc47 100644 --- a/chrome/browser/media/media_engagement_browsertest.cc +++ b/chrome/browser/media/media_engagement_browsertest.cc
@@ -6,6 +6,7 @@ #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" #include "base/test/scoped_feature_list.h" +#include "base/test/simple_test_clock.h" #include "base/test/test_mock_time_task_runner.h" #include "base/time/time.h" #include "chrome/browser/media/media_engagement_contents_observer.h" @@ -70,7 +71,8 @@ class MediaEngagementBrowserTest : public InProcessBrowserTest { public: MediaEngagementBrowserTest() - : task_runner_(new base::TestMockTimeTaskRunner()) { + : test_clock_(new base::SimpleTestClock()), + task_runner_(new base::TestMockTimeTaskRunner()) { http_server_.ServeFilesFromSourceDirectory(kMediaEngagementTestDataPath); http_server_origin2_.ServeFilesFromSourceDirectory( kMediaEngagementTestDataPath); @@ -86,6 +88,8 @@ media::kRecordMediaEngagementScores); InProcessBrowserTest::SetUp(); + + injected_clock_ = false; }; void LoadTestPage(const std::string& page) { @@ -110,7 +114,10 @@ }; void Advance(base::TimeDelta time) { + DCHECK(injected_clock_); task_runner_->FastForwardBy(time); + static_cast<base::SimpleTestClock*>(GetService()->clock_.get()) + ->Advance(time); base::RunLoop().RunUntilIdle(); } @@ -199,6 +206,11 @@ } void InjectTimerTaskRunner() { + if (!injected_clock_) { + GetService()->clock_ = std::move(test_clock_); + injected_clock_ = true; + } + contents_observer()->SetTaskRunnerForTest(task_runner_); } @@ -212,6 +224,10 @@ return *mei_service->contents_observers_.begin(); } + bool injected_clock_ = false; + + std::unique_ptr<base::SimpleTestClock> test_clock_; + net::EmbeddedTestServer http_server_; net::EmbeddedTestServer http_server_origin2_; @@ -432,3 +448,11 @@ CloseTab(); ExpectScores(1, 1, 3, 2); } + +IN_PROC_BROWSER_TEST_F(MediaEngagementBrowserTest, + RecordAudibleBasedOnShortTime) { + LoadTestPageAndWaitForPlayAndAudible("engagement_test.html", false); + Advance(base::TimeDelta::FromSeconds(4)); + CloseTab(); + ExpectScores(1, 0, 1, 0); +}
diff --git a/chrome/browser/media/media_engagement_contents_observer.cc b/chrome/browser/media/media_engagement_contents_observer.cc index 5e3b9526..da8beb2 100644 --- a/chrome/browser/media/media_engagement_contents_observer.cc +++ b/chrome/browser/media/media_engagement_contents_observer.cc
@@ -10,10 +10,10 @@ #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" -#include "content/public/common/associated_interface_provider.h" #include "services/metrics/public/cpp/ukm_builders.h" #include "services/metrics/public/cpp/ukm_entry_builder.h" #include "services/metrics/public/cpp/ukm_recorder.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" #include "third_party/WebKit/public/platform/media_engagement.mojom.h" namespace { @@ -36,6 +36,9 @@ const gfx::Size MediaEngagementContentsObserver::kSignificantSize = gfx::Size(200, 140); +const base::TimeDelta MediaEngagementContentsObserver::kMaxShortPlaybackTime = + base::TimeDelta::FromSeconds(3); + const char* const MediaEngagementContentsObserver::kHistogramScoreAtPlaybackName = "Media.Engagement.ScoreAtPlayback"; @@ -70,61 +73,148 @@ MediaEngagementContentsObserver::~MediaEngagementContentsObserver() = default; +MediaEngagementContentsObserver::PlaybackTimer::PlaybackTimer( + base::Clock* clock) + : clock_(clock) {} + +void MediaEngagementContentsObserver::PlaybackTimer::Start() { + start_time_ = clock_->Now(); +} + +void MediaEngagementContentsObserver::PlaybackTimer::Stop() { + recorded_time_ = Elapsed(); + start_time_.reset(); +} + +bool MediaEngagementContentsObserver::PlaybackTimer::IsRunning() const { + return start_time_.has_value(); +} + +base::TimeDelta MediaEngagementContentsObserver::PlaybackTimer::Elapsed() + const { + base::Time now = clock_->Now(); + base::TimeDelta duration = now - start_time_.value_or(now); + return recorded_time_ + duration; +} + +void MediaEngagementContentsObserver::PlaybackTimer::Reset() { + recorded_time_ = base::TimeDelta(); + start_time_.reset(); +} + void MediaEngagementContentsObserver::WebContentsDestroyed() { + StashAudiblePlayers(); + // Commit a visit if we have not had a playback. MaybeCommitPendingData(kVisitEnd); - playback_timer_->Stop(); - RecordUkmMetrics(); ClearPlayerStates(); service_->contents_observers_.erase(this); delete this; } void MediaEngagementContentsObserver::ClearPlayerStates() { + playback_timer_->Stop(); player_states_.clear(); significant_players_.clear(); } -void MediaEngagementContentsObserver::RecordUkmMetrics() { - ukm::UkmRecorder* ukm_recorder = ukm::UkmRecorder::Get(); - if (!ukm_recorder) +void MediaEngagementContentsObserver::RecordUkmMetrics( + int audible_players_count, + int significant_players_count) { + ukm::UkmRecorder* recorder = GetUkmRecorder(); + if (!recorder) return; - GURL url = committed_origin_.GetURL(); - if (!service_->ShouldRecordEngagement(url)) - return; - - ukm::SourceId source_id = ukm_recorder->GetNewSourceID(); - ukm_recorder->UpdateSourceURL(source_id, url); - - MediaEngagementScore score = service_->CreateEngagementScore(url); - ukm::builders::Media_Engagement_SessionFinished(source_id) + MediaEngagementScore score = + service_->CreateEngagementScore(committed_origin_.GetURL()); + ukm::builders::Media_Engagement_SessionFinished(ukm_source_id_) .SetPlaybacks_Total(score.media_playbacks()) .SetVisits_Total(score.visits()) .SetEngagement_Score(ConvertScoreToPercentage(score.actual_score())) .SetPlaybacks_Delta(significant_playback_recorded_) .SetEngagement_IsHigh(score.high_score()) - .Record(ukm_recorder); + .SetPlayer_Audible_Delta(audible_players_count) + .SetPlayer_Audible_Total(score.audible_playbacks()) + .SetPlayer_Significant_Delta(significant_players_count) + .SetPlayer_Significant_Total(score.significant_playbacks()) + .SetPlaybacks_SecondsSinceLast(time_since_playback_for_ukm_.InSeconds()) + .Record(recorder); + + time_since_playback_for_ukm_ = base::TimeDelta(); +} + +MediaEngagementContentsObserver::PendingCommitState& +MediaEngagementContentsObserver::GetPendingCommitState() { + if (!pending_data_to_commit_.has_value()) + pending_data_to_commit_ = PendingCommitState(); + return pending_data_to_commit_.value(); +} + +void MediaEngagementContentsObserver::RecordUkmIgnoredEvent(int length_msec) { + ukm::UkmRecorder* recorder = GetUkmRecorder(); + if (!recorder) + return; + + ukm::builders::Media_Engagement_ShortPlaybackIgnored(ukm_source_id_) + .SetLength(length_msec) + .Record(recorder); +} + +ukm::UkmRecorder* MediaEngagementContentsObserver::GetUkmRecorder() { + GURL url = committed_origin_.GetURL(); + if (!service_->ShouldRecordEngagement(url)) + return nullptr; + + ukm::UkmRecorder* ukm_recorder = ukm::UkmRecorder::Get(); + if (!ukm_recorder) + return nullptr; + + if (ukm_source_id_ == ukm::kInvalidSourceId) { + // TODO(beccahughes): Get from web contents. + ukm_source_id_ = ukm_recorder->GetNewSourceID(); + ukm_recorder->UpdateSourceURL(ukm_source_id_, url); + } + + return ukm_recorder; +} + +void MediaEngagementContentsObserver::StashAudiblePlayers() { + PendingCommitState& state = GetPendingCommitState(); + + for (const auto& row : audible_players_) { + const PlayerState& player_state = GetPlayerState(row.first); + const base::TimeDelta elapsed = player_state.playback_timer->Elapsed(); + + if (elapsed < kMaxShortPlaybackTime && player_state.reached_end_of_stream) { + RecordUkmIgnoredEvent(elapsed.InMilliseconds()); + continue; + } + + state.significant_players += row.second.first; + state.audible_players++; + } + + audible_players_.clear(); } void MediaEngagementContentsObserver::MaybeCommitPendingData( CommitTrigger trigger) { - // The audible players should only be recorded when the visit ends. - int audible_players_count = 0; - int significant_players_count = 0; - if (trigger == kVisitEnd) { - audible_players_count = audible_players_.size(); - for (const auto& row : audible_players_) - significant_players_count += row.second.first; - } + // If the visit is over, make sure we have stashed all audible player data. + DCHECK(trigger != kVisitEnd || audible_players_.empty()); - if (!pending_data_to_commit_.has_value() && !audible_players_count) + // If we don't have anything to commit then we can stop. + if (!pending_data_to_commit_.has_value()) { + // If we do not have anything to commit we should still record to UKM. + if (trigger == kVisitEnd) + RecordUkmMetrics(0, 0); return; + } + PendingCommitState& state = pending_data_to_commit_.value(); // If the current origin is not a valid URL then we should just silently reset // any pending data. - if (!committed_origin_.GetURL().is_valid()) { + if (!service_->ShouldRecordEngagement(committed_origin_.GetURL())) { pending_data_to_commit_.reset(); audible_players_.clear(); return; @@ -133,27 +223,35 @@ MediaEngagementScore score = service_->CreateEngagementScore(committed_origin_.GetURL()); - if (pending_data_to_commit_.has_value()) + if (state.visit) score.IncrementVisits(); - if (pending_data_to_commit_.value_or(false)) + if (state.media_playback) { + // Media playbacks trigger a commit so we should only increment media + // playbacks if a significant media playback has occured. + DCHECK_EQ(trigger, kSignificantMediaPlayback); + const base::Time old_time = score.last_media_playback_time(); score.IncrementMediaPlaybacks(); - if (audible_players_count > 0) - score.IncrementAudiblePlaybacks(audible_players_count); + if (!old_time.is_null()) { + // Calculate the time since the last playback and the first significant + // playback this visit. If there is no last playback time then we will + // record 0. + time_since_playback_for_ukm_ = + score.last_media_playback_time() - old_time; + } + } - if (significant_players_count > 0) - score.IncrementSignificantPlaybacks(significant_players_count); + score.IncrementAudiblePlaybacks(state.audible_players); + score.IncrementSignificantPlaybacks(state.significant_players); score.Commit(); pending_data_to_commit_.reset(); - // Reset the audible players set. - if (audible_players_count) { - DCHECK_EQ(kVisitEnd, trigger); - audible_players_.clear(); - } + // If the commit trigger was the end then we should record UKM metrics. + if (trigger == kVisitEnd) + RecordUkmMetrics(state.audible_players, state.significant_players); } void MediaEngagementContentsObserver::DidFinishNavigation( @@ -164,7 +262,7 @@ return; } - playback_timer_->Stop(); + StashAudiblePlayers(); ClearPlayerStates(); url::Origin new_origin = url::Origin::Create(navigation_handle->GetURL()); @@ -175,23 +273,24 @@ // updated. MaybeCommitPendingData(kVisitEnd); - RecordUkmMetrics(); - committed_origin_ = new_origin; significant_playback_recorded_ = false; + ukm_source_id_ = ukm::kInvalidSourceId; // As any pending data would have been committed above, we should have no // pending data and we should create a PendingData object. A visit will be // automatically recorded if the PendingData object is present when // MaybeCommitPendingData is called. DCHECK(!pending_data_to_commit_.has_value()); - pending_data_to_commit_ = false; + GetPendingCommitState().visit = true; } -MediaEngagementContentsObserver::PlayerState::PlayerState() = default; +MediaEngagementContentsObserver::PlayerState::PlayerState(base::Clock* clock) + : playback_timer(new PlaybackTimer(clock)) {} -MediaEngagementContentsObserver::PlayerState& -MediaEngagementContentsObserver::PlayerState::operator=(const PlayerState&) = +MediaEngagementContentsObserver::PlayerState::~PlayerState() = default; + +MediaEngagementContentsObserver::PlayerState::PlayerState(PlayerState&&) = default; MediaEngagementContentsObserver::PlayerState& @@ -200,8 +299,9 @@ if (state != player_states_.end()) return state->second; - player_states_[id] = PlayerState(); - return player_states_[id]; + auto iter = player_states_.insert( + std::make_pair(id, PlayerState(service_->clock_.get()))); + return iter.first->second; } void MediaEngagementContentsObserver::MediaStartedPlaying( @@ -212,6 +312,13 @@ state.has_audio = media_player_info.has_audio; state.has_video = media_player_info.has_video; + // Reset the playback timer if we previously reached the end of the stream. + if (state.reached_end_of_stream) { + state.playback_timer->Reset(); + state.reached_end_of_stream = false; + } + state.playback_timer->Start(); + MaybeInsertRemoveSignificantPlayer(media_player_id); UpdatePlayerTimer(media_player_id); RecordEngagementScoreToHistogramAtPlayback(media_player_id); @@ -258,7 +365,14 @@ const MediaPlayerInfo& media_player_info, const MediaPlayerId& media_player_id, WebContentsObserver::MediaStoppedReason reason) { - GetPlayerState(media_player_id).playing = false; + PlayerState& state = GetPlayerState(media_player_id); + state.playing = false; + state.reached_end_of_stream = + reason == WebContentsObserver::MediaStoppedReason::kReachedEndOfStream; + + // Reset the playback timer if we finished playing. + state.playback_timer->Stop(); + MaybeInsertRemoveSignificantPlayer(media_player_id); UpdatePlayerTimer(media_player_id); } @@ -332,7 +446,7 @@ // A playback always comes after a visit so the visit should always be pending // to commit. DCHECK(pending_data_to_commit_.has_value()); - pending_data_to_commit_ = true; + pending_data_to_commit_->media_playback = true; MaybeCommitPendingData(kSignificantMediaPlayback); }
diff --git a/chrome/browser/media/media_engagement_contents_observer.h b/chrome/browser/media/media_engagement_contents_observer.h index a02fa2c4..46132a2 100644 --- a/chrome/browser/media/media_engagement_contents_observer.h +++ b/chrome/browser/media/media_engagement_contents_observer.h
@@ -6,11 +6,20 @@ #define CHROME_BROWSER_MEDIA_MEDIA_ENGAGEMENT_CONTENTS_OBSERVER_H_ #include "content/public/browser/web_contents_observer.h" +#include "services/metrics/public/cpp/ukm_source_id.h" + +namespace base { +class Clock; +} // namespace base namespace gfx { class Size; } // namespace gfx +namespace ukm { +class UkmRecorder; +} // namespace ukm + class MediaEngagementContentsObserverTest; class MediaEngagementService; @@ -50,6 +59,9 @@ MediaEngagementContentsObserver(content::WebContents* web_contents, MediaEngagementService* service); + // This is the maximum playback time for media to be considered 'short'. + static const base::TimeDelta kMaxShortPlaybackTime; + // This enum is used to record a histogram and should not be renumbered. enum class InsignificantPlaybackReason { // The frame size of the video is too small. @@ -105,8 +117,33 @@ // significant playback. std::set<MediaPlayerId> significant_players_; + // Measures playback time for a player. + class PlaybackTimer { + public: + explicit PlaybackTimer(base::Clock*); + + void Start(); + void Stop(); + bool IsRunning() const; + base::TimeDelta Elapsed() const; + void Reset(); + + DISALLOW_COPY_AND_ASSIGN(PlaybackTimer); + + private: + // The clock is owned by |service_| which already owns |this|. + base::Clock* clock_; + + base::Optional<base::Time> start_time_; + base::TimeDelta recorded_time_; + }; + // A structure containing all the information we have about a player's state. struct PlayerState { + explicit PlayerState(base::Clock*); + ~PlayerState(); + PlayerState(PlayerState&&); + base::Optional<bool> muted; base::Optional<bool> playing; // Currently playing. base::Optional<bool> significant_size; // The video track has at least @@ -122,8 +159,10 @@ // to a histogram. bool reasons_recorded = false; - PlayerState(); - PlayerState& operator=(const PlayerState&); + bool reached_end_of_stream = false; + std::unique_ptr<PlaybackTimer> playback_timer; + + DISALLOW_COPY_AND_ASSIGN(PlayerState); }; std::map<MediaPlayerId, PlayerState> player_states_; PlayerState& GetPlayerState(const MediaPlayerId& id); @@ -172,7 +211,12 @@ static const int kMaxInsignificantPlaybackReason; // Record the score and change in score to UKM. - void RecordUkmMetrics(); + void RecordUkmMetrics(int audible_players_count, + int significant_players_count); + + // Record the length of an ignored media playback. + void RecordUkmIgnoredEvent(int length_msec); + ukm::UkmRecorder* GetUkmRecorder(); bool significant_playback_recorded_ = false; @@ -180,11 +224,19 @@ // can identify whether the playback would have been blocked. void RecordEngagementScoreToHistogramAtPlayback(const MediaPlayerId& id); + void StashAudiblePlayers(); + // Stores pending media engagement data that needs to be committed either // after a navigation to another domain, when the observer is destroyed or - // when we have had a media playback. A visit is automatically implied. If - // the bool is true then a playback will be recorded too. - base::Optional<bool> pending_data_to_commit_; + // when we have had a media playback. + struct PendingCommitState { + bool visit = false; + bool media_playback = false; + int audible_players = 0; + int significant_players = 0; + }; + PendingCommitState& GetPendingCommitState(); + base::Optional<PendingCommitState> pending_data_to_commit_; // Stores the ids of the players that were audible. The boolean will be true // if the player was significant. @@ -194,6 +246,12 @@ // The task runner to use when creating timers. It is used only for testing. scoped_refptr<base::SequencedTaskRunner> task_runner_; + // The current UKM source id for |committed_origin_|. + ukm::SourceId ukm_source_id_ = ukm::kInvalidSourceId; + + // The time between significant playbacks to be recorded to UKM. + base::TimeDelta time_since_playback_for_ukm_; + url::Origin committed_origin_; static const base::TimeDelta kSignificantMediaPlaybackTime;
diff --git a/chrome/browser/media/media_engagement_contents_observer_unittest.cc b/chrome/browser/media/media_engagement_contents_observer_unittest.cc index 13bf238..2c886db3 100644 --- a/chrome/browser/media/media_engagement_contents_observer_unittest.cc +++ b/chrome/browser/media/media_engagement_contents_observer_unittest.cc
@@ -7,6 +7,7 @@ #include "base/optional.h" #include "base/test/histogram_tester.h" #include "base/test/scoped_feature_list.h" +#include "base/test/simple_test_clock.h" #include "base/test/test_mock_time_task_runner.h" #include "base/timer/mock_timer.h" #include "build/build_config.h" @@ -27,7 +28,8 @@ : public ChromeRenderViewHostTestHarness { public: MediaEngagementContentsObserverTest() - : task_runner_(new base::TestMockTimeTaskRunner()){}; + : task_runner_(new base::TestMockTimeTaskRunner()), + test_clock_(new base::SimpleTestClock()) {} void SetUp() override { scoped_feature_list_.InitFromCommandLine("RecordMediaEngagementScores", @@ -37,10 +39,10 @@ SetContents(content::WebContentsTester::CreateTestWebContents( browser_context(), nullptr)); - service_ = MediaEngagementService::Get(profile()); - ASSERT_TRUE(service_); + service_ = base::WrapUnique( + new MediaEngagementService(profile(), base::WrapUnique(test_clock_))); contents_observer_ = - new MediaEngagementContentsObserver(web_contents(), service_); + new MediaEngagementContentsObserver(web_contents(), service_.get()); contents_observer_->SetTaskRunnerForTest(task_runner_); SimulateInaudible(); @@ -100,13 +102,24 @@ SimulateMutedStateChange(id, muted_state); } - void SimulatePlaybackStopped(int id) { + void SimulatePlaybackStoppedWithTime(int id, + bool finished, + base::TimeDelta elapsed) { + test_clock_->Advance(elapsed); + content::WebContentsObserver::MediaPlayerInfo player_info(true, true); content::WebContentsObserver::MediaPlayerId player_id = std::make_pair(nullptr /* RenderFrameHost */, id); contents_observer_->MediaStoppedPlaying( player_info, player_id, - content::WebContentsObserver::MediaStoppedReason::kUnspecified); + finished + ? content::WebContentsObserver::MediaStoppedReason:: + kReachedEndOfStream + : content::WebContentsObserver::MediaStoppedReason::kUnspecified); + } + + void SimulatePlaybackStopped(int id) { + SimulatePlaybackStoppedWithTime(id, true, base::TimeDelta::FromSeconds(0)); } void SimulateMutedStateChange(int id, bool muted) { @@ -132,6 +145,7 @@ } void SimulateSignificantPlaybackTimeForPlayer(int id) { + SimulateLongMediaPlayback(id); content::WebContentsObserver::MediaPlayerId player_id = std::make_pair(nullptr /* RenderFrameHost */, id); contents_observer_->OnSignificantMediaPlaybackTimeForPlayer(player_id); @@ -157,14 +171,24 @@ EXPECT_EQ(expected_significant_playbacks, score.significant_playbacks()); } - void SetScores(GURL url, int visits, int media_playbacks) { + void SetScores(GURL url, + int visits, + int media_playbacks, + int audible_playbacks, + int significant_playbacks) { MediaEngagementScore score = contents_observer_->service_->CreateEngagementScore(url); score.SetVisits(visits); score.SetMediaPlaybacks(media_playbacks); + score.set_audible_playbacks(audible_playbacks); + score.set_significant_playbacks(significant_playbacks); score.Commit(); } + void SetScores(GURL url, int visits, int media_playbacks) { + SetScores(url, visits, media_playbacks, 0, 0); + } + void Navigate(GURL url) { std::unique_ptr<content::NavigationHandle> test_handle = content::NavigationHandle::CreateNavigationHandleForTesting( @@ -188,7 +212,12 @@ int visits_total, int score, int playbacks_delta, - bool high_score) { + bool high_score, + int audible_players_delta, + int audible_players_total, + int significant_players_delta, + int significant_players_total, + int seconds_since_playback) { using Entry = ukm::builders::Media_Engagement_SessionFinished; std::vector<std::pair<const char*, int64_t>> metrics = { @@ -197,25 +226,38 @@ {Entry::kEngagement_ScoreName, score}, {Entry::kPlaybacks_DeltaName, playbacks_delta}, {Entry::kEngagement_IsHighName, high_score}, + {Entry::kPlayer_Audible_DeltaName, audible_players_delta}, + {Entry::kPlayer_Audible_TotalName, audible_players_total}, + {Entry::kPlayer_Significant_DeltaName, significant_players_delta}, + {Entry::kPlayer_Significant_TotalName, significant_players_total}, + {Entry::kPlaybacks_SecondsSinceLastName, seconds_since_playback}, }; const ukm::UkmSource* source = test_ukm_recorder_.GetSourceForUrl(url.spec().c_str()); EXPECT_EQ(url, source->url()); EXPECT_EQ(1, test_ukm_recorder_.CountEntries(*source, Entry::kEntryName)); - test_ukm_recorder_.ExpectMetric(*source, Entry::kEntryName, - Entry::kVisits_TotalName, visits_total); - test_ukm_recorder_.ExpectMetric(*source, Entry::kEntryName, - Entry::kPlaybacks_TotalName, - playbacks_total); - test_ukm_recorder_.ExpectMetric(*source, Entry::kEntryName, - Entry::kEngagement_ScoreName, score); - test_ukm_recorder_.ExpectMetric(*source, Entry::kEntryName, - Entry::kPlaybacks_DeltaName, - playbacks_delta); test_ukm_recorder_.ExpectEntry(*source, Entry::kEntryName, metrics); } + void ExpectUkmIgnoredEntries(GURL url, std::vector<int64_t> entries) { + using Entry = ukm::builders::Media_Engagement_ShortPlaybackIgnored; + auto ukm_entries = test_ukm_recorder_.GetEntriesByName(Entry::kEntryName); + + EXPECT_EQ(entries.size(), ukm_entries.size()); + for (std::vector<int>::size_type i = 0; i < entries.size(); i++) { + test_ukm_recorder_.ExpectEntrySourceHasUrl(ukm_entries[i], url); + EXPECT_EQ(entries[i], *test_ukm_recorder_.GetEntryMetric( + ukm_entries[i], Entry::kLengthName)); + } + } + + void ExpectNoUkmIgnoreEntry(GURL url) { + using Entry = ukm::builders::Media_Engagement_ShortPlaybackIgnored; + auto ukm_entries = test_ukm_recorder_.GetEntriesByName(Entry::kEntryName); + EXPECT_EQ(0U, ukm_entries.size()); + } + void ExpectNoUkmEntry() { EXPECT_FALSE(test_ukm_recorder_.sources_count()); } void SimulateDestroy() { contents_observer_->WebContentsDestroyed(); } @@ -265,11 +307,40 @@ static_cast<int>(reason), count); } + void ExpectPlaybackTime(int id, base::TimeDelta expected_time) { + content::WebContentsObserver::MediaPlayerId player_id = + std::make_pair(nullptr /* RenderFrameHost */, id); + EXPECT_EQ(expected_time, contents_observer_->GetPlayerState(player_id) + .playback_timer->Elapsed()); + } + + void SimulateLongMediaPlayback(int id) { + SimulatePlaybackStoppedWithTime( + id, false, MediaEngagementContentsObserver::kMaxShortPlaybackTime); + } + + void SetLastPlaybackTime(GURL url, base::Time new_time) { + MediaEngagementScore score = service_->CreateEngagementScore(url); + score.set_last_media_playback_time(new_time); + score.Commit(); + } + + void ExpectLastPlaybackTime(GURL url, const base::Time expected_time) { + MediaEngagementScore score = service_->CreateEngagementScore(url); + EXPECT_EQ(expected_time, score.last_media_playback_time()); + } + + base::Time Now() const { return test_clock_->Now(); } + + void Advance15Minutes() { + test_clock_->Advance(base::TimeDelta::FromMinutes(15)); + } + private: // contents_observer_ auto-destroys when WebContents is destroyed. MediaEngagementContentsObserver* contents_observer_; - MediaEngagementService* service_; + std::unique_ptr<MediaEngagementService> service_; base::test::ScopedFeatureList scoped_feature_list_; @@ -279,6 +350,8 @@ scoped_refptr<base::TestMockTimeTaskRunner> task_runner_; + base::SimpleTestClock* test_clock_; + const base::TimeDelta kMaxWaitingTime = MediaEngagementContentsObserver::kSignificantMediaPlaybackTime + base::TimeDelta::FromSeconds(2); @@ -690,59 +763,86 @@ TEST_F(MediaEngagementContentsObserverTest, RecordUkmMetricsOnDestroy) { GURL url("https://www.google.com"); - SetScores(url, 6, 5); - Navigate(url); - - EXPECT_FALSE(WasSignificantPlaybackRecorded()); - SimulateSignificantVideoPlayer(0); - SimulateSignificantPlaybackTimeForPage(); - ExpectScores(url, 6.0 / 7.0, 7, 6, 0, 0); - EXPECT_TRUE(WasSignificantPlaybackRecorded()); - - SimulateDestroy(); - ExpectUkmEntry(url, 6, 7, 86, 1, true); -} - -TEST_F(MediaEngagementContentsObserverTest, - RecordUkmMetricsOnDestroy_NoPlaybacks) { - GURL url("https://www.google.com"); - SetScores(url, 6, 5); - Navigate(url); - - EXPECT_FALSE(WasSignificantPlaybackRecorded()); - ExpectScores(url, 5.0 / 6.0, 6, 5, 0, 0); - - SimulateDestroy(); - ExpectUkmEntry(url, 5, 7, 71, 0, true); -} - -TEST_F(MediaEngagementContentsObserverTest, RecordUkmMetricsOnNavigate) { - GURL url("https://www.google.com"); - SetScores(url, 6, 5); + SetScores(url, 6, 5, 3, 1); Navigate(url); EXPECT_FALSE(WasSignificantPlaybackRecorded()); SimulateSignificantVideoPlayer(0); SimulateSignificantPlaybackTimeForPage(); SimulateSignificantPlaybackTimeForPlayer(0); + SimulateSignificantVideoPlayer(1); + EXPECT_TRUE(WasSignificantPlaybackRecorded()); + + SimulateDestroy(); + ExpectScores(url, 6.0 / 7.0, 7, 6, 5, 2); + ExpectUkmEntry(url, 6, 7, 86, 1, true, 2, 5, 1, 2, 0); +} + +TEST_F(MediaEngagementContentsObserverTest, + RecordUkmMetricsOnDestroy_NoPlaybacks) { + GURL url("https://www.google.com"); + SetScores(url, 6, 5, 2, 1); + Navigate(url); + + EXPECT_FALSE(WasSignificantPlaybackRecorded()); + + SimulateDestroy(); + ExpectScores(url, 5.0 / 7.0, 7, 5, 2, 1); + ExpectUkmEntry(url, 5, 7, 71, 0, true, 0, 2, 0, 1, 0); +} + +TEST_F(MediaEngagementContentsObserverTest, RecordUkmMetricsOnNavigate) { + GURL url("https://www.google.com"); + SetScores(url, 6, 5, 3, 1); + Navigate(url); + + EXPECT_FALSE(WasSignificantPlaybackRecorded()); + SimulateSignificantVideoPlayer(0); + SimulateSignificantPlaybackTimeForPage(); + SimulateSignificantPlaybackTimeForPlayer(0); + SimulateSignificantVideoPlayer(1); EXPECT_TRUE(WasSignificantPlaybackRecorded()); Navigate(GURL("https://www.example.org")); - ExpectScores(url, 6.0 / 7.0, 7, 6, 1, 1); - ExpectUkmEntry(url, 6, 7, 86, 1, true); + ExpectScores(url, 6.0 / 7.0, 7, 6, 5, 2); + ExpectUkmEntry(url, 6, 7, 86, 1, true, 2, 5, 1, 2, 0); } TEST_F(MediaEngagementContentsObserverTest, RecordUkmMetricsOnNavigate_NoPlaybacks) { GURL url("https://www.google.com"); - SetScores(url, 9, 2); + SetScores(url, 9, 2, 2, 1); Navigate(url); EXPECT_FALSE(WasSignificantPlaybackRecorded()); Navigate(GURL("https://www.example.org")); - ExpectScores(url, 2 / 10.0, 10, 2, 0, 0); - ExpectUkmEntry(url, 2, 10, 20, 0, false); + ExpectScores(url, 2 / 10.0, 10, 2, 2, 1); + ExpectUkmEntry(url, 2, 10, 20, 0, false, 0, 2, 0, 1, 0); +} + +TEST_F(MediaEngagementContentsObserverTest, + RecordUkmMetrics_MultiplePlaybackTime) { + GURL url("https://www.google.com"); + SetScores(url, 6, 5, 3, 1); + Advance15Minutes(); + SetLastPlaybackTime(url, Now()); + Navigate(url); + + Advance15Minutes(); + const base::Time first = Now(); + SimulateSignificantVideoPlayer(0); + SimulateSignificantPlaybackTimeForPage(); + SimulateSignificantPlaybackTimeForPlayer(0); + + Advance15Minutes(); + SimulateSignificantVideoPlayer(1); + SimulateSignificantPlaybackTimeForPlayer(1); + + SimulateDestroy(); + ExpectScores(url, 6.0 / 7.0, 7, 6, 5, 3); + ExpectLastPlaybackTime(url, first); + ExpectUkmEntry(url, 6, 7, 86, 1, true, 2, 5, 2, 3, 900); } TEST_F(MediaEngagementContentsObserverTest, DoNotRecordMetricsOnInternalUrl) { @@ -766,7 +866,7 @@ SimulateSignificantAudioPlayer(0); SimulateSignificantVideoPlayer(1); SimulateSignificantVideoPlayer(2); - SimulateSignificantVideoPlayer(2); + SimulateSignificantPlaybackTimeForPlayer(2); // This one is video only. SimulatePlaybackStarted(3, false, true); @@ -819,7 +919,8 @@ // Navigate to a sub page and continue watching. Navigate(GURL("https://www.google.com/test")); - SimulateSignificantAudioPlayer(6); + SimulateSignificantAudioPlayer(1); + SimulateLongMediaPlayback(1); ExpectScores(url, 0, 1, 1, 0, 0); // Test that when we navigate to a new origin the audible players the scores @@ -833,6 +934,7 @@ Navigate(url); SimulateSignificantVideoPlayer(0); + SimulateLongMediaPlayback(0); ForceUpdateTimer(1); SimulateDestroy(); @@ -876,3 +978,74 @@ SimulateDestroy(); ExpectScores(url, 0, 1, 0, 1, 1); } + +TEST_F(MediaEngagementContentsObserverTest, RecordPlaybackTime) { + SimulateSignificantAudioPlayer(0); + SimulatePlaybackStoppedWithTime(0, false, base::TimeDelta::FromSeconds(3)); + ExpectPlaybackTime(0, base::TimeDelta::FromSeconds(3)); + + SimulateSignificantAudioPlayer(0); + SimulatePlaybackStoppedWithTime(0, false, base::TimeDelta::FromSeconds(6)); + ExpectPlaybackTime(0, base::TimeDelta::FromSeconds(9)); + + SimulateSignificantAudioPlayer(0); + SimulatePlaybackStoppedWithTime(0, true, base::TimeDelta::FromSeconds(2)); + ExpectPlaybackTime(0, base::TimeDelta::FromSeconds(11)); + + SimulateSignificantAudioPlayer(0); + SimulatePlaybackStoppedWithTime(0, false, base::TimeDelta::FromSeconds(2)); + ExpectPlaybackTime(0, base::TimeDelta::FromSeconds(2)); +} + +TEST_F(MediaEngagementContentsObserverTest, ShortMediaIgnored) { + GURL url("https://www.google.com"); + Navigate(url); + + // Start three audible players. + SimulateSignificantAudioPlayer(0); + SimulateSignificantPlaybackTimeForPlayer(0); + SimulateSignificantVideoPlayer(1); + SimulatePlaybackStoppedWithTime(1, true, base::TimeDelta::FromSeconds(1)); + SimulateSignificantVideoPlayer(2); + SimulateSignificantPlaybackTimeForPlayer(2); + + // Navigate to a sub page and continue watching. + Navigate(GURL("https://www.google.com/test")); + SimulateSignificantAudioPlayer(1); + SimulatePlaybackStoppedWithTime(1, true, base::TimeDelta::FromSeconds(2)); + + // Test that when we navigate to a new origin the audible players the scores + // are recorded and we log extra UKM events with the times. + Navigate(GURL("https://www.google.co.uk")); + ExpectScores(url, 0, 1, 0, 2, 2); + ExpectUkmIgnoredEntries(url, std::vector<int64_t>{1000, 2000}); +} + +TEST_F(MediaEngagementContentsObserverTest, TotalTimeUsedInShortCalculation) { + GURL url("https://www.google.com"); + Navigate(url); + + SimulateSignificantAudioPlayer(0); + SimulatePlaybackStoppedWithTime(0, false, base::TimeDelta::FromSeconds(8)); + SimulateSignificantPlaybackTimeForPlayer(0); + + SimulateSignificantAudioPlayer(0); + SimulatePlaybackStoppedWithTime(0, true, base::TimeDelta::FromSeconds(2)); + ExpectPlaybackTime(0, base::TimeDelta::FromSeconds(10)); + + SimulateDestroy(); + ExpectScores(url, 0, 1, 0, 1, 1); + ExpectNoUkmIgnoreEntry(url); +} + +TEST_F(MediaEngagementContentsObserverTest, OnlyIgnoreFinishedMedia) { + GURL url("https://www.google.com"); + Navigate(url); + + SimulateSignificantAudioPlayer(0); + SimulatePlaybackStoppedWithTime(0, false, base::TimeDelta::FromSeconds(2)); + + SimulateDestroy(); + ExpectScores(url, 0, 1, 0, 1, 0); + ExpectNoUkmIgnoreEntry(url); +}
diff --git a/chrome/browser/media/media_engagement_score.h b/chrome/browser/media/media_engagement_score.h index 09e4a198..80209a52 100644 --- a/chrome/browser/media/media_engagement_score.h +++ b/chrome/browser/media/media_engagement_score.h
@@ -118,6 +118,9 @@ void set_visits_with_media_tag(int visits) { visits_with_media_tag_ = visits; } + void set_last_media_playback_time(base::Time new_time) { + last_media_playback_time_ = new_time; + } private: friend class MediaEngagementServiceTest;
diff --git a/chrome/browser/media/router/discovery/mdns/cast_media_sink_service_impl.cc b/chrome/browser/media/router/discovery/mdns/cast_media_sink_service_impl.cc index 0eed65a..bcfa772 100644 --- a/chrome/browser/media/router/discovery/mdns/cast_media_sink_service_impl.cc +++ b/chrome/browser/media/router/discovery/mdns/cast_media_sink_service_impl.cc
@@ -15,6 +15,7 @@ #include "chrome/common/media_router/discovery/media_sink_service.h" #include "chrome/common/media_router/media_sink.h" #include "components/cast_channel/cast_channel_enum.h" +#include "components/cast_channel/cast_channel_util.h" #include "components/cast_channel/cast_socket_service.h" #include "components/cast_channel/logger.h" #include "components/net_log/chrome_net_log.h" @@ -413,6 +414,9 @@ SinkSource sink_source) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + if (!cast_channel::IsValidCastIPAddress(ip_endpoint.address())) + return; + // Erase the entry from |dial_sink_failure_count_| since the device is now // known to be a Cast device. if (sink_source != SinkSource::kDial)
diff --git a/chrome/browser/media/router/discovery/mdns/cast_media_sink_service_impl_unittest.cc b/chrome/browser/media/router/discovery/mdns/cast_media_sink_service_impl_unittest.cc index f878b97f..ab9928f3 100644 --- a/chrome/browser/media/router/discovery/mdns/cast_media_sink_service_impl_unittest.cc +++ b/chrome/browser/media/router/discovery/mdns/cast_media_sink_service_impl_unittest.cc
@@ -121,7 +121,6 @@ .WillOnce(Invoke( [socket](const auto& ip_endpoint, auto* net_log, auto open_cb) { std::move(open_cb).Run(socket); - return socket->id(); })); } @@ -346,7 +345,6 @@ .WillRepeatedly( Invoke([&](const auto& ip_endpoint1, auto* net_log, auto open_cb) { std::move(open_cb).Run(&socket); - return socket.id(); })); media_sink_service_impl_.OpenChannel( ip_endpoint, cast_sink, nullptr, @@ -484,7 +482,6 @@ .WillRepeatedly( Invoke([&](const auto& ip_endpoint, auto* net_log, auto open_cb) { std::move(open_cb).Run(&socket); - return socket.id(); })); media_sink_service_impl_.OnError( @@ -534,18 +531,14 @@ // Channel 1, 2 opened. EXPECT_CALL(*mock_cast_socket_service_, OpenSocketInternal(ip_endpoint1, _, _)) - .WillOnce(DoAll( - WithArgs<2>(Invoke( - [&](const base::Callback<void(cast_channel::CastSocket * socket)>& - callback) { std::move(callback).Run(&socket1); })), - Return(1))); + .WillOnce(WithArgs<2>(Invoke( + [&](const base::Callback<void(cast_channel::CastSocket * socket)>& + callback) { std::move(callback).Run(&socket1); }))); EXPECT_CALL(*mock_cast_socket_service_, OpenSocketInternal(ip_endpoint2, _, _)) - .WillOnce(DoAll( - WithArgs<2>(Invoke( - [&](const base::Callback<void(cast_channel::CastSocket * socket)>& - callback) { std::move(callback).Run(&socket2); })), - Return(2))); + .WillOnce(WithArgs<2>(Invoke( + [&](const base::Callback<void(cast_channel::CastSocket * socket)>& + callback) { std::move(callback).Run(&socket2); }))); // Invoke CastSocketService::OpenSocket on the IO thread. media_sink_service_impl_.OnDialSinkAdded(dial_sink1); @@ -570,12 +563,10 @@ EXPECT_CALL(*mock_cast_socket_service_, OpenSocketInternal(ip_endpoint1, _, _)) .Times(1) - .WillOnce(DoAll( - WithArgs<2>(Invoke( - [&socket1]( - const base::Callback<void(cast_channel::CastSocket * socket)>& - callback) { std::move(callback).Run(&socket1); })), - Return(1))); + .WillOnce(WithArgs<2>(Invoke( + [&socket1]( + const base::Callback<void(cast_channel::CastSocket * socket)>& + callback) { std::move(callback).Run(&socket1); }))); media_sink_service_impl_.OnDialSinkAdded(dial_sink1); // We don't trigger retries, thus each iteration will only increment the @@ -585,13 +576,10 @@ EXPECT_CALL(*mock_cast_socket_service_, OpenSocketInternal(ip_endpoint1, _, _)) .Times(1) - .WillOnce(DoAll( - WithArgs<2>(Invoke( - [&socket1](const base::Callback<void(cast_channel::CastSocket * - socket)>& callback) { - std::move(callback).Run(&socket1); - })), - Return(1))); + .WillOnce(WithArgs<2>(Invoke( + [&socket1]( + const base::Callback<void(cast_channel::CastSocket * socket)>& + callback) { std::move(callback).Run(&socket1); }))); media_sink_service_impl_.OnDialSinkAdded(dial_sink1); }
diff --git a/chrome/browser/media/router/discovery/mdns/dns_sd_registry.cc b/chrome/browser/media/router/discovery/mdns/dns_sd_registry.cc index 5cce6f5..e9bda239 100644 --- a/chrome/browser/media/router/discovery/mdns/dns_sd_registry.cc +++ b/chrome/browser/media/router/discovery/mdns/dns_sd_registry.cc
@@ -11,6 +11,7 @@ #include "chrome/browser/local_discovery/service_discovery_shared_client.h" #include "chrome/browser/media/router/discovery/mdns/dns_sd_device_lister.h" #include "chrome/common/features.h" +#include "components/cast_channel/cast_channel_util.h" using local_discovery::ServiceDiscoveryClient; using local_discovery::ServiceDiscoverySharedClient; @@ -194,7 +195,12 @@ VLOG(1) << "ServiceChanged: service_type: " << service_type << ", known: " << IsRegistered(service_type) << ", service: " << service.service_name << ", added: " << added; - if (!IsRegistered(service_type)) { + if (!IsRegistered(service_type)) + return; + + net::IPAddress ip_address; + if (!cast_channel::IsValidCastIPAddressString(service.ip_address)) { + VLOG(1) << "Invalid IP address: " << service.ip_address; return; } @@ -202,9 +208,8 @@ service_data_map_[service_type]->UpdateService(added, service); VLOG(1) << "ServiceChanged: is_updated: " << is_updated; - if (is_updated) { + if (is_updated) DispatchApiEvent(service_type); - } } void DnsSdRegistry::ServiceRemoved(const std::string& service_type, @@ -213,9 +218,8 @@ VLOG(1) << "ServiceRemoved: service_type: " << service_type << ", known: " << IsRegistered(service_type) << ", service: " << service_name; - if (!IsRegistered(service_type)) { + if (!IsRegistered(service_type)) return; - } bool is_removed = service_data_map_[service_type]->RemoveService(service_name); @@ -229,9 +233,8 @@ DCHECK(thread_checker_.CalledOnValidThread()); VLOG(1) << "ServicesFlushed: service_type: " << service_type << ", known: " << IsRegistered(service_type); - if (!IsRegistered(service_type)) { + if (!IsRegistered(service_type)) return; - } bool is_cleared = service_data_map_[service_type]->ClearServices(); VLOG(1) << "ServicesFlushed: is_cleared: " << is_cleared;
diff --git a/chrome/browser/media/router/discovery/mdns/dns_sd_registry_unittest.cc b/chrome/browser/media/router/discovery/mdns/dns_sd_registry_unittest.cc index c988f51e..12a65718 100644 --- a/chrome/browser/media/router/discovery/mdns/dns_sd_registry_unittest.cc +++ b/chrome/browser/media/router/discovery/mdns/dns_sd_registry_unittest.cc
@@ -8,6 +8,8 @@ #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" +using testing::_; + namespace media_router { class MockDnsSdDeviceLister : public DnsSdDeviceLister { @@ -152,6 +154,29 @@ registry_->GetDelegate()->ServiceChanged(service_type, false, service); } +TEST_F(DnsSdRegistryTest, AddServiceWithInvalidIPAddress) { + const std::string service_type = "_testing._tcp.local"; + const std::string ip_address1 = "invalid"; + + // |ip_address2| is not a private IP address and is therefore invalid. + const std::string ip_address2 = "111.111.111.111"; + + DnsSdService service; + service.service_name = "_myDevice." + service_type; + + DnsSdRegistry::DnsSdServiceList service_list; + + EXPECT_CALL(observer_, OnDnsSdEvent(_, _)).Times(1); + registry_->RegisterDnsSdListener(service_type); + EXPECT_TRUE(testing::Mock::VerifyAndClearExpectations(&observer_)); + + EXPECT_CALL(observer_, OnDnsSdEvent(_, _)).Times(0); + service.ip_address = ip_address1; + registry_->GetDelegate()->ServiceChanged(service_type, true, service); + service.ip_address = ip_address2; + registry_->GetDelegate()->ServiceChanged(service_type, false, service); +} + // Tests registering a listener and receiving an added and removed event. TEST_F(DnsSdRegistryTest, AddAndRemove) { const std::string service_type = "_testing._tcp.local"; @@ -184,8 +209,8 @@ service.ip_address = "192.168.0.100"; DnsSdService service2; - service.service_name = "_myDevice2." + service_type; - service.ip_address = "192.168.0.101"; + service2.service_name = "_myDevice2." + service_type; + service2.ip_address = "192.168.0.101"; DnsSdRegistry::DnsSdServiceList service_list; EXPECT_CALL(observer_, OnDnsSdEvent(service_type, service_list)); @@ -209,8 +234,8 @@ service.ip_address = "192.168.0.100"; DnsSdService service2; - service.service_name = "_myDevice2." + service_type; - service.ip_address = "192.168.0.101"; + service2.service_name = "_myDevice2." + service_type; + service2.ip_address = "192.168.0.101"; DnsSdRegistry::DnsSdServiceList service_list; EXPECT_CALL(observer_, OnDnsSdEvent(service_type, service_list));
diff --git a/chrome/browser/media/router/mojo/media_router_desktop.cc b/chrome/browser/media/router/mojo/media_router_desktop.cc index 84fb5ff..89e3dcf 100644 --- a/chrome/browser/media/router/mojo/media_router_desktop.cc +++ b/chrome/browser/media/router/mojo/media_router_desktop.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/media/router/mojo/media_router_desktop.h" +#include "base/strings/string_util.h" #include "chrome/browser/media/router/discovery/dial/dial_media_sink_service_proxy.h" #include "chrome/browser/media/router/discovery/mdns/cast_media_sink_service.h" #include "chrome/browser/media/router/media_router_factory.h" @@ -59,6 +60,19 @@ #endif } +base::Optional<mojom::MediaRouteProvider::Id> +MediaRouterDesktop::GetProviderIdForPresentation( + const std::string& presentation_id) { + // TODO(takumif): Once the Android Media Router also uses MediaRouterMojoImpl, + // we must support these presentation IDs in Android as well. + if (presentation_id == kAutoJoinPresentationId || + base::StartsWith(presentation_id, kCastPresentationIdPrefix, + base::CompareCase::SENSITIVE)) { + return mojom::MediaRouteProvider::Id::EXTENSION; + } + return MediaRouterMojoImpl::GetProviderIdForPresentation(presentation_id); +} + MediaRouterDesktop::MediaRouterDesktop(content::BrowserContext* context, FirewallCheck check_firewall) : MediaRouterMojoImpl(context),
diff --git a/chrome/browser/media/router/mojo/media_router_desktop.h b/chrome/browser/media/router/mojo/media_router_desktop.h index 3dcd1a38..091b29f9 100644 --- a/chrome/browser/media/router/mojo/media_router_desktop.h +++ b/chrome/browser/media/router/mojo/media_router_desktop.h
@@ -46,6 +46,11 @@ // MediaRouter implementation. void OnUserGesture() override; + protected: + // MediaRouterMojoImpl override: + base::Optional<mojom::MediaRouteProvider::Id> GetProviderIdForPresentation( + const std::string& presentation_id) override; + private: friend class MediaRouterDesktopTest; friend class MediaRouterDesktopTestTest;
diff --git a/chrome/browser/media/router/mojo/media_router_desktop_unittest.cc b/chrome/browser/media/router/mojo/media_router_desktop_unittest.cc index eabd49b..441be0ff 100644 --- a/chrome/browser/media/router/mojo/media_router_desktop_unittest.cc +++ b/chrome/browser/media/router/mojo/media_router_desktop_unittest.cc
@@ -146,4 +146,11 @@ base::RunLoop().RunUntilIdle(); } +// Tests that auto-join and Cast SDK join requests are routed to the extension +// MediaRouteProvider. +TEST_F(MediaRouterDesktopTest, SendCastJoinRequestsToExtension) { + TestJoinRoute(kAutoJoinPresentationId); + TestJoinRoute(kCastPresentationIdPrefix + std::string("123")); +} + } // namespace media_router
diff --git a/chrome/browser/media/router/mojo/media_router_mojo_impl.h b/chrome/browser/media/router/mojo/media_router_mojo_impl.h index 7469bcc..2affdcc 100644 --- a/chrome/browser/media/router/mojo/media_router_mojo_impl.h +++ b/chrome/browser/media/router/mojo/media_router_mojo_impl.h
@@ -121,6 +121,11 @@ // Creates a binding between |this| and |request|. void BindToMojoRequest(mojo::InterfaceRequest<mojom::MediaRouter> request); + // Returns the ID of the provider associated with the presentation ID, or + // nullopt if not found. + virtual base::Optional<mojom::MediaRouteProvider::Id> + GetProviderIdForPresentation(const std::string& presentation_id); + content::BrowserContext* context() const { return context_; } // Mojo pointers to media route providers. Providers are added via @@ -386,16 +391,12 @@ // routes do not appear in |routes|. void RemoveInvalidRouteControllers(const std::vector<MediaRoute>& routes); - // Methods for obtaining a pointer to the provider associated with the given - // object. They return a nullptr when such a provider is not found. The - // returned pointer should not be stored or passed to another object, as the - // Mojo connection may be terminated at any later time. + // Methods for obtaining the ID of the provider associated with the given + // object. They return a nullopt when such a provider is not found. base::Optional<mojom::MediaRouteProvider::Id> GetProviderIdForRoute( const MediaRoute::Id& route_id); base::Optional<mojom::MediaRouteProvider::Id> GetProviderIdForSink( const MediaSink::Id& sink_id); - base::Optional<mojom::MediaRouteProvider::Id> GetProviderIdForPresentation( - const std::string& presentation_id); base::flat_map<MediaSource::Id, std::unique_ptr<MediaSinksQuery>> sinks_queries_;
diff --git a/chrome/browser/media/router/mojo/media_router_mojo_impl_unittest.cc b/chrome/browser/media/router/mojo/media_router_mojo_impl_unittest.cc index 00f0eae..0078497 100644 --- a/chrome/browser/media/router/mojo/media_router_mojo_impl_unittest.cc +++ b/chrome/browser/media/router/mojo/media_router_mojo_impl_unittest.cc
@@ -325,7 +325,7 @@ } TEST_F(MediaRouterMojoImplTest, JoinRoute) { - TestJoinRoute(); + TestJoinRoute(kPresentationId); ExpectResultBucketCount("JoinRoute", RouteRequestResult::OK, 1); }
diff --git a/chrome/browser/media/router/mojo/media_router_mojo_test.cc b/chrome/browser/media/router/mojo/media_router_mojo_test.cc index 15dd2da..9427902 100644 --- a/chrome/browser/media/router/mojo/media_router_mojo_test.cc +++ b/chrome/browser/media/router/mojo/media_router_mojo_test.cc
@@ -258,7 +258,7 @@ base::RunLoop().RunUntilIdle(); } -void MediaRouterMojoTest::TestJoinRoute() { +void MediaRouterMojoTest::TestJoinRoute(const std::string& presentation_id) { MediaSource media_source(kSource); MediaRoute expected_route(kRouteId, media_source, kSinkId, "", false, "", false); @@ -277,7 +277,7 @@ // in runnable parameter lists. EXPECT_CALL(mock_extension_provider_, JoinRouteInternal( - kSource, kPresentationId, url::Origin::Create(GURL(kOrigin)), + kSource, presentation_id, url::Origin::Create(GURL(kOrigin)), kInvalidTabId, base::TimeDelta::FromMilliseconds(kTimeoutMillis), _, _)) .WillOnce( @@ -295,7 +295,7 @@ std::vector<MediaRouteResponseCallback> route_response_callbacks; route_response_callbacks.push_back(base::BindOnce( &RouteResponseCallbackHandler::Invoke, base::Unretained(&handler))); - router()->JoinRoute(kSource, kPresentationId, + router()->JoinRoute(kSource, presentation_id, url::Origin::Create(GURL(kOrigin)), nullptr, std::move(route_response_callbacks), base::TimeDelta::FromMilliseconds(kTimeoutMillis), false);
diff --git a/chrome/browser/media/router/mojo/media_router_mojo_test.h b/chrome/browser/media/router/mojo/media_router_mojo_test.h index c1c6ed5..7904d80 100644 --- a/chrome/browser/media/router/mojo/media_router_mojo_test.h +++ b/chrome/browser/media/router/mojo/media_router_mojo_test.h
@@ -296,7 +296,7 @@ // Tests that calling MediaRouter methods result in calls to corresponding // MediaRouteProvider methods. void TestCreateRoute(); - void TestJoinRoute(); + void TestJoinRoute(const std::string& presentation_id); void TestConnectRouteByRouteId(); void TestTerminateRoute(); void TestSendRouteMessage();
diff --git a/chrome/browser/media/webrtc/media_stream_capture_indicator.cc b/chrome/browser/media/webrtc/media_stream_capture_indicator.cc index bebf5ea..4b723cbe 100644 --- a/chrome/browser/media/webrtc/media_stream_capture_indicator.cc +++ b/chrome/browser/media/webrtc/media_stream_capture_indicator.cc
@@ -61,20 +61,6 @@ web_contents->GetURL()); } -bool IsWhitelistedExtension(const extensions::Extension* extension) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - static const char* const kExtensionWhitelist[] = { - extension_misc::kHotwordNewExtensionId, - }; - - for (size_t i = 0; i < arraysize(kExtensionWhitelist); ++i) { - if (extension->id() == kExtensionWhitelist[i]) - return true; - } - - return false; -} #endif // BUILDFLAG(ENABLE_EXTENSIONS) base::string16 GetTitle(WebContents* web_contents) { @@ -392,7 +378,7 @@ // icon. #if BUILDFLAG(ENABLE_EXTENSIONS) const extensions::Extension* extension = GetExtension(web_contents); - if (!extension || IsWhitelistedExtension(extension)) + if (!extension) continue; #endif
diff --git a/chrome/browser/metrics/browser_window_histogram_helper.cc b/chrome/browser/metrics/browser_window_histogram_helper.cc index ff6fb56e..86e17c3 100644 --- a/chrome/browser/metrics/browser_window_histogram_helper.cc +++ b/chrome/browser/metrics/browser_window_histogram_helper.cc
@@ -15,7 +15,7 @@ ui::Compositor* compositor) { static bool did_first_paint = false; if (did_first_paint) - return std::unique_ptr<BrowserWindowHistogramHelper>(); + return nullptr; did_first_paint = true;
diff --git a/chrome/browser/metrics/chrome_metrics_service_client.h b/chrome/browser/metrics/chrome_metrics_service_client.h index 4fcb92e4..1fff193b3 100644 --- a/chrome/browser/metrics/chrome_metrics_service_client.h +++ b/chrome/browser/metrics/chrome_metrics_service_client.h
@@ -161,7 +161,7 @@ SEQUENCE_CHECKER(sequence_checker_); // Weak pointer to the MetricsStateManager. - metrics::MetricsStateManager* metrics_state_manager_; + metrics::MetricsStateManager* const metrics_state_manager_; // The MetricsService that |this| is a client of. std::unique_ptr<metrics::MetricsService> metrics_service_;
diff --git a/chrome/browser/metrics/chrome_metrics_services_manager_client.h b/chrome/browser/metrics/chrome_metrics_services_manager_client.h index 5eb0071..9101d19 100644 --- a/chrome/browser/metrics/chrome_metrics_services_manager_client.h +++ b/chrome/browser/metrics/chrome_metrics_services_manager_client.h
@@ -103,7 +103,7 @@ base::ThreadChecker thread_checker_; // Weak pointer to the local state prefs store. - PrefService* local_state_; + PrefService* const local_state_; #if defined(OS_CHROMEOS) std::unique_ptr<chromeos::CrosSettings::ObserverSubscription>
diff --git a/chrome/browser/net/net_error_tab_helper.cc b/chrome/browser/net/net_error_tab_helper.cc index a35b413d..ffd3258 100644 --- a/chrome/browser/net/net_error_tab_helper.cc +++ b/chrome/browser/net/net_error_tab_helper.cc
@@ -20,9 +20,9 @@ #include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" -#include "content/public/common/associated_interface_provider.h" #include "ipc/ipc_message_macros.h" #include "net/base/net_errors.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" #include "url/gurl.h" #if BUILDFLAG(ENABLE_OFFLINE_PAGES)
diff --git a/chrome/browser/notifications/notification_platform_bridge_android.cc b/chrome/browser/notifications/notification_platform_bridge_android.cc index 4bdabc6..c3d72a9 100644 --- a/chrome/browser/notifications/notification_platform_bridge_android.cc +++ b/chrome/browser/notifications/notification_platform_bridge_android.cc
@@ -44,6 +44,10 @@ namespace { +// Value used to represent the absence of a button index following a user +// interaction with a notification. +constexpr int kNotificationInvalidButtonIndex = -1; + // A Java counterpart will be generated for this enum. // GENERATED_JAVA_ENUM_PACKAGE: org.chromium.chrome.browser.notifications enum NotificationActionType { @@ -167,7 +171,7 @@ jboolean incognito, const JavaParamRef<jstring>& java_tag, const JavaParamRef<jstring>& java_webapk_package, - jint action_index, + jint java_action_index, const JavaParamRef<jstring>& java_reply) { std::string notification_id = ConvertJavaStringToUTF8(env, java_notification_id); @@ -185,6 +189,10 @@ regenerated_notification_infos_[notification_id] = RegeneratedNotificationInfo(origin, scope_url, tag, webapk_package); + base::Optional<int> action_index; + if (java_action_index != kNotificationInvalidButtonIndex) + action_index = java_action_index; + ProfileManager* profile_manager = g_browser_process->profile_manager(); DCHECK(profile_manager); @@ -192,7 +200,7 @@ profile_id, incognito, base::Bind(&ProfileLoadedCallback, NotificationCommon::CLICK, NotificationHandler::Type::WEB_PERSISTENT, origin, - notification_id, action_index, std::move(reply), + notification_id, std::move(action_index), std::move(reply), base::nullopt /* by_user */)); }
diff --git a/chrome/browser/notifications/notification_test_util.h b/chrome/browser/notifications/notification_test_util.h index 811feec2..5d2531a 100644 --- a/chrome/browser/notifications/notification_test_util.h +++ b/chrome/browser/notifications/notification_test_util.h
@@ -79,7 +79,7 @@ void Wait(); private: - Browser* browser_; + Browser* const browser_; bool desired_state_; DISALLOW_COPY_AND_ASSIGN(FullscreenStateWaiter);
diff --git a/chrome/browser/ntp_snippets/download_suggestions_provider.cc b/chrome/browser/ntp_snippets/download_suggestions_provider.cc index 3537bdb..1779f03 100644 --- a/chrome/browser/ntp_snippets/download_suggestions_provider.cc +++ b/chrome/browser/ntp_snippets/download_suggestions_provider.cc
@@ -265,8 +265,7 @@ ClearDismissedSuggestionsForDebugging(provided_category_); } -void DownloadSuggestionsProvider::ClearCachedSuggestions(Category category) { - DCHECK_EQ(provided_category_, category); +void DownloadSuggestionsProvider::ClearCachedSuggestions() { // Ignored. The internal caches are not stored on disk and they are just // partial copies of the data stored at OfflinePage model and DownloadManager. // If it is cleared there, it will be cleared in these caches as well.
diff --git a/chrome/browser/ntp_snippets/download_suggestions_provider.h b/chrome/browser/ntp_snippets/download_suggestions_provider.h index f0bd6d56..7696b39 100644 --- a/chrome/browser/ntp_snippets/download_suggestions_provider.h +++ b/chrome/browser/ntp_snippets/download_suggestions_provider.h
@@ -71,7 +71,7 @@ base::Time begin, base::Time end, const base::Callback<bool(const GURL& url)>& filter) override; - void ClearCachedSuggestions(ntp_snippets::Category category) override; + void ClearCachedSuggestions() override; void GetDismissedSuggestionsForDebugging( ntp_snippets::Category category, ntp_snippets::DismissedSuggestionsCallback callback) override;
diff --git a/chrome/browser/password_manager/credential_manager_browsertest.cc b/chrome/browser/password_manager/credential_manager_browsertest.cc index f754b80..f04d6bb9 100644 --- a/chrome/browser/password_manager/credential_manager_browsertest.cc +++ b/chrome/browser/password_manager/credential_manager_browsertest.cc
@@ -89,11 +89,11 @@ " challenge: new TextEncoder().encode('climb a mountain')," " rp: { id: '1098237235409872', name: 'Acme' }," " user: { " - " id: '1098237235409872'," + " id: new TextEncoder().encode('1098237235409872')," " name: 'avery.a.jones@example.com'," " displayName: 'Avery A. Jones', " " icon: 'https://pics.acme.com/00/p/aBjjjpqPb.png'}," - " parameters: [{ type: 'public-key', algorithm: '123'}]," + " pubKeyCredParams: [{ type: 'public-key', alg: '123'}]," " timeout: 60000," " excludeList: [] }" "}).catch(c => window.domAutomationController.send(c.toString()));";
diff --git a/chrome/browser/plugins/chrome_content_browser_client_plugins_part.cc b/chrome/browser/plugins/chrome_content_browser_client_plugins_part.cc index dc2520f..1963a0a 100644 --- a/chrome/browser/plugins/chrome_content_browser_client_plugins_part.cc +++ b/chrome/browser/plugins/chrome_content_browser_client_plugins_part.cc
@@ -13,11 +13,11 @@ #include "chrome/common/pepper_permission_util.h" #include "components/version_info/version_info.h" #include "content/public/browser/render_process_host.h" -#include "content/public/common/associated_interface_registry.h" #include "extensions/features/features.h" #include "ppapi/host/ppapi_host.h" #include "ppapi/shared_impl/ppapi_switches.h" #include "services/service_manager/public/cpp/binder_registry.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_registry.h" #if BUILDFLAG(ENABLE_EXTENSIONS) #include "chrome/browser/extensions/extension_service.h" @@ -38,7 +38,7 @@ void ChromeContentBrowserClientPluginsPart::ExposeInterfacesToRenderer( service_manager::BinderRegistry* registry, - content::AssociatedInterfaceRegistry* associated_registry, + blink::AssociatedInterfaceRegistry* associated_registry, content::RenderProcessHost* host) { Profile* profile = Profile::FromBrowserContext(host->GetBrowserContext()); host->GetChannel()->AddAssociatedInterfaceForIOThread(base::Bind(
diff --git a/chrome/browser/plugins/chrome_content_browser_client_plugins_part.h b/chrome/browser/plugins/chrome_content_browser_client_plugins_part.h index f3b0b63..7c07649 100644 --- a/chrome/browser/plugins/chrome_content_browser_client_plugins_part.h +++ b/chrome/browser/plugins/chrome_content_browser_client_plugins_part.h
@@ -46,7 +46,7 @@ private: void ExposeInterfacesToRenderer( service_manager::BinderRegistry* registry, - content::AssociatedInterfaceRegistry* associated_registry, + blink::AssociatedInterfaceRegistry* associated_registry, content::RenderProcessHost* render_process_host) override; DISALLOW_COPY_AND_ASSIGN(ChromeContentBrowserClientPluginsPart);
diff --git a/chrome/browser/prefs/tracked/pref_hash_browsertest.cc b/chrome/browser/prefs/tracked/pref_hash_browsertest.cc index f080d974..0a9172f 100644 --- a/chrome/browser/prefs/tracked/pref_hash_browsertest.cc +++ b/chrome/browser/prefs/tracked/pref_hash_browsertest.cc
@@ -35,6 +35,7 @@ #include "chrome/test/base/testing_profile.h" #include "components/search_engines/default_search_manager.h" #include "components/search_engines/template_url_data.h" +#include "content/public/test/test_launcher.h" #include "extensions/browser/pref_names.h" #include "extensions/common/extension.h" #include "services/preferences/public/cpp/tracked/tracked_preference_histogram_names.h" @@ -218,7 +219,7 @@ bool SetUpUserDataDirectory() override { // Do the normal setup in the PRE test and attack preferences in the main // test. - if (IsPRETest()) + if (content::IsPreTest()) return ExtensionBrowserTest::SetUpUserDataDirectory(); #if defined(OS_CHROMEOS) @@ -299,7 +300,7 @@ // Keys should be unique, but to avoid flakes in the long run make sure an // identical test key wasn't left behind by a previous test. - if (IsPRETest()) { + if (content::IsPreTest()) { base::win::RegKey key; if (key.Open(HKEY_CURRENT_USER, registry_key_for_external_validation_.c_str(), @@ -314,7 +315,7 @@ void TearDown() override { #if defined(OS_WIN) // When done, delete the Registry key to avoid polluting the registry. - if (!IsPRETest()) { + if (!content::IsPreTest()) { base::string16 registry_key = GetRegistryPathForTestProfile(); base::win::RegKey key; if (key.Open(HKEY_CURRENT_USER, registry_key.c_str(), @@ -343,7 +344,7 @@ num_tracked_prefs_file = num_tracked_prefs_file.AppendASCII(kNumTrackedPrefFilename); - if (IsPRETest()) { + if (content::IsPreTest()) { num_tracked_prefs_ = GetTrackedPrefHistogramCount( user_prefs::tracked::kTrackedPrefHistogramNullInitialized, ALLOW_ANY); EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM, @@ -416,13 +417,6 @@ const SettingsProtectionLevel protection_level_; private: - // Returns true if this is the PRE_ phase of the test. - bool IsPRETest() { - return base::StartsWith( - testing::UnitTest::GetInstance()->current_test_info()->name(), "PRE_", - base::CompareCase::SENSITIVE); - } - SettingsProtectionLevel GetProtectionLevelFromTrialGroup( const std::string& trial_group) { if (!ProfilePrefStoreManager::kPlatformSupportsPreferenceTracking) @@ -438,27 +432,24 @@ return PROTECTION_ENABLED_ALL; #else return PROTECTION_DISABLED_FOR_GROUP; -#endif +#endif // defined(OS_WIN) || defined(OS_MACOSX) #else // defined(OFFICIAL_BUILD) using namespace chrome_prefs::internals; - if (trial_group == kSettingsEnforcementGroupNoEnforcement) { + if (trial_group == kSettingsEnforcementGroupNoEnforcement) return PROTECTION_DISABLED_FOR_GROUP; - } else if (trial_group == kSettingsEnforcementGroupEnforceAlways) { + if (trial_group == kSettingsEnforcementGroupEnforceAlways) return PROTECTION_ENABLED_BASIC; - } else if (trial_group == kSettingsEnforcementGroupEnforceAlwaysWithDSE) { + if (trial_group == kSettingsEnforcementGroupEnforceAlwaysWithDSE) return PROTECTION_ENABLED_DSE; - } else if (trial_group == - kSettingsEnforcementGroupEnforceAlwaysWithExtensionsAndDSE) { + if (trial_group == + kSettingsEnforcementGroupEnforceAlwaysWithExtensionsAndDSE) { return PROTECTION_ENABLED_EXTENSIONS; - } else { - ADD_FAILURE(); - return static_cast<SettingsProtectionLevel>(-1); } - + ADD_FAILURE(); + return static_cast<SettingsProtectionLevel>(-1); #endif // defined(OFFICIAL_BUILD) - } int num_tracked_prefs_;
diff --git a/chrome/browser/previews/previews_browsertest.cc b/chrome/browser/previews/previews_browsertest.cc index 3ca2310..7cc89f8e 100644 --- a/chrome/browser/previews/previews_browsertest.cc +++ b/chrome/browser/previews/previews_browsertest.cc
@@ -127,7 +127,12 @@ #define MAYBE_NoScriptPreviewsEnabledHttpRedirectToHttps \ DISABLED_NoScriptPreviewsEnabledHttpRedirectToHttps #else +// Flaky on win7_chromium_rel_ng. crbug.com/789542 +#if defined(OS_WIN) +#define MAYBE_NoScriptPreviewsEnabled DISABLED_NoScriptPreviewsEnabled +#else #define MAYBE_NoScriptPreviewsEnabled NoScriptPreviewsEnabled +#endif #define MAYBE_NoScriptPreviewsEnabledHttpRedirectToHttps \ NoScriptPreviewsEnabledHttpRedirectToHttps #endif
diff --git a/chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc b/chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc index f78f58b..0e49fc2 100644 --- a/chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc +++ b/chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc
@@ -91,7 +91,6 @@ #include "chrome/browser/extensions/api/networking_private/networking_private_ui_delegate_factory_impl.h" #include "chrome/browser/extensions/browser_context_keyed_service_factories.h" #include "chrome/browser/extensions/extension_management.h" -#include "chrome/browser/search/hotword_service_factory.h" #include "chrome/browser/signin/easy_unlock_service_factory.h" #include "chrome/browser/ui/bookmarks/enhanced_bookmark_key_service_factory.h" #include "extensions/browser/api/networking_private/networking_private_delegate_factory.h" @@ -255,9 +254,6 @@ #endif GoogleURLTrackerFactory::GetInstance(); HistoryServiceFactory::GetInstance(); -#if BUILDFLAG(ENABLE_EXTENSIONS) - HotwordServiceFactory::GetInstance(); -#endif HostContentSettingsMapFactory::GetInstance(); InMemoryURLIndexFactory::GetInstance(); invalidation::ProfileInvalidationProviderFactory::GetInstance();
diff --git a/chrome/browser/profiles/profile_manager_unittest.cc b/chrome/browser/profiles/profile_manager_unittest.cc index e1bb5d0..972f8c0 100644 --- a/chrome/browser/profiles/profile_manager_unittest.cc +++ b/chrome/browser/profiles/profile_manager_unittest.cc
@@ -356,7 +356,14 @@ #endif -TEST_F(ProfileManagerTest, CreateAndUseTwoProfiles) { +// Data race on Linux bots. http://crbug.com/789214 +#if defined(OS_LINUX) +#define MAYBE_CreateAndUseTwoProfiles DISABLED_CreateAndUseTwoProfiles +#else +#define MAYBE_CreateAndUseTwoProfiles CreateAndUseTwoProfiles +#endif + +TEST_F(ProfileManagerTest, MAYBE_CreateAndUseTwoProfiles) { base::FilePath dest_path1 = temp_dir_.GetPath(); dest_path1 = dest_path1.Append(FILE_PATH_LITERAL("New Profile 1"));
diff --git a/chrome/browser/profiling_host/profiling_process_host.cc b/chrome/browser/profiling_host/profiling_process_host.cc index bfda42d0..03dea13 100644 --- a/chrome/browser/profiling_host/profiling_process_host.cc +++ b/chrome/browser/profiling_host/profiling_process_host.cc
@@ -319,6 +319,14 @@ kTraceEventArgTypes, nullptr /* arg_values */, &wrapper, TRACE_EVENT_FLAG_HAS_ID); } + + content::BrowserThread::GetTaskRunnerForThread(content::BrowserThread::UI) + ->PostTask(FROM_HERE, + base::Bind(&ProfilingProcessHost::DumpProcessFinishedUIThread, + base::Unretained(this))); +} + +void ProfilingProcessHost::DumpProcessFinishedUIThread() { if (dump_process_for_tracing_callback_) { std::move(dump_process_for_tracing_callback_).Run(); dump_process_for_tracing_callback_.Reset(); @@ -457,25 +465,52 @@ return; } + auto finish_report_callback = base::BindOnce( + [](std::string trigger_name, bool success, std::string trace) { + if (success) { + UploadTraceToCrashServer(std::move(trace), std::move(trigger_name)); + } + }, + std::move(trigger_name)); + RequestTraceWithHeapDump(std::move(finish_report_callback), false); +} + +void ProfilingProcessHost::RequestTraceWithHeapDump( + TraceFinishedCallback callback, + bool stop_immediately_after_heap_dump_for_tests) { + DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); + + if (!connector_) { + DLOG(ERROR) + << "Requesting heap dump when profiling process hasn't started."; + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::BindOnce(std::move(callback), false, std::string())); + return; + } + bool result = content::TracingController::GetInstance()->StartTracing( GetBackgroundTracingConfig(), base::Closure()); - if (!result) + if (!result) { + DLOG(ERROR) << "Requesting heap dump when tracing has already started."; + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::BindOnce(std::move(callback), false, std::string())); return; + } - // Once the trace has stopped, upload the log to the crash server. + // Once the trace has stopped, run |callback| on the UI thread. At this point, + // ownership of |callback| has been transfered to |finish_sink_callback|. auto finish_sink_callback = base::Bind( - [](std::string trigger_name, + [](TraceFinishedCallback callback, std::unique_ptr<const base::DictionaryValue> metadata, base::RefCountedString* in) { std::string result; result.swap(in->data()); content::BrowserThread::GetTaskRunnerForThread( content::BrowserThread::UI) - ->PostTask(FROM_HERE, base::BindOnce(&UploadTraceToCrashServer, - std::move(result), - std::move(trigger_name))); + ->PostTask(FROM_HERE, base::BindOnce(std::move(callback), true, + std::move(result))); }, - std::move(trigger_name)); + base::Passed(std::move(callback))); scoped_refptr<content::TracingController::TraceDataEndpoint> sink = content::TracingController::CreateStringEndpoint( @@ -486,16 +521,18 @@ &content::TracingController::StopTracing), base::Unretained(content::TracingController::GetInstance()), sink); - // Wait 10 seconds, then end the trace. - base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, std::move(stop_tracing_closure), - base::TimeDelta::FromSeconds(10)); -} - -void ProfilingProcessHost::SetDumpProcessForTracingCallback( - base::OnceClosure callback) { - DCHECK(!dump_process_for_tracing_callback_); - dump_process_for_tracing_callback_ = std::move(callback); + if (stop_immediately_after_heap_dump_for_tests) { + // There is no race condition between setting + // |dump_process_for_tracing_callback_| and starting tracing, since running + // the callback is an asynchronous task executed on the UI thread. + DCHECK(!dump_process_for_tracing_callback_); + dump_process_for_tracing_callback_ = std::move(stop_tracing_closure); + } else { + // Wait 10 seconds, then end the trace. + base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( + FROM_HERE, std::move(stop_tracing_closure), + base::TimeDelta::FromSeconds(10)); + } } void ProfilingProcessHost::MakeConnector(
diff --git a/chrome/browser/profiling_host/profiling_process_host.h b/chrome/browser/profiling_host/profiling_process_host.h index 94cc7a9..7cc92d4 100644 --- a/chrome/browser/profiling_host/profiling_process_host.h +++ b/chrome/browser/profiling_host/profiling_process_host.h
@@ -115,10 +115,22 @@ // memory data to the crash server (slow-report). void RequestProcessReport(std::string trigger_name); - // For testing. Only one can be set at a time. Will be called after the - // profiling process dumps heaps into the trace log. No guarantees are made - // about the task queue on which the callback will be Run. - void SetDumpProcessForTracingCallback(base::OnceClosure callback); + using TraceFinishedCallback = + base::OnceCallback<void(bool success, std::string trace_json)>; + + // This method must be called from the UI thread. |callback| will be called + // asynchronously on the UI thread. If + // |stop_immediately_after_heap_dump_for_tests| is true, then |callback| will + // be called as soon as the heap dump is added to the trace. Otherwise, + // |callback| will be called after 10s. This gives time for the + // MemoryDumpProviders to dump to the trace, which is asynchronous and has no + // finish notification. This intentionally avoids waiting for the heap-dump + // finished signal, in case there's a problem with the profiling process and + // the heap-dump is never added to the trace. + // Public for testing. + void RequestTraceWithHeapDump( + TraceFinishedCallback callback, + bool stop_immediately_after_heap_dump_for_tests); private: friend struct base::DefaultSingletonTraits<ProfilingProcessHost>; @@ -161,6 +173,9 @@ // Starts the profiling process. void LaunchAsService(); + // Called on the UI thread after the heap dump has been added to the trace. + void DumpProcessFinishedUIThread(); + // Sends the end of the data pipe to the profiling service. void AddClientToProfilingService(profiling::mojom::ProfilingClientPtr client, base::ProcessId pid, @@ -235,7 +250,8 @@ // a renderer process if one is already not going. bool always_sample_for_tests_; - // For tests. + // Only used for testing. Must only ever be used from the UI thread. Will be + // called after the profiling process dumps heaps into the trace log. base::OnceClosure dump_process_for_tracing_callback_; DISALLOW_COPY_AND_ASSIGN(ProfilingProcessHost);
diff --git a/chrome/browser/profiling_host/profiling_test_driver.cc b/chrome/browser/profiling_host/profiling_test_driver.cc index ccfa8e5..b444ec2 100644 --- a/chrome/browser/profiling_host/profiling_test_driver.cc +++ b/chrome/browser/profiling_host/profiling_test_driver.cc
@@ -253,7 +253,7 @@ } std::unique_ptr<base::Value> dump_json = - base::JSONReader::Read(serialized_trace_->data()); + base::JSONReader::Read(serialized_trace_); if (!dump_json) { LOG(ERROR) << "Failed to deserialize trace."; return false; @@ -352,44 +352,22 @@ base::Unretained(&wait_for_ui_thread_)); } - // Once the ProfilingProcessHost has dumped to the trace, stop the trace and - // collate the results into |result|, then quit the nested run loop. - auto finish_sink_callback = base::Bind( - [](scoped_refptr<base::RefCountedString>* result, base::Closure finished, - std::unique_ptr<const base::DictionaryValue> metadata, - base::RefCountedString* in) { - *result = in; - std::move(finished).Run(); - }, - &serialized_trace_, std::move(finish_tracing_closure)); - - scoped_refptr<content::TracingController::TraceDataEndpoint> sink = - content::TracingController::CreateStringEndpoint( - std::move(finish_sink_callback)); - base::OnceClosure stop_tracing_closure = base::BindOnce( - base::IgnoreResult<bool (content::TracingController::*)( // NOLINT - const scoped_refptr<content::TracingController::TraceDataEndpoint>&)>( - &content::TracingController::StopTracing), - base::Unretained(content::TracingController::GetInstance()), sink); - base::OnceClosure stop_tracing_ui_thread_closure = - base::BindOnce(base::IgnoreResult(&base::TaskRunner::PostTask), - base::ThreadTaskRunnerHandle::Get(), FROM_HERE, - std::move(stop_tracing_closure)); - profiling::ProfilingProcessHost::GetInstance() - ->SetDumpProcessForTracingCallback( - std::move(stop_tracing_ui_thread_closure)); - - // Spin a nested RunLoop until the heap dump has been added to the trace. - content::TracingController::GetInstance()->StartTracing( - base::trace_event::TraceConfig( - base::trace_event::TraceConfigMemoryTestUtil:: - GetTraceConfig_PeriodicTriggers(100000, 100000)), - base::Closure()); + profiling::ProfilingProcessHost::GetInstance()->RequestTraceWithHeapDump( + base::Bind(&ProfilingTestDriver::TraceFinished, base::Unretained(this), + std::move(finish_tracing_closure)), + true); if (synchronous) run_loop->Run(); } +void ProfilingTestDriver::TraceFinished(base::Closure closure, + bool success, + std::string trace_json) { + serialized_trace_.swap(trace_json); + std::move(closure).Run(); +} + bool ProfilingTestDriver::ValidateBrowserAllocations(base::Value* dump_json) { base::Value* heaps_v2 = FindHeapsV2(base::Process::Current().Pid(), dump_json);
diff --git a/chrome/browser/profiling_host/profiling_test_driver.h b/chrome/browser/profiling_host/profiling_test_driver.h index 3820e2a..6aaa8ed 100644 --- a/chrome/browser/profiling_host/profiling_test_driver.h +++ b/chrome/browser/profiling_host/profiling_test_driver.h
@@ -84,6 +84,10 @@ // signal |wait_for_ui_thread_|. void CollectResults(bool synchronous); + void TraceFinished(base::Closure closure, + bool success, + std::string trace_json); + bool ValidateBrowserAllocations(base::Value* dump_json); bool ValidateRendererAllocations(base::Value* dump_json); @@ -100,7 +104,7 @@ base::PartitionAllocatorGeneric partition_allocator_; // Contains nothing until |CollectResults| has been called. - scoped_refptr<base::RefCountedString> serialized_trace_; + std::string serialized_trace_; // Whether the test was invoked on the ui thread. bool running_on_ui_thread_ = true;
diff --git a/chrome/browser/renderer_context_menu/render_view_context_menu.cc b/chrome/browser/renderer_context_menu/render_view_context_menu.cc index f6f780d..179cded 100644 --- a/chrome/browser/renderer_context_menu/render_view_context_menu.cc +++ b/chrome/browser/renderer_context_menu/render_view_context_menu.cc
@@ -113,7 +113,6 @@ #include "content/public/browser/ssl_status.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" -#include "content/public/common/associated_interface_provider.h" #include "content/public/common/menu_item.h" #include "content/public/common/url_utils.h" #include "extensions/features/features.h" @@ -122,6 +121,7 @@ #include "ppapi/features/features.h" #include "printing/features/features.h" #include "services/service_manager/public/cpp/interface_provider.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" #include "third_party/WebKit/public/public_features.h" #include "third_party/WebKit/public/web/WebContextMenuData.h" #include "third_party/WebKit/public/web/WebMediaPlayerAction.h"
diff --git a/chrome/browser/renderer_context_menu/render_view_context_menu_browsertest.cc b/chrome/browser/renderer_context_menu/render_view_context_menu_browsertest.cc index a29abc3..71b26e97 100644 --- a/chrome/browser/renderer_context_menu/render_view_context_menu_browsertest.cc +++ b/chrome/browser/renderer_context_menu/render_view_context_menu_browsertest.cc
@@ -60,7 +60,6 @@ #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/web_contents.h" -#include "content/public/common/associated_interface_provider.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/test_utils.h" #include "extensions/browser/api/extensions_api_client.h" @@ -74,6 +73,7 @@ #include "net/url_request/url_request_filter.h" #include "net/url_request/url_request_interceptor.h" #include "services/service_manager/public/cpp/interface_provider.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" #include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/WebKit/public/web/WebContextMenuData.h" #include "ui/base/models/menu_model.h"
diff --git a/chrome/browser/resource_coordinator/tab_manager_unittest.cc b/chrome/browser/resource_coordinator/tab_manager_unittest.cc index f2753e19..ef93a0e 100644 --- a/chrome/browser/resource_coordinator/tab_manager_unittest.cc +++ b/chrome/browser/resource_coordinator/tab_manager_unittest.cc
@@ -666,11 +666,18 @@ tab_strip2.CloseAllTabs(); } +// Data race on Linux. http://crbug.com/787842 +#if defined(OS_LINUX) +#define MAYBE_DiscardTabWithNonVisibleTabs DISABLED_DiscardTabWithNonVisibleTabs +#else +#define MAYBE_DiscardTabWithNonVisibleTabs DiscardTabWithNonVisibleTabs +#endif + // Verify that: // - On ChromeOS, DiscardTab can discard every tab in a non-visible window, but // cannot discard the active tab in a visible window. // - On other platforms, DiscardTab can discard every non-active tab. -TEST_F(TabManagerTest, DiscardTabWithNonVisibleTabs) { +TEST_F(TabManagerTest, MAYBE_DiscardTabWithNonVisibleTabs) { TabManager tab_manager; TabStripDummyDelegate delegate;
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/automation_predicate.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/automation_predicate.js index a5d98d9..d4c81554 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/automation_predicate.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/automation_predicate.js
@@ -265,8 +265,8 @@ AutomationPredicate.container = function(node) { return AutomationPredicate.match({ anyRole: [ - Role.GENERIC_CONTAINER, Role.DOCUMENT, Role.GROUP, Role.LIST_ITEM, - Role.TOOLBAR, Role.WINDOW + Role.GENERIC_CONTAINER, Role.DOCUMENT, Role.GROUP, Role.LIST, + Role.LIST_ITEM, Role.TOOLBAR, Role.WINDOW ], anyPredicate: [ AutomationPredicate.landmark, AutomationPredicate.structuralContainer,
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/output.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/output.js index 355433e26..cf4ccc6 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/output.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/output.js
@@ -435,8 +435,8 @@ @describe_switch_off($name)) $description $state $restriction` }, tab: { - speak: `@describe_tab($name) $state $restriction $description - $if($setSize, @describe_index($posInSet, $setSize))`, + speak: `@describe_tab($name) $description + @describe_index($posInSet, $setSize) $state $restriction `, }, table: { enter: `@table_summary($name,
diff --git a/chrome/browser/resources/chromeos/select_to_speak/select_to_speak.js b/chrome/browser/resources/chromeos/select_to_speak/select_to_speak.js index e06bc9c..13e543b 100644 --- a/chrome/browser/resources/chromeos/select_to_speak/select_to_speak.js +++ b/chrome/browser/resources/chromeos/select_to_speak/select_to_speak.js
@@ -766,11 +766,11 @@ default: if (inForeground) { if (this.wordHighlight_ && this.currentNodeWord_ != null) { - // Only show the highlight if this is an inline text box or - // static text. Otherwise we'd be highlighting entire nodes, - // like images. Highlight should be only for text. - if (node.role == RoleType.INLINE_TEXT_BOX || - node.role == RoleType.STATIC_TEXT) { + // Only show the highlight if this is an inline text box. + // Otherwise we'd be highlighting entire nodes, like images. + // Highlight should be only for text. + // Note that boundsForRange doesn't work on staticText. + if (node.role == RoleType.INLINE_TEXT_BOX) { chrome.accessibilityPrivate.setHighlights( [node.boundsForRange( this.currentNodeWord_.start, this.currentNodeWord_.end)], @@ -787,8 +787,7 @@ // TODO: Better test: has no siblings in the group, highlight just // the one node. if it has siblings, highlight the parent. if (this.currentBlockParent_ != null && - (node.role == RoleType.STATIC_TEXT || - node.role == RoleType.INLINE_TEXT_BOX)) { + node.role == RoleType.INLINE_TEXT_BOX) { chrome.accessibilityPrivate.setFocusRing( [this.currentBlockParent_.location], this.color_); } else {
diff --git a/chrome/browser/resources/component_extension_resources.grd b/chrome/browser/resources/component_extension_resources.grd index 73e3f9f7..60df434 100644 --- a/chrome/browser/resources/component_extension_resources.grd +++ b/chrome/browser/resources/component_extension_resources.grd
@@ -13,7 +13,6 @@ <release seq="1"> <structures> <structure name="IDR_BOOKMARK_MANAGER_MAIN" file="bookmark_manager/main.html" flattenhtml="true" allowexternalscript="true" type="chrome_html" /> - <structure name="IDR_HOTWORD_AUDIO_VERIFICATION_MAIN" file="hotword_audio_verification/main.html" flattenhtml="true" allowexternalscript="true" type="chrome_html" /> <if expr="chromeos"> <structure name="IDR_WALLPAPER_MANAGER_MAIN" file="chromeos/wallpaper_manager/main.html" flattenhtml="true" allowexternalscript="true" type="chrome_html" /> <if expr="not _google_chrome"> @@ -48,49 +47,6 @@ <include name="IDR_HANGOUT_SERVICES_BACKGROUND_HTML" file="hangout_services/background.html" type="BINDATA" /> <include name="IDR_HANGOUT_SERVICES_THUNK_JS" file="hangout_services/thunk.js" type="BINDATA" /> </if> - <if expr="enable_extensions"> - <!-- Hotword Audio Verification app --> - <include name="IDR_HOTWORD_AUDIO_VERIFICATION_BACKGROUND_JS" file="hotword_audio_verification/event_page.js" type="BINDATA" /> - <include name="IDR_HOTWORD_AUDIO_VERIFICATION_MAIN_JS" file="hotword_audio_verification/main.js" type="BINDATA" /> - <include name="IDR_HOTWORD_AUDIO_VERIFICATION_FLOW_JS" file="hotword_audio_verification/flow.js" type="BINDATA" /> - <include name="IDR_START_STEP_HTML" file="hotword_audio_verification/steps/start_step.html" flattenhtml="true" type="BINDATA" /> - <include name="IDR_AUDIO_HISTORY_STEP_HTML" file="hotword_audio_verification/steps/audio_history_step.html" flattenhtml="true" type="BINDATA" /> - <include name="IDR_SPEECH_TRAINING_STEP_HTML" file="hotword_audio_verification/steps/speech_training_step.html" flattenhtml="true" type="BINDATA" /> - <include name="IDR_FINISHED_STEP_HTML" file="hotword_audio_verification/steps/finished_step.html" flattenhtml="true" type="BINDATA" /> - <include name="IDR_HOTWORD_AUDIO_VERIFICATION_STYLE_CSS" file="hotword_audio_verification/style.css" type="BINDATA" /> - <include name="IDR_HOTWORD_AUDIO_VERIFICATION_IMAGE_CLOSE_1X" file="hotword_audio_verification/images/ic-x-white-1x.png" type="BINDATA" /> - <include name="IDR_HOTWORD_AUDIO_VERIFICATION_IMAGE_CLOSE_2X" file="hotword_audio_verification/images/ic-x-white-2x.png" type="BINDATA" /> - <include name="IDR_HOTWORD_AUDIO_VERIFICATION_IMAGE_INTRO_1X" file="hotword_audio_verification/images/intro-1x.png" type="BINDATA" /> - <include name="IDR_HOTWORD_AUDIO_VERIFICATION_IMAGE_INTRO_2X" file="hotword_audio_verification/images/intro-2x.png" type="BINDATA" /> - <include name="IDR_HOTWORD_AUDIO_VERIFICATION_IMAGE_HEADER_1X" file="hotword_audio_verification/images/gradient-1x.png" type="BINDATA" /> - <include name="IDR_HOTWORD_AUDIO_VERIFICATION_IMAGE_HEADER_2X" file="hotword_audio_verification/images/gradient-2x.png" type="BINDATA" /> - <include name="IDR_HOTWORD_AUDIO_VERIFICATION_IMAGE_CHECK_BLUE_1X" file="hotword_audio_verification/images/ic-check-blue-1x.png" type="BINDATA" /> - <include name="IDR_HOTWORD_AUDIO_VERIFICATION_IMAGE_CHECK_BLUE_2X" file="hotword_audio_verification/images/ic-check-blue-2x.png" type="BINDATA" /> - <include name="IDR_HOTWORD_AUDIO_VERIFICATION_IMAGE_CHECK_GRAY_1X" file="hotword_audio_verification/images/ic-check-gray-1x.png" type="BINDATA" /> - <include name="IDR_HOTWORD_AUDIO_VERIFICATION_IMAGE_CHECK_GRAY_2X" file="hotword_audio_verification/images/ic-check-gray-2x.png" type="BINDATA" /> - <include name="IDR_HOTWORD_AUDIO_VERIFICATION_IMAGE_LOADER_1X" file="hotword_audio_verification/images/placeholder-loader-1x.png" type="BINDATA" /> - <include name="IDR_HOTWORD_AUDIO_VERIFICATION_IMAGE_LOADER_2X" file="hotword_audio_verification/images/placeholder-loader-2x.png" type="BINDATA" /> - <include name="IDR_HOTWORD_AUDIO_VERIFICATION_IMAGE_ERROR_1X" file="hotword_audio_verification/images/ic-error-1x.png" type="BINDATA" /> - <include name="IDR_HOTWORD_AUDIO_VERIFICATION_IMAGE_ERROR_2X" file="hotword_audio_verification/images/ic-error-2x.png" type="BINDATA" /> - <include name="IDR_HOTWORD_AUDIO_VERIFICATION_IMAGE_ICON_16" file="hotword_audio_verification/images/icon-16.png" type="BINDATA" /> - <include name="IDR_HOTWORD_AUDIO_VERIFICATION_IMAGE_ICON_48" file="hotword_audio_verification/images/icon-48.png" type="BINDATA" /> - <include name="IDR_HOTWORD_AUDIO_VERIFICATION_IMAGE_ICON_128" file="hotword_audio_verification/images/icon-128.png" type="BINDATA" /> - - <!-- Hotword extension --> - <include name="IDR_HOTWORD_ALWAYS_ON_MANAGER_JS" file="hotword/always_on_manager.js" type="BINDATA" /> - <include name="IDR_HOTWORD_AUDIO_CLIENT_JS" file="hotword/audio_client.js" type="BINDATA" /> - <include name="IDR_HOTWORD_BASE_SESSION_MANAGER_JS" file="hotword/base_session_manager.js" type="BINDATA" /> - <include name="IDR_HOTWORD_CONSTANTS_JS" file="hotword/constants.js" type="BINDATA" /> - <include name="IDR_HOTWORD_KEEP_ALIVE_JS" file="hotword/keep_alive.js" type="BINDATA" /> - <include name="IDR_HOTWORD_LAUNCHER_MANAGER_JS" file="hotword/launcher_manager.js" type="BINDATA" /> - <include name="IDR_HOTWORD_LOGGING_JS" file="hotword/logging.js" type="BINDATA" /> - <include name="IDR_HOTWORD_MANAGER_JS" file="hotword/manager.js" type="BINDATA" /> - <include name="IDR_HOTWORD_METRICS_JS" file="hotword/metrics.js" type="BINDATA" /> - <include name="IDR_HOTWORD_NACL_MANAGER_JS" file="hotword/nacl_manager.js" type="BINDATA" /> - <include name="IDR_HOTWORD_PAGE_AUDIO_MANAGER_JS" file="hotword/page_audio_manager.js" type="BINDATA" /> - <include name="IDR_HOTWORD_STATE_MANAGER_JS" file="hotword/state_manager.js" type="BINDATA" /> - <include name="IDR_HOTWORD_TRAINING_MANAGER_JS" file="hotword/training_manager.js" type="BINDATA" /> - </if> <if expr="not is_android"> <include name="IDR_FEEDBACK_DEFAULT_HTML" file="feedback/html/default.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" /> <include name="IDR_FEEDBACK_SYSINFO_HTML" file="feedback/html/sys_info.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
diff --git a/chrome/browser/resources/download_internals/download_internals.css b/chrome/browser/resources/download_internals/download_internals.css index 63dab4d..bc90901 100644 --- a/chrome/browser/resources/download_internals/download_internals.css +++ b/chrome/browser/resources/download_internals/download_internals.css
@@ -12,6 +12,10 @@ font-size: 15px; } +.sub-text { + font-size: 10px; +} + .service-entry-new { background-color: rgb(242, 242, 242) }
diff --git a/chrome/browser/resources/download_internals/download_internals.html b/chrome/browser/resources/download_internals/download_internals.html index 259ed42f..49e67cd 100644 --- a/chrome/browser/resources/download_internals/download_internals.html +++ b/chrome/browser/resources/download_internals/download_internals.html
@@ -29,6 +29,10 @@ File Monitor: <span id="service-status-file" class="status"></span> </div> <h4>Entry Requests</h4> + <div class="sub-text"> + The entry URLs have been modified to strip query params so that possibly + private information is hidden from view. + </div> <div id="download-service-request-info"> <table class="styled-table"> <thead>
diff --git a/chrome/browser/resources/hotword/OWNERS b/chrome/browser/resources/hotword/OWNERS deleted file mode 100644 index 2ae98b3a..0000000 --- a/chrome/browser/resources/hotword/OWNERS +++ /dev/null
@@ -1,2 +0,0 @@ -kcarattini@chromium.org -mgiuca@chromium.org
diff --git a/chrome/browser/resources/hotword/always_on_manager.js b/chrome/browser/resources/hotword/always_on_manager.js deleted file mode 100644 index f34bc6d..0000000 --- a/chrome/browser/resources/hotword/always_on_manager.js +++ /dev/null
@@ -1,38 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -cr.define('hotword', function() { - 'use strict'; - - /** - * Class used to manage always-on hotwording. Automatically starts hotwording - * on startup, if always-on is enabled, and starts/stops hotwording at - * appropriate times. - * @param {!hotword.StateManager} stateManager - * @constructor - * @extends {hotword.BaseSessionManager} - */ - function AlwaysOnManager(stateManager) { - hotword.BaseSessionManager.call( - this, stateManager, hotword.constants.SessionSource.ALWAYS); - } - - AlwaysOnManager.prototype = { - __proto__: hotword.BaseSessionManager.prototype, - - /** @override */ - enabled: function() { - return this.stateManager.isAlwaysOnEnabled(); - }, - - /** @override */ - updateListeners: function() { - hotword.BaseSessionManager.prototype.updateListeners.call(this); - if (this.enabled()) - this.startSession(); - } - }; - - return {AlwaysOnManager: AlwaysOnManager}; -});
diff --git a/chrome/browser/resources/hotword/audio_client.js b/chrome/browser/resources/hotword/audio_client.js deleted file mode 100644 index 552dd49..0000000 --- a/chrome/browser/resources/hotword/audio_client.js +++ /dev/null
@@ -1,375 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -'use strict'; - -/* eslint-disable no-restricted-properties */ - -/** - * @fileoverview This is the audio client content script injected into eligible - * Google.com and New tab pages for interaction between the Webpage and the - * Hotword extension. - */ - -(function() { -/** - * @constructor - */ -var AudioClient = function() { - /** @private {Element} */ - this.speechOverlay_ = null; - - /** @private {number} */ - this.checkSpeechUiRetries_ = 0; - - /** - * Port used to communicate with the audio manager. - * @private {?Port} - */ - this.port_ = null; - - /** - * Keeps track of the effects of different commands. Used to verify that - * proper UIs are shown to the user. - * @private {Object<AudioClient.CommandToPage, Object>} - */ - this.uiStatus_ = null; - - /** - * Bound function used to handle commands sent from the page to this script. - * @private {Function} - */ - this.handleCommandFromPageFunc_ = null; -}; - -/** - * Messages sent to the page to control the voice search UI. - * @enum {string} - */ -AudioClient.CommandToPage = { - HOTWORD_VOICE_TRIGGER: 'vt', - HOTWORD_STARTED: 'hs', - HOTWORD_ENDED: 'hd', - HOTWORD_TIMEOUT: 'ht', - HOTWORD_ERROR: 'he' -}; - -/** - * Messages received from the page used to indicate voice search state. - * @enum {string} - */ -AudioClient.CommandFromPage = { - SPEECH_START: 'ss', - SPEECH_END: 'se', - SPEECH_RESET: 'sr', - SHOWING_HOTWORD_START: 'shs', - SHOWING_ERROR_MESSAGE: 'sem', - SHOWING_TIMEOUT_MESSAGE: 'stm', - CLICKED_RESUME: 'hcc', - CLICKED_RESTART: 'hcr', - CLICKED_DEBUG: 'hcd' -}; - -/** - * Errors that are sent to the hotword extension. - * @enum {string} - */ -AudioClient.Error = { - NO_SPEECH_UI: 'ac1', - NO_HOTWORD_STARTED_UI: 'ac2', - NO_HOTWORD_TIMEOUT_UI: 'ac3', - NO_HOTWORD_ERROR_UI: 'ac4' -}; - -/** - * @const {string} - * @private - */ -AudioClient.HOTWORD_EXTENSION_ID_ = 'nbpagnldghgfoolbancepceaanlmhfmd'; - -/** - * Number of times to retry checking a transient error. - * @const {number} - * @private - */ -AudioClient.MAX_RETRIES = 3; - -/** - * Delay to wait in milliseconds before rechecking for any transient errors. - * @const {number} - * @private - */ -AudioClient.RETRY_TIME_MS_ = 2000; - -/** - * DOM ID for the speech UI overlay. - * @const {string} - * @private - */ -AudioClient.SPEECH_UI_OVERLAY_ID_ = 'spch'; - -/** - * @const {string} - * @private - */ -AudioClient.HELP_CENTER_URL_ = - 'https://support.google.com/chrome/?p=ui_hotword_search'; - -/** - * @const {string} - * @private - */ -AudioClient.CLIENT_PORT_NAME_ = 'chwcpn'; - -/** - * Existence of the Audio Client. - * @const {string} - * @private - */ -AudioClient.EXISTS_ = 'chwace'; - -/** - * Checks for the presence of speech overlay UI DOM elements. - * @private - */ -AudioClient.prototype.checkSpeechOverlayUi_ = function() { - if (!this.speechOverlay_) { - window.setTimeout( - this.delayedCheckSpeechOverlayUi_.bind(this), - AudioClient.RETRY_TIME_MS_); - } else { - this.checkSpeechUiRetries_ = 0; - } -}; - -/** - * Function called to check for the speech UI overlay after some time has - * passed since an initial check. Will either retry triggering the speech - * or sends an error message depending on the number of retries. - * @private - */ -AudioClient.prototype.delayedCheckSpeechOverlayUi_ = function() { - this.speechOverlay_ = - document.getElementById(AudioClient.SPEECH_UI_OVERLAY_ID_); - if (!this.speechOverlay_) { - if (this.checkSpeechUiRetries_++ < AudioClient.MAX_RETRIES) { - this.sendCommandToPage_(AudioClient.CommandToPage.VOICE_TRIGGER); - this.checkSpeechOverlayUi_(); - } else { - this.sendCommandToExtension_(AudioClient.Error.NO_SPEECH_UI); - } - } else { - this.checkSpeechUiRetries_ = 0; - } -}; - -/** - * Checks that the triggered UI is actually displayed. - * @param {AudioClient.CommandToPage} command Command that was send. - * @private - */ -AudioClient.prototype.checkUi_ = function(command) { - this.uiStatus_[command].timeoutId = window.setTimeout( - this.failedCheckUi_.bind(this, command), AudioClient.RETRY_TIME_MS_); -}; - -/** - * Function called when the UI verification is not called in time. Will either - * retry the command or sends an error message, depending on the number of - * retries for the command. - * @param {AudioClient.CommandToPage} command Command that was sent. - * @private - */ -AudioClient.prototype.failedCheckUi_ = function(command) { - if (this.uiStatus_[command].tries++ < AudioClient.MAX_RETRIES) { - this.sendCommandToPage_(command); - this.checkUi_(command); - } else { - this.sendCommandToExtension_(this.uiStatus_[command].error); - } -}; - -/** - * Confirm that an UI element has been shown. - * @param {AudioClient.CommandToPage} command UI to confirm. - * @private - */ -AudioClient.prototype.verifyUi_ = function(command) { - if (this.uiStatus_[command].timeoutId) { - window.clearTimeout(this.uiStatus_[command].timeoutId); - this.uiStatus_[command].timeoutId = null; - this.uiStatus_[command].tries = 0; - } -}; - -/** - * Sends a command to the audio manager. - * @param {string} commandStr command to send to plugin. - * @private - */ -AudioClient.prototype.sendCommandToExtension_ = function(commandStr) { - if (this.port_) - this.port_.postMessage({'cmd': commandStr}); -}; - -/** - * Handles a message from the audio manager. - * @param {{cmd: string}} commandObj Command from the audio manager. - * @private - */ -AudioClient.prototype.handleCommandFromExtension_ = function(commandObj) { - var command = commandObj['cmd']; - if (command) { - switch (command) { - case AudioClient.CommandToPage.HOTWORD_VOICE_TRIGGER: - this.sendCommandToPage_(command); - this.checkSpeechOverlayUi_(); - break; - case AudioClient.CommandToPage.HOTWORD_STARTED: - this.sendCommandToPage_(command); - this.checkUi_(command); - break; - case AudioClient.CommandToPage.HOTWORD_ENDED: - this.sendCommandToPage_(command); - break; - case AudioClient.CommandToPage.HOTWORD_TIMEOUT: - this.sendCommandToPage_(command); - this.checkUi_(command); - break; - case AudioClient.CommandToPage.HOTWORD_ERROR: - this.sendCommandToPage_(command); - this.checkUi_(command); - break; - } - } -}; - -/** - * @param {AudioClient.CommandToPage} commandStr Command to send. - * @private - */ -AudioClient.prototype.sendCommandToPage_ = function(commandStr) { - window.postMessage({'type': commandStr}, '*'); -}; - -/** - * Handles a message from the html window. - * @param {!MessageEvent} messageEvent Message event from the window. - * @private - */ -AudioClient.prototype.handleCommandFromPage_ = function(messageEvent) { - if (messageEvent.source == window && messageEvent.data.type) { - var command = messageEvent.data.type; - switch (command) { - case AudioClient.CommandFromPage.SPEECH_START: - this.speechActive_ = true; - this.sendCommandToExtension_(command); - break; - case AudioClient.CommandFromPage.SPEECH_END: - this.speechActive_ = false; - this.sendCommandToExtension_(command); - break; - case AudioClient.CommandFromPage.SPEECH_RESET: - this.speechActive_ = false; - this.sendCommandToExtension_(command); - break; - case 'SPEECH_RESET': // Legacy, for embedded NTP. - this.speechActive_ = false; - this.sendCommandToExtension_(AudioClient.CommandFromPage.SPEECH_END); - break; - case AudioClient.CommandFromPage.CLICKED_RESUME: - this.sendCommandToExtension_(command); - break; - case AudioClient.CommandFromPage.CLICKED_RESTART: - this.sendCommandToExtension_(command); - break; - case AudioClient.CommandFromPage.CLICKED_DEBUG: - window.open(AudioClient.HELP_CENTER_URL_, '_blank'); - break; - case AudioClient.CommandFromPage.SHOWING_HOTWORD_START: - this.verifyUi_(AudioClient.CommandToPage.HOTWORD_STARTED); - break; - case AudioClient.CommandFromPage.SHOWING_ERROR_MESSAGE: - this.verifyUi_(AudioClient.CommandToPage.HOTWORD_ERROR); - break; - case AudioClient.CommandFromPage.SHOWING_TIMEOUT_MESSAGE: - this.verifyUi_(AudioClient.CommandToPage.HOTWORD_TIMEOUT); - break; - } - } -}; - -/** - * Initialize the content script. - */ -AudioClient.prototype.initialize = function() { - if (AudioClient.EXISTS_ in window) - return; - window[AudioClient.EXISTS_] = true; - - // UI verification object. - this.uiStatus_ = {}; - this.uiStatus_[AudioClient.CommandToPage.HOTWORD_STARTED] = { - timeoutId: null, - tries: 0, - error: AudioClient.Error.NO_HOTWORD_STARTED_UI - }; - this.uiStatus_[AudioClient.CommandToPage.HOTWORD_TIMEOUT] = { - timeoutId: null, - tries: 0, - error: AudioClient.Error.NO_HOTWORD_TIMEOUT_UI - }; - this.uiStatus_[AudioClient.CommandToPage.HOTWORD_ERROR] = { - timeoutId: null, - tries: 0, - error: AudioClient.Error.NO_HOTWORD_ERROR_UI - }; - - this.handleCommandFromPageFunc_ = this.handleCommandFromPage_.bind(this); - window.addEventListener('message', this.handleCommandFromPageFunc_, false); - this.initPort_(); -}; - -/** - * Initialize the communications port with the audio manager. This - * function will be also be called again if the audio-manager - * disconnects for some reason (such as the extension - * background.html page being reloaded). - * @private - */ -AudioClient.prototype.initPort_ = function() { - this.port_ = chrome.runtime.connect( - AudioClient.HOTWORD_EXTENSION_ID_, - {'name': AudioClient.CLIENT_PORT_NAME_}); - // Note that this listen may have to be destroyed manually if AudioClient - // is ever destroyed on this tab. - this.port_.onDisconnect.addListener( - (function(e) { - if (this.handleCommandFromPageFunc_) { - window.removeEventListener( - 'message', this.handleCommandFromPageFunc_, false); - } - delete window[AudioClient.EXISTS_]; - }).bind(this)); - - // See note above. - this.port_.onMessage.addListener(this.handleCommandFromExtension_.bind(this)); - - if (this.speechActive_) { - this.sendCommandToExtension_(AudioClient.CommandFromPage.SPEECH_START); - } else { - // It's possible for this script to be injected into the page after it has - // completed loaded (i.e. when prerendering). In this case, this script - // won't receive a SPEECH_RESET from the page to forward onto the - // extension. To make up for this, always send a SPEECH_RESET. This means - // in most cases, the extension will receive SPEECH_RESET twice, one from - // this sendCommandToExtension_ and the one forwarded from the page. But - // that's OK and the extension can handle it. - this.sendCommandToExtension_(AudioClient.CommandFromPage.SPEECH_RESET); - } -}; - -// Initializes as soon as the code is ready, do not wait for the page. -new AudioClient().initialize(); -})();
diff --git a/chrome/browser/resources/hotword/base_session_manager.js b/chrome/browser/resources/hotword/base_session_manager.js deleted file mode 100644 index 6891199..0000000 --- a/chrome/browser/resources/hotword/base_session_manager.js +++ /dev/null
@@ -1,152 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -cr.define('hotword', function() { - 'use strict'; - - /** - * Base class for managing hotwording sessions. - * @param {!hotword.StateManager} stateManager Manager of global hotwording - * state. - * @param {!hotword.constants.SessionSource} sessionSource Source of the - * hotword session request. - * @constructor - */ - function BaseSessionManager(stateManager, sessionSource) { - /** - * Manager of global hotwording state. - * @protected {!hotword.StateManager} - */ - this.stateManager = stateManager; - - /** - * Source of the hotword session request. - * @private {!hotword.constants.SessionSource} - */ - this.sessionSource_ = sessionSource; - - /** - * Chrome event listeners. Saved so that they can be de-registered when - * hotwording is disabled. - * @private - */ - this.sessionRequestedListener_ = this.handleSessionRequested_.bind(this); - this.sessionStoppedListener_ = this.handleSessionStopped_.bind(this); - - // Need to setup listeners on startup, otherwise events that caused the - // event page to start up, will be lost. - this.setupListeners_(); - - this.stateManager.onStatusChanged.addListener(function() { - hotword.debug('onStatusChanged'); - this.updateListeners(); - }.bind(this)); - } - - BaseSessionManager.prototype = { - /** - * Return whether or not this session type is enabled. - * @protected - * @return {boolean} - */ - enabled: assertNotReached, - - /** - * Called when the hotwording session is stopped. - * @protected - */ - onSessionStop: function() {}, - - /** - * Starts a launcher hotwording session. - * @param {hotword.constants.TrainingMode=} opt_mode The mode to start the - * recognizer in. - */ - startSession: function(opt_mode) { - this.stateManager.startSession(this.sessionSource_, function() { - chrome.hotwordPrivate.setHotwordSessionState(true, function() {}); - }, this.handleHotwordTrigger.bind(this), opt_mode); - }, - - /** - * Stops a launcher hotwording session. - * @private - */ - stopSession_: function() { - this.stateManager.stopSession(this.sessionSource_); - this.onSessionStop(); - }, - - /** - * Handles a hotword triggered event. - * @param {?Object} log Audio log data, if audio logging is enabled. - * @protected - */ - handleHotwordTrigger: function(log) { - hotword.debug('Hotword triggered: ' + this.sessionSource_, log); - chrome.hotwordPrivate.notifyHotwordRecognition( - 'search', log, function() {}); - }, - - /** - * Handles a hotwordPrivate.onHotwordSessionRequested event. - * @private - */ - handleSessionRequested_: function() { - hotword.debug('handleSessionRequested_: ' + this.sessionSource_); - this.startSession(); - }, - - /** - * Handles a hotwordPrivate.onHotwordSessionStopped event. - * @private - */ - handleSessionStopped_: function() { - hotword.debug('handleSessionStopped_: ' + this.sessionSource_); - this.stopSession_(); - }, - - /** - * Set up event listeners. - * @private - */ - setupListeners_: function() { - if (chrome.hotwordPrivate.onHotwordSessionRequested.hasListener( - this.sessionRequestedListener_)) { - return; - } - - chrome.hotwordPrivate.onHotwordSessionRequested.addListener( - this.sessionRequestedListener_); - chrome.hotwordPrivate.onHotwordSessionStopped.addListener( - this.sessionStoppedListener_); - }, - - /** - * Remove event listeners. - * @private - */ - removeListeners_: function() { - chrome.hotwordPrivate.onHotwordSessionRequested.removeListener( - this.sessionRequestedListener_); - chrome.hotwordPrivate.onHotwordSessionStopped.removeListener( - this.sessionStoppedListener_); - }, - - /** - * Update event listeners based on the current hotwording state. - * @protected - */ - updateListeners: function() { - if (this.enabled()) { - this.setupListeners_(); - } else { - this.removeListeners_(); - this.stopSession_(); - } - } - }; - - return {BaseSessionManager: BaseSessionManager}; -});
diff --git a/chrome/browser/resources/hotword/constants.js b/chrome/browser/resources/hotword/constants.js deleted file mode 100644 index 0fbfa0e..0000000 --- a/chrome/browser/resources/hotword/constants.js +++ /dev/null
@@ -1,299 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -cr.define('hotword.constants', function() { - 'use strict'; - - /** - * Number of seconds of audio to record when logging is enabled. - * @const {number} - */ - var AUDIO_LOG_SECONDS = 2; - - /** - * Timeout in seconds, for detecting false positives with a hotword stream. - * @const {number} - */ - var HOTWORD_STREAM_TIMEOUT_SECONDS = 2; - - /** - * Hotword data shared module extension's ID. - * @const {string} - */ - var SHARED_MODULE_ID = 'lccekmodgklaepjeofjdjpbminllajkg'; - - /** - * Path to shared module data. - * @const {string} - */ - var SHARED_MODULE_ROOT = '_modules/' + SHARED_MODULE_ID; - - /** - * Name used by the content scripts to create communications Ports. - * @const {string} - */ - var CLIENT_PORT_NAME = 'chwcpn'; - - /** - * The field name to specify the command among pages. - * @const {string} - */ - var COMMAND_FIELD_NAME = 'cmd'; - - /** - * The speaker model file name. - * @const {string} - */ - var SPEAKER_MODEL_FILE_NAME = 'speaker_model.data'; - - /** - * The training utterance file name prefix. - * @const {string} - */ - var UTTERANCE_FILE_PREFIX = 'utterance-'; - - /** - * The training utterance file extension. - * @const {string} - */ - var UTTERANCE_FILE_EXTENSION = '.raw'; - - /** - * The number of training utterances required to train the speaker model. - * @const {number} - */ - var NUM_TRAINING_UTTERANCES = 3; - - /** - * The size of the file system requested for reading the speaker model and - * utterances. This number should always be larger than the combined file - * size, - * currently 576338 bytes as of February 2015. - * @const {number} - */ - var FILE_SYSTEM_SIZE_BYTES = 1048576; - - /** - * Time to wait for expected messages, in milliseconds. - * @enum {number} - */ - var TimeoutMs = {SHORT: 200, NORMAL: 500, LONG: 2000}; - - /** - * The URL of the files used by the plugin. - * @enum {string} - */ - var File = { - RECOGNIZER_CONFIG: 'hotword.data', - }; - - /** - * Errors emitted by the NaClManager. - * @enum {string} - */ - var Error = { - NACL_CRASH: 'nacl_crash', - TIMEOUT: 'timeout', - }; - - /** - * Event types supported by NaClManager. - * @enum {string} - */ - var Event = { - READY: 'ready', - TRIGGER: 'trigger', - SPEAKER_MODEL_SAVED: 'speaker model saved', - ERROR: 'error', - TIMEOUT: 'timeout', - }; - - /** - * Messages for communicating with the NaCl recognizer plugin. These must - * match - * constants in <google3>/hotword_plugin.c - * @enum {string} - */ - var NaClPlugin = { - RESTART: 'r', - SAMPLE_RATE_PREFIX: 'h', - MODEL_PREFIX: 'm', - STOP: 's', - LOG: 'l', - DSP: 'd', - BEGIN_SPEAKER_MODEL: 'b', - ADAPT_SPEAKER_MODEL: 'a', - FINISH_SPEAKER_MODEL: 'f', - SPEAKER_MODEL_SAVED: 'sm_saved', - REQUEST_MODEL: 'model', - MODEL_LOADED: 'model_loaded', - READY_FOR_AUDIO: 'audio', - STOPPED: 'stopped', - HOTWORD_DETECTED: 'hotword', - MS_CONFIGURED: 'ms_configured', - TIMEOUT: 'timeout' - }; - - /** - * Messages sent from the injected scripts to the Google page. - * @enum {string} - */ - var CommandToPage = { - HOTWORD_VOICE_TRIGGER: 'vt', - HOTWORD_STARTED: 'hs', - HOTWORD_ENDED: 'hd', - HOTWORD_TIMEOUT: 'ht', - HOTWORD_ERROR: 'he' - }; - - /** - * Messages sent from the Google page to the extension or to the - * injected script and then passed to the extension. - * @enum {string} - */ - var CommandFromPage = { - SPEECH_START: 'ss', - SPEECH_END: 'se', - SPEECH_RESET: 'sr', - SHOWING_HOTWORD_START: 'shs', - SHOWING_ERROR_MESSAGE: 'sem', - SHOWING_TIMEOUT_MESSAGE: 'stm', - CLICKED_RESUME: 'hcc', - CLICKED_RESTART: 'hcr', - CLICKED_DEBUG: 'hcd', - WAKE_UP_HELPER: 'wuh', - // Command specifically for the opt-in promo below this line. - // User has explicitly clicked 'no'. - CLICKED_NO_OPTIN: 'hcno', - // User has opted in. - CLICKED_OPTIN: 'hco', - // User clicked on the microphone. - PAGE_WAKEUP: 'wu' - }; - - /** - * Source of a hotwording session request. - * @enum {string} - */ - var SessionSource = { - LAUNCHER: 'launcher', - NTP: 'ntp', - ALWAYS: 'always', - TRAINING: 'training' - }; - - /** - * The mode to start the hotword recognizer in. - * @enum {string} - */ - var RecognizerStartMode = { - NORMAL: 'normal', - NEW_MODEL: 'new model', - ADAPT_MODEL: 'adapt model' - }; - - /** - * MediaStream open success/errors to be reported via UMA. - * DO NOT remove or renumber values in this enum. Only add new ones. - * @enum {number} - */ - var UmaMediaStreamOpenResult = { - SUCCESS: 0, - UNKNOWN: 1, - NOT_SUPPORTED: 2, - PERMISSION_DENIED: 3, - CONSTRAINT_NOT_SATISFIED: 4, - OVERCONSTRAINED: 5, - NOT_FOUND: 6, - ABORT: 7, - SOURCE_UNAVAILABLE: 8, - PERMISSION_DISMISSED: 9, - INVALID_STATE: 10, - DEVICES_NOT_FOUND: 11, - INVALID_SECURITY_ORIGIN: 12, - MAX: 12 - }; - - /** - * UMA metrics. - * DO NOT change these enum values. - * @enum {string} - */ - var UmaMetrics = { - TRIGGER: 'Hotword.HotwordTrigger', - MEDIA_STREAM_RESULT: 'Hotword.HotwordMediaStreamResult', - NACL_PLUGIN_LOAD_RESULT: 'Hotword.HotwordNaClPluginLoadResult', - NACL_MESSAGE_TIMEOUT: 'Hotword.HotwordNaClMessageTimeout', - TRIGGER_SOURCE: 'Hotword.HotwordTriggerSource' - }; - - /** - * Message waited for by NaCl plugin, to be reported via UMA. - * DO NOT remove or renumber values in this enum. Only add new ones. - * @enum {number} - */ - var UmaNaClMessageTimeout = { - REQUEST_MODEL: 0, - MODEL_LOADED: 1, - READY_FOR_AUDIO: 2, - STOPPED: 3, - HOTWORD_DETECTED: 4, - MS_CONFIGURED: 5, - MAX: 5 - }; - - /** - * NaCl plugin load success/errors to be reported via UMA. - * DO NOT remove or renumber values in this enum. Only add new ones. - * @enum {number} - */ - var UmaNaClPluginLoadResult = - {SUCCESS: 0, UNKNOWN: 1, CRASH: 2, NO_MODULE_FOUND: 3, MAX: 3}; - - /** - * Source of hotword triggering, to be reported via UMA. - * DO NOT remove or renumber values in this enum. Only add new ones. - * @enum {number} - */ - var UmaTriggerSource = - {LAUNCHER: 0, NTP_GOOGLE_COM: 1, ALWAYS_ON: 2, TRAINING: 3, MAX: 3}; - - /** - * The browser UI language. - * @const {string} - */ - var UI_LANGUAGE = (chrome.i18n && chrome.i18n.getUILanguage) ? - chrome.i18n.getUILanguage() : - ''; - - return { - AUDIO_LOG_SECONDS: AUDIO_LOG_SECONDS, - CLIENT_PORT_NAME: CLIENT_PORT_NAME, - COMMAND_FIELD_NAME: COMMAND_FIELD_NAME, - FILE_SYSTEM_SIZE_BYTES: FILE_SYSTEM_SIZE_BYTES, - HOTWORD_STREAM_TIMEOUT_SECONDS: HOTWORD_STREAM_TIMEOUT_SECONDS, - NUM_TRAINING_UTTERANCES: NUM_TRAINING_UTTERANCES, - SHARED_MODULE_ID: SHARED_MODULE_ID, - SHARED_MODULE_ROOT: SHARED_MODULE_ROOT, - SPEAKER_MODEL_FILE_NAME: SPEAKER_MODEL_FILE_NAME, - UI_LANGUAGE: UI_LANGUAGE, - UTTERANCE_FILE_EXTENSION: UTTERANCE_FILE_EXTENSION, - UTTERANCE_FILE_PREFIX: UTTERANCE_FILE_PREFIX, - CommandToPage: CommandToPage, - CommandFromPage: CommandFromPage, - Error: Error, - Event: Event, - File: File, - NaClPlugin: NaClPlugin, - RecognizerStartMode: RecognizerStartMode, - SessionSource: SessionSource, - TimeoutMs: TimeoutMs, - UmaMediaStreamOpenResult: UmaMediaStreamOpenResult, - UmaMetrics: UmaMetrics, - UmaNaClMessageTimeout: UmaNaClMessageTimeout, - UmaNaClPluginLoadResult: UmaNaClPluginLoadResult, - UmaTriggerSource: UmaTriggerSource - }; - -});
diff --git a/chrome/browser/resources/hotword/keep_alive.js b/chrome/browser/resources/hotword/keep_alive.js deleted file mode 100644 index 20ff2ea..0000000 --- a/chrome/browser/resources/hotword/keep_alive.js +++ /dev/null
@@ -1,52 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -cr.define('hotword', function() { - 'use strict'; - - /** - * Class used to keep this extension alive. When started, this calls an - * extension API on a regular basis which resets the event page keep-alive - * timer. - * @constructor - */ - function KeepAlive() { - this.timeoutId_ = null; - } - - KeepAlive.prototype = { - /** - * Start the keep alive process. Safe to call multiple times. - */ - start: function() { - if (this.timeoutId_ == null) - this.timeoutId_ = setTimeout(this.handleTimeout_.bind(this), 1000); - }, - - /** - * Stops the keep alive process. Safe to call multiple times. - */ - stop: function() { - if (this.timeoutId_ != null) { - clearTimeout(this.timeoutId_); - this.timeoutId_ = null; - } - }, - - /** - * Handle the timer timeout. Calls an extension API and schedules the next - * timeout. - * @private - */ - handleTimeout_: function() { - // Dummy extensions API call used to keep this event page alive by - // resetting the shutdown timer. - chrome.runtime.getPlatformInfo(function(info) {}); - - this.timeoutId_ = setTimeout(this.handleTimeout_.bind(this), 1000); - } - }; - - return {KeepAlive: KeepAlive}; -});
diff --git a/chrome/browser/resources/hotword/launcher_manager.js b/chrome/browser/resources/hotword/launcher_manager.js deleted file mode 100644 index 144c247..0000000 --- a/chrome/browser/resources/hotword/launcher_manager.js +++ /dev/null
@@ -1,35 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -cr.define('hotword', function() { - 'use strict'; - - /** - * Class used to manage the interaction between hotwording and the launcher - * (app list). - * @param {!hotword.StateManager} stateManager - * @constructor - * @extends {hotword.BaseSessionManager} - */ - function LauncherManager(stateManager) { - hotword.BaseSessionManager.call( - this, stateManager, hotword.constants.SessionSource.LAUNCHER); - } - - LauncherManager.prototype = { - __proto__: hotword.BaseSessionManager.prototype, - - /** @override */ - enabled: function() { - return this.stateManager.isSometimesOnEnabled(); - }, - - /** @override */ - onSessionStop: function() { - chrome.hotwordPrivate.setHotwordSessionState(false, function() {}); - } - }; - - return {LauncherManager: LauncherManager}; -});
diff --git a/chrome/browser/resources/hotword/logging.js b/chrome/browser/resources/hotword/logging.js deleted file mode 100644 index e0744e0..0000000 --- a/chrome/browser/resources/hotword/logging.js +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -cr.define('hotword', function() { - 'use strict'; - - /** - * Wrapper around console.log allowing debug log message to be enabled during - * development. - * @param {...*} varArgs - */ - function debug(varArgs) { - if (hotword.DEBUG || window.localStorage['hotword.DEBUG']) - console.log.apply(console, arguments); - } - - return {DEBUG: false, debug: debug}; -});
diff --git a/chrome/browser/resources/hotword/manager.js b/chrome/browser/resources/hotword/manager.js deleted file mode 100644 index f4ac147..0000000 --- a/chrome/browser/resources/hotword/manager.js +++ /dev/null
@@ -1,50 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -(function() { -'use strict'; - -/** - * @fileoverview This extension provides hotword triggering capabilites to - * Chrome. - * - * This extension contains all the JavaScript for loading and managing the - * hotword detector. The hotword detector and language model data will be - * provided by a shared module loaded from the web store. - * - * IMPORTANT! Whenever adding new events, the extension version number MUST be - * incremented. - */ - -// Hotwording state. -var stateManager = new hotword.StateManager(); -var pageAudioManager = new hotword.PageAudioManager(stateManager); -var alwaysOnManager = new hotword.AlwaysOnManager(stateManager); -var launcherManager = new hotword.LauncherManager(stateManager); -var trainingManager = new hotword.TrainingManager(stateManager); - -// Detect when hotword settings have changed. -chrome.hotwordPrivate.onEnabledChanged.addListener(function() { - stateManager.updateStatus(); -}); - -// Detect a request to delete the speaker model. -chrome.hotwordPrivate.onDeleteSpeakerModel.addListener(function() { - hotword.TrainingManager.handleDeleteSpeakerModel(); -}); - -// Detect a request for the speaker model existence. -chrome.hotwordPrivate.onSpeakerModelExists.addListener(function() { - hotword.TrainingManager.handleSpeakerModelExists(); -}); - -// Detect when the shared module containing the NaCL module and language model -// is installed. -chrome.management.onInstalled.addListener(function(info) { - if (info.id == hotword.constants.SHARED_MODULE_ID) { - hotword.debug('Shared module installed, reloading extension.'); - chrome.runtime.reload(); - } -}); -}());
diff --git a/chrome/browser/resources/hotword/manifest.json b/chrome/browser/resources/hotword/manifest.json deleted file mode 100644 index e22ff93..0000000 --- a/chrome/browser/resources/hotword/manifest.json +++ /dev/null
@@ -1,88 +0,0 @@ -{ - // Extension ID: nbpagnldghgfoolbancepceaanlmhfmd - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDbHXRPiq2De9EJ+4pvNN6uE/D2avxrqyLSpA/Hq3II+btkPl1gboY3oUPTfevpVOFa90Y1c1b3/W682dXqybT0klIvFLKhdQx0LiVqSUQyIaDrwOCSo/ZcukbEwDRojegWymCjHvX6WZk4kKZzTJYzY1vrp0TWKLhttEMN9KFmowIDAQAB", - - "name": "Hotword triggering", - "version": "0.0.1.4", - "manifest_version": 2, - - "background": { - "scripts": [ - "chrome://resources/js/cr.js", - "chrome://resources/js/util.js", - "chrome://resources/js/cr/event_target.js", - "constants.js", - "keep_alive.js", - "logging.js", - "metrics.js", - "nacl_manager.js", - "state_manager.js", - "base_session_manager.js", - "always_on_manager.js", - "launcher_manager.js", - "page_audio_manager.js", - "training_manager.js", - "manager.js" - ], - "persistent": false - }, - - "permissions": [ - "*://*.google.at/*", - "*://*.google.ca/*", - "*://*.google.com/*", - "*://*.google.com.au/*", - "*://*.google.com.mx/*", - "*://*.google.com.br/*", - "*://*.google.co.jp/*", - "*://*.google.co.kr/*", - "*://*.google.co.nz/*", - "*://*.google.co.uk/*", - "*://*.google.co.za/*", - "*://*.google.de/*", - "*://*.google.es/*", - "*://*.google.fr/*", - "*://*.google.it/*", - "*://*.google.ru/*", - "chrome://newtab/", - "chrome://resources/", - "audioCapture", - "hotwordPrivate", - "idle", - "management", - "metricsPrivate", - "tabs", - "unlimitedStorage" - ], - - "externally_connectable": { - "matches": [ - "*://*.google.at/*", - "*://*.google.ca/*", - "*://*.google.com/*", - "*://*.google.com.au/*", - "*://*.google.com.mx/*", - "*://*.google.com.br/*", - "*://*.google.co.jp/*", - "*://*.google.co.kr/*", - "*://*.google.co.nz/*", - "*://*.google.co.uk/*", - "*://*.google.co.za/*", - "*://*.google.de/*", - "*://*.google.es/*", - "*://*.google.fr/*", - "*://*.google.it/*", - "*://*.google.ru/*", - "chrome://newtab/" - ] - }, - - "import": [ - { - "id": "lccekmodgklaepjeofjdjpbminllajkg" - } - ], - - "content_security_policy": "object-src 'none'; script-src chrome://resources 'self' blob: filesystem:", - "minimum_chrome_version": "38" -}
diff --git a/chrome/browser/resources/hotword/metrics.js b/chrome/browser/resources/hotword/metrics.js deleted file mode 100644 index 7d4001bf..0000000 --- a/chrome/browser/resources/hotword/metrics.js +++ /dev/null
@@ -1,26 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -cr.define('hotword.metrics', function() { - 'use strict'; - - /** - * Helper function to record enum values in UMA. - * @param {!string} name - * @param {!number} value - * @param {!number} maxValue - */ - function recordEnum(name, value, maxValue) { - var metricDesc = { - 'metricName': name, - 'type': chrome.metricsPrivate.MetricTypeType.HISTOGRAM_LINEAR, - 'min': 1, - 'max': maxValue, - 'buckets': maxValue + 1 - }; - chrome.metricsPrivate.recordValue(metricDesc, value); - } - - return {recordEnum: recordEnum}; -});
diff --git a/chrome/browser/resources/hotword/nacl_manager.js b/chrome/browser/resources/hotword/nacl_manager.js deleted file mode 100644 index 015399f3..0000000 --- a/chrome/browser/resources/hotword/nacl_manager.js +++ /dev/null
@@ -1,612 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -cr.define('hotword', function() { - 'use strict'; - - /** - * Class used to manage the state of the NaCl recognizer plugin. Handles all - * control of the NaCl plugin, including creation, start, stop, trigger, and - * shutdown. - * - * @param {boolean} loggingEnabled Whether audio logging is enabled. - * @param {boolean} hotwordStream Whether the audio input stream is from a - * hotword stream. - * @constructor - * @extends {cr.EventTarget} - */ - function NaClManager(loggingEnabled, hotwordStream) { - /** - * Current state of this manager. - * @private {hotword.NaClManager.ManagerState_} - */ - this.recognizerState_ = ManagerState_.UNINITIALIZED; - - /** - * The window.timeout ID associated with a pending message. - * @private {?number} - */ - this.naclTimeoutId_ = null; - - /** - * The expected message that will cancel the current timeout. - * @private {?string} - */ - this.expectingMessage_ = null; - - /** - * Whether the plugin will be started as soon as it stops. - * @private {boolean} - */ - this.restartOnStop_ = false; - - /** - * NaCl plugin element on extension background page. - * @private {?HTMLEmbedElement} - */ - this.plugin_ = null; - - /** - * URL containing hotword-model data file. - * @private {string} - */ - this.modelUrl_ = ''; - - /** - * Media stream containing an audio input track. - * @private {?MediaStream} - */ - this.stream_ = null; - - /** - * The mode to start the recognizer in. - * @private {?chrome.hotwordPrivate.RecognizerStartMode} - */ - this.startMode_ = hotword.constants.RecognizerStartMode.NORMAL; - - /** - * Whether audio logging is enabled. - * @private {boolean} - */ - this.loggingEnabled_ = loggingEnabled; - - /** - * Whether the audio input stream is from a hotword stream. - * @private {boolean} - */ - this.hotwordStream_ = hotwordStream; - - /** - * Audio log of X seconds before hotword triggered. - * @private {?Object} - */ - this.preambleLog_ = null; - } - - /** - * States this manager can be in. Since messages to/from the plugin are - * asynchronous (and potentially queued), it's not possible to know what state - * the plugin is in. However, track a state machine for NaClManager based on - * what messages are sent/received. - * @enum {number} - * @private - */ - NaClManager.ManagerState_ = { - UNINITIALIZED: 0, - LOADING: 1, - STOPPING: 2, - STOPPED: 3, - STARTING: 4, - RUNNING: 5, - ERROR: 6, - SHUTDOWN: 7, - }; - var ManagerState_ = NaClManager.ManagerState_; - var Error_ = hotword.constants.Error; - var UmaNaClMessageTimeout_ = hotword.constants.UmaNaClMessageTimeout; - var UmaNaClPluginLoadResult_ = hotword.constants.UmaNaClPluginLoadResult; - - NaClManager.prototype.__proto__ = cr.EventTarget.prototype; - - /** - * Called when an error occurs. Dispatches an event. - * @param {!hotword.constants.Error} error - * @private - */ - NaClManager.prototype.handleError_ = function(error) { - var event = new Event(hotword.constants.Event.ERROR); - event.data = error; - this.dispatchEvent(event); - }; - - /** - * Record the result of loading the NaCl plugin to UMA. - * @param {!hotword.constants.UmaNaClPluginLoadResult} error - * @private - */ - NaClManager.prototype.logPluginLoadResult_ = function(error) { - hotword.metrics.recordEnum( - hotword.constants.UmaMetrics.NACL_PLUGIN_LOAD_RESULT, error, - UmaNaClPluginLoadResult_.MAX); - }; - - /** - * Set a timeout. Only allow one timeout to exist at any given time. - * @param {!function()} func - * @param {number} timeout - * @private - */ - NaClManager.prototype.setTimeout_ = function(func, timeout) { - assert(!this.naclTimeoutId_, 'Timeout already exists'); - this.naclTimeoutId_ = window.setTimeout(function() { - this.naclTimeoutId_ = null; - func(); - }.bind(this), timeout); - }; - - /** - * Clears the current timeout. - * @private - */ - NaClManager.prototype.clearTimeout_ = function() { - window.clearTimeout(this.naclTimeoutId_); - this.naclTimeoutId_ = null; - }; - - /** - * Starts a stopped or stopping hotword recognizer (NaCl plugin). - * @param {hotword.constants.RecognizerStartMode} mode The mode to start the - * recognizer in. - */ - NaClManager.prototype.startRecognizer = function(mode) { - this.startMode_ = mode; - if (this.recognizerState_ == ManagerState_.STOPPED) { - this.preambleLog_ = null; - this.recognizerState_ = ManagerState_.STARTING; - if (mode == hotword.constants.RecognizerStartMode.NEW_MODEL) { - hotword.debug('Starting Recognizer in START training mode'); - this.sendDataToPlugin_( - hotword.constants.NaClPlugin.BEGIN_SPEAKER_MODEL); - } else if (mode == hotword.constants.RecognizerStartMode.ADAPT_MODEL) { - hotword.debug('Starting Recognizer in ADAPT training mode'); - this.sendDataToPlugin_( - hotword.constants.NaClPlugin.ADAPT_SPEAKER_MODEL); - } else { - hotword.debug('Starting Recognizer in NORMAL mode'); - this.sendDataToPlugin_(hotword.constants.NaClPlugin.RESTART); - } - // Normally, there would be a waitForMessage_(READY_FOR_AUDIO) here. - // However, this message is sent the first time audio data is read and in - // some cases (ie. using the hotword stream), this won't happen until a - // potential hotword trigger is seen. Having a waitForMessage_() would - // time - // out in this case, so just leave it out. This ends up sacrificing a bit - // of - // error detection in the non-hotword-stream case, but I think we can live - // with that. - } else if (this.recognizerState_ == ManagerState_.STOPPING) { - // Wait until the plugin is stopped before trying to start it. - this.restartOnStop_ = true; - } else { - throw 'Attempting to start NaCl recogniser not in STOPPED or STOPPING ' + - 'state'; - } - }; - - /** - * Stops the hotword recognizer. - */ - NaClManager.prototype.stopRecognizer = function() { - if (this.recognizerState_ == ManagerState_.STARTING) { - // If the recognizer is stopped before it finishes starting, it causes an - // assertion to be raised in waitForMessage_() since we're waiting for the - // READY_FOR_AUDIO message. Clear the current timeout and expecting - // message - // since we no longer expect it and may never receive it. - this.clearTimeout_(); - this.expectingMessage_ = null; - } - this.sendDataToPlugin_(hotword.constants.NaClPlugin.STOP); - this.recognizerState_ = ManagerState_.STOPPING; - this.waitForMessage_( - hotword.constants.TimeoutMs.NORMAL, - hotword.constants.NaClPlugin.STOPPED); - }; - - /** - * Saves the speaker model. - */ - NaClManager.prototype.finalizeSpeakerModel = function() { - if (this.recognizerState_ == ManagerState_.UNINITIALIZED || - this.recognizerState_ == ManagerState_.ERROR || - this.recognizerState_ == ManagerState_.SHUTDOWN || - this.recognizerState_ == ManagerState_.LOADING) { - return; - } - this.sendDataToPlugin_(hotword.constants.NaClPlugin.FINISH_SPEAKER_MODEL); - }; - - /** - * Checks whether the file at the given path exists. - * @param {!string} path Path to a file. Can be any valid URL. - * @return {boolean} True if the patch exists. - * @private - */ - NaClManager.prototype.fileExists_ = function(path) { - var xhr = new XMLHttpRequest(); - xhr.open('HEAD', path, false); - try { - xhr.send(); - } catch (err) { - return false; - } - if (xhr.readyState != xhr.DONE || xhr.status != 200) { - return false; - } - return true; - }; - - /** - * Creates and returns a list of possible languages to check for hotword - * support. - * @return {!Array<string>} Array of languages. - * @private - */ - NaClManager.prototype.getPossibleLanguages_ = function() { - // Create array used to search first for language-country, if not found then - // search for language, if not found then no language (empty string). - // For example, search for 'en-us', then 'en', then ''. - var langs = new Array(); - if (hotword.constants.UI_LANGUAGE) { - // Chrome webstore doesn't support uppercase path: crbug.com/353407 - var language = hotword.constants.UI_LANGUAGE.toLowerCase(); - langs.push(language); // Example: 'en-us'. - // Remove country to add just the language to array. - var hyphen = language.lastIndexOf('-'); - if (hyphen >= 0) { - langs.push(language.substr(0, hyphen)); // Example: 'en'. - } - } - langs.push(''); - return langs; - }; - - /** - * Creates a NaCl plugin object and attaches it to the page. - * @param {!string} src Location of the plugin. - * @return {!HTMLEmbedElement} NaCl plugin DOM object. - * @private - */ - NaClManager.prototype.createPlugin_ = function(src) { - var plugin = - /** @type {HTMLEmbedElement} */ (document.createElement('embed')); - plugin.src = src; - plugin.type = 'application/x-nacl'; - document.body.appendChild(plugin); - return plugin; - }; - - /** - * Initializes the NaCl manager. - * @param {!string} naclArch Either 'arm', 'x86-32' or 'x86-64'. - * @param {!MediaStream} stream A stream containing an audio source track. - * @return {boolean} True if the successful. - */ - NaClManager.prototype.initialize = function(naclArch, stream) { - assert( - this.recognizerState_ == ManagerState_.UNINITIALIZED, - 'Recognizer not in uninitialized state. State: ' + - this.recognizerState_); - assert(this.plugin_ == null); - var langs = this.getPossibleLanguages_(); - var i, j; - // For country-lang variations. For example, when combined with path it will - // attempt to find: '/x86-32_en-gb/', else '/x86-32_en/', else '/x86-32_/'. - for (i = 0; i < langs.length; i++) { - var folder = hotword.constants.SHARED_MODULE_ROOT + - '/_platform_specific/' + naclArch + '_' + langs[i] + '/'; - var dataSrc = folder + hotword.constants.File.RECOGNIZER_CONFIG; - var pluginSrc = hotword.constants.SHARED_MODULE_ROOT + '/hotword_' + - langs[i] + '.nmf'; - var dataExists = this.fileExists_(dataSrc) && this.fileExists_(pluginSrc); - if (!dataExists) { - continue; - } - - var plugin = this.createPlugin_(pluginSrc); - if (!plugin || !plugin.postMessage) { - document.body.removeChild(plugin); - this.recognizerState_ = ManagerState_.ERROR; - return false; - } - this.plugin_ = plugin; - this.modelUrl_ = chrome.extension.getURL(dataSrc); - this.stream_ = stream; - this.recognizerState_ = ManagerState_.LOADING; - - plugin.addEventListener( - 'message', this.handlePluginMessage_.bind(this), false); - - plugin.addEventListener('crash', function() { - this.handleError_(Error_.NACL_CRASH); - this.logPluginLoadResult_(UmaNaClPluginLoadResult_.CRASH); - }.bind(this), false); - return true; - } - this.recognizerState_ = ManagerState_.ERROR; - this.logPluginLoadResult_(UmaNaClPluginLoadResult_.NO_MODULE_FOUND); - return false; - }; - - /** - * Shuts down the NaCl plugin and frees all resources. - */ - NaClManager.prototype.shutdown = function() { - if (this.plugin_ != null) { - document.body.removeChild(this.plugin_); - this.plugin_ = null; - } - this.clearTimeout_(); - this.recognizerState_ = ManagerState_.SHUTDOWN; - if (this.stream_) - this.stream_.getAudioTracks()[0].stop(); - this.stream_ = null; - }; - - /** - * Sends data to the NaCl plugin. - * @param {!string|!MediaStreamTrack} data Command to be sent to NaCl plugin. - * @private - */ - NaClManager.prototype.sendDataToPlugin_ = function(data) { - assert( - this.recognizerState_ != ManagerState_.UNINITIALIZED, - 'Recognizer in uninitialized state'); - this.plugin_.postMessage(data); - }; - - /** - * Waits, with a timeout, for a message to be received from the plugin. If the - * message is not seen within the timeout, dispatch an 'error' event and go - * into - * the ERROR state. - * @param {number} timeout Timeout, in milliseconds, to wait for the message. - * @param {!string} message Message to wait for. - * @private - */ - NaClManager.prototype.waitForMessage_ = function(timeout, message) { - assert( - this.expectingMessage_ == null, - 'Cannot wait for message: ' + message + - ', already waiting for message ' + this.expectingMessage_); - this.setTimeout_(function() { - this.recognizerState_ = ManagerState_.ERROR; - this.handleError_(Error_.TIMEOUT); - switch (this.expectingMessage_) { - case hotword.constants.NaClPlugin.REQUEST_MODEL: - var metricValue = UmaNaClMessageTimeout_.REQUEST_MODEL; - break; - case hotword.constants.NaClPlugin.MODEL_LOADED: - var metricValue = UmaNaClMessageTimeout_.MODEL_LOADED; - break; - case hotword.constants.NaClPlugin.READY_FOR_AUDIO: - var metricValue = UmaNaClMessageTimeout_.READY_FOR_AUDIO; - break; - case hotword.constants.NaClPlugin.STOPPED: - var metricValue = UmaNaClMessageTimeout_.STOPPED; - break; - case hotword.constants.NaClPlugin.HOTWORD_DETECTED: - var metricValue = UmaNaClMessageTimeout_.HOTWORD_DETECTED; - break; - case hotword.constants.NaClPlugin.MS_CONFIGURED: - var metricValue = UmaNaClMessageTimeout_.MS_CONFIGURED; - break; - } - hotword.metrics.recordEnum( - hotword.constants.UmaMetrics.NACL_MESSAGE_TIMEOUT, metricValue, - UmaNaClMessageTimeout_.MAX); - }.bind(this), timeout); - this.expectingMessage_ = message; - }; - - /** - * Called when a message is received from the plugin. If we're waiting for - * that - * message, cancel the pending timeout. - * @param {string} message Message received. - * @private - */ - NaClManager.prototype.receivedMessage_ = function(message) { - if (message == this.expectingMessage_) { - this.clearTimeout_(); - this.expectingMessage_ = null; - } - }; - - /** - * Handle a REQUEST_MODEL message from the plugin. - * The plugin sends this message immediately after starting. - * @private - */ - NaClManager.prototype.handleRequestModel_ = function() { - if (this.recognizerState_ != ManagerState_.LOADING) { - return; - } - this.logPluginLoadResult_(UmaNaClPluginLoadResult_.SUCCESS); - this.sendDataToPlugin_( - hotword.constants.NaClPlugin.MODEL_PREFIX + this.modelUrl_); - this.waitForMessage_( - hotword.constants.TimeoutMs.LONG, - hotword.constants.NaClPlugin.MODEL_LOADED); - - // Configure logging in the plugin. This can be configured any time before - // starting the recognizer, and now is as good a time as any. - if (this.loggingEnabled_) { - this.sendDataToPlugin_( - hotword.constants.NaClPlugin.LOG + ':' + - hotword.constants.AUDIO_LOG_SECONDS); - } - - // If the audio stream is from a hotword stream, tell the plugin. - if (this.hotwordStream_) { - this.sendDataToPlugin_( - hotword.constants.NaClPlugin.DSP + ':' + - hotword.constants.HOTWORD_STREAM_TIMEOUT_SECONDS); - } - }; - - /** - * Handle a MODEL_LOADED message from the plugin. - * The plugin sends this message after successfully loading the language - * model. - * @private - */ - NaClManager.prototype.handleModelLoaded_ = function() { - if (this.recognizerState_ != ManagerState_.LOADING) { - return; - } - this.sendDataToPlugin_(this.stream_.getAudioTracks()[0]); - // The plugin will send a MS_CONFIGURED, but don't set a timeout waiting for - // it. MediaStreamAudioTrack::Configure() will remain pending until the - // first - // audio buffer is received. When the audio source is a DSP for always-on - // detection, no audio sample is sent until the DSP detects a potential - // hotword trigger. Thus, Configure would remain pending indefinitely if we - // were to wait here. See https://crbug.com/616203 - }; - - /** - * Handle a MS_CONFIGURED message from the plugin. - * The plugin sends this message after successfully configuring the audio - * input - * stream. - * @private - */ - NaClManager.prototype.handleMsConfigured_ = function() { - if (this.recognizerState_ != ManagerState_.LOADING) { - return; - } - this.recognizerState_ = ManagerState_.STOPPED; - this.dispatchEvent(new Event(hotword.constants.Event.READY)); - }; - - /** - * Handle a READY_FOR_AUDIO message from the plugin. - * The plugin sends this message after the recognizer is started and - * successfully receives and processes audio data. - * @private - */ - NaClManager.prototype.handleReadyForAudio_ = function() { - if (this.recognizerState_ != ManagerState_.STARTING) { - return; - } - this.recognizerState_ = ManagerState_.RUNNING; - }; - - /** - * Handle a HOTWORD_DETECTED message from the plugin. - * The plugin sends this message after detecting the hotword. - * @private - */ - NaClManager.prototype.handleHotwordDetected_ = function() { - if (this.recognizerState_ != ManagerState_.RUNNING) { - return; - } - // We'll receive a STOPPED message very soon. - this.recognizerState_ = ManagerState_.STOPPING; - this.waitForMessage_( - hotword.constants.TimeoutMs.NORMAL, - hotword.constants.NaClPlugin.STOPPED); - var event = new Event(hotword.constants.Event.TRIGGER); - event.log = this.preambleLog_; - this.dispatchEvent(event); - }; - - /** - * Handle a STOPPED message from the plugin. - * This plugin sends this message after stopping the recognizer. This can - * happen - * either in response to a stop request, or after the hotword is detected. - * @private - */ - NaClManager.prototype.handleStopped_ = function() { - this.recognizerState_ = ManagerState_.STOPPED; - if (this.restartOnStop_) { - this.restartOnStop_ = false; - this.startRecognizer(this.startMode_); - } - }; - - /** - * Handle a TIMEOUT message from the plugin. - * The plugin sends this message when it thinks the stream is from a DSP and - * a hotword wasn't detected within a timeout period after arrival of the - * first - * audio samples. - * @private - */ - NaClManager.prototype.handleTimeout_ = function() { - if (this.recognizerState_ != ManagerState_.RUNNING) { - return; - } - this.recognizerState_ = ManagerState_.STOPPED; - this.dispatchEvent(new Event(hotword.constants.Event.TIMEOUT)); - }; - - /** - * Handle a SPEAKER_MODEL_SAVED message from the plugin. - * The plugin sends this message after writing the model to a file. - * @private - */ - NaClManager.prototype.handleSpeakerModelSaved_ = function() { - this.dispatchEvent(new Event(hotword.constants.Event.SPEAKER_MODEL_SAVED)); - }; - - /** - * Handles a message from the NaCl plugin. - * @param {!Event} msg Message from NaCl plugin. - * @private - */ - NaClManager.prototype.handlePluginMessage_ = function(msg) { - if (msg['data']) { - if (typeof(msg['data']) == 'object') { - // Save the preamble for delivery to the trigger handler when the - // trigger - // message arrives. - this.preambleLog_ = msg['data']; - return; - } - this.receivedMessage_(msg['data']); - switch (msg['data']) { - case hotword.constants.NaClPlugin.REQUEST_MODEL: - this.handleRequestModel_(); - break; - case hotword.constants.NaClPlugin.MODEL_LOADED: - this.handleModelLoaded_(); - break; - case hotword.constants.NaClPlugin.MS_CONFIGURED: - this.handleMsConfigured_(); - break; - case hotword.constants.NaClPlugin.READY_FOR_AUDIO: - this.handleReadyForAudio_(); - break; - case hotword.constants.NaClPlugin.HOTWORD_DETECTED: - this.handleHotwordDetected_(); - break; - case hotword.constants.NaClPlugin.STOPPED: - this.handleStopped_(); - break; - case hotword.constants.NaClPlugin.TIMEOUT: - this.handleTimeout_(); - break; - case hotword.constants.NaClPlugin.SPEAKER_MODEL_SAVED: - this.handleSpeakerModelSaved_(); - break; - } - } - }; - - return {NaClManager: NaClManager}; - -});
diff --git a/chrome/browser/resources/hotword/page_audio_manager.js b/chrome/browser/resources/hotword/page_audio_manager.js deleted file mode 100644 index 8c8c928..0000000 --- a/chrome/browser/resources/hotword/page_audio_manager.js +++ /dev/null
@@ -1,541 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -cr.define('hotword', function() { - 'use strict'; - - /** - * Class used to manage the interaction between hotwording and the - * NTP/google.com. Injects a content script to interact with NTP/google.com - * and updates the global hotwording state based on interaction with those - * pages. - * @param {!hotword.StateManager} stateManager - * @constructor - */ - function PageAudioManager(stateManager) { - /** - * Manager of global hotwording state. - * @private {!hotword.StateManager} - */ - this.stateManager_ = stateManager; - - /** - * Mapping between tab ID and port that is connected from the injected - * content script. - * @private {!Object<number, Port>} - */ - this.portMap_ = {}; - - /** - * Chrome event listeners. Saved so that they can be de-registered when - * hotwording is disabled. - */ - this.connectListener_ = this.handleConnect_.bind(this); - this.tabCreatedListener_ = this.handleCreatedTab_.bind(this); - this.tabUpdatedListener_ = this.handleUpdatedTab_.bind(this); - this.tabActivatedListener_ = this.handleActivatedTab_.bind(this); - this.microphoneStateChangedListener_ = - this.handleMicrophoneStateChanged_.bind(this); - this.windowFocusChangedListener_ = this.handleChangedWindow_.bind(this); - this.messageListener_ = this.handleMessageFromPage_.bind(this); - - // Need to setup listeners on startup, otherwise events that caused the - // event page to start up, will be lost. - this.setupListeners_(); - - this.stateManager_.onStatusChanged.addListener(function() { - this.updateListeners_(); - this.updateTabState_(); - }.bind(this)); - } - - var CommandToPage = hotword.constants.CommandToPage; - var CommandFromPage = hotword.constants.CommandFromPage; - - PageAudioManager.prototype = { - /** - * Helper function to test if a URL path is eligible for hotwording. - * @param {!string} url URL to check. - * @param {!string} base Base URL to compare against.. - * @return {boolean} True if url is an eligible hotword URL. - * @private - */ - checkUrlPathIsEligible_: function(url, base) { - if (url == base || url == base + '/' || - url.startsWith(base + '/_/chrome/newtab?') || // Appcache NTP. - url.startsWith(base + '/?') || url.startsWith(base + '/#') || - url.startsWith(base + '/webhp') || url.startsWith(base + '/search') || - url.startsWith(base + '/imghp')) { - return true; - } - return false; - }, - - /** - * Determines if a URL is eligible for hotwording. For now, the valid pages - * are the Google HP and SERP (this will include the NTP). - * @param {!string} url URL to check. - * @return {boolean} True if url is an eligible hotword URL. - * @private - */ - isEligibleUrl_: function(url) { - if (!url) - return false; - - var baseGoogleUrls = [ - 'https://encrypted.google.', 'https://images.google.', - 'https://www.google.' - ]; - // TODO(amistry): Get this list from a file in the shared module instead. - var tlds = [ - 'at', 'ca', 'com', 'com.au', 'com.mx', 'com.br', 'co.jp', 'co.kr', - 'co.nz', 'co.uk', 'co.za', 'de', 'es', 'fr', 'it', 'ru' - ]; - - // Check for the new tab page first. - if (this.checkUrlPathIsEligible_(url, 'chrome://newtab')) - return true; - - // Check URLs with each type of local-based TLD. - for (var i = 0; i < baseGoogleUrls.length; i++) { - for (var j = 0; j < tlds.length; j++) { - var base = baseGoogleUrls[i] + tlds[j]; - if (this.checkUrlPathIsEligible_(url, base)) - return true; - } - } - return false; - }, - - /** - * Locates the current active tab in the current focused window and - * performs a callback with the tab as the parameter. - * @param {function(?Tab)} callback Function to call with the - * active tab or null if not found. The function's |this| will be set to - * this object. - * @private - */ - findCurrentTab_: function(callback) { - chrome.windows.getAll({'populate': true}, function(windows) { - for (var i = 0; i < windows.length; ++i) { - if (!windows[i].focused) - continue; - - for (var j = 0; j < windows[i].tabs.length; ++j) { - var tab = windows[i].tabs[j]; - if (tab.active) { - callback.call(this, tab); - return; - } - } - } - callback.call(this, null); - }.bind(this)); - }, - - /** - * This function is called when a tab is activated (comes into focus). - * @param {Tab} tab Current active tab. - * @private - */ - activateTab_: function(tab) { - if (!tab) { - this.stopHotwording_(); - return; - } - if (tab.id in this.portMap_) { - this.startHotwordingIfEligible_(); - return; - } - this.stopHotwording_(); - this.prepareTab_(tab); - }, - - /** - * Prepare a new or updated tab by injecting the content script. - * @param {!Tab} tab Newly updated or created tab. - * @private - */ - prepareTab_: function(tab) { - if (!this.isEligibleUrl_(tab.url)) - return; - - chrome.tabs.executeScript( - tab.id, {'file': 'audio_client.js'}, function(results) { - if (chrome.runtime.lastError) { - // Ignore this error. For new tab pages, even though the URL is - // reported to be chrome://newtab/, the actual URL is a - // country-specific google domain. Since we don't have permission - // to inject on every page, an error will happen when the user is - // in an unsupported country. - // - // The property still needs to be accessed so that the error - // condition is cleared. If it isn't, exectureScript will log an - // error the next time it is called. - } - }); - }, - - /** - * Updates hotwording state based on the state of current tabs/windows. - * @private - */ - updateTabState_: function() { - this.findCurrentTab_(this.activateTab_); - }, - - /** - * Handles a newly created tab. - * @param {!Tab} tab Newly created tab. - * @private - */ - handleCreatedTab_: function(tab) { - this.prepareTab_(tab); - }, - - /** - * Handles an updated tab. - * @param {number} tabId Id of the updated tab. - * @param {{status: string}} info Change info of the tab. - * @param {!Tab} tab Updated tab. - * @private - */ - handleUpdatedTab_: function(tabId, info, tab) { - // Chrome fires multiple update events: undefined, loading and completed. - // We perform content injection on loading state. - if (info['status'] != 'loading') - return; - - this.prepareTab_(tab); - }, - - /** - * Handles a tab that has just become active. - * @param {{tabId: number}} info Information about the activated tab. - * @private - */ - handleActivatedTab_: function(info) { - this.updateTabState_(); - }, - - /** - * Handles the microphone state changing. - * @param {boolean} enabled Whether the microphone is now enabled. - * @private - */ - handleMicrophoneStateChanged_: function(enabled) { - if (enabled) { - this.updateTabState_(); - return; - } - - this.stopHotwording_(); - }, - - /** - * Handles a change in Chrome windows. - * Note: this does not always trigger in Linux. - * @param {number} windowId Id of newly focused window. - * @private - */ - handleChangedWindow_: function(windowId) { - this.updateTabState_(); - }, - - /** - * Handles a content script attempting to connect. - * @param {!Port} port Communications port from the client. - * @private - */ - handleConnect_: function(port) { - if (port.name != hotword.constants.CLIENT_PORT_NAME) - return; - - var tab = /** @type {!Tab} */ (port.sender.tab); - // An existing port from the same tab might already exist. But that port - // may be from the previous page, so just overwrite the port. - this.portMap_[tab.id] = port; - port.onDisconnect.addListener(function() { - this.handleClientDisconnect_(port); - }.bind(this)); - port.onMessage.addListener(function(msg) { - this.handleMessage_(msg, port.sender, port.postMessage); - }.bind(this)); - }, - - /** - * Handles a client content script disconnect. - * @param {Port} port Disconnected port. - * @private - */ - handleClientDisconnect_: function(port) { - var tabId = port.sender.tab.id; - if (tabId in this.portMap_ && this.portMap_[tabId] == port) { - // Due to a race between port disconnection and tabs.onUpdated messages, - // the port could have changed. - delete this.portMap_[port.sender.tab.id]; - } - this.stopHotwordingIfIneligibleTab_(); - }, - - /** - * Disconnect all connected clients. - * @private - */ - disconnectAllClients_: function() { - for (var id in this.portMap_) { - var port = this.portMap_[id]; - port.disconnect(); - delete this.portMap_[id]; - } - }, - - /** - * Sends a command to the client content script on an eligible tab. - * @param {hotword.constants.CommandToPage} command Command to send. - * @param {number} tabId Id of the target tab. - * @private - */ - sendClient_: function(command, tabId) { - if (tabId in this.portMap_) { - var message = {}; - message[hotword.constants.COMMAND_FIELD_NAME] = command; - this.portMap_[tabId].postMessage(message); - } - }, - - /** - * Sends a command to all connected clients. - * @param {hotword.constants.CommandToPage} command Command to send. - * @private - */ - sendAllClients_: function(command) { - for (var idStr in this.portMap_) { - var id = parseInt(idStr, 10); - assert(!isNaN(id), 'Tab ID is not a number: ' + idStr); - this.sendClient_(command, id); - } - }, - - /** - * Handles a hotword trigger. Sends a trigger message to the currently - * active tab. - * @private - */ - hotwordTriggered_: function() { - this.findCurrentTab_(function(tab) { - if (tab) - this.sendClient_(CommandToPage.HOTWORD_VOICE_TRIGGER, tab.id); - }); - }, - - /** - * Starts hotwording. - * @private - */ - startHotwording_: function() { - this.stateManager_.startSession( - hotword.constants.SessionSource.NTP, function() { - this.sendAllClients_(CommandToPage.HOTWORD_STARTED); - }.bind(this), this.hotwordTriggered_.bind(this)); - }, - - /** - * Starts hotwording if the currently active tab is eligible for hotwording - * (e.g. google.com). - * @private - */ - startHotwordingIfEligible_: function() { - this.findCurrentTab_(function(tab) { - if (!tab) { - this.stopHotwording_(); - return; - } - if (this.isEligibleUrl_(tab.url)) - this.startHotwording_(); - }); - }, - - /** - * Stops hotwording. - * @private - */ - stopHotwording_: function() { - this.stateManager_.stopSession(hotword.constants.SessionSource.NTP); - this.sendAllClients_(CommandToPage.HOTWORD_ENDED); - }, - - /** - * Stops hotwording if the currently active tab is not eligible for - * hotwording (i.e. google.com). - * @private - */ - stopHotwordingIfIneligibleTab_: function() { - this.findCurrentTab_(function(tab) { - if (!tab) { - this.stopHotwording_(); - return; - } - if (!this.isEligibleUrl_(tab.url)) - this.stopHotwording_(); - }); - }, - - /** - * Handles a message from the content script injected into the page. - * @param {!Object} request Request from the content script. - * @param {!MessageSender} sender Message sender. - * @param {!function(Object)} sendResponse Function for sending a response. - * @private - */ - handleMessage_: function(request, sender, sendResponse) { - switch (request[hotword.constants.COMMAND_FIELD_NAME]) { - // TODO(amistry): Handle other messages such as CLICKED_RESUME and - // CLICKED_RESTART, if necessary. - case CommandFromPage.SPEECH_START: - this.stopHotwording_(); - break; - case CommandFromPage.SPEECH_END: - case CommandFromPage.SPEECH_RESET: - this.startHotwording_(); - break; - } - }, - - - /** - * Handles a message directly from the NTP/HP/SERP. - * @param {!Object} request Message from the sender. - * @param {!MessageSender} sender Information about the sender. - * @param {!function(HotwordStatus)} sendResponse Callback to respond - * to sender. - * @return {boolean} Whether to maintain the port open to call sendResponse. - * @private - */ - handleMessageFromPage_: function(request, sender, sendResponse) { - switch (request.type) { - case CommandFromPage.PAGE_WAKEUP: - if (sender.tab && this.isEligibleUrl_(sender.tab.url)) { - chrome.hotwordPrivate.getStatus( - true /* getOptionalFields */, - this.statusDone_.bind( - this, request.tab || sender.tab || {incognito: true}, - sendResponse)); - return true; - } - - // Do not show the opt-in promo for ineligible urls. - this.sendResponse_({'doNotShowOptinMessage': true}, sendResponse); - break; - case CommandFromPage.CLICKED_OPTIN: - chrome.hotwordPrivate.setEnabled(true); - break; - // User has explicitly clicked 'no thanks'. - case CommandFromPage.CLICKED_NO_OPTIN: - chrome.hotwordPrivate.setEnabled(false); - break; - } - return false; - }, - - /** - * Sends a message directly to the sending page. - * @param {!HotwordStatus} response The response to send to the sender. - * @param {!function(HotwordStatus)} sendResponse Callback to respond - * to sender. - * @private - */ - sendResponse_: function(response, sendResponse) { - try { - sendResponse(response); - } catch (err) { - // Suppress the exception thrown by sendResponse() when the page doesn't - // specify a response callback in the call to - // chrome.runtime.sendMessage(). - // Unfortunately, there doesn't appear to be a way to detect one-way - // messages without explicitly saying in the message itself. This - // message is defined as a constant in - // extensions/renderer/messaging_bindings.cc - if (err.message == 'Attempting to use a disconnected port object') - return; - throw err; - } - }, - - /** - * Sends the response to the tab. - * @param {Tab} tab The tab that the request was sent from. - * @param {function(HotwordStatus)} sendResponse Callback function to - * respond to sender. - * @param {HotwordStatus} hotwordStatus Status of the hotword extension. - * @private - */ - statusDone_: function(tab, sendResponse, hotwordStatus) { - var response = {'doNotShowOptinMessage': true}; - - // If always-on is available, then we do not show the promo, as the promo - // only works with the sometimes-on pref. - if (!tab.incognito && hotwordStatus.available && - !hotwordStatus.enabledSet && !hotwordStatus.alwaysOnAvailable) { - response = hotwordStatus; - } - - this.sendResponse_(response, sendResponse); - }, - - /** - * Set up event listeners. - * @private - */ - setupListeners_: function() { - if (chrome.runtime.onConnect.hasListener(this.connectListener_)) - return; - - chrome.runtime.onConnect.addListener(this.connectListener_); - chrome.tabs.onCreated.addListener(this.tabCreatedListener_); - chrome.tabs.onUpdated.addListener(this.tabUpdatedListener_); - chrome.tabs.onActivated.addListener(this.tabActivatedListener_); - chrome.windows.onFocusChanged.addListener( - this.windowFocusChangedListener_); - chrome.hotwordPrivate.onMicrophoneStateChanged.addListener( - this.microphoneStateChangedListener_); - if (chrome.runtime.onMessage.hasListener(this.messageListener_)) - return; - chrome.runtime.onMessageExternal.addListener(this.messageListener_); - }, - - /** - * Remove event listeners. - * @private - */ - removeListeners_: function() { - chrome.runtime.onConnect.removeListener(this.connectListener_); - chrome.tabs.onCreated.removeListener(this.tabCreatedListener_); - chrome.tabs.onUpdated.removeListener(this.tabUpdatedListener_); - chrome.tabs.onActivated.removeListener(this.tabActivatedListener_); - chrome.windows.onFocusChanged.removeListener( - this.windowFocusChangedListener_); - chrome.hotwordPrivate.onMicrophoneStateChanged.removeListener( - this.microphoneStateChangedListener_); - // Don't remove the Message listener, as we want them listening all - // the time, - }, - - /** - * Update event listeners based on the current hotwording state. - * @private - */ - updateListeners_: function() { - if (this.stateManager_.isSometimesOnEnabled()) { - this.setupListeners_(); - } else { - this.removeListeners_(); - this.stopHotwording_(); - this.disconnectAllClients_(); - } - } - }; - - return {PageAudioManager: PageAudioManager}; -});
diff --git a/chrome/browser/resources/hotword/state_manager.js b/chrome/browser/resources/hotword/state_manager.js deleted file mode 100644 index 98e0a5c..0000000 --- a/chrome/browser/resources/hotword/state_manager.js +++ /dev/null
@@ -1,641 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -cr.define('hotword', function() { - 'use strict'; - - /** - * Trivial container class for session information. - * @param {!hotword.constants.SessionSource} source Source of the hotword - * session. - * @param {!function()} triggerCb Callback invoked when the hotword has - * triggered. - * @param {!function()} startedCb Callback invoked when the session has - * been started successfully. - * @param {function()=} opt_modelSavedCb Callback invoked when the speaker - * model has been saved successfully. - * @constructor - * @struct - * @private - */ - function Session_(source, triggerCb, startedCb, opt_modelSavedCb) { - /** - * Source of the hotword session request. - * @private {!hotword.constants.SessionSource} - */ - this.source_ = source; - - /** - * Callback invoked when the hotword has triggered. - * @private {!function()} - */ - this.triggerCb_ = triggerCb; - - /** - * Callback invoked when the session has been started successfully. - * @private {?function()} - */ - this.startedCb_ = startedCb; - - /** - * Callback invoked when the session has been started successfully. - * @private {?function()} - */ - this.speakerModelSavedCb_ = opt_modelSavedCb; - } - - /** - * Class to manage hotwording state. Starts/stops the hotword detector based - * on user settings, session requests, and any other factors that play into - * whether or not hotwording should be running. - * @constructor - */ - function StateManager() { - /** - * Current state. - * @private {hotword.StateManager.State_} - */ - this.state_ = State_.STOPPED; - - /** - * Current hotwording status. - * @private {?chrome.hotwordPrivate.StatusDetails} - */ - this.hotwordStatus_ = null; - - /** - * NaCl plugin manager. - * @private {?hotword.NaClManager} - */ - this.pluginManager_ = null; - - /** - * Currently active hotwording sessions. - * @private {!Array<Session_>} - */ - this.sessions_ = []; - - /** - * The mode to start the recognizer in. - * @private {!hotword.constants.RecognizerStartMode} - */ - this.startMode_ = hotword.constants.RecognizerStartMode.NORMAL; - - /** - * Event that fires when the hotwording status has changed. - * @type {!ChromeEvent} - */ - this.onStatusChanged = new chrome.Event(); - - /** - * Hotword trigger audio notification... a.k.a The Chime (tm). - * @private {!HTMLAudioElement} - */ - this.chime_ = - /** @type {!HTMLAudioElement} */ (document.createElement('audio')); - - /** - * Chrome event listeners. Saved so that they can be de-registered when - * hotwording is disabled. - * @private - */ - this.idleStateChangedListener_ = this.handleIdleStateChanged_.bind(this); - this.startupListener_ = this.handleStartup_.bind(this); - - /** - * Whether this user is locked. - * @private {boolean} - */ - this.isLocked_ = false; - - /** - * Current state of audio logging. - * This is tracked separately from hotwordStatus_ because we need to restart - * the hotword detector when this value changes. - * @private {boolean} - */ - this.loggingEnabled_ = false; - - /** - * Current state of training. - * This is tracked separately from |hotwordStatus_| because we need to - * restart the hotword detector when this value changes. - * @private {!boolean} - */ - this.trainingEnabled_ = false; - - /** - * Helper class to keep this extension alive while the hotword detector is - * running in always-on mode. - * @private {!hotword.KeepAlive} - */ - this.keepAlive_ = new hotword.KeepAlive(); - - // Get the initial status. - chrome.hotwordPrivate.getStatus(this.handleStatus_.bind(this)); - - // Setup the chime and insert into the page. - // Set preload=none to prevent an audio output stream from being created - // when the extension loads. - this.chime_.preload = 'none'; - this.chime_.src = chrome.extension.getURL( - hotword.constants.SHARED_MODULE_ROOT + '/audio/chime.wav'); - document.body.appendChild(this.chime_); - - // In order to remove this listener, it must first be added. This handles - // the case on first Chrome startup where this event is never registered, - // so can't be removed when it's determined that hotwording is disabled. - // Why not only remove the listener if it exists? Extension API events have - // two parts to them, the Javascript listeners, and a browser-side component - // that wakes up the extension if it's an event page. The browser-side - // wake-up event is only removed when the number of javascript listeners - // becomes 0. To clear the browser wake-up event, a listener first needs to - // be added, then removed in order to drop the count to 0 and remove the - // event. - chrome.runtime.onStartup.addListener(this.startupListener_); - } - - /** - * @enum {number} - * @private - */ - StateManager.State_ = { - STOPPED: 0, - STARTING: 1, - RUNNING: 2, - ERROR: 3, - }; - var State_ = StateManager.State_; - - var UmaMediaStreamOpenResults_ = { - // These first error are defined by the MediaStream spec: - // http://w3c.github.io/mediacapture-main/getusermedia.html#idl-def-MediaStreamError - 'NotSupportedError': - hotword.constants.UmaMediaStreamOpenResult.NOT_SUPPORTED, - 'PermissionDeniedError': - hotword.constants.UmaMediaStreamOpenResult.PERMISSION_DENIED, - 'ConstraintNotSatisfiedError': - hotword.constants.UmaMediaStreamOpenResult.CONSTRAINT_NOT_SATISFIED, - 'OverconstrainedError': - hotword.constants.UmaMediaStreamOpenResult.OVERCONSTRAINED, - 'NotFoundError': hotword.constants.UmaMediaStreamOpenResult.NOT_FOUND, - 'AbortError': hotword.constants.UmaMediaStreamOpenResult.ABORT, - 'SourceUnavailableError': - hotword.constants.UmaMediaStreamOpenResult.SOURCE_UNAVAILABLE, - // The next few errors are chrome-specific. See: - // content/renderer/media/user_media_client_impl.cc - // (UserMediaClientImpl::GetUserMediaRequestFailed) - 'PermissionDismissedError': - hotword.constants.UmaMediaStreamOpenResult.PERMISSION_DISMISSED, - 'InvalidStateError': - hotword.constants.UmaMediaStreamOpenResult.INVALID_STATE, - 'DevicesNotFoundError': - hotword.constants.UmaMediaStreamOpenResult.DEVICES_NOT_FOUND, - 'InvalidSecurityOriginError': - hotword.constants.UmaMediaStreamOpenResult.INVALID_SECURITY_ORIGIN - }; - - var UmaTriggerSources_ = { - 'launcher': hotword.constants.UmaTriggerSource.LAUNCHER, - 'ntp': hotword.constants.UmaTriggerSource.NTP_GOOGLE_COM, - 'always': hotword.constants.UmaTriggerSource.ALWAYS_ON, - 'training': hotword.constants.UmaTriggerSource.TRAINING - }; - - StateManager.prototype = { - /** - * Request status details update. Intended to be called from the - * hotwordPrivate.onEnabledChanged() event. - */ - updateStatus: function() { - chrome.hotwordPrivate.getStatus(this.handleStatus_.bind(this)); - }, - - /** - * @return {boolean} True if google.com/NTP/launcher hotwording is enabled. - */ - isSometimesOnEnabled: function() { - assert( - this.hotwordStatus_, 'No hotwording status (isSometimesOnEnabled)'); - // Although the two settings are supposed to be mutually exclusive, it's - // possible for both to be set. In that case, always-on takes precedence. - return this.hotwordStatus_.enabled && - !this.hotwordStatus_.alwaysOnEnabled; - }, - - /** - * @return {boolean} True if always-on hotwording is enabled. - */ - isAlwaysOnEnabled: function() { - assert(this.hotwordStatus_, 'No hotword status (isAlwaysOnEnabled)'); - return this.hotwordStatus_.alwaysOnEnabled && - !this.hotwordStatus_.trainingEnabled; - }, - - /** - * @return {boolean} True if training is enabled. - */ - isTrainingEnabled: function() { - assert(this.hotwordStatus_, 'No hotword status (isTrainingEnabled)'); - return this.hotwordStatus_.trainingEnabled; - }, - - /** - * Callback for hotwordPrivate.getStatus() function. - * @param {chrome.hotwordPrivate.StatusDetails} status Current hotword - * status. - * @private - */ - handleStatus_: function(status) { - hotword.debug('New hotword status', status); - this.hotwordStatus_ = status; - this.updateStateFromStatus_(); - - this.onStatusChanged.dispatch(); - }, - - /** - * Updates state based on the current status. - * @private - */ - updateStateFromStatus_: function() { - if (!this.hotwordStatus_) - return; - - if (this.hotwordStatus_.enabled || this.hotwordStatus_.alwaysOnEnabled || - this.hotwordStatus_.trainingEnabled) { - // Detect changes to audio logging and kill the detector if that setting - // has changed. - if (this.hotwordStatus_.audioLoggingEnabled != this.loggingEnabled_) - this.shutdownDetector_(); - this.loggingEnabled_ = this.hotwordStatus_.audioLoggingEnabled; - - // If the training state has changed, we need to first shut down the - // detector so that we can restart in a different mode. - if (this.hotwordStatus_.trainingEnabled != this.trainingEnabled_) - this.shutdownDetector_(); - this.trainingEnabled_ = this.hotwordStatus_.trainingEnabled; - - // Start the detector if there's a session and the user is unlocked, and - // stops it otherwise. - if (this.sessions_.length && !this.isLocked_ && - this.hotwordStatus_.userIsActive) { - this.startDetector_(); - } else { - this.shutdownDetector_(); - } - - if (!chrome.idle.onStateChanged.hasListener( - this.idleStateChangedListener_)) { - chrome.idle.onStateChanged.addListener( - this.idleStateChangedListener_); - } - if (!chrome.runtime.onStartup.hasListener(this.startupListener_)) - chrome.runtime.onStartup.addListener(this.startupListener_); - } else { - // Not enabled. Shut down if running. - this.shutdownDetector_(); - - chrome.idle.onStateChanged.removeListener( - this.idleStateChangedListener_); - // If hotwording isn't enabled, don't start this component extension on - // Chrome startup. If a user enables hotwording, the status change - // event will be fired and the onStartup event will be registered. - chrome.runtime.onStartup.removeListener(this.startupListener_); - } - }, - - /** - * Starts the hotword detector. - * @private - */ - startDetector_: function() { - // Last attempt to start detector resulted in an error. - if (this.state_ == State_.ERROR) { - // TODO(amistry): Do some error rate tracking here and disable the - // extension if we error too often. - } - - if (!this.pluginManager_) { - this.state_ = State_.STARTING; - var isHotwordStream = this.isAlwaysOnEnabled() && - this.hotwordStatus_.hotwordHardwareAvailable; - this.pluginManager_ = - new hotword.NaClManager(this.loggingEnabled_, isHotwordStream); - this.pluginManager_.addEventListener( - hotword.constants.Event.READY, this.onReady_.bind(this)); - this.pluginManager_.addEventListener( - hotword.constants.Event.ERROR, this.onError_.bind(this)); - this.pluginManager_.addEventListener( - hotword.constants.Event.TRIGGER, this.onTrigger_.bind(this)); - this.pluginManager_.addEventListener( - hotword.constants.Event.TIMEOUT, this.onTimeout_.bind(this)); - this.pluginManager_.addEventListener( - hotword.constants.Event.SPEAKER_MODEL_SAVED, - this.onSpeakerModelSaved_.bind(this)); - chrome.runtime.getPlatformInfo(function(platform) { - var naclArch = platform.nacl_arch; - - // googDucking set to false so that audio output level from other tabs - // is not affected when hotword is enabled. https://crbug.com/357773 - // content/common/media/media_stream_options.cc - // When always-on is enabled, request the hotword stream. - // Optional because we allow power users to bypass the hardware - // detection via a flag, and hence the hotword stream may not be - // available. - var constraints = /** @type {googMediaStreamConstraints} */ - ({ - audio: { - optional: [ - {googDucking: false}, - {googHotword: this.isAlwaysOnEnabled()} - ] - } - }); - navigator.webkitGetUserMedia( - /** @type {MediaStreamConstraints} */ (constraints), - function(stream) { - hotword.metrics.recordEnum( - hotword.constants.UmaMetrics.MEDIA_STREAM_RESULT, - hotword.constants.UmaMediaStreamOpenResult.SUCCESS, - hotword.constants.UmaMediaStreamOpenResult.MAX); - // The detector could have been shut down before the stream - // finishes opening. - if (this.pluginManager_ == null) { - stream.getAudioTracks()[0].stop(); - return; - } - - if (this.isAlwaysOnEnabled()) - this.keepAlive_.start(); - if (!this.pluginManager_.initialize(naclArch, stream)) { - this.state_ = State_.ERROR; - this.shutdownPluginManager_(); - } - }.bind(this), - function(error) { - if (error.name in UmaMediaStreamOpenResults_) { - var metricValue = UmaMediaStreamOpenResults_[error.name]; - } else { - var metricValue = - hotword.constants.UmaMediaStreamOpenResult.UNKNOWN; - } - hotword.metrics.recordEnum( - hotword.constants.UmaMetrics.MEDIA_STREAM_RESULT, - metricValue, - hotword.constants.UmaMediaStreamOpenResult.MAX); - this.state_ = State_.ERROR; - this.pluginManager_ = null; - }.bind(this)); - }.bind(this)); - } else if (this.state_ != State_.STARTING) { - // Don't try to start a starting detector. - this.startRecognizer_(); - } - }, - - /** - * Start the recognizer plugin. Assumes the plugin has been loaded and is - * ready to start. - * @private - */ - startRecognizer_: function() { - assert(this.pluginManager_, 'No NaCl plugin loaded'); - if (this.state_ != State_.RUNNING) { - this.state_ = State_.RUNNING; - if (this.isAlwaysOnEnabled()) - this.keepAlive_.start(); - this.pluginManager_.startRecognizer(this.startMode_); - } - for (var i = 0; i < this.sessions_.length; i++) { - var session = this.sessions_[i]; - if (session.startedCb_) { - session.startedCb_(); - session.startedCb_ = null; - } - } - }, - - /** - * Stops the hotword detector, if it's running. - * @private - */ - stopDetector_: function() { - this.keepAlive_.stop(); - if (this.pluginManager_ && this.state_ == State_.RUNNING) { - this.state_ = State_.STOPPED; - this.pluginManager_.stopRecognizer(); - } - }, - - /** - * Shuts down and removes the plugin manager, if it exists. - * @private - */ - shutdownPluginManager_: function() { - this.keepAlive_.stop(); - if (this.pluginManager_) { - this.pluginManager_.shutdown(); - this.pluginManager_ = null; - } - }, - - /** - * Shuts down the hotword detector. - * @private - */ - shutdownDetector_: function() { - this.state_ = State_.STOPPED; - this.shutdownPluginManager_(); - }, - - /** - * Finalizes the speaker model. Assumes the plugin has been loaded and - * started. - */ - finalizeSpeakerModel: function() { - assert( - this.pluginManager_, - 'Cannot finalize speaker model: No NaCl plugin loaded'); - if (this.state_ != State_.RUNNING) { - hotword.debug('Cannot finalize speaker model: NaCl plugin not started'); - return; - } - this.pluginManager_.finalizeSpeakerModel(); - }, - - /** - * Handle the hotword plugin being ready to start. - * @private - */ - onReady_: function() { - if (this.state_ != State_.STARTING) { - // At this point, we should not be in the RUNNING state. Doing so would - // imply the hotword detector was started without being ready. - assert(this.state_ != State_.RUNNING, 'Unexpected RUNNING state'); - this.shutdownPluginManager_(); - return; - } - this.startRecognizer_(); - }, - - /** - * Handle an error from the hotword plugin. - * @private - */ - onError_: function() { - this.state_ = State_.ERROR; - this.shutdownPluginManager_(); - }, - - /** - * Handle hotword triggering. - * @param {!Event} event Event containing audio log data. - * @private - */ - onTrigger_: function(event) { - this.keepAlive_.stop(); - hotword.debug('Hotword triggered!'); - chrome.metricsPrivate.recordUserAction( - hotword.constants.UmaMetrics.TRIGGER); - assert(this.pluginManager_, 'No NaCl plugin loaded on trigger'); - // Detector implicitly stops when the hotword is detected. - this.state_ = State_.STOPPED; - - // Play the chime. - this.chime_.play(); - - // Implicitly clear the top session. A session needs to be started in - // order to restart the detector. - if (this.sessions_.length) { - var session = this.sessions_.pop(); - session.triggerCb_(event.log); - - hotword.metrics.recordEnum( - hotword.constants.UmaMetrics.TRIGGER_SOURCE, - UmaTriggerSources_[session.source_], - hotword.constants.UmaTriggerSource.MAX); - } - - // If we're in always-on mode, shut down the hotword detector. The hotword - // stream requires that we close and re-open it after a trigger, and the - // only way to accomplish this is to shut everything down. - if (this.isAlwaysOnEnabled()) - this.shutdownDetector_(); - }, - - /** - * Handle hotword timeout. - * @private - */ - onTimeout_: function() { - hotword.debug('Hotword timeout!'); - - // We get this event when the hotword detector thinks there's a false - // trigger. In this case, we need to shut down and restart the detector to - // re-arm the DSP. - this.shutdownDetector_(); - this.updateStateFromStatus_(); - }, - - /** - * Handle speaker model saved. - * @private - */ - onSpeakerModelSaved_: function() { - hotword.debug('Speaker model saved!'); - - if (this.sessions_.length) { - // Only call the callback of the the top session. - var session = this.sessions_[this.sessions_.length - 1]; - if (session.speakerModelSavedCb_) - session.speakerModelSavedCb_(); - } - }, - - /** - * Remove a hotwording session from the given source. - * @param {!hotword.constants.SessionSource} source Source of the hotword - * session request. - * @private - */ - removeSession_: function(source) { - for (var i = 0; i < this.sessions_.length; i++) { - if (this.sessions_[i].source_ == source) { - this.sessions_.splice(i, 1); - break; - } - } - }, - - /** - * Start a hotwording session. - * @param {!hotword.constants.SessionSource} source Source of the hotword - * session request. - * @param {!function()} startedCb Callback invoked when the session has - * been started successfully. - * @param {!function()} triggerCb Callback invoked when the hotword has - * @param {function()=} modelSavedCb Callback invoked when the speaker model - * has been saved. - * @param {hotword.constants.RecognizerStartMode=} opt_mode The mode to - * start the recognizer in. - */ - startSession: function( - source, startedCb, triggerCb, opt_modelSavedCb, opt_mode) { - if (this.isTrainingEnabled() && opt_mode) { - this.startMode_ = opt_mode; - } else { - this.startMode_ = hotword.constants.RecognizerStartMode.NORMAL; - } - hotword.debug('Starting session for source: ' + source); - this.removeSession_(source); - this.sessions_.push( - new Session_(source, triggerCb, startedCb, opt_modelSavedCb)); - this.updateStateFromStatus_(); - }, - - /** - * Stops a hotwording session. - * @param {!hotword.constants.SessionSource} source Source of the hotword - * session request. - */ - stopSession: function(source) { - hotword.debug('Stopping session for source: ' + source); - this.removeSession_(source); - // If this is a training session then switch the start mode back to - // normal. - if (source == hotword.constants.SessionSource.TRAINING) - this.startMode_ = hotword.constants.RecognizerStartMode.NORMAL; - this.updateStateFromStatus_(); - }, - - /** - * Handles a chrome.idle.onStateChanged event. - * @param {!string} state State, one of "active", "idle", or "locked". - * @private - */ - handleIdleStateChanged_: function(state) { - hotword.debug('Idle state changed: ' + state); - var oldLocked = this.isLocked_; - if (state == 'locked') - this.isLocked_ = true; - else - this.isLocked_ = false; - - if (oldLocked != this.isLocked_) - this.updateStateFromStatus_(); - }, - - /** - * Handles a chrome.runtime.onStartup event. - * @private - */ - handleStartup_: function() { - // Nothing specific needs to be done here. This function exists solely to - // be registered on the startup event. - } - }; - - return {StateManager: StateManager}; -});
diff --git a/chrome/browser/resources/hotword/training_manager.js b/chrome/browser/resources/hotword/training_manager.js deleted file mode 100644 index f5b68d4..0000000 --- a/chrome/browser/resources/hotword/training_manager.js +++ /dev/null
@@ -1,201 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -cr.define('hotword', function() { - 'use strict'; - - /** - * Class used to manage speaker training. Starts a hotwording session - * if training is on, and automatically restarts the detector when a - * a hotword is triggered. - * @param {!hotword.StateManager} stateManager - * @constructor - * @extends {hotword.BaseSessionManager} - */ - function TrainingManager(stateManager) { - /** - * Chrome event listeners. Saved so that they can be de-registered when - * hotwording is disabled. - * @private - */ - this.finalizedSpeakerModelListener_ = - this.handleFinalizeSpeakerModel_.bind(this); - - hotword.BaseSessionManager.call( - this, stateManager, hotword.constants.SessionSource.TRAINING); - } - - /** - * Handles a success event on mounting the file system event and deletes - * the user data files. - * @param {FileSystem} fs The FileSystem object. - * @private - */ - TrainingManager.deleteFiles_ = function(fs) { - fs.root.getFile( - hotword.constants.SPEAKER_MODEL_FILE_NAME, {create: false}, - TrainingManager.deleteFile_, TrainingManager.fileErrorHandler_); - - for (var i = 0; i < hotword.constants.NUM_TRAINING_UTTERANCES; ++i) { - fs.root.getFile( - hotword.constants.UTTERANCE_FILE_PREFIX + i + - hotword.constants.UTTERANCE_FILE_EXTENSION, - {create: false}, TrainingManager.deleteFile_, - TrainingManager.fileErrorHandler_); - } - }; - - /** - * Deletes a file. - * @param {FileEntry} fileEntry The FileEntry object. - * @private - */ - TrainingManager.deleteFile_ = function(fileEntry) { - if (fileEntry.isFile) { - hotword.debug('File found: ' + fileEntry.fullPath); - if (hotword.DEBUG || window.localStorage['hotword.DEBUG']) { - fileEntry.getMetadata(function(md) { - hotword.debug('File size: ' + md.size); - }); - } - fileEntry.remove(function() { - hotword.debug('File removed: ' + fileEntry.fullPath); - }, TrainingManager.fileErrorHandler_); - } - }; - - /** - * Handles a failure event on mounting the file system event. - * @param {FileError} e The FileError object. - * @private - */ - TrainingManager.fileErrorHandler_ = function(e) { - hotword.debug('File error: ' + e.code); - }; - - /** - * Handles a failure event on checking for the existence of the speaker model. - * @param {FileError} e The FileError object. - * @private - */ - TrainingManager.sendNoSpeakerModelResponse_ = function(e) { - chrome.hotwordPrivate.speakerModelExistsResult(false); - }; - - /** - * Handles a success event on mounting the file system and checks for the - * existence of the speaker model. - * @param {FileSystem} fs The FileSystem object. - * @private - */ - TrainingManager.speakerModelExists_ = function(fs) { - fs.root.getFile( - hotword.constants.SPEAKER_MODEL_FILE_NAME, {create: false}, - TrainingManager.sendSpeakerModelExistsResponse_, - TrainingManager.sendNoSpeakerModelResponse_); - }; - - /** - * Sends a response through the HotwordPrivateApi indicating whether - * the speaker model exists. - * @param {FileEntry} fileEntry The FileEntry object. - * @private - */ - TrainingManager.sendSpeakerModelExistsResponse_ = function(fileEntry) { - if (fileEntry.isFile) { - hotword.debug('File found: ' + fileEntry.fullPath); - if (hotword.DEBUG || window.localStorage['hotword.DEBUG']) { - fileEntry.getMetadata(function(md) { - hotword.debug('File size: ' + md.size); - }); - } - } - chrome.hotwordPrivate.speakerModelExistsResult(fileEntry.isFile); - }; - - /** - * Handles a request to delete the speaker model. - */ - TrainingManager.handleDeleteSpeakerModel = function() { - window.webkitRequestFileSystem( - PERSISTENT, hotword.constants.FILE_SYSTEM_SIZE_BYTES, - TrainingManager.deleteFiles_, TrainingManager.fileErrorHandler_); - }; - - /** - * Handles a request for the speaker model existence. - */ - TrainingManager.handleSpeakerModelExists = function() { - window.webkitRequestFileSystem( - PERSISTENT, hotword.constants.FILE_SYSTEM_SIZE_BYTES, - TrainingManager.speakerModelExists_, TrainingManager.fileErrorHandler_); - }; - - TrainingManager.prototype = { - __proto__: hotword.BaseSessionManager.prototype, - - /** @override */ - enabled: function() { - return this.stateManager.isTrainingEnabled(); - }, - - /** @override */ - updateListeners: function() { - hotword.BaseSessionManager.prototype.updateListeners.call(this); - - if (this.enabled()) { - // Detect when the speaker model needs to be finalized. - if (!chrome.hotwordPrivate.onFinalizeSpeakerModel.hasListener( - this.finalizedSpeakerModelListener_)) { - chrome.hotwordPrivate.onFinalizeSpeakerModel.addListener( - this.finalizedSpeakerModelListener_); - } - this.startSession(hotword.constants.RecognizerStartMode.NEW_MODEL); - } else { - chrome.hotwordPrivate.onFinalizeSpeakerModel.removeListener( - this.finalizedSpeakerModelListener_); - } - }, - - /** @override */ - handleHotwordTrigger: function(log) { - if (this.enabled()) { - hotword.BaseSessionManager.prototype.handleHotwordTrigger.call( - this, log); - this.startSession(hotword.constants.RecognizerStartMode.ADAPT_MODEL); - } - }, - - /** @override */ - startSession: function(opt_mode) { - this.stateManager.startSession( - this.sessionSource_, - function() { - chrome.hotwordPrivate.setHotwordSessionState(true, function() {}); - }, - this.handleHotwordTrigger.bind(this), - this.handleSpeakerModelSaved_.bind(this), opt_mode); - }, - - /** - * Handles a hotwordPrivate.onFinalizeSpeakerModel event. - * @private - */ - handleFinalizeSpeakerModel_: function() { - if (this.enabled()) - this.stateManager.finalizeSpeakerModel(); - }, - - /** - * Handles a hotwordPrivate.onFinalizeSpeakerModel event. - * @private - */ - handleSpeakerModelSaved_: function() { - if (this.enabled()) - chrome.hotwordPrivate.notifySpeakerModelSaved(); - }, - }; - - return {TrainingManager: TrainingManager}; -});
diff --git a/chrome/browser/resources/hotword_audio_verification/OWNERS b/chrome/browser/resources/hotword_audio_verification/OWNERS deleted file mode 100644 index 99e2824..0000000 --- a/chrome/browser/resources/hotword_audio_verification/OWNERS +++ /dev/null
@@ -1 +0,0 @@ -kcarattini@chromium.org
diff --git a/chrome/browser/resources/hotword_audio_verification/event_page.js b/chrome/browser/resources/hotword_audio_verification/event_page.js deleted file mode 100644 index ea379d3..0000000 --- a/chrome/browser/resources/hotword_audio_verification/event_page.js +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -var appId = 'hotword_audio_verification'; - -chrome.app.runtime.onLaunched.addListener(function() { - // We need to focus the window if it already exists, since it - // is created as 'hidden'. - // - // Note: If we ever launch on another platform, make sure that this works - // with window managers that support hiding (e.g. Cmd+h on an app window on - // Mac). - var appWindow = chrome.app.window.get(appId); - if (appWindow) { - appWindow.focus(); - return; - } - - chrome.app.window.create('main.html', { - 'frame': 'none', - 'resizable': false, - 'hidden': true, - 'id': appId, - 'innerBounds': {'width': 784, 'height': 448} - }); -});
diff --git a/chrome/browser/resources/hotword_audio_verification/flow.js b/chrome/browser/resources/hotword_audio_verification/flow.js deleted file mode 100644 index c222114..0000000 --- a/chrome/browser/resources/hotword_audio_verification/flow.js +++ /dev/null
@@ -1,566 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -(function() { - -// Correspond to steps in the hotword opt-in flow. -/** @const */ var START = 'start-container'; -/** @const */ var AUDIO_HISTORY = 'audio-history-container'; -/** @const */ var SPEECH_TRAINING = 'speech-training-container'; -/** @const */ var FINISH = 'finish-container'; - -/** - * These flows correspond to the three LaunchModes as defined in - * chrome/browser/search/hotword_service.h and should be kept in sync - * with them. - * @const - */ -var FLOWS = [ - [START, SPEECH_TRAINING, FINISH], - [START, AUDIO_HISTORY, SPEECH_TRAINING, FINISH], [SPEECH_TRAINING, FINISH] -]; - -/** - * The launch mode. This enum needs to be kept in sync with that of - * the same name in hotword_service.h. - * @enum {number} - */ -var LaunchMode = {HOTWORD_ONLY: 0, HOTWORD_AND_AUDIO_HISTORY: 1, RETRAIN: 2}; - -/** - * The training state. - * @enum {string} - */ -var TrainingState = { - RESET: 'reset', - TIMEOUT: 'timeout', - ERROR: 'error', -}; - -/** - * Class to control the page flow of the always-on hotword and - * Audio History opt-in process. - * @constructor - */ -function Flow() { - this.currentStepIndex_ = -1; - this.currentFlow_ = []; - - /** - * The mode that this app was launched in. - * @private {LaunchMode} - */ - this.launchMode_ = LaunchMode.HOTWORD_AND_AUDIO_HISTORY; - - /** - * Whether this flow is currently in the process of training a voice model. - * @private {boolean} - */ - this.training_ = false; - - /** - * The current training state. - * @private {?TrainingState} - */ - this.trainingState_ = null; - - /** - * Whether an expected hotword trigger has been received, indexed by - * training step. - * @private {boolean[]} - */ - this.hotwordTriggerReceived_ = []; - - /** - * Prefix of the element ids for the page that is currently training. - * @private {string} - */ - this.trainingPagePrefix_ = 'speech-training'; - - /** - * Whether the speaker model for this flow has been finalized. - * @private {boolean} - */ - this.speakerModelFinalized_ = false; - - /** - * ID of the currently active timeout. - * @private {?number} - */ - this.timeoutId_ = null; - - /** - * Listener for the speakerModelSaved event. - * @private {Function} - */ - this.speakerModelFinalizedListener_ = - this.onSpeakerModelFinalized_.bind(this); - - /** - * Listener for the hotword trigger event. - * @private {Function} - */ - this.hotwordTriggerListener_ = this.handleHotwordTrigger_.bind(this); - - // Listen for the user locking the screen. - chrome.idle.onStateChanged.addListener( - this.handleIdleStateChanged_.bind(this)); - - // Listen for hotword settings changes. This used to detect when the user - // switches to a different profile. - if (chrome.hotwordPrivate.onEnabledChanged) { - chrome.hotwordPrivate.onEnabledChanged.addListener( - this.handleEnabledChanged_.bind(this)); - } -} - -/** - * Advances the current step. Begins training if the speech-training - * page has been reached. - */ -Flow.prototype.advanceStep = function() { - this.currentStepIndex_++; - if (this.currentStepIndex_ < this.currentFlow_.length) { - if (this.currentFlow_[this.currentStepIndex_] == SPEECH_TRAINING) - this.startTraining(); - this.showStep_.apply(this); - } -}; - -/** - * Gets the appropriate flow and displays its first page. - */ -Flow.prototype.startFlow = function() { - if (chrome.hotwordPrivate && chrome.hotwordPrivate.getLaunchState) - chrome.hotwordPrivate.getLaunchState(this.startFlowForMode_.bind(this)); -}; - -/** - * Starts the training process. - */ -Flow.prototype.startTraining = function() { - // Don't start a training session if one already exists. - if (this.training_) - return; - - this.training_ = true; - - if (chrome.hotwordPrivate.onHotwordTriggered && - !chrome.hotwordPrivate.onHotwordTriggered.hasListener( - this.hotwordTriggerListener_)) { - chrome.hotwordPrivate.onHotwordTriggered.addListener( - this.hotwordTriggerListener_); - } - - this.waitForHotwordTrigger_(0); - if (chrome.hotwordPrivate.startTraining) - chrome.hotwordPrivate.startTraining(); -}; - -/** - * Stops the training process. - */ -Flow.prototype.stopTraining = function() { - if (!this.training_) - return; - - this.training_ = false; - if (chrome.hotwordPrivate.onHotwordTriggered) { - chrome.hotwordPrivate.onHotwordTriggered.removeListener( - this.hotwordTriggerListener_); - } - if (chrome.hotwordPrivate.stopTraining) - chrome.hotwordPrivate.stopTraining(); -}; - -/** - * Attempts to enable audio history for the signed-in account. - */ -Flow.prototype.enableAudioHistory = function() { - // Update UI - $('audio-history-agree').disabled = true; - $('audio-history-cancel').disabled = true; - - $('audio-history-error').hidden = true; - $('audio-history-wait').hidden = false; - - if (chrome.hotwordPrivate.setAudioHistoryEnabled) { - chrome.hotwordPrivate.setAudioHistoryEnabled( - true, this.onAudioHistoryRequestCompleted_.bind(this)); - } -}; - -// ---- private methods: - -/** - * Shows an error if the audio history setting was not enabled successfully. - * @private - */ -Flow.prototype.handleAudioHistoryError_ = function() { - $('audio-history-agree').disabled = false; - $('audio-history-cancel').disabled = false; - - $('audio-history-wait').hidden = true; - $('audio-history-error').hidden = false; - - // Set a timeout before focusing the Enable button so that screenreaders - // have time to announce the error first. - this.setTimeout_(function() { - $('audio-history-agree').focus(); - }.bind(this), 50); -}; - -/** - * Callback for when an audio history request completes. - * @param {chrome.hotwordPrivate.AudioHistoryState} state The audio history - * request state. - * @private - */ -Flow.prototype.onAudioHistoryRequestCompleted_ = function(state) { - if (!state.success || !state.enabled) { - this.handleAudioHistoryError_(); - return; - } - - this.advanceStep(); -}; - -/** - * Shows an error if the speaker model has not been finalized. - * @private - */ -Flow.prototype.handleSpeakerModelFinalizedError_ = function() { - if (!this.training_) - return; - - if (this.speakerModelFinalized_) - return; - - this.updateTrainingState_(TrainingState.ERROR); - this.stopTraining(); -}; - -/** - * Handles the speaker model finalized event. - * @private - */ -Flow.prototype.onSpeakerModelFinalized_ = function() { - this.speakerModelFinalized_ = true; - if (chrome.hotwordPrivate.onSpeakerModelSaved) { - chrome.hotwordPrivate.onSpeakerModelSaved.removeListener( - this.speakerModelFinalizedListener_); - } - this.stopTraining(); - this.setTimeout_(this.finishFlow_.bind(this), 2000); -}; - -/** - * Completes the training process. - * @private - */ -Flow.prototype.finishFlow_ = function() { - if (chrome.hotwordPrivate.setHotwordAlwaysOnSearchEnabled) { - chrome.hotwordPrivate.setHotwordAlwaysOnSearchEnabled( - true, this.advanceStep.bind(this)); - } -}; - -/** - * Handles a user clicking on the retry button. - */ -Flow.prototype.handleRetry = function() { - if (!(this.trainingState_ == TrainingState.TIMEOUT || - this.trainingState_ == TrainingState.ERROR)) - return; - - this.startTraining(); - this.updateTrainingState_(TrainingState.RESET); -}; - -// ---- private methods: - -/** - * Completes the training process. - * @private - */ -Flow.prototype.finalizeSpeakerModel_ = function() { - if (!this.training_) - return; - - // Listen for the success event from the NaCl module. - if (chrome.hotwordPrivate.onSpeakerModelSaved && - !chrome.hotwordPrivate.onSpeakerModelSaved.hasListener( - this.speakerModelFinalizedListener_)) { - chrome.hotwordPrivate.onSpeakerModelSaved.addListener( - this.speakerModelFinalizedListener_); - } - - this.speakerModelFinalized_ = false; - this.setTimeout_(this.handleSpeakerModelFinalizedError_.bind(this), 30000); - if (chrome.hotwordPrivate.finalizeSpeakerModel) - chrome.hotwordPrivate.finalizeSpeakerModel(); -}; - -/** - * Returns the current training step. - * @param {string} curStepClassName The name of the class of the current - * training step. - * @return {Object} The current training step, its index, and an array of - * all training steps. Any of these can be undefined. - * @private - */ -Flow.prototype.getCurrentTrainingStep_ = function(curStepClassName) { - var steps = - $(this.trainingPagePrefix_ + '-training').querySelectorAll('.train'); - var curStep = - $(this.trainingPagePrefix_ + '-training').querySelector('.listening'); - - return { - current: curStep, - index: Array.prototype.indexOf.call(steps, curStep), - steps: steps - }; -}; - -/** - * Updates the training state. - * @param {TrainingState} state The training state. - * @private - */ -Flow.prototype.updateTrainingState_ = function(state) { - this.trainingState_ = state; - this.updateErrorUI_(); -}; - -/** - * Waits two minutes and then checks for a training error. - * @param {number} index The index of the training step. - * @private - */ -Flow.prototype.waitForHotwordTrigger_ = function(index) { - if (!this.training_) - return; - - this.hotwordTriggerReceived_[index] = false; - this.setTimeout_(this.handleTrainingTimeout_.bind(this, index), 120000); -}; - -/** - * Checks for and handles a training error. - * @param {number} index The index of the training step. - * @private - */ -Flow.prototype.handleTrainingTimeout_ = function(index) { - if (this.hotwordTriggerReceived_[index]) - return; - - this.timeoutTraining_(); -}; - -/** - * Times out training and updates the UI to show a "retry" message, if - * currently training. - * @private - */ -Flow.prototype.timeoutTraining_ = function() { - if (!this.training_) - return; - - this.clearTimeout_(); - this.updateTrainingState_(TrainingState.TIMEOUT); - this.stopTraining(); -}; - -/** - * Sets a timeout. If any timeout is active, clear it. - * @param {Function} func The function to invoke when the timeout occurs. - * @param {number} delay Timeout delay in milliseconds. - * @private - */ -Flow.prototype.setTimeout_ = function(func, delay) { - this.clearTimeout_(); - this.timeoutId_ = setTimeout(function() { - this.timeoutId_ = null; - func(); - }, delay); -}; - -/** - * Clears any currently active timeout. - * @private - */ -Flow.prototype.clearTimeout_ = function() { - if (this.timeoutId_ != null) { - clearTimeout(this.timeoutId_); - this.timeoutId_ = null; - } -}; - -/** - * Updates the training error UI. - * @private - */ -Flow.prototype.updateErrorUI_ = function() { - if (!this.training_) - return; - - var trainingSteps = this.getCurrentTrainingStep_('listening'); - var steps = trainingSteps.steps; - - $(this.trainingPagePrefix_ + '-toast').hidden = - this.trainingState_ != TrainingState.TIMEOUT; - if (this.trainingState_ == TrainingState.RESET) { - // We reset the training to begin at the first step. - // The first step is reset to 'listening', while the rest - // are reset to 'not-started'. - var prompt = loadTimeData.getString('trainingFirstPrompt'); - for (var i = 0; i < steps.length; ++i) { - steps[i].classList.remove('recorded'); - if (i == 0) { - steps[i].classList.remove('not-started'); - steps[i].classList.add('listening'); - } else { - steps[i].classList.add('not-started'); - if (i == steps.length - 1) - prompt = loadTimeData.getString('trainingLastPrompt'); - else - prompt = loadTimeData.getString('trainingMiddlePrompt'); - } - steps[i].querySelector('.text').textContent = prompt; - } - - // Reset the buttonbar. - $(this.trainingPagePrefix_ + '-processing').hidden = true; - $(this.trainingPagePrefix_ + '-wait').hidden = false; - $(this.trainingPagePrefix_ + '-error').hidden = true; - $(this.trainingPagePrefix_ + '-retry').hidden = true; - } else if (this.trainingState_ == TrainingState.TIMEOUT) { - var curStep = trainingSteps.current; - if (curStep) { - curStep.classList.remove('listening'); - curStep.classList.add('not-started'); - } - - // Set a timeout before focusing the Retry button so that screenreaders - // have time to announce the timeout first. - this.setTimeout_(function() { - $(this.trainingPagePrefix_ + '-toast').children[1].focus(); - }.bind(this), 50); - } else if (this.trainingState_ == TrainingState.ERROR) { - // Update the buttonbar. - $(this.trainingPagePrefix_ + '-wait').hidden = true; - $(this.trainingPagePrefix_ + '-error').hidden = false; - $(this.trainingPagePrefix_ + '-retry').hidden = false; - $(this.trainingPagePrefix_ + '-processing').hidden = false; - - // Set a timeout before focusing the Retry button so that screenreaders - // have time to announce the error first. - this.setTimeout_(function() { - $(this.trainingPagePrefix_ + '-retry').children[0].focus(); - }.bind(this), 50); - } -}; - -/** - * Handles a hotword trigger event and updates the training UI. - * @private - */ -Flow.prototype.handleHotwordTrigger_ = function() { - var trainingSteps = this.getCurrentTrainingStep_('listening'); - - if (!trainingSteps.current) - return; - - var index = trainingSteps.index; - this.hotwordTriggerReceived_[index] = true; - - trainingSteps.current.querySelector('.text').textContent = - loadTimeData.getString('trainingRecorded'); - trainingSteps.current.classList.remove('listening'); - trainingSteps.current.classList.add('recorded'); - - if (trainingSteps.steps[index + 1]) { - trainingSteps.steps[index + 1].classList.remove('not-started'); - trainingSteps.steps[index + 1].classList.add('listening'); - this.waitForHotwordTrigger_(index + 1); - return; - } - - // Only the last step makes it here. - var buttonElem = $(this.trainingPagePrefix_ + '-processing').hidden = false; - this.finalizeSpeakerModel_(); -}; - -/** - * Handles a chrome.idle.onStateChanged event and times out the training if - * the state is "locked". - * @param {!string} state State, one of "active", "idle", or "locked". - * @private - */ -Flow.prototype.handleIdleStateChanged_ = function(state) { - if (state == 'locked') - this.timeoutTraining_(); -}; - -/** - * Handles a chrome.hotwordPrivate.onEnabledChanged event and times out - * training if the user is no longer the active user (user switches profiles). - * @private - */ -Flow.prototype.handleEnabledChanged_ = function() { - if (chrome.hotwordPrivate.getStatus) { - chrome.hotwordPrivate.getStatus(function(status) { - if (status.userIsActive) - return; - - this.timeoutTraining_(); - }.bind(this)); - } -}; - -/** - * Gets and starts the appropriate flow for the launch mode. - * @param {chrome.hotwordPrivate.LaunchState} state Launch state of the - * Hotword Audio Verification App. - * @private - */ -Flow.prototype.startFlowForMode_ = function(state) { - this.launchMode_ = state.launchMode; - assert( - state.launchMode >= 0 && state.launchMode < FLOWS.length, - 'Invalid Launch Mode.'); - this.currentFlow_ = FLOWS[state.launchMode]; - if (state.launchMode == LaunchMode.HOTWORD_ONLY) { - $('intro-description-audio-history-enabled').hidden = false; - } else if (state.launchMode == LaunchMode.HOTWORD_AND_AUDIO_HISTORY) { - $('intro-description').hidden = false; - } - - this.advanceStep(); -}; - -/** - * Displays the current step. If the current step is not the first step, - * also hides the previous step. Focuses the current step's first button. - * @private - */ -Flow.prototype.showStep_ = function() { - var currentStepId = this.currentFlow_[this.currentStepIndex_]; - var currentStep = document.getElementById(currentStepId); - currentStep.hidden = false; - - cr.ui.setInitialFocus(currentStep); - - var previousStep = null; - if (this.currentStepIndex_ > 0) - previousStep = this.currentFlow_[this.currentStepIndex_ - 1]; - - if (previousStep) - document.getElementById(previousStep).hidden = true; - - chrome.app.window.current().show(); -}; - -window.Flow = Flow; -})();
diff --git a/chrome/browser/resources/hotword_audio_verification/images/gradient-1x.png b/chrome/browser/resources/hotword_audio_verification/images/gradient-1x.png deleted file mode 100644 index 6ff74200..0000000 --- a/chrome/browser/resources/hotword_audio_verification/images/gradient-1x.png +++ /dev/null Binary files differ
diff --git a/chrome/browser/resources/hotword_audio_verification/images/gradient-2x.png b/chrome/browser/resources/hotword_audio_verification/images/gradient-2x.png deleted file mode 100644 index 3c39792..0000000 --- a/chrome/browser/resources/hotword_audio_verification/images/gradient-2x.png +++ /dev/null Binary files differ
diff --git a/chrome/browser/resources/hotword_audio_verification/images/ic-check-blue-1x.png b/chrome/browser/resources/hotword_audio_verification/images/ic-check-blue-1x.png deleted file mode 100644 index c04541c..0000000 --- a/chrome/browser/resources/hotword_audio_verification/images/ic-check-blue-1x.png +++ /dev/null Binary files differ
diff --git a/chrome/browser/resources/hotword_audio_verification/images/ic-check-blue-2x.png b/chrome/browser/resources/hotword_audio_verification/images/ic-check-blue-2x.png deleted file mode 100644 index 7fca135..0000000 --- a/chrome/browser/resources/hotword_audio_verification/images/ic-check-blue-2x.png +++ /dev/null Binary files differ
diff --git a/chrome/browser/resources/hotword_audio_verification/images/ic-check-gray-1x.png b/chrome/browser/resources/hotword_audio_verification/images/ic-check-gray-1x.png deleted file mode 100644 index 1071613..0000000 --- a/chrome/browser/resources/hotword_audio_verification/images/ic-check-gray-1x.png +++ /dev/null Binary files differ
diff --git a/chrome/browser/resources/hotword_audio_verification/images/ic-check-gray-2x.png b/chrome/browser/resources/hotword_audio_verification/images/ic-check-gray-2x.png deleted file mode 100644 index e93d6e1..0000000 --- a/chrome/browser/resources/hotword_audio_verification/images/ic-check-gray-2x.png +++ /dev/null Binary files differ
diff --git a/chrome/browser/resources/hotword_audio_verification/images/ic-error-1x.png b/chrome/browser/resources/hotword_audio_verification/images/ic-error-1x.png deleted file mode 100644 index f8d7584..0000000 --- a/chrome/browser/resources/hotword_audio_verification/images/ic-error-1x.png +++ /dev/null Binary files differ
diff --git a/chrome/browser/resources/hotword_audio_verification/images/ic-error-2x.png b/chrome/browser/resources/hotword_audio_verification/images/ic-error-2x.png deleted file mode 100644 index dc0bf4f..0000000 --- a/chrome/browser/resources/hotword_audio_verification/images/ic-error-2x.png +++ /dev/null Binary files differ
diff --git a/chrome/browser/resources/hotword_audio_verification/images/ic-x-white-1x.png b/chrome/browser/resources/hotword_audio_verification/images/ic-x-white-1x.png deleted file mode 100644 index 23d17c9c3..0000000 --- a/chrome/browser/resources/hotword_audio_verification/images/ic-x-white-1x.png +++ /dev/null Binary files differ
diff --git a/chrome/browser/resources/hotword_audio_verification/images/ic-x-white-2x.png b/chrome/browser/resources/hotword_audio_verification/images/ic-x-white-2x.png deleted file mode 100644 index 63cf972..0000000 --- a/chrome/browser/resources/hotword_audio_verification/images/ic-x-white-2x.png +++ /dev/null Binary files differ
diff --git a/chrome/browser/resources/hotword_audio_verification/images/icon-128.png b/chrome/browser/resources/hotword_audio_verification/images/icon-128.png deleted file mode 100644 index d3a010c..0000000 --- a/chrome/browser/resources/hotword_audio_verification/images/icon-128.png +++ /dev/null Binary files differ
diff --git a/chrome/browser/resources/hotword_audio_verification/images/icon-16.png b/chrome/browser/resources/hotword_audio_verification/images/icon-16.png deleted file mode 100644 index 3a7caeb..0000000 --- a/chrome/browser/resources/hotword_audio_verification/images/icon-16.png +++ /dev/null Binary files differ
diff --git a/chrome/browser/resources/hotword_audio_verification/images/icon-48.png b/chrome/browser/resources/hotword_audio_verification/images/icon-48.png deleted file mode 100644 index 1f48e480..0000000 --- a/chrome/browser/resources/hotword_audio_verification/images/icon-48.png +++ /dev/null Binary files differ
diff --git a/chrome/browser/resources/hotword_audio_verification/images/intro-1x.png b/chrome/browser/resources/hotword_audio_verification/images/intro-1x.png deleted file mode 100644 index 3190980f..0000000 --- a/chrome/browser/resources/hotword_audio_verification/images/intro-1x.png +++ /dev/null Binary files differ
diff --git a/chrome/browser/resources/hotword_audio_verification/images/intro-2x.png b/chrome/browser/resources/hotword_audio_verification/images/intro-2x.png deleted file mode 100644 index 6465825..0000000 --- a/chrome/browser/resources/hotword_audio_verification/images/intro-2x.png +++ /dev/null Binary files differ
diff --git a/chrome/browser/resources/hotword_audio_verification/images/placeholder-loader-1x.png b/chrome/browser/resources/hotword_audio_verification/images/placeholder-loader-1x.png deleted file mode 100644 index 0bb41bc2..0000000 --- a/chrome/browser/resources/hotword_audio_verification/images/placeholder-loader-1x.png +++ /dev/null Binary files differ
diff --git a/chrome/browser/resources/hotword_audio_verification/images/placeholder-loader-2x.png b/chrome/browser/resources/hotword_audio_verification/images/placeholder-loader-2x.png deleted file mode 100644 index cd1ffa72..0000000 --- a/chrome/browser/resources/hotword_audio_verification/images/placeholder-loader-2x.png +++ /dev/null Binary files differ
diff --git a/chrome/browser/resources/hotword_audio_verification/main.html b/chrome/browser/resources/hotword_audio_verification/main.html deleted file mode 100644 index 2572c94..0000000 --- a/chrome/browser/resources/hotword_audio_verification/main.html +++ /dev/null
@@ -1,25 +0,0 @@ -<!doctype html> -<html i18n-values="dir:textdirection;lang:language"> - <head> - <meta charset=utf-8> - <title i18n-content="introTitle"></title> - <link rel="stylesheet" href="chrome://resources/css/text_defaults.css"> - <link type="text/css" rel="stylesheet" href="style.css"> - <script src="chrome://resources/js/action_link.js"></script> - <script src="chrome://resources/js/cr.js"></script> - <script src="chrome://resources/js/cr/ui/node_utils.js"></script> - <script src="chrome://resources/js/load_time_data.js"></script> - <script src="chrome://resources/js/util.js"></script> - <script src="chrome://resources/js/i18n_template_no_process.js"></script> - <script src="flow.js"></script> - <script src="main.js"></script> - </head> - <body> - <div id="steps"> - <include src="steps/start_step.html"> - <include src="steps/audio_history_step.html"> - <include src="steps/speech_training_step.html"> - <include src="steps/finished_step.html"> - </div> - </body> -</html>
diff --git a/chrome/browser/resources/hotword_audio_verification/main.js b/chrome/browser/resources/hotword_audio_verification/main.js deleted file mode 100644 index 33fc21a..0000000 --- a/chrome/browser/resources/hotword_audio_verification/main.js +++ /dev/null
@@ -1,50 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -var appWindow = chrome.app.window.current(); - -document.addEventListener('DOMContentLoaded', function() { - chrome.hotwordPrivate.getLocalizedStrings(function(strings) { - loadTimeData.data = strings; - i18nTemplate.process(document, loadTimeData); - - var flow = new Flow(); - flow.startFlow(); - - var pressFunction = function(e) { - // Only respond to 'Enter' key presses. - if (e.type == 'keyup' && e.key != 'Enter') - return; - - var classes = e.target.classList; - if (classes.contains('close') || classes.contains('finish-button')) { - flow.stopTraining(); - appWindow.close(); - e.preventDefault(); - } - if (classes.contains('retry-button')) { - flow.handleRetry(); - e.preventDefault(); - } - }; - - $('steps').addEventListener('click', pressFunction); - $('steps').addEventListener('keyup', pressFunction); - - $('audio-history-agree').addEventListener('click', function(e) { - flow.enableAudioHistory(); - e.preventDefault(); - }); - - $('hotword-start').addEventListener('click', function(e) { - flow.advanceStep(); - e.preventDefault(); - }); - - $('settings-link').addEventListener('click', function(e) { - chrome.browser.openTab({'url': 'chrome://settings'}, function() {}); - e.preventDefault(); - }); - }); -});
diff --git a/chrome/browser/resources/hotword_audio_verification/manifest.json b/chrome/browser/resources/hotword_audio_verification/manifest.json deleted file mode 100644 index a6e4091e..0000000 --- a/chrome/browser/resources/hotword_audio_verification/manifest.json +++ /dev/null
@@ -1,27 +0,0 @@ -{ - // chrome-extension://abjokfonkihficiokmkfboogholifghn/ - "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtfVZc80kw93gaZwHGhOLpxGKil8n/x1IQ2L/Oj76YeICJk5w4YKw+0N2IYA0gJnwqJdTu3ijrWqO2oQTWoZ3lHmAv9NHsUXHdrWuoGRuVqo0dakLnS+AB3rLGPSerZZNExpdK0Yd3wR6GMOJAoAQM9H6Zpo7LNYjPebx31QJZ6OgdYZA+Eu4fGIJkWIPY1LMsVO1jzFJ4JSPyNWmhxL4fHfQXVM5p1cgJSVxTXsB1ZGaRc4HF2kwSYMOimIiWqfU0VInTXVU7IS3hJaKzm/LExW/ABTGejf2sGIa725EQTavGFsQ07jFZdVzKGAjHCU/0Jy8PxDIg2B+ixlM2QXP/wIDAQAB", - "name": "Ok Google", - "version": "0.1", - "manifest_version": 2, - "icons": { - "16": "images/icon-16.png", - "48": "images/icon-48.png", - "128": "images/icon-128.png" - }, - "app": { - "background": { - "scripts": ["event_page.js"], - "persistent": false - }, - "content_security_policy": "default-src 'self' blob: filesystem:; script-src 'self' blob: filesystem: chrome://resources chrome://settings; style-src 'self' blob: filesystem: chrome://resources" - }, - "permissions": [ - "chrome://resources/", - "chrome://settings/", - "browser", - "hotwordPrivate", - "idle" - ], - "display_in_launcher": false -}
diff --git a/chrome/browser/resources/hotword_audio_verification/steps/audio_history_step.html b/chrome/browser/resources/hotword_audio_verification/steps/audio_history_step.html deleted file mode 100644 index 8c2304b..0000000 --- a/chrome/browser/resources/hotword_audio_verification/steps/audio_history_step.html +++ /dev/null
@@ -1,38 +0,0 @@ -<div id="audio-history-container" hidden> - <div class="container"> - <span class="close" tabindex="0" role="button" - i18n-values="aria-label:close"></span> - <div class="header"> - <h1 i18n-content="audioHistoryTitle" aria-live="polite"></h1> - </div> - <div class="content"> - <div i18n-content="audioHistoryDescription1"></div> - <div class="v-spacing"></div> - <div i18n-values=".innerHTML:audioHistoryDescription2"></div> - <div class="v-spacing"></div> - <div i18n-values=".innerHTML:audioHistoryDescription3"></div> - </div> - <div class="buttonbar"> - <div class="right"> - <div> - <button id="audio-history-agree" i18n-content="audioHistoryAgree" - class="primary"> - </button> - <button id="audio-history-cancel" i18n-content="cancel" - class="finish-button"> - </button> - </div> - </div> - <div class="left"> - <div id="audio-history-wait" class="message wait" hidden> - <span class="icon"></span> - <span i18n-content="audioHistoryWait" class="text"></span> - </div> - <div id="audio-history-error" class="message error" role="alert" hidden> - <span class="icon"></span> - <span i18n-content="error" class="text"></span> - </div> - </div> - </div> - </div> -</div>
diff --git a/chrome/browser/resources/hotword_audio_verification/steps/finished_step.html b/chrome/browser/resources/hotword_audio_verification/steps/finished_step.html deleted file mode 100644 index 71537dd4..0000000 --- a/chrome/browser/resources/hotword_audio_verification/steps/finished_step.html +++ /dev/null
@@ -1,30 +0,0 @@ -<div id="finish-container" hidden> - <div class="container"> - <span class="close" tabindex="0" role="button" - i18n-values="aria-label:close"></span> - <div class="header"> - <h1 i18n-content="finishedTitle" aria-live="polite"></h1> - </div> - <div class="content"> - <h3 i18n-content="finishedListIntro"></h3> - <div class="check"> - <span class="icon"></span> - <span i18n-content="finishedListItem1" class="text"> - </span> - </div> - <div class="check"> - <span class="icon"></span> - <span i18n-content="finishedListItem2" class="text"> - </span> - </div> - <div i18n-values=".innerHTML:finishedSettings"></div> - <div i18n-values=".innerHTML:finishedAudioHistory"></div> - </div> - <div class="buttonbar"> - <div class="right"> - <button id="done-button" i18n-content="finish" - class="primary finish-button"></button> - </div> - </div> - </div> -</div>
diff --git a/chrome/browser/resources/hotword_audio_verification/steps/speech_training_step.html b/chrome/browser/resources/hotword_audio_verification/steps/speech_training_step.html deleted file mode 100644 index fd373311..0000000 --- a/chrome/browser/resources/hotword_audio_verification/steps/speech_training_step.html +++ /dev/null
@@ -1,56 +0,0 @@ -<div id="speech-training-container" hidden> - <div class="container"> - <span class="close" tabindex="0" role="button" - i18n-values="aria-label:close"></span> - <div class="header"> - <h1 i18n-content="trainingTitle" aria-live="polite"></h1> - </div> - <div id="speech-training-training" class="content"> - <div class="col-2"> - <div i18n-content="trainingDescription"></div> - <br> - <h3 i18n-content="trainingSpeak"></h3> - </div> - <div class="col-spacing"></div> - <div class="col-2"> - <div class="train listening"> - <span class="icon"></span> - <span i18n-content="trainingFirstPrompt" - class="text"></span> - </div> - <div class="train not-started"> - <span class="icon"></span> - <span i18n-content="trainingMiddlePrompt" - class="text"></span> - </div> - <div class="train not-started"> - <span class="icon"></span> - <span i18n-content="trainingLastPrompt" - class="text"></span> - </div> - </div> - </div> - <div id="speech-training-toast" class="toast" hidden> - <span i18n-content="trainingTimeout" class="message" role="alert"></span> - <button i18n-content="trainingRetry" class="retry-button" tabindex="0"> - </button> - </div> - <div id="speech-training-processing" class="buttonbar" hidden> - <div id="speech-training-retry" class="right" hidden> - <button i18n-content="trainingRetry" class="primary retry-button"> - </button> - </div> - <div class="left"> - <div id="speech-training-wait" class="message wait"> - <span class="icon"></span> - <span i18n-content="finishedWait" class="text"></span> - </div> - <div id="speech-training-error" class="message error" - role="alert" hidden> - <span class="icon"></span> - <span i18n-content="error" class="text"></span> - </div> - </div> - </div> - </div> -</div>
diff --git a/chrome/browser/resources/hotword_audio_verification/steps/start_step.html b/chrome/browser/resources/hotword_audio_verification/steps/start_step.html deleted file mode 100644 index 441ae6b..0000000 --- a/chrome/browser/resources/hotword_audio_verification/steps/start_step.html +++ /dev/null
@@ -1,17 +0,0 @@ -<div id="start-container" hidden> - <div class="container"> - <span class="close" tabindex="0" role="button" - i18n-values="aria-label:close"></span> - <div class="intro-image"></div> - <div class="intro-text"> - <h1 i18n-content="introTitle"></h1> - <h2 i18n-content="introSubtitle"></h2> - <h3 id="intro-description" i18n-content="introDescription" hidden></h3> - <h3 id="intro-description-audio-history-enabled" - i18n-content="introDescriptionAudioHistoryEnabled" hidden></h3> - </div> - <div class="buttonbar"> - <button id="hotword-start" i18n-content="introStart"></button> - </div> - </div> -</div>
diff --git a/chrome/browser/resources/hotword_audio_verification/style.css b/chrome/browser/resources/hotword_audio_verification/style.css deleted file mode 100644 index 233ad31..0000000 --- a/chrome/browser/resources/hotword_audio_verification/style.css +++ /dev/null
@@ -1,361 +0,0 @@ -/* Copyright 2014 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. */ - -/* TODO(xdai): Remove hard-coded font-family for 'Roboto'. */ - -* { - box-sizing: border-box; - color: rgba(0, 0, 0, .54); - font-family: Roboto, 'Noto Sans', sans-serif; - font-size: 13px; - margin: 0; - padding: 0; -} - -#start-container * { - color: #fff; -} - -#start-container h2 { - font-size: 15px; - font-weight: normal; - line-height: 24px; - margin-top: 16px; -} - -#start-container h3 { - font-weight: normal; - margin: 42px 16px 24px 16px; -} - -#start-container div.container { - background: rgb(66, 133, 244); -} - -div.intro-image { - background: -webkit-image-set( - url(../images/intro-1x.png) 1x, - url(../images/intro-2x.png) 2x) - no-repeat; - height: 152px; - left: 24px; - position: absolute; - top: 122px; - width: 304px; -} - -div.intro-text { - left: 328px; - position: absolute; - text-align: center; - top: 116px; - width: 432px; -} - -#start-container div.buttonbar { - background-color: rgb(51, 103, 214); - height: 56px; - padding: 0; - text-align: center; -} - -#start-container .buttonbar button { - height: 100%; - margin: 0; - padding: 0 8px; - width: 100%; -} - -a { - -webkit-app-region: no-drag; - color: rgb(51, 103, 214); - text-decoration: none; -} - -button { - -webkit-app-region: no-drag; -} - -body { - -webkit-app-region: drag; - background: #ddd; -} - -h1 { - font-size: 20px; - font-weight: normal; - line-height: 32px; -} - -h3 { - font-size: 13px; - line-height: 20px; -} - -div.container { - background: #fff; - height: 448px; - position: relative; - width: 784px; -} - -div.header { - background: -webkit-image-set( - url(../images/gradient-1x.png) 1x, - url(../images/gradient-2x.png) 2x) - no-repeat; - height: 128px; - padding: 70px 42px 0 42px; -} - -div.header h1 { - color: #fff; -} - -div.content { - height: 264px; - line-height: 20px; - padding: 32px 42px 0 42px; -} - -div.content h3 { - color: rgba(0, 0, 0, .87); - margin-bottom: 16px; -} - -div.col-2 { - color: rgba(0, 0, 0, .54); - float: left; - width: 320px; -} - -div.col-spacing { - float: left; - height: 216px; - width: 60px; -} - -div.v-spacing { - height: 8px; -} - -a[is='action-link'] { - display: inline-block; - font-size: 14px; - margin-top: 22px; - text-decoration: none; - text-transform: uppercase; -} - -.train { - clear: both; - line-height: 18px; - margin-bottom: 24px; -} - -.train .icon { - display: inline-block; - height: 18px; - margin-right: 8px; - vertical-align: top; - width: 18px; -} - -.train .text { - color: rgba(0, 0, 0, .54); - display: inline-block; - line-height: 13px; - padding-top: 3px; - vertical-align: top; -} - -.train.recorded .text { - color: rgba(66, 133, 244, 1); -} - -@keyframes rotate { - from { transform: rotate(0); } - to { transform: rotate(359deg); } -} - -.train.listening .icon { - animation: rotate 2s linear infinite; - background: -webkit-image-set( - url(../images/placeholder-loader-1x.png) 1x, - url(../images/placeholder-loader-2x.png) 2x) - no-repeat; -} - -.train.not-started .icon { - background: -webkit-image-set( - url(../images/ic-check-gray-1x.png) 1x, - url(../images/ic-check-gray-2x.png) 2x) - no-repeat; -} - -.train.recorded .icon { - background: -webkit-image-set( - url(../images/ic-check-blue-1x.png) 1x, - url(../images/ic-check-blue-2x.png) 2x) - no-repeat; -} - -.check { - clear: both; - height: 18px; - margin-bottom: 24px; -} - -.check .icon { - background: -webkit-image-set( - url(../images/ic-check-blue-1x.png) 1x, - url(../images/ic-check-blue-2x.png) 2x) - no-repeat; - display: inline-block; - height: 18px; - margin-right: 8px; - vertical-align: top; - width: 18px; -} - -.check .text { - color: rgba(0, 0, 0, .54); - display: inline-block; - height: 18px; - line-height: 18px; - padding-top: 2px; - vertical-align: top; -} - -div.buttonbar { - background-color: rgba(236,239, 241, 1); - bottom: 0; - height: 56px; - padding: 12px; - position: absolute; - width: 100%; -} - -.buttonbar button { - background: none; - border: none; - display: inline-block; - font-weight: 700; - height: 32px; - line-height: 32px; - margin-left: 8px; - min-width: 56px; - padding: 1px 8px 0 8px; - text-transform: uppercase; -} - -.buttonbar button:disabled { - opacity: .5; -} - -.buttonbar button.grayed-out { - color: rgba(0, 0, 0, .28); - text-transform: none; -} - -.buttonbar button.primary { - color: rgb(51, 103, 214); -} - -.buttonbar .left { - float: left; - text-align: left; -} - -.buttonbar .left button:first-child { - margin-left: 0; -} - -.buttonbar .right { - float: right; - text-align: right; -} - -.buttonbar .message { - margin: 7px 0 0 2px; -} - -.buttonbar .message .icon { - display: inline-block; - height: 18px; - margin-right: 8px; - vertical-align: top; - width: 18px; -} - -.buttonbar .message.wait .icon { - animation: rotate 2s linear infinite; - background: -webkit-image-set( - url(../images/placeholder-loader-1x.png) 1x, - url(../images/placeholder-loader-2x.png) 2x) - no-repeat; -} - -.buttonbar .message.error .icon { - background: -webkit-image-set( - url(../images/ic-error-1x.png) 1x, - url(../images/ic-error-2x.png) 2x) - no-repeat; -} - -.buttonbar .message .text { - color: rgba(0, 0, 0, .54); - display: inline-block; - line-height: 18px; - padding-top: 2px; - vertical-align: top; -} - -.buttonbar .message.error .text { - color: rgb(213, 0, 0); -} - -.close { - -webkit-app-region: no-drag; - background: -webkit-image-set( - url(../images/ic-x-white-1x.png) 1x, - url(../images/ic-x-white-2x.png) 2x) - center center no-repeat; - border: none; - float: right; - height: 42px; - opacity: .54; - width: 42px; -} - -.close:hover { - opacity: 1; -} - -.toast { - background-color: rgb(38, 50, 56); - bottom: 0; - height: 52px; - padding: 10px 12px 0 42px; - position: absolute; - width: 100%; -} - -.toast .message { - color: #fff; - float: left; - padding: 9px 0 0 0; -} - -.toast button { - background: none; - border: none; - color: rgb(58, 218, 255); - float: right; - height: 32px; - margin-left: 18px; - min-width: 56px; - padding: 0 8px 0 8px; - text-transform: uppercase; -}
diff --git a/chrome/browser/resources/local_ntp/voice.css b/chrome/browser/resources/local_ntp/voice.css index bcd24e9..891d91f 100644 --- a/chrome/browser/resources/local_ntp/voice.css +++ b/chrome/browser/resources/local_ntp/voice.css
@@ -24,7 +24,6 @@ /* Color constants. */ :root { - --dark_grey: #dbdbdb; --dark_red: rgb(205, 0, 0); --grey: #777; --light_grey: #eee; @@ -33,6 +32,7 @@ --active_icon_color: white; --button_shadow: rgba(0, 0, 0, .1); --inactive_icon_color: #999; + --level_animation_color: #dbdbdb; --listening_icon_color: var(--light_red); --text_link_color: rgb(17, 85, 204); } @@ -64,13 +64,13 @@ /* The close 'x' button. */ .close-button { - color: var(--grey); + color: black; cursor: pointer; font-size: 26px; height: 11px; line-height: 15px; margin: 15px; - opacity: .6; + opacity: .54; padding: 0; position: absolute; right: 0; @@ -84,11 +84,11 @@ } .close-button:hover { - opacity: .8; + opacity: .66; } .close-button:active { - opacity: 1; + opacity: .78; } /* The vertical positioning container. */ @@ -172,7 +172,7 @@ /* Vibrating input volume level. */ .level { - background-color: var(--dark_grey); + background-color: var(--level_animation_color); border-radius: 100%; display: inline-block; height: 301px;
diff --git a/chrome/browser/resources/md_downloads/downloads.html b/chrome/browser/resources/md_downloads/downloads.html index 789c1d5..bc126bb 100644 --- a/chrome/browser/resources/md_downloads/downloads.html +++ b/chrome/browser/resources/md_downloads/downloads.html
@@ -7,7 +7,7 @@ <style> html { --downloads-card-margin: 24px; - --downloads-card-width: 640px; + --downloads-card-width: 680px; background: #f1f1f1; }
diff --git a/chrome/browser/resources/md_downloads/toolbar.html b/chrome/browser/resources/md_downloads/toolbar.html index 2985c1d0..ce6dee4 100644 --- a/chrome/browser/resources/md_downloads/toolbar.html +++ b/chrome/browser/resources/md_downloads/toolbar.html
@@ -25,7 +25,6 @@ } #toolbar { - --cr-toolbar-field-width: var(--downloads-card-width); flex: 1; }
diff --git a/chrome/browser/resources/md_extensions/detail_view.html b/chrome/browser/resources/md_extensions/detail_view.html index 160e7eb3..6ff7283d 100644 --- a/chrome/browser/resources/md_extensions/detail_view.html +++ b/chrome/browser/resources/md_extensions/detail_view.html
@@ -258,7 +258,9 @@ </div> <div class="section continuation block"> <div class="section-title">$i18n{itemDescriptionLabel}</div> - <div class="section-content">[[data.description]]</div> + <div class="section-content"> + [[getDescription_(data.description, '$i18nPolymer{noDescription}')]] + </div> </div> <div class="section block"> <div class="section-title">$i18n{itemVersion}</div>
diff --git a/chrome/browser/resources/md_extensions/detail_view.js b/chrome/browser/resources/md_extensions/detail_view.js index 28069d1..ce93827 100644 --- a/chrome/browser/resources/md_extensions/detail_view.js +++ b/chrome/browser/resources/md_extensions/detail_view.js
@@ -28,6 +28,16 @@ inDevMode: Boolean, }, + /** + * @param {string} description + * @param {string} fallback + * @return {string} + * @private + */ + getDescription_: function(description, fallback) { + return description || fallback; + }, + /** @private */ onCloseButtonTap_: function() { extensions.navigation.navigateTo({page: Page.LIST});
diff --git a/chrome/browser/resources/md_extensions/item.html b/chrome/browser/resources/md_extensions/item.html index e41a24ad5..a832300 100644 --- a/chrome/browser/resources/md_extensions/item.html +++ b/chrome/browser/resources/md_extensions/item.html
@@ -4,6 +4,7 @@ <link rel="import" href="chrome://resources/cr_elements/cr_toggle/cr_toggle.html"> <link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html"> <link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html"> +<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html"> <link rel="import" href="chrome://resources/html/action_link.html"> <link rel="import" href="chrome://resources/html/action_link_css.html"> <link rel="import" href="chrome://resources/html/assert.html"> @@ -18,6 +19,7 @@ <link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html"> <link rel="import" href="chrome://resources/polymer/v1_0/paper-icon-button/paper-icon-button-light.html"> <link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/shadow.html"> +<link rel="import" href="chrome://resources/polymer/v1_0/paper-tooltip/paper-tooltip.html"> <link rel="import" href="navigation_helper.html"> <dom-module id="extensions-item"> @@ -53,7 +55,6 @@ display: flex; flex-grow: 1; padding: 16px 20px 17px; - position: relative; } #content { @@ -107,9 +108,13 @@ text-decoration: none; } + #icon-wrapper { + position: relative; + } + #source-indicator { - -webkit-margin-start: 30px; - margin-top: 30px; + -webkit-margin-start: 24px; + margin-top: 24px; position: absolute; } @@ -131,26 +136,11 @@ width: 16px; } - #source-indicator-text { - -webkit-margin-start: 11px; /* To align with the center of the icon. */ - background: black; - border-radius: 2px; - color: white; - display: none; - margin-top: 8px; - max-width: 150px; - opacity: 0.6; - padding: 8px 12px; - transform: translateX(-50%); /* Move back 50% of width so that the - text and icon share an x-center. */ - } - - :host-context([dir='rtl']) #source-indicator-text { - transform: translateX(50%); - } - - #source-indicator:hover #source-indicator-text { - display: block; + paper-tooltip { + --paper-tooltip: { + @apply(--cr-tooltip); + min-width: 0; + }; } .action-button { @@ -175,26 +165,32 @@ </style> <div id="card" class$="[[computeClasses_(data.state, inDevMode)]]"> <div id="main"> - <template is="dom-if" - if="[[computeSourceIndicatorIcon_(data.*)]]"> - <div id="source-indicator"> - <div class="source-icon-wrapper" role="img" - aria-labelledby="source-indicator-text"> - <iron-icon icon="[[computeSourceIndicatorIcon_(data.*)]]"> - </iron-icon> - </div> - <div id="source-indicator-text"> - [[computeSourceIndicatorText_(data.*)]] - </div> - </div> - </template> <div id="icon-wrapper"> <img id="icon" src="[[data.iconUrl]]" alt$="[[appOrExtension( data.type, '$i18nPolymer{appIcon}', '$i18nPolymer{extensionIcon}')]]"> + <template is="dom-if" + if="[[computeSourceIndicatorIcon_(data.*)]]"> + <div id="source-indicator"> + <div class="source-icon-wrapper" role="img" + aria-labelledby="source-indicator-text"> + <iron-icon icon="[[computeSourceIndicatorIcon_(data.*)]]"> + </iron-icon> + </div> + </div> + </template> </div> + <!-- This needs to be separate from the source-indicator since it can't + be contained inside of a position:relative parent element. --> + <template is="dom-if" + if="[[computeSourceIndicatorIcon_(data.*)]]"> + <paper-tooltip id="source-indicator-text" for="source-indicator" + position="top" fit-to-visible-bounds> + [[computeSourceIndicatorText_(data.*)]] + </paper-tooltip> + </template> <div id="content"> <div id="name-and-version" class="layout horizontal center"> <div id="name">[[data.name]]</div>
diff --git a/chrome/browser/resources/md_extensions/item_behavior.js b/chrome/browser/resources/md_extensions/item_behavior.js index 9abf7df..40241f5 100644 --- a/chrome/browser/resources/md_extensions/item_behavior.js +++ b/chrome/browser/resources/md_extensions/item_behavior.js
@@ -12,9 +12,17 @@ * @return {string} The app or extension label depending on |type|. */ appOrExtension: function(type, appLabel, extensionLabel) { - return (type == chrome.developerPrivate.ExtensionType.EXTENSION) ? - extensionLabel : - appLabel; + const ExtensionType = chrome.developerPrivate.ExtensionType; + switch (type) { + case ExtensionType.HOSTED_APP: + case ExtensionType.LEGACY_PACKAGED_APP: + case ExtensionType.PLATFORM_APP: + return appLabel; + case ExtensionType.EXTENSION: + case ExtensionType.SHARED_MODULE: + return extensionLabel; + } + assertNotReached('Item type is not App or Extension.'); }, };
diff --git a/chrome/browser/resources/md_extensions/toggle_row.html b/chrome/browser/resources/md_extensions/toggle_row.html index c59c9608..325e4ce 100644 --- a/chrome/browser/resources/md_extensions/toggle_row.html +++ b/chrome/browser/resources/md_extensions/toggle_row.html
@@ -40,7 +40,7 @@ <input id="native" type="checkbox" checked="[[checked]]" on-change="onNativeChange_" on-click="onNativeClick_"> <slot></slot> - <cr-toggle id="crToggle" checked="{{checked}}" + <cr-toggle id="crToggle" checked="{{checked}}" aria-labelledby="label" on-change="onCrToggleChange_"></cr-toggle> </label> </template>
diff --git a/chrome/browser/resources/md_extensions/toolbar.html b/chrome/browser/resources/md_extensions/toolbar.html index 52a0864..fea7bbb 100644 --- a/chrome/browser/resources/md_extensions/toolbar.html +++ b/chrome/browser/resources/md_extensions/toolbar.html
@@ -51,6 +51,10 @@ #button-strip paper-button { -webkit-margin-end: 16px; color: white; + /* Increase contrast compared to default values. */ + --paper-button-flat-keyboard-focus: { + background: rgba(0, 0, 0, .3); + }; } .more-actions {
diff --git a/chrome/browser/resources/net_internals/main.js b/chrome/browser/resources/net_internals/main.js index ca6ce6d..875a933 100644 --- a/chrome/browser/resources/net_internals/main.js +++ b/chrome/browser/resources/net_internals/main.js
@@ -143,8 +143,11 @@ stopCapturing: function() { g_browser.disable(); - document.styleSheets[0].insertRule( - '.hide-when-not-capturing { display: none; }', 0); + var sheet = document.createElement('style'); + sheet.type = 'text/css'; + sheet.appendChild(document.createTextNode( + '.hide-when-not-capturing { display: none; }')); + document.head.appendChild(sheet); }, initTabs_: function() {
diff --git a/chrome/browser/resources/print_preview/data/coordinate2d.html b/chrome/browser/resources/print_preview/data/coordinate2d.html new file mode 100644 index 0000000..a121f096 --- /dev/null +++ b/chrome/browser/resources/print_preview/data/coordinate2d.html
@@ -0,0 +1,3 @@ +<link rel="import" href="chrome://resources/html/cr.html"> + +<script src="coordinate2d.js"></script>
diff --git a/chrome/browser/resources/print_preview/data/destination.html b/chrome/browser/resources/print_preview/data/destination.html new file mode 100644 index 0000000..5e1d059 --- /dev/null +++ b/chrome/browser/resources/print_preview/data/destination.html
@@ -0,0 +1,4 @@ +<link rel="import" href="chrome://resources/html/cr.html"> +<link rel="import" href="../print_preview_utils.html"> + +<script src="destination.js"></script>
diff --git a/chrome/browser/resources/print_preview/data/document_info.html b/chrome/browser/resources/print_preview/data/document_info.html new file mode 100644 index 0000000..d814e19a --- /dev/null +++ b/chrome/browser/resources/print_preview/data/document_info.html
@@ -0,0 +1,7 @@ +<link rel="import" href="chrome://resources/html/cr.html"> +<link rel="import" href="chrome://resources/html/cr/event_target.html"> +<link rel="import" href="size.html"> +<link rel="import" href="coordinate2d.html"> +<link rel="import" href="printable_area.html"> + +<script src="document_info.js"></script>
diff --git a/chrome/browser/resources/print_preview/data/document_info.js b/chrome/browser/resources/print_preview/data/document_info.js index 35adacc..8881596 100644 --- a/chrome/browser/resources/print_preview/data/document_info.js +++ b/chrome/browser/resources/print_preview/data/document_info.js
@@ -37,6 +37,12 @@ this.isScalingDisabled_ = false; /** + * Scaling required to fit to page. + * @private {number} + */ + this.fitToPageScaling_ = 100; + + /** * Margins of the document in points. * @private {print_preview.Margins} */ @@ -100,6 +106,11 @@ return this.isScalingDisabled_; } + /** @return {number} Scaling required to fit to page. */ + get fitToPageScaling() { + return this.fitToPageScaling_; + } + /** @return {print_preview.Margins} Margins of the document in points. */ get margins() { return this.margins_;
diff --git a/chrome/browser/resources/print_preview/data/printable_area.html b/chrome/browser/resources/print_preview/data/printable_area.html new file mode 100644 index 0000000..d6801fd --- /dev/null +++ b/chrome/browser/resources/print_preview/data/printable_area.html
@@ -0,0 +1,5 @@ +<link rel="import" href="chrome://resources/html/cr.html"> +<link rel="import" href="size.html"> +<link rel="import" href="coordinate2d.html"> + +<script src="printable_area.js"></script>
diff --git a/chrome/browser/resources/print_preview/data/size.html b/chrome/browser/resources/print_preview/data/size.html new file mode 100644 index 0000000..8eeefa0 --- /dev/null +++ b/chrome/browser/resources/print_preview/data/size.html
@@ -0,0 +1,3 @@ +<link rel="import" href="chrome://resources/html/cr.html"> + +<script src="size.js"></script>
diff --git a/chrome/browser/resources/print_preview/new/app.html b/chrome/browser/resources/print_preview/new/app.html index 7b73fe7d6a..bde13b1 100644 --- a/chrome/browser/resources/print_preview/new/app.html +++ b/chrome/browser/resources/print_preview/new/app.html
@@ -1,5 +1,6 @@ <link rel="import" href="chrome://resources/html/polymer.html"> +<link rel="import" href="model.html"> <link rel="import" href="header.html"> <link rel="import" href="destination_settings.html"> <link rel="import" href="pages_settings.html"> @@ -30,7 +31,7 @@ min-width: 310px; } - #settings { + #settings-sections { background: #fbfbfb; border-top: 1px solid #f3f3f3; flex: 1; @@ -46,25 +47,45 @@ justify-content: center; } </style> + <print-preview-model id="model" settings="{{settings}}" + destination="{{destination}}" document-info="{{documentInfo}}" + state="{{state}}"></print-preview-model> <div id="sidebar"> - <print-preview-header model="[[model_]]"></print-preview-header> - <div id="settings"> - <print-preview-destination-settings model="{{model_}}"> + <print-preview-header destination="[[destination]]" state="[[state]]" + settings="[[settings]]"></print-preview-header> + <div id="settings-sections"> + <print-preview-destination-settings destination="[[destination]]"> </print-preview-destination-settings> - <print-preview-pages-settings model="{{model_}}"> + <print-preview-pages-settings settings="{{settings}}" + document-info="[[documentInfo]]" + hidden$="[[!settings.pages.available]]"> </print-preview-pages-settings> - <print-preview-copies-settings model="{{model_}}"> + <print-preview-copies-settings settings="{{settings}}" + hidden$="[[!settings.copies.available]]"> </print-preview-copies-settings> - <print-preview-layout-settings></print-preview-layout-settings> - <print-preview-color-settings></print-preview-color-settings> - <print-preview-media-size-settings></print-preview-media-size-settings> - <print-preview-margins-settings></print-preview-margins-settings> - <print-preview-dpi-settings></print-preview-dpi-settings> - <print-preview-scaling-settings model="{{model_}}"> + <print-preview-layout-settings settings="{{settings}}" + hidden$="[[!settings.layout.available]]"> + </print-preview-layout-settings> + <print-preview-color-settings settings="{{settings}}" + hidden$="[[!settings.color.available]]"> + </print-preview-color-settings> + <print-preview-media-size-settings settings="{{settings}}" + hidden$="[[!settings.mediaSize.available]]"> + </print-preview-media-size-settings> + <print-preview-margins-settings settings="{{settings}}" + hidden$="[[!settings.margins.available]]"> + </print-preview-margins-settings> + <print-preview-dpi-settings settings="{{settings}}" + hidden$="[[!settings.dpi.available]]"> + </print-preview-dpi-settings> + <print-preview-scaling-settings settings="{{settings}}" + document-info="[[documentInfo]]" + hidden$="[[!settings.scaling.available]]"> </print-preview-scaling-settings> - <print-preview-other-options-settings model="{{model_}}"> + <print-preview-other-options-settings settings="{{settings}}"> </print-preview-other-options-settings> - <print-preview-advanced-options-settings> + <print-preview-advanced-options-settings settings="{{settings}}" + hidden$="[[!settings.vendorItems.available]]"> </print-preview-advanced-options-settings> </div> </div>
diff --git a/chrome/browser/resources/print_preview/new/app.js b/chrome/browser/resources/print_preview/new/app.js index 1ab7c18..9ca31b1 100644 --- a/chrome/browser/resources/print_preview/new/app.js +++ b/chrome/browser/resources/print_preview/new/app.js
@@ -6,30 +6,32 @@ is: 'print-preview-app', properties: { - /** @private {!print_preview_new.Model} */ - model_: { + /** + * Object containing current settings of Print Preview, for use by Polymer + * controls. + * @type {!Object} + */ + settings: { type: Object, notify: true, - value: { - previewLoading: false, - previewFailed: false, - cloudPrintError: '', - privetExtensionError: '', - invalidSettings: false, - destinationId: 'Foo Printer', - destinationLocation: 'ABC-123', - destinationOfflineStatus: '', - destinationIcon: '../images/1x/printer.png', - copies: 1, - pageRange: [1, 2, 3, 4, 5], - duplex: false, - copiesInvalid: false, - scalingInvalid: false, - pagesInvalid: false, - isPdfDocument: true, - fitToPageScaling: '94', - documentNumPages: 5, - }, }, - } + + /** @type {print_preview.Destination} */ + destination: { + type: Object, + notify: true, + }, + + /** @type {print_preview.DocumentInfo} */ + documentInfo: { + type: Object, + notify: true, + }, + + /** @type {!print_preview_new.State} */ + state: { + type: Object, + notify: true, + }, + }, });
diff --git a/chrome/browser/resources/print_preview/new/compiled_resources2.gyp b/chrome/browser/resources/print_preview/new/compiled_resources2.gyp index b0648e0..d8e8670 100644 --- a/chrome/browser/resources/print_preview/new/compiled_resources2.gyp +++ b/chrome/browser/resources/print_preview/new/compiled_resources2.gyp
@@ -25,7 +25,8 @@ { 'target_name': 'header', 'dependencies': [ - 'model', + '../data/compiled_resources2.gyp:destination', + 'settings_behavior', '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data', ], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], @@ -33,14 +34,15 @@ { 'target_name': 'destination_settings', 'dependencies': [ - 'model', + '../data/compiled_resources2.gyp:destination', ], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], }, { 'target_name': 'pages_settings', 'dependencies': [ - 'model', + 'settings_behavior', + '../data/compiled_resources2.gyp:document_info', '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr', '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data', ], @@ -49,8 +51,8 @@ { 'target_name': 'copies_settings', 'dependencies': [ - 'model', 'number_settings_section', + 'settings_behavior', ], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], }, @@ -87,22 +89,22 @@ { 'target_name': 'scaling_settings', 'dependencies': [ - 'model', + '../data/compiled_resources2.gyp:document_info', 'number_settings_section', + 'settings_behavior', ], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], }, { 'target_name': 'other_options_settings', 'dependencies': [ - 'model', + 'settings_behavior', ], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], }, { 'target_name': 'advanced_options_settings', 'dependencies': [ - 'model', ], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], }, @@ -113,9 +115,19 @@ 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], }, { + 'target_name': 'settings_behavior', + 'dependencies': [ + 'model', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { 'target_name': 'model', 'dependencies': [ '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr', + '../data/compiled_resources2.gyp:destination', + '../data/compiled_resources2.gyp:document_info', ], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], }
diff --git a/chrome/browser/resources/print_preview/new/copies_settings.html b/chrome/browser/resources/print_preview/new/copies_settings.html index fa903521..f6d9374 100644 --- a/chrome/browser/resources/print_preview/new/copies_settings.html +++ b/chrome/browser/resources/print_preview/new/copies_settings.html
@@ -3,6 +3,7 @@ <link rel="import" href="checkbox_radio_css.html"> <link rel="import" href="number_settings_section.html"> <link rel="import" href="print_preview_shared_css.html"> +<link rel="import" href="settings_behavior.html"> <dom-module id="print-preview-copies-settings"> <template>
diff --git a/chrome/browser/resources/print_preview/new/copies_settings.js b/chrome/browser/resources/print_preview/new/copies_settings.js index b54f98c5..b58408ff 100644 --- a/chrome/browser/resources/print_preview/new/copies_settings.js +++ b/chrome/browser/resources/print_preview/new/copies_settings.js
@@ -5,13 +5,9 @@ Polymer({ is: 'print-preview-copies-settings', - properties: { - /** @type {!print_preview_new.Model} */ - model: { - type: Object, - notify: true, - }, + behaviors: [SettingsBehavior], + properties: { /** @private {string} */ inputString_: String, @@ -19,17 +15,35 @@ inputValid_: Boolean, }, - observers: ['onCopiesChanged_(inputString_, inputValid_)'], + /** @private {boolean} */ + isInitialized_: false, + + observers: [ + 'onInputChanged_(inputString_, inputValid_)', + 'onInitialized_(settings.copies.value)' + ], + + /** + * Updates the input string when the setting has been initialized. + * @private + */ + onInitialized_: function() { + if (this.isInitialized_) + return; + this.isInitialized_ = true; + const copies = this.getSetting('copies'); + this.set('inputString_', copies.value); + }, /** * Updates model.copies and model.copiesInvalid based on the validity * and current value of the copies input. * @private */ - onCopiesChanged_: function() { - this.set( - 'model.copies', this.inputValid_ ? parseInt(this.inputString_, 10) : 1); - this.set('model.copiesInvalid', !this.inputValid_); + onInputChanged_: function() { + this.setSetting( + 'copies', this.inputValid_ ? parseInt(this.inputString_, 10) : 1); + this.setSettingValid('copies', this.inputValid_); }, /**
diff --git a/chrome/browser/resources/print_preview/new/destination_settings.html b/chrome/browser/resources/print_preview/new/destination_settings.html index d406785..d2882dde4 100644 --- a/chrome/browser/resources/print_preview/new/destination_settings.html +++ b/chrome/browser/resources/print_preview/new/destination_settings.html
@@ -2,6 +2,7 @@ <link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html"> <link rel="import" href="button_css.html"> +<link rel="import" href="../data/destination.html"> <link rel="import" href="print_preview_shared_css.html"> <link rel="import" href="throbber_css.html"> <link rel="import" href="settings_section.html"> @@ -64,13 +65,12 @@ </div> <div class="destination-settings-box" hidden="[[loadingDestination_]]"> <img class="destination-icon" - src="[[model.destinationIcon]]" alt=""> + src="[[destination.iconUrl]]" alt=""> <div class="destination-info-wrapper"> - <div class="destination-name">[[model.destinationId]]</div> - <div class="destination-location"> - [[model.destinationLocation]]</div> + <div class="destination-name">[[destination.id]]</div> + <div class="destination-location">[[destination.hint]]</div> <div class="destination-offline-status"> - [[model.destinationOfflineStatus]]</div> + [[destination.offlineStatusText]]</div> </div> </div> <button>$i18n{changeDestination}</button>
diff --git a/chrome/browser/resources/print_preview/new/destination_settings.js b/chrome/browser/resources/print_preview/new/destination_settings.js index 6ad0261..6fde6cc 100644 --- a/chrome/browser/resources/print_preview/new/destination_settings.js +++ b/chrome/browser/resources/print_preview/new/destination_settings.js
@@ -6,11 +6,8 @@ is: 'print-preview-destination-settings', properties: { - /** @type {!print_preview_new.Model} */ - model: { - type: Object, - notify: true, - }, + /** @type {!print_preview.Destination} */ + destination: Object, /** @private {boolean} */ loadingDestination_: Boolean,
diff --git a/chrome/browser/resources/print_preview/new/header.html b/chrome/browser/resources/print_preview/new/header.html index 45adf07..e16008d 100644 --- a/chrome/browser/resources/print_preview/new/header.html +++ b/chrome/browser/resources/print_preview/new/header.html
@@ -1,7 +1,9 @@ <link rel="import" href="chrome://resources/html/polymer.html"> -<link rel="import" href="print_preview_shared_css.html"> <link rel="import" href="button_css.html"> +<link rel="import" href="../data/destination.html"> +<link rel="import" href="settings_behavior.html"> +<link rel="import" href="print_preview_shared_css.html"> <link rel="import" href="strings.html"> <dom-module id="print-preview-header"> @@ -75,7 +77,7 @@ </button> <button class="print default" on-tap="onPrintButtonTap_" disabled$="[[printButtonDisabled_(currentErrorOrState_)]]"> - [[getPrintButton_(model.destinationId)]] + [[getPrintButton_(destination.id)]] </button> </div> </template>
diff --git a/chrome/browser/resources/print_preview/new/header.js b/chrome/browser/resources/print_preview/new/header.js index 67b46cac1..a9aed406 100644 --- a/chrome/browser/resources/print_preview/new/header.js +++ b/chrome/browser/resources/print_preview/new/header.js
@@ -2,21 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/** - * Enumeration of Google-promoted destination IDs. - * @enum {string} - */ -const GooglePromotedId = { - DOCS: '__google__docs', - SAVE_AS_PDF: 'Save as PDF' -}; - Polymer({ is: 'print-preview-header', + behaviors: [SettingsBehavior], + properties: { - /** @type {!print_preview_new.Model} */ - model: Object, + /** @type {!print_preview.Destination} */ + destination: Object, + + /** @type {!print_preview_new.State} */ + state: Object, /** @private {boolean} */ printInProgress_: { @@ -31,11 +27,9 @@ */ currentErrorOrState_: { type: String, - computed: 'computeErrorOrStateString_(model.previewLoading, ' + - 'model.previewFailed, model.cloudPrintError, ' + - 'model.privetExtensionError, model.invalidSettings, ' + - 'model.copiesInvalid, model.scalingInvalid, model.pagesInvalid, ' + - 'printInProgress_)' + computed: 'computeErrorOrStateString_(state.*, ' + + 'settings.copies.valid, settings.scaling.valid, ' + + 'settings.pages.valid, printInProgress_)' }, /** @@ -46,8 +40,9 @@ */ labelInfo_: { type: Object, - computed: 'getLabelInfo_(currentErrorOrState_, model.destinationId, ' + - 'model.copies, model.pageRange, model.duplex)' + computed: 'getLabelInfo_(currentErrorOrState_, destination.id, ' + + 'settings.copies.value, settings.pages.value, ' + + 'settings.duplex.value)' }, }, @@ -66,8 +61,9 @@ * @private */ isPdfOrDrive_: function() { - return this.model.destinationId == GooglePromotedId.SAVE_AS_PDF || - this.model.destinationId == GooglePromotedId.DOCS; + return this.destination.id == + print_preview.Destination.GooglePromotedId.SAVE_AS_PDF || + this.destination.id == print_preview.Destination.GooglePromotedId.DOCS; }, /** @@ -84,13 +80,13 @@ * @private */ computeErrorOrStateString_: function() { - if (this.model.cloudPrintError != '') - return this.model.cloudPrintError; - if (this.model.privetExtensionError != '') - return this.model.privetExtensionError; - if (this.model.invalidSettings || this.model.previewFailed || - this.model.previewLoading || this.model.copiesInvalid || - this.model.scalingInvalid || this.model.pagesInvalid) { + if (this.state.cloudPrintError != '') + return this.state.cloudPrintError; + if (this.state.privetExtensionError != '') + return this.state.privetExtensionError; + if (this.state.invalidSettings || this.state.previewFailed || + this.state.previewLoading || !this.getSetting('copies').valid || + !this.getSetting('scaling').valid || !this.getSetting('pages').valid) { return ''; } if (this.printInProgress_) { @@ -109,13 +105,13 @@ */ getLabelInfo_: function() { const saveToPdfOrDrive = this.isPdfOrDrive_(); - let numPages = this.model.pageRange.length; + let numPages = this.getSetting('pages').value.length; let numSheets = numPages; - if (!saveToPdfOrDrive && this.model.duplex) { + if (!saveToPdfOrDrive && this.getSetting('duplex').value) { numSheets = Math.ceil(numPages / 2); } - const copies = this.model.copies; + const copies = /** @type {number} */ (this.getSetting('copies').value); numSheets *= copies; numPages *= copies;
diff --git a/chrome/browser/resources/print_preview/new/model.html b/chrome/browser/resources/print_preview/new/model.html new file mode 100644 index 0000000..3c40ff26 --- /dev/null +++ b/chrome/browser/resources/print_preview/new/model.html
@@ -0,0 +1,6 @@ +<link rel="import" href="chrome://resources/html/polymer.html"> + +<link rel="import" href="../data/destination.html"> +<link rel="import" href="../data/document_info.html"> + +<script src="model.js"></script>
diff --git a/chrome/browser/resources/print_preview/new/model.js b/chrome/browser/resources/print_preview/new/model.js index 6f03954b..309f4884 100644 --- a/chrome/browser/resources/print_preview/new/model.js +++ b/chrome/browser/resources/print_preview/new/model.js
@@ -6,24 +6,192 @@ /** * @typedef {{ + * value: *, + * valid: boolean, + * available: boolean, + * updatesPreview: boolean + * }} + */ +print_preview_new.Setting; + +/** + * @typedef {{ * previewLoading: boolean, * previewFailed: boolean, * cloudPrintError: string, * privetExtensionError: string, * invalidSettings: boolean, - * destinationId: string, - * destinationHint: string, - * destinationOfflineStatus: string, - * destinationIcon: string, - * copies: number, - * pageRange: !Array<number>, - * duplex: boolean, - * copiesInvalid: boolean, - * scalingInvalid: boolean, - * pagesInvalid: boolean, - * isPdfDocument: boolean, - * fitToPageScaling: string, - * documentNumPages: number, * }} */ -print_preview_new.Model; +print_preview_new.State; + +Polymer({ + is: 'print-preview-model', + + properties: { + /** + * Object containing current settings of Print Preview, for use by Polymer + * controls. + * @type {{ + * pages: !print_preview_new.Setting, + * copies: !print_preview_new.Setting, + * collate: !print_preview_new.Setting, + * layout: !print_preview_new.Setting, + * color: !print_preview_new.Setting, + * mediaSize: !print_preview_new.Setting, + * margins: !print_preview_new.Setting, + * dpi: !print_preview_new.Setting, + * fitToPage: !print_preview_new.Setting, + * scaling: !print_preview_new.Setting, + * duplex: !print_preview_new.Setting, + * cssBackground: !print_preview_new.Setting, + * selectionOnly: !print_preview_new.Setting, + * headerFooter: !print_preview_new.Setting, + * rasterize: !print_preview_new.Setting, + * vendorItems: !print_preview_new.Setting, + * }} + */ + settings: { + type: Object, + notify: true, + value: { + pages: { + value: [1, 2, 3, 4, 5], + valid: true, + available: true, + updatesPreview: true, + }, + copies: { + value: '1', + valid: true, + available: true, + updatesPreview: false, + }, + collate: { + value: true, + valid: true, + available: true, + updatesPreview: false, + }, + layout: { + value: false, /* portrait */ + valid: true, + available: true, + updatesPreview: true, + }, + color: { + value: true, /* color */ + valid: true, + available: true, + updatesPreview: true, + }, + mediaSize: { + value: { + width_microns: 215900, + height_microns: 279400, + }, + valid: true, + available: true, + updatesPreview: true, + }, + margins: { + value: 0, + valid: true, + available: true, + updatesPreview: true, + }, + dpi: { + value: {}, + valid: true, + available: true, + updatesPreview: false, + }, + fitToPage: { + value: false, + valid: true, + available: true, + updatesPreview: true, + }, + scaling: { + value: '100', + valid: true, + available: true, + updatesPreview: true, + }, + duplex: { + value: true, + valid: true, + available: true, + updatesPreview: false, + }, + cssBackground: { + value: false, + valid: true, + available: true, + updatesPreview: true, + }, + selectionOnly: { + value: false, + valid: true, + available: true, + updatesPreview: true, + }, + headerFooter: { + value: true, + valid: true, + available: true, + updatesPreview: true, + }, + rasterize: { + value: false, + valid: true, + available: true, + updatesPreview: false, + }, + vendorItems: { + value: {}, + valid: true, + available: true, + updatesPreview: false, + }, + }, + }, + + /** @type {print_preview.Destination} */ + destination: { + type: Object, + notify: true, + value: new print_preview.Destination( + 'Foo Printer', print_preview.DestinationType.LOCAL, + print_preview.DestinationOrigin.LOCAL, 'Foo Printer', true, + print_preview.DestinationConnectionStatus.ONLINE, + {description: 'PrinterBrandAA 12345'}), + }, + + /** @type {print_preview.DocumentInfo} */ + documentInfo: { + type: Object, + notify: true, + value: function() { + const info = new print_preview.DocumentInfo(); + info.init(false, 'DocumentTitle', true); + info.updatePageCount(5); + info.fitToPageScaling_ = 94; + return info; + }, + }, + + /** @type {!print_preview_new.State} */ + state: { + type: Object, + notify: true, + value: { + previewLoading: false, + previewFailed: false, + cloudPrintError: '', + privetExtensionError: '', + invalidSettings: false, + }, + }, + }, +});
diff --git a/chrome/browser/resources/print_preview/new/number_settings_section.js b/chrome/browser/resources/print_preview/new/number_settings_section.js index b6de8c0..4084b852 100644 --- a/chrome/browser/resources/print_preview/new/number_settings_section.js +++ b/chrome/browser/resources/print_preview/new/number_settings_section.js
@@ -35,11 +35,6 @@ hintMessage: String, }, - /** @override */ - ready: function() { - this.inputString = this.defaultValue; - }, - /** * @param {!KeyboardEvent} e The keyboard event */
diff --git a/chrome/browser/resources/print_preview/new/other_options_settings.html b/chrome/browser/resources/print_preview/new/other_options_settings.html index 5a0bd343..7134953 100644 --- a/chrome/browser/resources/print_preview/new/other_options_settings.html +++ b/chrome/browser/resources/print_preview/new/other_options_settings.html
@@ -19,7 +19,7 @@ </div> <div id="duplex-container"> <label aria-live="polite"> - <input type="checkbox" checked="{{model.duplex::change}}"> + <input type="checkbox" checked="{{duplexValue_::change}}"> <span>$i18n{optionTwoSided}</span> </label> </div>
diff --git a/chrome/browser/resources/print_preview/new/other_options_settings.js b/chrome/browser/resources/print_preview/new/other_options_settings.js index 339f6b9..5399d54 100644 --- a/chrome/browser/resources/print_preview/new/other_options_settings.js +++ b/chrome/browser/resources/print_preview/new/other_options_settings.js
@@ -5,11 +5,28 @@ Polymer({ is: 'print-preview-other-options-settings', + behaviors: [SettingsBehavior], + properties: { - /** @type {!print_preview_new.Model} */ - model: { - type: Object, - notify: true, - }, + /** @private {boolean} */ + duplexValue_: Boolean, + }, + + observers: [ + 'onInitialized_(settings.duplex.value)', + 'onDuplexChange_(duplexValue_)', + ], + + isInitialized_: false, + + onInitialized_: function() { + if (this.isInitialized_) + return; + this.set('duplexValue_', this.getSetting('duplex').value); + this.isInitialized_ = true; + }, + + onDuplexChange_: function() { + this.setSetting('duplex', this.duplexValue_); }, });
diff --git a/chrome/browser/resources/print_preview/new/pages_settings.html b/chrome/browser/resources/print_preview/new/pages_settings.html index ac75921..72fc32d 100644 --- a/chrome/browser/resources/print_preview/new/pages_settings.html +++ b/chrome/browser/resources/print_preview/new/pages_settings.html
@@ -2,8 +2,10 @@ <link rel="import" href="chrome://resources/html/cr.html"> <link rel="import" href="checkbox_radio_css.html"> +<link rel="import" href="../data/document_info.html"> <link rel="import" href="input_css.html"> <link rel="import" href="print_preview_shared_css.html"> +<link rel="import" href="settings_behavior.html"> <link rel="import" href="settings_section.html"> <dom-module id="print-preview-pages-settings"> @@ -46,7 +48,7 @@ </div> <span class="hint" aria-live="polite" inner-h-t-m-l="[[getHintMessage_(errorState_, - model.documentNumPages)]]" + documentInfo.pageCount)]]" hidden$="[[hintHidden_(inputString_, errorState_)]]"> </span> </div>
diff --git a/chrome/browser/resources/print_preview/new/pages_settings.js b/chrome/browser/resources/print_preview/new/pages_settings.js index 6071e0fd..7b1408b 100644 --- a/chrome/browser/resources/print_preview/new/pages_settings.js +++ b/chrome/browser/resources/print_preview/new/pages_settings.js
@@ -14,12 +14,11 @@ Polymer({ is: 'print-preview-pages-settings', + behaviors: [SettingsBehavior], + properties: { - /** @type {!print_preview_new.Model} */ - model: { - type: Object, - notify: true, - }, + /** @type {!print_preview.DocumentInfo} */ + documentInfo: Object, /** @private {string} */ inputString_: { @@ -30,7 +29,7 @@ /** @private {!Array<number>} */ allPagesArray_: { type: Array, - computed: 'computeAllPagesArray_(model.documentNumPages)', + computed: 'computeAllPagesArray_(documentInfo.pageCount)', }, /** @private {boolean} */ @@ -70,7 +69,7 @@ * @private */ computeAllPagesArray_: function() { - const array = new Array(this.model.documentNumPages); + const array = new Array(this.documentInfo.pageCount); for (let i = 0; i < array.length; i++) array[i] = i + 1; return array; @@ -148,13 +147,13 @@ */ onRangeChange_: function() { if (this.errorState_ != PagesInputErrorState.NO_ERROR) { - this.set('model.pagesInvalid', true); + this.setSettingValid('pages', false); this.$$('.user-value').classList.add('invalid'); return; } this.$$('.user-value').classList.remove('invalid'); - this.set('model.pagesInvalid', false); - this.set('model.pageRange', this.pagesToPrint_); + this.setSettingValid('pages', true); + this.setSetting('pages', this.pagesToPrint_); }, /** @private */ @@ -202,7 +201,7 @@ loadTimeData.getString('examplePageRangeText')); } else { return loadTimeData.getStringF( - 'pageRangeLimitInstructionWithValue', this.model.documentNumPages); + 'pageRangeLimitInstructionWithValue', this.documentInfo.pageCount); } },
diff --git a/chrome/browser/resources/print_preview/new/scaling_settings.html b/chrome/browser/resources/print_preview/new/scaling_settings.html index eaba02e..6386cd27 100644 --- a/chrome/browser/resources/print_preview/new/scaling_settings.html +++ b/chrome/browser/resources/print_preview/new/scaling_settings.html
@@ -1,8 +1,10 @@ <link rel="import" href="chrome://resources/html/polymer.html"> <link rel="import" href="checkbox_radio_css.html"> +<link rel="import" href="../data/document_info.html"> <link rel="import" href="number_settings_section.html"> <link rel="import" href="print_preview_shared_css.html"> +<link rel="import" href="settings_behavior.html"> <dom-module id="print-preview-scaling-settings"> <template> @@ -13,7 +15,7 @@ input-string="{{inputString_}}" input-valid="{{inputValid_}}" hint-message="$i18n{scalingInstruction}" class="multirow-controls"> <div slot="opt-outside-content" id="fit-to-page-container" - class="checkbox" hidden$="[[!model.isPdfDocument]]"> + class="checkbox" hidden$="[[!settings.fitToPage.available]]"> <label aria-live="polite"> <input class="checkbox" type="checkbox" on-change="onFitToPageChange_">
diff --git a/chrome/browser/resources/print_preview/new/scaling_settings.js b/chrome/browser/resources/print_preview/new/scaling_settings.js index eac8afb..a6495e8 100644 --- a/chrome/browser/resources/print_preview/new/scaling_settings.js +++ b/chrome/browser/resources/print_preview/new/scaling_settings.js
@@ -5,12 +5,11 @@ Polymer({ is: 'print-preview-scaling-settings', + behaviors: [SettingsBehavior], + properties: { - /** @type {!print_preview_new.Model} */ - model: { - type: Object, - notify: true, - }, + /** @type {Object} */ + documentInfo: Object, /** @private {string} */ inputString_: String, @@ -25,25 +24,46 @@ /** @private {number} */ fitToPageFlag_: 0, - observers: ['onScalingChanged_(inputString_, inputValid_)'], + /** @private {boolean} */ + isInitialized_: false, + + observers: [ + 'onInputChanged_(inputString_, inputValid_, documentInfo.isModifiable)', + 'onInitialized_(settings.scaling.value)' + ], /** - * Updates model.scaling and model.scalingInvalid based on the validity - * and current value of the scaling input. + * Updates the input string when the setting has been initialized. * @private */ - onScalingChanged_: function() { + onInitialized_: function() { + // Avoid loops from setting inputString_ -> onInputChanged_ sets scaling + // value -> onInitialized_ sets inputString_ + if (this.isInitialized_) + return; + this.isInitialized_ = true; + const scaling = this.getSetting('scaling'); + this.inputString_ = /** @type {string} */ (scaling.value); + }, + + /** + * Updates model.settings.scaling based on the validity and current value of + * the scaling input. + * @private + */ + onInputChanged_: function() { if (this.fitToPageFlag_ > 0) { this.fitToPageFlag_--; - return; + } else { + const checkbox = this.$$('.checkbox input[type="checkbox"]'); + if (checkbox.checked && !this.documentInfo.isModifiable) { + checkbox.checked = false; + } else if (this.inputValid_) { + this.lastValidScaling_ = this.inputString_; + } + this.setSetting('scaling', this.inputString_); } - const checkbox = this.$$('.checkbox input[type="checkbox"]'); - if (checkbox.checked && this.model.isPdfDocument) { - checkbox.checked = false; - } else if (this.inputValid_) { - this.lastValidScaling_ = this.inputString_; - } - this.set('model.scalingInvalid', !this.inputValid_); + this.setSettingValid('scaling', this.inputValid_); }, /** @@ -52,7 +72,7 @@ onFitToPageChange_: function() { if (this.$$('.checkbox input[type="checkbox"]').checked) { this.fitToPageFlag_ = 2; - this.set('inputString_', this.model.fitToPageScaling); + this.set('inputString_', this.documentInfo.fitToPageScaling); } else { this.set('inputString_', this.lastValidScaling_); }
diff --git a/chrome/browser/resources/print_preview/new/settings_behavior.html b/chrome/browser/resources/print_preview/new/settings_behavior.html new file mode 100644 index 0000000..72cf371 --- /dev/null +++ b/chrome/browser/resources/print_preview/new/settings_behavior.html
@@ -0,0 +1,3 @@ +<link rel="import" href="chrome://resources/html/assert.html"> + +<script src="settings_behavior.js"></script>
diff --git a/chrome/browser/resources/print_preview/new/settings_behavior.js b/chrome/browser/resources/print_preview/new/settings_behavior.js new file mode 100644 index 0000000..d58cb86 --- /dev/null +++ b/chrome/browser/resources/print_preview/new/settings_behavior.js
@@ -0,0 +1,46 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** @polymerBehavior */ +const SettingsBehavior = { + properties: { + /** @type {Object} */ + settings: { + type: Object, + notify: true, + }, + }, + + /** + * @param {string} settingName Name of the setting to get. + * @return {print_preview_new.Setting} The setting object. + */ + getSetting: function(settingName) { + const setting = /** @type {print_preview_new.Setting} */ ( + this.get(settingName, this.settings)); + assert(!!setting, 'Setting is missing: ' + settingName); + return setting; + }, + + /** + * @param {string} settingName Name of the setting to set + * @param {boolean | string | number | Array | Object} value The value to set + * the setting to. + */ + setSetting: function(settingName, value) { + const setting = this.getSetting(settingName); + assert(setting.available, 'Setting is not available: ' + settingName); + this.set(`settings.${settingName}.value`, value); + }, + + /** + * @param {string} settingName Name of the setting to set + * @param {boolean} valid Whether the setting value is currently valid. + */ + setSettingValid: function(settingName, valid) { + const setting = this.getSetting(settingName); + assert(setting.available, 'Setting is not available: ' + settingName); + this.set(`settings.${settingName}.valid`, valid); + } +};
diff --git a/chrome/browser/resources/print_preview/print_preview_resources.grd b/chrome/browser/resources/print_preview/print_preview_resources.grd index c17f4ce..9066a7e 100644 --- a/chrome/browser/resources/print_preview/print_preview_resources.grd +++ b/chrome/browser/resources/print_preview/print_preview_resources.grd
@@ -23,12 +23,60 @@ <structure name="IDR_PRINT_PREVIEW_NEW_APP_JS" file="new/app.js" type="chrome_html" /> + <structure name="IDR_PRINT_PREVIEW_NEW_MODEL_HTML" + file="new/model.html" + type="chrome_html" /> + <structure name="IDR_PRINT_PREVIEW_NEW_MODEL_JS" + file="new/model.js" + type="chrome_html" /> + <structure name="IDR_PRINT_PREVIEW_DATA_DESTINATION_HTML" + file="data/destination.html" + type="chrome_html" /> + <structure name="IDR_PRINT_PREVIEW_DATA_DESTINATION_JS" + file="data/destination.js" + type="chrome_html" /> + <structure name="IDR_PRINT_PREVIEW_PRINT_PREVIEW_UTILS_HTML" + file="print_preview_utils.html" + type="chrome_html" /> + <structure name="IDR_PRINT_PREVIEW_PRINT_PREVIEW_UTILS_JS" + file="print_preview_utils.js" + type="chrome_html" /> + <structure name="IDR_PRINT_PREVIEW_DATA_DOCUMENT_INFO_HTML" + file="data/document_info.html" + type="chrome_html" /> + <structure name="IDR_PRINT_PREVIEW_DATA_DOCUMENT_INFO_JS" + file="data/document_info.js" + type="chrome_html" /> + <structure name="IDR_PRINT_PREVIEW_DATA_SIZE_HTML" + file="data/size.html" + type="chrome_html" /> + <structure name="IDR_PRINT_PREVIEW_DATA_SIZE_JS" + file="data/size.js" + type="chrome_html" /> + <structure name="IDR_PRINT_PREVIEW_DATA_COORDINATE2D_HTML" + file="data/coordinate2d.html" + type="chrome_html" /> + <structure name="IDR_PRINT_PREVIEW_DATA_COORDINATE2D_JS" + file="data/coordinate2d.js" + type="chrome_html" /> + <structure name="IDR_PRINT_PREVIEW_DATA_PRINTABLE_AREA_HTML" + file="data/printable_area.html" + type="chrome_html" /> + <structure name="IDR_PRINT_PREVIEW_DATA_PRINTABLE_AREA_JS" + file="data/printable_area.js" + type="chrome_html" /> <structure name="IDR_PRINT_PREVIEW_NEW_HEADER_HTML" file="new/header.html" type="chrome_html" /> <structure name="IDR_PRINT_PREVIEW_NEW_HEADER_JS" file="new/header.js" type="chrome_html" /> + <structure name="IDR_PRINT_PREVIEW_NEW_SETTINGS_BEHAVIOR_HTML" + file="new/settings_behavior.html" + type="chrome_html" /> + <structure name="IDR_PRINT_PREVIEW_NEW_SETTINGS_BEHAVIOR_JS" + file="new/settings_behavior.js" + type="chrome_html" /> <structure name="IDR_PRINT_PREVIEW_NEW_SETTINGS_SECTION_HTML" file="new/settings_section.html" type="chrome_html" />
diff --git a/chrome/browser/resources/print_preview/print_preview_utils.html b/chrome/browser/resources/print_preview/print_preview_utils.html new file mode 100644 index 0000000..6c28ddc3 --- /dev/null +++ b/chrome/browser/resources/print_preview/print_preview_utils.html
@@ -0,0 +1,3 @@ +<link rel="import" href="chrome://resources/html/cr.html"> + +<script src="print_preview_utils.js"></script>
diff --git a/chrome/browser/resources/settings/internet_page/compiled_resources2.gyp b/chrome/browser/resources/settings/internet_page/compiled_resources2.gyp index ec95eba..7ffb7c7 100644 --- a/chrome/browser/resources/settings/internet_page/compiled_resources2.gyp +++ b/chrome/browser/resources/settings/internet_page/compiled_resources2.gyp
@@ -11,11 +11,20 @@ '<(DEPTH)/ui/webui/resources/cr_elements/chromeos/network/compiled_resources2.gyp:cr_onc_types', '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:web_ui_listener_behavior', '<(EXTERNS_GYP):chrome_send', '<(EXTERNS_GYP):management', '<(EXTERNS_GYP):networking_private', '<(INTERFACES_GYP):networking_private_interface', 'internet_config', + 'internet_page_browser_proxy', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'internet_page_browser_proxy', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr', ], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], }, @@ -45,6 +54,7 @@ '<(EXTERNS_GYP):networking_private', '<(INTERFACES_GYP):networking_private_interface', 'tether_connection_dialog', + 'internet_page_browser_proxy', ], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], }, @@ -70,6 +80,7 @@ '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior', '<(EXTERNS_GYP):networking_private', '<(INTERFACES_GYP):networking_private_interface', + 'internet_page_browser_proxy', ], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], },
diff --git a/chrome/browser/resources/settings/internet_page/internet_detail_page.js b/chrome/browser/resources/settings/internet_page/internet_detail_page.js index d5a0022..84479ae 100644 --- a/chrome/browser/resources/settings/internet_page/internet_detail_page.js +++ b/chrome/browser/resources/settings/internet_page/internet_detail_page.js
@@ -145,6 +145,14 @@ */ shouldShowConfigureWhenNetworkLoaded_: false, + /** @private {settings.InternetPageBrowserProxy} */ + browserProxy_: null, + + /** @override */ + created: function() { + this.browserProxy_ = settings.InternetPageBrowserProxyImpl.getInstance(); + }, + /** * settings.RouteObserverBehavior * @param {!settings.Route} route @@ -304,11 +312,23 @@ this.close_(); return; } + + // Details page was closed while request was in progress, ignore the result. + if (!this.guid) + return; + if (!properties) { console.error('No properties for: ' + this.guid); this.close_(); return; } + + // Detail page should not be shown when Arc VPN is not connected. + if (this.isArcVpn_(properties) && !this.isConnectedState_(properties)) { + this.guid = ''; + this.close_(); + } + this.networkProperties = properties; this.networkPropertiesReceived_ = true; }, @@ -434,6 +454,11 @@ showConnect_: function(networkProperties, globalPolicy) { if (this.connectNotAllowed_(networkProperties, globalPolicy)) return false; + // TODO(lgcheng@) support connect Arc VPN from UI once Android support API + // to initiate a VPN session. + if (this.isArcVpn_(networkProperties)) + return false; + return networkProperties.Type != CrOnc.Type.ETHERNET && networkProperties.ConnectionState == CrOnc.ConnectionState.NOT_CONNECTED; @@ -459,6 +484,8 @@ var type = networkProperties.Type; if (type != CrOnc.Type.WI_FI && type != CrOnc.Type.VPN) return false; + if (this.isArcVpn_(networkProperties)) + return false; return !this.isPolicySource(networkProperties.Source) && this.isRemembered_(networkProperties); }, @@ -493,6 +520,10 @@ CrOnc.ConnectionState.NOT_CONNECTED) { return false; } + if (this.isArcVpn_(networkProperties) && + !this.isConnectedState_(networkProperties)) { + return false; + } return true; }, @@ -598,6 +629,11 @@ /** @private */ onConfigureTap_: function() { + if (this.networkProperties && this.isArcVpn_(this.networkProperties)) { + this.browserProxy_.showNetworkConfigure(this.guid); + return; + } + if (loadTimeData.getBoolean('networkSettingsConfig')) this.fire('show-config', this.networkProperties); else @@ -789,7 +825,8 @@ */ showAutoConnect_: function(networkProperties) { return networkProperties.Type != CrOnc.Type.ETHERNET && - this.isRemembered_(networkProperties); + this.isRemembered_(networkProperties) && + !this.isArcVpn_(networkProperties); }, /** @@ -825,7 +862,8 @@ showPreferNetwork_: function(networkProperties) { // TODO(stevenjb): Resolve whether or not we want to allow "preferred" for // networkProperties.Type == CrOnc.Type.ETHERNET. - return this.isRemembered_(networkProperties); + return this.isRemembered_(networkProperties) && + !this.isArcVpn_(networkProperties); }, /** @@ -869,6 +907,8 @@ var vpnType = CrOnc.getActiveValue(this.networkProperties.VPN.Type); if (vpnType == 'ThirdPartyVPN') { fields.push('VPN.ThirdPartyVPN.ProviderName'); + } else if (vpnType == 'ARCVPN') { + fields.push('VPN.Type'); } else { fields.push('VPN.Host', 'VPN.Type'); if (vpnType == 'OpenVPN') @@ -953,7 +993,8 @@ return false; } return this.hasAdvancedFields_() || this.hasDeviceFields_() || - this.isRememberedOrConnected_(networkProperties); + (networkProperties.Type != CrOnc.Type.VPN && + this.isRememberedOrConnected_(networkProperties)); }, /** @@ -1020,12 +1061,29 @@ }, /** + * @param {!CrOnc.NetworkProperties} networkProperties + * @return {boolean} + * @private + */ + isArcVpn_: function(networkProperties) { + return !!networkProperties.VPN && + CrOnc.getActiveValue(networkProperties.VPN.Type) == 'ARCVPN'; + }, + + /** * @param {string} ipAddress * @param {!CrOnc.NetworkProperties} networkProperties * @return {boolean} * @private */ showIpAddress_: function(ipAddress, networkProperties) { + // Arc Vpn does not currently pass IP configuration to ChromeOS. IP address + // property holds an internal IP address Android uses to talk to ChromeOS. + // TODO(lgcheng@) Show correct IP address when we implement IP configuration + // correclty. + if (this.isArcVpn_(networkProperties)) + return false; + return !!ipAddress && this.isConnectedState_(networkProperties); },
diff --git a/chrome/browser/resources/settings/internet_page/internet_page.html b/chrome/browser/resources/settings/internet_page/internet_page.html index fdee5441..ac34672 100644 --- a/chrome/browser/resources/settings/internet_page/internet_page.html +++ b/chrome/browser/resources/settings/internet_page/internet_page.html
@@ -4,6 +4,7 @@ <link rel="import" href="chrome://resources/cr_elements/cr_expand_button/cr_expand_button.html"> <link rel="import" href="chrome://resources/cr_elements/icons.html"> <link rel="import" href="chrome://resources/html/i18n_behavior.html"> +<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html"> <link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html"> <link rel="import" href="chrome://resources/polymer/v1_0/neon-animation/neon-animatable.html"> <link rel="import" href="chrome://resources/polymer/v1_0/paper-icon-button/paper-icon-button-light.html"> @@ -73,6 +74,15 @@ </button> </div> </template> + <template is="dom-if" if="[[arcVpnProviders_.length]]"> + <div actionable class="list-item" id="addArcVpn" + on-tap="onAddArcVpnTap_"> + <div class="start">$i18n{internetAddArcVPN}</div> + <button class="icon-external" is="paper-icon-button-light" + aria-label$="$i18n{internetAddArcVPN}"> + </button> + </div> + </template> </div> </template> </template> @@ -112,6 +122,7 @@ tether-device-state="[[get('Tether', deviceStates)]]" global-policy="[[globalPolicy_]]" third-party-vpn-providers="[[thirdPartyVpnProviders_]]" + arc-vpn-providers="[[arcVpnProviders_]]" networking-private="[[networkingPrivate]]" show-spinner="{{showSpinner_}}"> </settings-bluetooth-subpage>
diff --git a/chrome/browser/resources/settings/internet_page/internet_page.js b/chrome/browser/resources/settings/internet_page/internet_page.js index ad0c6fb..8e935fa 100644 --- a/chrome/browser/resources/settings/internet_page/internet_page.js +++ b/chrome/browser/resources/settings/internet_page/internet_page.js
@@ -10,7 +10,8 @@ Polymer({ is: 'settings-internet-page', - behaviors: [I18nBehavior, settings.RouteObserverBehavior], + behaviors: + [I18nBehavior, settings.RouteObserverBehavior, WebUIListenerBehavior], properties: { /** @@ -89,6 +90,18 @@ } }, + /** + * List of Arc VPN providers. + * @type {!Array<!settings.ArcVpnProvider>} + * @private + */ + arcVpnProviders_: { + type: Array, + value: function() { + return []; + } + }, + /** @private {!Map<string, string>} */ focusConfig_: { type: Object, @@ -128,6 +141,21 @@ /** @private {Function} */ onExtensionDisabledListener_: null, + /** @private {settings.InternetPageBrowserProxy} */ + browserProxy_: null, + + /** @override */ + created: function() { + this.browserProxy_ = settings.InternetPageBrowserProxyImpl.getInstance(); + }, + + /** @override */ + ready: function() { + this.browserProxy_.setUpdateArcVpnProvidersCallback( + this.onArcVpnProvidersReceived_.bind(this)); + this.browserProxy_.requestArcVpnProviders(); + }, + /** @override */ attached: function() { this.networkListChangedListener_ = this.networkListChangedListener_ || @@ -283,11 +311,7 @@ * @private */ onShowNetworks_: function(event) { - this.detailType_ = event.detail.Type; - var params = new URLSearchParams; - params.append('type', event.detail.Type); - this.subpageType_ = event.detail.Type; - settings.navigateTo(settings.routes.INTERNET_NETWORKS, params); + this.showNetworksSubpage_(event.detail.Type); }, /** @@ -375,7 +399,24 @@ */ onAddThirdPartyVpnTap_: function(event) { var provider = event.model.item; - chrome.send('addNetwork', [CrOnc.Type.VPN, provider.ExtensionID]); + this.browserProxy_.addThirdPartyVpn(CrOnc.Type.VPN, provider.ExtensionID); + }, + + /** @private */ + onAddArcVpnTap_: function() { + this.showNetworksSubpage_(CrOnc.Type.VPN); + }, + + /** + * @param {string} type + * @private + */ + showNetworksSubpage_: function(type) { + this.detailType_ = type; + var params = new URLSearchParams; + params.append('type', type); + this.subpageType_ = type; + settings.navigateTo(settings.routes.INTERNET_NETWORKS, params); }, /** @@ -478,6 +519,29 @@ }, /** + * Compares Arc VPN Providers based on LastlauchTime + * @param {!settings.ArcVpnProvider} arcVpnProvider1 + * @param {!settings.ArcVpnProvider} arcVpnProvider2 + * @private + */ + compareArcVpnProviders_: function(arcVpnProvider1, arcVpnProvider2) { + if (arcVpnProvider1.LastLaunchTime > arcVpnProvider2.LastLaunchTime) + return -1; + if (arcVpnProvider1.LastLaunchTime < arcVpnProvider2.LastLaunchTime) + return 1; + return 0; + }, + + /** + * @param {?Array<!settings.ArcVpnProvider>} arcVpnProviders + * @private + */ + onArcVpnProvidersReceived_: function(arcVpnProviders) { + arcVpnProviders.sort(this.compareArcVpnProviders_); + this.arcVpnProviders_ = arcVpnProviders; + }, + + /** * chrome.management.onDisabled event. * @param {{id: string}} extension * @private
diff --git a/chrome/browser/resources/settings/internet_page/internet_page_browser_proxy.html b/chrome/browser/resources/settings/internet_page/internet_page_browser_proxy.html new file mode 100644 index 0000000..5989a2f --- /dev/null +++ b/chrome/browser/resources/settings/internet_page/internet_page_browser_proxy.html
@@ -0,0 +1,2 @@ +<link rel="import" href="chrome://resources/html/cr.html"> +<script src="internet_page_browser_proxy.js"></script>
diff --git a/chrome/browser/resources/settings/internet_page/internet_page_browser_proxy.js b/chrome/browser/resources/settings/internet_page/internet_page_browser_proxy.js new file mode 100644 index 0000000..80cce5c --- /dev/null +++ b/chrome/browser/resources/settings/internet_page/internet_page_browser_proxy.js
@@ -0,0 +1,78 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** @fileoverview A helper object used for Internet page. */ +cr.exportPath('settings'); + +/** + * @typedef {{ + * PackageName: string, + * ProviderName: string, + * AppID: string, + * LastLaunchTime: number, + * }} + */ +settings.ArcVpnProvider; + +cr.define('settings', function() { + /** @interface */ + class InternetPageBrowserProxy { + /** + * Shows configuration of connnected external VPN network. + * @param {string} guid + */ + showNetworkConfigure(guid) {} + + /** + * Sends add VPN request to external VPN provider. + * @param {string} networkType + * @param {string} appId + */ + addThirdPartyVpn(networkType, appId) {} + + /** + * Requests Chrome to send list of Arc VPN providers. + */ + requestArcVpnProviders() {} + + /** + * |callback| is run when there is update of Arc VPN providers. + * Available after |requestArcVpnProviders| has been called. + * @param {function(?Array<settings.ArcVpnProvider>):void} callback + */ + setUpdateArcVpnProvidersCallback(callback) {} + } + + /** + * @implements {settings.InternetPageBrowserProxy} + */ + class InternetPageBrowserProxyImpl { + /** @override */ + showNetworkConfigure(guid) { + chrome.send('configureNetwork', [guid]); + } + + /** @override */ + addThirdPartyVpn(networkType, appId) { + chrome.send('addNetwork', [networkType, appId]); + } + + /** @override */ + requestArcVpnProviders() { + chrome.send('requestArcVpnProviders'); + } + + /** @override */ + setUpdateArcVpnProvidersCallback(callback) { + cr.addWebUIListener('sendArcVpnProviders', callback); + } + } + + cr.addSingletonGetter(InternetPageBrowserProxyImpl); + + return { + InternetPageBrowserProxy: InternetPageBrowserProxy, + InternetPageBrowserProxyImpl: InternetPageBrowserProxyImpl, + }; +});
diff --git a/chrome/browser/resources/settings/internet_page/internet_shared_css.html b/chrome/browser/resources/settings/internet_page/internet_shared_css.html index 1d60703..3b367ab3 100644 --- a/chrome/browser/resources/settings/internet_page/internet_shared_css.html +++ b/chrome/browser/resources/settings/internet_page/internet_shared_css.html
@@ -1,4 +1,5 @@ <link rel="import" href="../settings_shared_css.html"> +<link rel="import" href="internet_page_browser_proxy.html"> <!-- Common styles for Internet settings. --> <dom-module id="internet-shared">
diff --git a/chrome/browser/resources/settings/internet_page/internet_subpage.html b/chrome/browser/resources/settings/internet_page/internet_subpage.html index 3d0116ab..892b52e 100644 --- a/chrome/browser/resources/settings/internet_page/internet_subpage.html +++ b/chrome/browser/resources/settings/internet_page/internet_subpage.html
@@ -102,8 +102,8 @@ class="no-networks"> </div> - <!-- Third party VPNs. --> <template is="dom-if" if="[[isEqual_('VPN', deviceState.Type)]]"> + <!-- Third party VPNs. --> <template is="dom-repeat" items="[[thirdPartyVpnProviders]]"> <div id="[[item.ProviderName]]" class="vpn-header layout horizontal center"> @@ -123,6 +123,26 @@ $i18n{internetNoNetworks} </div> </template> + <!-- Arc VPNs. --> + <template is="dom-repeat" items="[[arcVpnProviders]]"> + <div id="[[item.ProviderName]]" + class="vpn-header layout horizontal center"> + <div class="flex">[[item.ProviderName]]</div> + <button is="paper-icon-button-light" class="icon-add-circle" + aria-label$="[[getAddArcVpnAllyString_(item)]]" + on-tap="onAddArcVpnTap_" tabindex$="[[tabindex]]"> + </button> + </div> + <cr-network-list show-buttons + hidden$="[[!haveArcVpnNetwork_(arcVpns_, item)]]" + networks="[[getArcVpnNetworks_(arcVpns_, item)]]" + on-selected="onNetworkSelected_"> + </cr-network-list> + <div hidden$="[[haveArcVpnNetwork_(arcVpns_, item)]]" + class="no-networks"> + $i18n{internetNoNetworks} + </div> + </template> </template> </div>
diff --git a/chrome/browser/resources/settings/internet_page/internet_subpage.js b/chrome/browser/resources/settings/internet_page/internet_subpage.js index af364579..69592e2c 100644 --- a/chrome/browser/resources/settings/internet_page/internet_subpage.js +++ b/chrome/browser/resources/settings/internet_page/internet_subpage.js
@@ -50,6 +50,12 @@ thirdPartyVpnProviders: Array, /** + * List of Arc VPN providers. + * @type {!Array<!settings.ArcVpnProvider>|undefined} + */ + arcVpnProviders: Array, + + /** * Interface for networkingPrivate calls, passed from internet_page. * @type {!NetworkingPrivate} */ @@ -82,6 +88,17 @@ return {}; }, }, + + /** + * Dictionary of lists of network states for Arc VPNs. + * @private {!Object<!Array<!CrOnc.NetworkStateProperties>>} + */ + arcVpns_: { + type: Object, + value: function() { + return {}; + } + } }, listeners: {'network-list-changed': 'getNetworkStateList_'}, @@ -91,6 +108,14 @@ /** @private {number|null} */ scanIntervalId_: null, + /** @private {settings.InternetPageBrowserProxy} */ + browserProxy_: null, + + /** @override */ + created: function() { + this.browserProxy_ = settings.InternetPageBrowserProxyImpl.getInstance(); + }, + /** override */ detached: function() { this.stopScanning_(); @@ -109,6 +134,7 @@ // Clear any stale data. this.networkStateList_ = []; this.thirdPartyVpns_ = {}; + this.arcVpns_ = {}; // Request the list of networks and start scanning if necessary. this.getNetworkStateList_(); this.updateScanning_(); @@ -214,23 +240,30 @@ return; } - // For VPNs, separate out third party VPNs. + // For VPNs, separate out third party VPNs and Arc VPNs. if (this.deviceState.Type == CrOnc.Type.VPN) { var builtinNetworkStates = []; var thirdPartyVpns = {}; + var arcVpns = {}; for (var i = 0; i < networkStates.length; ++i) { var state = networkStates[i]; - var providerType = state.VPN && state.VPN.ThirdPartyVPN && - state.VPN.ThirdPartyVPN.ProviderName; + var providerType = this.get('VPN.ThirdPartyVPN.ProviderName', state); if (providerType) { thirdPartyVpns[providerType] = thirdPartyVpns[providerType] || []; thirdPartyVpns[providerType].push(state); + } else if (this.get('VPN.Type', state) == 'ARCVPN') { + var arcProviderName = this.get('VPN.Host', state); + if (state.ConnectionState != CrOnc.ConnectionState.CONNECTED) + continue; + arcVpns[arcProviderName] = arcVpns[arcProviderName] || []; + arcVpns[arcProviderName].push(state); } else { builtinNetworkStates.push(state); } } networkStates = builtinNetworkStates; this.thirdPartyVpns_ = thirdPartyVpns; + this.arcVpns_ = arcVpns; } this.networkStateList_ = networkStates; @@ -306,6 +339,15 @@ }, /** + * @param {!settings.ArcVpnProvider} arcVpn + * @return {string} + * @private + */ + getAddArcVpnAllyString_: function(arcVpn) { + return this.i18n('internetAddArcVPNProvider', arcVpn.ProviderName); + }, + + /** * @param {!chrome.networkingPrivate.GlobalPolicy} globalPolicy * @return {boolean} * @private @@ -347,7 +389,19 @@ */ onAddThirdPartyVpnTap_: function(event) { var provider = event.model.item; - chrome.send('addNetwork', [CrOnc.Type.VPN, provider.ExtensionID]); + this.browserProxy_.addThirdPartyVpn(CrOnc.Type.VPN, provider.ExtensionID); + }, + + /** + * @param {!{model: + * !{item: !settings.ArcVpnProvider}, + * }} event + * @private + */ + onAddArcVpnTap_: function(event) { + var provider = event.model.item; + settings.InternetPageBrowserProxyImpl.getInstance().addThirdPartyVpn( + CrOnc.Type.VPN, provider.AppID); }, /** @@ -405,6 +459,27 @@ }, /** + * @param {!Object<!Array<!CrOnc.NetworkStateProperties>>} arcVpns + * @param {!settings.ArcVpnProvider} arcVpnProvider + * @return {!Array<!CrOnc.NetworkStateProperties>} + * @private + */ + getArcVpnNetworks_: function(arcVpns, arcVpnProvider) { + return arcVpns[arcVpnProvider.PackageName] || []; + }, + + /** + * @param {!Object<!Array<!CrOnc.NetworkStateProperties>>} arcVpns + * @param {!settings.ArcVpnProvider} arcVpnProvider + * @return {boolean} + * @private + */ + haveArcVpnNetwork_: function(arcVpns, arcVpnProvider) { + var list = this.getArcVpnNetworks_(arcVpns, arcVpnProvider); + return !!list.length; + }, + + /** * Event triggered when a network list item is selected. * @param {!{target: HTMLElement, detail: !CrOnc.NetworkStateProperties}} e * @private
diff --git a/chrome/browser/resources/settings/people_page/password_prompt_dialog.js b/chrome/browser/resources/settings/people_page/password_prompt_dialog.js index 2d3035a..5115c11f1 100644 --- a/chrome/browser/resources/settings/people_page/password_prompt_dialog.js +++ b/chrome/browser/resources/settings/people_page/password_prompt_dialog.js
@@ -136,6 +136,12 @@ // The password might have been cleared during the duration of the // getActiveModes call. this.passwordInvalid_ = !valid && !!this.password_; + // Return focus to the password input if it lost focus while being checked + // (user pressed confirm button). + if (this.passwordInvalid_ && + this.shadowRoot.activeElement != this.$.passwordInput) { + this.$.passwordInput.focus(); + } if (valid) { // Create the |this.setModes| closure and automatically clear it after
diff --git a/chrome/browser/resources/settings/search_engines_page/search_engines_browser_proxy.js b/chrome/browser/resources/settings/search_engines_page/search_engines_browser_proxy.js index 947dcbe..27db883 100644 --- a/chrome/browser/resources/settings/search_engines_page/search_engines_browser_proxy.js +++ b/chrome/browser/resources/settings/search_engines_page/search_engines_browser_proxy.js
@@ -37,18 +37,6 @@ */ var SearchEnginesInfo; -/** - * @typedef {{ - * allowed: boolean, - * enabled: boolean, - * alwaysOn: boolean, - * errorMessage: string, - * userName: string, - * historyEnabled: boolean - * }} - */ -var SearchPageHotwordInfo; - cr.define('settings', function() { /** @interface */ class SearchEnginesBrowserProxy { @@ -80,12 +68,6 @@ */ validateSearchEngineInput(fieldName, fieldValue) {} - /** @return {!Promise<!SearchPageHotwordInfo>} */ - getHotwordInfo() {} - - /** @param {boolean} enabled */ - setHotwordSearchEnabled(enabled) {} - turnOnGoogleAssistant() {} } @@ -134,16 +116,6 @@ } /** @override */ - getHotwordInfo() { - return cr.sendWithPromise('getHotwordInfo'); - } - - /** @override */ - setHotwordSearchEnabled(enabled) { - chrome.send('setHotwordSearchEnabled', [enabled]); - } - - /** @override */ turnOnGoogleAssistant() { chrome.send('turnOnGoogleAssistant'); }
diff --git a/chrome/browser/resources/settings/search_page/search_page.html b/chrome/browser/resources/settings/search_page/search_page.html index e10d814..1e9f88f 100644 --- a/chrome/browser/resources/settings/search_page/search_page.html +++ b/chrome/browser/resources/settings/search_page/search_page.html
@@ -82,62 +82,6 @@ </template> </div> - <template is="dom-if" if="[[hotwordInfo_.allowed]]"> - <!-- Hotword (OK Google) --> - <settings-toggle-button id="hotwordSearchEnable" - class="continuation indented" - pref="{{hotwordSearchEnablePref_}}" - label="$i18n{searchOkGoogleLabel}" - sub-label="[[getHotwordSearchEnableSubLabel_( - hotwordInfo_.alwaysOn)]]" - on-change="onHotwordSearchEnableChange_"> - </settings-toggle-button> - <div class="settings-row indented" - hidden$="[[!getShowHotwordSearchRetrain_(hotwordInfo_.*)]]"> - <div class="separator"></div> - <paper-button on-tap="onRetrainTap_" class="secondary-button"> - $i18n{searchOkGoogleRetrain} - </paper-button> - </div> - - <template is="dom-if" - if="[[getShowHotwordError_(hotwordInfo_.*, - hotwordSearchEnablePref_)]]"> - <div class="settings-box continuation indented"> - <iron-icon icon="settings:warning"></iron-icon> - <div inner-h-t-m-l="[[hotwordInfo_.errorMessage]]"></div> - </div> - </template> - - <template is="dom-if" if="[[hotwordInfo_.historyEnabled]]"> - <a class="settings-box two-line continuation indented inherit-color - no-outline" tabindex="-1" target="_blank" - href="$i18n{manageAudioHistoryUrl}"> - <div class="start"> - [[i18n('searchOkGoogleAudioHistoryLabel', - hotwordInfo_.userName)]] - <div class="secondary" id="audioHistorySecondary"> - $i18n{searchOkGoogleAudioHistorySubtext} - </div> - </div> - <button actionable class="icon-external" - is="paper-icon-button-light" - aria-label$="[[i18n('searchOkGoogleAudioHistoryLabel', - hotwordInfo_.userName)]]" - aria-describedby="audioHistorySecondary"></button> - </a> - </template> - </template> - -<if expr="chromeos"> - <template is="dom-if" - if="[[hotwordSearchEnablePref_.value]]"> - <div class="start settings-box continuation indented"> - $i18n{searchOkGoogleDisabled} - </div> - </template> -</if> - <!-- Manage search engines --> <div id="engines-subpage-trigger" class="settings-box" on-tap="onManageSearchEnginesTap_" actionable>
diff --git a/chrome/browser/resources/settings/search_page/search_page.js b/chrome/browser/resources/settings/search_page/search_page.js index 3dbfcf19..9a3d913 100644 --- a/chrome/browser/resources/settings/search_page/search_page.js +++ b/chrome/browser/resources/settings/search_page/search_page.js
@@ -34,18 +34,6 @@ /** @private Filter applied to search engines. */ searchEnginesFilter_: String, - /** @private {!SearchPageHotwordInfo|undefined} */ - hotwordInfo_: Object, - - /** - * This is a local PrefObject used to reflect the enabled state of hotword - * search. It is not tied directly to a pref. (There are two prefs - * associated with state and they do not map directly to whether or not - * hotword search is actually enabled). - * @private {!chrome.settingsPrivate.PrefObject|undefined} - */ - hotwordSearchEnablePref_: Object, - /** @type {?Map<string, string>} */ focusConfig_: Object, @@ -80,15 +68,10 @@ // Omnibox search engine var updateSearchEngines = searchEngines => { this.set('searchEngines_', searchEngines.defaults); - this.requestHotwordInfoUpdate_(); }; this.browserProxy_.getSearchEnginesList().then(updateSearchEngines); cr.addWebUIListener('search-engines-changed', updateSearchEngines); - // Hotword (OK Google) listener - cr.addWebUIListener( - 'hotword-info-update', this.hotwordInfoUpdate_.bind(this)); - this.focusConfig_ = new Map(); if (settings.routes.SEARCH_ENGINES) { this.focusConfig_.set( @@ -139,68 +122,6 @@ }, // </if> - /** - * @param {!Event} event - * @private - */ - onHotwordSearchEnableChange_: function(event) { - // Do not set the pref directly, allow Chrome to run the setup app instead. - this.browserProxy_.setHotwordSearchEnabled( - !!this.hotwordSearchEnablePref_.value); - }, - - /** @private */ - requestHotwordInfoUpdate_: function() { - this.browserProxy_.getHotwordInfo().then(hotwordInfo => { - this.hotwordInfoUpdate_(hotwordInfo); - }); - }, - - /** - * @param {!SearchPageHotwordInfo} hotwordInfo - * @private - */ - hotwordInfoUpdate_: function(hotwordInfo) { - this.hotwordInfo_ = hotwordInfo; - this.hotwordSearchEnablePref_ = { - key: 'unused', // required for PrefObject - type: chrome.settingsPrivate.PrefType.BOOLEAN, - value: this.hotwordInfo_.enabled, - }; - }, - - /** - * @return {string} - * @private - */ - getHotwordSearchEnableSubLabel_: function() { - return this.i18n( - this.hotwordInfo_.alwaysOn ? 'searchOkGoogleSubtextAlwaysOn' : - 'searchOkGoogleSubtextNoHardware'); - }, - - /** - * @return {boolean} - * @private - */ - getShowHotwordSearchRetrain_: function() { - return this.hotwordInfo_.enabled && this.hotwordInfo_.alwaysOn; - }, - - /** - * @return {boolean} True if the pref is enabled but hotword is not. - * @private - */ - getShowHotwordError_: function() { - return this.hotwordInfo_.enabled && !!this.hotwordInfo_.errorMessage; - }, - - /** @private */ - onRetrainTap_: function() { - // Re-enable hotword search enable; this will trigger the retrain UI. - this.browserProxy_.setHotwordSearchEnabled(this.hotwordInfo_.enabled); - }, - // <if expr="chromeos"> /** * @param {boolean} toggleValue
diff --git a/chrome/browser/resources/settings/settings_resources.grd b/chrome/browser/resources/settings/settings_resources.grd index 833b9fd..f5cc696 100644 --- a/chrome/browser/resources/settings/settings_resources.grd +++ b/chrome/browser/resources/settings/settings_resources.grd
@@ -1158,6 +1158,12 @@ <structure name="IDR_SETTINGS_INTERNET_KNOWN_NETWORKS_PAGE_JS" file="internet_page/internet_known_networks_page.js" type="chrome_html" /> + <structure name="IDR_SETTINGS_INTERNET_PAGE_BROWSER_PROXY_HTML" + file="internet_page/internet_page_browser_proxy.html" + type="chrome_html" /> + <structure name="IDR_SETTINGS_INTERNET_PAGE_BROWSER_PROXY_JS" + file="internet_page/internet_page_browser_proxy.js" + type="chrome_html" /> <structure name="IDR_SETTINGS_INTERNET_PAGE_HTML" file="internet_page/internet_page.html" type="chrome_html" />
diff --git a/chrome/browser/resources/settings/settings_ui/settings_ui.html b/chrome/browser/resources/settings/settings_ui/settings_ui.html index 0b217e7..7aca114 100644 --- a/chrome/browser/resources/settings/settings_ui/settings_ui.html +++ b/chrome/browser/resources/settings/settings_ui/settings_ui.html
@@ -39,7 +39,6 @@ cr-toolbar { @apply(--layout-center); - --cr-toolbar-field-width: var(--settings-card-max-width); --iron-icon-fill-color: white; background-color: var(--google-blue-700); color: white;
diff --git a/chrome/browser/resources/snippets_internals.html b/chrome/browser/resources/snippets_internals.html index 0789887..27ee59e 100644 --- a/chrome/browser/resources/snippets_internals.html +++ b/chrome/browser/resources/snippets_internals.html
@@ -99,6 +99,11 @@ <div> <button id="debug-log-dump" type="button">Dump the debug log</button> </div> + <div> + <button type="button" class="submit-clear-cached-suggestions"> + Clear cached suggestions + </button> + </div> </div> </div> @@ -150,10 +155,6 @@ </div> <div class="vertical-buttons"> <button jsvalues="category-id:categoryId" type="button" - class="submit-clear-cached-suggestions"> - Clear cached suggestions - </button> - <button jsvalues="category-id:categoryId" type="button" class="toggle-dismissed-suggestions"> Show dismissed suggestions </button>
diff --git a/chrome/browser/resources/snippets_internals.js b/chrome/browser/resources/snippets_internals.js index 63f19c5..eb316f77 100644 --- a/chrome/browser/resources/snippets_internals.js +++ b/chrome/browser/resources/snippets_internals.js
@@ -111,8 +111,7 @@ function onClearCachedButtonClicked(event) { event.preventDefault(); - var id = parseInt(event.currentTarget.getAttribute('category-id'), 10); - chrome.send('clearCachedSuggestions', [id]); + chrome.send('clearCachedSuggestions'); } function onClearDismissedButtonClicked(event) {
diff --git a/chrome/browser/safe_browsing/download_protection/check_client_download_request.cc b/chrome/browser/safe_browsing/download_protection/check_client_download_request.cc index b046b3e8..7d32a4cc 100644 --- a/chrome/browser/safe_browsing/download_protection/check_client_download_request.cc +++ b/chrome/browser/safe_browsing/download_protection/check_client_download_request.cc
@@ -516,12 +516,16 @@ archive_is_valid_ = (results.success ? ArchiveValid::VALID : ArchiveValid::INVALID); archived_executable_ = results.has_executable; - CopyArchivedBinaries(results.archived_binary, &archived_binary_); + CopyArchivedBinaries(results.archived_binary, &archived_binaries_); DVLOG(1) << "Zip analysis finished for " << item_->GetFullPath().value() << ", has_executable=" << results.has_executable << ", has_archive=" << results.has_archive << ", success=" << results.success; + if (archived_executable_) { + UMA_HISTOGRAM_COUNTS("SBClientDownload.ZipFileArchivedBinariesCount", + results.archived_binary.size()); + } UMA_HISTOGRAM_BOOLEAN("SBClientDownload.ZipFileSuccess", results.success); UMA_HISTOGRAM_BOOLEAN("SBClientDownload.ZipFileHasExecutable", archived_executable_); @@ -615,7 +619,8 @@ archive_is_valid_ = (results.success ? ArchiveValid::VALID : ArchiveValid::INVALID); archived_executable_ = results.has_executable; - archived_binary_.CopyFrom(results.archived_binary); + CopyArchivedBinaries(results.archived_binary, &archived_binaries_); + DVLOG(1) << "DMG analysis has finished for " << item_->GetFullPath().value() << ", has_executable=" << results.has_executable << ", success=" << results.success; @@ -634,6 +639,8 @@ if (archived_executable_) { UMA_HISTOGRAM_SPARSE_SLOWLY("SBClientDownload.DmgFileHasExecutableByType", uma_file_type); + UMA_HISTOGRAM_COUNTS("SBClientDownload.DmgFileArchivedBinariesCount", + results.archived_binary.size()); } else { UMA_HISTOGRAM_SPARSE_SLOWLY("SBClientDownload.DmgFileHasNoExecutableByType", uma_file_type); @@ -860,11 +867,14 @@ request.set_download_type(type_); ReferrerChainData* referrer_chain_data = static_cast<ReferrerChainData*>( - item_->GetUserData(kDownloadReferrerChainDataKey)); + item_->GetUserData(ReferrerChainData::kDownloadReferrerChainDataKey)); if (referrer_chain_data && !referrer_chain_data->GetReferrerChain()->empty()) { request.mutable_referrer_chain()->Swap( referrer_chain_data->GetReferrerChain()); + UMA_HISTOGRAM_COUNTS_100( + "SafeBrowsing.ReferrerURLChainSize.DownloadAttribution", + request.referrer_chain().size()); if (type_ == ClientDownloadRequest::SAMPLED_UNSUPPORTED_FILE) SafeBrowsingNavigationObserverManager::SanitizeReferrerChain( request.mutable_referrer_chain()); @@ -887,8 +897,8 @@ request.mutable_signature()->CopyFrom(signature_info_); if (image_headers_) request.set_allocated_image_headers(image_headers_.release()); - if (!archived_binary_.empty()) - request.mutable_archived_binary()->Swap(&archived_binary_); + if (!archived_binaries_.empty()) + request.mutable_archived_binary()->Swap(&archived_binaries_); if (!request.SerializeToString(&client_download_request_data_)) { FinishRequest(DownloadCheckResult::UNKNOWN, REASON_INVALID_REQUEST_PROTO); return; @@ -907,7 +917,7 @@ service_->client_download_request_callbacks_.Notify(item_, &request); DVLOG(2) << "Sending a request for URL: " << item_->GetUrlChain().back(); DVLOG(2) << "Detected " << request.archived_binary().size() << " archived " - << "binaries"; + << "binaries (may be capped)"; net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation("client_download_request", R"( semantics {
diff --git a/chrome/browser/safe_browsing/download_protection/check_client_download_request.h b/chrome/browser/safe_browsing/download_protection/check_client_download_request.h index f8a70d4..df71dda 100644 --- a/chrome/browser/safe_browsing/download_protection/check_client_download_request.h +++ b/chrome/browser/safe_browsing/download_protection/check_client_download_request.h
@@ -130,7 +130,7 @@ ClientDownloadRequest_SignatureInfo signature_info_; std::unique_ptr<ClientDownloadRequest_ImageHeaders> image_headers_; - ArchivedBinaries archived_binary_; + ArchivedBinaries archived_binaries_; CheckDownloadCallback callback_; // Will be NULL if the request has been canceled. DownloadProtectionService* service_;
diff --git a/chrome/browser/safe_browsing/download_protection/check_client_download_request_unittest.cc b/chrome/browser/safe_browsing/download_protection/check_client_download_request_unittest.cc index 8e53996..a2cc5ac0 100644 --- a/chrome/browser/safe_browsing/download_protection/check_client_download_request_unittest.cc +++ b/chrome/browser/safe_browsing/download_protection/check_client_download_request_unittest.cc
@@ -40,19 +40,26 @@ TEST_F(CheckClientDownloadRequestTest, CheckLimitArchivedExtensions) { CheckClientDownloadRequest::ArchivedBinaries src, dest; - for (int i = 0; i < 4; i++) { + const int max_to_try = 12; + for (int i = 0; i < max_to_try; i++) { src.Add(); } - SetMaxArchivedBinariesToReport(0); + // First check against the value set in .asciipb, which is currently 10 + // If that is raised above |max_to_try|, raise the latter. dest.Clear(); CheckClientDownloadRequest::CopyArchivedBinaries(src, &dest); - EXPECT_EQ(dest.size(), 0); + EXPECT_EQ(10, dest.size()); SetMaxArchivedBinariesToReport(2); dest.Clear(); CheckClientDownloadRequest::CopyArchivedBinaries(src, &dest); - EXPECT_EQ(dest.size(), 2); + EXPECT_EQ(2, dest.size()); + + SetMaxArchivedBinariesToReport(100000); + dest.Clear(); + CheckClientDownloadRequest::CopyArchivedBinaries(src, &dest); + EXPECT_EQ(max_to_try, dest.size()); } } // namespace safe_browsing
diff --git a/chrome/browser/safe_browsing/download_protection/download_protection_service.cc b/chrome/browser/safe_browsing/download_protection/download_protection_service.cc index 5a5177b..3c11fb6 100644 --- a/chrome/browser/safe_browsing/download_protection/download_protection_service.cc +++ b/chrome/browser/safe_browsing/download_protection/download_protection_service.cc
@@ -387,9 +387,6 @@ referrer_chain.get()); } - UMA_HISTOGRAM_COUNTS_100( - "SafeBrowsing.ReferrerURLChainSize.DownloadAttribution", - referrer_chain->size()); UMA_HISTOGRAM_ENUMERATION( "SafeBrowsing.ReferrerAttributionResult.DownloadAttribution", result, SafeBrowsingNavigationObserverManager::ATTRIBUTION_FAILURE_TYPE_MAX);
diff --git a/chrome/browser/safe_browsing/download_protection/download_protection_util.h b/chrome/browser/safe_browsing/download_protection/download_protection_util.h index c5189cb..85793b14 100644 --- a/chrome/browser/safe_browsing/download_protection/download_protection_util.h +++ b/chrome/browser/safe_browsing/download_protection/download_protection_util.h
@@ -13,9 +13,6 @@ namespace safe_browsing { -const void* const kDownloadReferrerChainDataKey = - &kDownloadReferrerChainDataKey; - enum class DownloadCheckResult { UNKNOWN, SAFE,
diff --git a/chrome/browser/safe_browsing/download_protection/download_url_sb_client.cc b/chrome/browser/safe_browsing/download_protection/download_url_sb_client.cc index 1bb0978..9763c38 100644 --- a/chrome/browser/safe_browsing/download_protection/download_url_sb_client.cc +++ b/chrome/browser/safe_browsing/download_protection/download_url_sb_client.cc
@@ -129,7 +129,7 @@ if (!item_) return; - item_->SetUserData(kDownloadReferrerChainDataKey, + item_->SetUserData(ReferrerChainData::kDownloadReferrerChainDataKey, base::MakeUnique<ReferrerChainData>( service_->IdentifyReferrerChain(*item_))); }
diff --git a/chrome/browser/safe_browsing/safe_browsing_blocking_page_unittest.cc b/chrome/browser/safe_browsing/safe_browsing_blocking_page_unittest.cc index 53d5f36a..47ad805d 100644 --- a/chrome/browser/safe_browsing/safe_browsing_blocking_page_unittest.cc +++ b/chrome/browser/safe_browsing/safe_browsing_blocking_page_unittest.cc
@@ -256,32 +256,6 @@ user_response_ = CANCEL; } - void DidNavigateCrossSite(const char* url, - int nav_entry_id, - bool did_create_new_entry) { - content::WebContentsTester::For(web_contents()) - ->TestDidNavigate(pending_main_rfh(), nav_entry_id, - did_create_new_entry, GURL(url), - ui::PAGE_TRANSITION_TYPED); - } - - void GoBack(bool is_cross_site) { - NavigationEntry* entry = - web_contents()->GetController().GetEntryAtOffset(-1); - ASSERT_TRUE(entry); - web_contents()->GetController().GoBack(); - - // The pending RVH should commit for cross-site navigations. - content::RenderFrameHost* rfh = - is_cross_site ? pending_main_rfh() : web_contents()->GetMainFrame(); - WebContentsTester::For(web_contents())->TestDidNavigate( - rfh, - entry->GetUniqueID(), - false, - entry->GetURL(), - ui::PAGE_TRANSITION_TYPED); - } - void ShowInterstitial(bool is_subresource, const char* url) { security_interstitials::UnsafeResource resource; InitResource(&resource, is_subresource, GURL(url)); @@ -320,7 +294,7 @@ SafeBrowsingBlockingPage* sb_interstitial) { // CommandReceived(kTakeMeBackCommand) does a back navigation for // subresource interstitials. - GoBack(true); + NavigationSimulator::GoBack(web_contents()); // DontProceed() posts a task to update the SafeBrowsingService::Client. base::RunLoop().RunUntilIdle(); } @@ -667,7 +641,7 @@ // Proceed, then navigate back. ProceedThroughInterstitial(sb_interstitial); navigation->Commit(); - GoBack(true); + NavigationSimulator::GoBack(web_contents()); // We are back on the good page. sb_interstitial = GetSafeBrowsingBlockingPage(); @@ -676,8 +650,9 @@ EXPECT_EQ(kGoodURL, controller().GetActiveEntry()->GetURL().spec()); // Navigate forward to the malware URL. - web_contents()->GetController().GoForward(); - int pending_id = controller().GetPendingEntry()->GetUniqueID(); + auto forward_navigation = NavigationSimulator::CreateHistoryNavigation( + 1 /* Offset */, web_contents()); + forward_navigation->Start(); ShowInterstitial(false, kBadURL); sb_interstitial = GetSafeBrowsingBlockingPage(); ASSERT_TRUE(sb_interstitial); @@ -685,9 +660,7 @@ // Let's proceed and make sure everything is OK (bug 17627). ProceedThroughInterstitial(sb_interstitial); // Commit the navigation. - // TODO(ahemery): Remove this and DidNavigateCrossSite function once we are - // able to use NavigationSimulator to do back/forward navigations. - DidNavigateCrossSite(kBadURL, pending_id, false); + forward_navigation->Commit(); sb_interstitial = GetSafeBrowsingBlockingPage(); ASSERT_FALSE(sb_interstitial); ASSERT_EQ(2, controller().GetEntryCount());
diff --git a/chrome/browser/safe_browsing/safe_browsing_navigation_observer_manager.cc b/chrome/browser/safe_browsing/safe_browsing_navigation_observer_manager.cc index 24c36513..f1e52d9c 100644 --- a/chrome/browser/safe_browsing/safe_browsing_navigation_observer_manager.cc +++ b/chrome/browser/safe_browsing/safe_browsing_navigation_observer_manager.cc
@@ -84,6 +84,11 @@ static const int kReferrerChainMaxLength = 10; // -------------------------ReferrerChainData----------------------- + +// String value of kDownloadReferrerChainDataKey is not used. +const char ReferrerChainData::kDownloadReferrerChainDataKey[] = + "referrer_chain_data_key"; + ReferrerChainData::ReferrerChainData( std::unique_ptr<ReferrerChain> referrer_chain) : referrer_chain_(std::move(referrer_chain)) {}
diff --git a/chrome/browser/safe_browsing/safe_browsing_navigation_observer_manager.h b/chrome/browser/safe_browsing/safe_browsing_navigation_observer_manager.h index 15a6c6f..66ce2cc6 100644 --- a/chrome/browser/safe_browsing/safe_browsing_navigation_observer_manager.h +++ b/chrome/browser/safe_browsing/safe_browsing_navigation_observer_manager.h
@@ -31,6 +31,10 @@ ~ReferrerChainData() override; ReferrerChain* GetReferrerChain(); + // Unique user data key used to get and set referrer chain data in + // DownloadItem. + static const char kDownloadReferrerChainDataKey[]; + private: std::unique_ptr<ReferrerChain> referrer_chain_; };
diff --git a/chrome/browser/safe_browsing/safe_browsing_tab_observer.cc b/chrome/browser/safe_browsing/safe_browsing_tab_observer.cc index dd907e9..65e2539 100644 --- a/chrome/browser/safe_browsing/safe_browsing_tab_observer.cc +++ b/chrome/browser/safe_browsing/safe_browsing_tab_observer.cc
@@ -18,7 +18,7 @@ #if defined(SAFE_BROWSING_CSD) #include "chrome/browser/safe_browsing/client_side_detection_host.h" #include "chrome/common/chrome_render_frame.mojom.h" -#include "content/public/common/associated_interface_provider.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" #endif DEFINE_WEB_CONTENTS_USER_DATA_KEY(safe_browsing::SafeBrowsingTabObserver);
diff --git a/chrome/browser/safe_json_parser_browsertest.cc b/chrome/browser/safe_json_parser_browsertest.cc index a2c7076..d30fa115 100644 --- a/chrome/browser/safe_json_parser_browsertest.cc +++ b/chrome/browser/safe_json_parser_browsertest.cc
@@ -9,12 +9,11 @@ #include "base/json/json_writer.h" #include "base/run_loop.h" #include "base/values.h" -#include "build/build_config.h" #include "chrome/test/base/in_process_browser_test.h" +#include "chrome/test/base/test_service_manager_listener.h" #include "content/public/common/service_manager_connection.h" #include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_utils.h" -#include "mojo/public/cpp/bindings/binding.h" #include "services/data_decoder/public/cpp/safe_json_parser.h" #include "services/data_decoder/public/interfaces/constants.mojom.h" #include "services/data_decoder/public/interfaces/json_parser.mojom.h" @@ -36,64 +35,6 @@ return json; } -// This class lets us wait for services to be started and tracks how many times -// a service was started. -class TestServiceManagerListener - : public service_manager::mojom::ServiceManagerListener { - public: - TestServiceManagerListener() = default; - - void WaitUntilServiceStarted(const std::string& service_name) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - DCHECK(!on_service_event_loop_closure_); - DCHECK(service_name_.empty()); - service_name_ = service_name; - base::RunLoop run_loop; - on_service_event_loop_closure_ = run_loop.QuitClosure(); - run_loop.Run(); - on_service_event_loop_closure_.Reset(); - } - - uint32_t GetServiceStartCount(const std::string& service_name) const { - auto iter = service_start_counters_.find(service_name); - return iter == service_start_counters_.end() ? 0 : iter->second; - } - - private: - // service_manager::mojom::ServiceManagerListener implementation: - void OnInit(std::vector<service_manager::mojom::RunningServiceInfoPtr> - running_services) override {} - - void OnServiceCreated( - service_manager::mojom::RunningServiceInfoPtr service) override {} - - void OnServiceStarted(const service_manager::Identity& identity, - uint32_t pid) override { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - service_start_counters_[identity.name()]++; - - if (identity.name() != service_name_) - return; - - service_name_.clear(); - std::move(on_service_event_loop_closure_).Run(); - } - - void OnServicePIDReceived(const service_manager::Identity& identity, - uint32_t pid) override {} - void OnServiceFailedToStart( - const service_manager::Identity& identity) override {} - - void OnServiceStopped(const service_manager::Identity& identity) override {} - - base::Closure on_service_event_loop_closure_; - std::string service_name_; - std::map<std::string, uint32_t> service_start_counters_; - - DISALLOW_COPY_AND_ASSIGN(TestServiceManagerListener); -}; - class ParseCallback { public: explicit ParseCallback(base::Closure callback) : callback_(callback) {} @@ -117,8 +58,6 @@ DISALLOW_COPY_AND_ASSIGN(ParseCallback); }; -} // namespace - class SafeJsonParserTest : public InProcessBrowserTest { protected: void TestParse(const std::string& json) { @@ -189,31 +128,23 @@ void SetUpOnMainThread() override { InProcessBrowserTest::SetUpOnMainThread(); - // Register a listener on the ServiceManager to track when services are - // started. - mojo::InterfacePtr<service_manager::mojom::ServiceManager> service_manager; - connector_ = - content::ServiceManagerConnection::GetForProcess()->GetConnector(); - connector_->BindInterface(service_manager::mojom::kServiceName, - &service_manager); - - service_manager::mojom::ServiceManagerListenerPtr listener_ptr; - listener_binding_ = std::make_unique< - mojo::Binding<service_manager::mojom::ServiceManagerListener>>( - &listener_, mojo::MakeRequest(&listener_ptr)); - service_manager->AddListener(std::move(listener_ptr)); + // Initialize the TestServiceManagerListener so it starts listening for + // service activity. + listener_.Init(); // The data_decoder service will stop if no connection is bound to it after // 5 seconds. We bind a connection to it for the duration of the test so it // is guaranteed the service is always running. - connector_->BindInterface(data_decoder::mojom::kServiceName, - &json_parser_ptr_); + connector()->BindInterface(data_decoder::mojom::kServiceName, + &json_parser_ptr_); listener_.WaitUntilServiceStarted(data_decoder::mojom::kServiceName); EXPECT_EQ( 1U, listener_.GetServiceStartCount(data_decoder::mojom::kServiceName)); } - service_manager::Connector* connector() const { return connector_; } + service_manager::Connector* connector() const { + return content::ServiceManagerConnection::GetForProcess()->GetConnector(); + } uint32_t GetServiceStartCount(const std::string& service_name) const { return listener_.GetServiceStartCount(service_name); @@ -221,14 +152,13 @@ private: data_decoder::mojom::JsonParserPtr json_parser_ptr_; - std::unique_ptr<mojo::Binding<service_manager::mojom::ServiceManagerListener>> - listener_binding_; TestServiceManagerListener listener_; - service_manager::Connector* connector_; DISALLOW_COPY_AND_ASSIGN(SafeJsonParserImplTest); }; +} // namespace + IN_PROC_BROWSER_TEST_F(SafeJsonParserTest, Parse) { TestParse("{}"); TestParse("choke");
diff --git a/chrome/browser/safe_xml_parser_browsertest.cc b/chrome/browser/safe_xml_parser_browsertest.cc new file mode 100644 index 0000000..b5a8395 --- /dev/null +++ b/chrome/browser/safe_xml_parser_browsertest.cc
@@ -0,0 +1,120 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include <memory> + +#include "base/bind.h" +#include "base/callback_helpers.h" +#include "base/json/json_reader.h" +#include "base/macros.h" +#include "base/values.h" +#include "chrome/test/base/in_process_browser_test.h" +#include "chrome/test/base/test_service_manager_listener.h" +#include "content/public/common/service_manager_connection.h" +#include "content/public/test/test_utils.h" +#include "services/data_decoder/public/cpp/safe_xml_parser.h" +#include "services/data_decoder/public/interfaces/constants.mojom.h" +#include "services/data_decoder/public/interfaces/xml_parser.mojom.h" +#include "services/service_manager/public/cpp/connector.h" + +namespace { + +constexpr char kTestXml[] = "<hello>bonjour</hello>"; +constexpr char kTestJson[] = R"( + {"type": "element", + "tag": "hello", + "children": [{"type": "text", "text": "bonjour"}] + } )"; + +class SafeXmlParserTest : public InProcessBrowserTest { + public: + SafeXmlParserTest() = default; + ~SafeXmlParserTest() override = default; + + protected: + void SetUpOnMainThread() override { + InProcessBrowserTest::SetUpOnMainThread(); + listener_.Init(); + } + + uint32_t GetServiceStartCount(const std::string& service_name) const { + return listener_.GetServiceStartCount(service_name); + } + + // Parses |xml| and compares its parsed representation with |expected_json|. + // If a |batch_id| is provided, it is passed to the ParseXml call (to group + // parsing of multiple XML documents in the same utility process). + // If |expected_json| is empty, the XML parsing is expected to fail. + void TestParse(base::StringPiece xml, + const std::string& expected_json, + const std::string& batch_id = std::string()) { + SCOPED_TRACE(xml); + + base::RunLoop run_loop; + std::unique_ptr<base::Value> expected_value; + if (!expected_json.empty()) { + expected_value = base::JSONReader::Read(expected_json); + DCHECK(expected_value) << "Bad test, incorrect JSON: " << expected_json; + } + + data_decoder::ParseXml( + content::ServiceManagerConnection::GetForProcess()->GetConnector(), + xml.as_string(), + base::BindOnce(&SafeXmlParserTest::XmlParsingDone, + base::Unretained(this), run_loop.QuitClosure(), + std::move(expected_value)), + batch_id); + run_loop.Run(); + } + + private: + void XmlParsingDone(base::Closure quit_loop_closure, + std::unique_ptr<base::Value> expected_value, + std::unique_ptr<base::Value> actual_value, + const base::Optional<std::string>& error) { + base::ScopedClosureRunner(std::move(quit_loop_closure)); + if (!expected_value) { + EXPECT_FALSE(actual_value); + EXPECT_TRUE(error); + return; + } + EXPECT_FALSE(error); + ASSERT_TRUE(actual_value); + EXPECT_EQ(*expected_value, *actual_value); + } + + data_decoder::mojom::XmlParserPtr xml_parser_ptr_; + TestServiceManagerListener listener_; + + DISALLOW_COPY_AND_ASSIGN(SafeXmlParserTest); +}; + +} // namespace + +// Tests that SafeXmlParser does parse. (actual XML parsing is tested in the +// service unit-tests). +IN_PROC_BROWSER_TEST_F(SafeXmlParserTest, Parse) { + TestParse("[\"this is JSON not XML\"]", ""); + TestParse(kTestXml, kTestJson); +} + +// Tests that a new service is created for each SafeXmlParser::Parse() call. +IN_PROC_BROWSER_TEST_F(SafeXmlParserTest, Isolation) { + constexpr size_t kParseCount = 5; + for (size_t i = 0; i < kParseCount; i++) + TestParse(kTestXml, kTestJson); + EXPECT_EQ(kParseCount, + GetServiceStartCount(data_decoder::mojom::kServiceName)); +} + +// Tests that using a batch ID allows service reuse. +IN_PROC_BROWSER_TEST_F(SafeXmlParserTest, IsolationWithBatchId) { + constexpr char kBatchId1[] = "batch1"; + constexpr char kBatchId2[] = "batch2"; + for (int i = 0; i < 5; i++) { + TestParse(kTestXml, kTestJson, kBatchId1); + TestParse(kTestXml, kTestJson, kBatchId2); + } + EXPECT_EQ(2U, GetServiceStartCount(data_decoder::mojom::kServiceName)); +}
diff --git a/chrome/browser/search/OWNERS b/chrome/browser/search/OWNERS index b97f2a3..a8188f9 100644 --- a/chrome/browser/search/OWNERS +++ b/chrome/browser/search/OWNERS
@@ -1,7 +1,5 @@ file://components/search/OWNERS -per-file hotword*=mgiuca@chromium.org -per-file hotword*=kcarattini@chromium.org per-file *source*=mathp@chromium.org per-file *source*=fserb@chromium.org per-file *source*=huangs@chromium.org
diff --git a/chrome/browser/search/hotword_audio_history_handler.cc b/chrome/browser/search/hotword_audio_history_handler.cc deleted file mode 100644 index 8b240a3..0000000 --- a/chrome/browser/search/hotword_audio_history_handler.cc +++ /dev/null
@@ -1,133 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/search/hotword_audio_history_handler.h" - -#include "chrome/browser/extensions/api/hotword_private/hotword_private_api.h" -#include "chrome/browser/history/web_history_service_factory.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/common/pref_names.h" -#include "components/history/core/browser/web_history_service.h" -#include "components/prefs/pref_service.h" - -using extensions::BrowserContextKeyedAPIFactory; -using extensions::HotwordPrivateEventService; - -// Max number of hours between audio history checks. -static const int kHoursUntilNextAudioHistoryCheck = 24; - -HotwordAudioHistoryHandler::HotwordAudioHistoryHandler( - content::BrowserContext* context, - const scoped_refptr<base::SingleThreadTaskRunner>& task_runner) - : task_runner_(task_runner), - profile_(Profile::FromBrowserContext(context)), - weak_ptr_factory_(this) { -} - -HotwordAudioHistoryHandler::~HotwordAudioHistoryHandler() { -} - -history::WebHistoryService* HotwordAudioHistoryHandler::GetWebHistory() { - return WebHistoryServiceFactory::GetForProfile(profile_); -} - -void HotwordAudioHistoryHandler::UpdateAudioHistoryState() { - GetAudioHistoryEnabled( - base::Bind(&HotwordAudioHistoryHandler::UpdateLocalPreference, - weak_ptr_factory_.GetWeakPtr())); - // Set the function to update in a day. - task_runner_->PostDelayedTask( - FROM_HERE, - base::BindOnce(&HotwordAudioHistoryHandler::UpdateAudioHistoryState, - weak_ptr_factory_.GetWeakPtr()), - base::TimeDelta::FromHours(kHoursUntilNextAudioHistoryCheck)); -} - -void HotwordAudioHistoryHandler::UpdateLocalPreference( - bool success, bool new_enabled_value) { - if (success) { - PrefService* prefs = profile_->GetPrefs(); - prefs->SetBoolean(prefs::kHotwordAudioLoggingEnabled, new_enabled_value); - } -} - -void HotwordAudioHistoryHandler::GetAudioHistoryEnabled( - const HotwordAudioHistoryCallback& callback) { -// Please add network traffic annotation if you want to remove this #if. -#if defined(OS_CHROMEOS) - history::WebHistoryService* web_history = GetWebHistory(); - if (web_history) { - web_history->GetAudioHistoryEnabled( - base::Bind(&HotwordAudioHistoryHandler::GetAudioHistoryComplete, - weak_ptr_factory_.GetWeakPtr(), callback), - NO_PARTIAL_TRAFFIC_ANNOTATION_YET); - } else { - // If web_history is null, the user is not signed in. Set the opt-in value - // to the last known value and run the callback with false for success. - PrefService* prefs = profile_->GetPrefs(); - callback.Run(false, prefs->GetBoolean(prefs::kHotwordAudioLoggingEnabled)); - } -#else - NOTREACHED() - << ": This functions is supposed to be called only in Chrome OS."; -#endif // defined(OS_CHROMEOS) -} - -void HotwordAudioHistoryHandler::SetAudioHistoryEnabled( - const bool enabled, - const HotwordAudioHistoryCallback& callback) { -// Please add network traffic annotation if you want to remove this #if. -#if defined(OS_CHROMEOS) - history::WebHistoryService* web_history = GetWebHistory(); - if (web_history) { - web_history->SetAudioHistoryEnabled( - enabled, - base::Bind(&HotwordAudioHistoryHandler::SetAudioHistoryComplete, - weak_ptr_factory_.GetWeakPtr(), enabled, callback), - NO_PARTIAL_TRAFFIC_ANNOTATION_YET); - } else { - // If web_history is null, run the callback with false for success - // and return the last known value for the opt-in pref. - PrefService* prefs = profile_->GetPrefs(); - callback.Run(false, prefs->GetBoolean(prefs::kHotwordAudioLoggingEnabled)); - } -#else - NOTREACHED() - << ": This functions is supposed to be called only in Chrome OS."; -#endif // defined(OS_CHROMEOS) -} - -void HotwordAudioHistoryHandler::GetAudioHistoryComplete( - const HotwordAudioHistoryCallback& callback, - bool success, bool new_enabled_value) { - // Initialize value to the last known value of the audio history pref. - PrefService* prefs = profile_->GetPrefs(); - bool value = prefs->GetBoolean(prefs::kHotwordAudioLoggingEnabled); - // If the call was successful, use the new value for updates. - if (success) { - value = new_enabled_value; - prefs->SetBoolean(prefs::kHotwordAudioLoggingEnabled, value); - // If the setting is now turned off, always on should also be turned off, - // and the speaker model should be deleted. - if (!value) { - if (prefs->GetBoolean(prefs::kHotwordAlwaysOnSearchEnabled)) { - prefs->SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, false); - HotwordPrivateEventService* event_service = - BrowserContextKeyedAPIFactory<HotwordPrivateEventService>::Get( - profile_); - if (event_service) - event_service->OnDeleteSpeakerModel(); - } - } - } - callback.Run(success, value); -} - -void HotwordAudioHistoryHandler::SetAudioHistoryComplete( - bool new_enabled_value, - const HotwordAudioHistoryCallback& callback, - bool success, bool callback_enabled_value) { - UpdateLocalPreference(success, new_enabled_value); - callback.Run(success, new_enabled_value); -}
diff --git a/chrome/browser/search/hotword_audio_history_handler.h b/chrome/browser/search/hotword_audio_history_handler.h deleted file mode 100644 index 8126b572..0000000 --- a/chrome/browser/search/hotword_audio_history_handler.h +++ /dev/null
@@ -1,81 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_SEARCH_HOTWORD_AUDIO_HISTORY_HANDLER_H_ -#define CHROME_BROWSER_SEARCH_HOTWORD_AUDIO_HISTORY_HANDLER_H_ - -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "components/prefs/pref_change_registrar.h" -#include "content/public/browser/browser_context.h" - -class Profile; - -namespace base { -class SingleThreadTaskRunner; -} - -namespace history { -class WebHistoryService; -} - -// A class which handles the audio history pref for hotwording. This has been -// pulled into its own class in order to transparently (to the rest of -// hotwording) handle changing user global pref management systems. -class HotwordAudioHistoryHandler { - public: - typedef base::Callback<void(bool success, bool new_enabled_value)> - HotwordAudioHistoryCallback; - - HotwordAudioHistoryHandler( - content::BrowserContext* context, - const scoped_refptr<base::SingleThreadTaskRunner>& task_runner); - - virtual ~HotwordAudioHistoryHandler(); - - // Initiates a call to get the updated audio history state. - void UpdateAudioHistoryState(); - - // Updates the current preference value based on the user's account info - // or false if the user is not signed in. - virtual void GetAudioHistoryEnabled( - const HotwordAudioHistoryCallback& callback); - - // Sets the user's global pref value for enabling audio history. - void SetAudioHistoryEnabled(const bool enabled, - const HotwordAudioHistoryCallback& callback); - - // This helper function is made public for testing. - virtual history::WebHistoryService* GetWebHistory(); - - private: - // Helper function used as a callback and to factor out common code. - void UpdateLocalPreference(bool success, bool new_enabled_value); - - // Called upon completion of web history->GetAudioHistoryEnabled. - void GetAudioHistoryComplete( - const HotwordAudioHistoryCallback& callback, - bool success, - bool new_enabled_value); - - // Called upon completion of web history->SetAudioHistoryEnabled. - // |new_enabled_value| is the desired value of the preference. - // |callback_enabled_value| should not be considered valid. - void SetAudioHistoryComplete( - bool new_enabled_value, - const HotwordAudioHistoryCallback& callback, - bool success, - bool callback_enabled_value); - - scoped_refptr<base::SingleThreadTaskRunner> task_runner_; - - Profile* profile_; - - base::WeakPtrFactory<HotwordAudioHistoryHandler> weak_ptr_factory_; - - DISALLOW_COPY_AND_ASSIGN(HotwordAudioHistoryHandler); -}; - -#endif // CHROME_BROWSER_SEARCH_HOTWORD_AUDIO_HISTORY_HANDLER_H_
diff --git a/chrome/browser/search/hotword_client.h b/chrome/browser/search/hotword_client.h deleted file mode 100644 index 13d2f35e..0000000 --- a/chrome/browser/search/hotword_client.h +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_SEARCH_HOTWORD_CLIENT_H_ -#define CHROME_BROWSER_SEARCH_HOTWORD_CLIENT_H_ - -#include "base/memory/ref_counted.h" - -namespace content { -struct SpeechRecognitionSessionPreamble; -} - -class HotwordClient { - public: - virtual ~HotwordClient() {} - - // Called when the hotword recognition session state has been changed. - virtual void OnHotwordStateChanged(bool started) {} - - // Called when the hotword is recognized. - virtual void OnHotwordRecognized( - const scoped_refptr<content::SpeechRecognitionSessionPreamble>& preamble) - = 0; -}; - -#endif // CHROME_BROWSER_SEARCH_HOTWORD_CLIENT_H_
diff --git a/chrome/browser/search/hotword_installer_browsertest.cc b/chrome/browser/search/hotword_installer_browsertest.cc deleted file mode 100644 index 2aa7eead..0000000 --- a/chrome/browser/search/hotword_installer_browsertest.cc +++ /dev/null
@@ -1,113 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <memory> - -#include "base/macros.h" -#include "base/memory/ptr_util.h" -#include "chrome/browser/extensions/extension_browsertest.h" -#include "chrome/browser/extensions/webstore_startup_installer.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/search/hotword_service.h" -#include "chrome/browser/search/hotword_service_factory.h" -#include "chrome/common/chrome_switches.h" -#include "chrome/common/extensions/extension_constants.h" -#include "chrome/common/extensions/webstore_install_result.h" -#include "chrome/test/base/testing_profile.h" -#include "content/public/test/test_utils.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace { -class MockHotwordWebstoreInstaller - : public HotwordService::HotwordWebstoreInstaller { - public: - MockHotwordWebstoreInstaller(Profile* profile, const Callback& callback) - : HotwordService::HotwordWebstoreInstaller( - extension_misc::kHotwordSharedModuleId, - profile, - callback) { - } - - const GURL& GetRequestorURL() const override { - // This should not be valid so it hangs. - return GURL::EmptyGURL(); - } - - void BeginInstall() { - WebstoreStandaloneInstaller::BeginInstall(); - } - - private: - ~MockHotwordWebstoreInstaller() override {} -}; - - -class MockHotwordService : public HotwordService { - public: - explicit MockHotwordService(Profile* profile) - : HotwordService(profile), - profile_(profile), - weak_factory_(this) { - } - - void InstallHotwordExtensionFromWebstore(int num_tries) override { - installer_ = new MockHotwordWebstoreInstaller( - profile_, - base::Bind(&MockHotwordService::InstallerCallback, - weak_factory_.GetWeakPtr(), - num_tries - 1)); - installer_->BeginInstall(); - } - - void InstallerCallback(int num_tries, - bool success, - const std::string& error, - extensions::webstore_install::Result result) { - } - - private: - Profile* profile_; - base::WeakPtrFactory<MockHotwordService> weak_factory_; -}; - -std::unique_ptr<KeyedService> BuildMockHotwordService( - content::BrowserContext* context) { - return base::MakeUnique<MockHotwordService>(static_cast<Profile*>(context)); -} - -} // namespace - -namespace extensions { - -class HotwordInstallerBrowserTest : public ExtensionBrowserTest { - public: - HotwordInstallerBrowserTest() {} - ~HotwordInstallerBrowserTest() override {} - - private: - DISALLOW_COPY_AND_ASSIGN(HotwordInstallerBrowserTest); -}; - -// Disabled on Windows due to https://crbug.com/717648. Since the installation -// is still in progress during shutdown, file handles may still be open. This -// causes TestingProfile to crash during shutdown. -#if defined(OS_WIN) -#define Maybe_AbortInstallOnShutdown DISABLED_AbortInstallOnShutdown -#else -#define Maybe_AbortInstallOnShutdown AbortInstallOnShutdown -#endif -// Test that installing to a non-existent URL (which should hang) does not -// crash. This test is successful if it does not crash and trigger any DCHECKS. -IN_PROC_BROWSER_TEST_F(HotwordInstallerBrowserTest, - Maybe_AbortInstallOnShutdown) { - TestingProfile test_profile; - HotwordServiceFactory* hotword_service_factory = - HotwordServiceFactory::GetInstance(); - MockHotwordService* hotword_service = static_cast<MockHotwordService*>( - hotword_service_factory->SetTestingFactoryAndUse( - &test_profile, BuildMockHotwordService)); - hotword_service->InstallHotwordExtensionFromWebstore(1); -} - -} // namespace extensions
diff --git a/chrome/browser/search/hotword_service.cc b/chrome/browser/search/hotword_service.cc deleted file mode 100644 index a19cdfe..0000000 --- a/chrome/browser/search/hotword_service.cc +++ /dev/null
@@ -1,883 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/search/hotword_service.h" - -#include <stddef.h> - -#include <string> - -#include "base/command_line.h" -#include "base/i18n/case_conversion.h" -#include "base/location.h" -#include "base/macros.h" -#include "base/metrics/field_trial.h" -#include "base/metrics/histogram_macros.h" -#include "base/metrics/sparse_histogram.h" -#include "base/path_service.h" -#include "base/single_thread_task_runner.h" -#include "base/threading/thread_task_runner_handle.h" -#include "build/build_config.h" -#include "chrome/browser/browser_process.h" -#include "chrome/browser/chrome_notification_types.h" -#include "chrome/browser/extensions/api/hotword_private/hotword_private_api.h" -#include "chrome/browser/extensions/extension_service.h" -#include "chrome/browser/extensions/pending_extension_manager.h" -#include "chrome/browser/extensions/updater/extension_updater.h" -#include "chrome/browser/notifications/notification_ui_manager.h" -#include "chrome/browser/plugins/plugin_prefs.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/profiles/profile_manager.h" -#include "chrome/browser/search/hotword_audio_history_handler.h" -#include "chrome/browser/search/hotword_service_factory.h" -#include "chrome/browser/ui/extensions/app_launch_params.h" -#include "chrome/browser/ui/extensions/application_launch.h" -#include "chrome/common/chrome_paths.h" -#include "chrome/common/chrome_switches.h" -#include "chrome/common/extensions/extension_constants.h" -#include "chrome/common/pref_names.h" -#include "chrome/grit/generated_resources.h" -#include "chrome/grit/theme_resources.h" -#include "components/language_usage_metrics/language_usage_metrics.h" -#include "components/prefs/pref_service.h" -#include "components/user_manager/user.h" -#include "components/user_manager/user_manager.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/browser/notification_service.h" -#include "content/public/browser/plugin_service.h" -#include "content/public/common/webplugininfo.h" -#include "extensions/browser/extension_system.h" -#include "extensions/browser/uninstall_reason.h" -#include "extensions/common/disable_reason.h" -#include "extensions/common/one_shot_event.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/message_center/notification.h" - -#if defined(OS_CHROMEOS) -#include "chromeos/audio/cras_audio_handler.h" -#endif - -using extensions::BrowserContextKeyedAPIFactory; -using extensions::HotwordPrivateEventService; - -namespace { - -// Allowed locales for hotwording. Note that Chrome does not support all of -// these locales, condensing them to their 2-letter equivalent, but the full -// list is here for completeness and testing. -static const char* kSupportedLocales[] = { - "en", - "en_au", - "en_ca", - "en_gb", - "en_nz", - "en_us", - "en_za", - "de", - "de_at", - "de_de", - "es", - "es_419", - "es_es", - "fr", - "fr_fr", - "it", - "it_it", - "ja", - "ja_jp", - "ko", - "ko_kr", - "pt_br", - "ru", - "ru_ru" -}; - -// Maximum number of retries for installing the hotword shared module from the -// web store. -static const int kMaxInstallRetries = 2; - -// Delay between retries for installing the hotword shared module from the web -// store. -static const int kInstallRetryDelaySeconds = 5; - -// The extension id of the old hotword voice search trigger extension. -const char kHotwordOldExtensionId[] = "bepbmhgboaologfdajaanbcjmnhjmhfn"; - -// Enum describing the state of the hotword preference. -// This is used for UMA stats -- do not reorder or delete items; only add to -// the end. -enum HotwordEnabled { - UNSET = 0, // No hotword preference has been set. - ENABLED, // The (classic) hotword preference is enabled. - DISABLED, // All hotwording is disabled. - ALWAYS_ON_ENABLED, // Always-on hotwording is enabled. - NUM_HOTWORD_ENABLED_METRICS -}; - -// Enum describing the availability state of the hotword extension. -// This is used for UMA stats -- do not reorder or delete items; only add to -// the end. -enum HotwordExtensionAvailability { - UNAVAILABLE = 0, - AVAILABLE, - PENDING_DOWNLOAD, - DISABLED_EXTENSION, - NUM_HOTWORD_EXTENSION_AVAILABILITY_METRICS -}; - -// Enum describing the types of errors that can arise when determining -// if hotwording can be used. NO_ERROR is used so it can be seen how often -// errors arise relative to when they do not. -// This is used for UMA stats -- do not reorder or delete items; only add to -// the end. -enum HotwordError { - NO_HOTWORD_ERROR = 0, - GENERIC_HOTWORD_ERROR, - NACL_HOTWORD_ERROR, - MICROPHONE_HOTWORD_ERROR, - NUM_HOTWORD_ERROR_METRICS -}; - -void RecordLoggingMetrics(Profile* profile) { - // If the user is not opted in to hotword voice search, the audio logging - // metric is not valid so it is not recorded. - if (!profile->GetPrefs()->GetBoolean(prefs::kHotwordSearchEnabled)) - return; - - UMA_HISTOGRAM_BOOLEAN( - "Hotword.HotwordAudioLogging", - profile->GetPrefs()->GetBoolean(prefs::kHotwordAudioLoggingEnabled)); -} - -void RecordErrorMetrics(int error_message) { - HotwordError error = NO_HOTWORD_ERROR; - switch (error_message) { - case IDS_HOTWORD_GENERIC_ERROR_MESSAGE: - error = GENERIC_HOTWORD_ERROR; - break; - case IDS_HOTWORD_NACL_DISABLED_ERROR_MESSAGE: - error = NACL_HOTWORD_ERROR; - break; - case IDS_HOTWORD_MICROPHONE_ERROR_MESSAGE: - error = MICROPHONE_HOTWORD_ERROR; - break; - default: - error = NO_HOTWORD_ERROR; - } - - UMA_HISTOGRAM_ENUMERATION("Hotword.HotwordError", - error, - NUM_HOTWORD_ERROR_METRICS); -} - -void RecordHotwordEnabledMetric(HotwordService *service, Profile* profile) { - HotwordEnabled enabled_state = DISABLED; - auto* prefs = profile->GetPrefs(); - if (!prefs->HasPrefPath(prefs::kHotwordSearchEnabled) && - !prefs->HasPrefPath(prefs::kHotwordAlwaysOnSearchEnabled)) { - enabled_state = UNSET; - } else if (service->IsAlwaysOnEnabled()) { - enabled_state = ALWAYS_ON_ENABLED; - } else if (prefs->GetBoolean(prefs::kHotwordSearchEnabled)) { - enabled_state = ENABLED; - } - UMA_HISTOGRAM_ENUMERATION("Hotword.Enabled", enabled_state, - NUM_HOTWORD_ENABLED_METRICS); -} - -ExtensionService* GetExtensionService(Profile* profile) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - extensions::ExtensionSystem* extension_system = - extensions::ExtensionSystem::Get(profile); - return extension_system ? extension_system->extension_service() : NULL; -} - -std::string GetCurrentLocale(Profile* profile) { -#if defined(OS_CHROMEOS) - std::string profile_locale = - profile->GetPrefs()->GetString(prefs::kApplicationLocale); - if (!profile_locale.empty()) { - // On ChromeOS locale is per-profile, but only if set. - return profile_locale; - } -#endif - return g_browser_process->GetApplicationLocale(); -} - -} // namespace - -namespace hotword_internal { -// String passed to indicate the training state has changed. -const char kHotwordTrainingEnabled[] = "hotword_training_enabled"; -// Id of the hotword notification. -const char kHotwordNotificationId[] = "hotword"; -// Notifier id for the hotword notification. -const char kHotwordNotifierId[] = "hotword.notification"; -} // namespace hotword_internal - -// Delegate for the hotword notification. -class HotwordNotificationDelegate - : public message_center::NotificationDelegate { - public: - explicit HotwordNotificationDelegate(Profile* profile) : profile_(profile) {} - - // Overridden from NotificationDelegate: - void ButtonClick(int button_index) override { - DCHECK_EQ(0, button_index); - Click(); - } - - void Click() override { - // Launch the hotword audio verification app in the right mode. - HotwordService::LaunchMode launch_mode = - HotwordService::HOTWORD_AND_AUDIO_HISTORY; - if (profile_->GetPrefs()->GetBoolean( - prefs::kHotwordAudioLoggingEnabled)) { - launch_mode = HotwordService::HOTWORD_ONLY; - } - - HotwordService* hotword_service = - HotwordServiceFactory::GetForProfile(profile_); - - if (!hotword_service) - return; - - hotword_service->LaunchHotwordAudioVerificationApp(launch_mode); - - // Close the notification after it's been clicked on to remove it - // from the notification tray. - g_browser_process->notification_ui_manager()->CancelById( - hotword_internal::kHotwordNotificationId, - NotificationUIManager::GetProfileID(profile_)); - } - - private: - ~HotwordNotificationDelegate() override {} - - Profile* profile_; - - DISALLOW_COPY_AND_ASSIGN(HotwordNotificationDelegate); -}; - -// static -bool HotwordService::DoesHotwordSupportLanguage(Profile* profile) { - std::string normalized_locale = - base::ToLowerASCII(l10n_util::NormalizeLocale(GetCurrentLocale(profile))); - - // For M43, we are limiting always-on to en_us only. - // TODO(kcarattini): Remove this once - // https://code.google.com/p/chrome-os-partner/issues/detail?id=39227 - // is fixed. - if (HotwordServiceFactory::IsAlwaysOnAvailable()) - return normalized_locale == "en_us"; - - for (size_t i = 0; i < arraysize(kSupportedLocales); i++) { - if (normalized_locale == kSupportedLocales[i]) - return true; - } - return false; -} - -// static -bool HotwordService::IsHotwordHardwareAvailable() { -#if defined(OS_CHROMEOS) - if (chromeos::CrasAudioHandler::IsInitialized()) { - chromeos::AudioDeviceList devices; - chromeos::CrasAudioHandler::Get()->GetAudioDevices(&devices); - for (size_t i = 0; i < devices.size(); ++i) { - if (devices[i].type == chromeos::AUDIO_TYPE_HOTWORD) { - DCHECK(devices[i].is_input); - return true; - } - } - } -#endif - return false; -} - -#if defined(OS_CHROMEOS) -class HotwordService::HotwordUserSessionStateObserver - : public user_manager::UserManager::UserSessionStateObserver { - public: - explicit HotwordUserSessionStateObserver(HotwordService* service) - : service_(service) {} - - // Overridden from UserSessionStateObserver: - void ActiveUserChanged(const user_manager::User* active_user) override { - service_->ActiveUserChanged(); - } - - private: - HotwordService* service_; // Not owned -}; -#else -// Dummy class to please the linker. -class HotwordService::HotwordUserSessionStateObserver { -}; -#endif - -void HotwordService::HotwordWebstoreInstaller::Shutdown() { - AbortInstall(); -} - -HotwordService::HotwordService(Profile* profile) - : profile_(profile), - extension_registry_observer_(this), - microphone_available_(false), - audio_device_state_updated_(false), - client_(NULL), - error_message_(0), - reinstall_pending_(false), - training_(false), - weak_factory_(this) { - extension_registry_observer_.Add(extensions::ExtensionRegistry::Get(profile)); - - // Disable the old extension so it doesn't interfere with the new stuff. - ExtensionService* extension_service = GetExtensionService(profile_); - if (extension_service) { - extension_service->DisableExtension( - kHotwordOldExtensionId, - extensions::disable_reason::DISABLE_USER_ACTION); - } - - // This will be called during profile initialization which is a good time - // to check the user's hotword state. - RecordHotwordEnabledMetric(this, profile_); - - pref_registrar_.Init(profile_->GetPrefs()); - pref_registrar_.Add( - prefs::kHotwordAlwaysOnSearchEnabled, - base::Bind(&HotwordService::OnHotwordAlwaysOnSearchEnabledChanged, - base::Unretained(this))); - - extensions::ExtensionSystem::Get(profile_)->ready().Post( - FROM_HERE, - base::Bind(base::IgnoreResult( - &HotwordService::MaybeReinstallHotwordExtension), - weak_factory_.GetWeakPtr())); - -// This service is actually used only on ChromeOS, and the next function -// results in a sequence of calls that triggers -// HotwordAudioHistoryHandler::GetAudioHistoryEnabled which is not supported -// on other platforms. -#if defined(OS_CHROMEOS) - SetAudioHistoryHandler(new HotwordAudioHistoryHandler( - profile_, base::ThreadTaskRunnerHandle::Get())); -#endif - - if (HotwordServiceFactory::IsAlwaysOnAvailable() && - IsHotwordAllowed()) { - // Show the hotword notification in 5 seconds if the experimental flag is - // on, or in 10 minutes if not. We need to wait at least a few seconds - // for the hotword extension to be installed. - base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); - if (command_line->HasSwitch(switches::kEnableExperimentalHotwordHardware)) { - base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, - base::BindOnce(&HotwordService::ShowHotwordNotification, - weak_factory_.GetWeakPtr()), - base::TimeDelta::FromSeconds(5)); - } else if (!profile_->GetPrefs()->GetBoolean( - prefs::kHotwordAlwaysOnNotificationSeen)) { - base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, - base::BindOnce(&HotwordService::ShowHotwordNotification, - weak_factory_.GetWeakPtr()), - base::TimeDelta::FromMinutes(10)); - } - } - -#if defined(OS_CHROMEOS) - if (user_manager::UserManager::IsInitialized()) { - session_observer_.reset(new HotwordUserSessionStateObserver(this)); - user_manager::UserManager::Get()->AddSessionStateObserver( - session_observer_.get()); - } -#endif - - // Register with the device observer list to update the microphone - // availability. - content::BrowserThread::PostTask( - content::BrowserThread::UI, FROM_HERE, - base::BindOnce(&HotwordService::InitializeMicrophoneObserver, - weak_factory_.GetWeakPtr())); -} - -HotwordService::~HotwordService() { -#if defined(OS_CHROMEOS) - if (user_manager::UserManager::IsInitialized() && session_observer_) { - user_manager::UserManager::Get()->RemoveSessionStateObserver( - session_observer_.get()); - } -#endif -} - -void HotwordService::Shutdown() { - if (installer_.get()) - installer_->Shutdown(); -} - -void HotwordService::ShowHotwordNotification() { - // Check for enabled here in case always-on was enabled during the delay. - if (!IsServiceAvailable() || IsAlwaysOnEnabled()) - return; - - message_center::RichNotificationData data; - const base::string16 label = l10n_util::GetStringUTF16( - IDS_HOTWORD_NOTIFICATION_BUTTON); - data.buttons.push_back(message_center::ButtonInfo(label)); - - message_center::Notification notification( - message_center::NOTIFICATION_TYPE_SIMPLE, - hotword_internal::kHotwordNotificationId, - l10n_util::GetStringUTF16(IDS_HOTWORD_NOTIFICATION_TITLE), - l10n_util::GetStringUTF16(IDS_HOTWORD_NOTIFICATION_DESCRIPTION), - ui::ResourceBundle::GetSharedInstance().GetImageNamed( - IDR_HOTWORD_NOTIFICATION_ICON), - base::string16(), GURL(), - message_center::NotifierId(message_center::NotifierId::SYSTEM_COMPONENT, - hotword_internal::kHotwordNotifierId), - data, new HotwordNotificationDelegate(profile_)); - - g_browser_process->notification_ui_manager()->Add(notification, profile_); - profile_->GetPrefs()->SetBoolean( - prefs::kHotwordAlwaysOnNotificationSeen, true); -} - -void HotwordService::OnExtensionUninstalled( - content::BrowserContext* browser_context, - const extensions::Extension* extension, - extensions::UninstallReason reason) { - CHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); - - if (extension->id() != extension_misc::kHotwordSharedModuleId || - profile_ != Profile::FromBrowserContext(browser_context) || - !GetExtensionService(profile_)) - return; - - // If the extension wasn't uninstalled due to language change, don't try to - // reinstall it. - if (!reinstall_pending_) - return; - - InstallHotwordExtensionFromWebstore(kMaxInstallRetries); - SetPreviousLanguagePref(); -} - -std::string HotwordService::ReinstalledExtensionId() { - return extension_misc::kHotwordSharedModuleId; -} - -void HotwordService::InitializeMicrophoneObserver() { - MediaCaptureDevicesDispatcher::GetInstance()->AddObserver(this); -} - -void HotwordService::InstalledFromWebstoreCallback( - int num_tries, - bool success, - const std::string& error, - extensions::webstore_install::Result result) { - if (result != extensions::webstore_install::SUCCESS && num_tries) { - // Try again on failure. - content::BrowserThread::PostDelayedTask( - content::BrowserThread::UI, FROM_HERE, - base::BindOnce(&HotwordService::InstallHotwordExtensionFromWebstore, - weak_factory_.GetWeakPtr(), num_tries), - base::TimeDelta::FromSeconds(kInstallRetryDelaySeconds)); - } -} - -void HotwordService::InstallHotwordExtensionFromWebstore(int num_tries) { - installer_ = new HotwordWebstoreInstaller( - ReinstalledExtensionId(), - profile_, - base::Bind(&HotwordService::InstalledFromWebstoreCallback, - weak_factory_.GetWeakPtr(), - num_tries - 1)); - installer_->BeginInstall(); -} - -void HotwordService::OnExtensionInstalled( - content::BrowserContext* browser_context, - const extensions::Extension* extension, - bool is_update) { - - if (extension->id() != extension_misc::kHotwordSharedModuleId || - profile_ != Profile::FromBrowserContext(browser_context)) - return; - - // If the previous locale pref has never been set, set it now since - // the extension has been installed. - if (!profile_->GetPrefs()->HasPrefPath(prefs::kHotwordPreviousLanguage)) - SetPreviousLanguagePref(); - - // If MaybeReinstallHotwordExtension already triggered an uninstall, we - // don't want to loop and trigger another uninstall-install cycle. - // However, if we arrived here via an uninstall-triggered-install (and in - // that case |reinstall_pending_| will be true) then we know install - // has completed and we can reset |reinstall_pending_|. - if (!reinstall_pending_) - MaybeReinstallHotwordExtension(); - else - reinstall_pending_ = false; -} - -bool HotwordService::MaybeReinstallHotwordExtension() { - CHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); - - ExtensionService* extension_service = GetExtensionService(profile_); - if (!extension_service) - return false; - - const extensions::Extension* extension = extension_service->GetExtensionById( - ReinstalledExtensionId(), true); - if (!extension) - return false; - - // If the extension is currently pending, return and we'll check again - // after the install is finished. - extensions::PendingExtensionManager* pending_manager = - extension_service->pending_extension_manager(); - if (pending_manager->IsIdPending(extension->id())) - return false; - - // If there is already a pending request from HotwordService, don't try - // to uninstall either. - if (reinstall_pending_) - return false; - - // Check if the current locale matches the previous. If they don't match, - // uninstall the extension. - if (!ShouldReinstallHotwordExtension()) - return false; - - // Ensure the call to OnExtensionUninstalled was triggered by a language - // change so it's okay to reinstall. - reinstall_pending_ = true; - - // Disable always-on on a language change. We do this because the speaker-id - // model needs to be re-trained. - if (IsAlwaysOnEnabled()) { - profile_->GetPrefs()->SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, - false); - } - - // Record re-installs due to language change. - UMA_HISTOGRAM_SPARSE_SLOWLY( - "Hotword.SharedModuleReinstallLanguage", - language_usage_metrics::LanguageUsageMetrics::ToLanguageCode( - GetCurrentLocale(profile_))); - return UninstallHotwordExtension(extension_service); -} - -bool HotwordService::UninstallHotwordExtension( - ExtensionService* extension_service) { - base::string16 error; - std::string extension_id = ReinstalledExtensionId(); - if (!extension_service->UninstallExtension( - extension_id, - extensions::UNINSTALL_REASON_INTERNAL_MANAGEMENT, - &error)) { - LOG(WARNING) << "Cannot uninstall extension with id " - << extension_id - << ": " << error; - reinstall_pending_ = false; - return false; - } - return true; -} - -bool HotwordService::IsServiceAvailable() { - error_message_ = 0; - - // Determine if the extension is available. - extensions::ExtensionSystem* system = - extensions::ExtensionSystem::Get(profile_); - ExtensionService* service = system->extension_service(); - // Include disabled extensions (true parameter) since it may not be enabled - // if the user opted out. - const extensions::Extension* extension = - service->GetExtensionById(ReinstalledExtensionId(), true); - if (!extension) - error_message_ = IDS_HOTWORD_GENERIC_ERROR_MESSAGE; - - // TODO(amistry): Record availability of shared module in UMA. - RecordLoggingMetrics(profile_); - - // Determine if NaCl is available. - bool nacl_enabled = false; - base::FilePath path; - if (PathService::Get(chrome::FILE_NACL_PLUGIN, &path)) { - content::WebPluginInfo info; - PluginPrefs* plugin_prefs = PluginPrefs::GetForProfile(profile_).get(); - if (content::PluginService::GetInstance()->GetPluginInfoByPath(path, &info)) - nacl_enabled = plugin_prefs->IsPluginEnabled(info); - } - if (!nacl_enabled) - error_message_ = IDS_HOTWORD_NACL_DISABLED_ERROR_MESSAGE; - - RecordErrorMetrics(error_message_); - - // Determine if the proper audio capabilities exist. The first time this is - // called, it probably won't return in time, but that's why it won't be - // included in the error calculation. However, this use case is rare and - // typically the devices will be initialized by the time a user goes to - // settings. - HotwordServiceFactory::GetInstance()->UpdateMicrophoneState(); - if (audio_device_state_updated_) { - bool audio_capture_allowed = - profile_->GetPrefs()->GetBoolean(prefs::kAudioCaptureAllowed); - if (!audio_capture_allowed || !microphone_available_) - error_message_ = IDS_HOTWORD_MICROPHONE_ERROR_MESSAGE; - } - - return (error_message_ == 0) && IsHotwordAllowed(); -} - -bool HotwordService::IsHotwordAllowed() { -#if defined(ENABLE_HOTWORDING) - return DoesHotwordSupportLanguage(profile_); -#else - return false; -#endif -} - -bool HotwordService::IsOptedIntoAudioLogging() { - // Do not opt the user in if the preference has not been set. - return - profile_->GetPrefs()->HasPrefPath(prefs::kHotwordAudioLoggingEnabled) && - profile_->GetPrefs()->GetBoolean(prefs::kHotwordAudioLoggingEnabled); -} - -bool HotwordService::IsAlwaysOnEnabled() { - return - profile_->GetPrefs()->HasPrefPath(prefs::kHotwordAlwaysOnSearchEnabled) && - profile_->GetPrefs()->GetBoolean(prefs::kHotwordAlwaysOnSearchEnabled) && - HotwordServiceFactory::IsAlwaysOnAvailable(); -} - -bool HotwordService::IsSometimesOnEnabled() { - return profile_->GetPrefs()->HasPrefPath(prefs::kHotwordSearchEnabled) && - profile_->GetPrefs()->GetBoolean(prefs::kHotwordSearchEnabled) && - !HotwordServiceFactory::IsAlwaysOnAvailable(); -} - -void HotwordService::SpeakerModelExistsComplete(bool exists) { - if (exists) { - profile_->GetPrefs()-> - SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, true); - } else { - LaunchHotwordAudioVerificationApp(HotwordService::HOTWORD_ONLY); - } -} - -void HotwordService::OptIntoHotwording( - const LaunchMode& launch_mode) { - // If the notification is in the notification tray, remove it (since the user - // is manually opting in to hotwording, they do not need the promotion). - g_browser_process->notification_ui_manager()->CancelById( - hotword_internal::kHotwordNotificationId, - NotificationUIManager::GetProfileID(profile_)); - - // First determine if we actually need to launch the app, or can just enable - // the pref. If Audio History has already been enabled, and we already have - // a speaker model, then we don't need to launch the app at all. - if (launch_mode == HotwordService::HOTWORD_ONLY) { - HotwordPrivateEventService* event_service = - BrowserContextKeyedAPIFactory<HotwordPrivateEventService>::Get( - profile_); - if (event_service) { - event_service->OnSpeakerModelExists(); - return; - } - } - - LaunchHotwordAudioVerificationApp(launch_mode); -} - -void HotwordService::LaunchHotwordAudioVerificationApp( - const LaunchMode& launch_mode) { - hotword_audio_verification_launch_mode_ = launch_mode; - - ExtensionService* extension_service = GetExtensionService(profile_); - if (!extension_service) - return; - const extensions::Extension* extension = extension_service->GetExtensionById( - extension_misc::kHotwordAudioVerificationAppId, true); - if (!extension) - return; - - OpenApplication(AppLaunchParams( - profile_, extension, extensions::LAUNCH_CONTAINER_WINDOW, - WindowOpenDisposition::NEW_WINDOW, extensions::SOURCE_CHROME_INTERNAL)); -} - -HotwordService::LaunchMode -HotwordService::GetHotwordAudioVerificationLaunchMode() { - return hotword_audio_verification_launch_mode_; -} - -void HotwordService::StartTraining() { - training_ = true; - - if (!IsServiceAvailable()) - return; - - HotwordPrivateEventService* event_service = - BrowserContextKeyedAPIFactory<HotwordPrivateEventService>::Get(profile_); - if (event_service) - event_service->OnEnabledChanged(hotword_internal::kHotwordTrainingEnabled); -} - -void HotwordService::FinalizeSpeakerModel() { - if (!IsServiceAvailable()) - return; - - HotwordPrivateEventService* event_service = - BrowserContextKeyedAPIFactory<HotwordPrivateEventService>::Get(profile_); - if (event_service) - event_service->OnFinalizeSpeakerModel(); -} - -void HotwordService::StopTraining() { - training_ = false; - - if (!IsServiceAvailable()) - return; - - HotwordPrivateEventService* event_service = - BrowserContextKeyedAPIFactory<HotwordPrivateEventService>::Get(profile_); - if (event_service) - event_service->OnEnabledChanged(hotword_internal::kHotwordTrainingEnabled); -} - -void HotwordService::NotifyHotwordTriggered() { - if (!IsServiceAvailable()) - return; - - HotwordPrivateEventService* event_service = - BrowserContextKeyedAPIFactory<HotwordPrivateEventService>::Get(profile_); - if (event_service) - event_service->OnHotwordTriggered(); -} - -bool HotwordService::IsTraining() { - return training_; -} - -HotwordAudioHistoryHandler* HotwordService::GetAudioHistoryHandler() { - return audio_history_handler_.get(); -} - -void HotwordService::SetAudioHistoryHandler( - HotwordAudioHistoryHandler* handler) { - audio_history_handler_.reset(handler); - audio_history_handler_->UpdateAudioHistoryState(); -} - -void HotwordService::DisableHotwordPreferences() { - if (IsSometimesOnEnabled()) { - profile_->GetPrefs()->SetBoolean(prefs::kHotwordSearchEnabled, false); - } - if (IsAlwaysOnEnabled()) { - profile_->GetPrefs()->SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, - false); - } -} - -void HotwordService::OnUpdateAudioDevices( - const content::MediaStreamDevices& devices) { - bool microphone_was_available = microphone_available_; - microphone_available_ = !devices.empty(); - audio_device_state_updated_ = true; - HotwordPrivateEventService* event_service = - BrowserContextKeyedAPIFactory<HotwordPrivateEventService>::Get(profile_); - if (event_service && microphone_was_available != microphone_available_) - event_service->OnMicrophoneStateChanged(microphone_available_); -} - -void HotwordService::OnHotwordAlwaysOnSearchEnabledChanged( - const std::string& pref_name) { - // If the pref for always on has been changed in some way, that means that - // the user is aware of always on (either from settings or another source) - // so they don't need to be shown the notification. - profile_->GetPrefs()->SetBoolean(prefs::kHotwordAlwaysOnNotificationSeen, - true); - pref_registrar_.Remove(prefs::kHotwordAlwaysOnSearchEnabled); -} - -void HotwordService::RequestHotwordSession(HotwordClient* client) { - if (!IsServiceAvailable() || (client_ && client_ != client)) - return; - - client_ = client; - - HotwordPrivateEventService* event_service = - BrowserContextKeyedAPIFactory<HotwordPrivateEventService>::Get(profile_); - if (event_service) - event_service->OnHotwordSessionRequested(); -} - -void HotwordService::StopHotwordSession(HotwordClient* client) { - if (!IsServiceAvailable()) - return; - - // Do nothing if there's no client. - if (!client_) - return; - DCHECK(client_ == client); - - client_ = NULL; - HotwordPrivateEventService* event_service = - BrowserContextKeyedAPIFactory<HotwordPrivateEventService>::Get(profile_); - if (event_service) - event_service->OnHotwordSessionStopped(); -} - -void HotwordService::SetPreviousLanguagePref() { - profile_->GetPrefs()->SetString(prefs::kHotwordPreviousLanguage, - GetCurrentLocale(profile_)); -} - -bool HotwordService::ShouldReinstallHotwordExtension() { - // If there is no previous locale pref, then this is the first install - // so no need to uninstall first. - if (!profile_->GetPrefs()->HasPrefPath(prefs::kHotwordPreviousLanguage)) - return false; - - std::string previous_locale = - profile_->GetPrefs()->GetString(prefs::kHotwordPreviousLanguage); - std::string locale = GetCurrentLocale(profile_); - - // If it's a new locale, then the old extension should be uninstalled. - return locale != previous_locale && - HotwordService::DoesHotwordSupportLanguage(profile_); -} - -void HotwordService::ActiveUserChanged() { - // Don't bother notifying the extension if hotwording is completely off. - if (!IsSometimesOnEnabled() && !IsAlwaysOnEnabled() && !IsTraining()) - return; - - HotwordPrivateEventService* event_service = - BrowserContextKeyedAPIFactory<HotwordPrivateEventService>::Get(profile_); - // "enabled" isn't being changed, but piggy-back off the notification anyway. - if (event_service) - event_service->OnEnabledChanged(prefs::kHotwordSearchEnabled); -} - -bool HotwordService::UserIsActive() { -#if defined(OS_CHROMEOS) - // Only support multiple profiles and profile switching in ChromeOS. - if (user_manager::UserManager::IsInitialized()) { - user_manager::User* user = - user_manager::UserManager::Get()->GetActiveUser(); - if (user && user->is_profile_created()) - return profile_ == ProfileManager::GetActiveUserProfile(); - } -#endif - return true; -}
diff --git a/chrome/browser/search/hotword_service.h b/chrome/browser/search/hotword_service.h deleted file mode 100644 index 46f1e15..0000000 --- a/chrome/browser/search/hotword_service.h +++ /dev/null
@@ -1,244 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_SEARCH_HOTWORD_SERVICE_H_ -#define CHROME_BROWSER_SEARCH_HOTWORD_SERVICE_H_ - -#include <string> - -#include "base/macros.h" -#include "base/memory/weak_ptr.h" -#include "base/scoped_observer.h" -#include "chrome/browser/extensions/webstore_startup_installer.h" -#include "chrome/browser/media/webrtc/media_capture_devices_dispatcher.h" -#include "chrome/common/extensions/webstore_install_result.h" -#include "components/keyed_service/core/keyed_service.h" -#include "components/prefs/pref_change_registrar.h" -#include "content/public/browser/notification_observer.h" -#include "content/public/browser/notification_registrar.h" -#include "extensions/browser/extension_registry.h" -#include "extensions/browser/extension_registry_observer.h" - -class ExtensionService; -class HotwordAudioHistoryHandler; -class HotwordClient; -class Profile; - -namespace extensions { -class Extension; -} // namespace extensions - -namespace hotword_internal { -// String passed to indicate the training state has changed. -extern const char kHotwordTrainingEnabled[]; -} // namespace hotword_internal - -// Provides an interface for the Hotword component that does voice triggered -// search. -class HotwordService : public MediaCaptureDevicesDispatcher::Observer, - public extensions::ExtensionRegistryObserver, - public KeyedService { - public: - // A simple subclass to allow for aborting an install during shutdown. - // HotwordWebstoreInstaller class is public for testing. - class HotwordWebstoreInstaller : public extensions::WebstoreStartupInstaller { - public: - HotwordWebstoreInstaller(const std::string& webstore_item_id, - Profile* profile, - const Callback& callback) - : extensions::WebstoreStartupInstaller(webstore_item_id, - profile, - false, - callback) {} - void Shutdown(); - protected: - ~HotwordWebstoreInstaller() override {} - }; - - // Returns true if the hotword supports the current system language. - static bool DoesHotwordSupportLanguage(Profile* profile); - - // Returns true if hotwording hardware is available. - static bool IsHotwordHardwareAvailable(); - - explicit HotwordService(Profile* profile); - ~HotwordService() override; - - // Overridden from ExtensionRegisterObserver: - void OnExtensionInstalled(content::BrowserContext* browser_context, - const extensions::Extension* extension, - bool is_update) override; - void OnExtensionUninstalled(content::BrowserContext* browser_context, - const extensions::Extension* extension, - extensions::UninstallReason reason) override; - - // Overriden from KeyedService - void Shutdown() override; - - // Checks for whether all the necessary files have downloaded to allow for - // using the extension. - virtual bool IsServiceAvailable(); - - // Determine if hotwording is allowed in this profile based on field trials - // and language. - virtual bool IsHotwordAllowed(); - - // Checks if the user has opted into audio logging. Returns true if the user - // is opted in, false otherwise.. - bool IsOptedIntoAudioLogging(); - - // Returns whether always-on hotwording is enabled. - bool IsAlwaysOnEnabled(); - - // Returns whether google.com/NTP/launcher hotwording is enabled. - bool IsSometimesOnEnabled(); - - // Handles enabling/disabling the hotword notification when the user - // changes the always on search settings. - void OnHotwordAlwaysOnSearchEnabledChanged(const std::string& pref_name); - - // Called to handle the hotword session from |client|. - void RequestHotwordSession(HotwordClient* client); - void StopHotwordSession(HotwordClient* client); - HotwordClient* client() { return client_; } - - // Checks if the current version of the hotword extension should be - // uninstalled in order to update to a different language version. - // Returns true if the extension was uninstalled. - bool MaybeReinstallHotwordExtension(); - - // Checks based on locale if the current version should be uninstalled so that - // a version with a different language can be installed. - bool ShouldReinstallHotwordExtension(); - - // Helper functions pulled out for testing purposes. - // UninstallHotwordExtension returns true if the extension was uninstalled. - virtual bool UninstallHotwordExtension(ExtensionService* extension_service); - virtual void InstallHotwordExtensionFromWebstore(int num_tries); - - // Sets the pref value of the previous language. - void SetPreviousLanguagePref(); - - // Returns the current error message id. A value of 0 indicates - // no error. - int error_message() { return error_message_; } - - bool microphone_available() { return microphone_available_; } - - // These methods are for launching, and getting and setting the launch mode of - // the Hotword Audio Verification App. - // - // OptIntoHotwording first determines if the app needs to be launched, and if - // so, launches the app (if Audio History is on and a speaker model exists, - // then we don't need to launch the app). - // - // LaunchHotwordAudioVerificationApp launches the app without the above - // check in the specified |launch_mode|. - enum LaunchMode { - HOTWORD_ONLY, - HOTWORD_AND_AUDIO_HISTORY, - RETRAIN - }; - void OptIntoHotwording(const LaunchMode& launch_mode); - void LaunchHotwordAudioVerificationApp(const LaunchMode& launch_mode); - virtual LaunchMode GetHotwordAudioVerificationLaunchMode(); - - // Called when the SpeakerModelExists request is complete. Either - // sets the always-on hotword pref to true, or launches the Hotword - // Audio Verification App, depending on the value of |exists|. - void SpeakerModelExistsComplete(bool exists); - - // These methods control the speaker training communication between - // the Hotword Audio Verification App and the Hotword Extension that - // contains the NaCl module. - void StartTraining(); - void FinalizeSpeakerModel(); - void StopTraining(); - void NotifyHotwordTriggered(); - - // Returns true if speaker training is currently in progress. - bool IsTraining(); - - // Indicate that the currently active user has changed. - void ActiveUserChanged(); - - // Return true if this profile corresponds to the currently active user. - bool UserIsActive(); - - // Returns a pointer to the audio history handler. - HotwordAudioHistoryHandler* GetAudioHistoryHandler(); - - // Sets the audio history handler. Used for tests. - void SetAudioHistoryHandler(HotwordAudioHistoryHandler* handler); - - // Turn off the currently enabled version of hotwording if one exists. - void DisableHotwordPreferences(); - - // Overridden from MediaCaptureDevicesDispatcher::Observer - void OnUpdateAudioDevices( - const content::MediaStreamDevices& devices) override; - - protected: - // Used in test subclasses. - scoped_refptr<HotwordWebstoreInstaller> installer_; - - private: - class HotwordUserSessionStateObserver; - - // Must be called from the UI thread since the instance of - // MediaCaptureDevicesDispatcher can only be accessed on the UI thread. - void InitializeMicrophoneObserver(); - - // Callback for webstore extension installer. - void InstalledFromWebstoreCallback( - int num_tries, - bool success, - const std::string& error, - extensions::webstore_install::Result result); - - // Returns the ID of the extension that may need to be reinstalled. - std::string ReinstalledExtensionId(); - - // Creates a notification for always-on hotwording. - void ShowHotwordNotification(); - - Profile* profile_; - - PrefChangeRegistrar pref_registrar_; - - content::NotificationRegistrar registrar_; - - // For observing the ExtensionRegistry. - ScopedObserver<extensions::ExtensionRegistry, - extensions::ExtensionRegistryObserver> - extension_registry_observer_; - - std::unique_ptr<HotwordAudioHistoryHandler> audio_history_handler_; - - bool microphone_available_; - - // Indicates if the check for audio devices has been run such that it can be - // included in the error checking. Audio checking is not done immediately - // upon start up because of the negative impact on performance. - bool audio_device_state_updated_; - - HotwordClient* client_; - int error_message_; - bool reinstall_pending_; - // Whether we are currently in the process of training the speaker model. - bool training_; - std::unique_ptr<HotwordUserSessionStateObserver> session_observer_; - - // Stores the launch mode for the Hotword Audio Verification App. - LaunchMode hotword_audio_verification_launch_mode_; - - // The WeakPtrFactory should be the last member, so the weak pointer - // gets invalidated before the destructors for other members run, - // to avoid callbacks into a half-destroyed object. - base::WeakPtrFactory<HotwordService> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(HotwordService); -}; - -#endif // CHROME_BROWSER_SEARCH_HOTWORD_SERVICE_H_
diff --git a/chrome/browser/search/hotword_service_factory.cc b/chrome/browser/search/hotword_service_factory.cc deleted file mode 100644 index d18b14c..0000000 --- a/chrome/browser/search/hotword_service_factory.cc +++ /dev/null
@@ -1,96 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/search/hotword_service_factory.h" - -#include "base/command_line.h" -#include "build/build_config.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/search/hotword_service.h" -#include "chrome/common/chrome_switches.h" -#include "chrome/common/pref_names.h" -#include "components/keyed_service/content/browser_context_dependency_manager.h" -#include "components/pref_registry/pref_registry_syncable.h" -#include "components/prefs/pref_service.h" -#include "content/public/browser/browser_context.h" -#include "content/public/browser/browser_thread.h" - -using content::BrowserContext; -using content::BrowserThread; - -// static -HotwordService* HotwordServiceFactory::GetForProfile(BrowserContext* context) { - return static_cast<HotwordService*>( - GetInstance()->GetServiceForBrowserContext(context, true)); -} - -// static -HotwordServiceFactory* HotwordServiceFactory::GetInstance() { - return base::Singleton<HotwordServiceFactory>::get(); -} - -// static -bool HotwordServiceFactory::IsServiceAvailable(BrowserContext* context) { - HotwordService* hotword_service = GetForProfile(context); - return hotword_service && hotword_service->IsServiceAvailable(); -} - -// static -bool HotwordServiceFactory::IsHotwordAllowed(BrowserContext* context) { - HotwordService* hotword_service = GetForProfile(context); - return hotword_service && hotword_service->IsHotwordAllowed(); -} - -// static -bool HotwordServiceFactory::IsAlwaysOnAvailable() { -#if defined(OS_CHROMEOS) - if (HotwordService::IsHotwordHardwareAvailable()) - return true; -#endif - base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); - return command_line->HasSwitch(switches::kEnableExperimentalHotwordHardware); -} - -// static -int HotwordServiceFactory::GetCurrentError(BrowserContext* context) { - HotwordService* hotword_service = GetForProfile(context); - if (!hotword_service) - return 0; - return hotword_service->error_message(); -} - -HotwordServiceFactory::HotwordServiceFactory() - : BrowserContextKeyedServiceFactory( - "HotwordService", - BrowserContextDependencyManager::GetInstance()) { - // No dependencies. -} - -HotwordServiceFactory::~HotwordServiceFactory() { -} - -void HotwordServiceFactory::UpdateMicrophoneState() { - // In order to trigger the monitor, just call getAudioCaptureDevices. - content::MediaStreamDevices devices = - MediaCaptureDevicesDispatcher::GetInstance()->GetAudioCaptureDevices(); -} - -void HotwordServiceFactory::RegisterProfilePrefs( - user_prefs::PrefRegistrySyncable* prefs) { - prefs->RegisterBooleanPref(prefs::kHotwordAudioLoggingEnabled, - false, - user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); - prefs->RegisterStringPref(prefs::kHotwordPreviousLanguage, - std::string(), - user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); - // Per-device settings (do not sync). - prefs->RegisterBooleanPref(prefs::kHotwordSearchEnabled, false); - prefs->RegisterBooleanPref(prefs::kHotwordAlwaysOnSearchEnabled, false); - prefs->RegisterBooleanPref(prefs::kHotwordAlwaysOnNotificationSeen, false); -} - -KeyedService* HotwordServiceFactory::BuildServiceInstanceFor( - BrowserContext* context) const { - return new HotwordService(Profile::FromBrowserContext(context)); -}
diff --git a/chrome/browser/search/hotword_service_factory.h b/chrome/browser/search/hotword_service_factory.h deleted file mode 100644 index 050872c1..0000000 --- a/chrome/browser/search/hotword_service_factory.h +++ /dev/null
@@ -1,58 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_SEARCH_HOTWORD_SERVICE_FACTORY_H_ -#define CHROME_BROWSER_SEARCH_HOTWORD_SERVICE_FACTORY_H_ - -#include "base/macros.h" -#include "base/memory/singleton.h" -#include "components/keyed_service/content/browser_context_keyed_service_factory.h" - -class HotwordService; - -// Singleton that owns all HotwordServices and associates them with Profiles. -class HotwordServiceFactory : public BrowserContextKeyedServiceFactory { - public: - // Returns the HotwordService for |context|. - static HotwordService* GetForProfile(content::BrowserContext* context); - - static HotwordServiceFactory* GetInstance(); - - // Returns true if the hotwording service is available for |context|. - static bool IsServiceAvailable(content::BrowserContext* context); - - // Returns true if hotwording is allowed for |context|. - static bool IsHotwordAllowed(content::BrowserContext* context); - - // Returns whether always-on hotwording is available. - static bool IsAlwaysOnAvailable(); - - // Returns the current error message for the service for |context|. - // A value of 0 indicates no error. - static int GetCurrentError(content::BrowserContext* context); - - // This will kick off the monitor that calls OnUpdateAudioDevices when the - // number of audio devices changes (or is initialized). It needs to be a - // separate function so it can be called after the service is initialized - // (i.e., after startup). The monitor can't be initialized during startup - // because it would slow down startup too much so it is delayed and not - // called until it's needed by the webui in browser_options_handler. - void UpdateMicrophoneState(); - - private: - friend struct base::DefaultSingletonTraits<HotwordServiceFactory>; - - HotwordServiceFactory(); - ~HotwordServiceFactory() override; - - // Overrides from BrowserContextKeyedServiceFactory: - void RegisterProfilePrefs( - user_prefs::PrefRegistrySyncable* registry) override; - KeyedService* BuildServiceInstanceFor( - content::BrowserContext* context) const override; - - DISALLOW_COPY_AND_ASSIGN(HotwordServiceFactory); -}; - -#endif // CHROME_BROWSER_SEARCH_HOTWORD_SERVICE_FACTORY_H_
diff --git a/chrome/browser/search/hotword_service_unittest.cc b/chrome/browser/search/hotword_service_unittest.cc deleted file mode 100644 index e0eb877..0000000 --- a/chrome/browser/search/hotword_service_unittest.cc +++ /dev/null
@@ -1,534 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/search/hotword_service.h" - -#include <memory> -#include <utility> - -#include "base/command_line.h" -#include "base/memory/ptr_util.h" -#include "base/metrics/field_trial.h" -#include "base/run_loop.h" -#include "base/test/test_simple_task_runner.h" -#include "build/build_config.h" -#include "chrome/browser/browser_process.h" -#include "chrome/browser/extensions/extension_service_test_base.h" -#include "chrome/browser/extensions/test_extension_service.h" -#include "chrome/browser/search/hotword_audio_history_handler.h" -#include "chrome/browser/search/hotword_service_factory.h" -#include "chrome/common/chrome_switches.h" -#include "chrome/common/extensions/extension_constants.h" -#include "chrome/common/pref_names.h" -#include "chrome/test/base/testing_profile.h" -#include "components/history/core/browser/web_history_service.h" -#include "components/prefs/pref_service.h" -#include "content/public/test/test_browser_thread_bundle.h" -#include "extensions/browser/extension_system.h" -#include "extensions/common/extension.h" -#include "extensions/common/extension_builder.h" -#include "extensions/common/manifest.h" -#include "extensions/common/one_shot_event.h" -#include "testing/gtest/include/gtest/gtest.h" - -#if defined(OS_CHROMEOS) -#include "chromeos/audio/cras_audio_handler.h" -#endif - -namespace { - -class MockAudioHistoryHandler : public HotwordAudioHistoryHandler { - public: - MockAudioHistoryHandler( - content::BrowserContext* context, - const scoped_refptr<base::SingleThreadTaskRunner>& task_runner, - history::WebHistoryService* web_history) - : HotwordAudioHistoryHandler(context, task_runner), - get_audio_history_calls_(0), - web_history_(web_history) { - } - ~MockAudioHistoryHandler() override {} - - void GetAudioHistoryEnabled( - const HotwordAudioHistoryCallback& callback) override { - get_audio_history_calls_++; - callback.Run(true, true); - } - - history::WebHistoryService* GetWebHistory() override { - return web_history_.get(); - } - - int GetAudioHistoryCalls() { - return get_audio_history_calls_; - } - - private: - int get_audio_history_calls_; - std::unique_ptr<history::WebHistoryService> web_history_; -}; - -class MockHotwordService : public HotwordService { - public: - explicit MockHotwordService(Profile* profile) - : HotwordService(profile), - uninstall_count_(0) { - } - - bool UninstallHotwordExtension(ExtensionService* extension_service) override { - uninstall_count_++; - return HotwordService::UninstallHotwordExtension(extension_service); - } - - void InstallHotwordExtensionFromWebstore(int num_tries) override { - std::unique_ptr<base::DictionaryValue> manifest = - extensions::DictionaryBuilder() - .Set("name", "Hotword Test Extension") - .Set("version", "1.0") - .Set("manifest_version", 2) - .Build(); - scoped_refptr<extensions::Extension> extension = - extensions::ExtensionBuilder() - .SetManifest(std::move(manifest)) - .AddFlags(extensions::Extension::FROM_WEBSTORE | - extensions::Extension::WAS_INSTALLED_BY_DEFAULT) - .SetID(extension_id_) - .SetLocation(extensions::Manifest::EXTERNAL_COMPONENT) - .Build(); - ASSERT_TRUE(extension.get()); - service_->OnExtensionInstalled(extension.get(), syncer::StringOrdinal()); - } - - - int uninstall_count() { return uninstall_count_; } - - void SetExtensionService(ExtensionService* service) { service_ = service; } - void SetExtensionId(const std::string& extension_id) { - extension_id_ = extension_id; - } - - ExtensionService* extension_service() { return service_; } - - private: - ExtensionService* service_; - int uninstall_count_; - std::string extension_id_; -}; - -std::unique_ptr<KeyedService> BuildMockHotwordService( - content::BrowserContext* context) { - return base::MakeUnique<MockHotwordService>(static_cast<Profile*>(context)); -} - -} // namespace - -class HotwordServiceTest : - public extensions::ExtensionServiceTestBase, - public ::testing::WithParamInterface<const char*> { - protected: - HotwordServiceTest() {} - virtual ~HotwordServiceTest() {} - - void SetApplicationLocale(Profile* profile, const std::string& new_locale) { -#if defined(OS_CHROMEOS) - // On ChromeOS locale is per-profile. - profile->GetPrefs()->SetString(prefs::kApplicationLocale, new_locale); -#else - g_browser_process->SetApplicationLocale(new_locale); -#endif - } - - void SetUp() override { - extension_id_ = GetParam(); -#if defined(OS_CHROMEOS) - // Tests on chromeos need to have the handler initialized. - chromeos::CrasAudioHandler::InitializeForTesting(); -#endif - - extensions::ExtensionServiceTestBase::SetUp(); - } - - void TearDown() override { -#if defined(OS_CHROMEOS) - DCHECK(chromeos::CrasAudioHandler::IsInitialized()); - chromeos::CrasAudioHandler::Shutdown(); -#endif - } - - std::string extension_id_; -}; - -INSTANTIATE_TEST_CASE_P(HotwordServiceTests, - HotwordServiceTest, - ::testing::Values( - extension_misc::kHotwordSharedModuleId)); - -// Disabled due to http://crbug.com/503963. -TEST_P(HotwordServiceTest, DISABLED_IsHotwordAllowedLocale) { - TestingProfile::Builder profile_builder; - std::unique_ptr<TestingProfile> profile = profile_builder.Build(); - -#if defined(ENABLE_HOTWORDING) - bool hotwording_enabled = true; -#else - bool hotwording_enabled = false; -#endif - - // Check that the service exists so that a NULL service be ruled out in - // following tests. - HotwordService* hotword_service = - HotwordServiceFactory::GetForProfile(profile.get()); - EXPECT_TRUE(hotword_service != NULL); - - // Set the language to an invalid one. - SetApplicationLocale(static_cast<Profile*>(profile.get()), "non-valid"); - EXPECT_FALSE(HotwordServiceFactory::IsHotwordAllowed(profile.get())); - - // Now with valid locales it should be fine. - SetApplicationLocale(static_cast<Profile*>(profile.get()), "en"); - EXPECT_EQ(hotwording_enabled, - HotwordServiceFactory::IsHotwordAllowed(profile.get())); - SetApplicationLocale(static_cast<Profile*>(profile.get()), "en-US"); - EXPECT_EQ(hotwording_enabled, - HotwordServiceFactory::IsHotwordAllowed(profile.get())); - SetApplicationLocale(static_cast<Profile*>(profile.get()), "en_us"); - EXPECT_EQ(hotwording_enabled, - HotwordServiceFactory::IsHotwordAllowed(profile.get())); - SetApplicationLocale(static_cast<Profile*>(profile.get()), "de_DE"); - EXPECT_EQ(hotwording_enabled, - HotwordServiceFactory::IsHotwordAllowed(profile.get())); - SetApplicationLocale(static_cast<Profile*>(profile.get()), "fr_fr"); - EXPECT_EQ(hotwording_enabled, - HotwordServiceFactory::IsHotwordAllowed(profile.get())); - - // Test that incognito even with a valid locale and valid field trial - // still returns false. - Profile* otr_profile = profile->GetOffTheRecordProfile(); - SetApplicationLocale(otr_profile, "en"); - EXPECT_FALSE(HotwordServiceFactory::IsHotwordAllowed(otr_profile)); -} - -TEST_P(HotwordServiceTest, ShouldReinstallExtension) { - InitializeEmptyExtensionService(); - - HotwordServiceFactory* hotword_service_factory = - HotwordServiceFactory::GetInstance(); - - MockHotwordService* hotword_service = static_cast<MockHotwordService*>( - hotword_service_factory->SetTestingFactoryAndUse( - profile(), BuildMockHotwordService)); - ASSERT_TRUE(hotword_service != NULL); - hotword_service->SetExtensionId(extension_id_); - - // If no locale has been set, no reason to uninstall. - EXPECT_FALSE(hotword_service->ShouldReinstallHotwordExtension()); - - SetApplicationLocale(profile(), "en"); - hotword_service->SetPreviousLanguagePref(); - - // Now a locale is set, but it hasn't changed. - EXPECT_FALSE(hotword_service->ShouldReinstallHotwordExtension()); - - SetApplicationLocale(profile(), "fr_fr"); - - // Now it's a different locale so it should uninstall. - EXPECT_TRUE(hotword_service->ShouldReinstallHotwordExtension()); -} - -TEST_P(HotwordServiceTest, PreviousLanguageSetOnInstall) { - InitializeEmptyExtensionService(); - service_->Init(); - - HotwordServiceFactory* hotword_service_factory = - HotwordServiceFactory::GetInstance(); - - MockHotwordService* hotword_service = static_cast<MockHotwordService*>( - hotword_service_factory->SetTestingFactoryAndUse( - profile(), BuildMockHotwordService)); - ASSERT_TRUE(hotword_service != NULL); - hotword_service->SetExtensionService(service()); - hotword_service->SetExtensionId(extension_id_); - - // If no locale has been set, no reason to uninstall. - EXPECT_FALSE(hotword_service->ShouldReinstallHotwordExtension()); - - SetApplicationLocale(profile(), "test_locale"); - - hotword_service->InstallHotwordExtensionFromWebstore(1); - base::RunLoop().RunUntilIdle(); - - EXPECT_EQ("test_locale", - profile()->GetPrefs()->GetString(prefs::kHotwordPreviousLanguage)); -} - -TEST_P(HotwordServiceTest, UninstallReinstallTriggeredCorrectly) { - InitializeEmptyExtensionService(); - service_->Init(); - - HotwordServiceFactory* hotword_service_factory = - HotwordServiceFactory::GetInstance(); - - MockHotwordService* hotword_service = static_cast<MockHotwordService*>( - hotword_service_factory->SetTestingFactoryAndUse( - profile(), BuildMockHotwordService)); - ASSERT_TRUE(hotword_service != NULL); - hotword_service->SetExtensionService(service()); - hotword_service->SetExtensionId(extension_id_); - - // Initialize the locale to "en". - SetApplicationLocale(profile(), "en"); - - // The previous locale should not be set. No reason to uninstall. - EXPECT_FALSE(hotword_service->MaybeReinstallHotwordExtension()); - - // Do an initial installation. - hotword_service->InstallHotwordExtensionFromWebstore(1); - base::RunLoop().RunUntilIdle(); - EXPECT_EQ("en", - profile()->GetPrefs()->GetString(prefs::kHotwordPreviousLanguage)); - - if (extension_id_ == extension_misc::kHotwordSharedModuleId) { - // Shared module is installed and enabled. - EXPECT_EQ(0U, registry()->disabled_extensions().size()); - EXPECT_TRUE(registry()->enabled_extensions().Contains(extension_id_)); - } else { - // Verify the extension is installed but disabled. - EXPECT_EQ(1U, registry()->disabled_extensions().size()); - EXPECT_TRUE(registry()->disabled_extensions().Contains(extension_id_)); - } - - // The previous locale should be set but should match the current - // locale. No reason to uninstall. - EXPECT_FALSE(hotword_service->MaybeReinstallHotwordExtension()); - - // Switch the locale to a valid but different one. - SetApplicationLocale(profile(), "fr_fr"); -#if defined(ENABLE_HOTWORDING) - EXPECT_TRUE(HotwordServiceFactory::IsHotwordAllowed(profile())); -#else - // Disabled due to http://crbug.com/503963. - // EXPECT_FALSE(HotwordServiceFactory::IsHotwordAllowed(profile())); -#endif - - // Different but valid locale so expect uninstall. - EXPECT_TRUE(hotword_service->MaybeReinstallHotwordExtension()); - EXPECT_EQ(1, hotword_service->uninstall_count()); - EXPECT_EQ("fr_fr", - profile()->GetPrefs()->GetString(prefs::kHotwordPreviousLanguage)); - - if (extension_id_ == extension_misc::kHotwordSharedModuleId) { - // Shared module is installed and enabled. - EXPECT_TRUE(registry()->enabled_extensions().Contains(extension_id_)); - } else { - // Verify the extension is installed. It's still disabled. - EXPECT_TRUE(registry()->disabled_extensions().Contains(extension_id_)); - } - - // Switch the locale to an invalid one. - SetApplicationLocale(profile(), "invalid"); - EXPECT_FALSE(HotwordServiceFactory::IsHotwordAllowed(profile())); - EXPECT_FALSE(hotword_service->MaybeReinstallHotwordExtension()); - EXPECT_EQ("fr_fr", - profile()->GetPrefs()->GetString(prefs::kHotwordPreviousLanguage)); - - // If the locale is set back to the last valid one, then an uninstall-install - // shouldn't be needed. - SetApplicationLocale(profile(), "fr_fr"); -#if defined(ENABLE_HOTWORDING) - EXPECT_TRUE(HotwordServiceFactory::IsHotwordAllowed(profile())); -#else - // Disabled due to http://crbug.com/503963. - // EXPECT_FALSE(HotwordServiceFactory::IsHotwordAllowed(profile())); -#endif - EXPECT_FALSE(hotword_service->MaybeReinstallHotwordExtension()); - EXPECT_EQ(1, hotword_service->uninstall_count()); // no change -} - -TEST_P(HotwordServiceTest, DisableAlwaysOnOnLanguageChange) { - // Bypass test for old hotwording. - if (extension_id_ != extension_misc::kHotwordSharedModuleId) - return; - - // Turn on Always On - base::CommandLine::ForCurrentProcess()->AppendSwitch( - switches::kEnableExperimentalHotwordHardware); - - InitializeEmptyExtensionService(); - service_->Init(); - - // Enable always-on. - profile()->GetPrefs()->SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, true); - - HotwordServiceFactory* hotword_service_factory = - HotwordServiceFactory::GetInstance(); - - MockHotwordService* hotword_service = static_cast<MockHotwordService*>( - hotword_service_factory->SetTestingFactoryAndUse( - profile(), BuildMockHotwordService)); - ASSERT_TRUE(hotword_service != NULL); - hotword_service->SetExtensionService(service()); - hotword_service->SetExtensionId(extension_id_); - - // Initialize the locale to "en_us". - SetApplicationLocale(profile(), "en_us"); - - // The previous locale should not be set. No reason to uninstall. - EXPECT_FALSE(hotword_service->MaybeReinstallHotwordExtension()); - EXPECT_TRUE(hotword_service->IsAlwaysOnEnabled()); - - // Do an initial installation. - hotword_service->InstallHotwordExtensionFromWebstore(1); - base::RunLoop().RunUntilIdle(); - - // The previous locale should be set but should match the current - // locale. No reason to uninstall. - EXPECT_FALSE(hotword_service->MaybeReinstallHotwordExtension()); - EXPECT_TRUE(hotword_service->IsAlwaysOnEnabled()); - - // TODO(kcarattini): Uncomment this sectione once we launch always-on - // in more languages. - // // Switch the locale to a valid but different one. - // SetApplicationLocale(profile(), "fr_fr"); - // EXPECT_TRUE(HotwordServiceFactory::IsHotwordAllowed(profile())); - - // // Different but valid locale so expect uninstall. - // EXPECT_TRUE(hotword_service->MaybeReinstallHotwordExtension()); - // EXPECT_FALSE(hotword_service->IsAlwaysOnEnabled()); - - // Re-enable always-on. - profile()->GetPrefs()->SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, true); - - // Switch the locale to an invalid one. - SetApplicationLocale(profile(), "invalid"); - EXPECT_FALSE(HotwordServiceFactory::IsHotwordAllowed(profile())); - EXPECT_FALSE(hotword_service->MaybeReinstallHotwordExtension()); - EXPECT_TRUE(hotword_service->IsAlwaysOnEnabled()); - - // TODO(kcarattini): Uncomment this sectione once we launch always-on - // in more languages. - // // If the locale is set back to the last valid one, then an - // // uninstall-install shouldn't be needed. - // SetApplicationLocale(profile(), "fr_fr"); - // EXPECT_TRUE(HotwordServiceFactory::IsHotwordAllowed(profile())); - // EXPECT_FALSE(hotword_service->MaybeReinstallHotwordExtension()); - // EXPECT_TRUE(hotword_service->IsAlwaysOnEnabled()); -} - -TEST_P(HotwordServiceTest, IsAlwaysOnEnabled) { - // Bypass test for old hotwording. - if (extension_id_ != extension_misc::kHotwordSharedModuleId) - return; - - InitializeEmptyExtensionService(); - service_->Init(); - HotwordServiceFactory* hotword_service_factory = - HotwordServiceFactory::GetInstance(); - - MockHotwordService* hotword_service = static_cast<MockHotwordService*>( - hotword_service_factory->SetTestingFactoryAndUse( - profile(), BuildMockHotwordService)); - ASSERT_TRUE(hotword_service != NULL); - hotword_service->SetExtensionService(service()); - hotword_service->SetExtensionId(extension_id_); - - // No hardware available. Should never be true. - EXPECT_FALSE(hotword_service->IsAlwaysOnEnabled()); - - // Enable always-on, still not available. - profile()->GetPrefs()->SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, true); - EXPECT_FALSE(hotword_service->IsAlwaysOnEnabled()); - - // Enable regular hotwording, still not available. - profile()->GetPrefs()->SetBoolean(prefs::kHotwordSearchEnabled, true); - EXPECT_FALSE(hotword_service->IsAlwaysOnEnabled()); - - // Bypass hardware check. - base::CommandLine::ForCurrentProcess()->AppendSwitch( - switches::kEnableExperimentalHotwordHardware); - EXPECT_TRUE(hotword_service->IsAlwaysOnEnabled()); - - // Disable. - profile()->GetPrefs()->SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, - false); - EXPECT_FALSE(hotword_service->IsAlwaysOnEnabled()); -} - -TEST_P(HotwordServiceTest, IsSometimesOnEnabled) { - InitializeEmptyExtensionService(); - service_->Init(); - HotwordServiceFactory* hotword_service_factory = - HotwordServiceFactory::GetInstance(); - - MockHotwordService* hotword_service = static_cast<MockHotwordService*>( - hotword_service_factory->SetTestingFactoryAndUse( - profile(), BuildMockHotwordService)); - ASSERT_TRUE(hotword_service != NULL); - hotword_service->SetExtensionService(service()); - hotword_service->SetExtensionId(extension_id_); - - // No pref set. - EXPECT_FALSE(hotword_service->IsSometimesOnEnabled()); - - // Set pref. - profile()->GetPrefs()->SetBoolean(prefs::kHotwordSearchEnabled, true); - EXPECT_TRUE(hotword_service->IsSometimesOnEnabled()); - - // Turn on always-on pref. Should have no effect. - profile()->GetPrefs()->SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, true); - EXPECT_TRUE(hotword_service->IsSometimesOnEnabled()); - - // Disable. - profile()->GetPrefs()->SetBoolean(prefs::kHotwordSearchEnabled, false); - EXPECT_FALSE(hotword_service->IsSometimesOnEnabled()); - - // Bypass rest of test for old hotwording. - if (extension_id_ != extension_misc::kHotwordSharedModuleId) - return; - - // Bypass hardware check. - base::CommandLine::ForCurrentProcess()->AppendSwitch( - switches::kEnableExperimentalHotwordHardware); - - // With hardware, only always-on is allowed. - EXPECT_FALSE(hotword_service->IsSometimesOnEnabled()); - - // Set pref. - profile()->GetPrefs()->SetBoolean(prefs::kHotwordSearchEnabled, true); - EXPECT_FALSE(hotword_service->IsSometimesOnEnabled()); - - // Disable always-on. - profile()->GetPrefs()->SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, - false); - EXPECT_FALSE(hotword_service->IsSometimesOnEnabled()); -} - -TEST_P(HotwordServiceTest, AudioHistorySyncOccurs) { - InitializeEmptyExtensionService(); - service_->Init(); - - HotwordServiceFactory* hotword_service_factory = - HotwordServiceFactory::GetInstance(); - - MockHotwordService* hotword_service = static_cast<MockHotwordService*>( - hotword_service_factory->SetTestingFactoryAndUse( - profile(), BuildMockHotwordService)); - ASSERT_TRUE(hotword_service != NULL); - hotword_service->SetExtensionService(service()); - hotword_service->SetExtensionId(extension_id_); - - scoped_refptr<base::TestSimpleTaskRunner> test_task_runner( - new base::TestSimpleTaskRunner()); - MockAudioHistoryHandler* audio_history_handler = - new MockAudioHistoryHandler(profile(), test_task_runner, nullptr); - hotword_service->SetAudioHistoryHandler(audio_history_handler); - EXPECT_EQ(1, audio_history_handler->GetAudioHistoryCalls()); - // We expect the next check for audio history to be in the queue. - EXPECT_EQ(base::TimeDelta::FromDays(1), - test_task_runner->NextPendingTaskDelay()); - EXPECT_TRUE(test_task_runner->HasPendingTask()); - test_task_runner->RunPendingTasks(); - EXPECT_EQ(2, audio_history_handler->GetAudioHistoryCalls()); - EXPECT_TRUE(test_task_runner->HasPendingTask()); - test_task_runner->ClearPendingTasks(); -}
diff --git a/chrome/browser/task_manager/providers/arc/arc_process_task_provider.cc b/chrome/browser/task_manager/providers/arc/arc_process_task_provider.cc index 36a390d..223adce 100644 --- a/chrome/browser/task_manager/providers/arc/arc_process_task_provider.cc +++ b/chrome/browser/task_manager/providers/arc/arc_process_task_provider.cc
@@ -38,9 +38,7 @@ ArcProcessTaskProvider::~ArcProcessTaskProvider() {} -Task* ArcProcessTaskProvider::GetTaskOfUrlRequest(int origin_pid, - int child_id, - int route_id) { +Task* ArcProcessTaskProvider::GetTaskOfUrlRequest(int child_id, int route_id) { // ARC tasks are not associated with any URL request. return nullptr; }
diff --git a/chrome/browser/task_manager/providers/arc/arc_process_task_provider.h b/chrome/browser/task_manager/providers/arc/arc_process_task_provider.h index b5a38c1..5e6153a 100644 --- a/chrome/browser/task_manager/providers/arc/arc_process_task_provider.h +++ b/chrome/browser/task_manager/providers/arc/arc_process_task_provider.h
@@ -34,9 +34,7 @@ ~ArcProcessTaskProvider() override; // task_manager::TaskProvider: - Task* GetTaskOfUrlRequest(int origin_pid, - int child_id, - int route_id) override; + Task* GetTaskOfUrlRequest(int child_id, int route_id) override; private: using ArcTaskMap =
diff --git a/chrome/browser/task_manager/providers/browser_process_task_provider.cc b/chrome/browser/task_manager/providers/browser_process_task_provider.cc index fb5e8f5d..95df43d2 100644 --- a/chrome/browser/task_manager/providers/browser_process_task_provider.cc +++ b/chrome/browser/task_manager/providers/browser_process_task_provider.cc
@@ -3,6 +3,7 @@ // found in the LICENSE file. #include "chrome/browser/task_manager/providers/browser_process_task_provider.h" +#include "content/public/common/child_process_host.h" namespace task_manager { @@ -12,10 +13,9 @@ BrowserProcessTaskProvider::~BrowserProcessTaskProvider() { } -Task* BrowserProcessTaskProvider::GetTaskOfUrlRequest(int origin_pid, - int child_id, +Task* BrowserProcessTaskProvider::GetTaskOfUrlRequest(int child_id, int route_id) { - if (origin_pid == 0 && child_id == -1) + if (child_id == content::ChildProcessHost::kInvalidUniqueID) return &browser_process_task_; return nullptr;
diff --git a/chrome/browser/task_manager/providers/browser_process_task_provider.h b/chrome/browser/task_manager/providers/browser_process_task_provider.h index 75a95110..42b3254 100644 --- a/chrome/browser/task_manager/providers/browser_process_task_provider.h +++ b/chrome/browser/task_manager/providers/browser_process_task_provider.h
@@ -19,9 +19,7 @@ ~BrowserProcessTaskProvider() override; // task_manager::TaskProvider: - Task* GetTaskOfUrlRequest(int origin_pid, - int child_id, - int route_id) override; + Task* GetTaskOfUrlRequest(int child_id, int route_id) override; private: // task_manager::TaskProvider:
diff --git a/chrome/browser/task_manager/providers/browser_process_task_unittest.cc b/chrome/browser/task_manager/providers/browser_process_task_unittest.cc index 45ff115f..43218bd5 100644 --- a/chrome/browser/task_manager/providers/browser_process_task_unittest.cc +++ b/chrome/browser/task_manager/providers/browser_process_task_unittest.cc
@@ -54,9 +54,9 @@ provider.SetObserver(this); EXPECT_NE(nullptr, provided_task_); - Task* result = provider.GetTaskOfUrlRequest(1, 0, 0); + Task* result = provider.GetTaskOfUrlRequest(2, 0); EXPECT_EQ(nullptr, result); - result = provider.GetTaskOfUrlRequest(0, -1, 0); + result = provider.GetTaskOfUrlRequest(-1, 0); EXPECT_EQ(provided_task_, result); }
diff --git a/chrome/browser/task_manager/providers/child_process_task_provider.cc b/chrome/browser/task_manager/providers/child_process_task_provider.cc index d7d05d2..920b7c4 100644 --- a/chrome/browser/task_manager/providers/child_process_task_provider.cc +++ b/chrome/browser/task_manager/providers/child_process_task_provider.cc
@@ -49,12 +49,11 @@ ChildProcessTaskProvider::~ChildProcessTaskProvider() { } -Task* ChildProcessTaskProvider::GetTaskOfUrlRequest(int origin_pid, - int child_id, +Task* ChildProcessTaskProvider::GetTaskOfUrlRequest(int child_id, int route_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - auto itr = tasks_by_pid_.find(static_cast<base::ProcessId>(origin_pid)); - if (itr == tasks_by_pid_.end()) + auto itr = tasks_by_child_id_.find(child_id); + if (itr == tasks_by_child_id_.end()) return nullptr; return itr->second; @@ -78,7 +77,7 @@ void ChildProcessTaskProvider::StartUpdating() { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(tasks_by_handle_.empty()); - DCHECK(tasks_by_pid_.empty()); + DCHECK(tasks_by_child_id_.empty()); // First, get the pre-existing child processes data. BrowserThread::PostTaskAndReplyWithResult( @@ -104,7 +103,7 @@ // Then delete all tasks (if any). tasks_by_handle_.clear(); - tasks_by_pid_.clear(); + tasks_by_child_id_.clear(); } void ChildProcessTaskProvider::ChildProcessDataCollected( @@ -132,7 +131,7 @@ // Create the task and notify the observer. task.reset(new ChildProcessTask(data)); - tasks_by_pid_[task->process_id()] = task.get(); + tasks_by_child_id_[task->GetChildProcessUniqueID()] = task.get(); NotifyObserverTaskAdded(task.get()); } @@ -153,8 +152,8 @@ NotifyObserverTaskRemoved(itr->second.get()); - // Clear from the pid index. - tasks_by_pid_.erase(itr->second->process_id()); + // Clear from the child_id index. + tasks_by_child_id_.erase(itr->second->GetChildProcessUniqueID()); // Finally delete the task. tasks_by_handle_.erase(itr);
diff --git a/chrome/browser/task_manager/providers/child_process_task_provider.h b/chrome/browser/task_manager/providers/child_process_task_provider.h index 6dab9345..97e3f49 100644 --- a/chrome/browser/task_manager/providers/child_process_task_provider.h +++ b/chrome/browser/task_manager/providers/child_process_task_provider.h
@@ -9,6 +9,7 @@ #include <memory> #include <vector> +#include "base/containers/flat_map.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/task_manager/providers/task_provider.h" @@ -32,9 +33,7 @@ ~ChildProcessTaskProvider() override; // task_manager::TaskProvider: - Task* GetTaskOfUrlRequest(int origin_pid, - int child_id, - int route_id) override; + Task* GetTaskOfUrlRequest(int child_id, int route_id) override; // content::BrowserChildProcessObserver: void BrowserChildProcessLaunchedAndConnected( @@ -64,23 +63,16 @@ // observer of its deletion. void DeleteTask(base::ProcessHandle handle); - // A map to track ChildProcessTask's by their handles. + // A map to track ChildProcessTasks by their handles. + // + // This uses handles instead of pids because on windows (where pids and + // handles differ), BrowserChildProcessObserver gives us a handle instead of a + // pid. std::map<base::ProcessHandle, std::unique_ptr<ChildProcessTask>> tasks_by_handle_; - // A map to track ChildProcessTask's by their PIDs. - // - // Why have both |tasks_by_handle_| and |tasks_by_pid_|? On Windows, where - // handles are not the same as PIDs, |DeleteTask| gets only a handle, which - // may be closed, making it impossible to query the PID from the handle. So - // we need an index on the handle. Meanwhile, we also need an index on the - // PID so that we can efficiently implement |GetTaskOfUrlRequest()|, which - // gets only a PID. - // - // TODO(afakhry): Fix this either by keeping the handle open via - // |base::Process|, or amending the |BrowserChildProcessObserver| interface to - // supply the PID. - std::map<base::ProcessId, ChildProcessTask*> tasks_by_pid_; + // A map to track ChildProcessTask's by their child process unique ids. + base::flat_map<int, ChildProcessTask*> tasks_by_child_id_; // Always keep this the last member of this class to make sure it's the // first thing to be destructed.
diff --git a/chrome/browser/task_manager/providers/child_process_task_unittest.cc b/chrome/browser/task_manager/providers/child_process_task_unittest.cc index 9a9c1fe..60306cb 100644 --- a/chrome/browser/task_manager/providers/child_process_task_unittest.cc +++ b/chrome/browser/task_manager/providers/child_process_task_unittest.cc
@@ -69,7 +69,8 @@ bool AreProviderContainersEmpty( const ChildProcessTaskProvider& provider) const { - return provider.tasks_by_handle_.empty() && provider.tasks_by_pid_.empty(); + return provider.tasks_by_handle_.empty() && + provider.tasks_by_child_id_.empty(); } protected: @@ -132,15 +133,13 @@ EXPECT_FALSE(task->ReportsV8Memory()); EXPECT_FALSE(task->ReportsWebCacheStats()); - // Make sure that the conversion from PID to Handle inside - // |GetTaskOfUrlRequest()| is working properly. - Task* found_task = - provider.GetTaskOfUrlRequest(base::GetCurrentProcId(), 0, 0); - ASSERT_EQ(task, found_task); + // Make sure that indexing by child_id works properly. + ASSERT_EQ(task, provider.GetTaskOfUrlRequest(unique_id, 0)); + ASSERT_EQ(task, provider.GetTaskOfUrlRequest(unique_id, 1)); + const int64_t bytes_read = 1024; - found_task->OnNetworkBytesRead(bytes_read); - found_task->Refresh(base::TimeDelta::FromSeconds(1), - REFRESH_TYPE_NETWORK_USAGE); + task->OnNetworkBytesRead(bytes_read); + task->Refresh(base::TimeDelta::FromSeconds(1), REFRESH_TYPE_NETWORK_USAGE); EXPECT_EQ(bytes_read, task->network_usage_rate()); @@ -180,4 +179,3 @@ } } // namespace task_manager -
diff --git a/chrome/browser/task_manager/providers/fallback_task_provider.cc b/chrome/browser/task_manager/providers/fallback_task_provider.cc index aac491d..758b6776 100644 --- a/chrome/browser/task_manager/providers/fallback_task_provider.cc +++ b/chrome/browser/task_manager/providers/fallback_task_provider.cc
@@ -49,14 +49,12 @@ FallbackTaskProvider::~FallbackTaskProvider() {} -Task* FallbackTaskProvider::GetTaskOfUrlRequest(int origin_pid, - int child_id, - int route_id) { +Task* FallbackTaskProvider::GetTaskOfUrlRequest(int child_id, int route_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); Task* task_of_url_request; for (const auto& source : sources_) { - task_of_url_request = source->subprovider()->GetTaskOfUrlRequest( - origin_pid, child_id, route_id); + task_of_url_request = + source->subprovider()->GetTaskOfUrlRequest(child_id, route_id); if (base::ContainsValue(shown_tasks_, task_of_url_request)) return task_of_url_request; }
diff --git a/chrome/browser/task_manager/providers/fallback_task_provider.h b/chrome/browser/task_manager/providers/fallback_task_provider.h index 691bb2e..7a51266 100644 --- a/chrome/browser/task_manager/providers/fallback_task_provider.h +++ b/chrome/browser/task_manager/providers/fallback_task_provider.h
@@ -27,9 +27,7 @@ ~FallbackTaskProvider() override; // task_manager::TaskProvider: - Task* GetTaskOfUrlRequest(int origin_pid, - int child_id, - int route_id) override; + Task* GetTaskOfUrlRequest(int child_id, int route_id) override; private: friend class FallbackTaskProviderTest;
diff --git a/chrome/browser/task_manager/providers/fallback_task_provider_unittest.cc b/chrome/browser/task_manager/providers/fallback_task_provider_unittest.cc index cd388029..9af40935 100644 --- a/chrome/browser/task_manager/providers/fallback_task_provider_unittest.cc +++ b/chrome/browser/task_manager/providers/fallback_task_provider_unittest.cc
@@ -45,9 +45,7 @@ public: FakeTaskProvider() {} ~FakeTaskProvider() override {} - Task* GetTaskOfUrlRequest(int origin_pid, - int child_id, - int route_id) override { + Task* GetTaskOfUrlRequest(int child_id, int route_id) override { return nullptr; }
diff --git a/chrome/browser/task_manager/providers/render_process_host_task_provider.cc b/chrome/browser/task_manager/providers/render_process_host_task_provider.cc index b9d6c05..42e89490 100644 --- a/chrome/browser/task_manager/providers/render_process_host_task_provider.cc +++ b/chrome/browser/task_manager/providers/render_process_host_task_provider.cc
@@ -37,8 +37,7 @@ RenderProcessHostTaskProvider::~RenderProcessHostTaskProvider() {} -Task* RenderProcessHostTaskProvider::GetTaskOfUrlRequest(int origin_pid, - int child_id, +Task* RenderProcessHostTaskProvider::GetTaskOfUrlRequest(int child_id, int route_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); auto itr = tasks_by_rph_id_.find(child_id);
diff --git a/chrome/browser/task_manager/providers/render_process_host_task_provider.h b/chrome/browser/task_manager/providers/render_process_host_task_provider.h index 472d6db..1b03d12e 100644 --- a/chrome/browser/task_manager/providers/render_process_host_task_provider.h +++ b/chrome/browser/task_manager/providers/render_process_host_task_provider.h
@@ -30,9 +30,7 @@ ~RenderProcessHostTaskProvider() override; // task_manager::TaskProvider: - Task* GetTaskOfUrlRequest(int origin_pid, - int child_id, - int route_id) override; + Task* GetTaskOfUrlRequest(int child_id, int route_id) override; // content::NotificationObserver: void Observe(int type,
diff --git a/chrome/browser/task_manager/providers/task_provider.h b/chrome/browser/task_manager/providers/task_provider.h index 2a47851..2df9c1b 100644 --- a/chrome/browser/task_manager/providers/task_provider.h +++ b/chrome/browser/task_manager/providers/task_provider.h
@@ -25,15 +25,11 @@ // nullptr will be returned if the desired task does not belong to this // provider. // - // |origin_pid| is the PID of the originating process of the URLRequest, if - // the request is sent on behalf of another process. Otherwise it's 0. // |child_id| is the unique ID of the host of the child process requestor. // |route_id| is the ID of the IPC route for the URLRequest (this identifies - // the RenderView or like-thing in the renderer that the request gets routed - // to). - virtual Task* GetTaskOfUrlRequest(int origin_pid, - int child_id, - int route_id) = 0; + // the RenderFrame in the renderer that initiated the request). |route_id| + // may be ignored if |child_id| is not a renderer process. + virtual Task* GetTaskOfUrlRequest(int child_id, int route_id) = 0; // Set the sole observer of this provider. It's an error to set an observer // if there's already one there.
diff --git a/chrome/browser/task_manager/providers/web_contents/web_contents_task_provider.cc b/chrome/browser/task_manager/providers/web_contents/web_contents_task_provider.cc index abca0016..a3fa759 100644 --- a/chrome/browser/task_manager/providers/web_contents/web_contents_task_provider.cc +++ b/chrome/browser/task_manager/providers/web_contents/web_contents_task_provider.cc
@@ -416,19 +416,15 @@ entries_map_.erase(itr); // Deletes the WebContentsEntry. } -Task* WebContentsTaskProvider::GetTaskOfUrlRequest(int origin_pid, - int child_id, - int route_id) { - // If an origin PID was specified then the URL request originated in a plugin - // working on the WebContents' behalf, so ignore it. - if (origin_pid) - return nullptr; - +Task* WebContentsTaskProvider::GetTaskOfUrlRequest(int child_id, int route_id) { content::RenderFrameHost* rfh = content::RenderFrameHost::FromID(child_id, route_id); content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(rfh); + if (!web_contents) + return nullptr; + auto itr = entries_map_.find(web_contents); if (itr == entries_map_.end()) { // Can happen if the tab was closed while a network request was being
diff --git a/chrome/browser/task_manager/providers/web_contents/web_contents_task_provider.h b/chrome/browser/task_manager/providers/web_contents/web_contents_task_provider.h index de74d3a..5b346c8 100644 --- a/chrome/browser/task_manager/providers/web_contents/web_contents_task_provider.h +++ b/chrome/browser/task_manager/providers/web_contents/web_contents_task_provider.h
@@ -35,9 +35,7 @@ void OnWebContentsTagRemoved(const WebContentsTag* tag); // task_manager::TaskProvider: - Task* GetTaskOfUrlRequest(int origin_pid, - int child_id, - int route_id) override; + Task* GetTaskOfUrlRequest(int child_id, int route_id) override; // Checks if the given |web_contents| is tracked by the provider. bool HasWebContents(content::WebContents* web_contents) const;
diff --git a/chrome/browser/task_manager/sampling/task_manager_impl.cc b/chrome/browser/task_manager/sampling/task_manager_impl.cc index 4361dc3..550217a1 100644 --- a/chrome/browser/task_manager/sampling/task_manager_impl.cc +++ b/chrome/browser/task_manager/sampling/task_manager_impl.cc
@@ -27,6 +27,7 @@ #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/web_contents.h" +#include "content/public/common/child_process_host.h" #include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h" #if defined(OS_CHROMEOS) @@ -429,8 +430,7 @@ if (!web_contents) return -1; content::RenderFrameHost* rfh = web_contents->GetMainFrame(); - Task* task = - GetTaskByPidOrRoute(0, rfh->GetProcess()->GetID(), rfh->GetRoutingID()); + Task* task = GetTaskByRoute(rfh->GetProcess()->GetID(), rfh->GetRoutingID()); if (!task) return -1; return task->task_id(); @@ -496,17 +496,11 @@ // We can't match a task to the notification. That might mean the // tab that started a download was closed, or the request may have had // no originating task associated with it in the first place. - // We attribute orphaned/unaccounted activity to the Browser process. - DCHECK(process_info.origin_pid || (process_info.child_id != -1)); - // Since the key is meant to be immutable we create a fake key for the - // purpose of attributing the orphaned/unaccounted activity to the Browser - // process. - int dummy_origin_pid = 0; - int dummy_child_id = -1; - int dummy_route_id = -1; - BytesTransferredKey dummy_key = {dummy_origin_pid, dummy_child_id, - dummy_route_id}; - GetInstance()->UpdateTasksWithBytesTransferred(dummy_key, + // + // Orphaned/unaccounted activity is credited to the Browser process. + BytesTransferredKey browser_process_key = { + content::ChildProcessHost::kInvalidUniqueID, MSG_ROUTING_NONE}; + GetInstance()->UpdateTasksWithBytesTransferred(browser_process_key, bytes_transferred); } } @@ -589,12 +583,9 @@ sorted_task_ids_.clear(); } -Task* TaskManagerImpl::GetTaskByPidOrRoute(int origin_pid, - int child_id, - int route_id) const { +Task* TaskManagerImpl::GetTaskByRoute(int child_id, int route_id) const { for (const auto& task_provider : task_providers_) { - Task* task = - task_provider->GetTaskOfUrlRequest(origin_pid, child_id, route_id); + Task* task = task_provider->GetTaskOfUrlRequest(child_id, route_id); if (task) return task; } @@ -606,7 +597,7 @@ const BytesTransferredParam& param) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - Task* task = GetTaskByPidOrRoute(key.origin_pid, key.child_id, key.route_id); + Task* task = GetTaskByRoute(key.child_id, key.route_id); if (task) { task->OnNetworkBytesRead(param.byte_read_count); task->OnNetworkBytesSent(param.byte_sent_count);
diff --git a/chrome/browser/task_manager/sampling/task_manager_impl.h b/chrome/browser/task_manager/sampling/task_manager_impl.h index 07852dad..8fdc1e6 100644 --- a/chrome/browser/task_manager/sampling/task_manager_impl.h +++ b/chrome/browser/task_manager/sampling/task_manager_impl.h
@@ -120,8 +120,8 @@ void StartUpdating() override; void StopUpdating() override; - // Lookup a task by its pid, child_id and possibly route_id. - Task* GetTaskByPidOrRoute(int pid, int child_id, int route_id) const; + // Lookup a task by child_id and possibly route_id. + Task* GetTaskByRoute(int child_id, int route_id) const; // Based on |param| the appropriate task will be updated by its network usage. // Returns true if it was able to match |param| to an existing task, returns
diff --git a/chrome/browser/task_manager/sampling/task_manager_io_thread_helper.cc b/chrome/browser/task_manager/sampling/task_manager_io_thread_helper.cc index 532c0d0d..b20d121 100644 --- a/chrome/browser/task_manager/sampling/task_manager_io_thread_helper.cc +++ b/chrome/browser/task_manager/sampling/task_manager_io_thread_helper.cc
@@ -18,16 +18,11 @@ size_t BytesTransferredKey::Hasher::operator()( const BytesTransferredKey& key) const { - if (key.child_id != -1) { - return base::HashInts(key.child_id, key.route_id); - } else { - return std::hash<int>()(key.origin_pid); - } + return base::HashInts(key.child_id, key.route_id); } bool BytesTransferredKey::operator==(const BytesTransferredKey& other) const { - return origin_pid == other.origin_pid && child_id == other.child_id && - route_id == other.route_id; + return child_id == other.child_id && route_id == other.route_id; } IoThreadHelperManager::IoThreadHelperManager(
diff --git a/chrome/browser/task_manager/sampling/task_manager_io_thread_helper.h b/chrome/browser/task_manager/sampling/task_manager_io_thread_helper.h index 384bb5e..55ba378 100644 --- a/chrome/browser/task_manager/sampling/task_manager_io_thread_helper.h +++ b/chrome/browser/task_manager/sampling/task_manager_io_thread_helper.h
@@ -20,14 +20,10 @@ namespace task_manager { -// Identifies the initiator of a network request, either by a (child_id, -// route_id) tuple, and/or via an OS process id. +// Identifies the initiator of a network request, by a (child_id, +// route_id) tuple. // BytesTransferredKey supports hashing and may be used as an unordered_map key. struct BytesTransferredKey { - // The PID of the originating process of the URLRequest, if the request is - // sent on behalf of another process. Otherwise it's 0. - int origin_pid; - // The unique ID of the host of the child process requester. int child_id;
diff --git a/chrome/browser/task_manager/sampling/task_manager_io_thread_helper_unittest.cc b/chrome/browser/task_manager/sampling/task_manager_io_thread_helper_unittest.cc index ee21e98..f148eed 100644 --- a/chrome/browser/task_manager/sampling/task_manager_io_thread_helper_unittest.cc +++ b/chrome/browser/task_manager/sampling/task_manager_io_thread_helper_unittest.cc
@@ -36,40 +36,11 @@ DISALLOW_COPY_AND_ASSIGN(TaskManagerIoThreadHelperTest); }; -// Tests that the origin_id is used in the map correctly. -TEST_F(TaskManagerIoThreadHelperTest, PidData) { - base::ScopedMockTimeMessageLoopTaskRunner mock_main_runner; - - BytesTransferredKey key = {123, -1, -1}; - - int64_t correct_read_bytes = 0; - int64_t correct_sent_bytes = 0; - - int read_bytes_array[] = {200, 400, 800}; - int sent_bytes_array[] = {100, 123, 234}; - - for (int i : read_bytes_array) { - TaskManagerIoThreadHelper::OnRawBytesTransferred(key, i, 0); - correct_read_bytes += i; - } - for (int i : sent_bytes_array) { - TaskManagerIoThreadHelper::OnRawBytesTransferred(key, 0, i); - correct_sent_bytes += i; - } - - EXPECT_TRUE(mock_main_runner->HasPendingTask()); - mock_main_runner->FastForwardBy(base::TimeDelta::FromSeconds(1)); - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(mock_main_runner->HasPendingTask()); - EXPECT_EQ(correct_sent_bytes, returned_map_[key].byte_sent_count); - EXPECT_EQ(correct_read_bytes, returned_map_[key].byte_read_count); -} - // Tests that the |child_id| and |route_id| are used in the map correctly. TEST_F(TaskManagerIoThreadHelperTest, ChildRouteData) { base::ScopedMockTimeMessageLoopTaskRunner mock_main_runner; - BytesTransferredKey key = {0, 100, 190}; + BytesTransferredKey key = {100, 190}; int64_t correct_read_bytes = 0; int64_t correct_sent_bytes = 0; @@ -95,102 +66,13 @@ EXPECT_EQ(correct_read_bytes, returned_map_[key].byte_read_count); } -// Tests that two distinct |origin_pid| are tracked separately in the unordered -// map. -TEST_F(TaskManagerIoThreadHelperTest, TwoPidData) { - base::ScopedMockTimeMessageLoopTaskRunner mock_main_runner; - - BytesTransferredKey key1 = {23, -1, -1}; - BytesTransferredKey key2 = {33, -1, -1}; - - int64_t correct_read_bytes1 = 0; - int64_t correct_sent_bytes1 = 0; - - int64_t correct_read_bytes2 = 0; - int64_t correct_sent_bytes2 = 0; - - int read_bytes_array1[] = {900, 300, 100}; - int sent_bytes_array1[] = {130, 153, 934}; - - int read_bytes_array2[] = {903, 340, 150}; - int sent_bytes_array2[] = {138, 157, 964}; - - for (int i : read_bytes_array1) { - TaskManagerIoThreadHelper::OnRawBytesTransferred(key1, i, 0); - correct_read_bytes1 += i; - } - for (int i : sent_bytes_array1) { - TaskManagerIoThreadHelper::OnRawBytesTransferred(key1, 0, i); - correct_sent_bytes1 += i; - } - - for (int i : read_bytes_array2) { - TaskManagerIoThreadHelper::OnRawBytesTransferred(key2, i, 0); - correct_read_bytes2 += i; - } - for (int i : sent_bytes_array2) { - TaskManagerIoThreadHelper::OnRawBytesTransferred(key2, 0, i); - correct_sent_bytes2 += i; - } - - mock_main_runner->FastForwardBy(base::TimeDelta::FromSeconds(1)); - base::RunLoop().RunUntilIdle(); - const unsigned long number_of_keys = 2; - EXPECT_EQ(number_of_keys, returned_map_.size()); - EXPECT_EQ(correct_sent_bytes1, returned_map_[key1].byte_sent_count); - EXPECT_EQ(correct_read_bytes1, returned_map_[key1].byte_read_count); - EXPECT_EQ(correct_sent_bytes2, returned_map_[key2].byte_sent_count); - EXPECT_EQ(correct_read_bytes2, returned_map_[key2].byte_read_count); -} - -// Tests that two keys with the same |origin_pid| are tracked together in the -// unordered map. -TEST_F(TaskManagerIoThreadHelperTest, TwoSamePidData) { - base::ScopedMockTimeMessageLoopTaskRunner mock_main_runner; - - BytesTransferredKey key1 = {23, -1, -1}; - BytesTransferredKey key2 = {23, -1, -1}; - - int64_t correct_read_bytes = 0; - int64_t correct_sent_bytes = 0; - - int read_bytes_array[] = {900, 300, 100}; - int sent_bytes_array[] = {130, 153, 934}; - - for (int i : read_bytes_array) { - TaskManagerIoThreadHelper::OnRawBytesTransferred(key1, i, 0); - correct_read_bytes += i; - } - for (int i : sent_bytes_array) { - TaskManagerIoThreadHelper::OnRawBytesTransferred(key1, 0, i); - correct_sent_bytes += i; - } - - for (int i : read_bytes_array) { - TaskManagerIoThreadHelper::OnRawBytesTransferred(key2, i, 0); - correct_read_bytes += i; - } - for (int i : sent_bytes_array) { - TaskManagerIoThreadHelper::OnRawBytesTransferred(key2, 0, i); - correct_sent_bytes += i; - } - - mock_main_runner->FastForwardBy(base::TimeDelta::FromSeconds(1)); - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(1U, returned_map_.size()); - EXPECT_EQ(correct_sent_bytes, returned_map_[key1].byte_sent_count); - EXPECT_EQ(correct_read_bytes, returned_map_[key1].byte_read_count); - EXPECT_EQ(correct_sent_bytes, returned_map_[key2].byte_sent_count); - EXPECT_EQ(correct_read_bytes, returned_map_[key2].byte_read_count); -} - // Tests that two distinct |child_id| and |route_id| pairs are tracked // separately in the unordered map. TEST_F(TaskManagerIoThreadHelperTest, TwoChildRouteData) { base::ScopedMockTimeMessageLoopTaskRunner mock_main_runner; - BytesTransferredKey key1 = {0, 32, 1}; - BytesTransferredKey key2 = {0, 17, 2}; + BytesTransferredKey key1 = {32, 1}; + BytesTransferredKey key2 = {17, 2}; int64_t correct_read_bytes1 = 0; int64_t correct_sent_bytes1 = 0; @@ -239,8 +121,8 @@ TEST_F(TaskManagerIoThreadHelperTest, TwoSameChildRouteData) { base::ScopedMockTimeMessageLoopTaskRunner mock_main_runner; - BytesTransferredKey key1 = {0, 123, 456}; - BytesTransferredKey key2 = {0, 123, 456}; + BytesTransferredKey key1 = {123, 456}; + BytesTransferredKey key2 = {123, 456}; int64_t correct_read_bytes = 0; int64_t correct_sent_bytes = 0; @@ -275,13 +157,11 @@ EXPECT_EQ(correct_read_bytes, returned_map_[key2].byte_read_count); } -// Tests that the unordered_map can hold both types of key in one map. -TEST_F(TaskManagerIoThreadHelperTest, OnePidOneChildRouteData) { +// Tests that the map can handle two child_ids with the same route_id. +TEST_F(TaskManagerIoThreadHelperTest, SameRouteDifferentProcesses) { base::ScopedMockTimeMessageLoopTaskRunner mock_main_runner; - // Test the pathological condition of a collision. - BytesTransferredKey key1 = {0, 12, 143}; - BytesTransferredKey key2 = {static_cast<int>(base::HashInts(12, 143)), -1, - -1}; + BytesTransferredKey key1 = {12, 143}; + BytesTransferredKey key2 = {13, 143}; int64_t correct_read_bytes1 = 0; int64_t correct_sent_bytes1 = 0; @@ -327,8 +207,8 @@ TEST_F(TaskManagerIoThreadHelperTest, MultipleWavesMixedData) { base::ScopedMockTimeMessageLoopTaskRunner mock_main_runner; - BytesTransferredKey key1 = {0, 12, 143}; - BytesTransferredKey key2 = {32, -1, -1}; + BytesTransferredKey key1 = {12, 143}; + BytesTransferredKey key2 = {-1, -1}; int64_t correct_read_bytes1 = 0; int64_t correct_sent_bytes1 = 0;
diff --git a/chrome/browser/task_manager/task_manager_interface.cc b/chrome/browser/task_manager/task_manager_interface.cc index 5796ac4..09c8843 100644 --- a/chrome/browser/task_manager/task_manager_interface.cc +++ b/chrome/browser/task_manager/task_manager_interface.cc
@@ -24,21 +24,21 @@ BytesTransferredKey KeyForRequest(const net::URLRequest& request) { // Only net::URLRequestJob instances created by the ResourceDispatcherHost // have an associated ResourceRequestInfo and a render frame associated. - // All other jobs will have -1 returned for the render process child and - // routing ids - the jobs may still match a resource based on their origin id, - // otherwise BytesRead() will attribute the activity to the Browser resource. const content::ResourceRequestInfo* info = content::ResourceRequestInfo::ForRequest(&request); - int child_id = -1; - int route_id = -1; - if (info) - info->GetAssociatedRenderFrame(&child_id, &route_id); + // Requests without ResourceRequestInfo are attributed to the browser process. + if (!info) + return {content::ChildProcessHost::kInvalidUniqueID, MSG_ROUTING_NONE}; - // Get the origin PID of the request's originator. This will only be set for - // plugins - for renderer or browser initiated requests it will be zero. - int origin_pid = info ? info->GetOriginPID() : 0; - return {origin_pid, child_id, route_id}; + // Requests from PPAPI instances are proxied through the renderer, and specify + // the plugin_child_id of the plugin process. + if (info->GetPluginChildID() != content::ChildProcessHost::kInvalidUniqueID) + return {info->GetPluginChildID(), MSG_ROUTING_NONE}; + + // Other requests are associated with the child process (and frame, if + // originating from a renderer process). + return {info->GetChildID(), info->GetRenderFrameID()}; } } // namespace
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index a3a0dc2..0988917 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -1465,8 +1465,6 @@ "webui/chromeos/system_web_dialog_delegate.h", "webui/chromeos/user_image_source.cc", "webui/chromeos/user_image_source.h", - "webui/chromeos/voice_search_ui.cc", - "webui/chromeos/voice_search_ui.h", "webui/extensions/chromeos/kiosk_apps_handler.cc", "webui/extensions/chromeos/kiosk_apps_handler.h", "webui/help/help_utils_chromeos.cc", @@ -2758,9 +2756,9 @@ "views/new_back_shortcut_bubble.h", "views/overlay/overlay_window_views.cc", "views/overlay/overlay_window_views.h", - "views/page_info/chosen_object_row.cc", - "views/page_info/chosen_object_row.h", - "views/page_info/chosen_object_row_observer.h", + "views/page_info/chosen_object_view.cc", + "views/page_info/chosen_object_view.h", + "views/page_info/chosen_object_view_observer.h", "views/page_info/non_accessible_image_view.cc", "views/page_info/non_accessible_image_view.h", "views/page_info/page_info_bubble_view.cc",
diff --git a/chrome/browser/ui/android/context_menu_helper.cc b/chrome/browser/ui/android/context_menu_helper.cc index 2e536893..70a71d8 100644 --- a/chrome/browser/ui/android/context_menu_helper.cc +++ b/chrome/browser/ui/android/context_menu_helper.cc
@@ -19,10 +19,10 @@ #include "components/data_reduction_proxy/core/common/data_reduction_proxy_headers.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" -#include "content/public/common/associated_interface_provider.h" #include "content/public/common/context_menu_params.h" #include "jni/ContextMenuHelper_jni.h" #include "jni/ContextMenuParams_jni.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" #include "third_party/WebKit/public/web/WebContextMenuData.h" #include "ui/android/view_android.h" #include "ui/gfx/android/java_bitmap.h"
diff --git a/chrome/browser/ui/app_list/search/search_resource_manager.cc b/chrome/browser/ui/app_list/search/search_resource_manager.cc index 011b1708..d596886 100644 --- a/chrome/browser/ui/app_list/search/search_resource_manager.cc +++ b/chrome/browser/ui/app_list/search/search_resource_manager.cc
@@ -4,6 +4,8 @@ #include "chrome/browser/ui/app_list/search/search_resource_manager.h" +#include <memory> + #include "ash/app_list/model/search_box_model.h" #include "base/memory/ptr_util.h" #include "chrome/browser/ui/app_list/start_page_service.h" @@ -20,16 +22,10 @@ std::unique_ptr<SearchBoxModel::SpeechButtonProperty> CreateNewProperty( SpeechRecognitionState state) { - if (state == SPEECH_RECOGNITION_OFF) - return nullptr; - - ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance(); - return base::MakeUnique<SearchBoxModel::SpeechButtonProperty>( - *bundle.GetImageSkiaNamed(IDR_APP_LIST_MIC_HOTWORD_ON), - l10n_util::GetStringUTF16(IDS_APP_LIST_HOTWORD_LISTENING), - *bundle.GetImageSkiaNamed(IDR_APP_LIST_MIC_HOTWORD_OFF), - l10n_util::GetStringUTF16(IDS_APP_LIST_START_SPEECH_RECOGNITION), - l10n_util::GetStringUTF16(IDS_TOOLTIP_MIC_SEARCH)); + // Currently no speech support in app list. + // TODO(xiaohuic): when implementing speech support in new app list, we should + // either reuse this and related logic or delete them. + return nullptr; } } // namespace @@ -58,10 +54,7 @@ search_box_->SetHintText( l10n_util::GetStringUTF16(IDS_SEARCH_BOX_HINT_FULLSCREEN)); } else { - search_box_->SetHintText(l10n_util::GetStringUTF16( - (new_state == SPEECH_RECOGNITION_HOTWORD_LISTENING) - ? IDS_SEARCH_BOX_HOTWORD_HINT - : IDS_SEARCH_BOX_HINT)); + search_box_->SetHintText(l10n_util::GetStringUTF16(IDS_SEARCH_BOX_HINT)); search_box_->SetSpeechRecognitionButton(CreateNewProperty(new_state)); } }
diff --git a/chrome/browser/ui/app_list/start_page_service.cc b/chrome/browser/ui/app_list/start_page_service.cc index c92b54a8..51f5d1bf 100644 --- a/chrome/browser/ui/app_list/start_page_service.cc +++ b/chrome/browser/ui/app_list/start_page_service.cc
@@ -21,8 +21,6 @@ #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/media/webrtc/media_stream_devices_controller.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/search/hotword_service.h" -#include "chrome/browser/search/hotword_service_factory.h" #include "chrome/browser/search_engines/template_url_service_factory.h" #include "chrome/browser/search_engines/ui_thread_search_terms_data.h" #include "chrome/browser/ui/app_list/speech_auth_helper.h" @@ -228,8 +226,6 @@ private: void CheckAndUpdate() { - // TODO(mukai): If the system can listen, this should also restart the - // hotword recognition. start_page_service_->OnMicrophoneChanged(CanListen()); } @@ -424,14 +420,6 @@ OnSpeechRecognitionStateChanged(SPEECH_RECOGNITION_READY); } -bool StartPageService::HotwordEnabled() { - HotwordService* service = HotwordServiceFactory::GetForProfile(profile_); - return state_ != SPEECH_RECOGNITION_OFF && - service && - (service->IsSometimesOnEnabled() || service->IsAlwaysOnEnabled()) && - service->IsServiceAvailable(); -} - content::WebContents* StartPageService::GetStartPageContents() { return contents_.get(); } @@ -481,12 +469,7 @@ } if (!InSpeechRecognition(state_) && InSpeechRecognition(new_state)) { - if (!speech_button_toggled_manually_ && - state_ == SPEECH_RECOGNITION_HOTWORD_LISTENING) { - RecordAction(UserMetricsAction("AppList_HotwordRecognized")); - } else { RecordAction(UserMetricsAction("AppList_VoiceSearchStartedManually")); - } } else if (InSpeechRecognition(state_) && !InSpeechRecognition(new_state) && !speech_result_obtained_) { RecordAction(UserMetricsAction("AppList_VoiceSearchCanceled")); @@ -498,18 +481,6 @@ observer.OnSpeechRecognitionStateChanged(new_state); } -void StartPageService::GetSpeechAuthParameters(std::string* auth_scope, - std::string* auth_token) { - HotwordService* service = HotwordServiceFactory::GetForProfile(profile_); - if (service && - service->IsOptedIntoAudioLogging() && - service->IsAlwaysOnEnabled() && - !speech_auth_helper_->GetToken().empty()) { - *auth_scope = speech_auth_helper_->GetScope(); - *auth_token = speech_auth_helper_->GetToken(); - } -} - void StartPageService::Shutdown() { UnloadContents(); audio_status_.reset();
diff --git a/chrome/browser/ui/app_list/start_page_service.h b/chrome/browser/ui/app_list/start_page_service.h index 1c325706f..184c43b 100644 --- a/chrome/browser/ui/app_list/start_page_service.h +++ b/chrome/browser/ui/app_list/start_page_service.h
@@ -77,9 +77,6 @@ // Called when the WebUI has finished loading. void WebUILoaded(); - // Returns true if the hotword is enabled in the app-launcher. - bool HotwordEnabled(); - // They return essentially the same web contents but might return NULL when // some flag disables the feature. content::WebContents* GetStartPageContents(); @@ -97,7 +94,7 @@ void OnSpeechRecognitionStateChanged( SpeechRecognitionState new_state) override; void GetSpeechAuthParameters(std::string* auth_scope, - std::string* auth_token) override; + std::string* auth_token) override {} protected: // Protected for testing.
diff --git a/chrome/browser/ui/ash/chrome_shell_delegate.cc b/chrome/browser/ui/ash/chrome_shell_delegate.cc index ce680f859..f841e90 100644 --- a/chrome/browser/ui/ash/chrome_shell_delegate.cc +++ b/chrome/browser/ui/ash/chrome_shell_delegate.cc
@@ -104,17 +104,6 @@ ash::Shell::Get()->RemoveShellObserver(AccessibilityManager::Get()); } - bool IsSpokenFeedbackEnabled() const override { - DCHECK(AccessibilityManager::Get()); - return AccessibilityManager::Get()->IsSpokenFeedbackEnabled(); - } - - void ToggleSpokenFeedback( - ash::AccessibilityNotificationVisibility notify) override { - DCHECK(AccessibilityManager::Get()); - AccessibilityManager::Get()->ToggleSpokenFeedback(notify); - } - void SetMagnifierEnabled(bool enabled) override { DCHECK(chromeos::MagnificationManager::Get()); return chromeos::MagnificationManager::Get()->SetMagnifierEnabled(enabled);
diff --git a/chrome/browser/ui/aura/accessibility/ax_tree_source_aura.cc b/chrome/browser/ui/aura/accessibility/ax_tree_source_aura.cc index f94ad133..a1532829 100644 --- a/chrome/browser/ui/aura/accessibility/ax_tree_source_aura.cc +++ b/chrome/browser/ui/aura/accessibility/ax_tree_source_aura.cc
@@ -130,6 +130,10 @@ int ax_tree_id = rfh->GetAXTreeID(); out_data->AddIntAttribute(ui::AX_ATTR_CHILD_TREE_ID, ax_tree_id); } + } else if (out_data->role == ui::AX_ROLE_WINDOW || + out_data->role == ui::AX_ROLE_DIALOG) { + // Add clips children flag by default to these roles. + out_data->AddBoolAttribute(ui::AX_ATTR_CLIPS_CHILDREN, true); } }
diff --git a/chrome/browser/ui/blocked_content/popup_blocker_tab_helper.cc b/chrome/browser/ui/blocked_content/popup_blocker_tab_helper.cc index 3cc09f9..80060f69 100644 --- a/chrome/browser/ui/blocked_content/popup_blocker_tab_helper.cc +++ b/chrome/browser/ui/blocked_content/popup_blocker_tab_helper.cc
@@ -29,7 +29,7 @@ #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" -#include "content/public/common/associated_interface_provider.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" #include "url/gurl.h" #if defined(OS_ANDROID)
diff --git a/chrome/browser/ui/bookmarks/bookmark_context_menu_controller.h b/chrome/browser/ui/bookmarks/bookmark_context_menu_controller.h index 3a021e2f..482f5f6 100644 --- a/chrome/browser/ui/bookmarks/bookmark_context_menu_controller.h +++ b/chrome/browser/ui/bookmarks/bookmark_context_menu_controller.h
@@ -93,7 +93,7 @@ gfx::NativeWindow parent_window_; BookmarkContextMenuControllerDelegate* delegate_; - Browser* browser_; + Browser* const browser_; Profile* profile_; content::PageNavigator* navigator_; const bookmarks::BookmarkNode* parent_;
diff --git a/chrome/browser/ui/browser.cc b/chrome/browser/ui/browser.cc index d3a3a94..0fc32db 100644 --- a/chrome/browser/ui/browser.cc +++ b/chrome/browser/ui/browser.cc
@@ -735,7 +735,7 @@ // pages). bool should_quit_if_last_browser = browser_shutdown::IsTryingToQuit() || - !KeepAliveRegistry::GetInstance()->IsKeepingAlive(); + KeepAliveRegistry::GetInstance()->IsKeepingAliveOnlyByBrowserOrigin(); if (should_quit_if_last_browser && ShouldStartShutdown()) browser_shutdown::OnShutdownStarting(browser_shutdown::WINDOW_CLOSE); @@ -2464,8 +2464,20 @@ return window_ && window_->ShouldHideUIForFullscreen(); } +bool Browser::IsBrowserClosing() const { + const BrowserList::BrowserSet& closing_browsers = + BrowserList::GetInstance()->currently_closing_browsers(); + + return base::ContainsKey(closing_browsers, this); +} + bool Browser::ShouldStartShutdown() const { - return BrowserList::GetInstance()->size() <= 1; + if (IsBrowserClosing()) + return false; + + const size_t closing_browsers_count = + BrowserList::GetInstance()->currently_closing_browsers().size(); + return BrowserList::GetInstance()->size() == closing_browsers_count + 1u; } bool Browser::MaybeCreateBackgroundContents(
diff --git a/chrome/browser/ui/browser.h b/chrome/browser/ui/browser.h index 5760913..fa3047d 100644 --- a/chrome/browser/ui/browser.h +++ b/chrome/browser/ui/browser.h
@@ -828,6 +828,10 @@ bool ShouldHideUIForFullscreen() const; + // Indicates if we have called BrowserList::NotifyBrowserCloseStarted for the + // browser. + bool IsBrowserClosing() const; + // Returns true if we can start the shutdown sequence for the browser, i.e. // the last browser window is being closed. bool ShouldStartShutdown() const;
diff --git a/chrome/browser/ui/browser_command_controller.h b/chrome/browser/ui/browser_command_controller.h index 7bfcde4..e5f23e0 100644 --- a/chrome/browser/ui/browser_command_controller.h +++ b/chrome/browser/ui/browser_command_controller.h
@@ -160,7 +160,7 @@ inline BrowserWindow* window(); inline Profile* profile(); - Browser* browser_; + Browser* const browser_; // The CommandUpdater that manages the browser window commands. CommandUpdater command_updater_;
diff --git a/chrome/browser/ui/browser_content_setting_bubble_model_delegate.h b/chrome/browser/ui/browser_content_setting_bubble_model_delegate.h index b3d451b..d10dd72 100644 --- a/chrome/browser/ui/browser_content_setting_bubble_model_delegate.h +++ b/chrome/browser/ui/browser_content_setting_bubble_model_delegate.h
@@ -26,7 +26,7 @@ void ShowLearnMorePage(ContentSettingsType type) override; private: - Browser* browser_; + Browser* const browser_; DISALLOW_COPY_AND_ASSIGN(BrowserContentSettingBubbleModelDelegate); };
diff --git a/chrome/browser/ui/browser_list.cc b/chrome/browser/ui/browser_list.cc index 2d25e705..7de1673 100644 --- a/chrome/browser/ui/browser_list.cc +++ b/chrome/browser/ui/browser_list.cc
@@ -84,6 +84,7 @@ // Remove |browser| from the appropriate list instance. BrowserList* browser_list = GetInstance(); RemoveBrowserFrom(browser, &browser_list->last_active_browsers_); + browser_list->currently_closing_browsers_.erase(browser); content::NotificationService::current()->Notify( chrome::NOTIFICATION_BROWSER_CLOSED, @@ -253,6 +254,8 @@ // static void BrowserList::NotifyBrowserCloseStarted(Browser* browser) { + GetInstance()->currently_closing_browsers_.insert(browser); + for (chrome::BrowserListObserver& observer : observers_.Get()) observer.OnBrowserClosing(browser); }
diff --git a/chrome/browser/ui/browser_list.h b/chrome/browser/ui/browser_list.h index ba78df21..f26a7c5 100644 --- a/chrome/browser/ui/browser_list.h +++ b/chrome/browser/ui/browser_list.h
@@ -10,6 +10,7 @@ #include <vector> #include "base/callback_forward.h" +#include "base/containers/flat_set.h" #include "base/lazy_instance.h" #include "base/macros.h" #include "base/observer_list.h" @@ -28,6 +29,7 @@ // Maintains a list of Browser objects. class BrowserList { public: + using BrowserSet = base::flat_set<Browser*>; using BrowserVector = std::vector<Browser*>; using CloseCallback = base::Callback<void(const base::FilePath&)>; using const_iterator = BrowserVector::const_iterator; @@ -57,6 +59,11 @@ return last_active_browsers_.rend(); } + // Returns the set of browsers that are currently in the closing state. + const BrowserSet& currently_closing_browsers() const { + return currently_closing_browsers_; + } + static BrowserList* GetInstance(); // Adds or removes |browser| from the list it is associated with. The browser @@ -153,6 +160,8 @@ // A vector of the browsers in this list that have been activated, in the // reverse order in which they were last activated. BrowserVector last_active_browsers_; + // A vector of the browsers that are currently in the closing state. + BrowserSet currently_closing_browsers_; // A list of observers which will be notified of every browser addition and // removal across all BrowserLists.
diff --git a/chrome/browser/ui/browser_live_tab_context.h b/chrome/browser/ui/browser_live_tab_context.h index 715f5b6..8e7bf16 100644 --- a/chrome/browser/ui/browser_live_tab_context.h +++ b/chrome/browser/ui/browser_live_tab_context.h
@@ -81,7 +81,7 @@ SessionID::id_type desired_id); private: - Browser* browser_; + Browser* const browser_; DISALLOW_COPY_AND_ASSIGN(BrowserLiveTabContext); };
diff --git a/chrome/browser/ui/browser_navigator.cc b/chrome/browser/ui/browser_navigator.cc index 7074c45..4077120c6 100644 --- a/chrome/browser/ui/browser_navigator.cc +++ b/chrome/browser/ui/browser_navigator.cc
@@ -676,9 +676,6 @@ url.host_piece() == chrome::kChromeUIThumbnailHost2 || url.host_piece() == chrome::kChromeUIThumbnailListHost || url.host_piece() == chrome::kChromeUISuggestionsHost || -#if defined(OS_CHROMEOS) - url.host_piece() == chrome::kChromeUIVoiceSearchHost || -#endif url.host_piece() == chrome::kChromeUIDevicesHost)) { return false; }
diff --git a/chrome/browser/ui/browser_tab_strip_model_delegate.h b/chrome/browser/ui/browser_tab_strip_model_delegate.h index 998cc900..2bc775c 100644 --- a/chrome/browser/ui/browser_tab_strip_model_delegate.h +++ b/chrome/browser/ui/browser_tab_strip_model_delegate.h
@@ -41,7 +41,7 @@ void CloseFrame(); - Browser* browser_; + Browser* const browser_; // The following factory is used to close the frame at a later time. base::WeakPtrFactory<BrowserTabStripModelDelegate> weak_factory_;
diff --git a/chrome/browser/ui/browser_toolbar_model_delegate.h b/chrome/browser/ui/browser_toolbar_model_delegate.h index 6babac7..9b3e5d5 100644 --- a/chrome/browser/ui/browser_toolbar_model_delegate.h +++ b/chrome/browser/ui/browser_toolbar_model_delegate.h
@@ -22,7 +22,7 @@ content::WebContents* GetActiveWebContents() const override; private: - Browser* browser_; + Browser* const browser_; DISALLOW_COPY_AND_ASSIGN(BrowserToolbarModelDelegate); };
diff --git a/chrome/browser/ui/cocoa/app_menu/app_menu_controller.mm b/chrome/browser/ui/cocoa/app_menu/app_menu_controller.mm index 0044946..89f8b4b 100644 --- a/chrome/browser/ui/cocoa/app_menu/app_menu_controller.mm +++ b/chrome/browser/ui/cocoa/app_menu/app_menu_controller.mm
@@ -184,6 +184,7 @@ recentTabsMenuModelDelegate_.reset(); [self setModel:nullptr]; appMenuModel_.reset(); + bookmarkMenuBridge_ = nullptr; buttonViewController_.reset(); // The observers should most likely already be destroyed (since they're reset @@ -304,7 +305,6 @@ } - (void)updateBookmarkSubMenu { - DCHECK(!bookmarkMenuBridge_); NSMenu* bookmarkMenu = [self bookmarkSubMenu]; if (!bookmarkMenu) return; // Guest profiles have no bookmarks menu. @@ -317,6 +317,12 @@ // which can't be reused across menu invocations. bookmarkMenuBridge_ = std::make_unique<BookmarkMenuBridge>( [self appMenuModel]->browser()->profile(), bookmarkMenu); + + // Note |bookmarkMenuBridge_| is useless after the menu closes, but it must + // exist when (and if) the menu action is sent. Unfortunately, AppKit sends + // menu actions after menuDidClose: and NSMenuDidEndTrackingNotification so + // |bookmarkMenuBridge_| is going to hang around until updateBookmarkSubMenu + // is called again. } - (void)updateBrowserActionsSubmenu { @@ -395,8 +401,6 @@ - (void)menuDidClose:(NSMenu*)menu { [super menuDidClose:menu]; - bookmarkMenuBridge_ = nullptr; - // We don't need to observe changes to zoom or toolbar size when the menu is // closed, since we instantiate it with the proper value and recreate the menu // on each show. (We do this in -menuNeedsUpdate:, which is called when the
diff --git a/chrome/browser/ui/cocoa/app_menu/app_menu_controller_unittest.mm b/chrome/browser/ui/cocoa/app_menu/app_menu_controller_unittest.mm index e013e5a..57cfda5 100644 --- a/chrome/browser/ui/cocoa/app_menu/app_menu_controller_unittest.mm +++ b/chrome/browser/ui/cocoa/app_menu/app_menu_controller_unittest.mm
@@ -11,10 +11,13 @@ #include "base/strings/sys_string_conversions.h" #include "base/strings/utf_string_conversions.h" #include "chrome/app/chrome_command_ids.h" +#include "chrome/browser/bookmarks/bookmark_model_factory.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/sync/profile_sync_test_util.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_list_observer.h" +#import "chrome/browser/ui/cocoa/bookmarks/bookmark_menu_bridge.h" +#import "chrome/browser/ui/cocoa/bookmarks/bookmark_menu_cocoa_controller.h" #include "chrome/browser/ui/cocoa/test/cocoa_profile_test.h" #include "chrome/browser/ui/cocoa/test/run_loop_testing.h" #import "chrome/browser/ui/cocoa/toolbar/toolbar_controller.h" @@ -27,6 +30,7 @@ #include "chrome/grit/generated_resources.h" #include "chrome/grit/theme_resources.h" #include "chrome/test/base/testing_profile.h" +#include "components/bookmarks/browser/bookmark_model.h" #include "components/browser_sync/profile_sync_service.h" #include "components/browser_sync/profile_sync_service_mock.h" #include "components/sync/base/sync_prefs.h" @@ -47,6 +51,25 @@ using testing::Invoke; using testing::Return; +@implementation AppMenuController (TestingAPI) +- (BookmarkMenuBridge*)bookmarkMenuBridge { + return bookmarkMenuBridge_.get(); +} +@end + +@interface TestBookmarkMenuCocoaController : BookmarkMenuCocoaController +@property(nonatomic, readonly) const bookmarks::BookmarkNode* lastOpenedNode; +@end + +@implementation TestBookmarkMenuCocoaController { + const bookmarks::BookmarkNode* lastOpenedNode_; +} +@synthesize lastOpenedNode = lastOpenedNode_; +- (void)openURLForNode:(const bookmarks::BookmarkNode*)node { + lastOpenedNode_ = node; +} +@end + namespace { class MockAppMenuModel : public AppMenuModel { @@ -64,6 +87,23 @@ void Stop() override {} }; +class BrowserRemovedObserver : public chrome::BrowserListObserver { + public: + BrowserRemovedObserver() { BrowserList::AddObserver(this); } + ~BrowserRemovedObserver() override { BrowserList::RemoveObserver(this); } + void WaitUntilBrowserRemoved() { run_loop_.Run(); } + void OnBrowserRemoved(Browser* browser) override { run_loop_.Quit(); } + + private: + base::RunLoop run_loop_; + + DISALLOW_COPY_AND_ASSIGN(BrowserRemovedObserver); +}; + +} // namespace + +namespace test { + class AppMenuControllerTest : public CocoaProfileTest { public: AppMenuControllerTest() { @@ -105,6 +145,17 @@ new syncer::SyncErrorFactoryMock)); } + TestBookmarkMenuCocoaController* SetTestBookmarksMenuDelegate( + BookmarkMenuBridge* bridge) { + base::scoped_nsobject<TestBookmarkMenuCocoaController> test_controller( + [[TestBookmarkMenuCocoaController alloc] initWithBridge:bridge]); + bridge->ClearBookmarkMenu(); + [bridge->BookmarkMenu() setDelegate:test_controller]; + bridge->controller_ = + base::scoped_nsobject<BookmarkMenuCocoaController>(test_controller); + return test_controller; + } + void RegisterRecentTabs(RecentTabsBuilderTestHelper* helper) { helper->ExportToSessionsSyncManager(manager_.get()); } @@ -270,18 +321,51 @@ // If the delete order is wrong then the test will crash on exit. } -class BrowserRemovedObserver : public chrome::BrowserListObserver { - public: - BrowserRemovedObserver() { BrowserList::AddObserver(this); } - ~BrowserRemovedObserver() override { BrowserList::RemoveObserver(this); } - void WaitUntilBrowserRemoved() { run_loop_.Run(); } - void OnBrowserRemoved(Browser* browser) override { run_loop_.Quit(); } +// Simulate opening a bookmark from the bookmark submenu. +TEST_F(AppMenuControllerTest, OpenBookmark) { + // Ensure there's at least one bookmark. + bookmarks::BookmarkModel* model = + BookmarkModelFactory::GetForBrowserContext(profile()); + ASSERT_TRUE(model); + const bookmarks::BookmarkNode* parent = model->bookmark_bar_node(); + const bookmarks::BookmarkNode* about = model->AddURL( + parent, 0, base::ASCIIToUTF16("About"), GURL("chrome://chrome")); - private: - base::RunLoop run_loop_; + EXPECT_FALSE([controller_ bookmarkMenuBridge]); - DISALLOW_COPY_AND_ASSIGN(BrowserRemovedObserver); -}; + [controller_ menuNeedsUpdate:[controller_ menu]]; + BookmarkMenuBridge* bridge = [controller_ bookmarkMenuBridge]; + EXPECT_TRUE(bridge); + + NSMenu* bookmarks_menu = + [[[controller_ menu] itemWithTitle:@"Bookmarks"] submenu]; + EXPECT_TRUE(bookmarks_menu); + EXPECT_TRUE([bookmarks_menu delegate]); + + // The bookmark item actions would do Browser::OpenURL(), which will fail in a + // unit test. So swap in a test delegate. + TestBookmarkMenuCocoaController* test_controller = + SetTestBookmarksMenuDelegate(bridge); + + // The fixed items from the default model. + EXPECT_EQ(5u, [bookmarks_menu numberOfItems]); + + // When AppKit shows the menu, the bookmark items are added (and a separator). + [[bookmarks_menu delegate] menuNeedsUpdate:bookmarks_menu]; + EXPECT_EQ(7u, [bookmarks_menu numberOfItems]); + + base::scoped_nsobject<NSMenuItem> item( + [[bookmarks_menu itemWithTitle:@"About"] retain]); + EXPECT_TRUE(item); + EXPECT_TRUE([item target]); + EXPECT_TRUE([item action]); + + // Simulate how AppKit would click the item (menuDidClose happens first). + [controller_ menuDidClose:[controller_ menu]]; + EXPECT_FALSE([test_controller lastOpenedNode]); + [[item target] performSelector:[item action] withObject:item]; + EXPECT_EQ(about, [test_controller lastOpenedNode]); +} // Test that AppMenuController can be destroyed after the Browser. // This can happen because the AppMenuController's owner (ToolbarController) @@ -296,4 +380,4 @@ // |controller_| is released in TearDown(). } -} // namespace +} // namespace test
diff --git a/chrome/browser/ui/cocoa/bookmarks/bookmark_menu_bridge.h b/chrome/browser/ui/cocoa/bookmarks/bookmark_menu_bridge.h index d8597a7..91defb4 100644 --- a/chrome/browser/ui/cocoa/bookmarks/bookmark_menu_bridge.h +++ b/chrome/browser/ui/cocoa/bookmarks/bookmark_menu_bridge.h
@@ -20,6 +20,10 @@ class BookmarkNode; } +namespace test { +class AppMenuControllerTest; +} + // C++ controller for the bookmark menu; one per AppController (which // means there is only one). When bookmarks are changed, this class // takes care of updating Cocoa bookmark menus. This is not named @@ -82,6 +86,7 @@ private: friend class BookmarkMenuBridgeTest; + friend class test::AppMenuControllerTest; void BuildRootMenu();
diff --git a/chrome/browser/ui/cocoa/browser_window_command_handler.mm b/chrome/browser/ui/cocoa/browser_window_command_handler.mm index fd6efdd..6efecd01 100644 --- a/chrome/browser/ui/cocoa/browser_window_command_handler.mm +++ b/chrome/browser/ui/cocoa/browser_window_command_handler.mm
@@ -15,6 +15,7 @@ #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_window.h" #import "chrome/browser/ui/cocoa/browser_window_controller_private.h" +#include "chrome/common/chrome_features.h" #include "chrome/common/pref_names.h" #include "chrome/grit/generated_resources.h" #include "content/public/browser/web_contents.h" @@ -65,11 +66,13 @@ if (tag == IDC_WINDOW_MUTE_TAB) { TabStripModel* model = browser->tab_strip_model(); + bool will_mute = + base::FeatureList::IsEnabled(features::kSoundContentSetting) + ? model->WillContextMenuMuteSites(model->active_index()) + : model->WillContextMenuMute(model->active_index()); // Menu items may be validated during browser startup, before the // TabStripModel has been populated. - SetToggleState( - !model->empty() && !model->WillContextMenuMute(model->active_index()), - item); + SetToggleState(!model->empty() && !will_mute, item); return; }
diff --git a/chrome/browser/ui/cocoa/browser_window_touch_bar.mm b/chrome/browser/ui/cocoa/browser_window_touch_bar.mm index af66171..381f9435 100644 --- a/chrome/browser/ui/cocoa/browser_window_touch_bar.mm +++ b/chrome/browser/ui/cocoa/browser_window_touch_bar.mm
@@ -123,7 +123,7 @@ } // A class registered for C++ notifications. This is used to detect changes in -// the home button preferences and the back/forward commands. +// the profile preferences and the back/forward commands. class BrowserTouchBarNotificationBridge : public CommandObserver { public: BrowserTouchBarNotificationBridge(BrowserWindowTouchBar* observer, @@ -162,6 +162,9 @@ // Used to monitor the optional home button pref. BooleanPrefMember showHomeButton_; + // Used to listen for default search engine pref changes. + PrefChangeRegistrar profilePrefRegistrar_; + // Used to receive and handle notifications. std::unique_ptr<BrowserTouchBarNotificationBridge> notificationBridge_; @@ -212,6 +215,12 @@ prefs::kShowHomeButton, prefs, base::Bind(&BrowserTouchBarNotificationBridge::UpdateTouchBar, base::Unretained(notificationBridge_.get()))); + + profilePrefRegistrar_.Init(prefs); + profilePrefRegistrar_.Add( + DefaultSearchManager::kDefaultSearchProviderDataPrefName, + base::Bind(&BrowserTouchBarNotificationBridge::UpdateTouchBar, + base::Unretained(notificationBridge_.get()))); } return self;
diff --git a/chrome/browser/ui/cocoa/browser_window_touch_bar_browsertest.mm b/chrome/browser/ui/cocoa/browser_window_touch_bar_browsertest.mm index 34ca3c1..2bcf94f 100644 --- a/chrome/browser/ui/cocoa/browser_window_touch_bar_browsertest.mm +++ b/chrome/browser/ui/cocoa/browser_window_touch_bar_browsertest.mm
@@ -7,7 +7,10 @@ #include "chrome/browser/ui/browser_window.h" #import "chrome/browser/ui/cocoa/browser_window_controller.h" #import "chrome/browser/ui/cocoa/browser_window_touch_bar.h" +#include "chrome/common/pref_names.h" #include "chrome/test/base/in_process_browser_test.h" +#include "components/prefs/pref_service.h" +#include "components/search_engines/search_engines_test_util.cc" #include "content/public/test/browser_test_utils.h" #include "content/public/test/test_utils.h" #include "testing/gtest_mac.h" @@ -105,3 +108,26 @@ EXPECT_NE(touch_bar, [window touchBar]); } } + +// Tests if the touch bar gets invalidated if the default search engine has +// changed. +IN_PROC_BROWSER_TEST_F(BrowserWindowTouchBarTest, SearchEngineChanges) { + if (@available(macOS 10.12.2, *)) { + PrefService* prefs = browser()->profile()->GetPrefs(); + DCHECK(prefs); + + NSWindow* window = [browser_window_controller() window]; + NSTouchBar* touch_bar = [browser_touch_bar() makeTouchBar]; + [window setTouchBar:touch_bar]; + EXPECT_TRUE([window touchBar]); + + // Change the default search engine. + std::unique_ptr<TemplateURLData> data = + GenerateDummyTemplateURLData("poutine"); + prefs->Set(DefaultSearchManager::kDefaultSearchProviderDataPrefName, + *TemplateURLDataToDictionary(*data)); + + // The window should have a new touch bar. + EXPECT_NE(touch_bar, [window touchBar]); + } +}
diff --git a/chrome/browser/ui/cocoa/download/download_shelf_controller.mm b/chrome/browser/ui/cocoa/download/download_shelf_controller.mm index f1452e4..4e199294 100644 --- a/chrome/browser/ui/cocoa/download/download_shelf_controller.mm +++ b/chrome/browser/ui/cocoa/download/download_shelf_controller.mm
@@ -175,7 +175,7 @@ [NSView cr_localizedAutoresizingMask:NSViewMinXMargin]; closeButton.icon = &vector_icons::kClose16Icon; [closeButton - cr_setAccessibilityLabel:l10n_util::GetNSString(IDS_ACCNAME_CLOSE)]; + cr_setAccessibilityLabel:l10n_util::GetNSString(IDS_HIDE_DOWNLOADS)]; closeButton.target = self; closeButton.action = @selector(handleClose:); hoverCloseButton_ = closeButton;
diff --git a/chrome/browser/ui/content_settings/content_setting_image_model.cc b/chrome/browser/ui/content_settings/content_setting_image_model.cc index 01e091d..f9944c0 100644 --- a/chrome/browser/ui/content_settings/content_setting_image_model.cc +++ b/chrome/browser/ui/content_settings/content_setting_image_model.cc
@@ -568,13 +568,7 @@ // Base class ------------------------------------------------------------------ -gfx::Image ContentSettingImageModel::GetIcon(SkColor nearby_text_color) const { -#if defined(OS_MACOSX) - SkColor icon_color = nearby_text_color; -#else - SkColor icon_color = color_utils::DeriveDefaultIconColor(nearby_text_color); -#endif - +gfx::Image ContentSettingImageModel::GetIcon(SkColor icon_color) const { return gfx::Image( gfx::CreateVectorIconWithBadge(*icon_, 16, icon_color, *icon_badge_)); }
diff --git a/chrome/browser/ui/content_settings/content_setting_image_model.h b/chrome/browser/ui/content_settings/content_setting_image_model.h index 490f30e9..727d9c3 100644 --- a/chrome/browser/ui/content_settings/content_setting_image_model.h +++ b/chrome/browser/ui/content_settings/content_setting_image_model.h
@@ -62,7 +62,7 @@ content::WebContents* web_contents); #endif - gfx::Image GetIcon(SkColor nearby_text_color) const; + gfx::Image GetIcon(SkColor icon_color) const; // Returns the resource ID of a string to show when the icon appears, or 0 if // we don't wish to show anything.
diff --git a/chrome/browser/ui/exclusive_access/fullscreen_controller_interactive_browsertest.cc b/chrome/browser/ui/exclusive_access/fullscreen_controller_interactive_browsertest.cc index 9a736f3a..243e3762 100644 --- a/chrome/browser/ui/exclusive_access/fullscreen_controller_interactive_browsertest.cc +++ b/chrome/browser/ui/exclusive_access/fullscreen_controller_interactive_browsertest.cc
@@ -157,8 +157,13 @@ // Tests that while in fullscreen creating a new tab will exit fullscreen. // Test is flaky: http://crbug.com/146006 +#if defined(OS_WIN) +#define MAYBE_TestNewTabExitsFullscreen TestNewTabExitsFullscreen +#else +#define MAYBE_TestNewTabExitsFullscreen DISABLED_TestNewTabExitsFullscreen +#endif IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest, - DISABLED_TestNewTabExitsFullscreen) { + MAYBE_TestNewTabExitsFullscreen) { ASSERT_TRUE(embedded_test_server()->Start()); AddTabAtIndex(0, GURL(url::kAboutBlankURL), PAGE_TRANSITION_TYPED); @@ -175,8 +180,14 @@ // Tests a tab exiting fullscreen will bring the browser out of fullscreen. // Test is flaky: http://crbug.com/146006 +#if defined(OS_WIN) +#define MAYBE_TestTabExitsItselfFromFullscreen TestTabExitsItselfFromFullscreen +#else +#define MAYBE_TestTabExitsItselfFromFullscreen \ + DISABLED_TestTabExitsItselfFromFullscreen +#endif IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest, - DISABLED_TestTabExitsItselfFromFullscreen) { + MAYBE_TestTabExitsItselfFromFullscreen) { ASSERT_TRUE(embedded_test_server()->Start()); AddTabAtIndex(0, GURL(url::kAboutBlankURL), PAGE_TRANSITION_TYPED); @@ -187,8 +198,13 @@ // Tests Fullscreen entered in Browser, then Tab mode, then exited via Browser. // Test is flaky: http://crbug.com/146006 +#if defined(OS_WIN) +#define MAYBE_BrowserFullscreenExit BrowserFullscreenExit +#else +#define MAYBE_BrowserFullscreenExit DISABLED_BrowserFullscreenExit +#endif IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest, - DISABLED_BrowserFullscreenExit) { + MAYBE_BrowserFullscreenExit) { // Enter browser fullscreen. ASSERT_NO_FATAL_FAILURE(ToggleBrowserFullscreen(true)); @@ -203,8 +219,14 @@ // Tests Browser Fullscreen remains active after Tab mode entered and exited. // Test is flaky: http://crbug.com/146006 +#if defined(OS_WIN) +#define MAYBE_BrowserFullscreenAfterTabFSExit BrowserFullscreenAfterTabFSExit +#else +#define MAYBE_BrowserFullscreenAfterTabFSExit \ + DISABLED_BrowserFullscreenAfterTabFSExit +#endif IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest, - DISABLED_BrowserFullscreenAfterTabFSExit) { + MAYBE_BrowserFullscreenAfterTabFSExit) { // Enter browser fullscreen. ASSERT_NO_FATAL_FAILURE(ToggleBrowserFullscreen(true)); @@ -219,8 +241,13 @@ // Tests fullscreen entered without permision prompt for file:// urls. // Test is flaky: http://crbug.com/146006 +#if defined(OS_WIN) +#define MAYBE_FullscreenFileURL FullscreenFileURL +#else +#define MAYBE_FullscreenFileURL DISABLED_FullscreenFileURL +#endif IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest, - DISABLED_FullscreenFileURL) { + MAYBE_FullscreenFileURL) { ui_test_utils::NavigateToURL( browser(), ui_test_utils::GetTestUrl( base::FilePath(base::FilePath::kCurrentDirectory), @@ -233,8 +260,15 @@ // Tests fullscreen is exited on page navigation. // Test is flaky: http://crbug.com/146006 +#if defined(OS_WIN) +#define MAYBE_TestTabExitsFullscreenOnNavigation \ + TestTabExitsFullscreenOnNavigation +#else +#define MAYBE_TestTabExitsFullscreenOnNavigation \ + DISABLED_TestTabExitsFullscreenOnNavigation +#endif IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest, - DISABLED_TestTabExitsFullscreenOnNavigation) { + MAYBE_TestTabExitsFullscreenOnNavigation) { ASSERT_TRUE(embedded_test_server()->Start()); ui_test_utils::NavigateToURL(browser(), GURL("about:blank")); @@ -246,8 +280,14 @@ // Tests fullscreen is exited when navigating back. // Test is flaky: http://crbug.com/146006 +#if defined(OS_WIN) +#define MAYBE_TestTabExitsFullscreenOnGoBack TestTabExitsFullscreenOnGoBack +#else +#define MAYBE_TestTabExitsFullscreenOnGoBack \ + DISABLED_TestTabExitsFullscreenOnGoBack +#endif IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest, - DISABLED_TestTabExitsFullscreenOnGoBack) { + MAYBE_TestTabExitsFullscreenOnGoBack) { ASSERT_TRUE(embedded_test_server()->Start()); ui_test_utils::NavigateToURL(browser(), GURL("about:blank")); @@ -262,9 +302,15 @@ // Tests fullscreen is not exited on sub frame navigation. // Test is flaky: http://crbug.com/146006 -IN_PROC_BROWSER_TEST_F( - FullscreenControllerInteractiveTest, - DISABLED_TestTabDoesntExitFullscreenOnSubFrameNavigation) { +#if defined(OS_WIN) +#define MAYBE_TestTabDoesntExitFullscreenOnSubFrameNavigation \ + TestTabDoesntExitFullscreenOnSubFrameNavigation +#else +#define MAYBE_TestTabDoesntExitFullscreenOnSubFrameNavigation \ + DISABLED_TestTabDoesntExitFullscreenOnSubFrameNavigation +#endif +IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest, + MAYBE_TestTabDoesntExitFullscreenOnSubFrameNavigation) { ASSERT_TRUE(embedded_test_server()->Start()); GURL url(ui_test_utils::GetTestUrl(base::FilePath( @@ -279,9 +325,16 @@ // Tests tab fullscreen exits, but browser fullscreen remains, on navigation. // Test is flaky: http://crbug.com/146006 +#if defined(OS_WIN) +#define MAYBE_TestFullscreenFromTabWhenAlreadyInBrowserFullscreenWorks \ + TestFullscreenFromTabWhenAlreadyInBrowserFullscreenWorks +#else +#define MAYBE_TestFullscreenFromTabWhenAlreadyInBrowserFullscreenWorks \ + DISABLED_TestFullscreenFromTabWhenAlreadyInBrowserFullscreenWorks +#endif IN_PROC_BROWSER_TEST_F( FullscreenControllerInteractiveTest, - DISABLED_TestFullscreenFromTabWhenAlreadyInBrowserFullscreenWorks) { + MAYBE_TestFullscreenFromTabWhenAlreadyInBrowserFullscreenWorks) { ASSERT_TRUE(embedded_test_server()->Start()); ui_test_utils::NavigateToURL(browser(), GURL("about:blank")); @@ -359,8 +412,14 @@ // Tests mouse lock and fullscreen modes can be escaped with ESC key. // Test is flaky: http://crbug.com/146006 +#if defined(OS_WIN) +#define MAYBE_EscapingMouseLockAndFullscreen EscapingMouseLockAndFullscreen +#else +#define MAYBE_EscapingMouseLockAndFullscreen \ + DISABLED_EscapingMouseLockAndFullscreen +#endif IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest, - DISABLED_EscapingMouseLockAndFullscreen) { + MAYBE_EscapingMouseLockAndFullscreen) { ASSERT_TRUE(embedded_test_server()->Start()); ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL(kFullscreenMouseLockHTML)); @@ -389,8 +448,13 @@ // Tests mouse lock then fullscreen. // Test is flaky: http://crbug.com/146006 +#if defined(OS_WIN) +#define MAYBE_MouseLockThenFullscreen MouseLockThenFullscreen +#else +#define MAYBE_MouseLockThenFullscreen DISABLED_MouseLockThenFullscreen +#endif IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest, - DISABLED_MouseLockThenFullscreen) { + MAYBE_MouseLockThenFullscreen) { ASSERT_TRUE(embedded_test_server()->Start()); ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL(kFullscreenMouseLockHTML)); @@ -423,8 +487,13 @@ // Mac: http://crbug.com/103912 // Windows: Failing flakily on try jobs also. // Tests mouse lock then fullscreen in same request. +#if defined(OS_WIN) +#define MAYBE_MouseLockAndFullscreen MouseLockAndFullscreen +#else +#define MAYBE_MouseLockAndFullscreen DISABLED_MouseLockAndFullscreen +#endif IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest, - DISABLED_MouseLockAndFullscreen) { + MAYBE_MouseLockAndFullscreen) { ASSERT_TRUE(embedded_test_server()->Start()); ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL(kFullscreenMouseLockHTML)); @@ -449,8 +518,14 @@ // embedded flash fullscreen, since the Flash plugin handles user permissions // requests itself). // Test is flaky: http://crbug.com/146006 +#if defined(OS_WIN) +#define MAYBE_PrivilegedMouseLockAndFullscreen PrivilegedMouseLockAndFullscreen +#else +#define MAYBE_PrivilegedMouseLockAndFullscreen \ + DISABLED_PrivilegedMouseLockAndFullscreen +#endif IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest, - DISABLED_PrivilegedMouseLockAndFullscreen) { + MAYBE_PrivilegedMouseLockAndFullscreen) { ASSERT_TRUE(embedded_test_server()->Start()); ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL(kFullscreenMouseLockHTML)); @@ -473,8 +548,8 @@ ASSERT_TRUE(IsWindowFullscreenForTabOrPending()); } -// Flaky on Windows, Linux, CrOS: http://crbug.com/159000 -#if defined(OS_WIN) || defined(OS_LINUX) || defined(OS_CHROMEOS) +// Flaky on Linux, CrOS: http://crbug.com/159000 +#if defined(OS_LINUX) || defined(OS_CHROMEOS) #define MAYBE_MouseLockSilentAfterTargetUnlock \ DISABLED_MouseLockSilentAfterTargetUnlock #else @@ -548,10 +623,7 @@ ASSERT_TRUE(IsMouseLocked()); } -#if defined(OS_WIN) || \ - (defined(OS_LINUX) && !defined(OS_CHROMEOS) && defined(USE_AURA)) -// These tests are very flaky on Vista. -// http://crbug.com/158762 +#if defined(OS_LINUX) && !defined(OS_CHROMEOS) && defined(USE_AURA) // These are flaky on linux_aura. // http://crbug.com/163931 #define MAYBE_TestTabExitsMouseLockOnNavigation \ @@ -648,8 +720,15 @@ // Tests Mouse Lock and Fullscreen are exited upon reload. // http://crbug.com/137486 // mac: http://crbug.com/103912 +#if defined(OS_WIN) +#define MAYBE_ReloadExitsMouseLockAndFullscreen \ + ReloadExitsMouseLockAndFullscreen +#else +#define MAYBE_ReloadExitsMouseLockAndFullscreen \ + DISABLED_ReloadExitsMouseLockAndFullscreen +#endif IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest, - DISABLED_ReloadExitsMouseLockAndFullscreen) { + MAYBE_ReloadExitsMouseLockAndFullscreen) { ASSERT_TRUE(embedded_test_server()->Start()); ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL(kFullscreenMouseLockHTML)); @@ -695,8 +774,13 @@ // Tests ToggleFullscreenModeForTab always causes window to change. // Test is flaky: http://crbug.com/146006 +#if defined(OS_WIN) +#define MAYBE_ToggleFullscreenModeForTab ToggleFullscreenModeForTab +#else +#define MAYBE_ToggleFullscreenModeForTab DISABLED_ToggleFullscreenModeForTab +#endif IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest, - DISABLED_ToggleFullscreenModeForTab) { + MAYBE_ToggleFullscreenModeForTab) { // Most fullscreen tests run sharded in fullscreen_controller_browsertest.cc // but flakiness required a while loop in // FullscreenControllerTest::ToggleTabFullscreen. This test verifies that
diff --git a/chrome/browser/ui/exclusive_access/fullscreen_controller_state_interactive_browsertest.cc b/chrome/browser/ui/exclusive_access/fullscreen_controller_state_interactive_browsertest.cc index f30eb5b..5c14228 100644 --- a/chrome/browser/ui/exclusive_access/fullscreen_controller_state_interactive_browsertest.cc +++ b/chrome/browser/ui/exclusive_access/fullscreen_controller_state_interactive_browsertest.cc
@@ -65,6 +65,17 @@ // An "empty" test is included as part of each "TEST_EVENT" because it makes // running the entire test suite less flaky on MacOS. All of the tests pass // when run individually. +#if defined(OS_WIN) +#define TEST_EVENT(state, event) \ + IN_PROC_BROWSER_TEST_F(FullscreenControllerStateInteractiveTest, \ + state##__##event##__Empty) {} \ + IN_PROC_BROWSER_TEST_F(FullscreenControllerStateInteractiveTest, \ + state##__##event) { \ + AddTabAtIndex(0, GURL(url::kAboutBlankURL), ui::PAGE_TRANSITION_TYPED); \ + ASSERT_NO_FATAL_FAILURE(TestStateAndEvent(state, event)) \ + << GetAndClearDebugLog(); \ + } +#else // defined(OS_WIN) #define TEST_EVENT(state, event) \ IN_PROC_BROWSER_TEST_F(FullscreenControllerStateInteractiveTest, \ DISABLED_##state##__##event##__Empty) {} \ @@ -75,8 +86,9 @@ ASSERT_NO_FATAL_FAILURE(TestStateAndEvent(state, event)) \ << GetAndClearDebugLog(); \ } - // Progress of tests can be examined by inserting the following line: - // LOG(INFO) << GetAndClearDebugLog(); } +#endif // defined(OS_WIN) + // Progress of tests can be examined by inserting the following line: + // LOG(INFO) << GetAndClearDebugLog(); } #include "chrome/browser/ui/exclusive_access/fullscreen_controller_state_tests.h"
diff --git a/chrome/browser/ui/extensions/extension_installed_bubble.h b/chrome/browser/ui/extensions/extension_installed_bubble.h index bd4a2883..e7347ac 100644 --- a/chrome/browser/ui/extensions/extension_installed_bubble.h +++ b/chrome/browser/ui/extensions/extension_installed_bubble.h
@@ -108,7 +108,7 @@ private: // |extension_| is NULL when we are deleted. const extensions::Extension* extension_; - Browser* browser_; + Browser* const browser_; const SkBitmap icon_; BubbleType type_;
diff --git a/chrome/browser/ui/extensions/extension_message_bubble_factory.h b/chrome/browser/ui/extensions/extension_message_bubble_factory.h index 771b9c33..e123cc9 100644 --- a/chrome/browser/ui/extensions/extension_message_bubble_factory.h +++ b/chrome/browser/ui/extensions/extension_message_bubble_factory.h
@@ -37,7 +37,7 @@ static void set_override_for_tests(OverrideForTesting override); private: - Browser* browser_; + Browser* const browser_; DISALLOW_COPY_AND_ASSIGN(ExtensionMessageBubbleFactory); };
diff --git a/chrome/browser/ui/extensions/hosted_app_browser_controller.h b/chrome/browser/ui/extensions/hosted_app_browser_controller.h index 7f41a29..b2823cfc 100644 --- a/chrome/browser/ui/extensions/hosted_app_browser_controller.h +++ b/chrome/browser/ui/extensions/hosted_app_browser_controller.h
@@ -64,7 +64,7 @@ // Gets the extension for this controller. const Extension* GetExtension() const; - Browser* browser_; + Browser* const browser_; const std::string extension_id_; DISALLOW_COPY_AND_ASSIGN(HostedAppBrowserController);
diff --git a/chrome/browser/ui/fast_unload_controller.h b/chrome/browser/ui/fast_unload_controller.h index 4911e86d..939c266 100644 --- a/chrome/browser/ui/fast_unload_controller.h +++ b/chrome/browser/ui/fast_unload_controller.h
@@ -163,7 +163,7 @@ return !on_close_confirmed_.is_null(); } - Browser* browser_; + Browser* const browser_; content::NotificationRegistrar registrar_;
diff --git a/chrome/browser/ui/find_bar/find_bar_controller.h b/chrome/browser/ui/find_bar/find_bar_controller.h index c5f7fb6..afd6000 100644 --- a/chrome/browser/ui/find_bar/find_bar_controller.h +++ b/chrome/browser/ui/find_bar/find_bar_controller.h
@@ -101,7 +101,7 @@ content::WebContents* web_contents_ = nullptr; // The Browser creating this controller. - Browser* browser_; + Browser* const browser_; // The last match count we reported to the user. This is used by // UpdateFindBarForCurrentResult to avoid flickering.
diff --git a/chrome/browser/ui/javascript_dialogs/javascript_dialog_tab_helper.cc b/chrome/browser/ui/javascript_dialogs/javascript_dialog_tab_helper.cc index 71bc4df..d3a1d8c0 100644 --- a/chrome/browser/ui/javascript_dialogs/javascript_dialog_tab_helper.cc +++ b/chrome/browser/ui/javascript_dialogs/javascript_dialog_tab_helper.cc
@@ -204,16 +204,26 @@ void JavaScriptDialogTabHelper::RunBeforeUnloadDialog( content::WebContents* web_contents, + content::RenderFrameHost* render_frame_host, bool is_reload, DialogClosedCallback callback) { + content::WebContents* parent_web_contents = + WebContentsObserver::web_contents(); + bool foremost = IsWebContentsForemost(parent_web_contents); + navigation_metrics::Scheme scheme = + navigation_metrics::GetScheme(render_frame_host->GetLastCommittedURL()); + UMA_HISTOGRAM_BOOLEAN("JSDialogs.IsForemost.BeforeUnload", foremost); + UMA_HISTOGRAM_ENUMERATION("JSDialogs.Scheme.BeforeUnload", scheme, + navigation_metrics::Scheme::COUNT); + // onbeforeunload dialogs are always handled with an app-modal dialog, because // - they are critical to the user not losing data // - they can be requested for tabs that are not foremost // - they can be requested for many tabs at the same time // and therefore auto-dismissal is inappropriate for them. - return AppModalDialogManager()->RunBeforeUnloadDialog(web_contents, is_reload, - std::move(callback)); + return AppModalDialogManager()->RunBeforeUnloadDialog( + web_contents, render_frame_host, is_reload, std::move(callback)); } bool JavaScriptDialogTabHelper::HandleJavaScriptDialog(
diff --git a/chrome/browser/ui/javascript_dialogs/javascript_dialog_tab_helper.h b/chrome/browser/ui/javascript_dialogs/javascript_dialog_tab_helper.h index d0044e1..88bcab2 100644 --- a/chrome/browser/ui/javascript_dialogs/javascript_dialog_tab_helper.h +++ b/chrome/browser/ui/javascript_dialogs/javascript_dialog_tab_helper.h
@@ -63,6 +63,7 @@ DialogClosedCallback callback, bool* did_suppress_message) override; void RunBeforeUnloadDialog(content::WebContents* web_contents, + content::RenderFrameHost* render_frame_host, bool is_reload, DialogClosedCallback callback) override; bool HandleJavaScriptDialog(content::WebContents* web_contents,
diff --git a/chrome/browser/ui/navigation_correction_tab_observer.cc b/chrome/browser/ui/navigation_correction_tab_observer.cc index 887d681..ee89911 100644 --- a/chrome/browser/ui/navigation_correction_tab_observer.cc +++ b/chrome/browser/ui/navigation_correction_tab_observer.cc
@@ -17,8 +17,8 @@ #include "components/prefs/pref_service.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" -#include "content/public/common/associated_interface_provider.h" #include "google_apis/google_api_keys.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" using content::RenderFrameHost; using content::WebContents;
diff --git a/chrome/browser/ui/passwords/manage_passwords_ui_controller.cc b/chrome/browser/ui/passwords/manage_passwords_ui_controller.cc index 2fe60f4..fddcb082 100644 --- a/chrome/browser/ui/passwords/manage_passwords_ui_controller.cc +++ b/chrome/browser/ui/passwords/manage_passwords_ui_controller.cc
@@ -399,6 +399,8 @@ // The maximum possible value is defined by OR-ing these values. UMA_HISTOGRAM_ENUMERATION("PasswordManager.EditsInSaveBubble", username_edited + 2 * password_changed, 4); + UMA_HISTOGRAM_BOOLEAN("PasswordManager.PasswordSavedWithManualFallback", + BubbleIsManualFallbackForSaving()); save_fallback_timer_.Stop(); SavePasswordInternal(); @@ -411,6 +413,8 @@ void ManagePasswordsUIController::UpdatePassword( const autofill::PasswordForm& password_form) { DCHECK_EQ(password_manager::ui::PENDING_PASSWORD_UPDATE_STATE, GetState()); + UMA_HISTOGRAM_BOOLEAN("PasswordManager.PasswordUpdatedWithManualFallback", + BubbleIsManualFallbackForSaving()); save_fallback_timer_.Stop(); UpdatePasswordInternal(password_form); passwords_data_.TransitionToState(password_manager::ui::MANAGE_STATE);
diff --git a/chrome/browser/ui/passwords/manage_passwords_ui_controller_unittest.cc b/chrome/browser/ui/passwords/manage_passwords_ui_controller_unittest.cc index 8fa2f6a..5a7273b2 100644 --- a/chrome/browser/ui/passwords/manage_passwords_ui_controller_unittest.cc +++ b/chrome/browser/ui/passwords/manage_passwords_ui_controller_unittest.cc
@@ -427,9 +427,12 @@ EXPECT_CALL(*controller(), OnUpdateBubbleAndIconVisibility()); controller()->OnPasswordSubmitted(std::move(test_form_manager)); + base::HistogramTester histogram_tester; controller()->SavePassword(test_local_form().username_value, test_local_form().password_value); ExpectIconStateIs(password_manager::ui::MANAGE_STATE); + histogram_tester.ExpectUniqueSample( + "PasswordManager.PasswordSavedWithManualFallback", false, 1); } TEST_F(ManagePasswordsUIControllerTest, PasswordSavedUKMRecording) { @@ -877,8 +880,11 @@ ExpectIconStateIs(password_manager::ui::PENDING_PASSWORD_UPDATE_STATE); EXPECT_CALL(*controller(), OnUpdateBubbleAndIconVisibility()); + base::HistogramTester histogram_tester; controller()->UpdatePassword(autofill::PasswordForm()); ExpectIconStateIs(password_manager::ui::MANAGE_STATE); + histogram_tester.ExpectUniqueSample( + "PasswordManager.PasswordUpdatedWithManualFallback", false, 1); } TEST_F(ManagePasswordsUIControllerTest, SavePendingStatePasswordAutofilled) { @@ -935,12 +941,17 @@ EXPECT_FALSE(controller()->opened_bubble()); // A user clicks on omnibox icon, opens the bubble and press Save/Update. + base::HistogramTester histogram_tester; if (is_update) { EXPECT_CALL(*controller(), OnUpdateBubbleAndIconVisibility()); controller()->UpdatePassword(autofill::PasswordForm()); + histogram_tester.ExpectUniqueSample( + "PasswordManager.PasswordUpdatedWithManualFallback", true, 1); } else { controller()->SavePassword(test_local_form().username_value, test_local_form().password_value); + histogram_tester.ExpectUniqueSample( + "PasswordManager.PasswordSavedWithManualFallback", true, 1); } ExpectIconAndControllerStateIs(password_manager::ui::MANAGE_STATE); testing::Mock::VerifyAndClearExpectations(controller());
diff --git a/chrome/browser/ui/permission_bubble/chooser_bubble_delegate.h b/chrome/browser/ui/permission_bubble/chooser_bubble_delegate.h index 134cda0..418e6e1 100644 --- a/chrome/browser/ui/permission_bubble/chooser_bubble_delegate.h +++ b/chrome/browser/ui/permission_bubble/chooser_bubble_delegate.h
@@ -31,7 +31,7 @@ private: const content::RenderFrameHost* const owning_frame_; - Browser* browser_; + Browser* const browser_; // |chooser_controller_| is not owned by this class, it is owned by // DeviceChooserContentView[Cocoa]. // This field only temporarily owns the ChooserController. It is moved
diff --git a/chrome/browser/ui/search/local_ntp_browsertest.cc b/chrome/browser/ui/search/local_ntp_browsertest.cc index 6731c39a..ba51b96 100644 --- a/chrome/browser/ui/search/local_ntp_browsertest.cc +++ b/chrome/browser/ui/search/local_ntp_browsertest.cc
@@ -29,9 +29,9 @@ #include "content/public/browser/web_contents.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/test_navigation_observer.h" -#include "net/test/embedded_test_server/embedded_test_server.h" #include "testing/gmock/include/gmock/gmock.h" #include "third_party/WebKit/public/platform/web_feature.mojom.h" +#include "url/gurl.h" class LocalNTPTest : public InProcessBrowserTest { public: @@ -432,101 +432,6 @@ EXPECT_EQ("rtl", dir); } -// A test class that sets up a local HTML file as the NTP URL. -class CustomNTPUrlTest : public LocalNTPTest { - public: - explicit CustomNTPUrlTest(const std::string& ntp_file_path) - : https_test_server_(net::EmbeddedTestServer::TYPE_HTTPS), - ntp_file_path_(ntp_file_path) { - https_test_server_.ServeFilesFromSourceDirectory( - "chrome/test/data/local_ntp"); - } - - private: - void SetUpOnMainThread() override { - ASSERT_TRUE(https_test_server_.Start()); - GURL ntp_url = https_test_server_.GetURL(ntp_file_path_); - local_ntp_test_utils::SetUserSelectedDefaultSearchProvider( - browser()->profile(), https_test_server_.base_url().spec(), - ntp_url.spec()); - } - - net::EmbeddedTestServer https_test_server_; - const std::string ntp_file_path_; -}; - -// A test class that sets up local_ntp_browsertest.html as the NTP URL. It's -// mostly a copy of the real local_ntp.html, but it adds some testing JS. -class LocalNTPJavascriptTest : public CustomNTPUrlTest { - public: - LocalNTPJavascriptTest() : CustomNTPUrlTest("/local_ntp_browsertest.html") {} -}; - -// This runs a bunch of pure JS-side tests, i.e. those that don't require any -// interaction from the native side. -IN_PROC_BROWSER_TEST_F(LocalNTPJavascriptTest, SimpleJavascriptTests) { - content::WebContents* active_tab = local_ntp_test_utils::OpenNewTab( - browser(), GURL(chrome::kChromeUINewTabURL)); - ASSERT_TRUE(search::IsInstantNTP(active_tab)); - - // Run the tests. - bool success = false; - ASSERT_TRUE(instant_test_utils::GetBoolFromJS( - active_tab, "!!runSimpleTests('localNtp')", &success)); - EXPECT_TRUE(success); -} - -// A test class that sets up voice_browsertest.html as the NTP URL. It's -// mostly a copy of the real local_ntp.html, but it adds some testing JS. -class LocalNTPVoiceJavascriptTest : public CustomNTPUrlTest { - public: - LocalNTPVoiceJavascriptTest() : CustomNTPUrlTest("/voice_browsertest.html") {} -}; - -IN_PROC_BROWSER_TEST_F(LocalNTPVoiceJavascriptTest, MicrophoneTests) { - content::WebContents* active_tab = local_ntp_test_utils::OpenNewTab( - browser(), GURL(chrome::kChromeUINewTabURL)); - - // Run the tests. - bool success = false; - ASSERT_TRUE(instant_test_utils::GetBoolFromJS( - active_tab, "!!runSimpleTests('microphone')", &success)); - EXPECT_TRUE(success); -} - -IN_PROC_BROWSER_TEST_F(LocalNTPVoiceJavascriptTest, TextTests) { - content::WebContents* active_tab = local_ntp_test_utils::OpenNewTab( - browser(), GURL(chrome::kChromeUINewTabURL)); - - // Run the tests. - bool success = false; - ASSERT_TRUE(instant_test_utils::GetBoolFromJS( - active_tab, "!!runSimpleTests('text')", &success)); - EXPECT_TRUE(success); -} - -IN_PROC_BROWSER_TEST_F(LocalNTPVoiceJavascriptTest, SpeechTests) { - content::WebContents* active_tab = local_ntp_test_utils::OpenNewTab( - browser(), GURL(chrome::kChromeUINewTabURL)); - - // Run the tests. - bool success = false; - ASSERT_TRUE(instant_test_utils::GetBoolFromJS( - active_tab, "!!runSimpleTests('speech')", &success)); - EXPECT_TRUE(success); -} - -IN_PROC_BROWSER_TEST_F(LocalNTPVoiceJavascriptTest, ViewTests) { - content::WebContents* active_tab = local_ntp_test_utils::OpenNewTab( - browser(), GURL(chrome::kChromeUINewTabURL)); - - // Run the tests. - bool success = false; - ASSERT_TRUE(instant_test_utils::GetBoolFromJS( - active_tab, "!!runSimpleTests('view')", &success)); - EXPECT_TRUE(success); -} - namespace { // Returns the RenderFrameHost corresponding to the most visited iframe in the @@ -542,26 +447,10 @@ } // namespace -IN_PROC_BROWSER_TEST_F(LocalNTPJavascriptTest, LoadsIframe) { - content::WebContents* active_tab = local_ntp_test_utils::OpenNewTab( - browser(), GURL(chrome::kChromeUINewTabURL)); - ASSERT_TRUE(search::IsInstantNTP(active_tab)); - - content::DOMMessageQueue msg_queue; - - bool result = false; - ASSERT_TRUE(instant_test_utils::GetBoolFromJS( - active_tab, "!!setupAdvancedTest(true)", &result)); - ASSERT_TRUE(result); - - // Wait for the MV iframe to load. - std::string message; - // First get rid of the "true" message from the GetBoolFromJS call above. - ASSERT_TRUE(msg_queue.PopMessage(&message)); - ASSERT_EQ("true", message); - // Now wait for the "loaded" message. - ASSERT_TRUE(msg_queue.WaitForMessage(&message)); - ASSERT_EQ("\"loaded\"", message); +IN_PROC_BROWSER_TEST_F(LocalNTPTest, LoadsIframe) { + content::WebContents* active_tab = + local_ntp_test_utils::OpenNewTab(browser(), GURL("about:blank")); + NavigateToNTPAndWaitUntilLoaded(); // Get the iframe and check that the tiles loaded correctly. content::RenderFrameHost* iframe = GetMostVisitedIframe(active_tab);
diff --git a/chrome/browser/ui/search/local_ntp_doodle_browsertest.cc b/chrome/browser/ui/search/local_ntp_doodle_browsertest.cc index a395dfb..034d0ef 100644 --- a/chrome/browser/ui/search/local_ntp_doodle_browsertest.cc +++ b/chrome/browser/ui/search/local_ntp_doodle_browsertest.cc
@@ -27,6 +27,7 @@ #include "content/public/browser/web_contents.h" #include "content/public/test/browser_test_utils.h" #include "testing/gmock/include/gmock/gmock.h" +#include "url/gurl.h" using search_provider_logos::EncodedLogo; using search_provider_logos::EncodedLogoCallback;
diff --git a/chrome/browser/ui/search/local_ntp_js_browsertest.cc b/chrome/browser/ui/search/local_ntp_js_browsertest.cc new file mode 100644 index 0000000..f9931e105 --- /dev/null +++ b/chrome/browser/ui/search/local_ntp_js_browsertest.cc
@@ -0,0 +1,114 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include <string> + +#include "chrome/browser/search/search.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/search/instant_test_utils.h" +#include "chrome/browser/ui/search/local_ntp_test_utils.h" +#include "chrome/common/url_constants.h" +#include "chrome/test/base/in_process_browser_test.h" +#include "net/test/embedded_test_server/embedded_test_server.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "url/gurl.h" + +// A test class that sets up a local HTML file as the NTP URL. +class LocalNTPJavascriptTestBase : public InProcessBrowserTest { + public: + explicit LocalNTPJavascriptTestBase(const std::string& ntp_file_path) + : https_test_server_(net::EmbeddedTestServer::TYPE_HTTPS), + ntp_file_path_(ntp_file_path) { + // Note: We can't use embedded_test_server() from BrowserTestBase because + // that one uses http:// while we want https://. + https_test_server_.ServeFilesFromSourceDirectory( + "chrome/test/data/local_ntp"); + } + + private: + void SetUpOnMainThread() override { + ASSERT_TRUE(https_test_server_.Start()); + GURL ntp_url = https_test_server_.GetURL(ntp_file_path_); + local_ntp_test_utils::SetUserSelectedDefaultSearchProvider( + browser()->profile(), https_test_server_.base_url().spec(), + ntp_url.spec()); + } + + net::EmbeddedTestServer https_test_server_; + const std::string ntp_file_path_; +}; + +// A test class that sets up local_ntp_browsertest.html as the NTP URL. It's +// mostly a copy of the real local_ntp.html, but it adds some testing JS. +class LocalNTPJavascriptTest : public LocalNTPJavascriptTestBase { + public: + LocalNTPJavascriptTest() + : LocalNTPJavascriptTestBase("/local_ntp_browsertest.html") {} +}; + +// This runs a bunch of pure JS-side tests, i.e. those that don't require any +// interaction from the native side. +IN_PROC_BROWSER_TEST_F(LocalNTPJavascriptTest, SimpleJavascriptTests) { + content::WebContents* active_tab = local_ntp_test_utils::OpenNewTab( + browser(), GURL(chrome::kChromeUINewTabURL)); + ASSERT_TRUE(search::IsInstantNTP(active_tab)); + + // Run the tests. + bool success = false; + ASSERT_TRUE(instant_test_utils::GetBoolFromJS( + active_tab, "!!runSimpleTests('localNtp')", &success)); + EXPECT_TRUE(success); +} + +// A test class that sets up voice_browsertest.html as the NTP URL. It's +// mostly a copy of the real local_ntp.html, but it adds some testing JS. +class LocalNTPVoiceJavascriptTest : public LocalNTPJavascriptTestBase { + public: + LocalNTPVoiceJavascriptTest() + : LocalNTPJavascriptTestBase("/voice_browsertest.html") {} +}; + +IN_PROC_BROWSER_TEST_F(LocalNTPVoiceJavascriptTest, MicrophoneTests) { + content::WebContents* active_tab = local_ntp_test_utils::OpenNewTab( + browser(), GURL(chrome::kChromeUINewTabURL)); + + // Run the tests. + bool success = false; + ASSERT_TRUE(instant_test_utils::GetBoolFromJS( + active_tab, "!!runSimpleTests('microphone')", &success)); + EXPECT_TRUE(success); +} + +IN_PROC_BROWSER_TEST_F(LocalNTPVoiceJavascriptTest, TextTests) { + content::WebContents* active_tab = local_ntp_test_utils::OpenNewTab( + browser(), GURL(chrome::kChromeUINewTabURL)); + + // Run the tests. + bool success = false; + ASSERT_TRUE(instant_test_utils::GetBoolFromJS( + active_tab, "!!runSimpleTests('text')", &success)); + EXPECT_TRUE(success); +} + +IN_PROC_BROWSER_TEST_F(LocalNTPVoiceJavascriptTest, SpeechTests) { + content::WebContents* active_tab = local_ntp_test_utils::OpenNewTab( + browser(), GURL(chrome::kChromeUINewTabURL)); + + // Run the tests. + bool success = false; + ASSERT_TRUE(instant_test_utils::GetBoolFromJS( + active_tab, "!!runSimpleTests('speech')", &success)); + EXPECT_TRUE(success); +} + +IN_PROC_BROWSER_TEST_F(LocalNTPVoiceJavascriptTest, ViewTests) { + content::WebContents* active_tab = local_ntp_test_utils::OpenNewTab( + browser(), GURL(chrome::kChromeUINewTabURL)); + + // Run the tests. + bool success = false; + ASSERT_TRUE(instant_test_utils::GetBoolFromJS( + active_tab, "!!runSimpleTests('view')", &success)); + EXPECT_TRUE(success); +}
diff --git a/chrome/browser/ui/search/local_ntp_one_google_bar_browsertest.cc b/chrome/browser/ui/search/local_ntp_one_google_bar_browsertest.cc index a94929c..cb1e182 100644 --- a/chrome/browser/ui/search/local_ntp_one_google_bar_browsertest.cc +++ b/chrome/browser/ui/search/local_ntp_one_google_bar_browsertest.cc
@@ -26,6 +26,7 @@ #include "content/public/browser/navigation_entry.h" #include "content/public/test/browser_test_utils.h" #include "testing/gtest/include/gtest/gtest.h" +#include "url/gurl.h" // A simple fake implementation of OneGoogleBarFetcher that immediately returns // a pre-configured OneGoogleBarData, which is null by default.
diff --git a/chrome/browser/ui/search/local_ntp_voice_search_browsertest.cc b/chrome/browser/ui/search/local_ntp_voice_search_browsertest.cc index 3ceff075..18f38c9f 100644 --- a/chrome/browser/ui/search/local_ntp_voice_search_browsertest.cc +++ b/chrome/browser/ui/search/local_ntp_voice_search_browsertest.cc
@@ -23,6 +23,7 @@ #include "content/public/browser/web_contents.h" #include "media/base/media_switches.h" #include "testing/gtest/include/gtest/gtest.h" +#include "url/gurl.h" class LocalNTPVoiceSearchSmokeTest : public InProcessBrowserTest { public:
diff --git a/chrome/browser/ui/search/search_ipc_router.cc b/chrome/browser/ui/search/search_ipc_router.cc index 2b66c0a..6e16501 100644 --- a/chrome/browser/ui/search/search_ipc_router.cc +++ b/chrome/browser/ui/search/search_ipc_router.cc
@@ -16,8 +16,8 @@ #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/web_contents.h" -#include "content/public/common/associated_interface_provider.h" #include "content/public/common/child_process_host.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" namespace {
diff --git a/chrome/browser/ui/signin_view_controller_delegate.h b/chrome/browser/ui/signin_view_controller_delegate.h index e50d79d..334a96b2 100644 --- a/chrome/browser/ui/signin_view_controller_delegate.h +++ b/chrome/browser/ui/signin_view_controller_delegate.h
@@ -106,8 +106,9 @@ bool CanGoBack(content::WebContents* web_ui_web_contents) const; SigninViewController* signin_view_controller_; // Not owned. - content::WebContents* web_contents_; // Not owned. - Browser* browser_; // Not owned. + content::WebContents* const web_contents_; // Not owned. + Browser* const browser_; // Not owned. + DISALLOW_COPY_AND_ASSIGN(SigninViewControllerDelegate); };
diff --git a/chrome/browser/ui/startup/startup_browser_creator.cc b/chrome/browser/ui/startup/startup_browser_creator.cc index 3aa1e05..2fae8c1 100644 --- a/chrome/browser/ui/startup/startup_browser_creator.cc +++ b/chrome/browser/ui/startup/startup_browser_creator.cc
@@ -20,6 +20,7 @@ #include "base/lazy_instance.h" #include "base/logging.h" #include "base/macros.h" +#include "base/metrics/histogram_base.h" #include "base/metrics/histogram_macros.h" #include "base/metrics/statistics_recorder.h" #include "base/strings/string16.h" @@ -55,6 +56,7 @@ #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/search_engines/util.h" +#include "components/startup_metric_utils/browser/startup_metric_utils.h" #include "components/url_formatter/url_fixer.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_security_policy.h" @@ -239,7 +241,8 @@ void DumpBrowserHistograms(const base::FilePath& output_file) { base::AssertBlockingAllowed(); - std::string output_string(base::StatisticsRecorder::ToJSON(std::string())); + std::string output_string( + base::StatisticsRecorder::ToJSON(base::JSON_VERBOSITY_LEVEL_FULL)); base::WriteFile(output_file, output_string.data(), static_cast<int>(output_string.size())); } @@ -248,8 +251,8 @@ // explicit user action. bool CanOpenProfileOnStartup(Profile* profile) { #if defined(OS_CHROMEOS) - // On ChromeOS, ther user has alrady chosen and logged into the profile - // before Chrome starts up. + // On ChromeOS, the user has already chosen and logged into the profile before + // Chrome starts up. return true; #else // Profiles that require signin are not available. @@ -557,9 +560,9 @@ TRACE_EVENT0("startup", "StartupBrowserCreator::ProcessCmdLineImpl"); DCHECK(last_used_profile); - if (process_startup) { - if (command_line.HasSwitch(switches::kDisablePromptOnRepost)) - content::NavigationController::DisablePromptOnRepost(); + if (process_startup && + command_line.HasSwitch(switches::kDisablePromptOnRepost)) { + content::NavigationController::DisablePromptOnRepost(); } bool silent_launch = false; @@ -662,8 +665,11 @@ silent_launch = true; // If we don't want to launch a new browser window or tab we are done here. - if (silent_launch) + if (silent_launch) { + if (process_startup) + startup_metric_utils::SetNonBrowserUIDisplayed(); return true; + } if (command_line.HasSwitch(extensions::switches::kLoadApps) && can_use_last_profile) {
diff --git a/chrome/browser/ui/startup/startup_browser_creator_corrupt_profiles_browsertest_win.cc b/chrome/browser/ui/startup/startup_browser_creator_corrupt_profiles_browsertest_win.cc index 171bc72e..bfffd91 100644 --- a/chrome/browser/ui/startup/startup_browser_creator_corrupt_profiles_browsertest_win.cc +++ b/chrome/browser/ui/startup/startup_browser_creator_corrupt_profiles_browsertest_win.cc
@@ -25,6 +25,7 @@ #include "chrome/common/chrome_switches.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/testing_browser_process.h" +#include "content/public/test/test_launcher.h" namespace { @@ -187,11 +188,8 @@ // If control goes here, it means SetUpUserDataDirectory is not handled. // This is okay for PRE_ tests, but not acceptable for main tests. - if (base::StartsWith( - testing::UnitTest::GetInstance()->current_test_info()->name(), - "PRE_", base::CompareCase::SENSITIVE)) { + if (content::IsPreTest()) return true; - } ADD_FAILURE() << "SetUpUserDataDirectory is not handled by the test."; return false;
diff --git a/chrome/browser/ui/sync/browser_synced_window_delegate.h b/chrome/browser/ui/sync/browser_synced_window_delegate.h index 71cdcef6d3e..a75a817 100644 --- a/chrome/browser/ui/sync/browser_synced_window_delegate.h +++ b/chrome/browser/ui/sync/browser_synced_window_delegate.h
@@ -38,7 +38,7 @@ bool ShouldSync() const override; private: - Browser* browser_; + Browser* const browser_; DISALLOW_COPY_AND_ASSIGN(BrowserSyncedWindowDelegate); };
diff --git a/chrome/browser/ui/sync/one_click_signin_links_delegate_impl.h b/chrome/browser/ui/sync/one_click_signin_links_delegate_impl.h index 9e910dc..a92b172642 100644 --- a/chrome/browser/ui/sync/one_click_signin_links_delegate_impl.h +++ b/chrome/browser/ui/sync/one_click_signin_links_delegate_impl.h
@@ -23,7 +23,7 @@ void OnAdvancedLinkClicked() override; // Browser in which the links should be opened. - Browser* browser_; + Browser* const browser_; DISALLOW_COPY_AND_ASSIGN(OneClickSigninLinksDelegateImpl); };
diff --git a/chrome/browser/ui/tab_contents/core_tab_helper.cc b/chrome/browser/ui/tab_contents/core_tab_helper.cc index 6c43b653..bf3be64d 100644 --- a/chrome/browser/ui/tab_contents/core_tab_helper.cc +++ b/chrome/browser/ui/tab_contents/core_tab_helper.cc
@@ -31,11 +31,11 @@ #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" -#include "content/public/common/associated_interface_provider.h" #include "content/public/common/content_switches.h" #include "content/public/common/context_menu_params.h" #include "net/base/load_states.h" #include "net/http/http_request_headers.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" #include "ui/base/l10n/l10n_util.h" #if !defined(OS_ANDROID)
diff --git a/chrome/browser/ui/toolbar/app_menu_model.h b/chrome/browser/ui/toolbar/app_menu_model.h index 47eb2f7..eb62c21 100644 --- a/chrome/browser/ui/toolbar/app_menu_model.h +++ b/chrome/browser/ui/toolbar/app_menu_model.h
@@ -224,7 +224,7 @@ ui::AcceleratorProvider* provider_; // weak - Browser* browser_; // weak + Browser* const browser_; // weak std::unique_ptr<content::HostZoomMap::Subscription> browser_zoom_subscription_;
diff --git a/chrome/browser/ui/toolbar/back_forward_menu_model.h b/chrome/browser/ui/toolbar/back_forward_menu_model.h index 183873e..ac8034c 100644 --- a/chrome/browser/ui/toolbar/back_forward_menu_model.h +++ b/chrome/browser/ui/toolbar/back_forward_menu_model.h
@@ -83,7 +83,7 @@ ui::MenuModelDelegate* GetMenuModelDelegate() const override; protected: - ui::MenuModelDelegate* menu_model_delegate() { return menu_model_delegate_; } + ui::MenuModelDelegate* menu_model_delegate() { return menu_model_delegate_; } private: friend class BackFwdMenuModelTest; @@ -187,7 +187,7 @@ // An index of -1 means no index. std::string BuildActionName(const std::string& name, int index) const; - Browser* browser_; + Browser* const browser_; // The unit tests will provide their own WebContents to use. content::WebContents* test_web_contents_;
diff --git a/chrome/browser/ui/toolbar/back_forward_menu_model_unittest.cc b/chrome/browser/ui/toolbar/back_forward_menu_model_unittest.cc index b5487b0..a7a0c90 100644 --- a/chrome/browser/ui/toolbar/back_forward_menu_model_unittest.cc +++ b/chrome/browser/ui/toolbar/back_forward_menu_model_unittest.cc
@@ -25,12 +25,14 @@ #include "content/public/browser/navigation_controller.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/web_contents.h" +#include "content/public/test/navigation_simulator.h" #include "content/public/test/web_contents_tester.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/codec/png_codec.h" using base::ASCIIToUTF16; +using content::NavigationSimulator; using content::WebContentsTester; namespace { @@ -95,16 +97,6 @@ controller().GoToIndex(index); WebContentsTester::For(web_contents())->CommitPendingNavigation(); } - - // Goes back/forward and commits the load. - void GoBack() { - controller().GoBack(); - WebContentsTester::For(web_contents())->CommitPendingNavigation(); - } - void GoForward() { - controller().GoForward(); - WebContentsTester::For(web_contents())->CommitPendingNavigation(); - } }; TEST_F(BackFwdMenuModelTest, BasicCase) { @@ -361,18 +353,18 @@ back_model->GetLabelAt(index + 2)); // If we go back two we should still see the same chapter stop at the end. - GoBack(); + NavigationSimulator::GoBack(web_contents()); EXPECT_EQ(ASCIIToUTF16("B3"), back_model->GetLabelAt(index)); - GoBack(); + NavigationSimulator::GoBack(web_contents()); EXPECT_EQ(ASCIIToUTF16("B3"), back_model->GetLabelAt(index)); // But if we go back again, it should change. - GoBack(); + NavigationSimulator::GoBack(web_contents()); EXPECT_EQ(ASCIIToUTF16("A3"), back_model->GetLabelAt(index)); - GoBack(); + NavigationSimulator::GoBack(web_contents()); EXPECT_EQ(ASCIIToUTF16("A3"), back_model->GetLabelAt(index)); - GoBack(); + NavigationSimulator::GoBack(web_contents()); EXPECT_EQ(ASCIIToUTF16("A3"), back_model->GetLabelAt(index)); - GoBack(); + NavigationSimulator::GoBack(web_contents()); // It is now a separator. EXPECT_EQ(base::string16(), back_model->GetLabelAt(index)); // Undo our position change. @@ -382,12 +374,12 @@ NavigateToOffset(-BackForwardMenuModel::kMaxHistoryItems); ValidateModel(forward_model.get(), BackForwardMenuModel::kMaxHistoryItems, 0); // Go forward (still no chapter stop) - GoForward(); + NavigationSimulator::GoForward(web_contents()); ValidateModel(forward_model.get(), BackForwardMenuModel::kMaxHistoryItems - 1, 0); // Go back two (one chapter stop should show up) - GoBack(); - GoBack(); + NavigationSimulator::GoBack(web_contents()); + NavigationSimulator::GoBack(web_contents()); ValidateModel(forward_model.get(), BackForwardMenuModel::kMaxHistoryItems, 1); @@ -410,16 +402,16 @@ forward_model->GetLabelAt(index + 2)); // If we advance one we should still see the same chapter stop at the end. - GoForward(); + NavigationSimulator::GoForward(web_contents()); EXPECT_EQ(ASCIIToUTF16("I3"), forward_model->GetLabelAt(index)); // But if we advance one again, it should change. - GoForward(); + NavigationSimulator::GoForward(web_contents()); EXPECT_EQ(ASCIIToUTF16("J3"), forward_model->GetLabelAt(index)); - GoForward(); + NavigationSimulator::GoForward(web_contents()); EXPECT_EQ(ASCIIToUTF16("J3"), forward_model->GetLabelAt(index)); - GoForward(); + NavigationSimulator::GoForward(web_contents()); EXPECT_EQ(ASCIIToUTF16("J3"), forward_model->GetLabelAt(index)); - GoForward(); + NavigationSimulator::GoForward(web_contents()); EXPECT_EQ(ASCIIToUTF16("K3"), forward_model->GetLabelAt(index)); // Now test the boundary cases by using the chapter stop function directly.
diff --git a/chrome/browser/ui/toolbar/recent_tabs_sub_menu_model.h b/chrome/browser/ui/toolbar/recent_tabs_sub_menu_model.h index 7d21280..df9a202 100644 --- a/chrome/browser/ui/toolbar/recent_tabs_sub_menu_model.h +++ b/chrome/browser/ui/toolbar/recent_tabs_sub_menu_model.h
@@ -153,7 +153,7 @@ void OnSyncConfigurationCompleted(syncer::SyncService* sync) override; void OnForeignSessionUpdated(syncer::SyncService* sync) override; - Browser* browser_; // Weak. + Browser* const browser_; // Weak. sync_sessions::OpenTabsUIDelegate* open_tabs_delegate_; // Weak.
diff --git a/chrome/browser/ui/toolbar/toolbar_actions_bar.h b/chrome/browser/ui/toolbar/toolbar_actions_bar.h index d6f581e..7c9f7e9 100644 --- a/chrome/browser/ui/toolbar/toolbar_actions_bar.h +++ b/chrome/browser/ui/toolbar/toolbar_actions_bar.h
@@ -293,7 +293,7 @@ ToolbarActionsBarDelegate* delegate_; // The associated browser. - Browser* browser_; + Browser* const browser_; // The observed toolbar model. ToolbarActionsModel* model_;
diff --git a/chrome/browser/ui/translate/translate_bubble_test_utils.h b/chrome/browser/ui/translate/translate_bubble_test_utils.h index 7b06c51..e7a0c9a 100644 --- a/chrome/browser/ui/translate/translate_bubble_test_utils.h +++ b/chrome/browser/ui/translate/translate_bubble_test_utils.h
@@ -5,6 +5,8 @@ #ifndef CHROME_BROWSER_UI_TRANSLATE_TRANSLATE_BUBBLE_TEST_UTILS_H_ #define CHROME_BROWSER_UI_TRANSLATE_TRANSLATE_BUBBLE_TEST_UTILS_H_ +#include "base/strings/string16.h" + class TranslateBubbleModel; class Browser; @@ -23,6 +25,11 @@ // Presses 'Revert' on the currently opened translate bubble. void PressRevert(Browser* browser); +// Selects the target language with the given display name on the opened +// translate bubble. +void SelectTargetLanguageByDisplayName(Browser* browser, + const base::string16& display_name); + } // namespace test_utils } // namespace translate
diff --git a/chrome/browser/ui/unload_controller.h b/chrome/browser/ui/unload_controller.h index d14fe7a..0c437c6 100644 --- a/chrome/browser/ui/unload_controller.h +++ b/chrome/browser/ui/unload_controller.h
@@ -133,7 +133,7 @@ return !on_close_confirmed_.is_null(); } - Browser* browser_; + Browser* const browser_; content::NotificationRegistrar registrar_;
diff --git a/chrome/browser/ui/views/autofill/save_card_icon_view.h b/chrome/browser/ui/views/autofill/save_card_icon_view.h index 7416e17f..52001230 100644 --- a/chrome/browser/ui/views/autofill/save_card_icon_view.h +++ b/chrome/browser/ui/views/autofill/save_card_icon_view.h
@@ -20,7 +20,7 @@ // it. class SaveCardIconView : public BubbleIconView { public: - explicit SaveCardIconView(CommandUpdater* command_updater, Browser* browser); + SaveCardIconView(CommandUpdater* command_updater, Browser* browser); ~SaveCardIconView() override; protected: @@ -33,7 +33,7 @@ SaveCardBubbleControllerImpl* GetController() const; // May be nullptr. - Browser* browser_; + Browser* const browser_; DISALLOW_COPY_AND_ASSIGN(SaveCardIconView); };
diff --git a/chrome/browser/ui/views/bookmarks/bookmark_bar_view.h b/chrome/browser/ui/views/bookmarks/bookmark_bar_view.h index 1a7b7b8..4716dc9 100644 --- a/chrome/browser/ui/views/bookmarks/bookmark_bar_view.h +++ b/chrome/browser/ui/views/bookmarks/bookmark_bar_view.h
@@ -434,7 +434,7 @@ ButtonSeparatorView* bookmarks_separator_view_; - Browser* browser_; + Browser* const browser_; BrowserView* browser_view_; // True if the owning browser is showing an infobar.
diff --git a/chrome/browser/ui/views/bookmarks/bookmark_menu_delegate.h b/chrome/browser/ui/views/bookmarks/bookmark_menu_delegate.h index b0f83b6..d82cbf0 100644 --- a/chrome/browser/ui/views/bookmarks/bookmark_menu_delegate.h +++ b/chrome/browser/ui/views/bookmarks/bookmark_menu_delegate.h
@@ -182,7 +182,7 @@ void AddMenuToMaps(views::MenuItemView* menu, const bookmarks::BookmarkNode* node); - Browser* browser_; + Browser* const browser_; Profile* profile_; content::PageNavigator* page_navigator_;
diff --git a/chrome/browser/ui/views/collected_cookies_views.cc b/chrome/browser/ui/views/collected_cookies_views.cc index 33b98d8c..db162186 100644 --- a/chrome/browser/ui/views/collected_cookies_views.cc +++ b/chrome/browser/ui/views/collected_cookies_views.cc
@@ -84,41 +84,67 @@ layout->StartRow(0, column_layout_id); } +base::string16 GetAnnotationTextForSetting(ContentSetting setting) { + switch (setting) { + case CONTENT_SETTING_BLOCK: + return l10n_util::GetStringUTF16(IDS_COLLECTED_COOKIES_BLOCKED_AUX_TEXT); + case CONTENT_SETTING_ALLOW: + return l10n_util::GetStringUTF16(IDS_COLLECTED_COOKIES_ALLOWED_AUX_TEXT); + case CONTENT_SETTING_SESSION_ONLY: + return l10n_util::GetStringUTF16( + IDS_COLLECTED_COOKIES_CLEAR_ON_EXIT_AUX_TEXT); + default: + NOTREACHED() << "Unknown ContentSetting value: " << setting; + return base::string16(); + } +} + } // namespace -// This DrawingProvider keeps track of a set of ui::TreeModelNode*s which are -// considered "invalidated", and marks them as such by lightening their text -// color and adding auxiliary text to them. +// This DrawingProvider allows TreeModelNodes to be annotated with auxiliary +// text. Annotated nodes will be drawn in a lighter color than normal to +// indicate that their state has changed, and will have their auxiliary text +// drawn on the trailing end of their row. class CookiesTreeViewDrawingProvider : public views::TreeViewDrawingProvider { public: CookiesTreeViewDrawingProvider() {} ~CookiesTreeViewDrawingProvider() override {} - void MarkNodeAsInvalidated(ui::TreeModelNode* node); + void AnnotateNode(ui::TreeModelNode* node, const base::string16& text); SkColor GetTextColorForNode(views::TreeView* tree_view, ui::TreeModelNode* node) override; + base::string16 GetAuxiliaryTextForNode(views::TreeView* tree_view, + ui::TreeModelNode* node) override; bool ShouldDrawIconForNode(views::TreeView* tree_view, ui::TreeModelNode* node) override; private: - std::set<ui::TreeModelNode*> invalidated_nodes_; + std::map<ui::TreeModelNode*, base::string16> annotations_; }; -void CookiesTreeViewDrawingProvider::MarkNodeAsInvalidated( - ui::TreeModelNode* node) { - invalidated_nodes_.insert(node); +void CookiesTreeViewDrawingProvider::AnnotateNode(ui::TreeModelNode* node, + const base::string16& text) { + annotations_[node] = text; } SkColor CookiesTreeViewDrawingProvider::GetTextColorForNode( views::TreeView* tree_view, ui::TreeModelNode* node) { SkColor color = TreeViewDrawingProvider::GetTextColorForNode(tree_view, node); - if (invalidated_nodes_.find(node) != invalidated_nodes_.end()) + if (annotations_.find(node) != annotations_.end()) color = SkColorSetA(color, 0x80); return color; } +base::string16 CookiesTreeViewDrawingProvider::GetAuxiliaryTextForNode( + views::TreeView* tree_view, + ui::TreeModelNode* node) { + if (annotations_.find(node) != annotations_.end()) + return annotations_[node]; + return TreeViewDrawingProvider::GetAuxiliaryTextForNode(tree_view, node); +} + bool CookiesTreeViewDrawingProvider::ShouldDrawIconForNode( views::TreeView* tree_view, ui::TreeModelNode* node) { @@ -650,7 +676,8 @@ CookiesTreeViewDrawingProvider* provider = (tree_view == allowed_cookies_tree_) ? allowed_cookies_drawing_provider_ : blocked_cookies_drawing_provider_; - provider->MarkNodeAsInvalidated(tree_view->GetSelectedNode()); + provider->AnnotateNode(tree_view->GetSelectedNode(), + GetAnnotationTextForSetting(setting)); tree_view->SchedulePaint(); }
diff --git a/chrome/browser/ui/views/conflicting_module_view_win.h b/chrome/browser/ui/views/conflicting_module_view_win.h index fbe7055..c6f74413 100644 --- a/chrome/browser/ui/views/conflicting_module_view_win.h +++ b/chrome/browser/ui/views/conflicting_module_view_win.h
@@ -42,7 +42,7 @@ // EnumerateModulesModel::Observer: void OnConflictsAcknowledged() override; - Browser* browser_; + Browser* const browser_; ScopedObserver<EnumerateModulesModel, EnumerateModulesModel::Observer> observer_;
diff --git a/chrome/browser/ui/views/download/download_shelf_view.h b/chrome/browser/ui/views/download/download_shelf_view.h index 5b557e1..ddf74ec2 100644 --- a/chrome/browser/ui/views/download/download_shelf_view.h +++ b/chrome/browser/ui/views/download/download_shelf_view.h
@@ -132,7 +132,7 @@ SkColor GetTextColorForIconMd(); // The browser for this shelf. - Browser* browser_; + Browser* const browser_; // The animation for adding new items to the shelf. gfx::SlideAnimation new_item_animation_;
diff --git a/chrome/browser/ui/views/extensions/extension_view_views.h b/chrome/browser/ui/views/extensions/extension_view_views.h index e5fd9c11..be3280b2 100644 --- a/chrome/browser/ui/views/extensions/extension_view_views.h +++ b/chrome/browser/ui/views/extensions/extension_view_views.h
@@ -72,7 +72,7 @@ extensions::ExtensionHost* host_; // The browser window that this view is in. - Browser* browser_; + Browser* const browser_; // What we should set the preferred width to once the ExtensionViewViews has // loaded.
diff --git a/chrome/browser/ui/views/first_run_bubble.h b/chrome/browser/ui/views/first_run_bubble.h index d700133..9430ea8 100644 --- a/chrome/browser/ui/views/first_run_bubble.h +++ b/chrome/browser/ui/views/first_run_bubble.h
@@ -69,7 +69,7 @@ // views::LinkListener overrides: void LinkClicked(views::Link* source, int event_flags) override; - Browser* browser_; + Browser* const browser_; FirstRunBubbleCloser bubble_closer_; DISALLOW_COPY_AND_ASSIGN(FirstRunBubble);
diff --git a/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash.cc b/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash.cc index 78cf820..541212aa 100644 --- a/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash.cc +++ b/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash.cc
@@ -244,6 +244,8 @@ void BrowserNonClientFrameViewAsh::ResetWindowControls() { caption_button_container_->SetVisible(true); caption_button_container_->ResetWindowControls(); + if (hosted_app_button_container_) + hosted_app_button_container_->RefreshContentSettingViews(); } void BrowserNonClientFrameViewAsh::UpdateWindowIcon() { @@ -512,12 +514,13 @@ caption_button_container_, back_button_); // Add the container for extra hosted app buttons (e.g app menu button). - SkColor text_color = default_frame_header->GetTitleColor(); + SkColor button_color = ash::FrameCaptionButton::GetButtonColor( + default_frame_header->ShouldUseLightImages()); hosted_app_button_container_ = new HostedAppButtonContainer( - browser_view(), text_color, - SkColorSetA(text_color, 255 * ash::kInactiveFrameButtonIconAlphaRatio)); + browser_view(), button_color, + SkColorSetA(button_color, + 255 * ash::kInactiveFrameButtonIconAlphaRatio)); caption_button_container_->AddChildViewAt(hosted_app_button_container_, 0); - } else { default_frame_header = std::make_unique<ash::DefaultFrameHeader>( frame(), this, caption_button_container_, back_button_);
diff --git a/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash_browsertest.cc b/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash_browsertest.cc index 069f2bb..29f405d 100644 --- a/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash_browsertest.cc +++ b/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash_browsertest.cc
@@ -43,7 +43,10 @@ #include "chrome/common/chrome_features.h" #include "chrome/common/web_application_info.h" #include "chrome/test/base/in_process_browser_test.h" +#include "chrome/test/base/ui_test_utils.h" #include "components/signin/core/account_id/account_id.h" +#include "content/public/browser/render_frame_host.h" +#include "content/public/browser/render_process_host.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/test/env_test_helper.h" #include "ui/base/hit_test.h" @@ -463,15 +466,20 @@ // Creates a browser for a bookmark app and verifies the window frame is // correct. IN_PROC_BROWSER_TEST_F(HostedAppNonClientFrameViewAshTest, HostedAppFrame) { + const GURL kAppStartURL("http://example.org/"); + base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitAndEnableFeature(features::kDesktopPWAWindowing); WebApplicationInfo web_app_info; - web_app_info.app_url = GURL("http://example.org/"); + web_app_info.app_url = kAppStartURL; web_app_info.theme_color = SK_ColorBLUE; const extensions::Extension* app = InstallBookmarkApp(web_app_info); Browser* app_browser = LaunchAppBrowser(app); + chrome::NavigateParams params(app_browser, kAppStartURL, + ui::PAGE_TRANSITION_LINK); + ui_test_utils::NavigateToURL(¶ms); BrowserView* browser_view = BrowserView::GetBrowserViewForBrowser(app_browser); @@ -500,6 +508,26 @@ menu_button->OnMousePressed(e); EXPECT_TRUE(menu_button->menu()->IsShowing()); + // Show a content setting icon. + const auto& content_setting_views = + frame_view->hosted_app_button_container_->content_setting_views_; + + for (auto* v : content_setting_views) + EXPECT_FALSE(v->visible()); + + content::RenderFrameHost* frame = + app_browser->tab_strip_model()->GetActiveWebContents()->GetMainFrame(); + TabSpecificContentSettings* content_settings = + TabSpecificContentSettings::GetForFrame(frame->GetProcess()->GetID(), + frame->GetRoutingID()); + + content_settings->OnGeolocationPermissionSet(kAppStartURL.GetOrigin(), true); + + int visible = std::count_if( + content_setting_views.begin(), content_setting_views.end(), + [](const ContentSettingImageView* v) { return v->visible(); }); + EXPECT_EQ(1, visible); + // The app and domain should render next to the window title. frame_header->LayoutRenderTexts(gfx::Rect(300, 30), 100, 100); EXPECT_EQ(gfx::Rect(100, 30),
diff --git a/chrome/browser/ui/views/frame/global_menu_bar_x11.h b/chrome/browser/ui/views/frame/global_menu_bar_x11.h index 5c32c279..f96bedf 100644 --- a/chrome/browser/ui/views/frame/global_menu_bar_x11.h +++ b/chrome/browser/ui/views/frame/global_menu_bar_x11.h
@@ -158,7 +158,7 @@ CHROMEG_CALLBACK_1(GlobalMenuBarX11, void, OnCreateProfileItemActivated, DbusmenuMenuitem*, unsigned int); - Browser* browser_; + Browser* const browser_; Profile* profile_; BrowserView* browser_view_; BrowserDesktopWindowTreeHostX11* host_;
diff --git a/chrome/browser/ui/views/frame/hosted_app_button_container.cc b/chrome/browser/ui/views/frame/hosted_app_button_container.cc index b6a6a15..ea274d3 100644 --- a/chrome/browser/ui/views/frame/hosted_app_button_container.cc +++ b/chrome/browser/ui/views/frame/hosted_app_button_container.cc
@@ -5,14 +5,25 @@ #include "chrome/browser/ui/views/frame/hosted_app_button_container.h" #include "chrome/app/vector_icons/vector_icons.h" +#include "chrome/browser/ui/browser_content_setting_bubble_model_delegate.h" +#include "chrome/browser/ui/content_settings/content_setting_image_model.h" #include "chrome/browser/ui/extensions/hosted_app_menu_model.h" #include "chrome/browser/ui/views/frame/browser_view.h" +#include "chrome/browser/ui/views/location_bar/content_setting_image_view.h" #include "chrome/browser/ui/views/toolbar/app_menu.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/color_palette.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/paint_vector_icon.h" #include "ui/views/layout/box_layout.h" +#include "ui/views/widget/native_widget_aura.h" + +namespace { + +// Padding around content setting icons. +constexpr int kContentSettingIconInteriorPadding = 4; + +} // namespace HostedAppButtonContainer::AppMenuButton::AppMenuButton( BrowserView* browser_view) @@ -49,19 +60,57 @@ active_icon_color_(active_icon_color), inactive_icon_color_(inactive_icon_color), app_menu_button_(new AppMenuButton(browser_view)) { + DCHECK(browser_view_); auto layout = std::make_unique<views::BoxLayout>(views::BoxLayout::kHorizontal); layout->set_cross_axis_alignment( views::BoxLayout::CROSS_AXIS_ALIGNMENT_CENTER); SetLayoutManager(layout.release()); + std::vector<std::unique_ptr<ContentSettingImageModel>> models = + ContentSettingImageModel::GenerateContentSettingImageModels(); + for (auto& model : models) { + auto image_view = std::make_unique<ContentSettingImageView>( + std::move(model), this, + views::NativeWidgetAura::GetWindowTitleFontList()); + image_view->SetIconColor(active_icon_color); + image_view->set_next_element_interior_padding( + kContentSettingIconInteriorPadding); + image_view->SetVisible(false); + image_view->disable_animation(); + content_setting_views_.push_back(image_view.get()); + AddChildView(image_view.release()); + } + app_menu_button_->SetIconColor(active_icon_color); AddChildView(app_menu_button_); } HostedAppButtonContainer::~HostedAppButtonContainer() {} +content::WebContents* HostedAppButtonContainer::GetContentSettingWebContents() { + return browser_view_->GetActiveWebContents(); +} + +ContentSettingBubbleModelDelegate* +HostedAppButtonContainer::GetContentSettingBubbleModelDelegate() { + return browser_view_->browser()->content_setting_bubble_model_delegate(); +} + +void HostedAppButtonContainer::RefreshContentSettingViews() { + for (auto* v : content_setting_views_) + v->Update(); +} + +void HostedAppButtonContainer::ChildVisibilityChanged(views::View* child) { + // Changes to layout need to be taken into account by the frame view. + browser_view_->frame()->GetFrameView()->Layout(); +} + void HostedAppButtonContainer::SetPaintAsActive(bool active) { + for (auto* v : content_setting_views_) + v->SetIconColor(active ? active_icon_color_ : inactive_icon_color_); + app_menu_button_->SetIconColor(active ? active_icon_color_ : inactive_icon_color_); }
diff --git a/chrome/browser/ui/views/frame/hosted_app_button_container.h b/chrome/browser/ui/views/frame/hosted_app_button_container.h index 1dfd0643..99fac99 100644 --- a/chrome/browser/ui/views/frame/hosted_app_button_container.h +++ b/chrome/browser/ui/views/frame/hosted_app_button_container.h
@@ -8,6 +8,7 @@ #include <memory> #include "base/macros.h" +#include "chrome/browser/ui/views/location_bar/content_setting_image_view.h" #include "ui/views/controls/button/menu_button.h" #include "ui/views/controls/button/menu_button_listener.h" #include "ui/views/view.h" @@ -17,7 +18,8 @@ class BrowserView; // A container for hosted app buttons in the title bar. -class HostedAppButtonContainer : public views::View { +class HostedAppButtonContainer : public views::View, + public ContentSettingImageView::Delegate { public: // |active_icon_color| and |inactive_icon_color| indicate the colors to use // for button icons when the window is focused and blurred respectively. @@ -26,6 +28,9 @@ SkColor inactive_icon_color); ~HostedAppButtonContainer() override; + // Updates the visibility of each content setting view. + void RefreshContentSettingViews(); + // Sets the container to paints its buttons the active/inactive color. void SetPaintAsActive(bool active); @@ -62,6 +67,14 @@ DISALLOW_COPY_AND_ASSIGN(AppMenuButton); }; + // ContentSettingsImageView::Delegate: + content::WebContents* GetContentSettingWebContents() override; + ContentSettingBubbleModelDelegate* GetContentSettingBubbleModelDelegate() + override; + + // views::View: + void ChildVisibilityChanged(views::View* child) override; + // The containing browser view. BrowserView* browser_view_; @@ -71,6 +84,7 @@ // Owned by the views hierarchy. AppMenuButton* app_menu_button_; + std::vector<ContentSettingImageView*> content_setting_views_; DISALLOW_COPY_AND_ASSIGN(HostedAppButtonContainer); };
diff --git a/chrome/browser/ui/views/frame/hosted_app_frame_header_ash.cc b/chrome/browser/ui/views/frame/hosted_app_frame_header_ash.cc index 537ca3e..0b302a5a 100644 --- a/chrome/browser/ui/views/frame/hosted_app_frame_header_ash.cc +++ b/chrome/browser/ui/views/frame/hosted_app_frame_header_ash.cc
@@ -11,6 +11,7 @@ #include "ui/gfx/canvas.h" #include "ui/gfx/render_text.h" #include "ui/views/view.h" +#include "ui/views/widget/native_widget_aura.h" HostedAppFrameHeaderAsh::HostedAppFrameHeaderAsh( extensions::HostedAppBrowserController* app_controller, @@ -46,7 +47,7 @@ std::unique_ptr<gfx::RenderText> HostedAppFrameHeaderAsh::CreateRenderText() { std::unique_ptr<gfx::RenderText> render_text( gfx::RenderText::CreateInstance()); - render_text->SetFontList(GetTitleFontList()); + render_text->SetFontList(views::NativeWidgetAura::GetWindowTitleFontList()); render_text->SetCursorEnabled(false); render_text->SetColor(GetTitleColor()); render_text->SetElideBehavior(gfx::FADE_TAIL);
diff --git a/chrome/browser/ui/views/frame/system_menu_model_delegate.h b/chrome/browser/ui/views/frame/system_menu_model_delegate.h index d695bdb7b..060a6f51 100644 --- a/chrome/browser/ui/views/frame/system_menu_model_delegate.h +++ b/chrome/browser/ui/views/frame/system_menu_model_delegate.h
@@ -31,8 +31,8 @@ void ExecuteCommand(int command_id, int event_flags) override; private: - ui::AcceleratorProvider* provider_; // weak - Browser* browser_; // weak + ui::AcceleratorProvider* const provider_; // weak + Browser* const browser_; // weak DISALLOW_COPY_AND_ASSIGN(SystemMenuModelDelegate); };
diff --git a/chrome/browser/ui/views/global_error_bubble_view.h b/chrome/browser/ui/views/global_error_bubble_view.h index 4071e909..7a638cc 100644 --- a/chrome/browser/ui/views/global_error_bubble_view.h +++ b/chrome/browser/ui/views/global_error_bubble_view.h
@@ -46,7 +46,7 @@ void CloseBubbleView() override; private: - Browser* browser_; + Browser* const browser_; base::WeakPtr<GlobalErrorWithStandardBubble> error_; std::unique_ptr<ElevationIconSetter> elevation_icon_setter_;
diff --git a/chrome/browser/ui/views/ime/ime_warning_bubble_view.h b/chrome/browser/ui/views/ime/ime_warning_bubble_view.h index 5272c2f..c2cfa1b 100644 --- a/chrome/browser/ui/views/ime/ime_warning_bubble_view.h +++ b/chrome/browser/ui/views/ime/ime_warning_bubble_view.h
@@ -74,7 +74,7 @@ // Saves the Browser instance of the browser view, which will be used in // OnBrowserRemoved(), as browser_view_->browser() may be null when // OnBrowserRemoved() is called. - Browser* browser_; + Browser* const browser_; // True if bubble anchors to the action of the extension. bool anchor_to_action_;
diff --git a/chrome/browser/ui/views/location_bar/content_setting_image_view.cc b/chrome/browser/ui/views/location_bar/content_setting_image_view.cc index d5fde203..a259b58 100644 --- a/chrome/browser/ui/views/location_bar/content_setting_image_view.cc +++ b/chrome/browser/ui/views/location_bar/content_setting_image_view.cc
@@ -5,11 +5,11 @@ #include "chrome/browser/ui/views/location_bar/content_setting_image_view.h" #include "base/strings/utf_string_conversions.h" +#include "chrome/browser/profiles/profile.h" #include "chrome/browser/themes/theme_properties.h" #include "chrome/browser/ui/content_settings/content_setting_bubble_model.h" #include "chrome/browser/ui/content_settings/content_setting_image_model.h" #include "chrome/browser/ui/views/content_setting_bubble_contents.h" -#include "chrome/browser/ui/views/location_bar/location_bar_view.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/material_design/material_design_controller.h" #include "ui/base/theme_provider.h" @@ -33,16 +33,16 @@ ContentSettingImageView::ContentSettingImageView( std::unique_ptr<ContentSettingImageModel> image_model, - LocationBarView* parent, + Delegate* delegate, const gfx::FontList& font_list) : IconLabelBubbleView(font_list), - parent_(parent), + delegate_(delegate), content_setting_image_model_(std::move(image_model)), slide_animator_(this), pause_animation_(false), pause_animation_state_(0.0), bubble_view_(nullptr) { - set_next_element_interior_padding(LocationBarView::kIconInteriorPadding); + DCHECK(delegate_); SetInkDropMode(InkDropMode::ON); SetFocusBehavior(FocusBehavior::ACCESSIBLE_ONLY); image()->EnableCanvasFlippingForRTLUI(true); @@ -58,7 +58,9 @@ bubble_view_->GetWidget()->RemoveObserver(this); } -void ContentSettingImageView::Update(content::WebContents* web_contents) { +void ContentSettingImageView::Update() { + content::WebContents* web_contents = + delegate_->GetContentSettingWebContents(); // Note: We explicitly want to call this even if |web_contents| is NULL, so we // get hidden properly while the user is editing the omnibox. content_setting_image_model_->UpdateFromWebContents(web_contents); @@ -73,8 +75,10 @@ // If the content usage or blockage should be indicated to the user, start the // animation and record that the icon has been shown. - if (!content_setting_image_model_->ShouldRunAnimation(web_contents)) + if (!can_animate_ || + !content_setting_image_model_->ShouldRunAnimation(web_contents)) { return; + } // We just ignore this blockage if we're already showing some other string to // the user. If this becomes a problem, we could design some sort of queueing @@ -90,6 +94,12 @@ content_setting_image_model_->SetAnimationHasRun(web_contents); } +void ContentSettingImageView::SetIconColor(SkColor color) { + icon_color_ = color; + if (content_setting_image_model_->is_visible()) + UpdateImage(); +} + const char* ContentSettingImageView::GetClassName() const { return "ContentSettingsImageView"; } @@ -164,16 +174,17 @@ slide_animator_.Reset(); } - content::WebContents* web_contents = parent_->GetWebContents(); + content::WebContents* web_contents = + delegate_->GetContentSettingWebContents(); if (web_contents && !bubble_view_) { views::View* anchor = this; if (ui::MaterialDesignController::IsSecondaryUiMaterial()) - anchor = parent_; + anchor = parent(); bubble_view_ = new ContentSettingBubbleContents( - content_setting_image_model_->CreateBubbleModel( - parent_->delegate()->GetContentSettingBubbleModelDelegate(), - web_contents, parent_->profile()), - web_contents, anchor, views::BubbleBorder::TOP_RIGHT); + content_setting_image_model_->CreateBubbleModel( + delegate_->GetContentSettingBubbleModelDelegate(), web_contents, + Profile::FromBrowserContext(web_contents->GetBrowserContext())), + web_contents, anchor, views::BubbleBorder::TOP_RIGHT); views::Widget* bubble_widget = views::BubbleDialogDelegateView::CreateBubble(bubble_view_); bubble_widget->AddObserver(this); @@ -197,12 +208,17 @@ return bubble_view_ != nullptr; } +SkColor ContentSettingImageView::GetInkDropBaseColor() const { + return icon_color_ ? icon_color_.value() + : IconLabelBubbleView::GetInkDropBaseColor(); +} + void ContentSettingImageView::AnimationEnded(const gfx::Animation* animation) { slide_animator_.Reset(); if (!pause_animation_) { label()->SetVisible(false); - parent_->Layout(); - parent_->SchedulePaint(); + parent()->Layout(); + parent()->SchedulePaint(); } GetInkDrop()->SetShowHighlightOnHover(true); @@ -212,8 +228,8 @@ void ContentSettingImageView::AnimationProgressed( const gfx::Animation* animation) { if (!pause_animation_) { - parent_->Layout(); - parent_->SchedulePaint(); + parent()->Layout(); + parent()->SchedulePaint(); } } @@ -243,7 +259,11 @@ } void ContentSettingImageView::UpdateImage() { - SetImage(content_setting_image_model_->GetIcon(GetTextColor()).AsImageSkia()); + SetImage(content_setting_image_model_ + ->GetIcon(icon_color_ ? icon_color_.value() + : color_utils::DeriveDefaultIconColor( + GetTextColor())) + .AsImageSkia()); } void ContentSettingImageView::AnimateIn() {
diff --git a/chrome/browser/ui/views/location_bar/content_setting_image_view.h b/chrome/browser/ui/views/location_bar/content_setting_image_view.h index 495c3fb..bf5547a 100644 --- a/chrome/browser/ui/views/location_bar/content_setting_image_view.h +++ b/chrome/browser/ui/views/location_bar/content_setting_image_view.h
@@ -17,7 +17,6 @@ #include "ui/views/view.h" class ContentSettingImageModel; -class LocationBarView; namespace content { class WebContents; @@ -36,13 +35,32 @@ // blocking, geolocation). class ContentSettingImageView : public IconLabelBubbleView { public: + class Delegate { + public: + // Gets the web contents the ContentSettingImageView is for. + virtual content::WebContents* GetContentSettingWebContents() = 0; + + // Gets the ContentSettingBubbleModelDelegate for this + // ContentSettingImageView. + virtual ContentSettingBubbleModelDelegate* + GetContentSettingBubbleModelDelegate() = 0; + + protected: + virtual ~Delegate() {} + }; + ContentSettingImageView(std::unique_ptr<ContentSettingImageModel> image_model, - LocationBarView* parent, + Delegate* delegate, const gfx::FontList& font_list); ~ContentSettingImageView() override; // Updates the decoration from the shown WebContents. - void Update(content::WebContents* web_contents); + void Update(); + + // Set the color of the button icon. Based on the text color by default. + void SetIconColor(SkColor color); + + void disable_animation() { can_animate_ = false; } private: // The total animation time, including open and close as well as an @@ -55,6 +73,7 @@ bool GetTooltipText(const gfx::Point& p, base::string16* tooltip) const override; void OnNativeThemeChanged(const ui::NativeTheme* native_theme) override; + SkColor GetInkDropBaseColor() const override; SkColor GetTextColor() const override; bool ShouldShowLabel() const override; double WidthMultiplier() const override; @@ -80,12 +99,15 @@ // animation is running. void AnimateIn(); - LocationBarView* parent_; // Weak, owns us. + Delegate* delegate_; // Weak. std::unique_ptr<ContentSettingImageModel> content_setting_image_model_; gfx::SlideAnimation slide_animator_; bool pause_animation_; double pause_animation_state_; views::BubbleDialogDelegateView* bubble_view_; + base::Optional<SkColor> icon_color_; + + bool can_animate_ = true; DISALLOW_COPY_AND_ASSIGN(ContentSettingImageView); };
diff --git a/chrome/browser/ui/views/location_bar/icon_label_bubble_view.h b/chrome/browser/ui/views/location_bar/icon_label_bubble_view.h index b1cba5e..fe9f893 100644 --- a/chrome/browser/ui/views/location_bar/icon_label_bubble_view.h +++ b/chrome/browser/ui/views/location_bar/icon_label_bubble_view.h
@@ -81,6 +81,10 @@ // Exposed for testing. SeparatorView* separator_view() const { return separator_view_; } + void set_next_element_interior_padding(int padding) { + next_element_interior_padding_ = padding; + } + protected: static constexpr int kOpenTimeMS = 150; @@ -92,10 +96,6 @@ return ink_drop_container_; } - void set_next_element_interior_padding(int padding) { - next_element_interior_padding_ = padding; - } - // Gets the color for displaying text. virtual SkColor GetTextColor() const = 0;
diff --git a/chrome/browser/ui/views/location_bar/location_bar_view.cc b/chrome/browser/ui/views/location_bar/location_bar_view.cc index e0ccf6f9..75c69a7 100644 --- a/chrome/browser/ui/views/location_bar/location_bar_view.cc +++ b/chrome/browser/ui/views/location_bar/location_bar_view.cc
@@ -30,6 +30,7 @@ #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/content_settings/content_setting_bubble_model.h" +#include "chrome/browser/ui/extensions/hosted_app_browser_controller.h" #include "chrome/browser/ui/find_bar/find_bar.h" #include "chrome/browser/ui/find_bar/find_bar_controller.h" #include "chrome/browser/ui/layout_constants.h" @@ -224,6 +225,7 @@ ContentSettingImageView* image_view = new ContentSettingImageView(std::move(model), this, font_list); content_setting_views_.push_back(image_view); + image_view->set_next_element_interior_padding(kIconInteriorPadding); image_view->SetVisible(false); AddChildView(image_view); } @@ -656,6 +658,18 @@ } //////////////////////////////////////////////////////////////////////////////// +// LocationBarView, public ContentSettingImageView::Delegate implementation: + +content::WebContents* LocationBarView::GetContentSettingWebContents() { + return GetToolbarModel()->input_in_progress() ? nullptr : GetWebContents(); +} + +ContentSettingBubbleModelDelegate* +LocationBarView::GetContentSettingBubbleModelDelegate() { + return delegate_->GetContentSettingBubbleModelDelegate(); +} + +//////////////////////////////////////////////////////////////////////////////// // LocationBarView, private: int LocationBarView::IncrementalMinimumWidth(views::View* view) const { @@ -698,13 +712,18 @@ } bool LocationBarView::RefreshContentSettingViews() { + if (extensions::HostedAppBrowserController::IsForExperimentalHostedAppBrowser( + browser_)) { + // For hosted apps, the location bar is normally hidden and icons appear in + // the window frame instead. + GetWidget()->non_client_view()->ResetWindowControls(); + } + bool visibility_changed = false; - for (ContentSettingViews::const_iterator i(content_setting_views_.begin()); - i != content_setting_views_.end(); ++i) { - const bool was_visible = (*i)->visible(); - (*i)->Update(GetToolbarModel()->input_in_progress() ? nullptr - : GetWebContents()); - if (was_visible != (*i)->visible()) + for (auto* v : content_setting_views_) { + const bool was_visible = v->visible(); + v->Update(); + if (was_visible != v->visible()) visibility_changed = true; } return visibility_changed;
diff --git a/chrome/browser/ui/views/location_bar/location_bar_view.h b/chrome/browser/ui/views/location_bar/location_bar_view.h index 99c28b2..65cae40 100644 --- a/chrome/browser/ui/views/location_bar/location_bar_view.h +++ b/chrome/browser/ui/views/location_bar/location_bar_view.h
@@ -18,6 +18,7 @@ #include "chrome/browser/ui/views/dropdown_bar_host.h" #include "chrome/browser/ui/views/dropdown_bar_host_delegate.h" #include "chrome/browser/ui/views/extensions/extension_popup.h" +#include "chrome/browser/ui/views/location_bar/content_setting_image_view.h" #include "chrome/browser/ui/views/omnibox/omnibox_view_views.h" #include "components/prefs/pref_member.h" #include "components/security_state/core/security_state.h" @@ -31,7 +32,6 @@ class CommandUpdater; class ContentSettingBubbleModelDelegate; -class ContentSettingImageView; class FindBarIcon; class GURL; class IntentPickerView; @@ -69,7 +69,8 @@ public ChromeOmniboxEditController, public DropdownBarHostDelegate, public zoom::ZoomEventManagerObserver, - public views::ButtonListener { + public views::ButtonListener, + public ContentSettingImageView::Delegate { public: class Delegate { public: @@ -237,6 +238,11 @@ ToolbarModel* GetToolbarModel() override; content::WebContents* GetWebContents() override; + // ContentSettingImageView::Delegate: + content::WebContents* GetContentSettingWebContents() override; + ContentSettingBubbleModelDelegate* GetContentSettingBubbleModelDelegate() + override; + // ZoomEventManagerObserver: // Updates the view for the zoom icon when default zoom levels change. void OnDefaultZoomLevelChanged() override; @@ -358,7 +364,7 @@ // The Browser this LocationBarView is in. Note that at least // chromeos::SimpleWebViewDialog uses a LocationBarView outside any browser // window, so this may be NULL. - Browser* browser_; + Browser* const browser_; OmniboxViewViews* omnibox_view_ = nullptr;
diff --git a/chrome/browser/ui/views/location_bar/star_view.h b/chrome/browser/ui/views/location_bar/star_view.h index f6a2347..5cf3462 100644 --- a/chrome/browser/ui/views/location_bar/star_view.h +++ b/chrome/browser/ui/views/location_bar/star_view.h
@@ -35,7 +35,7 @@ const gfx::VectorIcon& GetVectorIcon() const override; private: - Browser* browser_; + Browser* const browser_; // Observes the BookmarkPromoBubbleView's widget. Used to tell whether the // promo is open and gets called back when it closes.
diff --git a/chrome/browser/ui/views/page_info/chosen_object_row.cc b/chrome/browser/ui/views/page_info/chosen_object_row.cc deleted file mode 100644 index e12e717..0000000 --- a/chrome/browser/ui/views/page_info/chosen_object_row.cc +++ /dev/null
@@ -1,104 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/views/page_info/chosen_object_row.h" - -#include "chrome/browser/ui/views/harmony/chrome_layout_provider.h" -#include "chrome/browser/ui/views/harmony/chrome_typography.h" -#include "chrome/browser/ui/views/page_info/chosen_object_row_observer.h" -#include "chrome/browser/ui/views/page_info/page_info_bubble_view.h" -#include "components/vector_icons/vector_icons.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/base/material_design/material_design_controller.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/resources/grit/ui_resources.h" -#include "ui/views/controls/button/image_button.h" -#include "ui/views/controls/button/image_button_factory.h" -#include "ui/views/controls/image_view.h" -#include "ui/views/controls/label.h" -#include "ui/views/layout/grid_layout.h" - -ChosenObjectRow::ChosenObjectRow( - std::unique_ptr<PageInfoUI::ChosenObjectInfo> info) - : info_(std::move(info)) { - // |ChosenObjectRow| layout (fills parent): - // *------------------------------------* - // | Icon | Chosen Object Name | X | - // *------------------------------------* - // - // Where the icon and close button columns are fixed widths. - - constexpr float kFixed = 0.f; - constexpr float kStretchy = 1.f; - views::GridLayout* layout = views::GridLayout::CreateAndInstall(this); - const int column_set_id = 0; - views::ColumnSet* column_set = layout->AddColumnSet(column_set_id); - column_set->AddColumn(views::GridLayout::CENTER, views::GridLayout::CENTER, - kFixed, views::GridLayout::FIXED, - PageInfoBubbleView::kIconColumnWidth, 0); - column_set->AddPaddingColumn(kFixed, - ChromeLayoutProvider::Get()->GetDistanceMetric( - views::DISTANCE_RELATED_LABEL_HORIZONTAL)); - column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::CENTER, - kStretchy, views::GridLayout::USE_PREF, 0, 0); - column_set->AddColumn(views::GridLayout::TRAILING, views::GridLayout::CENTER, - kFixed, views::GridLayout::USE_PREF, - PageInfoBubbleView::kIconColumnWidth, 0); - - layout->StartRow(kStretchy, column_set_id); - // Create the chosen object icon. - icon_ = new views::ImageView(); - const gfx::Image& image = PageInfoUI::GetChosenObjectIcon(*info_, false); - icon_->SetImage(image.ToImageSkia()); - layout->AddView(icon_); - // Create the label that displays the chosen object name. - views::Label* label = new views::Label( - l10n_util::GetStringFUTF16(info_->ui_info.label_string_id, - PageInfoUI::ChosenObjectToUIString(*info_)), - CONTEXT_BODY_TEXT_LARGE); - layout->AddView(label); - // Create the delete button. - if (ui::MaterialDesignController::IsSecondaryUiMaterial()) { - delete_button_ = views::CreateVectorImageButton(this); - views::SetImageFromVectorIcon( - delete_button_, vector_icons::kClose16Icon, - views::style::GetColor(*this, CONTEXT_BODY_TEXT_LARGE, - views::style::STYLE_PRIMARY)); - - } else { - delete_button_ = new views::ImageButton(this); - ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); - delete_button_->SetImage(views::ImageButton::STATE_NORMAL, - rb.GetImageSkiaNamed(IDR_CLOSE_2)); - delete_button_->SetImage(views::ImageButton::STATE_HOVERED, - rb.GetImageSkiaNamed(IDR_CLOSE_2_H)); - delete_button_->SetImage(views::ImageButton::STATE_PRESSED, - rb.GetImageSkiaNamed(IDR_CLOSE_2_P)); - } - delete_button_->SetFocusForPlatform(); - delete_button_->set_request_focus_on_press(true); - delete_button_->SetTooltipText( - l10n_util::GetStringUTF16(info_->ui_info.delete_tooltip_string_id)); - layout->AddView(delete_button_); -} - -void ChosenObjectRow::AddObserver(ChosenObjectRowObserver* observer) { - observer_list_.AddObserver(observer); -} - -ChosenObjectRow::~ChosenObjectRow() {} - -void ChosenObjectRow::ButtonPressed(views::Button* sender, - const ui::Event& event) { - // Change the icon to reflect the selected setting. - const gfx::Image& image = PageInfoUI::GetChosenObjectIcon(*info_, true); - icon_->SetImage(image.ToImageSkia()); - - DCHECK(delete_button_->visible()); - delete_button_->SetVisible(false); - - for (ChosenObjectRowObserver& observer : observer_list_) { - observer.OnChosenObjectDeleted(*info_); - } -}
diff --git a/chrome/browser/ui/views/page_info/chosen_object_row.h b/chrome/browser/ui/views/page_info/chosen_object_row.h deleted file mode 100644 index 8623d34..0000000 --- a/chrome/browser/ui/views/page_info/chosen_object_row.h +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_VIEWS_PAGE_INFO_CHOSEN_OBJECT_ROW_H_ -#define CHROME_BROWSER_UI_VIEWS_PAGE_INFO_CHOSEN_OBJECT_ROW_H_ - -#include "base/macros.h" -#include "chrome/browser/ui/page_info/page_info_ui.h" -#include "ui/views/controls/button/button.h" -#include "ui/views/view.h" - -namespace views { -class ImageButton; -class ImageView; -} - -class ChosenObjectRowObserver; - -// A ChosenObjectRow is a row in the Page Info bubble that shows an individual -// object (e.g. a Bluetooth device, a USB device) that the current site has -// access to. -class ChosenObjectRow : public views::View, public views::ButtonListener { - public: - explicit ChosenObjectRow(std::unique_ptr<PageInfoUI::ChosenObjectInfo> info); - ~ChosenObjectRow() override; - - void AddObserver(ChosenObjectRowObserver* observer); - - private: - // views::ButtonListener implementation. - void ButtonPressed(views::Button* sender, const ui::Event& event) override; - - views::ImageView* icon_; // Owned by the views hierarchy. - views::ImageButton* delete_button_; // Owned by the views hierarchy. - - base::ObserverList<ChosenObjectRowObserver> observer_list_; - std::unique_ptr<PageInfoUI::ChosenObjectInfo> info_; - - DISALLOW_COPY_AND_ASSIGN(ChosenObjectRow); -}; - -#endif // CHROME_BROWSER_UI_VIEWS_PAGE_INFO_CHOSEN_OBJECT_ROW_H_
diff --git a/chrome/browser/ui/views/page_info/chosen_object_row_observer.h b/chrome/browser/ui/views/page_info/chosen_object_row_observer.h deleted file mode 100644 index 2737dec..0000000 --- a/chrome/browser/ui/views/page_info/chosen_object_row_observer.h +++ /dev/null
@@ -1,20 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_VIEWS_PAGE_INFO_CHOSEN_OBJECT_ROW_OBSERVER_H_ -#define CHROME_BROWSER_UI_VIEWS_PAGE_INFO_CHOSEN_OBJECT_ROW_OBSERVER_H_ - -#include "chrome/browser/ui/page_info/page_info_ui.h" - -class ChosenObjectRowObserver { - public: - // This method is called when permission for the object is revoked. - virtual void OnChosenObjectDeleted( - const PageInfoUI::ChosenObjectInfo& info) = 0; - - protected: - virtual ~ChosenObjectRowObserver() {} -}; - -#endif // CHROME_BROWSER_UI_VIEWS_PAGE_INFO_CHOSEN_OBJECT_ROW_OBSERVER_H_
diff --git a/chrome/browser/ui/views/page_info/chosen_object_view.cc b/chrome/browser/ui/views/page_info/chosen_object_view.cc new file mode 100644 index 0000000..7915b527 --- /dev/null +++ b/chrome/browser/ui/views/page_info/chosen_object_view.cc
@@ -0,0 +1,104 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/views/page_info/chosen_object_view.h" + +#include "chrome/browser/ui/views/harmony/chrome_layout_provider.h" +#include "chrome/browser/ui/views/harmony/chrome_typography.h" +#include "chrome/browser/ui/views/page_info/chosen_object_view_observer.h" +#include "chrome/browser/ui/views/page_info/page_info_bubble_view.h" +#include "components/vector_icons/vector_icons.h" +#include "ui/base/l10n/l10n_util.h" +#include "ui/base/material_design/material_design_controller.h" +#include "ui/base/resource/resource_bundle.h" +#include "ui/resources/grit/ui_resources.h" +#include "ui/views/controls/button/image_button.h" +#include "ui/views/controls/button/image_button_factory.h" +#include "ui/views/controls/image_view.h" +#include "ui/views/controls/label.h" +#include "ui/views/layout/grid_layout.h" + +ChosenObjectView::ChosenObjectView( + std::unique_ptr<PageInfoUI::ChosenObjectInfo> info) + : info_(std::move(info)) { + // |ChosenObjectView| layout (fills parent): + // *------------------------------------* + // | Icon | Chosen Object Name | X | + // *------------------------------------* + // + // Where the icon and close button columns are fixed widths. + + constexpr float kFixed = 0.f; + constexpr float kStretchy = 1.f; + views::GridLayout* layout = views::GridLayout::CreateAndInstall(this); + const int column_set_id = 0; + views::ColumnSet* column_set = layout->AddColumnSet(column_set_id); + column_set->AddColumn(views::GridLayout::CENTER, views::GridLayout::CENTER, + kFixed, views::GridLayout::FIXED, + PageInfoBubbleView::kIconColumnWidth, 0); + column_set->AddPaddingColumn(kFixed, + ChromeLayoutProvider::Get()->GetDistanceMetric( + views::DISTANCE_RELATED_LABEL_HORIZONTAL)); + column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::CENTER, + kStretchy, views::GridLayout::USE_PREF, 0, 0); + column_set->AddColumn(views::GridLayout::TRAILING, views::GridLayout::CENTER, + kFixed, views::GridLayout::USE_PREF, + PageInfoBubbleView::kIconColumnWidth, 0); + + layout->StartRow(kStretchy, column_set_id); + // Create the chosen object icon. + icon_ = new views::ImageView(); + const gfx::Image& image = PageInfoUI::GetChosenObjectIcon(*info_, false); + icon_->SetImage(image.ToImageSkia()); + layout->AddView(icon_); + // Create the label that displays the chosen object name. + views::Label* label = new views::Label( + l10n_util::GetStringFUTF16(info_->ui_info.label_string_id, + PageInfoUI::ChosenObjectToUIString(*info_)), + CONTEXT_BODY_TEXT_LARGE); + layout->AddView(label); + // Create the delete button. + if (ui::MaterialDesignController::IsSecondaryUiMaterial()) { + delete_button_ = views::CreateVectorImageButton(this); + views::SetImageFromVectorIcon( + delete_button_, vector_icons::kClose16Icon, + views::style::GetColor(*this, CONTEXT_BODY_TEXT_LARGE, + views::style::STYLE_PRIMARY)); + + } else { + delete_button_ = new views::ImageButton(this); + ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); + delete_button_->SetImage(views::ImageButton::STATE_NORMAL, + rb.GetImageSkiaNamed(IDR_CLOSE_2)); + delete_button_->SetImage(views::ImageButton::STATE_HOVERED, + rb.GetImageSkiaNamed(IDR_CLOSE_2_H)); + delete_button_->SetImage(views::ImageButton::STATE_PRESSED, + rb.GetImageSkiaNamed(IDR_CLOSE_2_P)); + } + delete_button_->SetFocusForPlatform(); + delete_button_->set_request_focus_on_press(true); + delete_button_->SetTooltipText( + l10n_util::GetStringUTF16(info_->ui_info.delete_tooltip_string_id)); + layout->AddView(delete_button_); +} + +void ChosenObjectView::AddObserver(ChosenObjectViewObserver* observer) { + observer_list_.AddObserver(observer); +} + +ChosenObjectView::~ChosenObjectView() {} + +void ChosenObjectView::ButtonPressed(views::Button* sender, + const ui::Event& event) { + // Change the icon to reflect the selected setting. + const gfx::Image& image = PageInfoUI::GetChosenObjectIcon(*info_, true); + icon_->SetImage(image.ToImageSkia()); + + DCHECK(delete_button_->visible()); + delete_button_->SetVisible(false); + + for (ChosenObjectViewObserver& observer : observer_list_) { + observer.OnChosenObjectDeleted(*info_); + } +}
diff --git a/chrome/browser/ui/views/page_info/chosen_object_view.h b/chrome/browser/ui/views/page_info/chosen_object_view.h new file mode 100644 index 0000000..49ac1e9 --- /dev/null +++ b/chrome/browser/ui/views/page_info/chosen_object_view.h
@@ -0,0 +1,43 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_VIEWS_PAGE_INFO_CHOSEN_OBJECT_VIEW_H_ +#define CHROME_BROWSER_UI_VIEWS_PAGE_INFO_CHOSEN_OBJECT_VIEW_H_ + +#include "base/macros.h" +#include "chrome/browser/ui/page_info/page_info_ui.h" +#include "ui/views/controls/button/button.h" +#include "ui/views/view.h" + +namespace views { +class ImageButton; +class ImageView; +} // namespace views + +class ChosenObjectViewObserver; + +// A ChosenObjectView is a row in the Page Info bubble that shows an individual +// object (e.g. a Bluetooth device, a USB device) that the current site has +// access to. +class ChosenObjectView : public views::View, public views::ButtonListener { + public: + explicit ChosenObjectView(std::unique_ptr<PageInfoUI::ChosenObjectInfo> info); + ~ChosenObjectView() override; + + void AddObserver(ChosenObjectViewObserver* observer); + + private: + // views::ButtonListener implementation. + void ButtonPressed(views::Button* sender, const ui::Event& event) override; + + views::ImageView* icon_; // Owned by the views hierarchy. + views::ImageButton* delete_button_; // Owned by the views hierarchy. + + base::ObserverList<ChosenObjectViewObserver> observer_list_; + std::unique_ptr<PageInfoUI::ChosenObjectInfo> info_; + + DISALLOW_COPY_AND_ASSIGN(ChosenObjectView); +}; + +#endif // CHROME_BROWSER_UI_VIEWS_PAGE_INFO_CHOSEN_OBJECT_VIEW_H_
diff --git a/chrome/browser/ui/views/page_info/chosen_object_view_observer.h b/chrome/browser/ui/views/page_info/chosen_object_view_observer.h new file mode 100644 index 0000000..636415c4 --- /dev/null +++ b/chrome/browser/ui/views/page_info/chosen_object_view_observer.h
@@ -0,0 +1,20 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_VIEWS_PAGE_INFO_CHOSEN_OBJECT_VIEW_OBSERVER_H_ +#define CHROME_BROWSER_UI_VIEWS_PAGE_INFO_CHOSEN_OBJECT_VIEW_OBSERVER_H_ + +#include "chrome/browser/ui/page_info/page_info_ui.h" + +class ChosenObjectViewObserver { + public: + // This method is called when permission for the object is revoked. + virtual void OnChosenObjectDeleted( + const PageInfoUI::ChosenObjectInfo& info) = 0; + + protected: + virtual ~ChosenObjectViewObserver() {} +}; + +#endif // CHROME_BROWSER_UI_VIEWS_PAGE_INFO_CHOSEN_OBJECT_VIEW_OBSERVER_H_
diff --git a/chrome/browser/ui/views/page_info/page_info_bubble_view.cc b/chrome/browser/ui/views/page_info/page_info_bubble_view.cc index 061e522..3bd18a79 100644 --- a/chrome/browser/ui/views/page_info/page_info_bubble_view.cc +++ b/chrome/browser/ui/views/page_info/page_info_bubble_view.cc
@@ -31,7 +31,7 @@ #include "chrome/browser/ui/views/harmony/chrome_layout_provider.h" #include "chrome/browser/ui/views/harmony/chrome_typography.h" #include "chrome/browser/ui/views/hover_button.h" -#include "chrome/browser/ui/views/page_info/chosen_object_row.h" +#include "chrome/browser/ui/views/page_info/chosen_object_view.h" #include "chrome/browser/ui/views/page_info/non_accessible_image_view.h" #include "chrome/browser/ui/views/page_info/permission_selector_row.h" #include "chrome/common/url_constants.h" @@ -873,7 +873,8 @@ GridLayout::USE_PREF, 0, 0); permissions_set->AddPaddingColumn(kFixed, side_margin); - // |ChosenObjectRow| will layout itself, so just add the missing padding here. + // |ChosenObjectView| will layout itself, so just add the missing padding + // here. constexpr int kChosenObjectSectionId = 1; views::ColumnSet* chosen_object_set = layout->AddColumnSet(kChosenObjectSectionId); @@ -920,7 +921,7 @@ 1, kChosenObjectSectionId, PermissionSelectorRow::MinHeightForPermissionRow() + list_item_padding); // The view takes ownership of the object info. - auto object_view = std::make_unique<ChosenObjectRow>(std::move(object)); + auto object_view = std::make_unique<ChosenObjectView>(std::move(object)); object_view->AddObserver(this); layout->AddView(object_view.release()); }
diff --git a/chrome/browser/ui/views/page_info/page_info_bubble_view.h b/chrome/browser/ui/views/page_info/page_info_bubble_view.h index 1c300c0..044996d 100644 --- a/chrome/browser/ui/views/page_info/page_info_bubble_view.h +++ b/chrome/browser/ui/views/page_info/page_info_bubble_view.h
@@ -12,7 +12,7 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/ui/page_info/page_info_ui.h" -#include "chrome/browser/ui/views/page_info/chosen_object_row_observer.h" +#include "chrome/browser/ui/views/page_info/chosen_object_view_observer.h" #include "chrome/browser/ui/views/page_info/permission_selector_row.h" #include "chrome/browser/ui/views/page_info/permission_selector_row_observer.h" #include "content/public/browser/web_contents_observer.h" @@ -52,7 +52,7 @@ // The views implementation of the page info UI. class PageInfoBubbleView : public content::WebContentsObserver, public PermissionSelectorRowObserver, - public ChosenObjectRowObserver, + public ChosenObjectViewObserver, public views::BubbleDialogDelegateView, public views::ButtonListener, public views::LinkListener, @@ -122,7 +122,7 @@ void OnPermissionChanged( const PageInfoUI::PermissionInfo& permission) override; - // ChosenObjectRowObserver implementation. + // ChosenObjectViewObserver implementation. void OnChosenObjectDeleted(const PageInfoUI::ChosenObjectInfo& info) override; // views::BubbleDialogDelegateView implementation.
diff --git a/chrome/browser/ui/views/page_info/page_info_bubble_view_unittest.cc b/chrome/browser/ui/views/page_info/page_info_bubble_view_unittest.cc index 81242b9..0ad3a32 100644 --- a/chrome/browser/ui/views/page_info/page_info_bubble_view_unittest.cc +++ b/chrome/browser/ui/views/page_info/page_info_bubble_view_unittest.cc
@@ -10,7 +10,7 @@ #include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h" #include "chrome/browser/ui/views/harmony/chrome_layout_provider.h" #include "chrome/browser/ui/views/hover_button.h" -#include "chrome/browser/ui/views/page_info/chosen_object_row.h" +#include "chrome/browser/ui/views/page_info/chosen_object_view.h" #include "chrome/browser/ui/views/page_info/permission_selector_row.h" #include "chrome/browser/usb/usb_chooser_context.h" #include "chrome/browser/usb/usb_chooser_context_factory.h" @@ -294,7 +294,7 @@ api_->SetPermissionInfo(list); EXPECT_EQ(kExpectedChildren + 1, api_->permissions_view()->child_count()); - ChosenObjectRow* object_view = static_cast<ChosenObjectRow*>( + ChosenObjectView* object_view = static_cast<ChosenObjectView*>( api_->permissions_view()->child_at(kExpectedChildren)); EXPECT_EQ(3, object_view->child_count());
diff --git a/chrome/browser/ui/views/payments/cvc_unmask_view_controller.cc b/chrome/browser/ui/views/payments/cvc_unmask_view_controller.cc index 7890735..81b0479 100644 --- a/chrome/browser/ui/views/payments/cvc_unmask_view_controller.cc +++ b/chrome/browser/ui/views/payments/cvc_unmask_view_controller.cc
@@ -159,8 +159,13 @@ views::GridLayout::SizeType::USE_PREF, 0, 0); layout->StartRow(0, 0); - std::unique_ptr<views::Label> instructions = base::MakeUnique<views::Label>( - l10n_util::GetStringUTF16(IDS_AUTOFILL_CARD_UNMASK_PROMPT_INSTRUCTIONS)); + // The prompt for server cards should reference Google Payments, whereas the + // prompt for local cards should not. + std::unique_ptr<views::Label> instructions = + base::MakeUnique<views::Label>(l10n_util::GetStringUTF16( + credit_card_.record_type() == autofill::CreditCard::LOCAL_CARD + ? IDS_AUTOFILL_CARD_UNMASK_PROMPT_INSTRUCTIONS_LOCAL_CARD + : IDS_AUTOFILL_CARD_UNMASK_PROMPT_INSTRUCTIONS)); instructions->SetMultiLine(true); instructions->SetHorizontalAlignment(gfx::ALIGN_LEFT); layout->AddView(instructions.release());
diff --git a/chrome/browser/ui/views/permission_bubble/chooser_bubble_ui.h b/chrome/browser/ui/views/permission_bubble/chooser_bubble_ui.h index 87ccafd6..8bf4b8ff 100644 --- a/chrome/browser/ui/views/permission_bubble/chooser_bubble_ui.h +++ b/chrome/browser/ui/views/permission_bubble/chooser_bubble_ui.h
@@ -43,7 +43,7 @@ // allow this bubble to be used in either. void CreateAndShow(views::BubbleDialogDelegateView* delegate); - Browser* browser_; // Weak. + Browser* const browser_; // Weak. // Weak. Owned by its parent view. ChooserBubbleUiViewDelegate* chooser_bubble_ui_view_delegate_;
diff --git a/chrome/browser/ui/views/permission_bubble/permission_prompt_impl.h b/chrome/browser/ui/views/permission_bubble/permission_prompt_impl.h index 86cbb30..3a51d98 100644 --- a/chrome/browser/ui/views/permission_bubble/permission_prompt_impl.h +++ b/chrome/browser/ui/views/permission_bubble/permission_prompt_impl.h
@@ -30,8 +30,8 @@ private: void Show(); - Browser* browser_; - Delegate* delegate_; + Browser* const browser_; + Delegate* const delegate_; PermissionsBubbleDialogDelegateView* bubble_delegate_; DISALLOW_COPY_AND_ASSIGN(PermissionPromptImpl);
diff --git a/chrome/browser/ui/views/profiles/forced_reauthentication_dialog_view.h b/chrome/browser/ui/views/profiles/forced_reauthentication_dialog_view.h index 9530c953..653ec7cf 100644 --- a/chrome/browser/ui/views/profiles/forced_reauthentication_dialog_view.h +++ b/chrome/browser/ui/views/profiles/forced_reauthentication_dialog_view.h
@@ -63,7 +63,7 @@ void OnCountDown(); base::TimeDelta GetTimeRemaining() const; - Browser* browser_; + Browser* const browser_; SigninManager* signin_manager_; const base::TimeTicks desired_close_time_;
diff --git a/chrome/browser/ui/views/profiles/profile_chooser_view.h b/chrome/browser/ui/views/profiles/profile_chooser_view.h index b1489ca6..f851a86f 100644 --- a/chrome/browser/ui/views/profiles/profile_chooser_view.h +++ b/chrome/browser/ui/views/profiles/profile_chooser_view.h
@@ -163,7 +163,7 @@ void PostActionPerformed(ProfileMetrics::ProfileDesktopMenu action_performed); std::unique_ptr<AvatarMenu> avatar_menu_; - Browser* browser_; + Browser* const browser_; // Other profiles used in the "fast profile switcher" view. ButtonIndexes open_other_profile_indexes_map_;
diff --git a/chrome/browser/ui/views/session_crashed_bubble_view.h b/chrome/browser/ui/views/session_crashed_bubble_view.h index 40323e7..0fc795c 100644 --- a/chrome/browser/ui/views/session_crashed_bubble_view.h +++ b/chrome/browser/ui/views/session_crashed_bubble_view.h
@@ -77,7 +77,7 @@ void CloseBubble(); // Used for opening the question mark link as well as access the tab strip. - Browser* browser_; + Browser* const browser_; // Checkbox for the user to opt-in to UMA reporting. views::Checkbox* uma_option_;
diff --git a/chrome/browser/ui/views/sync/profile_signin_confirmation_dialog_views.h b/chrome/browser/ui/views/sync/profile_signin_confirmation_dialog_views.h index a466abd..e82da04 100644 --- a/chrome/browser/ui/views/sync/profile_signin_confirmation_dialog_views.h +++ b/chrome/browser/ui/views/sync/profile_signin_confirmation_dialog_views.h
@@ -66,7 +66,7 @@ void Show(bool prompt_for_new_profile); // Weak ptr to parent view. - Browser* browser_; + Browser* const browser_; // The GAIA username being signed in. std::string username_;
diff --git a/chrome/browser/ui/views/tabs/tab.cc b/chrome/browser/ui/views/tabs/tab.cc index 75491012..cbbeb1b 100644 --- a/chrome/browser/ui/views/tabs/tab.cc +++ b/chrome/browser/ui/views/tabs/tab.cc
@@ -866,7 +866,6 @@ node_data->SetName(controller_->GetAccessibleTabName(this)); node_data->AddState(ui::AX_STATE_MULTISELECTABLE); node_data->AddState(ui::AX_STATE_SELECTABLE); - controller_->UpdateTabAccessibilityState(this, node_data); if (IsSelected()) node_data->AddState(ui::AX_STATE_SELECTED); }
diff --git a/chrome/browser/ui/views/tabs/tab_controller.h b/chrome/browser/ui/views/tabs/tab_controller.h index 785183ed3..82712ae4 100644 --- a/chrome/browser/ui/views/tabs/tab_controller.h +++ b/chrome/browser/ui/views/tabs/tab_controller.h
@@ -18,7 +18,6 @@ class Size; } namespace ui { -struct AXNodeData; class ListSelectionModel; class LocatedEvent; class MouseEvent; @@ -122,10 +121,6 @@ // background images have been customized; see implementation comments. virtual int GetBackgroundResourceId(bool* custom_image) const = 0; - // Adds private information to the tab's accessibility state. - virtual void UpdateTabAccessibilityState(const Tab* tab, - ui::AXNodeData* node_data) = 0; - // Returns the accessible tab name for this tab. virtual base::string16 GetAccessibleTabName(const Tab* tab) const = 0;
diff --git a/chrome/browser/ui/views/tabs/tab_strip_experimental.h b/chrome/browser/ui/views/tabs/tab_strip_experimental.h index 1429254e..d49d917 100644 --- a/chrome/browser/ui/views/tabs/tab_strip_experimental.h +++ b/chrome/browser/ui/views/tabs/tab_strip_experimental.h
@@ -179,8 +179,6 @@ SkColor GetToolbarTopSeparatorColor() const override; base::string16 GetAccessibleTabName(const Tab* tab) const override; int GetBackgroundResourceId(bool* custom_image) const override; - void UpdateTabAccessibilityState(const Tab* tab, - ui::AXNodeData* node_data) override; */ // MouseWatcherListener overrides:
diff --git a/chrome/browser/ui/views/tabs/tab_strip_impl.cc b/chrome/browser/ui/views/tabs/tab_strip_impl.cc index 9ff545f..fa9fbb5 100644 --- a/chrome/browser/ui/views/tabs/tab_strip_impl.cc +++ b/chrome/browser/ui/views/tabs/tab_strip_impl.cc
@@ -1043,12 +1043,6 @@ return id; } -void TabStripImpl::UpdateTabAccessibilityState(const Tab* tab, - ui::AXNodeData* node_data) { - node_data->AddIntAttribute(ui::AX_ATTR_SET_SIZE, tab_count()); - node_data->AddIntAttribute(ui::AX_ATTR_POS_IN_SET, GetModelIndexOfTab(tab)); -} - void TabStripImpl::MouseMovedOutOfHost() { ResizeLayoutTabs(); if (reset_to_shrink_on_exit_) {
diff --git a/chrome/browser/ui/views/tabs/tab_strip_impl.h b/chrome/browser/ui/views/tabs/tab_strip_impl.h index d4814967..f1f08dd 100644 --- a/chrome/browser/ui/views/tabs/tab_strip_impl.h +++ b/chrome/browser/ui/views/tabs/tab_strip_impl.h
@@ -223,8 +223,6 @@ SkColor GetToolbarTopSeparatorColor() const override; base::string16 GetAccessibleTabName(const Tab* tab) const override; int GetBackgroundResourceId(bool* custom_image) const override; - void UpdateTabAccessibilityState(const Tab* tab, - ui::AXNodeData* node_data) override; // MouseWatcherListener overrides: void MouseMovedOutOfHost() override;
diff --git a/chrome/browser/ui/views/tabs/tab_unittest.cc b/chrome/browser/ui/views/tabs/tab_unittest.cc index 63a8c6f..fe17b81 100644 --- a/chrome/browser/ui/views/tabs/tab_unittest.cc +++ b/chrome/browser/ui/views/tabs/tab_unittest.cc
@@ -78,8 +78,6 @@ *custom_image = false; return IDR_THEME_TAB_BACKGROUND; } - void UpdateTabAccessibilityState(const Tab* tab, - ui::AXNodeData* node_data) override {} base::string16 GetAccessibleTabName(const Tab* tab) const override { return base::string16(); }
diff --git a/chrome/browser/ui/views/toolbar/app_menu.h b/chrome/browser/ui/views/toolbar/app_menu.h index 7e34995c..4d574dd 100644 --- a/chrome/browser/ui/views/toolbar/app_menu.h +++ b/chrome/browser/ui/views/toolbar/app_menu.h
@@ -160,7 +160,7 @@ CommandIDToEntry command_id_to_entry_; // Browser the menu is being shown for. - Browser* browser_; + Browser* const browser_; // |CancelAndEvaluate| sets |selected_menu_model_| and |selected_index_|. // If |selected_menu_model_| is non-null after the menu completes
diff --git a/chrome/browser/ui/views/toolbar/browser_actions_container.h b/chrome/browser/ui/views/toolbar/browser_actions_container.h index c0fff1a..e802028 100644 --- a/chrome/browser/ui/views/toolbar/browser_actions_container.h +++ b/chrome/browser/ui/views/toolbar/browser_actions_container.h
@@ -242,7 +242,7 @@ ToolbarActionViews toolbar_action_views_; // The Browser object the container is associated with. - Browser* browser_; + Browser* const browser_; // The main container we are serving as overflow for, or NULL if this // class is the the main container. See class comments for details on
diff --git a/chrome/browser/ui/views/toolbar/extension_toolbar_menu_view.h b/chrome/browser/ui/views/toolbar/extension_toolbar_menu_view.h index 0b69ff3..23fbbf2 100644 --- a/chrome/browser/ui/views/toolbar/extension_toolbar_menu_view.h +++ b/chrome/browser/ui/views/toolbar/extension_toolbar_menu_view.h
@@ -62,7 +62,7 @@ int start_padding() const; // The associated browser. - Browser* browser_; + Browser* const browser_; // The app menu, which may need to be closed after a drag-and-drop. AppMenu* app_menu_;
diff --git a/chrome/browser/ui/views/toolbar/home_button.h b/chrome/browser/ui/views/toolbar/home_button.h index d66167c..3c6bcee7 100644 --- a/chrome/browser/ui/views/toolbar/home_button.h +++ b/chrome/browser/ui/views/toolbar/home_button.h
@@ -26,7 +26,7 @@ int OnDragUpdated(const ui::DropTargetEvent& event) override; int OnPerformDrop(const ui::DropTargetEvent& event) override; - Browser* browser_; + Browser* const browser_; DISALLOW_COPY_AND_ASSIGN(HomeButton); };
diff --git a/chrome/browser/ui/views/toolbar/media_router_action_platform_delegate_views.h b/chrome/browser/ui/views/toolbar/media_router_action_platform_delegate_views.h index aa82857..b2ce655 100644 --- a/chrome/browser/ui/views/toolbar/media_router_action_platform_delegate_views.h +++ b/chrome/browser/ui/views/toolbar/media_router_action_platform_delegate_views.h
@@ -20,7 +20,7 @@ private: // The corresponding browser. - Browser* browser_; + Browser* const browser_; DISALLOW_COPY_AND_ASSIGN(MediaRouterActionPlatformDelegateViews); };
diff --git a/chrome/browser/ui/views/toolbar/toolbar_view.h b/chrome/browser/ui/views/toolbar/toolbar_view.h index 638c8da..aa7305d 100644 --- a/chrome/browser/ui/views/toolbar/toolbar_view.h +++ b/chrome/browser/ui/views/toolbar/toolbar_view.h
@@ -203,7 +203,7 @@ BrowserActionsContainer* browser_actions_; AppMenuButton* app_menu_button_; - Browser* browser_; + Browser* const browser_; AppMenuIconController app_menu_icon_controller_;
diff --git a/chrome/browser/ui/views/translate/translate_bubble_test_utils_views.cc b/chrome/browser/ui/views/translate/translate_bubble_test_utils_views.cc index 1cae685b..de4c2371 100644 --- a/chrome/browser/ui/views/translate/translate_bubble_test_utils_views.cc +++ b/chrome/browser/ui/views/translate/translate_bubble_test_utils_views.cc
@@ -7,6 +7,7 @@ #include "base/logging.h" #include "chrome/browser/ui/translate/translate_bubble_model.h" #include "chrome/browser/ui/views/translate/translate_bubble_view.h" +#include "ui/views/controls/combobox/combobox.h" namespace translate { @@ -32,6 +33,34 @@ bubble->HandleButtonPressed(TranslateBubbleView::BUTTON_ID_SHOW_ORIGINAL); } +void SelectTargetLanguageByDisplayName(Browser* browser, + const base::string16& display_name) { + DCHECK(browser); + + TranslateBubbleView* bubble = TranslateBubbleView::GetCurrentBubble(); + DCHECK(bubble); + + TranslateBubbleModel* model = bubble->model(); + DCHECK(model); + + // Get index of the language with the matching display name. + int language_index = -1; + for (int i = 0; i < model->GetNumberOfLanguages(); ++i) { + const base::string16& language_name = model->GetLanguageNameAt(i); + + if (language_name == display_name) { + language_index = i; + break; + } + } + DCHECK_GE(language_index, 0); + + // Simulate selecting the correct index of the target language combo box. + bubble->target_language_combobox_->SetSelectedIndex(language_index); + bubble->HandleComboboxPerformAction( + TranslateBubbleView::COMBOBOX_ID_TARGET_LANGUAGE); +} + } // namespace test_utils } // namespace translate
diff --git a/chrome/browser/ui/views/translate/translate_bubble_view.h b/chrome/browser/ui/views/translate/translate_bubble_view.h index 1395834..57ba526 100644 --- a/chrome/browser/ui/views/translate/translate_bubble_view.h +++ b/chrome/browser/ui/views/translate/translate_bubble_view.h
@@ -10,6 +10,7 @@ #include "base/gtest_prod_util.h" #include "base/macros.h" +#include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/translate/chrome_translate_client.h" #include "chrome/browser/ui/translate/language_combobox_model.h" @@ -157,6 +158,9 @@ friend class TranslateBubbleViewTest; friend void ::translate::test_utils::PressTranslate(::Browser*); friend void ::translate::test_utils::PressRevert(::Browser*); + friend void ::translate::test_utils::SelectTargetLanguageByDisplayName( + ::Browser*, + const ::base::string16&); FRIEND_TEST_ALL_PREFIXES(TranslateBubbleViewTest, TranslateButton); FRIEND_TEST_ALL_PREFIXES(TranslateBubbleViewTest, TranslateButtonIn2016Q2UI); FRIEND_TEST_ALL_PREFIXES(TranslateBubbleViewTest, CloseButtonIn2016Q2UI);
diff --git a/chrome/browser/ui/views/translate/translate_language_browsertest.cc b/chrome/browser/ui/views/translate/translate_language_browsertest.cc index d586dee..6685878 100644 --- a/chrome/browser/ui/views/translate/translate_language_browsertest.cc +++ b/chrome/browser/ui/views/translate/translate_language_browsertest.cc
@@ -41,6 +41,8 @@ const base::FilePath::CharType kEnglishTestPath[] = FILE_PATH_LITERAL("english_page.html"); +const base::FilePath::CharType kItalianTestPath[] = + FILE_PATH_LITERAL("italian_page.html"); const base::FilePath::CharType kFrenchTestPath[] = FILE_PATH_LITERAL("french_page.html"); @@ -57,7 +59,7 @@ " return;" " }," " getDetectedLanguage : function() {" - " return \"fr\";" + " return \"\";" " }," " translatePage : function(originalLang, targetLang," " onTranslateProgress) {" @@ -88,27 +90,29 @@ void TearDown() override { InProcessBrowserTest::TearDown(); } protected: - void SwitchToIncognitoMode() { browser_ = CreateIncognitoBrowser(); } + void InitInIncognitoMode(const bool incognito) { + browser_ = incognito ? CreateIncognitoBrowser() : browser(); + } - void CheckForTranslateUI(const base::FilePath& path, - bool expect_translate, - const std::string& expected_lang) { - // Set browser_ here because |browser_| is not available during the - // InProcessBrowserTest parameter initialization phase. - if (!browser_) { - browser_ = browser(); - } - expected_lang_ = expected_lang; + void NavigateToUrl(const base::FilePath::StringPieceType path) { + const GURL url = + ui_test_utils::GetTestUrl(base::FilePath(), base::FilePath(path)); + ui_test_utils::NavigateToURL(browser_, url); + } + + void CheckForTranslateUI(const base::FilePath::StringPieceType path, + const bool expect_translate) { + CHECK(browser_); + content::WindowedNotificationObserver language_detected_signal( chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED, - base::Bind(&TranslateLanguageBrowserTest::OnLanguageDetermined, + base::Bind(&TranslateLanguageBrowserTest::ValidLanguageDetected, base::Unretained(this))); - - const GURL url = ui_test_utils::GetTestUrl(base::FilePath(), path); - ui_test_utils::NavigateToURL(browser_, url); + NavigateToUrl(path); language_detected_signal.Wait(); + TranslateBubbleView* const bubble = TranslateBubbleView::GetCurrentBubble(); - DCHECK_NE(expect_translate, bubble == nullptr); + CHECK_NE(expect_translate, bubble == nullptr); } language::UrlLanguageHistogram* GetUrlLanguageHistogram() { @@ -121,45 +125,57 @@ return UrlLanguageHistogramFactory::GetForBrowserContext(browser_context); } - void Translate() { - EXPECT_EQ(expected_lang_, GetLanguageState().current_language()); + void SetTargetLanguageByDisplayName(const base::string16& name) { + translate::test_utils::SelectTargetLanguageByDisplayName(browser_, name); + } + + void Translate(const bool first_translate) { content::WindowedNotificationObserver page_translated_signal( chrome::NOTIFICATION_PAGE_TRANSLATED, content::NotificationService::AllSources()); + EXPECT_EQ(TranslateBubbleModel::VIEW_STATE_BEFORE_TRANSLATE, GetCurrentModel(browser_)->GetViewState()); + translate::test_utils::PressTranslate(browser_); - SimulateURLFetch(); + if (first_translate) + SimulateURLFetch(); + page_translated_signal.Wait(); EXPECT_EQ(TranslateBubbleModel::VIEW_STATE_AFTER_TRANSLATE, GetCurrentModel(browser_)->GetViewState()); - EXPECT_EQ("en", GetLanguageState().current_language()); } - void Revert() { - EXPECT_EQ("en", GetLanguageState().current_language()); - // Make page |expected_lang_| again! - translate::test_utils::PressRevert(browser_); - EXPECT_EQ(expected_lang_, GetLanguageState().current_language()); + void Revert() { translate::test_utils::PressRevert(browser_); } + + translate::LanguageState& GetLanguageState() { + auto* const client = ChromeTranslateClient::FromWebContents( + browser_->tab_strip_model()->GetActiveWebContents()); + CHECK(client); + + return client->GetLanguageState(); + } + + std::unique_ptr<translate::TranslatePrefs> GetTranslatePrefs() { + auto* const client = ChromeTranslateClient::FromWebContents( + browser_->tab_strip_model()->GetActiveWebContents()); + CHECK(client); + + return client->GetTranslatePrefs(); } private: Browser* browser_; net::TestURLFetcherFactory url_fetcher_factory_; - std::string expected_lang_; - bool OnLanguageDetermined(const content::NotificationSource& source, - const content::NotificationDetails& details) { + // Language detection sometimes fires early with an "und" detected code. This + // callback is used to wait until language detection succeeds. + bool ValidLanguageDetected(const content::NotificationSource& source, + const content::NotificationDetails& details) { const std::string& language = content::Details<translate::LanguageDetectionDetails>(details) - ->cld_language; - return language == expected_lang_; - } - - translate::LanguageState& GetLanguageState() { - auto* const client = ChromeTranslateClient::FromWebContents( - browser_->tab_strip_model()->GetActiveWebContents()); - return client->GetLanguageState(); + ->adopted_language; + return language != "und"; } void SimulateURLFetch() { @@ -177,15 +193,17 @@ }; IN_PROC_BROWSER_TEST_F(TranslateLanguageBrowserTest, LanguageModelLogSucceed) { + InitInIncognitoMode(false); + for (int i = 0; i < 10; ++i) { - ASSERT_NO_FATAL_FAILURE( - CheckForTranslateUI(base::FilePath(kFrenchTestPath), true, "fr")); - ASSERT_NO_FATAL_FAILURE( - CheckForTranslateUI(base::FilePath(kEnglishTestPath), false, "en")); + ASSERT_NO_FATAL_FAILURE(CheckForTranslateUI(kFrenchTestPath, true)); + EXPECT_EQ("fr", GetLanguageState().current_language()); + ASSERT_NO_FATAL_FAILURE(CheckForTranslateUI(kEnglishTestPath, false)); + EXPECT_EQ("en", GetLanguageState().current_language()); } // Intentionally visit the french page one more time. - ASSERT_NO_FATAL_FAILURE( - CheckForTranslateUI(base::FilePath(kFrenchTestPath), true, "fr")); + ASSERT_NO_FATAL_FAILURE(CheckForTranslateUI(kFrenchTestPath, true)); + EXPECT_EQ("fr", GetLanguageState().current_language()); // We should expect fr and en. fr should be 11 / (11 + 10) = 0.5238. const language::UrlLanguageHistogram* const histograms = @@ -200,12 +218,13 @@ } IN_PROC_BROWSER_TEST_F(TranslateLanguageBrowserTest, DontLogInIncognito) { - SwitchToIncognitoMode(); + InitInIncognitoMode(true); + for (int i = 0; i < 10; ++i) { - ASSERT_NO_FATAL_FAILURE( - CheckForTranslateUI(base::FilePath(kEnglishTestPath), false, "en")); - ASSERT_NO_FATAL_FAILURE( - CheckForTranslateUI(base::FilePath(kFrenchTestPath), true, "fr")); + ASSERT_NO_FATAL_FAILURE(CheckForTranslateUI(kEnglishTestPath, false)); + EXPECT_EQ("en", GetLanguageState().current_language()); + ASSERT_NO_FATAL_FAILURE(CheckForTranslateUI(kFrenchTestPath, true)); + EXPECT_EQ("fr", GetLanguageState().current_language()); } // We should expect no url language histograms. const language::UrlLanguageHistogram* const histograms = @@ -214,13 +233,58 @@ } IN_PROC_BROWSER_TEST_F(TranslateLanguageBrowserTest, TranslateAndRevert) { + InitInIncognitoMode(false); + // Visit the french page. - ASSERT_NO_FATAL_FAILURE( - CheckForTranslateUI(base::FilePath(kFrenchTestPath), true, "fr")); + ASSERT_NO_FATAL_FAILURE(CheckForTranslateUI(kFrenchTestPath, true)); + EXPECT_EQ("fr", GetLanguageState().current_language()); + // Translate the page. - ASSERT_NO_FATAL_FAILURE(Translate()); + ASSERT_NO_FATAL_FAILURE(Translate(true)); + EXPECT_EQ("en", GetLanguageState().current_language()); + // Revert the page. ASSERT_NO_FATAL_FAILURE(Revert()); + EXPECT_EQ("fr", GetLanguageState().current_language()); +} + +IN_PROC_BROWSER_TEST_F(TranslateLanguageBrowserTest, RecentTargetLanguage) { + base::test::ScopedFeatureList enable_feature; + enable_feature.InitAndEnableFeature(translate::kTranslateRecentTarget); + + InitInIncognitoMode(false); + + // Before browsing: set auto translate from French to Chinese. + GetTranslatePrefs()->WhitelistLanguagePair("fr", "zh-CN"); + EXPECT_EQ("", GetTranslatePrefs()->GetRecentTargetLanguage()); + + // Load an Italian page and translate to Spanish. After this, Spanish should + // be our recent target language. + ASSERT_NO_FATAL_FAILURE(CheckForTranslateUI(kItalianTestPath, true)); + EXPECT_EQ("it", GetLanguageState().current_language()); + ASSERT_NO_FATAL_FAILURE( + SetTargetLanguageByDisplayName(base::ASCIIToUTF16("Spanish"))); + ASSERT_NO_FATAL_FAILURE(Translate(true)); + EXPECT_EQ("es", GetLanguageState().current_language()); + EXPECT_EQ("es", GetTranslatePrefs()->GetRecentTargetLanguage()); + + // Load a French page. This should trigger an auto-translate to Chinese, but + // not a recent target update. + content::WindowedNotificationObserver page_translated_signal( + chrome::NOTIFICATION_PAGE_TRANSLATED, + content::NotificationService::AllSources()); + NavigateToUrl(kFrenchTestPath); + page_translated_signal.Wait(); + EXPECT_EQ("zh-CN", GetLanguageState().current_language()); + EXPECT_EQ("es", GetTranslatePrefs()->GetRecentTargetLanguage()); + + // Load an English page. This should offer to translate to Spanish, since that + // is our recent target language. + ASSERT_NO_FATAL_FAILURE(CheckForTranslateUI(kEnglishTestPath, true)); + EXPECT_EQ("en", GetLanguageState().current_language()); + ASSERT_NO_FATAL_FAILURE(Translate(false)); + EXPECT_EQ("es", GetLanguageState().current_language()); + EXPECT_EQ("es", GetTranslatePrefs()->GetRecentTargetLanguage()); } #endif // defined(USE_AURA)
diff --git a/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc b/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc index 1b8b6f4..04b9a29 100644 --- a/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc +++ b/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc
@@ -149,7 +149,6 @@ #include "chrome/browser/ui/webui/chromeos/slow_trace_ui.h" #include "chrome/browser/ui/webui/chromeos/slow_ui.h" #include "chrome/browser/ui/webui/chromeos/sys_internals/sys_internals_ui.h" -#include "chrome/browser/ui/webui/chromeos/voice_search_ui.h" #include "components/proximity_auth/webui/proximity_auth_ui.h" #include "components/proximity_auth/webui/url_constants.h" #endif @@ -469,8 +468,6 @@ if (url.host_piece() == chrome::kChromeUISysInternalsHost && SysInternalsUI::IsEnabled()) return &NewWebUI<SysInternalsUI>; - if (url.host_piece() == chrome::kChromeUIVoiceSearchHost) - return &NewWebUI<VoiceSearchUI>; #if !defined(OFFICIAL_BUILD) if (!base::SysInfo::IsRunningOnChromeOS()) { if (url.host_piece() == chrome::kChromeUIDeviceEmulatorHost)
diff --git a/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.cc b/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.cc index 3e576f5..d88dd81 100644 --- a/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.cc +++ b/chrome/browser/ui/webui/chromeos/login/core_oobe_handler.cc
@@ -98,8 +98,7 @@ } } -CoreOobeHandler::~CoreOobeHandler() { -} +CoreOobeHandler::~CoreOobeHandler() {} void CoreOobeHandler::DeclareLocalizedValues( ::login::LocalizedValuesBuilder* builder) { @@ -153,16 +152,13 @@ } void CoreOobeHandler::RegisterMessages() { - AddCallback("screenStateInitialize", - &CoreOobeHandler::HandleInitialized); + AddCallback("screenStateInitialize", &CoreOobeHandler::HandleInitialized); AddCallback("skipUpdateEnrollAfterEula", &CoreOobeHandler::HandleSkipUpdateEnrollAfterEula); AddCallback("updateCurrentScreen", &CoreOobeHandler::HandleUpdateCurrentScreen); - AddCallback("enableHighContrast", - &CoreOobeHandler::HandleEnableHighContrast); - AddCallback("enableLargeCursor", - &CoreOobeHandler::HandleEnableLargeCursor); + AddCallback("enableHighContrast", &CoreOobeHandler::HandleEnableHighContrast); + AddCallback("enableLargeCursor", &CoreOobeHandler::HandleEnableLargeCursor); AddCallback("enableVirtualKeyboard", &CoreOobeHandler::HandleEnableVirtualKeyboard); AddCallback("enableScreenMagnifier", @@ -171,17 +167,14 @@ &CoreOobeHandler::HandleEnableSpokenFeedback); AddCallback("setDeviceRequisition", &CoreOobeHandler::HandleSetDeviceRequisition); - AddCallback("screenAssetsLoaded", - &CoreOobeHandler::HandleScreenAssetsLoaded); + AddCallback("screenAssetsLoaded", &CoreOobeHandler::HandleScreenAssetsLoaded); AddRawCallback("skipToLoginForTesting", &CoreOobeHandler::HandleSkipToLoginForTesting); - AddCallback("launchHelpApp", - &CoreOobeHandler::HandleLaunchHelpApp); + AddCallback("launchHelpApp", &CoreOobeHandler::HandleLaunchHelpApp); AddCallback("toggleResetScreen", &CoreOobeHandler::HandleToggleResetScreen); AddCallback("toggleEnableDebuggingScreen", &CoreOobeHandler::HandleEnableDebuggingScreen); - AddCallback("headerBarVisible", - &CoreOobeHandler::HandleHeaderBarVisible); + AddCallback("headerBarVisible", &CoreOobeHandler::HandleHeaderBarVisible); AddCallback("raiseTabKeyEvent", &CoreOobeHandler::HandleRaiseTabKeyEvent); AddCallback("setOobeBootstrappingSlave", &CoreOobeHandler::HandleSetOobeBootstrappingSlave); @@ -193,8 +186,8 @@ const std::string& help_link_text, HelpAppLauncher::HelpTopic help_topic_id) { LOG(ERROR) << "CoreOobeHandler::ShowSignInError: error_text=" << error_text; - CallJSOrDefer("showSignInError", login_attempts, error_text, - help_link_text, static_cast<int>(help_topic_id)); + CallJSOrDefer("showSignInError", login_attempts, error_text, help_link_text, + static_cast<int>(help_topic_id)); } void CoreOobeHandler::ShowTpmError() { @@ -234,8 +227,7 @@ void CoreOobeHandler::ShowEnableDebuggingScreen() { // Don't recreate WizardController if it already exists. - WizardController* wizard_controller = - WizardController::default_controller(); + WizardController* wizard_controller = WizardController::default_controller(); if (wizard_controller && !wizard_controller->login_screen_started()) { wizard_controller->AdvanceToScreen( OobeScreen::SCREEN_OOBE_ENABLE_DEBUGGING); @@ -349,8 +341,9 @@ void CoreOobeHandler::HandleEnableSpokenFeedback(bool /* enabled */) { // Checkbox is initialized on page init and updates when spoken feedback // setting is changed so just toggle spoken feedback here. - AccessibilityManager::Get()->ToggleSpokenFeedback( - ash::A11Y_NOTIFICATION_NONE); + AccessibilityManager* manager = AccessibilityManager::Get(); + manager->EnableSpokenFeedback(!manager->IsSpokenFeedbackEnabled(), + ash::A11Y_NOTIFICATION_NONE); } void CoreOobeHandler::HandleSetDeviceRequisition( @@ -371,7 +364,7 @@ // Exit Chrome to force the restart as soon as a new requisition is set. if (initial_requisition != - connector->GetDeviceCloudPolicyManager()->GetDeviceRequisition()) { + connector->GetDeviceCloudPolicyManager()->GetDeviceRequisition()) { chrome::AttemptRestart(); } } @@ -381,11 +374,10 @@ oobe_ui_->OnScreenAssetsLoaded(screen_async_load_id); } -void CoreOobeHandler::HandleSkipToLoginForTesting( - const base::ListValue* args) { +void CoreOobeHandler::HandleSkipToLoginForTesting(const base::ListValue* args) { LoginScreenContext context(args); if (WizardController::default_controller()) - WizardController::default_controller()->SkipToLoginForTesting(context); + WizardController::default_controller()->SkipToLoginForTesting(context); } void CoreOobeHandler::HandleToggleResetScreen() { @@ -435,8 +427,8 @@ void CoreOobeHandler::UpdateOobeUIVisibility() { const std::string& display = oobe_ui_->display_type(); CallJSOrDefer("showAPIKeysNotice", !google_apis::HasKeysConfigured() && - (display == OobeUI::kOobeDisplay || - display == OobeUI::kLoginDisplay)); + (display == OobeUI::kOobeDisplay || + display == OobeUI::kLoginDisplay)); // Don't show version label on the stable channel by default. bool should_show_version = true; @@ -456,8 +448,8 @@ UpdateLabel("version", os_version_label_text); } -void CoreOobeHandler::OnEnterpriseInfoUpdated( - const std::string& message_text, const std::string& asset_id) { +void CoreOobeHandler::OnEnterpriseInfoUpdated(const std::string& message_text, + const std::string& asset_id) { CallJSOrDefer("setEnterpriseInfo", message_text, asset_id); } @@ -489,9 +481,9 @@ keyboard::KeyboardController* keyboard_controller = keyboard::KeyboardController::GetInstance(); if (keyboard_controller) { - gfx::Rect bounds = keyboard_controller->current_keyboard_bounds(); - ShowControlBar(bounds.IsEmpty()); - SetVirtualKeyboardShown(!bounds.IsEmpty()); + const bool is_keyboard_shown = keyboard_controller->keyboard_visible(); + ShowControlBar(!is_keyboard_shown); + SetVirtualKeyboardShown(is_keyboard_shown); } }
diff --git a/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.cc b/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.cc index 8155f843..7b74243c 100644 --- a/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.cc +++ b/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.cc
@@ -601,7 +601,7 @@ cryptohome::MigrateToDircryptoRequest request; request.set_minimal_migration(IsMinimalMigration()); DBusThreadManager::Get()->GetCryptohomeClient()->AddObserver(this); - cryptohome::HomedirMethods::GetInstance()->MigrateToDircrypto( + DBusThreadManager::Get()->GetCryptohomeClient()->MigrateToDircrypto( cryptohome::Identification(user_context_.GetAccountId()), request, base::Bind(&EncryptionMigrationScreenHandler::OnMigrationRequested, weak_ptr_factory_.GetWeakPtr()));
diff --git a/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler_unittest.cc b/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler_unittest.cc index 585736b..de7754d 100644 --- a/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler_unittest.cc +++ b/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler_unittest.cc
@@ -110,6 +110,33 @@ int64_t free_disk_space_; }; +// Fake CryptohomeClient implementation for this test. +class TestCryptohomeClient : public FakeCryptohomeClient { + public: + TestCryptohomeClient() = default; + ~TestCryptohomeClient() override = default; + + const cryptohome::Identification& id() const { return id_; } + + const cryptohome::MigrateToDircryptoRequest& request() const { + return request_; + } + + void MigrateToDircrypto(const cryptohome::Identification& id, + const cryptohome::MigrateToDircryptoRequest& request, + VoidDBusMethodCallback callback) override { + id_ = id; + request_ = request; + FakeCryptohomeClient::MigrateToDircrypto(id, request, std::move(callback)); + } + + private: + cryptohome::Identification id_; + cryptohome::MigrateToDircryptoRequest request_; + + DISALLOW_COPY_AND_ASSIGN(TestCryptohomeClient); +}; + class EncryptionMigrationScreenHandlerTest : public testing::Test { public: EncryptionMigrationScreenHandlerTest() = default; @@ -119,7 +146,7 @@ // Set up a MockUserManager. MockUserManager* mock_user_manager = new NiceMock<MockUserManager>(); scoped_user_manager_enabler_ = - std::make_unique<user_manager::ScopedUserManager>( + base::MakeUnique<user_manager::ScopedUserManager>( base::WrapUnique(mock_user_manager)); // This is used by EncryptionMigrationScreenHandler to mount the existing @@ -136,10 +163,9 @@ mock_async_method_caller_); // Set up fake DBusThreadManager parts. - auto fake_cryptohome_client = base::MakeUnique<FakeCryptohomeClient>(); - fake_cryptohome_client_ = fake_cryptohome_client.get(); + fake_cryptohome_client_ = new TestCryptohomeClient(); DBusThreadManager::GetSetterForTesting()->SetCryptohomeClient( - std::move(fake_cryptohome_client)); + base::WrapUnique<CryptohomeClient>(fake_cryptohome_client_)); DBusThreadManager::GetSetterForTesting()->SetPowerManagerClient( base::MakeUnique<FakePowerManagerClient>()); @@ -179,6 +205,7 @@ // Sets up expectation that the existing user home will be mounted for // migration using |mock_homedir_methods_|. + // TODO(crbug.com/741274): Use the fake when homedir_methods is dead. void ExpectMountExistingVault(cryptohome::MountError mount_error) { EXPECT_CALL( *mock_homedir_methods_, @@ -195,34 +222,13 @@ }))); } - // Sets up expectation that migration will be started on - // |mock_homedir_methods_|. If |expect_minimal_migration| is true, verifies - // that minimal migration has been requested. - void ExpectStartMigration(bool expect_minimal_migration) { - EXPECT_CALL( - *mock_homedir_methods_, - MigrateToDircrypto(cryptohome::Identification( - user_context_.GetAccountId()) /* 0: id */, - _ /* 1: minimal_migration*/, _ /* 2: callback */)) - .WillOnce(WithArgs<1, 2>( - Invoke([expect_minimal_migration]( - const cryptohome::MigrateToDircryptoRequest request, - const cryptohome::HomedirMethods::DBusResultCallback& - callback) { - EXPECT_EQ(expect_minimal_migration, request.minimal_migration()); - // Call the callback immediately - actual result is sent later - // using DircryptoMigrationProgressHandler. - callback.Run(true /* success */); - }))); - } - protected: // Must be the first member. base::test::ScopedTaskEnvironment scoped_task_environment_; std::unique_ptr<user_manager::ScopedUserManager> scoped_user_manager_enabler_; cryptohome::MockHomedirMethods* mock_homedir_methods_ = nullptr; - FakeCryptohomeClient* fake_cryptohome_client_ = nullptr; + TestCryptohomeClient* fake_cryptohome_client_ = nullptr; cryptohome::MockAsyncMethodCaller* mock_async_method_caller_ = nullptr; std::unique_ptr<TestEncryptionMigrationScreenHandler> encryption_migration_screen_handler_; @@ -266,7 +272,6 @@ // Tests handling of a minimal migration run that finishes immediately. TEST_F(EncryptionMigrationScreenHandlerTest, MinimalMigration) { ExpectMountExistingVault(cryptohome::MountError::MOUNT_ERROR_NONE); - ExpectStartMigration(true /* minimal_migration */); encryption_migration_screen_handler_->SetMode( EncryptionMigrationMode::START_MINIMAL_MIGRATION); encryption_migration_screen_handler_->SetupInitialView(); @@ -284,6 +289,9 @@ EXPECT_TRUE(continue_login_callback_called_); EXPECT_FALSE( encryption_migration_screen_handler_->fake_wake_lock()->HasWakeLock()); + EXPECT_TRUE(fake_cryptohome_client_->request().minimal_migration()); + EXPECT_EQ(cryptohome::Identification(user_context_.GetAccountId()), + fake_cryptohome_client_->id()); } // Tests handling of a resumed minimal migration run. This should behave the @@ -291,7 +299,6 @@ // different, but we don't test that at the moment). TEST_F(EncryptionMigrationScreenHandlerTest, ResumeMinimalMigration) { ExpectMountExistingVault(cryptohome::MountError::MOUNT_ERROR_NONE); - ExpectStartMigration(true /* minimal_migration */); encryption_migration_screen_handler_->SetMode( EncryptionMigrationMode::RESUME_MINIMAL_MIGRATION); encryption_migration_screen_handler_->SetupInitialView(); @@ -305,6 +312,9 @@ 0 /* current */, 0 /* total */); EXPECT_TRUE(continue_login_callback_called_); + EXPECT_TRUE(fake_cryptohome_client_->request().minimal_migration()); + EXPECT_EQ(cryptohome::Identification(user_context_.GetAccountId()), + fake_cryptohome_client_->id()); } // Tests handling of a minimal migration run that takes a long time to finish. @@ -312,7 +322,6 @@ // re-enter their password. TEST_F(EncryptionMigrationScreenHandlerTest, MinimalMigrationSlow) { ExpectMountExistingVault(cryptohome::MountError::MOUNT_ERROR_NONE); - ExpectStartMigration(true /* minimal_migration */); encryption_migration_screen_handler_->SetMode( EncryptionMigrationMode::START_MINIMAL_MIGRATION); encryption_migration_screen_handler_->SetupInitialView(); @@ -328,12 +337,14 @@ 0 /* current */, 0 /* total */); EXPECT_TRUE(restart_login_callback_called_); + EXPECT_TRUE(fake_cryptohome_client_->request().minimal_migration()); + EXPECT_EQ(cryptohome::Identification(user_context_.GetAccountId()), + fake_cryptohome_client_->id()); } // Tests handling of a minimal migration run that fails. TEST_F(EncryptionMigrationScreenHandlerTest, MinimalMigrationFails) { ExpectMountExistingVault(cryptohome::MountError::MOUNT_ERROR_NONE); - ExpectStartMigration(true /* minimal_migration */); encryption_migration_screen_handler_->SetMode( EncryptionMigrationMode::START_MINIMAL_MIGRATION); encryption_migration_screen_handler_->SetupInitialView(); @@ -353,6 +364,9 @@ 0 /* current */, 0 /* total */); Mock::VerifyAndClearExpectations(mock_async_method_caller_); + EXPECT_TRUE(fake_cryptohome_client_->request().minimal_migration()); + EXPECT_EQ(cryptohome::Identification(user_context_.GetAccountId()), + fake_cryptohome_client_->id()); } } // namespace chromeos
diff --git a/chrome/browser/ui/webui/chromeos/voice_search_ui.cc b/chrome/browser/ui/webui/chromeos/voice_search_ui.cc deleted file mode 100644 index 8b6321c..0000000 --- a/chrome/browser/ui/webui/chromeos/voice_search_ui.cc +++ /dev/null
@@ -1,391 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/webui/chromeos/voice_search_ui.h" - -#include <memory> -#include <string> -#include <utility> - -#include "base/files/file_enumerator.h" -#include "base/macros.h" -#include "base/memory/weak_ptr.h" -#include "base/path_service.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/utf_string_conversions.h" -#include "base/task_scheduler/post_task.h" -#include "base/threading/thread_restrictions.h" -#include "chrome/browser/extensions/extension_service.h" -#include "chrome/browser/plugins/plugin_prefs.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/search/hotword_service.h" -#include "chrome/browser/search/hotword_service_factory.h" -#include "chrome/browser/ui/app_list/start_page_service.h" -#include "chrome/browser/ui/webui/version_handler.h" -#include "chrome/common/channel_info.h" -#include "chrome/common/chrome_content_client.h" -#include "chrome/common/chrome_paths.h" -#include "chrome/common/extensions/extension_constants.h" -#include "chrome/common/features.h" -#include "chrome/common/pref_names.h" -#include "chrome/common/url_constants.h" -#include "chrome/grit/browser_resources.h" -#include "chrome/grit/chromium_strings.h" -#include "chrome/grit/generated_resources.h" -#include "components/prefs/pref_service.h" -#include "components/strings/grit/components_strings.h" -#include "components/version_info/version_info.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/browser/plugin_service.h" -#include "content/public/browser/url_data_source.h" -#include "content/public/browser/web_ui.h" -#include "content/public/browser/web_ui_data_source.h" -#include "content/public/browser/web_ui_message_handler.h" -#include "content/public/common/user_agent.h" -#include "extensions/browser/extension_prefs.h" -#include "extensions/browser/extension_system.h" -#include "extensions/common/extension.h" -#include "extensions/features/features.h" -#include "ui/base/l10n/l10n_util.h" - -using base::ASCIIToUTF16; -using content::WebUIMessageHandler; - -namespace { - -content::WebUIDataSource* CreateVoiceSearchUiHtmlSource() { - content::WebUIDataSource* html_source = - content::WebUIDataSource::Create(chrome::kChromeUIVoiceSearchHost); - - html_source->AddLocalizedString("loadingMessage", - IDS_VOICESEARCH_LOADING_MESSAGE); - html_source->AddLocalizedString("voiceSearchLongTitle", - IDS_VOICESEARCH_TITLE_MESSAGE); - - html_source->SetJsonPath("strings.js"); - html_source->AddResourcePath("about_voicesearch.js", - IDR_ABOUT_VOICESEARCH_JS); - html_source->SetDefaultResource(IDR_ABOUT_VOICESEARCH_HTML); - return html_source; -} - -// Helper functions for collecting a list of key-value pairs that will -// be displayed. -void AddPair16(base::ListValue* list, - const base::string16& key, - const base::string16& value) { - auto results = std::make_unique<base::DictionaryValue>(); - results->SetString("key", key); - results->SetString("value", value); - list->Append(std::move(results)); -} - -void AddPair(base::ListValue* list, - const base::StringPiece& key, - const base::StringPiece& value) { - AddPair16(list, UTF8ToUTF16(key), UTF8ToUTF16(value)); -} - -void AddPairBool(base::ListValue* list, - const base::StringPiece& key, - bool value) { - AddPair(list, key, value ? "Yes" : "No"); -} - -// Generate an empty data-pair which acts as a line break. -void AddLineBreak(base::ListValue* list) { - AddPair(list, "", ""); -} - -void AddSharedModulePlatformsOnBlockingTaskRunner(base::ListValue* list, - const base::FilePath& path) { - base::AssertBlockingAllowed(); - - if (path.empty()) - return; - - // Display available platforms for shared module. - base::FilePath platforms_path = path.AppendASCII("_platform_specific"); - base::FileEnumerator enumerator(platforms_path, false, - base::FileEnumerator::DIRECTORIES); - base::string16 files; - for (base::FilePath name = enumerator.Next(); !name.empty(); - name = enumerator.Next()) { - files += name.BaseName().LossyDisplayName() + ASCIIToUTF16(" "); - } - AddPair16(list, ASCIIToUTF16("Shared Module Platforms"), - files.empty() ? ASCIIToUTF16("undefined") : files); - AddLineBreak(list); -} - -//////////////////////////////////////////////////////////////////////////////// -// -// VoiceSearchDomHandler -// -//////////////////////////////////////////////////////////////////////////////// - -// The handler for Javascript messages for the about:flags page. -class VoiceSearchDomHandler : public WebUIMessageHandler { - public: - explicit VoiceSearchDomHandler(Profile* profile) - : profile_(profile), weak_factory_(this) {} - - ~VoiceSearchDomHandler() override {} - - // WebUIMessageHandler implementation. - void RegisterMessages() override { - web_ui()->RegisterMessageCallback( - "requestVoiceSearchInfo", - base::Bind(&VoiceSearchDomHandler::HandleRequestVoiceSearchInfo, - base::Unretained(this))); - } - - private: - // Callback for the "requestVoiceSearchInfo" message. No arguments. - void HandleRequestVoiceSearchInfo(const base::ListValue* args) { - PopulatePageInformation(); - } - - void ReturnVoiceSearchInfo(std::unique_ptr<base::ListValue> info) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - DCHECK(info); - base::DictionaryValue voiceSearchInfo; - voiceSearchInfo.Set("voiceSearchInfo", std::move(info)); - web_ui()->CallJavascriptFunctionUnsafe("returnVoiceSearchInfo", - voiceSearchInfo); - } - - // Fill in the data to be displayed on the page. - void PopulatePageInformation() { - // Store Key-Value pairs of about-information. - auto list = std::make_unique<base::ListValue>(); - - // Populate information. - AddOperatingSystemInfo(list.get()); - AddAudioInfo(list.get()); - AddLanguageInfo(list.get()); - AddHotwordInfo(list.get()); - AddAppListInfo(list.get()); - - AddExtensionInfo(extension_misc::kHotwordNewExtensionId, "Extension", - list.get()); - - AddExtensionInfo(extension_misc::kHotwordSharedModuleId, "Shared Module", - list.get()); - - base::FilePath path; - extensions::ExtensionSystem* extension_system = - extensions::ExtensionSystem::Get(profile_); - if (extension_system) { - ExtensionService* extension_service = - extension_system->extension_service(); - const extensions::Extension* extension = - extension_service->GetExtensionById( - extension_misc::kHotwordSharedModuleId, true); - if (extension) - path = extension->path(); - } - base::ListValue* raw_list = list.get(); - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::TaskPriority::USER_VISIBLE, base::MayBlock()}, - base::BindOnce(&AddSharedModulePlatformsOnBlockingTaskRunner, raw_list, - path), - base::BindOnce(&VoiceSearchDomHandler::ReturnVoiceSearchInfo, - weak_factory_.GetWeakPtr(), - base::Passed(std::move(list)))); - } - - // Adds information regarding the system and chrome version info to list. - void AddOperatingSystemInfo(base::ListValue* list) { - // Obtain the Chrome version info. - AddPair(list, l10n_util::GetStringUTF8(IDS_PRODUCT_NAME), - version_info::GetVersionNumber() + " (" + - chrome::GetChannelString() + ")"); - - // OS version information. - std::string os_label = version_info::GetOSType(); - AddPair(list, l10n_util::GetStringUTF8(IDS_VERSION_UI_OS), os_label); - - AddLineBreak(list); - } - - // Adds information regarding audio to the list. - void AddAudioInfo(base::ListValue* list) { - // NaCl and its associated functions are not available on most mobile - // platforms. ENABLE_EXTENSIONS covers those platforms and hey would not - // allow Hotwording anyways since it is an extension. - std::string nacl_enabled = "not available"; - nacl_enabled = "No"; - // Determine if NaCl is available. - base::FilePath path; - if (PathService::Get(chrome::FILE_NACL_PLUGIN, &path)) { - content::WebPluginInfo info; - PluginPrefs* plugin_prefs = PluginPrefs::GetForProfile(profile_).get(); - if (content::PluginService::GetInstance()->GetPluginInfoByPath(path, - &info) && - plugin_prefs->IsPluginEnabled(info)) { - nacl_enabled = "Yes"; - } - } - - AddPair(list, "NaCl Enabled", nacl_enabled); - - HotwordService* hotword_service = - HotwordServiceFactory::GetForProfile(profile_); - AddPairBool(list, "Microphone Present", - hotword_service && hotword_service->microphone_available()); - - AddPairBool(list, "Audio Capture Allowed", - profile_->GetPrefs()->GetBoolean(prefs::kAudioCaptureAllowed)); - - AddLineBreak(list); - } - - // Adds information regarding languages to the list. - void AddLanguageInfo(base::ListValue* list) { - std::string locale = - profile_->GetPrefs()->GetString(prefs::kApplicationLocale); - AddPair(list, "Current Language", locale); - AddPair(list, "Hotword Previous Language", - profile_->GetPrefs()->GetString(prefs::kHotwordPreviousLanguage)); - - AddLineBreak(list); - } - - // Adds information specific to the hotword configuration to the list. - void AddHotwordInfo(base::ListValue* list) { - HotwordService* hotword_service = - HotwordServiceFactory::GetForProfile(profile_); - AddPairBool(list, "Hotword Module Installable", - hotword_service && hotword_service->IsHotwordAllowed()); - - AddPairBool(list, "Hotword Search Enabled", - profile_->GetPrefs()->GetBoolean(prefs::kHotwordSearchEnabled)); - - AddPairBool( - list, "Always-on Hotword Search Enabled", - profile_->GetPrefs()->GetBoolean(prefs::kHotwordAlwaysOnSearchEnabled)); - - AddPairBool(list, "Hotword Audio Logging Enabled", - hotword_service && hotword_service->IsOptedIntoAudioLogging()); - - AddLineBreak(list); - } - - // Adds information specific to an extension to the list. - void AddExtensionInfo(const std::string& extension_id, - const std::string& name_prefix, - base::ListValue* list) { - DCHECK(!name_prefix.empty()); - std::string version("undefined"); - std::string id("undefined"); - base::FilePath path; - - extensions::ExtensionSystem* extension_system = - extensions::ExtensionSystem::Get(profile_); - if (extension_system) { - ExtensionService* extension_service = - extension_system->extension_service(); - const extensions::Extension* extension = - extension_service->GetExtensionById(extension_id, true); - if (extension) { - id = extension->id(); - version = extension->VersionString(); - path = extension->path(); - } - } - AddPair(list, name_prefix + " Id", id); - AddPair(list, name_prefix + " Version", version); - AddPair16( - list, ASCIIToUTF16(name_prefix + " Path"), - path.empty() ? ASCIIToUTF16("undefined") : path.LossyDisplayName()); - - extensions::ExtensionPrefs* extension_prefs = - extensions::ExtensionPrefs::Get(profile_); - int pref_state = -1; - extension_prefs->ReadPrefAsInteger(extension_id, "state", &pref_state); - std::string state; - switch (pref_state) { - case extensions::Extension::DISABLED: - state = "DISABLED"; - break; - case extensions::Extension::ENABLED: - state = "ENABLED"; - break; - case extensions::Extension::EXTERNAL_EXTENSION_UNINSTALLED: - state = "EXTERNAL_EXTENSION_UNINSTALLED"; - break; - default: - state = "undefined"; - } - - AddPair(list, name_prefix + " State", state); - - AddLineBreak(list); - } - - // Adds information specific to voice search in the app launcher to the list. - void AddAppListInfo(base::ListValue* list) { -#if BUILDFLAG(ENABLE_APP_LIST) - std::string state = "No Start Page Service"; - app_list::StartPageService* start_page_service = - app_list::StartPageService::Get(profile_); - if (start_page_service) { - app_list::SpeechRecognitionState speech_state = - start_page_service->state(); - switch (speech_state) { - case app_list::SPEECH_RECOGNITION_OFF: - state = "SPEECH_RECOGNITION_OFF"; - break; - case app_list::SPEECH_RECOGNITION_READY: - state = "SPEECH_RECOGNITION_READY"; - break; - case app_list::SPEECH_RECOGNITION_HOTWORD_LISTENING: - state = "SPEECH_RECOGNITION_HOTWORD_LISTENING"; - break; - case app_list::SPEECH_RECOGNITION_RECOGNIZING: - state = "SPEECH_RECOGNITION_RECOGNIZING"; - break; - case app_list::SPEECH_RECOGNITION_IN_SPEECH: - state = "SPEECH_RECOGNITION_IN_SPEECH"; - break; - case app_list::SPEECH_RECOGNITION_STOPPING: - state = "SPEECH_RECOGNITION_STOPPING"; - break; - case app_list::SPEECH_RECOGNITION_NETWORK_ERROR: - state = "SPEECH_RECOGNITION_NETWORK_ERROR"; - break; - default: - state = "undefined"; - } - } - AddPair(list, "Start Page State", state); - AddLineBreak(list); -#endif - } - - Profile* const profile_; - base::WeakPtrFactory<VoiceSearchDomHandler> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(VoiceSearchDomHandler); -}; - -} // namespace - -/////////////////////////////////////////////////////////////////////////////// -// -// VoiceSearchUI -// -/////////////////////////////////////////////////////////////////////////////// - -VoiceSearchUI::VoiceSearchUI(content::WebUI* web_ui) - : content::WebUIController(web_ui) { - Profile* profile = Profile::FromWebUI(web_ui); - web_ui->AddMessageHandler(std::make_unique<VoiceSearchDomHandler>(profile)); - - // Set up the about:voicesearch source. - content::WebUIDataSource::Add(profile, CreateVoiceSearchUiHtmlSource()); -} - -VoiceSearchUI::~VoiceSearchUI() {}
diff --git a/chrome/browser/ui/webui/chromeos/voice_search_ui.h b/chrome/browser/ui/webui/chromeos/voice_search_ui.h deleted file mode 100644 index d3e5044..0000000 --- a/chrome/browser/ui/webui/chromeos/voice_search_ui.h +++ /dev/null
@@ -1,21 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_VOICE_SEARCH_UI_H_ -#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_VOICE_SEARCH_UI_H_ - -#include "base/macros.h" -#include "content/public/browser/web_ui_controller.h" - -// The WebUI handler for chrome://voicesearch. -class VoiceSearchUI : public content::WebUIController { - public: - explicit VoiceSearchUI(content::WebUI* web_ui); - ~VoiceSearchUI() override; - - private: - DISALLOW_COPY_AND_ASSIGN(VoiceSearchUI); -}; - -#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_VOICE_SEARCH_UI_H_
diff --git a/chrome/browser/ui/webui/extensions/extensions_ui.cc b/chrome/browser/ui/webui/extensions/extensions_ui.cc index bc1c3ba..5b80460 100644 --- a/chrome/browser/ui/webui/extensions/extensions_ui.cc +++ b/chrome/browser/ui/webui/extensions/extensions_ui.cc
@@ -143,6 +143,7 @@ source->AddLocalizedString("appsTitle", IDS_MD_EXTENSIONS_APPS_TITLE); source->AddLocalizedString("noExtensionsOrApps", IDS_MD_EXTENSIONS_NO_INSTALLED_ITEMS); + source->AddLocalizedString("noDescription", IDS_MD_EXTENSIONS_NO_DESCRIPTION); source->AddLocalizedString("noSearchResults", IDS_MD_EXTENSIONS_NO_SEARCH_RESULTS); source->AddLocalizedString("dropToInstall",
diff --git a/chrome/browser/ui/webui/settings/chromeos/internet_handler.cc b/chrome/browser/ui/webui/settings/chromeos/internet_handler.cc index ac139cee..38cb47f 100644 --- a/chrome/browser/ui/webui/settings/chromeos/internet_handler.cc +++ b/chrome/browser/ui/webui/settings/chromeos/internet_handler.cc
@@ -4,19 +4,28 @@ #include "chrome/browser/ui/webui/settings/chromeos/internet_handler.h" +#include <vector> + #include "base/bind.h" #include "base/values.h" #include "chrome/browser/chromeos/options/network_config_view.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h" +#include "chrome/browser/ui/app_list/arc/arc_app_utils.h" #include "chromeos/network/network_state.h" #include "chromeos/network/network_state_handler.h" +#include "components/arc/arc_bridge_service.h" +#include "components/arc/arc_service_manager.h" +#include "components/arc/common/net.mojom.h" +#include "components/arc/connection_holder.h" #include "components/onc/onc_constants.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "extensions/browser/api/vpn_provider/vpn_service.h" #include "extensions/browser/api/vpn_provider/vpn_service_factory.h" #include "third_party/cros_system_api/dbus/service_constants.h" +#include "ui/events/event_constants.h" namespace chromeos { @@ -24,6 +33,8 @@ const char kAddNetworkMessage[] = "addNetwork"; const char kConfigureNetworkMessage[] = "configureNetwork"; +const char kRequestArcVpnProviders[] = "requestArcVpnProviders"; +const char kSendArcVpnProviders[] = "sendArcVpnProviders"; std::string ServicePathFromGuid(const std::string& guid) { const NetworkState* network = @@ -37,13 +48,33 @@ user_manager::UserManager::Get()->GetPrimaryUser()); } +std::unique_ptr<base::DictionaryValue> ArcVpnProviderToValue( + const app_list::ArcVpnProviderManager::ArcVpnProvider* arc_vpn_provider) { + std::unique_ptr<base::DictionaryValue> serialized_entry = + std::make_unique<base::DictionaryValue>(); + serialized_entry->SetString("PackageName", arc_vpn_provider->package_name); + serialized_entry->SetString("ProviderName", arc_vpn_provider->app_name); + serialized_entry->SetString("AppID", arc_vpn_provider->app_id); + serialized_entry->SetDouble("LastLaunchTime", + arc_vpn_provider->last_launch_time.ToDoubleT()); + return serialized_entry; +} + } // namespace namespace settings { -InternetHandler::InternetHandler() {} +InternetHandler::InternetHandler(Profile* profile) : profile_(profile) { + DCHECK(profile_); + arc_vpn_provider_manager_ = app_list::ArcVpnProviderManager::Get(profile_); + if (arc_vpn_provider_manager_) + arc_vpn_provider_manager_->AddObserver(this); +} -InternetHandler::~InternetHandler() {} +InternetHandler::~InternetHandler() { + if (arc_vpn_provider_manager_) + arc_vpn_provider_manager_->RemoveObserver(this); +} void InternetHandler::RegisterMessages() { // TODO(stevenjb): Eliminate once network configuration UI is integrated @@ -54,12 +85,37 @@ web_ui()->RegisterMessageCallback( kConfigureNetworkMessage, base::Bind(&InternetHandler::ConfigureNetwork, base::Unretained(this))); + web_ui()->RegisterMessageCallback( + kRequestArcVpnProviders, + base::Bind(&InternetHandler::RequestArcVpnProviders, + base::Unretained(this))); } void InternetHandler::OnJavascriptAllowed() {} void InternetHandler::OnJavascriptDisallowed() {} +void InternetHandler::OnArcVpnProviderRemoved(const std::string& package_name) { + if (arc_vpn_providers_.find(package_name) == arc_vpn_providers_.end()) + return; + arc_vpn_providers_.erase(package_name); + SendArcVpnProviders(); +} + +void InternetHandler::OnArcVpnProvidersRefreshed( + const std::vector< + std::unique_ptr<app_list::ArcVpnProviderManager::ArcVpnProvider>>& + arc_vpn_providers) { + SetArcVpnProviders(arc_vpn_providers); +} + +void InternetHandler::OnArcVpnProviderUpdated( + app_list::ArcVpnProviderManager::ArcVpnProvider* arc_vpn_provider) { + arc_vpn_providers_[arc_vpn_provider->package_name] = + ArcVpnProviderToValue(arc_vpn_provider); + SendArcVpnProviders(); +} + void InternetHandler::AddNetwork(const base::ListValue* args) { std::string onc_type; if (args->GetSize() < 1 || !args->GetString(0, &onc_type)) { @@ -68,18 +124,24 @@ } if (onc_type == ::onc::network_type::kVPN) { - std::string extension_id; + std::string app_id; if (args->GetSize() >= 2) - args->GetString(1, &extension_id); - if (extension_id.empty()) { + args->GetString(1, &app_id); + if (app_id.empty()) { // Show the "add network" dialog for the built-in OpenVPN/L2TP provider. NetworkConfigView::ShowForType(shill::kTypeVPN); return; } + // Request to launch Arc VPN provider. + const auto* arc_app_list_prefs = ArcAppListPrefs::Get(profile_); + if (arc_app_list_prefs && arc_app_list_prefs->GetApp(app_id)) { + arc::LaunchApp(profile_, app_id, ui::EF_NONE); + return; + } // Request that the third-party VPN provider identified by |provider_id| // show its "add network" dialog. VpnServiceFactory::GetForBrowserContext(GetProfileForPrimaryUser()) - ->SendShowAddDialogToExtension(extension_id); + ->SendShowAddDialogToExtension(app_id); } else if (onc_type == ::onc::network_type::kWiFi) { NetworkConfigView::ShowForType(shill::kTypeWifi); } else { @@ -108,19 +170,64 @@ return; } - if (network->type() == shill::kTypeVPN && - network->vpn_provider_type() == shill::kProviderThirdPartyVpn) { - // Request that the third-party VPN provider used by the |network| show a - // configuration dialog for it. - VpnServiceFactory::GetForBrowserContext(GetProfileForPrimaryUser()) - ->SendShowConfigureDialogToExtension(network->vpn_provider_id(), - network->name()); - return; + if (network->type() == shill::kTypeVPN) { + if (profile_ != GetProfileForPrimaryUser()) + return; + + if (network->vpn_provider_type() == shill::kProviderThirdPartyVpn) { + // Request that the third-party VPN provider used by the |network| show a + // configuration dialog for it. + VpnServiceFactory::GetForBrowserContext(profile_) + ->SendShowConfigureDialogToExtension(network->vpn_provider_id(), + network->name()); + return; + } else if (network->vpn_provider_type() == shill::kProviderArcVpn) { + auto* net_instance = ARC_GET_INSTANCE_FOR_METHOD( + arc::ArcServiceManager::Get()->arc_bridge_service()->net(), + ConfigureAndroidVpn); + if (!net_instance) { + LOG(ERROR) << "User requested VPN configuration but API is unavailable"; + return; + } + net_instance->ConfigureAndroidVpn(); + return; + } } NetworkConfigView::ShowForNetworkId(network->guid()); } +void InternetHandler::RequestArcVpnProviders(const base::ListValue* args) { + if (!arc_vpn_provider_manager_) + return; + + AllowJavascript(); + SetArcVpnProviders(arc_vpn_provider_manager_->GetArcVpnProviders()); +} + +void InternetHandler::SetArcVpnProviders( + const std::vector< + std::unique_ptr<app_list::ArcVpnProviderManager::ArcVpnProvider>>& + arc_vpn_providers) { + arc_vpn_providers_.clear(); + for (const auto& arc_vpn_provider : arc_vpn_providers) { + arc_vpn_providers_[arc_vpn_provider->package_name] = + ArcVpnProviderToValue(arc_vpn_provider.get()); + } + SendArcVpnProviders(); +} + +void InternetHandler::SendArcVpnProviders() { + if (!IsJavascriptAllowed()) + return; + + base::ListValue arc_vpn_providers_value; + for (const auto& iter : arc_vpn_providers_) { + arc_vpn_providers_value.GetList().push_back(iter.second->Clone()); + } + FireWebUIListener(kSendArcVpnProviders, arc_vpn_providers_value); +} + gfx::NativeWindow InternetHandler::GetNativeWindow() const { return web_ui()->GetWebContents()->GetTopLevelNativeWindow(); }
diff --git a/chrome/browser/ui/webui/settings/chromeos/internet_handler.h b/chrome/browser/ui/webui/settings/chromeos/internet_handler.h index 64ceabfe..9b84562 100644 --- a/chrome/browser/ui/webui/settings/chromeos/internet_handler.h +++ b/chrome/browser/ui/webui/settings/chromeos/internet_handler.h
@@ -8,16 +8,22 @@ #include <memory> #include "base/macros.h" +#include "chrome/browser/ui/app_list/arc/arc_vpn_provider_manager.h" #include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" #include "ui/gfx/native_widget_types.h" +class Profile; + namespace chromeos { namespace settings { // Chrome OS Internet settings page UI handler. -class InternetHandler : public ::settings::SettingsPageUIHandler { +// TODO(lgcheng/stevenjb): Rename this ThirdPartyVpnHandler once configuration +// is handled in the Settings UI (crbug.com/380937 +class InternetHandler : public app_list::ArcVpnProviderManager::Observer, + public ::settings::SettingsPageUIHandler { public: - InternetHandler(); + explicit InternetHandler(Profile* profile); ~InternetHandler() override; // SettingsPageUIHandler implementation. @@ -25,13 +31,39 @@ void OnJavascriptAllowed() override; void OnJavascriptDisallowed() override; + // app_list::ArcVpnProviderManager::Observer: + void OnArcVpnProvidersRefreshed( + const std::vector< + std::unique_ptr<app_list::ArcVpnProviderManager::ArcVpnProvider>>& + arc_vpn_providers) override; + void OnArcVpnProviderRemoved(const std::string& package_name) override; + void OnArcVpnProviderUpdated(app_list::ArcVpnProviderManager::ArcVpnProvider* + arc_vpn_provider) override; + private: // Settings JS handlers. void AddNetwork(const base::ListValue* args); void ConfigureNetwork(const base::ListValue* args); + void RequestArcVpnProviders(const base::ListValue* args); + + // Sets list of Arc Vpn providers. + void SetArcVpnProviders( + const std::vector< + std::unique_ptr<app_list::ArcVpnProviderManager::ArcVpnProvider>>& + arc_vpn_providers); + + // Sends list of Arc Vpn providers to Chrome://settings. + void SendArcVpnProviders(); gfx::NativeWindow GetNativeWindow() const; + std::map<std::string, std::unique_ptr<base::DictionaryValue>> + arc_vpn_providers_; + + Profile* const profile_; + + app_list::ArcVpnProviderManager* arc_vpn_provider_manager_; + DISALLOW_COPY_AND_ASSIGN(InternetHandler); };
diff --git a/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc b/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc index a7c1486..21a58367 100644 --- a/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc +++ b/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc
@@ -977,6 +977,8 @@ IDS_SETTINGS_INTERNET_ADD_CONNECTION_NOT_ALLOWED}, {"internetAddThirdPartyVPN", IDS_SETTINGS_INTERNET_ADD_THIRD_PARTY_VPN}, {"internetAddVPN", IDS_SETTINGS_INTERNET_ADD_VPN}, + {"internetAddArcVPN", IDS_SETTINGS_INTERNET_ADD_ARC_VPN}, + {"internetAddArcVPNProvider", IDS_SETTINGS_INTERNET_ADD_ARC_VPN_PROVIDER}, {"internetAddWiFi", IDS_SETTINGS_INTERNET_ADD_WIFI}, {"internetConfigName", IDS_SETTINGS_INTERNET_CONFIG_NAME}, {"internetDetailPageTitle", IDS_SETTINGS_INTERNET_DETAIL}, @@ -1680,7 +1682,6 @@ {"searchPageTitle", IDS_SETTINGS_SEARCH}, #endif {"searchEnginesManage", IDS_SETTINGS_SEARCH_MANAGE_SEARCH_ENGINES}, - {"searchOkGoogleLabel", IDS_SETTINGS_SEARCH_OK_GOOGLE_LABEL}, #if defined(OS_CHROMEOS) {"searchGoogleAssistant", IDS_SETTINGS_SEARCH_GOOGLE_ASSISTANT}, {"searchGoogleAssistantEnabled", @@ -1689,25 +1690,9 @@ IDS_SETTINGS_SEARCH_GOOGLE_ASSISTANT_DISABLED}, {"assistantTurnOn", IDS_SETTINGS_SEARCH_GOOGLE_ASSISTANT_TURN_ON}, #endif - {"searchOkGoogleSubtextAlwaysOn", - IDS_SETTINGS_SEARCH_OK_GOOGLE_SUBTEXT_ALWAYS_ON}, - {"searchOkGoogleSubtextNoHardware", - IDS_SETTINGS_SEARCH_OK_GOOGLE_SUBTEXT_NO_HARDWARE}, - {"searchOkGoogleAudioHistoryLabel", - IDS_SETTINGS_SEARCH_OK_GOOGLE_AUDIO_HISTORY_LABEL}, - {"searchOkGoogleAudioHistorySubtext", - IDS_SETTINGS_SEARCH_OK_GOOGLE_AUDIO_HISTORY_SUBTEXT}, - {"searchOkGoogleRetrain", IDS_SETTINGS_SEARCH_OK_GOOGLE_RETRAIN}, -#if defined(OS_CHROMEOS) - {"searchOkGoogleDisabled", IDS_SETTINGS_SEARCH_OK_GOOGLE_DISABLED}, -#endif }; AddLocalizedStringsBulk(html_source, localized_strings, arraysize(localized_strings)); - html_source->AddString("hotwordLearnMoreUrl", - chrome::kHotwordLearnMoreURL); - html_source->AddString("manageAudioHistoryUrl", - chrome::kManageAudioHistoryURL); base::string16 search_explanation_text = l10n_util::GetStringFUTF16( IDS_SETTINGS_SEARCH_EXPLANATION, base::ASCIIToUTF16(chrome::kOmniboxLearnMoreURL));
diff --git a/chrome/browser/ui/webui/settings/md_settings_ui.cc b/chrome/browser/ui/webui/settings/md_settings_ui.cc index 455d1af..6c23035 100644 --- a/chrome/browser/ui/webui/settings/md_settings_ui.cc +++ b/chrome/browser/ui/webui/settings/md_settings_ui.cc
@@ -181,7 +181,7 @@ AddSettingsPageUIHandler( base::MakeUnique<chromeos::settings::StylusHandler>()); AddSettingsPageUIHandler( - base::MakeUnique<chromeos::settings::InternetHandler>()); + base::MakeUnique<chromeos::settings::InternetHandler>(profile)); #else AddSettingsPageUIHandler(base::MakeUnique<DefaultBrowserHandler>(web_ui)); AddSettingsPageUIHandler(base::MakeUnique<ManageProfileHandler>(profile));
diff --git a/chrome/browser/ui/webui/settings/search_engines_handler.cc b/chrome/browser/ui/webui/settings/search_engines_handler.cc index 3f932cd6..a283cd8 100644 --- a/chrome/browser/ui/webui/settings/search_engines_handler.cc +++ b/chrome/browser/ui/webui/settings/search_engines_handler.cc
@@ -4,6 +4,8 @@ #include "chrome/browser/ui/webui/settings/search_engines_handler.h" +#include <algorithm> +#include <string> #include <utility> #include "base/bind.h" @@ -15,9 +17,6 @@ #include "base/values.h" #include "chrome/browser/extensions/extension_util.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/search/hotword_audio_history_handler.h" -#include "chrome/browser/search/hotword_service.h" -#include "chrome/browser/search/hotword_service_factory.h" #include "chrome/browser/search_engines/template_url_service_factory.h" #include "chrome/browser/search_engines/ui_thread_search_terms_data.h" #include "chrome/browser/signin/signin_manager_factory.h" @@ -43,35 +42,9 @@ const char kKeywordField[] = "keyword"; const char kQueryUrlField[] = "queryUrl"; -// Fields for hotwordUpdateInfo result. -const char kHotwordSatusAllowed[] = "allowed"; -const char kHotwordSatusEnabled[] = "enabled"; -const char kHotwordStatusAlwaysOn[] = "alwaysOn"; -const char kHotwordSatusErrorMessage[] = "errorMessage"; -const char kHotwordSatusUserUserName[] = "userName"; -const char kHotwordSatusHistoryEnabled[] = "historyEnabled"; - // Dummy number used for indicating that a new search engine is added. const int kNewSearchEngineIndex = -1; -bool IsGoogleDefaultSearch(Profile* profile) { - TemplateURLService* template_url_service = - TemplateURLServiceFactory::GetForProfile(profile); - if (!template_url_service) - return false; - const TemplateURL* url_template = - template_url_service->GetDefaultSearchProvider(); - return url_template && - url_template->url_ref().HasGoogleBaseURLs( - template_url_service->search_terms_data()); -} - -bool GetHotwordAlwaysOn(Profile* profile) { - SigninManagerBase* signin = SigninManagerFactory::GetForProfile(profile); - return signin && signin->IsAuthenticated() && - HotwordServiceFactory::IsAlwaysOnAvailable(); -} - } // namespace namespace settings { @@ -116,23 +89,10 @@ "searchEngineEditCompleted", base::Bind(&SearchEnginesHandler::HandleSearchEngineEditCompleted, base::Unretained(this))); - web_ui()->RegisterMessageCallback( - "getHotwordInfo", base::Bind(&SearchEnginesHandler::HandleGetHotwordInfo, - base::Unretained(this))); - web_ui()->RegisterMessageCallback( - "setHotwordSearchEnabled", - base::Bind(&SearchEnginesHandler::HandleSetHotwordSearchEnabled, - base::Unretained(this))); } void SearchEnginesHandler::OnJavascriptAllowed() { list_controller_.table_model()->SetObserver(this); - pref_change_registrar_.Add(prefs::kHotwordSearchEnabled, - base::Bind(&SearchEnginesHandler::SendHotwordInfo, - base::Unretained(this))); - pref_change_registrar_.Add(prefs::kHotwordAlwaysOnSearchEnabled, - base::Bind(&SearchEnginesHandler::SendHotwordInfo, - base::Unretained(this))); } void SearchEnginesHandler::OnJavascriptDisallowed() { @@ -274,18 +234,6 @@ list_controller_.MakeDefaultTemplateURL(index); - // If the new search engine is not Google, disable hotword search. - // TODO(stevenjb): Investigate migrating this logic to - // MakeDefaultTemplateURL. - if (!IsGoogleDefaultSearch(profile_)) { - HotwordService* hotword_service = - HotwordServiceFactory::GetForProfile(profile_); - if (hotword_service) - hotword_service->DisableHotwordPreferences(); - } - // Hotword status may have changed. - SendHotwordInfo(); - base::RecordAction(base::UserMetricsAction("Options_SearchEngineSetDefault")); } @@ -399,137 +347,4 @@ } } -void SearchEnginesHandler::HandleGetHotwordInfo(const base::ListValue* args) { - AllowJavascript(); - - std::unique_ptr<base::Value> callback_id; - if (args) { - CHECK_EQ(1U, args->GetSize()); - const base::Value* id; - CHECK(args->Get(0, &id)); - callback_id = id->CreateDeepCopy(); - } - - std::unique_ptr<base::DictionaryValue> status = GetHotwordInfo(); - bool enabled = false; - status->GetBoolean(kHotwordSatusEnabled, &enabled); - bool always_on = false; - status->GetBoolean(kHotwordStatusAlwaysOn, &always_on); - if (!enabled || !always_on) { - HotwordInfoComplete(callback_id.get(), *status); - return; - } - - // OnGetHotwordAudioHistoryEnabled will call HotwordInfoComplete(). - HotwordServiceFactory::GetForProfile(profile_) - ->GetAudioHistoryHandler() - ->GetAudioHistoryEnabled( - base::Bind(&SearchEnginesHandler::OnGetHotwordAudioHistoryEnabled, - weak_ptr_factory_.GetWeakPtr(), base::Passed(&callback_id), - base::Passed(&status))); -} - -std::unique_ptr<base::DictionaryValue> SearchEnginesHandler::GetHotwordInfo() { - auto status = base::MakeUnique<base::DictionaryValue>(); - if (!IsGoogleDefaultSearch(profile_)) { - status->SetBoolean(kHotwordSatusAllowed, false); - return status; - } - - status->SetBoolean(kHotwordSatusAllowed, - HotwordServiceFactory::IsHotwordAllowed(profile_)); - - HotwordServiceFactory::IsServiceAvailable(profile_); // Update error value. - int hotword_error = HotwordServiceFactory::GetCurrentError(profile_); - if (hotword_error) { - base::string16 hotword_error_message; - if (hotword_error != IDS_HOTWORD_GENERIC_ERROR_MESSAGE) { - hotword_error_message = l10n_util::GetStringUTF16(hotword_error); - } else { - hotword_error_message = l10n_util::GetStringFUTF16( - hotword_error, base::ASCIIToUTF16(chrome::kHotwordLearnMoreURL)); - } - status->SetString(kHotwordSatusErrorMessage, hotword_error_message); - } - - if (!HotwordServiceFactory::GetForProfile(profile_)) { - status->SetBoolean(kHotwordSatusEnabled, false); - return status; - } - - bool always_on = GetHotwordAlwaysOn(profile_); - status->SetBoolean(kHotwordStatusAlwaysOn, always_on); - - std::string pref_name = always_on ? prefs::kHotwordAlwaysOnSearchEnabled - : prefs::kHotwordSearchEnabled; - bool enabled = profile_->GetPrefs()->GetBoolean(pref_name); - status->SetBoolean(kHotwordSatusEnabled, enabled); - if (!enabled) - return status; - - SigninManagerBase* signin = SigninManagerFactory::GetForProfile(profile_); - std::string user_display_name = - signin ? signin->GetAuthenticatedAccountInfo().email : ""; - status->SetString(kHotwordSatusUserUserName, user_display_name); - return status; -} - -void SearchEnginesHandler::OnGetHotwordAudioHistoryEnabled( - std::unique_ptr<base::Value> callback_id, - std::unique_ptr<base::DictionaryValue> status, - bool success, - bool logging_enabled) { - if (success) - status->SetBoolean(kHotwordSatusHistoryEnabled, logging_enabled); - HotwordInfoComplete(callback_id.get(), *status); -} - -void SearchEnginesHandler::HotwordInfoComplete( - const base::Value* callback_id, - const base::DictionaryValue& status) { - if (callback_id) - ResolveJavascriptCallback(*callback_id, status); - else - FireWebUIListener("hotword-info-update", status); -} - -void SearchEnginesHandler::SendHotwordInfo() { - HandleGetHotwordInfo(nullptr); -} - -void SearchEnginesHandler::HandleSetHotwordSearchEnabled( - const base::ListValue* args) { - CHECK_EQ(1U, args->GetSize()); - bool enabled; - CHECK(args->GetBoolean(0, &enabled)); - - bool always_on = GetHotwordAlwaysOn(profile_); - if (!always_on) { - profile_->GetPrefs()->SetBoolean(prefs::kHotwordSearchEnabled, enabled); - return; - } - - HotwordService* hotword_service = - HotwordServiceFactory::GetForProfile(profile_); - if (!enabled || !hotword_service) { - profile_->GetPrefs()->SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, - false); - return; - } - - bool was_enabled = - profile_->GetPrefs()->GetBoolean(prefs::kHotwordAlwaysOnSearchEnabled); - HotwordService::LaunchMode launch_mode; - if (was_enabled) { - launch_mode = HotwordService::RETRAIN; - } else { - bool logging_enabled = - profile_->GetPrefs()->GetBoolean(prefs::kHotwordAudioLoggingEnabled); - launch_mode = logging_enabled ? HotwordService::HOTWORD_ONLY - : HotwordService::HOTWORD_AND_AUDIO_HISTORY; - } - hotword_service->OptIntoHotwording(launch_mode); - SendHotwordInfo(); -} - } // namespace settings
diff --git a/chrome/browser/ui/webui/settings/search_engines_handler.h b/chrome/browser/ui/webui/settings/search_engines_handler.h index 30d4f2f3..b764a28 100644 --- a/chrome/browser/ui/webui/settings/search_engines_handler.h +++ b/chrome/browser/ui/webui/settings/search_engines_handler.h
@@ -6,6 +6,7 @@ #define CHROME_BROWSER_UI_WEBUI_SETTINGS_SEARCH_ENGINES_HANDLER_H_ #include <memory> +#include <string> #include "base/macros.h" #include "base/memory/weak_ptr.h" @@ -20,7 +21,6 @@ namespace base { class DictionaryValue; class ListValue; -class Value; } namespace extensions { @@ -96,29 +96,6 @@ base::DictionaryValue* CreateDictionaryForExtension( const extensions::Extension& extension); - // WebUI call to request a dictionary of hotword related properties. - void HandleGetHotwordInfo(const base::ListValue* args); - - // Constructs a SearchPageHotwordInfo dictionary. - std::unique_ptr<base::DictionaryValue> GetHotwordInfo(); - - // Callback for HotwordService::AudioHistoryHandler::GetAudioHistoryEnabled. - void OnGetHotwordAudioHistoryEnabled( - std::unique_ptr<base::Value> callback_id, - std::unique_ptr<base::DictionaryValue> status, - bool success, - bool logging_enabled); - - // Calls either ResolveJavascriptCallback or CallJavascriptFunction. - void HotwordInfoComplete(const base::Value* callback_id, - const base::DictionaryValue& status); - - // Calls WebUI to send hotword search info updates. - void SendHotwordInfo(); - - // WebUI call to enable hotword search. - void HandleSetHotwordSearchEnabled(const base::ListValue* args); - Profile* const profile_; KeywordEditorController list_controller_;
diff --git a/chrome/browser/ui/webui/snippets_internals_message_handler.cc b/chrome/browser/ui/webui/snippets_internals_message_handler.cc index fb5e6bd..54bfd17 100644 --- a/chrome/browser/ui/webui/snippets_internals_message_handler.cc +++ b/chrome/browser/ui/webui/snippets_internals_message_handler.cc
@@ -342,15 +342,9 @@ void SnippetsInternalsMessageHandler::HandleClearCachedSuggestions( const base::ListValue* args) { - DCHECK_EQ(1u, args->GetSize()); + DCHECK_EQ(0u, args->GetSize()); - int category_id; - if (!args->GetInteger(0, &category_id)) { - return; - } - - content_suggestions_service_->ClearCachedSuggestions( - Category::FromIDValue(category_id)); + content_suggestions_service_->ClearAllCachedSuggestions(); SendContentSuggestions(); }
diff --git a/chrome/browser/ui/webui/web_ui_test_handler.cc b/chrome/browser/ui/webui/web_ui_test_handler.cc index af1d863..9f070d57 100644 --- a/chrome/browser/ui/webui/web_ui_test_handler.cc +++ b/chrome/browser/ui/webui/web_ui_test_handler.cc
@@ -19,9 +19,9 @@ #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" -#include "content/public/common/associated_interface_provider.h" #include "content/public/test/test_utils.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" using content::RenderViewHost;
diff --git a/chrome/browser/ui/window_sizer/window_sizer.h b/chrome/browser/ui/window_sizer/window_sizer.h index 546e2cc..ea306102 100644 --- a/chrome/browser/ui/window_sizer/window_sizer.h +++ b/chrome/browser/ui/window_sizer/window_sizer.h
@@ -76,11 +76,12 @@ // An interface implemented by an object to identify on which // display a new window should be located. class TargetDisplayProvider { - public: - virtual ~TargetDisplayProvider() {} - virtual display::Display GetTargetDisplay( - const display::Screen* screen, - const gfx::Rect& bounds) const = 0; + public: + virtual ~TargetDisplayProvider() {} + + virtual display::Display GetTargetDisplay( + const display::Screen* screen, + const gfx::Rect& bounds) const = 0; }; // Determines the position and size for a window as it is created as well @@ -189,7 +190,7 @@ display::Screen* screen_; // not owned. // Note that this browser handle might be NULL. - const Browser* browser_; + const Browser* const browser_; DISALLOW_COPY_AND_ASSIGN(WindowSizer); };
diff --git a/chrome/browser/vr/BUILD.gn b/chrome/browser/vr/BUILD.gn index 65981c54..49a0c892 100644 --- a/chrome/browser/vr/BUILD.gn +++ b/chrome/browser/vr/BUILD.gn
@@ -298,6 +298,9 @@ ":vr_test_support", "//testing/perf", ] + if (is_android) { + deps += [ "//ui/android:ui_java" ] + } # Needed for isolate script to execute data = [
diff --git a/chrome/browser/vr/model/model.h b/chrome/browser/vr/model/model.h index 09a673e6..4ac415e 100644 --- a/chrome/browser/vr/model/model.h +++ b/chrome/browser/vr/model/model.h
@@ -55,6 +55,9 @@ bool browsing_mode() const { return !web_vr_mode && !web_vr_show_splash_screen; } + bool web_vr_has_produced_frames() const { + return web_vr_mode && web_vr_timeout_state == kWebVrNoTimeoutPending; + } WebVrTimeoutState web_vr_timeout_state = kWebVrNoTimeoutPending; // Controller state.
diff --git a/chrome/browser/vr/testapp/vr_test_context.cc b/chrome/browser/vr/testapp/vr_test_context.cc index 7afc1a4..82bec10 100644 --- a/chrome/browser/vr/testapp/vr_test_context.cc +++ b/chrome/browser/vr/testapp/vr_test_context.cc
@@ -14,6 +14,7 @@ #include "chrome/browser/vr/model/model.h" #include "chrome/browser/vr/model/omnibox_suggestions.h" #include "chrome/browser/vr/model/toolbar_state.h" +#include "chrome/browser/vr/speech_recognizer.h" #include "chrome/browser/vr/test/constants.h" #include "chrome/browser/vr/ui.h" #include "chrome/browser/vr/ui_element_renderer.h" @@ -102,6 +103,11 @@ ui_->OnProjMatrixChanged(render_info.left_eye_model.proj_matrix); ui_->ui_renderer()->Draw(render_info); + // This is required in order to show the WebVR toasts. + if (model_->web_vr_has_produced_frames()) { + ui_->ui_renderer()->DrawWebVrOverlayForeground(render_info); + } + // TODO(cjgrant): Render viewport-aware elements. } @@ -132,7 +138,7 @@ ui_->Dump(); break; case ui::DomCode::US_V: - ui_->SetVideoCaptureEnabled(!model_->permissions.video_capture_enabled); + CreateFakeVoiceSearchResult(); break; case ui::DomCode::US_W: CycleWebVrModes(); @@ -140,6 +146,9 @@ case ui::DomCode::US_S: ToggleSplashScreen(); break; + case ui::DomCode::US_R: + ui_->OnWebVrFrameAvailable(); + break; default: break; } @@ -313,10 +322,18 @@ ui_->SetOmniboxSuggestions(std::move(result)); } +void VrTestContext::CreateFakeVoiceSearchResult() { + if (!model_->speech.recognizing_speech) + return; + ui_->SetRecognitionResult( + base::UTF8ToUTF16("I would like to see cat videos, please.")); + SetVoiceSearchActive(false); +} + void VrTestContext::CycleWebVrModes() { switch (model_->web_vr_timeout_state) { case kWebVrNoTimeoutPending: - ui_->SetWebVrMode(true, true); + ui_->SetWebVrMode(true, false); break; case kWebVrAwaitingFirstFrame: ui_->OnWebVrTimeoutImminent(); @@ -356,8 +373,15 @@ } void VrTestContext::SetVoiceSearchActive(bool active) { - OnUnsupportedMode(UiUnsupportedMode::kAndroidPermissionNeeded); + if (!voice_search_enabled_) { + OnUnsupportedMode(UiUnsupportedMode::kAndroidPermissionNeeded); + return; + } + ui_->SetSpeechRecognitionEnabled(active); + if (active) + ui_->OnSpeechRecognitionStateChanged(SPEECH_RECOGNITION_RECOGNIZING); } + void VrTestContext::ExitPresent() {} void VrTestContext::ExitFullscreen() {} @@ -376,9 +400,14 @@ ui_->SetExitVrPromptEnabled(true, mode); } } + void VrTestContext::OnExitVrPromptResult(vr::ExitVrPromptChoice choice, vr::UiUnsupportedMode reason) { LOG(ERROR) << "exit prompt result: " << choice; + if (reason == UiUnsupportedMode::kAndroidPermissionNeeded && + choice == CHOICE_EXIT) { + voice_search_enabled_ = true; + } ui_->SetExitVrPromptEnabled(false, UiUnsupportedMode::kCount); }
diff --git a/chrome/browser/vr/testapp/vr_test_context.h b/chrome/browser/vr/testapp/vr_test_context.h index f89c94d..e23d41b 100644 --- a/chrome/browser/vr/testapp/vr_test_context.h +++ b/chrome/browser/vr/testapp/vr_test_context.h
@@ -31,6 +31,8 @@ ~VrTestContext() override; void OnGlInitialized(); + // TODO(vollick): we should refactor VrShellGl's rendering logic and use it + // directly. crbug.com/767282 void DrawFrame(); void HandleInput(ui::Event* event); @@ -53,6 +55,7 @@ private: unsigned int CreateFakeContentTexture(); void CreateFakeOmniboxSuggestions(); + void CreateFakeVoiceSearchResult(); void CycleWebVrModes(); void ToggleSplashScreen(); gfx::Transform ProjectionMatrix() const; @@ -79,6 +82,7 @@ bool incognito_ = false; bool show_web_vr_splash_screen_ = false; + bool voice_search_enabled_ = false; ControllerModel last_controller_model_;
diff --git a/chrome/browser/vr/ui.cc b/chrome/browser/vr/ui.cc index 6df6ba7..497d5aa 100644 --- a/chrome/browser/vr/ui.cc +++ b/chrome/browser/vr/ui.cc
@@ -116,6 +116,7 @@ void Ui::SetExitVrPromptEnabled(bool enabled, UiUnsupportedMode reason) { if (!enabled) { + DCHECK_EQ(reason, UiUnsupportedMode::kCount); model_->active_modal_prompt_type = kModalPromptTypeNone; return; } @@ -127,16 +128,22 @@ } switch (reason) { + case UiUnsupportedMode::kUnhandledCodePoint: + NOTREACHED(); // This mode does not prompt. + return; case UiUnsupportedMode::kUnhandledPageInfo: model_->active_modal_prompt_type = kModalPromptTypeExitVRForSiteInfo; - break; + return; case UiUnsupportedMode::kAndroidPermissionNeeded: model_->active_modal_prompt_type = kModalPromptTypeExitVRForAudioPermission; - break; - default: - NOTREACHED(); + return; + case UiUnsupportedMode::kCount: + NOTREACHED(); // Should never be used as a mode (when |enabled| is true). + return; } + + NOTREACHED(); } void Ui::SetSpeechRecognitionEnabled(bool enabled) { @@ -215,6 +222,8 @@ void Ui::OnWebVrTimeoutImminent() { model_->web_vr_timeout_state = kWebVrTimeoutImminent; + // We do not want to simultaneously show the splash screen and the timeout UI. + model_->web_vr_show_splash_screen = false; } void Ui::OnWebVrTimedOut() {
diff --git a/chrome/browser/vr/ui_scene_creator.cc b/chrome/browser/vr/ui_scene_creator.cc index 3a0910f7..50f5102a 100644 --- a/chrome/browser/vr/ui_scene_creator.cc +++ b/chrome/browser/vr/ui_scene_creator.cc
@@ -444,8 +444,7 @@ transient_parent->SetTransitionedProperties({OPACITY}); transient_parent->AddBinding(VR_BIND_FUNC( bool, Model, model_, - web_vr_show_splash_screen && - model->web_vr_timeout_state == kWebVrNoTimeoutPending, + web_vr_show_splash_screen && model->web_vr_has_produced_frames(), ShowUntilSignalTransientElement, transient_parent.get(), Signal)); scene_->AddUiElement(kSplashScreenViewportAwareRoot, std::move(transient_parent)); @@ -1071,10 +1070,11 @@ auto* parent = AddTransientParent(kWebVrUrlToastTransientParent, kWebVrViewportAwareRoot, kWebVrUrlToastTimeoutSeconds, true, scene_); - parent->AddBinding(VR_BIND_FUNC( - bool, Model, model_, - web_vr_started_for_autopresentation && !model->web_vr_show_splash_screen, - UiElement, parent, SetVisible)); + parent->AddBinding(VR_BIND_FUNC(bool, Model, model_, + web_vr_started_for_autopresentation && + !model->web_vr_show_splash_screen && + model->web_vr_has_produced_frames(), + UiElement, parent, SetVisible)); auto element = base::MakeUnique<WebVrUrlToast>( 512, base::Bind(&UiBrowserInterface::OnUnsupportedMode, @@ -1313,8 +1313,7 @@ // kick the visibility of this element. parent->AddBinding( VR_BIND_FUNC(bool, Model, model_, - web_vr_timeout_state == kWebVrNoTimeoutPending && - model->web_vr_mode && model->web_vr_show_toast, + web_vr_has_produced_frames() && model->web_vr_show_toast, UiElement, parent, SetVisible)); element = base::MakeUnique<ExclusiveScreenToast>(512);
diff --git a/chrome/browser/vr/ui_unittest.cc b/chrome/browser/vr/ui_unittest.cc index f8211f3..a3c1971 100644 --- a/chrome/browser/vr/ui_unittest.cc +++ b/chrome/browser/vr/ui_unittest.cc
@@ -389,6 +389,21 @@ EXPECT_FALSE(IsVisible(kWebVrUrlToast)); } +TEST_F(UiTest, WebVrSplashScreenHiddenWhenTimeoutImminent) { + CreateSceneForAutoPresentation(); + + // Initially, we should only show the splash screen. + VerifyOnlyElementsVisible("Initial", + {kSplashScreenText, kSplashScreenBackground}); + + ui_->SetWebVrMode(true, false); + ui_->OnWebVrTimeoutImminent(); + + VerifyOnlyElementsVisible( + "Timeout imminent", + {kWebVrTimeoutSpinner, kWebVrTimeoutSpinnerBackground}); +} + TEST_F(UiTest, AppButtonClickForAutopresentation) { CreateSceneForAutoPresentation(); @@ -515,7 +530,7 @@ // This would usually get called by the browser, but since it is mocked we // will call it explicitly here and check that the UI responds as we would // expect. - ui_->SetExitVrPromptEnabled(false, UiUnsupportedMode::kUnhandledPageInfo); + ui_->SetExitVrPromptEnabled(false, UiUnsupportedMode::kCount); VerifyOnlyElementsVisible("Prompt cleared", kElementsVisibleInBrowsing); }
diff --git a/chrome/browser/vr/ui_unsupported_mode.h b/chrome/browser/vr/ui_unsupported_mode.h index 91ab11b47..43950c0 100644 --- a/chrome/browser/vr/ui_unsupported_mode.h +++ b/chrome/browser/vr/ui_unsupported_mode.h
@@ -13,10 +13,10 @@ // GENERATED_JAVA_ENUM_PACKAGE: org.chromium.chrome.browser.vr_shell enum class UiUnsupportedMode : int { kUnhandledCodePoint = 0, - kCouldNotElideURL, - kUnhandledPageInfo, - kURLWithStrongRTLChars, - kAndroidPermissionNeeded, + // kCouldNotElideURL = 1, // Obsolete. + kUnhandledPageInfo = 2, + // kURLWithStrongRTLChars = 3, // Obsolete. + kAndroidPermissionNeeded = 4, // TODO(ddorwin): Rename to match enums.xml. // This must be last. kCount,
diff --git a/chrome/common/chrome_switches.cc b/chrome/common/chrome_switches.cc index 4dca90b..7fb3d11e 100644 --- a/chrome/common/chrome_switches.cc +++ b/chrome/common/chrome_switches.cc
@@ -311,9 +311,6 @@ const char kEnableExperimentalFullscreenExitUI[] = "enable-experimental-fullscreen-exit-ui"; -// Enables experimental hotword features specific to always-on. -const char kEnableExperimentalHotwordHardware[] = "enable-hotword-hardware"; - // Enables logging for extension activity. const char kEnableExtensionActivityLogging[] = "enable-extension-activity-logging";
diff --git a/chrome/common/chrome_switches.h b/chrome/common/chrome_switches.h index e5bab42..e62d8c9 100644 --- a/chrome/common/chrome_switches.h +++ b/chrome/common/chrome_switches.h
@@ -104,7 +104,6 @@ extern const char kEnableDevToolsExperiments[]; extern const char kEnableDomainReliability[]; extern const char kEnableExperimentalFullscreenExitUI[]; -extern const char kEnableExperimentalHotwordHardware[]; extern const char kEnableExtensionActivityLogging[]; extern const char kEnableExtensionActivityLogTesting[]; extern const char kEnableFastUnload[];
diff --git a/chrome/common/crash_keys.cc b/chrome/common/crash_keys.cc index 79fed14..eb80a46 100644 --- a/chrome/common/crash_keys.cc +++ b/chrome/common/crash_keys.cc
@@ -197,6 +197,9 @@ // Temporary for https://crbug.com/685996. {kUserCloudPolicyManagerConnectTrace, kMediumSize}, + // TODO(sunnyps): Remove after fixing crbug.com/724999. + {"gl-context-set-current-stack-trace", kMediumSize}, + // TODO(asvitkine): Remove after fixing https://crbug.com/736675 {"bad_histogram", kMediumSize},
diff --git a/chrome/common/extensions/api/BUILD.gn b/chrome/common/extensions/api/BUILD.gn index 6654e6c..f6fc7b8 100644 --- a/chrome/common/extensions/api/BUILD.gn +++ b/chrome/common/extensions/api/BUILD.gn
@@ -45,7 +45,6 @@ "font_settings.json", "gcm.json", "history.json", - "hotword_private.idl", "i18n.json", "identity.idl", "identity_private.idl",
diff --git a/chrome/common/extensions/api/_api_features.json b/chrome/common/extensions/api/_api_features.json index 18c2c6e..f6cad510 100644 --- a/chrome/common/extensions/api/_api_features.json +++ b/chrome/common/extensions/api/_api_features.json
@@ -501,10 +501,6 @@ "dependencies": ["permission:history"], "contexts": ["blessed_extension"] }, - "hotwordPrivate": { - "dependencies": ["permission:hotwordPrivate"], - "contexts": ["blessed_extension"] - }, "i18n": { "channel": "stable", "extension_types": ["extension", "legacy_packaged_app", "platform_app"],
diff --git a/chrome/common/extensions/api/_permission_features.json b/chrome/common/extensions/api/_permission_features.json index 57aaf346..9022d82 100644 --- a/chrome/common/extensions/api/_permission_features.json +++ b/chrome/common/extensions/api/_permission_features.json
@@ -139,6 +139,7 @@ "B6C2EFAB3EC3BF6EF03701408B6B09A67B2D0069", // http://crbug.com/642141 "96FF2FFA5C9173C76D47184B3E86D267B37781DE", // http://crbug.com/642141 "0136FCB13DB29FD5CD442F56E59E53B61F1DF96F", // http://crbug.com/642141 + "9834387FDA1F66A1B5CA06CB442137B556F12F2A", // http://crbug.com/772346 "930F7D9989A5FBCDCCD7D85BB5C3B7006C24D91D" // http://crbug.com/782139 ] }, @@ -365,14 +366,6 @@ "channel": "stable", "extension_types": ["extension", "legacy_packaged_app"] }, - "hotwordPrivate": { - "channel": "stable", - "extension_types": ["extension", "platform_app"], - "whitelist": [ - "62CCAAD339E6451BBF97C4BBDF758E934A05AD0B", // hotword component - "B6356EFF4047BC5F868C7D91868B6F5C01951A8A" // hotword_audio_verification - ] - }, "identity": { "channel": "stable", "extension_types": ["extension", "platform_app"]
diff --git a/chrome/common/extensions/api/hotword_private.idl b/chrome/common/extensions/api/hotword_private.idl deleted file mode 100644 index a7ffeb1..0000000 --- a/chrome/common/extensions/api/hotword_private.idl +++ /dev/null
@@ -1,189 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// The <code>chrome.hotwordPrivate</code> API allows extensions to access and -// mutate the preference for enabling hotword search. It also provides -// information on whether the hotword search is available. This API provides an -// event interface to transmit to the extension a signal that the preference fo -// hotword search has change. -// -// For an FYI, visit http://goo.gl/AyHbkH - -namespace hotwordPrivate { - - dictionary StatusDetails { - // Whether the hotword preference has been set. - boolean enabledSet; - - // If the hotword extension is enabled. Will always be false if |available| - // is false. - boolean enabled; - - // Whether the hotword extension is available to be enabled - // Optional field, only valid when getStatus() is called with - // |getOptionalFields| = true. Otherwise, set to false. - boolean available; - - // Whether always-on is available to be enabled - // Optional field, only valid when getStatus() is called with - // |getOptionalFields| = true. Otherwise, set to false. - boolean alwaysOnAvailable; - - // Whether the sound of "Ok, Google" plus a few seconds before is sent - // back to Google. - boolean audioLoggingEnabled; - - // Whether always-on hotwording is enabled. - boolean alwaysOnEnabled; - - // Whether training mode is enabled. - boolean trainingEnabled; - - // Whether the user corresponding to this profile is the active user. - boolean userIsActive; - - // Whether hotword hardware is available if requested. - boolean hotwordHardwareAvailable; - }; - - dictionary LaunchState { - // TODO(kcarattini): Consider adding more variables here, - // such as the available state of the hotword service. - - // The mode that the Hotword Audio Verification app was launched in. - long launchMode; - }; - - dictionary LogDetails { - // Number of audio channels. i.e. 1 = mono, 2 = stereo - long channels; - - // Bytes per sample per channel. - long bytes_per_sample; - - // Sample rate. Usually 32000 or 44100, but may be any integer. - long sample_rate; - - // Array containing audio data. Length is - // (channels * bytes_per_sample * sample_rate * <seconds of log>). - ArrayBuffer buffer; - }; - - dictionary AudioHistoryState { - // Whether the call to set or get this state was successful. - boolean success; - - // The current value of the audio history opt-in state after this - // call. - boolean enabled; - }; - - // The type of the recognized hotword. Right now it only has 'search' but - // could be expanded to other types of actions in the future. - enum HotwordType { search }; - - callback GenericDoneCallback = void (); - callback LaunchStateCallback = void(LaunchState result); - callback LocalizeStringsCallback = void(object result); - callback StatusDetailsCallback = void(StatusDetails result); - callback AudioHistoryCallback = void(AudioHistoryState result); - - interface Functions { - // Sets the current enabled state of hotword search. - // True: enable hotword search. False: disable hotword search. - static void setEnabled(boolean state, - optional GenericDoneCallback callback); - - // Retrieves the current state of hotword search. - // The result is put into a StatusDetails object. - // |getOptionalFields|: If true, fills in fields tagged as optional in - // StatusDetails with valid values. These fields are not valid by default - // since their current implementations may cause blocking operations. - static void getStatus(optional boolean getOptionalFields, - StatusDetailsCallback callback); - - // Retrieves a dictionary mapping names to localized resource strings. - static void getLocalizedStrings(LocalizeStringsCallback callback); - - // Sets the current enabled state of audio logging in the extension. - // True: logging enabled. False: no logging. - static void setAudioLoggingEnabled(boolean state, - optional GenericDoneCallback callback); - - // Sets the current enabled state of hotword-always-on-search pref. - // True: enable hotword always on search. - // False: disable hotword always on search. - static void setHotwordAlwaysOnSearchEnabled(boolean state, - optional GenericDoneCallback callback); - - // Sets the current state of the browser-requested hotword session. - static void setHotwordSessionState(boolean started, - optional GenericDoneCallback callback); - - // Notifies that a hotword has been recognized in the browser-requested - // hotword session. - static void notifyHotwordRecognition(HotwordType type, - optional LogDetails log, - optional GenericDoneCallback callback); - - // Retrieves the state that the Hotword Audio Verification app was - // launched in. The result is put into a LaunchState object. - static void getLaunchState(LaunchStateCallback callback); - - // Starts the speaker model training. - static void startTraining(optional GenericDoneCallback callback); - - // Finalizess the speaker model. - static void finalizeSpeakerModel(optional GenericDoneCallback callback); - - // Notifies that the speaker model has been saved. - static void notifySpeakerModelSaved(optional GenericDoneCallback callback); - - // Stops the speaker model training. - static void stopTraining(optional GenericDoneCallback callback); - - // Sets the audio history opt-in state. - static void setAudioHistoryEnabled(boolean enabled, - optional AudioHistoryCallback callback); - - // Gets the audio history opt-in state. - static void getAudioHistoryEnabled(optional AudioHistoryCallback callback); - - // Sends the result of whether a speaker model exists to the browser. - static void speakerModelExistsResult(boolean exists, - optional GenericDoneCallback callback); - }; - - interface Events { - // Fired when the hotword detector enabled state should be changed. - // This can be from various sources, e.g. a pref change or training - // a speaker model. - static void onEnabledChanged(); - - // Fired when the browser wants to start a hotword session. - static void onHotwordSessionRequested(); - - // Fired when the browser wants to stop the requested hotword session. - static void onHotwordSessionStopped(); - - // Fired when the speaker model should be finalized. - static void onFinalizeSpeakerModel(); - - // Fired when the speaker model has been saved. - static void onSpeakerModelSaved(); - - // Fired when a hotword has triggered. - static void onHotwordTriggered(); - - // Fired when the speaker model should be deleted. - static void onDeleteSpeakerModel(); - - // Fired when the browser wants to find out whether the speaker model - // exists. - static void onSpeakerModelExists(); - - // Fired when the microphone state changes. - static void onMicrophoneStateChanged(boolean enabled); - }; -};
diff --git a/chrome/common/extensions/api/privacy.json b/chrome/common/extensions/api/privacy.json index 2268876..1acf9c7 100644 --- a/chrome/common/extensions/api/privacy.json +++ b/chrome/common/extensions/api/privacy.json
@@ -59,11 +59,6 @@ "value": ["autofillEnabled", {"type":"boolean"}], "description": "If enabled, Chrome offers to automatically fill in forms. This preference's value is a boolean, defaulting to <code>true</code>." }, - "hotwordSearchEnabled": { - "$ref": "types.ChromeSetting", - "value": ["hotwordSearchEnabled", {"type":"boolean"}], - "description": "If enabled, Chrome will enable 'OK, Google' to start a voice search. This preference's value is a boolean, defaulting to <code>true</code>." - }, "passwordSavingEnabled": { "$ref": "types.ChromeSetting", "value": ["passwordSavingEnabled", {"type":"boolean"}],
diff --git a/chrome/common/extensions/extension_constants.cc b/chrome/common/extensions/extension_constants.cc index 819c0c64..20c8370 100644 --- a/chrome/common/extensions/extension_constants.cc +++ b/chrome/common/extensions/extension_constants.cc
@@ -57,10 +57,6 @@ const char kHTermDevAppId[] = "okddffdblfhhnmhodogpojmfkjmhinfp"; const char kIdentityApiUiAppId[] = "ahjaciijnoiaklcomgnblndopackapon"; const char kCroshBuiltinAppId[] = "nkoccljplnhpfnfiajclkommnmllphnl"; -const char kHotwordAudioVerificationAppId[] = - "abjokfonkihficiokmkfboogholifghn"; -const char kHotwordNewExtensionId[] = "nbpagnldghgfoolbancepceaanlmhfmd"; -const char kHotwordSharedModuleId[] = "lccekmodgklaepjeofjdjpbminllajkg"; const char kTextEditorAppId[] = "mmfbcljfglbokpmkimbfghdkjmjhdgbg"; const char kYoutubeAppId[] = "blpcfgokakmgnkcojhhkbfbldkacnbeo"; const char kInAppPaymentsSupportAppId[] = "nmmhkkegccagdldgiimedpiccmgmieda";
diff --git a/chrome/common/extensions/extension_constants.h b/chrome/common/extensions/extension_constants.h index d5c1db0..8b221cf 100644 --- a/chrome/common/extensions/extension_constants.h +++ b/chrome/common/extensions/extension_constants.h
@@ -115,15 +115,6 @@ // The extension id of the Crosh component app for ChromeOS. extern const char kCroshBuiltinAppId[]; -// The extension id of the hotword audio verification dialogue app. -extern const char kHotwordAudioVerificationAppId[]; - -// The extension id of the new (experimental) hotword extension. -extern const char kHotwordNewExtensionId[]; - -// The extension id of the hotword shared module. -extern const char kHotwordSharedModuleId[]; - // The extension id of the Text Editor application. extern const char kTextEditorAppId[];
diff --git a/chrome/common/extensions/permissions/chrome_api_permissions.cc b/chrome/common/extensions/permissions/chrome_api_permissions.cc index 49c594b..2f529481 100644 --- a/chrome/common/extensions/permissions/chrome_api_permissions.cc +++ b/chrome/common/extensions/permissions/chrome_api_permissions.cc
@@ -125,8 +125,6 @@ APIPermissionInfo::kFlagCannotBeOptional}, {APIPermission::kFileManagerPrivate, "fileManagerPrivate", APIPermissionInfo::kFlagCannotBeOptional}, - {APIPermission::kHotwordPrivate, "hotwordPrivate", - APIPermissionInfo::kFlagCannotBeOptional}, {APIPermission::kIdentityPrivate, "identityPrivate", APIPermissionInfo::kFlagCannotBeOptional}, {APIPermission::kWebcamPrivate, "webcamPrivate"},
diff --git a/chrome/common/extensions/permissions/permission_set_unittest.cc b/chrome/common/extensions/permissions/permission_set_unittest.cc index 5b81922..e4f01497 100644 --- a/chrome/common/extensions/permissions/permission_set_unittest.cc +++ b/chrome/common/extensions/permissions/permission_set_unittest.cc
@@ -821,7 +821,6 @@ skip.insert(APIPermission::kFileBrowserHandlerInternal); skip.insert(APIPermission::kFileManagerPrivate); skip.insert(APIPermission::kFirstRunPrivate); - skip.insert(APIPermission::kHotwordPrivate); skip.insert(APIPermission::kIdentityPrivate); skip.insert(APIPermission::kInputMethodPrivate); skip.insert(APIPermission::kLanguageSettingsPrivate);
diff --git a/chrome/common/features.gni b/chrome/common/features.gni index e25c86f..f9561c7 100644 --- a/chrome/common/features.gni +++ b/chrome/common/features.gni
@@ -38,10 +38,6 @@ # It is enableable separately to facilitate testing. enable_hangout_services_extension = is_chrome_branded - # 'Ok Google' hotwording is disabled to prepare for its removal. - # http://crbug.com/755579 - enable_hotwording = false - # Enables usage of the system-provided notification center. enable_native_notifications = is_android || is_mac || is_win || (is_desktop_linux && use_dbus) || is_chromeos @@ -86,7 +82,6 @@ "enable_extensions=$enable_extensions", "enable_google_now=$enable_google_now", "enable_hangout_services_extension=$enable_hangout_services_extension", - "enable_hotwording=$enable_hotwording", "enable_plugins=$enable_plugins", "enable_print_preview=$enable_print_preview", "enable_printing=$_enable_printing",
diff --git a/chrome/common/media_router/media_source_helper.cc b/chrome/common/media_router/media_source_helper.cc index 8088fc9f..0228285a 100644 --- a/chrome/common/media_router/media_source_helper.cc +++ b/chrome/common/media_router/media_source_helper.cc
@@ -28,10 +28,6 @@ constexpr char kCastPresentationUrlDomain[] = "google.com"; constexpr char kCastPresentationUrlPath[] = "/cast"; -// This value must be the same as |chrome.cast.AUTO_JOIN_PRESENTATION_ID| in the -// component extension. -constexpr char kAutoJoinPresentationId[] = "auto-join"; - // List of non-http(s) schemes that are allowed in a Presentation URL. constexpr std::array<const char* const, 5> kAllowedSchemes{ {kCastPresentationUrlScheme, kCastDialPresentationUrlScheme,
diff --git a/chrome/common/media_router/media_source_helper.h b/chrome/common/media_router/media_source_helper.h index 659221a..02f51dd 100644 --- a/chrome/common/media_router/media_source_helper.h +++ b/chrome/common/media_router/media_source_helper.h
@@ -24,6 +24,17 @@ constexpr char kLegacyCastPresentationUrlPrefix[] = "https://google.com/cast#__castAppId__="; +// Strings used in presentation IDs by the Cast SDK implementation. +// TODO(takumif): Move them out of media_source_helper, since they are not +// directly related to MediaSource. +// +// This value must be the same as |chrome.cast.AUTO_JOIN_PRESENTATION_ID| in the +// component extension. +constexpr char kAutoJoinPresentationId[] = "auto-join"; +// This value must be the same as |chrome.cast.PRESENTATION_ID_PREFIX| in the +// component extension. +constexpr char kCastPresentationIdPrefix[] = "cast-session_"; + // Helper library for protocol-specific media source object creation. // Returns MediaSource URI depending on the type of source. MediaSource MediaSourceForTab(int tab_id);
diff --git a/chrome/common/pref_names.cc b/chrome/common/pref_names.cc index 53bf29f..53098bd 100644 --- a/chrome/common/pref_names.cc +++ b/chrome/common/pref_names.cc
@@ -1713,30 +1713,6 @@ // capture devices without prompt. const char kVideoCaptureAllowedUrls[] = "hardware.video_capture_allowed_urls"; -// A boolean pref that controls the enabled-state of hotword search voice -// trigger. -const char kHotwordSearchEnabled[] = "hotword.search_enabled_2"; - -// A boolean pref that controls the enabled-state of hotword search voice -// trigger from any screen. -const char kHotwordAlwaysOnSearchEnabled[] = "hotword.always_on_search_enabled"; - -// A boolean pref that indicates whether the hotword always-on notification -// has been seen already. -const char kHotwordAlwaysOnNotificationSeen[] = - "hotword.always_on_notification_seen"; - -// A boolean pref that controls whether the sound of "Ok, Google" plus a few -// seconds of audio data before and the spoken query are sent back to be stored -// in a user's Voice & Audio Activity. Updated whenever the user opens -// chrome://settings and also polled for every 24 hours. -const char kHotwordAudioLoggingEnabled[] = "hotword.audio_logging_enabled"; - -// A string holding the locale information under which Hotword was installed. -// It is used for comparison since the hotword voice search trigger must be -// reinstalled to handle a new language. -const char kHotwordPreviousLanguage[] = "hotword.previous_language"; - #if defined(OS_CHROMEOS) // Dictionary for transient storage of settings that should go into device // settings storage before owner has been assigned.
diff --git a/chrome/common/pref_names.h b/chrome/common/pref_names.h index 2c7f5e1b..077cf87 100644 --- a/chrome/common/pref_names.h +++ b/chrome/common/pref_names.h
@@ -612,12 +612,6 @@ extern const char kVideoCaptureAllowed[]; extern const char kVideoCaptureAllowedUrls[]; -extern const char kHotwordSearchEnabled[]; -extern const char kHotwordAlwaysOnSearchEnabled[]; -extern const char kHotwordAlwaysOnNotificationSeen[]; -extern const char kHotwordAudioLoggingEnabled[]; -extern const char kHotwordPreviousLanguage[]; - #if defined(OS_CHROMEOS) extern const char kDeviceSettingsCache[]; extern const char kHardwareKeyboardLayout[];
diff --git a/chrome/common/url_constants.cc b/chrome/common/url_constants.cc index c639a31..552f2fe 100644 --- a/chrome/common/url_constants.cc +++ b/chrome/common/url_constants.cc
@@ -209,12 +209,6 @@ "https://support.google.com/chrome/?p=ib_blocked_plugin"; #endif -const char kHotwordLearnMoreURL[] = - "https://support.google.com/chrome/?p=ui_hotword_search"; - -const char kManageAudioHistoryURL[] = - "https://history.google.com/history/audio"; - const char kLearnMoreRegisterProtocolHandlerURL[] = "https://support.google.com/chrome/?p=ib_protocol_handler";
diff --git a/chrome/common/url_constants.h b/chrome/common/url_constants.h index 362854f..b0002a10 100644 --- a/chrome/common/url_constants.h +++ b/chrome/common/url_constants.h
@@ -148,12 +148,6 @@ // The URL for the "Learn more" page for the blocked plugin infobar. extern const char kBlockedPluginLearnMoreURL[]; -// The URL for the "Learn more" page for hotword search voice trigger. -extern const char kHotwordLearnMoreURL[]; - -// The URL for managing a user's audio history. -extern const char kManageAudioHistoryURL[]; - // The URL for the "Learn more" page for register protocol handler infobars. extern const char kLearnMoreRegisterProtocolHandlerURL[];
diff --git a/chrome/common/webui_url_constants.cc b/chrome/common/webui_url_constants.cc index 5416937..9eba678 100644 --- a/chrome/common/webui_url_constants.cc +++ b/chrome/common/webui_url_constants.cc
@@ -215,7 +215,6 @@ const char kChromeUITermsOemURL[] = "chrome://terms/oem"; const char kChromeUIUserImageHost[] = "userimage"; const char kChromeUIUserImageURL[] = "chrome://userimage/"; -const char kChromeUIVoiceSearchHost[] = "voicesearch"; #endif // defined(OS_CHROMEOS) #if defined(OS_WIN) @@ -381,7 +380,6 @@ kChromeUIPowerHost, kChromeUIInternetConfigDialogHost, kChromeUIInternetDetailDialogHost, - kChromeUIVoiceSearchHost, #endif #if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) kChromeUIDiscardsHost,
diff --git a/chrome/common/webui_url_constants.h b/chrome/common/webui_url_constants.h index ddc485ce..113561f 100644 --- a/chrome/common/webui_url_constants.h +++ b/chrome/common/webui_url_constants.h
@@ -212,7 +212,6 @@ extern const char kChromeUITermsOemURL[]; extern const char kChromeUIUserImageHost[]; extern const char kChromeUIUserImageURL[]; -extern const char kChromeUIVoiceSearchHost[]; #endif // defined(OS_CHROMEOS) #if defined(OS_WIN)
diff --git a/chrome/renderer/BUILD.gn b/chrome/renderer/BUILD.gn index 4b561b03..903f80f 100644 --- a/chrome/renderer/BUILD.gn +++ b/chrome/renderer/BUILD.gn
@@ -106,6 +106,7 @@ "//chrome:strings", "//chrome/common", "//chrome/common:mojo_bindings", + "//chrome/common:search_mojom", "//chrome/common/net", "//components/autofill/content/renderer", "//components/cdm/renderer", @@ -397,7 +398,6 @@ } if (!is_android) { - deps += [ "//chrome/common:search_mojom" ] sources += [ "searchbox/search_bouncer.cc", "searchbox/search_bouncer.h",
diff --git a/chrome/renderer/DEPS b/chrome/renderer/DEPS index 38e3341..8b88a94 100644 --- a/chrome/renderer/DEPS +++ b/chrome/renderer/DEPS
@@ -55,7 +55,7 @@ "+services/service_manager/public/cpp", "+skia", "+storage/common", - "+third_party/WebKit/common/page/page_visibility_state.mojom.h", + "+third_party/WebKit/common", "+third_party/metrics_proto", "-components/spellcheck/browser", # Allow all spellcheck but browser. ]
diff --git a/chrome/renderer/autofill/autofill_renderer_browsertest.cc b/chrome/renderer/autofill/autofill_renderer_browsertest.cc index 117016d..eb1553b 100644 --- a/chrome/renderer/autofill/autofill_renderer_browsertest.cc +++ b/chrome/renderer/autofill/autofill_renderer_browsertest.cc
@@ -9,10 +9,12 @@ #include "base/macros.h" #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" +#include "base/test/scoped_feature_list.h" #include "chrome/test/base/chrome_render_view_test.h" #include "chrome/test/base/ui_test_utils.h" #include "components/autofill/content/common/autofill_driver.mojom.h" #include "components/autofill/content/renderer/autofill_agent.h" +#include "components/autofill/core/common/autofill_features.h" #include "components/autofill/core/common/form_data.h" #include "components/autofill/core/common/form_field_data.h" #include "content/public/common/content_switches.h" @@ -30,6 +32,9 @@ #include "third_party/WebKit/public/web/WebLocalFrame.h" #include "third_party/WebKit/public/web/WebView.h" +using autofill::features::kAutofillEnforceMinRequiredFieldsForHeuristics; +using autofill::features::kAutofillEnforceMinRequiredFieldsForQuery; +using autofill::features::kAutofillEnforceMinRequiredFieldsForUpload; using base::ASCIIToUTF16; using blink::WebDocument; using blink::WebElement; @@ -247,7 +252,16 @@ EXPECT_FORM_FIELD_DATA_EQUALS(expected, forms[0].fields[2]); } -TEST_F(AutofillRendererTest, EnsureNoFormSeenIfTooFewFields) { +TEST_F(AutofillRendererTest, NoSmallFormsWhenMinimumEnforced) { + base::test::ScopedFeatureList feature_list; + feature_list.InitWithFeatures( + // Enabled. + {kAutofillEnforceMinRequiredFieldsForHeuristics, + kAutofillEnforceMinRequiredFieldsForQuery, + kAutofillEnforceMinRequiredFieldsForUpload}, + // Disabled. + {}); + LoadHTML("<form method='POST'>" " <input type='text' id='firstname'/>" " <input type='text' id='middlename'/>" @@ -261,6 +275,29 @@ ASSERT_EQ(0UL, forms.size()); } +TEST_F(AutofillRendererTest, SmallFormsFoundWhenMinimumNotEnforced) { + base::test::ScopedFeatureList feature_list; + feature_list.InitWithFeatures( + // Enabled. + {}, + // Disabled. + {kAutofillEnforceMinRequiredFieldsForHeuristics, + kAutofillEnforceMinRequiredFieldsForQuery, + kAutofillEnforceMinRequiredFieldsForUpload}); + LoadHTML( + "<form method='POST'>" + " <input type='text' id='firstname'/>" + " <input type='text' id='middlename'/>" + "</form>"); + + base::RunLoop run_loop; + run_loop.RunUntilIdle(); + // Verify that "FormsSeen" isn't sent, as there are too few fields. + ASSERT_TRUE(fake_driver_.forms()); + const std::vector<FormData>& forms = *(fake_driver_.forms()); + ASSERT_EQ(1UL, forms.size()); +} + // Regression test for [ http://crbug.com/346010 ]. TEST_F(AutofillRendererTest, DontCrashWhileAssociatingForms) { LoadHTML("<form id='form'>"
diff --git a/chrome/renderer/autofill/form_autofill_browsertest.cc b/chrome/renderer/autofill/form_autofill_browsertest.cc index 07c07e7f..af191503 100644 --- a/chrome/renderer/autofill/form_autofill_browsertest.cc +++ b/chrome/renderer/autofill/form_autofill_browsertest.cc
@@ -12,10 +12,12 @@ #include "base/strings/string16.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" +#include "base/test/scoped_feature_list.h" #include "chrome/test/base/chrome_render_view_test.h" #include "components/autofill/content/renderer/form_autofill_util.h" #include "components/autofill/content/renderer/form_cache.h" #include "components/autofill/core/common/autofill_data_validation.h" +#include "components/autofill/core/common/autofill_features.h" #include "components/autofill/core/common/form_data.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/WebKit/public/platform/WebString.h" @@ -29,6 +31,9 @@ #include "third_party/WebKit/public/web/WebLocalFrame.h" #include "third_party/WebKit/public/web/WebSelectElement.h" +using autofill::features::kAutofillEnforceMinRequiredFieldsForHeuristics; +using autofill::features::kAutofillEnforceMinRequiredFieldsForQuery; +using autofill::features::kAutofillEnforceMinRequiredFieldsForUpload; using base::ASCIIToUTF16; using blink::WebDocument; using blink::WebElement; @@ -2631,24 +2636,30 @@ WebLocalFrame* web_frame = GetMainFrame(); ASSERT_NE(nullptr, web_frame); - FormCache form_cache(web_frame); - std::vector<FormData> forms = form_cache.ExtractNewForms(); - ASSERT_TRUE(forms.empty()); -} + // If all minimums are enforced, we ignore this form. + { + base::test::ScopedFeatureList feature_list; + feature_list.InitWithFeatures( + // Enabled. + {kAutofillEnforceMinRequiredFieldsForHeuristics, + kAutofillEnforceMinRequiredFieldsForQuery, + kAutofillEnforceMinRequiredFieldsForUpload}, + // Disabled. + {}); + ASSERT_TRUE(FormCache(web_frame).ExtractNewForms().empty()); + } -// We should not report additional forms for empty forms. -TEST_F(FormAutofillTest, ExtractFormsSkippedForms) { - LoadHTML("<FORM name='TestForm' action='http://cnn.com' method='post'>" - " <INPUT type='text' id='firstname' value='John'/>" - " <INPUT type='text' id='lastname' value='Smith'/>" - "</FORM>"); - - WebLocalFrame* web_frame = GetMainFrame(); - ASSERT_NE(nullptr, web_frame); - - FormCache form_cache(web_frame); - std::vector<FormData> forms = form_cache.ExtractNewForms(); - ASSERT_TRUE(forms.empty()); + // If at least one of the minimums is not enforced, we parse the form. + { + base::test::ScopedFeatureList feature_list; + feature_list.InitWithFeatures( + // Enabled. + {kAutofillEnforceMinRequiredFieldsForHeuristics, + kAutofillEnforceMinRequiredFieldsForQuery}, + // Disabled. + {kAutofillEnforceMinRequiredFieldsForUpload}); + ASSERT_FALSE(FormCache(web_frame).ExtractNewForms().empty()); + } } // We should not report additional forms for empty forms. @@ -2678,9 +2689,31 @@ WebLocalFrame* web_frame = GetMainFrame(); ASSERT_NE(nullptr, web_frame); - FormCache form_cache(web_frame); - std::vector<FormData> forms = form_cache.ExtractNewForms(); - ASSERT_TRUE(forms.empty()); + // Without small form support, the form is not parsed. + { + base::test::ScopedFeatureList feature_list; + feature_list.InitWithFeatures( + // Enabled. + {kAutofillEnforceMinRequiredFieldsForHeuristics, + kAutofillEnforceMinRequiredFieldsForQuery, + kAutofillEnforceMinRequiredFieldsForUpload}, + // Disabled. + {}); + ASSERT_TRUE(FormCache(web_frame).ExtractNewForms().empty()); + } + + // With small form support, the form is parsed. + { + base::test::ScopedFeatureList feature_list; + feature_list.InitWithFeatures( + // Enabled. + {}, + // Disabled. + {kAutofillEnforceMinRequiredFieldsForHeuristics, + kAutofillEnforceMinRequiredFieldsForQuery, + kAutofillEnforceMinRequiredFieldsForUpload}); + ASSERT_FALSE(FormCache(web_frame).ExtractNewForms().empty()); + } } TEST_F(FormAutofillTest, WebFormElementToFormDataAutocomplete) { @@ -4601,30 +4634,42 @@ } TEST_F(FormAutofillTest, FormCache_ExtractNewForms) { + base::test::ScopedFeatureList feature_list; + feature_list.InitWithFeatures( + // Enabled. + {kAutofillEnforceMinRequiredFieldsForHeuristics, + kAutofillEnforceMinRequiredFieldsForQuery}, + // Disabled. + {kAutofillEnforceMinRequiredFieldsForUpload}); struct { + const char* description; const char* html; const bool has_extracted_form; const bool is_form_tag; const bool is_formless_checkout; } test_cases[] = { // An empty form should not be extracted - {"<FORM name='TestForm' action='http://abc.com' method='post'>" + {"Empty Form", + "<FORM name='TestForm' action='http://abc.com' method='post'>" "</FORM>", false, true, false}, // A form with less than three fields with no autocomplete type(s) should - // not be extracted. - {"<FORM name='TestForm' action='http://abc.com' method='post'>" - " <INPUT type='name' id='firstname'/>" + // be extracted because no minimum is being enforced for upload. + {"Small Form no autocomplete", + "<FORM name='TestForm' action='http://abc.com' method='post'>" + " <INPUT type='text' id='firstname'/>" "</FORM>", - false, true, false}, + true, true, false}, // A form with less than three fields with at least one autocomplete type // should be extracted. - {"<FORM name='TestForm' action='http://abc.com' method='post'>" - " <INPUT type='name' id='firstname' autocomplete='given-name'/>" + {"Small Form w/ autocomplete", + "<FORM name='TestForm' action='http://abc.com' method='post'>" + " <INPUT type='text' id='firstname' autocomplete='given-name'/>" "</FORM>", true, true, false}, // A form with three or more fields should be extracted. - {"<FORM name='TestForm' action='http://abc.com' method='post'>" + {"3 Field Form", + "<FORM name='TestForm' action='http://abc.com' method='post'>" " <INPUT type='text' id='firstname'/>" " <INPUT type='text' id='lastname'/>" " <INPUT type='text' id='email'/>" @@ -4634,21 +4679,25 @@ // An input field with an autocomplete attribute outside of a form should // be extracted. The is_formless_checkout attribute should // then be true. - {"<INPUT type='text' id='firstname' autocomplete='given-name'/>" + {"Small, formless, with autocomplete", + "<INPUT type='text' id='firstname' autocomplete='given-name'/>" "<INPUT type='submit' value='Send'/>", true, false, false}, - // An input field without an autocomplete attribute outside of a form - // should not be extracted. - {"<INPUT type='text' id='firstname'/>" + // An input field without an autocomplete attribute outside of a form, + // with no checkout hints, should not be extracted. + {"Small, formless, no autocomplete", + "<INPUT type='text' id='firstname'/>" "<INPUT type='submit' value='Send'/>", false, false, false}, - // A form with one field which is password should not be extracted. - {"<FORM name='TestForm' action='http://abc.com' method='post'>" + // A form with one field which is password gets extracted. + {"Password-Only", + "<FORM name='TestForm' action='http://abc.com' method='post'>" " <INPUT type='password' id='pw'/>" "</FORM>", - false, true, false}, + true, true, false}, // A form with two fields which are passwords should be extracted. - {"<FORM name='TestForm' action='http://abc.com' method='post'>" + {"two passwords", + "<FORM name='TestForm' action='http://abc.com' method='post'>" " <INPUT type='password' id='pw'/>" " <INPUT type='password' id='new_pw'/>" "</FORM>", @@ -4656,6 +4705,7 @@ }; for (auto test_case : test_cases) { + SCOPED_TRACE(test_case.description); LoadHTML(test_case.html); WebLocalFrame* web_frame = GetMainFrame();
diff --git a/chrome/renderer/autofill/password_autofill_agent_browsertest.cc b/chrome/renderer/autofill/password_autofill_agent_browsertest.cc index 1001499..cbd00380 100644 --- a/chrome/renderer/autofill/password_autofill_agent_browsertest.cc +++ b/chrome/renderer/autofill/password_autofill_agent_browsertest.cc
@@ -25,11 +25,11 @@ #include "components/autofill/core/common/password_form.h" #include "components/autofill/core/common/password_form_field_prediction_map.h" #include "components/password_manager/core/common/password_manager_features.h" -#include "content/public/common/associated_interface_provider.h" #include "content/public/renderer/render_frame.h" #include "content/public/renderer/render_view.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" #include "third_party/WebKit/public/platform/WebString.h" #include "third_party/WebKit/public/platform/WebVector.h" #include "third_party/WebKit/public/web/WebDocument.h" @@ -347,7 +347,7 @@ // Because the test cases only involve the main frame in this test, // the fake password client is only used for the main frame. - content::AssociatedInterfaceProvider* remote_associated_interfaces = + blink::AssociatedInterfaceProvider* remote_associated_interfaces = view_->GetMainRenderFrame()->GetRemoteAssociatedInterfaces(); remote_associated_interfaces->OverrideBinderForTesting( mojom::PasswordManagerClient::Name_,
diff --git a/chrome/renderer/autofill/password_generation_agent_browsertest.cc b/chrome/renderer/autofill/password_generation_agent_browsertest.cc index 4b1b1b0..be8a417a 100644 --- a/chrome/renderer/autofill/password_generation_agent_browsertest.cc +++ b/chrome/renderer/autofill/password_generation_agent_browsertest.cc
@@ -22,11 +22,11 @@ #include "components/autofill/core/common/form_data.h" #include "components/autofill/core/common/password_generation_util.h" #include "components/password_manager/core/common/password_manager_features.h" -#include "content/public/common/associated_interface_provider.h" #include "content/public/renderer/render_frame.h" #include "content/public/renderer/render_view.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" #include "third_party/WebKit/public/platform/WebString.h" #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" @@ -58,7 +58,7 @@ // Because the test cases only involve the main frame in this test, // the fake password client is only used for the main frame. - content::AssociatedInterfaceProvider* remote_associated_interfaces = + blink::AssociatedInterfaceProvider* remote_associated_interfaces = view_->GetMainRenderFrame()->GetRemoteAssociatedInterfaces(); remote_associated_interfaces->OverrideBinderForTesting( mojom::PasswordManagerClient::Name_,
diff --git a/chrome/renderer/chrome_content_renderer_client.cc b/chrome/renderer/chrome_content_renderer_client.cc index 90fdd72..5dc888b 100644 --- a/chrome/renderer/chrome_content_renderer_client.cc +++ b/chrome/renderer/chrome_content_renderer_client.cc
@@ -91,7 +91,6 @@ #include "components/version_info/version_info.h" #include "components/visitedlink/renderer/visitedlink_slave.h" #include "components/web_cache/renderer/web_cache_impl.h" -#include "content/public/common/associated_interface_provider.h" #include "content/public/common/content_constants.h" #include "content/public/common/content_features.h" #include "content/public/common/content_switches.h" @@ -113,6 +112,7 @@ #include "printing/features/features.h" #include "services/service_manager/public/cpp/connector.h" #include "services/service_manager/public/cpp/interface_provider.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" #include "third_party/WebKit/common/page/page_visibility_state.mojom.h" #include "third_party/WebKit/public/platform/URLConversion.h" #include "third_party/WebKit/public/platform/WebCache.h" @@ -628,7 +628,16 @@ #endif // !defined(OS_ANDROID) #if BUILDFLAG(ENABLE_SPELLCHECK) - new SpellCheckProvider(render_frame, spellcheck_.get(), this); + SpellCheckProvider* spell_check_provider = + new SpellCheckProvider(render_frame, spellcheck_.get(), this); + // TODO(xiaochengh): Design better way to sync between Chrome-side and + // Blink-side spellcheck enabled states. See crbug.com/710097. + // + // TODO(alexmos): Do this for all frames so that this works properly for + // OOPIFs. See https://crbug.com/789273. + if (render_frame->IsMainFrame()) + spell_check_provider->EnableSpellcheck(spellcheck_->IsSpellcheckEnabled()); + #if BUILDFLAG(HAS_SPELLCHECK_PANEL) new SpellCheckPanel(render_frame, registry, this); #endif // BUILDFLAG(HAS_SPELLCHECK_PANEL) @@ -640,16 +649,6 @@ void ChromeContentRendererClient::RenderViewCreated( content::RenderView* render_view) { -#if BUILDFLAG(ENABLE_SPELLCHECK) - // This is a workaround keeping the behavior that, the Blink side spellcheck - // enabled state is initialized on RenderView creation. - // TODO(xiaochengh): Design better way to sync between Chrome-side and - // Blink-side spellcheck enabled states. See crbug.com/710097. - if (SpellCheckProvider* provider = - SpellCheckProvider::Get(render_view->GetMainRenderFrame())) - provider->EnableSpellcheck(spellcheck_->IsSpellcheckEnabled()); -#endif // BUILDFLAG(ENABLE_SPELLCHECK) - new prerender::PrerendererClient(render_view); new ChromeRenderViewObserver(render_view, web_cache_impl_.get());
diff --git a/chrome/renderer/chrome_render_frame_observer.cc b/chrome/renderer/chrome_render_frame_observer.cc index c0c96dae..1ef6d21 100644 --- a/chrome/renderer/chrome_render_frame_observer.cc +++ b/chrome/renderer/chrome_render_frame_observer.cc
@@ -27,8 +27,6 @@ #include "chrome/renderer/safe_browsing/phishing_classifier_delegate.h" #include "chrome/renderer/web_apps.h" #include "components/translate/content/renderer/translate_helper.h" -#include "content/public/common/associated_interface_provider.h" -#include "content/public/common/associated_interface_registry.h" #include "content/public/common/bindings_policy.h" #include "content/public/renderer/render_frame.h" #include "content/public/renderer/render_view.h" @@ -37,6 +35,8 @@ #include "printing/features/features.h" #include "services/service_manager/public/cpp/binder_registry.h" #include "skia/ext/image_operations.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_registry.h" #include "third_party/WebKit/public/platform/WebImage.h" #include "third_party/WebKit/public/platform/WebURLRequest.h" #include "third_party/WebKit/public/web/WebDocument.h"
diff --git a/chrome/renderer/chrome_render_thread_observer.cc b/chrome/renderer/chrome_render_thread_observer.cc index 42143d1..aa704c2 100644 --- a/chrome/renderer/chrome_render_thread_observer.cc +++ b/chrome/renderer/chrome_render_thread_observer.cc
@@ -40,7 +40,6 @@ #include "chrome/renderer/security_filter_peer.h" #include "components/visitedlink/renderer/visitedlink_slave.h" #include "content/public/child/child_thread.h" -#include "content/public/common/associated_interface_registry.h" #include "content/public/common/content_switches.h" #include "content/public/common/resource_response.h" #include "content/public/common/service_manager_connection.h" @@ -58,6 +57,7 @@ #include "net/base/net_module.h" #include "services/service_manager/public/cpp/binder_registry.h" #include "services/service_manager/public/cpp/connector.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_registry.h" #include "third_party/WebKit/public/platform/WebCache.h" #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebFrame.h" @@ -296,14 +296,14 @@ ChromeRenderThreadObserver::~ChromeRenderThreadObserver() {} void ChromeRenderThreadObserver::RegisterMojoInterfaces( - content::AssociatedInterfaceRegistry* associated_interfaces) { + blink::AssociatedInterfaceRegistry* associated_interfaces) { associated_interfaces->AddInterface(base::Bind( &ChromeRenderThreadObserver::OnRendererConfigurationAssociatedRequest, base::Unretained(this))); } void ChromeRenderThreadObserver::UnregisterMojoInterfaces( - content::AssociatedInterfaceRegistry* associated_interfaces) { + blink::AssociatedInterfaceRegistry* associated_interfaces) { associated_interfaces->RemoveInterface( chrome::mojom::RendererConfiguration::Name_); }
diff --git a/chrome/renderer/chrome_render_thread_observer.h b/chrome/renderer/chrome_render_thread_observer.h index 7830d605..2d401850 100644 --- a/chrome/renderer/chrome_render_thread_observer.h +++ b/chrome/renderer/chrome_render_thread_observer.h
@@ -47,9 +47,9 @@ private: // content::RenderThreadObserver: void RegisterMojoInterfaces( - content::AssociatedInterfaceRegistry* associated_interfaces) override; + blink::AssociatedInterfaceRegistry* associated_interfaces) override; void UnregisterMojoInterfaces( - content::AssociatedInterfaceRegistry* associated_interfaces) override; + blink::AssociatedInterfaceRegistry* associated_interfaces) override; // chrome::mojom::RendererConfiguration: void SetInitialConfiguration(bool is_incognito_process) override;
diff --git a/chrome/renderer/content_settings_observer.cc b/chrome/renderer/content_settings_observer.cc index 82f86b2eb..61709b76 100644 --- a/chrome/renderer/content_settings_observer.cc +++ b/chrome/renderer/content_settings_observer.cc
@@ -16,7 +16,6 @@ #include "components/content_settings/core/common/content_settings.mojom.h" #include "components/content_settings/core/common/content_settings_pattern.h" #include "components/content_settings/core/common/content_settings_utils.h" -#include "content/public/common/associated_interface_provider.h" #include "content/public/common/origin_util.h" #include "content/public/common/previews_state.h" #include "content/public/common/url_constants.h" @@ -24,6 +23,7 @@ #include "content/public/renderer/render_frame.h" #include "content/public/renderer/render_view.h" #include "extensions/features/features.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" #include "third_party/WebKit/public/platform/URLConversion.h" #include "third_party/WebKit/public/platform/WebClientHintsType.h" #include "third_party/WebKit/public/platform/WebContentSettingCallbacks.h"
diff --git a/chrome/renderer/extensions/extension_hooks_delegate.cc b/chrome/renderer/extensions/extension_hooks_delegate.cc index b3d92a9..4e4577ea 100644 --- a/chrome/renderer/extensions/extension_hooks_delegate.cc +++ b/chrome/renderer/extensions/extension_hooks_delegate.cc
@@ -73,6 +73,20 @@ runtime_obj->Get(context, property_name).ToLocalChecked()); } +// A helper method to throw a deprecation error on access. +void ThrowDeprecatedAccessError( + v8::Local<v8::Name> name, + const v8::PropertyCallbackInfo<v8::Value>& info) { + static constexpr char kError[] = + "extension.sendRequest, extension.onRequest, and " + "extension.onRequestExternal are deprecated. Please use " + "runtime.sendMessage, runtime.onMessage, and runtime.onMessageExternal " + "instead."; + v8::Isolate* isolate = info.GetIsolate(); + isolate->ThrowException( + v8::Exception::Error(gin::StringToV8(isolate, kError))); +} + } // namespace ExtensionHooksDelegate::ExtensionHooksDelegate( @@ -134,7 +148,7 @@ v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> object_template, const APITypeReferenceMap& type_refs) { - static const char* const kAliases[] = { + static constexpr const char* kAliases[] = { "connect", "connectNative", "sendMessage", "sendNativeMessage", "onConnect", "onConnectExternal", "onMessage", "onMessageExternal", }; @@ -145,10 +159,34 @@ } } +void ExtensionHooksDelegate::InitializeInstance( + v8::Local<v8::Context> context, + v8::Local<v8::Object> instance) { + // Throw access errors for deprecated sendRequest-related properties. This + // isn't terribly efficient, but is only done for certain unpacked extensions + // and only if they access the chrome.extension module. + if (messaging_util::IsSendRequestDisabled( + ScriptContextSet::GetContextByV8Context(context))) { + static constexpr const char* kDeprecatedSendRequestProperties[] = { + "sendRequest", "onRequest", "onRequestExternal"}; + for (const char* property : kDeprecatedSendRequestProperties) { + v8::Maybe<bool> success = instance->SetAccessor( + context, gin::StringToV8(context->GetIsolate(), property), + &ThrowDeprecatedAccessError); + DCHECK(success.IsJust()); + DCHECK(success.FromJust()); + } + } +} + RequestResult ExtensionHooksDelegate::HandleSendRequest( ScriptContext* script_context, const std::vector<v8::Local<v8::Value>>& arguments) { DCHECK_EQ(3u, arguments.size()); + // This DCHECK() is correct because no context with sendRequest-related + // APIs disabled should have scriptable access to a context with them + // enabled. + DCHECK(!messaging_util::IsSendRequestDisabled(script_context)); std::string target_id; std::string error;
diff --git a/chrome/renderer/extensions/extension_hooks_delegate.h b/chrome/renderer/extensions/extension_hooks_delegate.h index a227d191..859de38 100644 --- a/chrome/renderer/extensions/extension_hooks_delegate.h +++ b/chrome/renderer/extensions/extension_hooks_delegate.h
@@ -32,6 +32,8 @@ void InitializeTemplate(v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> object_template, const APITypeReferenceMap& type_refs) override; + void InitializeInstance(v8::Local<v8::Context> context, + v8::Local<v8::Object> instance) override; private: // Request handlers for the corresponding API methods.
diff --git a/chrome/renderer/extensions/extension_hooks_delegate_unittest.cc b/chrome/renderer/extensions/extension_hooks_delegate_unittest.cc index 1383b2b..536f798 100644 --- a/chrome/renderer/extensions/extension_hooks_delegate_unittest.cc +++ b/chrome/renderer/extensions/extension_hooks_delegate_unittest.cc
@@ -6,6 +6,7 @@ #include "base/strings/stringprintf.h" #include "extensions/common/extension_builder.h" +#include "extensions/common/value_builder.h" #include "extensions/renderer/bindings/api_binding_test_util.h" #include "extensions/renderer/message_target.h" #include "extensions/renderer/messaging_util.h" @@ -107,4 +108,57 @@ SendMessageTester::OPEN); } +TEST_F(ExtensionHooksDelegateTest, SendRequestDisabled) { + // Construct an extension for which sendRequest is disabled (unpacked + // extension with an event page). + // TODO(devlin): Add a SetBackgroundPage() to ExtensionBuilder? + scoped_refptr<Extension> extension = + ExtensionBuilder("foo") + .MergeManifest( + DictionaryBuilder() + .Set("background", DictionaryBuilder() + .SetBoolean("persistent", false) + .Set("page", "page.html") + .Build()) + .Build()) + .SetLocation(Manifest::UNPACKED) + .Build(); + RegisterExtension(extension); + + v8::HandleScope handle_scope(isolate()); + v8::Local<v8::Context> context = AddContext(); + ScriptContext* script_context = CreateScriptContext( + context, extension.get(), Feature::BLESSED_EXTENSION_CONTEXT); + script_context->set_url(extension->url()); + bindings_system()->UpdateBindingsForContext(script_context); + ASSERT_TRUE(messaging_util::IsSendRequestDisabled(script_context)); + + enum AccessBehavior { + THROWS, + DOESNT_THROW, + }; + + auto check_access = [context](const char* object, AccessBehavior behavior) { + SCOPED_TRACE(object); + constexpr char kExpectedError[] = + "Uncaught Error: extension.sendRequest, extension.onRequest, and " + "extension.onRequestExternal are deprecated. Please use " + "runtime.sendMessage, runtime.onMessage, and runtime.onMessageExternal " + "instead."; + v8::Local<v8::Function> function = FunctionFromString( + context, base::StringPrintf("(function() {%s;})", object)); + if (behavior == THROWS) + RunFunctionAndExpectError(function, context, 0, nullptr, kExpectedError); + else + RunFunction(function, context, 0, nullptr); + }; + + check_access("chrome.extension.sendRequest", THROWS); + check_access("chrome.extension.onRequest", THROWS); + check_access("chrome.extension.onRequestExternal", THROWS); + check_access("chrome.extension.sendMessage", DOESNT_THROW); + check_access("chrome.extension.onMessage", DOESNT_THROW); + check_access("chrome.extension.onMessageExternal", DOESNT_THROW); +} + } // namespace extensions
diff --git a/chrome/renderer/extensions/webstore_bindings.cc b/chrome/renderer/extensions/webstore_bindings.cc index 6eb2635..4ba42f3 100644 --- a/chrome/renderer/extensions/webstore_bindings.cc +++ b/chrome/renderer/extensions/webstore_bindings.cc
@@ -10,11 +10,11 @@ #include "base/strings/string_util.h" #include "chrome/common/extensions/api/webstore/webstore_api_constants.h" #include "components/crx_file/id_util.h" -#include "content/public/common/associated_interface_provider.h" #include "content/public/renderer/render_frame.h" #include "extensions/common/extension.h" #include "extensions/common/extension_urls.h" #include "extensions/renderer/script_context.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebElement.h" #include "third_party/WebKit/public/web/WebLocalFrame.h"
diff --git a/chrome/renderer/net/net_error_helper.cc b/chrome/renderer/net/net_error_helper.cc index 862b4744..1470aff 100644 --- a/chrome/renderer/net/net_error_helper.cc +++ b/chrome/renderer/net/net_error_helper.cc
@@ -23,8 +23,6 @@ #include "components/error_page/common/localized_error.h" #include "components/error_page/common/net_error_info.h" #include "components/grit/components_resources.h" -#include "content/public/common/associated_interface_provider.h" -#include "content/public/common/associated_interface_registry.h" #include "content/public/common/content_client.h" #include "content/public/common/url_constants.h" #include "content/public/renderer/child_url_loader_factory_getter.h" @@ -37,6 +35,8 @@ #include "ipc/ipc_message.h" #include "ipc/ipc_message_macros.h" #include "net/traffic_annotation/network_traffic_annotation.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_registry.h" #include "third_party/WebKit/public/platform/WebSecurityOrigin.h" #include "third_party/WebKit/public/platform/WebURL.h" #include "third_party/WebKit/public/platform/WebURLRequest.h"
diff --git a/chrome/renderer/page_load_metrics/metrics_render_frame_observer.cc b/chrome/renderer/page_load_metrics/metrics_render_frame_observer.cc index ec805e12..6271c04 100644 --- a/chrome/renderer/page_load_metrics/metrics_render_frame_observer.cc +++ b/chrome/renderer/page_load_metrics/metrics_render_frame_observer.cc
@@ -12,9 +12,8 @@ #include "base/timer/timer.h" #include "chrome/renderer/page_load_metrics/page_timing_metrics_sender.h" #include "chrome/renderer/page_load_metrics/page_timing_sender.h" -#include "chrome/renderer/searchbox/search_bouncer.h" -#include "content/public/common/associated_interface_provider.h" #include "content/public/renderer/render_frame.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebDocumentLoader.h" #include "third_party/WebKit/public/web/WebLocalFrame.h"
diff --git a/chrome/renderer/plugins/chrome_plugin_placeholder.cc b/chrome/renderer/plugins/chrome_plugin_placeholder.cc index 1c453ad..7a814bb 100644 --- a/chrome/renderer/plugins/chrome_plugin_placeholder.cc +++ b/chrome/renderer/plugins/chrome_plugin_placeholder.cc
@@ -25,14 +25,14 @@ #include "chrome/renderer/plugins/plugin_preroller.h" #include "chrome/renderer/plugins/plugin_uma.h" #include "components/strings/grit/components_strings.h" -#include "content/public/common/associated_interface_provider.h" -#include "content/public/common/associated_interface_registry.h" #include "content/public/common/content_switches.h" #include "content/public/common/context_menu_params.h" #include "content/public/renderer/render_frame.h" #include "content/public/renderer/render_thread.h" #include "gin/object_template_builder.h" #include "ipc/ipc_sync_channel.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_registry.h" #include "third_party/WebKit/public/platform/URLConversion.h" #include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/WebKit/public/platform/WebMouseEvent.h"
diff --git a/chrome/renderer/plugins/non_loadable_plugin_placeholder.cc b/chrome/renderer/plugins/non_loadable_plugin_placeholder.cc index 4bf1993..7eec985 100644 --- a/chrome/renderer/plugins/non_loadable_plugin_placeholder.cc +++ b/chrome/renderer/plugins/non_loadable_plugin_placeholder.cc
@@ -11,8 +11,8 @@ #include "components/plugins/renderer/plugin_placeholder.h" #include "components/strings/grit/components_strings.h" #include "content/app/strings/grit/content_strings.h" -#include "content/public/common/associated_interface_provider.h" #include "content/public/renderer/render_frame.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/webui/jstemplate_builder.h"
diff --git a/chrome/renderer/searchbox/search_bouncer.cc b/chrome/renderer/searchbox/search_bouncer.cc index 33daac1..d63de8ab 100644 --- a/chrome/renderer/searchbox/search_bouncer.cc +++ b/chrome/renderer/searchbox/search_bouncer.cc
@@ -23,7 +23,7 @@ } void SearchBouncer::RegisterMojoInterfaces( - content::AssociatedInterfaceRegistry* associated_interfaces) { + blink::AssociatedInterfaceRegistry* associated_interfaces) { // Note: Unretained is safe here because this class is a leaky LazyInstance. // For the same reason, UnregisterMojoInterfaces isn't required. associated_interfaces->AddInterface(base::Bind(
diff --git a/chrome/renderer/searchbox/search_bouncer.h b/chrome/renderer/searchbox/search_bouncer.h index 9eaa5413..ca1886a 100644 --- a/chrome/renderer/searchbox/search_bouncer.h +++ b/chrome/renderer/searchbox/search_bouncer.h
@@ -7,9 +7,9 @@ #include "base/macros.h" #include "chrome/common/search.mojom.h" -#include "content/public/common/associated_interface_registry.h" #include "content/public/renderer/render_thread_observer.h" #include "mojo/public/cpp/bindings/associated_binding.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_registry.h" #include "url/gurl.h" // SearchBouncer tracks a set of URLs which should be transferred back to the @@ -24,7 +24,7 @@ // RenderThreadObserver: void RegisterMojoInterfaces( - content::AssociatedInterfaceRegistry* associated_interfaces) override; + blink::AssociatedInterfaceRegistry* associated_interfaces) override; // Returns whether a navigation to |url| should bounce back to the browser as // a potential Instant url. See search::ShouldAssignURLToInstantRenderer().
diff --git a/chrome/renderer/searchbox/searchbox.cc b/chrome/renderer/searchbox/searchbox.cc index 000f6f9..3a6bc70 100644 --- a/chrome/renderer/searchbox/searchbox.cc +++ b/chrome/renderer/searchbox/searchbox.cc
@@ -19,10 +19,10 @@ #include "chrome/renderer/searchbox/searchbox_extension.h" #include "components/favicon_base/favicon_types.h" #include "components/favicon_base/favicon_url_parser.h" -#include "content/public/common/associated_interface_provider.h" -#include "content/public/common/associated_interface_registry.h" #include "content/public/renderer/render_frame.h" #include "content/public/renderer/render_view.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_registry.h" #include "third_party/WebKit/public/web/WebFrame.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" #include "third_party/WebKit/public/web/WebPerformance.h"
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index d5a05b3..104b3b00 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -73,6 +73,8 @@ "base/test_browser_window.h", "base/test_launcher_utils.cc", "base/test_launcher_utils.h", + "base/test_service_manager_listener.cc", + "base/test_service_manager_listener.h", "base/test_switches.cc", "base/test_switches.h", "base/testing_browser_process.cc", @@ -435,6 +437,7 @@ "../browser/banners/app_banner_manager_browsertest.cc", "../browser/bitmap_fetcher/bitmap_fetcher_browsertest.cc", "../browser/browser_encoding_browsertest.cc", + "../browser/browser_shutdown_browsertest.cc", "../browser/browsing_data/autofill_counter_browsertest.cc", "../browser/browsing_data/browsing_data_cache_storage_helper_browsertest.cc", "../browser/browsing_data/browsing_data_database_helper_browsertest.cc", @@ -648,7 +651,7 @@ "../browser/safe_browsing/test_safe_browsing_database_helper.cc", "../browser/safe_browsing/test_safe_browsing_database_helper.h", "../browser/safe_json_parser_browsertest.cc", - "../browser/search/hotword_installer_browsertest.cc", + "../browser/safe_xml_parser_browsertest.cc", "../browser/search/suggestions/image_fetcher_impl_browsertest.cc", "../browser/search_engines/template_url_scraper_browsertest.cc", "../browser/secure_origin_whitelist_browsertest.cc", @@ -753,6 +756,7 @@ "../browser/ui/search/instant_theme_browsertest.cc", "../browser/ui/search/local_ntp_browsertest.cc", "../browser/ui/search/local_ntp_doodle_browsertest.cc", + "../browser/ui/search/local_ntp_js_browsertest.cc", "../browser/ui/search/local_ntp_one_google_bar_browsertest.cc", "../browser/ui/search/local_ntp_test_utils.cc", "../browser/ui/search/local_ntp_test_utils.h", @@ -1228,7 +1232,6 @@ "../browser/extensions/external_install_error_browsertest.cc", "../browser/extensions/fetch_apitest.cc", "../browser/extensions/gpu_browsertest.cc", - "../browser/extensions/hotword_browsertest.cc", "../browser/extensions/isolated_app_browsertest.cc", "../browser/extensions/lazy_background_page_apitest.cc", "../browser/extensions/lazy_background_page_test_util.h", @@ -1564,7 +1567,6 @@ "../browser/download/notification/download_notification_browsertest.cc", "../browser/drive/drive_notification_manager_factory_browsertest.cc", "../browser/extensions/api/certificate_provider/certificate_provider_apitest.cc", - "../browser/extensions/api/hotword_private/hotword_private_apitest.cc", "../browser/extensions/api/networking_private/networking_private_apitest.cc", "../browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc", "../browser/extensions/api/vpn_provider/vpn_provider_apitest.cc", @@ -3230,7 +3232,6 @@ "../browser/safe_browsing/settings_reset_prompt/settings_reset_prompt_test_utils.cc", "../browser/safe_browsing/settings_reset_prompt/settings_reset_prompt_test_utils.h", "../browser/safe_search_api/safe_search_url_checker_unittest.cc", - "../browser/search/hotword_service_unittest.cc", "../browser/signin/easy_unlock_app_manager_unittest.cc", "../browser/signin/easy_unlock_auth_attempt_unittest.cc", "../browser/signin/easy_unlock_notification_controller_chromeos_unittest.cc",
diff --git a/chrome/test/base/mash_browser_tests_main.cc b/chrome/test/base/mash_browser_tests_main.cc index 7b07c3a0..9f24c6b 100644 --- a/chrome/test/base/mash_browser_tests_main.cc +++ b/chrome/test/base/mash_browser_tests_main.cc
@@ -42,6 +42,8 @@ content::GetContentMainParams()->env_mode = aura::Env::Mode::MUS; content::GetContentMainParams()->create_discardable_memory = (config_ == AshConfig::MUS); + base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( + switches::kMus, switches::kMusHostVizValue); return ChromeTestLauncherDelegate::RunTestSuite(argc, argv); }
diff --git a/chrome/test/base/test_service_manager_listener.cc b/chrome/test/base/test_service_manager_listener.cc new file mode 100644 index 0000000..4ce21ff --- /dev/null +++ b/chrome/test/base/test_service_manager_listener.cc
@@ -0,0 +1,77 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/test/base/test_service_manager_listener.h" + +#include "base/run_loop.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/common/service_manager_connection.h" +#include "services/service_manager/public/cpp/connector.h" + +TestServiceManagerListener::TestServiceManagerListener() : binding_(this) {} + +TestServiceManagerListener::~TestServiceManagerListener() {} + +void TestServiceManagerListener::Init() { + DCHECK(!binding_.is_bound()); + // Register a listener on the ServiceManager to track when services are + // started. + mojo::InterfacePtr<service_manager::mojom::ServiceManager> service_manager; + service_manager::Connector* connector = + content::ServiceManagerConnection::GetForProcess()->GetConnector(); + connector->BindInterface(service_manager::mojom::kServiceName, + &service_manager); + service_manager::mojom::ServiceManagerListenerPtr listener_ptr; + binding_.Bind(mojo::MakeRequest(&listener_ptr)); + service_manager->AddListener(std::move(listener_ptr)); +} + +void TestServiceManagerListener::WaitUntilServiceStarted( + const std::string& service_name) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + DCHECK(!on_service_event_loop_closure_); + DCHECK(service_name_.empty()); + service_name_ = service_name; + base::RunLoop run_loop; + on_service_event_loop_closure_ = run_loop.QuitClosure(); + run_loop.Run(); + on_service_event_loop_closure_.Reset(); +} + +uint32_t TestServiceManagerListener::GetServiceStartCount( + const std::string& service_name) const { + auto iter = service_start_counters_.find(service_name); + return iter == service_start_counters_.end() ? 0 : iter->second; +} + +void TestServiceManagerListener::OnInit( + std::vector<service_manager::mojom::RunningServiceInfoPtr> + running_services) {} + +void TestServiceManagerListener::OnServiceCreated( + service_manager::mojom::RunningServiceInfoPtr service) {} + +void TestServiceManagerListener::OnServiceStarted( + const service_manager::Identity& identity, + uint32_t pid) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + + service_start_counters_[identity.name()]++; + + if (identity.name() != service_name_) + return; + + service_name_.clear(); + std::move(on_service_event_loop_closure_).Run(); +} + +void TestServiceManagerListener::OnServicePIDReceived( + const service_manager::Identity& identity, + uint32_t pid) {} + +void TestServiceManagerListener::OnServiceFailedToStart( + const service_manager::Identity& identity) {} + +void TestServiceManagerListener::OnServiceStopped( + const service_manager::Identity& identity) {}
diff --git a/chrome/test/base/test_service_manager_listener.h b/chrome/test/base/test_service_manager_listener.h new file mode 100644 index 0000000..175ccbe --- /dev/null +++ b/chrome/test/base/test_service_manager_listener.h
@@ -0,0 +1,59 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_TEST_BASE_TEST_SERVICE_MANAGER_LISTENER_H_ +#define CHROME_TEST_BASE_TEST_SERVICE_MANAGER_LISTENER_H_ + +#include <cstdint> +#include <map> +#include <string> +#include <vector> + +#include "base/callback_forward.h" +#include "base/macros.h" +#include "mojo/public/cpp/bindings/binding.h" +#include "services/service_manager/public/interfaces/service_manager.mojom.h" + +namespace service_manager { +class Identity; +} + +// This class lets us wait for services to be started and tracks how many times +// a service was started. +class TestServiceManagerListener + : public service_manager::mojom::ServiceManagerListener { + public: + TestServiceManagerListener(); + ~TestServiceManagerListener() override; + + // Must be called once before the other public methods can be used. + void Init(); + + void WaitUntilServiceStarted(const std::string& service_name); + uint32_t GetServiceStartCount(const std::string& service_name) const; + + private: + // service_manager::mojom::ServiceManagerListener implementation: + void OnInit(std::vector<service_manager::mojom::RunningServiceInfoPtr> + running_services) override; + void OnServiceCreated( + service_manager::mojom::RunningServiceInfoPtr service) override; + void OnServiceStarted(const service_manager::Identity& identity, + uint32_t pid) override; + void OnServicePIDReceived(const service_manager::Identity& identity, + uint32_t pid) override; + void OnServiceFailedToStart( + const service_manager::Identity& identity) override; + void OnServiceStopped(const service_manager::Identity& identity) override; + + base::Closure on_service_event_loop_closure_; + std::string service_name_; + std::map<std::string, uint32_t> service_start_counters_; + + mojo::Binding<service_manager::mojom::ServiceManagerListener> binding_; + + DISALLOW_COPY_AND_ASSIGN(TestServiceManagerListener); +}; + +#endif // CHROME_TEST_BASE_TEST_SERVICE_MANAGER_LISTENER_H_
diff --git a/chrome/test/base/ui_test_utils.h b/chrome/test/base/ui_test_utils.h index fac5d03..72beb06 100644 --- a/chrome/test/base/ui_test_utils.h +++ b/chrome/test/base/ui_test_utils.h
@@ -307,7 +307,7 @@ // chrome::BrowserListObserver override: void OnBrowserSetLastActive(Browser* browser) override; - const Browser* browser_; + const Browser* const browser_; bool observed_; scoped_refptr<content::MessageLoopRunner> message_loop_runner_;
diff --git a/chrome/test/data/devtools/dispatch_key_event_shows_auto_fill.html b/chrome/test/data/devtools/dispatch_key_event_shows_auto_fill.html index e418575..fcc91be 100644 --- a/chrome/test/data/devtools/dispatch_key_event_shows_auto_fill.html +++ b/chrome/test/data/devtools/dispatch_key_event_shows_auto_fill.html
@@ -9,13 +9,14 @@ console.log("ready"); return; } + document.getElementById("name").value = "Abbf"; document.getElementById("submit").click(); } </script> </head> <body onload="run()"> <form action="?" onsubmit="this.action += window.location.hash"> - <input type="text" id="name" name="name" value="Abbf" /> + <input type="text" id="name" name="name" value="" /> <input type="submit" id="submit" value="submit" /> </form> </body>
diff --git a/chrome/test/data/extensions/api_test/hotword_private/alwaysOnEnabled/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/alwaysOnEnabled/manifest.json deleted file mode 100644 index a6028ee..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/alwaysOnEnabled/manifest.json +++ /dev/null
@@ -1,11 +0,0 @@ -{ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -}
diff --git a/chrome/test/data/extensions/api_test/hotword_private/alwaysOnEnabled/test.js b/chrome/test/data/extensions/api_test/hotword_private/alwaysOnEnabled/test.js deleted file mode 100644 index 97f6973..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/alwaysOnEnabled/test.js +++ /dev/null
@@ -1,12 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function alwaysOnEnabled() { - chrome.hotwordPrivate.getStatus( - chrome.test.callbackPass(function(result) { - chrome.test.sendMessage("alwaysOnEnabled: " + result.alwaysOnEnabled); - })); - } -]);
diff --git a/chrome/test/data/extensions/api_test/hotword_private/audioHistory/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/audioHistory/manifest.json deleted file mode 100644 index 89dd7bc8..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/audioHistory/manifest.json +++ /dev/null
@@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -}
diff --git a/chrome/test/data/extensions/api_test/hotword_private/audioHistory/test.js b/chrome/test/data/extensions/api_test/hotword_private/audioHistory/test.js deleted file mode 100644 index 12692ef..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/audioHistory/test.js +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function audioHistory() { - chrome.hotwordPrivate.setAudioHistoryEnabled( - true, - chrome.test.callbackPass(function(state) { - if (state.success) - chrome.test.sendMessage("set AH True: "+state.enabled+" success"); - else - chrome.test.sendMessage("set AH True: "+state.enabled+" failure"); - })); - // Test with setting to false as well. - chrome.hotwordPrivate.setAudioHistoryEnabled( - false, - chrome.test.callbackPass(function(state) { - if (state.success) - chrome.test.sendMessage("set AH False: "+state.enabled+" success"); - else - chrome.test.sendMessage("set AH False: "+state.enabled+" failure"); - })); - chrome.hotwordPrivate.getAudioHistoryEnabled(chrome.test.callbackPass( - function(state) { - if (state.success) - chrome.test.sendMessage("get AH: "+state.enabled+" success"); - else - chrome.test.sendMessage("get AH: "+state.enabled+" failure"); - })); - } -]);
diff --git a/chrome/test/data/extensions/api_test/hotword_private/getEnabled/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/getEnabled/manifest.json deleted file mode 100644 index 89dd7bc8..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/getEnabled/manifest.json +++ /dev/null
@@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -}
diff --git a/chrome/test/data/extensions/api_test/hotword_private/getEnabled/test.js b/chrome/test/data/extensions/api_test/hotword_private/getEnabled/test.js deleted file mode 100644 index 1e86be6..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/getEnabled/test.js +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function getEnabled() { - chrome.hotwordPrivate.getStatus( - chrome.test.callbackPass(function(result) { - chrome.test.assertFalse(result.enabledSet); - })); - - chrome.hotwordPrivate.setEnabled(true, function() {}); - chrome.hotwordPrivate.getStatus( - chrome.test.callbackPass(function(result) { - chrome.test.assertTrue(result.enabled); - })); - chrome.hotwordPrivate.getStatus( - chrome.test.callbackPass(function(result) { - chrome.test.assertTrue(result.enabledSet); - })); - - chrome.hotwordPrivate.setEnabled(false, function() {}); - chrome.hotwordPrivate.getStatus( - chrome.test.callbackPass(function(result) { - chrome.test.assertFalse(result.enabled); - })); - chrome.hotwordPrivate.getStatus( - chrome.test.callbackPass(function(result) { - chrome.test.assertTrue(result.enabledSet); - })); - } -]);
diff --git a/chrome/test/data/extensions/api_test/hotword_private/getLaunchState/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/getLaunchState/manifest.json deleted file mode 100644 index a6028ee..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/getLaunchState/manifest.json +++ /dev/null
@@ -1,11 +0,0 @@ -{ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -}
diff --git a/chrome/test/data/extensions/api_test/hotword_private/getLaunchState/test.js b/chrome/test/data/extensions/api_test/hotword_private/getLaunchState/test.js deleted file mode 100644 index 957d11e5..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/getLaunchState/test.js +++ /dev/null
@@ -1,13 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function getLaunchState() { - chrome.hotwordPrivate.getLaunchState( - chrome.test.callbackPass(function(result) { - chrome.test.sendMessage("launchMode: " + - result.launchMode); - })); - } -]);
diff --git a/chrome/test/data/extensions/api_test/hotword_private/hotwordSession/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/hotwordSession/manifest.json deleted file mode 100644 index 89dd7bc8..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/hotwordSession/manifest.json +++ /dev/null
@@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -}
diff --git a/chrome/test/data/extensions/api_test/hotword_private/hotwordSession/test.js b/chrome/test/data/extensions/api_test/hotword_private/hotwordSession/test.js deleted file mode 100644 index 7f58b17..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/hotwordSession/test.js +++ /dev/null
@@ -1,28 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function hotwordSessionTest() { - chrome.hotwordPrivate.onHotwordSessionRequested.addListener(function () { - chrome.hotwordPrivate.setHotwordSessionState(true, function() { - chrome.hotwordPrivate.notifyHotwordRecognition('search', function() { - chrome.hotwordPrivate.onHotwordSessionStopped.addListener( - function() { - // Calling setHotwordSessionState and - // notifyHotwordRecognition after stopped should be ignored. - chrome.hotwordPrivate.setHotwordSessionState(false, function() { - chrome.hotwordPrivate.notifyHotwordRecognition( - 'search', function() { - chrome.test.sendMessage("stopped"); - chrome.test.succeed(); - }); - }); - }); - chrome.test.sendMessage("stopReady"); - }); - }); - }); - chrome.test.sendMessage("ready"); - } -]);
diff --git a/chrome/test/data/extensions/api_test/hotword_private/isAvailable/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/isAvailable/manifest.json deleted file mode 100644 index 89dd7bc8..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/isAvailable/manifest.json +++ /dev/null
@@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -}
diff --git a/chrome/test/data/extensions/api_test/hotword_private/isAvailable/test.js b/chrome/test/data/extensions/api_test/hotword_private/isAvailable/test.js deleted file mode 100644 index aa222696..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/isAvailable/test.js +++ /dev/null
@@ -1,13 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function isAvailable() { - chrome.hotwordPrivate.getStatus( - true, - chrome.test.callbackPass(function(result) { - chrome.test.sendMessage("available: " + result.available); - })); - } -]);
diff --git a/chrome/test/data/extensions/api_test/hotword_private/isAvailableNoGet/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/isAvailableNoGet/manifest.json deleted file mode 100644 index 89dd7bc8..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/isAvailableNoGet/manifest.json +++ /dev/null
@@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -}
diff --git a/chrome/test/data/extensions/api_test/hotword_private/isAvailableNoGet/test.js b/chrome/test/data/extensions/api_test/hotword_private/isAvailableNoGet/test.js deleted file mode 100644 index 01ef5b8..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/isAvailableNoGet/test.js +++ /dev/null
@@ -1,12 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function isAvailable() { - chrome.hotwordPrivate.getStatus( - chrome.test.callbackPass(function(result) { - chrome.test.sendMessage("available: " + result.available); - })); - } -]);
diff --git a/chrome/test/data/extensions/api_test/hotword_private/notifySpeakerModelSaved/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/notifySpeakerModelSaved/manifest.json deleted file mode 100644 index 89dd7bc8..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/notifySpeakerModelSaved/manifest.json +++ /dev/null
@@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -}
diff --git a/chrome/test/data/extensions/api_test/hotword_private/notifySpeakerModelSaved/test.js b/chrome/test/data/extensions/api_test/hotword_private/notifySpeakerModelSaved/test.js deleted file mode 100644 index 3ca6852..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/notifySpeakerModelSaved/test.js +++ /dev/null
@@ -1,12 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function notifySpeakerModelSaved() { - chrome.hotwordPrivate.notifySpeakerModelSaved( - chrome.test.callbackPass(function() { - chrome.test.sendMessage("speaker model saved"); - })); - } -]);
diff --git a/chrome/test/data/extensions/api_test/hotword_private/onDeleteSpeakerModel/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/onDeleteSpeakerModel/manifest.json deleted file mode 100644 index 89dd7bc8..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/onDeleteSpeakerModel/manifest.json +++ /dev/null
@@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -}
diff --git a/chrome/test/data/extensions/api_test/hotword_private/onDeleteSpeakerModel/test.js b/chrome/test/data/extensions/api_test/hotword_private/onDeleteSpeakerModel/test.js deleted file mode 100644 index aaa08e0..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/onDeleteSpeakerModel/test.js +++ /dev/null
@@ -1,15 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function onDeleteSpeakerModel() { - chrome.hotwordPrivate.onDeleteSpeakerModel.addListener(function () { - chrome.test.sendMessage("notification"); - chrome.test.succeed(); - }); - chrome.hotwordPrivate.getAudioHistoryEnabled( - chrome.test.callbackPass(function(state) {})); - chrome.test.sendMessage("ready"); - } -]);
diff --git a/chrome/test/data/extensions/api_test/hotword_private/onEnabledChanged/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/onEnabledChanged/manifest.json deleted file mode 100644 index 89dd7bc8..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/onEnabledChanged/manifest.json +++ /dev/null
@@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -}
diff --git a/chrome/test/data/extensions/api_test/hotword_private/onEnabledChanged/test.js b/chrome/test/data/extensions/api_test/hotword_private/onEnabledChanged/test.js deleted file mode 100644 index cd13ad63..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/onEnabledChanged/test.js +++ /dev/null
@@ -1,13 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function onEnabledChangedTest() { - chrome.hotwordPrivate.onEnabledChanged.addListener(function () { - chrome.test.sendMessage("notification"); - chrome.test.succeed(); - }); - chrome.test.sendMessage("ready"); - } -]);
diff --git a/chrome/test/data/extensions/api_test/hotword_private/onFinalizeSpeakerModel/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/onFinalizeSpeakerModel/manifest.json deleted file mode 100644 index 89dd7bc8..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/onFinalizeSpeakerModel/manifest.json +++ /dev/null
@@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -}
diff --git a/chrome/test/data/extensions/api_test/hotword_private/onFinalizeSpeakerModel/test.js b/chrome/test/data/extensions/api_test/hotword_private/onFinalizeSpeakerModel/test.js deleted file mode 100644 index 18b6399..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/onFinalizeSpeakerModel/test.js +++ /dev/null
@@ -1,13 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function onFinalizeSpeakerModel() { - chrome.hotwordPrivate.onFinalizeSpeakerModel.addListener(function () { - chrome.test.sendMessage("notification"); - chrome.test.succeed(); - }); - chrome.test.sendMessage("ready"); - } -]);
diff --git a/chrome/test/data/extensions/api_test/hotword_private/onHotwordTriggered/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/onHotwordTriggered/manifest.json deleted file mode 100644 index 89dd7bc8..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/onHotwordTriggered/manifest.json +++ /dev/null
@@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -}
diff --git a/chrome/test/data/extensions/api_test/hotword_private/onHotwordTriggered/test.js b/chrome/test/data/extensions/api_test/hotword_private/onHotwordTriggered/test.js deleted file mode 100644 index 7e62a916..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/onHotwordTriggered/test.js +++ /dev/null
@@ -1,13 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function onHotwordTriggered() { - chrome.hotwordPrivate.onHotwordTriggered.addListener(function () { - chrome.test.sendMessage("notification"); - chrome.test.succeed(); - }); - chrome.test.sendMessage("ready"); - } -]);
diff --git a/chrome/test/data/extensions/api_test/hotword_private/onSpeakerModelExists/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/onSpeakerModelExists/manifest.json deleted file mode 100644 index 89dd7bc8..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/onSpeakerModelExists/manifest.json +++ /dev/null
@@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -}
diff --git a/chrome/test/data/extensions/api_test/hotword_private/onSpeakerModelExists/test.js b/chrome/test/data/extensions/api_test/hotword_private/onSpeakerModelExists/test.js deleted file mode 100644 index a21cd08..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/onSpeakerModelExists/test.js +++ /dev/null
@@ -1,13 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function onSpeakerModelExistsTest() { - chrome.hotwordPrivate.onSpeakerModelExists.addListener(function () { - chrome.test.sendMessage("notification"); - chrome.test.succeed(); - }); - chrome.test.sendMessage("ready"); - } -]);
diff --git a/chrome/test/data/extensions/api_test/hotword_private/onSpeakerModelSaved/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/onSpeakerModelSaved/manifest.json deleted file mode 100644 index 89dd7bc8..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/onSpeakerModelSaved/manifest.json +++ /dev/null
@@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -}
diff --git a/chrome/test/data/extensions/api_test/hotword_private/onSpeakerModelSaved/test.js b/chrome/test/data/extensions/api_test/hotword_private/onSpeakerModelSaved/test.js deleted file mode 100644 index f4fc7fc..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/onSpeakerModelSaved/test.js +++ /dev/null
@@ -1,15 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function onSpeakerModelSaved() { - chrome.hotwordPrivate.onSpeakerModelSaved.addListener(function () { - chrome.test.sendMessage("notification"); - chrome.test.succeed(); - }); - chrome.hotwordPrivate.notifySpeakerModelSaved( - chrome.test.callbackPass(function() {})); - chrome.test.sendMessage("ready"); - } -]);
diff --git a/chrome/test/data/extensions/api_test/hotword_private/setAudioLoggingEnableFalse/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/setAudioLoggingEnableFalse/manifest.json deleted file mode 100644 index 89dd7bc8..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/setAudioLoggingEnableFalse/manifest.json +++ /dev/null
@@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -}
diff --git a/chrome/test/data/extensions/api_test/hotword_private/setAudioLoggingEnableFalse/test.js b/chrome/test/data/extensions/api_test/hotword_private/setAudioLoggingEnableFalse/test.js deleted file mode 100644 index 58d8452..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/setAudioLoggingEnableFalse/test.js +++ /dev/null
@@ -1,12 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function setAudioLoggingEnabledFalse() { - chrome.hotwordPrivate.setAudioLoggingEnabled( - false, chrome.test.callbackPass(function() { - chrome.test.sendMessage("ready"); - })); - } -]);
diff --git a/chrome/test/data/extensions/api_test/hotword_private/setAudioLoggingEnableTrue/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/setAudioLoggingEnableTrue/manifest.json deleted file mode 100644 index 89dd7bc8..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/setAudioLoggingEnableTrue/manifest.json +++ /dev/null
@@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -}
diff --git a/chrome/test/data/extensions/api_test/hotword_private/setAudioLoggingEnableTrue/test.js b/chrome/test/data/extensions/api_test/hotword_private/setAudioLoggingEnableTrue/test.js deleted file mode 100644 index a3c5d867..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/setAudioLoggingEnableTrue/test.js +++ /dev/null
@@ -1,12 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function setAudioLoggingEnabledTrue() { - chrome.hotwordPrivate.setAudioLoggingEnabled( - true, chrome.test.callbackPass(function() { - chrome.test.sendMessage("ready"); - })); - } -]);
diff --git a/chrome/test/data/extensions/api_test/hotword_private/setEnabledFalse/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/setEnabledFalse/manifest.json deleted file mode 100644 index 89dd7bc8..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/setEnabledFalse/manifest.json +++ /dev/null
@@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -}
diff --git a/chrome/test/data/extensions/api_test/hotword_private/setEnabledFalse/test.js b/chrome/test/data/extensions/api_test/hotword_private/setEnabledFalse/test.js deleted file mode 100644 index 32481db7..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/setEnabledFalse/test.js +++ /dev/null
@@ -1,12 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function setEnabledFalse() { - chrome.hotwordPrivate.setEnabled( - false, chrome.test.callbackPass(function() { - chrome.test.sendMessage("ready"); - })); - } -]);
diff --git a/chrome/test/data/extensions/api_test/hotword_private/setEnabledTrue/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/setEnabledTrue/manifest.json deleted file mode 100644 index 89dd7bc8..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/setEnabledTrue/manifest.json +++ /dev/null
@@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -}
diff --git a/chrome/test/data/extensions/api_test/hotword_private/setEnabledTrue/test.js b/chrome/test/data/extensions/api_test/hotword_private/setEnabledTrue/test.js deleted file mode 100644 index 1cfb2c2..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/setEnabledTrue/test.js +++ /dev/null
@@ -1,11 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function setEnabledTrue() { - chrome.hotwordPrivate.setEnabled(true, chrome.test.callbackPass(function() { - chrome.test.sendMessage("ready"); - })); - } -]);
diff --git a/chrome/test/data/extensions/api_test/hotword_private/setHotwordAlwaysOnSearchEnableFalse/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/setHotwordAlwaysOnSearchEnableFalse/manifest.json deleted file mode 100644 index 89dd7bc8..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/setHotwordAlwaysOnSearchEnableFalse/manifest.json +++ /dev/null
@@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -}
diff --git a/chrome/test/data/extensions/api_test/hotword_private/setHotwordAlwaysOnSearchEnableFalse/test.js b/chrome/test/data/extensions/api_test/hotword_private/setHotwordAlwaysOnSearchEnableFalse/test.js deleted file mode 100644 index d635d10..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/setHotwordAlwaysOnSearchEnableFalse/test.js +++ /dev/null
@@ -1,12 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function setHotwordAlwaysOnSearchEnabledFalse() { - chrome.hotwordPrivate.setHotwordAlwaysOnSearchEnabled( - false, chrome.test.callbackPass(function() { - chrome.test.sendMessage("ready"); - })); - } -]);
diff --git a/chrome/test/data/extensions/api_test/hotword_private/setHotwordAlwaysOnSearchEnableTrue/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/setHotwordAlwaysOnSearchEnableTrue/manifest.json deleted file mode 100644 index 89dd7bc8..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/setHotwordAlwaysOnSearchEnableTrue/manifest.json +++ /dev/null
@@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -}
diff --git a/chrome/test/data/extensions/api_test/hotword_private/setHotwordAlwaysOnSearchEnableTrue/test.js b/chrome/test/data/extensions/api_test/hotword_private/setHotwordAlwaysOnSearchEnableTrue/test.js deleted file mode 100644 index 0835a6a..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/setHotwordAlwaysOnSearchEnableTrue/test.js +++ /dev/null
@@ -1,12 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function setHotwordAlwaysOnSearchEnabledTrue() { - chrome.hotwordPrivate.setHotwordAlwaysOnSearchEnabled( - true, chrome.test.callbackPass(function() { - chrome.test.sendMessage("ready"); - })); - } -]);
diff --git a/chrome/test/data/extensions/api_test/hotword_private/speakerModelExistsResultFalse/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/speakerModelExistsResultFalse/manifest.json deleted file mode 100644 index 89dd7bc8..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/speakerModelExistsResultFalse/manifest.json +++ /dev/null
@@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -}
diff --git a/chrome/test/data/extensions/api_test/hotword_private/speakerModelExistsResultFalse/test.js b/chrome/test/data/extensions/api_test/hotword_private/speakerModelExistsResultFalse/test.js deleted file mode 100644 index b0b8559..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/speakerModelExistsResultFalse/test.js +++ /dev/null
@@ -1,12 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function speakerModelExistsResultFalse() { - chrome.hotwordPrivate.speakerModelExistsResult( - false, chrome.test.callbackPass(function() { - chrome.test.sendMessage("ready"); - })); - } -]);
diff --git a/chrome/test/data/extensions/api_test/hotword_private/speakerModelExistsResultTrue/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/speakerModelExistsResultTrue/manifest.json deleted file mode 100644 index 59c3612..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/speakerModelExistsResultTrue/manifest.json +++ /dev/null
@@ -1,13 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "persistent": false, - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -}
diff --git a/chrome/test/data/extensions/api_test/hotword_private/speakerModelExistsResultTrue/test.js b/chrome/test/data/extensions/api_test/hotword_private/speakerModelExistsResultTrue/test.js deleted file mode 100644 index d78f68a5..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/speakerModelExistsResultTrue/test.js +++ /dev/null
@@ -1,12 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function speakerModelExistsResultTrue() { - chrome.hotwordPrivate.speakerModelExistsResult( - true, chrome.test.callbackPass(function() { - chrome.test.sendMessage("ready"); - })); - } -]);
diff --git a/chrome/test/data/extensions/api_test/hotword_private/startTraining/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/startTraining/manifest.json deleted file mode 100644 index 89dd7bc8..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/startTraining/manifest.json +++ /dev/null
@@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -}
diff --git a/chrome/test/data/extensions/api_test/hotword_private/startTraining/test.js b/chrome/test/data/extensions/api_test/hotword_private/startTraining/test.js deleted file mode 100644 index e9636f8..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/startTraining/test.js +++ /dev/null
@@ -1,11 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function startTraining() { - chrome.hotwordPrivate.startTraining(chrome.test.callbackPass(function() { - chrome.test.sendMessage("start training"); - })); - } -]);
diff --git a/chrome/test/data/extensions/api_test/hotword_private/stopTraining/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/stopTraining/manifest.json deleted file mode 100644 index 89dd7bc8..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/stopTraining/manifest.json +++ /dev/null
@@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -}
diff --git a/chrome/test/data/extensions/api_test/hotword_private/stopTraining/test.js b/chrome/test/data/extensions/api_test/hotword_private/stopTraining/test.js deleted file mode 100644 index 379899c..0000000 --- a/chrome/test/data/extensions/api_test/hotword_private/stopTraining/test.js +++ /dev/null
@@ -1,11 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function stopTraining() { - chrome.hotwordPrivate.stopTraining(chrome.test.callbackPass(function() { - chrome.test.sendMessage("stop training"); - })); - } -]);
diff --git a/chrome/test/data/extensions/api_test/preference/standard/test.js b/chrome/test/data/extensions/api_test/preference/standard/test.js index 5022a6f..13424f2 100644 --- a/chrome/test/data/extensions/api_test/preference/standard/test.js +++ b/chrome/test/data/extensions/api_test/preference/standard/test.js
@@ -32,7 +32,6 @@ preferences: { alternateErrorPagesEnabled: false, autofillEnabled: false, - hotwordSearchEnabled: false, passwordSavingEnabled: false, safeBrowsingEnabled: false, safeBrowsingExtendedReportingEnabled: false,
diff --git a/chrome/test/data/extensions/hotword/manifest.json b/chrome/test/data/extensions/hotword/manifest.json deleted file mode 100644 index c99d6f11..0000000 --- a/chrome/test/data/extensions/hotword/manifest.json +++ /dev/null
@@ -1,11 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Helper Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser test for hotword helper extension", - "background" : { - "scripts": ["test.js"] - } -}
diff --git a/chrome/test/data/extensions/hotword/test.js b/chrome/test/data/extensions/hotword/test.js deleted file mode 100644 index 51a8c80..0000000 --- a/chrome/test/data/extensions/hotword/test.js +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// Send a WAKE_UP command to the hotword helper extension. -chrome.runtime.sendMessage( - 'dnhpdliibojhegemfjheidglijccjfmc', - {type: 'wu'}); - -// Assume messages are delivered in-order. In this case, this message will be -// handled after the previous one, and indicates the test case has completed. -chrome.runtime.sendMessage( - 'dnhpdliibojhegemfjheidglijccjfmc', - {type: 'wu'}, - function() { - chrome.test.sendMessage("done"); - });
diff --git a/chrome/test/data/italian_page.html b/chrome/test/data/italian_page.html new file mode 100644 index 0000000..0f2a6451 --- /dev/null +++ b/chrome/test/data/italian_page.html
@@ -0,0 +1,19 @@ +<html> +<head><title>Questa pagina è in italiano</title></head> +<body> +Sulle strade ed aree pubbliche sono vietate le competizioni sportive con +veicoli o animali e quelle atletiche, salvo autorizzazione. L'autorizzazione è +rilasciata dal comune in cui devono avere luogo le gare atletiche e ciclistiche +e quelle con animali o con veicoli a trazione animale. Essa è rilasciata dalla +regione e dalle province autonome di Trento e di Bolzano per le gare atletiche, +ciclistiche e per le gare con animali o con veicoli a trazione animale che +interessano più comuni. Per le gare con veicoli a motore l'autorizzazione è +rilasciata, sentite le federazioni nazionali sportive competenti e dandone +tempestiva informazione all'autorità di pubblica sicurezza: dalla regione e +dalle province autonome di Trento e di Bolzano per le strade che costituiscono +la rete di interesse nazionale; dalla regione per le strade regionali; dalle +province per le strade provinciali; dai comuni per le strade comunali. Nelle +autorizzazioni sono precisate le prescrizioni alle quali le gare sono +subordinate. +</body> +</html>
diff --git a/chrome/test/data/local_ntp/local_ntp_browsertest.js b/chrome/test/data/local_ntp/local_ntp_browsertest.js index 04da4b8d..3f032d66 100644 --- a/chrome/test/data/local_ntp/local_ntp_browsertest.js +++ b/chrome/test/data/local_ntp/local_ntp_browsertest.js
@@ -93,18 +93,8 @@ // Advanced tests are controlled from the native side. The helpers here are // called from native code to set up the page and to check results. -function handlePostMessage(event) { - if (event.data.cmd == 'loaded') { - domAutomationController.send('loaded'); - } -} - -function setupAdvancedTest(opt_waitForIframeLoaded) { - if (opt_waitForIframeLoaded) { - window.addEventListener('message', handlePostMessage); - } - +function setupAdvancedTest() { setUpPage('local-ntp-template'); initLocalNTP(/*isGooglePage=*/true);
diff --git a/chrome/test/data/webui/settings/internet_page_tests.js b/chrome/test/data/webui/settings/internet_page_tests.js index 563a9cf6..61086da0 100644 --- a/chrome/test/data/webui/settings/internet_page_tests.js +++ b/chrome/test/data/webui/settings/internet_page_tests.js
@@ -20,6 +20,8 @@ internetAddConnectionNotAllowed: 'internetAddConnectionNotAllowed', internetAddThirdPartyVPN: 'internetAddThirdPartyVPN', internetAddVPN: 'internetAddVPN', + internetAddArcVPN: 'internetAddArcVPN', + internetAddArcVPNProvider: 'internetAddArcVPNProvider', internetAddWiFi: 'internetAddWiFi', internetDetailPageTitle: 'internetDetailPageTitle', internetKnownNetworksPageTitle: 'internetKnownNetworksPageTitle', @@ -58,6 +60,10 @@ api_.addNetworksForTest(networks); } + function setArcVpnProvidersForTest(arcVpnProviders) { + cr.webUIListenerCallback('sendArcVpnProviders',arcVpnProviders); + } + setup(function() { PolymerTest.clearBody(); internetPage = document.createElement('settings-internet-page'); @@ -279,5 +285,35 @@ // party provider sections. }); }); + + test('ArcVPNProvider', function() { + setArcVpnProvidersForTest([ + { + Packagename: 'vpn.app.pacakge1', + ProviderName: 'MyArcVPN1', + AppID: 'arcid1', + LastLaunchTime: 0 + }, + { + Packagename: 'vpn.app.pacakge2', + ProviderName: 'MyArcVPN2', + AppID: 'arcid2', + LastLaunchTime: 1 + }]); + return flushAsync().then(() => { + var expandAddConnections = internetPage.$$('#expandAddConnections'); + assertTrue(!!expandAddConnections); + assertTrue(!expandAddConnections.expanded); + internetPage.addConnectionExpanded_ = true; + Polymer.dom.flush(); + var addArcVpn = internetPage.$$('#addArcVpn'); + assertTrue(!!addArcVpn); + MockInteractions.tap(addArcVpn); + Polymer.dom.flush(); + var subpage = internetPage.$$('settings-internet-subpage'); + assertTrue(!!subpage); + assertEquals(2, subpage.arcVpnProviders.length); + }); + }); }); });
diff --git a/chrome/test/data/webui/settings/quick_unlock_authenticate_browsertest_chromeos.js b/chrome/test/data/webui/settings/quick_unlock_authenticate_browsertest_chromeos.js index 9f0eb9e..d8d464a 100644 --- a/chrome/test/data/webui/settings/quick_unlock_authenticate_browsertest_chromeos.js +++ b/chrome/test/data/webui/settings/quick_unlock_authenticate_browsertest_chromeos.js
@@ -90,6 +90,16 @@ assertDeepEquals([''], quickUnlockPrivateApi.credentials); }); + test('TapConfirmButtonWithWrongPasswordRestoresFocus', function() { + var confirmButton = getFromElement('#passwordInput'); + quickUnlockPrivateApi.accountPassword = 'bar'; + passwordElement.value = 'foo'; + MockInteractions.tap( + getFromElement('paper-button[class="action-button"]')); + + assertEquals(element.shadowRoot.activeElement, passwordElement); + }); + // A bad password does not provide an authenticated setModes object, and a // entered password correctly uma should not be recorded. test('InvalidPasswordDoesNotProvideAuthentication', function() {
diff --git a/chrome/test/data/webui/settings/search_page_test.js b/chrome/test/data/webui/settings/search_page_test.js index 755be82..875f6ae 100644 --- a/chrome/test/data/webui/settings/search_page_test.js +++ b/chrome/test/data/webui/settings/search_page_test.js
@@ -119,58 +119,5 @@ }); }); - // Tests the UI when Hotword 'alwaysOn' is true. - test('HotwordAlwaysOn', function() { - return browserProxy.whenCalled('getSearchEnginesList').then(function() { - return browserProxy.whenCalled('getHotwordInfo'); - }).then(function() { - Polymer.dom.flush(); - assertTrue(page.hotwordInfo_.allowed); - assertTrue(page.hotwordInfo_.alwaysOn); - assertFalse(page.hotwordInfo_.enabled); - assertFalse(browserProxy.hotwordSearchEnabled); - assertFalse(page.hotwordSearchEnablePref_.value); - - var control = page.$$('#hotwordSearchEnable'); - assertTrue(!!control); - assertFalse(control.disabled); - assertFalse(control.checked); - MockInteractions.tap(control.$.control); - Polymer.dom.flush(); - return browserProxy.whenCalled('setHotwordSearchEnabled'); - }).then(function() { - assertTrue(browserProxy.hotwordSearchEnabled); - }); - }); - - // Tests the UI when Hotword 'alwaysOn' is false. - test('HotwordNotAlwaysOn', function() { - return browserProxy.whenCalled('getSearchEnginesList').then(function() { - return browserProxy.whenCalled('getHotwordInfo'); - }).then(function() { - browserProxy.setHotwordInfo({ - allowed: true, - enabled: false, - alwaysOn: false, - errorMessage: '', - userName: '', - historyEnabled: false, - }); - Polymer.dom.flush(); - assertTrue(page.hotwordInfo_.allowed); - assertFalse(page.hotwordInfo_.alwaysOn); - assertFalse(page.hotwordInfo_.enabled); - - var control = page.$$('#hotwordSearchEnable'); - assertTrue(!!control); - assertFalse(control.disabled); - assertFalse(control.checked); - MockInteractions.tap(control.$.control); - Polymer.dom.flush(); - return browserProxy.whenCalled('setHotwordSearchEnabled'); - }).then(function() { - assertTrue(browserProxy.hotwordSearchEnabled); - }); - }); }); });
diff --git a/chrome/test/data/webui/settings/test_search_engines_browser_proxy.js b/chrome/test/data/webui/settings/test_search_engines_browser_proxy.js index ef6eb97f..cb72d56 100644 --- a/chrome/test/data/webui/settings/test_search_engines_browser_proxy.js +++ b/chrome/test/data/webui/settings/test_search_engines_browser_proxy.js
@@ -20,25 +20,10 @@ 'searchEngineEditStarted', 'setDefaultSearchEngine', 'validateSearchEngineInput', - 'getHotwordInfo', - 'setHotwordSearchEnabled', ]); - /** @type {boolean} */ - this.hotwordSearchEnabled = false; - /** @private {!SearchEnginesInfo} */ this.searchEnginesInfo_ = {defaults: [], others: [], extensions: []}; - - /** @private {!SearchPageHotwordInfo} */ - this.hotwordInfo_ = { - allowed: true, - enabled: false, - alwaysOn: true, - errorMessage: '', - userName: 'user@test.org', - historyEnabled: false, - }; } /** @override */ @@ -78,20 +63,6 @@ return Promise.resolve(true); } - /** @override */ - getHotwordInfo() { - this.methodCalled('getHotwordInfo'); - return Promise.resolve(this.hotwordInfo_); - } - - /** @override */ - setHotwordSearchEnabled(enabled) { - this.hotwordSearchEnabled = enabled; - this.hotwordInfo_.enabled = true; - this.hotwordInfo_.historyEnabled = this.hotwordInfo_.alwaysOn; - this.methodCalled('setHotwordSearchEnabled'); - } - /** * Sets the response to be returned by |getSearchEnginesList|. * @param {!SearchEnginesInfo} searchEnginesInfo @@ -100,14 +71,6 @@ this.searchEnginesInfo_ = searchEnginesInfo; } - /** - * Sets the response to be returned by |getSearchEnginesList|. - * @param {!SearchPageHotwordInfo} hotwordInfo - */ - setHotwordInfo(hotwordInfo) { - this.hotwordInfo_ = hotwordInfo; - cr.webUIListenerCallback('hotword-info-update', this.hotwordInfo_); - } } /**
diff --git a/chromecast/browser/cast_content_browser_client.cc b/chromecast/browser/cast_content_browser_client.cc index 00a67f18..9d6623f 100644 --- a/chromecast/browser/cast_content_browser_client.cc +++ b/chromecast/browser/cast_content_browser_client.cc
@@ -552,7 +552,7 @@ void CastContentBrowserClient::ExposeInterfacesToRenderer( service_manager::BinderRegistry* registry, - content::AssociatedInterfaceRegistry* associated_registry, + blink::AssociatedInterfaceRegistry* associated_registry, content::RenderProcessHost* render_process_host) { registry->AddInterface( base::Bind(&media::MediaCapsImpl::AddBinding,
diff --git a/chromecast/browser/cast_content_browser_client.h b/chromecast/browser/cast_content_browser_client.h index 333a87f..f276b6d 100644 --- a/chromecast/browser/cast_content_browser_client.h +++ b/chromecast/browser/cast_content_browser_client.h
@@ -162,7 +162,7 @@ bool* no_javascript_access) override; void ExposeInterfacesToRenderer( service_manager::BinderRegistry* registry, - content::AssociatedInterfaceRegistry* associated_registry, + blink::AssociatedInterfaceRegistry* associated_registry, content::RenderProcessHost* render_process_host) override; void ExposeInterfacesToMediaService( service_manager::BinderRegistry* registry,
diff --git a/chromecast/browser/url_request_context_factory.cc b/chromecast/browser/url_request_context_factory.cc index 9e00a34..670bf90 100644 --- a/chromecast/browser/url_request_context_factory.cc +++ b/chromecast/browser/url_request_context_factory.cc
@@ -58,11 +58,11 @@ IgnoresCTPolicyEnforcer() = default; ~IgnoresCTPolicyEnforcer() override = default; - net::ct::CertPolicyCompliance DoesConformToCertPolicy( + net::ct::CTPolicyCompliance CheckCompliance( net::X509Certificate* cert, const net::SCTList& verified_scts, const net::NetLogWithSource& net_log) override { - return net::ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS; + return net::ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS; } };
diff --git a/chromecast/crash/cast_crash_keys.cc b/chromecast/crash/cast_crash_keys.cc index cf764b9..6120130 100644 --- a/chromecast/crash/cast_crash_keys.cc +++ b/chromecast/crash/cast_crash_keys.cc
@@ -78,6 +78,9 @@ // Temporary for https://crbug.com/685996. {"user-cloud-policy-manager-connect-trace", ::crash_keys::kMediumSize}, + // TODO(sunnyps): Remove after fixing crbug.com/724999. + {"gl-context-set-current-stack-trace", ::crash_keys::kMediumSize}, + // Accessibility keys. Temporary for http://crbug.com/765490. {"ax_tree_error", ::crash_keys::kSmallSize}, {"ax_tree_update", ::crash_keys::kMediumSize},
diff --git a/chromeos/BUILD.gn b/chromeos/BUILD.gn index 470b645..2e79426 100644 --- a/chromeos/BUILD.gn +++ b/chromeos/BUILD.gn
@@ -630,6 +630,7 @@ ":cryptohome_proto", ":power_manager_proto", ":test_support", + ":test_support_without_gmock", "//base/test:run_all_unittests", "//base/test:test_support", "//components/onc", @@ -684,6 +685,7 @@ "disks/disk_mount_manager_unittest.cc", "disks/suspend_unmount_manager_unittest.cc", "geolocation/simple_geolocation_unittest.cc", + "login/auth/authpolicy_login_helper_unittest.cc", "login/auth/key_unittest.cc", "login/login_state_unittest.cc", "network/auto_connect_handler_unittest.cc",
diff --git a/chromeos/accelerometer/accelerometer_reader.cc b/chromeos/accelerometer/accelerometer_reader.cc index 771f6f17..0a1ab3e 100644 --- a/chromeos/accelerometer/accelerometer_reader.cc +++ b/chromeos/accelerometer/accelerometer_reader.cc
@@ -188,7 +188,7 @@ std::vector<ReadingData> reading_data; }; - ~AccelerometerFileReader() {} + ~AccelerometerFileReader() = default; // When accelerometers are presented as separate iio_devices this will perform // the initialize for one of the devices, at the given |iio_path| and the @@ -508,8 +508,7 @@ } } -AccelerometerFileReader::ConfigurationData::~ConfigurationData() { -} +AccelerometerFileReader::ConfigurationData::~ConfigurationData() = default; // static AccelerometerReader* AccelerometerReader::GetInstance() { @@ -539,7 +538,6 @@ : accelerometer_file_reader_(new AccelerometerFileReader()) { } -AccelerometerReader::~AccelerometerReader() { -} +AccelerometerReader::~AccelerometerReader() = default; } // namespace chromeos
diff --git a/chromeos/accelerometer/accelerometer_types.cc b/chromeos/accelerometer/accelerometer_types.cc index a08fbdd..3fdd5b9 100644 --- a/chromeos/accelerometer/accelerometer_types.cc +++ b/chromeos/accelerometer/accelerometer_types.cc
@@ -9,13 +9,10 @@ AccelerometerReading::AccelerometerReading() : present(false) { } -AccelerometerReading::~AccelerometerReading() { -} +AccelerometerReading::~AccelerometerReading() = default; -AccelerometerUpdate::AccelerometerUpdate() { -} +AccelerometerUpdate::AccelerometerUpdate() = default; -AccelerometerUpdate::~AccelerometerUpdate() { -} +AccelerometerUpdate::~AccelerometerUpdate() = default; } // namespace chromeos
diff --git a/chromeos/attestation/attestation_flow.cc b/chromeos/attestation/attestation_flow.cc index 5a358fe..05aee62 100644 --- a/chromeos/attestation/attestation_flow.cc +++ b/chromeos/attestation/attestation_flow.cc
@@ -110,8 +110,7 @@ base::TimeDelta::FromMilliseconds(kRetryDelayInMilliseconds)), weak_factory_(this) {} -AttestationFlow::~AttestationFlow() { -} +AttestationFlow::~AttestationFlow() = default; void AttestationFlow::GetCertificate( AttestationCertificateProfile certificate_profile, @@ -324,7 +323,7 @@ } } -ServerProxy::~ServerProxy() {} +ServerProxy::~ServerProxy() = default; PrivacyCAType ServerProxy::GetType() { return DEFAULT_PCA;
diff --git a/chromeos/attestation/mock_attestation_flow.cc b/chromeos/attestation/mock_attestation_flow.cc index a0dbe64..5b5be20 100644 --- a/chromeos/attestation/mock_attestation_flow.cc +++ b/chromeos/attestation/mock_attestation_flow.cc
@@ -17,7 +17,7 @@ FakeServerProxy::FakeServerProxy() : result_(true) {} -FakeServerProxy::~FakeServerProxy() {} +FakeServerProxy::~FakeServerProxy() = default; void FakeServerProxy::SendEnrollRequest(const std::string& request, const DataCallback& callback) { @@ -33,7 +33,7 @@ DefaultValue<PrivacyCAType>::Set(DEFAULT_PCA); } -MockServerProxy::~MockServerProxy() {} +MockServerProxy::~MockServerProxy() = default; void MockServerProxy::DeferToFake(bool success) { fake_.set_result(success); @@ -43,14 +43,14 @@ .WillByDefault(Invoke(&fake_, &FakeServerProxy::SendCertificateRequest)); } -MockObserver::MockObserver() {} +MockObserver::MockObserver() = default; -MockObserver::~MockObserver() {} +MockObserver::~MockObserver() = default; MockAttestationFlow::MockAttestationFlow() : AttestationFlow(NULL, NULL, std::unique_ptr<ServerProxy>()) {} -MockAttestationFlow::~MockAttestationFlow() {} +MockAttestationFlow::~MockAttestationFlow() = default; } // namespace attestation } // namespace chromeos
diff --git a/chromeos/audio/audio_device.cc b/chromeos/audio/audio_device.cc index 24a2a5c..bd8de2a 100644 --- a/chromeos/audio/audio_device.cc +++ b/chromeos/audio/audio_device.cc
@@ -127,7 +127,7 @@ return AUDIO_TYPE_OTHER; } -AudioDevice::AudioDevice() {} +AudioDevice::AudioDevice() = default; AudioDevice::AudioDevice(const AudioNode& node) { is_input = node.is_input;
diff --git a/chromeos/audio/audio_devices_pref_handler_impl.cc b/chromeos/audio/audio_devices_pref_handler_impl.cc index b14ecffb..77fe1fc 100644 --- a/chromeos/audio/audio_devices_pref_handler_impl.cc +++ b/chromeos/audio/audio_devices_pref_handler_impl.cc
@@ -243,8 +243,7 @@ LoadDevicesStatePref(); } -AudioDevicesPrefHandlerImpl::~AudioDevicesPrefHandlerImpl() { -} +AudioDevicesPrefHandlerImpl::~AudioDevicesPrefHandlerImpl() = default; void AudioDevicesPrefHandlerImpl::InitializePrefObservers() { pref_change_registrar_.Init(local_state_);
diff --git a/chromeos/audio/audio_devices_pref_handler_impl_unittest.cc b/chromeos/audio/audio_devices_pref_handler_impl_unittest.cc index 7744f28..39663ca 100644 --- a/chromeos/audio/audio_devices_pref_handler_impl_unittest.cc +++ b/chromeos/audio/audio_devices_pref_handler_impl_unittest.cc
@@ -87,8 +87,8 @@ // false -> output_devices class AudioDevicesPrefHandlerTest : public testing::TestWithParam<bool> { public: - AudioDevicesPrefHandlerTest() {} - ~AudioDevicesPrefHandlerTest() override {} + AudioDevicesPrefHandlerTest() = default; + ~AudioDevicesPrefHandlerTest() override = default; void SetUp() override { pref_service_.reset(new TestingPrefServiceSimple());
diff --git a/chromeos/audio/audio_devices_pref_handler_stub.cc b/chromeos/audio/audio_devices_pref_handler_stub.cc index 9f71356..996d47b 100644 --- a/chromeos/audio/audio_devices_pref_handler_stub.cc +++ b/chromeos/audio/audio_devices_pref_handler_stub.cc
@@ -9,11 +9,9 @@ namespace chromeos { -AudioDevicesPrefHandlerStub::AudioDevicesPrefHandlerStub() { -} +AudioDevicesPrefHandlerStub::AudioDevicesPrefHandlerStub() = default; -AudioDevicesPrefHandlerStub::~AudioDevicesPrefHandlerStub() { -} +AudioDevicesPrefHandlerStub::~AudioDevicesPrefHandlerStub() = default; double AudioDevicesPrefHandlerStub::GetOutputVolumeValue( const AudioDevice* device) {
diff --git a/chromeos/audio/cras_audio_handler.cc b/chromeos/audio/cras_audio_handler.cc index b5eef92bd..8d37dc5 100644 --- a/chromeos/audio/cras_audio_handler.cc +++ b/chromeos/audio/cras_audio_handler.cc
@@ -72,11 +72,9 @@ } // namespace -CrasAudioHandler::AudioObserver::AudioObserver() { -} +CrasAudioHandler::AudioObserver::AudioObserver() = default; -CrasAudioHandler::AudioObserver::~AudioObserver() { -} +CrasAudioHandler::AudioObserver::~AudioObserver() = default; void CrasAudioHandler::AudioObserver::OnOutputNodeVolumeChanged( uint64_t /* node_id */,
diff --git a/chromeos/audio/cras_audio_handler_unittest.cc b/chromeos/audio/cras_audio_handler_unittest.cc index 00c45e6..7b94b45 100644 --- a/chromeos/audio/cras_audio_handler_unittest.cc +++ b/chromeos/audio/cras_audio_handler_unittest.cc
@@ -128,7 +128,7 @@ class TestObserver : public chromeos::CrasAudioHandler::AudioObserver { public: - TestObserver() {} + TestObserver() = default; int active_output_node_changed_count() const { return active_output_node_changed_count_; @@ -176,7 +176,7 @@ return output_channel_remixing_changed_count_; } - ~TestObserver() override {} + ~TestObserver() override = default; protected: // chromeos::CrasAudioHandler::AudioObserver overrides. @@ -230,7 +230,7 @@ : public base::SystemMonitor::DevicesChangedObserver { public: SystemMonitorObserver() : device_changes_received_(0) {} - ~SystemMonitorObserver() override {} + ~SystemMonitorObserver() override = default; void OnDevicesChanged(base::SystemMonitor::DeviceType device_type) override { if (device_type == base::SystemMonitor::DeviceType::DEVTYPE_AUDIO) @@ -247,8 +247,8 @@ class FakeVideoCaptureManager { public: - FakeVideoCaptureManager() {} - virtual ~FakeVideoCaptureManager() {} + FakeVideoCaptureManager() = default; + virtual ~FakeVideoCaptureManager() = default; void AddObserver(media::VideoCaptureObserver* observer) { observers_.AddObserver(observer); @@ -279,7 +279,7 @@ CrasAudioHandlerTest() : scoped_task_environment_( base::test::ScopedTaskEnvironment::MainThreadType::UI) {} - ~CrasAudioHandlerTest() override {} + ~CrasAudioHandlerTest() override = default; void SetUp() override { system_monitor_.AddDevicesChangedObserver(&system_monitor_observer_);
diff --git a/chromeos/binder/buffer_reader.cc b/chromeos/binder/buffer_reader.cc index 78dd81d1..2dbdd19 100644 --- a/chromeos/binder/buffer_reader.cc +++ b/chromeos/binder/buffer_reader.cc
@@ -11,7 +11,7 @@ BufferReader::BufferReader(const char* data, size_t size) : data_(data), size_(size), current_(data) {} -BufferReader::~BufferReader() {} +BufferReader::~BufferReader() = default; bool BufferReader::HasMoreData() const { return current_ < data_ + size_;
diff --git a/chromeos/binder/local_object.cc b/chromeos/binder/local_object.cc index 710e2232..4ecca1e 100644 --- a/chromeos/binder/local_object.cc +++ b/chromeos/binder/local_object.cc
@@ -13,7 +13,7 @@ LocalObject::LocalObject(std::unique_ptr<TransactionHandler> handler) : handler_(std::move(handler)) {} -LocalObject::~LocalObject() {} +LocalObject::~LocalObject() = default; Object::Type LocalObject::GetType() const { return TYPE_LOCAL;
diff --git a/chromeos/binder/transaction_data_reader.cc b/chromeos/binder/transaction_data_reader.cc index 634bd5a..9c9188cc 100644 --- a/chromeos/binder/transaction_data_reader.cc +++ b/chromeos/binder/transaction_data_reader.cc
@@ -29,7 +29,7 @@ : reader_(reinterpret_cast<const char*>(data.GetData()), data.GetDataSize()) {} -TransactionDataReader::~TransactionDataReader() {} +TransactionDataReader::~TransactionDataReader() = default; bool TransactionDataReader::HasMoreData() const { return reader_.HasMoreData();
diff --git a/chromeos/binder/transaction_status.cc b/chromeos/binder/transaction_status.cc index 4ac6a39..dafd07ab 100644 --- a/chromeos/binder/transaction_status.cc +++ b/chromeos/binder/transaction_status.cc
@@ -8,7 +8,7 @@ TransactionStatus::TransactionStatus(Status status) : status_(status) {} -TransactionStatus::~TransactionStatus() {} +TransactionStatus::~TransactionStatus() = default; uintptr_t TransactionStatus::GetCookie() const { return 0;
diff --git a/chromeos/binder/writable_transaction_data.cc b/chromeos/binder/writable_transaction_data.cc index 28f672d..dcbd4fa3 100644 --- a/chromeos/binder/writable_transaction_data.cc +++ b/chromeos/binder/writable_transaction_data.cc
@@ -12,9 +12,9 @@ namespace binder { -WritableTransactionData::WritableTransactionData() {} +WritableTransactionData::WritableTransactionData() = default; -WritableTransactionData::~WritableTransactionData() {} +WritableTransactionData::~WritableTransactionData() = default; uintptr_t WritableTransactionData::GetCookie() const { return 0;
diff --git a/chromeos/cert_loader.cc b/chromeos/cert_loader.cc index 73e519c4..48d2a5e 100644 --- a/chromeos/cert_loader.cc +++ b/chromeos/cert_loader.cc
@@ -220,8 +220,7 @@ base::BindRepeating(&CertLoader::CacheUpdated, base::Unretained(this))); } -CertLoader::~CertLoader() { -} +CertLoader::~CertLoader() = default; void CertLoader::SetSystemNSSDB(net::NSSCertDatabase* system_slot_database) { system_cert_cache_->SetNSSDB(system_slot_database);
diff --git a/chromeos/cert_loader_unittest.cc b/chromeos/cert_loader_unittest.cc index b3c54d8..3fd001b 100644 --- a/chromeos/cert_loader_unittest.cc +++ b/chromeos/cert_loader_unittest.cc
@@ -52,7 +52,7 @@ crypto::ScopedPK11Slot private_slot) : NSSCertDatabaseChromeOS(std::move(public_slot), std::move(private_slot)) {} - ~TestNSSCertDatabase() override {} + ~TestNSSCertDatabase() override = default; // Make this method visible in the public interface. void NotifyObserversCertDBChanged() { @@ -79,7 +79,7 @@ : cert_loader_(nullptr), certificates_loaded_events_count_(0U) {} - ~CertLoaderTest() override {} + ~CertLoaderTest() override = default; void SetUp() override { ASSERT_TRUE(primary_db_.is_open());
diff --git a/chromeos/components/tether/active_host.cc b/chromeos/components/tether/active_host.cc index ef75c87..a417786 100644 --- a/chromeos/components/tether/active_host.cc +++ b/chromeos/components/tether/active_host.cc
@@ -60,17 +60,9 @@ old_wifi_network_guid(old_wifi_network_guid) {} ActiveHost::ActiveHostChangeInfo::ActiveHostChangeInfo( - const ActiveHostChangeInfo& other) - : new_status(other.new_status), - old_status(other.old_status), - new_active_host(other.new_active_host), - old_active_host_id(other.old_active_host_id), - new_tether_network_guid(other.new_tether_network_guid), - old_tether_network_guid(other.old_tether_network_guid), - new_wifi_network_guid(other.new_wifi_network_guid), - old_wifi_network_guid(other.old_wifi_network_guid) {} + const ActiveHostChangeInfo& other) = default; -ActiveHost::ActiveHostChangeInfo::~ActiveHostChangeInfo() {} +ActiveHost::ActiveHostChangeInfo::~ActiveHostChangeInfo() = default; ActiveHost::ActiveHost(TetherHostFetcher* tether_host_fetcher, PrefService* pref_service) @@ -78,7 +70,7 @@ pref_service_(pref_service), weak_ptr_factory_(this) {} -ActiveHost::~ActiveHost() {} +ActiveHost::~ActiveHost() = default; // static void ActiveHost::RegisterPrefs(PrefRegistrySimple* registry) {
diff --git a/chromeos/components/tether/active_host_network_state_updater_unittest.cc b/chromeos/components/tether/active_host_network_state_updater_unittest.cc index a6d0535..6e1775f4a 100644 --- a/chromeos/components/tether/active_host_network_state_updater_unittest.cc +++ b/chromeos/components/tether/active_host_network_state_updater_unittest.cc
@@ -42,7 +42,7 @@ class ActiveHostNetworkStateUpdaterTest : public NetworkStateTest { protected: ActiveHostNetworkStateUpdaterTest() : NetworkStateTest() {} - ~ActiveHostNetworkStateUpdaterTest() override {} + ~ActiveHostNetworkStateUpdaterTest() override = default; void SetUp() override { DBusThreadManager::Initialize();
diff --git a/chromeos/components/tether/asynchronous_shutdown_object_container_impl.cc b/chromeos/components/tether/asynchronous_shutdown_object_container_impl.cc index ee9031d3..2bcb63b 100644 --- a/chromeos/components/tether/asynchronous_shutdown_object_container_impl.cc +++ b/chromeos/components/tether/asynchronous_shutdown_object_container_impl.cc
@@ -51,7 +51,7 @@ factory_instance_ = factory; } -AsynchronousShutdownObjectContainerImpl::Factory::~Factory() {} +AsynchronousShutdownObjectContainerImpl::Factory::~Factory() = default; std::unique_ptr<AsynchronousShutdownObjectContainer> AsynchronousShutdownObjectContainerImpl::Factory::BuildInstance(
diff --git a/chromeos/components/tether/ble_advertisement_device_queue.cc b/chromeos/components/tether/ble_advertisement_device_queue.cc index 8f2ea84d..0840f10 100644 --- a/chromeos/components/tether/ble_advertisement_device_queue.cc +++ b/chromeos/components/tether/ble_advertisement_device_queue.cc
@@ -37,11 +37,11 @@ const ConnectionPriority& connection_priority) : remote_device(remote_device), connection_priority(connection_priority) {} -BleAdvertisementDeviceQueue::PrioritizedDevice::~PrioritizedDevice() {} +BleAdvertisementDeviceQueue::PrioritizedDevice::~PrioritizedDevice() = default; -BleAdvertisementDeviceQueue::BleAdvertisementDeviceQueue() {} +BleAdvertisementDeviceQueue::BleAdvertisementDeviceQueue() = default; -BleAdvertisementDeviceQueue::~BleAdvertisementDeviceQueue() {} +BleAdvertisementDeviceQueue::~BleAdvertisementDeviceQueue() = default; bool BleAdvertisementDeviceQueue::SetDevices( const std::vector<PrioritizedDevice>& devices) {
diff --git a/chromeos/components/tether/ble_advertiser.cc b/chromeos/components/tether/ble_advertiser.cc index 4f5c594d..784ceaa1 100644 --- a/chromeos/components/tether/ble_advertiser.cc +++ b/chromeos/components/tether/ble_advertiser.cc
@@ -8,9 +8,9 @@ namespace tether { -BleAdvertiser::BleAdvertiser() {} +BleAdvertiser::BleAdvertiser() = default; -BleAdvertiser::~BleAdvertiser() {} +BleAdvertiser::~BleAdvertiser() = default; void BleAdvertiser::AddObserver(Observer* observer) { observer_list_.AddObserver(observer);
diff --git a/chromeos/components/tether/ble_advertiser_impl.cc b/chromeos/components/tether/ble_advertiser_impl.cc index 7f571169..37b3078 100644 --- a/chromeos/components/tether/ble_advertiser_impl.cc +++ b/chromeos/components/tether/ble_advertiser_impl.cc
@@ -50,7 +50,7 @@ std::unique_ptr<cryptauth::DataWithTimestamp> service_data) : device_id(device_id), service_data(std::move(service_data)) {} -BleAdvertiserImpl::AdvertisementMetadata::~AdvertisementMetadata() {} +BleAdvertiserImpl::AdvertisementMetadata::~AdvertisementMetadata() = default; BleAdvertiserImpl::BleAdvertiserImpl( cryptauth::LocalDeviceDataProvider* local_device_data_provider, @@ -62,7 +62,7 @@ task_runner_(base::ThreadTaskRunnerHandle::Get()), weak_ptr_factory_(this) {} -BleAdvertiserImpl::~BleAdvertiserImpl() {} +BleAdvertiserImpl::~BleAdvertiserImpl() = default; bool BleAdvertiserImpl::StartAdvertisingToDevice( const cryptauth::RemoteDevice& remote_device) {
diff --git a/chromeos/components/tether/ble_advertiser_impl_unittest.cc b/chromeos/components/tether/ble_advertiser_impl_unittest.cc index 88d1ad1..de40974 100644 --- a/chromeos/components/tether/ble_advertiser_impl_unittest.cc +++ b/chromeos/components/tether/ble_advertiser_impl_unittest.cc
@@ -41,8 +41,8 @@ class FakeErrorTolerantBleAdvertisementFactory : public ErrorTolerantBleAdvertisementImpl::Factory { public: - FakeErrorTolerantBleAdvertisementFactory() {} - ~FakeErrorTolerantBleAdvertisementFactory() override {} + FakeErrorTolerantBleAdvertisementFactory() = default; + ~FakeErrorTolerantBleAdvertisementFactory() override = default; const std::vector<FakeErrorTolerantBleAdvertisement*>& active_advertisements() { @@ -82,8 +82,8 @@ class TestObserver final : public BleAdvertiser::Observer { public: - TestObserver() {} - ~TestObserver() override {} + TestObserver() = default; + ~TestObserver() override = default; size_t num_times_all_advertisements_unregistered() { return num_times_all_advertisements_unregistered_; @@ -106,7 +106,7 @@ ble_advertiser_->AddObserver(this); } - ~DeletingObserver() override {} + ~DeletingObserver() override = default; // BleAdvertiser::Observer: void OnAllAdvertisementsUnregistered() override {
diff --git a/chromeos/components/tether/ble_connection_manager.cc b/chromeos/components/tether/ble_connection_manager.cc index f7bcebc..031f1117 100644 --- a/chromeos/components/tether/ble_connection_manager.cc +++ b/chromeos/components/tether/ble_connection_manager.cc
@@ -51,7 +51,7 @@ manager_(manager), weak_ptr_factory_(this) {} -BleConnectionManager::ConnectionMetadata::~ConnectionMetadata() {} +BleConnectionManager::ConnectionMetadata::~ConnectionMetadata() = default; void BleConnectionManager::ConnectionMetadata::RegisterConnectionReason( const MessageType& connection_reason) {
diff --git a/chromeos/components/tether/ble_connection_manager_unittest.cc b/chromeos/components/tether/ble_connection_manager_unittest.cc index bb7aca1..d4986fde6 100644 --- a/chromeos/components/tether/ble_connection_manager_unittest.cc +++ b/chromeos/components/tether/ble_connection_manager_unittest.cc
@@ -81,7 +81,7 @@ // status changes and messages received. class TestObserver final : public BleConnectionManager::Observer { public: - TestObserver() {} + TestObserver() = default; // BleConnectionManager::Observer: void OnSecureChannelStatusChanged( @@ -211,7 +211,7 @@ cryptauth::CryptAuthService* cryptauth_service) : cryptauth::FakeSecureChannel(std::move(connection), cryptauth_service) {} - ~FakeSecureChannel() override {} + ~FakeSecureChannel() override = default; void AddObserver(Observer* observer) override { cryptauth::FakeSecureChannel::AddObserver(observer); @@ -228,7 +228,7 @@ class FakeSecureChannelFactory final : public cryptauth::SecureChannel::Factory { public: - FakeSecureChannelFactory() {} + FakeSecureChannelFactory() = default; void SetExpectedDeviceAddress(const std::string& expected_device_address) { expected_device_address_ = expected_device_address;
diff --git a/chromeos/components/tether/ble_scanner.cc b/chromeos/components/tether/ble_scanner.cc index 140d823d..dd69a51 100644 --- a/chromeos/components/tether/ble_scanner.cc +++ b/chromeos/components/tether/ble_scanner.cc
@@ -8,9 +8,9 @@ namespace tether { -BleScanner::BleScanner() {} +BleScanner::BleScanner() = default; -BleScanner::~BleScanner() {} +BleScanner::~BleScanner() = default; void BleScanner::AddObserver(Observer* observer) { observer_list_.AddObserver(observer);
diff --git a/chromeos/components/tether/ble_scanner_impl.cc b/chromeos/components/tether/ble_scanner_impl.cc index ee0744a8..10b3164 100644 --- a/chromeos/components/tether/ble_scanner_impl.cc +++ b/chromeos/components/tether/ble_scanner_impl.cc
@@ -58,9 +58,9 @@ ble_synchronizer); } -BleScannerImpl::ServiceDataProviderImpl::ServiceDataProviderImpl() {} +BleScannerImpl::ServiceDataProviderImpl::ServiceDataProviderImpl() = default; -BleScannerImpl::ServiceDataProviderImpl::~ServiceDataProviderImpl() {} +BleScannerImpl::ServiceDataProviderImpl::~ServiceDataProviderImpl() = default; const std::vector<uint8_t>* BleScannerImpl::ServiceDataProviderImpl::GetServiceDataForUUID(
diff --git a/chromeos/components/tether/ble_scanner_impl_unittest.cc b/chromeos/components/tether/ble_scanner_impl_unittest.cc index a79d00b..8b863cf 100644 --- a/chromeos/components/tether/ble_scanner_impl_unittest.cc +++ b/chromeos/components/tether/ble_scanner_impl_unittest.cc
@@ -32,7 +32,7 @@ class TestBleScannerObserver final : public BleScanner::Observer { public: - TestBleScannerObserver() {} + TestBleScannerObserver() = default; std::vector<std::string>& device_addresses() { return device_addresses_; } @@ -165,9 +165,9 @@ protected: class TestServiceDataProvider : public BleScannerImpl::ServiceDataProvider { public: - TestServiceDataProvider() {} + TestServiceDataProvider() = default; - ~TestServiceDataProvider() override {} + ~TestServiceDataProvider() override = default; // ServiceDataProvider: const std::vector<uint8_t>* GetServiceDataForUUID(
diff --git a/chromeos/components/tether/ble_synchronizer.cc b/chromeos/components/tether/ble_synchronizer.cc index 204fed2c..cb5290b 100644 --- a/chromeos/components/tether/ble_synchronizer.cc +++ b/chromeos/components/tether/ble_synchronizer.cc
@@ -28,7 +28,7 @@ task_runner_(base::ThreadTaskRunnerHandle::Get()), weak_ptr_factory_(this) {} -BleSynchronizer::~BleSynchronizer() {} +BleSynchronizer::~BleSynchronizer() = default; void BleSynchronizer::ProcessQueue() { if (current_command_ || command_queue().empty())
diff --git a/chromeos/components/tether/ble_synchronizer_base.cc b/chromeos/components/tether/ble_synchronizer_base.cc index 3834f1a..185f17f8 100644 --- a/chromeos/components/tether/ble_synchronizer_base.cc +++ b/chromeos/components/tether/ble_synchronizer_base.cc
@@ -18,7 +18,7 @@ callback(callback), error_callback(error_callback) {} -BleSynchronizerBase::RegisterArgs::~RegisterArgs() {} +BleSynchronizerBase::RegisterArgs::~RegisterArgs() = default; BleSynchronizerBase::UnregisterArgs::UnregisterArgs( scoped_refptr<device::BluetoothAdvertisement> advertisement, @@ -28,14 +28,14 @@ callback(callback), error_callback(error_callback) {} -BleSynchronizerBase::UnregisterArgs::~UnregisterArgs() {} +BleSynchronizerBase::UnregisterArgs::~UnregisterArgs() = default; BleSynchronizerBase::StartDiscoveryArgs::StartDiscoveryArgs( const device::BluetoothAdapter::DiscoverySessionCallback& callback, const device::BluetoothAdapter::ErrorCallback& error_callback) : callback(callback), error_callback(error_callback) {} -BleSynchronizerBase::StartDiscoveryArgs::~StartDiscoveryArgs() {} +BleSynchronizerBase::StartDiscoveryArgs::~StartDiscoveryArgs() = default; BleSynchronizerBase::StopDiscoveryArgs::StopDiscoveryArgs( base::WeakPtr<device::BluetoothDiscoverySession> discovery_session, @@ -45,7 +45,7 @@ callback(callback), error_callback(error_callback) {} -BleSynchronizerBase::StopDiscoveryArgs::~StopDiscoveryArgs() {} +BleSynchronizerBase::StopDiscoveryArgs::~StopDiscoveryArgs() = default; BleSynchronizerBase::Command::Command( std::unique_ptr<RegisterArgs> register_args) @@ -67,11 +67,11 @@ : command_type(CommandType::STOP_DISCOVERY), stop_discovery_args(std::move(stop_discovery_args)) {} -BleSynchronizerBase::Command::~Command() {} +BleSynchronizerBase::Command::~Command() = default; -BleSynchronizerBase::BleSynchronizerBase() {} +BleSynchronizerBase::BleSynchronizerBase() = default; -BleSynchronizerBase::~BleSynchronizerBase() {} +BleSynchronizerBase::~BleSynchronizerBase() = default; void BleSynchronizerBase::RegisterAdvertisement( std::unique_ptr<device::BluetoothAdvertisement::Data> advertisement_data,
diff --git a/chromeos/components/tether/ble_synchronizer_unittest.cc b/chromeos/components/tether/ble_synchronizer_unittest.cc index e9f6dbb..874d559d 100644 --- a/chromeos/components/tether/ble_synchronizer_unittest.cc +++ b/chromeos/components/tether/ble_synchronizer_unittest.cc
@@ -101,7 +101,7 @@ } protected: - ~MockBluetoothAdapterWithAdvertisements() override {} + ~MockBluetoothAdapterWithAdvertisements() override = default; }; class FakeBluetoothAdvertisement : public device::BluetoothAdvertisement { @@ -124,7 +124,7 @@ } private: - ~FakeBluetoothAdvertisement() override {} + ~FakeBluetoothAdvertisement() override = default; base::Callback<void(const device::BluetoothAdvertisement::SuccessCallback&, const device::BluetoothAdvertisement::ErrorCallback&)> @@ -143,7 +143,7 @@ const device::BluetoothDiscoverySession::ErrorCallback&)>& stop_callback) : stop_callback_(stop_callback) {} - ~FakeDiscoverySession() override {} + ~FakeDiscoverySession() override = default; // BluetoothDiscoverySession: void Stop(const base::Closure& callback,
diff --git a/chromeos/components/tether/connect_tethering_operation.cc b/chromeos/components/tether/connect_tethering_operation.cc index acc4160..4677602 100644 --- a/chromeos/components/tether/connect_tethering_operation.cc +++ b/chromeos/components/tether/connect_tethering_operation.cc
@@ -72,7 +72,7 @@ ConnectTetheringResponse_ResponseCode:: ConnectTetheringResponse_ResponseCode_UNKNOWN_ERROR) {} -ConnectTetheringOperation::~ConnectTetheringOperation() {} +ConnectTetheringOperation::~ConnectTetheringOperation() = default; void ConnectTetheringOperation::AddObserver(Observer* observer) { observer_list_.AddObserver(observer);
diff --git a/chromeos/components/tether/connect_tethering_operation_unittest.cc b/chromeos/components/tether/connect_tethering_operation_unittest.cc index b08b355..6ca3189 100644 --- a/chromeos/components/tether/connect_tethering_operation_unittest.cc +++ b/chromeos/components/tether/connect_tethering_operation_unittest.cc
@@ -37,8 +37,8 @@ class TestObserver final : public ConnectTetheringOperation::Observer { public: - TestObserver() {} - ~TestObserver() {} + TestObserver() = default; + ~TestObserver() = default; const cryptauth::RemoteDevice& remote_device() { return remote_device_; } const std::string& ssid() { return ssid_; }
diff --git a/chromeos/components/tether/crash_recovery_manager_impl.cc b/chromeos/components/tether/crash_recovery_manager_impl.cc index bc23f73..56c4516 100644 --- a/chromeos/components/tether/crash_recovery_manager_impl.cc +++ b/chromeos/components/tether/crash_recovery_manager_impl.cc
@@ -40,7 +40,7 @@ factory_instance_ = factory; } -CrashRecoveryManagerImpl::Factory::~Factory() {} +CrashRecoveryManagerImpl::Factory::~Factory() = default; std::unique_ptr<CrashRecoveryManager> CrashRecoveryManagerImpl::Factory::BuildInstance( @@ -60,7 +60,7 @@ host_scan_cache_(host_scan_cache), weak_ptr_factory_(this) {} -CrashRecoveryManagerImpl::~CrashRecoveryManagerImpl() {} +CrashRecoveryManagerImpl::~CrashRecoveryManagerImpl() = default; void CrashRecoveryManagerImpl::RestorePreCrashStateIfNecessary( const base::Closure& on_restoration_finished) {
diff --git a/chromeos/components/tether/crash_recovery_manager_impl_unittest.cc b/chromeos/components/tether/crash_recovery_manager_impl_unittest.cc index 9cf5020..938d97f1 100644 --- a/chromeos/components/tether/crash_recovery_manager_impl_unittest.cc +++ b/chromeos/components/tether/crash_recovery_manager_impl_unittest.cc
@@ -48,7 +48,7 @@ protected: CrashRecoveryManagerImplTest() : test_device_(cryptauth::GenerateTestRemoteDevices(1u)[0]) {} - ~CrashRecoveryManagerImplTest() override {} + ~CrashRecoveryManagerImplTest() override = default; void SetUp() override { DBusThreadManager::Initialize();
diff --git a/chromeos/components/tether/device_id_tether_network_guid_map.cc b/chromeos/components/tether/device_id_tether_network_guid_map.cc index 9f22153..3d04b681 100644 --- a/chromeos/components/tether/device_id_tether_network_guid_map.cc +++ b/chromeos/components/tether/device_id_tether_network_guid_map.cc
@@ -8,9 +8,9 @@ namespace tether { -DeviceIdTetherNetworkGuidMap::DeviceIdTetherNetworkGuidMap() {} +DeviceIdTetherNetworkGuidMap::DeviceIdTetherNetworkGuidMap() = default; -DeviceIdTetherNetworkGuidMap::~DeviceIdTetherNetworkGuidMap() {} +DeviceIdTetherNetworkGuidMap::~DeviceIdTetherNetworkGuidMap() = default; std::string DeviceIdTetherNetworkGuidMap::GetDeviceIdForTetherNetworkGuid( const std::string& tether_network_guid) {
diff --git a/chromeos/components/tether/device_status_util_unittest.cc b/chromeos/components/tether/device_status_util_unittest.cc index 5eca9e0e..adc5341 100644 --- a/chromeos/components/tether/device_status_util_unittest.cc +++ b/chromeos/components/tether/device_status_util_unittest.cc
@@ -23,7 +23,7 @@ class DeviceStatusUtilTest : public testing::Test { public: - DeviceStatusUtilTest() {} + DeviceStatusUtilTest() = default; private: DISALLOW_COPY_AND_ASSIGN(DeviceStatusUtilTest);
diff --git a/chromeos/components/tether/disconnect_tethering_operation.cc b/chromeos/components/tether/disconnect_tethering_operation.cc index 82011db..07d412c8 100644 --- a/chromeos/components/tether/disconnect_tethering_operation.cc +++ b/chromeos/components/tether/disconnect_tethering_operation.cc
@@ -54,7 +54,7 @@ has_sent_message_(false), clock_(base::MakeUnique<base::DefaultClock>()) {} -DisconnectTetheringOperation::~DisconnectTetheringOperation() {} +DisconnectTetheringOperation::~DisconnectTetheringOperation() = default; void DisconnectTetheringOperation::AddObserver(Observer* observer) { observer_list_.AddObserver(observer);
diff --git a/chromeos/components/tether/disconnect_tethering_operation_unittest.cc b/chromeos/components/tether/disconnect_tethering_operation_unittest.cc index 4e2c25c..d4874de 100644 --- a/chromeos/components/tether/disconnect_tethering_operation_unittest.cc +++ b/chromeos/components/tether/disconnect_tethering_operation_unittest.cc
@@ -28,7 +28,7 @@ public: TestObserver() : success_(false) {} - virtual ~TestObserver() {} + virtual ~TestObserver() = default; std::string last_device_id() { return last_device_id_; }
diff --git a/chromeos/components/tether/disconnect_tethering_request_sender.cc b/chromeos/components/tether/disconnect_tethering_request_sender.cc index 543b9e4..ba8342a 100644 --- a/chromeos/components/tether/disconnect_tethering_request_sender.cc +++ b/chromeos/components/tether/disconnect_tethering_request_sender.cc
@@ -8,9 +8,9 @@ namespace tether { -DisconnectTetheringRequestSender::DisconnectTetheringRequestSender() {} +DisconnectTetheringRequestSender::DisconnectTetheringRequestSender() = default; -DisconnectTetheringRequestSender::~DisconnectTetheringRequestSender() {} +DisconnectTetheringRequestSender::~DisconnectTetheringRequestSender() = default; void DisconnectTetheringRequestSender::AddObserver(Observer* observer) { observer_list_.AddObserver(observer);
diff --git a/chromeos/components/tether/disconnect_tethering_request_sender_impl_unittest.cc b/chromeos/components/tether/disconnect_tethering_request_sender_impl_unittest.cc index d20070e..0b56c6e 100644 --- a/chromeos/components/tether/disconnect_tethering_request_sender_impl_unittest.cc +++ b/chromeos/components/tether/disconnect_tethering_request_sender_impl_unittest.cc
@@ -25,7 +25,7 @@ BleConnectionManager* connection_manager) : DisconnectTetheringOperation(device_to_connect, connection_manager) {} - ~FakeDisconnectTetheringOperation() override {} + ~FakeDisconnectTetheringOperation() override = default; void NotifyFinished(bool success) { NotifyObserversOperationFinished(success); @@ -40,8 +40,8 @@ class FakeDisconnectTetheringOperationFactory : public DisconnectTetheringOperation::Factory { public: - FakeDisconnectTetheringOperationFactory() {} - virtual ~FakeDisconnectTetheringOperationFactory() {} + FakeDisconnectTetheringOperationFactory() = default; + virtual ~FakeDisconnectTetheringOperationFactory() = default; std::vector<FakeDisconnectTetheringOperation*>& created_operations() { return created_operations_; @@ -69,7 +69,7 @@ FakeDisconnectTetheringRequestSenderObserver() : num_no_more_pending_requests_events_(0) {} - ~FakeDisconnectTetheringRequestSenderObserver() override {} + ~FakeDisconnectTetheringRequestSenderObserver() override = default; void OnPendingDisconnectRequestsComplete() override { num_no_more_pending_requests_events_++; @@ -89,7 +89,7 @@ public: DisconnectTetheringRequestSenderTest() : test_devices_(cryptauth::GenerateTestRemoteDevices(2u)) {} - ~DisconnectTetheringRequestSenderTest() override {} + ~DisconnectTetheringRequestSenderTest() override = default; void SetUp() override { fake_ble_connection_manager_ = base::MakeUnique<FakeBleConnectionManager>();
diff --git a/chromeos/components/tether/error_tolerant_ble_advertisement.cc b/chromeos/components/tether/error_tolerant_ble_advertisement.cc index 6e7fe56f0..6f18292 100644 --- a/chromeos/components/tether/error_tolerant_ble_advertisement.cc +++ b/chromeos/components/tether/error_tolerant_ble_advertisement.cc
@@ -12,7 +12,7 @@ const std::string& device_id) : device_id_(device_id) {} -ErrorTolerantBleAdvertisement::~ErrorTolerantBleAdvertisement() {} +ErrorTolerantBleAdvertisement::~ErrorTolerantBleAdvertisement() = default; } // namespace tether
diff --git a/chromeos/components/tether/error_tolerant_ble_advertisement_impl.cc b/chromeos/components/tether/error_tolerant_ble_advertisement_impl.cc index a851ba43..f3103764 100644 --- a/chromeos/components/tether/error_tolerant_ble_advertisement_impl.cc +++ b/chromeos/components/tether/error_tolerant_ble_advertisement_impl.cc
@@ -55,7 +55,7 @@ device_id, std::move(advertisement_data), ble_synchronizer); } -ErrorTolerantBleAdvertisementImpl::Factory::~Factory() {} +ErrorTolerantBleAdvertisementImpl::Factory::~Factory() = default; ErrorTolerantBleAdvertisementImpl::ErrorTolerantBleAdvertisementImpl( const std::string& device_id,
diff --git a/chromeos/components/tether/fake_active_host.cc b/chromeos/components/tether/fake_active_host.cc index ec63c37..6dc78ed 100644 --- a/chromeos/components/tether/fake_active_host.cc +++ b/chromeos/components/tether/fake_active_host.cc
@@ -21,7 +21,7 @@ tether_network_guid_(std::string()), wifi_network_guid_(std::string()) {} -FakeActiveHost::~FakeActiveHost() {} +FakeActiveHost::~FakeActiveHost() = default; void FakeActiveHost::SetActiveHostDisconnected() { SetActiveHost(ActiveHost::ActiveHostStatus::DISCONNECTED, "", "", "");
diff --git a/chromeos/components/tether/fake_ble_advertiser.cc b/chromeos/components/tether/fake_ble_advertiser.cc index 7edc24bf..df714b2 100644 --- a/chromeos/components/tether/fake_ble_advertiser.cc +++ b/chromeos/components/tether/fake_ble_advertiser.cc
@@ -17,7 +17,7 @@ : automatically_update_active_advertisements_( automatically_update_active_advertisements) {} -FakeBleAdvertiser::~FakeBleAdvertiser() {} +FakeBleAdvertiser::~FakeBleAdvertiser() = default; void FakeBleAdvertiser::NotifyAllAdvertisementsUnregistered() { BleAdvertiser::NotifyAllAdvertisementsUnregistered();
diff --git a/chromeos/components/tether/fake_ble_connection_manager.cc b/chromeos/components/tether/fake_ble_connection_manager.cc index 17eafcc..fd159d2 100644 --- a/chromeos/components/tether/fake_ble_connection_manager.cc +++ b/chromeos/components/tether/fake_ble_connection_manager.cc
@@ -17,12 +17,10 @@ FakeBleConnectionManager::StatusAndRegisteredMessageTypes:: StatusAndRegisteredMessageTypes( - const StatusAndRegisteredMessageTypes& other) - : status(other.status), - registered_message_types(other.registered_message_types) {} + const StatusAndRegisteredMessageTypes& other) = default; FakeBleConnectionManager::StatusAndRegisteredMessageTypes:: - ~StatusAndRegisteredMessageTypes() {} + ~StatusAndRegisteredMessageTypes() = default; FakeBleConnectionManager::FakeBleConnectionManager() : BleConnectionManager(nullptr, @@ -32,7 +30,7 @@ nullptr, nullptr) {} -FakeBleConnectionManager::~FakeBleConnectionManager() {} +FakeBleConnectionManager::~FakeBleConnectionManager() = default; void FakeBleConnectionManager::SetDeviceStatus( const cryptauth::RemoteDevice& remote_device,
diff --git a/chromeos/components/tether/fake_ble_scanner.cc b/chromeos/components/tether/fake_ble_scanner.cc index cf6c494..39d49373 100644 --- a/chromeos/components/tether/fake_ble_scanner.cc +++ b/chromeos/components/tether/fake_ble_scanner.cc
@@ -16,7 +16,7 @@ : automatically_update_discovery_session_( automatically_update_discovery_session) {} -FakeBleScanner::~FakeBleScanner() {} +FakeBleScanner::~FakeBleScanner() = default; void FakeBleScanner::NotifyReceivedAdvertisementFromDevice( const cryptauth::RemoteDevice& remote_device,
diff --git a/chromeos/components/tether/fake_ble_synchronizer.cc b/chromeos/components/tether/fake_ble_synchronizer.cc index 840ad44..9489197 100644 --- a/chromeos/components/tether/fake_ble_synchronizer.cc +++ b/chromeos/components/tether/fake_ble_synchronizer.cc
@@ -8,9 +8,9 @@ namespace tether { -FakeBleSynchronizer::FakeBleSynchronizer() {} +FakeBleSynchronizer::FakeBleSynchronizer() = default; -FakeBleSynchronizer::~FakeBleSynchronizer() {} +FakeBleSynchronizer::~FakeBleSynchronizer() = default; size_t FakeBleSynchronizer::GetNumCommands() { return command_queue().size();
diff --git a/chromeos/components/tether/fake_crash_recovery_manager.cc b/chromeos/components/tether/fake_crash_recovery_manager.cc index c4c8e26..299fbad5 100644 --- a/chromeos/components/tether/fake_crash_recovery_manager.cc +++ b/chromeos/components/tether/fake_crash_recovery_manager.cc
@@ -8,9 +8,9 @@ namespace tether { -FakeCrashRecoveryManager::FakeCrashRecoveryManager() {} +FakeCrashRecoveryManager::FakeCrashRecoveryManager() = default; -FakeCrashRecoveryManager::~FakeCrashRecoveryManager() {} +FakeCrashRecoveryManager::~FakeCrashRecoveryManager() = default; void FakeCrashRecoveryManager::RestorePreCrashStateIfNecessary( const base::Closure& on_restoration_finished) {
diff --git a/chromeos/components/tether/fake_disconnect_tethering_request_sender.cc b/chromeos/components/tether/fake_disconnect_tethering_request_sender.cc index 1857e4e..f6ca4dd7 100644 --- a/chromeos/components/tether/fake_disconnect_tethering_request_sender.cc +++ b/chromeos/components/tether/fake_disconnect_tethering_request_sender.cc
@@ -8,9 +8,11 @@ namespace tether { -FakeDisconnectTetheringRequestSender::FakeDisconnectTetheringRequestSender() {} +FakeDisconnectTetheringRequestSender::FakeDisconnectTetheringRequestSender() = + default; -FakeDisconnectTetheringRequestSender::~FakeDisconnectTetheringRequestSender() {} +FakeDisconnectTetheringRequestSender::~FakeDisconnectTetheringRequestSender() = + default; void FakeDisconnectTetheringRequestSender::SendDisconnectRequestToDevice( const std::string& device_id) {
diff --git a/chromeos/components/tether/fake_host_scan_cache.cc b/chromeos/components/tether/fake_host_scan_cache.cc index 8ee3a66..33aa28e2 100644 --- a/chromeos/components/tether/fake_host_scan_cache.cc +++ b/chromeos/components/tether/fake_host_scan_cache.cc
@@ -10,7 +10,7 @@ FakeHostScanCache::FakeHostScanCache() : HostScanCache() {} -FakeHostScanCache::~FakeHostScanCache() {} +FakeHostScanCache::~FakeHostScanCache() = default; const HostScanCacheEntry* FakeHostScanCache::GetCacheEntry( const std::string& tether_network_guid) {
diff --git a/chromeos/components/tether/fake_host_scan_scheduler.cc b/chromeos/components/tether/fake_host_scan_scheduler.cc index 565b403e..d2d949b 100644 --- a/chromeos/components/tether/fake_host_scan_scheduler.cc +++ b/chromeos/components/tether/fake_host_scan_scheduler.cc
@@ -8,9 +8,9 @@ namespace tether { -FakeHostScanScheduler::FakeHostScanScheduler() {} +FakeHostScanScheduler::FakeHostScanScheduler() = default; -FakeHostScanScheduler::~FakeHostScanScheduler() {} +FakeHostScanScheduler::~FakeHostScanScheduler() = default; void FakeHostScanScheduler::ScheduleScan() { ++num_scheduled_scans_;
diff --git a/chromeos/components/tether/fake_network_configuration_remover.cc b/chromeos/components/tether/fake_network_configuration_remover.cc index 89f4e96..0d00815 100644 --- a/chromeos/components/tether/fake_network_configuration_remover.cc +++ b/chromeos/components/tether/fake_network_configuration_remover.cc
@@ -13,7 +13,7 @@ nullptr /* network_state_handler */, nullptr /* managed_network_configuration_handler */) {} -FakeNetworkConfigurationRemover::~FakeNetworkConfigurationRemover() {} +FakeNetworkConfigurationRemover::~FakeNetworkConfigurationRemover() = default; void FakeNetworkConfigurationRemover::RemoveNetworkConfiguration( const std::string& wifi_network_guid) {
diff --git a/chromeos/components/tether/fake_notification_presenter.cc b/chromeos/components/tether/fake_notification_presenter.cc index 70d8cdf..080231ef 100644 --- a/chromeos/components/tether/fake_notification_presenter.cc +++ b/chromeos/components/tether/fake_notification_presenter.cc
@@ -20,7 +20,7 @@ is_setup_required_notification_shown_(false), is_connection_failed_notification_shown_(false) {} -FakeNotificationPresenter::~FakeNotificationPresenter() {} +FakeNotificationPresenter::~FakeNotificationPresenter() = default; cryptauth::RemoteDevice& FakeNotificationPresenter::GetPotentialHotspotRemoteDevice() {
diff --git a/chromeos/components/tether/fake_tether_component.cc b/chromeos/components/tether/fake_tether_component.cc index a59baa5..b9b20b54 100644 --- a/chromeos/components/tether/fake_tether_component.cc +++ b/chromeos/components/tether/fake_tether_component.cc
@@ -11,7 +11,7 @@ FakeTetherComponent::FakeTetherComponent(bool has_asynchronous_shutdown) : has_asynchronous_shutdown_(has_asynchronous_shutdown) {} -FakeTetherComponent::~FakeTetherComponent() {} +FakeTetherComponent::~FakeTetherComponent() = default; void FakeTetherComponent::FinishAsynchronousShutdown() { DCHECK(status() == TetherComponent::Status::SHUTTING_DOWN);
diff --git a/chromeos/components/tether/fake_tether_connector.cc b/chromeos/components/tether/fake_tether_connector.cc index 702cf73..e51b0b7 100644 --- a/chromeos/components/tether/fake_tether_connector.cc +++ b/chromeos/components/tether/fake_tether_connector.cc
@@ -8,9 +8,9 @@ namespace tether { -FakeTetherConnector::FakeTetherConnector() {} +FakeTetherConnector::FakeTetherConnector() = default; -FakeTetherConnector::~FakeTetherConnector() {} +FakeTetherConnector::~FakeTetherConnector() = default; void FakeTetherConnector::ConnectToNetwork( const std::string& tether_network_guid,
diff --git a/chromeos/components/tether/fake_tether_disconnector.cc b/chromeos/components/tether/fake_tether_disconnector.cc index 3302844..48eb36c91 100644 --- a/chromeos/components/tether/fake_tether_disconnector.cc +++ b/chromeos/components/tether/fake_tether_disconnector.cc
@@ -8,9 +8,9 @@ namespace tether { -FakeTetherDisconnector::FakeTetherDisconnector() {} +FakeTetherDisconnector::FakeTetherDisconnector() = default; -FakeTetherDisconnector::~FakeTetherDisconnector() {} +FakeTetherDisconnector::~FakeTetherDisconnector() = default; void FakeTetherDisconnector::DisconnectFromNetwork( const std::string& tether_network_guid,
diff --git a/chromeos/components/tether/fake_tether_host_fetcher.cc b/chromeos/components/tether/fake_tether_host_fetcher.cc index b8ea9f2..df28b3d 100644 --- a/chromeos/components/tether/fake_tether_host_fetcher.cc +++ b/chromeos/components/tether/fake_tether_host_fetcher.cc
@@ -22,7 +22,7 @@ : FakeTetherHostFetcher(std::vector<cryptauth::RemoteDevice>(), synchronously_reply_with_results) {} -FakeTetherHostFetcher::~FakeTetherHostFetcher() {} +FakeTetherHostFetcher::~FakeTetherHostFetcher() = default; void FakeTetherHostFetcher::SetTetherHosts( const std::vector<cryptauth::RemoteDevice> tether_hosts) {
diff --git a/chromeos/components/tether/fake_wifi_hotspot_connector.cc b/chromeos/components/tether/fake_wifi_hotspot_connector.cc index 1b22dda88..4afbd19 100644 --- a/chromeos/components/tether/fake_wifi_hotspot_connector.cc +++ b/chromeos/components/tether/fake_wifi_hotspot_connector.cc
@@ -17,7 +17,7 @@ : WifiHotspotConnector(network_state_handler, nullptr /* network_connect */) {} -FakeWifiHotspotConnector::~FakeWifiHotspotConnector() {} +FakeWifiHotspotConnector::~FakeWifiHotspotConnector() = default; void FakeWifiHotspotConnector::CallMostRecentCallback( const std::string& wifi_guid) {
diff --git a/chromeos/components/tether/fake_wifi_hotspot_disconnector.cc b/chromeos/components/tether/fake_wifi_hotspot_disconnector.cc index a90873f..2aa33539 100644 --- a/chromeos/components/tether/fake_wifi_hotspot_disconnector.cc +++ b/chromeos/components/tether/fake_wifi_hotspot_disconnector.cc
@@ -8,9 +8,9 @@ namespace tether { -FakeWifiHotspotDisconnector::FakeWifiHotspotDisconnector() {} +FakeWifiHotspotDisconnector::FakeWifiHotspotDisconnector() = default; -FakeWifiHotspotDisconnector::~FakeWifiHotspotDisconnector() {} +FakeWifiHotspotDisconnector::~FakeWifiHotspotDisconnector() = default; void FakeWifiHotspotDisconnector::DisconnectFromWifiHotspot( const std::string& wifi_network_guid,
diff --git a/chromeos/components/tether/host_connection_metrics_logger.cc b/chromeos/components/tether/host_connection_metrics_logger.cc index 4daeefbd..4bbc6f0c 100644 --- a/chromeos/components/tether/host_connection_metrics_logger.cc +++ b/chromeos/components/tether/host_connection_metrics_logger.cc
@@ -10,9 +10,9 @@ namespace tether { -HostConnectionMetricsLogger::HostConnectionMetricsLogger() {} +HostConnectionMetricsLogger::HostConnectionMetricsLogger() = default; -HostConnectionMetricsLogger::~HostConnectionMetricsLogger() {} +HostConnectionMetricsLogger::~HostConnectionMetricsLogger() = default; void HostConnectionMetricsLogger::RecordConnectionToHostResult( ConnectionToHostResult result) {
diff --git a/chromeos/components/tether/host_connection_metrics_logger_unittest.cc b/chromeos/components/tether/host_connection_metrics_logger_unittest.cc index 37d658a3..8cd30397 100644 --- a/chromeos/components/tether/host_connection_metrics_logger_unittest.cc +++ b/chromeos/components/tether/host_connection_metrics_logger_unittest.cc
@@ -14,7 +14,7 @@ class HostConnectionMetricsLoggerTest : public testing::Test { protected: - HostConnectionMetricsLoggerTest() {} + HostConnectionMetricsLoggerTest() = default; void SetUp() override { metrics_logger_ = base::MakeUnique<HostConnectionMetricsLogger>();
diff --git a/chromeos/components/tether/host_scan_cache.cc b/chromeos/components/tether/host_scan_cache.cc index 8f8bb2e..b00b657 100644 --- a/chromeos/components/tether/host_scan_cache.cc +++ b/chromeos/components/tether/host_scan_cache.cc
@@ -8,8 +8,8 @@ namespace tether { -HostScanCache::HostScanCache() {} -HostScanCache::~HostScanCache() {} +HostScanCache::HostScanCache() = default; +HostScanCache::~HostScanCache() = default; void HostScanCache::AddObserver(HostScanCache::Observer* observer) { observer_list_.AddObserver(observer);
diff --git a/chromeos/components/tether/host_scan_cache_entry.cc b/chromeos/components/tether/host_scan_cache_entry.cc index 83b15483..234dbd4 100644 --- a/chromeos/components/tether/host_scan_cache_entry.cc +++ b/chromeos/components/tether/host_scan_cache_entry.cc
@@ -10,9 +10,9 @@ namespace tether { -HostScanCacheEntry::Builder::Builder() {} +HostScanCacheEntry::Builder::Builder() = default; -HostScanCacheEntry::Builder::~Builder() {} +HostScanCacheEntry::Builder::~Builder() = default; std::unique_ptr<HostScanCacheEntry> HostScanCacheEntry::Builder::Build() { DCHECK(!tether_network_guid_.empty()); @@ -71,15 +71,10 @@ signal_strength(signal_strength), setup_required(setup_required) {} -HostScanCacheEntry::HostScanCacheEntry(const HostScanCacheEntry& other) - : tether_network_guid(other.tether_network_guid), - device_name(other.device_name), - carrier(other.carrier), - battery_percentage(other.battery_percentage), - signal_strength(other.signal_strength), - setup_required(other.setup_required) {} +HostScanCacheEntry::HostScanCacheEntry(const HostScanCacheEntry& other) = + default; -HostScanCacheEntry::~HostScanCacheEntry() {} +HostScanCacheEntry::~HostScanCacheEntry() = default; bool HostScanCacheEntry::operator==(const HostScanCacheEntry& other) const { return tether_network_guid == other.tether_network_guid &&
diff --git a/chromeos/components/tether/host_scan_device_prioritizer_impl.cc b/chromeos/components/tether/host_scan_device_prioritizer_impl.cc index d4a771d..2da7a7f 100644 --- a/chromeos/components/tether/host_scan_device_prioritizer_impl.cc +++ b/chromeos/components/tether/host_scan_device_prioritizer_impl.cc
@@ -38,7 +38,7 @@ TetherHostResponseRecorder* tether_host_response_recorder) : tether_host_response_recorder_(tether_host_response_recorder) {} -HostScanDevicePrioritizerImpl::~HostScanDevicePrioritizerImpl() {} +HostScanDevicePrioritizerImpl::~HostScanDevicePrioritizerImpl() = default; void HostScanDevicePrioritizerImpl::SortByHostScanOrder( std::vector<cryptauth::RemoteDevice>* remote_devices) const {
diff --git a/chromeos/components/tether/host_scan_scheduler_impl_unittest.cc b/chromeos/components/tether/host_scan_scheduler_impl_unittest.cc index 01fdba7..329032cb 100644 --- a/chromeos/components/tether/host_scan_scheduler_impl_unittest.cc +++ b/chromeos/components/tether/host_scan_scheduler_impl_unittest.cc
@@ -42,7 +42,7 @@ nullptr, nullptr), num_scans_started_(0) {} - ~FakeHostScanner() override {} + ~FakeHostScanner() override = default; void StartScan() override { is_scan_active_ = true;
diff --git a/chromeos/components/tether/host_scanner.cc b/chromeos/components/tether/host_scanner.cc index e184c50..70091d4 100644 --- a/chromeos/components/tether/host_scanner.cc +++ b/chromeos/components/tether/host_scanner.cc
@@ -41,7 +41,7 @@ clock_(clock), weak_ptr_factory_(this) {} -HostScanner::~HostScanner() {} +HostScanner::~HostScanner() = default; bool HostScanner::IsScanActive() { return is_fetching_hosts_ || host_scanner_operation_;
diff --git a/chromeos/components/tether/host_scanner_operation.cc b/chromeos/components/tether/host_scanner_operation.cc index 2737fc2..beb5b2d 100644 --- a/chromeos/components/tether/host_scanner_operation.cc +++ b/chromeos/components/tether/host_scanner_operation.cc
@@ -102,7 +102,7 @@ device_status(device_status), setup_required(setup_required) {} -HostScannerOperation::ScannedDeviceInfo::~ScannedDeviceInfo() {} +HostScannerOperation::ScannedDeviceInfo::~ScannedDeviceInfo() = default; bool operator==(const HostScannerOperation::ScannedDeviceInfo& first, const HostScannerOperation::ScannedDeviceInfo& second) { @@ -123,7 +123,7 @@ tether_host_response_recorder_(tether_host_response_recorder), clock_(base::MakeUnique<base::DefaultClock>()) {} -HostScannerOperation::~HostScannerOperation() {} +HostScannerOperation::~HostScannerOperation() = default; void HostScannerOperation::AddObserver(Observer* observer) { observer_list_.AddObserver(observer);
diff --git a/chromeos/components/tether/host_scanner_operation_unittest.cc b/chromeos/components/tether/host_scanner_operation_unittest.cc index 6a6d404..cfa33d4 100644 --- a/chromeos/components/tether/host_scanner_operation_unittest.cc +++ b/chromeos/components/tether/host_scanner_operation_unittest.cc
@@ -38,7 +38,7 @@ class TestHostScanDevicePrioritizer : public HostScanDevicePrioritizer { public: TestHostScanDevicePrioritizer() : HostScanDevicePrioritizer() {} - ~TestHostScanDevicePrioritizer() override {} + ~TestHostScanDevicePrioritizer() override = default; // HostScanDevicePrioritizer: void SortByHostScanOrder(
diff --git a/chromeos/components/tether/host_scanner_unittest.cc b/chromeos/components/tether/host_scanner_unittest.cc index a287c15..307c129 100644 --- a/chromeos/components/tether/host_scanner_unittest.cc +++ b/chromeos/components/tether/host_scanner_unittest.cc
@@ -50,7 +50,7 @@ class FakeHostScanDevicePrioritizer : public HostScanDevicePrioritizer { public: FakeHostScanDevicePrioritizer() : HostScanDevicePrioritizer() {} - ~FakeHostScanDevicePrioritizer() override {} + ~FakeHostScanDevicePrioritizer() override = default; // Simply leave |remote_devices| as-is. void SortByHostScanOrder( @@ -69,7 +69,7 @@ host_scan_device_prioritizer, tether_host_response_recorder) {} - ~FakeHostScannerOperation() override {} + ~FakeHostScannerOperation() override = default; void SendScannedDeviceListUpdate( const std::vector<HostScannerOperation::ScannedDeviceInfo>& @@ -85,7 +85,7 @@ FakeHostScannerOperationFactory( const std::vector<cryptauth::RemoteDevice>& test_devices) : expected_devices_(test_devices) {} - virtual ~FakeHostScannerOperationFactory() {} + virtual ~FakeHostScannerOperationFactory() = default; std::vector<FakeHostScannerOperation*>& created_operations() { return created_operations_;
diff --git a/chromeos/components/tether/keep_alive_operation.cc b/chromeos/components/tether/keep_alive_operation.cc index a74960b..709ff08 100644 --- a/chromeos/components/tether/keep_alive_operation.cc +++ b/chromeos/components/tether/keep_alive_operation.cc
@@ -50,7 +50,7 @@ remote_device_(device_to_connect), clock_(base::MakeUnique<base::DefaultClock>()) {} -KeepAliveOperation::~KeepAliveOperation() {} +KeepAliveOperation::~KeepAliveOperation() = default; void KeepAliveOperation::AddObserver(Observer* observer) { observer_list_.AddObserver(observer);
diff --git a/chromeos/components/tether/keep_alive_operation_unittest.cc b/chromeos/components/tether/keep_alive_operation_unittest.cc index ed74015..a05dc1f3 100644 --- a/chromeos/components/tether/keep_alive_operation_unittest.cc +++ b/chromeos/components/tether/keep_alive_operation_unittest.cc
@@ -29,7 +29,7 @@ public: TestObserver() : has_run_callback_(false) {} - virtual ~TestObserver() {} + virtual ~TestObserver() = default; bool has_run_callback() { return has_run_callback_; }
diff --git a/chromeos/components/tether/keep_alive_scheduler_unittest.cc b/chromeos/components/tether/keep_alive_scheduler_unittest.cc index c272f4b..e0af9e4 100644 --- a/chromeos/components/tether/keep_alive_scheduler_unittest.cc +++ b/chromeos/components/tether/keep_alive_scheduler_unittest.cc
@@ -58,7 +58,7 @@ public: FakeKeepAliveOperationFactory() : num_created_(0), num_deleted_(0), last_created_(nullptr) {} - ~FakeKeepAliveOperationFactory() {} + ~FakeKeepAliveOperationFactory() = default; uint32_t num_created() { return num_created_; }
diff --git a/chromeos/components/tether/master_host_scan_cache_unittest.cc b/chromeos/components/tether/master_host_scan_cache_unittest.cc index a96a9be..06248f20 100644 --- a/chromeos/components/tether/master_host_scan_cache_unittest.cc +++ b/chromeos/components/tether/master_host_scan_cache_unittest.cc
@@ -30,8 +30,8 @@ class FakePersistentHostScanCache : public FakeHostScanCache, public PersistentHostScanCache { public: - FakePersistentHostScanCache() {} - ~FakePersistentHostScanCache() override {} + FakePersistentHostScanCache() = default; + ~FakePersistentHostScanCache() override = default; // PersistentHostScanCache: std::unordered_map<std::string, HostScanCacheEntry> GetStoredCacheEntries() @@ -55,8 +55,8 @@ class TestTimerFactory : public TimerFactory { public: - TestTimerFactory() {} - ~TestTimerFactory() override {} + TestTimerFactory() = default; + ~TestTimerFactory() override = default; std::unordered_map<std::string, ExtendedMockTimer*>& tether_network_guid_to_timer_map() {
diff --git a/chromeos/components/tether/message_transfer_operation_unittest.cc b/chromeos/components/tether/message_transfer_operation_unittest.cc index 7a9713c..d537cd92 100644 --- a/chromeos/components/tether/message_transfer_operation_unittest.cc +++ b/chromeos/components/tether/message_transfer_operation_unittest.cc
@@ -33,7 +33,7 @@ TestOperation(const std::vector<cryptauth::RemoteDevice>& devices_to_connect, BleConnectionManager* connection_manager) : MessageTransferOperation(devices_to_connect, connection_manager) {} - ~TestOperation() override {} + ~TestOperation() override = default; bool HasDeviceAuthenticated(const cryptauth::RemoteDevice& remote_device) { const auto iter = device_map_.find(remote_device); @@ -96,8 +96,8 @@ private: struct DeviceMapValue { - DeviceMapValue() {} - ~DeviceMapValue() {} + DeviceMapValue() = default; + ~DeviceMapValue() = default; bool has_device_authenticated; std::vector<std::shared_ptr<MessageWrapper>> received_messages; @@ -113,7 +113,7 @@ class TestTimerFactory : public TimerFactory { public: - ~TestTimerFactory() override {} + ~TestTimerFactory() override = default; // TimerFactory: std::unique_ptr<base::Timer> CreateOneShotTimer() override {
diff --git a/chromeos/components/tether/message_wrapper.cc b/chromeos/components/tether/message_wrapper.cc index a4f1248..58c78ac 100644 --- a/chromeos/components/tether/message_wrapper.cc +++ b/chromeos/components/tether/message_wrapper.cc
@@ -146,7 +146,7 @@ std::shared_ptr<google::protobuf::MessageLite> proto) : type_(type), proto_(proto) {} -MessageWrapper::~MessageWrapper() {} +MessageWrapper::~MessageWrapper() = default; std::shared_ptr<google::protobuf::MessageLite> MessageWrapper::GetProto() const {
diff --git a/chromeos/components/tether/message_wrapper_unittest.cc b/chromeos/components/tether/message_wrapper_unittest.cc index 48075e3..f7299fd 100644 --- a/chromeos/components/tether/message_wrapper_unittest.cc +++ b/chromeos/components/tether/message_wrapper_unittest.cc
@@ -48,7 +48,7 @@ class MessageWrapperTest : public testing::Test { protected: - MessageWrapperTest() {} + MessageWrapperTest() = default; private: DISALLOW_COPY_AND_ASSIGN(MessageWrapperTest);
diff --git a/chromeos/components/tether/mock_host_connection_metrics_logger.cc b/chromeos/components/tether/mock_host_connection_metrics_logger.cc index d46cc4a..c2b79b3 100644 --- a/chromeos/components/tether/mock_host_connection_metrics_logger.cc +++ b/chromeos/components/tether/mock_host_connection_metrics_logger.cc
@@ -8,9 +8,9 @@ namespace tether { -MockHostConnectionMetricsLogger::MockHostConnectionMetricsLogger() {} +MockHostConnectionMetricsLogger::MockHostConnectionMetricsLogger() = default; -MockHostConnectionMetricsLogger::~MockHostConnectionMetricsLogger() {} +MockHostConnectionMetricsLogger::~MockHostConnectionMetricsLogger() = default; } // namespace tether
diff --git a/chromeos/components/tether/mock_tether_host_response_recorder.cc b/chromeos/components/tether/mock_tether_host_response_recorder.cc index 483c4def..b6a0312 100644 --- a/chromeos/components/tether/mock_tether_host_response_recorder.cc +++ b/chromeos/components/tether/mock_tether_host_response_recorder.cc
@@ -11,7 +11,7 @@ MockTetherHostResponseRecorder::MockTetherHostResponseRecorder() : TetherHostResponseRecorder(nullptr) {} -MockTetherHostResponseRecorder::~MockTetherHostResponseRecorder() {} +MockTetherHostResponseRecorder::~MockTetherHostResponseRecorder() = default; } // namespace tether
diff --git a/chromeos/components/tether/network_configuration_remover.cc b/chromeos/components/tether/network_configuration_remover.cc index 671e1a8..c76c2ce 100644 --- a/chromeos/components/tether/network_configuration_remover.cc +++ b/chromeos/components/tether/network_configuration_remover.cc
@@ -41,7 +41,7 @@ managed_network_configuration_handler_( managed_network_configuration_handler) {} -NetworkConfigurationRemover::~NetworkConfigurationRemover() {} +NetworkConfigurationRemover::~NetworkConfigurationRemover() = default; void NetworkConfigurationRemover::RemoveNetworkConfiguration( const std::string& wifi_network_guid) {
diff --git a/chromeos/components/tether/network_configuration_remover_unittest.cc b/chromeos/components/tether/network_configuration_remover_unittest.cc index f9d3c9bd..f3c2eec 100644 --- a/chromeos/components/tether/network_configuration_remover_unittest.cc +++ b/chromeos/components/tether/network_configuration_remover_unittest.cc
@@ -43,7 +43,7 @@ class NetworkConfigurationRemoverTest : public NetworkStateTest { protected: NetworkConfigurationRemoverTest() : NetworkStateTest() {} - ~NetworkConfigurationRemoverTest() override {} + ~NetworkConfigurationRemoverTest() override = default; void SetUp() override { DBusThreadManager::Initialize();
diff --git a/chromeos/components/tether/network_connection_handler_tether_delegate.cc b/chromeos/components/tether/network_connection_handler_tether_delegate.cc index 09fb329b..998fba92 100644 --- a/chromeos/components/tether/network_connection_handler_tether_delegate.cc +++ b/chromeos/components/tether/network_connection_handler_tether_delegate.cc
@@ -34,7 +34,7 @@ NetworkConnectionHandlerTetherDelegate::Callbacks::Callbacks( const Callbacks& other) = default; -NetworkConnectionHandlerTetherDelegate::Callbacks::~Callbacks() {} +NetworkConnectionHandlerTetherDelegate::Callbacks::~Callbacks() = default; NetworkConnectionHandlerTetherDelegate::NetworkConnectionHandlerTetherDelegate( NetworkConnectionHandler* network_connection_handler,
diff --git a/chromeos/components/tether/network_connection_handler_tether_delegate_unittest.cc b/chromeos/components/tether/network_connection_handler_tether_delegate_unittest.cc index 080b01f..f4507484 100644 --- a/chromeos/components/tether/network_connection_handler_tether_delegate_unittest.cc +++ b/chromeos/components/tether/network_connection_handler_tether_delegate_unittest.cc
@@ -45,7 +45,7 @@ class TestNetworkConnectionHandler : public NetworkConnectionHandler { public: TestNetworkConnectionHandler() : NetworkConnectionHandler() {} - ~TestNetworkConnectionHandler() override {} + ~TestNetworkConnectionHandler() override = default; void CallTetherConnect(const std::string& tether_network_guid, const base::Closure& success_callback, @@ -89,7 +89,7 @@ class NetworkConnectionHandlerTetherDelegateTest : public testing::Test { protected: - NetworkConnectionHandlerTetherDelegateTest() {} + NetworkConnectionHandlerTetherDelegateTest() = default; void SetUp() override { result_.clear();
diff --git a/chromeos/components/tether/network_list_sorter.cc b/chromeos/components/tether/network_list_sorter.cc index 74a2357..5c8cdb1e 100644 --- a/chromeos/components/tether/network_list_sorter.cc +++ b/chromeos/components/tether/network_list_sorter.cc
@@ -61,9 +61,9 @@ } // namespace -NetworkListSorter::NetworkListSorter() {} +NetworkListSorter::NetworkListSorter() = default; -NetworkListSorter::~NetworkListSorter() {} +NetworkListSorter::~NetworkListSorter() = default; void NetworkListSorter::SortTetherNetworkList( NetworkStateHandler::ManagedStateList* tether_networks) const {
diff --git a/chromeos/components/tether/network_list_sorter_unittest.cc b/chromeos/components/tether/network_list_sorter_unittest.cc index 72cefc8..98b58fad 100644 --- a/chromeos/components/tether/network_list_sorter_unittest.cc +++ b/chromeos/components/tether/network_list_sorter_unittest.cc
@@ -29,7 +29,7 @@ class NetworkListSorterTest : public testing::Test { protected: - NetworkListSorterTest() {} + NetworkListSorterTest() = default; void SetUp() override { network_list_sorter_ = base::MakeUnique<NetworkListSorter>();
diff --git a/chromeos/components/tether/persistent_host_scan_cache_impl.cc b/chromeos/components/tether/persistent_host_scan_cache_impl.cc index e3d13ade..317c29f 100644 --- a/chromeos/components/tether/persistent_host_scan_cache_impl.cc +++ b/chromeos/components/tether/persistent_host_scan_cache_impl.cc
@@ -97,7 +97,7 @@ PrefService* pref_service) : pref_service_(pref_service) {} -PersistentHostScanCacheImpl::~PersistentHostScanCacheImpl() {} +PersistentHostScanCacheImpl::~PersistentHostScanCacheImpl() = default; std::unordered_map<std::string, HostScanCacheEntry> PersistentHostScanCacheImpl::GetStoredCacheEntries() {
diff --git a/chromeos/components/tether/synchronous_shutdown_object_container_impl.cc b/chromeos/components/tether/synchronous_shutdown_object_container_impl.cc index 15513228..e6aca15 100644 --- a/chromeos/components/tether/synchronous_shutdown_object_container_impl.cc +++ b/chromeos/components/tether/synchronous_shutdown_object_container_impl.cc
@@ -59,7 +59,7 @@ factory_instance_ = factory; } -SynchronousShutdownObjectContainerImpl::Factory::~Factory() {} +SynchronousShutdownObjectContainerImpl::Factory::~Factory() = default; std::unique_ptr<SynchronousShutdownObjectContainer> SynchronousShutdownObjectContainerImpl::Factory::BuildInstance(
diff --git a/chromeos/components/tether/tether_component.cc b/chromeos/components/tether/tether_component.cc index 687ea74..e93ac6a 100644 --- a/chromeos/components/tether/tether_component.cc +++ b/chromeos/components/tether/tether_component.cc
@@ -8,9 +8,9 @@ namespace tether { -TetherComponent::TetherComponent() {} +TetherComponent::TetherComponent() = default; -TetherComponent::~TetherComponent() {} +TetherComponent::~TetherComponent() = default; void TetherComponent::AddObserver(Observer* observer) { observer_list_.AddObserver(observer);
diff --git a/chromeos/components/tether/tether_component_impl.cc b/chromeos/components/tether/tether_component_impl.cc index 341153f..ab7f065 100644 --- a/chromeos/components/tether/tether_component_impl.cc +++ b/chromeos/components/tether/tether_component_impl.cc
@@ -117,7 +117,7 @@ weak_ptr_factory_.GetWeakPtr())); } -TetherComponentImpl::~TetherComponentImpl() {} +TetherComponentImpl::~TetherComponentImpl() = default; void TetherComponentImpl::RequestShutdown() { has_shutdown_been_requested_ = true;
diff --git a/chromeos/components/tether/tether_component_impl_unittest.cc b/chromeos/components/tether/tether_component_impl_unittest.cc index f3381625..17cfc6a 100644 --- a/chromeos/components/tether/tether_component_impl_unittest.cc +++ b/chromeos/components/tether/tether_component_impl_unittest.cc
@@ -26,8 +26,8 @@ class TestTetherComponentObserver : public TetherComponent::Observer { public: - TestTetherComponentObserver() {} - ~TestTetherComponentObserver() override {} + TestTetherComponentObserver() = default; + ~TestTetherComponentObserver() override = default; bool shutdown_complete() { return shutdown_complete_; } @@ -45,7 +45,7 @@ FakeAsynchronousShutdownObjectContainer* fake_asynchronous_container) : fake_asynchronous_container_(fake_asynchronous_container) {} - ~FakeAsynchronousShutdownObjectContainerFactory() override {} + ~FakeAsynchronousShutdownObjectContainerFactory() override = default; // AsynchronousShutdownObjectContainerImpl::Factory: std::unique_ptr<AsynchronousShutdownObjectContainer> BuildInstance( @@ -69,7 +69,7 @@ FakeSynchronousShutdownObjectContainer* fake_synchronous_container) : fake_synchronous_container_(fake_synchronous_container) {} - ~FakeSynchronousShutdownObjectContainerFactory() override {} + ~FakeSynchronousShutdownObjectContainerFactory() override = default; // SynchronousShutdownObjectContainerImpl::Factory: std::unique_ptr<SynchronousShutdownObjectContainer> BuildInstance( @@ -93,7 +93,7 @@ FakeCrashRecoveryManager* fake_crash_recovery_manager) : fake_crash_recovery_manager_(fake_crash_recovery_manager) {} - ~FakeCrashRecoveryManagerFactory() override {} + ~FakeCrashRecoveryManagerFactory() override = default; // CrashRecoveryManagerImpl::Factory: std::unique_ptr<CrashRecoveryManager> BuildInstance( @@ -111,8 +111,8 @@ class TetherComponentImplTest : public testing::Test { protected: - TetherComponentImplTest() {} - ~TetherComponentImplTest() override {} + TetherComponentImplTest() = default; + ~TetherComponentImplTest() override = default; void SetUp() override { was_synchronous_container_deleted_ = false;
diff --git a/chromeos/components/tether/tether_connector_impl_unittest.cc b/chromeos/components/tether/tether_connector_impl_unittest.cc index 710abbe..668da4b 100644 --- a/chromeos/components/tether/tether_connector_impl_unittest.cc +++ b/chromeos/components/tether/tether_connector_impl_unittest.cc
@@ -68,7 +68,7 @@ setup_required), setup_required_(setup_required) {} - ~FakeConnectTetheringOperation() override {} + ~FakeConnectTetheringOperation() override = default; void NotifyConnectTetheringRequestSent() { ConnectTetheringOperation::NotifyConnectTetheringRequestSent(); @@ -97,8 +97,8 @@ class FakeConnectTetheringOperationFactory : public ConnectTetheringOperation::Factory { public: - FakeConnectTetheringOperationFactory() {} - virtual ~FakeConnectTetheringOperationFactory() {} + FakeConnectTetheringOperationFactory() = default; + virtual ~FakeConnectTetheringOperationFactory() = default; std::vector<FakeConnectTetheringOperation*>& created_operations() { return created_operations_; @@ -129,7 +129,7 @@ public: TetherConnectorImplTest() : test_devices_(cryptauth::GenerateTestRemoteDevices(2u)) {} - ~TetherConnectorImplTest() override {} + ~TetherConnectorImplTest() override = default; void SetUp() override { DBusThreadManager::Initialize();
diff --git a/chromeos/components/tether/tether_disconnector_impl.cc b/chromeos/components/tether/tether_disconnector_impl.cc index 98e5923..6dd52af8 100644 --- a/chromeos/components/tether/tether_disconnector_impl.cc +++ b/chromeos/components/tether/tether_disconnector_impl.cc
@@ -33,7 +33,7 @@ device_id_tether_network_guid_map_(device_id_tether_network_guid_map), weak_ptr_factory_(this) {} -TetherDisconnectorImpl::~TetherDisconnectorImpl() {} +TetherDisconnectorImpl::~TetherDisconnectorImpl() = default; void TetherDisconnectorImpl::DisconnectFromNetwork( const std::string& tether_network_guid,
diff --git a/chromeos/components/tether/tether_disconnector_impl_unittest.cc b/chromeos/components/tether/tether_disconnector_impl_unittest.cc index ea46ba6..c8f84354 100644 --- a/chromeos/components/tether/tether_disconnector_impl_unittest.cc +++ b/chromeos/components/tether/tether_disconnector_impl_unittest.cc
@@ -29,7 +29,7 @@ public: TetherDisconnectorImplTest() : test_devices_(cryptauth::GenerateTestRemoteDevices(2u)) {} - ~TetherDisconnectorImplTest() override {} + ~TetherDisconnectorImplTest() override = default; void SetUp() override { fake_active_host_ = base::MakeUnique<FakeActiveHost>();
diff --git a/chromeos/components/tether/tether_host_fetcher.cc b/chromeos/components/tether/tether_host_fetcher.cc index 3fab2ad..a998a6a 100644 --- a/chromeos/components/tether/tether_host_fetcher.cc +++ b/chromeos/components/tether/tether_host_fetcher.cc
@@ -26,18 +26,15 @@ : device_id(device_id), single_callback(single_callback) {} TetherHostFetcher::TetherHostFetchRequest::TetherHostFetchRequest( - const TetherHostFetchRequest& other) - : device_id(other.device_id), - list_callback(other.list_callback), - single_callback(other.single_callback) {} + const TetherHostFetchRequest& other) = default; -TetherHostFetcher::TetherHostFetchRequest::~TetherHostFetchRequest() {} +TetherHostFetcher::TetherHostFetchRequest::~TetherHostFetchRequest() = default; TetherHostFetcher::TetherHostFetcher( cryptauth::CryptAuthService* cryptauth_service) : cryptauth_service_(cryptauth_service), weak_ptr_factory_(this) {} -TetherHostFetcher::~TetherHostFetcher() {} +TetherHostFetcher::~TetherHostFetcher() = default; void TetherHostFetcher::FetchAllTetherHosts( const TetherHostListCallback& callback) {
diff --git a/chromeos/components/tether/tether_host_fetcher_unittest.cc b/chromeos/components/tether/tether_host_fetcher_unittest.cc index 9a470a18b..88f93fc 100644 --- a/chromeos/components/tether/tether_host_fetcher_unittest.cc +++ b/chromeos/components/tether/tether_host_fetcher_unittest.cc
@@ -37,7 +37,7 @@ class MockCryptAuthDeviceManager : public cryptauth::CryptAuthDeviceManager { public: - ~MockCryptAuthDeviceManager() override {} + ~MockCryptAuthDeviceManager() override = default; MOCK_CONST_METHOD0(GetTetherHosts, std::vector<cryptauth::ExternalDeviceInfo>()); @@ -55,7 +55,7 @@ cryptauth::GcmDeviceInfo(), fake_cryptauth_gcm_manager, nullptr /* pref_service */) {} - ~MockCryptAuthEnrollmentManager() override {} + ~MockCryptAuthEnrollmentManager() override = default; MOCK_CONST_METHOD0(GetUserPrivateKey, std::string()); }; @@ -90,7 +90,7 @@ "", "", nullptr) {} - ~MockDeviceLoader() override {} + ~MockDeviceLoader() override = default; MOCK_METHOD2( Load,
diff --git a/chromeos/components/tether/tether_host_response_recorder.cc b/chromeos/components/tether/tether_host_response_recorder.cc index 4df1bec0..615ead1 100644 --- a/chromeos/components/tether/tether_host_response_recorder.cc +++ b/chromeos/components/tether/tether_host_response_recorder.cc
@@ -32,7 +32,7 @@ PrefService* pref_service) : pref_service_(pref_service) {} -TetherHostResponseRecorder::~TetherHostResponseRecorder() {} +TetherHostResponseRecorder::~TetherHostResponseRecorder() = default; void TetherHostResponseRecorder::AddObserver(Observer* observer) { observer_list_.AddObserver(observer);
diff --git a/chromeos/components/tether/tether_host_response_recorder_unittest.cc b/chromeos/components/tether/tether_host_response_recorder_unittest.cc index 9b60d1b..ebf8568 100644 --- a/chromeos/components/tether/tether_host_response_recorder_unittest.cc +++ b/chromeos/components/tether/tether_host_response_recorder_unittest.cc
@@ -18,7 +18,7 @@ class TestObserver final : public TetherHostResponseRecorder::Observer { public: TestObserver() : num_callbacks_(0) {} - ~TestObserver() {} + ~TestObserver() = default; uint32_t num_callbacks() { return num_callbacks_; }
diff --git a/chromeos/components/tether/tether_network_disconnection_handler_unittest.cc b/chromeos/components/tether/tether_network_disconnection_handler_unittest.cc index bfb8fc47..c60f5c5f 100644 --- a/chromeos/components/tether/tether_network_disconnection_handler_unittest.cc +++ b/chromeos/components/tether/tether_network_disconnection_handler_unittest.cc
@@ -45,7 +45,7 @@ public: MockNetworkConfigurationRemover() : NetworkConfigurationRemover(nullptr, nullptr) {} - ~MockNetworkConfigurationRemover() override {} + ~MockNetworkConfigurationRemover() override = default; MOCK_METHOD1(RemoveNetworkConfiguration, void(const std::string&)); }; @@ -55,7 +55,7 @@ class TetherNetworkDisconnectionHandlerTest : public NetworkStateTest { protected: TetherNetworkDisconnectionHandlerTest() : NetworkStateTest() {} - ~TetherNetworkDisconnectionHandlerTest() override {} + ~TetherNetworkDisconnectionHandlerTest() override = default; void SetUp() override { DBusThreadManager::Initialize();
diff --git a/chromeos/components/tether/timer_factory.cc b/chromeos/components/tether/timer_factory.cc index c26f9b9..35a090cf8 100644 --- a/chromeos/components/tether/timer_factory.cc +++ b/chromeos/components/tether/timer_factory.cc
@@ -8,7 +8,7 @@ namespace tether { -TimerFactory::~TimerFactory() {} +TimerFactory::~TimerFactory() = default; std::unique_ptr<base::Timer> TimerFactory::CreateOneShotTimer() { return base::MakeUnique<base::OneShotTimer>();
diff --git a/chromeos/components/tether/wifi_hotspot_connector_unittest.cc b/chromeos/components/tether/wifi_hotspot_connector_unittest.cc index f4b4e7cf..969028c 100644 --- a/chromeos/components/tether/wifi_hotspot_connector_unittest.cc +++ b/chromeos/components/tether/wifi_hotspot_connector_unittest.cc
@@ -61,7 +61,7 @@ public: explicit TestNetworkConnect(NetworkStateTest* network_state_test) : network_state_test_(network_state_test) {} - ~TestNetworkConnect() override {} + ~TestNetworkConnect() override = default; base::DictionaryValue* last_configuration() { return last_configuration_.get(); @@ -138,8 +138,8 @@ uint32_t num_disconnection_attempts_ = 0; }; - WifiHotspotConnectorTest() {} - ~WifiHotspotConnectorTest() override {} + WifiHotspotConnectorTest() = default; + ~WifiHotspotConnectorTest() override = default; void SetUp() override { other_wifi_service_path_.clear();
diff --git a/chromeos/components/tether/wifi_hotspot_disconnector_impl.cc b/chromeos/components/tether/wifi_hotspot_disconnector_impl.cc index 20cce5bb..a8b1c4e 100644 --- a/chromeos/components/tether/wifi_hotspot_disconnector_impl.cc +++ b/chromeos/components/tether/wifi_hotspot_disconnector_impl.cc
@@ -45,7 +45,7 @@ } } -WifiHotspotDisconnectorImpl::~WifiHotspotDisconnectorImpl() {} +WifiHotspotDisconnectorImpl::~WifiHotspotDisconnectorImpl() = default; void WifiHotspotDisconnectorImpl::DisconnectFromWifiHotspot( const std::string& wifi_network_guid,
diff --git a/chromeos/components/tether/wifi_hotspot_disconnector_impl_unittest.cc b/chromeos/components/tether/wifi_hotspot_disconnector_impl_unittest.cc index cc05b40..a68a65c 100644 --- a/chromeos/components/tether/wifi_hotspot_disconnector_impl_unittest.cc +++ b/chromeos/components/tether/wifi_hotspot_disconnector_impl_unittest.cc
@@ -44,7 +44,7 @@ public: explicit TestNetworkConnectionHandler(base::Closure disconnect_callback) : disconnect_callback_(disconnect_callback) {} - ~TestNetworkConnectionHandler() override {} + ~TestNetworkConnectionHandler() override = default; std::string last_disconnect_service_path() { return last_disconnect_service_path_; @@ -94,8 +94,8 @@ class WifiHotspotDisconnectorImplTest : public NetworkStateTest { public: - WifiHotspotDisconnectorImplTest() {} - ~WifiHotspotDisconnectorImplTest() override {} + WifiHotspotDisconnectorImplTest() = default; + ~WifiHotspotDisconnectorImplTest() override = default; void SetUp() override { DBusThreadManager::Initialize();
diff --git a/chromeos/cryptohome/async_method_caller.cc b/chromeos/cryptohome/async_method_caller.cc index 9128d35..edef400f 100644 --- a/chromeos/cryptohome/async_method_caller.cc +++ b/chromeos/cryptohome/async_method_caller.cc
@@ -212,7 +212,7 @@ private: struct CallbackElement { - CallbackElement() {} + CallbackElement() = default; explicit CallbackElement(const AsyncMethodCaller::Callback& callback) : callback(callback), task_runner(base::ThreadTaskRunnerHandle::Get()) {} @@ -221,7 +221,7 @@ }; struct DataCallbackElement { - DataCallbackElement() {} + DataCallbackElement() = default; explicit DataCallbackElement( const AsyncMethodCaller::DataCallback& callback) : data_callback(callback),
diff --git a/chromeos/cryptohome/cryptohome_parameters.cc b/chromeos/cryptohome/cryptohome_parameters.cc index e521662..c9d741b 100644 --- a/chromeos/cryptohome/cryptohome_parameters.cc +++ b/chromeos/cryptohome/cryptohome_parameters.cc
@@ -30,7 +30,7 @@ } // anonymous namespace -Identification::Identification() {} +Identification::Identification() = default; Identification::Identification(const AccountId& account_id) : id_(GetCryptohomeId(account_id)) {} @@ -115,8 +115,7 @@ KeyDefinition::AuthorizationData::AuthorizationData( const AuthorizationData& other) = default; -KeyDefinition::AuthorizationData::~AuthorizationData() { -} +KeyDefinition::AuthorizationData::~AuthorizationData() = default; bool KeyDefinition::AuthorizationData::operator==( const AuthorizationData& other) const { @@ -129,8 +128,7 @@ return true; } -KeyDefinition::ProviderData::ProviderData() { -} +KeyDefinition::ProviderData::ProviderData() = default; KeyDefinition::ProviderData::ProviderData(const std::string& name) : name(name) { @@ -160,8 +158,7 @@ bytes.reset(other.bytes ? new std::string(*other.bytes) : NULL); } -KeyDefinition::ProviderData::~ProviderData() { -} +KeyDefinition::ProviderData::~ProviderData() = default; bool KeyDefinition::ProviderData::operator==(const ProviderData& other) const { const bool has_number = number != nullptr; @@ -192,8 +189,7 @@ KeyDefinition::KeyDefinition(const KeyDefinition& other) = default; -KeyDefinition::~KeyDefinition() { -} +KeyDefinition::~KeyDefinition() = default; bool KeyDefinition::operator==(const KeyDefinition& other) const { if (type != other.type ||
diff --git a/chromeos/cryptohome/homedir_methods.cc b/chromeos/cryptohome/homedir_methods.cc index d1877e75..14ba3df 100644 --- a/chromeos/cryptohome/homedir_methods.cc +++ b/chromeos/cryptohome/homedir_methods.cc
@@ -96,7 +96,7 @@ public: HomedirMethodsImpl() : weak_ptr_factory_(this) {} - ~HomedirMethodsImpl() override {} + ~HomedirMethodsImpl() override = default; void GetKeyDataEx(const Identification& id, const cryptohome::AuthorizationRequest& auth, @@ -175,15 +175,6 @@ weak_ptr_factory_.GetWeakPtr(), callback)); } - void MigrateToDircrypto(const Identification& id, - const cryptohome::MigrateToDircryptoRequest& request, - const DBusResultCallback& callback) override { - DBusThreadManager::Get()->GetCryptohomeClient()->MigrateToDircrypto( - id, request, - base::Bind(&HomedirMethodsImpl::OnDBusResultCallback, - weak_ptr_factory_.GetWeakPtr(), callback)); - } - private: void OnGetKeyDataExCallback(const GetKeyDataCallback& callback, base::Optional<BaseReply> reply) { @@ -328,10 +319,6 @@ callback.Run(true, MOUNT_ERROR_NONE); } - void OnDBusResultCallback(const DBusResultCallback& callback, bool result) { - callback.Run(result); - } - base::WeakPtrFactory<HomedirMethodsImpl> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(HomedirMethodsImpl);
diff --git a/chromeos/cryptohome/homedir_methods.h b/chromeos/cryptohome/homedir_methods.h index 7648423..9ef4c33 100644 --- a/chromeos/cryptohome/homedir_methods.h +++ b/chromeos/cryptohome/homedir_methods.h
@@ -43,7 +43,6 @@ MountCallback; typedef base::Callback<void(bool success, int64_t size)> GetAccountDiskUsageCallback; - typedef base::Callback<void(bool success)> DBusResultCallback; virtual ~HomedirMethods() {} @@ -111,12 +110,6 @@ const Identification& id, const GetAccountDiskUsageCallback& callback) = 0; - // Asks cryptohomed to migrate the cryptohome to the new encryption method - // for the user specified by |id|. - virtual void MigrateToDircrypto(const Identification& id, - const MigrateToDircryptoRequest& request, - const DBusResultCallback& callback) = 0; - // Creates the global HomedirMethods instance. static void Initialize();
diff --git a/chromeos/cryptohome/mock_async_method_caller.cc b/chromeos/cryptohome/mock_async_method_caller.cc index 7f39eef..bbd1f2e 100644 --- a/chromeos/cryptohome/mock_async_method_caller.cc +++ b/chromeos/cryptohome/mock_async_method_caller.cc
@@ -21,7 +21,7 @@ : success_(false), return_code_(cryptohome::MOUNT_ERROR_NONE) { } -MockAsyncMethodCaller::~MockAsyncMethodCaller() {} +MockAsyncMethodCaller::~MockAsyncMethodCaller() = default; void MockAsyncMethodCaller::SetUp(bool success, MountError return_code) { success_ = success;
diff --git a/chromeos/cryptohome/mock_homedir_methods.h b/chromeos/cryptohome/mock_homedir_methods.h index 0c9d6bb9..b71797e 100644 --- a/chromeos/cryptohome/mock_homedir_methods.h +++ b/chromeos/cryptohome/mock_homedir_methods.h
@@ -59,10 +59,6 @@ MOCK_METHOD2(GetAccountDiskUsage, void(const Identification& id, const GetAccountDiskUsageCallback& callback)); - MOCK_METHOD3(MigrateToDircrypto, - void(const Identification& id, - const MigrateToDircryptoRequest& request, - const DBusResultCallback& callback)); void set_mount_callback(const base::Closure& callback) { on_mount_called_ = callback;
diff --git a/chromeos/cryptohome/system_salt_getter.cc b/chromeos/cryptohome/system_salt_getter.cc index 09d120b6..4fec017 100644 --- a/chromeos/cryptohome/system_salt_getter.cc +++ b/chromeos/cryptohome/system_salt_getter.cc
@@ -27,8 +27,7 @@ SystemSaltGetter::SystemSaltGetter() : weak_ptr_factory_(this) { } -SystemSaltGetter::~SystemSaltGetter() { -} +SystemSaltGetter::~SystemSaltGetter() = default; void SystemSaltGetter::GetSystemSalt( const GetSystemSaltCallback& callback) {
diff --git a/chromeos/dbus/arc_obb_mounter_client.cc b/chromeos/dbus/arc_obb_mounter_client.cc index 36d4f4e..05e621b 100644 --- a/chromeos/dbus/arc_obb_mounter_client.cc +++ b/chromeos/dbus/arc_obb_mounter_client.cc
@@ -30,7 +30,7 @@ class ArcObbMounterClientImpl : public ArcObbMounterClient { public: ArcObbMounterClientImpl() : weak_ptr_factory_(this) {} - ~ArcObbMounterClientImpl() override {} + ~ArcObbMounterClientImpl() override = default; // ArcObbMounterClient override: void MountObb(const std::string& obb_file, @@ -82,9 +82,9 @@ } // namespace -ArcObbMounterClient::ArcObbMounterClient() {} +ArcObbMounterClient::ArcObbMounterClient() = default; -ArcObbMounterClient::~ArcObbMounterClient() {} +ArcObbMounterClient::~ArcObbMounterClient() = default; // static ArcObbMounterClient* ArcObbMounterClient::Create() {
diff --git a/chromeos/dbus/arc_oemcrypto_client.cc b/chromeos/dbus/arc_oemcrypto_client.cc index 9022eb0b..068a30c 100644 --- a/chromeos/dbus/arc_oemcrypto_client.cc +++ b/chromeos/dbus/arc_oemcrypto_client.cc
@@ -21,7 +21,7 @@ class ArcOemCryptoClientImpl : public ArcOemCryptoClient { public: ArcOemCryptoClientImpl() : weak_ptr_factory_(this) {} - ~ArcOemCryptoClientImpl() override {} + ~ArcOemCryptoClientImpl() override = default; // ArcOemCryptoClient override: void BootstrapMojoConnection(base::ScopedFD fd, @@ -73,9 +73,9 @@ } // namespace -ArcOemCryptoClient::ArcOemCryptoClient() {} +ArcOemCryptoClient::ArcOemCryptoClient() = default; -ArcOemCryptoClient::~ArcOemCryptoClient() {} +ArcOemCryptoClient::~ArcOemCryptoClient() = default; // static ArcOemCryptoClient* ArcOemCryptoClient::Create() {
diff --git a/chromeos/dbus/audio_node.cc b/chromeos/dbus/audio_node.cc index 1685a43..a973dd9 100644 --- a/chromeos/dbus/audio_node.cc +++ b/chromeos/dbus/audio_node.cc
@@ -12,7 +12,7 @@ namespace chromeos { -AudioNode::AudioNode() {} +AudioNode::AudioNode() = default; AudioNode::AudioNode(bool is_input, uint64_t id, @@ -37,7 +37,7 @@ AudioNode::AudioNode(const AudioNode& other) = default; -AudioNode::~AudioNode() {} +AudioNode::~AudioNode() = default; std::string AudioNode::ToString() const { std::string result;
diff --git a/chromeos/dbus/auth_policy_client.cc b/chromeos/dbus/auth_policy_client.cc index 7deaab0e..c243d8d 100644 --- a/chromeos/dbus/auth_policy_client.cc +++ b/chromeos/dbus/auth_policy_client.cc
@@ -59,7 +59,7 @@ public: AuthPolicyClientImpl() : weak_ptr_factory_(this) {} - ~AuthPolicyClientImpl() override {} + ~AuthPolicyClientImpl() override = default; // AuthPolicyClient override. void JoinAdDomain(const authpolicy::JoinDomainRequest& request, @@ -168,12 +168,11 @@ dbus::Response* response) { if (!response) { DLOG(ERROR) << "RefreshDevicePolicy: failed to call to authpolicy"; - std::move(callback).Run(false); + std::move(callback).Run(authpolicy::ERROR_DBUS_FAILURE); return; } dbus::MessageReader reader(response); - std::move(callback).Run(GetErrorFromReader(&reader) == - authpolicy::ERROR_NONE); + std::move(callback).Run(GetErrorFromReader(&reader)); } void HandleJoinCallback(JoinCallback callback, dbus::Response* response) { @@ -208,9 +207,9 @@ } // namespace -AuthPolicyClient::AuthPolicyClient() {} +AuthPolicyClient::AuthPolicyClient() = default; -AuthPolicyClient::~AuthPolicyClient() {} +AuthPolicyClient::~AuthPolicyClient() = default; // static AuthPolicyClient* AuthPolicyClient::Create() {
diff --git a/chromeos/dbus/auth_policy_client.h b/chromeos/dbus/auth_policy_client.h index 0137c86..d7932399 100644 --- a/chromeos/dbus/auth_policy_client.h +++ b/chromeos/dbus/auth_policy_client.h
@@ -33,7 +33,8 @@ base::OnceCallback<void(authpolicy::ErrorType error, const authpolicy::KerberosFiles& kerberos_files)>; using JoinCallback = base::OnceCallback<void(authpolicy::ErrorType error)>; - using RefreshPolicyCallback = base::OnceCallback<void(bool success)>; + using RefreshPolicyCallback = + base::OnceCallback<void(authpolicy::ErrorType error)>; ~AuthPolicyClient() override;
diff --git a/chromeos/dbus/biod/biod_client.cc b/chromeos/dbus/biod/biod_client.cc index 2538b92..076904c 100644 --- a/chromeos/dbus/biod/biod_client.cc +++ b/chromeos/dbus/biod/biod_client.cc
@@ -36,7 +36,7 @@ public: BiodClientImpl() : weak_ptr_factory_(this) {} - ~BiodClientImpl() override {} + ~BiodClientImpl() override = default; // BiodClient overrides: void AddObserver(Observer* observer) override { @@ -405,9 +405,9 @@ DISALLOW_COPY_AND_ASSIGN(BiodClientImpl); }; -BiodClient::BiodClient() {} +BiodClient::BiodClient() = default; -BiodClient::~BiodClient() {} +BiodClient::~BiodClient() = default; // static BiodClient* BiodClient::Create(DBusClientImplementationType type) {
diff --git a/chromeos/dbus/biod/biod_client_unittest.cc b/chromeos/dbus/biod/biod_client_unittest.cc index ab10eea..8eb8fba0 100644 --- a/chromeos/dbus/biod/biod_client_unittest.cc +++ b/chromeos/dbus/biod/biod_client_unittest.cc
@@ -60,8 +60,8 @@ class BiodClientTest : public testing::Test { public: - BiodClientTest() {} - ~BiodClientTest() override {} + BiodClientTest() = default; + ~BiodClientTest() override = default; void SetUp() override { dbus::Bus::Options options;
diff --git a/chromeos/dbus/biod/fake_biod_client.cc b/chromeos/dbus/biod/fake_biod_client.cc index d949be8..14c6248 100644 --- a/chromeos/dbus/biod/fake_biod_client.cc +++ b/chromeos/dbus/biod/fake_biod_client.cc
@@ -41,9 +41,9 @@ std::vector<std::string> fake_fingerprint; }; -FakeBiodClient::FakeBiodClient() {} +FakeBiodClient::FakeBiodClient() = default; -FakeBiodClient::~FakeBiodClient() {} +FakeBiodClient::~FakeBiodClient() = default; void FakeBiodClient::SendEnrollScanDone(const std::string& fingerprint, biod::ScanResult type_result,
diff --git a/chromeos/dbus/biod/fake_biod_client_unittest.cc b/chromeos/dbus/biod/fake_biod_client_unittest.cc index 4825d16..eedec84 100644 --- a/chromeos/dbus/biod/fake_biod_client_unittest.cc +++ b/chromeos/dbus/biod/fake_biod_client_unittest.cc
@@ -34,7 +34,7 @@ FakeBiodClientTest() : task_runner_(new base::TestSimpleTaskRunner), task_runner_handle_(task_runner_) {} - ~FakeBiodClientTest() override {} + ~FakeBiodClientTest() override = default; // Returns the stored records for |user_id|. Verified to work in // TestGetRecordsForUser.
diff --git a/chromeos/dbus/biod/test_utils.cc b/chromeos/dbus/biod/test_utils.cc index fe676f20..32fda8f 100644 --- a/chromeos/dbus/biod/test_utils.cc +++ b/chromeos/dbus/biod/test_utils.cc
@@ -33,9 +33,9 @@ *dest_result = src_result; } -TestBiodObserver::TestBiodObserver() {} +TestBiodObserver::TestBiodObserver() = default; -TestBiodObserver::~TestBiodObserver() {} +TestBiodObserver::~TestBiodObserver() = default; int TestBiodObserver::NumEnrollScansReceived() const { return num_complete_enroll_scans_received_ +
diff --git a/chromeos/dbus/blocking_method_caller.cc b/chromeos/dbus/blocking_method_caller.cc index a60cb6e9b..26b55c3 100644 --- a/chromeos/dbus/blocking_method_caller.cc +++ b/chromeos/dbus/blocking_method_caller.cc
@@ -37,8 +37,7 @@ base::WaitableEvent::ResetPolicy::AUTOMATIC, base::WaitableEvent::InitialState::NOT_SIGNALED) {} -BlockingMethodCaller::~BlockingMethodCaller() { -} +BlockingMethodCaller::~BlockingMethodCaller() = default; std::unique_ptr<dbus::Response> BlockingMethodCaller::CallMethodAndBlock( dbus::MethodCall* method_call) {
diff --git a/chromeos/dbus/blocking_method_caller_unittest.cc b/chromeos/dbus/blocking_method_caller_unittest.cc index 77840e61..12c709b 100644 --- a/chromeos/dbus/blocking_method_caller_unittest.cc +++ b/chromeos/dbus/blocking_method_caller_unittest.cc
@@ -38,7 +38,7 @@ bool RunsTasksInCurrentSequence() const override { return true; } protected: - ~FakeTaskRunner() override {} + ~FakeTaskRunner() override = default; }; } // namespace
diff --git a/chromeos/dbus/cras_audio_client.cc b/chromeos/dbus/cras_audio_client.cc index 92fd51c73..a66da99c 100644 --- a/chromeos/dbus/cras_audio_client.cc +++ b/chromeos/dbus/cras_audio_client.cc
@@ -25,7 +25,7 @@ public: CrasAudioClientImpl() : cras_proxy_(NULL), weak_ptr_factory_(this) {} - ~CrasAudioClientImpl() override {} + ~CrasAudioClientImpl() override = default; // CrasAudioClient overrides: void AddObserver(Observer* observer) override { @@ -515,8 +515,7 @@ DISALLOW_COPY_AND_ASSIGN(CrasAudioClientImpl); }; -CrasAudioClient::Observer::~Observer() { -} +CrasAudioClient::Observer::~Observer() = default; void CrasAudioClient::Observer::AudioClientRestarted() { } @@ -541,11 +540,9 @@ void CrasAudioClient::Observer::HotwordTriggered(uint64_t tv_sec, uint64_t tv_nsec) {} -CrasAudioClient::CrasAudioClient() { -} +CrasAudioClient::CrasAudioClient() = default; -CrasAudioClient::~CrasAudioClient() { -} +CrasAudioClient::~CrasAudioClient() = default; // static CrasAudioClient* CrasAudioClient::Create() {
diff --git a/chromeos/dbus/cras_audio_client_unittest.cc b/chromeos/dbus/cras_audio_client_unittest.cc index 3e0762d..e065b811 100644 --- a/chromeos/dbus/cras_audio_client_unittest.cc +++ b/chromeos/dbus/cras_audio_client_unittest.cc
@@ -84,8 +84,8 @@ // A mock CrasAudioClient Observer. class MockObserver : public CrasAudioClient::Observer { public: - MockObserver() {} - ~MockObserver() override {} + MockObserver() = default; + ~MockObserver() override = default; MOCK_METHOD1(OutputMuteChanged, void(bool mute_on)); MOCK_METHOD1(InputMuteChanged, void(bool mute_on)); MOCK_METHOD0(NodesChanged, void());
diff --git a/chromeos/dbus/cros_disks_client.cc b/chromeos/dbus/cros_disks_client.cc index 07fe123..3b0c08d8 100644 --- a/chromeos/dbus/cros_disks_client.cc +++ b/chromeos/dbus/cros_disks_client.cc
@@ -504,8 +504,7 @@ InitializeFromResponse(response); } -DiskInfo::~DiskInfo() { -} +DiskInfo::~DiskInfo() = default; // Initializes |this| from |response| given by the cros-disks service. // Below is an example of |response|'s raw message (long string is ellipsized). @@ -670,9 +669,9 @@ //////////////////////////////////////////////////////////////////////////////// // CrosDisksClient -CrosDisksClient::CrosDisksClient() {} +CrosDisksClient::CrosDisksClient() = default; -CrosDisksClient::~CrosDisksClient() {} +CrosDisksClient::~CrosDisksClient() = default; // static CrosDisksClient* CrosDisksClient::Create(DBusClientImplementationType type) {
diff --git a/chromeos/dbus/cryptohome_client.cc b/chromeos/dbus/cryptohome_client.cc index 4361363..a5cde3d 100644 --- a/chromeos/dbus/cryptohome_client.cc +++ b/chromeos/dbus/cryptohome_client.cc
@@ -1266,9 +1266,9 @@ //////////////////////////////////////////////////////////////////////////////// // CryptohomeClient -CryptohomeClient::CryptohomeClient() {} +CryptohomeClient::CryptohomeClient() = default; -CryptohomeClient::~CryptohomeClient() {} +CryptohomeClient::~CryptohomeClient() = default; // static CryptohomeClient* CryptohomeClient::Create() {
diff --git a/chromeos/dbus/dbus_clients_browser.cc b/chromeos/dbus/dbus_clients_browser.cc index 351d763..61d4d6d 100644 --- a/chromeos/dbus/dbus_clients_browser.cc +++ b/chromeos/dbus/dbus_clients_browser.cc
@@ -108,7 +108,7 @@ virtual_file_provider_client_.reset(new FakeVirtualFileProviderClient); } -DBusClientsBrowser::~DBusClientsBrowser() {} +DBusClientsBrowser::~DBusClientsBrowser() = default; void DBusClientsBrowser::Initialize(dbus::Bus* system_bus) { DCHECK(DBusThreadManager::IsInitialized());
diff --git a/chromeos/dbus/dbus_clients_common.cc b/chromeos/dbus/dbus_clients_common.cc index f23aa2f..385fa26 100644 --- a/chromeos/dbus/dbus_clients_common.cc +++ b/chromeos/dbus/dbus_clients_common.cc
@@ -114,7 +114,7 @@ update_engine_client_.reset(UpdateEngineClient::Create(client_impl_type)); } -DBusClientsCommon::~DBusClientsCommon() {} +DBusClientsCommon::~DBusClientsCommon() = default; void DBusClientsCommon::Initialize(dbus::Bus* system_bus) { DCHECK(DBusThreadManager::IsInitialized());
diff --git a/chromeos/dbus/dbus_thread_manager.cc b/chromeos/dbus/dbus_thread_manager.cc index f2b13c3f..d6297d9 100644 --- a/chromeos/dbus/dbus_thread_manager.cc +++ b/chromeos/dbus/dbus_thread_manager.cc
@@ -328,9 +328,9 @@ return g_dbus_thread_manager; } -DBusThreadManagerSetter::DBusThreadManagerSetter() {} +DBusThreadManagerSetter::DBusThreadManagerSetter() = default; -DBusThreadManagerSetter::~DBusThreadManagerSetter() {} +DBusThreadManagerSetter::~DBusThreadManagerSetter() = default; void DBusThreadManagerSetter::SetAuthPolicyClient( std::unique_ptr<AuthPolicyClient> client) {
diff --git a/chromeos/dbus/debug_daemon_client.cc b/chromeos/dbus/debug_daemon_client.cc index ee16e53..c88fff8 100644 --- a/chromeos/dbus/debug_daemon_client.cc +++ b/chromeos/dbus/debug_daemon_client.cc
@@ -116,7 +116,7 @@ public: DebugDaemonClientImpl() : debugdaemon_proxy_(NULL), weak_ptr_factory_(this) {} - ~DebugDaemonClientImpl() override {} + ~DebugDaemonClientImpl() override = default; // DebugDaemonClient override. void DumpDebugLogs(bool is_compressed, @@ -712,11 +712,9 @@ DISALLOW_COPY_AND_ASSIGN(DebugDaemonClientImpl); }; -DebugDaemonClient::DebugDaemonClient() { -} +DebugDaemonClient::DebugDaemonClient() = default; -DebugDaemonClient::~DebugDaemonClient() { -} +DebugDaemonClient::~DebugDaemonClient() = default; // static DebugDaemonClient::StopAgentTracingCallback
diff --git a/chromeos/dbus/easy_unlock_client.cc b/chromeos/dbus/easy_unlock_client.cc index a4955c1..136988b 100644 --- a/chromeos/dbus/easy_unlock_client.cc +++ b/chromeos/dbus/easy_unlock_client.cc
@@ -45,7 +45,7 @@ public: EasyUnlockClientImpl() : proxy_(NULL), weak_ptr_factory_(this) {} - ~EasyUnlockClientImpl() override {} + ~EasyUnlockClientImpl() override = default; // EasyUnlockClient override. void GenerateEcP256KeyPair(const KeyPairCallback& callback) override { @@ -185,19 +185,21 @@ } // namespace -EasyUnlockClient::CreateSecureMessageOptions::CreateSecureMessageOptions() {} +EasyUnlockClient::CreateSecureMessageOptions::CreateSecureMessageOptions() = + default; -EasyUnlockClient::CreateSecureMessageOptions::~CreateSecureMessageOptions() {} +EasyUnlockClient::CreateSecureMessageOptions::~CreateSecureMessageOptions() = + default; -EasyUnlockClient::UnwrapSecureMessageOptions::UnwrapSecureMessageOptions() {} +EasyUnlockClient::UnwrapSecureMessageOptions::UnwrapSecureMessageOptions() = + default; -EasyUnlockClient::UnwrapSecureMessageOptions::~UnwrapSecureMessageOptions() {} +EasyUnlockClient::UnwrapSecureMessageOptions::~UnwrapSecureMessageOptions() = + default; -EasyUnlockClient::EasyUnlockClient() { -} +EasyUnlockClient::EasyUnlockClient() = default; -EasyUnlockClient::~EasyUnlockClient() { -} +EasyUnlockClient::~EasyUnlockClient() = default; // static EasyUnlockClient* EasyUnlockClient::Create() {
diff --git a/chromeos/dbus/fake_arc_obb_mounter_client.cc b/chromeos/dbus/fake_arc_obb_mounter_client.cc index 7df1d19..1ccc98b 100644 --- a/chromeos/dbus/fake_arc_obb_mounter_client.cc +++ b/chromeos/dbus/fake_arc_obb_mounter_client.cc
@@ -12,9 +12,9 @@ namespace chromeos { -FakeArcObbMounterClient::FakeArcObbMounterClient() {} +FakeArcObbMounterClient::FakeArcObbMounterClient() = default; -FakeArcObbMounterClient::~FakeArcObbMounterClient() {} +FakeArcObbMounterClient::~FakeArcObbMounterClient() = default; void FakeArcObbMounterClient::Init(dbus::Bus* bus) {}
diff --git a/chromeos/dbus/fake_arc_oemcrypto_client.cc b/chromeos/dbus/fake_arc_oemcrypto_client.cc index 39f35ae4..46985f4d 100644 --- a/chromeos/dbus/fake_arc_oemcrypto_client.cc +++ b/chromeos/dbus/fake_arc_oemcrypto_client.cc
@@ -12,9 +12,9 @@ namespace chromeos { -FakeArcOemCryptoClient::FakeArcOemCryptoClient() {} +FakeArcOemCryptoClient::FakeArcOemCryptoClient() = default; -FakeArcOemCryptoClient::~FakeArcOemCryptoClient() {} +FakeArcOemCryptoClient::~FakeArcOemCryptoClient() = default; void FakeArcOemCryptoClient::Init(dbus::Bus* bus) {}
diff --git a/chromeos/dbus/fake_auth_policy_client.cc b/chromeos/dbus/fake_auth_policy_client.cc index 4120d437..5010932 100644 --- a/chromeos/dbus/fake_auth_policy_client.cc +++ b/chromeos/dbus/fake_auth_policy_client.cc
@@ -19,9 +19,11 @@ #include "base/threading/thread_task_runner_handle.h" #include "chromeos/chromeos_paths.h" #include "chromeos/cryptohome/cryptohome_parameters.h" +#include "chromeos/cryptohome/cryptohome_util.h" #include "chromeos/dbus/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/session_manager_client.h" +#include "chromeos/login/auth/authpolicy_login_helper.h" #include "components/policy/proto/chrome_device_policy.pb.h" #include "components/policy/proto/cloud_policy.pb.h" #include "components/policy/proto/device_management_backend.pb.h" @@ -33,12 +35,14 @@ namespace { -const size_t kMaxMachineNameLength = 15; -const char kInvalidMachineNameCharacters[] = "\\/:*?\"<>|"; +constexpr size_t kMaxMachineNameLength = 15; +constexpr char kInvalidMachineNameCharacters[] = "\\/:*?\"<>|"; void OnStorePolicy(chromeos::AuthPolicyClient::RefreshPolicyCallback callback, bool success) { - std::move(callback).Run(success); + const authpolicy::ErrorType error = + success ? authpolicy::ERROR_NONE : authpolicy::ERROR_STORE_POLICY_FAILED; + std::move(callback).Run(error); } // Posts |closure| on the ThreadTaskRunner with |delay|. @@ -74,16 +78,16 @@ chromeos::DBusThreadManager::Get()->GetSessionManagerClient(); session_manager_client->StoreDevicePolicy( response.SerializeAsString(), - base::Bind(&OnStorePolicy, base::Passed(std::move(callback)))); + base::BindOnce(&OnStorePolicy, std::move(callback))); } } // namespace namespace chromeos { -FakeAuthPolicyClient::FakeAuthPolicyClient() {} +FakeAuthPolicyClient::FakeAuthPolicyClient() = default; -FakeAuthPolicyClient::~FakeAuthPolicyClient() {} +FakeAuthPolicyClient::~FakeAuthPolicyClient() = default; void FakeAuthPolicyClient::Init(dbus::Bus* bus) {} @@ -174,7 +178,14 @@ void FakeAuthPolicyClient::RefreshDevicePolicy(RefreshPolicyCallback callback) { if (!started_) { LOG(ERROR) << "authpolicyd not started"; - std::move(callback).Run(false); + std::move(callback).Run(authpolicy::ERROR_DBUS_FAILURE); + return; + } + + if (!AuthPolicyLoginHelper::IsAdLocked()) { + // Pretend that policy was fetched and cached inside authpolicyd. + std::move(callback).Run( + authpolicy::ERROR_DEVICE_POLICY_CACHED_BUT_NOT_SENT); return; } @@ -195,11 +206,13 @@ void FakeAuthPolicyClient::RefreshUserPolicy(const AccountId& account_id, RefreshPolicyCallback callback) { + DCHECK(AuthPolicyLoginHelper::IsAdLocked()); if (!started_) { LOG(ERROR) << "authpolicyd not started"; - std::move(callback).Run(false); + std::move(callback).Run(authpolicy::ERROR_DBUS_FAILURE); return; } + SessionManagerClient* session_manager_client = DBusThreadManager::Get()->GetSessionManagerClient(); @@ -217,7 +230,7 @@ response.set_policy_data(policy_data.SerializeAsString()); session_manager_client->StorePolicyForUser( cryptohome::Identification(account_id), response.SerializeAsString(), - base::Bind(&OnStorePolicy, base::Passed(std::move(callback)))); + base::BindOnce(&OnStorePolicy, std::move(callback))); } void FakeAuthPolicyClient::ConnectToSignal( @@ -238,7 +251,7 @@ const std::string& protobuf) { if (response_type != SessionManagerClient::RetrievePolicyResponseType::SUCCESS) { - std::move(callback).Run(false); + std::move(callback).Run(authpolicy::ERROR_DBUS_FAILURE); return; } em::PolicyFetchResponse response;
diff --git a/chromeos/dbus/fake_auth_policy_client_unittest.cc b/chromeos/dbus/fake_auth_policy_client_unittest.cc index 65c40c5..41c8e850 100644 --- a/chromeos/dbus/fake_auth_policy_client_unittest.cc +++ b/chromeos/dbus/fake_auth_policy_client_unittest.cc
@@ -7,6 +7,10 @@ #include "base/bind.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "chromeos/dbus/dbus_thread_manager.h" +#include "chromeos/dbus/fake_cryptohome_client.h" +#include "chromeos/dbus/fake_session_manager_client.h" +#include "chromeos/login/auth/authpolicy_login_helper.h" #include "components/signin/core/account_id/account_id.h" #include "testing/gtest/include/gtest/gtest.h" @@ -21,11 +25,19 @@ class FakeAuthPolicyClientTest : public ::testing::Test { public: - FakeAuthPolicyClientTest() {} + FakeAuthPolicyClientTest() = default; protected: FakeAuthPolicyClient* authpolicy_client() { return &client_; } + void SetUp() override { + ::testing::Test::SetUp(); + DBusThreadManager::GetSetterForTesting()->SetSessionManagerClient( + std::make_unique<FakeSessionManagerClient>()); + DBusThreadManager::GetSetterForTesting()->SetCryptohomeClient( + std::make_unique<FakeCryptohomeClient>()); + } + void JoinAdDomain(const std::string& machine_name, const std::string& username, AuthPolicyClient::JoinCallback callback) { @@ -46,6 +58,11 @@ std::move(callback)); } + void LockDeviceActiveDirectory() { + EXPECT_TRUE(AuthPolicyLoginHelper::LockDeviceActiveDirectoryForTesting( + std::string())); + } + private: FakeAuthPolicyClient client_; base::MessageLoop loop_; @@ -56,24 +73,25 @@ // Tests parsing machine name. TEST_F(FakeAuthPolicyClientTest, JoinAdDomain_ParseMachineName) { authpolicy_client()->set_started(true); + LockDeviceActiveDirectory(); JoinAdDomain("correct_length1", kCorrectUserName, - base::Bind([](authpolicy::ErrorType error) { + base::BindOnce([](authpolicy::ErrorType error) { EXPECT_EQ(authpolicy::ERROR_NONE, error); })); JoinAdDomain("", kCorrectUserName, - base::Bind([](authpolicy::ErrorType error) { + base::BindOnce([](authpolicy::ErrorType error) { EXPECT_EQ(authpolicy::ERROR_INVALID_MACHINE_NAME, error); })); JoinAdDomain("too_long_machine_name", kCorrectUserName, - base::Bind([](authpolicy::ErrorType error) { + base::BindOnce([](authpolicy::ErrorType error) { EXPECT_EQ(authpolicy::ERROR_MACHINE_NAME_TOO_LONG, error); })); JoinAdDomain("invalid:name", kCorrectUserName, - base::Bind([](authpolicy::ErrorType error) { + base::BindOnce([](authpolicy::ErrorType error) { EXPECT_EQ(authpolicy::ERROR_INVALID_MACHINE_NAME, error); })); JoinAdDomain(">nvalidname", kCorrectUserName, - base::Bind([](authpolicy::ErrorType error) { + base::BindOnce([](authpolicy::ErrorType error) { EXPECT_EQ(authpolicy::ERROR_INVALID_MACHINE_NAME, error); })); @@ -83,28 +101,29 @@ // Tests parsing user name. TEST_F(FakeAuthPolicyClientTest, JoinAdDomain_ParseUPN) { authpolicy_client()->set_started(true); + LockDeviceActiveDirectory(); JoinAdDomain(kCorrectMachineName, "user@realm.com", - base::Bind([](authpolicy::ErrorType error) { + base::BindOnce([](authpolicy::ErrorType error) { EXPECT_EQ(authpolicy::ERROR_NONE, error); })); JoinAdDomain(kCorrectMachineName, "user", - base::Bind([](authpolicy::ErrorType error) { + base::BindOnce([](authpolicy::ErrorType error) { EXPECT_EQ(authpolicy::ERROR_PARSE_UPN_FAILED, error); })); JoinAdDomain(kCorrectMachineName, "", - base::Bind([](authpolicy::ErrorType error) { + base::BindOnce([](authpolicy::ErrorType error) { EXPECT_EQ(authpolicy::ERROR_PARSE_UPN_FAILED, error); })); JoinAdDomain(kCorrectMachineName, "user@", - base::Bind([](authpolicy::ErrorType error) { + base::BindOnce([](authpolicy::ErrorType error) { EXPECT_EQ(authpolicy::ERROR_PARSE_UPN_FAILED, error); })); JoinAdDomain(kCorrectMachineName, "@realm", - base::Bind([](authpolicy::ErrorType error) { + base::BindOnce([](authpolicy::ErrorType error) { EXPECT_EQ(authpolicy::ERROR_PARSE_UPN_FAILED, error); })); JoinAdDomain(kCorrectMachineName, "user@realm@com", - base::Bind([](authpolicy::ErrorType error) { + base::BindOnce([](authpolicy::ErrorType error) { EXPECT_EQ(authpolicy::ERROR_PARSE_UPN_FAILED, error); })); @@ -114,10 +133,11 @@ // Test AuthenticateUser. TEST_F(FakeAuthPolicyClientTest, AuthenticateUser_ByAccountId) { authpolicy_client()->set_started(true); + LockDeviceActiveDirectory(); // Check that account_id do not change. AuthenticateUser( kCorrectUserName, kAccountId, - base::Bind( + base::BindOnce( [](authpolicy::ErrorType error, const authpolicy::ActiveDirectoryAccountInfo& account_info) { EXPECT_EQ(authpolicy::ERROR_NONE, error); @@ -127,21 +147,43 @@ // Tests calls to not started authpolicyd fails. TEST_F(FakeAuthPolicyClientTest, NotStartedAuthPolicyService) { + LockDeviceActiveDirectory(); JoinAdDomain(kCorrectMachineName, kCorrectUserName, - base::Bind([](authpolicy::ErrorType error) { + base::BindOnce([](authpolicy::ErrorType error) { EXPECT_EQ(authpolicy::ERROR_DBUS_FAILURE, error); })); AuthenticateUser( kCorrectUserName, std::string() /* account_id */, - base::Bind([](authpolicy::ErrorType error, - const authpolicy::ActiveDirectoryAccountInfo&) { + base::BindOnce([](authpolicy::ErrorType error, + const authpolicy::ActiveDirectoryAccountInfo&) { EXPECT_EQ(authpolicy::ERROR_DBUS_FAILURE, error); })); authpolicy_client()->RefreshDevicePolicy( - base::Bind([](bool success) { EXPECT_FALSE(success); })); + base::BindOnce([](authpolicy::ErrorType error) { + EXPECT_EQ(authpolicy::ERROR_DBUS_FAILURE, error); + })); authpolicy_client()->RefreshUserPolicy( AccountId::FromUserEmail(kCorrectUserName), - base::Bind([](bool success) { EXPECT_FALSE(success); })); + base::BindOnce([](authpolicy::ErrorType error) { + EXPECT_EQ(authpolicy::ERROR_DBUS_FAILURE, error); + })); + + base::RunLoop().RunUntilIdle(); +} + +// Tests RefreshDevicePolicy. On a not locked device it should cache policy. On +// a locked device it should send policy to session_manager. +TEST_F(FakeAuthPolicyClientTest, NotLockedDeviceCachesPolicy) { + authpolicy_client()->set_started(true); + authpolicy_client()->RefreshDevicePolicy( + base::BindOnce([](authpolicy::ErrorType error) { + EXPECT_EQ(authpolicy::ERROR_DEVICE_POLICY_CACHED_BUT_NOT_SENT, error); + })); + LockDeviceActiveDirectory(); + authpolicy_client()->RefreshDevicePolicy( + base::BindOnce([](authpolicy::ErrorType error) { + EXPECT_EQ(authpolicy::ERROR_NONE, error); + })); base::RunLoop().RunUntilIdle(); }
diff --git a/chromeos/dbus/fake_cras_audio_client.cc b/chromeos/dbus/fake_cras_audio_client.cc index ad45915..065fbc00 100644 --- a/chromeos/dbus/fake_cras_audio_client.cc +++ b/chromeos/dbus/fake_cras_audio_client.cc
@@ -13,8 +13,7 @@ active_output_node_id_(0) { } -FakeCrasAudioClient::~FakeCrasAudioClient() { -} +FakeCrasAudioClient::~FakeCrasAudioClient() = default; void FakeCrasAudioClient::Init(dbus::Bus* bus) { VLOG(1) << "FakeCrasAudioClient is created";
diff --git a/chromeos/dbus/fake_cros_disks_client.cc b/chromeos/dbus/fake_cros_disks_client.cc index 0aaa82a2..aa1490f 100644 --- a/chromeos/dbus/fake_cros_disks_client.cc +++ b/chromeos/dbus/fake_cros_disks_client.cc
@@ -70,8 +70,7 @@ rename_call_count_(0), rename_success_(true) {} -FakeCrosDisksClient::~FakeCrosDisksClient() { -} +FakeCrosDisksClient::~FakeCrosDisksClient() = default; void FakeCrosDisksClient::Init(dbus::Bus* bus) { }
diff --git a/chromeos/dbus/fake_cryptohome_client.cc b/chromeos/dbus/fake_cryptohome_client.cc index ba632dc..cf0af293 100644 --- a/chromeos/dbus/fake_cryptohome_client.cc +++ b/chromeos/dbus/fake_cryptohome_client.cc
@@ -56,7 +56,7 @@ LoadInstallAttributes(); } -FakeCryptohomeClient::~FakeCryptohomeClient() {} +FakeCryptohomeClient::~FakeCryptohomeClient() = default; void FakeCryptohomeClient::Init(dbus::Bus* bus) { }
diff --git a/chromeos/dbus/fake_debug_daemon_client.cc b/chromeos/dbus/fake_debug_daemon_client.cc index 222b011..717fd9a 100644 --- a/chromeos/dbus/fake_debug_daemon_client.cc +++ b/chromeos/dbus/fake_debug_daemon_client.cc
@@ -35,7 +35,7 @@ service_is_available_(true) { } -FakeDebugDaemonClient::~FakeDebugDaemonClient() {} +FakeDebugDaemonClient::~FakeDebugDaemonClient() = default; void FakeDebugDaemonClient::Init(dbus::Bus* bus) {}
diff --git a/chromeos/dbus/fake_easy_unlock_client.cc b/chromeos/dbus/fake_easy_unlock_client.cc index 1264b9f..dc3a3ec 100644 --- a/chromeos/dbus/fake_easy_unlock_client.cc +++ b/chromeos/dbus/fake_easy_unlock_client.cc
@@ -56,7 +56,7 @@ FakeEasyUnlockClient::FakeEasyUnlockClient() : generated_keys_count_(0) {} -FakeEasyUnlockClient::~FakeEasyUnlockClient() {} +FakeEasyUnlockClient::~FakeEasyUnlockClient() = default; void FakeEasyUnlockClient::Init(dbus::Bus* bus) {}
diff --git a/chromeos/dbus/fake_gsm_sms_client.cc b/chromeos/dbus/fake_gsm_sms_client.cc index 4d4e571..4468251 100644 --- a/chromeos/dbus/fake_gsm_sms_client.cc +++ b/chromeos/dbus/fake_gsm_sms_client.cc
@@ -29,8 +29,7 @@ test_messages_.push_back("Test Message 6"); } -FakeGsmSMSClient::~FakeGsmSMSClient() { -} +FakeGsmSMSClient::~FakeGsmSMSClient() = default; void FakeGsmSMSClient::Init(dbus::Bus* bus) { }
diff --git a/chromeos/dbus/fake_image_burner_client.cc b/chromeos/dbus/fake_image_burner_client.cc index 7b9b9f7..ceb17df 100644 --- a/chromeos/dbus/fake_image_burner_client.cc +++ b/chromeos/dbus/fake_image_burner_client.cc
@@ -8,11 +8,9 @@ namespace chromeos { -FakeImageBurnerClient::FakeImageBurnerClient() { -} +FakeImageBurnerClient::FakeImageBurnerClient() = default; -FakeImageBurnerClient::~FakeImageBurnerClient() { -} +FakeImageBurnerClient::~FakeImageBurnerClient() = default; void FakeImageBurnerClient::Init(dbus::Bus* bus) { }
diff --git a/chromeos/dbus/fake_lorgnette_manager_client.cc b/chromeos/dbus/fake_lorgnette_manager_client.cc index 56f7827..803f1ee 100644 --- a/chromeos/dbus/fake_lorgnette_manager_client.cc +++ b/chromeos/dbus/fake_lorgnette_manager_client.cc
@@ -14,9 +14,9 @@ namespace chromeos { -FakeLorgnetteManagerClient::FakeLorgnetteManagerClient() {} +FakeLorgnetteManagerClient::FakeLorgnetteManagerClient() = default; -FakeLorgnetteManagerClient::~FakeLorgnetteManagerClient() {} +FakeLorgnetteManagerClient::~FakeLorgnetteManagerClient() = default; void FakeLorgnetteManagerClient::Init(dbus::Bus* bus) {}
diff --git a/chromeos/dbus/fake_media_analytics_client.cc b/chromeos/dbus/fake_media_analytics_client.cc index eeb54a6..e98589a 100644 --- a/chromeos/dbus/fake_media_analytics_client.cc +++ b/chromeos/dbus/fake_media_analytics_client.cc
@@ -15,7 +15,7 @@ current_state_.set_status(mri::State::UNINITIALIZED); } -FakeMediaAnalyticsClient::~FakeMediaAnalyticsClient() {} +FakeMediaAnalyticsClient::~FakeMediaAnalyticsClient() = default; bool FakeMediaAnalyticsClient::FireMediaPerceptionEvent( const mri::MediaPerception& media_perception) {
diff --git a/chromeos/dbus/fake_modem_messaging_client.cc b/chromeos/dbus/fake_modem_messaging_client.cc index 43ff75a..3461106 100644 --- a/chromeos/dbus/fake_modem_messaging_client.cc +++ b/chromeos/dbus/fake_modem_messaging_client.cc
@@ -14,8 +14,8 @@ namespace chromeos { -FakeModemMessagingClient::FakeModemMessagingClient() {} -FakeModemMessagingClient::~FakeModemMessagingClient() {} +FakeModemMessagingClient::FakeModemMessagingClient() = default; +FakeModemMessagingClient::~FakeModemMessagingClient() = default; void FakeModemMessagingClient::Init(dbus::Bus* bus) {}
diff --git a/chromeos/dbus/fake_permission_broker_client.cc b/chromeos/dbus/fake_permission_broker_client.cc index e6dd303..f5f28ea1 100644 --- a/chromeos/dbus/fake_permission_broker_client.cc +++ b/chromeos/dbus/fake_permission_broker_client.cc
@@ -47,9 +47,9 @@ } // namespace -FakePermissionBrokerClient::FakePermissionBrokerClient() {} +FakePermissionBrokerClient::FakePermissionBrokerClient() = default; -FakePermissionBrokerClient::~FakePermissionBrokerClient() {} +FakePermissionBrokerClient::~FakePermissionBrokerClient() = default; void FakePermissionBrokerClient::Init(dbus::Bus* bus) {}
diff --git a/chromeos/dbus/fake_power_manager_client_unittest.cc b/chromeos/dbus/fake_power_manager_client_unittest.cc index cf30d1d..8d474d6 100644 --- a/chromeos/dbus/fake_power_manager_client_unittest.cc +++ b/chromeos/dbus/fake_power_manager_client_unittest.cc
@@ -22,7 +22,7 @@ class TestObserver : public PowerManagerClient::Observer { public: TestObserver() : num_power_changed_(0) {} - ~TestObserver() override {} + ~TestObserver() override = default; const power_manager::PowerSupplyProperties& props() const { return props_; } int num_power_changed() const { return num_power_changed_; }
diff --git a/chromeos/dbus/fake_session_manager_client.cc b/chromeos/dbus/fake_session_manager_client.cc index 54216be6..797d3bb 100644 --- a/chromeos/dbus/fake_session_manager_client.cc +++ b/chromeos/dbus/fake_session_manager_client.cc
@@ -63,8 +63,7 @@ arc_available_(false), weak_ptr_factory_(this) {} -FakeSessionManagerClient::~FakeSessionManagerClient() { -} +FakeSessionManagerClient::~FakeSessionManagerClient() = default; void FakeSessionManagerClient::Init(dbus::Bus* bus) { } @@ -335,10 +334,10 @@ void FakeSessionManagerClient::GetArcStartTime( DBusMethodCallback<base::TimeTicks> callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::BindOnce(std::move(callback), - arc_available_ ? base::make_optional( - base::TimeTicks::Now()) - : base::nullopt)); + FROM_HERE, + base::BindOnce(std::move(callback), + arc_available_ ? base::make_optional(arc_start_time_) + : base::nullopt)); } void FakeSessionManagerClient::RemoveArcData(
diff --git a/chromeos/dbus/fake_session_manager_client.h b/chromeos/dbus/fake_session_manager_client.h index 3493b25a..1657164 100644 --- a/chromeos/dbus/fake_session_manager_client.h +++ b/chromeos/dbus/fake_session_manager_client.h
@@ -12,6 +12,7 @@ #include "base/compiler_specific.h" #include "base/macros.h" #include "base/observer_list.h" +#include "base/time/time.h" #include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/session_manager_client.h" @@ -146,6 +147,9 @@ } void set_arc_available(bool available) { arc_available_ = available; } + void set_arc_start_time(base::TimeTicks arc_start_time) { + arc_start_time_ = arc_start_time; + } void set_low_disk(bool low_disk) { low_disk_ = low_disk; } @@ -174,6 +178,8 @@ int notify_lock_screen_dismissed_call_count_; bool arc_available_; + base::TimeTicks arc_start_time_; + bool low_disk_ = false; // Pseudo running container id. If not running, empty. std::string container_instance_id_;
diff --git a/chromeos/dbus/fake_shill_device_client.cc b/chromeos/dbus/fake_shill_device_client.cc index 8511828f..f412e84d 100644 --- a/chromeos/dbus/fake_shill_device_client.cc +++ b/chromeos/dbus/fake_shill_device_client.cc
@@ -68,8 +68,7 @@ tdls_busy_count_(0), weak_ptr_factory_(this) {} -FakeShillDeviceClient::~FakeShillDeviceClient() { -} +FakeShillDeviceClient::~FakeShillDeviceClient() = default; // ShillDeviceClient overrides.
diff --git a/chromeos/dbus/fake_shill_ipconfig_client.cc b/chromeos/dbus/fake_shill_ipconfig_client.cc index 7879ec1..c28bf1a1 100644 --- a/chromeos/dbus/fake_shill_ipconfig_client.cc +++ b/chromeos/dbus/fake_shill_ipconfig_client.cc
@@ -26,8 +26,7 @@ FakeShillIPConfigClient::FakeShillIPConfigClient() : weak_ptr_factory_(this) { } -FakeShillIPConfigClient::~FakeShillIPConfigClient() { -} +FakeShillIPConfigClient::~FakeShillIPConfigClient() = default; void FakeShillIPConfigClient::Init(dbus::Bus* bus) { }
diff --git a/chromeos/dbus/fake_shill_manager_client.cc b/chromeos/dbus/fake_shill_manager_client.cc index 5d2c8033..cb78752b 100644 --- a/chromeos/dbus/fake_shill_manager_client.cc +++ b/chromeos/dbus/fake_shill_manager_client.cc
@@ -151,7 +151,7 @@ ParseCommandLineSwitch(); } -FakeShillManagerClient::~FakeShillManagerClient() {} +FakeShillManagerClient::~FakeShillManagerClient() = default; // ShillManagerClient overrides.
diff --git a/chromeos/dbus/fake_shill_profile_client.cc b/chromeos/dbus/fake_shill_profile_client.cc index 620642a..a48fbed 100644 --- a/chromeos/dbus/fake_shill_profile_client.cc +++ b/chromeos/dbus/fake_shill_profile_client.cc
@@ -40,9 +40,9 @@ } // namespace -FakeShillProfileClient::FakeShillProfileClient() {} +FakeShillProfileClient::FakeShillProfileClient() = default; -FakeShillProfileClient::~FakeShillProfileClient() {} +FakeShillProfileClient::~FakeShillProfileClient() = default; void FakeShillProfileClient::Init(dbus::Bus* bus) {}
diff --git a/chromeos/dbus/fake_shill_service_client.cc b/chromeos/dbus/fake_shill_service_client.cc index 9ae9a97..071801f 100644 --- a/chromeos/dbus/fake_shill_service_client.cc +++ b/chromeos/dbus/fake_shill_service_client.cc
@@ -52,9 +52,7 @@ FakeShillServiceClient::FakeShillServiceClient() : weak_ptr_factory_(this) { } -FakeShillServiceClient::~FakeShillServiceClient() { -} - +FakeShillServiceClient::~FakeShillServiceClient() = default; // ShillServiceClient overrides.
diff --git a/chromeos/dbus/fake_shill_third_party_vpn_driver_client.cc b/chromeos/dbus/fake_shill_third_party_vpn_driver_client.cc index 52596d1..dfd206e4 100644 --- a/chromeos/dbus/fake_shill_third_party_vpn_driver_client.cc +++ b/chromeos/dbus/fake_shill_third_party_vpn_driver_client.cc
@@ -15,11 +15,11 @@ namespace chromeos { -FakeShillThirdPartyVpnDriverClient::FakeShillThirdPartyVpnDriverClient() { -} +FakeShillThirdPartyVpnDriverClient::FakeShillThirdPartyVpnDriverClient() = + default; -FakeShillThirdPartyVpnDriverClient::~FakeShillThirdPartyVpnDriverClient() { -} +FakeShillThirdPartyVpnDriverClient::~FakeShillThirdPartyVpnDriverClient() = + default; void FakeShillThirdPartyVpnDriverClient::Init(dbus::Bus* bus) { }
diff --git a/chromeos/dbus/fake_sms_client.cc b/chromeos/dbus/fake_sms_client.cc index 4f104721..ea5c3cc 100644 --- a/chromeos/dbus/fake_sms_client.cc +++ b/chromeos/dbus/fake_sms_client.cc
@@ -20,7 +20,7 @@ FakeSMSClient::FakeSMSClient() : weak_ptr_factory_(this) {} -FakeSMSClient::~FakeSMSClient() {} +FakeSMSClient::~FakeSMSClient() = default; void FakeSMSClient::Init(dbus::Bus* bus) {}
diff --git a/chromeos/dbus/fake_system_clock_client.cc b/chromeos/dbus/fake_system_clock_client.cc index 3579a4ab..baba88ac 100644 --- a/chromeos/dbus/fake_system_clock_client.cc +++ b/chromeos/dbus/fake_system_clock_client.cc
@@ -8,10 +8,9 @@ namespace chromeos { -FakeSystemClockClient::FakeSystemClockClient() {} +FakeSystemClockClient::FakeSystemClockClient() = default; -FakeSystemClockClient::~FakeSystemClockClient() { -} +FakeSystemClockClient::~FakeSystemClockClient() = default; void FakeSystemClockClient::NotifyObserversSystemClockUpdated() { for (auto& observer : observers_)
diff --git a/chromeos/dbus/fake_update_engine_client.cc b/chromeos/dbus/fake_update_engine_client.cc index db0a9c3..859cfd9 100644 --- a/chromeos/dbus/fake_update_engine_client.cc +++ b/chromeos/dbus/fake_update_engine_client.cc
@@ -17,8 +17,7 @@ rollback_call_count_(0), can_rollback_call_count_(0) {} -FakeUpdateEngineClient::~FakeUpdateEngineClient() { -} +FakeUpdateEngineClient::~FakeUpdateEngineClient() = default; void FakeUpdateEngineClient::Init(dbus::Bus* bus) { }
diff --git a/chromeos/dbus/fake_upstart_client.cc b/chromeos/dbus/fake_upstart_client.cc index 8661ed5..efea42c98a 100644 --- a/chromeos/dbus/fake_upstart_client.cc +++ b/chromeos/dbus/fake_upstart_client.cc
@@ -4,15 +4,16 @@ #include "chromeos/dbus/fake_upstart_client.h" +#include "base/threading/thread_task_runner_handle.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/fake_auth_policy_client.h" #include "chromeos/dbus/fake_media_analytics_client.h" namespace chromeos { -FakeUpstartClient::FakeUpstartClient() {} +FakeUpstartClient::FakeUpstartClient() = default; -FakeUpstartClient::~FakeUpstartClient() {} +FakeUpstartClient::~FakeUpstartClient() = default; void FakeUpstartClient::Init(dbus::Bus* bus) {} @@ -30,14 +31,17 @@ authpolicy_client->set_started(true); } -void FakeUpstartClient::StartMediaAnalytics(const UpstartCallback& callback) { +void FakeUpstartClient::StartMediaAnalytics( + const std::vector<std::string>& /* upstart_env */, + const UpstartCallback& callback) { FakeMediaAnalyticsClient* media_analytics_client = static_cast<FakeMediaAnalyticsClient*>( DBusThreadManager::Get()->GetMediaAnalyticsClient()); DLOG_IF(WARNING, media_analytics_client->process_running()) << "Trying to start media analytics which is already started."; media_analytics_client->set_process_running(true); - callback.Run(true); + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::BindOnce(std::move(callback), true)); } void FakeUpstartClient::RestartMediaAnalytics(const UpstartCallback& callback) { @@ -47,7 +51,8 @@ media_analytics_client->set_process_running(false); media_analytics_client->set_process_running(true); media_analytics_client->SetStateSuspended(); - callback.Run(true); + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::BindOnce(std::move(callback), true)); } void FakeUpstartClient::StopMediaAnalytics() { @@ -59,4 +64,13 @@ media_analytics_client->set_process_running(false); } +void FakeUpstartClient::StopMediaAnalytics(const UpstartCallback& callback) { + FakeMediaAnalyticsClient* media_analytics_client = + static_cast<FakeMediaAnalyticsClient*>( + DBusThreadManager::Get()->GetMediaAnalyticsClient()); + media_analytics_client->set_process_running(false); + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::BindOnce(std::move(callback), true)); +} + } // namespace chromeos
diff --git a/chromeos/dbus/fake_upstart_client.h b/chromeos/dbus/fake_upstart_client.h index 45b6911f..43c7669 100644 --- a/chromeos/dbus/fake_upstart_client.h +++ b/chromeos/dbus/fake_upstart_client.h
@@ -22,9 +22,11 @@ // UpstartClient overrides. void StartAuthPolicyService() override; void RestartAuthPolicyService() override; - void StartMediaAnalytics(const UpstartCallback& callback) override; + void StartMediaAnalytics(const std::vector<std::string>& upstart_env, + const UpstartCallback& callback) override; void RestartMediaAnalytics(const UpstartCallback& callback) override; void StopMediaAnalytics() override; + void StopMediaAnalytics(const UpstartCallback& callback) override; private: DISALLOW_COPY_AND_ASSIGN(FakeUpstartClient);
diff --git a/chromeos/dbus/gsm_sms_client.cc b/chromeos/dbus/gsm_sms_client.cc index 943b3bcb..9deade5 100644 --- a/chromeos/dbus/gsm_sms_client.cc +++ b/chromeos/dbus/gsm_sms_client.cc
@@ -240,9 +240,9 @@ //////////////////////////////////////////////////////////////////////////////// // GsmSMSClient -GsmSMSClient::GsmSMSClient() {} +GsmSMSClient::GsmSMSClient() = default; -GsmSMSClient::~GsmSMSClient() {} +GsmSMSClient::~GsmSMSClient() = default; // static GsmSMSClient* GsmSMSClient::Create() {
diff --git a/chromeos/dbus/image_burner_client.cc b/chromeos/dbus/image_burner_client.cc index 00f94b2..39de073 100644 --- a/chromeos/dbus/image_burner_client.cc +++ b/chromeos/dbus/image_burner_client.cc
@@ -24,7 +24,7 @@ public: ImageBurnerClientImpl() : proxy_(NULL), weak_ptr_factory_(this) {} - ~ImageBurnerClientImpl() override {} + ~ImageBurnerClientImpl() override = default; // ImageBurnerClient override. void BurnImage(const std::string& from_path, @@ -139,11 +139,9 @@ } // namespace -ImageBurnerClient::ImageBurnerClient() { -} +ImageBurnerClient::ImageBurnerClient() = default; -ImageBurnerClient::~ImageBurnerClient() { -} +ImageBurnerClient::~ImageBurnerClient() = default; // static ImageBurnerClient* ImageBurnerClient::Create() {
diff --git a/chromeos/dbus/image_loader_client.cc b/chromeos/dbus/image_loader_client.cc index 5454b080..f128f02 100644 --- a/chromeos/dbus/image_loader_client.cc +++ b/chromeos/dbus/image_loader_client.cc
@@ -21,9 +21,9 @@ class ImageLoaderClientImpl : public ImageLoaderClient { public: - ImageLoaderClientImpl() {} + ImageLoaderClientImpl() = default; - ~ImageLoaderClientImpl() override {} + ~ImageLoaderClientImpl() override = default; void RegisterComponent(const std::string& name, const std::string& version, @@ -122,9 +122,9 @@ } // namespace -ImageLoaderClient::ImageLoaderClient() {} +ImageLoaderClient::ImageLoaderClient() = default; -ImageLoaderClient::~ImageLoaderClient() {} +ImageLoaderClient::~ImageLoaderClient() = default; // static ImageLoaderClient* ImageLoaderClient::Create() {
diff --git a/chromeos/dbus/lorgnette_manager_client.cc b/chromeos/dbus/lorgnette_manager_client.cc index 7d65d7e..594e234 100644 --- a/chromeos/dbus/lorgnette_manager_client.cc +++ b/chromeos/dbus/lorgnette_manager_client.cc
@@ -31,7 +31,7 @@ LorgnetteManagerClientImpl() : lorgnette_daemon_proxy_(NULL), weak_ptr_factory_(this) {} - ~LorgnetteManagerClientImpl() override {} + ~LorgnetteManagerClientImpl() override = default; void ListScanners(const ListScannersCallback& callback) override { dbus::MethodCall method_call(lorgnette::kManagerServiceInterface, @@ -234,11 +234,9 @@ DISALLOW_COPY_AND_ASSIGN(LorgnetteManagerClientImpl); }; -LorgnetteManagerClient::LorgnetteManagerClient() { -} +LorgnetteManagerClient::LorgnetteManagerClient() = default; -LorgnetteManagerClient::~LorgnetteManagerClient() { -} +LorgnetteManagerClient::~LorgnetteManagerClient() = default; // static LorgnetteManagerClient* LorgnetteManagerClient::Create() {
diff --git a/chromeos/dbus/media_analytics_client.cc b/chromeos/dbus/media_analytics_client.cc index e760741a..5dbf385c 100644 --- a/chromeos/dbus/media_analytics_client.cc +++ b/chromeos/dbus/media_analytics_client.cc
@@ -23,7 +23,7 @@ public: MediaAnalyticsClientImpl() : dbus_proxy_(nullptr), weak_ptr_factory_(this) {} - ~MediaAnalyticsClientImpl() override {} + ~MediaAnalyticsClientImpl() override = default; void SetMediaPerceptionSignalHandler( const MediaPerceptionSignalHandler& handler) override { @@ -186,12 +186,12 @@ DISALLOW_COPY_AND_ASSIGN(MediaAnalyticsClientImpl); }; -MediaAnalyticsClient::~MediaAnalyticsClient() {} +MediaAnalyticsClient::~MediaAnalyticsClient() = default; MediaAnalyticsClient* MediaAnalyticsClient::Create() { return new MediaAnalyticsClientImpl; } -MediaAnalyticsClient::MediaAnalyticsClient() {} +MediaAnalyticsClient::MediaAnalyticsClient() = default; } // namespace chromeos
diff --git a/chromeos/dbus/mock_shill_manager_client.cc b/chromeos/dbus/mock_shill_manager_client.cc index bee9fa1..07d4eee 100644 --- a/chromeos/dbus/mock_shill_manager_client.cc +++ b/chromeos/dbus/mock_shill_manager_client.cc
@@ -15,6 +15,6 @@ EXPECT_CALL(*this, Init(_)).Times(AnyNumber()); } -MockShillManagerClient::~MockShillManagerClient() {} +MockShillManagerClient::~MockShillManagerClient() = default; } // namespace chromeos
diff --git a/chromeos/dbus/mock_shill_profile_client.cc b/chromeos/dbus/mock_shill_profile_client.cc index c158905..5bb888c 100644 --- a/chromeos/dbus/mock_shill_profile_client.cc +++ b/chromeos/dbus/mock_shill_profile_client.cc
@@ -13,6 +13,6 @@ EXPECT_CALL(*this, Init(_)).Times(AnyNumber()); } -MockShillProfileClient::~MockShillProfileClient() {} +MockShillProfileClient::~MockShillProfileClient() = default; } // namespace chromeos
diff --git a/chromeos/dbus/mock_shill_service_client.cc b/chromeos/dbus/mock_shill_service_client.cc index 5ecbc60..06ea287 100644 --- a/chromeos/dbus/mock_shill_service_client.cc +++ b/chromeos/dbus/mock_shill_service_client.cc
@@ -6,8 +6,8 @@ namespace chromeos { -MockShillServiceClient::MockShillServiceClient() {} +MockShillServiceClient::MockShillServiceClient() = default; -MockShillServiceClient::~MockShillServiceClient() {} +MockShillServiceClient::~MockShillServiceClient() = default; } // namespace chromeos
diff --git a/chromeos/dbus/modem_messaging_client.cc b/chromeos/dbus/modem_messaging_client.cc index 89baf12..6f59706 100644 --- a/chromeos/dbus/modem_messaging_client.cc +++ b/chromeos/dbus/modem_messaging_client.cc
@@ -43,7 +43,7 @@ base::Bind(&ModemMessagingProxy::OnSignalConnected, weak_ptr_factory_.GetWeakPtr())); } - virtual ~ModemMessagingProxy() {} + virtual ~ModemMessagingProxy() = default; // Sets SmsReceived signal handler. void SetSmsReceivedHandler(const SmsReceivedHandler& handler) { @@ -194,10 +194,9 @@ //////////////////////////////////////////////////////////////////////////////// // ModemMessagingClient -ModemMessagingClient::ModemMessagingClient() {} +ModemMessagingClient::ModemMessagingClient() = default; -ModemMessagingClient::~ModemMessagingClient() {} - +ModemMessagingClient::~ModemMessagingClient() = default; // static ModemMessagingClient* ModemMessagingClient::Create() {
diff --git a/chromeos/dbus/permission_broker_client.cc b/chromeos/dbus/permission_broker_client.cc index aeac8cf..4b5072a 100644 --- a/chromeos/dbus/permission_broker_client.cc +++ b/chromeos/dbus/permission_broker_client.cc
@@ -173,9 +173,9 @@ DISALLOW_COPY_AND_ASSIGN(PermissionBrokerClientImpl); }; -PermissionBrokerClient::PermissionBrokerClient() {} +PermissionBrokerClient::PermissionBrokerClient() = default; -PermissionBrokerClient::~PermissionBrokerClient() {} +PermissionBrokerClient::~PermissionBrokerClient() = default; PermissionBrokerClient* PermissionBrokerClient::Create() { return new PermissionBrokerClientImpl();
diff --git a/chromeos/dbus/power_manager_client.cc b/chromeos/dbus/power_manager_client.cc index 90e53cb9..ad64c34 100644 --- a/chromeos/dbus/power_manager_client.cc +++ b/chromeos/dbus/power_manager_client.cc
@@ -1008,11 +1008,9 @@ DISALLOW_COPY_AND_ASSIGN(PowerManagerClientImpl); }; -PowerManagerClient::PowerManagerClient() { -} +PowerManagerClient::PowerManagerClient() = default; -PowerManagerClient::~PowerManagerClient() { -} +PowerManagerClient::~PowerManagerClient() = default; // static PowerManagerClient* PowerManagerClient::Create(
diff --git a/chromeos/dbus/power_manager_client_unittest.cc b/chromeos/dbus/power_manager_client_unittest.cc index b2430c5..588c809 100644 --- a/chromeos/dbus/power_manager_client_unittest.cc +++ b/chromeos/dbus/power_manager_client_unittest.cc
@@ -162,7 +162,7 @@ explicit TestDelegate(PowerManagerClient* client) : weak_ptr_factory_(this) { client->SetRenderProcessManagerDelegate(weak_ptr_factory_.GetWeakPtr()); } - ~TestDelegate() override {} + ~TestDelegate() override = default; int num_suspend_imminent() const { return num_suspend_imminent_; } int num_suspend_done() const { return num_suspend_done_; } @@ -185,8 +185,8 @@ class PowerManagerClientTest : public testing::Test { public: - PowerManagerClientTest() {} - ~PowerManagerClientTest() override {} + PowerManagerClientTest() = default; + ~PowerManagerClientTest() override = default; void SetUp() override { dbus::Bus::Options options;
diff --git a/chromeos/dbus/power_policy_controller.cc b/chromeos/dbus/power_policy_controller.cc index a341459..bc39c41 100644 --- a/chromeos/dbus/power_policy_controller.cc +++ b/chromeos/dbus/power_policy_controller.cc
@@ -313,8 +313,7 @@ : type(type), reason(reason), description(description) { } -PowerPolicyController::WakeLock::~WakeLock() { -} +PowerPolicyController::WakeLock::~WakeLock() = default; int PowerPolicyController::AddWakeLockInternal(WakeLock::Type type, WakeLockReason reason,
diff --git a/chromeos/dbus/power_policy_controller_unittest.cc b/chromeos/dbus/power_policy_controller_unittest.cc index f35a3ec..f9a7c09 100644 --- a/chromeos/dbus/power_policy_controller_unittest.cc +++ b/chromeos/dbus/power_policy_controller_unittest.cc
@@ -17,7 +17,7 @@ PowerPolicyControllerTest() : fake_power_client_(new FakePowerManagerClient) {} - ~PowerPolicyControllerTest() override {} + ~PowerPolicyControllerTest() override = default; void SetUp() override { PowerPolicyController::Initialize(fake_power_client_.get());
diff --git a/chromeos/dbus/proto/media_perception.proto b/chromeos/dbus/proto/media_perception.proto index d0a77db..c3f8474 100644 --- a/chromeos/dbus/proto/media_perception.proto +++ b/chromeos/dbus/proto/media_perception.proto
@@ -36,6 +36,7 @@ RUNNING = 3; // Analysis process running and injesting frames. SUSPENDED = 4; // Media analytics process waiting to be started. RESTARTING = 5; // Media analytics process should be restarted. + STOPPED = 6; // Media analytics process should be stopped. } // Note: RUNNING and SUSPENDED are the only two states which should be sent to @@ -81,6 +82,9 @@ // The list of entities detected for this frame. repeated Entity entity = 5; + + // Latency measurement for a list of packet streams in drishti graph. + repeated PacketLatency packet_latency = 6; } message Entity { @@ -93,6 +97,7 @@ FACE = 1; PERSON = 2; MOTION_REGION = 3; + LABELED_REGION = 4; } optional EntityType type = 2; @@ -105,6 +110,9 @@ // Perpendicular distance (depth) from the camera plane to the entity. optional Distance depth = 5; + + // String label for this entity. + optional string label = 6; } message BoundingBox { @@ -116,6 +124,14 @@ optional bool normalized = 3 [default = false]; } +message PacketLatency { + // An identifier label for the packet. + optional string label = 1; + + // Delay in microseconds with respect to a reference packet. + optional uint64 latency_usec = 2; +} + message Point { // x represents the horizontal distance from the top left corner of the image // to the point.
diff --git a/chromeos/dbus/services/component_updater_service_provider.cc b/chromeos/dbus/services/component_updater_service_provider.cc index da050c7..ac95151 100644 --- a/chromeos/dbus/services/component_updater_service_provider.cc +++ b/chromeos/dbus/services/component_updater_service_provider.cc
@@ -22,7 +22,7 @@ std::unique_ptr<Delegate> delegate) : delegate_(std::move(delegate)), weak_ptr_factory_(this) {} -ComponentUpdaterServiceProvider::~ComponentUpdaterServiceProvider() {} +ComponentUpdaterServiceProvider::~ComponentUpdaterServiceProvider() = default; void ComponentUpdaterServiceProvider::Start( scoped_refptr<dbus::ExportedObject> exported_object) {
diff --git a/chromeos/dbus/services/console_service_provider.cc b/chromeos/dbus/services/console_service_provider.cc index ff606da..84bbd1a 100644 --- a/chromeos/dbus/services/console_service_provider.cc +++ b/chromeos/dbus/services/console_service_provider.cc
@@ -27,8 +27,7 @@ ConsoleServiceProvider::ConsoleServiceProvider(Delegate* delegate) : delegate_(delegate), weak_ptr_factory_(this) {} -ConsoleServiceProvider::~ConsoleServiceProvider() { -} +ConsoleServiceProvider::~ConsoleServiceProvider() = default; void ConsoleServiceProvider::Start( scoped_refptr<dbus::ExportedObject> exported_object) {
diff --git a/chromeos/dbus/services/display_power_service_provider.cc b/chromeos/dbus/services/display_power_service_provider.cc index e208c034..b08d5e3 100644 --- a/chromeos/dbus/services/display_power_service_provider.cc +++ b/chromeos/dbus/services/display_power_service_provider.cc
@@ -26,7 +26,7 @@ std::unique_ptr<Delegate> delegate) : delegate_(std::move(delegate)), weak_ptr_factory_(this) {} -DisplayPowerServiceProvider::~DisplayPowerServiceProvider() {} +DisplayPowerServiceProvider::~DisplayPowerServiceProvider() = default; void DisplayPowerServiceProvider::Start( scoped_refptr<dbus::ExportedObject> exported_object) {
diff --git a/chromeos/dbus/services/liveness_service_provider.cc b/chromeos/dbus/services/liveness_service_provider.cc index 424fcecb..30c23bf 100644 --- a/chromeos/dbus/services/liveness_service_provider.cc +++ b/chromeos/dbus/services/liveness_service_provider.cc
@@ -15,7 +15,7 @@ const std::string& service_interface) : service_interface_(service_interface), weak_ptr_factory_(this) {} -LivenessServiceProvider::~LivenessServiceProvider() {} +LivenessServiceProvider::~LivenessServiceProvider() = default; void LivenessServiceProvider::Start( scoped_refptr<dbus::ExportedObject> exported_object) {
diff --git a/chromeos/dbus/services/service_provider_test_helper.cc b/chromeos/dbus/services/service_provider_test_helper.cc index 163bf57..66ce2fd 100644 --- a/chromeos/dbus/services/service_provider_test_helper.cc +++ b/chromeos/dbus/services/service_provider_test_helper.cc
@@ -26,8 +26,7 @@ message_loop_.reset(new base::MessageLoop()); } -ServiceProviderTestHelper::~ServiceProviderTestHelper() { -} +ServiceProviderTestHelper::~ServiceProviderTestHelper() = default; void ServiceProviderTestHelper::SetUp( const std::string& service_name,
diff --git a/chromeos/dbus/session_manager_client.cc b/chromeos/dbus/session_manager_client.cc index 954cc0ba..c86a2a1 100644 --- a/chromeos/dbus/session_manager_client.cc +++ b/chromeos/dbus/session_manager_client.cc
@@ -1071,11 +1071,9 @@ DISALLOW_COPY_AND_ASSIGN(SessionManagerClientStubImpl); }; -SessionManagerClient::SessionManagerClient() { -} +SessionManagerClient::SessionManagerClient() = default; -SessionManagerClient::~SessionManagerClient() { -} +SessionManagerClient::~SessionManagerClient() = default; SessionManagerClient* SessionManagerClient::Create( DBusClientImplementationType type) {
diff --git a/chromeos/dbus/shill_client_unittest_base.cc b/chromeos/dbus/shill_client_unittest_base.cc index 5c98035..887938e 100644 --- a/chromeos/dbus/shill_client_unittest_base.cc +++ b/chromeos/dbus/shill_client_unittest_base.cc
@@ -75,13 +75,11 @@ *os << "value does not equal " << expected_value_str; } +ShillClientUnittestBase::MockPropertyChangeObserver:: + MockPropertyChangeObserver() = default; ShillClientUnittestBase::MockPropertyChangeObserver:: - MockPropertyChangeObserver() {} - -ShillClientUnittestBase::MockPropertyChangeObserver:: - ~MockPropertyChangeObserver() {} - + ~MockPropertyChangeObserver() = default; ShillClientUnittestBase::ShillClientUnittestBase( const std::string& interface_name, @@ -91,8 +89,7 @@ response_(NULL) { } -ShillClientUnittestBase::~ShillClientUnittestBase() { -} +ShillClientUnittestBase::~ShillClientUnittestBase() = default; void ShillClientUnittestBase::SetUp() { // Create a mock bus.
diff --git a/chromeos/dbus/shill_device_client.cc b/chromeos/dbus/shill_device_client.cc index 585ced8..fe140ba 100644 --- a/chromeos/dbus/shill_device_client.cc +++ b/chromeos/dbus/shill_device_client.cc
@@ -274,9 +274,9 @@ } // namespace -ShillDeviceClient::ShillDeviceClient() {} +ShillDeviceClient::ShillDeviceClient() = default; -ShillDeviceClient::~ShillDeviceClient() {} +ShillDeviceClient::~ShillDeviceClient() = default; // static ShillDeviceClient* ShillDeviceClient::Create() {
diff --git a/chromeos/dbus/shill_ipconfig_client.cc b/chromeos/dbus/shill_ipconfig_client.cc index b3071e1..75727b8 100644 --- a/chromeos/dbus/shill_ipconfig_client.cc +++ b/chromeos/dbus/shill_ipconfig_client.cc
@@ -169,9 +169,9 @@ } // namespace -ShillIPConfigClient::ShillIPConfigClient() {} +ShillIPConfigClient::ShillIPConfigClient() = default; -ShillIPConfigClient::~ShillIPConfigClient() {} +ShillIPConfigClient::~ShillIPConfigClient() = default; // static ShillIPConfigClient* ShillIPConfigClient::Create() {
diff --git a/chromeos/dbus/shill_manager_client.cc b/chromeos/dbus/shill_manager_client.cc index c52eb02b..acd88ea 100644 --- a/chromeos/dbus/shill_manager_client.cc +++ b/chromeos/dbus/shill_manager_client.cc
@@ -243,9 +243,9 @@ } // namespace -ShillManagerClient::ShillManagerClient() {} +ShillManagerClient::ShillManagerClient() = default; -ShillManagerClient::~ShillManagerClient() {} +ShillManagerClient::~ShillManagerClient() = default; // static ShillManagerClient* ShillManagerClient::Create() { @@ -253,10 +253,8 @@ } // ShillManagerClient::VerificationProperties implementation. -ShillManagerClient::VerificationProperties::VerificationProperties() { -} +ShillManagerClient::VerificationProperties::VerificationProperties() = default; -ShillManagerClient::VerificationProperties::~VerificationProperties() { -} +ShillManagerClient::VerificationProperties::~VerificationProperties() = default; } // namespace chromeos
diff --git a/chromeos/dbus/shill_profile_client.cc b/chromeos/dbus/shill_profile_client.cc index ae50e55d..582e80d 100644 --- a/chromeos/dbus/shill_profile_client.cc +++ b/chromeos/dbus/shill_profile_client.cc
@@ -129,9 +129,9 @@ } // namespace -ShillProfileClient::ShillProfileClient() {} +ShillProfileClient::ShillProfileClient() = default; -ShillProfileClient::~ShillProfileClient() {} +ShillProfileClient::~ShillProfileClient() = default; // static ShillProfileClient* ShillProfileClient::Create() {
diff --git a/chromeos/dbus/shill_service_client.cc b/chromeos/dbus/shill_service_client.cc index b9bd110..d41c003 100644 --- a/chromeos/dbus/shill_service_client.cc +++ b/chromeos/dbus/shill_service_client.cc
@@ -273,9 +273,9 @@ } // namespace -ShillServiceClient::ShillServiceClient() {} +ShillServiceClient::ShillServiceClient() = default; -ShillServiceClient::~ShillServiceClient() {} +ShillServiceClient::~ShillServiceClient() = default; // static ShillServiceClient* ShillServiceClient::Create() {
diff --git a/chromeos/dbus/shill_third_party_vpn_driver_client.cc b/chromeos/dbus/shill_third_party_vpn_driver_client.cc index 9449fde..08d4070 100644 --- a/chromeos/dbus/shill_third_party_vpn_driver_client.cc +++ b/chromeos/dbus/shill_third_party_vpn_driver_client.cc
@@ -334,11 +334,9 @@ } // namespace -ShillThirdPartyVpnDriverClient::ShillThirdPartyVpnDriverClient() { -} +ShillThirdPartyVpnDriverClient::ShillThirdPartyVpnDriverClient() = default; -ShillThirdPartyVpnDriverClient::~ShillThirdPartyVpnDriverClient() { -} +ShillThirdPartyVpnDriverClient::~ShillThirdPartyVpnDriverClient() = default; // static ShillThirdPartyVpnDriverClient* ShillThirdPartyVpnDriverClient::Create() {
diff --git a/chromeos/dbus/shill_third_party_vpn_driver_client_unittest.cc b/chromeos/dbus/shill_third_party_vpn_driver_client_unittest.cc index a9daede..2314210 100644 --- a/chromeos/dbus/shill_third_party_vpn_driver_client_unittest.cc +++ b/chromeos/dbus/shill_third_party_vpn_driver_client_unittest.cc
@@ -25,8 +25,8 @@ class MockShillThirdPartyVpnObserver : public ShillThirdPartyVpnObserver { public: - MockShillThirdPartyVpnObserver() {} - ~MockShillThirdPartyVpnObserver() override {} + MockShillThirdPartyVpnObserver() = default; + ~MockShillThirdPartyVpnObserver() override = default; MOCK_METHOD1(OnPacketReceived, void(const std::vector<char>& data)); MOCK_METHOD1(OnPlatformMessage, void(uint32_t message)); };
diff --git a/chromeos/dbus/sms_client.cc b/chromeos/dbus/sms_client.cc index 4a983cc..96fe82d 100644 --- a/chromeos/dbus/sms_client.cc +++ b/chromeos/dbus/sms_client.cc
@@ -102,7 +102,7 @@ public: SMSClientImpl() : bus_(NULL), weak_ptr_factory_(this) {} - ~SMSClientImpl() override {} + ~SMSClientImpl() override = default; // Calls GetAll method. |callback| is called after the method call succeeds. void GetAll(const std::string& service_name, @@ -149,10 +149,9 @@ const char SMSClient::kSMSPropertyText[] = "Text"; const char SMSClient::kSMSPropertyTimestamp[] = "Timestamp"; -SMSClient::SMSClient() {} +SMSClient::SMSClient() = default; -SMSClient::~SMSClient() {} - +SMSClient::~SMSClient() = default; // static SMSClient* SMSClient::Create() {
diff --git a/chromeos/dbus/system_clock_client.cc b/chromeos/dbus/system_clock_client.cc index 244f8c5..4e4a099 100644 --- a/chromeos/dbus/system_clock_client.cc +++ b/chromeos/dbus/system_clock_client.cc
@@ -49,7 +49,7 @@ system_clock_proxy_(nullptr), weak_ptr_factory_(this) {} - ~SystemClockClientImpl() override {} + ~SystemClockClientImpl() override = default; void AddObserver(Observer* observer) override { observers_.AddObserver(observer); @@ -189,6 +189,6 @@ return new SystemClockClientImpl(); } -SystemClockClient::SystemClockClient() {} +SystemClockClient::SystemClockClient() = default; } // namespace chromeos
diff --git a/chromeos/dbus/update_engine_client.cc b/chromeos/dbus/update_engine_client.cc index c948c49b..747dc8d 100644 --- a/chromeos/dbus/update_engine_client.cc +++ b/chromeos/dbus/update_engine_client.cc
@@ -93,7 +93,7 @@ UpdateEngineClientImpl() : update_engine_proxy_(NULL), last_status_(), weak_ptr_factory_(this) {} - ~UpdateEngineClientImpl() override {} + ~UpdateEngineClientImpl() override = default; // UpdateEngineClient implementation: void AddObserver(Observer* observer) override { @@ -601,7 +601,7 @@ UpdateEngineClientFakeImpl() : weak_factory_(this) { } - ~UpdateEngineClientFakeImpl() override {} + ~UpdateEngineClientFakeImpl() override = default; // UpdateEngineClient implementation: void AddObserver(Observer* observer) override { @@ -690,11 +690,9 @@ DISALLOW_COPY_AND_ASSIGN(UpdateEngineClientFakeImpl); }; -UpdateEngineClient::UpdateEngineClient() { -} +UpdateEngineClient::UpdateEngineClient() = default; -UpdateEngineClient::~UpdateEngineClient() { -} +UpdateEngineClient::~UpdateEngineClient() = default; // static UpdateEngineClient::UpdateCheckCallback
diff --git a/chromeos/dbus/upstart_client.cc b/chromeos/dbus/upstart_client.cc index aea27674..7953e7e 100644 --- a/chromeos/dbus/upstart_client.cc +++ b/chromeos/dbus/upstart_client.cc
@@ -4,9 +4,6 @@ #include "chromeos/dbus/upstart_client.h" -#include <string> -#include <vector> - #include "base/bind.h" #include "base/memory/weak_ptr.h" #include "dbus/bus.h" @@ -31,14 +28,14 @@ public: UpstartClientImpl() : weak_ptr_factory_(this) {} - ~UpstartClientImpl() override {} + ~UpstartClientImpl() override = default; // UpstartClient override. void StartAuthPolicyService() override { dbus::MethodCall method_call(kUpstartJobInterface, kUpstartStartMethod); dbus::MessageWriter writer(&method_call); writer.AppendArrayOfStrings(std::vector<std::string>()); - writer.AppendBool(true); // Wait for response. + writer.AppendBool(true /* wait for response */); auth_proxy_->CallMethod( &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, base::BindOnce(&UpstartClientImpl::HandleAuthResponse, @@ -49,21 +46,22 @@ dbus::MethodCall method_call(kUpstartJobInterface, kUpstartRestartMethod); dbus::MessageWriter writer(&method_call); writer.AppendArrayOfStrings(std::vector<std::string>()); - writer.AppendBool(true); // Wait for response. + writer.AppendBool(true /* wait for response */); auth_proxy_->CallMethod( &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, base::BindOnce(&UpstartClientImpl::HandleAuthResponse, weak_ptr_factory_.GetWeakPtr())); } - void StartMediaAnalytics(const UpstartCallback& callback) override { + void StartMediaAnalytics(const std::vector<std::string>& upstart_env, + const UpstartCallback& callback) override { dbus::MethodCall method_call(kUpstartJobInterface, kUpstartStartMethod); dbus::MessageWriter writer(&method_call); - writer.AppendArrayOfStrings(std::vector<std::string>()); - writer.AppendBool(true); // Wait for response. + writer.AppendArrayOfStrings(upstart_env); + writer.AppendBool(true /* wait for response */); ma_proxy_->CallMethod( &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, - base::BindOnce(&UpstartClientImpl::HandleStartMediaAnalyticsResponse, + base::BindOnce(&UpstartClientImpl::HandleUpstartMediaAnalyticsResponse, weak_ptr_factory_.GetWeakPtr(), callback)); } @@ -71,10 +69,10 @@ dbus::MethodCall method_call(kUpstartJobInterface, kUpstartRestartMethod); dbus::MessageWriter writer(&method_call); writer.AppendArrayOfStrings(std::vector<std::string>()); - writer.AppendBool(true); // Wait for response. + writer.AppendBool(true /* wait for response */); ma_proxy_->CallMethod( &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, - base::BindOnce(&UpstartClientImpl::HandleStartMediaAnalyticsResponse, + base::BindOnce(&UpstartClientImpl::HandleUpstartMediaAnalyticsResponse, weak_ptr_factory_.GetWeakPtr(), callback)); } @@ -82,13 +80,24 @@ dbus::MethodCall method_call(kUpstartJobInterface, kUpstartStopMethod); dbus::MessageWriter writer(&method_call); writer.AppendArrayOfStrings(std::vector<std::string>()); - writer.AppendBool(true); // Wait for response. + writer.AppendBool(true /* wait for response */); ma_proxy_->CallMethod( &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, base::BindOnce(&UpstartClientImpl::HandleStopMediaAnalyticsResponse, weak_ptr_factory_.GetWeakPtr())); } + void StopMediaAnalytics(const UpstartCallback& callback) override { + dbus::MethodCall method_call(kUpstartJobInterface, kUpstartStopMethod); + dbus::MessageWriter writer(&method_call); + writer.AppendArrayOfStrings(std::vector<std::string>()); + writer.AppendBool(true /* wait for response */); + ma_proxy_->CallMethod( + &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, + base::BindOnce(&UpstartClientImpl::HandleUpstartMediaAnalyticsResponse, + weak_ptr_factory_.GetWeakPtr(), callback)); + } + protected: void Init(dbus::Bus* bus) override { bus_ = bus; @@ -103,8 +112,8 @@ LOG_IF(ERROR, !response) << "Failed to signal Upstart, response is null"; } - void HandleStartMediaAnalyticsResponse(const UpstartCallback& callback, - dbus::Response* response) { + void HandleUpstartMediaAnalyticsResponse(const UpstartCallback& callback, + dbus::Response* response) { if (!response) { LOG(ERROR) << "Failed to signal Upstart, response is null."; callback.Run(false); @@ -130,9 +139,9 @@ } // namespace -UpstartClient::UpstartClient() {} +UpstartClient::UpstartClient() = default; -UpstartClient::~UpstartClient() {} +UpstartClient::~UpstartClient() = default; // static UpstartClient* UpstartClient::Create() {
diff --git a/chromeos/dbus/upstart_client.h b/chromeos/dbus/upstart_client.h index 39bd067..2db9d4d9 100644 --- a/chromeos/dbus/upstart_client.h +++ b/chromeos/dbus/upstart_client.h
@@ -5,6 +5,9 @@ #ifndef CHROMEOS_DBUS_UPSTART_CLIENT_H_ #define CHROMEOS_DBUS_UPSTART_CLIENT_H_ +#include <string> +#include <vector> + #include "base/callback.h" #include "base/macros.h" #include "chromeos/chromeos_export.h" @@ -31,7 +34,10 @@ virtual void RestartAuthPolicyService() = 0; // Starts the media analytics process. - virtual void StartMediaAnalytics(const UpstartCallback& callback) = 0; + // |upstart_env|: List of upstart environment variables to be passed to the + // upstart service. + virtual void StartMediaAnalytics(const std::vector<std::string>& upstart_env, + const UpstartCallback& callback) = 0; // Restarts the media analytics process. virtual void RestartMediaAnalytics(const UpstartCallback& callback) = 0; @@ -39,6 +45,9 @@ // Stops the media analytics process. virtual void StopMediaAnalytics() = 0; + // Provides an interface for stopping the media analytics process. + virtual void StopMediaAnalytics(const UpstartCallback& callback) = 0; + protected: // Create() should be used instead. UpstartClient();
diff --git a/chromeos/disks/disk_mount_manager.cc b/chromeos/disks/disk_mount_manager.cc index 052a940..5b9853c 100644 --- a/chromeos/disks/disk_mount_manager.cc +++ b/chromeos/disks/disk_mount_manager.cc
@@ -57,8 +57,7 @@ weak_ptr_factory_.GetWeakPtr())); } - ~DiskMountManagerImpl() override { - } + ~DiskMountManagerImpl() override = default; // DiskMountManager override. void AddObserver(Observer* observer) override { @@ -898,7 +897,7 @@ DiskMountManager::Disk::Disk(const Disk& other) = default; -DiskMountManager::Disk::~Disk() {} +DiskMountManager::Disk::~Disk() = default; void DiskMountManager::Disk::SetMountPath(const std::string& mount_path) { mount_path_ = mount_path;
diff --git a/chromeos/disks/disk_mount_manager_unittest.cc b/chromeos/disks/disk_mount_manager_unittest.cc index 7c817d24..8c94e15 100644 --- a/chromeos/disks/disk_mount_manager_unittest.cc +++ b/chromeos/disks/disk_mount_manager_unittest.cc
@@ -183,7 +183,7 @@ struct ObserverEvent { public: virtual ObserverEventType type() const = 0; - virtual ~ObserverEvent() {} + virtual ~ObserverEvent() = default; }; // Represents an invocation of |DiskMountManager::Observer::OnDeviceEvent()|. @@ -191,7 +191,7 @@ DiskMountManager::DeviceEvent event; std::string device_path; - DeviceEvent() {} + DeviceEvent() = default; DeviceEvent(DiskMountManager::DeviceEvent event, const std::string& device_path) @@ -241,7 +241,7 @@ chromeos::FormatError error_code; std::string device_path; - FormatEvent() {} + FormatEvent() = default; FormatEvent(DiskMountManager::FormatEvent event, chromeos::FormatError error_code, const std::string& device_path) @@ -326,7 +326,7 @@ public: explicit MockDiskMountManagerObserver(const DiskMountManager* manager) : manager_(manager) {} - ~MockDiskMountManagerObserver() override {} + ~MockDiskMountManagerObserver() override = default; // Mock notify methods. void OnDeviceEvent(DiskMountManager::DeviceEvent event, @@ -472,7 +472,7 @@ DiskMountManagerTest() : scoped_task_environment_( base::test::ScopedTaskEnvironment::MainThreadType::UI) {} - ~DiskMountManagerTest() override {} + ~DiskMountManagerTest() override = default; // Sets up test dbus tread manager and disks mount manager. // Initializes disk mount manager disks and mount points.
diff --git a/chromeos/disks/mock_disk_mount_manager.cc b/chromeos/disks/mock_disk_mount_manager.cc index b84489a..d2d4c4866 100644 --- a/chromeos/disks/mock_disk_mount_manager.cc +++ b/chromeos/disks/mock_disk_mount_manager.cc
@@ -66,8 +66,7 @@ this, &MockDiskMountManager::EnsureMountInfoRefreshedInternal)); } -MockDiskMountManager::~MockDiskMountManager() { -} +MockDiskMountManager::~MockDiskMountManager() = default; void MockDiskMountManager::NotifyDeviceInsertEvents() { std::unique_ptr<DiskMountManager::Disk> disk1_ptr =
diff --git a/chromeos/disks/suspend_unmount_manager_unittest.cc b/chromeos/disks/suspend_unmount_manager_unittest.cc index 2c3a9bf7..773d801 100644 --- a/chromeos/disks/suspend_unmount_manager_unittest.cc +++ b/chromeos/disks/suspend_unmount_manager_unittest.cc
@@ -50,7 +50,7 @@ public: SuspendUnmountManagerTest() : suspend_unmount_manager_(&disk_mount_manager_, &fake_power_client_) {} - ~SuspendUnmountManagerTest() override {} + ~SuspendUnmountManagerTest() override = default; protected: FakeDiskMountManager disk_mount_manager_;
diff --git a/chromeos/geolocation/simple_geolocation_request_test_monitor.cc b/chromeos/geolocation/simple_geolocation_request_test_monitor.cc index d303b8c..e30f624 100644 --- a/chromeos/geolocation/simple_geolocation_request_test_monitor.cc +++ b/chromeos/geolocation/simple_geolocation_request_test_monitor.cc
@@ -6,9 +6,11 @@ namespace chromeos { -SimpleGeolocationRequestTestMonitor::SimpleGeolocationRequestTestMonitor() {} +SimpleGeolocationRequestTestMonitor::SimpleGeolocationRequestTestMonitor() = + default; -SimpleGeolocationRequestTestMonitor::~SimpleGeolocationRequestTestMonitor() {} +SimpleGeolocationRequestTestMonitor::~SimpleGeolocationRequestTestMonitor() = + default; void SimpleGeolocationRequestTestMonitor::OnRequestCreated( SimpleGeolocationRequest* request) {}
diff --git a/chromeos/geolocation/simple_geolocation_unittest.cc b/chromeos/geolocation/simple_geolocation_unittest.cc index 3a009a9..26b85db3f4 100644 --- a/chromeos/geolocation/simple_geolocation_unittest.cc +++ b/chromeos/geolocation/simple_geolocation_unittest.cc
@@ -204,7 +204,7 @@ class WirelessTestMonitor : public SimpleGeolocationRequestTestMonitor { public: - WirelessTestMonitor() {} + WirelessTestMonitor() = default; void OnRequestCreated(SimpleGeolocationRequest* request) override {} void OnStart(SimpleGeolocationRequest* request) override { @@ -343,7 +343,7 @@ public: SimpleGeolocationWirelessTest() : manager_test_(nullptr) {} - ~SimpleGeolocationWirelessTest() override {} + ~SimpleGeolocationWirelessTest() override = default; void SetUp() override { // This initializes DBusThreadManager and markes it "for tests only".
diff --git a/chromeos/login/auth/auth_attempt_state.cc b/chromeos/login/auth/auth_attempt_state.cc index e9c5279..cc46698d 100644 --- a/chromeos/login/auth/auth_attempt_state.cc +++ b/chromeos/login/auth/auth_attempt_state.cc
@@ -25,8 +25,7 @@ username_hash_valid_(true) { } -AuthAttemptState::~AuthAttemptState() { -} +AuthAttemptState::~AuthAttemptState() = default; void AuthAttemptState::RecordOnlineLoginStatus(const AuthFailure& outcome) { online_complete_ = true;
diff --git a/chromeos/login/auth/auth_attempt_state_resolver.cc b/chromeos/login/auth/auth_attempt_state_resolver.cc index b8def0d1..18762800 100644 --- a/chromeos/login/auth/auth_attempt_state_resolver.cc +++ b/chromeos/login/auth/auth_attempt_state_resolver.cc
@@ -6,10 +6,8 @@ namespace chromeos { -AuthAttemptStateResolver::AuthAttemptStateResolver() { -} +AuthAttemptStateResolver::AuthAttemptStateResolver() = default; -AuthAttemptStateResolver::~AuthAttemptStateResolver() { -} +AuthAttemptStateResolver::~AuthAttemptStateResolver() = default; } // namespace chromeos
diff --git a/chromeos/login/auth/authenticator.cc b/chromeos/login/auth/authenticator.cc index bf8d626..ba8f37f 100644 --- a/chromeos/login/auth/authenticator.cc +++ b/chromeos/login/auth/authenticator.cc
@@ -12,8 +12,7 @@ : consumer_(consumer), authentication_context_(NULL) { } -Authenticator::~Authenticator() { -} +Authenticator::~Authenticator() = default; void Authenticator::SetConsumer(AuthStatusConsumer* consumer) { consumer_ = consumer;
diff --git a/chromeos/login/auth/authpolicy_login_helper.cc b/chromeos/login/auth/authpolicy_login_helper.cc index a1534c44..e51fd2ed 100644 --- a/chromeos/login/auth/authpolicy_login_helper.cc +++ b/chromeos/login/auth/authpolicy_login_helper.cc
@@ -6,13 +6,20 @@ #include "base/files/file_util.h" #include "base/task_scheduler/post_task.h" +#include "chromeos/cryptohome/cryptohome_util.h" #include "chromeos/dbus/auth_policy_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/upstart_client.h" namespace chromeos { + +namespace cu = cryptohome_util; + namespace { +constexpr char kAttrMode[] = "enterprise.mode"; +constexpr char kDeviceModeEnterpriseAD[] = "enterprise_ad"; + base::ScopedFD GetDataReadPipe(const std::string& data) { int pipe_fds[2]; if (!base::CreateLocalNonBlockingPipe(pipe_fds)) { @@ -59,10 +66,26 @@ ->RestartAuthPolicyService(); } +bool AuthPolicyLoginHelper::IsAdLocked() { + std::string mode; + return chromeos::cryptohome_util::InstallAttributesGet(kAttrMode, &mode) && + mode == kDeviceModeEnterpriseAD; +} + +// static +bool AuthPolicyLoginHelper::LockDeviceActiveDirectoryForTesting( + const std::string& realm) { + return cu::InstallAttributesSet("enterprise.owned", "true") && + cu::InstallAttributesSet("enterprise.mode", "enterprise_ad") && + cu::InstallAttributesSet("enterprise.realm", realm) && + cu::InstallAttributesFinalize(); +} + void AuthPolicyLoginHelper::JoinAdDomain(const std::string& machine_name, const std::string& username, const std::string& password, JoinCallback callback) { + DCHECK(!IsAdLocked()); DCHECK(!weak_factory_.HasWeakPtrs()) << "Another operation is in progress"; authpolicy::JoinDomainRequest request; request.set_machine_name(machine_name); @@ -94,6 +117,28 @@ void AuthPolicyLoginHelper::OnJoinCallback(JoinCallback callback, authpolicy::ErrorType error) { + DCHECK(!IsAdLocked()); + if (error != authpolicy::ERROR_NONE) { + std::move(callback).Run(error); + return; + } + chromeos::DBusThreadManager::Get() + ->GetAuthPolicyClient() + ->RefreshDevicePolicy( + base::BindOnce(&AuthPolicyLoginHelper::OnFirstPolicyRefreshCallback, + weak_factory_.GetWeakPtr(), base::Passed(&callback))); +} + +void AuthPolicyLoginHelper::OnFirstPolicyRefreshCallback( + JoinCallback callback, + authpolicy::ErrorType error) { + DCHECK(!IsAdLocked()); + // First policy refresh happens before device is locked. So policy store + // should not succeed. The error means that authpolicyd cached device policy + // and stores it in the next call to RefreshDevicePolicy in STEP_STORE_POLICY. + DCHECK(error != authpolicy::ERROR_NONE); + if (error == authpolicy::ERROR_DEVICE_POLICY_CACHED_BUT_NOT_SENT) + error = authpolicy::ERROR_NONE; std::move(callback).Run(error); } @@ -104,6 +149,6 @@ std::move(callback).Run(error, account_info); } -AuthPolicyLoginHelper::~AuthPolicyLoginHelper() {} +AuthPolicyLoginHelper::~AuthPolicyLoginHelper() = default; } // namespace chromeos
diff --git a/chromeos/login/auth/authpolicy_login_helper.h b/chromeos/login/auth/authpolicy_login_helper.h index e3a4dcb..9b59d722 100644 --- a/chromeos/login/auth/authpolicy_login_helper.h +++ b/chromeos/login/auth/authpolicy_login_helper.h
@@ -37,11 +37,19 @@ // Restarts AuthPolicy service. static void Restart(); + // Checks if device is locked for Active Directory management. + static bool IsAdLocked(); + + // Sets install attributes for Active Directory managed device. Persists it on + // disk. + static bool LockDeviceActiveDirectoryForTesting(const std::string& realm); + // Packs arguments and calls AuthPolicyClient::JoinAdDomain. Joins machine to - // Active directory domain. |machine_name| is a name for a local machine. - // |username|, |password| are credentials of the Active directory account - // which has right to join the machine to the domain. |callback| is called - // after getting (or failing to get) D-BUS response. + // Active directory domain. Then it calls RefreshDevicePolicy to cache the + // policy on the authpolicyd side. |machine_name| is a name for a local + // machine. |username|, |password| are credentials of the Active directory + // account which has right to join the machine to the domain. |callback| is + // called after getting (or failing to get) D-BUS response. void JoinAdDomain(const std::string& machine_name, const std::string& username, const std::string& password, @@ -65,6 +73,11 @@ // Called from AuthPolicyClient::JoinAdDomain. void OnJoinCallback(JoinCallback callback, authpolicy::ErrorType error); + // Called from AuthPolicyClient::RefreshDevicePolicy. This is used only once + // during device enrollment with the first device policy refresh. + void OnFirstPolicyRefreshCallback(JoinCallback callback, + authpolicy::ErrorType error); + // Called from AuthPolicyClient::AuthenticateUser. void OnAuthCallback( AuthCallback callback,
diff --git a/chromeos/login/auth/authpolicy_login_helper_unittest.cc b/chromeos/login/auth/authpolicy_login_helper_unittest.cc new file mode 100644 index 0000000..0a585ce --- /dev/null +++ b/chromeos/login/auth/authpolicy_login_helper_unittest.cc
@@ -0,0 +1,69 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chromeos/login/auth/authpolicy_login_helper.h" + +#include "base/bind.h" +#include "chromeos/dbus/dbus_thread_manager.h" +#include "chromeos/dbus/fake_auth_policy_client.h" +#include "chromeos/dbus/fake_cryptohome_client.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace chromeos { +namespace { + +class MockAuthPolicyClient : public FakeAuthPolicyClient { + public: + MockAuthPolicyClient() = default; + ~MockAuthPolicyClient() override = default; + + void JoinAdDomain(const authpolicy::JoinDomainRequest& request, + int password_fd, + JoinCallback callback) override { + EXPECT_FALSE(join_ad_domain_called_); + EXPECT_FALSE(refresh_device_policy_called_); + join_ad_domain_called_ = true; + std::move(callback).Run(authpolicy::ERROR_NONE); + } + + void RefreshDevicePolicy(RefreshPolicyCallback callback) override { + EXPECT_TRUE(join_ad_domain_called_); + EXPECT_FALSE(refresh_device_policy_called_); + refresh_device_policy_called_ = true; + std::move(callback).Run( + authpolicy::ERROR_DEVICE_POLICY_CACHED_BUT_NOT_SENT); + } + + void CheckExpectations() { + EXPECT_TRUE(join_ad_domain_called_); + EXPECT_TRUE(refresh_device_policy_called_); + } + + private: + bool join_ad_domain_called_ = false; + bool refresh_device_policy_called_ = false; + + DISALLOW_COPY_AND_ASSIGN(MockAuthPolicyClient); +}; + +} // namespace + +// Check that helper calls RefreshDevicePolicy after JoinAdDomain. +TEST(AuthPolicyLoginHelper, JoinFollowedByRefreshDevicePolicy) { + std::unique_ptr<MockAuthPolicyClient> mock_client = + std::make_unique<MockAuthPolicyClient>(); + MockAuthPolicyClient* mock_client_ptr = mock_client.get(); + DBusThreadManager::GetSetterForTesting()->SetAuthPolicyClient( + std::move(mock_client)); + DBusThreadManager::GetSetterForTesting()->SetCryptohomeClient( + std::make_unique<FakeCryptohomeClient>()); + AuthPolicyLoginHelper helper; + helper.JoinAdDomain(std::string(), std::string(), std::string(), + base::BindOnce([](authpolicy::ErrorType error) { + EXPECT_EQ(authpolicy::ERROR_NONE, error); + })); + mock_client_ptr->CheckExpectations(); +} + +} // namespace chromeos
diff --git a/chromeos/login/auth/cryptohome_authenticator.cc b/chromeos/login/auth/cryptohome_authenticator.cc index b919171c..d2948fd 100644 --- a/chromeos/login/auth/cryptohome_authenticator.cc +++ b/chromeos/login/auth/cryptohome_authenticator.cc
@@ -907,8 +907,7 @@ } } -CryptohomeAuthenticator::~CryptohomeAuthenticator() { -} +CryptohomeAuthenticator::~CryptohomeAuthenticator() = default; CryptohomeAuthenticator::AuthState CryptohomeAuthenticator::ResolveState() { DCHECK(task_runner_->RunsTasksInCurrentSequence());
diff --git a/chromeos/login/auth/extended_authenticator.cc b/chromeos/login/auth/extended_authenticator.cc index 31ce974e..de4d2be 100644 --- a/chromeos/login/auth/extended_authenticator.cc +++ b/chromeos/login/auth/extended_authenticator.cc
@@ -20,10 +20,8 @@ return base::MakeRefCounted<ExtendedAuthenticatorImpl>(consumer); } -ExtendedAuthenticator::ExtendedAuthenticator() { -} +ExtendedAuthenticator::ExtendedAuthenticator() = default; -ExtendedAuthenticator::~ExtendedAuthenticator() { -} +ExtendedAuthenticator::~ExtendedAuthenticator() = default; } // namespace chromeos
diff --git a/chromeos/login/auth/extended_authenticator_impl.cc b/chromeos/login/auth/extended_authenticator_impl.cc index 650050f..a08d9b2 100644 --- a/chromeos/login/auth/extended_authenticator_impl.cc +++ b/chromeos/login/auth/extended_authenticator_impl.cc
@@ -169,8 +169,7 @@ callback.Run(transformed_context); } -ExtendedAuthenticatorImpl::~ExtendedAuthenticatorImpl() { -} +ExtendedAuthenticatorImpl::~ExtendedAuthenticatorImpl() = default; void ExtendedAuthenticatorImpl::OnSaltObtained(const std::string& system_salt) { salt_obtained_ = true;
diff --git a/chromeos/login/auth/fake_extended_authenticator.cc b/chromeos/login/auth/fake_extended_authenticator.cc index b44255b..f8f0b8a5 100644 --- a/chromeos/login/auth/fake_extended_authenticator.cc +++ b/chromeos/login/auth/fake_extended_authenticator.cc
@@ -26,8 +26,7 @@ expected_user_context_(expected_user_context) { } -FakeExtendedAuthenticator::~FakeExtendedAuthenticator() { -} +FakeExtendedAuthenticator::~FakeExtendedAuthenticator() = default; void FakeExtendedAuthenticator::SetConsumer(AuthStatusConsumer* consumer) { old_consumer_ = consumer;
diff --git a/chromeos/login/auth/key.cc b/chromeos/login/auth/key.cc index 10180645..b1b9061 100644 --- a/chromeos/login/auth/key.cc +++ b/chromeos/login/auth/key.cc
@@ -26,12 +26,7 @@ Key::Key() : key_type_(KEY_TYPE_PASSWORD_PLAIN) { } -Key::Key(const Key& other) - : key_type_(other.key_type_), - salt_(other.salt_), - secret_(other.secret_), - label_(other.label_) { -} +Key::Key(const Key& other) = default; Key::Key(const std::string& plain_text_password) : key_type_(KEY_TYPE_PASSWORD_PLAIN), secret_(plain_text_password) { @@ -41,8 +36,7 @@ : key_type_(key_type), salt_(salt), secret_(secret) { } -Key::~Key() { -} +Key::~Key() = default; bool Key::operator==(const Key& other) const { return other.key_type_ == key_type_ && other.salt_ == salt_ &&
diff --git a/chromeos/login/auth/mock_auth_attempt_state_resolver.cc b/chromeos/login/auth/mock_auth_attempt_state_resolver.cc index d14dffc..5fa06da 100644 --- a/chromeos/login/auth/mock_auth_attempt_state_resolver.cc +++ b/chromeos/login/auth/mock_auth_attempt_state_resolver.cc
@@ -6,10 +6,8 @@ namespace chromeos { -MockAuthAttemptStateResolver::MockAuthAttemptStateResolver() { -} +MockAuthAttemptStateResolver::MockAuthAttemptStateResolver() = default; -MockAuthAttemptStateResolver::~MockAuthAttemptStateResolver() { -} +MockAuthAttemptStateResolver::~MockAuthAttemptStateResolver() = default; } // namespace chromeos
diff --git a/chromeos/login/auth/mock_auth_status_consumer.cc b/chromeos/login/auth/mock_auth_status_consumer.cc index 9989c6d8..1409dee 100644 --- a/chromeos/login/auth/mock_auth_status_consumer.cc +++ b/chromeos/login/auth/mock_auth_status_consumer.cc
@@ -10,11 +10,9 @@ namespace chromeos { -MockAuthStatusConsumer::MockAuthStatusConsumer() { -} +MockAuthStatusConsumer::MockAuthStatusConsumer() = default; -MockAuthStatusConsumer::~MockAuthStatusConsumer() { -} +MockAuthStatusConsumer::~MockAuthStatusConsumer() = default; // static void MockAuthStatusConsumer::OnRetailModeSuccessQuit(
diff --git a/chromeos/login/auth/mock_url_fetchers.cc b/chromeos/login/auth/mock_url_fetchers.cc index 9bc04c9..9f1e10a 100644 --- a/chromeos/login/auth/mock_url_fetchers.cc +++ b/chromeos/login/auth/mock_url_fetchers.cc
@@ -29,8 +29,7 @@ : net::TestURLFetcher(0, url, d), weak_factory_(this) { } -ExpectCanceledFetcher::~ExpectCanceledFetcher() { -} +ExpectCanceledFetcher::~ExpectCanceledFetcher() = default; void ExpectCanceledFetcher::Start() { base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( @@ -58,8 +57,7 @@ set_response_code(net::HTTP_FORBIDDEN); } -GotCanceledFetcher::~GotCanceledFetcher() { -} +GotCanceledFetcher::~GotCanceledFetcher() = default; void GotCanceledFetcher::Start() { delegate()->OnURLFetchComplete(this); @@ -76,8 +74,7 @@ set_response_code(net::HTTP_OK); } -SuccessFetcher::~SuccessFetcher() { -} +SuccessFetcher::~SuccessFetcher() = default; void SuccessFetcher::Start() { delegate()->OnURLFetchComplete(this); @@ -94,8 +91,7 @@ set_response_code(net::HTTP_OK); } -FailFetcher::~FailFetcher() { -} +FailFetcher::~FailFetcher() = default; void FailFetcher::Start() { delegate()->OnURLFetchComplete(this); @@ -130,8 +126,7 @@ kCaptchaToken)); } -CaptchaFetcher::~CaptchaFetcher() { -} +CaptchaFetcher::~CaptchaFetcher() = default; // static std::string CaptchaFetcher::GetCaptchaToken() { @@ -163,8 +158,7 @@ set_response_code(net::HTTP_OK); } -HostedFetcher::~HostedFetcher() { -} +HostedFetcher::~HostedFetcher() = default; void HostedFetcher::Start() { VLOG(1) << upload_data();
diff --git a/chromeos/login/auth/stub_authenticator.cc b/chromeos/login/auth/stub_authenticator.cc index 6fbfb00..6145ca8 100644 --- a/chromeos/login/auth/stub_authenticator.cc +++ b/chromeos/login/auth/stub_authenticator.cc
@@ -117,7 +117,6 @@ expected_user_context_ = user_context; } -StubAuthenticator::~StubAuthenticator() { -} +StubAuthenticator::~StubAuthenticator() = default; } // namespace chromeos
diff --git a/chromeos/login/auth/test_attempt_state.cc b/chromeos/login/auth/test_attempt_state.cc index 186534f..4d263d7 100644 --- a/chromeos/login/auth/test_attempt_state.cc +++ b/chromeos/login/auth/test_attempt_state.cc
@@ -16,8 +16,7 @@ user_is_new) { } -TestAttemptState::~TestAttemptState() { -} +TestAttemptState::~TestAttemptState() = default; void TestAttemptState::PresetOnlineLoginStatus(const AuthFailure& outcome) { online_complete_ = true;
diff --git a/chromeos/login/auth/user_context.cc b/chromeos/login/auth/user_context.cc index f5bdd1366..344211e1 100644 --- a/chromeos/login/auth/user_context.cc +++ b/chromeos/login/auth/user_context.cc
@@ -9,22 +9,7 @@ UserContext::UserContext() : account_id_(EmptyAccountId()) {} -UserContext::UserContext(const UserContext& other) - : account_id_(other.account_id_), - key_(other.key_), - auth_code_(other.auth_code_), - refresh_token_(other.refresh_token_), - access_token_(other.access_token_), - user_id_hash_(other.user_id_hash_), - is_using_oauth_(other.is_using_oauth_), - is_using_pin_(other.is_using_pin_), - is_forcing_dircrypto_(other.is_forcing_dircrypto_), - auth_flow_(other.auth_flow_), - user_type_(other.user_type_), - public_session_locale_(other.public_session_locale_), - public_session_input_method_(other.public_session_input_method_), - device_id_(other.device_id_), - gaps_cookie_(other.gaps_cookie_) {} +UserContext::UserContext(const UserContext& other) = default; UserContext::UserContext(const AccountId& account_id) : account_id_(account_id) { @@ -40,8 +25,7 @@ user_manager::CanonicalizeUserID(account_id_.GetUserEmail())); } -UserContext::~UserContext() { -} +UserContext::~UserContext() = default; bool UserContext::operator==(const UserContext& context) const { return context.account_id_ == account_id_ && context.key_ == key_ &&
diff --git a/chromeos/login/login_state.cc b/chromeos/login/login_state.cc index 99c5dfe..f0825a4 100644 --- a/chromeos/login/login_state.cc +++ b/chromeos/login/login_state.cc
@@ -129,8 +129,7 @@ always_logged_in_(AlwaysLoggedInByDefault()) { } -LoginState::~LoginState() { -} +LoginState::~LoginState() = default; void LoginState::NotifyObservers() { for (auto& observer : observer_list_)
diff --git a/chromeos/login/login_state_unittest.cc b/chromeos/login/login_state_unittest.cc index c683496..e5d8f4d 100644 --- a/chromeos/login/login_state_unittest.cc +++ b/chromeos/login/login_state_unittest.cc
@@ -22,7 +22,7 @@ LoginStateTest() : logged_in_user_type_(LoginState::LOGGED_IN_USER_NONE), login_state_changes_count_(0) { } - ~LoginStateTest() override {} + ~LoginStateTest() override = default; // testing::Test void SetUp() override {
diff --git a/chromeos/login_event_recorder.cc b/chromeos/login_event_recorder.cc index 92a7d9f..b6c79bf 100644 --- a/chromeos/login_event_recorder.cc +++ b/chromeos/login_event_recorder.cc
@@ -16,8 +16,7 @@ LoginEventRecorder::LoginEventRecorder() : delegate_(NULL) { } -LoginEventRecorder::~LoginEventRecorder() { -} +LoginEventRecorder::~LoginEventRecorder() = default; // static LoginEventRecorder* LoginEventRecorder::Get() {
diff --git a/chromeos/network/auto_connect_handler_unittest.cc b/chromeos/network/auto_connect_handler_unittest.cc index 2e20215..f957c1fd 100644 --- a/chromeos/network/auto_connect_handler_unittest.cc +++ b/chromeos/network/auto_connect_handler_unittest.cc
@@ -61,7 +61,7 @@ TestNetworkConnectionHandler( const base::Callback<void(const std::string&)>& disconnect_handler) : NetworkConnectionHandler(), disconnect_handler_(disconnect_handler) {} - ~TestNetworkConnectionHandler() override {} + ~TestNetworkConnectionHandler() override = default; // NetworkConnectionHandler: void DisconnectNetwork(
diff --git a/chromeos/network/certificate_pattern.cc b/chromeos/network/certificate_pattern.cc index 28c541a..15b3729c 100644 --- a/chromeos/network/certificate_pattern.cc +++ b/chromeos/network/certificate_pattern.cc
@@ -45,14 +45,12 @@ organizational_unit_(organizational_unit) { } -IssuerSubjectPattern::IssuerSubjectPattern() { -} +IssuerSubjectPattern::IssuerSubjectPattern() = default; IssuerSubjectPattern::IssuerSubjectPattern(const IssuerSubjectPattern& other) = default; -IssuerSubjectPattern::~IssuerSubjectPattern() { -} +IssuerSubjectPattern::~IssuerSubjectPattern() = default; bool IssuerSubjectPattern::Empty() const { return common_name_.empty() && locality_.empty() && organization_.empty() && @@ -82,14 +80,12 @@ //////////////////////////////////////////////////////////////////////////////// // CertificatePattern -CertificatePattern::CertificatePattern() { -} +CertificatePattern::CertificatePattern() = default; CertificatePattern::CertificatePattern(const CertificatePattern& other) = default; -CertificatePattern::~CertificatePattern() { -} +CertificatePattern::~CertificatePattern() = default; bool CertificatePattern::Empty() const { return issuer_ca_pems_.empty() && issuer_.Empty() && subject_.Empty();
diff --git a/chromeos/network/client_cert_resolver_unittest.cc b/chromeos/network/client_cert_resolver_unittest.cc index 94e3d19..2041f97 100644 --- a/chromeos/network/client_cert_resolver_unittest.cc +++ b/chromeos/network/client_cert_resolver_unittest.cc
@@ -53,8 +53,8 @@ class ClientCertResolverTest : public testing::Test, public ClientCertResolver::Observer { public: - ClientCertResolverTest() {} - ~ClientCertResolverTest() override {} + ClientCertResolverTest() = default; + ~ClientCertResolverTest() override = default; void SetUp() override { ASSERT_TRUE(test_nssdb_.is_open());
diff --git a/chromeos/network/device_state.cc b/chromeos/network/device_state.cc index 9ada46827..f1f2806 100644 --- a/chromeos/network/device_state.cc +++ b/chromeos/network/device_state.cc
@@ -27,8 +27,7 @@ eap_authentication_completed_(false) { } -DeviceState::~DeviceState() { -} +DeviceState::~DeviceState() = default; bool DeviceState::PropertyChanged(const std::string& key, const base::Value& value) {
diff --git a/chromeos/network/dhcp_proxy_script_fetcher_chromeos.cc b/chromeos/network/dhcp_proxy_script_fetcher_chromeos.cc index 25600b6f..0998de1 100644 --- a/chromeos/network/dhcp_proxy_script_fetcher_chromeos.cc +++ b/chromeos/network/dhcp_proxy_script_fetcher_chromeos.cc
@@ -41,8 +41,7 @@ network_handler_task_runner_ = NetworkHandler::Get()->task_runner(); } -DhcpProxyScriptFetcherChromeos::~DhcpProxyScriptFetcherChromeos() { -} +DhcpProxyScriptFetcherChromeos::~DhcpProxyScriptFetcherChromeos() = default; int DhcpProxyScriptFetcherChromeos::Fetch( base::string16* utf16_text,
diff --git a/chromeos/network/dhcp_proxy_script_fetcher_factory_chromeos.cc b/chromeos/network/dhcp_proxy_script_fetcher_factory_chromeos.cc index 0fd5e1a..96aeef0a 100644 --- a/chromeos/network/dhcp_proxy_script_fetcher_factory_chromeos.cc +++ b/chromeos/network/dhcp_proxy_script_fetcher_factory_chromeos.cc
@@ -10,11 +10,11 @@ namespace chromeos { -DhcpProxyScriptFetcherFactoryChromeos::DhcpProxyScriptFetcherFactoryChromeos() { -} +DhcpProxyScriptFetcherFactoryChromeos::DhcpProxyScriptFetcherFactoryChromeos() = + default; DhcpProxyScriptFetcherFactoryChromeos:: - ~DhcpProxyScriptFetcherFactoryChromeos() {} + ~DhcpProxyScriptFetcherFactoryChromeos() = default; std::unique_ptr<net::DhcpProxyScriptFetcher> DhcpProxyScriptFetcherFactoryChromeos::Create(
diff --git a/chromeos/network/fake_network_device_handler.cc b/chromeos/network/fake_network_device_handler.cc index 25e5a9d..b2cc3d4 100644 --- a/chromeos/network/fake_network_device_handler.cc +++ b/chromeos/network/fake_network_device_handler.cc
@@ -6,9 +6,9 @@ namespace chromeos { -FakeNetworkDeviceHandler::FakeNetworkDeviceHandler() {} +FakeNetworkDeviceHandler::FakeNetworkDeviceHandler() = default; -FakeNetworkDeviceHandler::~FakeNetworkDeviceHandler() {} +FakeNetworkDeviceHandler::~FakeNetworkDeviceHandler() = default; void FakeNetworkDeviceHandler::GetDeviceProperties( const std::string& device_path,
diff --git a/chromeos/network/geolocation_handler_unittest.cc b/chromeos/network/geolocation_handler_unittest.cc index aefe170..d5c16308 100644 --- a/chromeos/network/geolocation_handler_unittest.cc +++ b/chromeos/network/geolocation_handler_unittest.cc
@@ -25,7 +25,7 @@ : scoped_task_environment_( base::test::ScopedTaskEnvironment::MainThreadType::UI) {} - ~GeolocationHandlerTest() override {} + ~GeolocationHandlerTest() override = default; void SetUp() override { // Initialize DBusThreadManager with a stub implementation.
diff --git a/chromeos/network/host_resolver_impl_chromeos.cc b/chromeos/network/host_resolver_impl_chromeos.cc index d46262d..ac4fbbb 100644 --- a/chromeos/network/host_resolver_impl_chromeos.cc +++ b/chromeos/network/host_resolver_impl_chromeos.cc
@@ -136,8 +136,7 @@ base::ThreadTaskRunnerHandle::Get(), network_state_handler)); } -HostResolverImplChromeOS::~HostResolverImplChromeOS() { -} +HostResolverImplChromeOS::~HostResolverImplChromeOS() = default; int HostResolverImplChromeOS::Resolve( const RequestInfo& info,
diff --git a/chromeos/network/host_resolver_impl_chromeos_unittest.cc b/chromeos/network/host_resolver_impl_chromeos_unittest.cc index beb7231..deb8c88d 100644 --- a/chromeos/network/host_resolver_impl_chromeos_unittest.cc +++ b/chromeos/network/host_resolver_impl_chromeos_unittest.cc
@@ -48,7 +48,7 @@ : scoped_task_environment_( base::test::ScopedTaskEnvironment::MainThreadType::IO) {} - ~HostResolverImplChromeOSTest() override {} + ~HostResolverImplChromeOSTest() override = default; void SetUp() override { DBusThreadManager::Initialize();
diff --git a/chromeos/network/managed_network_configuration_handler.cc b/chromeos/network/managed_network_configuration_handler.cc index b58d1f87..ec71e82 100644 --- a/chromeos/network/managed_network_configuration_handler.cc +++ b/chromeos/network/managed_network_configuration_handler.cc
@@ -12,6 +12,7 @@ namespace chromeos { -ManagedNetworkConfigurationHandler::~ManagedNetworkConfigurationHandler() {} +ManagedNetworkConfigurationHandler::~ManagedNetworkConfigurationHandler() = + default; } // namespace chromeos
diff --git a/chromeos/network/managed_network_configuration_handler_impl.cc b/chromeos/network/managed_network_configuration_handler_impl.cc index 0bc606b..a23d18757 100644 --- a/chromeos/network/managed_network_configuration_handler_impl.cc +++ b/chromeos/network/managed_network_configuration_handler_impl.cc
@@ -97,7 +97,7 @@ base::DictionaryValue global_network_config; }; -ManagedNetworkConfigurationHandlerImpl::Policies::~Policies() {} +ManagedNetworkConfigurationHandlerImpl::Policies::~Policies() = default; void ManagedNetworkConfigurationHandlerImpl::AddObserver( NetworkPolicyObserver* observer) {
diff --git a/chromeos/network/managed_network_configuration_handler_unittest.cc b/chromeos/network/managed_network_configuration_handler_unittest.cc index 61ebde0..6f162f8a6 100644 --- a/chromeos/network/managed_network_configuration_handler_unittest.cc +++ b/chromeos/network/managed_network_configuration_handler_unittest.cc
@@ -191,7 +191,7 @@ TestNetworkProfileHandler() { Init(); } - ~TestNetworkProfileHandler() override {} + ~TestNetworkProfileHandler() override = default; void AddProfileForTest(const NetworkProfile& profile) { AddProfile(profile); @@ -335,7 +335,7 @@ mock_profile_client_(NULL), mock_service_client_(NULL) {} - ~ManagedNetworkConfigurationHandlerMockTest() override {} + ~ManagedNetworkConfigurationHandlerMockTest() override = default; void SetUp() override { std::unique_ptr<DBusThreadManagerSetter> dbus_setter =
diff --git a/chromeos/network/managed_state.cc b/chromeos/network/managed_state.cc index 0a7b4ec..51c93ee 100644 --- a/chromeos/network/managed_state.cc +++ b/chromeos/network/managed_state.cc
@@ -40,8 +40,7 @@ update_requested_(false) { } -ManagedState::~ManagedState() { -} +ManagedState::~ManagedState() = default; std::unique_ptr<ManagedState> ManagedState::Create(ManagedType type, const std::string& path) {
diff --git a/chromeos/network/mock_managed_network_configuration_handler.cc b/chromeos/network/mock_managed_network_configuration_handler.cc index 1769264a..7c22743 100644 --- a/chromeos/network/mock_managed_network_configuration_handler.cc +++ b/chromeos/network/mock_managed_network_configuration_handler.cc
@@ -7,11 +7,9 @@ namespace chromeos { MockManagedNetworkConfigurationHandler:: - MockManagedNetworkConfigurationHandler() { -} + MockManagedNetworkConfigurationHandler() = default; MockManagedNetworkConfigurationHandler:: - ~MockManagedNetworkConfigurationHandler() { -} + ~MockManagedNetworkConfigurationHandler() = default; } // namespace chromeos
diff --git a/chromeos/network/mock_network_device_handler.cc b/chromeos/network/mock_network_device_handler.cc index a013b2c..ffce5c1 100644 --- a/chromeos/network/mock_network_device_handler.cc +++ b/chromeos/network/mock_network_device_handler.cc
@@ -6,8 +6,8 @@ namespace chromeos { -MockNetworkDeviceHandler::MockNetworkDeviceHandler() {} +MockNetworkDeviceHandler::MockNetworkDeviceHandler() = default; -MockNetworkDeviceHandler::~MockNetworkDeviceHandler() {} +MockNetworkDeviceHandler::~MockNetworkDeviceHandler() = default; } // namespace chromeos
diff --git a/chromeos/network/network_activation_handler.cc b/chromeos/network/network_activation_handler.cc index 90ed374..a6845e3 100644 --- a/chromeos/network/network_activation_handler.cc +++ b/chromeos/network/network_activation_handler.cc
@@ -17,8 +17,8 @@ // static const char NetworkActivationHandler::kErrorShillError[] = "shill-error"; -NetworkActivationHandler::NetworkActivationHandler() {} -NetworkActivationHandler::~NetworkActivationHandler() {} +NetworkActivationHandler::NetworkActivationHandler() = default; +NetworkActivationHandler::~NetworkActivationHandler() = default; void NetworkActivationHandler::Activate( const std::string& service_path,
diff --git a/chromeos/network/network_cert_migrator.cc b/chromeos/network/network_cert_migrator.cc index 7f5a790..256c9c97 100644 --- a/chromeos/network/network_cert_migrator.cc +++ b/chromeos/network/network_cert_migrator.cc
@@ -161,8 +161,7 @@ private: friend class base::RefCounted<MigrationTask>; - virtual ~MigrationTask() { - } + virtual ~MigrationTask() = default; bool CorrespondingCertificateDatabaseLoaded(const NetworkState* network) { if (network->IsPrivate())
diff --git a/chromeos/network/network_cert_migrator_unittest.cc b/chromeos/network/network_cert_migrator_unittest.cc index 0bb79d5..984c7a95 100644 --- a/chromeos/network/network_cert_migrator_unittest.cc +++ b/chromeos/network/network_cert_migrator_unittest.cc
@@ -45,7 +45,7 @@ base::test::ScopedTaskEnvironment::MainThreadType::DEFAULT, base::test::ScopedTaskEnvironment::ExecutionMode::QUEUED), service_test_(nullptr) {} - ~NetworkCertMigratorTest() override {} + ~NetworkCertMigratorTest() override = default; void SetUp() override { ASSERT_TRUE(test_system_nssdb_.is_open());
diff --git a/chromeos/network/network_certificate_handler.cc b/chromeos/network/network_certificate_handler.cc index cc8de67..eb75d604 100644 --- a/chromeos/network/network_certificate_handler.cc +++ b/chromeos/network/network_certificate_handler.cc
@@ -49,9 +49,9 @@ } // namespace -NetworkCertificateHandler::Certificate::Certificate() {} +NetworkCertificateHandler::Certificate::Certificate() = default; -NetworkCertificateHandler::Certificate::~Certificate() {} +NetworkCertificateHandler::Certificate::~Certificate() = default; NetworkCertificateHandler::Certificate::Certificate(const Certificate& other) = default;
diff --git a/chromeos/network/network_change_notifier_chromeos.cc b/chromeos/network/network_change_notifier_chromeos.cc index ede81943..2fffa00fd 100644 --- a/chromeos/network/network_change_notifier_chromeos.cc +++ b/chromeos/network/network_change_notifier_chromeos.cc
@@ -33,11 +33,9 @@ virtual void OnNetworkChange(); }; -NetworkChangeNotifierChromeos::DnsConfigService::DnsConfigService() { -} +NetworkChangeNotifierChromeos::DnsConfigService::DnsConfigService() = default; -NetworkChangeNotifierChromeos::DnsConfigService::~DnsConfigService() { -} +NetworkChangeNotifierChromeos::DnsConfigService::~DnsConfigService() = default; bool NetworkChangeNotifierChromeos::DnsConfigService::StartWatching() { // DNS config changes are handled and notified by the network state handlers. @@ -62,8 +60,7 @@ weak_ptr_factory_.GetWeakPtr()); } -NetworkChangeNotifierChromeos::~NetworkChangeNotifierChromeos() { -} +NetworkChangeNotifierChromeos::~NetworkChangeNotifierChromeos() = default; void NetworkChangeNotifierChromeos::Initialize() { DBusThreadManager::Get()->GetPowerManagerClient()->AddObserver(this);
diff --git a/chromeos/network/network_change_notifier_chromeos_unittest.cc b/chromeos/network/network_change_notifier_chromeos_unittest.cc index 271906d..8562be3 100644 --- a/chromeos/network/network_change_notifier_chromeos_unittest.cc +++ b/chromeos/network/network_change_notifier_chromeos_unittest.cc
@@ -121,7 +121,7 @@ protected: NetworkChangeNotifierChromeosUpdateTest() : default_network_("") { } - ~NetworkChangeNotifierChromeosUpdateTest() override {} + ~NetworkChangeNotifierChromeosUpdateTest() override = default; void SetNotifierState(const NotifierState& notifier_state) { notifier_.connection_type_ = notifier_state.type;
diff --git a/chromeos/network/network_configuration_handler.cc b/chromeos/network/network_configuration_handler.cc index df2c71b..481446de 100644 --- a/chromeos/network/network_configuration_handler.cc +++ b/chromeos/network/network_configuration_handler.cc
@@ -468,8 +468,7 @@ NetworkConfigurationHandler::NetworkConfigurationHandler() : network_state_handler_(nullptr), weak_ptr_factory_(this) {} -NetworkConfigurationHandler::~NetworkConfigurationHandler() { -} +NetworkConfigurationHandler::~NetworkConfigurationHandler() = default; void NetworkConfigurationHandler::Init( NetworkStateHandler* network_state_handler,
diff --git a/chromeos/network/network_connect.cc b/chromeos/network/network_connect.cc index 9c9b38d1..0ca26f5a 100644 --- a/chromeos/network/network_connect.cc +++ b/chromeos/network/network_connect.cc
@@ -113,7 +113,7 @@ NetworkConnectImpl::NetworkConnectImpl(Delegate* delegate) : delegate_(delegate), weak_factory_(this) {} -NetworkConnectImpl::~NetworkConnectImpl() {} +NetworkConnectImpl::~NetworkConnectImpl() = default; void NetworkConnectImpl::HandleUnconfiguredNetwork( const std::string& network_id) { @@ -583,8 +583,8 @@ return g_network_connect; } -NetworkConnect::NetworkConnect() {} +NetworkConnect::NetworkConnect() = default; -NetworkConnect::~NetworkConnect() {} +NetworkConnect::~NetworkConnect() = default; } // namespace chromeos
diff --git a/chromeos/network/network_connect_unittest.cc b/chromeos/network/network_connect_unittest.cc index d6fb1f9..be242d7 100644 --- a/chromeos/network/network_connect_unittest.cc +++ b/chromeos/network/network_connect_unittest.cc
@@ -44,8 +44,8 @@ class MockDelegate : public NetworkConnect::Delegate { public: - MockDelegate() {} - ~MockDelegate() override {} + MockDelegate() = default; + ~MockDelegate() override = default; MOCK_METHOD1(ShowNetworkConfigure, void(const std::string& network_id)); MOCK_METHOD1(ShowNetworkSettings, void(const std::string& network_id)); @@ -59,8 +59,8 @@ class FakeTetherDelegate : public NetworkConnectionHandler::TetherDelegate { public: - FakeTetherDelegate() {} - ~FakeTetherDelegate() override {} + FakeTetherDelegate() = default; + ~FakeTetherDelegate() override = default; std::string last_connected_tether_network_guid() { return last_connected_tether_network_guid_; @@ -87,8 +87,8 @@ class NetworkConnectTest : public testing::Test { public: - NetworkConnectTest() {} - ~NetworkConnectTest() override {} + NetworkConnectTest() = default; + ~NetworkConnectTest() override = default; void SetUp() override { testing::Test::SetUp();
diff --git a/chromeos/network/network_connection_handler.cc b/chromeos/network/network_connection_handler.cc index 3e792333..59b0d47 100644 --- a/chromeos/network/network_connection_handler.cc +++ b/chromeos/network/network_connection_handler.cc
@@ -64,7 +64,7 @@ NetworkConnectionHandler::NetworkConnectionHandler() : tether_delegate_(nullptr), weak_ptr_factory_(this) {} -NetworkConnectionHandler::~NetworkConnectionHandler() {} +NetworkConnectionHandler::~NetworkConnectionHandler() = default; void NetworkConnectionHandler::AddObserver( NetworkConnectionObserver* observer) {
diff --git a/chromeos/network/network_connection_handler_impl.cc b/chromeos/network/network_connection_handler_impl.cc index 66d65a1..4107064c 100644 --- a/chromeos/network/network_connection_handler_impl.cc +++ b/chromeos/network/network_connection_handler_impl.cc
@@ -105,15 +105,10 @@ success_callback(success), error_callback(error) {} -NetworkConnectionHandlerImpl::ConnectRequest::~ConnectRequest() {} +NetworkConnectionHandlerImpl::ConnectRequest::~ConnectRequest() = default; NetworkConnectionHandlerImpl::ConnectRequest::ConnectRequest( - const ConnectRequest& other) - : service_path(other.service_path), - profile_path(other.profile_path), - connect_state(other.connect_state), - success_callback(other.success_callback), - error_callback(other.error_callback) {} + const ConnectRequest& other) = default; NetworkConnectionHandlerImpl::NetworkConnectionHandlerImpl() : cert_loader_(NULL),
diff --git a/chromeos/network/network_connection_handler_impl_unittest.cc b/chromeos/network/network_connection_handler_impl_unittest.cc index e7f41ab..23953fa 100644 --- a/chromeos/network/network_connection_handler_impl_unittest.cc +++ b/chromeos/network/network_connection_handler_impl_unittest.cc
@@ -44,8 +44,8 @@ class TestNetworkConnectionObserver : public NetworkConnectionObserver { public: - TestNetworkConnectionObserver() {} - ~TestNetworkConnectionObserver() override {} + TestNetworkConnectionObserver() = default; + ~TestNetworkConnectionObserver() override = default; // NetworkConnectionObserver void ConnectToNetworkRequested(const std::string& service_path) override { @@ -87,7 +87,7 @@ public: FakeTetherDelegate() : last_delegate_function_type_(DelegateFunctionType::NONE) {} - ~FakeTetherDelegate() override {} + ~FakeTetherDelegate() override = default; enum class DelegateFunctionType { NONE, CONNECT, DISCONNECT }; @@ -138,7 +138,7 @@ : scoped_task_environment_( base::test::ScopedTaskEnvironment::MainThreadType::UI) {} - ~NetworkConnectionHandlerImplTest() override {} + ~NetworkConnectionHandlerImplTest() override = default; void SetUp() override { ASSERT_TRUE(test_nssdb_.is_open());
diff --git a/chromeos/network/network_connection_observer.cc b/chromeos/network/network_connection_observer.cc index 0cd31ec..0884986 100644 --- a/chromeos/network/network_connection_observer.cc +++ b/chromeos/network/network_connection_observer.cc
@@ -6,8 +6,7 @@ namespace chromeos { -NetworkConnectionObserver::NetworkConnectionObserver() { -} +NetworkConnectionObserver::NetworkConnectionObserver() = default; void NetworkConnectionObserver::ConnectToNetworkRequested( const std::string& service_path) { @@ -25,7 +24,6 @@ const std::string& service_path) { } -NetworkConnectionObserver::~NetworkConnectionObserver() { -} +NetworkConnectionObserver::~NetworkConnectionObserver() = default; } // namespace chromeos
diff --git a/chromeos/network/network_device_handler.cc b/chromeos/network/network_device_handler.cc index 0aaadfe..700ec897 100644 --- a/chromeos/network/network_device_handler.cc +++ b/chromeos/network/network_device_handler.cc
@@ -15,10 +15,8 @@ const char NetworkDeviceHandler::kErrorTimeout[] = "timeout"; const char NetworkDeviceHandler::kErrorUnknown[] = "unknown"; -NetworkDeviceHandler::NetworkDeviceHandler() { -} +NetworkDeviceHandler::NetworkDeviceHandler() = default; -NetworkDeviceHandler::~NetworkDeviceHandler() { -} +NetworkDeviceHandler::~NetworkDeviceHandler() = default; } // namespace chromeos
diff --git a/chromeos/network/network_device_handler_unittest.cc b/chromeos/network/network_device_handler_unittest.cc index 22a4479d..291e7a7 100644 --- a/chromeos/network/network_device_handler_unittest.cc +++ b/chromeos/network/network_device_handler_unittest.cc
@@ -34,7 +34,7 @@ NetworkDeviceHandlerTest() : scoped_task_environment_( base::test::ScopedTaskEnvironment::MainThreadType::UI) {} - ~NetworkDeviceHandlerTest() override {} + ~NetworkDeviceHandlerTest() override = default; void SetUp() override { fake_device_client_ = new FakeShillDeviceClient;
diff --git a/chromeos/network/network_ip_config.cc b/chromeos/network/network_ip_config.cc index 370a029..80a3f354 100644 --- a/chromeos/network/network_ip_config.cc +++ b/chromeos/network/network_ip_config.cc
@@ -39,7 +39,7 @@ name_servers(name_servers) { } -NetworkIPConfig::~NetworkIPConfig() {} +NetworkIPConfig::~NetworkIPConfig() = default; std::string NetworkIPConfig::ToString() const { return std::string("path: ") + device_path
diff --git a/chromeos/network/network_sms_handler.cc b/chromeos/network/network_sms_handler.cc index d5d2fde..e86464c9 100644 --- a/chromeos/network/network_sms_handler.cc +++ b/chromeos/network/network_sms_handler.cc
@@ -43,8 +43,8 @@ class NetworkSmsHandler::NetworkSmsDeviceHandler { public: - NetworkSmsDeviceHandler() {} - virtual ~NetworkSmsDeviceHandler() {} + NetworkSmsDeviceHandler() = default; + virtual ~NetworkSmsDeviceHandler() = default; virtual void RequestUpdate() = 0; };
diff --git a/chromeos/network/network_sms_handler_unittest.cc b/chromeos/network/network_sms_handler_unittest.cc index f1e09e9..9931bcf 100644 --- a/chromeos/network/network_sms_handler_unittest.cc +++ b/chromeos/network/network_sms_handler_unittest.cc
@@ -23,8 +23,8 @@ class TestObserver : public NetworkSmsHandler::Observer { public: - TestObserver() {} - ~TestObserver() override {} + TestObserver() = default; + ~TestObserver() override = default; void MessageReceived(const base::DictionaryValue& message) override { std::string text; @@ -54,7 +54,7 @@ NetworkSmsHandlerTest() : scoped_task_environment_( base::test::ScopedTaskEnvironment::MainThreadType::UI) {} - ~NetworkSmsHandlerTest() override {} + ~NetworkSmsHandlerTest() override = default; void SetUp() override { // Append '--sms-test-messages' to the command line to tell
diff --git a/chromeos/network/network_state.cc b/chromeos/network/network_state.cc index 6296db2..68210a66 100644 --- a/chromeos/network/network_state.cc +++ b/chromeos/network/network_state.cc
@@ -81,7 +81,7 @@ NetworkState::NetworkState(const std::string& path) : ManagedState(MANAGED_TYPE_NETWORK, path) {} -NetworkState::~NetworkState() {} +NetworkState::~NetworkState() = default; bool NetworkState::PropertyChanged(const std::string& key, const base::Value& value) {
diff --git a/chromeos/network/network_state_handler.cc b/chromeos/network/network_state_handler.cc index 02cba55..67d076d 100644 --- a/chromeos/network/network_state_handler.cc +++ b/chromeos/network/network_state_handler.cc
@@ -94,7 +94,7 @@ const char NetworkStateHandler::kDefaultCheckPortalList[] = "ethernet,wifi,cellular"; -NetworkStateHandler::NetworkStateHandler() {} +NetworkStateHandler::NetworkStateHandler() = default; NetworkStateHandler::~NetworkStateHandler() { // Normally Shutdown() will get called in ~NetworkHandler, however unit
diff --git a/chromeos/network/network_state_handler_observer.cc b/chromeos/network/network_state_handler_observer.cc index 4b80c01..ae08bc6f 100644 --- a/chromeos/network/network_state_handler_observer.cc +++ b/chromeos/network/network_state_handler_observer.cc
@@ -6,11 +6,9 @@ namespace chromeos { -NetworkStateHandlerObserver::NetworkStateHandlerObserver() { -} +NetworkStateHandlerObserver::NetworkStateHandlerObserver() = default; -NetworkStateHandlerObserver::~NetworkStateHandlerObserver() { -} +NetworkStateHandlerObserver::~NetworkStateHandlerObserver() = default; void NetworkStateHandlerObserver::NetworkListChanged() { }
diff --git a/chromeos/network/network_state_handler_unittest.cc b/chromeos/network/network_state_handler_unittest.cc index 725c3545..0eafbe5 100644 --- a/chromeos/network/network_state_handler_unittest.cc +++ b/chromeos/network/network_state_handler_unittest.cc
@@ -83,7 +83,7 @@ scan_requested_count_(0), scan_completed_count_(0) {} - ~TestObserver() override {} + ~TestObserver() override = default; void DeviceListChanged() override { NetworkStateHandler::DeviceStateList devices; @@ -204,8 +204,8 @@ class TestTetherSortDelegate : public NetworkStateHandler::TetherSortDelegate { public: - TestTetherSortDelegate() {} - ~TestTetherSortDelegate() {} + TestTetherSortDelegate() = default; + ~TestTetherSortDelegate() = default; // NetworkStateHandler::TetherSortDelegate: void SortTetherNetworkList( @@ -238,7 +238,7 @@ manager_test_(nullptr), profile_test_(nullptr), service_test_(nullptr) {} - ~NetworkStateHandlerTest() override {} + ~NetworkStateHandlerTest() override = default; void SetUp() override { // Initialize DBusThreadManager with a stub implementation.
diff --git a/chromeos/network/network_state_test.cc b/chromeos/network/network_state_test.cc index 904e56f..15a3b67 100644 --- a/chromeos/network/network_state_test.cc +++ b/chromeos/network/network_state_test.cc
@@ -26,7 +26,7 @@ NetworkStateTest::NetworkStateTest() : test_manager_client_(nullptr), weak_ptr_factory_(this) {} -NetworkStateTest::~NetworkStateTest() {} +NetworkStateTest::~NetworkStateTest() = default; void NetworkStateTest::SetUp() { DBusThreadManager* dbus_manager = DBusThreadManager::Get();
diff --git a/chromeos/network/network_ui_data.cc b/chromeos/network/network_ui_data.cc index f194f6d..901656c 100644 --- a/chromeos/network/network_ui_data.cc +++ b/chromeos/network/network_ui_data.cc
@@ -87,8 +87,7 @@ user_settings_.reset(user_settings->DeepCopy()); } -NetworkUIData::~NetworkUIData() { -} +NetworkUIData::~NetworkUIData() = default; void NetworkUIData::set_user_settings( std::unique_ptr<base::DictionaryValue> dict) {
diff --git a/chromeos/network/network_util.cc b/chromeos/network/network_util.cc index 4ed4ec9..8884143a 100644 --- a/chromeos/network/network_util.cc +++ b/chromeos/network/network_util.cc
@@ -34,23 +34,20 @@ WifiAccessPoint::WifiAccessPoint(const WifiAccessPoint& other) = default; -WifiAccessPoint::~WifiAccessPoint() { -} +WifiAccessPoint::~WifiAccessPoint() = default; -CellTower::CellTower() {} +CellTower::CellTower() = default; CellTower::CellTower(const CellTower& other) = default; -CellTower::~CellTower() {} +CellTower::~CellTower() = default; -CellularScanResult::CellularScanResult() { -} +CellularScanResult::CellularScanResult() = default; CellularScanResult::CellularScanResult(const CellularScanResult& other) = default; -CellularScanResult::~CellularScanResult() { -} +CellularScanResult::~CellularScanResult() = default; namespace network_util {
diff --git a/chromeos/network/onc/onc_certificate_importer_impl.cc b/chromeos/network/onc/onc_certificate_importer_impl.cc index a0e593f..0b74cf1a 100644 --- a/chromeos/network/onc/onc_certificate_importer_impl.cc +++ b/chromeos/network/onc/onc_certificate_importer_impl.cc
@@ -52,8 +52,7 @@ CHECK(target_nssdb); } -CertificateImporterImpl::~CertificateImporterImpl() { -} +CertificateImporterImpl::~CertificateImporterImpl() = default; void CertificateImporterImpl::ImportCertificates( const base::ListValue& certificates,
diff --git a/chromeos/network/onc/onc_certificate_importer_impl_unittest.cc b/chromeos/network/onc/onc_certificate_importer_impl_unittest.cc index 3e02a128..c9cae15 100644 --- a/chromeos/network/onc/onc_certificate_importer_impl_unittest.cc +++ b/chromeos/network/onc/onc_certificate_importer_impl_unittest.cc
@@ -28,8 +28,8 @@ class ONCCertificateImporterImplTest : public testing::Test { public: - ONCCertificateImporterImplTest() {} - ~ONCCertificateImporterImplTest() override {} + ONCCertificateImporterImplTest() = default; + ~ONCCertificateImporterImplTest() override = default; void SetUp() override { ASSERT_TRUE(public_nssdb_.is_open());
diff --git a/chromeos/network/onc/onc_mapper.cc b/chromeos/network/onc/onc_mapper.cc index 7c9f78df..ff1ac50 100644 --- a/chromeos/network/onc/onc_mapper.cc +++ b/chromeos/network/onc/onc_mapper.cc
@@ -14,11 +14,9 @@ namespace chromeos { namespace onc { -Mapper::Mapper() { -} +Mapper::Mapper() = default; -Mapper::~Mapper() { -} +Mapper::~Mapper() = default; std::unique_ptr<base::Value> Mapper::MapValue( const OncValueSignature& signature,
diff --git a/chromeos/network/onc/onc_merger.cc b/chromeos/network/onc/onc_merger.cc index a3d4782f..0169013 100644 --- a/chromeos/network/onc/onc_merger.cc +++ b/chromeos/network/onc/onc_merger.cc
@@ -88,11 +88,9 @@ public: typedef std::vector<const base::DictionaryValue*> DictPtrs; - MergeListOfDictionaries() { - } + MergeListOfDictionaries() = default; - virtual ~MergeListOfDictionaries() { - } + virtual ~MergeListOfDictionaries() = default; // For each path in any of the dictionaries |dicts|, the function // MergeListOfValues is called with the list of values that are located at @@ -176,7 +174,7 @@ bool device_editable; }; - MergeSettingsAndPolicies() {} + MergeSettingsAndPolicies() = default; // Merge the provided dictionaries. For each path in any of the dictionaries, // MergeValues is called. Its results are collected in a new dictionary which @@ -273,7 +271,7 @@ // MergeSettingsAndPoliciesToEffective. class MergeToEffective : public MergeSettingsAndPolicies { public: - MergeToEffective() {} + MergeToEffective() = default; protected: // Merges |values| to the effective value (Mandatory policy overwrites user @@ -352,7 +350,7 @@ // dictionaries. See the description of MergeSettingsAndPoliciesToAugmented. class MergeToAugmented : public MergeToEffective { public: - MergeToAugmented() {} + MergeToAugmented() = default; DictionaryPtr MergeDictionaries( const OncValueSignature& signature,
diff --git a/chromeos/network/onc/onc_normalizer.cc b/chromeos/network/onc/onc_normalizer.cc index 3076748..dfac5ac 100644 --- a/chromeos/network/onc/onc_normalizer.cc +++ b/chromeos/network/onc/onc_normalizer.cc
@@ -19,8 +19,7 @@ : remove_recommended_fields_(remove_recommended_fields) { } -Normalizer::~Normalizer() { -} +Normalizer::~Normalizer() = default; std::unique_ptr<base::DictionaryValue> Normalizer::NormalizeObject( const OncValueSignature* object_signature,
diff --git a/chromeos/network/onc/onc_signature.cc b/chromeos/network/onc/onc_signature.cc index 3c3dc326..d6c40f9 100644 --- a/chromeos/network/onc/onc_signature.cc +++ b/chromeos/network/onc/onc_signature.cc
@@ -61,6 +61,7 @@ // Deprecated. {::onc::eap::kServerCARef, &kStringSignature}, {::onc::eap::kServerCARefs, &kStringListSignature}, + {::onc::eap::kTLSVersionMax, &kStringSignature}, {::onc::eap::kUseProactiveKeyCaching, &kBoolSignature}, {::onc::eap::kUseSystemCAs, &kBoolSignature}, {NULL}};
diff --git a/chromeos/network/onc/onc_translation_tables.cc b/chromeos/network/onc/onc_translation_tables.cc index c222bda..a3e8acc 100644 --- a/chromeos/network/onc/onc_translation_tables.cc +++ b/chromeos/network/onc/onc_translation_tables.cc
@@ -33,6 +33,7 @@ {::onc::eap::kSaveCredentials, shill::kSaveCredentialsProperty}, {::onc::eap::kServerCAPEMs, shill::kEapCaCertPemProperty}, {::onc::eap::kSubjectMatch, shill::kEapSubjectMatchProperty}, + {::onc::eap::kTLSVersionMax, shill::kEapTLSVersionMaxProperty}, {::onc::eap::kUseSystemCAs, shill::kEapUseSystemCasProperty}, {::onc::eap::kUseProactiveKeyCaching, shill::kEapUseProactiveKeyCachingProperty},
diff --git a/chromeos/network/onc/onc_utils.cc b/chromeos/network/onc/onc_utils.cc index 149f6bb4..68c9c25 100644 --- a/chromeos/network/onc/onc_utils.cc +++ b/chromeos/network/onc/onc_utils.cc
@@ -74,7 +74,7 @@ public: explicit UserStringSubstitution(const user_manager::User* user) : user_(user) {} - ~UserStringSubstitution() override {} + ~UserStringSubstitution() override = default; bool GetSubstitute(const std::string& placeholder, std::string* substitute) const override {
diff --git a/chromeos/network/onc/onc_utils_unittest.cc b/chromeos/network/onc/onc_utils_unittest.cc index 8e20606..63407c5 100644 --- a/chromeos/network/onc/onc_utils_unittest.cc +++ b/chromeos/network/onc/onc_utils_unittest.cc
@@ -85,7 +85,7 @@ class StringSubstitutionStub : public StringSubstitution { public: - StringSubstitutionStub() {} + StringSubstitutionStub() = default; bool GetSubstitute(const std::string& placeholder, std::string* substitute) const override { if (placeholder == ::onc::substitutes::kLoginIDField)
diff --git a/chromeos/network/onc/onc_validator.cc b/chromeos/network/onc/onc_validator.cc index 6248bc1..29446059 100644 --- a/chromeos/network/onc/onc_validator.cc +++ b/chromeos/network/onc/onc_validator.cc
@@ -44,7 +44,7 @@ managed_onc_(managed_onc), onc_source_(::onc::ONC_SOURCE_NONE) {} -Validator::~Validator() {} +Validator::~Validator() = default; std::unique_ptr<base::DictionaryValue> Validator::ValidateAndRepairObject( const OncValueSignature* object_signature,
diff --git a/chromeos/network/portal_detector/mock_network_portal_detector.cc b/chromeos/network/portal_detector/mock_network_portal_detector.cc index e507980..e293578 100644 --- a/chromeos/network/portal_detector/mock_network_portal_detector.cc +++ b/chromeos/network/portal_detector/mock_network_portal_detector.cc
@@ -6,8 +6,8 @@ namespace chromeos { -MockNetworkPortalDetector::MockNetworkPortalDetector() {} +MockNetworkPortalDetector::MockNetworkPortalDetector() = default; -MockNetworkPortalDetector::~MockNetworkPortalDetector() {} +MockNetworkPortalDetector::~MockNetworkPortalDetector() = default; } // namespace chromeos
diff --git a/chromeos/network/portal_detector/network_portal_detector_strategy.cc b/chromeos/network/portal_detector/network_portal_detector_strategy.cc index 6e3533b..1ec6775 100644 --- a/chromeos/network/portal_detector/network_portal_detector_strategy.cc +++ b/chromeos/network/portal_detector/network_portal_detector_strategy.cc
@@ -25,7 +25,7 @@ explicit LoginScreenStrategy(PortalDetectorStrategy::Delegate* delegate) : PortalDetectorStrategy(delegate) {} - ~LoginScreenStrategy() override {} + ~LoginScreenStrategy() override = default; protected: // PortalDetectorStrategy overrides: @@ -53,7 +53,7 @@ explicit ErrorScreenStrategy(PortalDetectorStrategy::Delegate* delegate) : PortalDetectorStrategy(delegate) {} - ~ErrorScreenStrategy() override {} + ~ErrorScreenStrategy() override = default; protected: // PortalDetectorStrategy overrides: @@ -74,7 +74,7 @@ explicit SessionStrategy(PortalDetectorStrategy::Delegate* delegate) : PortalDetectorStrategy(delegate) {} - ~SessionStrategy() override {} + ~SessionStrategy() override = default; protected: StrategyId Id() const override { return STRATEGY_ID_SESSION; } @@ -95,7 +95,7 @@ // PortalDetectorStrategy::Delegate -------------------------------------------- -PortalDetectorStrategy::Delegate::~Delegate() {} +PortalDetectorStrategy::Delegate::~Delegate() = default; // PortalDetectorStrategy ----------------------------------------------------- @@ -130,8 +130,7 @@ backoff_entry_.reset(new net::BackoffEntry(&policy_, delegate_)); } -PortalDetectorStrategy::~PortalDetectorStrategy() { -} +PortalDetectorStrategy::~PortalDetectorStrategy() = default; // static std::unique_ptr<PortalDetectorStrategy> PortalDetectorStrategy::CreateById(
diff --git a/chromeos/network/portal_detector/network_portal_detector_stub.cc b/chromeos/network/portal_detector/network_portal_detector_stub.cc index f779366..d6aac35 100644 --- a/chromeos/network/portal_detector/network_portal_detector_stub.cc +++ b/chromeos/network/portal_detector/network_portal_detector_stub.cc
@@ -6,9 +6,9 @@ namespace chromeos { -NetworkPortalDetectorStub::NetworkPortalDetectorStub() {} +NetworkPortalDetectorStub::NetworkPortalDetectorStub() = default; -NetworkPortalDetectorStub::~NetworkPortalDetectorStub() {} +NetworkPortalDetectorStub::~NetworkPortalDetectorStub() = default; void NetworkPortalDetectorStub::AddObserver(Observer* observer) {}
diff --git a/chromeos/network/prohibited_technologies_handler.cc b/chromeos/network/prohibited_technologies_handler.cc index 69bc503..0db65090 100644 --- a/chromeos/network/prohibited_technologies_handler.cc +++ b/chromeos/network/prohibited_technologies_handler.cc
@@ -11,7 +11,7 @@ namespace chromeos { -ProhibitedTechnologiesHandler::ProhibitedTechnologiesHandler() {} +ProhibitedTechnologiesHandler::ProhibitedTechnologiesHandler() = default; ProhibitedTechnologiesHandler::~ProhibitedTechnologiesHandler() { if (managed_network_configuration_handler_)
diff --git a/chromeos/network/proxy/ui_proxy_config.cc b/chromeos/network/proxy/ui_proxy_config.cc index cae782d..8111f47 100644 --- a/chromeos/network/proxy/ui_proxy_config.cc +++ b/chromeos/network/proxy/ui_proxy_config.cc
@@ -21,7 +21,7 @@ state(ProxyPrefs::CONFIG_UNSET), user_modifiable(true) {} -UIProxyConfig::~UIProxyConfig() {} +UIProxyConfig::~UIProxyConfig() = default; void UIProxyConfig::SetPacUrl(const GURL& pac_url) { mode = UIProxyConfig::MODE_PAC_SCRIPT;
diff --git a/chromeos/network/proxy/ui_proxy_config_service.cc b/chromeos/network/proxy/ui_proxy_config_service.cc index b2145e1..026764b 100644 --- a/chromeos/network/proxy/ui_proxy_config_service.cc +++ b/chromeos/network/proxy/ui_proxy_config_service.cc
@@ -90,7 +90,7 @@ base::Unretained(this))); } -UIProxyConfigService::~UIProxyConfigService() {} +UIProxyConfigService::~UIProxyConfigService() = default; void UIProxyConfigService::UpdateFromPrefs(const std::string& network_guid) { current_ui_network_guid_ = network_guid;
diff --git a/chromeos/network/shill_property_handler_unittest.cc b/chromeos/network/shill_property_handler_unittest.cc index 0a42780..47ca0534 100644 --- a/chromeos/network/shill_property_handler_unittest.cc +++ b/chromeos/network/shill_property_handler_unittest.cc
@@ -166,7 +166,7 @@ device_test_(NULL), service_test_(NULL), profile_test_(NULL) {} - ~ShillPropertyHandlerTest() override {} + ~ShillPropertyHandlerTest() override = default; void SetUp() override { // Initialize DBusThreadManager with a stub implementation.
diff --git a/chromeos/printing/ppd_cache.cc b/chromeos/printing/ppd_cache.cc index ff45ff6..9e358fc2 100644 --- a/chromeos/printing/ppd_cache.cc +++ b/chromeos/printing/ppd_cache.cc
@@ -148,7 +148,7 @@ } private: - ~PpdCacheImpl() override {} + ~PpdCacheImpl() override = default; base::FilePath cache_base_dir_; scoped_refptr<base::SequencedTaskRunner> fetch_task_runner_;
diff --git a/chromeos/printing/ppd_provider.cc b/chromeos/printing/ppd_provider.cc index 1bf5b71..2f50cf2 100644 --- a/chromeos/printing/ppd_provider.cc +++ b/chromeos/printing/ppd_provider.cc
@@ -1227,7 +1227,7 @@ base::WeakPtrFactory<PpdProviderImpl> weak_factory_; protected: - ~PpdProviderImpl() override {} + ~PpdProviderImpl() override = default; }; } // namespace
diff --git a/chromeos/printing/printer_configuration.cc b/chromeos/printing/printer_configuration.cc index 359cf284..fb618e45 100644 --- a/chromeos/printing/printer_configuration.cc +++ b/chromeos/printing/printer_configuration.cc
@@ -60,7 +60,7 @@ Printer& Printer::operator=(const Printer& other) = default; -Printer::~Printer() {} +Printer::~Printer() = default; bool Printer::IsIppEverywhere() const { return ppd_reference_.autoconf;
diff --git a/chromeos/process_proxy/process_output_watcher.cc b/chromeos/process_proxy/process_output_watcher.cc index b9eee0d..ac6a64ac 100644 --- a/chromeos/process_proxy/process_output_watcher.cc +++ b/chromeos/process_proxy/process_output_watcher.cc
@@ -61,7 +61,7 @@ read_buffer_capacity_ = arraysize(read_buffer_) - 1; } -ProcessOutputWatcher::~ProcessOutputWatcher() {} +ProcessOutputWatcher::~ProcessOutputWatcher() = default; void ProcessOutputWatcher::Start() { WatchProcessOutput();
diff --git a/chromeos/process_proxy/process_output_watcher_unittest.cc b/chromeos/process_proxy/process_output_watcher_unittest.cc index 73c566d..61275db 100644 --- a/chromeos/process_proxy/process_output_watcher_unittest.cc +++ b/chromeos/process_proxy/process_output_watcher_unittest.cc
@@ -49,7 +49,7 @@ class ProcessWatcherExpectations { public: - ProcessWatcherExpectations() {} + ProcessWatcherExpectations() = default; void SetTestCase(const TestCase& test_case) { received_from_out_ = 0; @@ -101,7 +101,7 @@ failed_(false) { } - ~ProcessOutputWatcherTest() override {} + ~ProcessOutputWatcherTest() override = default; void TearDown() override { if (output_watch_thread_started_)
diff --git a/chromeos/process_proxy/process_proxy_registry.cc b/chromeos/process_proxy/process_proxy_registry.cc index 5b9a5b3..76972694 100644 --- a/chromeos/process_proxy/process_proxy_registry.cc +++ b/chromeos/process_proxy/process_proxy_registry.cc
@@ -34,8 +34,7 @@ } // namespace -ProcessProxyRegistry::ProcessProxyInfo::ProcessProxyInfo() { -} +ProcessProxyRegistry::ProcessProxyInfo::ProcessProxyInfo() = default; ProcessProxyRegistry::ProcessProxyInfo::ProcessProxyInfo( const ProcessProxyInfo& other) { @@ -43,11 +42,9 @@ DCHECK(!other.proxy.get()); } -ProcessProxyRegistry::ProcessProxyInfo::~ProcessProxyInfo() { -} +ProcessProxyRegistry::ProcessProxyInfo::~ProcessProxyInfo() = default; -ProcessProxyRegistry::ProcessProxyRegistry() { -} +ProcessProxyRegistry::ProcessProxyRegistry() = default; ProcessProxyRegistry::~ProcessProxyRegistry() { // TODO(tbarzic): Fix issue with ProcessProxyRegistry being destroyed
diff --git a/chromeos/process_proxy/process_proxy_unittest.cc b/chromeos/process_proxy/process_proxy_unittest.cc index b2e6af4..ef22021 100644 --- a/chromeos/process_proxy/process_proxy_unittest.cc +++ b/chromeos/process_proxy/process_proxy_unittest.cc
@@ -43,8 +43,8 @@ class TestRunner { public: - TestRunner() {} - virtual ~TestRunner() {} + TestRunner() = default; + virtual ~TestRunner() = default; virtual void SetupExpectations(int terminal_id) = 0; virtual void OnSomeRead(int terminal_id, const std::string& type, @@ -63,7 +63,7 @@ class RegistryTestRunner : public TestRunner { public: - ~RegistryTestRunner() override {} + ~RegistryTestRunner() override = default; void SetupExpectations(int terminal_id) override { terminal_id_ = terminal_id; @@ -141,7 +141,7 @@ class RegistryNotifiedOnProcessExitTestRunner : public TestRunner { public: - ~RegistryNotifiedOnProcessExitTestRunner() override {} + ~RegistryNotifiedOnProcessExitTestRunner() override = default; void SetupExpectations(int terminal_id) override { output_received_ = false; @@ -178,8 +178,8 @@ class ProcessProxyTest : public testing::Test { public: - ProcessProxyTest() {} - ~ProcessProxyTest() override {} + ProcessProxyTest() = default; + ~ProcessProxyTest() override = default; protected: void InitRegistryTest(base::OnceClosure done_closure) {
diff --git a/chromeos/settings/cros_settings_provider.cc b/chromeos/settings/cros_settings_provider.cc index d6e90144..f6f2860 100644 --- a/chromeos/settings/cros_settings_provider.cc +++ b/chromeos/settings/cros_settings_provider.cc
@@ -17,8 +17,7 @@ : notify_cb_(notify_cb) { } -CrosSettingsProvider::~CrosSettingsProvider() { -} +CrosSettingsProvider::~CrosSettingsProvider() = default; void CrosSettingsProvider::Set(const std::string& path, const base::Value& value) {
diff --git a/chromeos/settings/timezone_settings.cc b/chromeos/settings/timezone_settings.cc index 9f30f764..3884eb10 100644 --- a/chromeos/settings/timezone_settings.cc +++ b/chromeos/settings/timezone_settings.cc
@@ -339,8 +339,7 @@ DISALLOW_COPY_AND_ASSIGN(TimezoneSettingsStubImpl); }; -TimezoneSettingsBaseImpl::~TimezoneSettingsBaseImpl() { -} +TimezoneSettingsBaseImpl::~TimezoneSettingsBaseImpl() = default; const icu::TimeZone& TimezoneSettingsBaseImpl::GetTimezone() { return *timezone_.get(); @@ -470,7 +469,7 @@ namespace chromeos { namespace system { -TimezoneSettings::Observer::~Observer() {} +TimezoneSettings::Observer::~Observer() = default; // static TimezoneSettings* TimezoneSettings::GetInstance() {
diff --git a/chromeos/settings/timezone_settings_unittest.cc b/chromeos/settings/timezone_settings_unittest.cc index 2e23ae1..f176315 100644 --- a/chromeos/settings/timezone_settings_unittest.cc +++ b/chromeos/settings/timezone_settings_unittest.cc
@@ -31,8 +31,8 @@ class KnownTimeZoneTest : public testing::Test { public: - KnownTimeZoneTest() {} - ~KnownTimeZoneTest() override {} + KnownTimeZoneTest() = default; + ~KnownTimeZoneTest() override = default; void SetUp() override { for (const char* id : kTimeZones) {
diff --git a/chromeos/system/cpu_temperature_reader.cc b/chromeos/system/cpu_temperature_reader.cc index 8a3e5c0..5d51bd2 100644 --- a/chromeos/system/cpu_temperature_reader.cc +++ b/chromeos/system/cpu_temperature_reader.cc
@@ -72,7 +72,7 @@ } // namespace -CPUTemperatureReader::CPUTemperatureInfo::CPUTemperatureInfo() {} +CPUTemperatureReader::CPUTemperatureInfo::CPUTemperatureInfo() = default; CPUTemperatureReader::CPUTemperatureInfo::~CPUTemperatureInfo() = default;
diff --git a/chromeos/system/fake_statistics_provider.cc b/chromeos/system/fake_statistics_provider.cc index 1d7ccf7..3b3beb8 100644 --- a/chromeos/system/fake_statistics_provider.cc +++ b/chromeos/system/fake_statistics_provider.cc
@@ -7,11 +7,9 @@ namespace chromeos { namespace system { -FakeStatisticsProvider::FakeStatisticsProvider() { -} +FakeStatisticsProvider::FakeStatisticsProvider() = default; -FakeStatisticsProvider::~FakeStatisticsProvider() { -} +FakeStatisticsProvider::~FakeStatisticsProvider() = default; void FakeStatisticsProvider::StartLoadingMachineStatistics( bool load_oem_manifest) {
diff --git a/chromeos/system/statistics_provider.cc b/chromeos/system/statistics_provider.cc index 10856bc..203baaf8 100644 --- a/chromeos/system/statistics_provider.cc +++ b/chromeos/system/statistics_provider.cc
@@ -422,8 +422,7 @@ &GetInitialTimezoneFromRegionalData; } -StatisticsProviderImpl::~StatisticsProviderImpl() { -} +StatisticsProviderImpl::~StatisticsProviderImpl() = default; void StatisticsProviderImpl::StartLoadingMachineStatistics( bool load_oem_manifest) {
diff --git a/chromeos/test/data/network/shill_wifi_eap_tls.json b/chromeos/test/data/network/shill_wifi_eap_tls.json index ffceea5..fc680a7 100644 --- a/chromeos/test/data/network/shill_wifi_eap_tls.json +++ b/chromeos/test/data/network/shill_wifi_eap_tls.json
@@ -4,6 +4,7 @@ "EAP.Identity": "my_identity", "EAP.KeyID": "1:123456abcdef", "EAP.PIN": "111111", + "EAP.TLSVersionMax": "1.2", "EAP.UseSystemCAs": true, "GUID": "{77db0089-0bc8-4358-929c-123xcv}", "Mode": "managed",
diff --git a/chromeos/test/data/network/translation_of_shill_wifi_eap_tls.onc b/chromeos/test/data/network/translation_of_shill_wifi_eap_tls.onc index 0ab3eb1..0f01ad3 100644 --- a/chromeos/test/data/network/translation_of_shill_wifi_eap_tls.onc +++ b/chromeos/test/data/network/translation_of_shill_wifi_eap_tls.onc
@@ -9,6 +9,7 @@ "ClientCertPKCS11Id": "1:123456abcdef", "Outer": "EAP-TLS", "Identity": "my_identity", + "TLSVersionMax": "1.2", "UseSystemCAs": true, "SaveCredentials": true }
diff --git a/chromeos/test/data/network/wifi_eap_tls.onc b/chromeos/test/data/network/wifi_eap_tls.onc index 0b05a49..e5bc0f05 100644 --- a/chromeos/test/data/network/wifi_eap_tls.onc +++ b/chromeos/test/data/network/wifi_eap_tls.onc
@@ -11,6 +11,7 @@ "ClientCertType": "PKCS11Id", "ClientCertPKCS11Id": "1:123456abcdef", "SaveCredentials": true, + "TLSVersionMax": "1.2", "UseSystemCAs": true } },
diff --git a/chromeos/timezone/timezone_resolver.cc b/chromeos/timezone/timezone_resolver.cc index 11b0f3c..88628bd 100644 --- a/chromeos/timezone/timezone_resolver.cc +++ b/chromeos/timezone/timezone_resolver.cc
@@ -182,8 +182,7 @@ DISALLOW_COPY_AND_ASSIGN(TZRequest); }; -TZRequest::~TZRequest() { -} +TZRequest::~TZRequest() = default; void TZRequest::StartRequestOnNetworkAvailable() { resolver_->RecordAttempt(); @@ -390,8 +389,8 @@ // ------------------------------------------------------------------------ // TimeZoneResolver::Delegate implementation -TimeZoneResolver::Delegate::Delegate() {} -TimeZoneResolver::Delegate::~Delegate() {} +TimeZoneResolver::Delegate::Delegate() = default; +TimeZoneResolver::Delegate::~Delegate() = default; // ------------------------------------------------------------------------ // TimeZoneResolver implementation
diff --git a/chromeos/tpm/tpm_password_fetcher.cc b/chromeos/tpm/tpm_password_fetcher.cc index a3d83dfc..5650c3a28 100644 --- a/chromeos/tpm/tpm_password_fetcher.cc +++ b/chromeos/tpm/tpm_password_fetcher.cc
@@ -26,8 +26,7 @@ DCHECK(delegate_); } -TpmPasswordFetcher::~TpmPasswordFetcher() { -} +TpmPasswordFetcher::~TpmPasswordFetcher() = default; void TpmPasswordFetcher::Fetch() { // Since this method is also called directly.
diff --git a/chromeos/tpm/tpm_token_info_getter.cc b/chromeos/tpm/tpm_token_info_getter.cc index afcab9d..89fe318 100644 --- a/chromeos/tpm/tpm_token_info_getter.cc +++ b/chromeos/tpm/tpm_token_info_getter.cc
@@ -56,7 +56,7 @@ TYPE_SYSTEM, EmptyAccountId(), cryptohome_client, delayed_task_runner)); } -TPMTokenInfoGetter::~TPMTokenInfoGetter() {} +TPMTokenInfoGetter::~TPMTokenInfoGetter() = default; void TPMTokenInfoGetter::Start(TpmTokenInfoCallback callback) { CHECK(state_ == STATE_INITIAL);
diff --git a/chromeos/tpm/tpm_token_info_getter_unittest.cc b/chromeos/tpm/tpm_token_info_getter_unittest.cc index c941d62..8dfab79e 100644 --- a/chromeos/tpm/tpm_token_info_getter_unittest.cc +++ b/chromeos/tpm/tpm_token_info_getter_unittest.cc
@@ -60,7 +60,7 @@ bool RunsTasksInCurrentSequence() const override { return true; } protected: - ~FakeTaskRunner() override {} + ~FakeTaskRunner() override = default; private: // The vector of delays. @@ -87,7 +87,7 @@ get_tpm_token_info_not_set_count_(0), get_tpm_token_info_succeeded_(false) {} - ~TestCryptohomeClient() override {} + ~TestCryptohomeClient() override = default; void set_tpm_is_enabled(bool value) { tpm_is_enabled_ = value; @@ -208,8 +208,8 @@ class SystemTPMTokenInfoGetterTest : public testing::Test { public: - SystemTPMTokenInfoGetterTest() {} - ~SystemTPMTokenInfoGetterTest() override {} + SystemTPMTokenInfoGetterTest() = default; + ~SystemTPMTokenInfoGetterTest() override = default; void SetUp() override { cryptohome_client_.reset(new TestCryptohomeClient(EmptyAccountId())); @@ -234,7 +234,7 @@ public: UserTPMTokenInfoGetterTest() : account_id_(AccountId::FromUserEmail("user@gmail.com")) {} - ~UserTPMTokenInfoGetterTest() override {} + ~UserTPMTokenInfoGetterTest() override = default; void SetUp() override { cryptohome_client_.reset(new TestCryptohomeClient(account_id_));
diff --git a/components/app_modal/javascript_dialog_manager.cc b/components/app_modal/javascript_dialog_manager.cc index 2808328..0768108 100644 --- a/components/app_modal/javascript_dialog_manager.cc +++ b/components/app_modal/javascript_dialog_manager.cc
@@ -195,6 +195,7 @@ void JavaScriptDialogManager::RunBeforeUnloadDialog( content::WebContents* web_contents, + content::RenderFrameHost* render_frame_host, bool is_reload, DialogClosedCallback callback) { ChromeJavaScriptDialogExtraData* extra_data =
diff --git a/components/app_modal/javascript_dialog_manager.h b/components/app_modal/javascript_dialog_manager.h index baf5386..0c11818 100644 --- a/components/app_modal/javascript_dialog_manager.h +++ b/components/app_modal/javascript_dialog_manager.h
@@ -50,6 +50,7 @@ DialogClosedCallback callback, bool* did_suppress_message) override; void RunBeforeUnloadDialog(content::WebContents* web_contents, + content::RenderFrameHost* render_frame_host, bool is_reload, DialogClosedCallback callback) override; bool HandleJavaScriptDialog(content::WebContents* web_contents,
diff --git a/components/arc/BUILD.gn b/components/arc/BUILD.gn index 188e808..a4550c6f 100644 --- a/components/arc/BUILD.gn +++ b/components/arc/BUILD.gn
@@ -182,6 +182,8 @@ "test/fake_voice_interaction_framework_instance.h", "test/fake_wallpaper_instance.cc", "test/fake_wallpaper_instance.h", + "test/test_browser_context.cc", + "test/test_browser_context.h", ] public_deps = [ @@ -190,6 +192,10 @@ deps = [ "//base", + "//components/keyed_service/content", + "//components/prefs:test_support", + "//components/user_prefs", + "//content/test:test_support", "//mojo/common:common_base", "//mojo/edk/embedder:headers", ] @@ -211,6 +217,7 @@ "intent_helper/intent_filter_unittest.cc", "intent_helper/link_handler_model_unittest.cc", "intent_helper/page_transition_util_unittest.cc", + "metrics/arc_metrics_service_unittest.cc", "power/arc_power_bridge_unittest.cc", ] @@ -222,11 +229,13 @@ "//chromeos", "//chromeos:power_manager_proto", "//chromeos:test_support_without_gmock", + "//components/keyed_service/content", "//components/prefs:test_support", "//components/signin/core/account_id", "//components/user_manager", "//components/user_manager:test_support", "//content/public/common", + "//content/test:test_support", "//device/bluetooth", "//mojo/public/cpp/system:system", "//services/device/public/cpp/test:test_support",
diff --git a/components/arc/DEPS b/components/arc/DEPS index cbf51bdb..adc4743 100644 --- a/components/arc/DEPS +++ b/components/arc/DEPS
@@ -25,4 +25,7 @@ "arc_util_unittest.cc": [ "+ui/aura", ], + ".*_unittest.cc": [ + "+content/public/test/test_browser_thread_bundle.h" + ] }
diff --git a/components/arc/arc_session_runner.cc b/components/arc/arc_session_runner.cc index 85c8899..1e3eccb 100644 --- a/components/arc/arc_session_runner.cc +++ b/components/arc/arc_session_runner.cc
@@ -340,7 +340,8 @@ // instance may depend on such as cras, EmitLoginPromptVisibleCalled() is the // safe place to start a mini instance. DCHECK(!arc_session_); - RequestStart(ArcInstanceMode::MINI_INSTANCE); + if (IsArcAvailable()) + RequestStart(ArcInstanceMode::MINI_INSTANCE); } } // namespace arc
diff --git a/components/arc/arc_session_runner_unittest.cc b/components/arc/arc_session_runner_unittest.cc index 2e997fd9..8a531e8 100644 --- a/components/arc/arc_session_runner_unittest.cc +++ b/components/arc/arc_session_runner_unittest.cc
@@ -8,6 +8,7 @@ #include "base/bind.h" #include "base/bind_helpers.h" #include "base/callback_helpers.h" +#include "base/command_line.h" #include "base/macros.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" @@ -16,6 +17,7 @@ #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/fake_session_manager_client.h" #include "components/arc/arc_session_runner.h" +#include "components/arc/arc_util.h" #include "components/arc/test/fake_arc_session.h" #include "mojo/public/cpp/system/message_pipe.h" #include "testing/gtest/include/gtest/gtest.h" @@ -276,6 +278,8 @@ TEST_F(ArcSessionRunnerTest, EmitLoginPromptVisible) { EXPECT_FALSE(arc_session()); + SetArcAvailableCommandLineForTesting(base::CommandLine::ForCurrentProcess()); + chromeos::DBusThreadManager::Get() ->GetSessionManagerClient() ->EmitLoginPromptVisible(); @@ -283,6 +287,17 @@ EXPECT_FALSE(arc_session()->is_running()); } +// We expect mini instance does not start on EmitLoginPromptVisible when ARC +// is not available. +TEST_F(ArcSessionRunnerTest, EmitLoginPromptVisible_NoOp) { + EXPECT_FALSE(arc_session()); + + chromeos::DBusThreadManager::Get() + ->GetSessionManagerClient() + ->EmitLoginPromptVisible(); + EXPECT_FALSE(arc_session()); +} + // If the instance is stopped, it should be re-started. TEST_F(ArcSessionRunnerTest, Restart) { arc_session_runner()->SetRestartDelayForTesting(base::TimeDelta());
diff --git a/components/arc/metrics/arc_metrics_service.cc b/components/arc/metrics/arc_metrics_service.cc index 647fa55f..79de7ed 100644 --- a/components/arc/metrics/arc_metrics_service.cc +++ b/components/arc/metrics/arc_metrics_service.cc
@@ -68,6 +68,11 @@ } // namespace // static +BrowserContextKeyedServiceFactory* ArcMetricsService::GetFactory() { + return ArcMetricsServiceFactory::GetInstance(); +} + +// static ArcMetricsService* ArcMetricsService::GetForBrowserContext( content::BrowserContext* context) { return ArcMetricsServiceFactory::GetForBrowserContext(context);
diff --git a/components/arc/metrics/arc_metrics_service.h b/components/arc/metrics/arc_metrics_service.h index a3bc620..76ea2e8 100644 --- a/components/arc/metrics/arc_metrics_service.h +++ b/components/arc/metrics/arc_metrics_service.h
@@ -17,6 +17,8 @@ #include "components/arc/connection_observer.h" #include "components/keyed_service/core/keyed_service.h" +class BrowserContextKeyedServiceFactory; + namespace content { class BrowserContext; } // namespace content @@ -29,6 +31,9 @@ class ArcMetricsService : public KeyedService, public mojom::MetricsHost { public: + // Returns the factory instance for this class. + static BrowserContextKeyedServiceFactory* GetFactory(); + // Returns singleton instance for the given BrowserContext, // or nullptr if the browser |context| is not allowed to use ARC. static ArcMetricsService* GetForBrowserContext(
diff --git a/components/arc/metrics/arc_metrics_service_unittest.cc b/components/arc/metrics/arc_metrics_service_unittest.cc new file mode 100644 index 0000000..75fc712b --- /dev/null +++ b/components/arc/metrics/arc_metrics_service_unittest.cc
@@ -0,0 +1,228 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/arc/metrics/arc_metrics_service.h" + +#include <algorithm> +#include <array> +#include <memory> +#include <string> +#include <utility> + +#include "base/metrics/histogram_samples.h" +#include "base/run_loop.h" +#include "base/test/histogram_tester.h" +#include "chromeos/dbus/dbus_thread_manager.h" +#include "chromeos/dbus/fake_session_manager_client.h" +#include "components/arc/arc_bridge_service.h" +#include "components/arc/arc_service_manager.h" +#include "components/arc/test/fake_arc_session.h" +#include "components/arc/test/test_browser_context.h" +#include "components/keyed_service/content/browser_context_keyed_service_factory.h" +#include "content/public/test/test_browser_thread_bundle.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace arc { +namespace { + +// The event names the container sends to Chrome. +constexpr std::array<const char*, 11> kBootEvents{ + "boot_progress_start", + "boot_progress_preload_start", + "boot_progress_preload_end", + "boot_progress_system_run", + "boot_progress_pms_start", + "boot_progress_pms_system_scan_start", + "boot_progress_pms_data_scan_start", + "boot_progress_pms_scan_end", + "boot_progress_pms_ready", + "boot_progress_ams_ready", + "boot_progress_enable_screen"}; + +ArcMetricsService* GetArcMetricsService(content::BrowserContext* context) { + ArcMetricsService::GetFactory()->SetTestingFactoryAndUse( + context, + [](content::BrowserContext* context) -> std::unique_ptr<KeyedService> { + return std::make_unique<ArcMetricsService>( + context, ArcServiceManager::Get()->arc_bridge_service()); + }); + return ArcMetricsService::GetForBrowserContext(context); +} + +class ArcMetricsServiceTest : public testing::Test { + public: + ArcMetricsServiceTest() + : arc_service_manager_(std::make_unique<ArcServiceManager>()), + context_(std::make_unique<TestBrowserContext>()), + metrics_service_(GetArcMetricsService(context_.get())) { + chromeos::DBusThreadManager::GetSetterForTesting()->SetSessionManagerClient( + std::make_unique<chromeos::FakeSessionManagerClient>()); + GetSessionManagerClient()->set_arc_available(true); + } + + ~ArcMetricsServiceTest() override { + metrics_service_->Shutdown(); + chromeos::DBusThreadManager::Shutdown(); + } + + ArcMetricsService* metrics_service() { return metrics_service_; } + + protected: + void SetArcStartTimeInMs(uint64_t arc_start_time_in_ms) { + const base::TimeTicks arc_start_time = + base::TimeDelta::FromMilliseconds(arc_start_time_in_ms) + + base::TimeTicks(); + GetSessionManagerClient()->set_arc_start_time(arc_start_time); + } + + std::vector<mojom::BootProgressEventPtr> GetBootProgressEvents( + uint64_t start_in_ms, + uint64_t step_in_ms) { + std::vector<mojom::BootProgressEventPtr> events; + for (size_t i = 0; i < kBootEvents.size(); ++i) { + events.emplace_back(mojom::BootProgressEvent::New( + kBootEvents[i], start_in_ms + (step_in_ms * i))); + } + return events; + } + + private: + chromeos::FakeSessionManagerClient* GetSessionManagerClient() { + return static_cast<chromeos::FakeSessionManagerClient*>( + chromeos::DBusThreadManager::Get()->GetSessionManagerClient()); + } + + content::TestBrowserThreadBundle thread_bundle_; + std::unique_ptr<ArcServiceManager> arc_service_manager_; + std::unique_ptr<TestBrowserContext> context_; + + ArcMetricsService* const metrics_service_; + + DISALLOW_COPY_AND_ASSIGN(ArcMetricsServiceTest); +}; + +// Tests that ReportBootProgress() actually records UMA stats. +TEST_F(ArcMetricsServiceTest, ReportBootProgress_FirstBoot) { + // Start the full ARC container at t=10. Also set boot_progress_start to 10, + // boot_progress_preload_start to 11, and so on. + constexpr uint64_t kArcStartTimeMs = 10; + SetArcStartTimeInMs(kArcStartTimeMs); + std::vector<mojom::BootProgressEventPtr> events( + GetBootProgressEvents(kArcStartTimeMs, 1 /* step_in_ms */)); + + // Call ReportBootProgress() and then confirm that + // Arc.boot_progress_start.FirstBoot is recorded with 0 (ms), + // Arc.boot_progress_preload_start.FirstBoot is with 1 (ms), etc. + base::HistogramTester tester; + metrics_service()->ReportBootProgress(std::move(events), + mojom::BootType::FIRST_BOOT); + base::RunLoop().RunUntilIdle(); + for (size_t i = 0; i < kBootEvents.size(); ++i) { + tester.ExpectUniqueSample( + std::string("Arc.") + kBootEvents[i] + ".FirstBoot", i, + 1 /* count of the sample */); + } + // Confirm that Arc.AndroidBootTime.FirstBoot is also recorded, and has the + // same value as "Arc.boot_progress_enable_screen.FirstBoot". + std::unique_ptr<base::HistogramSamples> samples = + tester.GetHistogramSamplesSinceCreation( + "Arc." + std::string(kBootEvents.back()) + ".FirstBoot"); + ASSERT_TRUE(samples.get()); + tester.ExpectUniqueSample("Arc.AndroidBootTime.FirstBoot", samples->sum(), 1); +} + +// Does the same but with negative values and FIRST_BOOT_AFTER_UPDATE. +TEST_F(ArcMetricsServiceTest, ReportBootProgress_FirstBootAfterUpdate) { + // Start the full ARC container at t=10. Also set boot_progress_start to 5, + // boot_progress_preload_start to 7, and so on. This can actually happen + // because the mini container can finish up to boot_progress_preload_end + // before the full container is started. + constexpr uint64_t kArcStartTimeMs = 10; + SetArcStartTimeInMs(kArcStartTimeMs); + std::vector<mojom::BootProgressEventPtr> events( + GetBootProgressEvents(kArcStartTimeMs - 5, 2 /* step_in_ms */)); + + // Call ReportBootProgress() and then confirm that + // Arc.boot_progress_start.FirstBoot is recorded with 0 (ms), + // Arc.boot_progress_preload_start.FirstBoot is with 0 (ms), etc. Unlike our + // performance dashboard where negative performance numbers are treated as-is, + // UMA treats them as zeros. + base::HistogramTester tester; + // This time, use mojom::BootType::FIRST_BOOT_AFTER_UPDATE. + metrics_service()->ReportBootProgress( + std::move(events), mojom::BootType::FIRST_BOOT_AFTER_UPDATE); + base::RunLoop().RunUntilIdle(); + for (size_t i = 0; i < kBootEvents.size(); ++i) { + const int expected = std::max<int>(0, i * 2 - 5); + tester.ExpectUniqueSample( + std::string("Arc.") + kBootEvents[i] + ".FirstBootAfterUpdate", + expected, 1); + } + std::unique_ptr<base::HistogramSamples> samples = + tester.GetHistogramSamplesSinceCreation( + "Arc." + std::string(kBootEvents.back()) + ".FirstBootAfterUpdate"); + ASSERT_TRUE(samples.get()); + tester.ExpectUniqueSample("Arc.AndroidBootTime.FirstBootAfterUpdate", + samples->sum(), 1); +} + +// Does the same but with REGULAR_BOOT. +TEST_F(ArcMetricsServiceTest, ReportBootProgress_RegularBoot) { + constexpr uint64_t kArcStartTimeMs = 10; + SetArcStartTimeInMs(kArcStartTimeMs); + std::vector<mojom::BootProgressEventPtr> events( + GetBootProgressEvents(kArcStartTimeMs - 5, 2 /* step_in_ms */)); + + base::HistogramTester tester; + metrics_service()->ReportBootProgress(std::move(events), + mojom::BootType::REGULAR_BOOT); + base::RunLoop().RunUntilIdle(); + for (size_t i = 0; i < kBootEvents.size(); ++i) { + const int expected = std::max<int>(0, i * 2 - 5); + tester.ExpectUniqueSample( + std::string("Arc.") + kBootEvents[i] + ".RegularBoot", expected, 1); + } + std::unique_ptr<base::HistogramSamples> samples = + tester.GetHistogramSamplesSinceCreation( + "Arc." + std::string(kBootEvents.back()) + ".RegularBoot"); + ASSERT_TRUE(samples.get()); + tester.ExpectUniqueSample("Arc.AndroidBootTime.RegularBoot", samples->sum(), + 1); +} + +// Tests that no UMA is recorded when nothing is reported. +TEST_F(ArcMetricsServiceTest, ReportBootProgress_EmptyResults) { + SetArcStartTimeInMs(100); + std::vector<mojom::BootProgressEventPtr> events; // empty + + base::HistogramTester tester; + metrics_service()->ReportBootProgress(std::move(events), + mojom::BootType::FIRST_BOOT); + base::RunLoop().RunUntilIdle(); + for (size_t i = 0; i < kBootEvents.size(); ++i) { + tester.ExpectTotalCount(std::string("Arc.") + kBootEvents[i] + ".FirstBoot", + 0); + } + tester.ExpectTotalCount("Arc.AndroidBootTime.FirstBoot", 0); +} + +// Tests that no UMA is recorded when BootType is invalid. +TEST_F(ArcMetricsServiceTest, ReportBootProgress_InvalidBootType) { + SetArcStartTimeInMs(100); + std::vector<mojom::BootProgressEventPtr> events( + GetBootProgressEvents(123, 456)); + base::HistogramTester tester; + metrics_service()->ReportBootProgress(std::move(events), + mojom::BootType::UNKNOWN); + base::RunLoop().RunUntilIdle(); + for (const std::string& suffix : + {".FirstBoot", ".FirstBootAfterUpdate", ".RegularBoot"}) { + tester.ExpectTotalCount("Arc." + (kBootEvents.front() + suffix), 0); + tester.ExpectTotalCount("Arc." + (kBootEvents.back() + suffix), 0); + tester.ExpectTotalCount("Arc.AndroidBootTime" + suffix, 0); + } +} + +} // namespace +} // namespace arc
diff --git a/components/arc/test/DEPS b/components/arc/test/DEPS new file mode 100644 index 0000000..461938c --- /dev/null +++ b/components/arc/test/DEPS
@@ -0,0 +1,9 @@ +specific_include_rules = { + "test_browser_context.h": [ + "+content/public/test/test_browser_context.h", + ], + "test_browser_context.cc": [ + "+components/user_prefs/user_prefs.h", + ] +} +
diff --git a/components/arc/test/test_browser_context.cc b/components/arc/test/test_browser_context.cc new file mode 100644 index 0000000..f9f6274 --- /dev/null +++ b/components/arc/test/test_browser_context.cc
@@ -0,0 +1,22 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/arc/test/test_browser_context.h" + +#include "components/keyed_service/content/browser_context_dependency_manager.h" +#include "components/user_prefs/user_prefs.h" + +namespace arc { + +TestBrowserContext::TestBrowserContext() + : browser_context_dependency_manager_( + BrowserContextDependencyManager::GetInstance()) { + user_prefs::UserPrefs::Set(this, &prefs_); +} + +TestBrowserContext::~TestBrowserContext() { + browser_context_dependency_manager_->DestroyBrowserContextServices(this); +} + +} // namespace arc
diff --git a/components/arc/test/test_browser_context.h b/components/arc/test/test_browser_context.h new file mode 100644 index 0000000..89051d8 --- /dev/null +++ b/components/arc/test/test_browser_context.h
@@ -0,0 +1,32 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_ARC_TEST_TEST_BROWSER_CONTEXT_H_ +#define COMPONENTS_ARC_TEST_TEST_BROWSER_CONTEXT_H_ + +#include "base/macros.h" +#include "components/prefs/testing_pref_service.h" +#include "content/public/test/test_browser_context.h" + +class BrowserContextDependencyManager; + +namespace arc { + +// A browser context for testing that can be used for getting objects +// through ArcBrowserContextKeyedServiceFactoryBase<>. +class TestBrowserContext : public content::TestBrowserContext { + public: + TestBrowserContext(); + ~TestBrowserContext() override; + + private: + BrowserContextDependencyManager* const browser_context_dependency_manager_; + TestingPrefServiceSimple prefs_; + + DISALLOW_COPY_AND_ASSIGN(TestBrowserContext); +}; + +} // namespace arc + +#endif // COMPONENTS_ARC_TEST_TEST_BROWSER_CONTEXT_H_
diff --git a/components/autofill/content/renderer/DEPS b/components/autofill/content/renderer/DEPS index e4129d098..ab852225 100644 --- a/components/autofill/content/renderer/DEPS +++ b/components/autofill/content/renderer/DEPS
@@ -3,6 +3,7 @@ "+content/public/renderer", "+third_party/re2", # Allow inclusion of WebKit API files. + "+third_party/WebKit/common", "+third_party/WebKit/public/platform", "+third_party/WebKit/public/web", ]
diff --git a/components/autofill/content/renderer/form_cache.cc b/components/autofill/content/renderer/form_cache.cc index 05451fe..e57ea9cc 100644 --- a/components/autofill/content/renderer/form_cache.cc +++ b/components/autofill/content/renderer/form_cache.cc
@@ -153,7 +153,9 @@ // If there are no autocomplete attributes, the form needs to have at least // the required number of editable fields for the prediction routines to be a // candidate for autofill. - return num_editable_elements >= kRequiredFieldsForPredictionRoutines || + return num_editable_elements >= MinRequiredFieldsForHeuristics() || + num_editable_elements >= MinRequiredFieldsForQuery() || + num_editable_elements >= MinRequiredFieldsForUpload() || (all_fields_are_passwords && num_editable_elements >= kRequiredFieldsForFormsWithOnlyPasswordFields);
diff --git a/components/autofill/content/renderer/password_generation_agent.cc b/components/autofill/content/renderer/password_generation_agent.cc index e4021b31..8c13ee7 100644 --- a/components/autofill/content/renderer/password_generation_agent.cc +++ b/components/autofill/content/renderer/password_generation_agent.cc
@@ -21,10 +21,10 @@ #include "components/autofill/core/common/password_form_generation_data.h" #include "components/autofill/core/common/password_generation_util.h" #include "components/autofill/core/common/signatures_util.h" -#include "content/public/common/associated_interface_provider.h" #include "content/public/renderer/render_frame.h" #include "content/public/renderer/render_view.h" #include "google_apis/gaia/gaia_urls.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" #include "third_party/WebKit/public/platform/WebSecurityOrigin.h" #include "third_party/WebKit/public/platform/WebVector.h" #include "third_party/WebKit/public/web/WebDocument.h"
diff --git a/components/autofill/core/browser/autofill_manager.cc b/components/autofill/core/browser/autofill_manager.cc index e328ca9..d218556 100644 --- a/components/autofill/core/browser/autofill_manager.cc +++ b/components/autofill/core/browser/autofill_manager.cc
@@ -378,16 +378,14 @@ CreditCard credit_card = form_data_importer_->ExtractCreditCardFromForm(*submitted_form); - if (IsValidCreditCardNumber(credit_card.number())) { - credit_card_form_event_logger_->DetectedCardInSubmittedForm(); - if (personal_data_->IsKnownCard(credit_card)) { - credit_card_form_event_logger_->SubmittedKnownCard(); - } - } + AutofillMetrics::CardNumberStatus card_number_status = + GetCardNumberStatus(credit_card); - address_form_event_logger_->OnFormSubmitted(/*force_logging=*/false); + address_form_event_logger_->OnFormSubmitted(/*force_logging=*/false, + card_number_status); if (IsCreditCardAutofillEnabled()) - credit_card_form_event_logger_->OnFormSubmitted(enable_ablation_logging_); + credit_card_form_event_logger_->OnFormSubmitted(enable_ablation_logging_, + card_number_status); // Update Personal Data with the form's submitted data. // Also triggers offering local/upload credit card save, if applicable. @@ -1084,11 +1082,7 @@ bool AutofillManager::ShouldUploadForm(const FormStructure& form) { return IsAutofillEnabled() && !driver()->IsIncognito() && - form.ShouldBeParsed() && - (form.active_field_count() >= kRequiredFieldsForUpload || - (form.all_fields_are_passwords() && - form.active_field_count() >= - kRequiredFieldsForFormsWithOnlyPasswordFields)); + form.ShouldBeUploaded(); } // Note that |submitted_form| is passed as a pointer rather than as a reference @@ -1101,11 +1095,14 @@ const TimeTicks& interaction_time, const TimeTicks& submission_time, bool observed_submission) { - submitted_form->LogQualityMetrics(load_time, interaction_time, - submission_time, - form_interactions_ukm_logger_.get(), - did_show_suggestions_, observed_submission); - if (submitted_form->ShouldBeCrowdsourced()) + if (submitted_form->ShouldRunHeuristics() || + submitted_form->ShouldBeQueried()) { + submitted_form->LogQualityMetrics( + load_time, interaction_time, submission_time, + form_interactions_ukm_logger_.get(), did_show_suggestions_, + observed_submission); + } + if (submitted_form->ShouldBeUploaded()) UploadFormData(*submitted_form, observed_submission); } @@ -1215,9 +1212,6 @@ CountryNames::SetLocaleString(app_locale_); if (personal_data_ && client_) personal_data_->OnSyncServiceInitialized(client_->GetSyncService()); - - if (personal_data_ && driver) - personal_data_->SetURLRequestContextGetter(driver->GetURLRequestContext()); } bool AutofillManager::RefreshDataModels() { @@ -1354,8 +1348,9 @@ continue; if (form_structure->field(i)->only_fill_when_focused() && - !form_structure->field(i)->SameFieldAs(field)) + !form_structure->field(i)->SameFieldAs(field)) { continue; + } DCHECK(form_structure->field(i)->SameFieldAs(result.fields[i])); @@ -1603,7 +1598,7 @@ form_types.insert(current_form_types.begin(), current_form_types.end()); // Set aside forms with method GET or author-specified types, so that they // are not included in the query to the server. - if (form_structure->ShouldBeCrowdsourced()) + if (form_structure->ShouldBeQueried()) queryable_forms.push_back(form_structure); else non_queryable_forms.push_back(form_structure); @@ -1936,4 +1931,19 @@ } } +AutofillMetrics::CardNumberStatus AutofillManager::GetCardNumberStatus( + CreditCard& credit_card) { + base::string16 number = credit_card.number(); + if (number.empty()) + return AutofillMetrics::EMPTY_CARD; + else if (!HasCorrectLength(number)) + return AutofillMetrics::WRONG_SIZE_CARD; + else if (!PassesLuhnCheck(number)) + return AutofillMetrics::FAIL_LUHN_CHECK_CARD; + else if (personal_data_->IsKnownCard(credit_card)) + return AutofillMetrics::KNOWN_CARD; + else + return AutofillMetrics::UNKNOWN_CARD; +} + } // namespace autofill
diff --git a/components/autofill/core/browser/autofill_manager.h b/components/autofill/core/browser/autofill_manager.h index a08b331..36882ea5 100644 --- a/components/autofill/core/browser/autofill_manager.h +++ b/components/autofill/core/browser/autofill_manager.h
@@ -457,6 +457,9 @@ bool should_notify, const base::string16& cvc); + AutofillMetrics::CardNumberStatus GetCardNumberStatus( + CreditCard& credit_card); + AutofillClient* const client_; // Handles Payments service requests.
diff --git a/components/autofill/core/browser/autofill_manager_unittest.cc b/components/autofill/core/browser/autofill_manager_unittest.cc index 672fa7a..068102c 100644 --- a/components/autofill/core/browser/autofill_manager_unittest.cc +++ b/components/autofill/core/browser/autofill_manager_unittest.cc
@@ -45,6 +45,7 @@ #include "components/autofill/core/browser/validation.h" #include "components/autofill/core/browser/webdata/autofill_webdata_service.h" #include "components/autofill/core/common/autofill_clock.h" +#include "components/autofill/core/common/autofill_features.h" #include "components/autofill/core/common/autofill_pref_names.h" #include "components/autofill/core/common/autofill_switches.h" #include "components/autofill/core/common/autofill_util.h" @@ -65,6 +66,9 @@ #include "ui/gfx/geometry/rect.h" #include "url/gurl.h" +using autofill::features::kAutofillEnforceMinRequiredFieldsForHeuristics; +using autofill::features::kAutofillEnforceMinRequiredFieldsForQuery; +using autofill::features::kAutofillEnforceMinRequiredFieldsForUpload; using base::ASCIIToUTF16; using base::UTF8ToUTF16; using testing::_; @@ -1136,9 +1140,13 @@ external_delegate_->CheckNoSuggestions(kDefaultPageID); } -// Test that no suggestions are returned when there are less than three fields -// and none of them have an autocomplete attribute. -TEST_F(AutofillManagerTest, GetProfileSuggestions_SmallFormNoAutocomplete) { +// Test that when small forms are disabled (min required fields enforced) no +// suggestions are returned when there are less than three fields and none of +// them have an autocomplete attribute. +TEST_F(AutofillManagerTest, + GetProfileSuggestions_MinFieldsEnforced_NoAutocomplete) { + base::test::ScopedFeatureList features; + features.InitAndEnableFeature(kAutofillEnforceMinRequiredFieldsForHeuristics); // Set up our form data. FormData form; form.name = ASCIIToUTF16("MyForm"); @@ -1164,10 +1172,13 @@ EXPECT_FALSE(external_delegate_->on_suggestions_returned_seen()); } -// Test that for form with two fields with one that has an autocomplete -// attribute, suggestions are only made for the one that has the attribute. +// Test that when small forms are disabled (min required fields enforced) +// for a form with two fields with one that has an autocomplete attribute, +// suggestions are only made for the one that has the attribute. TEST_F(AutofillManagerTest, - GetProfileSuggestions_SmallFormWithOneAutocomplete) { + GetProfileSuggestions_MinFieldsEnforced_WithOneAutocomplete) { + base::test::ScopedFeatureList features; + features.InitAndEnableFeature(kAutofillEnforceMinRequiredFieldsForHeuristics); // Set up our form data. FormData form; form.name = ASCIIToUTF16("MyForm"); @@ -1197,10 +1208,84 @@ EXPECT_FALSE(external_delegate_->on_suggestions_returned_seen()); } +// Test that suggestions are returned by default when there are less than +// three fields and none of them have an autocomplete attribute. +TEST_F(AutofillManagerTest, + GetProfileSuggestions_NoMinFieldsEnforced_NoAutocomplete) { + base::test::ScopedFeatureList features; + features.InitAndDisableFeature( + kAutofillEnforceMinRequiredFieldsForHeuristics); + // Set up our form data. + FormData form; + form.name = ASCIIToUTF16("MyForm"); + form.origin = GURL("https://myform.com/form.html"); + form.action = GURL("https://myform.com/submit.html"); + FormFieldData field; + test::CreateTestFormField("First Name", "firstname", "", "text", &field); + form.fields.push_back(field); + test::CreateTestFormField("Last Name", "lastname", "", "text", &field); + form.fields.push_back(field); + + std::vector<FormData> forms(1, form); + FormsSeen(forms); + + // Ensure that autocomplete manager is called for both fields. + MockAutocompleteHistoryManager* m = RecreateMockAutocompleteHistoryManager(); + EXPECT_CALL(*m, OnGetAutocompleteSuggestions(_, _, _, _)).Times(0); + + GetAutofillSuggestions(form, form.fields[0]); + external_delegate_->CheckSuggestions( + kDefaultPageID, Suggestion("Charles", "Charles Hardin Holley", "", 1), + Suggestion("Elvis", "Elvis Aaron Presley", "", 2)); + + GetAutofillSuggestions(form, form.fields[1]); + external_delegate_->CheckSuggestions( + kDefaultPageID, Suggestion("Holley", "Charles Hardin Holley", "", 1), + Suggestion("Presley", "Elvis Aaron Presley", "", 2)); +} + +// Test that for form with two fields with one that has an autocomplete +// attribute, suggestions are made for both if small form support is enabled +// (no mininum number of fields enforced). +TEST_F(AutofillManagerTest, + GetProfileSuggestions_NoMinFieldsEnforced_WithOneAutocomplete) { + base::test::ScopedFeatureList features; + features.InitAndDisableFeature( + kAutofillEnforceMinRequiredFieldsForHeuristics); + // Set up our form data. + FormData form; + form.name = ASCIIToUTF16("MyForm"); + form.origin = GURL("https://myform.com/form.html"); + form.action = GURL("https://myform.com/submit.html"); + FormFieldData field; + test::CreateTestFormField("First Name", "firstname", "", "text", &field); + field.autocomplete_attribute = "given-name"; + form.fields.push_back(field); + test::CreateTestFormField("Last Name", "lastname", "", "text", &field); + field.autocomplete_attribute = ""; + form.fields.push_back(field); + + std::vector<FormData> forms(1, form); + FormsSeen(forms); + + GetAutofillSuggestions(form, form.fields[0]); + external_delegate_->CheckSuggestions( + kDefaultPageID, Suggestion("Charles", "Charles Hardin Holley", "", 1), + Suggestion("Elvis", "Elvis Aaron Presley", "", 2)); + + GetAutofillSuggestions(form, form.fields[1]); + external_delegate_->CheckSuggestions( + kDefaultPageID, Suggestion("Holley", "Charles Hardin Holley", "", 1), + Suggestion("Presley", "Elvis Aaron Presley", "", 2)); +} + // Test that for a form with two fields with autocomplete attributes, -// suggestions are made for both fields. +// suggestions are made for both fields. This is true even if a minimum number +// of fields is enforced. TEST_F(AutofillManagerTest, GetProfileSuggestions_SmallFormWithTwoAutocomplete) { + base::test::ScopedFeatureList features; + features.InitAndEnableFeature(kAutofillEnforceMinRequiredFieldsForHeuristics); // Set up our form data. FormData form; form.name = ASCIIToUTF16("MyForm"); @@ -5658,63 +5743,117 @@ } TEST_F(AutofillManagerTest, ShouldUploadForm) { + // Note: The enforcement of a minimum number of required fields for upload + // is disabled by default. This tests validates both the disabled and enabled + // scenarios. FormData form; form.name = ASCIIToUTF16("TestForm"); form.origin = GURL("http://example.com/form.html"); form.action = GURL("http://example.com/submit.html"); + // Empty Form. + EXPECT_FALSE(autofill_manager_->ShouldUploadForm(FormStructure(form))); + + // Add a field to the form. FormFieldData field; test::CreateTestFormField("Name", "name", "", "text", &field); form.fields.push_back(field); + + // With min required fields enabled. + { + base::test::ScopedFeatureList features; + features.InitAndEnableFeature(kAutofillEnforceMinRequiredFieldsForUpload); + EXPECT_FALSE(autofill_manager_->ShouldUploadForm(FormStructure(form))); + } + + // With min required fields disabled. + { + base::test::ScopedFeatureList features; + features.InitAndDisableFeature(kAutofillEnforceMinRequiredFieldsForUpload); + EXPECT_TRUE(autofill_manager_->ShouldUploadForm(FormStructure(form))); + } + + // Add a second field to the form. test::CreateTestFormField("Email", "email", "", "text", &field); form.fields.push_back(field); - FormStructure form_structure(form); + // With min required fields enabled. + { + base::test::ScopedFeatureList features; + features.InitAndEnableFeature(kAutofillEnforceMinRequiredFieldsForUpload); + EXPECT_FALSE(autofill_manager_->ShouldUploadForm(FormStructure(form))); + } - // Has less than 3 fields. - EXPECT_FALSE(autofill_manager_->ShouldUploadForm(form_structure)); + // With min required fields disabled. + { + base::test::ScopedFeatureList features; + features.InitAndDisableFeature(kAutofillEnforceMinRequiredFieldsForUpload); + EXPECT_TRUE(autofill_manager_->ShouldUploadForm(FormStructure(form))); + } // Has less than 3 fields but has autocomplete attribute. form.fields[0].autocomplete_attribute = "given-name"; - FormStructure form_structure_2(form); - EXPECT_FALSE(autofill_manager_->ShouldUploadForm(form_structure_2)); + + // With min required fields enabled. + { + base::test::ScopedFeatureList features; + features.InitAndEnableFeature(kAutofillEnforceMinRequiredFieldsForUpload); + EXPECT_FALSE(autofill_manager_->ShouldUploadForm(FormStructure(form))); + } + + // With min required fields disabled. + { + base::test::ScopedFeatureList features; + features.InitAndDisableFeature(kAutofillEnforceMinRequiredFieldsForUpload); + EXPECT_TRUE(autofill_manager_->ShouldUploadForm(FormStructure(form))); + } // Has more than 3 fields, no autocomplete attribute. form.fields[0].autocomplete_attribute = ""; test::CreateTestFormField("Country", "country", "", "text", &field); form.fields.push_back(field); FormStructure form_structure_3(form); - EXPECT_TRUE(autofill_manager_->ShouldUploadForm(form_structure_3)); + EXPECT_TRUE(autofill_manager_->ShouldUploadForm(FormStructure(form))); // Has more than 3 fields and at least one autocomplete attribute. form.fields[0].autocomplete_attribute = "given-name"; - FormStructure form_structure_4(form); - EXPECT_TRUE(autofill_manager_->ShouldUploadForm(form_structure_4)); + EXPECT_TRUE(autofill_manager_->ShouldUploadForm(FormStructure(form))); // Is off the record. autofill_driver_->SetIsIncognito(true); - EXPECT_FALSE(autofill_manager_->ShouldUploadForm(form_structure_4)); + EXPECT_FALSE(autofill_manager_->ShouldUploadForm(FormStructure(form))); // Make sure it's reset for the next test case. autofill_driver_->SetIsIncognito(false); - EXPECT_TRUE(autofill_manager_->ShouldUploadForm(form_structure_4)); + EXPECT_TRUE(autofill_manager_->ShouldUploadForm(FormStructure(form))); - // Has one field which is a password field. + // Has one field which is appears to be a password field. form.fields.clear(); - test::CreateTestFormField("Password", "pw", "", "password", &field); + test::CreateTestFormField("Password", "password", "", "password", &field); form.fields.push_back(field); - FormStructure form_structure_5(form); - EXPECT_FALSE(autofill_manager_->ShouldUploadForm(form_structure_5)); + + // With min required fields enabled. + { + base::test::ScopedFeatureList features; + features.InitAndEnableFeature(kAutofillEnforceMinRequiredFieldsForUpload); + EXPECT_FALSE(autofill_manager_->ShouldUploadForm(FormStructure(form))); + } + + // With min required fields disabled. + { + base::test::ScopedFeatureList features; + features.InitAndDisableFeature(kAutofillEnforceMinRequiredFieldsForUpload); + EXPECT_TRUE(autofill_manager_->ShouldUploadForm(FormStructure(form))); + } // Has two fields which are password fields. test::CreateTestFormField("New Password", "new_pw", "", "password", &field); form.fields.push_back(field); - FormStructure form_structure_6(form); - EXPECT_TRUE(autofill_manager_->ShouldUploadForm(form_structure_6)); + EXPECT_TRUE(autofill_manager_->ShouldUploadForm(FormStructure(form))); // Autofill disabled. autofill_manager_->set_autofill_enabled(false); - EXPECT_FALSE(autofill_manager_->ShouldUploadForm(form_structure_3)); + EXPECT_FALSE(autofill_manager_->ShouldUploadForm(FormStructure(form))); } // Verify that no suggestions are shown on desktop for non credit card related @@ -6004,4 +6143,52 @@ uploaded_available_types.find(autofill::PASSWORD)); } +// Test that with small form upload enabled but heuristics and query disabled +// we get uploads but not quality metrics. +TEST_F(AutofillManagerTest, SmallForm_Upload_NoHeuristicsOrQuery) { + // Setup the feature environment. + base::test::ScopedFeatureList features; + features.InitWithFeatures( + // Enabled. + {kAutofillEnforceMinRequiredFieldsForHeuristics, + kAutofillEnforceMinRequiredFieldsForQuery}, + // Disabled. + {kAutofillEnforceMinRequiredFieldsForUpload}); + + // Add a local card to allow data matching for upload votes. + CreditCard credit_card = + autofill::test::GetRandomCreditCard(CreditCard::LOCAL_CARD); + autofill_manager_->AddCreditCard(credit_card); + + // Set up the form. + FormData form; + form.origin = GURL("http://myform.com/form.html"); + form.action = GURL("http://myform.com/submit.html"); + FormFieldData field; + test::CreateTestFormField("Unknown", "unknown", "", "text", &field); + form.fields.push_back(field); + + // Have the browser encounter the form. + FormsSeen({form}); + + // Populate the form with a credit card value. + form.fields.back().value = credit_card.number(); + + // Setup expectation on the test autofill manager (these are validated + // during the simlulated submit). + autofill_manager_->set_expected_submitted_field_types({{CREDIT_CARD_NUMBER}}); + autofill_manager_->set_expected_observed_submission(true); + autofill_manager_->set_call_parent_upload_form_data(true); + EXPECT_CALL(*download_manager_, + StartUploadRequest(_, false, _, std::string(), true)); + + base::HistogramTester histogram_tester; + FormSubmitted(form); + + EXPECT_EQ(FormStructure(form).FormSignatureAsStr(), + autofill_manager_->GetSubmittedFormSignature()); + + histogram_tester.ExpectTotalCount("Autofill.FieldPrediction.CreditCard", 0); +} + } // namespace autofill
diff --git a/components/autofill/core/browser/autofill_merge_unittest.cc b/components/autofill/core/browser/autofill_merge_unittest.cc index 3d10faf..ce993ac6 100644 --- a/components/autofill/core/browser/autofill_merge_unittest.cc +++ b/components/autofill/core/browser/autofill_merge_unittest.cc
@@ -297,7 +297,9 @@ } TEST_P(AutofillMergeTest, DataDrivenMergeProfiles) { - RunOneDataDrivenTest(GetParam(), GetOutputDirectory(kTestName)); + const bool kIsExpectedToPass = true; + RunOneDataDrivenTest(GetParam(), GetOutputDirectory(kTestName), + kIsExpectedToPass); } INSTANTIATE_TEST_CASE_P(, AutofillMergeTest, testing::ValuesIn(GetTestFiles()));
diff --git a/components/autofill/core/browser/autofill_metrics.cc b/components/autofill/core/browser/autofill_metrics.cc index bd87453..5ffd70c 100644 --- a/components/autofill/core/browser/autofill_metrics.cc +++ b/components/autofill/core/browser/autofill_metrics.cc
@@ -477,6 +477,30 @@ KMaxFieldTypeGroupMetric); } +AutofillMetrics::FormEvent GetCardNumberStatusFormEvent( + const AutofillMetrics::CardNumberStatus card_number_status) { + switch (card_number_status) { + case AutofillMetrics::EMPTY_CARD: + return AutofillMetrics:: + FORM_EVENT_SUBMIT_WITHOUT_SELECTING_SUGGESTIONS_NO_CARD; + case AutofillMetrics::WRONG_SIZE_CARD: + return AutofillMetrics:: + FORM_EVENT_SUBMIT_WITHOUT_SELECTING_SUGGESTIONS_WRONG_SIZE_CARD; + case AutofillMetrics::FAIL_LUHN_CHECK_CARD: + return AutofillMetrics:: + FORM_EVENT_SUBMIT_WITHOUT_SELECTING_SUGGESTIONS_FAIL_LUHN_CHECK_CARD; + case AutofillMetrics::KNOWN_CARD: + return AutofillMetrics:: + FORM_EVENT_SUBMIT_WITHOUT_SELECTING_SUGGESTIONS_KNOWN_CARD; + case AutofillMetrics::UNKNOWN_CARD: + return AutofillMetrics:: + FORM_EVENT_SUBMIT_WITHOUT_SELECTING_SUGGESTIONS_UNKNOWN_CARD; + } + NOTREACHED(); + return AutofillMetrics:: + FORM_EVENT_SUBMIT_WITHOUT_SELECTING_SUGGESTIONS_NO_CARD; +} + } // namespace // static @@ -1162,8 +1186,6 @@ has_logged_will_submit_(false), has_logged_submitted_(false), has_logged_bank_name_available_(false), - has_logged_detected_card_in_submitted_form_(false), - has_logged_submitted_known_card(false), logged_suggestion_filled_was_server_data_(false), logged_suggestion_filled_was_masked_server_card_(false), form_interactions_ukm_logger_(form_interactions_ukm_logger) {} @@ -1328,7 +1350,9 @@ base::RecordAction(base::UserMetricsAction("Autofill_OnWillSubmitForm")); } -void AutofillMetrics::FormEventLogger::OnFormSubmitted(bool force_logging) { +void AutofillMetrics::FormEventLogger::OnFormSubmitted( + bool force_logging, + const CardNumberStatus card_number_status) { // Not logging this kind of form if we haven't logged a user interaction. if (!has_logged_interacted_) return; @@ -1352,16 +1376,7 @@ if (has_logged_suggestions_shown_ || force_logging) { Log(AutofillMetrics::FORM_EVENT_SUGGESTION_SHOWN_SUBMITTED_ONCE); if (is_for_credit_card_ && !has_logged_suggestion_filled_) { - if (!has_logged_detected_card_in_submitted_form_) { - Log(AutofillMetrics:: - FORM_EVENT_SUBMIT_WITHOUT_SELECTING_SUGGESTIONS_NO_CARD); - } else if (has_logged_submitted_known_card) { - Log(AutofillMetrics:: - FORM_EVENT_SUBMIT_WITHOUT_SELECTING_SUGGESTIONS_KNOWN_CARD); - } else { - Log(AutofillMetrics:: - FORM_EVENT_SUBMIT_WITHOUT_SELECTING_SUGGESTIONS_UNKNOWN_CARD); - } + Log(GetCardNumberStatusFormEvent(card_number_status)); } } } @@ -1370,14 +1385,6 @@ has_logged_bank_name_available_ = true; } -void AutofillMetrics::FormEventLogger::DetectedCardInSubmittedForm() { - has_logged_detected_card_in_submitted_form_ = true; -} - -void AutofillMetrics::FormEventLogger::SubmittedKnownCard() { - has_logged_submitted_known_card = true; -} - void AutofillMetrics::FormEventLogger::Log(FormEvent event) const { DCHECK_LT(event, NUM_FORM_EVENTS); std::string name("Autofill.FormEvents.");
diff --git a/components/autofill/core/browser/autofill_metrics.h b/components/autofill/core/browser/autofill_metrics.h index 1d24bee..f3c6192 100644 --- a/components/autofill/core/browser/autofill_metrics.h +++ b/components/autofill/core/browser/autofill_metrics.h
@@ -432,16 +432,28 @@ // A dropdown with credit card suggestions was shown, but they were not used // to fill the form. Depending on the user submitting a card known by the // browser, submitting a card that the browser does not know about, - // or Autofill failing to detect the card, one of the following will be - // triggered. Only one of the following three metrics will be triggered per - // page load. + // submitting with an empty card number, submitting with a card number of + // wrong size or submitting with a card number that does not pass luhn + // check, one of the following will be triggered. At most one of the + // following five metrics will be triggered per submit. FORM_EVENT_SUBMIT_WITHOUT_SELECTING_SUGGESTIONS_KNOWN_CARD, FORM_EVENT_SUBMIT_WITHOUT_SELECTING_SUGGESTIONS_UNKNOWN_CARD, FORM_EVENT_SUBMIT_WITHOUT_SELECTING_SUGGESTIONS_NO_CARD, + FORM_EVENT_SUBMIT_WITHOUT_SELECTING_SUGGESTIONS_WRONG_SIZE_CARD, + FORM_EVENT_SUBMIT_WITHOUT_SELECTING_SUGGESTIONS_FAIL_LUHN_CHECK_CARD, NUM_FORM_EVENTS, }; + // Indicates submitted card information. + enum CardNumberStatus { + EMPTY_CARD, + WRONG_SIZE_CARD, + FAIL_LUHN_CHECK_CARD, + KNOWN_CARD, + UNKNOWN_CARD + }; + // Form Events for autofill with bank name available for display. enum BankNameDisplayedFormEvent { // A dropdown with suggestions was shown and at least one suggestion has a @@ -925,14 +937,11 @@ void OnWillSubmitForm(); - void OnFormSubmitted(bool force_logging); + void OnFormSubmitted(bool force_logging, + const CardNumberStatus card_number_status); void SetBankNameAvailable(); - void DetectedCardInSubmittedForm(); - - void SubmittedKnownCard(); - private: void Log(FormEvent event) const; void Log(BankNameDisplayedFormEvent event) const; @@ -948,8 +957,6 @@ bool has_logged_will_submit_; bool has_logged_submitted_; bool has_logged_bank_name_available_; - bool has_logged_detected_card_in_submitted_form_; - bool has_logged_submitted_known_card; bool logged_suggestion_filled_was_server_data_; bool logged_suggestion_filled_was_masked_server_card_;
diff --git a/components/autofill/core/browser/autofill_metrics_unittest.cc b/components/autofill/core/browser/autofill_metrics_unittest.cc index eef7def..180e74f0 100644 --- a/components/autofill/core/browser/autofill_metrics_unittest.cc +++ b/components/autofill/core/browser/autofill_metrics_unittest.cc
@@ -32,6 +32,7 @@ #include "components/autofill/core/browser/test_autofill_driver.h" #include "components/autofill/core/browser/webdata/autofill_webdata_service.h" #include "components/autofill/core/common/autofill_clock.h" +#include "components/autofill/core/common/autofill_features.h" #include "components/autofill/core/common/form_data.h" #include "components/autofill/core/common/form_field_data.h" #include "components/prefs/pref_service.h" @@ -48,6 +49,9 @@ #include "ui/gfx/geometry/rect.h" #include "url/gurl.h" +using autofill::features::kAutofillEnforceMinRequiredFieldsForHeuristics; +using autofill::features::kAutofillEnforceMinRequiredFieldsForQuery; +using autofill::features::kAutofillEnforceMinRequiredFieldsForUpload; using base::ASCIIToUTF16; using base::Bucket; using base::TimeTicks; @@ -1441,29 +1445,31 @@ // Verify that when a field is annotated with the autocomplete attribute, its // predicted type is remembered when quality metrics are logged. TEST_F(AutofillMetricsTest, PredictedMetricsWithAutocomplete) { - // Set up our form data. + // Allow heuristics to run (and be accepted) for small forms. + base::test::ScopedFeatureList feature_list; + feature_list.InitAndDisableFeature( + kAutofillEnforceMinRequiredFieldsForHeuristics); + + // Set up our form data. Note that the fields have default values not found + // in the user profiles. They will be changed between the time the form is + // seen/parsed, and the time it is submitted. FormData form; + FormFieldData field; form.name = ASCIIToUTF16("TestForm"); form.origin = GURL("http://example.com/form.html"); form.action = GURL("http://example.com/submit.html"); form.main_frame_origin = url::Origin::Create(GURL("http://example_root.com/form.html")); - FormFieldData field1; - test::CreateTestFormField("Select", "select", "USA", "select-one", &field1); - field1.autocomplete_attribute = "country"; - form.fields.push_back(field1); + test::CreateTestFormField("Select", "select", "USA", "select-one", &field); + form.fields.push_back(field); + form.fields.back().autocomplete_attribute = "country"; - // Two other fields to have the minimum of 3 to be parsed by autofill. Note - // that they have default values not found in the user profiles. They will be - // changed between the time the form is seen/parsed, and the time it is - // submitted. - FormFieldData field2; - test::CreateTestFormField("Unknown", "Unknown", "", "text", &field2); - form.fields.push_back(field2); - FormFieldData field3; - test::CreateTestFormField("Phone", "phone", "", "tel", &field3); - form.fields.push_back(field3); + test::CreateTestFormField("Unknown", "Unknown", "", "text", &field); + form.fields.push_back(field); + + test::CreateTestFormField("Phone", "phone", "", "tel", &field); + form.fields.push_back(field); std::vector<FormData> forms(1, form); @@ -1481,26 +1487,39 @@ std::string histogram_name = "Autofill.FieldPredictionQuality.ByFieldType." + source; // First verify that country was not predicted by client or server. - histogram_tester.ExpectBucketCount( - histogram_name, - GetFieldTypeGroupMetric(ADDRESS_HOME_COUNTRY, - source == "Overall" - ? AutofillMetrics::TRUE_POSITIVE - : AutofillMetrics::FALSE_NEGATIVE_UNKNOWN), - 1); + { + SCOPED_TRACE("ADDRESS_HOME_COUNTRY"); + histogram_tester.ExpectBucketCount( + histogram_name, + GetFieldTypeGroupMetric( + ADDRESS_HOME_COUNTRY, + source == "Overall" ? AutofillMetrics::TRUE_POSITIVE + : AutofillMetrics::FALSE_NEGATIVE_UNKNOWN), + 1); + } - // We did not predict zip code or phone number, because they did not have - // |autocomplete_attribute|, nor client or server predictions. - histogram_tester.ExpectBucketCount( - histogram_name, - GetFieldTypeGroupMetric(ADDRESS_HOME_ZIP, - AutofillMetrics::FALSE_NEGATIVE_UNKNOWN), - 1); - histogram_tester.ExpectBucketCount( - histogram_name, - GetFieldTypeGroupMetric(PHONE_HOME_WHOLE_NUMBER, - AutofillMetrics::FALSE_NEGATIVE_UNKNOWN), - 1); + // We did not predict zip code because it did not have an autocomplete + // attribute, nor client or server predictions. + { + SCOPED_TRACE("ADDRESS_HOME_ZIP"); + histogram_tester.ExpectBucketCount( + histogram_name, + GetFieldTypeGroupMetric(ADDRESS_HOME_ZIP, + AutofillMetrics::FALSE_NEGATIVE_UNKNOWN), + 1); + } + + // Phone should have been predicted by the heuristics but not the server. + { + SCOPED_TRACE("PHONE_HOME_WHOLE_NUMBER"); + histogram_tester.ExpectBucketCount( + histogram_name, + GetFieldTypeGroupMetric(PHONE_HOME_WHOLE_NUMBER, + source == "Server" + ? AutofillMetrics::FALSE_NEGATIVE_UNKNOWN + : AutofillMetrics::TRUE_POSITIVE), + 1); + } // Sanity check. histogram_tester.ExpectTotalCount(histogram_name, 3); @@ -1641,6 +1660,8 @@ // Verify that when submitting a non-autofillable form, the stored profile // metric is not logged. TEST_F(AutofillMetricsTest, StoredProfileCountNonAutofillableFormSubmission) { + base::test::ScopedFeatureList features; + features.InitAndEnableFeature(kAutofillEnforceMinRequiredFieldsForHeuristics); // Construct a non-fillable form. FormData form; form.name = ASCIIToUTF16("TestForm"); @@ -1793,7 +1814,8 @@ std::vector<FormData> forms(1, form); - // Ensure no metrics are logged when loading a non-fillable form. + // Ensure no metrics are logged when small form support is disabled (min + // number of fields enforced). { base::HistogramTester histogram_tester; autofill_manager_->OnFormsSeen(forms, TimeTicks()); @@ -1801,6 +1823,19 @@ histogram_tester.ExpectTotalCount("Autofill.DeveloperEngagement", 0); } + // Otherwise, log developer engagement for all forms. + { + base::test::ScopedFeatureList features; + features.InitAndDisableFeature( + kAutofillEnforceMinRequiredFieldsForHeuristics); + base::HistogramTester histogram_tester; + autofill_manager_->OnFormsSeen(forms, TimeTicks()); + autofill_manager_->Reset(); + histogram_tester.ExpectUniqueSample( + "Autofill.DeveloperEngagement", + AutofillMetrics::FILLABLE_FORM_PARSED_WITHOUT_TYPE_HINTS, 1); + } + // Add another field to the form, so that it becomes fillable. test::CreateTestFormField("Phone", "phone", "", "text", &field); forms.back().fields.push_back(field); @@ -1886,6 +1921,9 @@ // Ensure no metrics are logged when loading a non-fillable form. { + base::test::ScopedFeatureList features; + features.InitAndEnableFeature( + kAutofillEnforceMinRequiredFieldsForHeuristics); autofill_manager_->OnFormsSeen(forms, TimeTicks::Now()); autofill_manager_->Reset(); @@ -1966,6 +2004,14 @@ // Verify that we correctly log UKM for form parsed with type hints regarding // developer engagement. TEST_F(AutofillMetricsTest, UkmDeveloperEngagement_LogUpiVpaTypeHint) { + base::test::ScopedFeatureList feature_list; + feature_list.InitWithFeatures( + // Enabled. + {kAutofillEnforceMinRequiredFieldsForHeuristics, + kAutofillEnforceMinRequiredFieldsForQuery, + kAutofillEnforceMinRequiredFieldsForUpload}, + // Disabled. + {}); FormData form; form.name = ASCIIToUTF16("TestForm"); form.origin = GURL("http://example.com/form.html"); @@ -1987,6 +2033,7 @@ // Expect the "upi-vpa hint" metric to be logged and the "form loaded" form // interaction event to be logged. { + SCOPED_TRACE("VPA is the only hint"); autofill_manager_->OnFormsSeen(forms, TimeTicks::Now()); autofill_manager_->Reset(); @@ -2003,6 +2050,7 @@ forms.back().fields.push_back(field); { + SCOPED_TRACE("VPA and other autocomplete hint present"); autofill_manager_->OnFormsSeen(forms, TimeTicks::Now()); autofill_manager_->Reset(); @@ -3271,6 +3319,93 @@ } TEST_F(AutofillMetricsTest, + CreditCardSubmittedWithoutSelectingSuggestionsWrongSizeCard) { + EnableWalletSync(); + // Create a local card for testing, card number is 4111111111111111. + personal_data_->RecreateCreditCards( + true /* include_local_credit_card */, + false /* include_masked_server_credit_card */, + false /* include_full_server_credit_card */); + + // Set up our form data. + FormData form; + form.name = ASCIIToUTF16("TestForm"); + form.origin = GURL("http://example.com/form.html"); + form.action = GURL("http://example.com/submit.html"); + + FormFieldData field; + std::vector<ServerFieldType> field_types; + test::CreateTestFormField("Month", "card_month", "", "text", &field); + form.fields.push_back(field); + field_types.push_back(CREDIT_CARD_EXP_MONTH); + test::CreateTestFormField("Year", "card_year", "", "text", &field); + form.fields.push_back(field); + field_types.push_back(CREDIT_CARD_EXP_2_DIGIT_YEAR); + test::CreateTestFormField("Credit card", "card", "411111111", "text", &field); + form.fields.push_back(field); + field_types.push_back(CREDIT_CARD_NUMBER); + + // Simulate having seen this form on page load. + // |form_structure| will be owned by |autofill_manager_|. + autofill_manager_->AddSeenForm(form, field_types, field_types); + + // Simulating submission with suggestion shown, but not selected. + base::HistogramTester histogram_tester; + autofill_manager_->DidShowSuggestions(true /* is_new_popup */, form, field); + autofill_manager_->OnQueryFormFieldAutofill(0, form, field, gfx::RectF()); + autofill_manager_->SubmitForm(form, TimeTicks::Now()); + histogram_tester.ExpectBucketCount( + "Autofill.FormEvents.CreditCard", + AutofillMetrics:: + FORM_EVENT_SUBMIT_WITHOUT_SELECTING_SUGGESTIONS_WRONG_SIZE_CARD, + 1); +} + +TEST_F(AutofillMetricsTest, + CreditCardSubmittedWithoutSelectingSuggestionsFailLuhnCheckCard) { + EnableWalletSync(); + // Create a local card for testing, card number is 4111111111111111. + personal_data_->RecreateCreditCards( + true /* include_local_credit_card */, + false /* include_masked_server_credit_card */, + false /* include_full_server_credit_card */); + + // Set up our form data. + FormData form; + form.name = ASCIIToUTF16("TestForm"); + form.origin = GURL("http://example.com/form.html"); + form.action = GURL("http://example.com/submit.html"); + + FormFieldData field; + std::vector<ServerFieldType> field_types; + test::CreateTestFormField("Month", "card_month", "", "text", &field); + form.fields.push_back(field); + field_types.push_back(CREDIT_CARD_EXP_MONTH); + test::CreateTestFormField("Year", "card_year", "", "text", &field); + form.fields.push_back(field); + field_types.push_back(CREDIT_CARD_EXP_2_DIGIT_YEAR); + test::CreateTestFormField("Credit card", "card", "4444444444444444", "text", + &field); + form.fields.push_back(field); + field_types.push_back(CREDIT_CARD_NUMBER); + + // Simulate having seen this form on page load. + // |form_structure| will be owned by |autofill_manager_|. + autofill_manager_->AddSeenForm(form, field_types, field_types); + + // Simulating submission with suggestion shown, but not selected. + base::HistogramTester histogram_tester; + autofill_manager_->DidShowSuggestions(true /* is_new_popup */, form, field); + autofill_manager_->OnQueryFormFieldAutofill(0, form, field, gfx::RectF()); + autofill_manager_->SubmitForm(form, TimeTicks::Now()); + histogram_tester.ExpectBucketCount( + "Autofill.FormEvents.CreditCard", + AutofillMetrics:: + FORM_EVENT_SUBMIT_WITHOUT_SELECTING_SUGGESTIONS_FAIL_LUHN_CHECK_CARD, + 1); +} + +TEST_F(AutofillMetricsTest, CreditCardSubmittedWithoutSelectingSuggestionsUnknownCard) { EnableWalletSync(); // Create a local card for testing, card number is 4111111111111111. @@ -4886,8 +5021,8 @@ } // Non fillable form. - form.fields[0].value = ASCIIToUTF16("Elvis Aaron Presley"); - form.fields[1].value = ASCIIToUTF16("theking@gmail.com"); + form.fields[0].value = ASCIIToUTF16("Unknown Person"); + form.fields[1].value = ASCIIToUTF16("unknown.person@gmail.com"); forms.front() = form; { @@ -4914,7 +5049,9 @@ expected_field_fill_status_ukm_metrics); } - // Fill in the third field. + // Fillable form. + form.fields[0].value = ASCIIToUTF16("Elvis Aaron Presley"); + form.fields[1].value = ASCIIToUTF16("theking@gmail.com"); form.fields[2].value = ASCIIToUTF16("12345678901"); forms.front() = form; @@ -5044,8 +5181,12 @@ form.fields[2].value = base::string16(); forms.front() = form; - // Non fillable form. + // This form is non-fillable if small form support is disabled (min number + // of fields enforced.) { + base::test::ScopedFeatureList features; + features.InitAndEnableFeature( + kAutofillEnforceMinRequiredFieldsForHeuristics); base::HistogramTester histogram_tester; base::UserActionTester user_action_tester; autofill_manager_->SubmitForm(form, TimeTicks::Now()); @@ -5234,7 +5375,7 @@ form.main_frame_origin = url::Origin::Create(GURL("http://example_root.com/form.html")); - // Construct a valid credit card form with minimal fields. + // Construct a valid credit card form. FormFieldData field; std::vector<ServerFieldType> field_types; test::CreateTestFormField("Card Number", "card_number", "", "text", &field); @@ -5251,6 +5392,7 @@ // Expect a notification when the form is first seen. { + SCOPED_TRACE("First seen"); base::HistogramTester histogram_tester; autofill_manager_->OnFormsSeen(forms, TimeTicks()); histogram_tester.ExpectUniqueSample("Autofill.UserHappiness", @@ -5261,6 +5403,7 @@ // Simulate typing. { + SCOPED_TRACE("Initial typing"); base::HistogramTester histogram_tester; autofill_manager_->OnTextFieldDidChange(form, form.fields.front(), gfx::RectF(), TimeTicks()); @@ -5275,6 +5418,7 @@ // Simulate suggestions shown twice with separate popups. { + SCOPED_TRACE("Separate pop-ups"); base::HistogramTester histogram_tester; autofill_manager_->DidShowSuggestions(true, form, field); autofill_manager_->DidShowSuggestions(true, form, field); @@ -5295,6 +5439,7 @@ // Simulate suggestions shown twice for a single edit (i.e. multiple // keystrokes in a single field). { + SCOPED_TRACE("Multiple keystrokes"); base::HistogramTester histogram_tester; autofill_manager_->DidShowSuggestions(true, form, field); autofill_manager_->DidShowSuggestions(false, form, field); @@ -5311,6 +5456,7 @@ // Simulate suggestions shown for a different field. { + SCOPED_TRACE("Different field"); base::HistogramTester histogram_tester; autofill_manager_->DidShowSuggestions(true, form, form.fields[1]); histogram_tester.ExpectUniqueSample("Autofill.UserHappiness", @@ -5321,6 +5467,7 @@ // Simulate invoking autofill. { + SCOPED_TRACE("Invoke autofill"); base::HistogramTester histogram_tester; autofill_manager_->OnDidFillAutofillFormData(form, TimeTicks()); histogram_tester.ExpectBucketCount("Autofill.UserHappiness", @@ -5336,6 +5483,7 @@ // Simulate editing an autofilled field. { + SCOPED_TRACE("Edit autofilled field"); base::HistogramTester histogram_tester; std::string guid("10000000-0000-0000-0000-000000000001"); autofill_manager_->FillOrPreviewForm( @@ -5362,6 +5510,7 @@ // Simulate invoking autofill again. { + SCOPED_TRACE("Invoke autofill again"); base::HistogramTester histogram_tester; autofill_manager_->OnDidFillAutofillFormData(form, TimeTicks()); histogram_tester.ExpectUniqueSample("Autofill.UserHappiness", @@ -5372,6 +5521,7 @@ // Simulate editing another autofilled field. { + SCOPED_TRACE("Edit another autofilled field"); base::HistogramTester histogram_tester; autofill_manager_->OnTextFieldDidChange(form, form.fields[1], gfx::RectF(), TimeTicks());
diff --git a/components/autofill/core/browser/data_driven_test.cc b/components/autofill/core/browser/data_driven_test.cc index 7f9c52b..d30b91f 100644 --- a/components/autofill/core/browser/data_driven_test.cc +++ b/components/autofill/core/browser/data_driven_test.cc
@@ -43,17 +43,18 @@ false, base::FileEnumerator::FILES, file_name_pattern); - + const bool kIsExpectedToPass = true; for (base::FilePath input_file = input_files.Next(); !input_file.empty(); input_file = input_files.Next()) { - RunOneDataDrivenTest(input_file, output_directory); + RunOneDataDrivenTest(input_file, output_directory, kIsExpectedToPass); } } void DataDrivenTest::RunOneDataDrivenTest( const base::FilePath& test_file_name, - const base::FilePath& output_directory) { + const base::FilePath& output_directory, + bool is_expected_to_pass) { base::ScopedAllowBlockingForTesting allow_blocking; // iOS doesn't get rid of removed test files. TODO(estade): remove this after // all iOS bots are clobbered. @@ -76,28 +77,30 @@ FILE_PATH_LITERAL(".out"))); std::string output_file_contents; - if (ReadFile(output_file, &output_file_contents)) - EXPECT_EQ(output_file_contents, output); - else + if (!ReadFile(output_file, &output_file_contents)) { ASSERT_TRUE(WriteFile(output_file, output)); + return; + } + + if (is_expected_to_pass) { + EXPECT_EQ(output_file_contents, output); + } else { + EXPECT_NE(output_file_contents, output); + } } base::FilePath DataDrivenTest::GetInputDirectory( const base::FilePath::StringType& test_name) { - base::FilePath dir; - dir = test_data_directory_.AppendASCII("autofill") - .Append(test_name) - .AppendASCII("input"); - return dir; + return test_data_directory_.AppendASCII("autofill") + .Append(test_name) + .AppendASCII("input"); } base::FilePath DataDrivenTest::GetOutputDirectory( const base::FilePath::StringType& test_name) { - base::FilePath dir; - dir = test_data_directory_.AppendASCII("autofill") - .Append(test_name) - .AppendASCII("output"); - return dir; + return test_data_directory_.AppendASCII("autofill") + .Append(test_name) + .AppendASCII("output"); } DataDrivenTest::DataDrivenTest(const base::FilePath& test_data_directory)
diff --git a/components/autofill/core/browser/data_driven_test.h b/components/autofill/core/browser/data_driven_test.h index 8249916..12b98adb 100644 --- a/components/autofill/core/browser/data_driven_test.h +++ b/components/autofill/core/browser/data_driven_test.h
@@ -32,7 +32,8 @@ // As above, but runs a test for a single file, the full path of which is // given by |test_file_name|. void RunOneDataDrivenTest(const base::FilePath& test_file_name, - const base::FilePath& output_directory); + const base::FilePath& output_directory, + bool is_expected_to_pass); // Given the |input| data, generates the |output| results. The output results // must be stable across runs.
diff --git a/components/autofill/core/browser/form_field.cc b/components/autofill/core/browser/form_field.cc index a1997eb..b9329ef 100644 --- a/components/autofill/core/browser/form_field.cc +++ b/components/autofill/core/browser/form_field.cc
@@ -23,6 +23,7 @@ #include "components/autofill/core/browser/form_structure.h" #include "components/autofill/core/browser/name_field.h" #include "components/autofill/core/browser/phone_field.h" +#include "components/autofill/core/common/autofill_constants.h" #include "components/autofill/core/common/autofill_regexes.h" #include "components/autofill/core/common/autofill_util.h" @@ -75,13 +76,14 @@ // Name pass. ParseFormFieldsPass(NameField::Parse, processed_fields, &field_candidates); - // Do not autofill a form if there are less than 3 recognized fields. - // Otherwise it is very easy to have false positives. http://crbug.com/447332 - // For <form> tags, make an exception for email fields, which are commonly the - // only recognized field on account registration sites. - static const size_t kThreshold = 3; - const bool accept_parsing = (field_candidates.size() >= kThreshold || - (is_form_tag && email_count > 0)); + // Do not autofill a form if there aren't enough fields. Otherwise, it is + // very easy to have false positives. See http://crbug.com/447332 + // For <form> tags, make an exception for email fields, which are commonly + // the only recognized field on account registration sites. + const bool accept_parsing = + field_candidates.size() >= MinRequiredFieldsForHeuristics() || + (is_form_tag && email_count > 0); + if (!accept_parsing) field_candidates.clear();
diff --git a/components/autofill/core/browser/form_field_unittest.cc b/components/autofill/core/browser/form_field_unittest.cc index 3fd473d..a5f89c7b 100644 --- a/components/autofill/core/browser/form_field_unittest.cc +++ b/components/autofill/core/browser/form_field_unittest.cc
@@ -7,11 +7,14 @@ #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" +#include "base/test/scoped_feature_list.h" #include "components/autofill/core/browser/autofill_field.h" #include "components/autofill/core/browser/form_field.h" +#include "components/autofill/core/common/autofill_features.h" #include "testing/gtest/include/gtest/gtest.h" using base::ASCIIToUTF16; +using autofill::features::kAutofillEnforceMinRequiredFieldsForHeuristics; namespace autofill { @@ -130,40 +133,65 @@ FormFieldData field_data; field_data.form_control_type = "text"; - field_data.label = ASCIIToUTF16("Address line1"); - fields.push_back( - std::make_unique<AutofillField>(field_data, field_data.label)); - field_data.check_status = FormFieldData::CHECKABLE_BUT_UNCHECKED; field_data.label = ASCIIToUTF16("Is PO Box"); fields.push_back( std::make_unique<AutofillField>(field_data, field_data.label)); + // Does not parse since there are only field and it's checkable. + EXPECT_TRUE(FormField::ParseFormFields(fields, true).empty()); + // reset |is_checkable| to false. field_data.check_status = FormFieldData::NOT_CHECKABLE; + field_data.label = ASCIIToUTF16("Address line1"); + fields.push_back( + std::make_unique<AutofillField>(field_data, field_data.label)); + + // Parse a single address line 1 field. + { + base::test::ScopedFeatureList enforce_min_fields; + enforce_min_fields.InitAndEnableFeature( + kAutofillEnforceMinRequiredFieldsForHeuristics); + ASSERT_EQ(0u, FormField::ParseFormFields(fields, true).size()); + } + { + base::test::ScopedFeatureList do_not_enforce_min_fields; + do_not_enforce_min_fields.InitAndDisableFeature( + kAutofillEnforceMinRequiredFieldsForHeuristics); + const FieldCandidatesMap field_candidates_map = + FormField::ParseFormFields(fields, true); + ASSERT_EQ(1u, field_candidates_map.size()); + EXPECT_EQ(ADDRESS_HOME_LINE1, + field_candidates_map.find(ASCIIToUTF16("Address line1")) + ->second.BestHeuristicType()); + } + + // Parses address line 1 and 2. field_data.label = ASCIIToUTF16("Address line2"); fields.push_back( std::make_unique<AutofillField>(field_data, field_data.label)); - // Does not parse since there are only 2 recognized fields. - ASSERT_TRUE(FormField::ParseFormFields(fields, true).empty()); - - field_data.label = ASCIIToUTF16("City"); - fields.push_back( - std::make_unique<AutofillField>(field_data, field_data.label)); - - // Checkable element shouldn't interfere with inference of Address line2. - const FieldCandidatesMap field_candidates_map = - FormField::ParseFormFields(fields, true); - ASSERT_EQ(3U, field_candidates_map.size()); - - EXPECT_EQ(ADDRESS_HOME_LINE1, - field_candidates_map.find(ASCIIToUTF16("Address line1")) - ->second.BestHeuristicType()); - EXPECT_EQ(ADDRESS_HOME_LINE2, - field_candidates_map.find(ASCIIToUTF16("Address line2")) - ->second.BestHeuristicType()); + { + base::test::ScopedFeatureList enforce_min_fields; + enforce_min_fields.InitAndEnableFeature( + kAutofillEnforceMinRequiredFieldsForHeuristics); + ASSERT_EQ(0u, FormField::ParseFormFields(fields, true).size()); + } + { + base::test::ScopedFeatureList do_not_enforce_min_fields; + do_not_enforce_min_fields.InitAndDisableFeature( + kAutofillEnforceMinRequiredFieldsForHeuristics); + const FieldCandidatesMap field_candidates_map = + FormField::ParseFormFields(fields, true); + ASSERT_EQ(2u, field_candidates_map.size()); + EXPECT_EQ(ADDRESS_HOME_LINE1, + field_candidates_map.find(ASCIIToUTF16("Address line1")) + ->second.BestHeuristicType()); + EXPECT_EQ(ADDRESS_HOME_LINE2, + field_candidates_map.find(ASCIIToUTF16("Address line2")) + ->second.BestHeuristicType()); + } } // All parsers see the same form and should not modify it.
diff --git a/components/autofill/core/browser/form_structure.cc b/components/autofill/core/browser/form_structure.cc index 03721663..972c782 100644 --- a/components/autofill/core/browser/form_structure.cc +++ b/components/autofill/core/browser/form_structure.cc
@@ -319,7 +319,7 @@ has_password_field_(false), is_form_tag_(form.is_form_tag), is_formless_checkout_(form.is_formless_checkout), - all_fields_are_passwords_(true), + all_fields_are_passwords_(!form.fields.empty()), is_signin_upload_(false) { // Copy the form fields. std::map<base::string16, size_t> unique_names; @@ -359,14 +359,14 @@ // Then if there are enough active fields, and if we are dealing with either a // proper <form> or a <form>-less checkout, run the heuristics and server // prediction routines. - if (active_field_count() >= kRequiredFieldsForPredictionRoutines && - (is_form_tag_ || is_formless_checkout_)) { + if (ShouldRunHeuristics()) { const FieldCandidatesMap field_type_map = FormField::ParseFormFields(fields_, is_form_tag_); for (const auto& field : fields_) { const auto iter = field_type_map.find(field->unique_name()); - if (iter != field_type_map.end()) + if (iter != field_type_map.end()) { field->set_heuristic_type(iter->second.BestHeuristicType()); + } } } @@ -408,7 +408,7 @@ const std::string& login_form_signature, bool observed_submission, AutofillUploadContents* upload) const { - DCHECK(ShouldBeCrowdsourced()); + DCHECK(ShouldBeUploaded()); DCHECK(AllTypesCaptured(*this, available_field_types)); upload->set_submission(observed_submission); @@ -601,7 +601,10 @@ } bool FormStructure::IsAutofillable() const { - if (autofill_count() < kRequiredFieldsForPredictionRoutines) + size_t min_required_fields = + std::min({MinRequiredFieldsForHeuristics(), MinRequiredFieldsForQuery(), + MinRequiredFieldsForUpload()}); + if (autofill_count() < min_required_fields) return false; return ShouldBeParsed(); @@ -632,7 +635,10 @@ } bool FormStructure::ShouldBeParsed() const { - if (active_field_count() < kRequiredFieldsForPredictionRoutines && + size_t min_required_fields = + std::min({MinRequiredFieldsForHeuristics(), MinRequiredFieldsForQuery(), + MinRequiredFieldsForUpload()}); + if (active_field_count() < min_required_fields && (!all_fields_are_passwords() || active_field_count() < kRequiredFieldsForFormsWithOnlyPasswordFields) && !is_signin_upload_ && !has_author_specified_types_) { @@ -642,8 +648,9 @@ // Rule out http(s)://*/search?... // e.g. http://www.google.com/search?q=... // http://search.yahoo.com/search?p=... - if (target_url_.path_piece() == "/search") + if (target_url_.path_piece() == "/search") { return false; + } bool has_text_field = false; for (const auto& it : *this) { @@ -653,9 +660,20 @@ return has_text_field; } -bool FormStructure::ShouldBeCrowdsourced() const { +bool FormStructure::ShouldRunHeuristics() const { + return active_field_count() >= MinRequiredFieldsForHeuristics() && + (is_form_tag_ || is_formless_checkout_); +} + +bool FormStructure::ShouldBeQueried() const { return (has_password_field_ || - active_field_count() >= kRequiredFieldsForPredictionRoutines) && + active_field_count() >= MinRequiredFieldsForQuery()) && + ShouldBeParsed(); +} + +bool FormStructure::ShouldBeUploaded() const { + return (has_password_field_ || + active_field_count() >= MinRequiredFieldsForUpload()) && ShouldBeParsed(); } @@ -771,7 +789,8 @@ // submission event. if (observed_submission) { AutofillMetrics::AutofillFormSubmittedState state; - if (num_detected_field_types < kRequiredFieldsForPredictionRoutines) { + if (num_detected_field_types < MinRequiredFieldsForHeuristics() && + num_detected_field_types < MinRequiredFieldsForQuery()) { state = AutofillMetrics::NON_FILLABLE_FORM_OR_NEW_DATA; } else { if (did_autofill_all_possible_fields) { @@ -860,7 +879,8 @@ // type hint or whether autocomplete should be enabled at all. Ignore the // latter type of attribute value. if (tokens.empty() || - (tokens.size() == 1 && (tokens[0] == "on" || tokens[0] == "off"))) { + (tokens.size() == 1 && + (tokens[0] == "on" || tokens[0] == "off" || tokens[0] == "false"))) { continue; }
diff --git a/components/autofill/core/browser/form_structure.h b/components/autofill/core/browser/form_structure.h index 109feb1..23e757b 100644 --- a/components/autofill/core/browser/form_structure.h +++ b/components/autofill/core/browser/form_structure.h
@@ -103,14 +103,22 @@ // Returns true if this form matches the structural requirements for Autofill. bool ShouldBeParsed() const; - // Returns true if we should query the crowdsourcing server to determine this - // form's field types. If the form includes author-specified types, this will + // Returns true if heuristic autofill type detection should be attempted for + // this form. + bool ShouldRunHeuristics() const; + + // Returns true if we should query the crowd-sourcing server to determine this + // form's field types. If the form includes author-specified types, this will // return false unless there are password fields in the form. If there are no // password fields the assumption is that the author has expressed their // intent and crowdsourced data should not be used to override this. Password // fields are different because there is no way to specify password generation // directly. - bool ShouldBeCrowdsourced() const; + bool ShouldBeQueried() const; + + // Returns true if we should upload votes for this form to the crowd-sourcing + // server. + bool ShouldBeUploaded() const; // Sets the field types to be those set for |cached_form|. void UpdateFromCache(const FormStructure& cached_form,
diff --git a/components/autofill/core/browser/form_structure_unittest.cc b/components/autofill/core/browser/form_structure_unittest.cc index 38784dc..d6dcec11 100644 --- a/components/autofill/core/browser/form_structure_unittest.cc +++ b/components/autofill/core/browser/form_structure_unittest.cc
@@ -17,7 +17,7 @@ #include "base/test/scoped_feature_list.h" #include "components/autofill/core/browser/autofill_experiments.h" #include "components/autofill/core/browser/autofill_test_utils.h" -#include "components/autofill/core/common/autofill_switches.h" +#include "components/autofill/core/common/autofill_features.h" #include "components/autofill/core/common/form_data.h" #include "components/autofill/core/common/form_field_data.h" #include "components/autofill/core/common/signatures_util.h" @@ -26,6 +26,9 @@ #include "url/gurl.h" using base::ASCIIToUTF16; +using autofill::features::kAutofillEnforceMinRequiredFieldsForHeuristics; +using autofill::features::kAutofillEnforceMinRequiredFieldsForQuery; +using autofill::features::kAutofillEnforceMinRequiredFieldsForUpload; namespace autofill { @@ -41,6 +44,85 @@ } protected: + void InitFeature(base::test::ScopedFeatureList* feature_list, + const base::Feature& feature, + bool is_enabled) { + if (is_enabled) + feature_list->InitAndEnableFeature(feature); + else + feature_list->InitAndDisableFeature(feature); + } + + // Single field forms are not parseable iff all of the minimum required field + // values are enforced. + void CheckFormShouldBeParsed(const char* trace_message, + const FormData form, + bool expected_if_all_enforced, + bool expected_if_not_all_enforced) { + SCOPED_TRACE(trace_message); + for (bool enforce_min_for_heuristics : {true, false}) { + base::test::ScopedFeatureList heuristics, query, upload; + InitFeature(&heuristics, kAutofillEnforceMinRequiredFieldsForHeuristics, + enforce_min_for_heuristics); + for (bool enforce_min_for_query : {true, false}) { + base::test::ScopedFeatureList heuristics, query, upload; + InitFeature(&query, kAutofillEnforceMinRequiredFieldsForQuery, + enforce_min_for_query); + for (bool enforce_min_for_upload : {true, false}) { + base::test::ScopedFeatureList heuristics, query, upload; + InitFeature(&upload, kAutofillEnforceMinRequiredFieldsForUpload, + enforce_min_for_upload); + bool all_enforced = enforce_min_for_heuristics && + enforce_min_for_query && enforce_min_for_upload; + FormStructure form_structure(form); + if (all_enforced) { + EXPECT_EQ(expected_if_all_enforced, + form_structure.ShouldBeParsed()); + } else { + EXPECT_EQ(expected_if_not_all_enforced, + form_structure.ShouldBeParsed()) + << "heuristics:" << enforce_min_for_heuristics << "; " + << "query:" << enforce_min_for_query << "; " + << "upload:" << enforce_min_for_upload; + } + } + } + } + } + + bool FormIsAutofillable(const FormData& form, bool enforce_min_fields) { + base::test::ScopedFeatureList feature_list; + InitFeature(&feature_list, kAutofillEnforceMinRequiredFieldsForHeuristics, + enforce_min_fields); + FormStructure form_structure(form); + form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); + return form_structure.IsAutofillable(); + } + + bool FormShouldRunHeuristics(const FormData& form, bool enforce_min_fields) { + base::test::ScopedFeatureList feature_list; + InitFeature(&feature_list, kAutofillEnforceMinRequiredFieldsForHeuristics, + enforce_min_fields); + FormStructure form_structure(form); + return form_structure.ShouldRunHeuristics(); + } + + bool FormShouldBeQueried(const FormData& form, bool enforce_min_fields) { + base::test::ScopedFeatureList feature_list; + InitFeature(&feature_list, kAutofillEnforceMinRequiredFieldsForQuery, + enforce_min_fields); + FormStructure form_structure(form); + return form_structure.ShouldBeQueried(); + } + + bool FormShouldBeUploaded(const FormData& form, bool enforce_min_fields) { + base::test::ScopedFeatureList feature_list; + InitFeature(&feature_list, kAutofillEnforceMinRequiredFieldsForUpload, + enforce_min_fields); + FormStructure form_structure(form); + return form_structure.ShouldBeUploaded(); + } + void DisableAutofillMetadataFieldTrial() { field_trial_list_.reset(); } private: @@ -151,93 +233,103 @@ } TEST_F(FormStructureTest, IsAutofillable) { - std::unique_ptr<FormStructure> form_structure; FormData form; - - // We need at least three text fields to be auto-fillable. FormFieldData field; + // Start with a username field. It should be picked up by the password but + // not by autofill. field.label = ASCIIToUTF16("username"); field.name = ASCIIToUTF16("username"); field.form_control_type = "text"; form.fields.push_back(field); + // With min required fields enabled. + EXPECT_FALSE(FormIsAutofillable(form, true)); // Min enforced. + EXPECT_FALSE(FormIsAutofillable(form, false)); // Min not enforced. + + // Add a password field. The form should be picked up by the password but + // not by autofill. field.label = ASCIIToUTF16("password"); field.name = ASCIIToUTF16("password"); field.form_control_type = "password"; form.fields.push_back(field); - field.label = base::string16(); - field.name = ASCIIToUTF16("Submit"); - field.form_control_type = "submit"; - form.fields.push_back(field); + EXPECT_FALSE(FormIsAutofillable(form, true)); // Min enforced. + EXPECT_FALSE(FormIsAutofillable(form, false)); // Min not enforced. - form_structure.reset(new FormStructure(form)); - form_structure->DetermineHeuristicTypes(nullptr /* ukm_service */); - EXPECT_FALSE(form_structure->IsAutofillable()); - - // We now have three text fields, but only two auto-fillable fields. - field.label = ASCIIToUTF16("First Name"); - field.name = ASCIIToUTF16("firstname"); + // Add an auto-fillable fields. With just one auto-fillable field, this should + // be picked up by autofill only if there is no minimum field enforcement. + field.label = ASCIIToUTF16("Full Name"); + field.name = ASCIIToUTF16("fullname"); field.form_control_type = "text"; form.fields.push_back(field); - field.label = ASCIIToUTF16("Last Name"); - field.name = ASCIIToUTF16("lastname"); + EXPECT_FALSE(FormIsAutofillable(form, true)); // Min enforced. + EXPECT_TRUE(FormIsAutofillable(form, false)); // Min not enforced. + + // Add an auto-fillable fields. With just one auto-fillable field, this should + // be picked up by autofill only if there is no minimum field enforcement. + field.label = ASCIIToUTF16("Address Line 1"); + field.name = ASCIIToUTF16("address1"); field.form_control_type = "text"; form.fields.push_back(field); - form_structure.reset(new FormStructure(form)); - form_structure->DetermineHeuristicTypes(nullptr /* ukm_service */); - EXPECT_FALSE(form_structure->IsAutofillable()); + EXPECT_FALSE(FormIsAutofillable(form, true)); // Min enforced. + EXPECT_TRUE(FormIsAutofillable(form, false)); // Min not enforced. - // We now have three auto-fillable fields. + // We now have three auto-fillable fields. It's always autofillable. field.label = ASCIIToUTF16("Email"); field.name = ASCIIToUTF16("email"); field.form_control_type = "email"; form.fields.push_back(field); - form_structure.reset(new FormStructure(form)); - form_structure->DetermineHeuristicTypes(nullptr /* ukm_service */); - EXPECT_TRUE(form_structure->IsAutofillable()); + EXPECT_TRUE(FormIsAutofillable(form, true)); // Min enforced. + EXPECT_TRUE(FormIsAutofillable(form, false)); // Min not enforced. // The target cannot include http(s)://*/search... form.action = GURL("http://google.com/search?q=hello"); - form_structure.reset(new FormStructure(form)); - form_structure->DetermineHeuristicTypes(nullptr /* ukm_service */); - EXPECT_FALSE(form_structure->IsAutofillable()); + + EXPECT_FALSE(FormIsAutofillable(form, true)); // Min enforced. + EXPECT_FALSE(FormIsAutofillable(form, false)); // Min not enforced. // But search can be in the URL. form.action = GURL("http://search.com/?q=hello"); - form_structure.reset(new FormStructure(form)); - form_structure->DetermineHeuristicTypes(nullptr /* ukm_service */); - EXPECT_TRUE(form_structure->IsAutofillable()); + + EXPECT_TRUE(FormIsAutofillable(form, true)); // Min enforced. + EXPECT_TRUE(FormIsAutofillable(form, false)); // Min not enforced. } TEST_F(FormStructureTest, ShouldBeParsed) { - std::unique_ptr<FormStructure> form_structure; FormData form; - // We need at least three text fields to be parseable. - FormFieldData field; - field.label = ASCIIToUTF16("username"); - field.name = ASCIIToUTF16("username"); - field.form_control_type = "text"; - form.fields.push_back(field); - + // Start with a single checkable field. FormFieldData checkable_field; checkable_field.check_status = FormFieldData::CHECKABLE_BUT_UNCHECKED; checkable_field.name = ASCIIToUTF16("radiobtn"); checkable_field.form_control_type = "radio"; form.fields.push_back(checkable_field); + // A form with a single checkable field isn't interesting. + CheckFormShouldBeParsed("one checkable", form, false, false); + + // Add a second checkable field. checkable_field.name = ASCIIToUTF16("checkbox"); checkable_field.form_control_type = "checkbox"; form.fields.push_back(checkable_field); - // We have only one text field, should not be parsed. - form_structure.reset(new FormStructure(form)); - EXPECT_FALSE(form_structure->ShouldBeParsed()); + // A form with a only checkable fields isn't interesting. + CheckFormShouldBeParsed("two checkable", form, false, false); + + // Add a text field. + FormFieldData field; + field.label = ASCIIToUTF16("username"); + field.name = ASCIIToUTF16("username"); + field.form_control_type = "text"; + form.fields.push_back(field); + + // Single text field forms shouldn't be parsed if all of the minimums are + // enforced but should be parsed if ANY of the minimums is not enforced. + CheckFormShouldBeParsed("username", form, false, true); // We now have three text fields, though only two are auto-fillable. field.label = ASCIIToUTF16("First Name"); @@ -250,22 +342,16 @@ field.form_control_type = "text"; form.fields.push_back(field); - form_structure.reset(new FormStructure(form)); - EXPECT_TRUE(form_structure->ShouldBeParsed()); - - form_structure.reset(new FormStructure(form)); - EXPECT_FALSE(form_structure->IsAutofillable()); - EXPECT_TRUE(form_structure->ShouldBeParsed()); + // Three text field forms should always be parsed. + CheckFormShouldBeParsed("three field", form, true, true); // The target cannot include http(s)://*/search... form.action = GURL("http://google.com/search?q=hello"); - form_structure.reset(new FormStructure(form)); - EXPECT_FALSE(form_structure->ShouldBeParsed()); + CheckFormShouldBeParsed("search path", form, false, false); // But search can be in the URL. form.action = GURL("http://search.com/?q=hello"); - form_structure.reset(new FormStructure(form)); - EXPECT_TRUE(form_structure->ShouldBeParsed()); + CheckFormShouldBeParsed("search domain", form, true, true); // The form need only have three fields, but at least one must be a text // field. @@ -286,34 +372,30 @@ field.form_control_type = "select-one"; form.fields.push_back(field); - form_structure.reset(new FormStructure(form)); - EXPECT_TRUE(form_structure->ShouldBeParsed()); - - form.fields[0].form_control_type = "select-one"; + CheckFormShouldBeParsed("text + selects", form, true, true); // Now, no text fields. - form_structure.reset(new FormStructure(form)); - EXPECT_FALSE(form_structure->ShouldBeParsed()); + form.fields[0].form_control_type = "select-one"; + CheckFormShouldBeParsed("only selects", form, false, false); - // We have only one field, which is password, should not be parsed. + // We have only one field, which is password. form.fields.clear(); field.label = ASCIIToUTF16("Password"); field.name = ASCIIToUTF16("pw"); field.form_control_type = "password"; form.fields.push_back(field); - form_structure.reset(new FormStructure(form)); - EXPECT_FALSE(form_structure->ShouldBeParsed()); + CheckFormShouldBeParsed("password", form, false, true); // We have two fields, which are passwords, should be parsed. field.label = ASCIIToUTF16("New password"); field.name = ASCIIToUTF16("new_pw"); field.form_control_type = "password"; form.fields.push_back(field); - form_structure.reset(new FormStructure(form)); - EXPECT_TRUE(form_structure->ShouldBeParsed()); + CheckFormShouldBeParsed("new password", form, true, true); // There are 2 fields, one of which is password, and this is an upload of - // a sign-in form submission, should be parsed. + // a sign-in form submission, should be parsed. even if all minimums are + // enforced. form.fields.clear(); field.name = ASCIIToUTF16("username"); field.form_control_type = "text"; @@ -321,9 +403,17 @@ field.name = ASCIIToUTF16("pw"); field.form_control_type = "password"; form.fields.push_back(field); - form_structure.reset(new FormStructure(form)); - form_structure->set_is_signin_upload(true); - EXPECT_TRUE(form_structure->ShouldBeParsed()); + base::test::ScopedFeatureList feature_list; + feature_list.InitWithFeatures( + // Enabled. + {kAutofillEnforceMinRequiredFieldsForHeuristics, + kAutofillEnforceMinRequiredFieldsForQuery, + kAutofillEnforceMinRequiredFieldsForUpload}, + // Disabled. + {}); + FormStructure form_structure(form); + form_structure.set_is_signin_upload(true); + EXPECT_TRUE(form_structure.ShouldBeParsed()); } // Tests that ShouldBeParsed returns true for a form containing less than three @@ -350,6 +440,41 @@ EXPECT_TRUE(form_structure->ShouldBeParsed()); } +// Tests that ShouldBeParsed returns true for a form containing less than three +// fields if at least one has an autocomplete attribute. +TEST_F(FormStructureTest, DetermineHeuristicTypes_AutocompleteFalse) { + std::unique_ptr<FormStructure> form_structure; + FormData form; + FormFieldData field; + + field.label = ASCIIToUTF16("Name"); + field.name = ASCIIToUTF16("name"); + field.form_control_type = "text"; + field.autocomplete_attribute = "false"; + form.fields.push_back(field); + + field.label = ASCIIToUTF16("Email"); + field.name = ASCIIToUTF16("email"); + field.form_control_type = "text"; + field.autocomplete_attribute = "false"; + form.fields.push_back(field); + + field.label = ASCIIToUTF16("State"); + field.name = ASCIIToUTF16("state"); + field.form_control_type = "select-one"; + field.autocomplete_attribute = "false"; + form.fields.push_back(field); + + form_structure.reset(new FormStructure(form)); + form_structure->DetermineHeuristicTypes(nullptr); + EXPECT_TRUE(form_structure->ShouldBeParsed()); + EXPECT_EQ(3U, form_structure->autofill_count()); + EXPECT_EQ(NAME_FULL, form_structure->field(0)->Type().GetStorableType()); + EXPECT_EQ(EMAIL_ADDRESS, form_structure->field(1)->Type().GetStorableType()); + EXPECT_EQ(ADDRESS_HOME_STATE, + form_structure->field(2)->Type().GetStorableType()); +} + TEST_F(FormStructureTest, HeuristicsContactInfo) { std::unique_ptr<FormStructure> form_structure; FormData form; @@ -797,7 +922,8 @@ form_structure.reset(new FormStructure(form)); form_structure->DetermineHeuristicTypes(nullptr /* ukm_service */); EXPECT_TRUE(form_structure->IsAutofillable()); - EXPECT_TRUE(form_structure->ShouldBeCrowdsourced()); + EXPECT_TRUE(form_structure->ShouldBeQueried()); + EXPECT_TRUE(form_structure->ShouldBeUploaded()); ASSERT_EQ(3U, form_structure->field_count()); ASSERT_EQ(3U, form_structure->autofill_count()); @@ -835,7 +961,8 @@ form_structure.reset(new FormStructure(form)); form_structure->DetermineHeuristicTypes(nullptr /* ukm_service */); EXPECT_TRUE(form_structure->IsAutofillable()); - EXPECT_TRUE(form_structure->ShouldBeCrowdsourced()); + EXPECT_TRUE(form_structure->ShouldBeQueried()); + EXPECT_TRUE(form_structure->ShouldBeUploaded()); ASSERT_EQ(3U, form_structure->field_count()); ASSERT_EQ(3U, form_structure->autofill_count()); @@ -878,7 +1005,7 @@ form_structure.reset(new FormStructure(form)); form_structure->DetermineHeuristicTypes(nullptr /* ukm_service */); EXPECT_TRUE(form_structure->IsAutofillable()); - EXPECT_TRUE(form_structure->ShouldBeCrowdsourced()); + EXPECT_TRUE(form_structure->ShouldBeQueried()); ASSERT_EQ(4U, form_structure->field_count()); ASSERT_EQ(3U, form_structure->autofill_count()); @@ -889,43 +1016,82 @@ EXPECT_EQ(EMAIL_ADDRESS, form_structure->field(3)->heuristic_type()); } -// Tests the heuristics and server predictions are not run for forms with less -// than 3 fields. +// Tests whether the heuristics and server predictions are run for forms with +// fewer than 3 fields and no autocomplete attributes. TEST_F(FormStructureTest, HeuristicsAndServerPredictions_SmallForm_NoAutocompleteAttribute) { - std::unique_ptr<FormStructure> form_structure; FormData form; - FormFieldData field; field.form_control_type = "text"; - field.label = ASCIIToUTF16("First Name"); field.name = ASCIIToUTF16("firstname"); form.fields.push_back(field); - field.label = ASCIIToUTF16("Last Name"); field.name = ASCIIToUTF16("lastname"); form.fields.push_back(field); - form_structure.reset(new FormStructure(form)); - form_structure->DetermineHeuristicTypes(nullptr /* ukm_service */); - EXPECT_FALSE(form_structure->IsAutofillable()); - EXPECT_FALSE(form_structure->ShouldBeCrowdsourced()); + EXPECT_FALSE(FormShouldRunHeuristics(form, true)); // Min enforced. + EXPECT_TRUE(FormShouldRunHeuristics(form, false)); // Min not enforced. - ASSERT_EQ(2U, form_structure->field_count()); - ASSERT_EQ(0U, form_structure->autofill_count()); + EXPECT_FALSE(FormShouldBeQueried(form, true)); // Min enforced. + EXPECT_TRUE(FormShouldBeQueried(form, false)); // Min not enforced. - EXPECT_EQ(UNKNOWN_TYPE, form_structure->field(0)->heuristic_type()); - EXPECT_EQ(UNKNOWN_TYPE, form_structure->field(1)->heuristic_type()); - EXPECT_EQ(NO_SERVER_DATA, form_structure->field(0)->overall_server_type()); - EXPECT_EQ(NO_SERVER_DATA, form_structure->field(1)->overall_server_type()); + // Status Quo (Q3/2017) - Small forms not supported. + { + base::test::ScopedFeatureList feature_list; + feature_list.InitWithFeatures( + // Enabled. + {kAutofillEnforceMinRequiredFieldsForHeuristics, + kAutofillEnforceMinRequiredFieldsForQuery, + kAutofillEnforceMinRequiredFieldsForUpload}, + // Disabled. + {}); + FormStructure form_structure(form); + form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); + ASSERT_EQ(2U, form_structure.field_count()); + ASSERT_EQ(0U, form_structure.autofill_count()); + EXPECT_EQ(UNKNOWN_TYPE, form_structure.field(0)->heuristic_type()); + EXPECT_EQ(UNKNOWN_TYPE, form_structure.field(1)->heuristic_type()); + EXPECT_EQ(NO_SERVER_DATA, form_structure.field(0)->overall_server_type()); + EXPECT_EQ(NO_SERVER_DATA, form_structure.field(1)->overall_server_type()); + EXPECT_FALSE(form_structure.IsAutofillable()); + } + + // Default configuration. + { + FormStructure form_structure(form); + form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); + ASSERT_EQ(2U, form_structure.field_count()); + ASSERT_EQ(0U, form_structure.autofill_count()); + EXPECT_EQ(UNKNOWN_TYPE, form_structure.field(0)->heuristic_type()); + EXPECT_EQ(UNKNOWN_TYPE, form_structure.field(1)->heuristic_type()); + EXPECT_EQ(NO_SERVER_DATA, form_structure.field(0)->overall_server_type()); + EXPECT_EQ(NO_SERVER_DATA, form_structure.field(1)->overall_server_type()); + EXPECT_FALSE(form_structure.IsAutofillable()); + } + + // Enable small form heuristics. + { + base::test::ScopedFeatureList feature_list; + feature_list.InitAndDisableFeature( + kAutofillEnforceMinRequiredFieldsForHeuristics); + FormStructure form_structure(form); + form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); + ASSERT_EQ(2U, form_structure.field_count()); + ASSERT_EQ(2U, form_structure.autofill_count()); + EXPECT_EQ(NAME_FIRST, form_structure.field(0)->heuristic_type()); + EXPECT_EQ(NAME_LAST, form_structure.field(1)->heuristic_type()); + EXPECT_EQ(NO_SERVER_DATA, form_structure.field(0)->overall_server_type()); + EXPECT_EQ(NO_SERVER_DATA, form_structure.field(1)->overall_server_type()); + EXPECT_TRUE(form_structure.IsAutofillable()); + } } // Tests the heuristics and server predictions are not run for forms with less -// than 3 fields, even if an autocomplete attribute is specified. +// than 3 fields, if the minimum fields required feature is enforced, even if an +// autocomplete attribute is specified. TEST_F(FormStructureTest, HeuristicsAndServerPredictions_SmallForm_ValidAutocompleteAttribute) { - std::unique_ptr<FormStructure> form_structure; FormData form; FormFieldData field; @@ -942,25 +1108,76 @@ field.autocomplete_attribute = ""; form.fields.push_back(field); - form_structure.reset(new FormStructure(form)); - form_structure->DetermineHeuristicTypes(nullptr /* ukm_service */); - EXPECT_FALSE(form_structure->IsAutofillable()); - EXPECT_FALSE(form_structure->ShouldBeCrowdsourced()); + EXPECT_FALSE(FormShouldRunHeuristics(form, true)); // Min enforced. + EXPECT_TRUE(FormShouldRunHeuristics(form, false)); // Min not enforced. - ASSERT_EQ(2U, form_structure->field_count()); - ASSERT_EQ(1U, form_structure->autofill_count()); + EXPECT_FALSE(FormShouldBeQueried(form, true)); // Min enforced. + EXPECT_TRUE(FormShouldBeQueried(form, false)); // Min not enforced. - EXPECT_EQ(UNKNOWN_TYPE, form_structure->field(0)->heuristic_type()); - EXPECT_EQ(UNKNOWN_TYPE, form_structure->field(1)->heuristic_type()); - EXPECT_EQ(NO_SERVER_DATA, form_structure->field(0)->overall_server_type()); - EXPECT_EQ(NO_SERVER_DATA, form_structure->field(1)->overall_server_type()); + // Status Quo (Q3/2017) - Small forms not supported. + { + base::test::ScopedFeatureList feature_list; + feature_list.InitWithFeatures( + // Enabled. + {kAutofillEnforceMinRequiredFieldsForHeuristics, + kAutofillEnforceMinRequiredFieldsForQuery, + kAutofillEnforceMinRequiredFieldsForUpload}, + // Disabled. + {}); + FormStructure form_structure(form); + form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); + ASSERT_EQ(2U, form_structure.field_count()); + ASSERT_EQ(1U, form_structure.autofill_count()); + EXPECT_EQ(UNKNOWN_TYPE, form_structure.field(0)->heuristic_type()); + EXPECT_EQ(UNKNOWN_TYPE, form_structure.field(1)->heuristic_type()); + EXPECT_EQ(NO_SERVER_DATA, form_structure.field(0)->overall_server_type()); + EXPECT_EQ(NO_SERVER_DATA, form_structure.field(1)->overall_server_type()); + EXPECT_FALSE(form_structure.IsAutofillable()); + } + + // Enable small form heuristics. + { + base::test::ScopedFeatureList feature_list; + feature_list.InitAndDisableFeature( + kAutofillEnforceMinRequiredFieldsForHeuristics); + FormStructure form_structure(form); + form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); + ASSERT_EQ(2U, form_structure.field_count()); + ASSERT_EQ(2U, form_structure.autofill_count()); + EXPECT_EQ(NAME_FIRST, form_structure.field(0)->heuristic_type()); + EXPECT_EQ(NAME_LAST, form_structure.field(1)->heuristic_type()); + EXPECT_EQ(NO_SERVER_DATA, form_structure.field(0)->overall_server_type()); + EXPECT_EQ(NO_SERVER_DATA, form_structure.field(1)->overall_server_type()); + EXPECT_EQ(NAME_FIRST, form_structure.field(0)->Type().GetStorableType()); + EXPECT_EQ(NAME_LAST, form_structure.field(1)->Type().GetStorableType()); + EXPECT_TRUE(form_structure.IsAutofillable()); + } + + // As a side effect of parsing small forms (if any of the heuristics, query, + // or upload minimmums are disabled, we'll autofill fields with an + // autocomplete attribute, even if its the only field in the form. + { + base::test::ScopedFeatureList feature_list; + feature_list.InitAndDisableFeature( + kAutofillEnforceMinRequiredFieldsForUpload); + FormData form_copy = form; + form_copy.fields.pop_back(); + FormStructure form_structure(form_copy); + form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); + ASSERT_EQ(1U, form_structure.field_count()); + ASSERT_EQ(1U, form_structure.autofill_count()); + EXPECT_EQ(UNKNOWN_TYPE, form_structure.field(0)->heuristic_type()); + EXPECT_EQ(NO_SERVER_DATA, form_structure.field(0)->overall_server_type()); + EXPECT_EQ(NAME_FIRST, form_structure.field(0)->Type().GetStorableType()); + EXPECT_TRUE(form_structure.IsAutofillable()); + } } -// Even with an 'autocomplete' attribute set, ShouldBeCrowdsourced() should +// Even with an 'autocomplete' attribute set, ShouldBeQueried() should // return true if the structure contains a password field, since there are // no local heuristics to depend upon in this case. Fields will still not be // considered autofillable though. -TEST_F(FormStructureTest, PasswordFormShouldBeCrowdsourced) { +TEST_F(FormStructureTest, PasswordFormShouldBeQueried) { FormData form; // Start with a regular contact form. @@ -987,7 +1204,8 @@ FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); - EXPECT_TRUE(form_structure.ShouldBeCrowdsourced()); + EXPECT_TRUE(form_structure.ShouldBeQueried()); + EXPECT_TRUE(form_structure.ShouldBeUploaded()); } // Verify that we can correctly process sections listed in the |autocomplete|
diff --git a/components/autofill/core/browser/personal_data_manager.cc b/components/autofill/core/browser/personal_data_manager.cc index 029ec607d..302334a 100644 --- a/components/autofill/core/browser/personal_data_manager.cc +++ b/components/autofill/core/browser/personal_data_manager.cc
@@ -1609,7 +1609,7 @@ // Since Android places the label on its own row, there's more // horizontal // space to work with. Show "Amex - 1234" rather than desktop's "*1234". - suggestion->label = credit_card->NetworkAndLastFourDigits(); + suggestion->label = credit_card->NetworkOrBankNameAndLastFourDigits(); #else suggestion->label = base::ASCIIToUTF16("*"); suggestion->label.append(credit_card->LastFourDigits());
diff --git a/components/autofill/core/browser/personal_data_manager.h b/components/autofill/core/browser/personal_data_manager.h index 1323842..69f21fd 100644 --- a/components/autofill/core/browser/personal_data_manager.h +++ b/components/autofill/core/browser/personal_data_manager.h
@@ -28,7 +28,6 @@ #include "components/prefs/pref_change_registrar.h" #include "components/prefs/pref_member.h" #include "components/webdata/common/web_data_service_consumer.h" -#include "net/url_request/url_request_context_getter.h" class AccountTrackerService; class Browser; @@ -285,18 +284,6 @@ // Notifies test observers that personal data has changed. void NotifyPersonalDataChangedForTest() { NotifyPersonalDataChanged(); } - // Sets the URL request context getter to be used when normalizing addresses - // with libaddressinput's address validator. - void SetURLRequestContextGetter( - net::URLRequestContextGetter* context_getter) { - context_getter_ = context_getter; - } - - // Returns the class used to fetch the address validation rules. - net::URLRequestContextGetter* GetURLRequestContextGetter() const { - return context_getter_.get(); - } - // This function assumes |credit_card| contains the full PAN. Returns |true| // if the card number of |credit_card| is equal to any local card or any // unmasked server card known by the browser, or |TypeAndLastFourDigits| of @@ -627,10 +614,6 @@ bool has_created_test_addresses_ = false; bool has_created_test_credit_cards_ = false; - // The context for the request to be used to fetch libaddressinput's address - // validation rules. - scoped_refptr<net::URLRequestContextGetter> context_getter_; - DISALLOW_COPY_AND_ASSIGN(PersonalDataManager); };
diff --git a/components/autofill/core/browser/ui/card_unmask_prompt_controller_impl.cc b/components/autofill/core/browser/ui/card_unmask_prompt_controller_impl.cc index 0a921d9f..84d9457 100644 --- a/components/autofill/core/browser/ui/card_unmask_prompt_controller_impl.cc +++ b/components/autofill/core/browser/ui/card_unmask_prompt_controller_impl.cc
@@ -229,13 +229,19 @@ } base::string16 CardUnmaskPromptControllerImpl::GetInstructionsMessage() const { +// The prompt for server cards should reference Google Payments, whereas the +// prompt for local cards should not. #if defined(OS_IOS) int ids; if (reason_ == AutofillClient::UNMASK_FOR_AUTOFILL && ShouldRequestExpirationDate()) { - ids = IDS_AUTOFILL_CARD_UNMASK_PROMPT_INSTRUCTIONS_EXPIRED; + ids = card_.record_type() == autofill::CreditCard::LOCAL_CARD + ? IDS_AUTOFILL_CARD_UNMASK_PROMPT_INSTRUCTIONS_EXPIRED_LOCAL_CARD + : IDS_AUTOFILL_CARD_UNMASK_PROMPT_INSTRUCTIONS_EXPIRED; } else { - ids = IDS_AUTOFILL_CARD_UNMASK_PROMPT_INSTRUCTIONS; + ids = card_.record_type() == autofill::CreditCard::LOCAL_CARD + ? IDS_AUTOFILL_CARD_UNMASK_PROMPT_INSTRUCTIONS_LOCAL_CARD + : IDS_AUTOFILL_CARD_UNMASK_PROMPT_INSTRUCTIONS; } // The iOS UI shows the card details in the instructions text since they // don't fit in the title. @@ -243,7 +249,9 @@ card_.NetworkOrBankNameAndLastFourDigits()); #else return l10n_util::GetStringUTF16( - IDS_AUTOFILL_CARD_UNMASK_PROMPT_INSTRUCTIONS); + card_.record_type() == autofill::CreditCard::LOCAL_CARD + ? IDS_AUTOFILL_CARD_UNMASK_PROMPT_INSTRUCTIONS_LOCAL_CARD + : IDS_AUTOFILL_CARD_UNMASK_PROMPT_INSTRUCTIONS); #endif }
diff --git a/components/autofill/core/browser/validation.cc b/components/autofill/core/browser/validation.cc index c09ea98..a2940bf 100644 --- a/components/autofill/core/browser/validation.cc +++ b/components/autofill/core/browser/validation.cc
@@ -46,13 +46,20 @@ bool IsValidCreditCardNumber(const base::string16& text) { base::string16 number = CreditCard::StripSeparators(text); + if (!HasCorrectLength(number)) + return false; + + return PassesLuhnCheck(number); +} + +bool HasCorrectLength(const base::string16& number) { // Credit card numbers are at most 19 digits in length, 12 digits seems to // be a fairly safe lower-bound [1]. Specific card issuers have more rigidly // defined sizes. // (Last updated: May 29, 2017) // [1] https://en.wikipedia.org/wiki/Payment_card_number. // CardEditor.isCardNumberLengthMaxium() needs to be kept in sync. - const char* const type = CreditCard::GetCardNetwork(text); + const char* const type = CreditCard::GetCardNetwork(number); if (type == kAmericanExpressCard && number.size() != 15) return false; if (type == kDinersCard && number.size() != 14) @@ -75,6 +82,10 @@ if (type == kGenericCard && (number.size() < 12 || number.size() > 19)) return false; + return true; +} + +bool PassesLuhnCheck(base::string16& number) { // Use the Luhn formula [3] to validate the number. // [3] http://en.wikipedia.org/wiki/Luhn_algorithm int sum = 0;
diff --git a/components/autofill/core/browser/validation.h b/components/autofill/core/browser/validation.h index ebcf5db..76d499fc 100644 --- a/components/autofill/core/browser/validation.h +++ b/components/autofill/core/browser/validation.h
@@ -44,6 +44,12 @@ // Uses the Luhn formula to validate the number. bool IsValidCreditCardNumber(const base::string16& text); +// Returns true if |number| has correct length according to card network. +bool HasCorrectLength(const base::string16& number); + +// Returns true if |number| passes the validation by Luhn formula. +bool PassesLuhnCheck(base::string16& number); + // Returns true if |code| looks like a valid credit card security code // for the given credit card type. bool IsValidCreditCardSecurityCode(const base::string16& code,
diff --git a/components/autofill/core/common/autofill_constants.cc b/components/autofill/core/common/autofill_constants.cc index 6e30f511..53a8b46 100644 --- a/components/autofill/core/common/autofill_constants.cc +++ b/components/autofill/core/common/autofill_constants.cc
@@ -5,6 +5,7 @@ #include "components/autofill/core/common/autofill_constants.h" #include "build/build_config.h" +#include "components/autofill/core/common/autofill_features.h" namespace autofill { @@ -17,4 +18,23 @@ const char kSettingsOrigin[] = "Chrome settings"; +size_t MinRequiredFieldsForHeuristics() { + return base::FeatureList::IsEnabled( + autofill::features::kAutofillEnforceMinRequiredFieldsForHeuristics) + ? 3 + : 1; +} +size_t MinRequiredFieldsForQuery() { + return base::FeatureList::IsEnabled( + autofill::features::kAutofillEnforceMinRequiredFieldsForQuery) + ? 3 + : 1; +} +size_t MinRequiredFieldsForUpload() { + return base::FeatureList::IsEnabled( + autofill::features::kAutofillEnforceMinRequiredFieldsForUpload) + ? 3 + : 1; +} + } // namespace autofill
diff --git a/components/autofill/core/common/autofill_constants.h b/components/autofill/core/common/autofill_constants.h index 872f6974..c3d5135a 100644 --- a/components/autofill/core/common/autofill_constants.h +++ b/components/autofill/core/common/autofill_constants.h
@@ -18,15 +18,10 @@ extern const char kSettingsOrigin[]; // The number of fields required by Autofill to execute its heuristic and -// crowdsourcing prediction routines. Ideally we would execute those routines no -// matter how many fields are in the forms; however, finding the label for each -// field is a costly operation and we can't spare the cycles if it's not -// necessary. -const size_t kRequiredFieldsForPredictionRoutines = 3; - -// The minimum number of fields required to upload a form to the Autofill -// servers. -const size_t kRequiredFieldsForUpload = 3; +// crowd-sourcing query/upload routines. +size_t MinRequiredFieldsForHeuristics(); +size_t MinRequiredFieldsForQuery(); +size_t MinRequiredFieldsForUpload(); // The minimum number of fields in a form that contains only password fields to // upload the form to and request predictions from the Autofill servers.
diff --git a/components/autofill/core/common/autofill_features.cc b/components/autofill/core/common/autofill_features.cc index cedb59ca..3a1cb2f 100644 --- a/components/autofill/core/common/autofill_features.cc +++ b/components/autofill/core/common/autofill_features.cc
@@ -12,6 +12,24 @@ const base::Feature kAutofillAddressNormalizer{ "AutofillAddressNormalizer", base::FEATURE_ENABLED_BY_DEFAULT}; +// Controls whether or not a minimum number of fields is required before +// heuristic field type prediction is run for a form. +const base::Feature kAutofillEnforceMinRequiredFieldsForHeuristics{ + "AutofillEnforceMinRequiredFieldsForHeuristics", + base::FEATURE_ENABLED_BY_DEFAULT}; + +// Controls whether or not a minimum number of fields is required before +// crowd-sourced field type predictions are queried for a form. +const base::Feature kAutofillEnforceMinRequiredFieldsForQuery{ + "AutofillEnforceMinRequiredFieldsForQuery", + base::FEATURE_ENABLED_BY_DEFAULT}; + +// Controls whether or not a minimum number of fields is required before +// field type votes are uploaded to the crowd-sourcing server. +const base::Feature kAutofillEnforceMinRequiredFieldsForUpload{ + "AutofillEnforceMinRequiredFieldsForUpload", + base::FEATURE_ENABLED_BY_DEFAULT}; + // Controls attaching the autofill type predictions to their respective // element in the DOM. const base::Feature kAutofillShowTypePredictions{
diff --git a/components/autofill/core/common/autofill_features.h b/components/autofill/core/common/autofill_features.h index 101eb04..6e8ed1f 100644 --- a/components/autofill/core/common/autofill_features.h +++ b/components/autofill/core/common/autofill_features.h
@@ -12,6 +12,9 @@ // All features in alphabetical order. extern const base::Feature kAutofillAddressNormalizer; +extern const base::Feature kAutofillEnforceMinRequiredFieldsForHeuristics; +extern const base::Feature kAutofillEnforceMinRequiredFieldsForQuery; +extern const base::Feature kAutofillEnforceMinRequiredFieldsForUpload; extern const base::Feature kAutofillShowTypePredictions; } // namespace features
diff --git a/components/autofill/core/common/form_field_data.cc b/components/autofill/core/common/form_field_data.cc index 1c323b01..b26f3f9 100644 --- a/components/autofill/core/common/form_field_data.cc +++ b/components/autofill/core/common/form_field_data.cc
@@ -370,7 +370,7 @@ } std::ostream& operator<<(std::ostream& os, const FormFieldData& field) { - std::string check_status_str; + const char* check_status_str = nullptr; switch (field.check_status) { case FormFieldData::CheckStatus::NOT_CHECKABLE: check_status_str = "NOT_CHECKABLE"; @@ -381,9 +381,12 @@ case FormFieldData::CheckStatus::CHECKED: check_status_str = "CHECKED"; break; + default: + NOTREACHED(); + check_status_str = "<invalid>"; } - std::string role_str; + const char* role_str = nullptr; switch (field.role) { case FormFieldData::RoleAttribute::ROLE_ATTRIBUTE_PRESENTATION: role_str = "ROLE_ATTRIBUTE_PRESENTATION"; @@ -391,19 +394,27 @@ case FormFieldData::RoleAttribute::ROLE_ATTRIBUTE_OTHER: role_str = "ROLE_ATTRIBUTE_OTHER"; break; + default: + NOTREACHED(); + role_str = "<invalid>"; } - return os << base::UTF16ToUTF8(field.label) << " " - << base::UTF16ToUTF8(field.name) << " " - << base::UTF16ToUTF8(field.id) << " " - << base::UTF16ToUTF8(field.value) << " " << field.form_control_type - << " " << field.autocomplete_attribute << " " << field.placeholder - << " " << field.max_length << " " << field.css_classes << " " - << (field.is_autofilled ? "true" : "false") << " " - << check_status_str << (field.is_focusable ? "true" : "false") - << " " << (field.should_autocomplete ? "true" : "false") << " " - << role_str << " " << field.text_direction << " " - << field.properties_mask; + return os << "label='" << base::UTF16ToUTF8(field.label) << "' " + << "name='" << base::UTF16ToUTF8(field.name) << "' " + << "id='" << base::UTF16ToUTF8(field.id) << "' " + << "value='" << base::UTF16ToUTF8(field.value) << "' " + << "control='" << field.form_control_type << "' " + << "autocomplete='" << field.autocomplete_attribute << "' " + << "placeholder='" << field.placeholder << "' " + << "max_length=" << field.max_length << " " + << "css_classes='" << field.css_classes << "' " + << "autofilled=" << field.is_autofilled << " " + << "check_status=" << check_status_str << " " + << "is_focusable=" << field.is_focusable << " " + << "should_autocomplete=" << field.should_autocomplete << " " + << "role=" << role_str << " " + << "text_direction=" << field.text_direction << " " + << "properties_mask=" << field.properties_mask; } } // namespace autofill
diff --git a/components/autofill/ios/browser/autofill_agent.mm b/components/autofill/ios/browser/autofill_agent.mm index 0a852a2..9e85b0bcf 100644 --- a/components/autofill/ios/browser/autofill_agent.mm +++ b/components/autofill/ios/browser/autofill_agent.mm
@@ -733,12 +733,13 @@ [strongSelf notifyAutofillManager:autofillManager ofFormsSeen:forms]; }; // The document has now been fully loaded. Scan for forms to be extracted. - // Because of the cost of communicating with the server, only forms that have - // enough forms to make them likely candidates for profile completion are - // extracted. + size_t min_required_fields = + MIN(autofill::MinRequiredFieldsForUpload(), + MIN(autofill::MinRequiredFieldsForHeuristics(), + autofill::MinRequiredFieldsForQuery())); [self fetchFormsFiltered:NO withName:base::string16() - minimumRequiredFieldsCount:autofill::kRequiredFieldsForPredictionRoutines + minimumRequiredFieldsCount:min_required_fields pageURL:pageURL completionHandler:completionHandler]; }
diff --git a/components/autofill_strings.grdp b/components/autofill_strings.grdp index 4d55b7e..f629e67 100644 --- a/components/autofill_strings.grdp +++ b/components/autofill_strings.grdp
@@ -325,6 +325,9 @@ <message name="IDS_AUTOFILL_CARD_UNMASK_PROMPT_INSTRUCTIONS" desc="Text explaining what the user should do in the card unmasking dialog."> After you confirm, card details from your Google Payments account will be shared with this site. </message> + <message name="IDS_AUTOFILL_CARD_UNMASK_PROMPT_INSTRUCTIONS_LOCAL_CARD" desc="Text explaining what the user should do in the card unmasking dialog. Appears specifically for local cards already stored on the device."> + Once you confirm, your card details will be shared with this site. + </message> <message name="IDS_AUTOFILL_CARD_UNMASK_CVC_IMAGE_DESCRIPTION" desc="Accessible description for the CVC image. It should describe where to find the CVC on a credit card."> The CVC is located behind your card. </message> @@ -336,9 +339,15 @@ <message name="IDS_AUTOFILL_CARD_UNMASK_PROMPT_INSTRUCTIONS" desc="Text explaining what the user should do in the card unmasking dialog."> Enter the CVC for <ph name="CREDIT_CARD">$1<ex>Visa - 5679</ex></ph>. After you confirm, card details from your Google Payments account will be shared with this site. </message> + <message name="IDS_AUTOFILL_CARD_UNMASK_PROMPT_INSTRUCTIONS_LOCAL_CARD" desc="Text explaining what the user should do in the card unmasking dialog. Appears specifically for local cards already stored on the device."> + Enter the CVC for <ph name="CREDIT_CARD">$1<ex>Visa - 5679</ex></ph>. Once you confirm, your card details will be shared with this site. + </message> <message name="IDS_AUTOFILL_CARD_UNMASK_PROMPT_INSTRUCTIONS_EXPIRED" desc="Text explaining what the user should do in the card unmasking dialog to update an expired card."> Enter the expiration date and CVC for <ph name="CREDIT_CARD">$1<ex>Visa - 5679</ex></ph> to update your card details. After you confirm, card details from your Google Payments account will be shared with this site. </message> + <message name="IDS_AUTOFILL_CARD_UNMASK_PROMPT_INSTRUCTIONS_EXPIRED_LOCAL_CARD" desc="Text explaining what the user should do in the card unmasking dialog to update an expired card. Appears specifically for local cards already stored on the device."> + Enter the expiration date and CVC for <ph name="CREDIT_CARD">$1<ex>Visa - 5679</ex></ph> to update your card details. Once you confirm, your card details will be shared with this site. + </message> </if> <message name="IDS_AUTOFILL_CARD_UNMASK_PROMPT_STORAGE_CHECKBOX" desc="Text for checkbox in card unmasking dialog that allows user to store a Wallet card on their local device. If checked, the dialog won't show up again for the given credit card." formatter_data="android_java"> Keep a copy of this card on this device
diff --git a/components/cast_channel/BUILD.gn b/components/cast_channel/BUILD.gn index a766875..15db44c 100644 --- a/components/cast_channel/BUILD.gn +++ b/components/cast_channel/BUILD.gn
@@ -8,6 +8,8 @@ "cast_auth_util.h", "cast_channel_enum.cc", "cast_channel_enum.h", + "cast_channel_util.cc", + "cast_channel_util.h", "cast_framer.cc", "cast_framer.h", "cast_message_util.cc",
diff --git a/components/cast_channel/cast_channel_util.cc b/components/cast_channel/cast_channel_util.cc new file mode 100644 index 0000000..0c83ae5 --- /dev/null +++ b/components/cast_channel/cast_channel_util.cc
@@ -0,0 +1,20 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/cast_channel/cast_channel_util.h" + +namespace cast_channel { + +bool IsValidCastIPAddress(const net::IPAddress& ip_address) { + // A valid Cast IP address must be private. + return ip_address.IsReserved(); +} + +bool IsValidCastIPAddressString(const std::string& ip_address_string) { + net::IPAddress ip_address; + return ip_address.AssignFromIPLiteral(ip_address_string) && + IsValidCastIPAddress(ip_address); +} + +} // namespace cast_channel
diff --git a/components/cast_channel/cast_channel_util.h b/components/cast_channel/cast_channel_util.h new file mode 100644 index 0000000..3df5525 --- /dev/null +++ b/components/cast_channel/cast_channel_util.h
@@ -0,0 +1,20 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_CAST_CHANNEL_CAST_CHANNEL_UTIL_H_ +#define COMPONENTS_CAST_CHANNEL_CAST_CHANNEL_UTIL_H_ + +#include "net/base/ip_address.h" + +namespace cast_channel { + +// Returns true if |ip_address| represents a valid IP address of a Cast device. +bool IsValidCastIPAddress(const net::IPAddress& ip_address); + +// Similar to above, but takes a std::string as input. +bool IsValidCastIPAddressString(const std::string& ip_address_string); + +} // namespace cast_channel + +#endif // COMPONENTS_CAST_CHANNEL_CAST_CHANNEL_UTIL_H_
diff --git a/components/cast_channel/cast_socket_service.cc b/components/cast_channel/cast_socket_service.cc index 3e007af..663e55b 100644 --- a/components/cast_channel/cast_socket_service.cc +++ b/components/cast_channel/cast_socket_service.cc
@@ -5,6 +5,7 @@ #include "components/cast_channel/cast_socket_service.h" #include "base/memory/ptr_util.h" +#include "components/cast_channel/cast_channel_util.h" #include "components/cast_channel/cast_socket.h" #include "components/cast_channel/logger.h" #include "content/public/browser/browser_thread.h" @@ -75,11 +76,14 @@ return it == sockets_.end() ? nullptr : it->second.get(); } -int CastSocketService::OpenSocket(const CastSocketOpenParams& open_params, - CastSocket::OnOpenCallback open_cb) { +void CastSocketService::OpenSocket(const CastSocketOpenParams& open_params, + CastSocket::OnOpenCallback open_cb) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - auto* socket = GetSocket(open_params.ip_endpoint); + const net::IPEndPoint& ip_endpoint = open_params.ip_endpoint; + CHECK(IsValidCastIPAddress(ip_endpoint.address())); + + auto* socket = GetSocket(ip_endpoint); if (!socket) { // If cast socket does not exist. if (socket_for_test_) { @@ -94,8 +98,6 @@ socket->AddObserver(&observer); socket->Connect(std::move(open_cb)); - - return socket->id(); } void CastSocketService::AddObserver(CastSocket::Observer* observer) {
diff --git a/components/cast_channel/cast_socket_service.h b/components/cast_channel/cast_socket_service.h index f4ccf2f..407038a 100644 --- a/components/cast_channel/cast_socket_service.h +++ b/components/cast_channel/cast_socket_service.h
@@ -28,10 +28,6 @@ // Returns a pointer to the Logger member variable. scoped_refptr<cast_channel::Logger> GetLogger(); - // Adds |socket| to |sockets_| and returns raw pointer of |socket|. Takes - // ownership of |socket|. - CastSocket* AddSocket(std::unique_ptr<CastSocket> socket); - // Removes the CastSocket corresponding to |channel_id| from the // CastSocketRegistry. Returns nullptr if no such CastSocket exists. std::unique_ptr<CastSocket> RemoveSocket(int channel_id); @@ -42,14 +38,15 @@ CastSocket* GetSocket(const net::IPEndPoint& ip_endpoint) const; - // Opens cast socket with |ip_endpoint| and invokes |open_cb| when opening + // Opens cast socket with |open_params| and invokes |open_cb| when opening // operation finishes. If cast socket with |ip_endpoint| already exists, - // invoke |open_cb| directly with existing socket's channel ID. - // Parameters: + // invoke |open_cb| directly with the existing socket. + // It is the caller's responsibility to ensure |open_params.ip_address| is + // a valid private IP address as determined by |IsValidCastIPAddress()|. // |open_params|: Parameters necessary to open a Cast channel. // |open_cb|: OnOpenCallback invoked when cast socket is opened. - virtual int OpenSocket(const CastSocketOpenParams& open_params, - CastSocket::OnOpenCallback open_cb); + virtual void OpenSocket(const CastSocketOpenParams& open_params, + CastSocket::OnOpenCallback open_cb); // Adds |observer| to socket service. When socket service opens cast socket, // it passes |observer| to opened socket. @@ -71,6 +68,10 @@ CastSocketService(); virtual ~CastSocketService(); + // Adds |socket| to |sockets_| and returns raw pointer of |socket|. Takes + // ownership of |socket|. + CastSocket* AddSocket(std::unique_ptr<CastSocket> socket); + // Used to generate CastSocket id. static int last_channel_id_;
diff --git a/components/cast_channel/cast_socket_service_unittest.cc b/components/cast_channel/cast_socket_service_unittest.cc index aa4e508..24f61b5f 100644 --- a/components/cast_channel/cast_socket_service_unittest.cc +++ b/components/cast_channel/cast_socket_service_unittest.cc
@@ -22,9 +22,7 @@ class CastSocketServiceTest : public testing::Test { public: - CastSocketServiceTest() - : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP), - cast_socket_service_(new CastSocketService()) {} + CastSocketServiceTest() : cast_socket_service_(new CastSocketService()) {} CastSocket* AddSocket(std::unique_ptr<CastSocket> socket) { return cast_socket_service_->AddSocket(std::move(socket)); @@ -33,7 +31,6 @@ void TearDown() override { cast_socket_service_ = nullptr; } protected: - content::TestBrowserThreadBundle thread_bundle_; std::unique_ptr<CastSocketService> cast_socket_service_; base::MockCallback<CastSocket::OnOpenCallback> mock_on_open_callback_; MockCastSocketObserver mock_observer_;
diff --git a/components/cast_channel/cast_test_util.h b/components/cast_channel/cast_test_util.h index 8c3627f..675ade85 100644 --- a/components/cast_channel/cast_test_util.h +++ b/components/cast_channel/cast_test_util.h
@@ -70,19 +70,18 @@ MockCastSocketService(); ~MockCastSocketService() override; - int OpenSocket(const CastSocketOpenParams& open_params, - CastSocket::OnOpenCallback open_cb) override { + void OpenSocket(const CastSocketOpenParams& open_params, + CastSocket::OnOpenCallback open_cb) override { // Unit test should not call |open_cb| more than once. Just use // base::AdaptCallbackForRepeating to pass |open_cb| to a mock method. - return OpenSocketInternal( - open_params.ip_endpoint, open_params.net_log, - base::AdaptCallbackForRepeating(std::move(open_cb))); + OpenSocketInternal(open_params.ip_endpoint, open_params.net_log, + base::AdaptCallbackForRepeating(std::move(open_cb))); } MOCK_METHOD3(OpenSocketInternal, - int(const net::IPEndPoint& ip_endpoint, - net::NetLog* net_log, - const base::Callback<void(CastSocket*)>& open_cb)); + void(const net::IPEndPoint& ip_endpoint, + net::NetLog* net_log, + const base::Callback<void(CastSocket*)>& open_cb)); MOCK_CONST_METHOD1(GetSocket, CastSocket*(int channel_id)); };
diff --git a/components/cronet/android/BUILD.gn b/components/cronet/android/BUILD.gn index 8b4ac723..4e6c0b2 100644 --- a/components/cronet/android/BUILD.gn +++ b/components/cronet/android/BUILD.gn
@@ -1195,6 +1195,9 @@ "--stamp", rebase_path(_stamp_file, root_build_dir), + "--android-sdk-jar", + rebase_path(android_sdk_jar, root_build_dir), + # JavaDoc is generated from Cronet's API source jar. "--input-src-jar", rebase_path("$_package_dir/cronet_api-src.jar", root_build_dir),
diff --git a/components/cronet/ios/test/cronet_test_base.h b/components/cronet/ios/test/cronet_test_base.h index b58d25e..10c6a11f 100644 --- a/components/cronet/ios/test/cronet_test_base.h +++ b/components/cronet/ios/test/cronet_test_base.h
@@ -78,7 +78,7 @@ void SetUp() override; void TearDown() override; bool StartDataTaskAndWaitForCompletion(NSURLSessionDataTask* task, - int64_t deadline_ns = 30 * + int64_t deadline_ns = 15 * NSEC_PER_SEC); std::unique_ptr<net::MockCertVerifier> CreateMockCertVerifier( const std::vector<std::string>& certs,
diff --git a/components/cronet/tools/generate_javadoc.py b/components/cronet/tools/generate_javadoc.py index f1974e5bd..6bf72c9 100755 --- a/components/cronet/tools/generate_javadoc.py +++ b/components/cronet/tools/generate_javadoc.py
@@ -38,6 +38,11 @@ working_dir = os.path.join(options.input_dir, 'android', 'api') overview_file = os.path.abspath(options.overview_file) + android_sdk_jar = os.path.abspath(options.android_sdk_jar) + if not android_sdk_jar: + android_sdk_jar = os.path.join( + SDK_DIR, 'platforms', 'android-27', 'android.jar') + build_utils.DeleteDirectory(output_dir) build_utils.MakeDirectory(output_dir) javadoc_cmd = [ @@ -52,7 +57,7 @@ '-federate', 'Android', 'https://developer.android.com/', '-federationapi', 'Android', os.path.join(DOCLAVA_DIR, 'current.txt'), '-bootclasspath', - '%s:%s' % (os.path.join(SDK_DIR, 'platforms', 'android-26', 'android.jar'), + '%s:%s' % (android_sdk_jar, os.path.join(SDK_DIR, 'extras', 'android', 'support', 'annotations', 'android-support-annotations.jar')), ] @@ -77,6 +82,7 @@ parser.add_option('--overview-file', help='Path of the overview page') parser.add_option('--readme-file', help='Path of the README.md') parser.add_option('--stamp', help='Path to touch on success.') + parser.add_option('--android-sdk-jar', help='Path to android.jar') options, _ = parser.parse_args() # A temporary directory to put the output of cronet api source jar files.
diff --git a/components/cronet/url_request_context_config.cc b/components/cronet/url_request_context_config.cc index 39ec9fb..1d2bc364 100644 --- a/components/cronet/url_request_context_config.cc +++ b/components/cronet/url_request_context_config.cc
@@ -113,11 +113,11 @@ DoNothingCTPolicyEnforcer() = default; ~DoNothingCTPolicyEnforcer() override = default; - net::ct::CertPolicyCompliance DoesConformToCertPolicy( + net::ct::CTPolicyCompliance CheckCompliance( net::X509Certificate* cert, const net::SCTList& verified_scts, const net::NetLogWithSource& net_log) override { - return net::ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS; + return net::ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS; } };
diff --git a/components/download/components_unittests.filter b/components/download/components_unittests.filter index 3a41428..a0360b2 100644 --- a/components/download/components_unittests.filter +++ b/components/download/components_unittests.filter
@@ -9,6 +9,7 @@ DownloadServiceModelImplTest.* DownloadStoreTest.* FileMonitorTest.* +InProgressConversionsTest.* NavigationMonitorImplTest.* NetworkListenerTest.* ProtoConversionsTest.*
diff --git a/components/download/downloader/in_progress/BUILD.gn b/components/download/downloader/in_progress/BUILD.gn index 6f45a44..a1995c6 100644 --- a/components/download/downloader/in_progress/BUILD.gn +++ b/components/download/downloader/in_progress/BUILD.gn
@@ -11,6 +11,7 @@ sources = [ "download_entry.cc", "download_entry.h", + "download_source.h", "in_progress_cache.cc", "in_progress_cache.h", "in_progress_conversions.cc",
diff --git a/components/download/downloader/in_progress/download_entry.cc b/components/download/downloader/in_progress/download_entry.cc index ffd31057..0bb3a60 100644 --- a/components/download/downloader/in_progress/download_entry.cc +++ b/components/download/downloader/in_progress/download_entry.cc
@@ -11,13 +11,17 @@ DownloadEntry::DownloadEntry(const DownloadEntry& other) = default; DownloadEntry::DownloadEntry(const std::string& guid, - const std::string& request_origin) - : guid(guid), request_origin(request_origin){}; + const std::string& request_origin, + DownloadSource download_source) + : guid(guid), + request_origin(request_origin), + download_source(download_source) {} DownloadEntry::~DownloadEntry() = default; bool DownloadEntry::operator==(const DownloadEntry& other) const { - return guid == other.guid && request_origin == other.request_origin; + return guid == other.guid && request_origin == other.request_origin && + download_source == other.download_source; } } // namespace download
diff --git a/components/download/downloader/in_progress/download_entry.h b/components/download/downloader/in_progress/download_entry.h index 3e2271b..cd5ae77 100644 --- a/components/download/downloader/in_progress/download_entry.h +++ b/components/download/downloader/in_progress/download_entry.h
@@ -7,6 +7,8 @@ #include <string> +#include "components/download/downloader/in_progress/download_source.h" + namespace download { // Contains various in-progress information related to a download. @@ -14,7 +16,9 @@ public: DownloadEntry(); DownloadEntry(const DownloadEntry& other); - DownloadEntry(const std::string& guid, const std::string& request_origin); + DownloadEntry(const std::string& guid, + const std::string& request_origin, + DownloadSource download_source); ~DownloadEntry(); bool operator==(const DownloadEntry& other) const; @@ -24,6 +28,9 @@ // Represents the origin information for this download. Used by offline pages. std::string request_origin; + + // The source that triggered the download. + DownloadSource download_source = DownloadSource::UNKNOWN; }; } // namespace download
diff --git a/components/download/downloader/in_progress/download_source.h b/components/download/downloader/in_progress/download_source.h new file mode 100644 index 0000000..d02a6e0 --- /dev/null +++ b/components/download/downloader/in_progress/download_source.h
@@ -0,0 +1,34 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_DOWNLOAD_DOWNLOADER_IN_PROGRESS_DOWNLOAD_SOURCE_H_ +#define COMPONENTS_DOWNLOAD_DOWNLOADER_IN_PROGRESS_DOWNLOAD_SOURCE_H_ + +#include <string> + +namespace download { +// The source of download. +// This enum should match content::DownloadSource in +// content/public/browser/download_source.h. +// Any changes here should also apply to download_source.proto. +enum class DownloadSource { + UNKNOWN = 0, + NAVIGATION = 1, + DRAG_AND_DROP = 2, + MANUAL_RESUMPTION = 3, + AUTO_RESUMPTION = 4, + FROM_RENDERER = 5, + EXTENSION_API = 6, + EXTENSION_INSTALLER = 7, + PLUGIN = 8, + PLUGIN_INSTALLER = 9, + INTERNAL_API = 10, + SAVE_PACKAGE = 11, + OFFLINE_PAGE = 12, + COUNT = 13 +}; + +} // namespace download + +#endif // COMPONENTS_DOWNLOAD_DOWNLOADER_IN_PROGRESS_DOWNLOAD_SOURCE_H_
diff --git a/components/download/downloader/in_progress/in_progress_conversions.cc b/components/download/downloader/in_progress/in_progress_conversions.cc index ebb7e0a..44947832 100644 --- a/components/download/downloader/in_progress/in_progress_conversions.cc +++ b/components/download/downloader/in_progress/in_progress_conversions.cc
@@ -5,6 +5,7 @@ #include "components/download/downloader/in_progress/in_progress_conversions.h" #include <utility> +#include "base/logging.h" // TODO(jming): Write unit tests for conversion methods. namespace download { @@ -14,6 +15,7 @@ DownloadEntry entry; entry.guid = proto.guid(); entry.request_origin = proto.request_origin(); + entry.download_source = DownloadSourceFromProto(proto.download_source()); return entry; } @@ -22,9 +24,83 @@ metadata_pb::DownloadEntry proto; proto.set_guid(entry.guid); proto.set_request_origin(entry.request_origin); + proto.set_download_source(DownloadSourceToProto(entry.download_source)); return proto; } +// static +DownloadSource InProgressConversions::DownloadSourceFromProto( + metadata_pb::DownloadSource download_source) { + switch (download_source) { + case metadata_pb::DownloadSource::UNKNOWN: + return DownloadSource::UNKNOWN; + case metadata_pb::DownloadSource::NAVIGATION: + return DownloadSource::NAVIGATION; + case metadata_pb::DownloadSource::DRAG_AND_DROP: + return DownloadSource::DRAG_AND_DROP; + case metadata_pb::DownloadSource::MANUAL_RESUMPTION: + return DownloadSource::MANUAL_RESUMPTION; + case metadata_pb::DownloadSource::AUTO_RESUMPTION: + return DownloadSource::AUTO_RESUMPTION; + case metadata_pb::DownloadSource::FROM_RENDERER: + return DownloadSource::FROM_RENDERER; + case metadata_pb::DownloadSource::EXTENSION_API: + return DownloadSource::EXTENSION_API; + case metadata_pb::DownloadSource::EXTENSION_INSTALLER: + return DownloadSource::EXTENSION_INSTALLER; + case metadata_pb::DownloadSource::PLUGIN: + return DownloadSource::PLUGIN; + case metadata_pb::DownloadSource::PLUGIN_INSTALLER: + return DownloadSource::PLUGIN_INSTALLER; + case metadata_pb::DownloadSource::INTERNAL_API: + return DownloadSource::INTERNAL_API; + case metadata_pb::DownloadSource::SAVE_PACKAGE: + return DownloadSource::SAVE_PACKAGE; + case metadata_pb::DownloadSource::OFFLINE_PAGE: + return DownloadSource::OFFLINE_PAGE; + } + NOTREACHED(); + return DownloadSource::UNKNOWN; +} + +// static +metadata_pb::DownloadSource InProgressConversions::DownloadSourceToProto( + DownloadSource download_source) { + switch (download_source) { + case DownloadSource::UNKNOWN: + return metadata_pb::DownloadSource::UNKNOWN; + case DownloadSource::NAVIGATION: + return metadata_pb::DownloadSource::NAVIGATION; + case DownloadSource::DRAG_AND_DROP: + return metadata_pb::DownloadSource::DRAG_AND_DROP; + case DownloadSource::MANUAL_RESUMPTION: + return metadata_pb::DownloadSource::MANUAL_RESUMPTION; + case DownloadSource::AUTO_RESUMPTION: + return metadata_pb::DownloadSource::AUTO_RESUMPTION; + case DownloadSource::FROM_RENDERER: + return metadata_pb::DownloadSource::FROM_RENDERER; + case DownloadSource::EXTENSION_API: + return metadata_pb::DownloadSource::EXTENSION_API; + case DownloadSource::EXTENSION_INSTALLER: + return metadata_pb::DownloadSource::EXTENSION_INSTALLER; + case DownloadSource::PLUGIN: + return metadata_pb::DownloadSource::PLUGIN; + case DownloadSource::PLUGIN_INSTALLER: + return metadata_pb::DownloadSource::PLUGIN_INSTALLER; + case DownloadSource::INTERNAL_API: + return metadata_pb::DownloadSource::INTERNAL_API; + case DownloadSource::SAVE_PACKAGE: + return metadata_pb::DownloadSource::SAVE_PACKAGE; + case DownloadSource::OFFLINE_PAGE: + return metadata_pb::DownloadSource::OFFLINE_PAGE; + case DownloadSource::COUNT: + break; + } + + NOTREACHED(); + return metadata_pb::DownloadSource::UNKNOWN; +} + std::vector<DownloadEntry> InProgressConversions::DownloadEntriesFromProto( const metadata_pb::DownloadEntries& proto) { std::vector<DownloadEntry> entries;
diff --git a/components/download/downloader/in_progress/in_progress_conversions.h b/components/download/downloader/in_progress/in_progress_conversions.h index 81c6f91..0aa53f0 100644 --- a/components/download/downloader/in_progress/in_progress_conversions.h +++ b/components/download/downloader/in_progress/in_progress_conversions.h
@@ -8,6 +8,7 @@ #include "base/macros.h" #include "components/download/downloader/in_progress/download_entry.h" #include "components/download/downloader/in_progress/proto/download_entry.pb.h" +#include "components/download/downloader/in_progress/proto/download_source.pb.h" namespace download { @@ -19,6 +20,12 @@ static metadata_pb::DownloadEntry DownloadEntryToProto( const DownloadEntry& entry); + static DownloadSource DownloadSourceFromProto( + metadata_pb::DownloadSource download_source); + + static metadata_pb::DownloadSource DownloadSourceToProto( + DownloadSource download_source); + static std::vector<DownloadEntry> DownloadEntriesFromProto( const metadata_pb::DownloadEntries& proto);
diff --git a/components/download/downloader/in_progress/in_progress_conversions_unittest.cc b/components/download/downloader/in_progress/in_progress_conversions_unittest.cc index ef2b2f6..1a10589 100644 --- a/components/download/downloader/in_progress/in_progress_conversions_unittest.cc +++ b/components/download/downloader/in_progress/in_progress_conversions_unittest.cc
@@ -18,9 +18,10 @@ DownloadEntry entry; EXPECT_EQ(entry, DownloadEntryFromProto(DownloadEntryToProto(entry))); - // Entry with guid and request origin. + // Entry with guid, request origin and download source. entry.guid = "guid"; entry.request_origin = "request origin"; + entry.download_source = DownloadSource::DRAG_AND_DROP; EXPECT_EQ(entry, DownloadEntryFromProto(DownloadEntryToProto(entry))); } @@ -30,12 +31,29 @@ EXPECT_EQ(entries, DownloadEntriesFromProto(DownloadEntriesToProto(entries))); // Entries vector with one entry. - entries.push_back(DownloadEntry("guid", "request origin")); + entries.push_back( + DownloadEntry("guid", "request origin", DownloadSource::UNKNOWN)); EXPECT_EQ(entries, DownloadEntriesFromProto(DownloadEntriesToProto(entries))); // Entries vector with multiple entries. - entries.push_back(DownloadEntry("guid2", "request origin")); + entries.push_back( + DownloadEntry("guid2", "request origin", DownloadSource::UNKNOWN)); EXPECT_EQ(entries, DownloadEntriesFromProto(DownloadEntriesToProto(entries))); } +TEST_F(InProgressConversionsTest, DownloadSource) { + DownloadSource sources[] = { + DownloadSource::UNKNOWN, DownloadSource::NAVIGATION, + DownloadSource::DRAG_AND_DROP, DownloadSource::MANUAL_RESUMPTION, + DownloadSource::AUTO_RESUMPTION, DownloadSource::FROM_RENDERER, + DownloadSource::EXTENSION_API, DownloadSource::EXTENSION_INSTALLER, + DownloadSource::PLUGIN, DownloadSource::PLUGIN_INSTALLER, + DownloadSource::INTERNAL_API, DownloadSource::SAVE_PACKAGE, + DownloadSource::OFFLINE_PAGE}; + + for (auto source : sources) { + EXPECT_EQ(source, DownloadSourceFromProto(DownloadSourceToProto(source))); + } +} + } // namespace download
diff --git a/components/download/downloader/in_progress/proto/BUILD.gn b/components/download/downloader/in_progress/proto/BUILD.gn index 5ee88a9e..c7151fe 100644 --- a/components/download/downloader/in_progress/proto/BUILD.gn +++ b/components/download/downloader/in_progress/proto/BUILD.gn
@@ -9,5 +9,6 @@ sources = [ "download_entry.proto", + "download_source.proto", ] }
diff --git a/components/download/downloader/in_progress/proto/download_entry.proto b/components/download/downloader/in_progress/proto/download_entry.proto index 015612e..beb8d244 100644 --- a/components/download/downloader/in_progress/proto/download_entry.proto +++ b/components/download/downloader/in_progress/proto/download_entry.proto
@@ -8,10 +8,13 @@ package metadata_pb; +import "download_source.proto"; + // Stores various in-progress metadata related to a download. message DownloadEntry { optional string guid = 1; optional string request_origin = 2; + optional DownloadSource download_source = 3; } // Contains a list of entries.
diff --git a/components/download/downloader/in_progress/proto/download_source.proto b/components/download/downloader/in_progress/proto/download_source.proto new file mode 100644 index 0000000..e979b3c --- /dev/null +++ b/components/download/downloader/in_progress/proto/download_source.proto
@@ -0,0 +1,27 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +syntax = "proto2"; + +option optimize_for = LITE_RUNTIME; + +package metadata_pb; + +// This should stay in sync with the download::DownloadSource enum in +// components/download/downloader/in_progress/download_source.h. +enum DownloadSource { + UNKNOWN = 0; + NAVIGATION = 1; + DRAG_AND_DROP = 2; + MANUAL_RESUMPTION = 3; + AUTO_RESUMPTION = 4; + FROM_RENDERER = 5; + EXTENSION_API = 6; + EXTENSION_INSTALLER = 7; + PLUGIN = 8; + PLUGIN_INSTALLER = 9; + INTERNAL_API = 10; + SAVE_PACKAGE = 11; + OFFLINE_PAGE = 12; +}
diff --git a/components/exo/BUILD.gn b/components/exo/BUILD.gn index d3d8bc5..b99ab1a6 100644 --- a/components/exo/BUILD.gn +++ b/components/exo/BUILD.gn
@@ -190,6 +190,7 @@ "//mojo/edk/embedder:headers", "//testing/gtest", "//ui/aura", + "//ui/aura:test_support", "//ui/base", "//ui/compositor:test_support", "//ui/gl:test_support",
diff --git a/components/exo/wayland/BUILD.gn b/components/exo/wayland/BUILD.gn index 47d552b..6a0aabe 100644 --- a/components/exo/wayland/BUILD.gn +++ b/components/exo/wayland/BUILD.gn
@@ -322,6 +322,7 @@ "//mojo/edk/embedder:headers", "//testing/perf", "//ui/aura", + "//ui/aura:test_support", "//ui/base", "//ui/compositor:test_support", "//ui/events:gesture_detection",
diff --git a/components/exo/wayland/server.cc b/components/exo/wayland/server.cc index cc99b30..3a067e19 100644 --- a/components/exo/wayland/server.cc +++ b/components/exo/wayland/server.cc
@@ -2082,10 +2082,6 @@ display::Screen::GetScreen()->RemoveObserver(this); } - bool IsMultiDisplaySupported() const { - return wl_resource_get_version(remote_shell_resource_) >= 5; - } - std::unique_ptr<ShellSurface> CreateShellSurface( Surface* surface, int container, @@ -2102,21 +2098,15 @@ // Overridden from display::DisplayObserver: void OnDisplayAdded(const display::Display& new_display) override { - if (IsMultiDisplaySupported()) - ScheduleSendDisplayMetrics(0); + ScheduleSendDisplayMetrics(0); } void OnDisplayRemoved(const display::Display& old_display) override { - if (IsMultiDisplaySupported()) - ScheduleSendDisplayMetrics(0); + ScheduleSendDisplayMetrics(0); } void OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) override { - if (!IsMultiDisplaySupported() && - display::Screen::GetScreen()->GetPrimaryDisplay().id() != display.id()) - return; - // No need to update when a primary display has changed without bounds // change. See WaylandPrimaryDisplayObserver::OnDisplayMetricsChanged // for more details. @@ -2177,37 +2167,23 @@ const display::Screen* screen = display::Screen::GetScreen(); - if (IsMultiDisplaySupported()) { - for (const auto& display : screen->GetAllDisplays()) { - const gfx::Rect& bounds = display.bounds(); - const gfx::Insets& insets = display.GetWorkAreaInsets(); + for (const auto& display : screen->GetAllDisplays()) { + const gfx::Rect& bounds = display.bounds(); + const gfx::Insets& insets = display.GetWorkAreaInsets(); - double device_scale_factor = - WMHelper::GetInstance()->GetDisplayInfo(display.id()) - .device_scale_factor(); + double device_scale_factor = WMHelper::GetInstance() + ->GetDisplayInfo(display.id()) + .device_scale_factor(); - zcr_remote_shell_v1_send_workspace( - remote_shell_resource_, static_cast<uint32_t>(display.id() >> 32), - static_cast<uint32_t>(display.id()), bounds.x(), bounds.y(), - bounds.width(), bounds.height(), insets.left(), insets.top(), - insets.right(), insets.bottom(), - DisplayTransform(display.rotation()), - wl_fixed_from_double(device_scale_factor), display.IsInternal()); - } - - zcr_remote_shell_v1_send_configure(remote_shell_resource_, layout_mode_); + zcr_remote_shell_v1_send_workspace( + remote_shell_resource_, static_cast<uint32_t>(display.id() >> 32), + static_cast<uint32_t>(display.id()), bounds.x(), bounds.y(), + bounds.width(), bounds.height(), insets.left(), insets.top(), + insets.right(), insets.bottom(), DisplayTransform(display.rotation()), + wl_fixed_from_double(device_scale_factor), display.IsInternal()); } - display::Display primary_display = screen->GetPrimaryDisplay(); - const gfx::Insets& insets = primary_display.GetWorkAreaInsets(); - - zcr_remote_shell_v1_send_configuration_changed( - remote_shell_resource_, primary_display.size().width(), - primary_display.size().height(), - DisplayTransform(primary_display.rotation()), - wl_fixed_from_double(primary_display.device_scale_factor()), - insets.left(), insets.top(), insets.right(), insets.bottom(), - layout_mode_); + zcr_remote_shell_v1_send_configure(remote_shell_resource_, layout_mode_); wl_client_flush(wl_resource_get_client(remote_shell_resource_)); } @@ -2360,11 +2336,9 @@ shell_surface->set_state_changed_callback( base::Bind(&HandleRemoteSurfaceStateChangedCallback, base::Unretained(remote_surface_resource))); - if (shell->IsMultiDisplaySupported()) { - shell_surface->set_configure_callback( - base::Bind(&HandleRemoteSurfaceConfigureCallback, - base::Unretained(remote_surface_resource))); - } + shell_surface->set_configure_callback( + base::Bind(&HandleRemoteSurfaceConfigureCallback, + base::Unretained(remote_surface_resource))); SetImplementation(remote_surface_resource, &remote_surface_implementation, std::move(shell_surface));
diff --git a/components/feature_engagement/public/android/java/src/org/chromium/components/feature_engagement/EventConstants.java b/components/feature_engagement/public/android/java/src/org/chromium/components/feature_engagement/EventConstants.java index 93168d2..a82f175 100644 --- a/components/feature_engagement/public/android/java/src/org/chromium/components/feature_engagement/EventConstants.java +++ b/components/feature_engagement/public/android/java/src/org/chromium/components/feature_engagement/EventConstants.java
@@ -46,6 +46,12 @@ "bottom_sheet_expanded_from_button"; /** + * The bottom sheet was expanded by the user focusing the omnibox. + */ + public static final String BOTTOM_SHEET_EXPANDED_FROM_OMNIBOX_FOCUS = + "bottom_sheet_expanded_from_omnibox_focus"; + + /** * The user triggered pull to refresh. Used to help determine when to show the Chrome Home * in-product help. */
diff --git a/components/feedback/system_logs/system_logs_fetcher.cc b/components/feedback/system_logs/system_logs_fetcher.cc index 4e7e510..82909f28 100644 --- a/components/feedback/system_logs/system_logs_fetcher.cc +++ b/components/feedback/system_logs/system_logs_fetcher.cc
@@ -65,8 +65,9 @@ } } -void SystemLogsFetcher::OnFetched(const std::string& source_name, - SystemLogsResponse* response) { +void SystemLogsFetcher::OnFetched( + const std::string& source_name, + std::unique_ptr<SystemLogsResponse> response) { DCHECK_CURRENTLY_ON(BrowserThread::UI); VLOG(1) << "Received SystemLogSource: " << source_name; @@ -77,11 +78,12 @@ element.second = anonymizer_->Anonymize(element.second); } } - AddResponse(source_name, response); + AddResponse(source_name, std::move(response)); } -void SystemLogsFetcher::AddResponse(const std::string& source_name, - SystemLogsResponse* response) { +void SystemLogsFetcher::AddResponse( + const std::string& source_name, + std::unique_ptr<SystemLogsResponse> response) { for (const auto& it : *response) { // An element with a duplicate key would not be successfully inserted. bool ok = response_->emplace(it).second;
diff --git a/components/feedback/system_logs/system_logs_fetcher.h b/components/feedback/system_logs/system_logs_fetcher.h index 8211668..60b9d17 100644 --- a/components/feedback/system_logs/system_logs_fetcher.h +++ b/components/feedback/system_logs/system_logs_fetcher.h
@@ -43,8 +43,6 @@ class SystemLogsFetcher { public: // If scrub_data is true, logs will be anonymized. - // TODO(battre): This class needs to be expanded to provide better scrubbing - // of system logs. explicit SystemLogsFetcher(bool scrub_data); ~SystemLogsFetcher(); @@ -58,13 +56,14 @@ private: // Callback passed to all the data sources. May call Scrub(), then calls // AddResponse(). - void OnFetched(const std::string& source_name, SystemLogsResponse* response); + void OnFetched(const std::string& source_name, + std::unique_ptr<SystemLogsResponse> response); // Merges the |response| it receives into response_. When all the data sources // have responded, it deletes their objects and returns the response to the // callback_. After this it deletes this instance of the object. void AddResponse(const std::string& source_name, - SystemLogsResponse* response); + std::unique_ptr<SystemLogsResponse> response); std::vector<std::unique_ptr<SystemLogsSource>> data_sources_; SysLogsFetcherCallback callback_;
diff --git a/components/feedback/system_logs/system_logs_source.h b/components/feedback/system_logs/system_logs_source.h index 6b267ef..8a32d2d 100644 --- a/components/feedback/system_logs/system_logs_source.h +++ b/components/feedback/system_logs/system_logs_source.h
@@ -5,6 +5,7 @@ #ifndef COMPONENTS_FEEDBACK_SYSTEM_LOGS_SYSTEM_LOGS_SOURCE_H_ #define COMPONENTS_FEEDBACK_SYSTEM_LOGS_SYSTEM_LOGS_SOURCE_H_ +#include <memory> #include <string> #include "base/callback.h" @@ -15,7 +16,8 @@ using SystemLogsResponse = FeedbackCommon::SystemLogsMap; // Callback that the data sources use to return data. -using SysLogsSourceCallback = base::Callback<void(SystemLogsResponse*)>; +using SysLogsSourceCallback = + base::Callback<void(std::unique_ptr<SystemLogsResponse>)>; // The SystemLogsSource provides an interface for the data sources that // the SystemLogsFetcher class uses to fetch logs and other information.
diff --git a/components/keep_alive_registry/keep_alive_registry.cc b/components/keep_alive_registry/keep_alive_registry.cc index e29e94c0..a01e103 100644 --- a/components/keep_alive_registry/keep_alive_registry.cc +++ b/components/keep_alive_registry/keep_alive_registry.cc
@@ -26,6 +26,14 @@ return registered_count_ > 0; } +bool KeepAliveRegistry::IsKeepingAliveOnlyByBrowserOrigin() const { + for (const auto& value : registered_keep_alives_) { + if (value.first != KeepAliveOrigin::BROWSER) + return false; + } + return true; +} + bool KeepAliveRegistry::IsRestartAllowed() const { return registered_count_ == restart_allowed_count_; }
diff --git a/components/keep_alive_registry/keep_alive_registry.h b/components/keep_alive_registry/keep_alive_registry.h index 156b3292..bcddc11 100644 --- a/components/keep_alive_registry/keep_alive_registry.h +++ b/components/keep_alive_registry/keep_alive_registry.h
@@ -32,6 +32,7 @@ // Methods to query the state of the registry. bool IsKeepingAlive() const; + bool IsKeepingAliveOnlyByBrowserOrigin() const; bool IsRestartAllowed() const; bool IsOriginRegistered(KeepAliveOrigin origin) const;
diff --git a/components/metrics/metrics_state_manager.cc b/components/metrics/metrics_state_manager.cc index 0e390f83..3ab6e8d 100644 --- a/components/metrics/metrics_state_manager.cc +++ b/components/metrics/metrics_state_manager.cc
@@ -5,6 +5,7 @@ #include "components/metrics/metrics_state_manager.h" #include <stddef.h> +#include <utility> #include "base/command_line.h" #include "base/guid.h" @@ -82,7 +83,7 @@ std::string previous_client_id) : local_state_(local_state), metrics_ids_were_reset_(metrics_ids_were_reset), - previous_client_id_(previous_client_id) {} + previous_client_id_(std::move(previous_client_id)) {} // MetricsProvider: void ProvideSystemProfileMetrics( @@ -115,10 +116,10 @@ } private: - PrefService* local_state_; - bool metrics_ids_were_reset_; + PrefService* const local_state_; + const bool metrics_ids_were_reset_; // |previous_client_id_| is set only (if known) when |metrics_ids_were_reset_| - std::string previous_client_id_; + const std::string previous_client_id_; DISALLOW_COPY_AND_ASSIGN(MetricsStateMetricsProvider); };
diff --git a/components/metrics/metrics_state_manager.h b/components/metrics/metrics_state_manager.h index eb14c6c..a1a15b34 100644 --- a/components/metrics/metrics_state_manager.h +++ b/components/metrics/metrics_state_manager.h
@@ -28,7 +28,7 @@ // Responsible for managing MetricsService state prefs, specifically the UMA // client id and low entropy source. Code outside the metrics directory should // not be instantiating or using this class directly. -class MetricsStateManager { +class MetricsStateManager final { public: // A callback that can be invoked to store client info to persistent storage. // Storing an empty client_id will resulted in the backup being voided. @@ -40,7 +40,7 @@ typedef base::Callback<std::unique_ptr<ClientInfo>(void)> LoadClientInfoCallback; - virtual ~MetricsStateManager(); + ~MetricsStateManager(); std::unique_ptr<MetricsProvider> GetProvider();
diff --git a/components/metrics_services_manager/metrics_services_manager.h b/components/metrics_services_manager/metrics_services_manager.h index 3837823..1a1e81b 100644 --- a/components/metrics_services_manager/metrics_services_manager.h +++ b/components/metrics_services_manager/metrics_services_manager.h
@@ -104,7 +104,7 @@ bool current_may_upload); // The client passed in from the embedder. - std::unique_ptr<MetricsServicesManagerClient> client_; + const std::unique_ptr<MetricsServicesManagerClient> client_; // Ensures that all functions are called from the same thread. base::ThreadChecker thread_checker_;
diff --git a/components/net_log/resources/net_export.html b/components/net_log/resources/net_export.html index b6556e8..aaa5077e 100644 --- a/components/net_log/resources/net_export.html +++ b/components/net_log/resources/net_export.html
@@ -37,7 +37,7 @@ * Has controls to start logging. ========================================================================= --> - <div id="state-initial"> + <div id="state-initial" hidden> <h2>Capture Network Log</h2> <button id="start-logging">Start Logging to Disk</button> @@ -87,7 +87,7 @@ * Has controls to stop logging ========================================================================= --> - <div id="state-logging"> + <div id="state-logging" hidden> <h2>Saving network events to disk...</h2> <button id="stop-logging">Stop Logging</button> @@ -113,7 +113,7 @@ * Has controls to email the log (mobile) ========================================================================= --> - <div id="state-stopped"> + <div id="state-stopped" hidden> <h2>Log file written</h2> <if expr="is_ios or is_android">
diff --git a/components/ntp_snippets/bookmarks/bookmark_suggestions_provider.cc b/components/ntp_snippets/bookmarks/bookmark_suggestions_provider.cc index 283edaa..c0be92cb 100644 --- a/components/ntp_snippets/bookmarks/bookmark_suggestions_provider.cc +++ b/components/ntp_snippets/bookmarks/bookmark_suggestions_provider.cc
@@ -145,8 +145,7 @@ FetchBookmarks(); } -void BookmarkSuggestionsProvider::ClearCachedSuggestions(Category category) { - DCHECK_EQ(category, provided_category_); +void BookmarkSuggestionsProvider::ClearCachedSuggestions() { // Ignored. }
diff --git a/components/ntp_snippets/bookmarks/bookmark_suggestions_provider.h b/components/ntp_snippets/bookmarks/bookmark_suggestions_provider.h index 474bf5a3..ad2aca0 100644 --- a/components/ntp_snippets/bookmarks/bookmark_suggestions_provider.h +++ b/components/ntp_snippets/bookmarks/bookmark_suggestions_provider.h
@@ -40,7 +40,7 @@ base::Time begin, base::Time end, const base::Callback<bool(const GURL& url)>& filter) override; - void ClearCachedSuggestions(Category category) override; + void ClearCachedSuggestions() override; void GetDismissedSuggestionsForDebugging( Category category, DismissedSuggestionsCallback callback) override;
diff --git a/components/ntp_snippets/content_suggestions_provider.h b/components/ntp_snippets/content_suggestions_provider.h index 966155a0..71aeb10 100644 --- a/components/ntp_snippets/content_suggestions_provider.h +++ b/components/ntp_snippets/content_suggestions_provider.h
@@ -123,9 +123,9 @@ base::Time end, const base::Callback<bool(const GURL& url)>& filter) = 0; - // Clears all caches for the given category, so that the next fetch starts - // from scratch. - virtual void ClearCachedSuggestions(Category category) = 0; + // Clears suggestions for any non-history related reason (e.g., sign-in status + // change, etc.) so that the next fetch starts from scratch. + virtual void ClearCachedSuggestions() = 0; // Called when the sign in state has changed. Should be used instead of // directly registering with the SignInManager so that the
diff --git a/components/ntp_snippets/content_suggestions_service.cc b/components/ntp_snippets/content_suggestions_service.cc index fbc6a2c..2fafcfc3 100644 --- a/components/ntp_snippets/content_suggestions_service.cc +++ b/components/ntp_snippets/content_suggestions_service.cc
@@ -324,20 +324,11 @@ void ContentSuggestionsService::ClearAllCachedSuggestions() { suggestions_by_category_.clear(); - for (const auto& category_provider_pair : providers_by_category_) { - category_provider_pair.second->ClearCachedSuggestions( - category_provider_pair.first); - for (Observer& observer : observers_) { - observer.OnNewSuggestions(category_provider_pair.first); - } + for (const auto& provider : providers_) { + provider->ClearCachedSuggestions(); } -} - -void ContentSuggestionsService::ClearCachedSuggestions(Category category) { - suggestions_by_category_[category].clear(); - auto iterator = providers_by_category_.find(category); - if (iterator != providers_by_category_.end()) { - iterator->second->ClearCachedSuggestions(category); + for (Observer& observer : observers_) { + observer.OnFullRefreshRequired(); } }
diff --git a/components/ntp_snippets/content_suggestions_service.h b/components/ntp_snippets/content_suggestions_service.h index 5582a25..e9c46044 100644 --- a/components/ntp_snippets/content_suggestions_service.h +++ b/components/ntp_snippets/content_suggestions_service.h
@@ -209,17 +209,12 @@ const base::Callback<bool(const GURL& url)>& filter); // Removes all suggestions from all caches or internal stores in all - // providers. See |ClearCachedSuggestions|. + // providers. It does, however, not remove any suggestions from the provider's + // sources, so if its configuration hasn't changed, it might return the same + // results when it fetches the next time. In particular, calling this method + // will not mark any suggestions as dismissed. void ClearAllCachedSuggestions(); - // Removes all suggestions of the given |category| from all caches or internal - // stores in the service and the corresponding provider. It does, however, not - // remove any suggestions from the provider's sources, so if its configuration - // hasn't changed, it might return the same results when it fetches the next - // time. In particular, calling this method will not mark any suggestions as - // dismissed. - void ClearCachedSuggestions(Category category); - // Only for debugging use through the internals page. // Retrieves suggestions of the given |category| that have previously been // dismissed and are still stored in the respective provider. If the
diff --git a/components/ntp_snippets/mock_content_suggestions_provider.h b/components/ntp_snippets/mock_content_suggestions_provider.h index a45f6cad..22c43d1d 100644 --- a/components/ntp_snippets/mock_content_suggestions_provider.h +++ b/components/ntp_snippets/mock_content_suggestions_provider.h
@@ -64,7 +64,7 @@ void(const Category&, const std::set<std::string>&, FetchDoneCallback*)); - MOCK_METHOD1(ClearCachedSuggestions, void(Category category)); + MOCK_METHOD0(ClearCachedSuggestions, void()); void GetDismissedSuggestionsForDebugging( Category category, DismissedSuggestionsCallback callback) override;
diff --git a/components/ntp_snippets/offline_pages/recent_tab_suggestions_provider.cc b/components/ntp_snippets/offline_pages/recent_tab_suggestions_provider.cc index 73ab775..84adf71 100644 --- a/components/ntp_snippets/offline_pages/recent_tab_suggestions_provider.cc +++ b/components/ntp_snippets/offline_pages/recent_tab_suggestions_provider.cc
@@ -135,7 +135,7 @@ FetchRecentTabs(); } -void RecentTabSuggestionsProvider::ClearCachedSuggestions(Category category) { +void RecentTabSuggestionsProvider::ClearCachedSuggestions() { // Ignored. }
diff --git a/components/ntp_snippets/offline_pages/recent_tab_suggestions_provider.h b/components/ntp_snippets/offline_pages/recent_tab_suggestions_provider.h index 83d49b15..0dd05266 100644 --- a/components/ntp_snippets/offline_pages/recent_tab_suggestions_provider.h +++ b/components/ntp_snippets/offline_pages/recent_tab_suggestions_provider.h
@@ -51,7 +51,7 @@ base::Time begin, base::Time end, const base::Callback<bool(const GURL& url)>& filter) override; - void ClearCachedSuggestions(Category category) override; + void ClearCachedSuggestions() override; void GetDismissedSuggestionsForDebugging( Category category, DismissedSuggestionsCallback callback) override;
diff --git a/components/ntp_snippets/physical_web_pages/physical_web_page_suggestions_provider.cc b/components/ntp_snippets/physical_web_pages/physical_web_page_suggestions_provider.cc index d7ad5373..8d05d52 100644 --- a/components/ntp_snippets/physical_web_pages/physical_web_page_suggestions_provider.cc +++ b/components/ntp_snippets/physical_web_pages/physical_web_page_suggestions_provider.cc
@@ -166,8 +166,7 @@ ClearDismissedSuggestionsForDebugging(provided_category_); } -void PhysicalWebPageSuggestionsProvider::ClearCachedSuggestions( - Category category) { +void PhysicalWebPageSuggestionsProvider::ClearCachedSuggestions() { // Ignored }
diff --git a/components/ntp_snippets/physical_web_pages/physical_web_page_suggestions_provider.h b/components/ntp_snippets/physical_web_pages/physical_web_page_suggestions_provider.h index 1c356c4..20c00f8 100644 --- a/components/ntp_snippets/physical_web_pages/physical_web_page_suggestions_provider.h +++ b/components/ntp_snippets/physical_web_pages/physical_web_page_suggestions_provider.h
@@ -51,7 +51,7 @@ base::Time begin, base::Time end, const base::Callback<bool(const GURL& url)>& filter) override; - void ClearCachedSuggestions(Category category) override; + void ClearCachedSuggestions() override; void GetDismissedSuggestionsForDebugging( Category category, DismissedSuggestionsCallback callback) override;
diff --git a/components/ntp_snippets/reading_list/reading_list_suggestions_provider.cc b/components/ntp_snippets/reading_list/reading_list_suggestions_provider.cc index 7690d2e..57a715f 100644 --- a/components/ntp_snippets/reading_list/reading_list_suggestions_provider.cc +++ b/components/ntp_snippets/reading_list/reading_list_suggestions_provider.cc
@@ -107,8 +107,7 @@ // Ignored, Reading List does not depend on history. } -void ReadingListSuggestionsProvider::ClearCachedSuggestions(Category category) { - DCHECK_EQ(category, provided_category_); +void ReadingListSuggestionsProvider::ClearCachedSuggestions() { // Ignored. }
diff --git a/components/ntp_snippets/reading_list/reading_list_suggestions_provider.h b/components/ntp_snippets/reading_list/reading_list_suggestions_provider.h index 4fbfc8e..69c603f 100644 --- a/components/ntp_snippets/reading_list/reading_list_suggestions_provider.h +++ b/components/ntp_snippets/reading_list/reading_list_suggestions_provider.h
@@ -42,7 +42,7 @@ base::Time begin, base::Time end, const base::Callback<bool(const GURL& url)>& filter) override; - void ClearCachedSuggestions(Category category) override; + void ClearCachedSuggestions() override; void GetDismissedSuggestionsForDebugging( Category category, DismissedSuggestionsCallback callback) override;
diff --git a/components/ntp_snippets/remote/remote_suggestions_provider_impl.cc b/components/ntp_snippets/remote/remote_suggestions_provider_impl.cc index d06539b..32fe6e5 100644 --- a/components/ntp_snippets/remote/remote_suggestions_provider_impl.cc +++ b/components/ntp_snippets/remote/remote_suggestions_provider_impl.cc
@@ -385,6 +385,7 @@ image_fetcher_(std::move(image_fetcher), pref_service, database_.get()), status_service_(std::move(status_service)), clear_history_dependent_state_when_initialized_(false), + clear_cached_suggestions_when_initialized_(false), clock_(base::MakeUnique<base::DefaultClock>()), prefetched_pages_tracker_(std::move(prefetched_pages_tracker)), breaking_news_raw_data_provider_( @@ -726,32 +727,6 @@ ClearHistoryDependentState(); } -void RemoteSuggestionsProviderImpl::ClearCachedSuggestions(Category category) { - if (!initialized()) { - categories_clear_when_initialized_.insert(category); - return; - } - - auto content_it = category_contents_.find(category); - if (content_it == category_contents_.end()) { - return; - } - CategoryContent* content = &content_it->second; - // TODO(tschumann): We do the unnecessary checks for .empty() in many places - // before calling database methods. Change the RemoteSuggestionsDatabase to - // return early for those and remove the many if statements in this file. - if (!content->suggestions.empty()) { - database_->DeleteSnippets(GetSuggestionIDVector(content->suggestions)); - database_->DeleteImages(GetSuggestionIDVector(content->suggestions)); - content->suggestions.clear(); - } - if (!content->archived.empty()) { - database_->DeleteSnippets(GetSuggestionIDVector(content->archived)); - database_->DeleteImages(GetSuggestionIDVector(content->archived)); - content->archived.clear(); - } -} - void RemoteSuggestionsProviderImpl::OnSignInStateChanged() { // Make sure the status service is registered and we already initialised its // start state. @@ -1361,24 +1336,41 @@ remote_suggestions_scheduler_->OnHistoryCleared(); } -void RemoteSuggestionsProviderImpl::ClearSuggestions() { - DCHECK(initialized()); +void RemoteSuggestionsProviderImpl::ClearCachedSuggestions() { + if (!initialized()) { + clear_cached_suggestions_when_initialized_ = true; + return; + } NukeAllSuggestions(); remote_suggestions_scheduler_->OnSuggestionsCleared(); } void RemoteSuggestionsProviderImpl::NukeAllSuggestions() { + DCHECK(initialized()); // TODO(tschumann): Should Nuke also cancel outstanding requests? Or should we // only block the results of such outstanding requests? - for (const auto& item : category_contents_) { + for (auto& item : category_contents_) { Category category = item.first; - const CategoryContent& content = item.second; + CategoryContent* content = &item.second; - ClearCachedSuggestions(category); + // TODO(tschumann): We do the unnecessary checks for .empty() in many places + // before calling database methods. Change the RemoteSuggestionsDatabase to + // return early for those and remove the many if statements in this file. + if (!content->suggestions.empty()) { + database_->DeleteSnippets(GetSuggestionIDVector(content->suggestions)); + database_->DeleteImages(GetSuggestionIDVector(content->suggestions)); + content->suggestions.clear(); + } + if (!content->archived.empty()) { + database_->DeleteSnippets(GetSuggestionIDVector(content->archived)); + database_->DeleteImages(GetSuggestionIDVector(content->archived)); + content->archived.clear(); + } + // Update listeners about the new (empty) state. - if (IsCategoryStatusAvailable(content.status)) { - NotifyNewSuggestions(category, content.suggestions); + if (IsCategoryStatusAvailable(content->status)) { + NotifyNewSuggestions(category, content->suggestions); } // TODO(tschumann): We should not call debug code from production code. ClearDismissedSuggestionsForDebugging(category); @@ -1476,7 +1468,7 @@ DCHECK(state_ == State::READY); // Clear nonpersonalized suggestions (and notify the scheduler there are // no suggestions). - ClearSuggestions(); + ClearCachedSuggestions(); } else { EnterState(State::READY); } @@ -1487,7 +1479,7 @@ DCHECK(state_ == State::READY); // Clear personalized suggestions (and notify the scheduler there are // no suggestions). - ClearSuggestions(); + ClearCachedSuggestions(); } else { EnterState(State::READY); } @@ -1527,11 +1519,9 @@ UpdateAllCategoryStatus(CategoryStatus::AVAILABLE); - if (!categories_clear_when_initialized_.empty()) { - for (auto category : categories_clear_when_initialized_) { - ClearCachedSuggestions(category); - } - categories_clear_when_initialized_.clear(); + if (clear_cached_suggestions_when_initialized_) { + ClearCachedSuggestions(); + clear_cached_suggestions_when_initialized_ = false; } if (clear_history_dependent_state_when_initialized_) { clear_history_dependent_state_when_initialized_ = false; @@ -1552,17 +1542,13 @@ // suggestions below tells the scheduler to fetch them again if the // scheduler is not disabled. It is disabled; thus the calls are ignored. NotifyStateChanged(); - if (!categories_clear_when_initialized_.empty()) { - for (auto category : categories_clear_when_initialized_) { - ClearCachedSuggestions(category); - } - categories_clear_when_initialized_.clear(); - } if (clear_history_dependent_state_when_initialized_) { clear_history_dependent_state_when_initialized_ = false; ClearHistoryDependentState(); } - ClearSuggestions(); + ClearCachedSuggestions(); + clear_cached_suggestions_when_initialized_ = false; + if (breaking_news_raw_data_provider_ && breaking_news_raw_data_provider_->IsListening()) { breaking_news_raw_data_provider_->StopListening();
diff --git a/components/ntp_snippets/remote/remote_suggestions_provider_impl.h b/components/ntp_snippets/remote/remote_suggestions_provider_impl.h index e20b5b8..c8292e0 100644 --- a/components/ntp_snippets/remote/remote_suggestions_provider_impl.h +++ b/components/ntp_snippets/remote/remote_suggestions_provider_impl.h
@@ -110,7 +110,7 @@ base::Time begin, base::Time end, const base::Callback<bool(const GURL& url)>& filter) override; - void ClearCachedSuggestions(Category category) override; + void ClearCachedSuggestions() override; void OnSignInStateChanged() override; void GetDismissedSuggestionsForDebugging( Category category, @@ -335,10 +335,6 @@ // Clears suggestions because any history item has been removed. void ClearHistoryDependentState(); - // Clears suggestions for any non-history related reason (e.g., sign-in status - // change, etc.). - void ClearSuggestions(); - // Clears all stored suggestions and updates the observer. void NukeAllSuggestions(); @@ -432,10 +428,10 @@ // or enters the READY state. bool clear_history_dependent_state_when_initialized_; - // Set containing the categories for which ClearCachedSuggestions has been - // called while the service isn't ready. The nuke will be executed once the - // service finishes initialization or enters the READY state. - std::set<Category, Category::CompareByID> categories_clear_when_initialized_; + // Set to true if ClearCachedSuggestions has been called while the service + // isn't ready. The clearing will be executed once the service finishes + // initialization or enters the READY state. + bool clear_cached_suggestions_when_initialized_; // A clock for getting the time. This allows to inject a clock in tests. std::unique_ptr<base::Clock> clock_;
diff --git a/components/ntp_snippets/remote/remote_suggestions_provider_impl_unittest.cc b/components/ntp_snippets/remote/remote_suggestions_provider_impl_unittest.cc index 7b20454..2c8651f 100644 --- a/components/ntp_snippets/remote/remote_suggestions_provider_impl_unittest.cc +++ b/components/ntp_snippets/remote/remote_suggestions_provider_impl_unittest.cc
@@ -1210,8 +1210,7 @@ /*use_mock_prefetched_pages_tracker=*/false, /*use_fake_breaking_news_listener=*/false, /*use_mock_remote_suggestions_status_service=*/false); - provider->ClearCachedSuggestions(Category::FromRemoteCategory(1)); - provider->ClearCachedSuggestions(Category::FromRemoteCategory(2)); + provider->ClearCachedSuggestions(); // The suggestions in both categories should have been cleared after the init. WaitForSuggestionsProviderInitialization(provider.get()); @@ -1283,7 +1282,7 @@ EXPECT_THAT(provider->GetSuggestionsForTesting(articles_category()), SizeIs(1)); - provider->ClearCachedSuggestions(articles_category()); + provider->ClearCachedSuggestions(); EXPECT_THAT(provider->GetSuggestionsForTesting(articles_category()), IsEmpty()); }
diff --git a/components/ntp_snippets/remote/remote_suggestions_scheduler_impl_unittest.cc b/components/ntp_snippets/remote/remote_suggestions_scheduler_impl_unittest.cc index f03381a4..92891d5d 100644 --- a/components/ntp_snippets/remote/remote_suggestions_scheduler_impl_unittest.cc +++ b/components/ntp_snippets/remote/remote_suggestions_scheduler_impl_unittest.cc
@@ -133,7 +133,7 @@ const std::set<std::string>&, FetchDoneCallback*)); MOCK_METHOD0(ReloadSuggestions, void()); - MOCK_METHOD1(ClearCachedSuggestions, void(Category)); + MOCK_METHOD0(ClearCachedSuggestions, void()); MOCK_METHOD1(ClearDismissedSuggestionsForDebugging, void(Category)); MOCK_METHOD1(DismissSuggestion, void(const ContentSuggestion::ID&)); // Gmock cannot mock a method with movable-only type callback
diff --git a/components/ntp_snippets/sessions/foreign_sessions_suggestions_provider.cc b/components/ntp_snippets/sessions/foreign_sessions_suggestions_provider.cc index e59f1071..dbdb6013 100644 --- a/components/ntp_snippets/sessions/foreign_sessions_suggestions_provider.cc +++ b/components/ntp_snippets/sessions/foreign_sessions_suggestions_provider.cc
@@ -257,9 +257,7 @@ dismissed_ids); } -void ForeignSessionsSuggestionsProvider::ClearCachedSuggestions( - Category category) { - DCHECK_EQ(category, provided_category_); +void ForeignSessionsSuggestionsProvider::ClearCachedSuggestions() { // Ignored. }
diff --git a/components/ntp_snippets/sessions/foreign_sessions_suggestions_provider.h b/components/ntp_snippets/sessions/foreign_sessions_suggestions_provider.h index 3450c80..0399a8b1 100644 --- a/components/ntp_snippets/sessions/foreign_sessions_suggestions_provider.h +++ b/components/ntp_snippets/sessions/foreign_sessions_suggestions_provider.h
@@ -63,7 +63,7 @@ base::Time begin, base::Time end, const base::Callback<bool(const GURL& url)>& filter) override; - void ClearCachedSuggestions(Category category) override; + void ClearCachedSuggestions() override; void GetDismissedSuggestionsForDebugging( Category category, DismissedSuggestionsCallback callback) override;
diff --git a/components/offline_pages/core/model/add_page_task.cc b/components/offline_pages/core/model/add_page_task.cc index fc49d20..7e81f26 100644 --- a/components/offline_pages/core/model/add_page_task.cc +++ b/components/offline_pages/core/model/add_page_task.cc
@@ -82,7 +82,9 @@ : store_(store), offline_page_(offline_page), callback_(std::move(callback)), - weak_ptr_factory_(this) {} + weak_ptr_factory_(this) { + DCHECK(!callback_.is_null()); +} AddPageTask::~AddPageTask() {}
diff --git a/components/offline_pages/core/model/clear_digest_task.cc b/components/offline_pages/core/model/clear_digest_task.cc index 3ff412b9..0348793419 100644 --- a/components/offline_pages/core/model/clear_digest_task.cc +++ b/components/offline_pages/core/model/clear_digest_task.cc
@@ -30,7 +30,9 @@ ClearDigestTask::ClearDigestTask(OfflinePageMetadataStoreSQL* store, int64_t offline_id) - : store_(store), offline_id_(offline_id), weak_ptr_factory_(this) {} + : store_(store), offline_id_(offline_id), weak_ptr_factory_(this) { + DCHECK(store_); +} ClearDigestTask::~ClearDigestTask(){};
diff --git a/components/offline_pages/core/model/clear_legacy_temporary_pages_task.cc b/components/offline_pages/core/model/clear_legacy_temporary_pages_task.cc index b844290e..b2802c85 100644 --- a/components/offline_pages/core/model/clear_legacy_temporary_pages_task.cc +++ b/components/offline_pages/core/model/clear_legacy_temporary_pages_task.cc
@@ -120,7 +120,10 @@ : store_(store), policy_controller_(policy_controller), legacy_archives_dir_(legacy_archives_dir), - weak_ptr_factory_(this) {} + weak_ptr_factory_(this) { + DCHECK(store_); + DCHECK(policy_controller_); +} ClearLegacyTemporaryPagesTask::~ClearLegacyTemporaryPagesTask() {}
diff --git a/components/offline_pages/core/model/clear_storage_task.cc b/components/offline_pages/core/model/clear_storage_task.cc index f711daa..5729bc0 100644 --- a/components/offline_pages/core/model/clear_storage_task.cc +++ b/components/offline_pages/core/model/clear_storage_task.cc
@@ -230,7 +230,12 @@ policy_controller_(policy_controller), callback_(std::move(callback)), clearup_time_(clearup_time), - weak_ptr_factory_(this) {} + weak_ptr_factory_(this) { + DCHECK(store_); + DCHECK(archive_manager_); + DCHECK(policy_controller_); + DCHECK(!callback_.is_null()); +} ClearStorageTask::~ClearStorageTask() {}
diff --git a/components/offline_pages/core/model/create_archive_task.cc b/components/offline_pages/core/model/create_archive_task.cc index 2291757..4258913 100644 --- a/components/offline_pages/core/model/create_archive_task.cc +++ b/components/offline_pages/core/model/create_archive_task.cc
@@ -25,7 +25,9 @@ archiver_(archiver), callback_(callback), clock_(new base::DefaultClock()), - skip_clearing_original_url_for_testing_(false) {} + skip_clearing_original_url_for_testing_(false) { + DCHECK(!callback_.is_null()); +} CreateArchiveTask::~CreateArchiveTask() {}
diff --git a/components/offline_pages/core/model/delete_page_task.cc b/components/offline_pages/core/model/delete_page_task.cc index 0d0ef01..61d8c06 100644 --- a/components/offline_pages/core/model/delete_page_task.cc +++ b/components/offline_pages/core/model/delete_page_task.cc
@@ -394,7 +394,10 @@ : store_(store), func_(std::move(func)), callback_(std::move(callback)), - weak_ptr_factory_(this) {} + weak_ptr_factory_(this) { + DCHECK(store_); + DCHECK(!callback_.is_null()); +} DeletePageTask::~DeletePageTask() {}
diff --git a/components/offline_pages/core/model/mark_page_accessed_task.cc b/components/offline_pages/core/model/mark_page_accessed_task.cc index d5d749b..d380a75 100644 --- a/components/offline_pages/core/model/mark_page_accessed_task.cc +++ b/components/offline_pages/core/model/mark_page_accessed_task.cc
@@ -38,7 +38,9 @@ : store_(store), offline_id_(offline_id), access_time_(access_time), - weak_ptr_factory_(this) {} + weak_ptr_factory_(this) { + DCHECK(store_); +} MarkPageAccessedTask::~MarkPageAccessedTask(){};
diff --git a/components/offline_pages/core/model/persistent_pages_consistency_check_task.cc b/components/offline_pages/core/model/persistent_pages_consistency_check_task.cc index 629551c..cdaf304a 100644 --- a/components/offline_pages/core/model/persistent_pages_consistency_check_task.cc +++ b/components/offline_pages/core/model/persistent_pages_consistency_check_task.cc
@@ -156,7 +156,10 @@ : store_(store), policy_controller_(policy_controller), archives_dir_(archives_dir), - weak_ptr_factory_(this) {} + weak_ptr_factory_(this) { + DCHECK(store_); + DCHECK(policy_controller_); +} PersistentPagesConsistencyCheckTask::~PersistentPagesConsistencyCheckTask() {}
diff --git a/components/offline_pages/core/model/temporary_pages_consistency_check_task.cc b/components/offline_pages/core/model/temporary_pages_consistency_check_task.cc index 17373528..b23e79a 100644 --- a/components/offline_pages/core/model/temporary_pages_consistency_check_task.cc +++ b/components/offline_pages/core/model/temporary_pages_consistency_check_task.cc
@@ -150,7 +150,10 @@ : store_(store), policy_controller_(policy_controller), archives_dir_(archives_dir), - weak_ptr_factory_(this) {} + weak_ptr_factory_(this) { + DCHECK(store_); + DCHECK(policy_controller_); +} TemporaryPagesConsistencyCheckTask::~TemporaryPagesConsistencyCheckTask() {}
diff --git a/components/omnibox/browser/omnibox_field_trial.cc b/components/omnibox/browser/omnibox_field_trial.cc index 306cc51..450d46f 100644 --- a/components/omnibox/browser/omnibox_field_trial.cc +++ b/components/omnibox/browser/omnibox_field_trial.cc
@@ -36,14 +36,6 @@ namespace omnibox { -// Feature used to enable the new set of answers in suggest types (currency, -// dictionary, sports, translation, when is). Note that the state of this -// Feature is not consulted anywhere in the code. It is only used to force a -// Finch experiment arm which sends an experiment ID to GWS which triggers -// serving the new types. -const base::Feature kNewOmniboxAnswerTypes{"NewOmniboxAnswerTypes", - base::FEATURE_DISABLED_BY_DEFAULT}; - // Feature used to enable the transmission of entity suggestions from GWS // to this client. const base::Feature kOmniboxEntitySuggestions{ @@ -333,6 +325,7 @@ #endif } +// static bool OmniboxFieldTrial::InZeroSuggestPersonalizedFieldTrial( PrefService* prefs) { std::string variant(variations::GetVariationParamValue(
diff --git a/components/omnibox/browser/omnibox_field_trial.h b/components/omnibox/browser/omnibox_field_trial.h index b0917ce..0dffa8b 100644 --- a/components/omnibox/browser/omnibox_field_trial.h +++ b/components/omnibox/browser/omnibox_field_trial.h
@@ -34,7 +34,6 @@ namespace omnibox { -extern const base::Feature kNewOmniboxAnswerTypes; extern const base::Feature kOmniboxEntitySuggestions; extern const base::Feature kOmniboxTailSuggestions; extern const base::Feature kOmniboxTabSwitchSuggestions;
diff --git a/components/omnibox/browser/zero_suggest_provider.cc b/components/omnibox/browser/zero_suggest_provider.cc index 1dea4b6..8068d2b 100644 --- a/components/omnibox/browser/zero_suggest_provider.cc +++ b/components/omnibox/browser/zero_suggest_provider.cc
@@ -35,6 +35,7 @@ #include "components/omnibox/browser/verbatim_match.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/pref_service.h" +#include "components/search_engines/search_engine_type.h" #include "components/search_engines/template_url_service.h" #include "components/url_formatter/url_formatter.h" #include "components/variations/net/variations_http_headers.h" @@ -86,6 +87,31 @@ // Used for testing whether zero suggest is ever available. constexpr char kArbitraryInsecureUrlString[] = "http://www.google.com/"; +// Used to determine whether or not Most Visited URLs will be displayed. +// This is true in either of these two cases: +// 1. The user is in zero suggest most visited field trial. +// 2. The user is in zero suggest field trial that enables search-for +// queries as suggestions and the user does not have Google set up as +// their default search engine +bool DisplayZeroSuggestMostVisitedURLs( + PrefService* prefs, + const TemplateURLService* template_url_service) { + if (OmniboxFieldTrial::InZeroSuggestMostVisitedFieldTrial(prefs)) + return true; + + if (OmniboxFieldTrial::InZeroSuggestPersonalizedFieldTrial(prefs) && + template_url_service != nullptr) { + const TemplateURL* default_provider = + template_url_service->GetDefaultSearchProvider(); + return default_provider == nullptr || + default_provider->GetEngineType( + template_url_service->search_terms_data()) != + SEARCH_ENGINE_GOOGLE; + } + + return false; +} + } // namespace // static @@ -170,8 +196,8 @@ // suggestions, if based on local browsing history. MaybeUseCachedSuggestions(); - if (OmniboxFieldTrial::InZeroSuggestMostVisitedFieldTrial( - client()->GetPrefs())) { + if (DisplayZeroSuggestMostVisitedURLs(client()->GetPrefs(), + template_url_service)) { most_visited_urls_.clear(); scoped_refptr<history::TopSites> ts = client()->GetTopSites(); if (ts) { @@ -442,8 +468,8 @@ UMA_HISTOGRAM_COUNTS("ZeroSuggest.AllResults", num_results); // Show Most Visited results after ZeroSuggest response is received. - if (OmniboxFieldTrial::InZeroSuggestMostVisitedFieldTrial( - client()->GetPrefs())) { + if (DisplayZeroSuggestMostVisitedURLs(client()->GetPrefs(), + template_url_service)) { if (!current_url_match_.destination_url.is_valid()) return; matches_.push_back(current_url_match_);
diff --git a/components/onc/docs/onc_spec.md b/components/onc/docs/onc_spec.md index 8605291..b451ba6 100644 --- a/components/onc/docs/onc_spec.md +++ b/components/onc/docs/onc_spec.md
@@ -1207,6 +1207,16 @@ * WiFi only. A substring which a remote RADIUS service certificate subject name must contain in order to connect. +* **TLSVersionMax** + * (optional) - **string** + * Sets the maximum TLS protocol version used by the OS for EAP. + This is only needed when connecting to an AP with a buggy TLS + implementation, as the protocol will normally auto-negotiate. + * Allowed values are: + * *1.0* + * *1.1* + * *1.2* + * **UseSystemCAs** * (optional, defaults to *true*) - **boolean** * Required server certificate to be signed by "system default certificate
diff --git a/components/onc/onc_constants.cc b/components/onc/onc_constants.cc index b6456bb..077a35ff 100644 --- a/components/onc/onc_constants.cc +++ b/components/onc/onc_constants.cc
@@ -315,6 +315,7 @@ const char kServerCARef[] = "ServerCARef"; const char kServerCARefs[] = "ServerCARefs"; const char kSubjectMatch[] = "SubjectMatch"; +const char kTLSVersionMax[] = "TLSVersionMax"; const char kUseSystemCAs[] = "UseSystemCAs"; const char kUseProactiveKeyCaching[] = "UseProactiveKeyCaching"; } // namespace eap
diff --git a/components/onc/onc_constants.h b/components/onc/onc_constants.h index c31bb0a..a1d9a1f 100644 --- a/components/onc/onc_constants.h +++ b/components/onc/onc_constants.h
@@ -328,6 +328,7 @@ ONC_EXPORT extern const char kServerCARef[]; ONC_EXPORT extern const char kServerCARefs[]; ONC_EXPORT extern const char kSubjectMatch[]; +ONC_EXPORT extern const char kTLSVersionMax[]; ONC_EXPORT extern const char kUseSystemCAs[]; ONC_EXPORT extern const char kUseProactiveKeyCaching[]; } // namespace eap
diff --git a/components/password_manager/content/renderer/DEPS b/components/password_manager/content/renderer/DEPS index d30225b5..440a225 100644 --- a/components/password_manager/content/renderer/DEPS +++ b/components/password_manager/content/renderer/DEPS
@@ -3,6 +3,7 @@ "+content/public/renderer", "+content/test", "+services/service_manager/public/cpp", + "+third_party/WebKit/common", "+third_party/WebKit/public/platform", "+third_party/WebKit/public/web", ]
diff --git a/components/password_manager/content/renderer/credential_manager_client.cc b/components/password_manager/content/renderer/credential_manager_client.cc index e6e04967..c394e25 100644 --- a/components/password_manager/content/renderer/credential_manager_client.cc +++ b/components/password_manager/content/renderer/credential_manager_client.cc
@@ -12,9 +12,9 @@ #include "base/bind.h" #include "base/logging.h" #include "components/password_manager/core/common/credential_manager_types.h" -#include "content/public/common/associated_interface_provider.h" #include "content/public/renderer/render_frame.h" #include "content/public/renderer/render_view.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" #include "third_party/WebKit/public/platform/WebCredential.h" #include "third_party/WebKit/public/platform/WebCredentialManagerError.h" #include "third_party/WebKit/public/platform/WebFederatedCredential.h"
diff --git a/components/password_manager/content/renderer/credential_manager_client_browsertest.cc b/components/password_manager/content/renderer/credential_manager_client_browsertest.cc index c02af2a..fca3c878 100644 --- a/components/password_manager/content/renderer/credential_manager_client_browsertest.cc +++ b/components/password_manager/content/renderer/credential_manager_client_browsertest.cc
@@ -13,13 +13,13 @@ #include "base/location.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" -#include "content/public/common/associated_interface_provider.h" #include "content/public/renderer/render_frame.h" #include "content/public/renderer/render_view.h" #include "content/public/test/render_view_test.h" #include "content/public/test/test_utils.h" #include "mojo/public/cpp/bindings/associated_binding_set.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" #include "third_party/WebKit/public/platform/WebCredential.h" #include "third_party/WebKit/public/platform/WebCredentialManagerClient.h" #include "third_party/WebKit/public/platform/WebCredentialManagerError.h" @@ -86,7 +86,7 @@ content::RenderViewTest::SetUp(); client_.reset(new CredentialManagerClient(view_)); - content::AssociatedInterfaceProvider* remote_interfaces = + blink::AssociatedInterfaceProvider* remote_interfaces = view_->GetMainRenderFrame()->GetRemoteAssociatedInterfaces(); remote_interfaces->OverrideBinderForTesting( mojom::CredentialManager::Name_,
diff --git a/components/password_manager/core/browser/password_form_manager.cc b/components/password_manager/core/browser/password_form_manager.cc index 8f44c97..ee374a2 100644 --- a/components/password_manager/core/browser/password_form_manager.cc +++ b/components/password_manager/core/browser/password_form_manager.cc
@@ -213,6 +213,7 @@ std::unique_ptr<FormSaver> form_saver, FormFetcher* form_fetcher) : observed_form_(observed_form), + observed_form_signature_(CalculateFormSignature(observed_form.form_data)), other_possible_username_action_( PasswordFormManager::IGNORE_OTHER_POSSIBLE_USERNAMES), form_path_segments_( @@ -337,8 +338,7 @@ result |= RESULT_ORIGINS_OR_FRAMES_MATCH; - if (CalculateFormSignature(form.form_data) == - CalculateFormSignature(observed_form_.form_data)) + if (CalculateFormSignature(form.form_data) == observed_form_signature_) result |= RESULT_SIGNATURE_MATCH; if (!form.form_data.name.empty() && @@ -873,8 +873,7 @@ // re-uses credentials, a vote about the saved form is sent. If the user saves // credentials, the observed and pending forms are the same. FormStructure form_structure(form_to_upload.form_data); - if (!autofill_manager->ShouldUploadForm(form_structure) || - !form_structure.ShouldBeCrowdsourced()) { + if (!autofill_manager->ShouldUploadForm(form_structure)) { UMA_HISTOGRAM_BOOLEAN("PasswordGeneration.UploadStarted", false); return false; } @@ -1511,8 +1510,9 @@ *username_correction_vote_, autofill::USERNAME, FormStructure(observed_form_.form_data).FormSignatureAsStr()); } - } else + } else { SendVoteOnCredentialsReuse(observed_form_, &pending_credentials_); + } } void PasswordFormManager::SendSignInVote(const FormData& form_data) { @@ -1522,7 +1522,7 @@ return; std::unique_ptr<FormStructure> form_structure(new FormStructure(form_data)); form_structure->set_is_signin_upload(true); - DCHECK(form_structure->ShouldBeCrowdsourced()); + DCHECK(form_structure->ShouldBeUploaded()); DCHECK_EQ(2u, form_structure->field_count()); form_structure->field(1)->set_possible_types({autofill::PASSWORD}); autofill_manager->StartUploadProcess(std::move(form_structure),
diff --git a/components/password_manager/core/browser/password_form_manager.h b/components/password_manager/core/browser/password_form_manager.h index 1b0ab1b..c40125a 100644 --- a/components/password_manager/core/browser/password_form_manager.h +++ b/components/password_manager/core/browser/password_form_manager.h
@@ -20,6 +20,7 @@ #include "components/autofill/core/browser/field_types.h" #include "components/autofill/core/browser/form_structure.h" #include "components/autofill/core/common/password_form.h" +#include "components/autofill/core/common/signatures_util.h" #include "components/password_manager/core/browser/form_fetcher.h" #include "components/password_manager/core/browser/password_form_metrics_recorder.h" #include "components/password_manager/core/browser/password_form_user_action.h" @@ -478,6 +479,9 @@ // The PasswordForm from the page or dialog managed by |this|. const autofill::PasswordForm observed_form_; + // The form signature of |observed_form_| + const autofill::FormSignature observed_form_signature_; + // Stores a submitted form. std::unique_ptr<const autofill::PasswordForm> submitted_form_;
diff --git a/components/password_manager/core/browser/password_form_manager_unittest.cc b/components/password_manager/core/browser/password_form_manager_unittest.cc index 9b84089..8a93eb9 100644 --- a/components/password_manager/core/browser/password_form_manager_unittest.cc +++ b/components/password_manager/core/browser/password_form_manager_unittest.cc
@@ -18,11 +18,13 @@ #include "base/test/histogram_tester.h" #include "base/test/scoped_feature_list.h" #include "base/test/user_action_tester.h" +#include "components/autofill/core/browser/autofill_experiments.h" #include "components/autofill/core/browser/autofill_manager.h" #include "components/autofill/core/browser/proto/server.pb.h" #include "components/autofill/core/browser/test_autofill_client.h" #include "components/autofill/core/browser/test_autofill_driver.h" #include "components/autofill/core/browser/test_personal_data_manager.h" +#include "components/autofill/core/common/autofill_features.h" #include "components/autofill/core/common/autofill_pref_names.h" #include "components/autofill/core/common/password_form.h" #include "components/password_manager/core/browser/fake_form_fetcher.h" @@ -46,6 +48,9 @@ #include "url/gurl.h" #include "url/origin.h" +using autofill::features::kAutofillEnforceMinRequiredFieldsForHeuristics; +using autofill::features::kAutofillEnforceMinRequiredFieldsForQuery; +using autofill::features::kAutofillEnforceMinRequiredFieldsForUpload; using autofill::FieldPropertiesFlags; using autofill::FieldPropertiesMask; using autofill::PasswordForm; @@ -409,7 +414,7 @@ psl_saved_match_.signon_realm = "http://m.accounts.google.com"; autofill::FormFieldData field; - field.label = ASCIIToUTF16("full_name"); + field.label = ASCIIToUTF16("Full name"); field.name = ASCIIToUTF16("full_name"); field.form_control_type = "text"; saved_match_.form_data.fields.push_back(field); @@ -3368,6 +3373,11 @@ } TEST_F(PasswordFormManagerTest, UploadUsernameCorrectionVote) { + // TODO(rogerm,kolos): Fix this test so that it works correctly when the + // enforcement of the minimum number of required for fields is upload is + // relaxed. + base::test::ScopedFeatureList features; + features.InitAndEnableFeature(kAutofillEnforceMinRequiredFieldsForUpload); for (bool is_form_with_2_fields : {false, true}) { SCOPED_TRACE(testing::Message() << "is_form_with_2_fields=" << is_form_with_2_fields);
diff --git a/components/password_manager/core/browser/password_syncable_service_unittest.cc b/components/password_manager/core/browser/password_syncable_service_unittest.cc index 7473f08..9f1975d0 100644 --- a/components/password_manager/core/browser/password_syncable_service_unittest.cc +++ b/components/password_manager/core/browser/password_syncable_service_unittest.cc
@@ -1004,7 +1004,7 @@ const bool local_data_correct = !!combination[1]; for (unsigned val = 0; val < 2 * 2; ++val) { - std::vector<unsigned> dates = ExtractTimestamps(i, 2); + std::vector<unsigned> dates = ExtractTimestamps(val, 2); ASSERT_EQ(2u, dates.size()); const PasswordFormData sync_data = sync_data_correct
diff --git a/components/pdf/renderer/DEPS b/components/pdf/renderer/DEPS index 9401253..2ab25aa 100644 --- a/components/pdf/renderer/DEPS +++ b/components/pdf/renderer/DEPS
@@ -3,6 +3,7 @@ "+gin", "+mojo/public/cpp/bindings", "+skia/ext", + "+third_party/WebKit/common", "+ui/accessibility", "+ui/gfx", ]
diff --git a/components/pdf/renderer/pepper_pdf_host.cc b/components/pdf/renderer/pepper_pdf_host.cc index 6280016..4610a20 100644 --- a/components/pdf/renderer/pepper_pdf_host.cc +++ b/components/pdf/renderer/pepper_pdf_host.cc
@@ -7,7 +7,6 @@ #include "base/lazy_instance.h" #include "base/memory/ptr_util.h" #include "components/pdf/renderer/pdf_accessibility_tree.h" -#include "content/public/common/associated_interface_provider.h" #include "content/public/common/referrer.h" #include "content/public/renderer/pepper_plugin_instance.h" #include "content/public/renderer/render_frame.h" @@ -23,6 +22,7 @@ #include "ppapi/shared_impl/scoped_pp_resource.h" #include "ppapi/thunk/enter.h" #include "ppapi/thunk/ppb_image_data_api.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" namespace pdf {
diff --git a/components/policy/resources/policy_templates.json b/components/policy/resources/policy_templates.json index 3f90b41..6d6f7b4 100644 --- a/components/policy/resources/policy_templates.json +++ b/components/policy/resources/policy_templates.json
@@ -8481,12 +8481,11 @@ 'name': 'ForceBrowserSignin', 'type': 'main', 'schema': { 'type': 'boolean' }, - 'supported_on': ['chrome.win:62-', 'chrome.linux:62-', 'android:63-'], + 'supported_on': ['chrome.win:64-', 'android:65-'], 'features': { 'dynamic_refresh': False, 'per_profile': False, }, - 'future': True, 'example_value': False, 'id': 346, 'caption': '''Enables force sign in for <ph name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph>''',
diff --git a/components/prefs/pref_service.cc b/components/prefs/pref_service.cc index d14046b..c4b27676 100644 --- a/components/prefs/pref_service.cc +++ b/components/prefs/pref_service.cc
@@ -543,22 +543,14 @@ // PrefService::Preference PrefService::Preference::Preference(const PrefService* service, - const std::string& name, + std::string name, base::Value::Type type) - : name_(name), type_(type), pref_service_(service) { - DCHECK(service); - // Cache the registration flags at creation time to avoid multiple map lookups - // later. - registration_flags_ = service->pref_registry_->GetRegistrationFlags(name_); -} - -const std::string PrefService::Preference::name() const { - return name_; -} - -base::Value::Type PrefService::Preference::GetType() const { - return type_; -} + : name_(std::move(name)), + type_(type), + // Cache the registration flags at creation time to avoid multiple map + // lookups later. + registration_flags_(service->pref_registry_->GetRegistrationFlags(name_)), + pref_service_(service) {} const base::Value* PrefService::Preference::GetValue() const { const base::Value* result = pref_service_->GetPreferenceValue(name_);
diff --git a/components/prefs/pref_service.h b/components/prefs/pref_service.h index 7aaf65a..665905ce 100644 --- a/components/prefs/pref_service.h +++ b/components/prefs/pref_service.h
@@ -77,16 +77,16 @@ // dictionary (a branch), or list. You shouldn't need to construct this on // your own; use the PrefService::Register*Pref methods instead. Preference(const PrefService* service, - const std::string& name, + std::string name, base::Value::Type type); ~Preference() {} // Returns the name of the Preference (i.e., the key, e.g., // browser.window_placement). - const std::string name() const; + std::string name() const { return name_; } // Returns the registered type of the preference. - base::Value::Type GetType() const; + base::Value::Type GetType() const { return type_; } // Returns the value of the Preference, falling back to the registered // default value if no other has been set. @@ -155,10 +155,10 @@ const base::Value::Type type_; - uint32_t registration_flags_; + const uint32_t registration_flags_; // Reference to the PrefService in which this pref was created. - const PrefService* pref_service_; + const PrefService* const pref_service_; }; // You may wish to use PrefServiceFactory or one of its subclasses
diff --git a/components/previews/content/previews_optimization_guide.cc b/components/previews/content/previews_optimization_guide.cc index 7d23694..3aa60653 100644 --- a/components/previews/content/previews_optimization_guide.cc +++ b/components/previews/content/previews_optimization_guide.cc
@@ -128,6 +128,9 @@ bool PreviewsOptimizationGuide::IsWhitelisted(const net::URLRequest& request, PreviewsType type) const { + if (!hints_) + return false; + return hints_->IsWhitelisted(request.url(), type); }
diff --git a/components/previews/content/previews_optimization_guide_unittest.cc b/components/previews/content/previews_optimization_guide_unittest.cc index 3813353..3e62a75e 100644 --- a/components/previews/content/previews_optimization_guide_unittest.cc +++ b/components/previews/content/previews_optimization_guide_unittest.cc
@@ -95,6 +95,12 @@ DISALLOW_COPY_AND_ASSIGN(PreviewsOptimizationGuideTest); }; +TEST_F(PreviewsOptimizationGuideTest, IsWhitelistedWithoutHints) { + std::unique_ptr<net::URLRequest> request = + CreateRequestWithURL(GURL("https://m.facebook.com")); + EXPECT_FALSE(guide()->IsWhitelisted(*request, PreviewsType::NOSCRIPT)); +} + TEST_F(PreviewsOptimizationGuideTest, ProcessHintsWhitelistForNoScriptPopulatedCorrectly) { optimization_guide::proto::Configuration config;
diff --git a/components/safe_browsing/android/java/src/org/chromium/components/safe_browsing/SafeBrowsingApiBridge.java b/components/safe_browsing/android/java/src/org/chromium/components/safe_browsing/SafeBrowsingApiBridge.java index 3241ded..81c7542e 100644 --- a/components/safe_browsing/android/java/src/org/chromium/components/safe_browsing/SafeBrowsingApiBridge.java +++ b/components/safe_browsing/android/java/src/org/chromium/components/safe_browsing/SafeBrowsingApiBridge.java
@@ -54,14 +54,6 @@ long callbackId, int resultStatus, String metadata, long checkDelta) { nativeOnUrlCheckDone(callbackId, resultStatus, metadata, checkDelta); } - - // TODO(csharrison): Temporary to avoid breaking downstream. Sending a 0 - // checkDelta is fine since the native code doesn't use the value yet. - @Override - public void onUrlCheckDone(long callbackId, int resultStatus, String metadata) { - nativeOnUrlCheckDone( - callbackId, resultStatus, metadata, 0 /* checkDelta */); - } }); return initSuccesssful ? handler : null; }
diff --git a/components/safe_browsing/android/java/src/org/chromium/components/safe_browsing/SafeBrowsingApiHandler.java b/components/safe_browsing/android/java/src/org/chromium/components/safe_browsing/SafeBrowsingApiHandler.java index bb675bf..1b84e2c 100644 --- a/components/safe_browsing/android/java/src/org/chromium/components/safe_browsing/SafeBrowsingApiHandler.java +++ b/components/safe_browsing/android/java/src/org/chromium/components/safe_browsing/SafeBrowsingApiHandler.java
@@ -24,8 +24,6 @@ // Note: |checkDelta| is the time the remote call took in microseconds. void onUrlCheckDone(long callbackId, @SafeBrowsingResult int resultStatus, String metadata, long checkDelta); - // TODO(csharrison): Temporary to avoid breaking downstream. - void onUrlCheckDone(long callbackId, @SafeBrowsingResult int resultStatus, String metadata); } // Possible values for resultStatus. Native side has the same definitions.
diff --git a/components/safe_browsing/android/safe_browsing_api_handler_bridge.cc b/components/safe_browsing/android/safe_browsing_api_handler_bridge.cc index 305089b..87b52df1 100644 --- a/components/safe_browsing/android/safe_browsing_api_handler_bridge.cc +++ b/components/safe_browsing/android/safe_browsing_api_handler_bridge.cc
@@ -96,6 +96,7 @@ jlong check_delta) { DCHECK(callback_id); TRACE_EVENT0("safe_browsing", "SafeBrowsingApiHandlerBridge::OnUrlCheckDone"); + UMA_HISTOGRAM_COUNTS_10M("SB2.RemoteCall.CheckDelta", check_delta); const std::string metadata_str = (metadata ? ConvertJavaStringToUTF8(env, metadata) : "");
diff --git a/components/search_engines/template_url.cc b/components/search_engines/template_url.cc index cb4f8277..ffd01e3 100644 --- a/components/search_engines/template_url.cc +++ b/components/search_engines/template_url.cc
@@ -1071,7 +1071,8 @@ case GOOGLE_IMAGE_THUMBNAIL: HandleReplacement( std::string(), search_terms_args.image_thumbnail_content, *i, &url); - post_params_[i->index].content_type = "image/jpeg"; + if (i->is_post_param) + post_params_[i->index].content_type = "image/jpeg"; break; case GOOGLE_IMAGE_URL:
diff --git a/components/search_engines/template_url_unittest.cc b/components/search_engines/template_url_unittest.cc index 4862a436e..60ea384 100644 --- a/components/search_engines/template_url_unittest.cc +++ b/components/search_engines/template_url_unittest.cc
@@ -263,6 +263,21 @@ } } +TEST_F(TemplateURLTest, ImageURLWithGetShouldNotCrash) { + TemplateURLData data; + data.SetURL("http://foo/?q={searchTerms}&t={google:imageThumbnail}"); + TemplateURL url(data); + EXPECT_TRUE(url.url_ref().IsValid(search_terms_data_)); + ASSERT_TRUE(url.url_ref().SupportsReplacement(search_terms_data_)); + + TemplateURLRef::SearchTermsArgs search_args(ASCIIToUTF16("X")); + search_args.image_thumbnail_content = "dummy-image-thumbnail"; + GURL result( + url.url_ref().ReplaceSearchTerms(search_args, search_terms_data_)); + ASSERT_TRUE(result.is_valid()); + EXPECT_EQ("http://foo/?q=X&t=dummy-image-thumbnail", result.spec()); +} + // Test that setting the prepopulate ID from TemplateURL causes the stored // TemplateURLRef to handle parsing the URL parameters differently. TEST_F(TemplateURLTest, SetPrepopulatedAndParse) {
diff --git a/components/signin/core/browser/account_reconcilor.cc b/components/signin/core/browser/account_reconcilor.cc index b2af34f..5353b79 100644 --- a/components/signin/core/browser/account_reconcilor.cc +++ b/components/signin/core/browser/account_reconcilor.cc
@@ -299,23 +299,18 @@ return; } - reconcile_start_time_ = base::Time::Now(); - for (auto& observer : observer_list_) - observer.OnStartReconcile(); - - // Reset state for validating oauth2 tokens. - add_to_cookie_.clear(); - bool is_primary_account_valid = false; - chrome_accounts_ = LoadValidAccountsFromTokenService( - &primary_account_, &is_primary_account_valid); - if (!is_primary_account_valid && + primary_account_ = signin_manager_->GetAuthenticatedAccountId(); + if (token_service_->GetDelegate()->RefreshTokenHasError(primary_account_) && delegate_->ShouldAbortReconcileIfPrimaryHasError()) { VLOG(1) << "AccountReconcilor::StartReconcile: primary has error, abort."; primary_account_.clear(); - chrome_accounts_.clear(); return; } + for (auto& observer : observer_list_) + observer.OnStartReconcile(); + add_to_cookie_.clear(); + reconcile_start_time_ = base::Time::Now(); is_reconcile_started_ = true; error_during_last_reconcile_ = false; reconcile_is_noop_ = true; @@ -351,7 +346,24 @@ << "Ignoring " << accounts.size() - verified_gaia_accounts.size() << " unverified account(s)."; - FinishReconcile(std::move(verified_gaia_accounts)); + if (delegate_->ShouldRevokeAllSecondaryTokensBeforeReconcile( + verified_gaia_accounts)) { + for (const std::string& account : token_service_->GetAccounts()) { + if (account != primary_account_) + token_service_->RevokeCredentials(account); + } + } + + if (delegate_->ShouldAbortReconcileIfPrimaryHasError() && + token_service_->GetDelegate()->RefreshTokenHasError(primary_account_)) { + VLOG(1) << "Primary account has error, abort."; + primary_account_.clear(); + is_reconcile_started_ = false; + return; + } + + FinishReconcile(LoadValidAccountsFromTokenService(), + std::move(verified_gaia_accounts)); } else { if (is_reconcile_started_) error_during_last_reconcile_ = true; @@ -359,23 +371,15 @@ } } -std::vector<std::string> AccountReconcilor::LoadValidAccountsFromTokenService( - std::string* out_primary_account, - bool* out_is_primary_account_valid) const { - DCHECK(out_primary_account); - DCHECK(out_is_primary_account_valid); - *out_primary_account = signin_manager_->GetAuthenticatedAccountId(); +std::vector<std::string> AccountReconcilor::LoadValidAccountsFromTokenService() + const { std::vector<std::string> chrome_accounts = token_service_->GetAccounts(); - *out_is_primary_account_valid = true; // Remove any accounts that have an error. There is no point in trying to // reconcile them, since it won't work anyway. If the list ends up being - // empty, or if the primary account is in error, then don't reconcile any - // accounts. + // empty then don't reconcile any accounts. for (auto i = chrome_accounts.begin(); i != chrome_accounts.end(); ++i) { if (token_service_->GetDelegate()->RefreshTokenHasError(*i)) { - if (*out_primary_account == *i) - *out_is_primary_account_valid = false; VLOG(1) << "AccountReconcilor::ValidateAccountsFromTokenService: " << *i << " has error, won't reconcile"; i->clear(); @@ -387,8 +391,7 @@ chrome_accounts.end()); VLOG(1) << "AccountReconcilor::ValidateAccountsFromTokenService: " - << "Chrome " << chrome_accounts.size() << " accounts, " - << "Primary is '" << *out_primary_account << "'"; + << "Chrome " << chrome_accounts.size() << " accounts"; return chrome_accounts; } @@ -401,15 +404,17 @@ } void AccountReconcilor::FinishReconcile( + const std::vector<std::string>& chrome_accounts, std::vector<gaia::ListedAccount>&& gaia_accounts) { VLOG(1) << "AccountReconcilor::FinishReconcile"; DCHECK(add_to_cookie_.empty()); + std::string first_account = delegate_->GetFirstGaiaAccountForReconcile( - chrome_accounts_, gaia_accounts, primary_account_, first_execution_); - // |first_account| must be in |chrome_accounts_|. + chrome_accounts, gaia_accounts, primary_account_, first_execution_); + // |first_account| must be in |chrome_accounts|. DCHECK(first_account.empty() || - (std::find(chrome_accounts_.begin(), chrome_accounts_.end(), - first_account) != chrome_accounts_.end())); + (std::find(chrome_accounts.begin(), chrome_accounts.end(), + first_account) != chrome_accounts.end())); size_t number_gaia_accounts = gaia_accounts.size(); bool first_account_mismatch = (number_gaia_accounts > 0) && (first_account != gaia_accounts[0].id); @@ -420,9 +425,9 @@ int removed_from_cookie = 0; for (size_t i = 0; i < number_gaia_accounts; ++i) { if (gaia_accounts[i].valid && - chrome_accounts_.end() == std::find(chrome_accounts_.begin(), - chrome_accounts_.end(), - gaia_accounts[i].id)) { + chrome_accounts.end() == std::find(chrome_accounts.begin(), + chrome_accounts.end(), + gaia_accounts[i].id)) { ++removed_from_cookie; } } @@ -443,13 +448,13 @@ // Gaia cookie has been cleared or was already empty. DCHECK((first_account_mismatch && rebuild_cookie) || (number_gaia_accounts == 0)); - RevokeAllSecondaryTokens(); + RevokeAllSecondaryTokens(chrome_accounts); } else { // Create a list of accounts that need to be added to the Gaia cookie. add_to_cookie_.push_back(first_account); - for (size_t i = 0; i < chrome_accounts_.size(); ++i) { - if (chrome_accounts_[i] != first_account) - add_to_cookie_.push_back(chrome_accounts_[i]); + for (size_t i = 0; i < chrome_accounts.size(); ++i) { + if (chrome_accounts[i] != first_account) + add_to_cookie_.push_back(chrome_accounts[i]); } } @@ -478,7 +483,7 @@ } signin_metrics::LogSigninAccountReconciliation( - chrome_accounts_.size(), added_to_cookie, removed_from_cookie, + chrome_accounts.size(), added_to_cookie, removed_from_cookie, !first_account_mismatch, first_execution_, number_gaia_accounts); first_execution_ = false; CalculateIfReconcileIsDone(); @@ -520,8 +525,9 @@ } } -void AccountReconcilor::RevokeAllSecondaryTokens() { - for (const std::string& account : chrome_accounts_) { +void AccountReconcilor::RevokeAllSecondaryTokens( + const std::vector<std::string>& chrome_accounts) { + for (const std::string& account : chrome_accounts) { if (account != primary_account_) { reconcile_is_noop_ = false; if (delegate_->IsAccountConsistencyEnforced()) {
diff --git a/components/signin/core/browser/account_reconcilor.h b/components/signin/core/browser/account_reconcilor.h index 6233ed9c..3630c16 100644 --- a/components/signin/core/browser/account_reconcilor.h +++ b/components/signin/core/browser/account_reconcilor.h
@@ -125,6 +125,9 @@ DiceNoMigrationAfterReconcile); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorTest, DiceReconcileReuseGaiaFirstAccount); + FRIEND_TEST_ALL_PREFIXES(AccountReconcilorTest, + MigrationClearSecondaryTokens); + FRIEND_TEST_ALL_PREFIXES(AccountReconcilorTest, MigrationClearAllTokens); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorTest, TokensNotLoaded); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorTest, StartReconcileCookiesDisabled); @@ -180,18 +183,17 @@ // Used during periodic reconciliation. void StartReconcile(); // |gaia_accounts| are the accounts in the Gaia cookie. - void FinishReconcile(std::vector<gaia::ListedAccount>&& gaia_accounts); + void FinishReconcile(const std::vector<std::string>& chrome_accounts, + std::vector<gaia::ListedAccount>&& gaia_accounts); void AbortReconcile(); void CalculateIfReconcileIsDone(); void ScheduleStartReconcileIfChromeAccountsChanged(); - // Revokes tokens for all accounts in chrome_accounts_ but primary_account_. - void RevokeAllSecondaryTokens(); + // Revokes tokens for all accounts in chrome_accounts but primary_account_. + void RevokeAllSecondaryTokens( + const std::vector<std::string>& chrome_accounts); // Returns the list of valid accounts from the TokenService. - // The primary account is returned in |out_primary_account| if any. - std::vector<std::string> LoadValidAccountsFromTokenService( - std::string* out_primary_account, - bool* out_is_primary_account_valid) const; + std::vector<std::string> LoadValidAccountsFromTokenService() const; // Note internally that this |account_id| is added to the cookie jar. bool MarkAccountAsAddedToCookie(const std::string& account_id); @@ -262,7 +264,6 @@ // Used during reconcile action. // These members are used to validate the tokens in OAuth2TokenService. std::string primary_account_; - std::vector<std::string> chrome_accounts_; std::vector<std::string> add_to_cookie_; bool chrome_accounts_changed_;
diff --git a/components/signin/core/browser/account_reconcilor_delegate.cc b/components/signin/core/browser/account_reconcilor_delegate.cc index f3e5a37..d867f08 100644 --- a/components/signin/core/browser/account_reconcilor_delegate.cc +++ b/components/signin/core/browser/account_reconcilor_delegate.cc
@@ -26,4 +26,9 @@ return std::string(); } +bool AccountReconcilorDelegate::ShouldRevokeAllSecondaryTokensBeforeReconcile( + const std::vector<gaia::ListedAccount>& gaia_accounts) { + return false; +} + } // namespace signin
diff --git a/components/signin/core/browser/account_reconcilor_delegate.h b/components/signin/core/browser/account_reconcilor_delegate.h index aaa9fcd..cb797af4 100644 --- a/components/signin/core/browser/account_reconcilor_delegate.h +++ b/components/signin/core/browser/account_reconcilor_delegate.h
@@ -41,6 +41,11 @@ const std::string& primary_account, bool first_execution) const; + // Returns true if all secondary accounts should be cleared at the beginning + // of the reconcile. + virtual bool ShouldRevokeAllSecondaryTokensBeforeReconcile( + const std::vector<gaia::ListedAccount>& gaia_accounts); + // Called when reconcile is finished. virtual void OnReconcileFinished(const std::string& first_account, bool reconcile_is_noop) {}
diff --git a/components/signin/core/browser/account_reconcilor_unittest.cc b/components/signin/core/browser/account_reconcilor_unittest.cc index ce99499..b55b8f5 100644 --- a/components/signin/core/browser/account_reconcilor_unittest.cc +++ b/components/signin/core/browser/account_reconcilor_unittest.cc
@@ -956,10 +956,9 @@ // Enable Dice migration. SetAccountConsistency(signin::AccountConsistencyMethod::kDiceMigration); - // Add a token in Chrome but do not sign in. + // Add a token in Chrome. const std::string account_id = - PickAccountIdForAccount("12345", "user@gmail.com"); - token_service()->UpdateCredentials(account_id, "refresh_token"); + ConnectProfileToAccount("12345", "user@gmail.com"); cookie_manager_service()->SetListAccountsResponseNoAccounts(); AccountReconcilor* reconcilor = GetMockReconcilor(); signin::DiceAccountReconcilorDelegate* dice_delegate = @@ -987,6 +986,81 @@ EXPECT_FALSE(dice_delegate->IsAccountConsistencyEnforced()); } +// Tests that secondary refresh tokens are cleared when cookie is empty during +// Dice migration. +TEST_F(AccountReconcilorTest, MigrationClearSecondaryTokens) { + // Enable Dice migration. + SetAccountConsistency(signin::AccountConsistencyMethod::kDiceMigration); + + // Add a tokens in Chrome, signin to Sync, but no Gaia cookies. + const std::string account_id_1 = + ConnectProfileToAccount("12345", "user@gmail.com"); + const std::string account_id_2 = + PickAccountIdForAccount("67890", "other@gmail.com"); + token_service()->UpdateCredentials(account_id_2, "refresh_token"); + cookie_manager_service()->SetListAccountsResponseNoAccounts(); + ASSERT_TRUE(token_service()->RefreshTokenIsAvailable(account_id_1)); + ASSERT_TRUE(token_service()->RefreshTokenIsAvailable(account_id_2)); + + // Reconcile should revoke the secondary account. + AccountReconcilor* reconcilor = GetMockReconcilor(); + EXPECT_CALL(*GetMockReconcilor(), PerformMergeAction(account_id_1)); + signin::DiceAccountReconcilorDelegate* dice_delegate = + static_cast<signin::DiceAccountReconcilorDelegate*>( + reconcilor->delegate_.get()); + reconcilor->StartReconcile(); + ASSERT_TRUE(reconcilor->is_reconcile_started_); + base::RunLoop().RunUntilIdle(); + SimulateAddAccountToCookieCompleted(reconcilor, account_id_1, + GoogleServiceAuthError::AuthErrorNone()); + ASSERT_FALSE(reconcilor->is_reconcile_started_); + ASSERT_EQ(signin_metrics::ACCOUNT_RECONCILOR_OK, reconcilor->GetState()); + + EXPECT_TRUE(token_service()->RefreshTokenIsAvailable(account_id_1)); + EXPECT_FALSE(token_service()->RefreshTokenIsAvailable(account_id_2)); + + // Profile was not migrated. + EXPECT_FALSE( + dice_delegate->IsReadyForDiceMigration(false /* is_new_profile */)); +} + +// Tests that all refresh tokens are cleared when cookie is empty during +// Dice migration, if Sync is not enabled. +TEST_F(AccountReconcilorTest, MigrationClearAllTokens) { + // Enable Dice migration. + SetAccountConsistency(signin::AccountConsistencyMethod::kDiceMigration); + + // Add a tokens in Chrome but no Gaia cookies. + const std::string account_id_1 = + PickAccountIdForAccount("12345", "user@gmail.com"); + const std::string account_id_2 = + PickAccountIdForAccount("67890", "other@gmail.com"); + token_service()->UpdateCredentials(account_id_1, "refresh_token"); + token_service()->UpdateCredentials(account_id_2, "refresh_token"); + cookie_manager_service()->SetListAccountsResponseNoAccounts(); + ASSERT_TRUE(token_service()->RefreshTokenIsAvailable(account_id_1)); + ASSERT_TRUE(token_service()->RefreshTokenIsAvailable(account_id_2)); + + // Reconcile should revoke the secondary account. + AccountReconcilor* reconcilor = GetMockReconcilor(); + signin::DiceAccountReconcilorDelegate* dice_delegate = + static_cast<signin::DiceAccountReconcilorDelegate*>( + reconcilor->delegate_.get()); + reconcilor->StartReconcile(); + ASSERT_TRUE(reconcilor->is_reconcile_started_); + base::RunLoop().RunUntilIdle(); + ASSERT_FALSE(reconcilor->is_reconcile_started_); + ASSERT_EQ(signin_metrics::ACCOUNT_RECONCILOR_OK, reconcilor->GetState()); + + EXPECT_FALSE(token_service()->RefreshTokenIsAvailable(account_id_1)); + EXPECT_FALSE(token_service()->RefreshTokenIsAvailable(account_id_2)); + + // Profile is now ready for migration on next startup. + base::RunLoop().RunUntilIdle(); + EXPECT_TRUE( + dice_delegate->IsReadyForDiceMigration(false /* is_new_profile */)); +} + #endif // BUILDFLAG(ENABLE_DICE_SUPPORT) // Tests that reconcile cannot start before the tokens are loaded, and is
diff --git a/components/signin/core/browser/dice_account_reconcilor_delegate.cc b/components/signin/core/browser/dice_account_reconcilor_delegate.cc index eb8b08c..8d85714 100644 --- a/components/signin/core/browser/dice_account_reconcilor_delegate.cc +++ b/components/signin/core/browser/dice_account_reconcilor_delegate.cc
@@ -155,6 +155,15 @@ return std::string(); } +bool DiceAccountReconcilorDelegate:: + ShouldRevokeAllSecondaryTokensBeforeReconcile( + const std::vector<gaia::ListedAccount>& gaia_accounts) { + // During the Dice migration step, before Dice is actually enabled, chrome + // tokens must be cleared when the cookies are cleared. + return signin::IsDicePrepareMigrationEnabled() && + !signin::IsDiceEnabledForProfile(user_prefs_) && gaia_accounts.empty(); +} + void DiceAccountReconcilorDelegate::OnReconcileFinished( const std::string& first_account, bool reconcile_is_noop) {
diff --git a/components/signin/core/browser/dice_account_reconcilor_delegate.h b/components/signin/core/browser/dice_account_reconcilor_delegate.h index 688a4d01..76d90d4 100644 --- a/components/signin/core/browser/dice_account_reconcilor_delegate.h +++ b/components/signin/core/browser/dice_account_reconcilor_delegate.h
@@ -40,6 +40,8 @@ const std::vector<gaia::ListedAccount>& gaia_accounts, const std::string& primary_account, bool first_execution) const override; + bool ShouldRevokeAllSecondaryTokensBeforeReconcile( + const std::vector<gaia::ListedAccount>& gaia_accounts) override; void OnReconcileFinished(const std::string& first_account, bool reconcile_is_noop) override;
diff --git a/components/signin/core/browser/dice_account_reconcilor_delegate_unittest.cc b/components/signin/core/browser/dice_account_reconcilor_delegate_unittest.cc index aa14ff0..5527e76 100644 --- a/components/signin/core/browser/dice_account_reconcilor_delegate_unittest.cc +++ b/components/signin/core/browser/dice_account_reconcilor_delegate_unittest.cc
@@ -58,3 +58,29 @@ signin::DiceAccountReconcilorDelegate delegate(&pref_service, true); EXPECT_TRUE(signin::IsDiceEnabledForProfile(&pref_service)); } + +TEST(DiceAccountReconcilorDelegateTest, RevokeTokens) { + sync_preferences::TestingPrefServiceSyncable pref_service; + signin::DiceAccountReconcilorDelegate::RegisterProfilePrefs( + pref_service.registry()); + signin::RegisterAccountConsistencyProfilePrefs(pref_service.registry()); + { + // Dice is enabled, don't revoke. + signin::ScopedAccountConsistencyDice scoped_dice; + signin::DiceAccountReconcilorDelegate delegate(&pref_service, false); + EXPECT_FALSE(delegate.ShouldRevokeAllSecondaryTokensBeforeReconcile( + std::vector<gaia::ListedAccount>())); + } + { + signin::ScopedAccountConsistencyDiceMigration scoped_dice_migration; + signin::DiceAccountReconcilorDelegate delegate(&pref_service, false); + // Gaia accounts are not empty, don't revoke. + gaia::ListedAccount gaia_account; + gaia_account.id = "other"; + EXPECT_FALSE(delegate.ShouldRevokeAllSecondaryTokensBeforeReconcile( + std::vector<gaia::ListedAccount>{gaia_account})); + // Revoke. + EXPECT_TRUE(delegate.ShouldRevokeAllSecondaryTokensBeforeReconcile( + std::vector<gaia::ListedAccount>())); + } +}
diff --git a/components/sync/model_impl/processor_entity_tracker.cc b/components/sync/model_impl/processor_entity_tracker.cc index 25c2a09..edea6ef 100644 --- a/components/sync/model_impl/processor_entity_tracker.cc +++ b/components/sync/model_impl/processor_entity_tracker.cc
@@ -76,7 +76,6 @@ data->id = metadata_.server_id(); data->creation_time = ProtoTimeToTime(metadata_.creation_time()); data->modification_time = ProtoTimeToTime(metadata_.modification_time()); - DCHECK(MatchesSpecificsHash(data->specifics)); commit_data_.reset(); CacheCommitData(data->PassToPtr());
diff --git a/components/sync/model_impl/processor_entity_tracker_unittest.cc b/components/sync/model_impl/processor_entity_tracker_unittest.cc index f16bf8e..998ac2a3 100644 --- a/components/sync/model_impl/processor_entity_tracker_unittest.cc +++ b/components/sync/model_impl/processor_entity_tracker_unittest.cc
@@ -106,6 +106,7 @@ std::unique_ptr<ProcessorEntityTracker> CreateNew() { return ProcessorEntityTracker::CreateNew(kKey, kHash, "", ctime_); } + std::unique_ptr<ProcessorEntityTracker> CreateNewWithEmptyStorageKey() { return ProcessorEntityTracker::CreateNew("", kHash, "", ctime_); } @@ -118,6 +119,11 @@ return entity; } + std::unique_ptr<ProcessorEntityTracker> RestoreFromMetadata( + sync_pb::EntityMetadata* entity_metadata) { + return ProcessorEntityTracker::CreateFromMetadata(kKey, entity_metadata); + } + const base::Time ctime_; }; @@ -520,4 +526,21 @@ EXPECT_EQ(1, request.base_version); } +// Tests that entity restored after restart accepts specifics that don't match +// the ones passed originally to MakeLocalChange. +TEST_F(ProcessorEntityTrackerTest, RestoredLocalChangeWithUpdatedSpecifics) { + // Create new entity and preserver its metadata. + std::unique_ptr<ProcessorEntityTracker> entity = CreateNew(); + entity->MakeLocalChange(GenerateEntityData(kHash, kName, kValue1)); + sync_pb::EntityMetadata entity_metadata = entity->metadata(); + + // Restore entity from metadata and emulate bridge passing different specifics + // to SetCommitData. + entity = RestoreFromMetadata(&entity_metadata); + auto entity_data = GenerateEntityData(kHash, kName, kValue2); + entity->SetCommitData(entity_data.get()); + + // No verification is necessary. SetCommitData shouldn't DCHECK. +} + } // namespace syncer
diff --git a/components/test/data/autofill/heuristics/output/017_checkout_advanceautoparts.com.out b/components/test/data/autofill/heuristics/output/017_checkout_advanceautoparts.com.out index 7fae45a..e9a02b3 100644 --- a/components/test/data/autofill/heuristics/output/017_checkout_advanceautoparts.com.out +++ b/components/test/data/autofill/heuristics/output/017_checkout_advanceautoparts.com.out
@@ -1,3 +1,6 @@ +UNKNOWN_TYPE | logonId | Email Address: | | logonId_1-default +UNKNOWN_TYPE | logonPassword | Password: | | logonId_1-default +UNKNOWN_TYPE | rememberMe | Remember Me on Future Visits | true | logonId_1-default UNKNOWN_TYPE | billingShippingSame | Make shipping the same as my billing address | false | billingShippingSame_1-default NAME_FIRST | billFirstName | *First Name: | | billingShippingSame_1-default NAME_LAST | billLastName | *Last Name: | | billingShippingSame_1-default @@ -26,3 +29,4 @@ PHONE_HOME_CITY_CODE | shipNightPhonePart1 | Night Phone: | | shipFirstName_1-default PHONE_HOME_NUMBER | shipNightPhonePart2 | Night Phone: | | shipFirstName_1-default PHONE_HOME_NUMBER | shipNightPhonePart3 | Night Phone: | | shipFirstName_1-default +UNKNOWN_TYPE | zipCode | | | zipCode_1-default
diff --git a/components/test/data/autofill/heuristics/output/018_checkout_ae.com.out b/components/test/data/autofill/heuristics/output/018_checkout_ae.com.out index 32055e8..8966f63 100644 --- a/components/test/data/autofill/heuristics/output/018_checkout_ae.com.out +++ b/components/test/data/autofill/heuristics/output/018_checkout_ae.com.out
@@ -1,6 +1,12 @@ +UNKNOWN_TYPE | logonUsername | Secure account sign in | Email Address | logonUsername_1-default +UNKNOWN_TYPE | logonPassword | password | password | logonUsername_1-default +UNKNOWN_TYPE | zip | Find a store | Enter ZIP/Postal | zip_1-default +UNKNOWN_TYPE | username | Access your wish list | Email | username_1-default +UNKNOWN_TYPE | password | Password | Password | username_1-default NAME_FIRST | firstName | Search wish lists by name | First Name | firstName_1-default NAME_LAST | lastName | Last Name | Last Name | firstName_1-default EMAIL_ADDRESS | email | Or search wish lists by email | Email | firstName_1-default +UNKNOWN_TYPE | /aeo/commerce/search/formhandlers/AEOQueryFormHandler.searchRequest.question | Keyword or Style # | Keyword or Style # | /aeo/commerce/search/formhandlers/AEOQueryFormHandler.searchRequest.question_1-default ADDRESS_HOME_COUNTRY | countryType | Country Type | usa | countryType_1-default ADDRESS_HOME_COUNTRY | country | Country, APO/FPO | US | countryType_1-default NAME_FIRST | firstName | First Name | | countryType_1-default @@ -13,6 +19,8 @@ UNKNOWN_TYPE | shippingChoice | Standard3 - 7 business days$7dates: Jun 08 - Jun 14 | Standard | countryType_1-default UNKNOWN_TYPE | shippingChoice | Two Day2 business days$15date: Jun 07 | SecondDay | countryType_1-default UNKNOWN_TYPE | shippingChoice | Overnight1 business day$20date: Jun 06 | Overnight | countryType_1-default +UNKNOWN_TYPE | giftNumEntry | Gift Card Number: CLOSEYour 19-digit Gift Card number and four-digit pin number are on the back of your Gift Card. Enter these numbers in the Gift Card fields, then click the Apply button.Learn More about how to use Gift Cards. | | giftNumEntry_1-default +UNKNOWN_TYPE | pinNumEntry | PIN: | | giftNumEntry_1-default CREDIT_CARD_TYPE | ccType | Card Type: | | ccType_1-cc CREDIT_CARD_NUMBER | ccNumber | Card Number: | | ccType_1-cc CREDIT_CARD_EXP_MONTH | expMonth | Expiration: | 1 | ccType_1-cc @@ -49,3 +57,4 @@ UNKNOWN_TYPE | aerieEmail | aerie | on | ccType_1-default UNKNOWN_TYPE | kidsEmail | 77kids | on | ccType_1-default UNKNOWN_TYPE | loyaltyTerms | I accept the Terms & Conditions | | ccType_1-default +UNKNOWN_TYPE | CouponCode | Discount Code: CLOSEApplying DiscountsEnter your 8 or 20 digit code into the Discount Code field without any spaces, then click the Apply Discount button.Learn More about how to find and apply discounts | | CouponCode_1-default
diff --git a/components/test/data/autofill/heuristics/output/019_checkout_bedbathandbeyond.com.out b/components/test/data/autofill/heuristics/output/019_checkout_bedbathandbeyond.com.out index a7ade04..a6f8fa8 100644 --- a/components/test/data/autofill/heuristics/output/019_checkout_bedbathandbeyond.com.out +++ b/components/test/data/autofill/heuristics/output/019_checkout_bedbathandbeyond.com.out
@@ -36,3 +36,4 @@ PHONE_HOME_CITY_CODE | ship_eve_phone_part1 | Evening phone | | ship_first_nm_1-default PHONE_HOME_NUMBER | ship_eve_phone_part2 | Evening phone | | ship_first_nm_1-default PHONE_HOME_NUMBER | ship_eve_phone_part3 | Evening phone | | ship_first_nm_1-default +UNKNOWN_TYPE | email | Privacy policy - Your Privacy Rights | enter your email address | email_1-default
diff --git a/components/test/data/autofill/heuristics/output/024_checkout_homedepot.com.out b/components/test/data/autofill/heuristics/output/024_checkout_homedepot.com.out index df4e302..acf5c80 100644 --- a/components/test/data/autofill/heuristics/output/024_checkout_homedepot.com.out +++ b/components/test/data/autofill/heuristics/output/024_checkout_homedepot.com.out
@@ -12,3 +12,4 @@ PHONE_HOME_NUMBER | altfieldphone2_1 | Alternate Phone: | | firstName_1_1-default PHONE_HOME_NUMBER | altfieldphone3_1 | Alternate Phone: | | firstName_1_1-default UNKNOWN_TYPE | isBillingAddress_1 | Check here if the above shipping address is | on | firstName_1_1-default +UNKNOWN_TYPE | emailInput | Add Shipping Addresses | Enter Email Address | emailInput_1-default
diff --git a/components/test/data/autofill/heuristics/output/027_checkout_jcrew.com.out b/components/test/data/autofill/heuristics/output/027_checkout_jcrew.com.out index d09bf68c..e659750 100644 --- a/components/test/data/autofill/heuristics/output/027_checkout_jcrew.com.out +++ b/components/test/data/autofill/heuristics/output/027_checkout_jcrew.com.out
@@ -1,3 +1,4 @@ +UNKNOWN_TYPE | searchTerm | search keyword or item # | search keyword or item # | searchTerm_1-default ADDRESS_HOME_COUNTRY | ADDRESS<>country_cd | country * | US | ADDRESS<>country_cd_1-default NAME_FIRST | ADDRESS<>firstName | first name * | | ADDRESS<>country_cd_1-default NAME_LAST | ADDRESS<>lastName | last name * | | ADDRESS<>country_cd_1-default @@ -11,3 +12,4 @@ UNKNOWN_TYPE | anonPassword | create password | | ADDRESS<>country_cd_1-default UNKNOWN_TYPE | anonPasswordConfirm | confirm password | | ADDRESS<>country_cd_1-default UNKNOWN_TYPE | anonPasswordHint | create password hint | | ADDRESS<>country_cd_1-default +UNKNOWN_TYPE | emailID | enter email | enter email | emailID_1-default
diff --git a/components/test/data/autofill/heuristics/output/029_checkout_kohls.com.out b/components/test/data/autofill/heuristics/output/029_checkout_kohls.com.out index 7a98487a..e2899feb 100644 --- a/components/test/data/autofill/heuristics/output/029_checkout_kohls.com.out +++ b/components/test/data/autofill/heuristics/output/029_checkout_kohls.com.out
@@ -1,3 +1,5 @@ +UNKNOWN_TYPE | LOGIN<>userid | E-mail Address: | | LOGIN<>userid_1-default +UNKNOWN_TYPE | LOGIN<>passwordLogin | Password: | | LOGIN<>userid_1-default NAME_FIRST | BILL_TO_ADDRESS<>firstName | First Name: | | BILL_TO_ADDRESS<>firstName_1-default NAME_LAST | BILL_TO_ADDRESS<>lastName | Last Name: | | BILL_TO_ADDRESS<>firstName_1-default ADDRESS_HOME_LINE1 | BILL_TO_ADDRESS<>address1 | Address: | | BILL_TO_ADDRESS<>firstName_1-default
diff --git a/components/test/data/autofill/heuristics/output/030_checkout_lowes.com.out b/components/test/data/autofill/heuristics/output/030_checkout_lowes.com.out index e7ee5e7..5e535de 100644 --- a/components/test/data/autofill/heuristics/output/030_checkout_lowes.com.out +++ b/components/test/data/autofill/heuristics/output/030_checkout_lowes.com.out
@@ -1,3 +1,5 @@ +UNKNOWN_TYPE | zipCode | Enter ZIP Code | | zipCode_1-default +UNKNOWN_TYPE | Ntt | Search keywords | | Ntt_1-default ADDRESS_HOME_COUNTRY | country | USA | USA | country_1-default ADDRESS_HOME_LINE1 | addressField2 | Address Name: | | country_1-default NAME_FIRST | firstName | First Name: | | country_1-default
diff --git a/components/test/data/autofill/heuristics/output/032_checkout_nordstrom.com.out b/components/test/data/autofill/heuristics/output/032_checkout_nordstrom.com.out index 4592aba..4f29b3f 100644 --- a/components/test/data/autofill/heuristics/output/032_checkout_nordstrom.com.out +++ b/components/test/data/autofill/heuristics/output/032_checkout_nordstrom.com.out
@@ -1,3 +1,4 @@ +UNKNOWN_TYPE | keyword | | | keyword_1-default EMAIL_ADDRESS | ctl00$mainContentPlaceHolder$emailAddress | E-mail Address | | ctl00$mainContentPlaceHolder$emailAddress_1-default EMAIL_ADDRESS | ctl00$mainContentPlaceHolder$emailAddressConfirm | Confirm E-mail | | ctl00$mainContentPlaceHolder$emailAddress_1-default PHONE_HOME_WHOLE_NUMBER | ctl00$mainContentPlaceHolder$phoneNumber | Phone Number | | ctl00$mainContentPlaceHolder$emailAddress_1-default
diff --git a/components/test/data/autofill/heuristics/output/033_checkout_officemax.com.out b/components/test/data/autofill/heuristics/output/033_checkout_officemax.com.out index bb0b7f6..1f111f4 100644 --- a/components/test/data/autofill/heuristics/output/033_checkout_officemax.com.out +++ b/components/test/data/autofill/heuristics/output/033_checkout_officemax.com.out
@@ -12,3 +12,5 @@ UNKNOWN_TYPE | emailOptIn | Yes! Send me exclusive coupons and special online savings via OfficeMax email.OfficeMax is committed to safeguarding your privacy. Our Privacy Policy outlines how OfficeMax handles your information. | https://www.officemax.com:443/ | fname_1-default UNKNOWN_TYPE | /atg/commerce/order/purchase/ShippingGroupFormHandler.maxPerksNumber | MaxPerks® ID: < What is this? | | fname_1-default UNKNOWN_TYPE | TaxExemptID | Tax Exempt ID: < What is this? | | fname_1-default +UNKNOWN_TYPE | 21919024 | Quantity | 1 | 21919024_1-default +UNKNOWN_TYPE | promoCode | Enter Promotional Code and Save! | | promoCode_1-default
diff --git a/components/test/data/autofill/heuristics/output/035_checkout_petco.com.out b/components/test/data/autofill/heuristics/output/035_checkout_petco.com.out index 354425b..c0cc80b 100644 --- a/components/test/data/autofill/heuristics/output/035_checkout_petco.com.out +++ b/components/test/data/autofill/heuristics/output/035_checkout_petco.com.out
@@ -1,3 +1,6 @@ +UNKNOWN_TYPE | zip | Your ZIP Code | Your ZIP Code | zip_1-default +UNKNOWN_TYPE | Ntt | Search PETCO.com | Search PETCO.com | Ntt_1-default +UNKNOWN_TYPE | txtEmail | Your Email Address | Your Email Address | txtEmail_1-default NAME_FIRST | ctl00$ctl00$cphBody$cphBody$txtSA_FirstName | First Name * | | ctl00$ctl00$cphBody$cphBody$txtSA_FirstName_1-default NAME_LAST | ctl00$ctl00$cphBody$cphBody$txtSA_LastName | Last Name * | | ctl00$ctl00$cphBody$cphBody$txtSA_FirstName_1-default ADDRESS_HOME_LINE1 | ctl00$ctl00$cphBody$cphBody$txtSA_Address1 | Address Line 1 * | | ctl00$ctl00$cphBody$cphBody$txtSA_FirstName_1-default
diff --git a/components/test/data/autofill/heuristics/output/036_checkout_petsmart.com.out b/components/test/data/autofill/heuristics/output/036_checkout_petsmart.com.out index f32faeb..e3f9e226 100644 --- a/components/test/data/autofill/heuristics/output/036_checkout_petsmart.com.out +++ b/components/test/data/autofill/heuristics/output/036_checkout_petsmart.com.out
@@ -1,3 +1,4 @@ +UNKNOWN_TYPE | kw | search petsmart.com | search petsmart.com | kw_1-default ADDRESS_HOME_COUNTRY | billCountry | • Country: | US | billCountry_1-default NAME_FIRST | billFname | • First Name: | | billCountry_1-default NAME_LAST | billLname | • Last Name: | | billCountry_1-default @@ -11,3 +12,5 @@ EMAIL_ADDRESS | guestEmail | • Email Address: | | billCountry_1-default UNKNOWN_TYPE | shipOptions | Ship to the above billing address | useShip | billCountry_1-default UNKNOWN_TYPE | shipOptions | Ship to a different address | provideNew | billCountry_1-default +UNKNOWN_TYPE | mail_id | User Name: | | mail_id_1-default +UNKNOWN_TYPE | password | Password: | | mail_id_1-default
diff --git a/components/test/data/autofill/heuristics/output/038_checkout_sears.com.out b/components/test/data/autofill/heuristics/output/038_checkout_sears.com.out index d87ccdf74..6c65ecd 100644 --- a/components/test/data/autofill/heuristics/output/038_checkout_sears.com.out +++ b/components/test/data/autofill/heuristics/output/038_checkout_sears.com.out
@@ -22,3 +22,4 @@ PHONE_HOME_WHOLE_NUMBER | day1 | Phone Number* | | firstName_1-default PHONE_HOME_EXTENSION | ext1 | Ext. | | firstName_1-default ADDRESS_HOME_STATE | county | County County | UNKNOWN | firstName_1-default +UNKNOWN_TYPE | KmartSpuSpecialInstr | | | KmartSpuSpecialInstr_1-default
diff --git a/components/test/data/autofill/heuristics/output/040_checkout_urbanoutfitters.com.out b/components/test/data/autofill/heuristics/output/040_checkout_urbanoutfitters.com.out index aefdadda..3baba2f 100644 --- a/components/test/data/autofill/heuristics/output/040_checkout_urbanoutfitters.com.out +++ b/components/test/data/autofill/heuristics/output/040_checkout_urbanoutfitters.com.out
@@ -1,3 +1,4 @@ +UNKNOWN_TYPE | searchPhrase | | | searchPhrase_1-default UNKNOWN_TYPE | shipto | Select a Saved Shipping Address | | shipto_1-default NAME_FIRST | shippingFirstName | First Name | First Name | shipto_1-default NAME_LAST | shippingLastName | Last Name | Last Name | shipto_1-default @@ -31,3 +32,6 @@ CREDIT_CARD_EXP_4_DIGIT_YEAR | expyear | | | billingFirstName_1-cc CREDIT_CARD_VERIFICATION_CODE | payment_cidnew | CID / Security Code | CID / Security Code | billingFirstName_1-cc UNKNOWN_TYPE | makeDefaultCreditCard | Make this my default credit card | true | billingFirstName_1-default +UNKNOWN_TYPE | giftMessageField | | | giftMessageField_1-default +UNKNOWN_TYPE | giftCardNumberFromBalance | Gift Card Number | Gift Card Number | giftCardNumberFromBalance_1-default +UNKNOWN_TYPE | giftCardPIN | Gift Card PIN | Gift Card PIN | giftCardNumberFromBalance_1-default
diff --git a/components/test/data/autofill/heuristics/output/042_checkout_williams-sonoma.com.out b/components/test/data/autofill/heuristics/output/042_checkout_williams-sonoma.com.out index de0790f..c4b9d08 100644 --- a/components/test/data/autofill/heuristics/output/042_checkout_williams-sonoma.com.out +++ b/components/test/data/autofill/heuristics/output/042_checkout_williams-sonoma.com.out
@@ -1,3 +1,4 @@ +UNKNOWN_TYPE | words | Search by keyword, recipe or item # | Enter keyword, recipe or item # | words_1-default NAME_FULL | shipTos[0].address.fullName | Full Name* | | shipTos[0].address.fullName_1-default ADDRESS_HOME_LINE1 | shipTos[0].address.addrLine1 | Address* | | shipTos[0].address.fullName_1-default ADDRESS_HOME_LINE2 | shipTos[0].address.addrLine2 | Address Line 2 | | shipTos[0].address.fullName_1-default @@ -11,3 +12,4 @@ EMAIL_ADDRESS | shipTos[0].confirmEmailAddr | Confirm Email* | | shipTos[0].address.fullName_1-default UNKNOWN_TYPE | shipTos[0].shipType | Standard (5-7 business days) | Standard | shipTos[0].address.fullName_1-default UNKNOWN_TYPE | shipTos[0].shipType | Rush (2-3 business days) | Rush | shipTos[0].address.fullName_1-default +UNKNOWN_TYPE | email | Enter your email address | Enter your email address | email_1-default
diff --git a/components/test/data/autofill/heuristics/output/046_register_bestbuy.com.out b/components/test/data/autofill/heuristics/output/046_register_bestbuy.com.out index b5e6a877..04fe5e7 100644 --- a/components/test/data/autofill/heuristics/output/046_register_bestbuy.com.out +++ b/components/test/data/autofill/heuristics/output/046_register_bestbuy.com.out
@@ -1,3 +1,5 @@ +UNKNOWN_TYPE | st | SEARCH FOR | Keyword or Item # | st_1-default +UNKNOWN_TYPE | sc | IN | Global | st_1-default NAME_FIRST | TxtFirstName | *First Name | | TxtFirstName_1-default NAME_MIDDLE_INITIAL | TxtMI | MI | | TxtFirstName_1-default NAME_LAST | TxtLastName | *Last Name | | TxtFirstName_1-default
diff --git a/components/test/data/autofill/heuristics/output/048_register_deviantart.com.out b/components/test/data/autofill/heuristics/output/048_register_deviantart.com.out index be69036..73e36ae 100644 --- a/components/test/data/autofill/heuristics/output/048_register_deviantart.com.out +++ b/components/test/data/autofill/heuristics/output/048_register_deviantart.com.out
@@ -1,3 +1,7 @@ +UNKNOWN_TYPE | q | deviantARTBrowse ArtPrints ShopT-Shirts & GearFind More ArtDaily DeviationsDiscover | | q_1-default +UNKNOWN_TYPE | emailAddress | Email Address | | emailAddress_1-default +UNKNOWN_TYPE | password | Password | | emailAddress_1-default +UNKNOWN_TYPE | remember_me | Stay logged in | 1 | emailAddress_1-default UNKNOWN_TYPE | existingAccount | Create a new Buyer Account | 0 | existingAccount_1-default UNKNOWN_TYPE | existingAccount | I have an existing deviantART account (email or username) | 1 | existingAccount_1-default EMAIL_ADDRESS | emailAddress | Email Address | | existingAccount_1-default
diff --git a/components/test/data/autofill/heuristics/output/051_register_epson.com.out b/components/test/data/autofill/heuristics/output/051_register_epson.com.out index ff04062..304a897 100644 --- a/components/test/data/autofill/heuristics/output/051_register_epson.com.out +++ b/components/test/data/autofill/heuristics/output/051_register_epson.com.out
@@ -1,6 +1,9 @@ +UNKNOWN_TYPE | query | United States | | query_1-default NAME_FIRST | fname | * First Name | | fname_1-default NAME_LAST | lname | * Last Name | | fname_1-default EMAIL_ADDRESS | emLogin | * E-mail address | | fname_1-default UNKNOWN_TYPE | pw | * Password | | fname_1-default UNKNOWN_TYPE | verifypw | * Re-Confirm Password | | fname_1-default UNKNOWN_TYPE | wantMsg | I'd like to hear about new product information, special discounts and offers exclusive to Epson customers only. Please sign me up! | on | fname_1-default +UNKNOWN_TYPE | EMAIL_ADDRESS | Email Address | (Required) | EMAIL_ADDRESS_1-default +UNKNOWN_TYPE | FIRST_NAME | First Name | (Optional) | EMAIL_ADDRESS_1-default
diff --git a/components/test/data/autofill/heuristics/output/053_register_gymboree.com.out b/components/test/data/autofill/heuristics/output/053_register_gymboree.com.out index f531577..7e7699c 100644 --- a/components/test/data/autofill/heuristics/output/053_register_gymboree.com.out +++ b/components/test/data/autofill/heuristics/output/053_register_gymboree.com.out
@@ -1,3 +1,4 @@ +UNKNOWN_TYPE | SEARCH_INPUT<>searchFor | search by keyword or item# | search by keyword or item# | SEARCH_INPUT<>searchFor_1-default EMAIL_ADDRESS | LOYALTY_ACCOUNT<>email | Email* | | LOYALTY_ACCOUNT<>email_1-default ADDRESS_HOME_COUNTRY | LOYALTY_ADDRESS<>country_cd | Country* | US | LOYALTY_ACCOUNT<>email_1-default NAME_FIRST | USER_ACCOUNT<>firstName | First Name* | | LOYALTY_ACCOUNT<>email_1-default @@ -15,3 +16,4 @@ UNKNOWN_TYPE | LOYALTY_ADDRESS<>ATR_indBillAsRewards | Save the address above as my default billing address. | true | LOYALTY_ACCOUNT<>email_1-default UNKNOWN_TYPE | LOYALTY_ACCOUNT<>sendEmail | Save the address above as my default billing address. I would like to receive promotions and special offers from Gymboree. | true | LOYALTY_ACCOUNT<>email_1-default UNKNOWN_TYPE | accept | I have read and accept the terms and conditions of Gymboree Rewards. (Rewards information and offers will be emailed to you.) | on | LOYALTY_ACCOUNT<>email_1-default +UNKNOWN_TYPE | SUBSCRIBER_INFO<>email | Exclusive E-Mail Sign Up | Sign Up Today! | SUBSCRIBER_INFO<>email_1-default
diff --git a/components/test/data/autofill/heuristics/output/055_register_imdb.com.out b/components/test/data/autofill/heuristics/output/055_register_imdb.com.out index 307cd7e..6d706de 100644 --- a/components/test/data/autofill/heuristics/output/055_register_imdb.com.out +++ b/components/test/data/autofill/heuristics/output/055_register_imdb.com.out
@@ -1,3 +1,5 @@ +UNKNOWN_TYPE | s | Search | all | s_1-default +UNKNOWN_TYPE | q | Search | | s_1-default EMAIL_ADDRESS | email1 | E-mail: | | email1_1-default EMAIL_ADDRESS | email2 | Confirm E-mail: | | email1_1-default UNKNOWN_TYPE | gender | Male | M | email1_1-default
diff --git a/components/test/data/autofill/heuristics/output/059_register_macys.com.out b/components/test/data/autofill/heuristics/output/059_register_macys.com.out index 142ad425..1608a64 100644 --- a/components/test/data/autofill/heuristics/output/059_register_macys.com.out +++ b/components/test/data/autofill/heuristics/output/059_register_macys.com.out
@@ -1,3 +1,4 @@ +UNKNOWN_TYPE | Keyword | | | Keyword_1-default NAME_FIRST | FirstName | First Name | | FirstName_1-default NAME_LAST | LastName | Last Name | | FirstName_1-default ADDRESS_HOME_LINE1 | Address1 | Address | | FirstName_1-default
diff --git a/components/test/data/autofill/heuristics/output/060_register_mcphee.com.out b/components/test/data/autofill/heuristics/output/060_register_mcphee.com.out index 725c53f8..aa6ed3df 100644 --- a/components/test/data/autofill/heuristics/output/060_register_mcphee.com.out +++ b/components/test/data/autofill/heuristics/output/060_register_mcphee.com.out
@@ -1,3 +1,4 @@ +UNKNOWN_TYPE | search_query | Search | | search_query_1-default EMAIL_ADDRESS | FormField[1][1] | * Email Address: | | FormField[1][1]_1-default UNKNOWN_TYPE | FormField[1][2] | * Password: | | FormField[1][1]_1-default UNKNOWN_TYPE | FormField[1][3] | * Confirm Password: | | FormField[1][1]_1-default
diff --git a/components/test/data/autofill/heuristics/output/061_register_myspace.com.out b/components/test/data/autofill/heuristics/output/061_register_myspace.com.out index 19ba2d2b..ec0fe34 100644 --- a/components/test/data/autofill/heuristics/output/061_register_myspace.com.out +++ b/components/test/data/autofill/heuristics/output/061_register_myspace.com.out
@@ -1,3 +1,4 @@ +UNKNOWN_TYPE | q | Search People | | q_1-default UNKNOWN_TYPE | accountType | Personal | 2 | accountType_1-default UNKNOWN_TYPE | accountType | Musician | 7 | accountType_1-default UNKNOWN_TYPE | accountType | Comedian | 15 | accountType_1-default @@ -15,3 +16,6 @@ UNKNOWN_TYPE | ddlYear | | | accountType_1-default UNKNOWN_TYPE | rblGender | Male | M | accountType_1-default UNKNOWN_TYPE | rblGender | Female | F | accountType_1-default +UNKNOWN_TYPE | Email | Email | | Email_1-default +UNKNOWN_TYPE | Password | Password | | Email_1-default +UNKNOWN_TYPE | Remember | Keep me logged in | on | Email_1-default
diff --git a/components/test/data/autofill/heuristics/output/062_register_newegg.com.out b/components/test/data/autofill/heuristics/output/062_register_newegg.com.out index 347c5ed..356c04c 100644 --- a/components/test/data/autofill/heuristics/output/062_register_newegg.com.out +++ b/components/test/data/autofill/heuristics/output/062_register_newegg.com.out
@@ -1,3 +1,4 @@ +UNKNOWN_TYPE | Description | Search site | | Description_1-default EMAIL_ADDRESS | LoginName | Email Address* | | LoginName_1-default EMAIL_ADDRESS | LoginName1 | Confirm Email Address* | | LoginName_1-default UNKNOWN_TYPE | Password | Password* | | LoginName_1-default @@ -43,3 +44,4 @@ UNKNOWN_TYPE | GameHours | How many hours per week do you play PC games? | 0 | LoginName_1-default UNKNOWN_TYPE | Spam | Sign me up for exclusive newsletter deals, sweepstakes, and 24-hour sales only available to subscribers | 1 | LoginName_1-default UNKNOWN_TYPE | SMS | I would like to receive SMS messages via my wireless device. | 1 | LoginName_1-default +UNKNOWN_TYPE | TrackingNumber | Track My Order | Tracking Number | TrackingNumber_1-default
diff --git a/components/test/data/autofill/heuristics/output/063_register_officedepot.com.out b/components/test/data/autofill/heuristics/output/063_register_officedepot.com.out index 83d9a1d..62fb696 100644 --- a/components/test/data/autofill/heuristics/output/063_register_officedepot.com.out +++ b/components/test/data/autofill/heuristics/output/063_register_officedepot.com.out
@@ -1,3 +1,5 @@ +UNKNOWN_TYPE | zip | | | zip_1-default +UNKNOWN_TYPE | Ntt | Search | | Ntt_1-default NAME_FIRST | addrsForm[0].firstName | *First Name: | | addrsForm[0].firstName_1-default NAME_MIDDLE_INITIAL | addrsForm[0].middleInitial | Middle Initial: | | addrsForm[0].firstName_1-default NAME_LAST | addrsForm[0].lastName | *Last Name: | | addrsForm[0].firstName_1-default
diff --git a/components/test/data/autofill/heuristics/output/064_register_officemax.com.out b/components/test/data/autofill/heuristics/output/064_register_officemax.com.out index 0630083..2264b5b 100644 --- a/components/test/data/autofill/heuristics/output/064_register_officemax.com.out +++ b/components/test/data/autofill/heuristics/output/064_register_officemax.com.out
@@ -6,3 +6,4 @@ ADDRESS_HOME_ZIP | /atg/userprofiling/ProfileFormHandler.value.zip | * Zip: | | /atg/userprofiling/ProfileFormHandler.value.maxPerks_1-default UNKNOWN_TYPE | /atg/userprofiling/ProfileFormHandler.value.password | * Password: | | /atg/userprofiling/ProfileFormHandler.value.maxPerks_1-default UNKNOWN_TYPE | /atg/userprofiling/ProfileFormHandler.value.confirmPassword | * Confirm Password: | | /atg/userprofiling/ProfileFormHandler.value.maxPerks_1-default +UNKNOWN_TYPE | freeText | Search by Keyword or Item # | Search by Keyword or Item # | freeText_1-default
diff --git a/components/test/data/autofill/heuristics/output/065_register_pyramidcollection.com.out b/components/test/data/autofill/heuristics/output/065_register_pyramidcollection.com.out index 2602fed..15ecbc5 100644 --- a/components/test/data/autofill/heuristics/output/065_register_pyramidcollection.com.out +++ b/components/test/data/autofill/heuristics/output/065_register_pyramidcollection.com.out
@@ -1,3 +1,4 @@ +UNKNOWN_TYPE | q | search | enter keyword(s) or item number | q_1-default EMAIL_ADDRESS | E1 | Email Address * | | E1_1-default NAME_FIRST | F1 | First Name * | | E1_1-default NAME_LAST | L1 | Last Name * | | E1_1-default @@ -22,3 +23,4 @@ PHONE_HOME_WHOLE_NUMBER | SP2 | Day Phone * | | SF1_1-default PHONE_HOME_WHOLE_NUMBER | SP3 | Evening Phone | | SF1_1-default UNKNOWN_TYPE | sameAsBilling | My Shipping address is same as billing address. | on | SF1_1-default +UNKNOWN_TYPE | email | ENTER TO WIN A $100 GIFT CARD! | enter email address | email_1-default
diff --git a/components/test/data/autofill/heuristics/output/067_register_rei.com.out b/components/test/data/autofill/heuristics/output/067_register_rei.com.out index a2ae850..32466d6 100644 --- a/components/test/data/autofill/heuristics/output/067_register_rei.com.out +++ b/components/test/data/autofill/heuristics/output/067_register_rei.com.out
@@ -6,3 +6,5 @@ ADDRESS_HOME_ZIP | zipCode | ZIP (Postal) Code:* | | firstName_1-default EMAIL_ADDRESS | email1 | E-mail Address:* | | firstName_1-default UNKNOWN_TYPE | gearmail | Yes, I'd like to be notified of news, offers and events at REI via this email address. | y | firstName_1-default +UNKNOWN_TYPE | query | | | query_1-default +UNKNOWN_TYPE | EmailAddress | Email Address | Email Address | EmailAddress_1-default
diff --git a/components/test/data/autofill/heuristics/output/071_register_sourceforge.net.out b/components/test/data/autofill/heuristics/output/071_register_sourceforge.net.out index 4afcfce..285f7b1 100644 --- a/components/test/data/autofill/heuristics/output/071_register_sourceforge.net.out +++ b/components/test/data/autofill/heuristics/output/071_register_sourceforge.net.out
@@ -1,3 +1,4 @@ +UNKNOWN_TYPE | q | Find Open Source Software | | q_1-default NAME_FULL | X1mRVeMqejLnZpd1etxNGHllat2M | Name: | | X1mRVeMqejLnZpd1etxNGHllat2M_1-default EMAIL_ADDRESS | X129ZdMbfixhIflk8_zHDFWB72qk | Email: | | X1mRVeMqejLnZpd1etxNGHllat2M_1-default UNKNOWN_TYPE | X2n9HcN3dx1-mSbLywp_L-szMydw | Username: | | X1mRVeMqejLnZpd1etxNGHllat2M_1-default
diff --git a/components/test/data/autofill/heuristics/output/073_register_target.com.out b/components/test/data/autofill/heuristics/output/073_register_target.com.out index 59c601d..50344b5 100644 --- a/components/test/data/autofill/heuristics/output/073_register_target.com.out +++ b/components/test/data/autofill/heuristics/output/073_register_target.com.out
@@ -1,3 +1,9 @@ +UNKNOWN_TYPE | keywords | | | keywords_1-default +UNKNOWN_TYPE | searchNodeID | | 1038576|1287991011 | keywords_1-default +UNKNOWN_TYPE | email | Email address: | | email_1-default +UNKNOWN_TYPE | password | Password: | | email_1-default +UNKNOWN_TYPE | email | Email address: | | email_1-default +UNKNOWN_TYPE | password | Password: | | email_1-default UNKNOWN_TYPE | userName | Your name:* | | userName_1-default EMAIL_ADDRESS | email | Your email address:* | | userName_1-default EMAIL_ADDRESS | emailCheck | Re-enter email address:* | | userName_1-default @@ -6,3 +12,11 @@ UNKNOWN_TYPE | subscribeEmail | Yes, please send me e-mails about special offers, exclusives and promotions from Target. | 1 | userName_1-default UNKNOWN_TYPE | ageCheck | Yes | yes | userName_1-default UNKNOWN_TYPE | ageCheck | No | no | userName_1-default +UNKNOWN_TYPE | firstName | First Name* | | firstName_1-default +UNKNOWN_TYPE | lastName | Last Name* | | firstName_1-default +UNKNOWN_TYPE | firstName | First Name* | | firstName_1-default +UNKNOWN_TYPE | lastName | Last Name* | | firstName_1-default +UNKNOWN_TYPE | firstName | First Name* | | firstName_1-default +UNKNOWN_TYPE | lastName | Last Name* | | firstName_1-default +UNKNOWN_TYPE | emailId | E-mail Address: | E-mail Address | emailId_1-default +UNKNOWN_TYPE | ue_back | 1 | 1 | ue_back_1-default
diff --git a/components/test/data/autofill/heuristics/output/074_register_threadless.com.out b/components/test/data/autofill/heuristics/output/074_register_threadless.com.out index 46aea7c..aa660792 100644 --- a/components/test/data/autofill/heuristics/output/074_register_threadless.com.out +++ b/components/test/data/autofill/heuristics/output/074_register_threadless.com.out
@@ -1,6 +1,17 @@ +UNKNOWN_TYPE | username | Username or email | | username_1-default +UNKNOWN_TYPE | password | Password | | username_1-default +UNKNOWN_TYPE | q | Search Tees Search Tees | | q_1-default +UNKNOWN_TYPE | type | Search Tees | product | q_1-default +UNKNOWN_TYPE | type | Search Forums | blogs | q_1-default +UNKNOWN_TYPE | type | Search Users | users | q_1-default +UNKNOWN_TYPE | type | Search Submissions | subs | q_1-default +UNKNOWN_TYPE | type | Search All | all | q_1-default UNKNOWN_TYPE | create_username | Desired username | | create_username_1-default UNKNOWN_TYPE | create_password | Password | | create_username_1-default UNKNOWN_TYPE | retype_password | Re-type password | | create_username_1-default EMAIL_ADDRESS | email | Email | | create_username_1-default UNKNOWN_TYPE | join_newsletter | Join our newsletter and be first to know about new tees and great deals! | on | create_username_1-default UNKNOWN_TYPE | recaptcha_response_field | Type the words above Type the numbers you hear | | create_username_1-default +UNKNOWN_TYPE | username | Username or email | | username_1-default +UNKNOWN_TYPE | password | Password | | username_1-default +UNKNOWN_TYPE | email | Enter your email address | | email_1-default
diff --git a/components/test/data/autofill/heuristics/output/081_crbug_64569.out b/components/test/data/autofill/heuristics/output/081_crbug_64569.out index 1e55975..70841ca9 100644 --- a/components/test/data/autofill/heuristics/output/081_crbug_64569.out +++ b/components/test/data/autofill/heuristics/output/081_crbug_64569.out
@@ -13,3 +13,4 @@ ADDRESS_HOME_CITY | addrCity | City | | payment_group_1-default ADDRESS_HOME_STATE | addrState | State | | payment_group_1-default ADDRESS_HOME_ZIP | addrZip | Postal code | | payment_group_1-default +UNKNOWN_TYPE | email | Enter your email address | | email_1-default
diff --git a/components/test/data/autofill/heuristics/output/094_checkout_staples.com.out b/components/test/data/autofill/heuristics/output/094_checkout_staples.com.out index 311b025..a1f83c7 100644 --- a/components/test/data/autofill/heuristics/output/094_checkout_staples.com.out +++ b/components/test/data/autofill/heuristics/output/094_checkout_staples.com.out
@@ -1,3 +1,5 @@ +UNKNOWN_TYPE | emailAddress | * Indicates a required field | | emailAddress_1-default +UNKNOWN_TYPE | emailPreference | , I would like to receive emails about special money-saving offers from Staples. Yes | emailYes | emailAddress_1-default NAME_FIRST | sFirstName | First Name * | | sFirstName_1-default NAME_LAST | sLastName | Last Name * | | sFirstName_1-default COMPANY_NAME | sCompany | Company Name (optional) | | sFirstName_1-default
diff --git a/components/test/data/autofill/heuristics/output/137_bug_555010.out b/components/test/data/autofill/heuristics/output/137_bug_555010.out index 06382e97..9899668 100644 --- a/components/test/data/autofill/heuristics/output/137_bug_555010.out +++ b/components/test/data/autofill/heuristics/output/137_bug_555010.out
@@ -1,3 +1,5 @@ +UNKNOWN_TYPE | userName | Username or Email address | | userName_1-default +UNKNOWN_TYPE | password | Password | | userName_1-default CREDIT_CARD_NAME_FULL | cardName | Full Name (First Name Last Name) | | cardName_1-cc ADDRESS_HOME_LINE1 | id_skCOShipAddress | Shipping Address | | cardName_1-default UNKNOWN_TYPE | id_skCOShipAptBldg | Apt/Bldg (optional) | | cardName_1-default
diff --git a/components/test/data/autofill/heuristics/output/147_panera.custhelp.com_app_ask.out b/components/test/data/autofill/heuristics/output/147_panera.custhelp.com_app_ask.out index f9ed47c5..d0b401fb 100644 --- a/components/test/data/autofill/heuristics/output/147_panera.custhelp.com_app_ask.out +++ b/components/test/data/autofill/heuristics/output/147_panera.custhelp.com_app_ask.out
@@ -1,3 +1,4 @@ +UNKNOWN_TYPE | rn_KeywordText_3_Text | Search by Keyword | | rn_KeywordText_3_Text_1-default UNKNOWN_TYPE | Incident.CustomFields.c.escalated_gift_card_devalue | Yes | 1 | Incident.CustomFields.c.escalated_gift_card_devalue_1-default UNKNOWN_TYPE | Incident.CustomFields.c.escalated_gift_card_devalue | No | 0 | Incident.CustomFields.c.escalated_gift_card_devalue_1-default UNKNOWN_TYPE | Incident.CustomFields.c.escalated_catering_sales | Yes | 1 | Incident.CustomFields.c.escalated_gift_card_devalue_1-default
diff --git a/components/test/data/payments/render_tests/PaymentRequestFreeShippingTest.unmask.Nexus_5-19.png b/components/test/data/payments/render_tests/PaymentRequestFreeShippingTest.unmask.Nexus_5-19.png index 302a458..222fce0 100644 --- a/components/test/data/payments/render_tests/PaymentRequestFreeShippingTest.unmask.Nexus_5-19.png +++ b/components/test/data/payments/render_tests/PaymentRequestFreeShippingTest.unmask.Nexus_5-19.png Binary files differ
diff --git a/components/translate/core/browser/translate_manager.cc b/components/translate/core/browser/translate_manager.cc index 2c069e0..a0bd5e7b 100644 --- a/components/translate/core/browser/translate_manager.cc +++ b/components/translate/core/browser/translate_manager.cc
@@ -396,6 +396,15 @@ std::string TranslateManager::GetTargetLanguage( const TranslatePrefs* prefs, language::LanguageModel* language_model) { + DCHECK(prefs); + const std::string& recent_target = prefs->GetRecentTargetLanguage(); + + // If we've recorded the most recent target language, use that. + if (base::FeatureList::IsEnabled(kTranslateRecentTarget) && + !recent_target.empty()) { + return recent_target; + } + if (language_model) { // Use the first language from the model that translate supports. for (const auto& lang : language_model->GetLanguages()) {
diff --git a/components/translate/core/browser/translate_manager_unittest.cc b/components/translate/core/browser/translate_manager_unittest.cc index 5831c09..0c44c80 100644 --- a/components/translate/core/browser/translate_manager_unittest.cc +++ b/components/translate/core/browser/translate_manager_unittest.cc
@@ -234,7 +234,7 @@ ASSERT_TRUE(TranslateDownloadManager::IsSupportedLanguage("en")); mock_language_model_.details = { MockLanguageModel::LanguageDetails("en", 1.0)}; - EXPECT_EQ("en", TranslateManager::GetTargetLanguage(nullptr, + EXPECT_EQ("en", TranslateManager::GetTargetLanguage(&translate_prefs_, &mock_language_model_)); // Try with two supported languages. @@ -242,7 +242,7 @@ mock_language_model_.details = { MockLanguageModel::LanguageDetails("de", 1.0), MockLanguageModel::LanguageDetails("en", 0.5)}; - EXPECT_EQ("de", TranslateManager::GetTargetLanguage(nullptr, + EXPECT_EQ("de", TranslateManager::GetTargetLanguage(&translate_prefs_, &mock_language_model_)); // Try with first supported language lower in the list. @@ -250,7 +250,7 @@ mock_language_model_.details = { MockLanguageModel::LanguageDetails("xx", 1.0), MockLanguageModel::LanguageDetails("en", 0.5)}; - EXPECT_EQ("en", TranslateManager::GetTargetLanguage(nullptr, + EXPECT_EQ("en", TranslateManager::GetTargetLanguage(&translate_prefs_, &mock_language_model_)); // Try with no supported languages. @@ -258,8 +258,8 @@ mock_language_model_.details = { MockLanguageModel::LanguageDetails("xx", 1.0), MockLanguageModel::LanguageDetails("yy", 0.5)}; - EXPECT_EQ( - "", TranslateManager::GetTargetLanguage(nullptr, &mock_language_model_)); + EXPECT_EQ("", TranslateManager::GetTargetLanguage(&translate_prefs_, + &mock_language_model_)); // Try non standard codes. // 'he', 'fil', 'nb' => 'iw', 'tl', 'no' @@ -267,21 +267,21 @@ ASSERT_FALSE(TranslateDownloadManager::IsSupportedLanguage("he")); mock_language_model_.details = { MockLanguageModel::LanguageDetails("he", 1.0)}; - EXPECT_EQ("iw", TranslateManager::GetTargetLanguage(nullptr, + EXPECT_EQ("iw", TranslateManager::GetTargetLanguage(&translate_prefs_, &mock_language_model_)); ASSERT_TRUE(TranslateDownloadManager::IsSupportedLanguage("tl")); ASSERT_FALSE(TranslateDownloadManager::IsSupportedLanguage("fil")); mock_language_model_.details = { MockLanguageModel::LanguageDetails("fil", 1.0)}; - EXPECT_EQ("tl", TranslateManager::GetTargetLanguage(nullptr, + EXPECT_EQ("tl", TranslateManager::GetTargetLanguage(&translate_prefs_, &mock_language_model_)); ASSERT_TRUE(TranslateDownloadManager::IsSupportedLanguage("no")); ASSERT_FALSE(TranslateDownloadManager::IsSupportedLanguage("nb")); mock_language_model_.details = { MockLanguageModel::LanguageDetails("nb", 1.0)}; - EXPECT_EQ("no", TranslateManager::GetTargetLanguage(nullptr, + EXPECT_EQ("no", TranslateManager::GetTargetLanguage(&translate_prefs_, &mock_language_model_)); }
diff --git a/components/translate/core/browser/translate_prefs.cc b/components/translate/core/browser/translate_prefs.cc index 00d608e..13df37c 100644 --- a/components/translate/core/browser/translate_prefs.cc +++ b/components/translate/core/browser/translate_prefs.cc
@@ -44,6 +44,8 @@ "translate_last_denied_time_for_language"; const char TranslatePrefs::kPrefTranslateTooOftenDeniedForLanguage[] = "translate_too_often_denied_for_language"; +const char TranslatePrefs::kPrefTranslateRecentTarget[] = + "translate_recent_target"; const char kTranslateUI2016Q2TrialName[] = "TranslateUI2016Q2"; const char kAlwaysTranslateOfferThreshold[] = @@ -105,6 +107,9 @@ const base::Feature kImprovedLanguageSettings{ "ImprovedLanguageSettings", base::FEATURE_DISABLED_BY_DEFAULT}; +const base::Feature kTranslateRecentTarget{"TranslateRecentTarget", + base::FEATURE_ENABLED_BY_DEFAULT}; + DenialTimeUpdate::DenialTimeUpdate(PrefService* prefs, const std::string& language, size_t max_denial_count) @@ -746,6 +751,15 @@ return false; } +void TranslatePrefs::SetRecentTargetLanguage( + const std::string& target_language) { + prefs_->SetString(kPrefTranslateRecentTarget, target_language); +} + +std::string TranslatePrefs::GetRecentTargetLanguage() const { + return prefs_->GetString(kPrefTranslateRecentTarget); +} + // static void TranslatePrefs::RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* registry) { @@ -769,6 +783,8 @@ registry->RegisterDictionaryPref( kPrefTranslateTooOftenDeniedForLanguage, user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); + registry->RegisterStringPref(kPrefTranslateRecentTarget, "", + user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); #if defined(OS_ANDROID) registry->RegisterDictionaryPref( kPrefTranslateAutoAlwaysCount,
diff --git a/components/translate/core/browser/translate_prefs.h b/components/translate/core/browser/translate_prefs.h index 8aa1046..7c763ba 100644 --- a/components/translate/core/browser/translate_prefs.h +++ b/components/translate/core/browser/translate_prefs.h
@@ -38,6 +38,10 @@ // These settings support the new UI. extern const base::Feature kImprovedLanguageSettings; +// Enables or disables using the most recent target language as the default +// target language option. +extern const base::Feature kTranslateRecentTarget; + // The trial (study) name in finch study config. extern const char kTranslateUI2016Q2TrialName[]; @@ -106,6 +110,7 @@ static const char kPrefTranslateBlockedLanguages[]; static const char kPrefTranslateLastDeniedTimeForLanguage[]; static const char kPrefTranslateTooOftenDeniedForLanguage[]; + static const char kPrefTranslateRecentTarget[]; #if defined(OS_ANDROID) static const char kPrefTranslateAutoAlwaysCount[]; static const char kPrefTranslateAutoNeverCount[]; @@ -250,6 +255,11 @@ bool ShouldAutoTranslate(const std::string& original_language, std::string* target_language); + // Stores and retrieves the last-observed translate target language. Used to + // determine which target language to offer in future. + void SetRecentTargetLanguage(const std::string& target_language); + std::string GetRecentTargetLanguage() const; + static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry); static void MigrateUserPrefs(PrefService* user_prefs, const char* accept_languages_pref);
diff --git a/components/translate/core/browser/translate_ui_delegate.cc b/components/translate/core/browser/translate_ui_delegate.cc index ce79bf8..d4801ad 100644 --- a/components/translate/core/browser/translate_ui_delegate.cc +++ b/components/translate/core/browser/translate_ui_delegate.cc
@@ -214,6 +214,7 @@ prefs_->ResetTranslationDeniedCount(GetOriginalLanguageCode()); prefs_->ResetTranslationIgnoredCount(GetOriginalLanguageCode()); prefs_->IncrementTranslationAcceptedCount(GetOriginalLanguageCode()); + prefs_->SetRecentTargetLanguage(GetTargetLanguageCode()); } if (translate_manager_) {
diff --git a/components/ukm/ukm_recorder_impl.cc b/components/ukm/ukm_recorder_impl.cc index ef42d542..d60a9666 100644 --- a/components/ukm/ukm_recorder_impl.cc +++ b/components/ukm/ukm_recorder_impl.cc
@@ -39,6 +39,14 @@ kUkmFeature, "MaxSources", kDefaultMaxSources)); } +// Gets the maximum number of unferenced Sources kept after purging sources +// that were added to the log. +size_t GetMaxKeptSources() { + constexpr size_t kDefaultMaxKeptSources = 100; + return static_cast<size_t>(base::GetFieldTrialParamByFeatureAsInt( + kUkmFeature, "MaxKeptSources", kDefaultMaxKeptSources)); +} + // Gets the maximum number of Entries we'll keep in memory before discarding any // new ones being added. size_t GetMaxEntries() { @@ -109,21 +117,57 @@ void UkmRecorderImpl::StoreRecordingsInReport(Report* report) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - for (const auto& kv : sources_) { + + std::set<SourceId> ids_seen; + for (const auto& entry : entries_) { + Entry* proto_entry = report->add_entries(); + StoreEntryProto(*entry, proto_entry); + ids_seen.insert(entry->source_id); + } + + std::vector<std::unique_ptr<UkmSource>> unsent_sources; + for (auto& kv : sources_) { + // If the source id is not whitelisted, don't send it unless it has + // associated entries. Note: If ShouldRestrictToWhitelistedSourceIds() is + // true, this logic will not be hit as the source would have already been + // filtered in UpdateSourceURL(). + if (!IsWhitelistedSourceId(kv.first) && + !base::ContainsKey(ids_seen, kv.first)) { + unsent_sources.push_back(std::move(kv.second)); + continue; + } Source* proto_source = report->add_sources(); kv.second->PopulateProto(proto_source); if (!ShouldRecordInitialUrl()) proto_source->clear_initial_url(); } - for (const auto& entry : entries_) { - Entry* proto_entry = report->add_entries(); - StoreEntryProto(*entry, proto_entry); - } - UMA_HISTOGRAM_COUNTS_1000("UKM.Sources.SerializedCount", sources_.size()); + UMA_HISTOGRAM_COUNTS_1000("UKM.Sources.SerializedCount", + sources_.size() - unsent_sources.size()); UMA_HISTOGRAM_COUNTS_1000("UKM.Entries.SerializedCount", entries_.size()); + UMA_HISTOGRAM_COUNTS_1000("UKM.Sources.UnsentSourcesCount", + unsent_sources.size()); sources_.clear(); entries_.clear(); + + // Keep at most |max_kept_sources|, prioritizing most-recent entries (by + // creation time). + const size_t max_kept_sources = GetMaxKeptSources(); + if (unsent_sources.size() > max_kept_sources) { + std::nth_element(unsent_sources.begin(), + unsent_sources.begin() + max_kept_sources, + unsent_sources.end(), + [](const std::unique_ptr<ukm::UkmSource>& lhs, + const std::unique_ptr<ukm::UkmSource>& rhs) { + return lhs->creation_time() > rhs->creation_time(); + }); + unsent_sources.resize(max_kept_sources); + } + + for (auto& source : unsent_sources) { + sources_.emplace(source->id(), std::move(source)); + } + UMA_HISTOGRAM_COUNTS_1000("UKM.Sources.KeptSourcesCount", sources_.size()); } bool UkmRecorderImpl::ShouldRestrictToWhitelistedSourceIds() const {
diff --git a/components/ukm/ukm_recorder_impl.h b/components/ukm/ukm_recorder_impl.h index 00c79a2..a24820a 100644 --- a/components/ukm/ukm_recorder_impl.h +++ b/components/ukm/ukm_recorder_impl.h
@@ -46,7 +46,7 @@ // Writes recordings into a report proto, and clears recordings. void StoreRecordingsInReport(Report* report); - const std::map<ukm::SourceId, std::unique_ptr<UkmSource>>& sources() const { + const std::map<SourceId, std::unique_ptr<UkmSource>>& sources() const { return sources_; } @@ -68,8 +68,8 @@ bool recording_enabled_; // Contains newly added sources and entries of UKM metrics which periodically - // get serialized and cleared by BuildAndStoreLog(). - std::map<ukm::SourceId, std::unique_ptr<UkmSource>> sources_; + // get serialized and cleared by StoreRecordingsInReport(). + std::map<SourceId, std::unique_ptr<UkmSource>> sources_; std::vector<mojom::UkmEntryPtr> entries_; // Whitelisted Entry hashes, only the ones in this set will be recorded.
diff --git a/components/ukm/ukm_service_unittest.cc b/components/ukm/ukm_service_unittest.cc index 61dc025..7eabee4 100644 --- a/components/ukm/ukm_service_unittest.cc +++ b/components/ukm/ukm_service_unittest.cc
@@ -10,9 +10,13 @@ #include "base/hash.h" #include "base/metrics/metrics_hashes.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/string_util.h" #include "base/test/scoped_feature_list.h" #include "base/test/test_simple_task_runner.h" +#include "base/threading/platform_thread.h" #include "base/threading/thread_task_runner_handle.h" +#include "base/time/time.h" #include "components/metrics/test_metrics_provider.h" #include "components/metrics/test_metrics_service_client.h" #include "components/prefs/testing_pref_service.h" @@ -140,6 +144,10 @@ return ConvertToSourceId(id, SourceIdType::NAVIGATION_ID); } + static SourceId GetNonWhitelistedSourceId(int64_t id) { + return ConvertToSourceId(id, SourceIdType::UKM); + } + protected: TestingPrefServiceSimple prefs_; metrics::TestMetricsServiceClient client_; @@ -629,4 +637,87 @@ EXPECT_EQ("URLTooLong", proto_source.url()); } +TEST_F(UkmServiceTest, UnreferencedNonWhitelistedSources) { + for (bool restrict_to_whitelisted_source_ids : {true, false}) { + base::FieldTrialList field_trial_list(nullptr /* entropy_provider */); + // Set a threshold of number of Sources via Feature Params. + ScopedUkmFeatureParams params( + base::FeatureList::OVERRIDE_ENABLE_FEATURE, + {{"MaxKeptSources", "3"}, + {"WhitelistEntries", "EntryA,EntryB"}, + {"RestrictToWhitelistedSourceIds", + restrict_to_whitelisted_source_ids ? "true" : "false"}}); + + ClearPrefs(); + UkmService service(&prefs_, &client_); + TestRecordingHelper recorder(&service); + EXPECT_EQ(0, GetPersistedLogCount()); + service.Initialize(); + task_runner_->RunUntilIdle(); + service.EnableRecording(); + service.EnableReporting(); + + std::vector<SourceId> ids; + base::TimeTicks last_time = base::TimeTicks::Now(); + for (int i = 0; i < 6; ++i) { + // Wait until base::TimeTicks::Now() no longer equals |last_time|. This + // ensures each source has a unique timestamp to avoid flakes. Should take + // between 1-15ms per documented resolution of base::TimeTicks. + while (base::TimeTicks::Now() == last_time) { + base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(1)); + } + + ids.push_back(GetNonWhitelistedSourceId(i)); + recorder.UpdateSourceURL(ids.back(), GURL("https://google.com/foobar" + + base::NumberToString(i))); + last_time = base::TimeTicks::Now(); + } + + // Add whitelisted entries for 0, 2 and non-whitelisted entries for 2, 3. + recorder.GetEntryBuilder(ids[0], "EntryA")->AddMetric("Metric", 500); + recorder.GetEntryBuilder(ids[2], "EntryB")->AddMetric("Metric", 500); + recorder.GetEntryBuilder(ids[2], "EntryC")->AddMetric("Metric", 500); + recorder.GetEntryBuilder(ids[3], "EntryC")->AddMetric("Metric", 500); + + service.Flush(); + EXPECT_EQ(1, GetPersistedLogCount()); + auto proto_report = GetPersistedReport(); + + if (restrict_to_whitelisted_source_ids) { + ASSERT_EQ(0, proto_report.sources_size()); + } else { + ASSERT_EQ(2, proto_report.sources_size()); + EXPECT_EQ(ids[0], proto_report.sources(0).id()); + EXPECT_EQ("https://google.com/foobar0", proto_report.sources(0).url()); + EXPECT_EQ(ids[2], proto_report.sources(1).id()); + EXPECT_EQ("https://google.com/foobar2", proto_report.sources(1).url()); + } + + // Since MaxKeptSources is 3, only Sources 5, 4, 3 should be retained. + // Log entries under 0, 1, 3 and 4. Log them in reverse order - which + // shouldn't affect source ordering in the output. + // - Source 0 should not be re-transmitted since it was sent before. + // - Source 1 should not be transmitted due to MaxKeptSources param. + // - Sources 3 and 4 should be transmitted since they were not sent before. + recorder.GetEntryBuilder(ids[4], "EntryA")->AddMetric("Metric", 500); + recorder.GetEntryBuilder(ids[3], "EntryA")->AddMetric("Metric", 500); + recorder.GetEntryBuilder(ids[1], "EntryA")->AddMetric("Metric", 500); + recorder.GetEntryBuilder(ids[0], "EntryA")->AddMetric("Metric", 500); + + service.Flush(); + EXPECT_EQ(2, GetPersistedLogCount()); + proto_report = GetPersistedReport(); + + if (restrict_to_whitelisted_source_ids) { + ASSERT_EQ(0, proto_report.sources_size()); + } else { + ASSERT_EQ(2, proto_report.sources_size()); + EXPECT_EQ(ids[3], proto_report.sources(0).id()); + EXPECT_EQ("https://google.com/foobar3", proto_report.sources(0).url()); + EXPECT_EQ(ids[4], proto_report.sources(1).id()); + EXPECT_EQ("https://google.com/foobar4", proto_report.sources(1).url()); + } + } +} + } // namespace ukm
diff --git a/components/ukm/ukm_source.cc b/components/ukm/ukm_source.cc index e6fe138..e74e0535 100644 --- a/components/ukm/ukm_source.cc +++ b/components/ukm/ukm_source.cc
@@ -39,7 +39,9 @@ g_custom_tab_state = visible ? kCustomTabTrue : kCustomTabFalse; } -UkmSource::UkmSource() : custom_tab_state_(g_custom_tab_state) {} +UkmSource::UkmSource() + : custom_tab_state_(g_custom_tab_state), + creation_time_(base::TimeTicks::Now()) {} UkmSource::~UkmSource() = default;
diff --git a/components/ukm/ukm_source.h b/components/ukm/ukm_source.h index 6492cd1c..e053a1f 100644 --- a/components/ukm/ukm_source.h +++ b/components/ukm/ukm_source.h
@@ -35,6 +35,10 @@ const GURL& initial_url() const { return initial_url_; } const GURL& url() const { return url_; } + // The object creation time. This is for internal purposes only and is not + // intended to be anything useful for UKM clients. + const base::TimeTicks creation_time() const { return creation_time_; } + // Sets the URL for this source. Should be invoked when a source is // initialized. void set_url(const GURL& url) { url_ = url; } @@ -66,6 +70,9 @@ // the metric was created. const CustomTabState custom_tab_state_; + // When this object was created. + const base::TimeTicks creation_time_; + DISALLOW_COPY_AND_ASSIGN(UkmSource); };
diff --git a/components/update_client/action_runner.cc b/components/update_client/action_runner.cc index 974c6ab8..058750b 100644 --- a/components/update_client/action_runner.cc +++ b/components/update_client/action_runner.cc
@@ -13,9 +13,7 @@ #include "base/files/file_util.h" #include "base/location.h" #include "base/logging.h" -#include "base/single_thread_task_runner.h" -#include "base/threading/sequenced_task_runner_handle.h" -#include "base/threading/thread_task_runner_handle.h" +#include "base/task_scheduler/post_task.h" #include "components/update_client/component.h" #include "components/update_client/task_traits.h" #include "components/update_client/update_client.h" @@ -37,8 +35,9 @@ run_complete_ = std::move(run_complete); - base::SequencedTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::BindOnce(&ActionRunner::Unpack, base::Unretained(this))); + base::CreateSequencedTaskRunnerWithTraits(kTaskTraits) + ->PostTask(FROM_HERE, + base::BindOnce(&ActionRunner::Unpack, base::Unretained(this))); } void ActionRunner::Unpack() {
diff --git a/components/version_info/channel_android.cc b/components/version_info/channel_android.cc index b63b5ac..4e1cd4700 100644 --- a/components/version_info/channel_android.cc +++ b/components/version_info/channel_android.cc
@@ -9,8 +9,7 @@ namespace version_info { Channel ChannelFromPackageName(const char* package_name) { - if (!strcmp(package_name, "com.android.chrome") || - !strcmp(package_name, "com.chrome.work")) + if (!strcmp(package_name, "com.android.chrome")) return Channel::STABLE; if (!strcmp(package_name, "com.chrome.beta")) return Channel::BETA;
diff --git a/components/viz/host/host_frame_sink_manager.cc b/components/viz/host/host_frame_sink_manager.cc index e232f0f..17f812d7 100644 --- a/components/viz/host/host_frame_sink_manager.cc +++ b/components/viz/host/host_frame_sink_manager.cc
@@ -26,6 +26,10 @@ frame_sink_manager_impl_ = frame_sink_manager_impl; frame_sink_manager_ = frame_sink_manager_impl; + + // Assign temporary references if FrameSinkManagerImpl is using them. + assign_temporary_references_ = + frame_sink_manager_impl_->surface_manager()->using_surface_references(); } void HostFrameSinkManager::BindAndSetManager( @@ -176,13 +180,19 @@ frame_sink_data_map_.erase(parent_frame_sink_id); } +void HostFrameSinkManager::WillAssignTemporaryReferencesExternally() { + assign_temporary_references_ = false; +} + void HostFrameSinkManager::AssignTemporaryReference( const SurfaceId& surface_id, const FrameSinkId& frame_sink_id) { + DCHECK(!assign_temporary_references_); frame_sink_manager_->AssignTemporaryReference(surface_id, frame_sink_id); } void HostFrameSinkManager::DropTemporaryReference(const SurfaceId& surface_id) { + DCHECK(!assign_temporary_references_); frame_sink_manager_->DropTemporaryReference(surface_id); } @@ -223,10 +233,14 @@ void HostFrameSinkManager::PerformAssignTemporaryReference( const SurfaceId& surface_id) { - // Find the expected embedder for the new surface and assign the temporary - // reference to it. auto iter = frame_sink_data_map_.find(surface_id.frame_sink_id()); - DCHECK(iter != frame_sink_data_map_.end()); + if (iter == frame_sink_data_map_.end()) { + // We don't have any hierarchy information for what will embed the new + // surface, drop the temporary reference. + frame_sink_manager_->DropTemporaryReference(surface_id); + return; + } + const FrameSinkData& data = iter->second; // Display roots don't have temporary references to assign. @@ -244,7 +258,7 @@ for (const FrameSinkId& parent_id : data.parents) { const FrameSinkData& parent_data = frame_sink_data_map_[parent_id]; if (parent_data.IsFrameSinkRegistered()) { - frame_sink_manager_impl_->AssignTemporaryReference(surface_id, parent_id); + frame_sink_manager_->AssignTemporaryReference(surface_id, parent_id); return; } } @@ -264,7 +278,7 @@ binding_.Close(); frame_sink_manager_ptr_.reset(); - frame_sink_manager_impl_ = nullptr; + frame_sink_manager_ = nullptr; // CompositorFrameSinks are lost along with the connection to // mojom::FrameSinkManager. @@ -297,23 +311,20 @@ void HostFrameSinkManager::OnFirstSurfaceActivation( const SurfaceInfo& surface_info) { + // TODO(kylechar): This needs to happen when the surface is created, not when + // it first activates. + if (assign_temporary_references_) + PerformAssignTemporaryReference(surface_info.id()); + auto it = frame_sink_data_map_.find(surface_info.id().frame_sink_id()); + // If we've received a bogus or stale SurfaceId from Viz then just ignore it. - if (it == frame_sink_data_map_.end()) { - // We don't have any hierarchy information for what will embed the new - // surface, drop the temporary reference. - frame_sink_manager_->DropTemporaryReference(surface_info.id()); + if (it == frame_sink_data_map_.end()) return; - } FrameSinkData& frame_sink_data = it->second; if (frame_sink_data.client) frame_sink_data.client->OnFirstSurfaceActivation(surface_info); - - if (frame_sink_manager_impl_ && - frame_sink_manager_impl_->surface_manager()->using_surface_references()) { - PerformAssignTemporaryReference(surface_info.id()); - } } void HostFrameSinkManager::OnClientConnectionClosed(
diff --git a/components/viz/host/host_frame_sink_manager.h b/components/viz/host/host_frame_sink_manager.h index cd60b2b..5e007f3 100644 --- a/components/viz/host/host_frame_sink_manager.h +++ b/components/viz/host/host_frame_sink_manager.h
@@ -44,11 +44,12 @@ : public mojom::FrameSinkManagerClient, public CompositorFrameSinkSupportManager { public: + using DisplayHitTestQueryMap = + base::flat_map<FrameSinkId, std::unique_ptr<HitTestQuery>>; + HostFrameSinkManager(); ~HostFrameSinkManager() override; - using DisplayHitTestQueryMap = - base::flat_map<FrameSinkId, std::unique_ptr<HitTestQuery>>; const DisplayHitTestQueryMap& display_hit_test_query() const { return display_hit_test_query_; } @@ -114,9 +115,10 @@ void UnregisterFrameSinkHierarchy(const FrameSinkId& parent_frame_sink_id, const FrameSinkId& child_frame_sink_id); - // These two functions should only be used by WindowServer. + // These three functions should only be used by WindowServer. // TODO(riajiang): Find a better way for HostFrameSinkManager to do the assign // and drop instead. + void WillAssignTemporaryReferencesExternally(); void AssignTemporaryReference(const SurfaceId& surface_id, const FrameSinkId& owner); void DropTemporaryReference(const SurfaceId& surface_id); @@ -227,6 +229,11 @@ // If |frame_sink_manager_ptr_| connection was lost. bool connection_was_lost_ = false; + // If a FrameSinkId owner should be assigned when a new surface is created. + // This will be set false if using surface sequences or if temporary + // references are being assigned externally. + bool assign_temporary_references_ = true; + base::RepeatingClosure connection_lost_callback_; DisplayHitTestQueryMap display_hit_test_query_;
diff --git a/components/viz/host/host_frame_sink_manager_unittest.cc b/components/viz/host/host_frame_sink_manager_unittest.cc index c643209d..73cdc13 100644 --- a/components/viz/host/host_frame_sink_manager_unittest.cc +++ b/components/viz/host/host_frame_sink_manager_unittest.cc
@@ -624,5 +624,33 @@ kFrameSinkChild1, 1); } +// Verify that HostFrameSinkManager assigns temporary references when connected +// to a remote mojom::FrameSinkManager. +TEST_F(HostFrameSinkManagerRemoteTest, AssignTemporaryReference) { + FakeHostFrameSinkClient host_client; + host().RegisterFrameSinkId(kFrameSinkParent1, &host_client); + + const SurfaceId surface_id = MakeSurfaceId(kFrameSinkChild1, 1); + host().RegisterFrameSinkId(surface_id.frame_sink_id(), &host_client); + MockCompositorFrameSinkClient compositor_frame_sink_client; + mojom::CompositorFrameSinkPtr compositor_frame_sink; + host().CreateCompositorFrameSink( + kFrameSinkChild1, MakeRequest(&compositor_frame_sink), + compositor_frame_sink_client.BindInterfacePtr()); + + host().RegisterFrameSinkHierarchy(kFrameSinkParent1, + surface_id.frame_sink_id()); + + // When HostFrameSinkManager gets OnFirstSurfaceActivation() it should assign + // the temporary reference to the registered parent |kFrameSinkParent1|. + GetFrameSinkManagerClient()->OnFirstSurfaceActivation( + MakeSurfaceInfo(surface_id)); + + base::RunLoop run_loop; + EXPECT_CALL(impl(), AssignTemporaryReference(surface_id, kFrameSinkParent1)) + .WillOnce(InvokeClosure(run_loop.QuitClosure())); + run_loop.Run(); +} + } // namespace test } // namespace viz
diff --git a/components/viz/service/display/renderer_pixeltest.cc b/components/viz/service/display/renderer_pixeltest.cc index b06029b..1026d47 100644 --- a/components/viz/service/display/renderer_pixeltest.cc +++ b/components/viz/service/display/renderer_pixeltest.cc
@@ -1325,7 +1325,7 @@ GLRendererPixelTest::SetUp(); bool use_stream_video_draw_quad = false; video_resource_updater_ = std::make_unique<cc::VideoResourceUpdater>( - output_surface_->context_provider(), resource_provider_.get(), + child_context_provider_.get(), child_resource_provider_.get(), use_stream_video_draw_quad); }
diff --git a/components/viz/service/display/surface_aggregator.cc b/components/viz/service/display/surface_aggregator.cc index 72df7c16..2baaa13 100644 --- a/components/viz/service/display/surface_aggregator.cc +++ b/components/viz/service/display/surface_aggregator.cc
@@ -42,6 +42,8 @@ "Compositing.SurfaceAggregator.SurfaceDrawQuad.MissingSurface"; const char kUmaNoActiveFrame[] = "Compositing.SurfaceAggregator.SurfaceDrawQuad.NoActiveFrame"; +const char kUmaUsingFallbackSurface[] = + "Compositing.SurfaceAggregator.SurfaceDrawQuad.UsingFallbackSurface"; void MoveMatchingRequests( RenderPassId render_pass_id, @@ -245,6 +247,8 @@ fallback_frame.metadata.root_background_color, dest_pass); } + ++uma_stats_.using_fallback_surface; + EmitSurfaceContent(fallback_surface, parent_device_scale_factor, surface_quad->shared_quad_state, surface_quad->rect, surface_quad->visible_rect, target_transform, clip_rect, @@ -1205,7 +1209,9 @@ kUmaStatMaxSurfaces); UMA_HISTOGRAM_EXACT_LINEAR(kUmaNoActiveFrame, uma_stats_.no_active_frame, kUmaStatMaxSurfaces); - + UMA_HISTOGRAM_EXACT_LINEAR(kUmaUsingFallbackSurface, + uma_stats_.using_fallback_surface, + kUmaStatMaxSurfaces); return frame; }
diff --git a/components/viz/service/display/surface_aggregator.h b/components/viz/service/display/surface_aggregator.h index cf7eabc..f7976df9 100644 --- a/components/viz/service/display/surface_aggregator.h +++ b/components/viz/service/display/surface_aggregator.h
@@ -83,14 +83,21 @@ valid_surface = 0; missing_surface = 0; no_active_frame = 0; + using_fallback_surface = 0; } // The surface exists and has an active frame. int valid_surface; + // The surface doesn't exist. int missing_surface; + // The surface exists but doesn't have an active frame. int no_active_frame; + + // The primary surface is not available but the fallback + // is used. + int using_fallback_surface; }; ClipData CalculateClipRect(const ClipData& surface_clip,
diff --git a/components/viz/service/gl/gpu_service_impl.cc b/components/viz/service/gl/gpu_service_impl.cc index 6205322..0fdea8a 100644 --- a/components/viz/service/gl/gpu_service_impl.cc +++ b/components/viz/service/gl/gpu_service_impl.cc
@@ -480,6 +480,11 @@ } #endif +void GpuServiceImpl::DidCreateContextSuccessfully() { + DCHECK(main_runner_->BelongsToCurrentThread()); + (*gpu_host_)->DidCreateContextSuccessfully(); +} + void GpuServiceImpl::DidCreateOffscreenContext(const GURL& active_url) { DCHECK(main_runner_->BelongsToCurrentThread()); (*gpu_host_)->DidCreateOffscreenContext(active_url);
diff --git a/components/viz/service/gl/gpu_service_impl.h b/components/viz/service/gl/gpu_service_impl.h index 5c9784e..3e26b06 100644 --- a/components/viz/service/gl/gpu_service_impl.h +++ b/components/viz/service/gl/gpu_service_impl.h
@@ -117,6 +117,7 @@ void UpdateGpuInfoPlatform(base::OnceClosure on_gpu_info_updated); // gpu::GpuChannelManagerDelegate: + void DidCreateContextSuccessfully() override; void DidCreateOffscreenContext(const GURL& active_url) override; void DidDestroyChannel(int client_id) override; void DidDestroyOffscreenContext(const GURL& active_url) override;
diff --git a/components/viz/service/surfaces/surface_dependency_deadline.cc b/components/viz/service/surfaces/surface_dependency_deadline.cc index 20bbad6b..4147e8d8 100644 --- a/components/viz/service/surfaces/surface_dependency_deadline.cc +++ b/components/viz/service/surfaces/surface_dependency_deadline.cc
@@ -4,6 +4,8 @@ #include "components/viz/service/surfaces/surface_dependency_deadline.h" +#include "base/metrics/histogram_macros.h" + namespace viz { SurfaceDependencyDeadline::SurfaceDependencyDeadline( @@ -23,14 +25,12 @@ DCHECK_GT(number_of_frames_to_deadline, 0u); DCHECK(!number_of_frames_to_deadline_); number_of_frames_to_deadline_ = number_of_frames_to_deadline; + start_time_ = base::TimeTicks::Now(); begin_frame_source_->AddObserver(this); } void SurfaceDependencyDeadline::Cancel() { - if (!number_of_frames_to_deadline_) - return; - begin_frame_source_->RemoveObserver(this); - number_of_frames_to_deadline_.reset(); + CancelInternal(false); } bool SurfaceDependencyDeadline::InheritFrom( @@ -38,12 +38,14 @@ if (*this == other) return false; - Cancel(); + CancelInternal(false); last_begin_frame_args_ = other.last_begin_frame_args_; begin_frame_source_ = other.begin_frame_source_; number_of_frames_to_deadline_ = other.number_of_frames_to_deadline_; - if (number_of_frames_to_deadline_) + if (number_of_frames_to_deadline_) { + start_time_ = base::TimeTicks::Now(); begin_frame_source_->AddObserver(this); + } return true; } @@ -64,7 +66,7 @@ if (--(*number_of_frames_to_deadline_) > 0) return; - Cancel(); + CancelInternal(true); client_->OnDeadline(); } @@ -76,4 +78,17 @@ void SurfaceDependencyDeadline::OnBeginFrameSourcePausedChanged(bool paused) {} +void SurfaceDependencyDeadline::CancelInternal(bool deadline) { + if (!number_of_frames_to_deadline_) + return; + begin_frame_source_->RemoveObserver(this); + number_of_frames_to_deadline_.reset(); + + UMA_HISTOGRAM_TIMES("Compositing.SurfaceDependencyDeadline.Duration", + base::TimeTicks::Now() - start_time_); + + UMA_HISTOGRAM_BOOLEAN("Compositing.SurfaceDependencyDeadline.DeadlineHit", + deadline); +} + } // namespace viz
diff --git a/components/viz/service/surfaces/surface_dependency_deadline.h b/components/viz/service/surfaces/surface_dependency_deadline.h index 522b13c..7bb100c 100644 --- a/components/viz/service/surfaces/surface_dependency_deadline.h +++ b/components/viz/service/surfaces/surface_dependency_deadline.h
@@ -39,9 +39,12 @@ void OnBeginFrameSourcePausedChanged(bool paused) override; private: + void CancelInternal(bool deadline); + SurfaceDeadlineClient* const client_; BeginFrameSource* begin_frame_source_ = nullptr; base::Optional<uint32_t> number_of_frames_to_deadline_; + base::TimeTicks start_time_; BeginFrameArgs last_begin_frame_args_;
diff --git a/components/viz/test/data/blur_filter_with_clip_sw.png b/components/viz/test/data/blur_filter_with_clip_sw.png index 997a767..8902770 100644 --- a/components/viz/test/data/blur_filter_with_clip_sw.png +++ b/components/viz/test/data/blur_filter_with_clip_sw.png Binary files differ
diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index 33aa1c7f..7540b10 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn
@@ -1453,10 +1453,6 @@ "service_worker/embedded_worker_registry.cc", "service_worker/embedded_worker_registry.h", "service_worker/embedded_worker_status.h", - "service_worker/foreign_fetch_request_handler.cc", - "service_worker/foreign_fetch_request_handler.h", - "service_worker/link_header_support.cc", - "service_worker/link_header_support.h", "service_worker/service_worker_blob_reader.cc", "service_worker/service_worker_blob_reader.h", "service_worker/service_worker_cache_writer.cc", @@ -2142,12 +2138,12 @@ "speech/speech_recognizer_impl.h", # Most webauth code is non-Android - "webauth/attestation_data.cc", - "webauth/attestation_data.h", "webauth/attestation_object.cc", "webauth/attestation_object.h", "webauth/attestation_statement.cc", "webauth/attestation_statement.h", + "webauth/attested_credential_data.cc", + "webauth/attested_credential_data.h", "webauth/authenticator_data.cc", "webauth/authenticator_data.h", "webauth/authenticator_impl.cc",
diff --git a/content/browser/accessibility/dump_accessibility_tree_browsertest.cc b/content/browser/accessibility/dump_accessibility_tree_browsertest.cc index 22af9d5..9a0adcd 100644 --- a/content/browser/accessibility/dump_accessibility_tree_browsertest.cc +++ b/content/browser/accessibility/dump_accessibility_tree_browsertest.cc
@@ -283,6 +283,11 @@ RunHtmlTest(FILE_PATH_LITERAL("abbr.html")); } +IN_PROC_BROWSER_TEST_F(DumpAccessibilityTreeTest, + AccessibilityAbsoluteOffscreen) { + RunHtmlTest(FILE_PATH_LITERAL("absolute-offscreen.html")); +} + IN_PROC_BROWSER_TEST_F(DumpAccessibilityTreeTest, AccessibilityActionVerbs) { RunHtmlTest(FILE_PATH_LITERAL("action-verbs.html")); }
diff --git a/content/browser/accessibility/one_shot_accessibility_tree_search_unittest.cc b/content/browser/accessibility/one_shot_accessibility_tree_search_unittest.cc index 603e838..13a377496 100644 --- a/content/browser/accessibility/one_shot_accessibility_tree_search_unittest.cc +++ b/content/browser/accessibility/one_shot_accessibility_tree_search_unittest.cc
@@ -67,6 +67,7 @@ root.SetName("Document"); root.role = ui::AX_ROLE_ROOT_WEB_AREA; root.location = gfx::RectF(0, 0, 800, 600); + root.AddBoolAttribute(ui::AX_ATTR_CLIPS_CHILDREN, true); root.child_ids.push_back(2); root.child_ids.push_back(3); root.child_ids.push_back(6);
diff --git a/content/browser/background_fetch/background_fetch_data_manager.cc b/content/browser/background_fetch/background_fetch_data_manager.cc index 12ad59f1..21b9620 100644 --- a/content/browser/background_fetch/background_fetch_data_manager.cc +++ b/content/browser/background_fetch/background_fetch_data_manager.cc
@@ -274,7 +274,6 @@ auto registration = std::make_unique<BackgroundFetchRegistration>(); registration->developer_id = developer_id; registration->unique_id = unique_id; - registration->title = data->options().title; // TODO(crbug.com/774054): Uploads are not yet supported. registration->upload_total = 0; registration->uploaded = 0;
diff --git a/content/browser/background_fetch/background_fetch_service_unittest.cc b/content/browser/background_fetch/background_fetch_service_unittest.cc index d61536c..bbe524e 100644 --- a/content/browser/background_fetch/background_fetch_service_unittest.cc +++ b/content/browser/background_fetch/background_fetch_service_unittest.cc
@@ -263,7 +263,6 @@ // The |registration| should reflect the options given in |options|. EXPECT_EQ(registration.developer_id, kExampleDeveloperId); - EXPECT_EQ(registration.title, options.title); EXPECT_EQ(registration.download_total, options.download_total); blink::mojom::BackgroundFetchError second_error; @@ -276,7 +275,6 @@ // The |second_registration| should reflect the options given in |options|. EXPECT_EQ(second_registration.developer_id, kExampleDeveloperId); - EXPECT_EQ(second_registration.title, options.title); EXPECT_EQ(second_registration.download_total, options.download_total); } @@ -539,7 +537,6 @@ Fetch(service_worker_registration_id, kExampleDeveloperId, requests, options, &error, ®istration); ASSERT_EQ(blink::mojom::BackgroundFetchError::NONE, error); - ASSERT_EQ(options.title, registration.title); std::string second_title = "2nd title"; @@ -553,8 +550,6 @@ GetRegistration(service_worker_registration_id, kExampleDeveloperId, &error, &second_registration); ASSERT_EQ(blink::mojom::BackgroundFetchError::NONE, error); - EXPECT_NE(options.title, second_registration.title); - EXPECT_EQ(second_title, second_registration.title); } TEST_F(BackgroundFetchServiceTest, Abort) { @@ -737,7 +732,6 @@ &gotten_registration); EXPECT_EQ(blink::mojom::BackgroundFetchError::NONE, error); EXPECT_EQ(second_registration.unique_id, gotten_registration.unique_id); - EXPECT_EQ(second_registration.title, gotten_registration.title); // Calling UpdateUI for the second registration should succeed, and update the // title of the second registration only. @@ -760,7 +754,6 @@ &gotten_registration); EXPECT_EQ(blink::mojom::BackgroundFetchError::NONE, error); EXPECT_EQ(second_registration.unique_id, gotten_registration.unique_id); - EXPECT_EQ(updated_second_registration_title, gotten_registration.title); // Aborting the previously aborted registration should fail with INVALID_ID // since it is no longer active.
diff --git a/content/browser/background_fetch/storage/create_registration_task.cc b/content/browser/background_fetch/storage/create_registration_task.cc index 41aee0ca..e949232 100644 --- a/content/browser/background_fetch/storage/create_registration_task.cc +++ b/content/browser/background_fetch/storage/create_registration_task.cc
@@ -79,7 +79,6 @@ registration_ = std::make_unique<BackgroundFetchRegistration>(); registration_->developer_id = registration_id_.developer_id(); registration_->unique_id = registration_id_.unique_id(); - registration_->title = options_.title; // TODO(crbug.com/774054): Uploads are not yet supported. registration_->upload_total = 0; registration_->uploaded = 0;
diff --git a/content/browser/background_sync/background_sync_manager.cc b/content/browser/background_sync/background_sync_manager.cc index 6b9aa9e..c5fd8e3 100644 --- a/content/browser/background_sync/background_sync_manager.cc +++ b/content/browser/background_sync/background_sync_manager.cc
@@ -285,7 +285,7 @@ parameters_(new BackgroundSyncParameters()), disabled_(false), num_firing_registrations_(0), - clock_(new base::DefaultClock()), + clock_(base::DefaultClock::GetInstance()), weak_ptr_factory_(this) { DCHECK_CURRENTLY_ON(BrowserThread::IO);
diff --git a/content/browser/background_sync/background_sync_manager.h b/content/browser/background_sync/background_sync_manager.h index 06fc25d..c5b144e 100644 --- a/content/browser/background_sync/background_sync_manager.h +++ b/content/browser/background_sync/background_sync_manager.h
@@ -95,9 +95,9 @@ return network_observer_.get(); } - void set_clock(std::unique_ptr<base::Clock> clock) { + void set_clock(base::Clock* clock) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - clock_ = std::move(clock); + clock_ = clock; } // Called from DevTools @@ -299,7 +299,7 @@ std::unique_ptr<BackgroundSyncNetworkObserver> network_observer_; - std::unique_ptr<base::Clock> clock_; + base::Clock* clock_; base::WeakPtrFactory<BackgroundSyncManager> weak_ptr_factory_;
diff --git a/content/browser/background_sync/background_sync_manager_unittest.cc b/content/browser/background_sync/background_sync_manager_unittest.cc index 68c24b5..7b20c5b 100644 --- a/content/browser/background_sync/background_sync_manager_unittest.cc +++ b/content/browser/background_sync/background_sync_manager_unittest.cc
@@ -212,8 +212,7 @@ new TestBackgroundSyncManager(helper_->context_wrapper()); background_sync_manager_.reset(test_background_sync_manager_); - test_clock_ = new base::SimpleTestClock(); - background_sync_manager_->set_clock(base::WrapUnique(test_clock_)); + background_sync_manager_->set_clock(&test_clock_); // Many tests do not expect the sync event to fire immediately after // register (and cleanup up the sync registrations). Tests can control when @@ -248,7 +247,6 @@ void DeleteBackgroundSyncManager() { background_sync_manager_.reset(); test_background_sync_manager_ = nullptr; - test_clock_ = nullptr; } bool Register(const BackgroundSyncRegistrationOptions& sync_options) { @@ -422,7 +420,7 @@ std::unique_ptr<BackgroundSyncManager> background_sync_manager_; std::unique_ptr<StoragePartitionImpl> storage_partition_impl_; TestBackgroundSyncManager* test_background_sync_manager_ = nullptr; - base::SimpleTestClock* test_clock_ = nullptr; + base::SimpleTestClock test_clock_; int64_t sw_registration_id_1_; int64_t sw_registration_id_2_; @@ -1192,7 +1190,7 @@ test_background_sync_manager_->delayed_task_delta()); // Fire again and this time it should permanently fail. - test_clock_->Advance(test_background_sync_manager_->delayed_task_delta()); + test_clock_.Advance(test_background_sync_manager_->delayed_task_delta()); test_background_sync_manager_->RunDelayedTask(); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(GetRegistration(sync_options_1_)); @@ -1210,7 +1208,7 @@ // The second run will fail but it will setup a timer to try again. base::TimeDelta first_delta = test_background_sync_manager_->delayed_task_delta(); - test_clock_->Advance(test_background_sync_manager_->delayed_task_delta()); + test_clock_.Advance(test_background_sync_manager_->delayed_task_delta()); test_background_sync_manager_->RunDelayedTask(); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(GetRegistration(sync_options_1_)); @@ -1219,7 +1217,7 @@ EXPECT_LT(first_delta, test_background_sync_manager_->delayed_task_delta()); // The third run will permanently fail. - test_clock_->Advance(test_background_sync_manager_->delayed_task_delta()); + test_clock_.Advance(test_background_sync_manager_->delayed_task_delta()); test_background_sync_manager_->RunDelayedTask(); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(GetRegistration(sync_options_1_)); @@ -1236,8 +1234,8 @@ // Fire again one second before it's ready to retry. Expect it to reschedule // the delay timer for one more second. - test_clock_->Advance(test_background_sync_manager_->delayed_task_delta() - - base::TimeDelta::FromSeconds(1)); + test_clock_.Advance(test_background_sync_manager_->delayed_task_delta() - + base::TimeDelta::FromSeconds(1)); test_background_sync_manager_->RunDelayedTask(); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(GetRegistration(sync_options_1_)); @@ -1245,7 +1243,7 @@ test_background_sync_manager_->delayed_task_delta()); // Fire one second later and it should fail permanently. - test_clock_->Advance(base::TimeDelta::FromSeconds(1)); + test_clock_.Advance(base::TimeDelta::FromSeconds(1)); test_background_sync_manager_->RunDelayedTask(); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(GetRegistration(sync_options_1_)); @@ -1263,7 +1261,7 @@ base::TimeDelta delta = test_background_sync_manager_->delayed_task_delta(); CreateBackgroundSyncManager(); InitFailedSyncEventTest(); - test_clock_->Advance(delta); + test_clock_.Advance(delta); InitBackgroundSyncManager(); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(GetRegistration(sync_options_1_)); @@ -1281,7 +1279,7 @@ base::TimeDelta delta = test_background_sync_manager_->delayed_task_delta(); CreateBackgroundSyncManager(); InitFailedSyncEventTest(); - test_clock_->Advance(delta - base::TimeDelta::FromSeconds(1)); + test_clock_.Advance(delta - base::TimeDelta::FromSeconds(1)); InitBackgroundSyncManager(); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(GetRegistration(sync_options_1_)); @@ -1300,7 +1298,7 @@ // fire once and then fail permanently. CreateBackgroundSyncManager(); InitFailedSyncEventTest(); - test_clock_->Advance(delta); + test_clock_.Advance(delta); InitBackgroundSyncManager(); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(GetRegistration(sync_options_1_)); @@ -1314,7 +1312,7 @@ EXPECT_TRUE(Register(sync_options_1_)); // Run it a second time. - test_clock_->Advance(test_background_sync_manager_->delayed_task_delta()); + test_clock_.Advance(test_background_sync_manager_->delayed_task_delta()); test_background_sync_manager_->RunDelayedTask(); base::RunLoop().RunUntilIdle(); @@ -1326,7 +1324,7 @@ EXPECT_GT(delay_delta, test_background_sync_manager_->delayed_task_delta()); while (test_background_sync_manager_->IsDelayedTaskScheduled()) { - test_clock_->Advance(test_background_sync_manager_->delayed_task_delta()); + test_clock_.Advance(test_background_sync_manager_->delayed_task_delta()); test_background_sync_manager_->RunDelayedTask(); EXPECT_FALSE(test_background_sync_manager_->IsDelayedTaskScheduled()); base::RunLoop().RunUntilIdle(); @@ -1346,7 +1344,7 @@ EXPECT_TRUE(GetRegistration(sync_options_1_)); // Run it again. - test_clock_->Advance(test_background_sync_manager_->delayed_task_delta()); + test_clock_.Advance(test_background_sync_manager_->delayed_task_delta()); test_background_sync_manager_->RunDelayedTask(); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(GetRegistration(sync_options_1_));
diff --git a/content/browser/browser_main_loop.cc b/content/browser/browser_main_loop.cc index 54ad1c51..f3d5fb6 100644 --- a/content/browser/browser_main_loop.cc +++ b/content/browser/browser_main_loop.cc
@@ -130,6 +130,7 @@ #include "third_party/boringssl/src/include/openssl/evp.h" #include "ui/base/clipboard/clipboard.h" #include "ui/base/ui_base_switches.h" +#include "ui/base/ui_base_switches_util.h" #include "ui/display/display_switches.h" #include "ui/gfx/switches.h" @@ -1454,9 +1455,6 @@ #if BUILDFLAG(ENABLE_MUS) if (IsUsingMus()) { - base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( - switches::kMus, - IsMusHostingViz() ? switches::kMusHostVizValue : std::string()); base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableSurfaceSynchronization); } @@ -1480,7 +1478,7 @@ BrowserThread::GetTaskRunnerForThread(BrowserThread::IO)); // If mus is not hosting viz, then the browser must. - bool browser_is_viz_host = !IsMusHostingViz(); + bool browser_is_viz_host = !switches::IsMusHostingViz(); bool always_uses_gpu = true; bool established_gpu_channel = false;
diff --git a/content/browser/compositor/gpu_process_transport_factory.cc b/content/browser/compositor/gpu_process_transport_factory.cc index f230ebf5..cddd17c 100644 --- a/content/browser/compositor/gpu_process_transport_factory.cc +++ b/content/browser/compositor/gpu_process_transport_factory.cc
@@ -60,6 +60,7 @@ #include "services/service_manager/runner/common/client_util.h" #include "services/ui/public/cpp/gpu/context_provider_command_buffer.h" #include "third_party/khronos/GLES2/gl2.h" +#include "ui/base/ui_base_switches_util.h" #include "ui/compositor/compositor.h" #include "ui/compositor/compositor_switches.h" #include "ui/compositor/layer.h" @@ -242,7 +243,7 @@ return base::WrapUnique(new viz::SoftwareOutputDevice); #if defined(USE_AURA) - if (IsMusHostingViz()) { + if (switches::IsMusHostingViz()) { NOTREACHED(); return nullptr; }
diff --git a/content/browser/devtools/devtools_frontend_host_impl.cc b/content/browser/devtools/devtools_frontend_host_impl.cc index 6f9890943..afa8104 100644 --- a/content/browser/devtools/devtools_frontend_host_impl.cc +++ b/content/browser/devtools/devtools_frontend_host_impl.cc
@@ -11,8 +11,8 @@ #include "content/browser/devtools/grit/devtools_resources_map.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" -#include "content/public/common/associated_interface_provider.h" #include "content/public/common/content_client.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" namespace content {
diff --git a/content/browser/devtools/devtools_url_interceptor_request_job.cc b/content/browser/devtools/devtools_url_interceptor_request_job.cc index 08e5bf01..5ddde72 100644 --- a/content/browser/devtools/devtools_url_interceptor_request_job.cc +++ b/content/browser/devtools/devtools_url_interceptor_request_job.cc
@@ -122,7 +122,7 @@ resource_request_info->requester_info(), resource_request_info->GetRouteID(), resource_request_info->GetFrameTreeNodeId(), - resource_request_info->GetOriginPID(), + resource_request_info->GetPluginChildID(), resource_request_info->GetRequestID(), resource_request_info->GetRenderFrameID(), resource_request_info->IsMainFrame(),
diff --git a/content/browser/devtools/protocol/devtools_protocol_browsertest.cc b/content/browser/devtools/protocol/devtools_protocol_browsertest.cc index aecef74..4344899 100644 --- a/content/browser/devtools/protocol/devtools_protocol_browsertest.cc +++ b/content/browser/devtools/protocol/devtools_protocol_browsertest.cc
@@ -153,6 +153,7 @@ }; void RunBeforeUnloadDialog(WebContents* web_contents, + RenderFrameHost* render_frame_host, bool is_reload, DialogClosedCallback callback) override {}
diff --git a/content/browser/devtools/protocol/service_worker_handler.cc b/content/browser/devtools/protocol/service_worker_handler.cc index 54e667e..d2478ae3 100644 --- a/content/browser/devtools/protocol/service_worker_handler.cc +++ b/content/browser/devtools/protocol/service_worker_handler.cc
@@ -29,6 +29,7 @@ #include "content/public/browser/web_contents.h" #include "content/public/common/push_event_payload.h" #include "content/public/common/push_messaging_status.mojom.h" +#include "third_party/WebKit/common/service_worker/service_worker_provider_type.mojom.h" #include "third_party/WebKit/public/platform/modules/serviceworker/service_worker_object.mojom.h" #include "url/gurl.h" @@ -383,7 +384,8 @@ base::flat_set<std::string> client_set; for (const auto& client : version.clients) { - if (client.second.type == SERVICE_WORKER_PROVIDER_FOR_WINDOW) { + if (client.second.type == + blink::mojom::ServiceWorkerProviderType::kForWindow) { // PlzNavigate: a navigation may not yet be associated with a // RenderFrameHost. Use the |web_contents_getter| instead. WebContents* web_contents =
diff --git a/content/browser/devtools/render_frame_devtools_agent_host.cc b/content/browser/devtools/render_frame_devtools_agent_host.cc index bab7e26..0e5d035 100644 --- a/content/browser/devtools/render_frame_devtools_agent_host.cc +++ b/content/browser/devtools/render_frame_devtools_agent_host.cc
@@ -46,10 +46,10 @@ #include "content/public/browser/network_service_instance.h" #include "content/public/browser/render_widget_host_iterator.h" #include "content/public/browser/web_contents_delegate.h" -#include "content/public/common/associated_interface_provider.h" #include "content/public/common/browser_side_navigation_policy.h" #include "content/public/common/content_features.h" #include "mojo/public/cpp/bindings/associated_binding.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" #if defined(OS_ANDROID) #include "content/public/browser/render_widget_host_view.h"
diff --git a/content/browser/dom_storage/dom_storage_browsertest.cc b/content/browser/dom_storage/dom_storage_browsertest.cc index 2e5e126..91e83e0 100644 --- a/content/browser/dom_storage/dom_storage_browsertest.cc +++ b/content/browser/dom_storage/dom_storage_browsertest.cc
@@ -16,6 +16,7 @@ #include "content/public/test/browser_test_utils.h" #include "content/public/test/content_browser_test.h" #include "content/public/test/content_browser_test_utils.h" +#include "content/public/test/test_launcher.h" #include "content/shell/browser/shell.h" namespace content { @@ -123,9 +124,7 @@ void SetUpCommandLine(base::CommandLine* command_line) override { ContentBrowserTest::SetUpCommandLine(command_line); // Only enable mojo local storage if this is not a PRE_ test. - const testing::TestInfo* test = - testing::UnitTest::GetInstance()->current_test_info(); - if (base::StartsWith(test->name(), "PRE_", base::CompareCase::SENSITIVE)) + if (IsPreTest()) command_line->AppendSwitch(switches::kDisableMojoLocalStorage); } };
diff --git a/content/browser/download/download_manager_impl.cc b/content/browser/download/download_manager_impl.cc index ae9078e3..f8830e1 100644 --- a/content/browser/download/download_manager_impl.cc +++ b/content/browser/download/download_manager_impl.cc
@@ -194,14 +194,17 @@ return nullptr; } + ResourceRequestInfo::WebContentsGetter getter = + base::Bind(&GetWebContents, params->render_process_host_id(), + params->render_frame_host_routing_id(), -1); // TODO(qinmin): Check the storage permission before creating the URLLoader. // This is already done for context menu download, but it is missing for // download service and download resumption. return DownloadManagerImpl::UniqueUrlDownloadHandlerPtr( ResourceDownloader::BeginDownload( download_manager, std::move(params), std::move(request), - url_loader_factory_getter, file_system_context, - base::Bind(&GetWebContents, -1, -1, -1), download_id, false) + url_loader_factory_getter, file_system_context, getter, download_id, + false) .release()); } @@ -221,8 +224,8 @@ GURL url = resource_request->url; std::string method = resource_request->method; ResourceRequestInfo::WebContentsGetter getter = - base::Bind(&GetWebContents, resource_request->origin_pid, - resource_request->render_frame_id, frame_tree_node_id); + base::Bind(&GetWebContents, ChildProcessHost::kInvalidUniqueID, + MSG_ROUTING_NONE, frame_tree_node_id); std::unique_ptr<ResourceDownloader> resource_downloader = ResourceDownloader::CreateWithURLLoader( download_manager, std::move(resource_request), getter, @@ -713,7 +716,6 @@ int render_view_route_id, int render_frame_route_id, bool do_not_prompt_for_login) { - LOG(ERROR) << "BeginDownloadRequest"; if (ResourceDispatcherHostImpl::Get()->is_shutdown()) return DOWNLOAD_INTERRUPT_REASON_USER_SHUTDOWN; @@ -978,8 +980,9 @@ download::InProgressCache* in_progress_cache = GetBrowserContext()->GetDownloadManagerDelegate()->GetInProgressCache(); if (in_progress_cache) { - in_progress_cache->AddOrReplaceEntry(download::DownloadEntry( - params.get()->guid(), params.get()->request_origin())); + in_progress_cache->AddOrReplaceEntry( + download::DownloadEntry(params->guid(), params->request_origin(), + ToDownloadSource(params->download_source()))); } if (base::FeatureList::IsEnabled(features::kNetworkService)) {
diff --git a/content/browser/download/download_stats.cc b/content/browser/download/download_stats.cc index dbb9a18..24d6481 100644 --- a/content/browser/download/download_stats.cc +++ b/content/browser/download/download_stats.cc
@@ -273,7 +273,7 @@ "Download.Counts", type, DOWNLOAD_COUNT_TYPES_LAST_ENTRY); } -void RecordDownloadSource(DownloadSource source) { +void RecordDownloadSource(DownloadTriggerSource source) { UMA_HISTOGRAM_ENUMERATION( "Download.Sources", source, DOWNLOAD_SOURCE_LAST_ENTRY); }
diff --git a/content/browser/download/download_stats.h b/content/browser/download/download_stats.h index 3aeb473..ca82af1 100644 --- a/content/browser/download/download_stats.h +++ b/content/browser/download/download_stats.h
@@ -123,7 +123,8 @@ DOWNLOAD_COUNT_TYPES_LAST_ENTRY }; -enum DownloadSource { +// TODO(xingliu): Deprecate this enum. +enum DownloadTriggerSource { // The download was initiated when the SavePackage system rejected // a Save Page As ... by returning false from // SavePackage::IsSaveableContents(). @@ -205,7 +206,7 @@ void RecordDownloadCount(DownloadCountTypes type); // Record initiation of a download from a specific source. -void RecordDownloadSource(DownloadSource source); +void RecordDownloadSource(DownloadTriggerSource source); // Record COMPLETED_COUNT and how long the download took. void RecordDownloadCompleted(const base::TimeTicks& start,
diff --git a/content/browser/download/download_utils.cc b/content/browser/download/download_utils.cc index da7bf3d..5f198aa0 100644 --- a/content/browser/download/download_utils.cc +++ b/content/browser/download/download_utils.cc
@@ -174,10 +174,8 @@ request->allow_download = true; request->is_main_frame = true; - if (params->render_process_host_id() >= 0) { - request->origin_pid = params->render_process_host_id(); + if (params->render_process_host_id() >= 0) request->render_frame_id = params->render_frame_host_routing_id(); - } bool has_upload_data = false; if (!params->post_body().empty()) { @@ -407,4 +405,40 @@ headers->response_code() == net::HTTP_PARTIAL_CONTENT); } +download::DownloadSource ToDownloadSource( + content::DownloadSource download_source) { + switch (download_source) { + case DownloadSource::UNKNOWN: + return download::DownloadSource::UNKNOWN; + case DownloadSource::NAVIGATION: + return download::DownloadSource::NAVIGATION; + case DownloadSource::DRAG_AND_DROP: + return download::DownloadSource::DRAG_AND_DROP; + case DownloadSource::MANUAL_RESUMPTION: + return download::DownloadSource::MANUAL_RESUMPTION; + case DownloadSource::AUTO_RESUMPTION: + return download::DownloadSource::AUTO_RESUMPTION; + case DownloadSource::FROM_RENDERER: + return download::DownloadSource::FROM_RENDERER; + case DownloadSource::EXTENSION_API: + return download::DownloadSource::EXTENSION_API; + case DownloadSource::EXTENSION_INSTALLER: + return download::DownloadSource::EXTENSION_INSTALLER; + case DownloadSource::PLUGIN: + return download::DownloadSource::PLUGIN; + case DownloadSource::PLUGIN_INSTALLER: + return download::DownloadSource::PLUGIN_INSTALLER; + case DownloadSource::INTERNAL_API: + return download::DownloadSource::INTERNAL_API; + case DownloadSource::SAVE_PACKAGE: + return download::DownloadSource::SAVE_PACKAGE; + case DownloadSource::OFFLINE_PAGE: + return download::DownloadSource::OFFLINE_PAGE; + case DownloadSource::COUNT: + break; + } + NOTREACHED(); + return download::DownloadSource::UNKNOWN; +} + } // namespace content
diff --git a/content/browser/download/download_utils.h b/content/browser/download/download_utils.h index b1cafe2..dd7856c 100644 --- a/content/browser/download/download_utils.h +++ b/content/browser/download/download_utils.h
@@ -5,7 +5,9 @@ #ifndef CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_UTILS_H_ #define CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_UTILS_H_ +#include "components/download/downloader/in_progress/download_source.h" #include "content/public/browser/download_interrupt_reasons.h" +#include "content/public/browser/download_source.h" #include "net/base/net_errors.h" #include "net/cert/cert_status_flags.h" #include "net/http/http_response_headers.h" @@ -48,6 +50,10 @@ const net::HttpResponseHeaders* headers, DownloadCreateInfo* create_info); +// Converts content::DownloadSource to download::DownloadSource. +CONTENT_EXPORT download::DownloadSource ToDownloadSource( + content::DownloadSource download_source); + } // namespace content #endif // CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_UTILS_H_
diff --git a/content/browser/download/resource_downloader.cc b/content/browser/download/resource_downloader.cc index df8e708..bcfb12e 100644 --- a/content/browser/download/resource_downloader.cc +++ b/content/browser/download/resource_downloader.cc
@@ -159,7 +159,8 @@ mojom::kURLLoadOptionSendSSLInfoWithResponse | mojom::kURLLoadOptionSniffMimeType, *(resource_request_.get()), url_loader_client_.get(), - download_url_parameters->GetNetworkTrafficAnnotation()); + download_url_parameters->GetNetworkTrafficAnnotation(), + base::ThreadTaskRunnerHandle::Get()); url_loader_->SetPriority(net::RequestPriority::IDLE, 0 /* intra_priority_value */); }
diff --git a/content/browser/frame_host/render_frame_host_impl.cc b/content/browser/frame_host/render_frame_host_impl.cc index 49575dc7..4b1ab48 100644 --- a/content/browser/frame_host/render_frame_host_impl.cc +++ b/content/browser/frame_host/render_frame_host_impl.cc
@@ -791,7 +791,7 @@ return remote_interfaces_.get(); } -AssociatedInterfaceProvider* +blink::AssociatedInterfaceProvider* RenderFrameHostImpl::GetRemoteAssociatedInterfaces() { if (!remote_associated_interfaces_) { mojom::AssociatedInterfaceProviderAssociatedPtr remote_interfaces; @@ -3636,7 +3636,7 @@ mojom::FrameHostAssociatedRequest request) { impl->frame_host_associated_binding_.Bind(std::move(request)); }; - static_cast<AssociatedInterfaceRegistry*>(associated_registry_.get()) + static_cast<blink::AssociatedInterfaceRegistry*>(associated_registry_.get()) ->AddInterface(base::Bind(make_binding, base::Unretained(this))); RegisterMojoInterfaces();
diff --git a/content/browser/frame_host/render_frame_host_impl.h b/content/browser/frame_host/render_frame_host_impl.h index bb0f716c..fdcaeef 100644 --- a/content/browser/frame_host/render_frame_host_impl.h +++ b/content/browser/frame_host/render_frame_host_impl.h
@@ -207,7 +207,7 @@ void SaveImageAt(int x, int y) override; RenderViewHost* GetRenderViewHost() override; service_manager::InterfaceProvider* GetRemoteInterfaces() override; - AssociatedInterfaceProvider* GetRemoteAssociatedInterfaces() override; + blink::AssociatedInterfaceProvider* GetRemoteAssociatedInterfaces() override; blink::mojom::PageVisibilityState GetVisibilityState() override; bool IsRenderFrameLive() override; bool IsCurrent() override;
diff --git a/content/browser/frame_host/render_frame_host_impl_browsertest.cc b/content/browser/frame_host/render_frame_host_impl_browsertest.cc index 6cd0e6f..40fa602a 100644 --- a/content/browser/frame_host/render_frame_host_impl_browsertest.cc +++ b/content/browser/frame_host/render_frame_host_impl_browsertest.cc
@@ -212,6 +212,7 @@ bool* did_suppress_message) override {} void RunBeforeUnloadDialog(WebContents* web_contents, + RenderFrameHost* render_frame_host, bool is_reload, DialogClosedCallback callback) override { callback_ = std::move(callback);
diff --git a/content/browser/gpu/browser_gpu_channel_host_factory.cc b/content/browser/gpu/browser_gpu_channel_host_factory.cc index 2c130f5..01e7fab 100644 --- a/content/browser/gpu/browser_gpu_channel_host_factory.cc +++ b/content/browser/gpu/browser_gpu_channel_host_factory.cc
@@ -29,6 +29,7 @@ #include "gpu/command_buffer/service/gpu_switches.h" #include "services/resource_coordinator/public/interfaces/memory_instrumentation/constants.mojom.h" #include "services/service_manager/runner/common/client_util.h" +#include "ui/base/ui_base_switches_util.h" namespace content { @@ -266,7 +267,7 @@ void BrowserGpuChannelHostFactory::EstablishGpuChannel( const gpu::GpuChannelEstablishedCallback& callback) { #if defined(USE_AURA) - DCHECK(!IsMusHostingViz()); + DCHECK(!switches::IsMusHostingViz()); #endif DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (gpu_channel_.get() && gpu_channel_->IsLost()) {
diff --git a/content/browser/gpu/gpu_process_host.cc b/content/browser/gpu/gpu_process_host.cc index 4858634..e31b60d6 100644 --- a/content/browser/gpu/gpu_process_host.cc +++ b/content/browser/gpu/gpu_process_host.cc
@@ -773,10 +773,6 @@ surface_id, base::Bind(&GpuProcessHost::OnDestroyingVideoSurfaceAck, weak_ptr_factory_.GetWeakPtr())); } - -void GpuProcessHost::DidSuccessfullyInitializeContext() { - gpu_recent_crash_count_ = 0; -} #endif void GpuProcessHost::OnChannelEstablished( @@ -887,6 +883,15 @@ RunRequestGPUInfoCallbacks(gpu_data_manager->GetGPUInfo()); } +void GpuProcessHost::DidCreateContextSuccessfully() { +#if defined(OS_ANDROID) + // Android may kill the GPU process to free memory, especially when the app + // is the background, so Android cannot have a hard limit on GPU starts. + // Reset crash count on Android when context creation succeeds. + gpu_recent_crash_count_ = 0; +#endif +} + void GpuProcessHost::DidCreateOffscreenContext(const GURL& url) { urls_with_live_offscreen_contexts_.insert(url); }
diff --git a/content/browser/gpu/gpu_process_host.h b/content/browser/gpu/gpu_process_host.h index 4927579d..379cf8b 100644 --- a/content/browser/gpu/gpu_process_host.h +++ b/content/browser/gpu/gpu_process_host.h
@@ -157,12 +157,6 @@ // Tells the GPU process that the given surface is being destroyed so that it // can stop using it. void SendDestroyingVideoSurface(int surface_id, const base::Closure& done_cb); - - // Android-only notification when a context is initialized. Because the gpu - // process can be killed arbitrarily on this OS, the host needs to always - // restart it. This signal is used to differentiate a repeatedly failing gpu - // process from one that was functional but killed. - void DidSuccessfullyInitializeContext(); #endif // What kind of GPU process, e.g. sandboxed or unsandboxed. @@ -202,6 +196,7 @@ void DidInitialize(const gpu::GPUInfo& gpu_info, const gpu::GpuFeatureInfo& gpu_feature_info) override; void DidFailInitialize() override; + void DidCreateContextSuccessfully() override; void DidCreateOffscreenContext(const GURL& url) override; void DidDestroyOffscreenContext(const GURL& url) override; void DidDestroyChannel(int32_t client_id) override;
diff --git a/content/browser/host_zoom_map_impl.cc b/content/browser/host_zoom_map_impl.cc index f4518184..96267b1 100644 --- a/content/browser/host_zoom_map_impl.cc +++ b/content/browser/host_zoom_map_impl.cc
@@ -128,7 +128,7 @@ HostZoomMapImpl::HostZoomMapImpl() : default_zoom_level_(0.0), store_last_modified_(false), - clock_(std::make_unique<base::DefaultClock>()) { + clock_(base::DefaultClock::GetInstance()) { DCHECK_CURRENTLY_ON(BrowserThread::UI); } @@ -561,8 +561,8 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); } -void HostZoomMapImpl::SetClockForTesting(std::unique_ptr<base::Clock> clock) { - clock_ = std::move(clock); +void HostZoomMapImpl::SetClockForTesting(base::Clock* clock) { + clock_ = clock; } } // namespace content
diff --git a/content/browser/host_zoom_map_impl.h b/content/browser/host_zoom_map_impl.h index e35249b..c3d813d 100644 --- a/content/browser/host_zoom_map_impl.h +++ b/content/browser/host_zoom_map_impl.h
@@ -95,7 +95,7 @@ void WillCloseRenderView(int render_process_id, int render_view_id); - void SetClockForTesting(std::unique_ptr<base::Clock> clock) override; + void SetClockForTesting(base::Clock* clock) override; private: struct ZoomLevel { @@ -151,7 +151,7 @@ bool store_last_modified_; - std::unique_ptr<base::Clock> clock_; + base::Clock* clock_; DISALLOW_COPY_AND_ASSIGN(HostZoomMapImpl); };
diff --git a/content/browser/host_zoom_map_impl_unittest.cc b/content/browser/host_zoom_map_impl_unittest.cc index c0d9aa21..843f88a 100644 --- a/content/browser/host_zoom_map_impl_unittest.cc +++ b/content/browser/host_zoom_map_impl_unittest.cc
@@ -93,16 +93,15 @@ host_zoom_map.SetStoreLastModified(true); base::Time now = base::Time::Now(); - auto test_clock = std::make_unique<base::SimpleTestClock>(); - base::SimpleTestClock* clock = test_clock.get(); - host_zoom_map.SetClockForTesting(std::move(test_clock)); + base::SimpleTestClock test_clock; + host_zoom_map.SetClockForTesting(&test_clock); - clock->SetNow(now); + test_clock.SetNow(now); host_zoom_map.SetZoomLevelForHost("zoomed.com", 1.5); host_zoom_map.SetZoomLevelForHost("zoomed2.com", 2.0); base::Time later = now + base::TimeDelta::FromSeconds(1); - clock->SetNow(later); + test_clock.SetNow(later); host_zoom_map.SetZoomLevelForHost("zoomed2.com", 2.5); host_zoom_map.SetZoomLevelForHost("zoomzoom.com", 3); host_zoom_map.SetZoomLevelForHostAndScheme("chrome", "login", 3); @@ -131,14 +130,13 @@ HostZoomMapImpl host_zoom_map; host_zoom_map.SetStoreLastModified(true); - auto test_clock = std::make_unique<base::SimpleTestClock>(); - base::SimpleTestClock* clock = test_clock.get(); - host_zoom_map.SetClockForTesting(std::move(test_clock)); + base::SimpleTestClock test_clock; + host_zoom_map.SetClockForTesting(&test_clock); base::Time now = base::Time::Now(); - clock->SetNow(now - base::TimeDelta::FromHours(3)); + test_clock.SetNow(now - base::TimeDelta::FromHours(3)); host_zoom_map.SetZoomLevelForHost("zoomzoom.com", 3.5); - clock->SetNow(now - base::TimeDelta::FromHours(1)); + test_clock.SetNow(now - base::TimeDelta::FromHours(1)); host_zoom_map.SetZoomLevelForHost("zoom.com", 1.5); EXPECT_EQ(2u, host_zoom_map.GetAllZoomLevels().size());
diff --git a/content/browser/host_zoom_map_observer.cc b/content/browser/host_zoom_map_observer.cc index 90f2695..beefe1e 100644 --- a/content/browser/host_zoom_map_observer.cc +++ b/content/browser/host_zoom_map_observer.cc
@@ -9,7 +9,7 @@ #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/storage_partition.h" -#include "content/public/common/associated_interface_provider.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" namespace content {
diff --git a/content/browser/indexed_db/indexed_db_backing_store_unittest.cc b/content/browser/indexed_db/indexed_db_backing_store_unittest.cc index 4cb3d30..652fc66 100644 --- a/content/browser/indexed_db/indexed_db_backing_store_unittest.cc +++ b/content/browser/indexed_db/indexed_db_backing_store_unittest.cc
@@ -194,8 +194,7 @@ class TestIDBFactory : public IndexedDBFactoryImpl { public: explicit TestIDBFactory(IndexedDBContextImpl* idb_context) - : IndexedDBFactoryImpl(idb_context, - std::make_unique<base::DefaultClock>()) {} + : IndexedDBFactoryImpl(idb_context, base::DefaultClock::GetInstance()) {} scoped_refptr<TestableIndexedDBBackingStore> OpenBackingStoreForTest( const Origin& origin,
diff --git a/content/browser/indexed_db/indexed_db_context_impl.cc b/content/browser/indexed_db/indexed_db_context_impl.cc index 3d2b18ec..e686284 100644 --- a/content/browser/indexed_db/indexed_db_context_impl.cc +++ b/content/browser/indexed_db/indexed_db_context_impl.cc
@@ -131,7 +131,7 @@ // detect when dbs are newly created. GetOriginSet(); factory_ = - new IndexedDBFactoryImpl(this, std::make_unique<base::DefaultClock>()); + new IndexedDBFactoryImpl(this, base::DefaultClock::GetInstance()); } return factory_.get(); }
diff --git a/content/browser/indexed_db/indexed_db_context_impl.h b/content/browser/indexed_db/indexed_db_context_impl.h index 554265c..11b6592 100644 --- a/content/browser/indexed_db/indexed_db_context_impl.h +++ b/content/browser/indexed_db/indexed_db_context_impl.h
@@ -47,6 +47,8 @@ FORCE_CLOSE_BACKING_STORE_FAILURE, FORCE_CLOSE_INTERNALS_PAGE, FORCE_CLOSE_COPY_ORIGIN, + // Append new values here and update IDBContextForcedCloseReason in + // enums.xml. FORCE_CLOSE_REASON_MAX };
diff --git a/content/browser/indexed_db/indexed_db_factory_impl.cc b/content/browser/indexed_db/indexed_db_factory_impl.cc index e58db4c..fa8fd12 100644 --- a/content/browser/indexed_db/indexed_db_factory_impl.cc +++ b/content/browser/indexed_db/indexed_db_factory_impl.cc
@@ -93,9 +93,9 @@ IndexedDBFactoryImpl::kMaxEarliestOriginSweepFromNow; IndexedDBFactoryImpl::IndexedDBFactoryImpl(IndexedDBContextImpl* context, - std::unique_ptr<base::Clock> clock) + base::Clock* clock) : context_(context), - clock_(std::move(clock)), + clock_(clock), earliest_sweep_(GenerateNextGlobalSweepTime(clock_->Now())) {} IndexedDBFactoryImpl::~IndexedDBFactoryImpl() {
diff --git a/content/browser/indexed_db/indexed_db_factory_impl.h b/content/browser/indexed_db/indexed_db_factory_impl.h index 743cbac..cb730b4 100644 --- a/content/browser/indexed_db/indexed_db_factory_impl.h +++ b/content/browser/indexed_db/indexed_db_factory_impl.h
@@ -45,8 +45,7 @@ static constexpr const base::TimeDelta kMaxEarliestOriginSweepFromNow = base::TimeDelta::FromDays(7); - IndexedDBFactoryImpl(IndexedDBContextImpl* context, - std::unique_ptr<base::Clock> clock); + IndexedDBFactoryImpl(IndexedDBContextImpl* context, base::Clock* clock); // content::IndexedDBFactory overrides: void ReleaseDatabase(const IndexedDBDatabase::Identifier& identifier, @@ -178,7 +177,7 @@ backing_stores_with_active_blobs_; std::set<url::Origin> backends_opened_since_boot_; - const std::unique_ptr<base::Clock> clock_; + base::Clock* clock_; base::Time earliest_sweep_; DISALLOW_COPY_AND_ASSIGN(IndexedDBFactoryImpl);
diff --git a/content/browser/indexed_db/indexed_db_factory_unittest.cc b/content/browser/indexed_db/indexed_db_factory_unittest.cc index 1fab978..73d2f19 100644 --- a/content/browser/indexed_db/indexed_db_factory_unittest.cc +++ b/content/browser/indexed_db/indexed_db_factory_unittest.cc
@@ -43,10 +43,9 @@ class MockIDBFactory : public IndexedDBFactoryImpl { public: explicit MockIDBFactory(IndexedDBContextImpl* context) - : MockIDBFactory(context, std::make_unique<base::DefaultClock>()) {} - MockIDBFactory(IndexedDBContextImpl* context, - std::unique_ptr<base::Clock> clock) - : IndexedDBFactoryImpl(context, std::move(clock)) {} + : MockIDBFactory(context, base::DefaultClock::GetInstance()) {} + MockIDBFactory(IndexedDBContextImpl* context, base::Clock* clock) + : IndexedDBFactoryImpl(context, clock) {} scoped_refptr<IndexedDBBackingStore> TestOpenBackingStore( const Origin& origin, const base::FilePath& data_directory) { @@ -186,12 +185,11 @@ FROM_HERE, base::BindOnce( [](IndexedDBContextImpl* context) { - base::SimpleTestClock* clock_ptr = new base::SimpleTestClock(); - clock_ptr->SetNow(base::Time::Now()); + base::SimpleTestClock clock; + clock.SetNow(base::Time::Now()); scoped_refptr<MockIDBFactory> factory = - base::MakeRefCounted<MockIDBFactory>( - context, base::WrapUnique(clock_ptr)); + base::MakeRefCounted<MockIDBFactory>(context, &clock); const Origin origin = Origin::Create(GURL("http://localhost:81")); @@ -223,8 +221,7 @@ EXPECT_FALSE(store_ptr->close_timer()->IsRunning()); // Move the clock to start the next sweep. - clock_ptr->Advance( - IndexedDBFactoryImpl::kMaxEarliestGlobalSweepFromNow); + clock.Advance(IndexedDBFactoryImpl::kMaxEarliestGlobalSweepFromNow); factory->TestReleaseBackingStore(store_ptr, false); // Sweep should NOT be occurring. @@ -247,12 +244,11 @@ FROM_HERE, base::BindOnce( [](IndexedDBContextImpl* context) { - base::SimpleTestClock* clock_ptr = new base::SimpleTestClock(); - clock_ptr->SetNow(base::Time::Now()); + base::SimpleTestClock clock; + clock.SetNow(base::Time::Now()); scoped_refptr<MockIDBFactory> factory = - base::MakeRefCounted<MockIDBFactory>( - context, base::WrapUnique(clock_ptr)); + base::MakeRefCounted<MockIDBFactory>(context, &clock); const Origin origin = Origin::Create(GURL("http://localhost:81")); @@ -284,8 +280,7 @@ EXPECT_FALSE(store_ptr->close_timer()->IsRunning()); // Move the clock to start the next sweep. - clock_ptr->Advance( - IndexedDBFactoryImpl::kMaxEarliestGlobalSweepFromNow); + clock.Advance(IndexedDBFactoryImpl::kMaxEarliestGlobalSweepFromNow); factory->TestReleaseBackingStore(store_ptr, false); // Sweep should be occuring. @@ -301,8 +296,7 @@ // Move clock forward to trigger next sweep, but origin has longer // sweep minimum, so nothing happens. - clock_ptr->Advance( - IndexedDBFactoryImpl::kMaxEarliestGlobalSweepFromNow); + clock.Advance(IndexedDBFactoryImpl::kMaxEarliestGlobalSweepFromNow); factory->TestReleaseBackingStore(store_ptr, false); EXPECT_TRUE(store_ptr->close_timer()->IsRunning()); @@ -311,8 +305,7 @@ // Reset, and move clock forward so the origin should allow a sweep. factory->TestOpenBackingStore(origin, context->data_path()); EXPECT_EQ(nullptr, store_ptr->pre_close_task_queue()); - clock_ptr->Advance( - IndexedDBFactoryImpl::kMaxEarliestOriginSweepFromNow); + clock.Advance(IndexedDBFactoryImpl::kMaxEarliestOriginSweepFromNow); factory->TestReleaseBackingStore(store_ptr, false); // Sweep should be occuring. @@ -411,7 +404,7 @@ class DiskFullFactory : public IndexedDBFactoryImpl { public: explicit DiskFullFactory(IndexedDBContextImpl* context) - : IndexedDBFactoryImpl(context, std::make_unique<base::DefaultClock>()) {} + : IndexedDBFactoryImpl(context, base::DefaultClock::GetInstance()) {} private: ~DiskFullFactory() override {}
diff --git a/content/browser/loader/async_resource_handler.cc b/content/browser/loader/async_resource_handler.cc index 5316de1..aeea9dc4 100644 --- a/content/browser/loader/async_resource_handler.cc +++ b/content/browser/loader/async_resource_handler.cc
@@ -285,8 +285,7 @@ return; } filter->Send(new ResourceMsg_SetDataBuffer( - GetRequestID(), handle, buffer_->GetSharedMemory().mapped_size(), - filter->peer_pid())); + GetRequestID(), handle, buffer_->GetSharedMemory().mapped_size())); sent_data_buffer_msg_ = true; }
diff --git a/content/browser/loader/navigation_url_loader_network_service.cc b/content/browser/loader/navigation_url_loader_network_service.cc index cd7121a..0a0e1874 100644 --- a/content/browser/loader/navigation_url_loader_network_service.cc +++ b/content/browser/loader/navigation_url_loader_network_service.cc
@@ -175,7 +175,8 @@ GetContentClient()->browser()->CreateURLLoaderThrottles( web_contents_getter_), 0 /* routing_id */, 0 /* request_id? */, mojom::kURLLoadOptionNone, - *resource_request_, this, kNavigationUrlLoaderTrafficAnnotation); + *resource_request_, this, kNavigationUrlLoaderTrafficAnnotation, + base::ThreadTaskRunnerHandle::Get()); return; } @@ -239,7 +240,8 @@ GetContentClient()->browser()->CreateURLLoaderThrottles( web_contents_getter_), frame_tree_node_id_, *resource_request_, this, - kNavigationUrlLoaderTrafficAnnotation); + kNavigationUrlLoaderTrafficAnnotation, + base::ThreadTaskRunnerHandle::Get()); subresource_loader_params_ = handler->MaybeCreateSubresourceLoaderParams(); @@ -313,7 +315,8 @@ GetContentClient()->browser()->CreateURLLoaderThrottles( web_contents_getter_), frame_tree_node_id_, 0 /* request_id? */, options, *resource_request_, - this, kNavigationUrlLoaderTrafficAnnotation); + this, kNavigationUrlLoaderTrafficAnnotation, + base::ThreadTaskRunnerHandle::Get()); } void FollowRedirect() {
diff --git a/content/browser/loader/resource_dispatcher_host_impl.cc b/content/browser/loader/resource_dispatcher_host_impl.cc index a48bcc6..3b7bb57d 100644 --- a/content/browser/loader/resource_dispatcher_host_impl.cc +++ b/content/browser/loader/resource_dispatcher_host_impl.cc
@@ -65,8 +65,6 @@ #include "content/browser/loader/upload_data_stream_builder.h" #include "content/browser/loader/wake_lock_resource_throttle.h" #include "content/browser/resource_context_impl.h" -#include "content/browser/service_worker/foreign_fetch_request_handler.h" -#include "content/browser/service_worker/link_header_support.h" #include "content/browser/service_worker/service_worker_context_wrapper.h" #include "content/browser/service_worker/service_worker_navigation_handle_core.h" #include "content/browser/service_worker/service_worker_request_handler.h" @@ -77,7 +75,10 @@ #include "content/common/resource_messages.h" #include "content/common/site_isolation_policy.h" #include "content/common/view_messages.h" +#include "content/public/browser/browser_child_process_host.h" #include "content/public/browser/browser_thread.h" +#include "content/public/browser/child_process_data.h" +#include "content/public/browser/content_browser_client.h" #include "content/public/browser/global_request_id.h" #include "content/public/browser/navigation_ui_data.h" #include "content/public/browser/plugin_service.h" @@ -87,6 +88,8 @@ #include "content/public/browser/stream_handle.h" #include "content/public/browser/stream_info.h" #include "content/public/common/browser_side_navigation_policy.h" +#include "content/public/common/child_process_host.h" +#include "content/public/common/content_client.h" #include "content/public/common/content_features.h" #include "content/public/common/origin_util.h" #include "content/public/common/resource_request.h" @@ -249,6 +252,32 @@ filter->Send(sync_result.release()); } +bool ValidatePluginChildId(int plugin_child_id) { + if (plugin_child_id == ChildProcessHost::kInvalidUniqueID) + return true; + +#if BUILDFLAG(ENABLE_PLUGINS) + // TODO(nick): These checks could be stricter, since they enforce only that + // |plugin_child_id| is a valid plugin process, and not that it has a plugin + // instance owned by the renderer process making the resource request. Fix + // this by eliminating |plugin_child_id| altogether, and stop proxying plugin + // URL requests through the renderer (https://crbug.com/778711). + auto* plugin_host = BrowserChildProcessHost::FromID(plugin_child_id); + if (plugin_host) { + int process_type = plugin_host->GetData().process_type; + if (process_type == PROCESS_TYPE_PPAPI_PLUGIN) { + return true; + } else if (process_type >= PROCESS_TYPE_CONTENT_END) { + if (GetContentClient()->browser()->GetExternalBrowserPpapiHost( + plugin_child_id) != nullptr) { + return true; + } + } + } +#endif + return false; +} + // Used to log the cache flags for back-forward navigation requests. // Because this enum is used to back a histogrma, DO NOT REMOVE OR RENAME VALUES // in this enum. Instead, add a new one at the end. @@ -615,8 +644,6 @@ info->GetChildID(), info->GetRouteID()); } - ProcessRequestForLinkHeaders(request); - if (delegate_) delegate_->OnResponseStarted(request, info->GetContext(), response); @@ -880,9 +907,8 @@ // ResourceHandlers should always get state related to the request from the // ResourceRequestInfo rather than caching it locally. This lets us update // the info object when a transfer occurs. - info->UpdateForTransfer(route_id, request_data.render_frame_id, - request_data.origin_pid, request_id, requester_info, - std::move(mojo_request), + info->UpdateForTransfer(route_id, request_data.render_frame_id, request_id, + requester_info, std::move(mojo_request), std::move(url_loader_client)); // Update maps that used the old IDs, if necessary. Some transfers in tests @@ -1311,7 +1337,7 @@ ResourceRequestInfoImpl* extra_info = new ResourceRequestInfoImpl( requester_info, route_id, -1, // frame_tree_node_id - request_data.origin_pid, request_id, request_data.render_frame_id, + request_data.plugin_child_id, request_id, request_data.render_frame_id, request_data.is_main_frame, request_data.resource_type, request_data.transition_type, request_data.should_replace_current_entry, false, // is download @@ -1360,16 +1386,6 @@ request_data.fetch_request_context_type, request_data.fetch_frame_type, request_data.request_body); - ForeignFetchRequestHandler::InitializeHandler( - new_request.get(), requester_info->service_worker_context(), - blob_context, child_id, request_data.service_worker_provider_id, - service_worker_mode, request_data.fetch_request_mode, - request_data.fetch_credentials_mode, request_data.fetch_redirect_mode, - request_data.fetch_integrity, request_data.keepalive, - request_data.resource_type, request_data.fetch_request_context_type, - request_data.fetch_frame_type, request_data.request_body, - request_data.initiated_in_secure_context); - // Have the appcache associate its extra info with the request. AppCacheInterceptor::SetExtraRequestInfo( new_request.get(), requester_info->appcache_service(), child_id, @@ -1656,8 +1672,9 @@ return new ResourceRequestInfoImpl( ResourceRequesterInfo::CreateForDownloadOrPageSave(child_id), render_view_route_id, - -1, // frame_tree_node_id - 0, MakeRequestID(), render_frame_route_id, + -1, // frame_tree_node_id + ChildProcessHost::kInvalidUniqueID, // plugin_child_id + MakeRequestID(), render_frame_route_id, false, // is_main_frame RESOURCE_TYPE_SUB_RESOURCE, ui::PAGE_TRANSITION_LINK, false, // should_replace_current_entry @@ -2075,7 +2092,7 @@ : scoped_refptr<ServiceWorkerContextWrapper>()), -1, // route_id info.frame_tree_node_id, - -1, // request_data.origin_pid, + ChildProcessHost::kInvalidUniqueID, // plugin_child_id MakeRequestID(), -1, // request_data.render_frame_id, info.is_main_frame, resource_type, info.common_params.transition, @@ -2676,6 +2693,14 @@ return false; } + // Check that |plugin_child_id|, if present, is actually a plugin process. + if (!ValidatePluginChildId(request_data.plugin_child_id)) { + NOTREACHED() << "Invalid request_data.plugin_child_id: " + << request_data.plugin_child_id << " (" << child_id << ", " + << request_data.render_frame_id << ")"; + return false; + } + return true; }
diff --git a/content/browser/loader/resource_dispatcher_host_unittest.cc b/content/browser/loader/resource_dispatcher_host_unittest.cc index 1bab86d..add2be7 100644 --- a/content/browser/loader/resource_dispatcher_host_unittest.cc +++ b/content/browser/loader/resource_dispatcher_host_unittest.cc
@@ -172,7 +172,7 @@ url::Origin::Create(url); // ensure initiator is set request.referrer_policy = blink::kWebReferrerPolicyDefault; request.load_flags = 0; - request.origin_pid = 0; + request.plugin_child_id = -1; request.resource_type = type; request.request_context = 0; request.appcache_host_id = kAppCacheNoHostId; @@ -1197,7 +1197,8 @@ const GURL& url, ResourceType type) { ResourceRequest request = CreateResourceRequest("GET", type, url); - request.origin_pid = web_contents_->GetMainFrame()->GetProcess()->GetID(); + DCHECK_EQ(web_contents_filter_->child_id(), + web_contents_->GetMainFrame()->GetProcess()->GetID()); request.render_frame_id = web_contents_->GetMainFrame()->GetRoutingID(); ResourceHostMsg_RequestResource msg( web_contents_->GetRenderViewHost()->GetRoutingID(), request_id, request,
diff --git a/content/browser/loader/resource_request_info_impl.cc b/content/browser/loader/resource_request_info_impl.cc index 2188236..d875a4f6 100644 --- a/content/browser/loader/resource_request_info_impl.cc +++ b/content/browser/loader/resource_request_info_impl.cc
@@ -61,25 +61,25 @@ ResourceRequestInfoImpl* info = new ResourceRequestInfoImpl( ResourceRequesterInfo::CreateForRendererTesting( - render_process_id), // resource_requester_info - render_view_id, // route_id - -1, // frame_tree_node_id - 0, // origin_pid - 0, // request_id - render_frame_id, // render_frame_id - is_main_frame, // is_main_frame - resource_type, // resource_type - ui::PAGE_TRANSITION_LINK, // transition_type - false, // should_replace_current_entry - false, // is_download - false, // is_stream - allow_download, // allow_download - false, // has_user_gesture - false, // enable load timing - request->has_upload(), // enable upload progress - false, // do_not_prompt_for_login - false, // keep_alive - blink::kWebReferrerPolicyDefault, // referrer_policy + render_process_id), // resource_requester_info + render_view_id, // route_id + -1, // frame_tree_node_id + ChildProcessHost::kInvalidUniqueID, // plugin_child_id + 0, // request_id + render_frame_id, // render_frame_id + is_main_frame, // is_main_frame + resource_type, // resource_type + ui::PAGE_TRANSITION_LINK, // transition_type + false, // should_replace_current_entry + false, // is_download + false, // is_stream + allow_download, // allow_download + false, // has_user_gesture + false, // enable load timing + request->has_upload(), // enable upload progress + false, // do_not_prompt_for_login + false, // keep_alive + blink::kWebReferrerPolicyDefault, // referrer_policy blink::mojom::PageVisibilityState::kVisible, // visibility_state context, // context false, // report_raw_headers @@ -132,7 +132,7 @@ scoped_refptr<ResourceRequesterInfo> requester_info, int route_id, int frame_tree_node_id, - int origin_pid, + int plugin_child_id, int request_id, int render_frame_id, bool is_main_frame, @@ -159,7 +159,7 @@ requester_info_(std::move(requester_info)), route_id_(route_id), frame_tree_node_id_(frame_tree_node_id), - origin_pid_(origin_pid), + plugin_child_id_(plugin_child_id), request_id_(request_id), render_frame_id_(render_frame_id), is_main_frame_(is_main_frame), @@ -246,8 +246,8 @@ return GlobalRequestID(GetChildID(), request_id_); } -int ResourceRequestInfoImpl::GetOriginPID() const { - return origin_pid_; +int ResourceRequestInfoImpl::GetPluginChildID() const { + return plugin_child_id_; } int ResourceRequestInfoImpl::GetRenderFrameID() const { @@ -342,14 +342,13 @@ void ResourceRequestInfoImpl::UpdateForTransfer( int route_id, int render_frame_id, - int origin_pid, int request_id, ResourceRequesterInfo* requester_info, mojom::URLLoaderRequest url_loader_request, mojom::URLLoaderClientPtr url_loader_client) { route_id_ = route_id; render_frame_id_ = render_frame_id; - origin_pid_ = origin_pid; + plugin_child_id_ = ChildProcessHost::kInvalidUniqueID; request_id_ = request_id; requester_info_ = requester_info;
diff --git a/content/browser/loader/resource_request_info_impl.h b/content/browser/loader/resource_request_info_impl.h index 1bba4b3..d21c5ee 100644 --- a/content/browser/loader/resource_request_info_impl.h +++ b/content/browser/loader/resource_request_info_impl.h
@@ -50,7 +50,7 @@ scoped_refptr<ResourceRequesterInfo> requester_info, int route_id, int frame_tree_node_id, - int origin_pid, + int plugin_child_id, int request_id, int render_frame_id, bool is_main_frame, @@ -82,7 +82,7 @@ int GetChildID() const override; int GetRouteID() const override; GlobalRequestID GetGlobalRequestID() const override; - int GetOriginPID() const override; + int GetPluginChildID() const override; int GetRenderFrameID() const override; int GetFrameTreeNodeId() const override; bool IsMainFrame() const override; @@ -122,7 +122,6 @@ // does not need to be updated. void UpdateForTransfer(int route_id, int render_frame_id, - int origin_pid, int request_id, ResourceRequesterInfo* requester_info, mojom::URLLoaderRequest url_loader_request, @@ -214,7 +213,7 @@ scoped_refptr<ResourceRequesterInfo> requester_info_; int route_id_; const int frame_tree_node_id_; - int origin_pid_; + int plugin_child_id_; int request_id_; int render_frame_id_; bool is_main_frame_;
diff --git a/content/browser/manifest/manifest_browsertest.cc b/content/browser/manifest/manifest_browsertest.cc index d6864db5..990943f 100644 --- a/content/browser/manifest/manifest_browsertest.cc +++ b/content/browser/manifest/manifest_browsertest.cc
@@ -12,7 +12,6 @@ #include "base/strings/stringprintf.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" -#include "content/public/common/associated_interface_provider.h" #include "content/public/common/content_switches.h" #include "content/public/common/manifest.h" #include "content/public/test/browser_test_utils.h" @@ -23,6 +22,7 @@ #include "net/test/embedded_test_server/embedded_test_server.h" #include "net/test/embedded_test_server/http_request.h" #include "net/test/embedded_test_server/http_response.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" #include "third_party/WebKit/public/platform/modules/manifest/manifest_manager.mojom.h" namespace content {
diff --git a/content/browser/manifest/manifest_manager_host.cc b/content/browser/manifest/manifest_manager_host.cc index e22d2ea..31fa59f5 100644 --- a/content/browser/manifest/manifest_manager_host.cc +++ b/content/browser/manifest/manifest_manager_host.cc
@@ -12,6 +12,7 @@ #include "content/public/browser/web_contents.h" #include "content/public/common/manifest.h" #include "services/service_manager/public/cpp/interface_provider.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" namespace content {
diff --git a/content/browser/media/audible_metrics.cc b/content/browser/media/audible_metrics.cc index aef60623..b02977c 100644 --- a/content/browser/media/audible_metrics.cc +++ b/content/browser/media/audible_metrics.cc
@@ -13,8 +13,7 @@ AudibleMetrics::AudibleMetrics() : max_concurrent_audible_web_contents_in_session_(0), - clock_(new base::DefaultTickClock()) { -} + clock_(base::DefaultTickClock::GetInstance()) {} AudibleMetrics::~AudibleMetrics() { } @@ -32,9 +31,8 @@ RemoveAudibleWebContents(web_contents); } -void AudibleMetrics::SetClockForTest( - std::unique_ptr<base::TickClock> test_clock) { - clock_ = std::move(test_clock); +void AudibleMetrics::SetClockForTest(base::TickClock* test_clock) { + clock_ = test_clock; } void AudibleMetrics::AddAudibleWebContents(const WebContents* web_contents) {
diff --git a/content/browser/media/audible_metrics.h b/content/browser/media/audible_metrics.h index 6ff9351..3c90da94 100644 --- a/content/browser/media/audible_metrics.h +++ b/content/browser/media/audible_metrics.h
@@ -29,7 +29,7 @@ void UpdateAudibleWebContentsState(const WebContents* web_contents, bool audible); - void SetClockForTest(std::unique_ptr<base::TickClock> test_clock); + void SetClockForTest(base::TickClock* test_clock); private: void AddAudibleWebContents(const WebContents* web_contents); @@ -37,7 +37,7 @@ base::TimeTicks concurrent_web_contents_start_time_; size_t max_concurrent_audible_web_contents_in_session_; - std::unique_ptr<base::TickClock> clock_; + base::TickClock* clock_; std::set<const WebContents*> audible_web_contents_;
diff --git a/content/browser/media/audible_metrics_unittest.cc b/content/browser/media/audible_metrics_unittest.cc index 6989dc7e..d122e317 100644 --- a/content/browser/media/audible_metrics_unittest.cc +++ b/content/browser/media/audible_metrics_unittest.cc
@@ -31,19 +31,13 @@ AudibleMetricsTest() = default; void SetUp() override { - clock_ = new base::SimpleTestTickClock(); // Set the clock to a value different than 0 so the time it gives is // recognized as initialized. - clock_->Advance(base::TimeDelta::FromMilliseconds(1)); - audible_metrics_.SetClockForTest( - std::unique_ptr<base::SimpleTestTickClock>(clock_)); + clock_.Advance(base::TimeDelta::FromMilliseconds(1)); + audible_metrics_.SetClockForTest(&clock_); } - void TearDown() override { - clock_ = nullptr; - } - - base::SimpleTestTickClock* clock() { return clock_; } + base::SimpleTestTickClock* clock() { return &clock_; } AudibleMetrics* audible_metrics() { return &audible_metrics_; @@ -59,7 +53,7 @@ } private: - base::SimpleTestTickClock* clock_ = nullptr; + base::SimpleTestTickClock clock_; AudibleMetrics audible_metrics_; base::HistogramTester histogram_tester_; base::UserActionTester user_action_tester_;
diff --git a/content/browser/media/audio_stream_monitor.cc b/content/browser/media/audio_stream_monitor.cc index 427d7dd..6d4bbdc2 100644 --- a/content/browser/media/audio_stream_monitor.cc +++ b/content/browser/media/audio_stream_monitor.cc
@@ -51,7 +51,7 @@ AudioStreamMonitor::AudioStreamMonitor(WebContents* contents) : web_contents_(contents), - clock_(&default_tick_clock_), + clock_(base::DefaultTickClock::GetInstance()), was_recently_audible_(false), is_audible_(false) { DCHECK(web_contents_);
diff --git a/content/browser/media/audio_stream_monitor.h b/content/browser/media/audio_stream_monitor.h index a36d77e..0e8da39 100644 --- a/content/browser/media/audio_stream_monitor.h +++ b/content/browser/media/audio_stream_monitor.h
@@ -142,9 +142,8 @@ // pointer should be valid for the lifetime of AudioStreamMonitor. WebContents* const web_contents_; - // Note: |clock_| is always |&default_tick_clock_|, except during unit + // Note: |clock_| is always a DefaultTickClock, except during unit // testing. - base::DefaultTickClock default_tick_clock_; base::TickClock* const clock_; // Confirms single-threaded access in debug builds.
diff --git a/content/browser/media/capture/cursor_renderer.cc b/content/browser/media/capture/cursor_renderer.cc index f59fc25..b698f1e 100644 --- a/content/browser/media/capture/cursor_renderer.cc +++ b/content/browser/media/capture/cursor_renderer.cc
@@ -29,7 +29,7 @@ CursorDisplaySetting cursor_display_setting) : captured_view_(view), cursor_display_setting_(cursor_display_setting), - tick_clock_(&default_tick_clock_), + tick_clock_(base::DefaultTickClock::GetInstance()), weak_factory_(this) { Clear(); }
diff --git a/content/browser/media/capture/cursor_renderer.h b/content/browser/media/capture/cursor_renderer.h index a26e043..c658e33b 100644 --- a/content/browser/media/capture/cursor_renderer.h +++ b/content/browser/media/capture/cursor_renderer.h
@@ -109,7 +109,6 @@ CursorDisplaySetting cursor_display_setting_; // Allows tests to replace the clock. - base::DefaultTickClock default_tick_clock_; base::TickClock* tick_clock_; base::WeakPtrFactory<CursorRenderer> weak_factory_;
diff --git a/content/browser/media/session/media_session_impl_browsertest.cc b/content/browser/media/session/media_session_impl_browsertest.cc index e8f27ad..7ffbda71 100644 --- a/content/browser/media/session/media_session_impl_browsertest.cc +++ b/content/browser/media/session/media_session_impl_browsertest.cc
@@ -1281,14 +1281,13 @@ base::HistogramTester tester; MediaSessionUmaHelper* media_session_uma_helper = GetMediaSessionUMAHelper(); - base::SimpleTestTickClock* clock = new base::SimpleTestTickClock(); - clock->SetNowTicks(base::TimeTicks::Now()); - media_session_uma_helper->SetClockForTest( - std::unique_ptr<base::SimpleTestTickClock>(clock)); + base::SimpleTestTickClock clock; + clock.SetNowTicks(base::TimeTicks::Now()); + media_session_uma_helper->SetClockForTest(&clock); StartNewPlayer(player_observer.get(), media::MediaContentType::Persistent); - clock->Advance(base::TimeDelta::FromMilliseconds(1000)); + clock.Advance(base::TimeDelta::FromMilliseconds(1000)); media_session_->Stop(MediaSession::SuspendType::UI); std::unique_ptr<base::HistogramSamples> samples( @@ -1303,20 +1302,19 @@ base::HistogramTester tester; MediaSessionUmaHelper* media_session_uma_helper = GetMediaSessionUMAHelper(); - base::SimpleTestTickClock* clock = new base::SimpleTestTickClock(); - clock->SetNowTicks(base::TimeTicks::Now()); - media_session_uma_helper->SetClockForTest( - std::unique_ptr<base::SimpleTestTickClock>(clock)); + base::SimpleTestTickClock clock; + clock.SetNowTicks(base::TimeTicks::Now()); + media_session_uma_helper->SetClockForTest(&clock); StartNewPlayer(player_observer.get(), media::MediaContentType::Persistent); - clock->Advance(base::TimeDelta::FromMilliseconds(1000)); + clock.Advance(base::TimeDelta::FromMilliseconds(1000)); UISuspend(); - clock->Advance(base::TimeDelta::FromMilliseconds(2000)); + clock.Advance(base::TimeDelta::FromMilliseconds(2000)); UIResume(); - clock->Advance(base::TimeDelta::FromMilliseconds(1000)); + clock.Advance(base::TimeDelta::FromMilliseconds(1000)); media_session_->Stop(MediaSession::SuspendType::UI); std::unique_ptr<base::HistogramSamples> samples( @@ -1331,20 +1329,19 @@ base::HistogramTester tester; MediaSessionUmaHelper* media_session_uma_helper = GetMediaSessionUMAHelper(); - base::SimpleTestTickClock* clock = new base::SimpleTestTickClock(); - clock->SetNowTicks(base::TimeTicks::Now()); - media_session_uma_helper->SetClockForTest( - std::unique_ptr<base::SimpleTestTickClock>(clock)); + base::SimpleTestTickClock clock; + clock.SetNowTicks(base::TimeTicks::Now()); + media_session_uma_helper->SetClockForTest(&clock); StartNewPlayer(player_observer.get(), media::MediaContentType::Persistent); - clock->Advance(base::TimeDelta::FromMilliseconds(1000)); + clock.Advance(base::TimeDelta::FromMilliseconds(1000)); SystemSuspend(true); - clock->Advance(base::TimeDelta::FromMilliseconds(2000)); + clock.Advance(base::TimeDelta::FromMilliseconds(2000)); SystemResume(); - clock->Advance(base::TimeDelta::FromMilliseconds(1000)); + clock.Advance(base::TimeDelta::FromMilliseconds(1000)); media_session_->Stop(MediaSession::SuspendType::UI); std::unique_ptr<base::HistogramSamples> samples( @@ -1359,13 +1356,12 @@ base::HistogramTester tester; MediaSessionUmaHelper* media_session_uma_helper = GetMediaSessionUMAHelper(); - base::SimpleTestTickClock* clock = new base::SimpleTestTickClock(); - clock->SetNowTicks(base::TimeTicks::Now()); - media_session_uma_helper->SetClockForTest( - std::unique_ptr<base::SimpleTestTickClock>(clock)); + base::SimpleTestTickClock clock; + clock.SetNowTicks(base::TimeTicks::Now()); + media_session_uma_helper->SetClockForTest(&clock); StartNewPlayer(player_observer.get(), media::MediaContentType::Persistent); - clock->Advance(base::TimeDelta::FromMilliseconds(500)); + clock.Advance(base::TimeDelta::FromMilliseconds(500)); SystemSuspend(true); { @@ -1375,7 +1371,7 @@ } SystemResume(); - clock->Advance(base::TimeDelta::FromMilliseconds(5000)); + clock.Advance(base::TimeDelta::FromMilliseconds(5000)); UISuspend(); { @@ -1391,18 +1387,17 @@ base::HistogramTester tester; MediaSessionUmaHelper* media_session_uma_helper = GetMediaSessionUMAHelper(); - base::SimpleTestTickClock* clock = new base::SimpleTestTickClock(); - clock->SetNowTicks(base::TimeTicks::Now()); - media_session_uma_helper->SetClockForTest( - std::unique_ptr<base::SimpleTestTickClock>(clock)); + base::SimpleTestTickClock clock; + clock.SetNowTicks(base::TimeTicks::Now()); + media_session_uma_helper->SetClockForTest(&clock); StartNewPlayer(player_observer.get(), media::MediaContentType::Persistent); - clock->Advance(base::TimeDelta::FromMilliseconds(500)); + clock.Advance(base::TimeDelta::FromMilliseconds(500)); SystemSuspend(true); media_session_->Stop(MediaSession::SuspendType::UI); StartNewPlayer(player_observer.get(), media::MediaContentType::Persistent); - clock->Advance(base::TimeDelta::FromMilliseconds(5000)); + clock.Advance(base::TimeDelta::FromMilliseconds(5000)); SystemResume(); media_session_->Stop(MediaSession::SuspendType::UI); @@ -1419,17 +1414,16 @@ base::HistogramTester tester; MediaSessionUmaHelper* media_session_uma_helper = GetMediaSessionUMAHelper(); - base::SimpleTestTickClock* clock = new base::SimpleTestTickClock(); - clock->SetNowTicks(base::TimeTicks::Now()); - media_session_uma_helper->SetClockForTest( - std::unique_ptr<base::SimpleTestTickClock>(clock)); + base::SimpleTestTickClock clock; + clock.SetNowTicks(base::TimeTicks::Now()); + media_session_uma_helper->SetClockForTest(&clock); StartNewPlayer(player_observer.get(), media::MediaContentType::Persistent); - clock->Advance(base::TimeDelta::FromMilliseconds(10000)); + clock.Advance(base::TimeDelta::FromMilliseconds(10000)); RemovePlayer(player_observer.get(), 0); StartNewPlayer(player_observer.get(), media::MediaContentType::Persistent); - clock->Advance(base::TimeDelta::FromMilliseconds(1000)); + clock.Advance(base::TimeDelta::FromMilliseconds(1000)); media_session_->Stop(MediaSession::SuspendType::UI); std::unique_ptr<base::HistogramSamples> samples(
diff --git a/content/browser/media/session/media_session_uma_helper.cc b/content/browser/media/session/media_session_uma_helper.cc index d8f825b..10073466 100644 --- a/content/browser/media/session/media_session_uma_helper.cc +++ b/content/browser/media/session/media_session_uma_helper.cc
@@ -15,8 +15,7 @@ using HistogramBase = base::HistogramBase; MediaSessionUmaHelper::MediaSessionUmaHelper() - : clock_(new base::DefaultTickClock()) -{} + : clock_(base::DefaultTickClock::GetInstance()) {} MediaSessionUmaHelper::~MediaSessionUmaHelper() {} @@ -66,9 +65,8 @@ total_active_time_ = base::TimeDelta(); } -void MediaSessionUmaHelper::SetClockForTest( - std::unique_ptr<base::TickClock> testing_clock) { - clock_ = std::move(testing_clock); +void MediaSessionUmaHelper::SetClockForTest(base::TickClock* testing_clock) { + clock_ = testing_clock; } } // namespace content
diff --git a/content/browser/media/session/media_session_uma_helper.h b/content/browser/media/session/media_session_uma_helper.h index 78f8a30..bd928c3 100644 --- a/content/browser/media/session/media_session_uma_helper.h +++ b/content/browser/media/session/media_session_uma_helper.h
@@ -58,12 +58,12 @@ void OnSessionSuspended(); void OnSessionInactive(); - void SetClockForTest(std::unique_ptr<base::TickClock> testing_clock); + void SetClockForTest(base::TickClock* testing_clock); private: base::TimeDelta total_active_time_; base::TimeTicks current_active_time_; - std::unique_ptr<base::TickClock> clock_; + base::TickClock* clock_; }; } // namespace content
diff --git a/content/browser/media/session/media_session_uma_helper_unittest.cc b/content/browser/media/session/media_session_uma_helper_unittest.cc index c0931d2..4b6fc027 100644 --- a/content/browser/media/session/media_session_uma_helper_unittest.cc +++ b/content/browser/media/session/media_session_uma_helper_unittest.cc
@@ -21,17 +21,11 @@ MediaSessionUmaHelperTest() = default; void SetUp() override { - clock_ = new base::SimpleTestTickClock(); - clock_->SetNowTicks(base::TimeTicks::Now()); - media_session_uma_helper_.SetClockForTest( - std::unique_ptr<base::SimpleTestTickClock>(clock_)); + clock_.SetNowTicks(base::TimeTicks::Now()); + media_session_uma_helper_.SetClockForTest(&clock_); } - void TearDown() override { - clock_ = nullptr; - } - - base::SimpleTestTickClock* clock() { return clock_; } + base::SimpleTestTickClock* clock() { return &clock_; } MediaSessionUmaHelper& media_session_uma_helper() { return media_session_uma_helper_; @@ -43,7 +37,7 @@ } private: - base::SimpleTestTickClock* clock_ = nullptr; + base::SimpleTestTickClock clock_; MediaSessionUmaHelper media_session_uma_helper_; base::HistogramTester histogram_tester_; };
diff --git a/content/browser/memory/memory_coordinator_impl.cc b/content/browser/memory/memory_coordinator_impl.cc index 9ca628e3..8c916774 100644 --- a/content/browser/memory/memory_coordinator_impl.cc +++ b/content/browser/memory/memory_coordinator_impl.cc
@@ -133,7 +133,7 @@ memory_monitor_(std::move(memory_monitor)), condition_observer_( std::make_unique<MemoryConditionObserver>(this, task_runner)), - tick_clock_(std::make_unique<base::DefaultTickClock>()), + tick_clock_(base::DefaultTickClock::GetInstance()), minimum_state_transition_period_(base::TimeDelta::FromSeconds( kDefaultMinimumTransitionPeriodSeconds)) { DCHECK(memory_monitor_.get()); @@ -363,8 +363,8 @@ } void MemoryCoordinatorImpl::SetTickClockForTesting( - std::unique_ptr<base::TickClock> tick_clock) { - tick_clock_ = std::move(tick_clock); + base::TickClock* tick_clock) { + tick_clock_ = tick_clock; } void MemoryCoordinatorImpl::OnConnectionError(int render_process_id) {
diff --git a/content/browser/memory/memory_coordinator_impl.h b/content/browser/memory/memory_coordinator_impl.h index cd3638f..8f42d98d 100644 --- a/content/browser/memory/memory_coordinator_impl.h +++ b/content/browser/memory/memory_coordinator_impl.h
@@ -169,7 +169,7 @@ mojom::ChildMemoryCoordinatorPtr child); // Sets a TickClock for testing. - void SetTickClockForTesting(std::unique_ptr<base::TickClock> tick_clock); + void SetTickClockForTesting(base::TickClock* tick_clock); // Callback invoked by mojo when the child connection goes down. Exposed // for testing. @@ -207,7 +207,7 @@ std::unique_ptr<MemoryCoordinatorDelegate> delegate_; std::unique_ptr<MemoryMonitor> memory_monitor_; std::unique_ptr<MemoryConditionObserver> condition_observer_; - std::unique_ptr<base::TickClock> tick_clock_; + base::TickClock* tick_clock_; NotificationRegistrar notification_registrar_; // The current memory condition.
diff --git a/content/browser/memory/memory_coordinator_impl_unittest.cc b/content/browser/memory/memory_coordinator_impl_unittest.cc index 43f703e..2418018 100644 --- a/content/browser/memory/memory_coordinator_impl_unittest.cc +++ b/content/browser/memory/memory_coordinator_impl_unittest.cc
@@ -158,7 +158,9 @@ std::make_unique<MockMemoryMonitor>()) { SetDelegateForTesting(std::make_unique<TestMemoryCoordinatorDelegate>()); SetPolicyForTesting(std::make_unique<MockMemoryCoordinatorPolicy>(this)); - SetTickClockForTesting(task_runner->GetMockTickClock()); + + clock_ = task_runner->GetMockTickClock(); + SetTickClockForTesting(clock_.get()); } ~TestMemoryCoordinatorImpl() override {} @@ -204,6 +206,10 @@ return result; } + // TODO(tzik): Remove |clock_| after updating GetMockTickClock to own the + // instance. + std::unique_ptr<base::TickClock> clock_; + TestBrowserContext browser_context_; std::vector<std::unique_ptr<Child>> children_; std::map<int, std::unique_ptr<MockRenderProcessHost>> render_process_hosts_;
diff --git a/content/browser/mus_util.cc b/content/browser/mus_util.cc index 596a41c..5f45f248 100644 --- a/content/browser/mus_util.cc +++ b/content/browser/mus_util.cc
@@ -5,7 +5,6 @@ #include "content/browser/mus_util.h" #if defined(USE_AURA) -#include "content/public/browser/context_factory.h" #include "ui/aura/env.h" #endif @@ -19,9 +18,4 @@ #endif } -bool IsMusHostingViz() { - // TODO(sad): Currently mus always is the viz host. - return IsUsingMus(); -} - } // namespace content
diff --git a/content/browser/mus_util.h b/content/browser/mus_util.h index cb0a37c..4b7c78d3 100644 --- a/content/browser/mus_util.h +++ b/content/browser/mus_util.h
@@ -11,8 +11,6 @@ CONTENT_EXPORT bool IsUsingMus(); -bool IsMusHostingViz(); - } // namespace content #endif // CONTENT_BROWSER_MUS_UTIL_H_
diff --git a/content/browser/notifications/blink_notification_service_impl.cc b/content/browser/notifications/blink_notification_service_impl.cc index 5c78c0f..fd3420da 100644 --- a/content/browser/notifications/blink_notification_service_impl.cc +++ b/content/browser/notifications/blink_notification_service_impl.cc
@@ -28,10 +28,12 @@ PlatformNotificationContextImpl* notification_context, ResourceContext* resource_context, int render_process_id, + const url::Origin& origin, mojo::InterfaceRequest<blink::mojom::NotificationService> request) : notification_context_(notification_context), resource_context_(resource_context), render_process_id_(render_process_id), + origin_(origin), binding_(this, std::move(request)) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(notification_context_); @@ -47,17 +49,15 @@ } void BlinkNotificationServiceImpl::GetPermissionStatus( - const std::string& origin, GetPermissionStatusCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - if (!Service()) { std::move(callback).Run(blink::mojom::PermissionStatus::DENIED); return; } blink::mojom::PermissionStatus permission_status = - Service()->CheckPermissionOnIOThread(resource_context_, GURL(origin), + Service()->CheckPermissionOnIOThread(resource_context_, origin_.GetURL(), render_process_id_); std::move(callback).Run(permission_status);
diff --git a/content/browser/notifications/blink_notification_service_impl.h b/content/browser/notifications/blink_notification_service_impl.h index 7674b8a..140784d 100644 --- a/content/browser/notifications/blink_notification_service_impl.h +++ b/content/browser/notifications/blink_notification_service_impl.h
@@ -9,6 +9,7 @@ #include "mojo/public/cpp/bindings/binding.h" #include "mojo/public/cpp/bindings/interface_request.h" #include "third_party/WebKit/public/platform/modules/notifications/notification_service.mojom.h" +#include "url/origin.h" namespace content { @@ -24,12 +25,12 @@ PlatformNotificationContextImpl* notification_context, ResourceContext* resource_context, int render_process_id, + const url::Origin& origin, mojo::InterfaceRequest<blink::mojom::NotificationService> request); ~BlinkNotificationServiceImpl() override; // blink::mojom::NotificationService implementation. - void GetPermissionStatus(const std::string& origin, - GetPermissionStatusCallback callback) override; + void GetPermissionStatus(GetPermissionStatusCallback callback) override; private: // Called when an error is detected on binding_. @@ -42,6 +43,9 @@ int render_process_id_; + // The origin that this notification service is communicating with. + url::Origin origin_; + mojo::Binding<blink::mojom::NotificationService> binding_; DISALLOW_COPY_AND_ASSIGN(BlinkNotificationServiceImpl);
diff --git a/content/browser/notifications/platform_notification_context_impl.cc b/content/browser/notifications/platform_notification_context_impl.cc index db017fc..a5397ea 100644 --- a/content/browser/notifications/platform_notification_context_impl.cc +++ b/content/browser/notifications/platform_notification_context_impl.cc
@@ -125,22 +125,25 @@ void PlatformNotificationContextImpl::CreateService( int render_process_id, + const url::Origin& origin, blink::mojom::NotificationServiceRequest request) { DCHECK_CURRENTLY_ON(BrowserThread::UI); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::BindOnce(&PlatformNotificationContextImpl::CreateServiceOnIO, this, - render_process_id, browser_context_->GetResourceContext(), + render_process_id, origin, + browser_context_->GetResourceContext(), base::Passed(&request))); } void PlatformNotificationContextImpl::CreateServiceOnIO( int render_process_id, + const url::Origin& origin, ResourceContext* resource_context, mojo::InterfaceRequest<blink::mojom::NotificationService> request) { DCHECK_CURRENTLY_ON(BrowserThread::IO); services_.push_back(std::make_unique<BlinkNotificationServiceImpl>( - this, resource_context, render_process_id, std::move(request))); + this, resource_context, render_process_id, origin, std::move(request))); } void PlatformNotificationContextImpl::RemoveService(
diff --git a/content/browser/notifications/platform_notification_context_impl.h b/content/browser/notifications/platform_notification_context_impl.h index af5d335..157a54c5 100644 --- a/content/browser/notifications/platform_notification_context_impl.h +++ b/content/browser/notifications/platform_notification_context_impl.h
@@ -29,6 +29,10 @@ class SequencedTaskRunner; } +namespace url { +class Origin; +} + namespace content { class BlinkNotificationServiceImpl; @@ -64,6 +68,7 @@ // be called on the UI thread, although the service will be created on and // bound to the IO thread. void CreateService(int render_process_id, + const url::Origin& origin, blink::mojom::NotificationServiceRequest request); // Removes |service| from the list of owned services, for example because the @@ -109,6 +114,7 @@ void ShutdownOnIO(); void CreateServiceOnIO( int render_process_id, + const url::Origin& origin, ResourceContext* resource_context, mojo::InterfaceRequest<blink::mojom::NotificationService> request);
diff --git a/content/browser/payments/payment_app_provider_impl.cc b/content/browser/payments/payment_app_provider_impl.cc index 337411c..8816724 100644 --- a/content/browser/payments/payment_app_provider_impl.cc +++ b/content/browser/payments/payment_app_provider_impl.cc
@@ -16,6 +16,7 @@ #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" #include "mojo/common/time.mojom.h" +#include "third_party/WebKit/common/service_worker/service_worker_provider_type.mojom.h" namespace content { namespace { @@ -141,7 +142,7 @@ std::vector<std::pair<int, int>> ids; for (const auto& controllee : service_worker_version_->controllee_map()) { if (controllee.second->provider_type() == - SERVICE_WORKER_PROVIDER_FOR_WINDOW) { + blink::mojom::ServiceWorkerProviderType::kForWindow) { ids.emplace_back(std::make_pair(controllee.second->process_id(), controllee.second->frame_id())); }
diff --git a/content/browser/quota_dispatcher_host.cc b/content/browser/quota_dispatcher_host.cc index af7cbb8a..f04b400ab 100644 --- a/content/browser/quota_dispatcher_host.cc +++ b/content/browser/quota_dispatcher_host.cc
@@ -13,8 +13,8 @@ #include "base/memory/weak_ptr.h" #include "base/numerics/safe_conversions.h" #include "base/trace_event/trace_event.h" -#include "content/common/quota_messages.h" #include "content/public/browser/quota_permission_context.h" +#include "mojo/public/cpp/bindings/strong_binding.h" #include "net/base/url_util.h" #include "storage/browser/quota/quota_manager.h" #include "url/gurl.h" @@ -29,15 +29,14 @@ // Created one per request to carry the request's request_id around. // Dispatches requests from renderer/worker to the QuotaManager and // sends back the response to the renderer/worker. +// TODO(sashab): Remove, since request_id is no longer needed. class QuotaDispatcherHost::RequestDispatcher { public: - RequestDispatcher(base::WeakPtr<QuotaDispatcherHost> dispatcher_host, - int request_id) + RequestDispatcher(base::WeakPtr<QuotaDispatcherHost> dispatcher_host) : dispatcher_host_(dispatcher_host), - render_process_id_(dispatcher_host->process_id_), - request_id_(request_id) { - dispatcher_host_->outstanding_requests_.AddWithID(base::WrapUnique(this), - request_id_); + render_process_id_(dispatcher_host->process_id_) { + request_id_ = + dispatcher_host_->outstanding_requests_.Add(base::WrapUnique(this)); } virtual ~RequestDispatcher() {} @@ -59,7 +58,6 @@ : nullptr; } int render_process_id() const { return render_process_id_; } - int request_id() const { return request_id_; } private: base::WeakPtr<QuotaDispatcherHost> dispatcher_host_; @@ -72,8 +70,9 @@ public: QueryUsageAndQuotaDispatcher( base::WeakPtr<QuotaDispatcherHost> dispatcher_host, - int request_id) - : RequestDispatcher(dispatcher_host, request_id), + QueryStorageUsageAndQuotaCallback callback) + : RequestDispatcher(dispatcher_host), + callback_(std::move(callback)), weak_factory_(this) {} ~QueryUsageAndQuotaDispatcher() override {} @@ -98,16 +97,11 @@ // crbug.com/349708 TRACE_EVENT0("io", "QuotaDispatcherHost::RequestQuotaDispatcher" "::DidQueryStorageUsageAndQuota"); - - if (status != storage::kQuotaStatusOk) { - dispatcher_host()->Send(new QuotaMsg_DidFail(request_id(), status)); - } else { - dispatcher_host()->Send(new QuotaMsg_DidQueryStorageUsageAndQuota( - request_id(), usage, quota)); - } + std::move(callback_).Run(status, usage, quota); Completed(); } + QueryStorageUsageAndQuotaCallback callback_; base::WeakPtrFactory<QueryUsageAndQuotaDispatcher> weak_factory_; }; @@ -116,19 +110,27 @@ public: typedef RequestQuotaDispatcher self_type; - RequestQuotaDispatcher(base::WeakPtr<QuotaDispatcherHost> dispatcher_host, - const StorageQuotaParams& params) - : RequestDispatcher(dispatcher_host, params.request_id), - params_(params), + RequestQuotaDispatcher( + base::WeakPtr<QuotaDispatcherHost> dispatcher_host, + int64_t render_frame_id, + const GURL& origin_url, + storage::StorageType storage_type, + uint64_t requested_size, + mojom::QuotaDispatcherHost::RequestStorageQuotaCallback callback) + : RequestDispatcher(dispatcher_host), + render_frame_id_(render_frame_id), + origin_url_(origin_url), + storage_type_(storage_type), + requested_size_(requested_size), + callback_(std::move(callback)), current_usage_(0), current_quota_(0), requested_quota_(0), weak_factory_(this) { // Convert the requested size from uint64_t to int64_t since the quota - // backend - // requires int64_t values. + // backend requires int64_t values. // TODO(nhiroki): The backend should accept uint64_t values. - requested_quota_ = base::saturated_cast<int64_t>(params_.requested_size); + requested_quota_ = base::saturated_cast<int64_t>(requested_size); } ~RequestQuotaDispatcher() override {} @@ -137,16 +139,16 @@ // crbug.com/349708 TRACE_EVENT0("io", "QuotaDispatcherHost::RequestQuotaDispatcher::Start"); - DCHECK(params_.storage_type == storage::kStorageTypeTemporary || - params_.storage_type == storage::kStorageTypePersistent); - if (params_.storage_type == storage::kStorageTypePersistent) { + DCHECK(storage_type_ == storage::kStorageTypeTemporary || + storage_type_ == storage::kStorageTypePersistent); + if (storage_type_ == storage::kStorageTypePersistent) { quota_manager()->GetUsageAndQuotaForWebApps( - params_.origin_url, params_.storage_type, + origin_url_, storage_type_, base::Bind(&self_type::DidGetPersistentUsageAndQuota, weak_factory_.GetWeakPtr())); } else { quota_manager()->GetUsageAndQuotaForWebApps( - params_.origin_url, params_.storage_type, + origin_url_, storage_type_, base::Bind(&self_type::DidGetTemporaryUsageAndQuota, weak_factory_.GetWeakPtr())); } @@ -163,11 +165,10 @@ return; } - if (quota_manager()->IsStorageUnlimited(params_.origin_url, - params_.storage_type) || + if (quota_manager()->IsStorageUnlimited(origin_url_, storage_type_) || requested_quota_ <= quota) { // Seems like we can just let it go. - DidFinish(storage::kQuotaStatusOk, usage, params_.requested_size); + DidFinish(storage::kQuotaStatusOk, usage, requested_size_); return; } current_usage_ = usage; @@ -176,7 +177,15 @@ // Otherwise we need to consult with the permission context and // possibly show a prompt. DCHECK(permission_context()); - permission_context()->RequestQuotaPermission(params_, render_process_id(), + + StorageQuotaParams params; + params.render_frame_id = render_frame_id_; + params.origin_url = origin_url_; + params.storage_type = storage_type_; + params.requested_size = requested_size_; + + permission_context()->RequestQuotaPermission( + params, render_process_id(), base::Bind(&self_type::DidGetPermissionResponse, weak_factory_.GetWeakPtr())); } @@ -198,7 +207,7 @@ } // Now we're allowed to set the new quota. quota_manager()->SetPersistentHostQuota( - net::GetHostOrSpecFromURL(params_.origin_url), params_.requested_size, + net::GetHostOrSpecFromURL(origin_url_), requested_size_, base::Bind(&self_type::DidSetHostQuota, weak_factory_.GetWeakPtr())); } @@ -210,70 +219,71 @@ if (!dispatcher_host()) return; DCHECK(dispatcher_host()); - if (status != storage::kQuotaStatusOk) { - dispatcher_host()->Send(new QuotaMsg_DidFail(request_id(), status)); - } else { - dispatcher_host()->Send(new QuotaMsg_DidGrantStorageQuota( - request_id(), usage, granted_quota)); - } + std::move(callback_).Run(status, usage, granted_quota); Completed(); } - StorageQuotaParams params_; + const int64_t render_frame_id_; + const GURL origin_url_; + const storage::StorageType storage_type_; + const uint64_t requested_size_; + mojom::QuotaDispatcherHost::RequestStorageQuotaCallback callback_; + int64_t current_usage_; int64_t current_quota_; int64_t requested_quota_; base::WeakPtrFactory<self_type> weak_factory_; }; +// static +void QuotaDispatcherHost::Create( + int process_id, + QuotaManager* quota_manager, + scoped_refptr<QuotaPermissionContext> permission_context, + mojom::QuotaDispatcherHostRequest request) { + mojo::MakeStrongBinding( + base::MakeUnique<QuotaDispatcherHost>(process_id, quota_manager, + std::move(permission_context)), + std::move(request)); +} + QuotaDispatcherHost::QuotaDispatcherHost( int process_id, QuotaManager* quota_manager, - QuotaPermissionContext* permission_context) - : BrowserMessageFilter(QuotaMsgStart), - process_id_(process_id), + scoped_refptr<QuotaPermissionContext> permission_context) + : process_id_(process_id), quota_manager_(quota_manager), permission_context_(permission_context), - weak_factory_(this) { -} + weak_factory_(this) {} -bool QuotaDispatcherHost::OnMessageReceived(const IPC::Message& message) { - bool handled = true; - IPC_BEGIN_MESSAGE_MAP(QuotaDispatcherHost, message) - IPC_MESSAGE_HANDLER(QuotaHostMsg_QueryStorageUsageAndQuota, - OnQueryStorageUsageAndQuota) - IPC_MESSAGE_HANDLER(QuotaHostMsg_RequestStorageQuota, - OnRequestStorageQuota) - IPC_MESSAGE_UNHANDLED(handled = false) - IPC_END_MESSAGE_MAP() - return handled; -} - -QuotaDispatcherHost::~QuotaDispatcherHost() {} - -void QuotaDispatcherHost::OnQueryStorageUsageAndQuota( - int request_id, - const GURL& origin, - StorageType type) { +void QuotaDispatcherHost::QueryStorageUsageAndQuota( + const GURL& origin_url, + storage::StorageType storage_type, + QueryStorageUsageAndQuotaCallback callback) { QueryUsageAndQuotaDispatcher* dispatcher = new QueryUsageAndQuotaDispatcher( - weak_factory_.GetWeakPtr(), request_id); - dispatcher->QueryStorageUsageAndQuota(origin, type); + weak_factory_.GetWeakPtr(), std::move(callback)); + dispatcher->QueryStorageUsageAndQuota(origin_url, storage_type); } -void QuotaDispatcherHost::OnRequestStorageQuota( - const StorageQuotaParams& params) { - if (params.storage_type != storage::kStorageTypeTemporary && - params.storage_type != storage::kStorageTypePersistent) { +void QuotaDispatcherHost::RequestStorageQuota( + int64_t render_frame_id, + const GURL& origin_url, + storage::StorageType storage_type, + uint64_t requested_size, + mojom::QuotaDispatcherHost::RequestStorageQuotaCallback callback) { + if (storage_type != storage::kStorageTypeTemporary && + storage_type != storage::kStorageTypePersistent) { // Unsupported storage types. - Send(new QuotaMsg_DidFail(params.request_id, - storage::kQuotaErrorNotSupported)); + std::move(callback).Run(storage::kQuotaErrorNotSupported, 0, 0); return; } - RequestQuotaDispatcher* dispatcher = - new RequestQuotaDispatcher(weak_factory_.GetWeakPtr(), - params); + RequestQuotaDispatcher* dispatcher = new RequestQuotaDispatcher( + weak_factory_.GetWeakPtr(), render_frame_id, origin_url, storage_type, + requested_size, std::move(callback)); dispatcher->Start(); } +QuotaDispatcherHost::~QuotaDispatcherHost() = default; + } // namespace content
diff --git a/content/browser/quota_dispatcher_host.h b/content/browser/quota_dispatcher_host.h index 8aebb6e0..40677a2 100644 --- a/content/browser/quota_dispatcher_host.h +++ b/content/browser/quota_dispatcher_host.h
@@ -7,45 +7,47 @@ #include "base/containers/id_map.h" #include "base/macros.h" +#include "content/common/quota_dispatcher_host.mojom.h" #include "content/public/browser/browser_message_filter.h" -#include "storage/common/quota/quota_types.h" class GURL; -namespace IPC { -class Message; -} - namespace storage { class QuotaManager; } namespace content { class QuotaPermissionContext; -struct StorageQuotaParams; -class QuotaDispatcherHost : public BrowserMessageFilter { +class QuotaDispatcherHost : public mojom::QuotaDispatcherHost { public: + static void Create(int process_id, + storage::QuotaManager* quota_manager, + scoped_refptr<QuotaPermissionContext> permission_context, + mojom::QuotaDispatcherHostRequest request); + QuotaDispatcherHost(int process_id, storage::QuotaManager* quota_manager, - QuotaPermissionContext* permission_context); + scoped_refptr<QuotaPermissionContext> permission_context); - // BrowserMessageFilter: - bool OnMessageReceived(const IPC::Message& message) override; - - protected: ~QuotaDispatcherHost() override; + // content::mojom::QuotaDispatcherHost: + void QueryStorageUsageAndQuota( + const GURL& origin_url, + storage::StorageType storage_type, + QueryStorageUsageAndQuotaCallback callback) override; + void RequestStorageQuota(int64_t render_frame_id, + const GURL& origin_url, + storage::StorageType storage_type, + uint64_t requested_size, + RequestStorageQuotaCallback callback) override; + private: class RequestDispatcher; class QueryUsageAndQuotaDispatcher; class RequestQuotaDispatcher; - void OnQueryStorageUsageAndQuota(int request_id, - const GURL& origin_url, - storage::StorageType type); - void OnRequestStorageQuota(const StorageQuotaParams& params); - // The ID of this process. int process_id_;
diff --git a/content/browser/renderer_host/compositor_impl_android.cc b/content/browser/renderer_host/compositor_impl_android.cc index 919b403..7de855d 100644 --- a/content/browser/renderer_host/compositor_impl_android.cc +++ b/content/browser/renderer_host/compositor_impl_android.cc
@@ -54,7 +54,6 @@ #include "content/browser/browser_main_loop.h" #include "content/browser/compositor/surface_utils.h" #include "content/browser/gpu/compositor_util.h" -#include "content/browser/gpu/gpu_process_host.h" #include "content/browser/renderer_host/render_widget_host_impl.h" #include "content/common/gpu_stream_constants.h" #include "content/public/browser/android/compositor.h" @@ -689,8 +688,6 @@ AddChildFrameSink(frame_sink_id); pending_child_frame_sink_ids_.clear(); - - DidSuccessfullyInitializeContext(); } void CompositorImpl::DidFailToInitializeLayerTreeFrameSink() { @@ -791,8 +788,6 @@ return; } - DidSuccessfullyInitializeContext(); - // Unretained is safe this owns viz::Display which owns OutputSurface. auto display_output_surface = std::make_unique<AndroidOutputSurface>( context_provider, @@ -863,16 +858,6 @@ client_->DidSwapBuffers(); } -void CompositorImpl::DidSuccessfullyInitializeContext() { - auto on_io_thread = [] { - GpuProcessHost* host = GpuProcessHost::Get(); - if (host) - host->DidSuccessfullyInitializeContext(); - }; - BrowserThread::GetTaskRunnerForThread(BrowserThread::IO) - ->PostTask(FROM_HERE, base::BindOnce(on_io_thread)); -} - cc::UIResourceId CompositorImpl::CreateUIResource( cc::UIResourceClient* client) { TRACE_EVENT0("compositor", "CompositorImpl::CreateUIResource");
diff --git a/content/browser/renderer_host/compositor_impl_android.h b/content/browser/renderer_host/compositor_impl_android.h index dc931d14..80fabcb 100644 --- a/content/browser/renderer_host/compositor_impl_android.h +++ b/content/browser/renderer_host/compositor_impl_android.h
@@ -148,8 +148,6 @@ scoped_refptr<viz::VulkanContextProvider> vulkan_context_provider, scoped_refptr<viz::ContextProvider> context_provider); void DidSwapBuffers(); - // Reports back when the gpu process is functioning. See crbug.com/772049. - void DidSuccessfullyInitializeContext(); bool HavePendingReadbacks();
diff --git a/content/browser/renderer_host/compositor_resize_lock.cc b/content/browser/renderer_host/compositor_resize_lock.cc index f4a24a1..7336dba0 100644 --- a/content/browser/renderer_host/compositor_resize_lock.cc +++ b/content/browser/renderer_host/compositor_resize_lock.cc
@@ -32,6 +32,8 @@ UMA_HISTOGRAM_TIMES("UI.CompositorResizeLock.Duration", base::TimeTicks::Now() - acquisition_time_); + + UMA_HISTOGRAM_BOOLEAN("UI.CompositorResizeLock.TimedOut", timed_out_); } bool CompositorResizeLock::Lock() {
diff --git a/content/browser/renderer_host/delegated_frame_host.cc b/content/browser/renderer_host/delegated_frame_host.cc index 5905087..8ad3743e 100644 --- a/content/browser/renderer_host/delegated_frame_host.cc +++ b/content/browser/renderer_host/delegated_frame_host.cc
@@ -53,7 +53,7 @@ client_(client), enable_surface_synchronization_(enable_surface_synchronization), enable_viz_(enable_viz), - tick_clock_(std::make_unique<base::DefaultTickClock>()), + tick_clock_(base::DefaultTickClock::GetInstance()), background_color_(SK_ColorRED), frame_evictor_(std::make_unique<viz::FrameEvictor>(this)), weak_ptr_factory_(this) {
diff --git a/content/browser/renderer_host/delegated_frame_host.h b/content/browser/renderer_host/delegated_frame_host.h index c67503e..6766d00 100644 --- a/content/browser/renderer_host/delegated_frame_host.h +++ b/content/browser/renderer_host/delegated_frame_host.h
@@ -298,7 +298,7 @@ base::TimeDelta vsync_interval_; // Overridable tick clock used for testing functions using current time. - std::unique_ptr<base::TickClock> tick_clock_; + base::TickClock* tick_clock_; // True after a delegated frame has been skipped, until a frame is not // skipped.
diff --git a/content/browser/renderer_host/input/mouse_latency_browsertest.cc b/content/browser/renderer_host/input/mouse_latency_browsertest.cc index 18e16642a..b6234b6e 100644 --- a/content/browser/renderer_host/input/mouse_latency_browsertest.cc +++ b/content/browser/renderer_host/input/mouse_latency_browsertest.cc
@@ -237,8 +237,9 @@ #define MAYBE_CoalescedMouseMovesCorrectlyTerminated \ DISABLED_CoalescedMouseMovesCorrectlyTerminated #else +// Test fails/flakes on multiple platforms. https://crbug.com/789096 #define MAYBE_CoalescedMouseMovesCorrectlyTerminated \ - CoalescedMouseMovesCorrectlyTerminated + DISABLED_CoalescedMouseMovesCorrectlyTerminated #endif IN_PROC_BROWSER_TEST_F(MouseLatencyBrowserTest, MAYBE_CoalescedMouseMovesCorrectlyTerminated) {
diff --git a/content/browser/renderer_host/media/media_devices_dispatcher_host_unittest.cc b/content/browser/renderer_host/media/media_devices_dispatcher_host_unittest.cc index 227f707..b6cb0ad 100644 --- a/content/browser/renderer_host/media/media_devices_dispatcher_host_unittest.cc +++ b/content/browser/renderer_host/media/media_devices_dispatcher_host_unittest.cc
@@ -15,6 +15,7 @@ #include "base/command_line.h" #include "base/memory/ptr_util.h" #include "base/run_loop.h" +#include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/threading/thread_task_runner_handle.h" #include "content/browser/renderer_host/media/in_process_video_capture_provider.h" @@ -51,7 +52,9 @@ const char kNoFormatsVideoDeviceID[] = "/dev/video1"; const char kZeroResolutionVideoDeviceID[] = "/dev/video2"; const char* const kDefaultVideoDeviceID = kZeroResolutionVideoDeviceID; -const char kDefaultAudioDeviceID[] = "fake_audio_input_2"; +const char kUserDefaultAudioInputDeviceID[] = "fake_audio_input_2"; +const char kSystemDefaultAudioInputLabel[] = "Fake Audio Input 1"; +const char kSystemDefaultAudioOutputLabel[] = "Fake Audio Output 1"; const auto kIgnoreLogMessageCB = base::BindRepeating([](const std::string&) {}); @@ -92,7 +95,8 @@ switches::kUseFakeDeviceForMediaStream, base::StringPrintf("video-input-default-id=%s, " "audio-input-default-id=%s", - kDefaultVideoDeviceID, kDefaultAudioDeviceID)); + kDefaultVideoDeviceID, + kUserDefaultAudioInputDeviceID)); audio_manager_ = std::make_unique<media::MockAudioManager>( std::make_unique<media::TestAudioThread>()); audio_system_ = @@ -198,7 +202,7 @@ EXPECT_EQ(kNumExpectedEntries, capabilities.size()); std::string expected_first_device_id = GetHMACForMediaDeviceID(browser_context_->GetMediaDeviceIDSalt(), - origin_, kDefaultAudioDeviceID); + origin_, kUserDefaultAudioInputDeviceID); EXPECT_EQ(expected_first_device_id, capabilities[0]->device_id); for (const auto& capability : capabilities) EXPECT_TRUE(capability->parameters.IsValid()); @@ -304,8 +308,15 @@ } // Returns true if all devices have labels, false otherwise. - bool DoesContainLabels(const MediaDeviceInfoArray& device_infos) { + bool DoesContainLabels( + const MediaDeviceInfoArray& device_infos, + const std::string& system_default_label = std::string()) { for (const auto& device_info : device_infos) { + if (media::AudioDeviceDescription::IsDefaultDevice( + device_info.device_id)) { + EXPECT_TRUE(base::EndsWith(device_info.label, system_default_label, + base::CompareCase::SENSITIVE)); + } if (device_info.label.empty()) return false; } @@ -314,8 +325,13 @@ // Returns true if all devices have labels, false otherwise. bool DoesContainLabels(const std::vector<MediaDeviceInfoArray>& enumeration) { - for (const auto& device_infos : enumeration) { - if (!DoesContainLabels(device_infos)) + for (int i = 0; i < NUM_MEDIA_DEVICE_TYPES; i++) { + std::string default_label; + if (i == MEDIA_DEVICE_TYPE_AUDIO_INPUT) + default_label = kSystemDefaultAudioInputLabel; + else if (i == MEDIA_DEVICE_TYPE_AUDIO_OUTPUT) + default_label = kSystemDefaultAudioOutputLabel; + if (!DoesContainLabels(enumeration[i], default_label)) return false; } return true;
diff --git a/content/browser/renderer_host/media/media_devices_manager.cc b/content/browser/renderer_host/media/media_devices_manager.cc index 5ad8bf2..50435cd 100644 --- a/content/browser/renderer_host/media/media_devices_manager.cc +++ b/content/browser/renderer_host/media/media_devices_manager.cc
@@ -49,23 +49,23 @@ return output_string; } -MediaDeviceInfoArray GetFakeAudioDevices(bool is_input) { - MediaDeviceInfoArray result; +media::AudioDeviceDescriptions GetFakeAudioDevices(bool is_input) { + media::AudioDeviceDescriptions result; if (is_input) { - result.emplace_back(media::AudioDeviceDescription::kDefaultDeviceId, - "Fake Default Audio Input", - "fake_group_audio_input_default"); - result.emplace_back("fake_audio_input_1", "Fake Audio Input 1", - "fake_group_audio_input_1"); - result.emplace_back("fake_audio_input_2", "Fake Audio Input 2", + result.emplace_back("Fake Default Audio Input", + media::AudioDeviceDescription::kDefaultDeviceId, + "fake_group_audio_1"); + result.emplace_back("Fake Audio Input 1", "fake_audio_input_1", + "fake_group_audio_1"); + result.emplace_back("Fake Audio Input 2", "fake_audio_input_2", "fake_group_audio_input_2"); } else { - result.emplace_back(media::AudioDeviceDescription::kDefaultDeviceId, - "Fake Default Audio Output", - "fake_group_audio_output_default"); - result.emplace_back("fake_audio_output_1", "Fake Audio Output 1", - "fake_group_audio_output_1"); - result.emplace_back("fake_audio_output_2", "Fake Audio Output 2", + result.emplace_back("Fake Default Audio Output", + media::AudioDeviceDescription::kDefaultDeviceId, + "fake_group_audio_1"); + result.emplace_back("Fake Audio Output 1", "fake_audio_output_1", + "fake_group_audio_1"); + result.emplace_back("Fake Audio Output 2", "fake_audio_output_2", "fake_group_audio_output_2"); } @@ -339,7 +339,7 @@ is_input ? MEDIA_DEVICE_TYPE_AUDIO_INPUT : MEDIA_DEVICE_TYPE_AUDIO_OUTPUT; if (use_fake_devices_) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::BindOnce(&MediaDevicesManager::DevicesEnumerated, + FROM_HERE, base::BindOnce(&MediaDevicesManager::AudioDevicesEnumerated, weak_factory_.GetWeakPtr(), type, GetFakeAudioDevices(is_input))); return; @@ -365,10 +365,56 @@ media::AudioDeviceDescriptions device_descriptions) { DCHECK_CURRENTLY_ON(BrowserThread::IO); + auto it_default_device = + std::find_if(device_descriptions.begin(), device_descriptions.end(), + [](const media::AudioDeviceDescription& description) { + return media::AudioDeviceDescription::IsDefaultDevice( + description.unique_id); + }); + + auto it_real_default_device = device_descriptions.end(); + if (it_default_device != device_descriptions.end()) { + // Find the real device that maps to the default device by finding + // coincidence in the group ID. + // This approach works only when the following is true: + // * group ID is properly supported so that the default device has the + // same group ID as some real device. + // * For input devices, the default device has an associated output device. + // * There is only one device with the same group ID of the default device. + // TODO(guidou): Get the real ID of the default input device from + // media::AudioSystem when the functionality becomes available. + // http://crbug.com/788758 + for (auto it = device_descriptions.begin(); it != device_descriptions.end(); + ++it) { + if (it->group_id == it_default_device->group_id && + !media::AudioDeviceDescription::IsDefaultDevice(it->unique_id)) { + if (it_real_default_device != device_descriptions.end()) { + // If there is more than one real device with the same group ID as the + // default device, the exact mapping cannot be found. + it_real_default_device = device_descriptions.end(); + break; + } else { + it_real_default_device = it; + } + } + } + } + MediaDeviceInfoArray snapshot; for (const media::AudioDeviceDescription& description : device_descriptions) { - snapshot.emplace_back(description); + if (it_real_default_device != device_descriptions.end() && + media::AudioDeviceDescription::IsDefaultDevice(description.unique_id)) { + // TODO(guidou): Make the concatenation of the default and real device + // labels in a properly localized manner. http://crbug.com/788767 + snapshot.emplace_back( + description.unique_id, + description.device_name + " - " + it_real_default_device->device_name, + description.group_id); + } else { + snapshot.emplace_back(description); + } } + DevicesEnumerated(type, snapshot); }
diff --git a/content/browser/renderer_host/render_process_host_impl.cc b/content/browser/renderer_host/render_process_host_impl.cc index 96698dfa..c2216f7 100644 --- a/content/browser/renderer_host/render_process_host_impl.cc +++ b/content/browser/renderer_host/render_process_host_impl.cc
@@ -33,6 +33,7 @@ #include "base/memory/shared_memory.h" #include "base/memory/shared_memory_handle.h" #include "base/message_loop/message_loop.h" +#include "base/metrics/histogram_base.h" #include "base/metrics/histogram_macros.h" #include "base/metrics/persistent_histogram_allocator.h" #include "base/metrics/persistent_memory_allocator.h" @@ -103,7 +104,6 @@ #include "content/browser/mus_util.h" #include "content/browser/net/reporting_service_proxy.h" #include "content/browser/notifications/notification_message_filter.h" -#include "content/browser/notifications/platform_notification_context_impl.h" #include "content/browser/payments/payment_manager.h" #include "content/browser/permissions/permission_service_context.h" #include "content/browser/permissions/permission_service_impl.h" @@ -152,6 +152,7 @@ #include "content/public/browser/content_browser_client.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_types.h" +#include "content/public/browser/quota_permission_context.h" #include "content/public/browser/render_process_host_factory.h" #include "content/public/browser/render_process_host_observer.h" #include "content/public/browser/render_widget_host.h" @@ -1773,9 +1774,6 @@ AddFilter(new TraceMessageFilter(GetID())); AddFilter(new ResolveProxyMsgHelper(request_context.get())); - AddFilter(new QuotaDispatcherHost( - GetID(), storage_partition_impl_->GetQuotaManager(), - GetContentClient()->browser()->CreateQuotaPermissionContext())); scoped_refptr<ServiceWorkerContextWrapper> service_worker_context( static_cast<ServiceWorkerContextWrapper*>( @@ -1829,12 +1827,6 @@ storage_partition_impl_->GetBackgroundSyncContext()))); AddUIThreadInterface( registry.get(), - base::Bind(&PlatformNotificationContextImpl::CreateService, - base::Unretained( - storage_partition_impl_->GetPlatformNotificationContext()), - GetID())); - AddUIThreadInterface( - registry.get(), base::Bind(&RenderProcessHostImpl::CreateStoragePartitionService, base::Unretained(this))); AddUIThreadInterface( @@ -1919,6 +1911,12 @@ registry->AddInterface( base::Bind(&metrics::CreateSingleSampleMetricsProvider)); + registry->AddInterface(base::Bind( + QuotaDispatcherHost::Create, GetID(), + base::RetainedRef(storage_partition_impl_->GetQuotaManager()), + base::WrapRefCounted( + GetContentClient()->browser()->CreateQuotaPermissionContext()))); + registry->AddInterface( base::Bind(&CreateReportingServiceProxy, storage_partition_impl_)); @@ -1927,7 +1925,7 @@ associated_interfaces_.reset(new AssociatedInterfaceRegistryImpl()); GetContentClient()->browser()->ExposeInterfacesToRenderer( registry.get(), associated_interfaces_.get(), this); - AssociatedInterfaceRegistry* associated_registry = + blink::AssociatedInterfaceRegistry* associated_registry = associated_interfaces_.get(); associated_registry->AddInterface(base::Bind( &RenderProcessHostImpl::BindRouteProvider, base::Unretained(this))); @@ -4161,7 +4159,7 @@ if (!histogram) { histogram_json = "{}"; } else { - histogram->WriteJSON(&histogram_json); + histogram->WriteJSON(&histogram_json, base::JSON_VERBOSITY_LEVEL_FULL); } std::move(callback).Run(histogram_json); }
diff --git a/content/browser/renderer_host/render_process_host_unittest.cc b/content/browser/renderer_host/render_process_host_unittest.cc index 890330b7..d2855208 100644 --- a/content/browser/renderer_host/render_process_host_unittest.cc +++ b/content/browser/renderer_host/render_process_host_unittest.cc
@@ -405,12 +405,7 @@ // Navigate back and simulate an error. Getting a RenderProcessHost with the // REUSE_PENDING_OR_COMMITTED_SITE policy should return a new process. - web_contents()->GetController().GoBack(); - TestRenderFrameHost* pending_rfh = contents()->GetPendingMainFrame(); - if (!IsBrowserSideNavigationEnabled()) - pending_rfh->SimulateNavigationStart(kUrl1); - pending_rfh->SimulateNavigationError(kUrl1, net::ERR_TIMED_OUT); - pending_rfh->SimulateNavigationErrorPageCommit(); + NavigationSimulator::GoBackAndFail(contents(), net::ERR_TIMED_OUT); site_instance = SiteInstanceImpl::CreateForURL(browser_context(), kUrl1); site_instance->set_process_reuse_policy( SiteInstanceImpl::ProcessReusePolicy::REUSE_PENDING_OR_COMMITTED_SITE);
diff --git a/content/browser/renderer_host/render_widget_host_view_aura.cc b/content/browser/renderer_host/render_widget_host_view_aura.cc index 2cb4ecc..3adf96e 100644 --- a/content/browser/renderer_host/render_widget_host_view_aura.cc +++ b/content/browser/renderer_host/render_widget_host_view_aura.cc
@@ -82,6 +82,7 @@ #include "ui/base/hit_test.h" #include "ui/base/ime/input_method.h" #include "ui/base/ui_base_switches.h" +#include "ui/base/ui_base_switches_util.h" #include "ui/base/ui_base_types.h" #include "ui/compositor/compositor_vsync_manager.h" #include "ui/compositor/dip_util.h" @@ -413,7 +414,7 @@ is_guest_view_hack_(is_guest_view_hack), device_scale_factor_(0.0f), event_handler_(new RenderWidgetHostViewEventHandler(host_, this, this)), - frame_sink_id_(IsMusHostingViz() + frame_sink_id_(switches::IsMusHostingViz() ? viz::FrameSinkId() : host_->AllocateFrameSinkId(is_guest_view_hack_)), weak_ptr_factory_(this) {
diff --git a/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc b/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc index 1d83ea6..6b141cd 100644 --- a/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc +++ b/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc
@@ -3669,7 +3669,6 @@ : callback_count_(0), result_(false), frame_subscriber_(nullptr), - tick_clock_(nullptr), view_rect_(100, 100) {} void CallbackMethod(bool result) { @@ -3708,9 +3707,7 @@ } void InstallFakeTickClock() { - // Create a fake tick clock and transfer ownership to the frame host. - tick_clock_ = new base::SimpleTestTickClock(); - view_->GetDelegatedFrameHost()->tick_clock_ = base::WrapUnique(tick_clock_); + view_->GetDelegatedFrameHost()->tick_clock_ = &tick_clock_; } void SubmitCompositorFrame() { @@ -3762,7 +3759,7 @@ int callback_count_; bool result_; FakeFrameSubscriber* frame_subscriber_; // Owned by |view_|. - base::SimpleTestTickClock* tick_clock_; // Owned by DelegatedFrameHost. + base::SimpleTestTickClock tick_clock_; const gfx::Rect view_rect_; private: @@ -3867,13 +3864,13 @@ // Verify our initial state. EXPECT_EQ(base::TimeTicks(), frame_subscriber_->last_present_time()); - EXPECT_EQ(base::TimeTicks(), tick_clock_->NowTicks()); + EXPECT_EQ(base::TimeTicks(), tick_clock_.NowTicks()); // Start our fake clock from a non-zero, but not an even multiple of the // interval, value to differentiate it from our initialization state. const base::TimeDelta kDefaultInterval = viz::BeginFrameArgs::DefaultInterval(); - tick_clock_->Advance(kDefaultInterval / 3); + tick_clock_.Advance(kDefaultInterval / 3); // Swap the first frame without any vsync information. ASSERT_EQ(base::TimeTicks(), vsync_timebase()); @@ -3882,7 +3879,7 @@ // During this first call, there is no known vsync information, so while the // callback should succeed the present time is effectively just current time. SubmitCompositorFrameAndRelease(); - EXPECT_EQ(tick_clock_->NowTicks(), frame_subscriber_->last_present_time()); + EXPECT_EQ(tick_clock_.NowTicks(), frame_subscriber_->last_present_time()); // Now initialize the vsync parameters with a null timebase, but a known vsync // interval; which should give us slightly better frame time estimates. @@ -3899,7 +3896,7 @@ // Now initialize the vsync parameters with a valid timebase and a known vsync // interval; which should give us the best frame time estimates. - const base::TimeTicks kBaseTime = tick_clock_->NowTicks(); + const base::TimeTicks kBaseTime = tick_clock_.NowTicks(); OnUpdateVSyncParameters(kBaseTime, kDefaultInterval); ASSERT_EQ(kBaseTime, vsync_timebase()); ASSERT_EQ(kDefaultInterval, vsync_interval()); @@ -3909,7 +3906,7 @@ // the vsync timebase. Advance time by a non integer number of intervals to // verify. const double kElapsedIntervals = 2.5; - tick_clock_->Advance(kDefaultInterval * kElapsedIntervals); + tick_clock_.Advance(kDefaultInterval * kElapsedIntervals); SubmitCompositorFrameAndRelease(); EXPECT_EQ(kBaseTime + kDefaultInterval * std::ceil(kElapsedIntervals), frame_subscriber_->last_present_time());
diff --git a/content/browser/renderer_interface_binders.cc b/content/browser/renderer_interface_binders.cc index 6526538..082e5c9 100644 --- a/content/browser/renderer_interface_binders.cc +++ b/content/browser/renderer_interface_binders.cc
@@ -9,6 +9,7 @@ #include "base/bind.h" #include "content/browser/background_fetch/background_fetch_service_impl.h" #include "content/browser/dedicated_worker/dedicated_worker_host.h" +#include "content/browser/notifications/platform_notification_context_impl.h" #include "content/browser/payments/payment_manager.h" #include "content/browser/permissions/permission_service_context.h" #include "content/browser/renderer_host/render_process_host_impl.h" @@ -27,6 +28,7 @@ #include "services/shape_detection/public/interfaces/constants.mojom.h" #include "services/shape_detection/public/interfaces/facedetection_provider.mojom.h" #include "services/shape_detection/public/interfaces/textdetection.mojom.h" +#include "third_party/WebKit/public/platform/modules/notifications/notification_service.mojom.h" #include "url/origin.h" namespace content { @@ -123,6 +125,13 @@ })); parameterized_binder_registry_.AddInterface( base::Bind(&CreateDedicatedWorkerHostFactory)); + parameterized_binder_registry_.AddInterface( + base::Bind([](blink::mojom::NotificationServiceRequest request, + RenderProcessHost* host, const url::Origin& origin) { + static_cast<StoragePartitionImpl*>(host->GetStoragePartition()) + ->GetPlatformNotificationContext() + ->CreateService(host->GetID(), origin, std::move(request)); + })); } RendererInterfaceBinders& GetRendererInterfaceBinders() {
diff --git a/content/browser/security_exploit_browsertest.cc b/content/browser/security_exploit_browsertest.cc index 933d1ee..503162b 100644 --- a/content/browser/security_exploit_browsertest.cc +++ b/content/browser/security_exploit_browsertest.cc
@@ -124,7 +124,7 @@ request.referrer_policy = blink::kWebReferrerPolicyDefault; request.request_initiator = url::Origin(); request.load_flags = 0; - request.origin_pid = 0; + request.plugin_child_id = -1; request.resource_type = RESOURCE_TYPE_XHR; request.request_context = 0; request.appcache_host_id = kAppCacheNoHostId;
diff --git a/content/browser/service_manager/service_manager_context.cc b/content/browser/service_manager/service_manager_context.cc index 0c0ba18..fb85ee0 100644 --- a/content/browser/service_manager/service_manager_context.cc +++ b/content/browser/service_manager/service_manager_context.cc
@@ -24,6 +24,7 @@ #include "content/browser/browser_main_loop.h" #include "content/browser/child_process_launcher.h" #include "content/browser/gpu/gpu_process_host.h" +#include "content/browser/mus_util.h" #include "content/browser/service_manager/common_browser_interfaces.h" #include "content/browser/utility_process_host_impl.h" #include "content/browser/wake_lock/wake_lock_context_host.h" @@ -65,6 +66,7 @@ #include "services/video_capture/public/cpp/constants.h" #include "services/video_capture/public/interfaces/constants.mojom.h" #include "services/viz/public/interfaces/constants.mojom.h" +#include "ui/base/ui_base_switches_util.h" #include "ui/base/ui_features.h" #if defined(OS_ANDROID) @@ -250,16 +252,21 @@ config.resource_runner = task_runner; config.image_cursors_set_weak_ptr = image_cursors_set_weak_ptr; config.memory_manager = memory_manager; + config.should_host_viz = switches::IsMusHostingViz(); return base::MakeUnique<ui::Service>(&config); } void RegisterUIServiceInProcessIfNecessary( ServiceManagerConnection* connection) { // Some tests don't create BrowserMainLoop. - if (!base::CommandLine::ForCurrentProcess()->HasSwitch("mus") || - !BrowserMainLoop::GetInstance()) { + if (!BrowserMainLoop::GetInstance()) return; - } + // Do not embed the UI service when running in mash. + if (base::CommandLine::ForCurrentProcess()->HasSwitch("mash")) + return; + // Do not embed the UI service if not running with --mus. + if (!IsUsingMus()) + return; service_manager::EmbeddedServiceInfo info; info.factory = base::Bind(
diff --git a/content/browser/service_worker/embedded_worker_test_helper.cc b/content/browser/service_worker/embedded_worker_test_helper.cc index edde602..9bebc03 100644 --- a/content/browser/service_worker/embedded_worker_test_helper.cc +++ b/content/browser/service_worker/embedded_worker_test_helper.cc
@@ -187,11 +187,10 @@ ~MockServiceWorkerEventDispatcher() override {} void DispatchInstallEvent( - mojom::ServiceWorkerInstallEventMethodsAssociatedPtrInfo client, DispatchInstallEventCallback callback) override { if (!helper_) return; - helper_->OnInstallEventStub(std::move(client), std::move(callback)); + helper_->OnInstallEventStub(std::move(callback)); } void DispatchActivateEvent(DispatchActivateEventCallback callback) override { @@ -642,7 +641,6 @@ } void EmbeddedWorkerTestHelper::OnInstallEvent( - mojom::ServiceWorkerInstallEventMethodsAssociatedPtrInfo client, mojom::ServiceWorkerEventDispatcher::DispatchInstallEventCallback callback) { dispatched_events()->push_back(Event::Install); @@ -945,13 +943,11 @@ } void EmbeddedWorkerTestHelper::OnInstallEventStub( - mojom::ServiceWorkerInstallEventMethodsAssociatedPtrInfo client, mojom::ServiceWorkerEventDispatcher::DispatchInstallEventCallback callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::BindOnce(&EmbeddedWorkerTestHelper::OnInstallEvent, AsWeakPtr(), - base::Passed(&client), base::Passed(&callback))); + FROM_HERE, base::BindOnce(&EmbeddedWorkerTestHelper::OnInstallEvent, + AsWeakPtr(), std::move(callback))); } void EmbeddedWorkerTestHelper::OnFetchEventStub(
diff --git a/content/browser/service_worker/embedded_worker_test_helper.h b/content/browser/service_worker/embedded_worker_test_helper.h index 0399e6b..a54fddf 100644 --- a/content/browser/service_worker/embedded_worker_test_helper.h +++ b/content/browser/service_worker/embedded_worker_test_helper.h
@@ -233,7 +233,6 @@ mojom::ServiceWorkerEventDispatcher:: DispatchExtendableMessageEventCallback callback); virtual void OnInstallEvent( - mojom::ServiceWorkerInstallEventMethodsAssociatedPtrInfo client, mojom::ServiceWorkerEventDispatcher::DispatchInstallEventCallback callback); virtual void OnFetchEvent( @@ -341,7 +340,6 @@ mojom::ServiceWorkerEventDispatcher:: DispatchExtendableMessageEventCallback callback); void OnInstallEventStub( - mojom::ServiceWorkerInstallEventMethodsAssociatedPtrInfo client, mojom::ServiceWorkerEventDispatcher::DispatchInstallEventCallback callback); void OnLegacyFetchEventStub(
diff --git a/content/browser/service_worker/foreign_fetch_request_handler.cc b/content/browser/service_worker/foreign_fetch_request_handler.cc deleted file mode 100644 index 6ec227a7..0000000 --- a/content/browser/service_worker/foreign_fetch_request_handler.cc +++ /dev/null
@@ -1,324 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/browser/service_worker/foreign_fetch_request_handler.h" - -#include <string> -#include <utility> - -#include "base/command_line.h" -#include "base/macros.h" -#include "base/memory/ptr_util.h" -#include "base/stl_util.h" -#include "content/browser/service_worker/service_worker_context_wrapper.h" -#include "content/browser/service_worker/service_worker_response_info.h" -#include "content/browser/service_worker/service_worker_url_request_job.h" -#include "content/common/service_worker/service_worker_utils.h" -#include "content/public/browser/content_browser_client.h" -#include "content/public/browser/resource_request_info.h" -#include "content/public/common/content_client.h" -#include "content/public/common/content_switches.h" -#include "content/public/common/origin_trial_policy.h" -#include "content/public/common/resource_request_body.h" -#include "content/public/common/service_worker_modes.h" -#include "net/url_request/url_request.h" -#include "net/url_request/url_request_interceptor.h" -#include "services/network/public/interfaces/fetch_api.mojom.h" -#include "storage/browser/blob/blob_storage_context.h" - -namespace content { - -namespace { - -class ForeignFetchRequestInterceptor : public net::URLRequestInterceptor { - public: - explicit ForeignFetchRequestInterceptor(ResourceContext* resource_context) - : resource_context_(resource_context) {} - ~ForeignFetchRequestInterceptor() override {} - net::URLRequestJob* MaybeInterceptRequest( - net::URLRequest* request, - net::NetworkDelegate* network_delegate) const override { - ForeignFetchRequestHandler* handler = - ForeignFetchRequestHandler::GetHandler(request); - if (!handler) - return nullptr; - return handler->MaybeCreateJob(request, network_delegate, - resource_context_); - } - - private: - ResourceContext* resource_context_; - DISALLOW_COPY_AND_ASSIGN(ForeignFetchRequestInterceptor); -}; - -} // namespace - -// static -int ForeignFetchRequestHandler::user_data_key_; - -bool ForeignFetchRequestHandler::IsForeignFetchEnabled() { - if (base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kEnableExperimentalWebPlatformFeatures)) { - return true; - } - OriginTrialPolicy* origin_trial_policy = - GetContentClient()->GetOriginTrialPolicy(); - return origin_trial_policy && - !origin_trial_policy->IsFeatureDisabled("ForeignFetch"); -} - -void ForeignFetchRequestHandler::InitializeHandler( - net::URLRequest* request, - ServiceWorkerContextWrapper* context_wrapper, - storage::BlobStorageContext* blob_storage_context, - int process_id, - int provider_id, - ServiceWorkerMode service_worker_mode, - network::mojom::FetchRequestMode request_mode, - network::mojom::FetchCredentialsMode credentials_mode, - FetchRedirectMode redirect_mode, - const std::string& integrity, - bool keepalive, - ResourceType resource_type, - RequestContextType request_context_type, - RequestContextFrameType frame_type, - scoped_refptr<ResourceRequestBody> body, - bool initiated_in_secure_context) { - if (!IsForeignFetchEnabled()) - return; - - if (!context_wrapper || !context_wrapper->context() || - provider_id == kInvalidServiceWorkerProviderId) { - return; - } - - if (service_worker_mode == ServiceWorkerMode::NONE) - return; - - if (!initiated_in_secure_context) - return; - - // ServiceWorkerUtils::IsMainResource doesn't consider all worker types to - // be main resources. This code shouldn't handle any main resource requests - // though, so explicitly exclude the extra worker types. - if (ServiceWorkerUtils::IsMainResourceType(resource_type) || - resource_type == RESOURCE_TYPE_WORKER || - resource_type == RESOURCE_TYPE_SERVICE_WORKER) - return; - - if (request->initiator().has_value() && - request->initiator()->IsSameOriginWith( - url::Origin::Create(request->url()))) { - return; - } - - ServiceWorkerProviderHost* provider_host = - context_wrapper->context()->GetProviderHost(process_id, provider_id); - if (!provider_host || !provider_host->IsContextAlive()) - return; - - base::Optional<base::TimeDelta> timeout; - if (provider_host->IsHostToRunningServiceWorker()) { - timeout = base::make_optional( - provider_host->running_hosted_version()->remaining_timeout()); - } - - if (!context_wrapper->OriginHasForeignFetchRegistrations( - request->url().GetOrigin())) { - return; - } - - // Any more precise checks to see if the request should be intercepted are - // asynchronous, so just create our handler in all cases. - std::unique_ptr<ForeignFetchRequestHandler> handler = - base::WrapUnique(new ForeignFetchRequestHandler( - context_wrapper, blob_storage_context->AsWeakPtr(), request_mode, - credentials_mode, redirect_mode, integrity, keepalive, resource_type, - request_context_type, frame_type, body, timeout)); - request->SetUserData(&user_data_key_, std::move(handler)); -} - -ForeignFetchRequestHandler* ForeignFetchRequestHandler::GetHandler( - net::URLRequest* request) { - return static_cast<ForeignFetchRequestHandler*>( - request->GetUserData(&user_data_key_)); -} - -std::unique_ptr<net::URLRequestInterceptor> -ForeignFetchRequestHandler::CreateInterceptor( - ResourceContext* resource_context) { - return std::unique_ptr<net::URLRequestInterceptor>( - new ForeignFetchRequestInterceptor(resource_context)); -} - -ForeignFetchRequestHandler::~ForeignFetchRequestHandler() {} - -net::URLRequestJob* ForeignFetchRequestHandler::MaybeCreateJob( - net::URLRequest* request, - net::NetworkDelegate* network_delegate, - ResourceContext* resource_context) { - ClearJob(); - ServiceWorkerResponseInfo::ResetDataForRequest(request); - - if (!context_) { - // We can't do anything other than to fall back to network. - job_.reset(); - return nullptr; - } - - // This may get called multiple times for original and redirect requests: - // A. original request case: use_network_ is false, no previous location info. - // B. redirect or restarted request case: - // a) use_network_ is false if the previous location was forwarded to SW. - // b) use_network_ is false if the previous location was fallback. - // c) use_network_ is true if additional restart was required to fall back. - - // Fall back to network. (Case B-c) - if (use_network_) { - // TODO(mek): Determine if redirects should be able to be intercepted by - // other foreign fetch service workers. - return nullptr; - } - - // It's for original request (A) or redirect case (B-a or B-b). - DCHECK(!job_.get() || job_->ShouldForwardToServiceWorker()); - - ServiceWorkerURLRequestJob* job = new ServiceWorkerURLRequestJob( - request, network_delegate, std::string(), blob_storage_context_, - resource_context, request_mode_, credentials_mode_, redirect_mode_, - integrity_, keepalive_, resource_type_, request_context_type_, - frame_type_, body_, ServiceWorkerFetchType::FOREIGN_FETCH, timeout_, - this); - job_ = job->GetWeakPtr(); - resource_context_ = resource_context; - - context_->FindReadyRegistrationForDocument( - request->url(), - base::Bind(&ForeignFetchRequestHandler::DidFindRegistration, - weak_factory_.GetWeakPtr(), job_)); - - return job_.get(); -} - -ForeignFetchRequestHandler::ForeignFetchRequestHandler( - ServiceWorkerContextWrapper* context, - base::WeakPtr<storage::BlobStorageContext> blob_storage_context, - network::mojom::FetchRequestMode request_mode, - network::mojom::FetchCredentialsMode credentials_mode, - FetchRedirectMode redirect_mode, - const std::string& integrity, - bool keepalive, - ResourceType resource_type, - RequestContextType request_context_type, - RequestContextFrameType frame_type, - scoped_refptr<ResourceRequestBody> body, - const base::Optional<base::TimeDelta>& timeout) - : context_(context), - blob_storage_context_(blob_storage_context), - resource_type_(resource_type), - request_mode_(request_mode), - credentials_mode_(credentials_mode), - redirect_mode_(redirect_mode), - integrity_(integrity), - keepalive_(keepalive), - request_context_type_(request_context_type), - frame_type_(frame_type), - body_(body), - timeout_(timeout), - weak_factory_(this) {} - -void ForeignFetchRequestHandler::DidFindRegistration( - const base::WeakPtr<ServiceWorkerURLRequestJob>& job, - ServiceWorkerStatusCode status, - scoped_refptr<ServiceWorkerRegistration> registration) { - if (!job || job.get() != job_.get()) { - // No more job to handle, or job changed somehow, so just return. - return; - } - - if (status != SERVICE_WORKER_OK || !job->request()) { - job->FallbackToNetwork(); - return; - } - - ServiceWorkerVersion* active_version = registration->active_version(); - DCHECK(active_version); - - const GURL& request_url = job->request()->url(); - bool scope_matches = false; - for (const GURL& scope : active_version->foreign_fetch_scopes()) { - if (ServiceWorkerUtils::ScopeMatches(scope, request_url)) { - scope_matches = true; - break; - } - } - - const url::Origin& request_origin = job->request()->initiator().value(); - bool origin_matches = active_version->foreign_fetch_origins().empty(); - for (const url::Origin& origin : active_version->foreign_fetch_origins()) { - if (request_origin.IsSameOriginWith(origin)) - origin_matches = true; - } - - if (!scope_matches || !origin_matches) { - job->FallbackToNetwork(); - return; - } - - if (!IsForeignFetchEnabled() && !CheckOriginTrialToken(active_version)) { - job->FallbackToNetwork(); - return; - } - - auto* request_info = ResourceRequestInfo::ForRequest(job->request()); - base::Callback<WebContents*(void)> web_contents_getter; - if (request_info) - web_contents_getter = request_info->GetWebContentsGetterForRequest(); - - if (!GetContentClient()->browser()->AllowServiceWorker( - registration->pattern(), job->request()->site_for_cookies(), - resource_context_, web_contents_getter)) { - job->FallbackToNetwork(); - return; - } - - target_worker_ = active_version; - job->ForwardToServiceWorker(); -} - -void ForeignFetchRequestHandler::OnPrepareToRestart() { - use_network_ = true; - ClearJob(); -} - -ServiceWorkerVersion* ForeignFetchRequestHandler::GetServiceWorkerVersion( - ServiceWorkerMetrics::URLRequestJobResult* result) { - // TODO(mek): Figure out what should happen if the active worker changes or - // gets uninstalled before this point is reached. - if (!target_worker_) { - *result = ServiceWorkerMetrics::REQUEST_JOB_ERROR_NO_ACTIVE_VERSION; - return nullptr; - } - return target_worker_.get(); -} - -void ForeignFetchRequestHandler::ClearJob() { - job_.reset(); - target_worker_ = nullptr; - resource_context_ = nullptr; -} - -// static -bool ForeignFetchRequestHandler::CheckOriginTrialToken( - const ServiceWorkerVersion* const active_version) { - // The worker entry in the database was written by old version Chrome (< M56) - // and the main script was not loaded yet. In this case, we can't check the - // origin trial token. - if (!active_version->origin_trial_tokens()) - return true; - const auto& token_map = *active_version->origin_trial_tokens(); - return base::ContainsKey(token_map, "ForeignFetch"); -} - -} // namespace content
diff --git a/content/browser/service_worker/foreign_fetch_request_handler.h b/content/browser/service_worker/foreign_fetch_request_handler.h deleted file mode 100644 index 441ab36..0000000 --- a/content/browser/service_worker/foreign_fetch_request_handler.h +++ /dev/null
@@ -1,158 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_BROWSER_SERVICE_WORKER_FOREIGN_FETCH_REQUEST_HANDLER_H_ -#define CONTENT_BROWSER_SERVICE_WORKER_FOREIGN_FETCH_REQUEST_HANDLER_H_ - -#include "base/macros.h" -#include "base/memory/weak_ptr.h" -#include "base/optional.h" -#include "base/supports_user_data.h" -#include "base/time/time.h" -#include "content/browser/service_worker/service_worker_url_request_job.h" -#include "content/common/content_export.h" -#include "content/common/service_worker/service_worker_status_code.h" -#include "content/public/common/request_context_frame_type.h" -#include "content/public/common/request_context_type.h" -#include "content/public/common/resource_type.h" -#include "content/public/common/service_worker_modes.h" -#include "net/url_request/url_request_job_factory.h" -#include "services/network/public/interfaces/fetch_api.mojom.h" - -namespace net { -class NetworkDelegate; -class URLRequest; -class URLRequestInterceptor; -} - -namespace storage { -class BlobStorageContext; -} - -namespace content { - -class ResourceContext; -class ResourceRequestBody; -class ServiceWorkerContextWrapper; -class ServiceWorkerRegistration; - -// Class for routing network requests to ServiceWorkers for foreign fetch -// events. Created one per URLRequest and attached to each request. -// TODO(mek): Does this need something similar to ServiceWorkerRequestHandler's -// GetExtraResponseInfo method? -class CONTENT_EXPORT ForeignFetchRequestHandler - : public base::SupportsUserData::Data, - public ServiceWorkerURLRequestJob::Delegate { - public: - // Returns true if Foreign Fetch is enabled. Foreign Fetch is considered to be - // enabled if an OriginTrialPolicy exists, and that policy doesn't disable the - // feature. When the policy does disable the feature, that can be overridden - // with the experimental web platform features command line flag. - static bool IsForeignFetchEnabled(); - - // Attaches a newly created handler if the given |request| needs to - // be handled by a foreign fetch handling ServiceWorker. - static void InitializeHandler( - net::URLRequest* request, - ServiceWorkerContextWrapper* context_wrapper, - storage::BlobStorageContext* blob_storage_context, - int process_id, - int provider_id, - ServiceWorkerMode service_worker_mode, - network::mojom::FetchRequestMode request_mode, - network::mojom::FetchCredentialsMode credentials_mode, - FetchRedirectMode redirect_mode, - const std::string& integrity, - bool keepalive, - ResourceType resource_type, - RequestContextType request_context_type, - RequestContextFrameType frame_type, - scoped_refptr<ResourceRequestBody> body, - bool initiated_in_secure_context); - - // Returns the handler attached to |request|. This may return null - // if no handler is attached. - static ForeignFetchRequestHandler* GetHandler(net::URLRequest* request); - - // Creates a protocol interceptor for foreign fetch. - static std::unique_ptr<net::URLRequestInterceptor> CreateInterceptor( - ResourceContext* resource_context); - - ~ForeignFetchRequestHandler() override; - - // Called via custom URLRequestJobFactory. - net::URLRequestJob* MaybeCreateJob(net::URLRequest* request, - net::NetworkDelegate* network_delegate, - ResourceContext* resource_context); - - private: - friend class ForeignFetchRequestHandlerTest; - - ForeignFetchRequestHandler( - ServiceWorkerContextWrapper* context, - base::WeakPtr<storage::BlobStorageContext> blob_storage_context, - network::mojom::FetchRequestMode request_mode, - network::mojom::FetchCredentialsMode credentials_mode, - FetchRedirectMode redirect_mode, - const std::string& integrity, - bool keepalive, - ResourceType resource_type, - RequestContextType request_context_type, - RequestContextFrameType frame_type, - scoped_refptr<ResourceRequestBody> body, - const base::Optional<base::TimeDelta>& timeout); - - // Called when a ServiceWorkerRegistration has (or hasn't) been found for the - // request being handled. - void DidFindRegistration( - const base::WeakPtr<ServiceWorkerURLRequestJob>& job, - ServiceWorkerStatusCode status, - scoped_refptr<ServiceWorkerRegistration> registration); - - // ServiceWorkerURLRequestJob::Delegate implementation: - void OnPrepareToRestart() override; - ServiceWorkerVersion* GetServiceWorkerVersion( - ServiceWorkerMetrics::URLRequestJobResult* result) override; - - // Sets |job_| to nullptr, and clears all extra response info associated with - // that job. - void ClearJob(); - - // Returns true if the version doesn't have origin_trial_tokens entry (this - // happens if the existing worker's entry in the database was written by old - // version (< M56) Chrome), or the version has valid Origin Trial token. - static bool CheckOriginTrialToken( - const ServiceWorkerVersion* const active_version); - - scoped_refptr<ServiceWorkerContextWrapper> context_; - base::WeakPtr<storage::BlobStorageContext> blob_storage_context_; - ResourceType resource_type_; - network::mojom::FetchRequestMode request_mode_; - network::mojom::FetchCredentialsMode credentials_mode_; - FetchRedirectMode redirect_mode_; - std::string integrity_; - const bool keepalive_; - RequestContextType request_context_type_; - RequestContextFrameType frame_type_; - scoped_refptr<ResourceRequestBody> body_; - ResourceContext* resource_context_; - base::Optional<base::TimeDelta> timeout_; - - base::WeakPtr<ServiceWorkerURLRequestJob> job_; - scoped_refptr<ServiceWorkerVersion> target_worker_; - - // True if the next time this request is started, the response should be - // delivered from the network, bypassing the ServiceWorker. - bool use_network_ = false; - - base::WeakPtrFactory<ForeignFetchRequestHandler> weak_factory_; - - static int user_data_key_; // Only address is used. - - DISALLOW_COPY_AND_ASSIGN(ForeignFetchRequestHandler); -}; - -} // namespace content - -#endif // CONTENT_BROWSER_SERVICE_WORKER_FOREIGN_FETCH_REQUEST_HANDLER_H_
diff --git a/content/browser/service_worker/foreign_fetch_request_handler_unittest.cc b/content/browser/service_worker/foreign_fetch_request_handler_unittest.cc deleted file mode 100644 index 5502881..0000000 --- a/content/browser/service_worker/foreign_fetch_request_handler_unittest.cc +++ /dev/null
@@ -1,408 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/browser/service_worker/foreign_fetch_request_handler.h" - -#include "base/bind_helpers.h" -#include "base/memory/ptr_util.h" -#include "base/run_loop.h" -#include "base/test/simple_test_clock.h" -#include "base/test/simple_test_tick_clock.h" -#include "content/browser/browser_thread_impl.h" -#include "content/browser/service_worker/embedded_worker_test_helper.h" -#include "content/browser/service_worker/service_worker_context_core.h" -#include "content/browser/service_worker/service_worker_registration.h" -#include "content/browser/service_worker/service_worker_test_utils.h" -#include "content/browser/service_worker/service_worker_version.h" -#include "content/common/service_worker/service_worker_utils.h" -#include "content/public/common/content_client.h" -#include "content/public/common/origin_trial_policy.h" -#include "content/public/test/test_browser_thread_bundle.h" -#include "content/test/test_content_browser_client.h" -#include "net/http/http_response_info.h" -#include "net/test/cert_test_util.h" -#include "net/test/test_data_directory.h" -#include "net/traffic_annotation/network_traffic_annotation_test_helper.h" -#include "net/url_request/url_request_context.h" -#include "net/url_request/url_request_test_util.h" -#include "storage/browser/blob/blob_storage_context.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "third_party/WebKit/public/platform/modules/serviceworker/service_worker_registration.mojom.h" - -namespace content { - -namespace { - -// This is a sample public key for testing the API. The corresponding private -// key (use this to generate new samples for this test file) is: -// -// 0x83, 0x67, 0xf4, 0xcd, 0x2a, 0x1f, 0x0e, 0x04, 0x0d, 0x43, 0x13, -// 0x4c, 0x67, 0xc4, 0xf4, 0x28, 0xc9, 0x90, 0x15, 0x02, 0xe2, 0xba, -// 0xfd, 0xbb, 0xfa, 0xbc, 0x92, 0x76, 0x8a, 0x2c, 0x4b, 0xc7, 0x75, -// 0x10, 0xac, 0xf9, 0x3a, 0x1c, 0xb8, 0xa9, 0x28, 0x70, 0xd2, 0x9a, -// 0xd0, 0x0b, 0x59, 0xe1, 0xac, 0x2b, 0xb7, 0xd5, 0xca, 0x1f, 0x64, -// 0x90, 0x08, 0x8e, 0xa8, 0xe0, 0x56, 0x3a, 0x04, 0xd0 -const uint8_t kTestPublicKey[] = { - 0x75, 0x10, 0xac, 0xf9, 0x3a, 0x1c, 0xb8, 0xa9, 0x28, 0x70, 0xd2, - 0x9a, 0xd0, 0x0b, 0x59, 0xe1, 0xac, 0x2b, 0xb7, 0xd5, 0xca, 0x1f, - 0x64, 0x90, 0x08, 0x8e, 0xa8, 0xe0, 0x56, 0x3a, 0x04, 0xd0, -}; - -int kMockProviderId = 1; - -const char* kValidUrl = "https://valid.example.com/foo/bar"; - -// This timestamp is set to a time after the expiry timestamp of the expired -// tokens in this test, but before the expiry timestamp of the valid ones. -double kNowTimestamp = 1500000000; - -} // namespace - -class ForeignFetchRequestHandlerTest : public testing::Test { - public: - ForeignFetchRequestHandlerTest() - : browser_thread_bundle_(TestBrowserThreadBundle::IO_MAINLOOP) { - SetContentClient(&test_content_client_); - SetBrowserClientForTesting(&test_content_browser_client_); - } - ~ForeignFetchRequestHandlerTest() override {} - - void SetUp() override { - const GURL kScope("https://valid.example.com/scope/"); - const GURL kResource1("https://valid.example.com/scope/sw.js"); - const int64_t kRegistrationId = 0; - const int64_t kVersionId = 0; - helper_.reset(new EmbeddedWorkerTestHelper(base::FilePath())); - - // Create a registration for the worker which has foreign fetch event - // handler. - registration_ = new ServiceWorkerRegistration( - blink::mojom::ServiceWorkerRegistrationOptions(kScope), kRegistrationId, - context()->AsWeakPtr()); - version_ = new ServiceWorkerVersion(registration_.get(), kResource1, - kVersionId, context()->AsWeakPtr()); - version_->set_foreign_fetch_scopes({kScope}); - - // Fix the time for testing to kNowTimestamp - std::unique_ptr<base::SimpleTestClock> clock = - std::make_unique<base::SimpleTestClock>(); - clock->SetNow(base::Time::FromDoubleT(kNowTimestamp)); - version_->SetClockForTesting(std::move(clock)); - - context()->storage()->LazyInitializeForTest( - base::BindOnce(&base::DoNothing)); - base::RunLoop().RunUntilIdle(); - - // Persist the registration data. - std::vector<ServiceWorkerDatabase::ResourceRecord> records; - records.push_back(WriteToDiskCacheSync( - context()->storage(), version_->script_url(), 10, {} /* headers */, - "I'm the body", "I'm the meta data")); - version_->script_cache_map()->SetResources(records); - version_->set_fetch_handler_existence( - ServiceWorkerVersion::FetchHandlerExistence::EXISTS); - version_->SetStatus(ServiceWorkerVersion::ACTIVATED); - registration_->SetActiveVersion(version_); - context()->storage()->StoreRegistration( - registration_.get(), version_.get(), - base::Bind(&ServiceWorkerUtils::NoOpStatusCallback)); - base::RunLoop().RunUntilIdle(); - } - - void TearDown() override { - version_ = nullptr; - registration_ = nullptr; - helper_.reset(); - base::RunLoop().RunUntilIdle(); - } - - protected: - ServiceWorkerContextCore* context() const { return helper_->context(); } - ServiceWorkerContextWrapper* context_wrapper() const { - return helper_->context_wrapper(); - } - ServiceWorkerProviderHost* provider_host() const { - return provider_host_.get(); - } - - bool CheckOriginTrialToken(const ServiceWorkerVersion* const version) const { - return ForeignFetchRequestHandler::CheckOriginTrialToken(version); - } - - base::Optional<base::TimeDelta> timeout_for_request( - ForeignFetchRequestHandler* handler) { - return handler->timeout_; - } - - ServiceWorkerVersion* version() const { return version_.get(); } - - static std::unique_ptr<net::HttpResponseInfo> CreateTestHttpResponseInfo() { - std::unique_ptr<net::HttpResponseInfo> http_info( - std::make_unique<net::HttpResponseInfo>()); - http_info->ssl_info.cert = - net::ImportCertFromFile(net::GetTestCertsDirectory(), "ok_cert.pem"); - DCHECK(http_info->ssl_info.is_valid()); - http_info->ssl_info.security_bits = 0x100; - // SSL3 TLS_DHE_RSA_WITH_AES_256_CBC_SHA - http_info->ssl_info.connection_status = 0x300039; - http_info->headers = base::MakeRefCounted<net::HttpResponseHeaders>(""); - return http_info; - } - - ForeignFetchRequestHandler* InitializeHandler(const std::string& url, - ResourceType resource_type, - const char* initiator) { - request_ = url_request_context_.CreateRequest( - GURL(url), net::DEFAULT_PRIORITY, &url_request_delegate_, - TRAFFIC_ANNOTATION_FOR_TESTS); - if (initiator) - request_->set_initiator(url::Origin::Create(GURL(initiator))); - ForeignFetchRequestHandler::InitializeHandler( - request_.get(), context_wrapper(), &blob_storage_context_, - helper_->mock_render_process_id(), provider_host()->provider_id(), - ServiceWorkerMode::ALL, network::mojom::FetchRequestMode::kCORS, - network::mojom::FetchCredentialsMode::kOmit, - FetchRedirectMode::FOLLOW_MODE, std::string() /* integrity */, - false /* keepalive */, resource_type, REQUEST_CONTEXT_TYPE_FETCH, - REQUEST_CONTEXT_FRAME_TYPE_NONE, nullptr, - true /* initiated_in_secure_context */); - - return ForeignFetchRequestHandler::GetHandler(request_.get()); - } - - void CreateWindowTypeProviderHost() { - remote_endpoints_.emplace_back(); - std::unique_ptr<ServiceWorkerProviderHost> host = - CreateProviderHostForWindow( - helper_->mock_render_process_id(), kMockProviderId, - true /* is_parent_frame_secure */, helper_->context()->AsWeakPtr(), - &remote_endpoints_.back()); - EXPECT_FALSE( - context()->GetProviderHost(host->process_id(), host->provider_id())); - host->SetDocumentUrl(GURL("https://host/scope/")); - provider_host_ = host->AsWeakPtr(); - context()->AddProviderHost(std::move(host)); - } - - void CreateServiceWorkerTypeProviderHost() { - // Create another worker whose requests will be intercepted by the foreign - // fetch event handler. - scoped_refptr<ServiceWorkerRegistration> registration = - new ServiceWorkerRegistration( - blink::mojom::ServiceWorkerRegistrationOptions( - GURL("https://host/scope")), - 1L, context()->AsWeakPtr()); - scoped_refptr<ServiceWorkerVersion> version = new ServiceWorkerVersion( - registration.get(), GURL("https://host/script.js"), 1L, - context()->AsWeakPtr()); - - std::vector<ServiceWorkerDatabase::ResourceRecord> records; - records.push_back( - ServiceWorkerDatabase::ResourceRecord(10, version->script_url(), 100)); - version->script_cache_map()->SetResources(records); - version->set_fetch_handler_existence( - ServiceWorkerVersion::FetchHandlerExistence::EXISTS); - version->SetStatus(ServiceWorkerVersion::ACTIVATED); - registration->SetActiveVersion(version); - context()->storage()->StoreRegistration( - registration.get(), version.get(), - base::Bind(&ServiceWorkerUtils::NoOpStatusCallback)); - base::RunLoop().RunUntilIdle(); - - remote_endpoints_.emplace_back(); - std::unique_ptr<ServiceWorkerProviderHost> host = - CreateProviderHostForServiceWorkerContext( - helper_->mock_render_process_id(), - true /* is_parent_frame_secure */, version.get(), - helper_->context()->AsWeakPtr(), &remote_endpoints_.back()); - EXPECT_FALSE( - context()->GetProviderHost(host->process_id(), host->provider_id())); - provider_host_ = host->AsWeakPtr(); - context()->AddProviderHost(std::move(host)); - } - - private: - class TestContentClient : public ContentClient { - public: - // ContentRendererClient methods - OriginTrialPolicy* GetOriginTrialPolicy() override { - return &origin_trial_policy_; - } - - private: - class TestOriginTrialPolicy : public OriginTrialPolicy { - public: - base::StringPiece GetPublicKey() const override { - return base::StringPiece(reinterpret_cast<const char*>(kTestPublicKey), - arraysize(kTestPublicKey)); - } - }; - - TestOriginTrialPolicy origin_trial_policy_; - }; - - scoped_refptr<ServiceWorkerRegistration> registration_; - scoped_refptr<ServiceWorkerVersion> version_; - TestContentClient test_content_client_; - TestContentBrowserClient test_content_browser_client_; - std::unique_ptr<EmbeddedWorkerTestHelper> helper_; - TestBrowserThreadBundle browser_thread_bundle_; - - net::URLRequestContext url_request_context_; - net::TestDelegate url_request_delegate_; - base::WeakPtr<ServiceWorkerProviderHost> provider_host_; - storage::BlobStorageContext blob_storage_context_; - std::unique_ptr<net::URLRequest> request_; - std::vector<ServiceWorkerRemoteProviderEndpoint> remote_endpoints_; - - DISALLOW_COPY_AND_ASSIGN(ForeignFetchRequestHandlerTest); -}; - -TEST_F(ForeignFetchRequestHandlerTest, CheckOriginTrialToken_NoToken) { - CreateWindowTypeProviderHost(); - EXPECT_TRUE(CheckOriginTrialToken(version())); - std::unique_ptr<net::HttpResponseInfo> http_info( - CreateTestHttpResponseInfo()); - version()->SetMainScriptHttpResponseInfo(*http_info); - EXPECT_FALSE(CheckOriginTrialToken(version())); -} - -TEST_F(ForeignFetchRequestHandlerTest, CheckOriginTrialToken_ValidToken) { - CreateWindowTypeProviderHost(); - EXPECT_TRUE(CheckOriginTrialToken(version())); - std::unique_ptr<net::HttpResponseInfo> http_info( - CreateTestHttpResponseInfo()); - const std::string kOriginTrial("Origin-Trial: "); - // Token for ForeignFetch which expires 2033-05-18. - // generate_token.py valid.example.com ForeignFetch - // --expire-timestamp=2000000000 - // TODO(horo): Generate this sample token during the build. - const std::string kFeatureToken( - "AsDmvl17hoVfq9G6OT0VEhX28Nnl0VnbGZJoG6XFzosIamNfxNJ28m40PRA3PtFv3BfOlRe1" - "5bLrEZhtICdDnwwAAABceyJvcmlnaW4iOiAiaHR0cHM6Ly92YWxpZC5leGFtcGxlLmNvbTo0" - "NDMiLCAiZmVhdHVyZSI6ICJGb3JlaWduRmV0Y2giLCAiZXhwaXJ5IjogMjAwMDAwMDAwMH0" - "="); - http_info->headers->AddHeader(kOriginTrial + kFeatureToken); - version()->SetMainScriptHttpResponseInfo(*http_info); - EXPECT_TRUE(CheckOriginTrialToken(version())); -} - -TEST_F(ForeignFetchRequestHandlerTest, CheckOriginTrialToken_InvalidToken) { - CreateWindowTypeProviderHost(); - EXPECT_TRUE(CheckOriginTrialToken(version())); - std::unique_ptr<net::HttpResponseInfo> http_info( - CreateTestHttpResponseInfo()); - const std::string kOriginTrial("Origin-Trial: "); - // Token for FooBar which expires 2033-05-18. - // generate_token.py valid.example.com FooBar - // --expire-timestamp=2000000000 - // TODO(horo): Generate this sample token during the build. - const std::string kFeatureToken( - "AqwtRpuoLdc6MKSFH8TbzoLFvLouL8VXTv6OJIqQvRtJBynRMbAbFwjUlcwMuj4pXUBbquBj" - "zj/w/d1H/ZsOcQIAAABWeyJvcmlnaW4iOiAiaHR0cHM6Ly92YWxpZC5leGFtcGxlLmNvbTo0" - "NDMiLCAiZmVhdHVyZSI6ICJGb29CYXIiLCAiZXhwaXJ5IjogMjAwMDAwMDAwMH0="); - http_info->headers->AddHeader(kOriginTrial + kFeatureToken); - version()->SetMainScriptHttpResponseInfo(*http_info); - EXPECT_FALSE(CheckOriginTrialToken(version())); -} - -TEST_F(ForeignFetchRequestHandlerTest, CheckOriginTrialToken_ExpiredToken) { - CreateWindowTypeProviderHost(); - EXPECT_TRUE(CheckOriginTrialToken(version())); - std::unique_ptr<net::HttpResponseInfo> http_info( - CreateTestHttpResponseInfo()); - const std::string kOriginTrial("Origin-Trial: "); - // Token for ForeignFetch which expired 2001-09-09. - // generate_token.py valid.example.com ForeignFetch - // --expire-timestamp=1000000000 - const std::string kFeatureToken( - "AgBgj4Zhwzn85LJw7rzh4ZFRFqp49+9Es2SrCwZdDcoqtqQEjbvui4SKLn6GqMpr4DynGfJh" - "tIy9dpOuK8PVTwkAAABceyJvcmlnaW4iOiAiaHR0cHM6Ly92YWxpZC5leGFtcGxlLmNvbTo0" - "NDMiLCAiZmVhdHVyZSI6ICJGb3JlaWduRmV0Y2giLCAiZXhwaXJ5IjogMTAwMDAwMDAwMH0" - "="); - http_info->headers->AddHeader(kOriginTrial + kFeatureToken); - version()->SetMainScriptHttpResponseInfo(*http_info); - EXPECT_FALSE(CheckOriginTrialToken(version())); -} - -TEST_F(ForeignFetchRequestHandlerTest, InitializeHandler_Success) { - CreateWindowTypeProviderHost(); - EXPECT_TRUE(InitializeHandler(kValidUrl, RESOURCE_TYPE_IMAGE, - nullptr /* initiator */)); -} - -TEST_F(ForeignFetchRequestHandlerTest, InitializeHandler_WrongResourceType) { - CreateWindowTypeProviderHost(); - EXPECT_FALSE(InitializeHandler(kValidUrl, RESOURCE_TYPE_MAIN_FRAME, - nullptr /* initiator */)); - EXPECT_FALSE(InitializeHandler(kValidUrl, RESOURCE_TYPE_SUB_FRAME, - nullptr /* initiator */)); - EXPECT_FALSE(InitializeHandler(kValidUrl, RESOURCE_TYPE_WORKER, - nullptr /* initiator */)); - EXPECT_FALSE(InitializeHandler(kValidUrl, RESOURCE_TYPE_SHARED_WORKER, - nullptr /* initiator */)); - EXPECT_FALSE(InitializeHandler(kValidUrl, RESOURCE_TYPE_SERVICE_WORKER, - nullptr /* initiator */)); -} - -TEST_F(ForeignFetchRequestHandlerTest, InitializeHandler_SameOriginRequest) { - CreateWindowTypeProviderHost(); - EXPECT_FALSE(InitializeHandler(kValidUrl, RESOURCE_TYPE_IMAGE, - kValidUrl /* initiator */)); -} - -TEST_F(ForeignFetchRequestHandlerTest, InitializeHandler_NoRegisteredHandlers) { - CreateWindowTypeProviderHost(); - EXPECT_FALSE(InitializeHandler("https://invalid.example.com/foo", - RESOURCE_TYPE_IMAGE, nullptr /* initiator */)); -} - -TEST_F(ForeignFetchRequestHandlerTest, - InitializeHandler_TimeoutBehaviorForWindow) { - CreateWindowTypeProviderHost(); - ForeignFetchRequestHandler* handler = - InitializeHandler("https://valid.example.com/foo", RESOURCE_TYPE_IMAGE, - nullptr /* initiator */); - ASSERT_TRUE(handler); - - EXPECT_EQ(base::nullopt, timeout_for_request(handler)); -} - -TEST_F(ForeignFetchRequestHandlerTest, - InitializeHandler_TimeoutBehaviorForServiceWorker) { - CreateServiceWorkerTypeProviderHost(); - ServiceWorkerVersion* version = provider_host()->running_hosted_version(); - std::unique_ptr<net::HttpResponseInfo> http_info( - CreateTestHttpResponseInfo()); - version->SetMainScriptHttpResponseInfo(*http_info); - - // Set mock clock on version to check timeout behavior. - base::SimpleTestTickClock* tick_clock = new base::SimpleTestTickClock(); - tick_clock->SetNowTicks(base::TimeTicks::Now()); - version->SetTickClockForTesting(base::WrapUnique(tick_clock)); - - // Make sure worker has a non-zero timeout. - version->StartWorker(ServiceWorkerMetrics::EventType::UNKNOWN, - base::BindOnce(&ServiceWorkerUtils::NoOpStatusCallback)); - base::RunLoop().RunUntilIdle(); - version->StartRequestWithCustomTimeout( - ServiceWorkerMetrics::EventType::ACTIVATE, - base::BindOnce(&ServiceWorkerUtils::NoOpStatusCallback), - base::TimeDelta::FromSeconds(10), ServiceWorkerVersion::KILL_ON_TIMEOUT); - - // Advance clock by a couple seconds. - tick_clock->Advance(base::TimeDelta::FromSeconds(4)); - base::TimeDelta remaining_time = version->remaining_timeout(); - EXPECT_EQ(base::TimeDelta::FromSeconds(6), remaining_time); - - // Make sure new request only gets remaining timeout. - ForeignFetchRequestHandler* handler = - InitializeHandler("https://valid.example.com/foo", RESOURCE_TYPE_IMAGE, - nullptr /* initiator */); - ASSERT_TRUE(handler); - ASSERT_TRUE(timeout_for_request(handler).has_value()); - EXPECT_EQ(remaining_time, timeout_for_request(handler).value()); -} - -} // namespace content
diff --git a/content/browser/service_worker/link_header_support.cc b/content/browser/service_worker/link_header_support.cc deleted file mode 100644 index 3dee66b..0000000 --- a/content/browser/service_worker/link_header_support.cc +++ /dev/null
@@ -1,177 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/browser/service_worker/link_header_support.h" - -#include "base/command_line.h" -#include "base/strings/string_split.h" -#include "base/strings/string_util.h" -#include "base/time/time.h" -#include "components/link_header_util/link_header_util.h" -#include "content/browser/loader/resource_message_filter.h" -#include "content/browser/loader/resource_request_info_impl.h" -#include "content/browser/service_worker/service_worker_context_wrapper.h" -#include "content/browser/service_worker/service_worker_request_handler.h" -#include "content/common/origin_trials/trial_policy_impl.h" -#include "content/common/service_worker/service_worker_utils.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/browser/content_browser_client.h" -#include "content/public/common/browser_side_navigation_policy.h" -#include "content/public/common/content_client.h" -#include "content/public/common/content_switches.h" -#include "content/public/common/origin_util.h" -#include "net/http/http_util.h" -#include "net/url_request/url_request.h" -#include "third_party/WebKit/common/origin_trials/trial_token_validator.h" - -namespace content { - -namespace { - -void RegisterServiceWorkerFinished(int64_t trace_id, bool result) { - TRACE_EVENT_ASYNC_END1("ServiceWorker", - "LinkHeaderResourceThrottle::HandleServiceWorkerLink", - trace_id, "Success", result); -} - -void HandleServiceWorkerLink( - net::URLRequest* request, - const std::string& url, - const std::unordered_map<std::string, base::Optional<std::string>>& params, - const blink::TrialTokenValidator& validator, - ServiceWorkerContextWrapper* service_worker_context_for_testing) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - - if (!base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kEnableExperimentalWebPlatformFeatures) && - !validator.RequestEnablesFeature(request, "ForeignFetch", - base::Time::Now())) { - // TODO(mek): Log attempt to use without having correct token? - return; - } - - if (ContainsKey(params, "anchor")) - return; - - ResourceRequestInfoImpl* request_info = - ResourceRequestInfoImpl::ForRequest(request); - ServiceWorkerContext* service_worker_context = - service_worker_context_for_testing - ? service_worker_context_for_testing - : request_info->requester_info()->service_worker_context(); - - if (!service_worker_context) - return; - - ServiceWorkerProviderHost* provider_host = - ServiceWorkerRequestHandler::GetProviderHost(request); - - // If fetched from a service worker, make sure fetching service worker is - // controlling at least one client to prevent a service worker from spawning - // new service workers in the background. - if (provider_host && provider_host->IsHostToRunningServiceWorker()) { - if (!provider_host->running_hosted_version()->HasControllee()) - return; - } - - if (ServiceWorkerUtils::IsMainResourceType(request_info->GetResourceType())) { - // In case of navigations, make sure the navigation will actually result in - // a secure context. - if (!provider_host || !provider_host->IsContextSecureForServiceWorker()) - return; - } else { - // If this is not a navigation, make sure the request was initiated from a - // secure context. - if (!request_info->initiated_in_secure_context()) - return; - } - - // TODO(mek): support for a serviceworker link on a request that wouldn't ever - // be able to be intercepted by a serviceworker isn't very useful, so this - // should share logic with ServiceWorkerRequestHandler and - // ForeignFetchRequestHandler to limit the requests for which serviceworker - // links are processed. - - GURL context_url = request->url(); - GURL script_url = context_url.Resolve(url); - auto scope_param = params.find("scope"); - GURL scope_url = scope_param == params.end() - ? script_url.Resolve("./") - : context_url.Resolve(scope_param->second.value_or("")); - - if (!context_url.is_valid() || !script_url.is_valid() || - !scope_url.is_valid()) - return; - if (!ServiceWorkerUtils::AllOriginsMatchAndCanAccessServiceWorkers( - {context_url, scope_url, script_url})) { - return; - } - std::string error; - if (ServiceWorkerUtils::ContainsDisallowedCharacter(scope_url, script_url, - &error)) - return; - - if (!GetContentClient()->browser()->AllowServiceWorker( - scope_url, request->site_for_cookies(), request_info->GetContext(), - request_info->GetWebContentsGetterForRequest())) - return; - - static int64_t trace_id = 0; - TRACE_EVENT_ASYNC_BEGIN2( - "ServiceWorker", "LinkHeaderResourceThrottle::HandleServiceWorkerLink", - ++trace_id, "Pattern", scope_url.spec(), "Script URL", script_url.spec()); - service_worker_context->RegisterServiceWorker( - scope_url, script_url, - base::Bind(&RegisterServiceWorkerFinished, trace_id)); -} - -void ProcessLinkHeaderValueForRequest( - net::URLRequest* request, - std::string::const_iterator value_begin, - std::string::const_iterator value_end, - ServiceWorkerContextWrapper* service_worker_context_for_testing) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - - std::string url; - std::unordered_map<std::string, base::Optional<std::string>> params; - if (!link_header_util::ParseLinkHeaderValue(value_begin, value_end, &url, - ¶ms)) - return; - - auto rel_param = params.find("rel"); - if (rel_param == params.end() || !rel_param->second) - return; - - const auto validator = TrialPolicyImpl::CreateValidatorForPolicy(); - for (const auto& rel : base::SplitStringPiece(rel_param->second.value(), - HTTP_LWS, base::TRIM_WHITESPACE, - base::SPLIT_WANT_NONEMPTY)) { - if (base::EqualsCaseInsensitiveASCII(rel, "serviceworker")) - HandleServiceWorkerLink(request, url, params, *validator, - service_worker_context_for_testing); - } -} - -} // namespace - -void ProcessRequestForLinkHeaders(net::URLRequest* request) { - std::string link_header; - request->GetResponseHeaderByName("link", &link_header); - if (link_header.empty()) - return; - - ProcessLinkHeaderForRequest(request, link_header); -} - -void ProcessLinkHeaderForRequest( - net::URLRequest* request, - const std::string& link_header, - ServiceWorkerContextWrapper* service_worker_context_for_testing) { - for (const auto& value : link_header_util::SplitLinkHeader(link_header)) { - ProcessLinkHeaderValueForRequest(request, value.first, value.second, - service_worker_context_for_testing); - } -} - -} // namespace content
diff --git a/content/browser/service_worker/link_header_support.h b/content/browser/service_worker/link_header_support.h deleted file mode 100644 index b57dfbf..0000000 --- a/content/browser/service_worker/link_header_support.h +++ /dev/null
@@ -1,38 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_BROWSER_SERVICE_WORKER_LINK_HEADER_SUPPORT_H_ -#define CONTENT_BROWSER_SERVICE_WORKER_LINK_HEADER_SUPPORT_H_ - -#include <string> -#include <unordered_map> -#include <vector> - -#include "base/macros.h" -#include "content/common/content_export.h" - -namespace net { -class URLRequest; -} - -namespace content { -class ServiceWorkerContextWrapper; - -void ProcessRequestForLinkHeaders(net::URLRequest* request); - -CONTENT_EXPORT void ProcessLinkHeaderForRequest( - net::URLRequest* request, - const std::string& link_header, - ServiceWorkerContextWrapper* service_worker_context_for_testing = nullptr); - -CONTENT_EXPORT void SplitLinkHeaderForTesting(const std::string& header, - std::vector<std::string>* values); -CONTENT_EXPORT bool ParseLinkHeaderValueForTesting( - const std::string& link, - std::string* url, - std::unordered_map<std::string, std::string>* params); - -} // namespace content - -#endif // CONTENT_BROWSER_SERVICE_WORKER_LINK_HEADER_SUPPORT_H_
diff --git a/content/browser/service_worker/link_header_support_unittest.cc b/content/browser/service_worker/link_header_support_unittest.cc deleted file mode 100644 index 2c7bca8..0000000 --- a/content/browser/service_worker/link_header_support_unittest.cc +++ /dev/null
@@ -1,452 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/browser/service_worker/link_header_support.h" - -#include "base/command_line.h" -#include "base/logging.h" -#include "base/run_loop.h" -#include "content/browser/loader/resource_request_info_impl.h" -#include "content/browser/service_worker/embedded_worker_test_helper.h" -#include "content/browser/service_worker/service_worker_context_wrapper.h" -#include "content/browser/service_worker/service_worker_registration.h" -#include "content/browser/service_worker/service_worker_request_handler.h" -#include "content/browser/service_worker/service_worker_test_utils.h" -#include "content/common/service_worker/service_worker_utils.h" -#include "content/public/common/content_switches.h" -#include "content/public/common/previews_state.h" -#include "content/public/test/mock_resource_context.h" -#include "content/public/test/test_browser_thread_bundle.h" -#include "net/http/http_response_headers.h" -#include "net/traffic_annotation/network_traffic_annotation_test_helper.h" -#include "net/url_request/url_request_test_job.h" -#include "net/url_request/url_request_test_util.h" -#include "storage/browser/blob/blob_storage_context.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "third_party/WebKit/public/platform/modules/serviceworker/service_worker_registration.mojom.h" - -namespace content { - -namespace { - -const int kMockProviderId = 1; - -void SaveFoundRegistrationsCallback( - ServiceWorkerStatusCode expected_status, - bool* called, - std::vector<ServiceWorkerRegistrationInfo>* registrations, - ServiceWorkerStatusCode status, - const std::vector<ServiceWorkerRegistrationInfo>& result) { - EXPECT_EQ(expected_status, status); - *called = true; - *registrations = result; -} - -ServiceWorkerContextWrapper::GetRegistrationsInfosCallback -SaveFoundRegistrations( - ServiceWorkerStatusCode expected_status, - bool* called, - std::vector<ServiceWorkerRegistrationInfo>* registrations) { - *called = false; - return base::Bind(&SaveFoundRegistrationsCallback, expected_status, called, - registrations); -} - -} // namespace - -class LinkHeaderServiceWorkerTest : public ::testing::Test { - public: - LinkHeaderServiceWorkerTest() - : thread_bundle_(TestBrowserThreadBundle::IO_MAINLOOP), - resource_context_(&request_context_) { - base::CommandLine::ForCurrentProcess()->AppendSwitch( - switches::kEnableExperimentalWebPlatformFeatures); - } - ~LinkHeaderServiceWorkerTest() override {} - - void SetUp() override { - helper_.reset(new EmbeddedWorkerTestHelper(base::FilePath())); - } - - void TearDown() override { helper_.reset(); } - - ServiceWorkerContextCore* context() { return helper_->context(); } - ServiceWorkerContextWrapper* context_wrapper() { - return helper_->context_wrapper(); - } - ServiceWorkerProviderHost* provider_host() { return provider_host_.get(); } - int render_process_id() const { return helper_->mock_render_process_id(); } - - void CreateDocumentProviderHost() { - // An empty host. - remote_endpoints_.emplace_back(); - std::unique_ptr<ServiceWorkerProviderHost> host = - CreateProviderHostForWindow(render_process_id(), kMockProviderId, - true /* is_parent_frame_secure */, - context()->AsWeakPtr(), - &remote_endpoints_.back()); - provider_host_ = host->AsWeakPtr(); - EXPECT_FALSE( - context()->GetProviderHost(host->process_id(), host->provider_id())); - context()->AddProviderHost(std::move(host)); - } - - void CreateInsecureDocumentProviderHost() { - // An empty host. - remote_endpoints_.emplace_back(); - std::unique_ptr<ServiceWorkerProviderHost> host = - CreateProviderHostForWindow(render_process_id(), kMockProviderId, - false /* is_parent_frame_secure */, - context()->AsWeakPtr(), - &remote_endpoints_.back()); - provider_host_ = host->AsWeakPtr(); - EXPECT_FALSE( - context()->GetProviderHost(host->process_id(), host->provider_id())); - context()->AddProviderHost(std::move(host)); - } - - void CreateServiceWorkerProviderHost() { - scoped_refptr<ServiceWorkerRegistration> registration = - new ServiceWorkerRegistration( - blink::mojom::ServiceWorkerRegistrationOptions( - GURL("https://host/scope")), - 1L, context()->AsWeakPtr()); - scoped_refptr<ServiceWorkerVersion> version = new ServiceWorkerVersion( - registration.get(), GURL("https://host/script.js"), 1L, - context()->AsWeakPtr()); - - remote_endpoints_.emplace_back(); - std::unique_ptr<ServiceWorkerProviderHost> host = - CreateProviderHostForServiceWorkerContext( - render_process_id(), true /* is_parent_frame_secure */, - version.get(), context()->AsWeakPtr(), &remote_endpoints_.back()); - provider_host_ = host->AsWeakPtr(); - EXPECT_FALSE( - context()->GetProviderHost(host->process_id(), host->provider_id())); - context()->AddProviderHost(std::move(host)); - } - - std::unique_ptr<net::URLRequest> CreateRequest(const GURL& request_url, - ResourceType resource_type, - int provider_id) { - std::unique_ptr<net::URLRequest> request = request_context_.CreateRequest( - request_url, net::DEFAULT_PRIORITY, &request_delegate_, - TRAFFIC_ANNOTATION_FOR_TESTS); - ResourceRequestInfo::AllocateForTesting( - request.get(), resource_type, &resource_context_, - -1 /* render_process_id */, -1 /* render_view_id */, - -1 /* render_frame_id */, resource_type == RESOURCE_TYPE_MAIN_FRAME, - true /* allow_download */, true /* is_async */, - PREVIEWS_OFF /* previews_state */, nullptr /* navigation_ui_data */); - ResourceRequestInfoImpl::ForRequest(request.get()) - ->set_initiated_in_secure_context_for_testing(true); - - ServiceWorkerRequestHandler::InitializeHandler( - request.get(), context_wrapper(), &blob_storage_context_, - render_process_id(), provider_id, false /* skip_service_worker */, - network::mojom::FetchRequestMode::kNoCORS, - network::mojom::FetchCredentialsMode::kOmit, - FetchRedirectMode::FOLLOW_MODE, std::string() /* integrity */, - false /* keepalive */, resource_type, REQUEST_CONTEXT_TYPE_HYPERLINK, - REQUEST_CONTEXT_FRAME_TYPE_TOP_LEVEL, nullptr); - - return request; - } - - std::unique_ptr<net::URLRequest> CreateSubresourceRequest( - const GURL& request_url, - int provider_id) { - return CreateRequest(request_url, RESOURCE_TYPE_SCRIPT, provider_id); - } - - std::vector<ServiceWorkerRegistrationInfo> GetRegistrations() { - bool called; - std::vector<ServiceWorkerRegistrationInfo> registrations; - context_wrapper()->GetAllRegistrations( - SaveFoundRegistrations(SERVICE_WORKER_OK, &called, ®istrations)); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(called); - return registrations; - } - - protected: - TestBrowserThreadBundle thread_bundle_; - std::unique_ptr<EmbeddedWorkerTestHelper> helper_; - net::TestURLRequestContext request_context_; - net::TestDelegate request_delegate_; - MockResourceContext resource_context_; - base::WeakPtr<ServiceWorkerProviderHost> provider_host_; - storage::BlobStorageContext blob_storage_context_; - std::vector<ServiceWorkerRemoteProviderEndpoint> remote_endpoints_; -}; - -TEST_F(LinkHeaderServiceWorkerTest, InstallServiceWorker_Basic) { - CreateDocumentProviderHost(); - ProcessLinkHeaderForRequest( - CreateSubresourceRequest(GURL("https://example.com/foo/bar/"), - provider_host()->provider_id()) - .get(), - "<../foo.js>; rel=serviceworker", context_wrapper()); - base::RunLoop().RunUntilIdle(); - - std::vector<ServiceWorkerRegistrationInfo> registrations = GetRegistrations(); - ASSERT_EQ(1u, registrations.size()); - EXPECT_EQ(GURL("https://example.com/foo/"), registrations[0].pattern); - EXPECT_EQ(GURL("https://example.com/foo/foo.js"), - registrations[0].active_version.script_url); -} - -TEST_F(LinkHeaderServiceWorkerTest, InstallServiceWorker_ScopeWithFragment) { - CreateDocumentProviderHost(); - ProcessLinkHeaderForRequest( - CreateSubresourceRequest(GURL("https://example.com/foo/bar/"), - provider_host()->provider_id()) - .get(), - "<../bar.js>; rel=serviceworker; scope=\"scope#ref\"", context_wrapper()); - base::RunLoop().RunUntilIdle(); - - std::vector<ServiceWorkerRegistrationInfo> registrations = GetRegistrations(); - ASSERT_EQ(1u, registrations.size()); - EXPECT_EQ(GURL("https://example.com/foo/bar/scope"), - registrations[0].pattern); - EXPECT_EQ(GURL("https://example.com/foo/bar.js"), - registrations[0].active_version.script_url); -} - -TEST_F(LinkHeaderServiceWorkerTest, InstallServiceWorker_ScopeAbsoluteUrl) { - CreateDocumentProviderHost(); - ProcessLinkHeaderForRequest( - CreateSubresourceRequest(GURL("https://example.com/foo/bar/"), - provider_host()->provider_id()) - .get(), - "<bar.js>; rel=serviceworker; " - "scope=\"https://example.com:443/foo/bar/scope\"", - context_wrapper()); - base::RunLoop().RunUntilIdle(); - - std::vector<ServiceWorkerRegistrationInfo> registrations = GetRegistrations(); - ASSERT_EQ(1u, registrations.size()); - EXPECT_EQ(GURL("https://example.com/foo/bar/scope"), - registrations[0].pattern); - EXPECT_EQ(GURL("https://example.com/foo/bar/bar.js"), - registrations[0].active_version.script_url); -} - -TEST_F(LinkHeaderServiceWorkerTest, InstallServiceWorker_ScopeDifferentOrigin) { - CreateDocumentProviderHost(); - ProcessLinkHeaderForRequest( - CreateSubresourceRequest(GURL("https://example.com/foobar/"), - provider_host()->provider_id()) - .get(), - "<bar.js>; rel=serviceworker; scope=\"https://google.com/scope\"", - context_wrapper()); - base::RunLoop().RunUntilIdle(); - - std::vector<ServiceWorkerRegistrationInfo> registrations = GetRegistrations(); - ASSERT_EQ(0u, registrations.size()); -} - -TEST_F(LinkHeaderServiceWorkerTest, InstallServiceWorker_ScopeUrlEncodedSlash) { - CreateDocumentProviderHost(); - ProcessLinkHeaderForRequest( - CreateSubresourceRequest(GURL("https://example.com/foobar/"), - provider_host()->provider_id()) - .get(), - "<bar.js>; rel=serviceworker; scope=\"./foo%2Fbar\"", context_wrapper()); - base::RunLoop().RunUntilIdle(); - - std::vector<ServiceWorkerRegistrationInfo> registrations = GetRegistrations(); - ASSERT_EQ(0u, registrations.size()); -} - -TEST_F(LinkHeaderServiceWorkerTest, - InstallServiceWorker_ScriptUrlEncodedSlash) { - CreateDocumentProviderHost(); - ProcessLinkHeaderForRequest( - CreateSubresourceRequest(GURL("https://example.com/foobar/"), - provider_host()->provider_id()) - .get(), - "<foo%2Fbar.js>; rel=serviceworker", context_wrapper()); - base::RunLoop().RunUntilIdle(); - - std::vector<ServiceWorkerRegistrationInfo> registrations = GetRegistrations(); - ASSERT_EQ(0u, registrations.size()); -} - -TEST_F(LinkHeaderServiceWorkerTest, InstallServiceWorker_ScriptAbsoluteUrl) { - CreateDocumentProviderHost(); - ProcessLinkHeaderForRequest( - CreateSubresourceRequest(GURL("https://example.com/foobar/"), - provider_host()->provider_id()) - .get(), - "<https://example.com/bar.js>; rel=serviceworker; scope=foo", - context_wrapper()); - base::RunLoop().RunUntilIdle(); - - std::vector<ServiceWorkerRegistrationInfo> registrations = GetRegistrations(); - ASSERT_EQ(1u, registrations.size()); - EXPECT_EQ(GURL("https://example.com/foobar/foo"), registrations[0].pattern); - EXPECT_EQ(GURL("https://example.com/bar.js"), - registrations[0].active_version.script_url); -} - -TEST_F(LinkHeaderServiceWorkerTest, - InstallServiceWorker_ScriptDifferentOrigin) { - CreateDocumentProviderHost(); - ProcessLinkHeaderForRequest( - CreateSubresourceRequest(GURL("https://example.com/foobar/"), - provider_host()->provider_id()) - .get(), - "<https://google.com/bar.js>; rel=serviceworker; scope=foo", - context_wrapper()); - base::RunLoop().RunUntilIdle(); - - std::vector<ServiceWorkerRegistrationInfo> registrations = GetRegistrations(); - ASSERT_EQ(0u, registrations.size()); -} - -TEST_F(LinkHeaderServiceWorkerTest, InstallServiceWorker_MultipleWorkers) { - CreateDocumentProviderHost(); - ProcessLinkHeaderForRequest( - CreateSubresourceRequest(GURL("https://example.com/foobar/"), - provider_host()->provider_id()) - .get(), - "<bar.js>; rel=serviceworker; scope=foo, <baz.js>; " - "rel=serviceworker; scope=scope", - context_wrapper()); - base::RunLoop().RunUntilIdle(); - - std::vector<ServiceWorkerRegistrationInfo> registrations = GetRegistrations(); - ASSERT_EQ(2u, registrations.size()); - EXPECT_EQ(GURL("https://example.com/foobar/foo"), registrations[0].pattern); - EXPECT_EQ(GURL("https://example.com/foobar/bar.js"), - registrations[0].active_version.script_url); - EXPECT_EQ(GURL("https://example.com/foobar/scope"), registrations[1].pattern); - EXPECT_EQ(GURL("https://example.com/foobar/baz.js"), - registrations[1].active_version.script_url); -} - -TEST_F(LinkHeaderServiceWorkerTest, - InstallServiceWorker_ValidAndInvalidValues) { - CreateDocumentProviderHost(); - ProcessLinkHeaderForRequest( - CreateSubresourceRequest(GURL("https://example.com/foobar/"), - provider_host()->provider_id()) - .get(), - "<https://google.com/bar.js>; rel=serviceworker; scope=foo, <baz.js>; " - "rel=serviceworker; scope=scope", - context_wrapper()); - base::RunLoop().RunUntilIdle(); - - std::vector<ServiceWorkerRegistrationInfo> registrations = GetRegistrations(); - ASSERT_EQ(1u, registrations.size()); - EXPECT_EQ(GURL("https://example.com/foobar/scope"), registrations[0].pattern); - EXPECT_EQ(GURL("https://example.com/foobar/baz.js"), - registrations[0].active_version.script_url); -} - -TEST_F(LinkHeaderServiceWorkerTest, InstallServiceWorker_InsecureContext) { - CreateDocumentProviderHost(); - std::unique_ptr<net::URLRequest> request = CreateSubresourceRequest( - GURL("https://example.com/foo/bar/"), provider_host()->provider_id()); - ResourceRequestInfoImpl::ForRequest(request.get()) - ->set_initiated_in_secure_context_for_testing(false); - ProcessLinkHeaderForRequest(request.get(), "<../foo.js>; rel=serviceworker", - context_wrapper()); - base::RunLoop().RunUntilIdle(); - - std::vector<ServiceWorkerRegistrationInfo> registrations = GetRegistrations(); - ASSERT_EQ(0u, registrations.size()); -} - -TEST_F(LinkHeaderServiceWorkerTest, - InstallServiceWorker_NavigationFromInsecureContextToSecureContext) { - CreateDocumentProviderHost(); - std::unique_ptr<net::URLRequest> request = - CreateRequest(GURL("https://example.com/foo/bar/"), - RESOURCE_TYPE_MAIN_FRAME, provider_host()->provider_id()); - ResourceRequestInfoImpl::ForRequest(request.get()) - ->set_initiated_in_secure_context_for_testing(false); - - provider_host()->SetDocumentUrl(GURL("https://example.com/foo/bar/")); - - ProcessLinkHeaderForRequest(request.get(), "<../foo.js>; rel=serviceworker", - context_wrapper()); - base::RunLoop().RunUntilIdle(); - - std::vector<ServiceWorkerRegistrationInfo> registrations = GetRegistrations(); - ASSERT_EQ(1u, registrations.size()); - EXPECT_EQ(GURL("https://example.com/foo/"), registrations[0].pattern); - EXPECT_EQ(GURL("https://example.com/foo/foo.js"), - registrations[0].active_version.script_url); -} - -TEST_F(LinkHeaderServiceWorkerTest, - InstallServiceWorker_NavigationToInsecureContext) { - CreateDocumentProviderHost(); - provider_host()->SetDocumentUrl(GURL("http://example.com/foo/bar/")); - ProcessLinkHeaderForRequest( - CreateRequest(GURL("http://example.com/foo/bar/"), - RESOURCE_TYPE_MAIN_FRAME, provider_host()->provider_id()) - .get(), - "<../foo.js>; rel=serviceworker", context_wrapper()); - base::RunLoop().RunUntilIdle(); - - std::vector<ServiceWorkerRegistrationInfo> registrations = GetRegistrations(); - ASSERT_EQ(0u, registrations.size()); -} - -TEST_F(LinkHeaderServiceWorkerTest, - InstallServiceWorker_NavigationToInsecureHttpsContext) { - CreateInsecureDocumentProviderHost(); - provider_host()->SetDocumentUrl(GURL("https://example.com/foo/bar/")); - ProcessLinkHeaderForRequest( - CreateRequest(GURL("https://example.com/foo/bar/"), - RESOURCE_TYPE_MAIN_FRAME, provider_host()->provider_id()) - .get(), - "<../foo.js>; rel=serviceworker", context_wrapper()); - base::RunLoop().RunUntilIdle(); - - std::vector<ServiceWorkerRegistrationInfo> registrations = GetRegistrations(); - ASSERT_EQ(0u, registrations.size()); -} - -TEST_F(LinkHeaderServiceWorkerTest, - InstallServiceWorker_FromWorkerWithoutControllees) { - CreateServiceWorkerProviderHost(); - ProcessLinkHeaderForRequest( - CreateSubresourceRequest(GURL("https://example.com/foo/bar/"), - provider_host()->provider_id()) - .get(), - "<../foo.js>; rel=serviceworker", context_wrapper()); - base::RunLoop().RunUntilIdle(); - - std::vector<ServiceWorkerRegistrationInfo> registrations = GetRegistrations(); - ASSERT_EQ(0u, registrations.size()); -} - -TEST_F(LinkHeaderServiceWorkerTest, - InstallServiceWorker_FromWorkerWithControllees) { - CreateServiceWorkerProviderHost(); - - remote_endpoints_.emplace_back(); - std::unique_ptr<ServiceWorkerProviderHost> controllee = - CreateProviderHostForWindow(render_process_id(), kMockProviderId, - true /* is_parent_frame_secure */, - context()->AsWeakPtr(), - &remote_endpoints_.back()); - provider_host()->running_hosted_version()->AddControllee(controllee.get()); - - ProcessLinkHeaderForRequest( - CreateSubresourceRequest(GURL("https://example.com/foo/bar/"), - provider_host()->provider_id()) - .get(), - "<../foo.js>; rel=serviceworker", context_wrapper()); - base::RunLoop().RunUntilIdle(); - - std::vector<ServiceWorkerRegistrationInfo> registrations = GetRegistrations(); - ASSERT_EQ(1u, registrations.size()); -} - -} // namespace content
diff --git a/content/browser/service_worker/service_worker_browsertest.cc b/content/browser/service_worker/service_worker_browsertest.cc index b0691f2d..b7c15c1 100644 --- a/content/browser/service_worker/service_worker_browsertest.cc +++ b/content/browser/service_worker/service_worker_browsertest.cc
@@ -807,10 +807,7 @@ int request_id = version_->StartRequest(ServiceWorkerMetrics::EventType::INSTALL, CreateReceiver(BrowserThread::UI, done, result)); - mojom::ServiceWorkerInstallEventMethodsAssociatedPtrInfo ptr_info; - mojo::MakeRequest(&ptr_info); version_->event_dispatcher()->DispatchInstallEvent( - std::move(ptr_info), base::BindOnce(&self::ReceiveInstallEventOnIOThread, base::Unretained(this), done, result, request_id)); }
diff --git a/content/browser/service_worker/service_worker_context_core.cc b/content/browser/service_worker/service_worker_context_core.cc index b163c214..c717e64b 100644 --- a/content/browser/service_worker/service_worker_context_core.cc +++ b/content/browser/service_worker/service_worker_context_core.cc
@@ -39,6 +39,7 @@ #include "net/http/http_response_headers.h" #include "net/http/http_response_info.h" #include "storage/browser/quota/quota_manager_proxy.h" +#include "third_party/WebKit/common/service_worker/service_worker_provider_type.mojom.h" #include "third_party/WebKit/public/platform/modules/serviceworker/service_worker_registration.mojom.h" #include "url/gurl.h" @@ -94,7 +95,7 @@ bool IsSameOriginWindowProviderHost(const GURL& origin, ServiceWorkerProviderHost* host) { return host->provider_type() == - ServiceWorkerProviderType::SERVICE_WORKER_PROVIDER_FOR_WINDOW && + blink::mojom::ServiceWorkerProviderType::kForWindow && host->document_url().GetOrigin() == origin; }
diff --git a/content/browser/service_worker/service_worker_context_core.h b/content/browser/service_worker/service_worker_context_core.h index a5775b3..6d2db80f 100644 --- a/content/browser/service_worker/service_worker_context_core.h +++ b/content/browser/service_worker/service_worker_context_core.h
@@ -181,7 +181,8 @@ const GURL& origin); // Runs the callback with true if there is a ProviderHost for |origin| of type - // SERVICE_WORKER_PROVIDER_FOR_WINDOW which is a main (top-level) frame. + // blink::mojom::ServiceWorkerProviderType::kForWindow which is a main + // (top-level) frame. void HasMainFrameProviderHost(const GURL& origin, const BoolCallback& callback) const;
diff --git a/content/browser/service_worker/service_worker_context_core_observer.h b/content/browser/service_worker/service_worker_context_core_observer.h index e8bf108..44e788b8 100644 --- a/content/browser/service_worker/service_worker_context_core_observer.h +++ b/content/browser/service_worker/service_worker_context_core_observer.h
@@ -12,6 +12,7 @@ #include "base/time/time.h" #include "content/browser/service_worker/service_worker_info.h" #include "content/browser/service_worker/service_worker_version.h" +#include "third_party/WebKit/common/service_worker/service_worker_provider_type.mojom.h" #include "url/gurl.h" namespace content { @@ -85,7 +86,7 @@ int process_id, int route_id, const base::Callback<WebContents*(void)>& web_contents_getter, - ServiceWorkerProviderType type) {} + blink::mojom::ServiceWorkerProviderType type) {} virtual void OnControlleeRemoved(int64_t version_id, const std::string& uuid) {} virtual void OnRegistrationStored(int64_t registration_id,
diff --git a/content/browser/service_worker/service_worker_context_unittest.cc b/content/browser/service_worker/service_worker_context_unittest.cc index 293ed90..00986969 100644 --- a/content/browser/service_worker/service_worker_context_unittest.cc +++ b/content/browser/service_worker/service_worker_context_unittest.cc
@@ -90,7 +90,6 @@ RejectInstallTestHelper() : EmbeddedWorkerTestHelper(base::FilePath()) {} void OnInstallEvent( - mojom::ServiceWorkerInstallEventMethodsAssociatedPtrInfo client, mojom::ServiceWorkerEventDispatcher::DispatchInstallEventCallback callback) override { dispatched_events()->push_back(Event::Install);
diff --git a/content/browser/service_worker/service_worker_context_watcher.cc b/content/browser/service_worker/service_worker_context_watcher.cc index 430bff3..e2210fa 100644 --- a/content/browser/service_worker/service_worker_context_watcher.cc +++ b/content/browser/service_worker/service_worker_context_watcher.cc
@@ -11,7 +11,6 @@ #include "content/browser/service_worker/embedded_worker_status.h" #include "content/browser/service_worker/service_worker_context_wrapper.h" #include "content/browser/service_worker/service_worker_version.h" -#include "content/common/service_worker/service_worker_types.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/console_message_level.h" #include "third_party/WebKit/public/platform/modules/serviceworker/service_worker_object.mojom.h" @@ -342,7 +341,7 @@ int process_id, int route_id, const base::Callback<WebContents*(void)>& web_contents_getter, - ServiceWorkerProviderType type) { + blink::mojom::ServiceWorkerProviderType type) { DCHECK_CURRENTLY_ON(BrowserThread::IO); auto it = version_info_map_.find(version_id); if (it == version_info_map_.end())
diff --git a/content/browser/service_worker/service_worker_context_watcher.h b/content/browser/service_worker/service_worker_context_watcher.h index 10847d4a..3d3f008 100644 --- a/content/browser/service_worker/service_worker_context_watcher.h +++ b/content/browser/service_worker/service_worker_context_watcher.h
@@ -14,6 +14,7 @@ #include "content/browser/service_worker/service_worker_context_core_observer.h" #include "content/browser/service_worker/service_worker_info.h" #include "content/common/content_export.h" +#include "third_party/WebKit/common/service_worker/service_worker_provider_type.mojom.h" namespace content { @@ -108,7 +109,7 @@ int process_id, int route_id, const base::Callback<WebContents*(void)>& web_contents_getter, - ServiceWorkerProviderType type) override; + blink::mojom::ServiceWorkerProviderType type) override; void OnControlleeRemoved(int64_t version_id, const std::string& uuid) override; void OnRegistrationStored(int64_t registration_id,
diff --git a/content/browser/service_worker/service_worker_context_wrapper.cc b/content/browser/service_worker/service_worker_context_wrapper.cc index 6b7ccda..51aa2b3 100644 --- a/content/browser/service_worker/service_worker_context_wrapper.cc +++ b/content/browser/service_worker/service_worker_context_wrapper.cc
@@ -802,14 +802,6 @@ core_observer_list_->RemoveObserver(observer); } -bool ServiceWorkerContextWrapper::OriginHasForeignFetchRegistrations( - const GURL& origin) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - if (!context_core_) - return false; - return context_core_->storage()->OriginHasForeignFetchRegistrations(origin); -} - ServiceWorkerContextWrapper::~ServiceWorkerContextWrapper() { // Explicitly remove this object as an observer to avoid use-after-frees in // tests where this object is not guaranteed to outlive the
diff --git a/content/browser/service_worker/service_worker_context_wrapper.h b/content/browser/service_worker/service_worker_context_wrapper.h index b59957c..93bc750 100644 --- a/content/browser/service_worker/service_worker_context_wrapper.h +++ b/content/browser/service_worker/service_worker_context_wrapper.h
@@ -255,16 +255,12 @@ bool is_incognito() const { return is_incognito_; } - // Must be called from the IO thread. - bool OriginHasForeignFetchRegistrations(const GURL& origin); - private: friend class BackgroundSyncManagerTest; friend class base::RefCountedThreadSafe<ServiceWorkerContextWrapper>; friend class EmbeddedWorkerTestHelper; friend class EmbeddedWorkerBrowserTest; friend class FakeServiceWorkerContextWrapper; - friend class ForeignFetchRequestHandler; friend class ServiceWorkerDispatcherHost; friend class ServiceWorkerInternalsUI; friend class ServiceWorkerNavigationHandleCore;
diff --git a/content/browser/service_worker/service_worker_database.cc b/content/browser/service_worker/service_worker_database.cc index e927ccf..5fe2983 100644 --- a/content/browser/service_worker/service_worker_database.cc +++ b/content/browser/service_worker/service_worker_database.cc
@@ -76,18 +76,19 @@ // key: "REGID_TO_ORIGIN:" + <int64_t 'registration_id'> // value: <GURL 'origin'> // -// OBSOLETE: http://crbug.com/539713 +// OBSOLETE: https://crbug.com/539713 // key: "INITDATA_DISKCACHE_MIGRATION_NOT_NEEDED" // value: <empty> // - This entry represents that the diskcache uses the Simple backend and // does not have to do diskcache migration (http://crbug.com/487482). // -// OBSOLETE: http://crbug.com/539713 +// OBSOLETE: https://crbug.com/539713 // key: "INITDATA_OLD_DISKCACHE_DELETION_NOT_NEEDED" // value: <empty> // - This entry represents that the old BlockFile diskcache was deleted // after diskcache migration (http://crbug.com/487482). // +// OBSOLETE: https://crbug.com/788604 // key: "INITDATA_FOREIGN_FETCH_ORIGIN:" + <GURL 'origin'> // value: <empty> namespace content { @@ -99,7 +100,6 @@ const char kNextResIdKey[] = "INITDATA_NEXT_RESOURCE_ID"; const char kNextVerIdKey[] = "INITDATA_NEXT_VERSION_ID"; const char kUniqueOriginKey[] = "INITDATA_UNIQUE_ORIGIN:"; -const char kForeignFetchOriginKey[] = "INITDATA_FOREIGN_FETCH_ORIGIN:"; const char kRegKeyPrefix[] = "REG:"; const char kRegUserDataKeyPrefix[] = "REG_USER_DATA:"; @@ -162,12 +162,6 @@ origin.GetOrigin().spec().c_str()); } -std::string CreateForeignFetchOriginKey(const GURL& origin) { - return base::StringPrintf("%s%s", - service_worker_internals::kForeignFetchOriginKey, - origin.GetOrigin().spec().c_str()); -} - std::string CreateResourceIdKey(const char* key_prefix, int64_t resource_id) { return base::StringPrintf( "%s%s", key_prefix, base::Int64ToString(resource_id).c_str()); @@ -218,12 +212,6 @@ ""); } -void PutForeignFetchOriginToBatch(const GURL& origin, - leveldb::WriteBatch* batch) { - // Value should be empty. - batch->Put(CreateForeignFetchOriginKey(origin), ""); -} - ServiceWorkerDatabase::Status ParseId(const std::string& serialized, int64_t* out) { DCHECK(out); @@ -391,50 +379,6 @@ return status; } -ServiceWorkerDatabase::Status -ServiceWorkerDatabase::GetOriginsWithForeignFetchRegistrations( - std::set<GURL>* origins) { - DCHECK(sequence_checker_.CalledOnValidSequence()); - DCHECK(origins->empty()); - - Status status = LazyOpen(false); - if (IsNewOrNonexistentDatabase(status)) - return STATUS_OK; - if (status != STATUS_OK) - return status; - - { - std::unique_ptr<leveldb::Iterator> itr( - db_->NewIterator(leveldb::ReadOptions())); - for (itr->Seek(service_worker_internals::kForeignFetchOriginKey); - itr->Valid(); itr->Next()) { - status = LevelDBStatusToServiceWorkerDBStatus(itr->status()); - if (status != STATUS_OK) { - origins->clear(); - break; - } - - std::string origin_str; - if (!RemovePrefix(itr->key().ToString(), - service_worker_internals::kForeignFetchOriginKey, - &origin_str)) - break; - - GURL origin(origin_str); - if (!origin.is_valid()) { - status = STATUS_ERROR_CORRUPTED; - origins->clear(); - break; - } - - origins->insert(origin); - } - } - - HandleReadResult(FROM_HERE, status); - return status; -} - ServiceWorkerDatabase::Status ServiceWorkerDatabase::GetRegistrationsForOrigin( const GURL& origin, std::vector<RegistrationData>* registrations, @@ -616,9 +560,6 @@ PutUniqueOriginToBatch(registration.scope.GetOrigin(), &batch); - if (!registration.foreign_fetch_scopes.empty()) - PutForeignFetchOriginToBatch(registration.scope.GetOrigin(), &batch); - DCHECK_EQ(AccumulateResourceSizeInBytes(resources), registration.resources_total_size_bytes) << "The total size in the registration must match the cumulative " @@ -672,31 +613,6 @@ DCHECK(base::STLSetIntersection<std::set<int64_t>>(pushed_resources, deleted_resources) .empty()); - - // If old registration had foreign fetch scopes, but new registration - // doesn't, the origin might have to be removed from the list of origins - // with foreign fetch scopes. - // TODO(mek): Like the similar check in DeleteRegistration, ideally this - // could be done more efficiently. - if (!old_registration->foreign_fetch_scopes.empty() && - registration.foreign_fetch_scopes.empty()) { - std::vector<RegistrationData> registrations; - status = GetRegistrationsForOrigin(registration.scope.GetOrigin(), - ®istrations, nullptr); - if (status != STATUS_OK) - return status; - bool remaining_ff_scopes = false; - for (const auto& existing_reg : registrations) { - if (existing_reg.registration_id != registration.registration_id && - !existing_reg.foreign_fetch_scopes.empty()) { - remaining_ff_scopes = true; - break; - } - } - if (!remaining_ff_scopes) - batch.Delete( - CreateForeignFetchOriginKey(registration.scope.GetOrigin())); - } } return WriteBatch(&batch); @@ -832,19 +748,6 @@ batch.Delete(CreateUniqueOriginKey(origin)); } - // Remove |origin| from foreign fetch origins if a registration specified by - // |registration_id| is the only one with foreign fetch scopes for |origin|. - bool remaining_ff_scopes = false; - for (const auto& registration : registrations) { - if (registration.registration_id != registration_id && - !registration.foreign_fetch_scopes.empty()) { - remaining_ff_scopes = true; - break; - } - } - if (!remaining_ff_scopes) - batch.Delete(CreateForeignFetchOriginKey(origin)); - // Delete a registration specified by |registration_id|. batch.Delete(CreateRegistrationKey(registration_id, origin)); batch.Delete(CreateRegistrationIdToOriginKey(registration_id)); @@ -1287,9 +1190,6 @@ // Delete from the unique origin list. batch.Delete(CreateUniqueOriginKey(origin)); - // Delete from the foreign fetch origin list. - batch.Delete(CreateForeignFetchOriginKey(origin)); - std::vector<RegistrationData> registrations; status = GetRegistrationsForOrigin(origin, ®istrations, nullptr); if (status != STATUS_OK) @@ -1488,27 +1388,6 @@ out->last_update_check = base::Time::FromInternalValue(data.last_update_check_time()); out->resources_total_size_bytes = data.resources_total_size_bytes(); - for (int i = 0; i < data.foreign_fetch_scope_size(); ++i) { - GURL sub_scope_url(data.foreign_fetch_scope(i)); - if (!sub_scope_url.is_valid() || - !ServiceWorkerUtils::ScopeMatches(scope_url, sub_scope_url)) { - DLOG(ERROR) << "Foreign fetch scope '" << data.foreign_fetch_scope(i) - << "' is not valid or does not match Scope URL '" << scope_url - << "'."; - return ServiceWorkerDatabase::STATUS_ERROR_CORRUPTED; - } - out->foreign_fetch_scopes.push_back(sub_scope_url); - } - for (int i = 0; i < data.foreign_fetch_origin_size(); ++i) { - url::Origin parsed_origin = - url::Origin::Create(GURL(data.foreign_fetch_origin(i))); - if (parsed_origin.unique()) { - DLOG(ERROR) << "Foreign fetch origin '" << data.foreign_fetch_origin(i) - << "' is not valid."; - return ServiceWorkerDatabase::STATUS_ERROR_CORRUPTED; - } - out->foreign_fetch_origins.push_back(parsed_origin); - } if (data.has_origin_trial_tokens()) { const ServiceWorkerOriginTrialInfo& info = data.origin_trial_tokens(); blink::TrialTokenValidator::FeatureToTokensMap origin_trial_tokens; @@ -1553,15 +1432,6 @@ data.set_last_update_check_time( registration.last_update_check.ToInternalValue()); data.set_resources_total_size_bytes(registration.resources_total_size_bytes); - for (const GURL& url : registration.foreign_fetch_scopes) { - DCHECK(ServiceWorkerUtils::ScopeMatches(registration.scope, url)) - << "Foreign fetch scope '" << url - << "' does not match service worker scope '" << registration.scope - << "'."; - data.add_foreign_fetch_scope(url.spec()); - } - for (const url::Origin& origin : registration.foreign_fetch_origins) - data.add_foreign_fetch_origin(origin.Serialize()); if (registration.origin_trial_tokens) { ServiceWorkerOriginTrialInfo* info = data.mutable_origin_trial_tokens(); for (const auto& feature : *registration.origin_trial_tokens) {
diff --git a/content/browser/service_worker/service_worker_database.h b/content/browser/service_worker/service_worker_database.h index efa99c5..d20005c 100644 --- a/content/browser/service_worker/service_worker_database.h +++ b/content/browser/service_worker/service_worker_database.h
@@ -76,8 +76,6 @@ bool is_active; bool has_fetch_handler; base::Time last_update_check; - std::vector<GURL> foreign_fetch_scopes; - std::vector<url::Origin> foreign_fetch_origins; base::Optional<blink::TrialTokenValidator::FeatureToTokensMap> origin_trial_tokens; blink::mojom::NavigationPreloadState navigation_preload_state; @@ -115,11 +113,6 @@ // Otherwise, returns an error. Status GetOriginsWithRegistrations(std::set<GURL>* origins); - // Reads origins that have one or more than one registration with at least one - // foreign fetch scope registered. Returns OK if they are successfully read or - // not found. Otherwise returns an error. - Status GetOriginsWithForeignFetchRegistrations(std::set<GURL>* origins); - // Reads registrations for |origin| from the database. Returns OK if they are // successfully read or not found. Otherwise, returns an error. Status GetRegistrationsForOrigin(
diff --git a/content/browser/service_worker/service_worker_database.proto b/content/browser/service_worker/service_worker_database.proto index 892001d0..32c628c 100644 --- a/content/browser/service_worker/service_worker_database.proto +++ b/content/browser/service_worker/service_worker_database.proto
@@ -40,8 +40,8 @@ optional uint64 resources_total_size_bytes = 8; - repeated string foreign_fetch_scope = 9; - repeated string foreign_fetch_origin = 10; + // repeated string foreign_fetch_scope = 9; // obsolete + // repeated string foreign_fetch_origin = 10; // obsolete // If the registration data was created by old Chrome (< M56), // |origin_trial_tokens| is not set. In this case, we have to start the
diff --git a/content/browser/service_worker/service_worker_database_unittest.cc b/content/browser/service_worker/service_worker_database_unittest.cc index d132f49..4fd4cb6 100644 --- a/content/browser/service_worker/service_worker_database_unittest.cc +++ b/content/browser/service_worker/service_worker_database_unittest.cc
@@ -76,8 +76,6 @@ EXPECT_EQ(expected.last_update_check, actual.last_update_check); EXPECT_EQ(expected.resources_total_size_bytes, actual.resources_total_size_bytes); - EXPECT_EQ(expected.foreign_fetch_scopes, actual.foreign_fetch_scopes); - EXPECT_EQ(expected.foreign_fetch_origins, actual.foreign_fetch_origins); EXPECT_EQ(expected.used_features, actual.used_features); } @@ -629,7 +627,6 @@ data.script = URL(origin, "/resource1"); data.version_id = 200; data.resources_total_size_bytes = 10939 + 200; - data.foreign_fetch_scopes.push_back(URL(origin, "/foo/bar")); data.used_features = {124, 901, 1019}; std::vector<Resource> resources; @@ -771,9 +768,6 @@ data.script = URL(origin, "/resource1"); data.version_id = 200; data.resources_total_size_bytes = 10 + 11; - data.foreign_fetch_scopes.push_back(URL(origin, "/foo")); - data.foreign_fetch_origins.push_back( - url::Origin::Create(GURL("https://chromium.org"))); data.used_features = {124, 901, 1019}; std::vector<Resource> resources1; @@ -805,9 +799,6 @@ updated_data.script = URL(origin, "/resource3"); updated_data.version_id = data.version_id + 1; updated_data.resources_total_size_bytes = 12 + 13; - updated_data.foreign_fetch_scopes.clear(); - updated_data.foreign_fetch_origins.push_back( - url::Origin::Create(GURL("https://example.com"))); updated_data.used_features = {109, 421, 9101}; std::vector<Resource> resources2; resources2.push_back(CreateResource(3, URL(origin, "/resource3"), 12)); @@ -1784,7 +1775,6 @@ data1.script = URL(origin1, "/resource1"); data1.version_id = 100; data1.resources_total_size_bytes = 2013 + 512; - data1.foreign_fetch_scopes.push_back(URL(origin1, "/foo/ff")); std::vector<Resource> resources1; resources1.push_back(CreateResource(1, URL(origin1, "/resource1"), 2013)); @@ -1828,7 +1818,6 @@ data3.script = URL(origin2, "/resource5"); data3.version_id = 102; data3.resources_total_size_bytes = 6 + 7; - data3.foreign_fetch_scopes.push_back(URL(origin2, "/hoge/ff")); std::vector<Resource> resources3; resources3.push_back(CreateResource(5, URL(origin2, "/resource5"), 6)); @@ -1857,13 +1846,6 @@ EXPECT_EQ(1u, unique_origins.size()); EXPECT_TRUE(base::ContainsKey(unique_origins, origin2)); - // |origin1| should be removed from the foreign fetch origin list. - unique_origins.clear(); - EXPECT_EQ(ServiceWorkerDatabase::STATUS_OK, - database->GetOriginsWithForeignFetchRegistrations(&unique_origins)); - EXPECT_EQ(1u, unique_origins.size()); - EXPECT_TRUE(base::ContainsKey(unique_origins, origin2)); - // The registrations for |origin1| should be removed. std::vector<RegistrationData> registrations; EXPECT_EQ( @@ -1938,142 +1920,6 @@ ASSERT_FALSE(base::DirectoryExists(database_dir.GetPath())); } -TEST(ServiceWorkerDatabaseTest, GetOriginsWithForeignFetchRegistrations) { - std::unique_ptr<ServiceWorkerDatabase> database(CreateDatabaseInMemory()); - - std::set<GURL> origins; - EXPECT_EQ(ServiceWorkerDatabase::STATUS_OK, - database->GetOriginsWithForeignFetchRegistrations(&origins)); - EXPECT_TRUE(origins.empty()); - - ServiceWorkerDatabase::RegistrationData deleted_version; - std::vector<int64_t> newly_purgeable_resources; - - GURL origin1("http://example.com"); - RegistrationData data1; - data1.registration_id = 123; - data1.scope = URL(origin1, "/foo"); - data1.script = URL(origin1, "/script1.js"); - data1.version_id = 456; - data1.resources_total_size_bytes = 100; - data1.foreign_fetch_scopes.push_back(URL(origin1, "/foo/bar")); - std::vector<Resource> resources1; - resources1.push_back(CreateResource(1, data1.script, 100)); - ASSERT_EQ(ServiceWorkerDatabase::STATUS_OK, - database->WriteRegistration(data1, resources1, &deleted_version, - &newly_purgeable_resources)); - - GURL origin2("https://www.example.com"); - RegistrationData data2; - data2.registration_id = 234; - data2.scope = URL(origin2, "/bar"); - data2.script = URL(origin2, "/script2.js"); - data2.version_id = 567; - data2.resources_total_size_bytes = 200; - std::vector<Resource> resources2; - resources2.push_back(CreateResource(2, data2.script, 200)); - ASSERT_EQ(ServiceWorkerDatabase::STATUS_OK, - database->WriteRegistration(data2, resources2, &deleted_version, - &newly_purgeable_resources)); - - GURL origin3("https://example.org"); - RegistrationData data3; - data3.registration_id = 345; - data3.scope = URL(origin3, "/hoge"); - data3.script = URL(origin3, "/script3.js"); - data3.version_id = 678; - data3.resources_total_size_bytes = 300; - data3.foreign_fetch_scopes.push_back(URL(origin3, "/hoge/foo")); - std::vector<Resource> resources3; - resources3.push_back(CreateResource(3, data3.script, 300)); - ASSERT_EQ(ServiceWorkerDatabase::STATUS_OK, - database->WriteRegistration(data3, resources3, &deleted_version, - &newly_purgeable_resources)); - - // |origin3| has three registrations. - RegistrationData data4; - data4.registration_id = 456; - data4.scope = URL(origin3, "/fuga"); - data4.script = URL(origin3, "/script4.js"); - data4.version_id = 789; - data4.resources_total_size_bytes = 400; - data4.foreign_fetch_scopes.push_back(URL(origin3, "/fuga/bar")); - std::vector<Resource> resources4; - resources4.push_back(CreateResource(4, data4.script, 400)); - ASSERT_EQ(ServiceWorkerDatabase::STATUS_OK, - database->WriteRegistration(data4, resources4, &deleted_version, - &newly_purgeable_resources)); - - RegistrationData data5; - data5.registration_id = 567; - data5.scope = URL(origin3, "/bla"); - data5.script = URL(origin3, "/script5.js"); - data5.version_id = 890; - data5.resources_total_size_bytes = 500; - std::vector<Resource> resources5; - resources5.push_back(CreateResource(5, data5.script, 500)); - ASSERT_EQ(ServiceWorkerDatabase::STATUS_OK, - database->WriteRegistration(data5, resources5, &deleted_version, - &newly_purgeable_resources)); - - origins.clear(); - EXPECT_EQ(ServiceWorkerDatabase::STATUS_OK, - database->GetOriginsWithForeignFetchRegistrations(&origins)); - EXPECT_EQ(2U, origins.size()); - EXPECT_TRUE(base::ContainsKey(origins, origin1)); - EXPECT_TRUE(base::ContainsKey(origins, origin3)); - - // |origin3| has another registration, so should not remove it from the - // foreign fetch origin list. - ASSERT_EQ(ServiceWorkerDatabase::STATUS_OK, - database->DeleteRegistration(data4.registration_id, origin3, - &deleted_version, - &newly_purgeable_resources)); - EXPECT_EQ(data4.registration_id, deleted_version.registration_id); - - origins.clear(); - EXPECT_EQ(ServiceWorkerDatabase::STATUS_OK, - database->GetOriginsWithForeignFetchRegistrations(&origins)); - EXPECT_EQ(2U, origins.size()); - EXPECT_TRUE(base::ContainsKey(origins, origin1)); - EXPECT_TRUE(base::ContainsKey(origins, origin3)); - - // |origin3| should be removed from the foreign fetch origin list, since its - // only remaining registration doesn't have foreign fetch scopes. - ASSERT_EQ(ServiceWorkerDatabase::STATUS_OK, - database->DeleteRegistration(data3.registration_id, origin3, - &deleted_version, - &newly_purgeable_resources)); - EXPECT_EQ(data3.registration_id, deleted_version.registration_id); - - origins.clear(); - EXPECT_EQ(ServiceWorkerDatabase::STATUS_OK, - database->GetOriginsWithForeignFetchRegistrations(&origins)); - EXPECT_EQ(1U, origins.size()); - EXPECT_TRUE(base::ContainsKey(origins, origin1)); - - // |origin1| should be removed from the foreign fetch origin list, since we - // replace its registration with one without scopes. - RegistrationData updated_data1 = data1; - updated_data1.version_id++; - updated_data1.resources_total_size_bytes = 12 + 13; - updated_data1.foreign_fetch_scopes.clear(); - std::vector<Resource> updated_resources1; - updated_resources1.push_back( - CreateResource(13, URL(origin1, "/resource3"), 12)); - updated_resources1.push_back( - CreateResource(14, URL(origin1, "/resource4"), 13)); - EXPECT_EQ(ServiceWorkerDatabase::STATUS_OK, - database->WriteRegistration(updated_data1, updated_resources1, - &deleted_version, - &newly_purgeable_resources)); - - origins.clear(); - EXPECT_EQ(ServiceWorkerDatabase::STATUS_OK, - database->GetOriginsWithForeignFetchRegistrations(&origins)); - EXPECT_EQ(0U, origins.size()); -} - TEST(ServiceWorkerDatabaseTest, Corruption_NoMainResource) { std::unique_ptr<ServiceWorkerDatabase> database(CreateDatabaseInMemory()); ServiceWorkerDatabase::RegistrationData deleted_version;
diff --git a/content/browser/service_worker/service_worker_dispatcher_host.cc b/content/browser/service_worker/service_worker_dispatcher_host.cc index 72edad2..a4e5b723 100644 --- a/content/browser/service_worker/service_worker_dispatcher_host.cc +++ b/content/browser/service_worker/service_worker_dispatcher_host.cc
@@ -25,7 +25,6 @@ #include "content/common/service_worker/embedded_worker_messages.h" #include "content/common/service_worker/service_worker_event_dispatcher.mojom.h" #include "content/common/service_worker/service_worker_messages.h" -#include "content/common/service_worker/service_worker_types.h" #include "content/common/service_worker/service_worker_utils.h" #include "content/public/browser/content_browser_client.h" #include "content/public/browser/render_frame_host.h" @@ -35,6 +34,7 @@ #include "content/public/common/content_client.h" #include "content/public/common/origin_util.h" #include "ipc/ipc_message_macros.h" +#include "third_party/WebKit/common/service_worker/service_worker_provider_type.mojom.h" #include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerError.h" #include "third_party/WebKit/public/platform/modules/serviceworker/service_worker_error_type.mojom.h" #include "third_party/WebKit/public/platform/modules/serviceworker/service_worker_object.mojom.h" @@ -231,8 +231,8 @@ ServiceWorkerProviderHost* sender_provider_host, const StatusCallback& callback) { switch (sender_provider_host->provider_type()) { - case SERVICE_WORKER_PROVIDER_FOR_WINDOW: - case SERVICE_WORKER_PROVIDER_FOR_SHARED_WORKER: + case blink::mojom::ServiceWorkerProviderType::kForWindow: + case blink::mojom::ServiceWorkerProviderType::kForSharedWorker: service_worker_client_utils::GetClient( sender_provider_host, base::Bind(&ServiceWorkerDispatcherHost:: @@ -241,7 +241,7 @@ this, worker, message, source_origin, sent_message_ports, base::nullopt, callback)); break; - case SERVICE_WORKER_PROVIDER_FOR_SERVICE_WORKER: { + case blink::mojom::ServiceWorkerProviderType::kForServiceWorker: { // Clamp timeout to the sending worker's remaining timeout, to prevent // postMessage from keeping workers alive forever. base::TimeDelta timeout = @@ -260,7 +260,7 @@ callback, *worker_info)); break; } - case SERVICE_WORKER_PROVIDER_UNKNOWN: + case blink::mojom::ServiceWorkerProviderType::kUnknown: default: NOTREACHED() << sender_provider_host->provider_type(); break; @@ -298,7 +298,7 @@ } // Otherwise, completed the initialization of the pre-created host. - if (info.type != SERVICE_WORKER_PROVIDER_FOR_WINDOW) { + if (info.type != blink::mojom::ServiceWorkerProviderType::kForWindow) { bad_message::ReceivedBadMessage( this, bad_message::SWDH_PROVIDER_CREATED_ILLEGAL_TYPE_NOT_WINDOW); return; @@ -309,7 +309,8 @@ } else { // Provider hosts for service workers should be pre-created in StartWorker // in ServiceWorkerVersion. - if (info.type == SERVICE_WORKER_PROVIDER_FOR_SERVICE_WORKER) { + if (info.type == + blink::mojom::ServiceWorkerProviderType::kForServiceWorker) { bad_message::ReceivedBadMessage( this, bad_message::SWDH_PROVIDER_CREATED_ILLEGAL_TYPE_CONTROLLER); return;
diff --git a/content/browser/service_worker/service_worker_dispatcher_host_unittest.cc b/content/browser/service_worker/service_worker_dispatcher_host_unittest.cc index 6e664cca..6e30afa 100644 --- a/content/browser/service_worker/service_worker_dispatcher_host_unittest.cc +++ b/content/browser/service_worker/service_worker_dispatcher_host_unittest.cc
@@ -26,13 +26,13 @@ #include "content/browser/service_worker/service_worker_test_utils.h" #include "content/common/service_worker/embedded_worker_messages.h" #include "content/common/service_worker/service_worker_messages.h" -#include "content/common/service_worker/service_worker_types.h" #include "content/common/service_worker/service_worker_utils.h" #include "content/public/common/browser_side_navigation_policy.h" #include "content/public/common/content_switches.h" #include "content/public/test/mock_resource_context.h" #include "content/public/test/test_browser_thread_bundle.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/WebKit/common/service_worker/service_worker_provider_type.mojom.h" #include "third_party/WebKit/public/platform/modules/serviceworker/service_worker.mojom.h" #include "third_party/WebKit/public/platform/modules/serviceworker/service_worker_registration.mojom.h" @@ -207,7 +207,7 @@ EXPECT_EQ(SERVICE_WORKER_OK, status); } - void SendProviderCreated(ServiceWorkerProviderType type, + void SendProviderCreated(blink::mojom::ServiceWorkerProviderType type, const GURL& pattern) { const int64_t kProviderId = 99; ServiceWorkerProviderHostInfo info(kProviderId, MSG_ROUTING_NONE, type, @@ -261,6 +261,7 @@ } TestBrowserThreadBundle browser_thread_bundle_; + base::SimpleTestTickClock tick_clock_; content::MockResourceContext resource_context_; std::unique_ptr<EmbeddedWorkerTestHelper> helper_; scoped_refptr<TestingServiceWorkerDispatcherHost> dispatcher_host_; @@ -277,15 +278,18 @@ int process_id = helper_->mock_render_process_id(); // Setup ServiceWorkerProviderHostInfo. - ServiceWorkerProviderHostInfo host_info_1(kProviderId, 1 /* route_id */, - SERVICE_WORKER_PROVIDER_FOR_WINDOW, - true /* is_parent_frame_secure */); - ServiceWorkerProviderHostInfo host_info_2(kProviderId, 1 /* route_id */, - SERVICE_WORKER_PROVIDER_FOR_WINDOW, - true /* is_parent_frame_secure */); - ServiceWorkerProviderHostInfo host_info_3(kProviderId, 1 /* route_id */, - SERVICE_WORKER_PROVIDER_FOR_WINDOW, - true /* is_parent_frame_secure */); + ServiceWorkerProviderHostInfo host_info_1( + kProviderId, 1 /* route_id */, + blink::mojom::ServiceWorkerProviderType::kForWindow, + true /* is_parent_frame_secure */); + ServiceWorkerProviderHostInfo host_info_2( + kProviderId, 1 /* route_id */, + blink::mojom::ServiceWorkerProviderType::kForWindow, + true /* is_parent_frame_secure */); + ServiceWorkerProviderHostInfo host_info_3( + kProviderId, 1 /* route_id */, + blink::mojom::ServiceWorkerProviderType::kForWindow, + true /* is_parent_frame_secure */); RemoteProviderInfo remote_info_1 = SetupProviderHostInfoPtrs(&host_info_1); RemoteProviderInfo remote_info_2 = SetupProviderHostInfoPtrs(&host_info_2); RemoteProviderInfo remote_info_3 = SetupProviderHostInfoPtrs(&host_info_3); @@ -342,7 +346,8 @@ GURL script_url = GURL("http://www.example.com/service_worker.js"); int process_id = helper_->mock_render_process_id(); - SendProviderCreated(SERVICE_WORKER_PROVIDER_FOR_WINDOW, pattern); + SendProviderCreated(blink::mojom::ServiceWorkerProviderType::kForWindow, + pattern); SetUpRegistration(pattern, script_url); int64_t provider_id = provider_host_->provider_id(); @@ -380,9 +385,10 @@ // To show the new dispatcher can operate, simulate provider creation. Since // the old dispatcher cleaned up the old provider host, the new one won't // complain. - ServiceWorkerProviderHostInfo host_info(provider_id, MSG_ROUTING_NONE, - SERVICE_WORKER_PROVIDER_FOR_WINDOW, - true /* is_parent_frame_secure */); + ServiceWorkerProviderHostInfo host_info( + provider_id, MSG_ROUTING_NONE, + blink::mojom::ServiceWorkerProviderType::kForWindow, + true /* is_parent_frame_secure */); ServiceWorkerRemoteProviderEndpoint remote_endpoint; remote_endpoint.BindWithProviderHostInfo(&host_info); new_dispatcher_host->OnProviderCreated(std::move(host_info)); @@ -408,9 +414,8 @@ const int ref_count = sender_worker_handle->ref_count(); // Set mock clock on version_ to check timeout behavior. - base::SimpleTestTickClock* tick_clock = new base::SimpleTestTickClock(); - tick_clock->SetNowTicks(base::TimeTicks::Now()); - version_->SetTickClockForTesting(base::WrapUnique(tick_clock)); + tick_clock_.SetNowTicks(base::TimeTicks::Now()); + version_->SetTickClockForTesting(&tick_clock_); // Make sure worker has a non-zero timeout. bool called = false; @@ -426,7 +431,7 @@ base::TimeDelta::FromSeconds(10), ServiceWorkerVersion::KILL_ON_TIMEOUT); // Advance clock by a couple seconds. - tick_clock->Advance(base::TimeDelta::FromSeconds(4)); + tick_clock_.Advance(base::TimeDelta::FromSeconds(4)); base::TimeDelta remaining_time = version_->remaining_timeout(); EXPECT_EQ(base::TimeDelta::FromSeconds(6), remaining_time); @@ -455,7 +460,8 @@ GURL script_url = GURL("http://www.example.com/service_worker.js"); Initialize(base::WrapUnique(new FailToStartWorkerTestHelper)); - SendProviderCreated(SERVICE_WORKER_PROVIDER_FOR_SHARED_WORKER, pattern); + SendProviderCreated(blink::mojom::ServiceWorkerProviderType::kForSharedWorker, + pattern); SetUpRegistration(pattern, script_url); // Try to dispatch ExtendableMessageEvent. This should fail to start the
diff --git a/content/browser/service_worker/service_worker_fetch_dispatcher.cc b/content/browser/service_worker/service_worker_fetch_dispatcher.cc index f332b96..2d0a618 100644 --- a/content/browser/service_worker/service_worker_fetch_dispatcher.cc +++ b/content/browser/service_worker/service_worker_fetch_dispatcher.cc
@@ -289,13 +289,6 @@ base::Bind(&NetLogServiceWorkerStatusCallback, status)); } -ServiceWorkerMetrics::EventType FetchTypeToWaitUntilEventType( - ServiceWorkerFetchType type) { - if (type == ServiceWorkerFetchType::FOREIGN_FETCH) - return ServiceWorkerMetrics::EventType::FOREIGN_FETCH_WAITUNTIL; - return ServiceWorkerMetrics::EventType::FETCH_WAITUNTIL; -} - const net::NetworkTrafficAnnotationTag kNavigationPreloadTrafficAnnotation = net::DefineNetworkTrafficAnnotation("service_worker_navigation_preload", R"( @@ -604,7 +597,7 @@ std::move(response_callback)), *timeout_, ServiceWorkerVersion::CONTINUE_ON_TIMEOUT); event_finish_id = version_->StartRequestWithCustomTimeout( - FetchTypeToWaitUntilEventType(GetFetchType()), + ServiceWorkerMetrics::EventType::FETCH_WAITUNTIL, base::BindOnce(&ServiceWorkerUtils::NoOpStatusCallback), *timeout_, ServiceWorkerVersion::CONTINUE_ON_TIMEOUT); } else { @@ -614,7 +607,7 @@ weak_factory_.GetWeakPtr(), std::move(response_callback))); event_finish_id = version_->StartRequest( - FetchTypeToWaitUntilEventType(GetFetchType()), + ServiceWorkerMetrics::EventType::FETCH_WAITUNTIL, base::BindOnce(&ServiceWorkerUtils::NoOpStatusCallback)); } response_callback_rawptr->set_fetch_event_id(fetch_event_id); @@ -871,8 +864,6 @@ ServiceWorkerMetrics::EventType ServiceWorkerFetchDispatcher::GetEventType() const { - if (GetFetchType() == ServiceWorkerFetchType::FOREIGN_FETCH) - return ServiceWorkerMetrics::EventType::FOREIGN_FETCH; return ResourceTypeToEventType(resource_type_); }
diff --git a/content/browser/service_worker/service_worker_info.cc b/content/browser/service_worker/service_worker_info.cc index 9703edd5..0bf9e35 100644 --- a/content/browser/service_worker/service_worker_info.cc +++ b/content/browser/service_worker/service_worker_info.cc
@@ -18,13 +18,13 @@ : ClientInfo(ChildProcessHost::kInvalidUniqueID, MSG_ROUTING_NONE, base::Callback<WebContents*(void)>(), - SERVICE_WORKER_PROVIDER_UNKNOWN) {} + blink::mojom::ServiceWorkerProviderType::kUnknown) {} ServiceWorkerVersionInfo::ClientInfo::ClientInfo( int process_id, int route_id, const base::Callback<WebContents*(void)>& web_contents_getter, - ServiceWorkerProviderType type) + blink::mojom::ServiceWorkerProviderType type) : process_id(process_id), route_id(route_id), web_contents_getter(web_contents_getter),
diff --git a/content/browser/service_worker/service_worker_info.h b/content/browser/service_worker/service_worker_info.h index eef4eafb..2e81a1a 100644 --- a/content/browser/service_worker/service_worker_info.h +++ b/content/browser/service_worker/service_worker_info.h
@@ -14,6 +14,7 @@ #include "content/browser/service_worker/service_worker_version.h" #include "content/common/content_export.h" #include "content/common/service_worker/service_worker_types.h" +#include "third_party/WebKit/common/service_worker/service_worker_provider_type.mojom.h" #include "url/gurl.h" namespace content { @@ -28,14 +29,14 @@ ClientInfo(int process_id, int route_id, const base::Callback<WebContents*(void)>& web_contents_getter, - ServiceWorkerProviderType type); + blink::mojom::ServiceWorkerProviderType type); ClientInfo(const ClientInfo& other); ~ClientInfo(); int process_id; int route_id; // |web_contents_getter| is only set for PlzNavigate. base::Callback<WebContents*(void)> web_contents_getter; - ServiceWorkerProviderType type; + blink::mojom::ServiceWorkerProviderType type; }; ServiceWorkerVersionInfo();
diff --git a/content/browser/service_worker/service_worker_job_unittest.cc b/content/browser/service_worker/service_worker_job_unittest.cc index 1d321564..d264b6ce 100644 --- a/content/browser/service_worker/service_worker_job_unittest.cc +++ b/content/browser/service_worker/service_worker_job_unittest.cc
@@ -141,25 +141,6 @@ return base::Bind(&SaveUnregistrationCallback, expected_status, called); } -// This is for the test of mojom::ServiceWorkerInstallEventMethods. -void RegisterForeignFetchScopes( - mojom::ServiceWorkerInstallEventMethodsAssociatedPtrInfo client) { - GURL valid_scope_1("http://www.example.com/test/subscope"); - GURL valid_scope_2("http://www.example.com/test/othersubscope"); - std::vector<GURL> valid_scopes; - valid_scopes.push_back(valid_scope_1); - valid_scopes.push_back(valid_scope_2); - - std::vector<url::Origin> all_origins; - url::Origin valid_origin = url::Origin::Create(GURL("https://chromium.org/")); - std::vector<url::Origin> valid_origin_list(1, valid_origin); - - mojom::ServiceWorkerInstallEventMethodsAssociatedPtr install_event_methods; - install_event_methods.Bind(std::move(client)); - install_event_methods->RegisterForeignFetchScopes(valid_scopes, - valid_origin_list); -} - } // namespace class ServiceWorkerJobTest : public testing::Test { @@ -335,46 +316,17 @@ ASSERT_NE(registration1, registration2); } -class RegisterForeignFetchTestHelper : public EmbeddedWorkerTestHelper { - public: - RegisterForeignFetchTestHelper() - : EmbeddedWorkerTestHelper(base::FilePath()) {} - - void OnInstallEvent( - mojom::ServiceWorkerInstallEventMethodsAssociatedPtrInfo client, - mojom::ServiceWorkerEventDispatcher::DispatchInstallEventCallback - callback) override { - RegisterForeignFetchScopes(std::move(client)); - dispatched_events()->push_back(Event::Install); - std::move(callback).Run(blink::mojom::ServiceWorkerEventStatus::COMPLETED, - true /* has_fetch_handler */, base::Time::Now()); - } -}; - // Make sure basic registration is working. TEST_F(ServiceWorkerJobTest, Register) { - helper_.reset(new RegisterForeignFetchTestHelper); - scoped_refptr<ServiceWorkerRegistration> registration = RunRegisterJob(GURL("http://www.example.com/"), GURL("http://www.example.com/service_worker.js")); - ASSERT_NE(scoped_refptr<ServiceWorkerRegistration>(nullptr), registration); + EXPECT_TRUE(registration); EXPECT_EQ(EmbeddedWorkerTestHelper::Event::Install, helper_->dispatched_events()->at(0)); EXPECT_EQ(EmbeddedWorkerTestHelper::Event::Activate, helper_->dispatched_events()->at(1)); - - GURL valid_scope_1("http://www.example.com/test/subscope"); - GURL valid_scope_2("http://www.example.com/test/othersubscope"); - url::Origin valid_origin = url::Origin::Create(GURL("https://chromium.org/")); - - ServiceWorkerVersion* version_ = registration->active_version(); - EXPECT_EQ(2u, version_->foreign_fetch_scopes_.size()); - EXPECT_EQ(valid_scope_1, version_->foreign_fetch_scopes_[0]); - EXPECT_EQ(valid_scope_2, version_->foreign_fetch_scopes_[1]); - EXPECT_EQ(1u, version_->foreign_fetch_origins_.size()); - EXPECT_EQ(valid_origin, version_->foreign_fetch_origins_[0]); } // Make sure registrations are cleaned up when they are unregistered. @@ -1629,7 +1581,6 @@ blink::mojom::ServiceWorkerEventStatus::COMPLETED) {} void OnInstallEvent( - mojom::ServiceWorkerInstallEventMethodsAssociatedPtrInfo client, mojom::ServiceWorkerEventDispatcher::DispatchInstallEventCallback callback) override { if (!install_callback_.is_null())
diff --git a/content/browser/service_worker/service_worker_lifetime_tracker.cc b/content/browser/service_worker/service_worker_lifetime_tracker.cc index f10fe80..6a6d28cf 100644 --- a/content/browser/service_worker/service_worker_lifetime_tracker.cc +++ b/content/browser/service_worker/service_worker_lifetime_tracker.cc
@@ -12,12 +12,11 @@ namespace content { ServiceWorkerLifetimeTracker::ServiceWorkerLifetimeTracker() - : ServiceWorkerLifetimeTracker(std::make_unique<base::DefaultTickClock>()) { -} + : ServiceWorkerLifetimeTracker(base::DefaultTickClock::GetInstance()) {} ServiceWorkerLifetimeTracker::ServiceWorkerLifetimeTracker( - std::unique_ptr<base::TickClock> tick_clock) - : tick_clock_(std::move(tick_clock)) {} + base::TickClock* tick_clock) + : tick_clock_(tick_clock) {} ServiceWorkerLifetimeTracker::~ServiceWorkerLifetimeTracker() = default;
diff --git a/content/browser/service_worker/service_worker_lifetime_tracker.h b/content/browser/service_worker/service_worker_lifetime_tracker.h index b9cb2bcb..12b0eb1 100644 --- a/content/browser/service_worker/service_worker_lifetime_tracker.h +++ b/content/browser/service_worker/service_worker_lifetime_tracker.h
@@ -22,8 +22,7 @@ class CONTENT_EXPORT ServiceWorkerLifetimeTracker { public: ServiceWorkerLifetimeTracker(); - explicit ServiceWorkerLifetimeTracker( - std::unique_ptr<base::TickClock> tick_clock); + explicit ServiceWorkerLifetimeTracker(base::TickClock* tick_clock); virtual ~ServiceWorkerLifetimeTracker(); // Called when the worker started running. @@ -39,7 +38,7 @@ void RecordHistograms(); - std::unique_ptr<base::TickClock> tick_clock_; + base::TickClock* tick_clock_; std::map<int64_t /* embedded_worker_id */, base::TimeTicks /* start_time */> running_workers_;
diff --git a/content/browser/service_worker/service_worker_lifetime_tracker_unittest.cc b/content/browser/service_worker/service_worker_lifetime_tracker_unittest.cc index 75754826..9b42bdb 100644 --- a/content/browser/service_worker/service_worker_lifetime_tracker_unittest.cc +++ b/content/browser/service_worker/service_worker_lifetime_tracker_unittest.cc
@@ -14,16 +14,13 @@ class ServiceWorkerLifetimeTrackerTest : public testing::Test { public: - ServiceWorkerLifetimeTrackerTest() - : tick_clock_(new base::SimpleTestTickClock()), - tracker_(base::WrapUnique(tick_clock_)) {} + ServiceWorkerLifetimeTrackerTest() : tracker_(&tick_clock_) {} - base::SimpleTestTickClock* tick_clock() { return tick_clock_; } + base::SimpleTestTickClock* tick_clock() { return &tick_clock_; } ServiceWorkerLifetimeTracker* tracker() { return &tracker_; } private: - // Not owned. - base::SimpleTestTickClock* tick_clock_; + base::SimpleTestTickClock tick_clock_; ServiceWorkerLifetimeTracker tracker_; };
diff --git a/content/browser/service_worker/service_worker_provider_host.cc b/content/browser/service_worker/service_worker_provider_host.cc index 2909f3d..ca80f936 100644 --- a/content/browser/service_worker/service_worker_provider_host.cc +++ b/content/browser/service_worker/service_worker_provider_host.cc
@@ -149,7 +149,8 @@ ChildProcessHost::kInvalidUniqueID, ServiceWorkerProviderHostInfo( NextBrowserProvidedProviderId(), MSG_ROUTING_NONE, - SERVICE_WORKER_PROVIDER_FOR_WINDOW, are_ancestors_secure), + blink::mojom::ServiceWorkerProviderType::kForWindow, + are_ancestors_secure), context, nullptr /* dispatcher_host */)); host->web_contents_getter_ = web_contents_getter; return host; @@ -161,10 +162,10 @@ base::WeakPtr<ServiceWorkerContextCore> context) { auto host = base::WrapUnique(new ServiceWorkerProviderHost( ChildProcessHost::kInvalidUniqueID, - ServiceWorkerProviderHostInfo(NextBrowserProvidedProviderId(), - MSG_ROUTING_NONE, - SERVICE_WORKER_PROVIDER_FOR_SERVICE_WORKER, - true /* is_parent_frame_secure */), + ServiceWorkerProviderHostInfo( + NextBrowserProvidedProviderId(), MSG_ROUTING_NONE, + blink::mojom::ServiceWorkerProviderType::kForServiceWorker, + true /* is_parent_frame_secure */), std::move(context), nullptr)); return host; } @@ -194,9 +195,10 @@ allow_association_(true), binding_(this), interface_provider_binding_(this) { - DCHECK_NE(SERVICE_WORKER_PROVIDER_UNKNOWN, info_.type); + DCHECK_NE(blink::mojom::ServiceWorkerProviderType::kUnknown, info_.type); - if (info_.type == SERVICE_WORKER_PROVIDER_FOR_SERVICE_WORKER) { + if (info_.type == + blink::mojom::ServiceWorkerProviderType::kForServiceWorker) { // Actual |render_process_id| will be set after choosing a process for the // controller, and |render_thread id| will be set when the service worker // context gets started. @@ -215,7 +217,8 @@ // CompleteStartWorkerPreparation (providers for service workers). if (!info_.client_ptr_info.is_valid() && !info_.host_request.is_pending()) { DCHECK(IsBrowserSideNavigationEnabled() || - info_.type == SERVICE_WORKER_PROVIDER_FOR_SERVICE_WORKER); + info_.type == + blink::mojom::ServiceWorkerProviderType::kForServiceWorker); return; } @@ -244,7 +247,7 @@ } int ServiceWorkerProviderHost::frame_id() const { - if (info_.type == SERVICE_WORKER_PROVIDER_FOR_WINDOW) + if (info_.type == blink::mojom::ServiceWorkerProviderType::kForWindow) return info_.route_id; return MSG_ROUTING_NONE; } @@ -345,12 +348,12 @@ bool ServiceWorkerProviderHost::IsProviderForClient() const { switch (info_.type) { - case SERVICE_WORKER_PROVIDER_FOR_WINDOW: - case SERVICE_WORKER_PROVIDER_FOR_SHARED_WORKER: + case blink::mojom::ServiceWorkerProviderType::kForWindow: + case blink::mojom::ServiceWorkerProviderType::kForSharedWorker: return true; - case SERVICE_WORKER_PROVIDER_FOR_SERVICE_WORKER: + case blink::mojom::ServiceWorkerProviderType::kForServiceWorker: return false; - case SERVICE_WORKER_PROVIDER_UNKNOWN: + case blink::mojom::ServiceWorkerProviderType::kUnknown: NOTREACHED() << info_.type; } NOTREACHED() << info_.type; @@ -360,12 +363,12 @@ blink::mojom::ServiceWorkerClientType ServiceWorkerProviderHost::client_type() const { switch (info_.type) { - case SERVICE_WORKER_PROVIDER_FOR_WINDOW: + case blink::mojom::ServiceWorkerProviderType::kForWindow: return blink::mojom::ServiceWorkerClientType::kWindow; - case SERVICE_WORKER_PROVIDER_FOR_SHARED_WORKER: + case blink::mojom::ServiceWorkerProviderType::kForSharedWorker: return blink::mojom::ServiceWorkerClientType::kSharedWorker; - case SERVICE_WORKER_PROVIDER_FOR_SERVICE_WORKER: - case SERVICE_WORKER_PROVIDER_UNKNOWN: + case blink::mojom::ServiceWorkerProviderType::kForServiceWorker: + case blink::mojom::ServiceWorkerProviderType::kUnknown: NOTREACHED() << info_.type; } NOTREACHED() << info_.type; @@ -577,7 +580,7 @@ DCHECK_NE(ChildProcessHost::kInvalidUniqueID, render_process_id_); DCHECK_NE(MSG_ROUTING_NONE, info_.route_id); DCHECK_EQ(kDocumentMainThreadId, render_thread_id_); - DCHECK_NE(SERVICE_WORKER_PROVIDER_UNKNOWN, info_.type); + DCHECK_NE(blink::mojom::ServiceWorkerProviderType::kUnknown, info_.type); // Clear the controller from the renderer-side provider, since no one knows // what's going to happen until after cross-site transfer finishes. @@ -647,7 +650,7 @@ base::WeakPtr<ServiceWorkerDispatcherHost> dispatcher_host) { CHECK(IsBrowserSideNavigationEnabled()); DCHECK_EQ(ChildProcessHost::kInvalidUniqueID, render_process_id_); - DCHECK_EQ(SERVICE_WORKER_PROVIDER_FOR_WINDOW, info_.type); + DCHECK_EQ(blink::mojom::ServiceWorkerProviderType::kForWindow, info_.type); DCHECK_EQ(kDocumentMainThreadId, render_thread_id_); DCHECK_NE(ChildProcessHost::kInvalidUniqueID, process_id); @@ -687,7 +690,8 @@ DCHECK(context_); DCHECK_EQ(kInvalidEmbeddedWorkerThreadId, render_thread_id_); DCHECK_EQ(ChildProcessHost::kInvalidUniqueID, render_process_id_); - DCHECK_EQ(SERVICE_WORKER_PROVIDER_FOR_SERVICE_WORKER, provider_type()); + DCHECK_EQ(blink::mojom::ServiceWorkerProviderType::kForServiceWorker, + provider_type()); DCHECK(!running_hosted_version_); DCHECK_NE(ChildProcessHost::kInvalidUniqueID, process_id);
diff --git a/content/browser/service_worker/service_worker_provider_host.h b/content/browser/service_worker/service_worker_provider_host.h index bf8565ed..f4c69d0 100644 --- a/content/browser/service_worker/service_worker_provider_host.h +++ b/content/browser/service_worker/service_worker_provider_host.h
@@ -32,6 +32,7 @@ #include "mojo/public/cpp/bindings/binding.h" #include "mojo/public/cpp/bindings/binding_set.h" #include "services/network/public/interfaces/fetch_api.mojom.h" +#include "third_party/WebKit/common/service_worker/service_worker_provider_type.mojom.h" #include "third_party/WebKit/public/platform/modules/serviceworker/service_worker_registration.mojom.h" namespace blink { @@ -192,7 +193,8 @@ // loads for. ServiceWorkerVersion* running_hosted_version() const { DCHECK(!running_hosted_version_ || - info_.type == SERVICE_WORKER_PROVIDER_FOR_SERVICE_WORKER); + info_.type == + blink::mojom::ServiceWorkerProviderType::kForServiceWorker); return running_hosted_version_.get(); } @@ -205,7 +207,9 @@ void SetTopmostFrameUrl(const GURL& url); const GURL& topmost_frame_url() const { return topmost_frame_url_; } - ServiceWorkerProviderType provider_type() const { return info_.type; } + blink::mojom::ServiceWorkerProviderType provider_type() const { + return info_.type; + } bool IsProviderForClient() const; blink::mojom::ServiceWorkerClientType client_type() const; @@ -328,7 +332,6 @@ void NotifyControllerLost(); private: - friend class ForeignFetchRequestHandlerTest; friend class LinkHeaderServiceWorkerTest; friend class ServiceWorkerProviderHostTest; friend class ServiceWorkerWriteToCacheJobTest;
diff --git a/content/browser/service_worker/service_worker_provider_host_unittest.cc b/content/browser/service_worker/service_worker_provider_host_unittest.cc index 7363573..ef789a8 100644 --- a/content/browser/service_worker/service_worker_provider_host_unittest.cc +++ b/content/browser/service_worker/service_worker_provider_host_unittest.cc
@@ -221,9 +221,10 @@ host = ServiceWorkerProviderHost::PreCreateNavigationHost( helper_->context()->AsWeakPtr(), true, base::Callback<WebContents*(void)>()); - ServiceWorkerProviderHostInfo info(host->provider_id(), 1 /* route_id */, - SERVICE_WORKER_PROVIDER_FOR_WINDOW, - true /* is_parent_frame_secure */); + ServiceWorkerProviderHostInfo info( + host->provider_id(), 1 /* route_id */, + blink::mojom::ServiceWorkerProviderType::kForWindow, + true /* is_parent_frame_secure */); remote_endpoint->BindWithProviderHostInfo(&info); host->CompleteNavigationInitialized( helper_->mock_render_process_id(), std::move(info), @@ -402,7 +403,8 @@ const int process_id = provider_host->process_id(); const int provider_id = provider_host->provider_id(); const int frame_id = provider_host->frame_id(); - const ServiceWorkerProviderType type = provider_host->provider_type(); + const blink::mojom::ServiceWorkerProviderType type = + provider_host->provider_type(); const bool is_parent_frame_secure = provider_host->is_parent_frame_secure(); const ServiceWorkerDispatcherHost* dispatcher_host = provider_host->dispatcher_host(); @@ -422,7 +424,8 @@ EXPECT_EQ(ChildProcessHost::kInvalidUniqueID, provider_host->process_id()); EXPECT_EQ(kInvalidServiceWorkerProviderId, provider_host->provider_id()); EXPECT_EQ(MSG_ROUTING_NONE, provider_host->frame_id()); - EXPECT_EQ(SERVICE_WORKER_PROVIDER_UNKNOWN, provider_host->provider_type()); + EXPECT_EQ(blink::mojom::ServiceWorkerProviderType::kUnknown, + provider_host->provider_type()); EXPECT_FALSE(provider_host->is_parent_frame_secure()); EXPECT_EQ(nullptr, provider_host->dispatcher_host()); @@ -439,7 +442,8 @@ EXPECT_EQ(kInvalidServiceWorkerProviderId, provisional_host->provider_id()); EXPECT_EQ(MSG_ROUTING_NONE, provisional_host->frame_id()); - EXPECT_EQ(SERVICE_WORKER_PROVIDER_UNKNOWN, provisional_host->provider_type()); + EXPECT_EQ(blink::mojom::ServiceWorkerProviderType::kUnknown, + provisional_host->provider_type()); EXPECT_FALSE(provisional_host->is_parent_frame_secure()); EXPECT_EQ(dispatcher_host, provisional_host->dispatcher_host()); @@ -495,9 +499,10 @@ ServiceWorkerProviderHost::PreCreateNavigationHost( helper_->context()->AsWeakPtr(), true /* are_ancestors_secure */, base::Callback<WebContents*(void)>()); - ServiceWorkerProviderHostInfo info(host->provider_id(), 1 /* route_id */, - SERVICE_WORKER_PROVIDER_FOR_WINDOW, - true /* is_parent_frame_secure */); + ServiceWorkerProviderHostInfo info( + host->provider_id(), 1 /* route_id */, + blink::mojom::ServiceWorkerProviderType::kForWindow, + true /* is_parent_frame_secure */); remote_endpoints_.emplace_back(); remote_endpoints_.back().BindWithProviderHostInfo(&info); auto container = std::make_unique<MockServiceWorkerContainer>( @@ -535,9 +540,10 @@ ServiceWorkerProviderHost::PreCreateNavigationHost( helper_->context()->AsWeakPtr(), true /* are_ancestors_secure */, base::Callback<WebContents*(void)>()); - ServiceWorkerProviderHostInfo info(host->provider_id(), 1 /* route_id */, - SERVICE_WORKER_PROVIDER_FOR_WINDOW, - true /* is_parent_frame_secure */); + ServiceWorkerProviderHostInfo info( + host->provider_id(), 1 /* route_id */, + blink::mojom::ServiceWorkerProviderType::kForWindow, + true /* is_parent_frame_secure */); remote_endpoints_.emplace_back(); remote_endpoints_.back().BindWithProviderHostInfo(&info); auto container = std::make_unique<MockServiceWorkerContainer>(
diff --git a/content/browser/service_worker/service_worker_register_job.cc b/content/browser/service_worker/service_worker_register_job.cc index 52f51758..2a0c311 100644 --- a/content/browser/service_worker/service_worker_register_job.cc +++ b/content/browser/service_worker/service_worker_register_job.cc
@@ -29,39 +29,6 @@ namespace content { -namespace { - -class InstallEventMethodsReceiver - : public mojom::ServiceWorkerInstallEventMethods { - public: - InstallEventMethodsReceiver(ServiceWorkerVersion* version) - : version_(version), install_methods_binding_(this) {} - ~InstallEventMethodsReceiver() override {} - - void BindInterface( - mojom::ServiceWorkerInstallEventMethodsAssociatedPtrInfo* ptr_info) { - install_methods_binding_.Bind(mojo::MakeRequest(ptr_info)); - } - - // Implements mojom::ServiceWorkerInstallEventMethod. - void RegisterForeignFetchScopes( - const std::vector<GURL>& sub_scopes, - const std::vector<url::Origin>& origins) override { - DCHECK(version_); - version_->RegisterForeignFetchScopes(sub_scopes, origins); - } - - private: - ServiceWorkerVersion* version_; - - mojo::AssociatedBinding<mojom::ServiceWorkerInstallEventMethods> - install_methods_binding_; - - DISALLOW_COPY_AND_ASSIGN(InstallEventMethodsReceiver); -}; - -} // namespace - typedef ServiceWorkerRegisterJobBase::RegistrationJobType RegistrationJobType; ServiceWorkerRegisterJob::ServiceWorkerRegisterJob( @@ -465,24 +432,16 @@ base::Bind(&ServiceWorkerRegisterJob::OnInstallFailed, weak_factory_.GetWeakPtr())); - std::unique_ptr<InstallEventMethodsReceiver> install_methods_receiver = - std::make_unique<InstallEventMethodsReceiver>(new_version()); - mojom::ServiceWorkerInstallEventMethodsAssociatedPtrInfo ptr_info; - install_methods_receiver->BindInterface(&ptr_info); new_version()->event_dispatcher()->DispatchInstallEvent( - std::move(ptr_info), base::BindOnce(&ServiceWorkerRegisterJob::OnInstallFinished, - weak_factory_.GetWeakPtr(), request_id, - base::Passed(&install_methods_receiver))); + weak_factory_.GetWeakPtr(), request_id)); } void ServiceWorkerRegisterJob::OnInstallFinished( int request_id, - std::unique_ptr<InstallEventMethodsReceiver> install_methods_receiver, blink::mojom::ServiceWorkerEventStatus event_status, bool has_fetch_handler, base::Time dispatch_event_time) { - install_methods_receiver.reset(); bool succeeded = event_status == blink::mojom::ServiceWorkerEventStatus::COMPLETED; new_version()->FinishRequest(request_id, succeeded, dispatch_event_time); @@ -493,9 +452,6 @@ } ServiceWorkerMetrics::RecordInstallEventStatus(SERVICE_WORKER_OK); - ServiceWorkerMetrics::RecordForeignFetchRegistrationCount( - new_version()->foreign_fetch_scopes().size(), - new_version()->foreign_fetch_origins().size()); SetPhase(STORE); DCHECK(!registration()->last_update_check().is_null());
diff --git a/content/browser/service_worker/service_worker_register_job.h b/content/browser/service_worker/service_worker_register_job.h index 1524a64c7..22b4939 100644 --- a/content/browser/service_worker/service_worker_register_job.h +++ b/content/browser/service_worker/service_worker_register_job.h
@@ -21,10 +21,6 @@ namespace content { -namespace { -class InstallEventMethodsReceiver; -} // namespace - // Handles the initial registration of a Service Worker and the // subsequent update of existing registrations. // @@ -128,7 +124,6 @@ void DispatchInstallEvent(); void OnInstallFinished( int request_id, - std::unique_ptr<InstallEventMethodsReceiver> install_event_methods, blink::mojom::ServiceWorkerEventStatus event_status, bool has_fetch_handler, base::Time dispatch_event_time);
diff --git a/content/browser/service_worker/service_worker_registration_unittest.cc b/content/browser/service_worker/service_worker_registration_unittest.cc index 5c4e7460..2dc47b9 100644 --- a/content/browser/service_worker/service_worker_registration_unittest.cc +++ b/content/browser/service_worker/service_worker_registration_unittest.cc
@@ -508,9 +508,9 @@ TEST_F(ServiceWorkerActivationTest, TimeSinceSkipWaiting_Installing) { scoped_refptr<ServiceWorkerRegistration> reg = registration(); scoped_refptr<ServiceWorkerVersion> version = reg->waiting_version(); - base::SimpleTestTickClock* clock = new base::SimpleTestTickClock(); - clock->SetNowTicks(base::TimeTicks::Now()); - version->SetTickClockForTesting(base::WrapUnique(clock)); + base::SimpleTestTickClock clock; + clock.SetNowTicks(base::TimeTicks::Now()); + version->SetTickClockForTesting(&clock); // Reset version to the installing phase. reg->UnsetVersion(version.get()); @@ -520,14 +520,14 @@ // since the version is not yet installed. SimulateSkipWaiting(version.get(), 77 /* dummy request_id */); base::RunLoop().RunUntilIdle(); - clock->Advance(base::TimeDelta::FromSeconds(11)); + clock.Advance(base::TimeDelta::FromSeconds(11)); EXPECT_EQ(base::TimeDelta(), version->TimeSinceSkipWaiting()); // Install the version. Now the skip waiting time starts ticking. version->SetStatus(ServiceWorkerVersion::INSTALLED); reg->SetWaitingVersion(version); base::RunLoop().RunUntilIdle(); - clock->Advance(base::TimeDelta::FromSeconds(33)); + clock.Advance(base::TimeDelta::FromSeconds(33)); EXPECT_EQ(base::TimeDelta::FromSeconds(33), version->TimeSinceSkipWaiting()); // Call skipWaiting() again. It doesn't reset the time. @@ -541,12 +541,12 @@ scoped_refptr<ServiceWorkerRegistration> reg = registration(); scoped_refptr<ServiceWorkerVersion> version_1 = reg->active_version(); scoped_refptr<ServiceWorkerVersion> version_2 = reg->waiting_version(); - base::SimpleTestTickClock* clock_1 = new base::SimpleTestTickClock(); - base::SimpleTestTickClock* clock_2 = new base::SimpleTestTickClock(); - clock_1->SetNowTicks(base::TimeTicks::Now()); - clock_2->SetNowTicks(clock_1->NowTicks()); - version_1->SetTickClockForTesting(base::WrapUnique(clock_1)); - version_2->SetTickClockForTesting(base::WrapUnique(clock_2)); + base::SimpleTestTickClock clock_1; + base::SimpleTestTickClock clock_2; + clock_1.SetNowTicks(base::TimeTicks::Now()); + clock_2.SetNowTicks(clock_1.NowTicks()); + version_1->SetTickClockForTesting(&clock_1); + version_2->SetTickClockForTesting(&clock_2); // Set skip waiting flag. Since there is still an in-flight request, // activation should not happen. But the lame duck timer should start. @@ -557,7 +557,7 @@ EXPECT_TRUE(IsLameDuckTimerRunning()); // Move forward by lame duck time. - clock_2->Advance(kMaxLameDuckTime + base::TimeDelta::FromSeconds(1)); + clock_2.Advance(kMaxLameDuckTime + base::TimeDelta::FromSeconds(1)); // Activation should happen by the lame duck timer. RunLameDuckTimer(); @@ -571,12 +571,12 @@ scoped_refptr<ServiceWorkerRegistration> reg = registration(); scoped_refptr<ServiceWorkerVersion> version_1 = reg->active_version(); scoped_refptr<ServiceWorkerVersion> version_2 = reg->waiting_version(); - base::SimpleTestTickClock* clock_1 = new base::SimpleTestTickClock(); - base::SimpleTestTickClock* clock_2 = new base::SimpleTestTickClock(); - clock_1->SetNowTicks(base::TimeTicks::Now()); - clock_2->SetNowTicks(clock_1->NowTicks()); - version_1->SetTickClockForTesting(base::WrapUnique(clock_1)); - version_2->SetTickClockForTesting(base::WrapUnique(clock_2)); + base::SimpleTestTickClock clock_1; + base::SimpleTestTickClock clock_2; + clock_1.SetNowTicks(base::TimeTicks::Now()); + clock_2.SetNowTicks(clock_1.NowTicks()); + version_1->SetTickClockForTesting(&clock_1); + version_2->SetTickClockForTesting(&clock_2); // Remove the controllee. Since there is still an in-flight request, // activation should not happen. But the lame duck timer should start. @@ -588,7 +588,7 @@ // Move clock forward by a little bit. constexpr base::TimeDelta kLittleBit = base::TimeDelta::FromMinutes(1); - clock_1->Advance(kLittleBit); + clock_1.Advance(kLittleBit); // Add a controllee again to reset the lame duck period. version_1->AddControllee(controllee()); @@ -601,8 +601,8 @@ EXPECT_TRUE(IsLameDuckTimerRunning()); // Move clock forward to the next lame duck timer tick. - clock_1->Advance(kMaxLameDuckTime - kLittleBit + - base::TimeDelta::FromSeconds(1)); + clock_1.Advance(kMaxLameDuckTime - kLittleBit + + base::TimeDelta::FromSeconds(1)); // Run the lame duck timer. Activation should not yet happen // since the lame duck period has not expired. @@ -612,7 +612,7 @@ EXPECT_TRUE(IsLameDuckTimerRunning()); // Continue on to the next lame duck timer tick. - clock_1->Advance(kMaxLameDuckTime + base::TimeDelta::FromSeconds(1)); + clock_1.Advance(kMaxLameDuckTime + base::TimeDelta::FromSeconds(1)); // Activation should happen by the lame duck timer. RunLameDuckTimer();
diff --git a/content/browser/service_worker/service_worker_response_info.cc b/content/browser/service_worker/service_worker_response_info.cc index 38fc093..814ffd7 100644 --- a/content/browser/service_worker/service_worker_response_info.cc +++ b/content/browser/service_worker/service_worker_response_info.cc
@@ -39,7 +39,6 @@ ResourceResponseInfo* response_info) const { response_info->was_fetched_via_service_worker = was_fetched_via_service_worker_; - response_info->was_fetched_via_foreign_fetch = was_fetched_via_foreign_fetch_; response_info->was_fallback_required_by_service_worker = was_fallback_required_; response_info->url_list_via_service_worker = url_list_via_service_worker_; @@ -74,7 +73,6 @@ void ServiceWorkerResponseInfo::OnStartCompleted( bool was_fetched_via_service_worker, - bool was_fetched_via_foreign_fetch, bool was_fallback_required, const std::vector<GURL>& url_list_via_service_worker, network::mojom::FetchResponseType response_type_via_service_worker, @@ -85,7 +83,6 @@ const ServiceWorkerHeaderList& cors_exposed_header_names, bool did_navigation_preload) { was_fetched_via_service_worker_ = was_fetched_via_service_worker; - was_fetched_via_foreign_fetch_ = was_fetched_via_foreign_fetch; was_fallback_required_ = was_fallback_required; url_list_via_service_worker_ = url_list_via_service_worker; response_type_via_service_worker_ = response_type_via_service_worker; @@ -104,7 +101,6 @@ void ServiceWorkerResponseInfo::ResetData() { was_fetched_via_service_worker_ = false; - was_fetched_via_foreign_fetch_ = false; was_fallback_required_ = false; url_list_via_service_worker_.clear(); response_type_via_service_worker_ =
diff --git a/content/browser/service_worker/service_worker_response_info.h b/content/browser/service_worker/service_worker_response_info.h index 2ab68de..6dc1f0b 100644 --- a/content/browser/service_worker/service_worker_response_info.h +++ b/content/browser/service_worker/service_worker_response_info.h
@@ -36,7 +36,6 @@ bool did_navigation_preload); void OnStartCompleted( bool was_fetched_via_service_worker, - bool was_fetched_via_foreign_fetch, bool was_fallback_required, const std::vector<GURL>& url_list_via_service_worker, network::mojom::FetchResponseType response_type_via_service_worker, @@ -97,7 +96,6 @@ ServiceWorkerResponseInfo(); bool was_fetched_via_service_worker_ = false; - bool was_fetched_via_foreign_fetch_ = false; bool was_fallback_required_ = false; std::vector<GURL> url_list_via_service_worker_; network::mojom::FetchResponseType response_type_via_service_worker_ =
diff --git a/content/browser/service_worker/service_worker_storage.cc b/content/browser/service_worker/service_worker_storage.cc index 60997b59..538048ab 100644 --- a/content/browser/service_worker/service_worker_storage.cc +++ b/content/browser/service_worker/service_worker_storage.cc
@@ -400,8 +400,6 @@ data.version_id = version->version_id(); data.last_update_check = registration->last_update_check(); data.is_active = (version == registration->active_version()); - data.foreign_fetch_scopes = version->foreign_fetch_scopes(); - data.foreign_fetch_origins = version->foreign_fetch_origins(); if (version->origin_trial_tokens()) data.origin_trial_tokens = *version->origin_trial_tokens(); data.navigation_preload_state = registration->navigation_preload_state(); @@ -882,12 +880,6 @@ weak_factory_.GetWeakPtr(), callback))); } -bool ServiceWorkerStorage::OriginHasForeignFetchRegistrations( - const GURL& origin) { - return !IsDisabled() && - foreign_fetch_origins_.find(origin) != foreign_fetch_origins_.end(); -} - void ServiceWorkerStorage::DeleteAndStartOver(const StatusCallback& callback) { Disable(); @@ -1058,7 +1050,6 @@ next_version_id_ = data->next_version_id; next_resource_id_ = data->next_resource_id; registered_origins_.swap(data->origins); - foreign_fetch_origins_.swap(data->foreign_fetch_origins); state_ = INITIALIZED; ServiceWorkerMetrics::RecordRegisteredOriginCount( registered_origins_.size()); @@ -1304,8 +1295,6 @@ return; } registered_origins_.insert(origin); - if (!new_version.foreign_fetch_scopes.empty()) - foreign_fetch_origins_.insert(origin); scoped_refptr<ServiceWorkerRegistration> registration = context_->GetLiveRegistration(new_version.registration_id); @@ -1359,11 +1348,8 @@ storage::StorageType::kStorageTypeTemporary, -deleted_version.resources_total_size_bytes); } - if (origin_state == OriginState::DELETE_FROM_ALL) + if (origin_state == OriginState::kDelete) registered_origins_.erase(params.origin); - if (origin_state == OriginState::DELETE_FROM_ALL || - origin_state == OriginState::DELETE_FROM_FOREIGN_FETCH) - foreign_fetch_origins_.erase(params.origin); params.callback.Run(SERVICE_WORKER_OK); if (!context_->GetLiveVersion(deleted_version.version_id)) @@ -1468,8 +1454,6 @@ version->SetStatus(data.is_active ? ServiceWorkerVersion::ACTIVATED : ServiceWorkerVersion::INSTALLED); version->script_cache_map()->SetResources(resources); - version->set_foreign_fetch_scopes(data.foreign_fetch_scopes); - version->set_foreign_fetch_origins(data.foreign_fetch_origins); if (data.origin_trial_tokens) version->SetValidOriginTrialTokens(*data.origin_trial_tokens); @@ -1748,8 +1732,6 @@ return; } - status = database->GetOriginsWithForeignFetchRegistrations( - &data->foreign_fetch_origins); original_task_runner->PostTask( FROM_HERE, base::BindOnce(callback, base::Passed(std::move(data)), status)); @@ -1769,9 +1751,8 @@ registration_id, origin, &deleted_version, &newly_purgeable_resources); if (status != ServiceWorkerDatabase::STATUS_OK) { original_task_runner->PostTask( - FROM_HERE, - base::BindOnce(callback, OriginState::KEEP_ALL, deleted_version, - std::vector<int64_t>(), status)); + FROM_HERE, base::BindOnce(callback, OriginState::kKeep, deleted_version, + std::vector<int64_t>(), status)); return; } @@ -1781,24 +1762,13 @@ status = database->GetRegistrationsForOrigin(origin, ®istrations, nullptr); if (status != ServiceWorkerDatabase::STATUS_OK) { original_task_runner->PostTask( - FROM_HERE, - base::BindOnce(callback, OriginState::KEEP_ALL, deleted_version, - std::vector<int64_t>(), status)); + FROM_HERE, base::BindOnce(callback, OriginState::kKeep, deleted_version, + std::vector<int64_t>(), status)); return; } - OriginState origin_state = registrations.empty() - ? OriginState::DELETE_FROM_ALL - : OriginState::DELETE_FROM_FOREIGN_FETCH; - - // TODO(mek): Add convenient method to ServiceWorkerDatabase to check the - // foreign fetch scope origin list. - for (const auto& registration : registrations) { - if (!registration.foreign_fetch_scopes.empty()) { - origin_state = OriginState::KEEP_ALL; - break; - } - } + OriginState origin_state = + registrations.empty() ? OriginState::kDelete : OriginState::kKeep; original_task_runner->PostTask( FROM_HERE, base::BindOnce(callback, origin_state, deleted_version, newly_purgeable_resources, status));
diff --git a/content/browser/service_worker/service_worker_storage.h b/content/browser/service_worker/service_worker_storage.h index 1f10c3bf..50b5b8e 100644 --- a/content/browser/service_worker/service_worker_storage.h +++ b/content/browser/service_worker/service_worker_storage.h
@@ -227,10 +227,6 @@ const std::string& key_prefix, const GetUserDataForAllRegistrationsCallback& callback); - // Returns true if any service workers at |origin| have registered for foreign - // fetch. - bool OriginHasForeignFetchRegistrations(const GURL& origin); - // Deletes the storage and starts over. void DeleteAndStartOver(const StatusCallback& callback); @@ -284,7 +280,6 @@ int64_t next_version_id; int64_t next_resource_id; std::set<GURL> origins; - std::set<GURL> foreign_fetch_origins; InitialData(); ~InitialData(); @@ -302,13 +297,10 @@ }; enum class OriginState { - // Other registrations with foreign fetch scopes exist for the origin. - KEEP_ALL, - // Other registrations exist at this origin, but none of them have foreign - // fetch scopes. - DELETE_FROM_FOREIGN_FETCH, - // No other registrations exist at this origin. - DELETE_FROM_ALL + // Registrations may exist at this origin. It cannot be deleted. + kKeep, + // No registrations exist at this origin. It can be deleted. + kDelete }; typedef std::vector<ServiceWorkerDatabase::RegistrationData> RegistrationList; @@ -551,7 +543,6 @@ // Origins having registations. std::set<GURL> registered_origins_; - std::set<GURL> foreign_fetch_origins_; // Pending database tasks waiting for initialization. std::vector<base::OnceClosure> pending_tasks_;
diff --git a/content/browser/service_worker/service_worker_storage_unittest.cc b/content/browser/service_worker/service_worker_storage_unittest.cc index 885efc8..ec74e853 100644 --- a/content/browser/service_worker/service_worker_storage_unittest.cc +++ b/content/browser/service_worker/service_worker_storage_unittest.cc
@@ -679,9 +679,6 @@ EXPECT_EQ(SERVICE_WORKER_ERROR_ABORT, GetUserDataForAllRegistrations(kUserDataKey, &data_list_out)); - EXPECT_FALSE( - storage()->OriginHasForeignFetchRegistrations(kScope.GetOrigin())); - // Next available ids should be invalid. EXPECT_EQ(blink::mojom::kInvalidServiceWorkerRegistrationId, storage()->NewRegistrationId()); @@ -699,9 +696,6 @@ const int64_t kResource2Size = 51; const int64_t kRegistrationId = 0; const int64_t kVersionId = 0; - const GURL kForeignFetchScope("http://www.test.not/scope/ff/"); - const url::Origin kForeignFetchOrigin = - url::Origin::Create(GURL("https://example.com/")); const base::Time kToday = base::Time::Now(); const base::Time kYesterday = kToday - base::TimeDelta::FromDays(1); std::set<uint32_t> used_features = {124, 901, 1019}; @@ -737,10 +731,6 @@ ServiceWorkerVersion::FetchHandlerExistence::EXISTS); live_version->SetStatus(ServiceWorkerVersion::INSTALLED); live_version->script_cache_map()->SetResources(resources); - live_version->set_foreign_fetch_scopes( - std::vector<GURL>(1, kForeignFetchScope)); - live_version->set_foreign_fetch_origins( - std::vector<url::Origin>(1, kForeignFetchOrigin)); live_version->set_used_features(used_features); live_registration->SetWaitingVersion(live_version); live_registration->set_last_update_check(kYesterday); @@ -833,15 +823,6 @@ EXPECT_EQ(kYesterday, found_registration->last_update_check()); EXPECT_EQ(ServiceWorkerVersion::INSTALLED, found_registration->waiting_version()->status()); - EXPECT_EQ( - 1u, found_registration->waiting_version()->foreign_fetch_scopes().size()); - EXPECT_EQ(kForeignFetchScope, - found_registration->waiting_version()->foreign_fetch_scopes()[0]); - EXPECT_EQ( - 1u, - found_registration->waiting_version()->foreign_fetch_origins().size()); - EXPECT_EQ(kForeignFetchOrigin, - found_registration->waiting_version()->foreign_fetch_origins()[0]); // Update to active and update the last check time. scoped_refptr<ServiceWorkerVersion> temp_version = @@ -1762,83 +1743,6 @@ } }; -TEST_F(ServiceWorkerStorageDiskTest, OriginHasForeignFetchRegistrations) { - LazyInitialize(); - - // Registration 1 for http://www.example.com - const GURL kScope1("http://www.example.com/scope/"); - const GURL kScript1("http://www.example.com/script1.js"); - scoped_refptr<ServiceWorkerRegistration> live_registration1 = - CreateLiveRegistrationAndVersion(kScope1, kScript1); - const int64_t kRegistrationId1 = live_registration1->id(); - ServiceWorkerVersion* live_version1 = live_registration1->waiting_version(); - live_version1->set_foreign_fetch_scopes(std::vector<GURL>(1, kScope1)); - - // Registration 2 for http://www.example.com - const GURL kScope2("http://www.example.com/scope/foo"); - const GURL kScript2("http://www.example.com/script2.js"); - scoped_refptr<ServiceWorkerRegistration> live_registration2 = - CreateLiveRegistrationAndVersion(kScope2, kScript2); - const int64_t kRegistrationId2 = live_registration2->id(); - ServiceWorkerVersion* live_version2 = live_registration2->waiting_version(); - live_version2->set_foreign_fetch_scopes(std::vector<GURL>(1, kScope2)); - - // Registration for http://www.test.com - const GURL kScope3("http://www.test.com/scope/foobar"); - const GURL kScript3("http://www.test.com/script3.js"); - scoped_refptr<ServiceWorkerRegistration> live_registration3 = - CreateLiveRegistrationAndVersion(kScope3, kScript3); - ServiceWorkerVersion* live_version3 = live_registration3->waiting_version(); - - // Neither origin should have registrations before they are stored. - const GURL kOrigin1 = kScope1.GetOrigin(); - const GURL kOrigin2 = kScope3.GetOrigin(); - EXPECT_FALSE(storage()->OriginHasForeignFetchRegistrations(kOrigin1)); - EXPECT_FALSE(storage()->OriginHasForeignFetchRegistrations(kOrigin2)); - - // Store all registrations. - EXPECT_EQ(SERVICE_WORKER_OK, - StoreRegistration(live_registration1, live_version1)); - EXPECT_EQ(SERVICE_WORKER_OK, - StoreRegistration(live_registration2, live_version2)); - EXPECT_EQ(SERVICE_WORKER_OK, - StoreRegistration(live_registration3, live_version3)); - - // Now first origin should have foreign fetch registrations, second doesn't. - EXPECT_TRUE(storage()->OriginHasForeignFetchRegistrations(kOrigin1)); - EXPECT_FALSE(storage()->OriginHasForeignFetchRegistrations(kOrigin2)); - - // Remove one registration at first origin. - EXPECT_EQ(SERVICE_WORKER_OK, - DeleteRegistration(kRegistrationId1, kScope1.GetOrigin())); - - // First origin should still have a registration left. - EXPECT_TRUE(storage()->OriginHasForeignFetchRegistrations(kOrigin1)); - EXPECT_FALSE(storage()->OriginHasForeignFetchRegistrations(kOrigin2)); - - // Simulate browser shutdown and restart. - live_registration1 = nullptr; - live_version1 = nullptr; - live_registration2 = nullptr; - live_version2 = nullptr; - live_registration3 = nullptr; - live_version3 = nullptr; - InitializeTestHelper(); - LazyInitialize(); - - // First origin should still have a registration left. - EXPECT_TRUE(storage()->OriginHasForeignFetchRegistrations(kOrigin1)); - EXPECT_FALSE(storage()->OriginHasForeignFetchRegistrations(kOrigin2)); - - // Remove other registration at first origin. - EXPECT_EQ(SERVICE_WORKER_OK, - DeleteRegistration(kRegistrationId2, kScope2.GetOrigin())); - - // No foreign fetch registrations remain. - EXPECT_FALSE(storage()->OriginHasForeignFetchRegistrations(kOrigin1)); - EXPECT_FALSE(storage()->OriginHasForeignFetchRegistrations(kOrigin2)); -} - TEST_F(ServiceWorkerStorageTest, OriginTrialsAbsentEntryAndEmptyEntry) { const GURL origin1("http://www1.example.com"); const GURL scope1("http://www1.example.com/foo/");
diff --git a/content/browser/service_worker/service_worker_test_utils.cc b/content/browser/service_worker/service_worker_test_utils.cc index 5c8ebc61..4d05a43 100644 --- a/content/browser/service_worker/service_worker_test_utils.cc +++ b/content/browser/service_worker/service_worker_test_utils.cc
@@ -114,9 +114,10 @@ bool is_parent_frame_secure, base::WeakPtr<ServiceWorkerContextCore> context, ServiceWorkerRemoteProviderEndpoint* output_endpoint) { - ServiceWorkerProviderHostInfo info(provider_id, 1 /* route_id */, - SERVICE_WORKER_PROVIDER_FOR_WINDOW, - is_parent_frame_secure); + ServiceWorkerProviderHostInfo info( + provider_id, 1 /* route_id */, + blink::mojom::ServiceWorkerProviderType::kForWindow, + is_parent_frame_secure); output_endpoint->BindWithProviderHostInfo(&info); return ServiceWorkerProviderHost::Create(process_id, std::move(info), std::move(context), nullptr); @@ -131,7 +132,8 @@ ServiceWorkerRemoteProviderEndpoint* output_endpoint) { ServiceWorkerProviderHostInfo info( kInvalidServiceWorkerProviderId, MSG_ROUTING_NONE, - SERVICE_WORKER_PROVIDER_FOR_SERVICE_WORKER, is_parent_frame_secure); + blink::mojom::ServiceWorkerProviderType::kForServiceWorker, + is_parent_frame_secure); std::unique_ptr<ServiceWorkerProviderHost> host = ServiceWorkerProviderHost::PreCreateForController(std::move(context)); mojom::ServiceWorkerProviderInfoForStartWorkerPtr provider_info = @@ -147,8 +149,9 @@ int route_id, ServiceWorkerDispatcherHost* dispatcher_host, ServiceWorkerRemoteProviderEndpoint* output_endpoint) { - ServiceWorkerProviderHostInfo info(provider_id, route_id, - SERVICE_WORKER_PROVIDER_FOR_WINDOW, true); + ServiceWorkerProviderHostInfo info( + provider_id, route_id, + blink::mojom::ServiceWorkerProviderType::kForWindow, true); output_endpoint->BindWithProviderHostInfo(&info); return ServiceWorkerProviderHost::Create(process_id, std::move(info), std::move(context),
diff --git a/content/browser/service_worker/service_worker_url_loader_job_unittest.cc b/content/browser/service_worker/service_worker_url_loader_job_unittest.cc index b9b1d64a..3768f17 100644 --- a/content/browser/service_worker/service_worker_url_loader_job_unittest.cc +++ b/content/browser/service_worker/service_worker_url_loader_job_unittest.cc
@@ -475,9 +475,9 @@ // responding as if a service worker is running in the renderer. // // ServiceWorkerURLLoaderJobTest is also a ServiceWorkerURLLoaderJob::Delegate. -// In production code, ServiceWorkerControlleeRequestHandler is the Delegate -// (for non-"foreign fetch" request interceptions). So this class also basically -// mocks that part of ServiceWorkerControlleeRequestHandler. +// In production code, ServiceWorkerControlleeRequestHandler is the Delegate. So +// this class also basically mocks that part of +// ServiceWorkerControlleeRequestHandler. class ServiceWorkerURLLoaderJobTest : public testing::Test, public ServiceWorkerURLLoaderJob::Delegate {
diff --git a/content/browser/service_worker/service_worker_url_request_job.cc b/content/browser/service_worker/service_worker_url_request_job.cc index 93cc073e..79a7984c 100644 --- a/content/browser/service_worker/service_worker_url_request_job.cc +++ b/content/browser/service_worker/service_worker_url_request_job.cc
@@ -382,7 +382,6 @@ void ServiceWorkerURLRequestJob::FallbackToNetworkOrRenderer() { DCHECK_EQ(ResponseType::NOT_DETERMINED, response_type_); - DCHECK_NE(ServiceWorkerFetchType::FOREIGN_FETCH, fetch_type_); if (IsFallbackToRendererNeeded()) { response_type_ = ResponseType::FALLBACK_TO_RENDERER; } else { @@ -848,9 +847,6 @@ } void ServiceWorkerURLRequestJob::FinalizeFallbackToRenderer() { - // TODO(mek): http://crbug.com/604084 Figure out what to do about CORS - // preflight and fallbacks for foreign fetch events. - DCHECK_NE(fetch_type_, ServiceWorkerFetchType::FOREIGN_FETCH); fall_back_required_ = true; if (ShouldRecordResult()) RecordResult(ServiceWorkerMetrics::REQUEST_JOB_FALLBACK_FOR_CORS); @@ -866,12 +862,7 @@ // document, we can't simply fallback to the network in the browser process. // It is because the CORS preflight logic is implemented in the renderer. So // we return a fall_back_required response to the renderer. - // If fetch_type is |FOREIGN_FETCH| any required CORS checks will have already - // been done in the renderer (and if a preflight was necesary the request - // would never have reached foreign fetch), so such requests can always - // fallback to the network directly. return !IsMainResourceLoad() && - fetch_type_ != ServiceWorkerFetchType::FOREIGN_FETCH && (request_mode_ == network::mojom::FetchRequestMode::kCORS || request_mode_ == network::mojom::FetchRequestMode::kCORSWithForcedPreflight) && @@ -934,7 +925,6 @@ ServiceWorkerResponseInfo::ForRequest(request_, true) ->OnStartCompleted( false /* was_fetched_via_service_worker */, - false /* was_fetched_via_foreign_fetch */, false /* was_fallback_required */, std::vector<GURL>() /* url_list_via_service_worker */, network::mojom::FetchResponseType::kDefault, @@ -953,7 +943,6 @@ ServiceWorkerResponseInfo::ForRequest(request_, true) ->OnStartCompleted( true /* was_fetched_via_service_worker */, - fetch_type_ == ServiceWorkerFetchType::FOREIGN_FETCH, fall_back_required_, response_url_list_, fetch_response_type_, worker_start_time_, worker_ready_time_, response_is_in_cache_storage_, response_cache_storage_cache_name_,
diff --git a/content/browser/service_worker/service_worker_url_request_job.h b/content/browser/service_worker/service_worker_url_request_job.h index 8f0e9089..232d5dd 100644 --- a/content/browser/service_worker/service_worker_url_request_job.h +++ b/content/browser/service_worker/service_worker_url_request_job.h
@@ -98,11 +98,9 @@ // When an in-flight request possibly needs CORS check, use // FallbackToNetworkOrRenderer. This method will decide whether the request // can directly go to the network or should fallback to a renderer to send - // CORS preflight. You can use FallbackToNetwork only when, like main resource - // or foreign fetch cases, it's apparent that the request should go to the - // network directly. - // TODO(shimazu): Update the comment when what should we do at foreign fetch - // fallback is determined: crbug.com/604084 + // CORS preflight. You can use FallbackToNetwork only when it's apparent that + // the request can go to the network directly (e.g., main resource requests or + // same-origin requests). void FallbackToNetwork(); void FallbackToNetworkOrRenderer(); void ForwardToServiceWorker();
diff --git a/content/browser/service_worker/service_worker_url_request_job_unittest.cc b/content/browser/service_worker/service_worker_url_request_job_unittest.cc index 3a525d4..f844794 100644 --- a/content/browser/service_worker/service_worker_url_request_job_unittest.cc +++ b/content/browser/service_worker/service_worker_url_request_job_unittest.cc
@@ -421,6 +421,7 @@ // --------------------------------------------------------------------------- TestBrowserThreadBundle thread_bundle_; + base::SimpleTestTickClock tick_clock_; std::unique_ptr<TestBrowserContext> browser_context_; std::unique_ptr<EmbeddedWorkerTestHelper> helper_; @@ -710,11 +711,8 @@ version_->SetStatus(ServiceWorkerVersion::ACTIVATED); // Set mock clock on version_ to check timeout behavior. - { - auto tick_clock = std::make_unique<base::SimpleTestTickClock>(); - tick_clock->SetNowTicks(base::TimeTicks::Now()); - version_->SetTickClockForTesting(std::move(tick_clock)); - } + tick_clock_.SetNowTicks(base::TimeTicks::Now()); + version_->SetTickClockForTesting(&tick_clock_); protocol_handler_->set_custom_timeout(base::TimeDelta::FromSeconds(5)); TestRequest(200, "OK", std::string(), true /* expect_valid_ssl */);
diff --git a/content/browser/service_worker/service_worker_version.cc b/content/browser/service_worker/service_worker_version.cc index 49f8283..3d3b727 100644 --- a/content/browser/service_worker/service_worker_version.cc +++ b/content/browser/service_worker/service_worker_version.cc
@@ -291,8 +291,8 @@ binding_(this), context_(context), script_cache_map_(this, context), - tick_clock_(std::make_unique<base::DefaultTickClock>()), - clock_(std::make_unique<base::DefaultClock>()), + tick_clock_(base::DefaultTickClock::GetInstance()), + clock_(base::DefaultClock::GetInstance()), ping_controller_(new PingController(this)), validator_(TrialPolicyImpl::CreateValidatorForPolicy()), weak_factory_(this) { @@ -840,14 +840,12 @@ ping_controller_->SimulateTimeoutForTesting(); } -void ServiceWorkerVersion::SetTickClockForTesting( - std::unique_ptr<base::TickClock> tick_clock) { - tick_clock_ = std::move(tick_clock); +void ServiceWorkerVersion::SetTickClockForTesting(base::TickClock* tick_clock) { + tick_clock_ = tick_clock; } -void ServiceWorkerVersion::SetClockForTesting( - std::unique_ptr<base::Clock> clock) { - clock_ = std::move(clock); +void ServiceWorkerVersion::SetClockForTesting(base::Clock* clock) { + clock_ = clock; } const net::HttpResponseInfo* @@ -1411,38 +1409,6 @@ ping_controller_->OnPongReceived(); } -void ServiceWorkerVersion::RegisterForeignFetchScopes( - const std::vector<GURL>& sub_scopes, - const std::vector<url::Origin>& origins) { - DCHECK(status() == INSTALLING || status() == REDUNDANT) << status(); - // Renderer should have already verified all these urls are inside the - // worker's scope, but verify again here on the browser process side. - GURL origin = scope_.GetOrigin(); - std::string scope_path = scope_.path(); - for (const GURL& url : sub_scopes) { - if (!url.is_valid() || url.GetOrigin() != origin || - !base::StartsWith(url.path(), scope_path, - base::CompareCase::SENSITIVE)) { - DVLOG(1) << "Received unexpected invalid URL from renderer process."; - BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, - base::BindOnce(&KillEmbeddedWorkerProcess, - embedded_worker_->process_id())); - return; - } - } - for (const url::Origin& url : origins) { - if (url.unique()) { - DVLOG(1) << "Received unexpected unique origin from renderer process."; - BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, - base::BindOnce(&KillEmbeddedWorkerProcess, - embedded_worker_->process_id())); - return; - } - } - set_foreign_fetch_scopes(sub_scopes); - set_foreign_fetch_origins(origins); -} - void ServiceWorkerVersion::DidEnsureLiveRegistrationForStartWorker( ServiceWorkerMetrics::EventType purpose, Status prestart_status,
diff --git a/content/browser/service_worker/service_worker_version.h b/content/browser/service_worker/service_worker_version.h index cb4708f8..d368672 100644 --- a/content/browser/service_worker/service_worker_version.h +++ b/content/browser/service_worker/service_worker_version.h
@@ -168,20 +168,6 @@ // This also updates |site_for_uma_| when it was Site::OTHER. void set_fetch_handler_existence(FetchHandlerExistence existence); - const std::vector<GURL>& foreign_fetch_scopes() const { - return foreign_fetch_scopes_; - } - void set_foreign_fetch_scopes(const std::vector<GURL>& scopes) { - foreign_fetch_scopes_ = scopes; - } - - const std::vector<url::Origin>& foreign_fetch_origins() const { - return foreign_fetch_origins_; - } - void set_foreign_fetch_origins(const std::vector<url::Origin>& origins) { - foreign_fetch_origins_ = origins; - } - base::TimeDelta TimeSinceNoControllees() const { return GetTickDuration(no_controllees_time_); } @@ -287,9 +273,6 @@ bool was_handled, base::Time dispatch_event_time); - void RegisterForeignFetchScopes(const std::vector<GURL>& sub_scopes, - const std::vector<url::Origin>& origins); - // Finishes an external request that was started by StartExternalRequest(). // Returns false if there was an error finishing the request: e.g. the request // was not found or the worker already terminated. @@ -407,10 +390,10 @@ void SimulatePingTimeoutForTesting(); // Used to allow tests to change time for testing. - void SetTickClockForTesting(std::unique_ptr<base::TickClock> tick_clock); + void SetTickClockForTesting(base::TickClock* tick_clock); // Used to allow tests to change wall clock for testing. - void SetClockForTesting(std::unique_ptr<base::Clock> clock); + void SetClockForTesting(base::Clock* clock); // Returns true if the service worker has work to do: it has pending // requests, in-progress streaming URLRequestJobs, or pending start callbacks. @@ -465,8 +448,6 @@ FRIEND_TEST_ALL_PREFIXES(ServiceWorkerStallInStoppingTest, DetachThenRestart); FRIEND_TEST_ALL_PREFIXES(ServiceWorkerStallInStoppingTest, DetachThenRestartNoCrash); - FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionTest, - RegisterForeignFetchScopes); FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionTest, RequestNowTimeout); FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionTest, RequestNowTimeoutKill); FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionTest, RequestCustomizedTimeout); @@ -674,8 +655,6 @@ const GURL script_url_; const url::Origin script_origin_; const GURL scope_; - std::vector<GURL> foreign_fetch_scopes_; - std::vector<url::Origin> foreign_fetch_origins_; FetchHandlerExistence fetch_handler_existence_; // The source of truth for navigation preload state is the // ServiceWorkerRegistration. |navigation_preload_state_| is essentially a @@ -772,10 +751,10 @@ ServiceWorkerStatusCode start_worker_status_ = SERVICE_WORKER_OK; // The clock used to vend tick time. - std::unique_ptr<base::TickClock> tick_clock_; + base::TickClock* tick_clock_; // The clock used for actual (wall clock) time - std::unique_ptr<base::Clock> clock_; + base::Clock* clock_; std::unique_ptr<PingController> ping_controller_;
diff --git a/content/browser/service_worker/service_worker_version_unittest.cc b/content/browser/service_worker/service_worker_version_unittest.cc index 493e364..bb2edcbf 100644 --- a/content/browser/service_worker/service_worker_version_unittest.cc +++ b/content/browser/service_worker/service_worker_version_unittest.cc
@@ -306,10 +306,8 @@ EXPECT_EQ(SERVICE_WORKER_ERROR_MAX_VALUE, status); } - base::SimpleTestTickClock* SetTickClockForTesting() { - base::SimpleTestTickClock* tick_clock = new base::SimpleTestTickClock(); - version_->SetTickClockForTesting(base::WrapUnique(tick_clock)); - return tick_clock; + void SetTickClockForTesting(base::SimpleTestTickClock* tick_clock) { + version_->SetTickClockForTesting(tick_clock); } TestBrowserThreadBundle thread_bundle_; @@ -1095,7 +1093,8 @@ version_->SetStatus(ServiceWorkerVersion::ACTIVATED); StartWorker(version_.get(), ServiceWorkerMetrics::EventType::SYNC); - base::SimpleTestTickClock* tick_clock = SetTickClockForTesting(); + base::SimpleTestTickClock tick_clock; + SetTickClockForTesting(&tick_clock); // Create two requests. One which times out in 10 seconds, one in 20 seconds. int timeout_seconds = 10; @@ -1120,7 +1119,7 @@ EXPECT_EQ(SERVICE_WORKER_ERROR_MAX_VALUE, second_status); // Now advance time until the second task timeout should expire. - tick_clock->Advance(base::TimeDelta::FromSeconds(timeout_seconds + 1)); + tick_clock.Advance(base::TimeDelta::FromSeconds(timeout_seconds + 1)); version_->timeout_timer_.user_task().Run(); base::RunLoop().RunUntilIdle(); EXPECT_EQ(SERVICE_WORKER_ERROR_MAX_VALUE, first_status); @@ -1130,7 +1129,7 @@ EXPECT_EQ(EmbeddedWorkerStatus::RUNNING, version_->running_status()); // Now advance time until both tasks should be expired. - tick_clock->Advance(base::TimeDelta::FromSeconds(timeout_seconds + 1)); + tick_clock.Advance(base::TimeDelta::FromSeconds(timeout_seconds + 1)); version_->timeout_timer_.user_task().Run(); base::RunLoop().RunUntilIdle(); EXPECT_EQ(SERVICE_WORKER_ERROR_TIMEOUT, first_status); @@ -1300,77 +1299,6 @@ EXPECT_EQ(SERVICE_WORKER_OK, start_status); } -TEST_F(ServiceWorkerVersionTest, RegisterForeignFetchScopes) { - version_->SetStatus(ServiceWorkerVersion::INSTALLING); - // Start a worker. - StartWorker(version_.get(), ServiceWorkerMetrics::EventType::UNKNOWN); - EXPECT_EQ(0, helper_->mock_render_process_host()->bad_msg_count()); - - GURL valid_scope_1("https://www.example.com/test/subscope"); - GURL valid_scope_2("https://www.example.com/test/othersubscope"); - std::vector<GURL> valid_scopes; - valid_scopes.push_back(valid_scope_1); - valid_scopes.push_back(valid_scope_2); - - std::vector<url::Origin> all_origins; - url::Origin valid_origin = url::Origin::Create(GURL("https://chromium.org/")); - std::vector<url::Origin> valid_origin_list(1, valid_origin); - - // Invalid subscope, should kill worker (but in tests will only increase bad - // message count). - version_->RegisterForeignFetchScopes(std::vector<GURL>(1, GURL()), - valid_origin_list); - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(1, helper_->mock_render_process_host()->bad_msg_count()); - EXPECT_EQ(0u, version_->foreign_fetch_scopes_.size()); - EXPECT_EQ(0u, version_->foreign_fetch_origins_.size()); - - // Subscope outside the scope of the worker. - version_->RegisterForeignFetchScopes( - std::vector<GURL>(1, GURL("https://www.example.com/wrong")), - valid_origin_list); - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(2, helper_->mock_render_process_host()->bad_msg_count()); - EXPECT_EQ(0u, version_->foreign_fetch_scopes_.size()); - EXPECT_EQ(0u, version_->foreign_fetch_origins_.size()); - - // Subscope on wrong origin. - version_->RegisterForeignFetchScopes( - std::vector<GURL>(1, GURL("https://example.com/test/")), - valid_origin_list); - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(3, helper_->mock_render_process_host()->bad_msg_count()); - EXPECT_EQ(0u, version_->foreign_fetch_scopes_.size()); - EXPECT_EQ(0u, version_->foreign_fetch_origins_.size()); - - // Invalid origin. - version_->RegisterForeignFetchScopes( - valid_scopes, std::vector<url::Origin>(1, url::Origin())); - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(4, helper_->mock_render_process_host()->bad_msg_count()); - EXPECT_EQ(0u, version_->foreign_fetch_scopes_.size()); - EXPECT_EQ(0u, version_->foreign_fetch_origins_.size()); - - // Valid subscope, no origins. - version_->RegisterForeignFetchScopes(std::vector<GURL>(1, valid_scope_1), - all_origins); - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(4, helper_->mock_render_process_host()->bad_msg_count()); - EXPECT_EQ(1u, version_->foreign_fetch_scopes_.size()); - EXPECT_EQ(valid_scope_1, version_->foreign_fetch_scopes_[0]); - EXPECT_EQ(0u, version_->foreign_fetch_origins_.size()); - - // Valid subscope, explicit origins. - version_->RegisterForeignFetchScopes(valid_scopes, valid_origin_list); - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(4, helper_->mock_render_process_host()->bad_msg_count()); - EXPECT_EQ(2u, version_->foreign_fetch_scopes_.size()); - EXPECT_EQ(valid_scope_1, version_->foreign_fetch_scopes_[0]); - EXPECT_EQ(valid_scope_2, version_->foreign_fetch_scopes_[1]); - EXPECT_EQ(1u, version_->foreign_fetch_origins_.size()); - EXPECT_EQ(valid_origin, version_->foreign_fetch_origins_[0]); -} - TEST_F(ServiceWorkerVersionTest, RendererCrashDuringEvent) { version_->SetStatus(ServiceWorkerVersion::ACTIVATED); StartWorker(version_.get(), ServiceWorkerMetrics::EventType::SYNC);
diff --git a/content/browser/shared_worker/shared_worker_service_impl.cc b/content/browser/shared_worker/shared_worker_service_impl.cc index 9103f43b..ddebc97 100644 --- a/content/browser/shared_worker/shared_worker_service_impl.cc +++ b/content/browser/shared_worker/shared_worker_service_impl.cc
@@ -121,9 +121,11 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); if (RenderFrameHost::FromID(process_id, frame_id)) { - RenderFrameHost* main_frame = RenderFrameHost::FromID(process_id, frame_id) - ->GetRenderViewHost() - ->GetMainFrame(); + RenderFrameHost* main_frame = + RenderFrameHostImpl::FromID(process_id, frame_id) + ->frame_tree_node() + ->frame_tree() + ->GetMainFrame(); if (!GetContentClient()->browser()->AllowSharedWorker( info->url, main_frame->GetLastCommittedURL(), info->name,
diff --git a/content/browser/storage_partition_impl_map.cc b/content/browser/storage_partition_impl_map.cc index 0393dba..972dcb3 100644 --- a/content/browser/storage_partition_impl_map.cc +++ b/content/browser/storage_partition_impl_map.cc
@@ -30,7 +30,6 @@ #include "content/browser/fileapi/browser_file_system_helper.h" #include "content/browser/loader/resource_request_info_impl.h" #include "content/browser/resource_context_impl.h" -#include "content/browser/service_worker/foreign_fetch_request_handler.h" #include "content/browser/service_worker/service_worker_request_handler.h" #include "content/browser/storage_partition_impl.h" #include "content/browser/streams/stream.h" @@ -423,11 +422,6 @@ std::make_unique<DevToolsURLRequestInterceptor>(browser_context_)); request_interceptors.push_back(ServiceWorkerRequestHandler::CreateInterceptor( browser_context_->GetResourceContext())); - if (ForeignFetchRequestHandler::IsForeignFetchEnabled()) { - request_interceptors.push_back( - ForeignFetchRequestHandler::CreateInterceptor( - browser_context_->GetResourceContext())); - } request_interceptors.push_back(std::make_unique<AppCacheInterceptor>()); // These calls must happen after StoragePartitionImpl::Create().
diff --git a/content/browser/utility_process_host_impl.cc b/content/browser/utility_process_host_impl.cc index 190e139..b2d2ab86 100644 --- a/content/browser/utility_process_host_impl.cc +++ b/content/browser/utility_process_host_impl.cc
@@ -297,6 +297,9 @@ #if defined(OS_MACOSX) switches::kEnableSandboxLogging, #endif +#if defined(USE_AURA) + switches::kMus, +#endif switches::kUseFakeDeviceForMediaStream, switches::kUseFileForFakeVideoCapture, #if defined(OS_WIN)
diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc index f037204..7e037ea 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc
@@ -4716,7 +4716,7 @@ if (dialog_manager_) { dialog_manager_->RunBeforeUnloadDialog( - this, is_reload, + this, render_frame_host, is_reload, base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false)); } }
diff --git a/content/browser/web_contents/web_contents_impl_browsertest.cc b/content/browser/web_contents/web_contents_impl_browsertest.cc index 1066147..998bd41 100644 --- a/content/browser/web_contents/web_contents_impl_browsertest.cc +++ b/content/browser/web_contents/web_contents_impl_browsertest.cc
@@ -1128,6 +1128,7 @@ }; void RunBeforeUnloadDialog(WebContents* web_contents, + RenderFrameHost* render_frame_host, bool is_reload, DialogClosedCallback callback) override { std::move(callback).Run(true, base::string16());
diff --git a/content/browser/web_contents/web_contents_impl_unittest.cc b/content/browser/web_contents/web_contents_impl_unittest.cc index 0c6753e..714be06 100644 --- a/content/browser/web_contents/web_contents_impl_unittest.cc +++ b/content/browser/web_contents/web_contents_impl_unittest.cc
@@ -3549,6 +3549,7 @@ }; void RunBeforeUnloadDialog(WebContents* web_contents, + RenderFrameHost* render_frame_host, bool is_reload, DialogClosedCallback callback) override {}
diff --git a/content/browser/webauth/attestation_data.cc b/content/browser/webauth/attestation_data.cc deleted file mode 100644 index 126e387..0000000 --- a/content/browser/webauth/attestation_data.cc +++ /dev/null
@@ -1,59 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/browser/webauth/attestation_data.h" - -#include <utility> - -#include "base/numerics/safe_math.h" -#include "content/browser/webauth/authenticator_utils.h" - -namespace content { - -// static -std::unique_ptr<AttestationData> AttestationData::CreateFromU2fRegisterResponse( - const std::vector<uint8_t>& u2f_data, - std::vector<uint8_t> aaguid, - std::unique_ptr<PublicKey> public_key) { - // Extract the length of the credential (i.e. of the U2FResponse key - // handle). Length is big endian. - std::vector<uint8_t> credential_id_length(2, 0); - std::vector<uint8_t> extracted_length = authenticator_utils::Extract( - u2f_data, authenticator_utils::kU2fResponseLengthPos, 1); - - // Note that U2F responses only use one byte for length. - credential_id_length[1] = extracted_length[0]; - - // Extract the credential id (i.e. key handle). - std::vector<uint8_t> credential_id = authenticator_utils::Extract( - u2f_data, authenticator_utils::kU2fResponseKeyHandleStartPos, - base::strict_cast<size_t>(credential_id_length[1])); - - return std::make_unique<AttestationData>( - std::move(aaguid), std::move(credential_id_length), - std::move(credential_id), std::move(public_key)); -} - -AttestationData::AttestationData(std::vector<uint8_t> aaguid, - std::vector<uint8_t> length, - std::vector<uint8_t> credential_id, - std::unique_ptr<PublicKey> public_key) - : aaguid_(std::move(aaguid)), - credential_id_length_(std::move(length)), - credential_id_(std::move(credential_id)), - public_key_(std::move(public_key)) {} - -std::vector<uint8_t> AttestationData::SerializeAsBytes() { - std::vector<uint8_t> attestation_data; - std::vector<uint8_t> cbor_encoded_key = public_key_->EncodeAsCBOR(); - authenticator_utils::Append(&attestation_data, aaguid_); - authenticator_utils::Append(&attestation_data, credential_id_length_); - authenticator_utils::Append(&attestation_data, credential_id_); - authenticator_utils::Append(&attestation_data, cbor_encoded_key); - return attestation_data; -} - -AttestationData::~AttestationData() {} - -} // namespace content
diff --git a/content/browser/webauth/attestation_data.h b/content/browser/webauth/attestation_data.h deleted file mode 100644 index 42792da..0000000 --- a/content/browser/webauth/attestation_data.h +++ /dev/null
@@ -1,56 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_BROWSER_WEBAUTH_ATTESTATION_DATA_H_ -#define CONTENT_BROWSER_WEBAUTH_ATTESTATION_DATA_H_ - -#include "content/browser/webauth/public_key.h" - -#include <stdint.h> -#include <memory> -#include <vector> - -#include "base/macros.h" -#include "content/common/content_export.h" - -namespace content { - -// https://www.w3.org/TR/2017/WD-webauthn-20170505/#sec-attestation-data -class CONTENT_EXPORT AttestationData { - public: - AttestationData(std::vector<uint8_t> aaguid, - std::vector<uint8_t> length, - std::vector<uint8_t> credential_id, - std::unique_ptr<PublicKey> public_key); - virtual ~AttestationData(); - - static std::unique_ptr<AttestationData> CreateFromU2fRegisterResponse( - const std::vector<uint8_t>& u2f_data, - std::vector<uint8_t> aaguid, - std::unique_ptr<PublicKey> public_key); - - const std::vector<uint8_t>& credential_id() { return credential_id_; } - - // Produces a byte array consisting of: - // * AAGUID (16 bytes) - // * Len (2 bytes) - // * Credential Id (Len bytes) - // * Credential Public Key. - std::vector<uint8_t> SerializeAsBytes(); - - private: - // The 16-byte AAGUID of the authenticator. - const std::vector<uint8_t> aaguid_; - - // Big-endian length of the credential (i.e. key handle). - const std::vector<uint8_t> credential_id_length_; - const std::vector<uint8_t> credential_id_; - const std::unique_ptr<PublicKey> public_key_; - - DISALLOW_COPY_AND_ASSIGN(AttestationData); -}; - -} // namespace content - -#endif // CONTENT_BROWSER_WEBAUTH_ATTESTATION_DATA_H_
diff --git a/content/browser/webauth/attestation_statement.h b/content/browser/webauth/attestation_statement.h index f6cefd5..6ba3720 100644 --- a/content/browser/webauth/attestation_statement.h +++ b/content/browser/webauth/attestation_statement.h
@@ -6,7 +6,6 @@ #define CONTENT_BROWSER_WEBAUTH_ATTESTATION_STATEMENT_H_ #include "base/macros.h" -#include "content/browser/webauth/attestation_data.h" #include "content/browser/webauth/cbor/cbor_values.h" namespace content {
diff --git a/content/browser/webauth/attested_credential_data.cc b/content/browser/webauth/attested_credential_data.cc new file mode 100644 index 0000000..ba2d394 --- /dev/null +++ b/content/browser/webauth/attested_credential_data.cc
@@ -0,0 +1,61 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/browser/webauth/attested_credential_data.h" + +#include <utility> + +#include "base/numerics/safe_math.h" +#include "content/browser/webauth/authenticator_utils.h" + +namespace content { + +// static +std::unique_ptr<AttestedCredentialData> +AttestedCredentialData::CreateFromU2fRegisterResponse( + const std::vector<uint8_t>& u2f_data, + std::vector<uint8_t> aaguid, + std::unique_ptr<PublicKey> public_key) { + // Extract the length of the credential (i.e. of the U2FResponse key + // handle). Length is big endian. + std::vector<uint8_t> credential_id_length(2, 0); + std::vector<uint8_t> extracted_length = authenticator_utils::Extract( + u2f_data, authenticator_utils::kU2fResponseLengthPos, 1); + + // Note that U2F responses only use one byte for length. + credential_id_length[1] = extracted_length[0]; + + // Extract the credential id (i.e. key handle). + std::vector<uint8_t> credential_id = authenticator_utils::Extract( + u2f_data, authenticator_utils::kU2fResponseKeyHandleStartPos, + base::strict_cast<size_t>(credential_id_length[1])); + + return std::make_unique<AttestedCredentialData>( + std::move(aaguid), std::move(credential_id_length), + std::move(credential_id), std::move(public_key)); +} + +AttestedCredentialData::AttestedCredentialData( + std::vector<uint8_t> aaguid, + std::vector<uint8_t> length, + std::vector<uint8_t> credential_id, + std::unique_ptr<PublicKey> public_key) + : aaguid_(std::move(aaguid)), + credential_id_length_(std::move(length)), + credential_id_(std::move(credential_id)), + public_key_(std::move(public_key)) {} + +std::vector<uint8_t> AttestedCredentialData::SerializeAsBytes() { + std::vector<uint8_t> attestation_data; + std::vector<uint8_t> cbor_encoded_key = public_key_->EncodeAsCBOR(); + authenticator_utils::Append(&attestation_data, aaguid_); + authenticator_utils::Append(&attestation_data, credential_id_length_); + authenticator_utils::Append(&attestation_data, credential_id_); + authenticator_utils::Append(&attestation_data, cbor_encoded_key); + return attestation_data; +} + +AttestedCredentialData::~AttestedCredentialData() {} + +} // namespace content
diff --git a/content/browser/webauth/attested_credential_data.h b/content/browser/webauth/attested_credential_data.h new file mode 100644 index 0000000..5ff2bd13 --- /dev/null +++ b/content/browser/webauth/attested_credential_data.h
@@ -0,0 +1,56 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_BROWSER_WEBAUTH_ATTESTED_CREDENTIAL_DATA_H_ +#define CONTENT_BROWSER_WEBAUTH_ATTESTED_CREDENTIAL_DATA_H_ + +#include "content/browser/webauth/public_key.h" + +#include <stdint.h> +#include <memory> +#include <vector> + +#include "base/macros.h" +#include "content/common/content_export.h" + +namespace content { + +// https://www.w3.org/TR/2017/WD-webauthn-20170505/#sec-attestation-data +class CONTENT_EXPORT AttestedCredentialData { + public: + AttestedCredentialData(std::vector<uint8_t> aaguid, + std::vector<uint8_t> length, + std::vector<uint8_t> credential_id, + std::unique_ptr<PublicKey> public_key); + virtual ~AttestedCredentialData(); + + static std::unique_ptr<AttestedCredentialData> CreateFromU2fRegisterResponse( + const std::vector<uint8_t>& u2f_data, + std::vector<uint8_t> aaguid, + std::unique_ptr<PublicKey> public_key); + + const std::vector<uint8_t>& credential_id() { return credential_id_; } + + // Produces a byte array consisting of: + // * AAGUID (16 bytes) + // * Len (2 bytes) + // * Credential Id (Len bytes) + // * Credential Public Key. + std::vector<uint8_t> SerializeAsBytes(); + + private: + // The 16-byte AAGUID of the authenticator. + const std::vector<uint8_t> aaguid_; + + // Big-endian length of the credential (i.e. key handle). + const std::vector<uint8_t> credential_id_length_; + const std::vector<uint8_t> credential_id_; + const std::unique_ptr<PublicKey> public_key_; + + DISALLOW_COPY_AND_ASSIGN(AttestedCredentialData); +}; + +} // namespace content + +#endif // CONTENT_BROWSER_WEBAUTH_ATTESTED_CREDENTIAL_DATA_H_
diff --git a/content/browser/webauth/authenticator_data.cc b/content/browser/webauth/authenticator_data.cc index f0d8d144..e987657 100644 --- a/content/browser/webauth/authenticator_data.cc +++ b/content/browser/webauth/authenticator_data.cc
@@ -8,7 +8,7 @@ #include "base/json/json_reader.h" #include "base/values.h" -#include "content/browser/webauth/attestation_data.h" +#include "content/browser/webauth/attested_credential_data.h" #include "content/browser/webauth/authenticator_utils.h" #include "crypto/sha2.h" @@ -19,7 +19,7 @@ std::string client_data_json, Flags flags, std::vector<uint8_t> counter, - std::unique_ptr<AttestationData> data) { + std::unique_ptr<AttestedCredentialData> data) { base::DictionaryValue* client_data_dictionary; std::unique_ptr<base::Value> client_data = base::JSONReader::Read(client_data_json); @@ -32,14 +32,15 @@ std::move(relying_party_id), flags, std::move(counter), std::move(data)); } -AuthenticatorData::AuthenticatorData(std::string relying_party_id, - Flags flags, - std::vector<uint8_t> counter, - std::unique_ptr<AttestationData> data) +AuthenticatorData::AuthenticatorData( + std::string relying_party_id, + Flags flags, + std::vector<uint8_t> counter, + std::unique_ptr<AttestedCredentialData> data) : relying_party_id_(std::move(relying_party_id)), flags_(flags), counter_(std::move(counter)), - attestation_data_(std::move(data)) { + attested_data_(std::move(data)) { CHECK_EQ(counter_.size(), 4u); } @@ -51,8 +52,7 @@ authenticator_utils::Append(&authenticator_data, rp_id_hash); authenticator_data.insert(authenticator_data.end(), flags_); authenticator_utils::Append(&authenticator_data, counter_); - std::vector<uint8_t> attestation_bytes = - attestation_data_->SerializeAsBytes(); + std::vector<uint8_t> attestation_bytes = attested_data_->SerializeAsBytes(); authenticator_utils::Append(&authenticator_data, attestation_bytes); return authenticator_data;
diff --git a/content/browser/webauth/authenticator_data.h b/content/browser/webauth/authenticator_data.h index 4219a828..76c8b84f 100644 --- a/content/browser/webauth/authenticator_data.h +++ b/content/browser/webauth/authenticator_data.h
@@ -15,7 +15,7 @@ namespace content { -class AttestationData; +class AttestedCredentialData; // https://www.w3.org/TR/2017/WD-webauthn-20170505/#sec-authenticator-data. class CONTENT_EXPORT AuthenticatorData { @@ -30,14 +30,14 @@ AuthenticatorData(std::string relying_party_id, Flags flags, std::vector<uint8_t> counter, - std::unique_ptr<AttestationData> data); + std::unique_ptr<AttestedCredentialData> data); virtual ~AuthenticatorData(); static std::unique_ptr<AuthenticatorData> Create( std::string client_data_json, Flags flags, std::vector<uint8_t> counter, - std::unique_ptr<AttestationData> data); + std::unique_ptr<AttestedCredentialData> data); // Produces a byte array consisting of: // * hash(relying_party_id) @@ -60,7 +60,7 @@ // Signature counter, 32-bit unsigned big-endian integer. const std::vector<uint8_t> counter_; - const std::unique_ptr<AttestationData> attestation_data_; + const std::unique_ptr<AttestedCredentialData> attested_data_; DISALLOW_COPY_AND_ASSIGN(AuthenticatorData); };
diff --git a/content/browser/webauth/authenticator_impl.cc b/content/browser/webauth/authenticator_impl.cc index 5be712a..eb72298 100644 --- a/content/browser/webauth/authenticator_impl.cc +++ b/content/browser/webauth/authenticator_impl.cc
@@ -60,7 +60,7 @@ // mojom::Authenticator void AuthenticatorImpl::MakeCredential( - webauth::mojom::MakeCredentialOptionsPtr options, + webauth::mojom::MakePublicKeyCredentialOptionsPtr options, MakeCredentialCallback callback) { // Ensure no other operations are in flight. // TODO(kpaulhamus): Do this properly. http://crbug.com/785954. @@ -94,14 +94,15 @@ // Check that at least one of the cryptographic parameters is supported. // Only ES256 is currently supported by U2F_V2. - if (!HasValidAlgorithm(options->crypto_parameters)) { + if (!HasValidAlgorithm(options->public_key_parameters)) { std::move(callback).Run( webauth::mojom::AuthenticatorStatus::NOT_SUPPORTED_ERROR, nullptr); return; } std::unique_ptr<CollectedClientData> client_data = - CollectedClientData::Create(caller_origin.Serialize(), + CollectedClientData::Create(authenticator_utils::kCreateType, + caller_origin.Serialize(), std::move(options->challenge)); // SHA-256 hash of the JSON data structure
diff --git a/content/browser/webauth/authenticator_impl.h b/content/browser/webauth/authenticator_impl.h index 891aa63..bf645f9 100644 --- a/content/browser/webauth/authenticator_impl.h +++ b/content/browser/webauth/authenticator_impl.h
@@ -43,7 +43,7 @@ private: // mojom:Authenticator - void MakeCredential(webauth::mojom::MakeCredentialOptionsPtr options, + void MakeCredential(webauth::mojom::MakePublicKeyCredentialOptionsPtr options, MakeCredentialCallback callback) override; // Callback to handle the async response from a U2fDevice.
diff --git a/content/browser/webauth/authenticator_impl_unittest.cc b/content/browser/webauth/authenticator_impl_unittest.cc index e77c07f..f9fc3eb 100644 --- a/content/browser/webauth/authenticator_impl_unittest.cc +++ b/content/browser/webauth/authenticator_impl_unittest.cc
@@ -9,8 +9,8 @@ #include "base/base64url.h" #include "base/run_loop.h" #include "base/test/gtest_util.h" -#include "content/browser/webauth/attestation_data.h" #include "content/browser/webauth/attestation_object.h" +#include "content/browser/webauth/attested_credential_data.h" #include "content/browser/webauth/authenticator_data.h" #include "content/browser/webauth/authenticator_utils.h" #include "content/browser/webauth/cbor/cbor_writer.h" @@ -33,10 +33,12 @@ using webauth::mojom::AuthenticatorPtr; using webauth::mojom::AuthenticatorStatus; -using webauth::mojom::MakeCredentialOptions; -using webauth::mojom::MakeCredentialOptionsPtr; -using webauth::mojom::PublicKeyCredentialEntity; -using webauth::mojom::PublicKeyCredentialEntityPtr; +using webauth::mojom::MakePublicKeyCredentialOptions; +using webauth::mojom::MakePublicKeyCredentialOptionsPtr; +using webauth::mojom::PublicKeyCredentialRpEntity; +using webauth::mojom::PublicKeyCredentialRpEntityPtr; +using webauth::mojom::PublicKeyCredentialUserEntity; +using webauth::mojom::PublicKeyCredentialUserEntityPtr; using webauth::mojom::PublicKeyCredentialInfoPtr; using webauth::mojom::PublicKeyCredentialParameters; using webauth::mojom::PublicKeyCredentialParametersPtr; @@ -57,8 +59,10 @@ 0xB8, 0x8C, 0x25, 0xDB, 0x9E, 0x60, 0x26, 0x45, 0xF1, 0x41}; constexpr char kTestClientDataJsonString[] = - "{\"challenge\":\"aHE0loIi7BcgLkJQX47SsWriLxa7BbiMJdueYCZF8UE\",\"hashAlg\"" - ":\"SHA-256\",\"origin\":\"google.com\",\"tokenBinding\":\"unused\"}"; + "{\"challenge\":\"aHE0loIi7BcgLkJQX47SsWriLxa7BbiMJdueYCZF8UE\"," + "\"hashAlgorithm\"" + ":\"SHA-256\",\"origin\":\"google.com\",\"tokenBinding\":\"unused\"," + "\"type\":\"webauthn.create\"}"; constexpr uint8_t kTestCredentialRawIdBytes[] = { 0x89, 0xAF, 0xB5, 0x24, 0x91, 0x1C, 0x40, 0x2B, 0x7F, 0x74, 0x59, @@ -166,9 +170,9 @@ 0x6F, 0x48, 0xB8, 0x25, 0x69, 0xEA, 0xD8, 0x23, 0x1A, 0x5A, 0x6C, 0x3A, 0x14, 0x48, 0xDE, 0xAA, 0xAF, 0x15, 0xC0, 0xEF, 0x29, 0x63, 0x1A}; -// The attestation data, excluding the CBOR public key bytes. Append with -// kTestECPublicKeyCBOR to get the complete attestation data. -constexpr uint8_t kTestAttestationDataPrefix[] = { +// The attested credential data, excluding the CBOR public key bytes. Append +// with kTestECPublicKeyCBOR to get the complete attestation data. +constexpr uint8_t kTestAttestedCredentialDataPrefix[] = { // clang-format off 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 16-byte aaguid @@ -182,8 +186,8 @@ // clang-format on }; -// The authenticator data, excluding the attestation data bytes. Append with -// attestation data to get the complete authenticator data. +// The authenticator data, excluding the attested credential data bytes. Append +// with attested credential data to get the complete authenticator data. constexpr uint8_t kTestAuthenticatorDataPrefix[] = { // clang-format off // sha256 hash of kTestRelyingPartyId @@ -350,17 +354,18 @@ return data; } -PublicKeyCredentialEntityPtr GetTestPublicKeyCredentialRPEntity() { - auto entity = PublicKeyCredentialEntity::New(); +PublicKeyCredentialRpEntityPtr GetTestPublicKeyCredentialRPEntity() { + auto entity = PublicKeyCredentialRpEntity::New(); entity->id = std::string("localhost"); entity->name = std::string("TestRP@example.com"); return entity; } -PublicKeyCredentialEntityPtr GetTestPublicKeyCredentialUserEntity() { - auto entity = PublicKeyCredentialEntity::New(); +PublicKeyCredentialUserEntityPtr GetTestPublicKeyCredentialUserEntity() { + auto entity = PublicKeyCredentialUserEntity::New(); entity->display_name = std::string("User A. Name"); - entity->id = std::string("1098237235409872"); + std::vector<uint8_t> id(32, 0x0A); + entity->id = id; entity->name = std::string("username@example.com"); entity->icon = GURL("fakeurl2.png"); return entity; @@ -376,32 +381,34 @@ return parameters; } -MakeCredentialOptionsPtr GetTestMakeCredentialOptions() { - auto options = MakeCredentialOptions::New(); +MakePublicKeyCredentialOptionsPtr GetTestMakePublicKeyCredentialOptions() { + auto options = MakePublicKeyCredentialOptions::New(); std::vector<uint8_t> buffer(32, 0x0A); options->relying_party = GetTestPublicKeyCredentialRPEntity(); options->user = GetTestPublicKeyCredentialUserEntity(); - options->crypto_parameters = GetTestPublicKeyCredentialParameters(kCoseEs256); + options->public_key_parameters = + GetTestPublicKeyCredentialParameters(kCoseEs256); options->challenge = std::move(buffer); options->adjusted_timeout = base::TimeDelta::FromMinutes(1); return options; } -std::unique_ptr<CollectedClientData> GetTestClientData() { +std::unique_ptr<CollectedClientData> GetTestClientData(std::string type) { std::unique_ptr<CollectedClientData> client_data = - CollectedClientData::Create(kTestRelyingPartyId, GetTestChallengeBytes()); + CollectedClientData::Create(type, kTestRelyingPartyId, + GetTestChallengeBytes()); return client_data; } -std::vector<uint8_t> GetTestAttestationDataBytes() { - // Combine kTestAttestationDataPrefix and kTestECPublicKeyCBOR. - std::vector<uint8_t> test_attestation_data( - std::begin(kTestAttestationDataPrefix), - std::end(kTestAttestationDataPrefix)); - test_attestation_data.insert(test_attestation_data.end(), - std::begin(kTestECPublicKeyCBOR), - std::end(kTestECPublicKeyCBOR)); - return test_attestation_data; +std::vector<uint8_t> GetTestAttestedCredentialDataBytes() { + // Combine kTestAttestedCredentialDataPrefix and kTestECPublicKeyCBOR. + std::vector<uint8_t> test_attested_data( + std::begin(kTestAttestedCredentialDataPrefix), + std::end(kTestAttestedCredentialDataPrefix)); + test_attested_data.insert(test_attested_data.end(), + std::begin(kTestECPublicKeyCBOR), + std::end(kTestECPublicKeyCBOR)); + return test_attested_data; } std::vector<uint8_t> GetTestAuthenticatorDataBytes() { @@ -409,10 +416,11 @@ std::vector<uint8_t> test_authenticator_data( std::begin(kTestAuthenticatorDataPrefix), std::end(kTestAuthenticatorDataPrefix)); - std::vector<uint8_t> test_attestation_data = GetTestAttestationDataBytes(); + std::vector<uint8_t> test_attested_data = + GetTestAttestedCredentialDataBytes(); test_authenticator_data.insert(test_authenticator_data.end(), - test_attestation_data.begin(), - test_attestation_data.end()); + test_attested_data.begin(), + test_attested_data.end()); return test_authenticator_data; } @@ -502,7 +510,8 @@ TEST_F(AuthenticatorImplTest, MakeCredentialOpaqueOrigin) { NavigateAndCommit(GURL("data:text/html,opaque")); AuthenticatorPtr authenticator = ConnectToAuthenticator(); - MakeCredentialOptionsPtr options = GetTestMakeCredentialOptions(); + MakePublicKeyCredentialOptionsPtr options = + GetTestMakePublicKeyCredentialOptions(); TestMakeCredentialCallback cb; authenticator->MakeCredential(std::move(options), cb.callback()); @@ -519,8 +528,9 @@ SimulateNavigation(GURL(kTestOrigin1)); AuthenticatorPtr authenticator = ConnectToAuthenticator(); - MakeCredentialOptionsPtr options = GetTestMakeCredentialOptions(); - options->crypto_parameters = GetTestPublicKeyCredentialParameters(123); + MakePublicKeyCredentialOptionsPtr options = + GetTestMakePublicKeyCredentialOptions(); + options->public_key_parameters = GetTestPublicKeyCredentialParameters(123); TestMakeCredentialCallback cb; authenticator->MakeCredential(std::move(options), cb.callback()); @@ -533,9 +543,9 @@ // Test that client data serializes to JSON properly. TEST_F(AuthenticatorImplTest, TestSerializedClientData) { - std::unique_ptr<CollectedClientData> client_data = - CollectedClientData::Create(kTestRelyingPartyId, GetTestChallengeBytes()); - EXPECT_EQ(kTestClientDataJsonString, client_data->SerializeToJson()); + EXPECT_EQ( + kTestClientDataJsonString, + GetTestClientData(authenticator_utils::kCreateType)->SerializeToJson()); } // Test that an EC public key serializes to CBOR properly. @@ -557,18 +567,18 @@ EXPECT_EQ(GetU2fAttestationStatementCBOR(), cbor.value()); } -// Tests that well-formed attestation data serializes properly. -TEST_F(AuthenticatorImplTest, TestAttestationData) { +// Tests that well-formed attested credential data serializes properly. +TEST_F(AuthenticatorImplTest, TestAttestedCredentialData) { std::unique_ptr<ECPublicKey> public_key = ECPublicKey::ExtractFromU2fRegistrationResponse( authenticator_utils::kEs256, GetTestRegisterResponse()); - std::unique_ptr<AttestationData> attestation_data = - AttestationData::CreateFromU2fRegisterResponse( + std::unique_ptr<AttestedCredentialData> attested_data = + AttestedCredentialData::CreateFromU2fRegisterResponse( GetTestRegisterResponse(), std::vector<uint8_t>(16, 0) /* aaguid */, std::move(public_key)); - EXPECT_EQ(GetTestAttestationDataBytes(), - attestation_data->SerializeAsBytes()); + EXPECT_EQ(GetTestAttestedCredentialDataBytes(), + attested_data->SerializeAsBytes()); } // Tests that well-formed authenticator data serializes properly. @@ -576,8 +586,8 @@ std::unique_ptr<ECPublicKey> public_key = ECPublicKey::ExtractFromU2fRegistrationResponse( authenticator_utils::kEs256, GetTestRegisterResponse()); - std::unique_ptr<AttestationData> attestation_data = - AttestationData::CreateFromU2fRegisterResponse( + std::unique_ptr<AttestedCredentialData> attested_data = + AttestedCredentialData::CreateFromU2fRegisterResponse( GetTestRegisterResponse(), std::vector<uint8_t>(16, 0) /* aaguid */, std::move(public_key)); @@ -588,9 +598,11 @@ AuthenticatorData::Flag::ATTESTATION); std::unique_ptr<AuthenticatorData> authenticator_data = - AuthenticatorData::Create(GetTestClientData()->SerializeToJson(), flags, - std::vector<uint8_t>(4, 0) /* counter */, - std::move(attestation_data)); + AuthenticatorData::Create( + GetTestClientData(authenticator_utils::kCreateType) + ->SerializeToJson(), + flags, std::vector<uint8_t>(4, 0) /* counter */, + std::move(attested_data)); EXPECT_EQ(GetTestAuthenticatorDataBytes(), authenticator_data->SerializeToByteArray()); @@ -601,8 +613,8 @@ std::unique_ptr<ECPublicKey> public_key = ECPublicKey::ExtractFromU2fRegistrationResponse( authenticator_utils::kEs256, GetTestRegisterResponse()); - std::unique_ptr<AttestationData> attestation_data = - AttestationData::CreateFromU2fRegisterResponse( + std::unique_ptr<AttestedCredentialData> attested_data = + AttestedCredentialData::CreateFromU2fRegisterResponse( GetTestRegisterResponse(), std::vector<uint8_t>(16, 0) /* aaguid */, std::move(public_key)); @@ -612,9 +624,11 @@ static_cast<AuthenticatorData::Flags>( AuthenticatorData::Flag::ATTESTATION); std::unique_ptr<AuthenticatorData> authenticator_data = - AuthenticatorData::Create(GetTestClientData()->SerializeToJson(), flags, - std::vector<uint8_t>(4, 0) /* counter */, - std::move(attestation_data)); + AuthenticatorData::Create( + GetTestClientData(authenticator_utils::kCreateType) + ->SerializeToJson(), + flags, std::vector<uint8_t>(4, 0) /* counter */, + std::move(attested_data)); // Construct the attestation statement. std::unique_ptr<FidoAttestationStatement> fido_attestation_statement = @@ -631,7 +645,8 @@ // Test that a U2F register response is properly parsed. TEST_F(AuthenticatorImplTest, TestRegisterResponseData) { - std::unique_ptr<CollectedClientData> client_data = GetTestClientData(); + std::unique_ptr<CollectedClientData> client_data = + GetTestClientData(authenticator_utils::kCreateType); std::unique_ptr<RegisterResponseData> response = RegisterResponseData::CreateFromU2fRegisterResponse( std::move(client_data), GetTestRegisterResponse());
diff --git a/content/browser/webauth/authenticator_utils.h b/content/browser/webauth/authenticator_utils.h index 16f6674..3a2e963 100644 --- a/content/browser/webauth/authenticator_utils.h +++ b/content/browser/webauth/authenticator_utils.h
@@ -13,9 +13,10 @@ namespace authenticator_utils { // JSON key values +constexpr char kTypeKey[] = "type"; constexpr char kChallengeKey[] = "challenge"; constexpr char kOriginKey[] = "origin"; -constexpr char kHashAlg[] = "hashAlg"; +constexpr char kHashAlgorithm[] = "hashAlgorithm"; constexpr char kTokenBindingKey[] = "tokenBinding"; // U2FResponse byte positions
diff --git a/content/browser/webauth/cbor/cbor_values.h b/content/browser/webauth/cbor/cbor_values.h index 1bc546b..6fe9e14 100644 --- a/content/browser/webauth/cbor/cbor_values.h +++ b/content/browser/webauth/cbor/cbor_values.h
@@ -12,7 +12,7 @@ #include "base/containers/flat_map.h" #include "base/macros.h" -#include "base/strings/string_piece_forward.h" +#include "base/strings/string_piece.h" #include "content/common/content_export.h" namespace content { @@ -37,22 +37,21 @@ // (byte-wise) lexical order sorts earlier. // // See section 6 of https://fidoalliance.org/specs/fido-v2.0-rd-20170927/ - // fido-client-to-authenticator-protocol-v2.0-rd-20170927.html and - // https://tools.ietf.org/html/rfc7049#section-3.9 also. - bool operator()(const std::string& a, const std::string& b) const { + // fido-client-to-authenticator-protocol-v2.0-rd-20170927.html. + // + // The sort order defined in + // https://tools.ietf.org/html/rfc7049#section-3.9 is similar to the CTAP + // order implemented here, but it sorts purely by serialised key and + // doesn't specify that major types are compared first. Thus the shortest + // key sorts first by the RFC rules (irrespective of the major type), but + // may not by CTAP rules. + bool operator()(const base::StringPiece& a, + const base::StringPiece& b) const { const size_t a_size = a.size(); const size_t b_size = b.size(); return std::tie(a_size, a) < std::tie(b_size, b); } - bool operator()(const char* a, const std::string& b) const { - return operator()(std::string(a), b); - } - - bool operator()(const std::string& a, const char* b) const { - return operator()(a, std::string(b)); - } - using is_transparent = void; };
diff --git a/content/browser/webauth/collected_client_data.cc b/content/browser/webauth/collected_client_data.cc index 288c97d..5f3a82a 100644 --- a/content/browser/webauth/collected_client_data.cc +++ b/content/browser/webauth/collected_client_data.cc
@@ -15,6 +15,7 @@ // static std::unique_ptr<CollectedClientData> CollectedClientData::Create( + std::string type, std::string relying_party_id, std::vector<uint8_t> challenge) { // The base64url encoding of options.challenge. @@ -28,22 +29,25 @@ // supports Token Binding, but is not using it to talk to the origin. // TODO(kpaulhamus): Fetch and add the Token Binding ID public key used to // communicate with the origin. - return std::make_unique<CollectedClientData>(std::move(encoded_challenge), - std::move(relying_party_id), - "SHA-256", "unused"); + return std::make_unique<CollectedClientData>( + std::move(type), std::move(encoded_challenge), + std::move(relying_party_id), "SHA-256", "unused"); } -CollectedClientData::CollectedClientData(std::string base64_encoded_challenge, +CollectedClientData::CollectedClientData(std::string type, + std::string base64_encoded_challenge, std::string origin, - std::string hash_alg, + std::string hash_algorithm, std::string token_binding_id) - : base64_encoded_challenge_(std::move(base64_encoded_challenge)), + : type_(std::move(type)), + base64_encoded_challenge_(std::move(base64_encoded_challenge)), origin_(std::move(origin)), - hash_alg_(std::move(hash_alg)), + hash_algorithm_(std::move(hash_algorithm)), token_binding_id_(std::move(token_binding_id)) {} std::string CollectedClientData::SerializeToJson() { base::DictionaryValue client_data; + client_data.SetString(authenticator_utils::kTypeKey, type_); client_data.SetString(authenticator_utils::kChallengeKey, base64_encoded_challenge_); @@ -52,7 +56,7 @@ // The recognized algorithm name of the hash algorithm selected by the client // for generating the hash of the serialized client data. - client_data.SetString(authenticator_utils::kHashAlg, hash_alg_); + client_data.SetString(authenticator_utils::kHashAlgorithm, hash_algorithm_); client_data.SetString(authenticator_utils::kTokenBindingKey, token_binding_id_);
diff --git a/content/browser/webauth/collected_client_data.h b/content/browser/webauth/collected_client_data.h index 1df6c14..35d8f8e 100644 --- a/content/browser/webauth/collected_client_data.h +++ b/content/browser/webauth/collected_client_data.h
@@ -15,18 +15,24 @@ namespace content { +namespace authenticator_utils { +constexpr char kCreateType[] = "webauthn.create"; +} + // Represents the contextual bindings of both the Relying Party and the // client platform that is used in authenticator signatures. // https://www.w3.org/TR/2017/WD-webauthn-20170505/#dictdef-collectedclientdata class CONTENT_EXPORT CollectedClientData { public: - CollectedClientData(std::string base64_encoded_challenge_, + CollectedClientData(std::string type_, + std::string base64_encoded_challenge_, std::string origin, - std::string hash_alg, + std::string hash_algorithm, std::string token_binding_id); virtual ~CollectedClientData(); static std::unique_ptr<CollectedClientData> Create( + std::string type, std::string relying_party_id, std::vector<uint8_t> challenge); @@ -35,9 +41,10 @@ std::string SerializeToJson(); private: + const std::string type_; const std::string base64_encoded_challenge_; const std::string origin_; - const std::string hash_alg_; + const std::string hash_algorithm_; const std::string token_binding_id_; // TODO(kpaulhamus): Add extensions support. https://crbug/757502.
diff --git a/content/browser/webauth/register_response_data.cc b/content/browser/webauth/register_response_data.cc index bb3c192c..73d4ca8 100644 --- a/content/browser/webauth/register_response_data.cc +++ b/content/browser/webauth/register_response_data.cc
@@ -6,7 +6,7 @@ #include <utility> -#include "content/browser/webauth/attestation_data.h" +#include "content/browser/webauth/attested_credential_data.h" #include "content/browser/webauth/authenticator_utils.h" #include "content/browser/webauth/ec_public_key.h" #include "content/browser/webauth/fido_attestation_statement.h" @@ -25,12 +25,12 @@ // Construct the attestation data. // AAGUID is zeroed out for U2F responses. std::vector<uint8_t> aaguid(16u, 0u); - std::unique_ptr<AttestationData> attestation_data = - AttestationData::CreateFromU2fRegisterResponse( + std::unique_ptr<AttestedCredentialData> attested_data = + AttestedCredentialData::CreateFromU2fRegisterResponse( u2f_data, std::move(aaguid), std::move(public_key)); // Extract the credential_id for packing into the reponse data. - std::vector<uint8_t> credential_id = attestation_data->credential_id(); + std::vector<uint8_t> credential_id = attested_data->credential_id(); // Construct the authenticator data. // The counter is zeroed out for Register requests. @@ -43,8 +43,7 @@ std::unique_ptr<AuthenticatorData> authenticator_data = AuthenticatorData::Create(client_data->SerializeToJson(), flags, - std::move(counter), - std::move(attestation_data)); + std::move(counter), std::move(attested_data)); // Construct the attestation statement. std::unique_ptr<FidoAttestationStatement> fido_attestation_statement =
diff --git a/content/common/BUILD.gn b/content/common/BUILD.gn index 803b79e..01fcfb5 100644 --- a/content/common/BUILD.gn +++ b/content/common/BUILD.gn
@@ -263,7 +263,6 @@ "quarantine/quarantine_linux.cc", "quarantine/quarantine_mac.mm", "quarantine/quarantine_win.cc", - "quota_messages.h", "render_widget_surface_properties.cc", "render_widget_surface_properties.h", "resize_params.cc", @@ -587,6 +586,7 @@ "native_types.mojom", "page_state.mojom", "push_messaging.mojom", + "quota_dispatcher_host.mojom", "render_frame_message_filter.mojom", "render_message_filter.mojom", "render_widget_window_tree_client_factory.mojom", @@ -600,7 +600,6 @@ "service_worker/service_worker_fetch_response_callback.mojom", "service_worker/service_worker_installed_scripts_manager.mojom", "service_worker/service_worker_provider.mojom", - "service_worker/service_worker_types.mojom", "shared_worker/shared_worker.mojom", "shared_worker/shared_worker_client.mojom", "shared_worker/shared_worker_connector.mojom", @@ -632,6 +631,7 @@ "//services/video_capture/public/interfaces", "//services/viz/public/interfaces", "//skia/public/interfaces", + "//storage/common:mojo_bindings", "//third_party/WebKit/public:mojo_bindings", "//ui/base/clipboard/mojom:mojo_bindings", "//ui/base/mojo:mojo_bindings",
diff --git a/content/common/associated_interface_provider_impl.h b/content/common/associated_interface_provider_impl.h index 71bca77..cf5f0af 100644 --- a/content/common/associated_interface_provider_impl.h +++ b/content/common/associated_interface_provider_impl.h
@@ -5,7 +5,7 @@ #ifndef CONTENT_COMMON_ASSOCIATED_INTERFACE_PROVIDER_IMPL_H_ #define CONTENT_COMMON_ASSOCIATED_INTERFACE_PROVIDER_IMPL_H_ -#include "content/public/common/associated_interface_provider.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" #include <stdint.h> #include <memory> @@ -15,7 +15,8 @@ namespace content { -class AssociatedInterfaceProviderImpl : public AssociatedInterfaceProvider { +class AssociatedInterfaceProviderImpl + : public blink::AssociatedInterfaceProvider { public: // Binds this to a remote mojom::AssociatedInterfaceProvider. explicit AssociatedInterfaceProviderImpl(
diff --git a/content/common/associated_interface_registry_impl.h b/content/common/associated_interface_registry_impl.h index 527647d..2e4a107 100644 --- a/content/common/associated_interface_registry_impl.h +++ b/content/common/associated_interface_registry_impl.h
@@ -10,12 +10,13 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" -#include "content/public/common/associated_interface_registry.h" #include "mojo/public/cpp/bindings/scoped_interface_endpoint_handle.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_registry.h" namespace content { -class AssociatedInterfaceRegistryImpl : public AssociatedInterfaceRegistry { +class AssociatedInterfaceRegistryImpl + : public blink::AssociatedInterfaceRegistry { public: AssociatedInterfaceRegistryImpl(); ~AssociatedInterfaceRegistryImpl() override;
diff --git a/content/common/background_fetch/background_fetch_struct_traits.cc b/content/common/background_fetch/background_fetch_struct_traits.cc index 048154cf..becd175c 100644 --- a/content/common/background_fetch/background_fetch_struct_traits.cc +++ b/content/common/background_fetch/background_fetch_struct_traits.cc
@@ -29,8 +29,7 @@ Read(blink::mojom::BackgroundFetchRegistrationDataView data, content::BackgroundFetchRegistration* registration) { if (!data.ReadDeveloperId(®istration->developer_id) || - !data.ReadUniqueId(®istration->unique_id) || - !data.ReadTitle(®istration->title)) { + !data.ReadUniqueId(®istration->unique_id)) { return false; }
diff --git a/content/common/background_fetch/background_fetch_struct_traits.h b/content/common/background_fetch/background_fetch_struct_traits.h index a20e83c..22ccecb 100644 --- a/content/common/background_fetch/background_fetch_struct_traits.h +++ b/content/common/background_fetch/background_fetch_struct_traits.h
@@ -69,10 +69,6 @@ const content::BackgroundFetchRegistration& registration) { return registration.downloaded; } - static const std::string& title( - const content::BackgroundFetchRegistration& registration) { - return registration.title; - } static bool Read(blink::mojom::BackgroundFetchRegistrationDataView data, content::BackgroundFetchRegistration* registration);
diff --git a/content/common/background_fetch/background_fetch_struct_traits_unittest.cc b/content/common/background_fetch/background_fetch_struct_traits_unittest.cc index af3522b..3e8c85f 100644 --- a/content/common/background_fetch/background_fetch_struct_traits_unittest.cc +++ b/content/common/background_fetch/background_fetch_struct_traits_unittest.cc
@@ -61,7 +61,6 @@ BackgroundFetchRegistration registration; registration.developer_id = "my_id"; registration.unique_id = "7e57ab1e-c0de-a150-ca75-1e75f005ba11"; - registration.title = "My Background Fetch"; registration.download_total = 9001; BackgroundFetchRegistration roundtrip_registration; @@ -72,7 +71,6 @@ EXPECT_EQ(roundtrip_registration.developer_id, registration.developer_id); EXPECT_EQ(roundtrip_registration.unique_id, registration.unique_id); - EXPECT_EQ(roundtrip_registration.title, registration.title); EXPECT_EQ(roundtrip_registration.download_total, registration.download_total); }
diff --git a/content/common/background_fetch/background_fetch_types.h b/content/common/background_fetch/background_fetch_types.h index 43e99e4b..685b624c 100644 --- a/content/common/background_fetch/background_fetch_types.h +++ b/content/common/background_fetch/background_fetch_types.h
@@ -65,9 +65,6 @@ uint64_t download_total = 0; uint64_t downloaded = 0; // TODO(crbug.com/699957): Support the `activeFetches` member. - - // TODO(crbug.com/769770): Remove the following deprecated members. - std::string title; }; // Represents a request/response pair for a settled Background Fetch fetch.
diff --git a/content/common/common_param_traits_unittest.cc b/content/common/common_param_traits_unittest.cc index 984c00cf..915ca42 100644 --- a/content/common/common_param_traits_unittest.cc +++ b/content/common/common_param_traits_unittest.cc
@@ -194,9 +194,8 @@ net::SignedCertificateTimestampAndStatus( sct, net::ct::SCT_STATUS_LOG_UNKNOWN)); - in.ct_compliance_details_available = true; - in.ct_cert_policy_compliance = - net::ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS; + in.ct_policy_compliance = + net::ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS; in.ocsp_result.response_status = net::OCSPVerifyResult::PROVIDED; in.ocsp_result.revocation_status = net::OCSPRevocationStatus::REVOKED; @@ -248,9 +247,7 @@ ASSERT_EQ(in.signed_certificate_timestamps[0].sct->log_description, out.signed_certificate_timestamps[0].sct->log_description); - ASSERT_EQ(in.ct_compliance_details_available, - out.ct_compliance_details_available); - ASSERT_EQ(in.ct_cert_policy_compliance, out.ct_cert_policy_compliance); + ASSERT_EQ(in.ct_policy_compliance, out.ct_policy_compliance); ASSERT_EQ(in.ocsp_result, out.ocsp_result); }
diff --git a/content/common/content_message_generator.h b/content/common/content_message_generator.h index 9c569e3d..d125b090 100644 --- a/content/common/content_message_generator.h +++ b/content/common/content_message_generator.h
@@ -104,11 +104,6 @@ #ifndef CONTENT_COMMON_PLATFORM_NOTIFICATION_MESSAGES_H_ #error "Failed to include content/common/platform_notification_messages.h" #endif -#undef CONTENT_COMMON_QUOTA_MESSAGES_H_ -#include "content/common/quota_messages.h" -#ifndef CONTENT_COMMON_QUOTA_MESSAGES_H_ -#error "Failed to include content/common/quota_messages.h" -#endif #undef CONTENT_COMMON_RESOURCE_MESSAGES_H_ #include "content/common/resource_messages.h" #ifndef CONTENT_COMMON_RESOURCE_MESSAGES_H_
diff --git a/content/common/quota_dispatcher_host.mojom b/content/common/quota_dispatcher_host.mojom new file mode 100644 index 0000000..385860d --- /dev/null +++ b/content/common/quota_dispatcher_host.mojom
@@ -0,0 +1,35 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +module content.mojom; + +import "storage/common/quota/quota_types.mojom"; +import "url/mojo/url.mojom"; + +// API for the renderer process to request quota information from the browser +// process. +// TODO(sashab): Put callback parameters in an optional struct, only set on +// success. +// TODO(sashab): Remove origin_url and render_frame_id, moving this interface to +// be per-execution context instead of per-process. +// TODO(sashab): Change origin_url to a url.mojom.Origin instead. +// TODO(sashab): Move this API and the necessary types to WebKit/common/. +interface QuotaDispatcherHost { + // Renderer process queries storage usage and quota from the browser process. + QueryStorageUsageAndQuota(url.mojom.Url origin_url, + storage.mojom.StorageType storage_type) => + (storage.mojom.QuotaStatusCode error, + int64 current_usage, + int64 current_quota); + + // Renderer process requests storage quota from the browser process. + // render_frame_id is used for showing the permissions UI. + RequestStorageQuota(int64 render_frame_id, + url.mojom.Url origin_url, + storage.mojom.StorageType storage_type, + uint64 requested_size) => + (storage.mojom.QuotaStatusCode error, + int64 current_usage, + int64 granted_quota); +};
diff --git a/content/common/quota_messages.h b/content/common/quota_messages.h deleted file mode 100644 index 04ac323e..0000000 --- a/content/common/quota_messages.h +++ /dev/null
@@ -1,54 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_COMMON_QUOTA_MESSAGES_H_ -#define CONTENT_COMMON_QUOTA_MESSAGES_H_ - -#include <stdint.h> - -#include "content/public/common/storage_quota_params.h" -#include "ipc/ipc_message_macros.h" -#include "storage/common/quota/quota_types.h" -#include "url/gurl.h" - -#define IPC_MESSAGE_START QuotaMsgStart - -IPC_ENUM_TRAITS_MAX_VALUE(storage::StorageType, storage::kStorageTypeLast) -IPC_ENUM_TRAITS_MAX_VALUE(storage::QuotaStatusCode, storage::kQuotaStatusLast) - -IPC_STRUCT_TRAITS_BEGIN(content::StorageQuotaParams) - IPC_STRUCT_TRAITS_MEMBER(render_frame_id) - IPC_STRUCT_TRAITS_MEMBER(request_id) - IPC_STRUCT_TRAITS_MEMBER(origin_url) - IPC_STRUCT_TRAITS_MEMBER(storage_type) - IPC_STRUCT_TRAITS_MEMBER(requested_size) -IPC_STRUCT_TRAITS_END() - -// Quota messages sent from the browser to the child process. - -IPC_MESSAGE_CONTROL3(QuotaMsg_DidGrantStorageQuota, - int /* request_id */, - int64_t /* current_usage */, - int64_t /* granted_quota */) - -IPC_MESSAGE_CONTROL3(QuotaMsg_DidQueryStorageUsageAndQuota, - int /* request_id */, - int64_t /* current_usage */, - int64_t /* current_quota */) - -IPC_MESSAGE_CONTROL2(QuotaMsg_DidFail, - int /* request_id */, - storage::QuotaStatusCode /* error */) - -// Quota messages sent from the child process to the browser. - -IPC_MESSAGE_CONTROL3(QuotaHostMsg_QueryStorageUsageAndQuota, - int /* request_id */, - GURL /* origin_url */, - storage::StorageType /* type */) - -IPC_MESSAGE_CONTROL1(QuotaHostMsg_RequestStorageQuota, - content::StorageQuotaParams) - -#endif // CONTENT_COMMON_QUOTA_MESSAGES_H_
diff --git a/content/common/resource_messages.cc b/content/common/resource_messages.cc index 0377b1f..b97fa77 100644 --- a/content/common/resource_messages.cc +++ b/content/common/resource_messages.cc
@@ -83,8 +83,7 @@ WriteParam(m, p.public_key_hashes); WriteParam(m, p.pinning_failure_log); WriteParam(m, p.signed_certificate_timestamps); - WriteParam(m, p.ct_compliance_details_available); - WriteParam(m, p.ct_cert_policy_compliance); + WriteParam(m, p.ct_policy_compliance); WriteParam(m, p.ocsp_result.response_status); WriteParam(m, p.ocsp_result.revocation_status); } @@ -113,8 +112,7 @@ ReadParam(m, iter, &r->public_key_hashes) && ReadParam(m, iter, &r->pinning_failure_log) && ReadParam(m, iter, &r->signed_certificate_timestamps) && - ReadParam(m, iter, &r->ct_compliance_details_available) && - ReadParam(m, iter, &r->ct_cert_policy_compliance) && + ReadParam(m, iter, &r->ct_policy_compliance) && ReadParam(m, iter, &r->ocsp_result.response_status) && ReadParam(m, iter, &r->ocsp_result.revocation_status); } @@ -185,11 +183,11 @@ break; } case storage::DataElement::TYPE_DATA_PIPE: { - blink::mojom::SizeGetterPtr size_getter; - WriteParam( - m, - const_cast<param_type&>(p).ReleaseDataPipe(&size_getter).release()); - WriteParam(m, size_getter.PassInterface().PassHandle().release()); + WriteParam(m, + const_cast<network::mojom::DataPipeGetterPtr&>(p.data_pipe()) + .PassInterface() + .PassHandle() + .release()); break; } case storage::DataElement::TYPE_UNKNOWN: { @@ -291,17 +289,13 @@ return false; } case storage::DataElement::TYPE_DATA_PIPE: { - mojo::DataPipeConsumerHandle data_pipe; - blink::mojom::SizeGetterPtr size_getter; - if (!ReadParam(m, iter, &data_pipe)) - return false; + network::mojom::DataPipeGetterPtr data_pipe_getter; mojo::MessagePipeHandle message_pipe; if (!ReadParam(m, iter, &message_pipe)) return false; - size_getter.Bind(blink::mojom::SizeGetterPtrInfo( + data_pipe_getter.Bind(network::mojom::DataPipeGetterPtrInfo( mojo::ScopedMessagePipeHandle(message_pipe), 0u)); - r->SetToDataPipe(mojo::ScopedDataPipeConsumerHandle(data_pipe), - std::move(size_getter)); + r->SetToDataPipe(std::move(data_pipe_getter)); return true; } case storage::DataElement::TYPE_UNKNOWN: {
diff --git a/content/common/resource_messages.h b/content/common/resource_messages.h index cce5aa6..3b37496 100644 --- a/content/common/resource_messages.h +++ b/content/common/resource_messages.h
@@ -143,8 +143,8 @@ IPC_ENUM_TRAITS_MAX_VALUE(net::SSLInfo::HandshakeType, net::SSLInfo::HANDSHAKE_FULL) IPC_ENUM_TRAITS_MAX_VALUE( - net::ct::CertPolicyCompliance, - net::ct::CertPolicyCompliance::CERT_POLICY_BUILD_NOT_TIMELY) + net::ct::CTPolicyCompliance, + net::ct::CTPolicyCompliance::CT_POLICY_COMPLIANCE_DETAILS_NOT_AVAILABLE) IPC_ENUM_TRAITS_MAX_VALUE(net::OCSPVerifyResult::ResponseStatus, net::OCSPVerifyResult::PARSE_RESPONSE_DATA_ERROR) IPC_ENUM_TRAITS_MAX_VALUE(net::OCSPRevocationStatus, @@ -254,7 +254,7 @@ IPC_STRUCT_TRAITS_MEMBER(visibility_state) IPC_STRUCT_TRAITS_MEMBER(headers) IPC_STRUCT_TRAITS_MEMBER(load_flags) - IPC_STRUCT_TRAITS_MEMBER(origin_pid) + IPC_STRUCT_TRAITS_MEMBER(plugin_child_id) IPC_STRUCT_TRAITS_MEMBER(resource_type) IPC_STRUCT_TRAITS_MEMBER(priority) IPC_STRUCT_TRAITS_MEMBER(request_context) @@ -344,15 +344,10 @@ // // NOTE: The shared memory handle should already be mapped into the process // that receives this message. -// -// TODO(darin): The |renderer_pid| parameter is just a temporary parameter, -// added to help in debugging crbug/160401. -// -IPC_MESSAGE_CONTROL4(ResourceMsg_SetDataBuffer, +IPC_MESSAGE_CONTROL3(ResourceMsg_SetDataBuffer, int /* request_id */, base::SharedMemoryHandle /* shm_handle */, - int /* shm_size */, - base::ProcessId /* renderer_pid */) + int /* shm_size */) // Sent when some data from a resource request is ready. The data offset and // length specify a byte range into the shared memory buffer provided by the
diff --git a/content/common/service_worker/service_worker_container.mojom b/content/common/service_worker/service_worker_container.mojom index 3a59055..3be3efd 100644 --- a/content/common/service_worker/service_worker_container.mojom +++ b/content/common/service_worker/service_worker_container.mojom
@@ -5,7 +5,6 @@ module content.mojom; import "content/common/service_worker/controller_service_worker.mojom"; -import "content/common/service_worker/service_worker_types.mojom"; import "mojo/common/string16.mojom"; import "third_party/WebKit/public/platform/modules/serviceworker/service_worker_error_type.mojom"; import "third_party/WebKit/public/platform/modules/serviceworker/service_worker_object.mojom";
diff --git a/content/common/service_worker/service_worker_event_dispatcher.mojom b/content/common/service_worker/service_worker_event_dispatcher.mojom index 7a4a5dfb..bb2b3bf 100644 --- a/content/common/service_worker/service_worker_event_dispatcher.mojom +++ b/content/common/service_worker/service_worker_event_dispatcher.mojom
@@ -61,7 +61,7 @@ // 'simple events'. ServiceWorkerVersion::CreateSimpleEventCallback can be used // to create the callback for these. interface ServiceWorkerEventDispatcher { - DispatchInstallEvent(associated ServiceWorkerInstallEventMethods method) + DispatchInstallEvent() => (blink.mojom.ServiceWorkerEventStatus status, bool has_fetch_handler, mojo.common.mojom.Time dispatch_event_time); @@ -157,11 +157,3 @@ // dispatch an event. Ping() => (); }; - -// This interface is passed from the browser to the renderer with -// DispatchInstallEvent. The ordering between RegisterForeignFetchScopes and the -// callback of DispatchInstallEvent should be preserved. -interface ServiceWorkerInstallEventMethods { - RegisterForeignFetchScopes(array<url.mojom.Url> sub_scopes, - array<url.mojom.Origin> origins); -};
diff --git a/content/common/service_worker/service_worker_fetch_request_struct_traits.cc b/content/common/service_worker/service_worker_fetch_request_struct_traits.cc index 822e19b..5e7b4b1 100644 --- a/content/common/service_worker/service_worker_fetch_request_struct_traits.cc +++ b/content/common/service_worker/service_worker_fetch_request_struct_traits.cc
@@ -284,8 +284,6 @@ switch (input) { case content::ServiceWorkerFetchType::FETCH: return ServiceWorkerFetchType::FETCH; - case content::ServiceWorkerFetchType::FOREIGN_FETCH: - return ServiceWorkerFetchType::FOREIGN_FETCH; } NOTREACHED(); @@ -299,9 +297,6 @@ case ServiceWorkerFetchType::FETCH: *out = content::ServiceWorkerFetchType::FETCH; return true; - case ServiceWorkerFetchType::FOREIGN_FETCH: - *out = content::ServiceWorkerFetchType::FOREIGN_FETCH; - return true; } return false;
diff --git a/content/common/service_worker/service_worker_loader_helpers.cc b/content/common/service_worker/service_worker_loader_helpers.cc index 334e380..a0c0b10 100644 --- a/content/common/service_worker/service_worker_loader_helpers.cc +++ b/content/common/service_worker/service_worker_loader_helpers.cc
@@ -76,7 +76,6 @@ const ServiceWorkerResponse& response, ResourceResponseHead* out_head) { out_head->was_fetched_via_service_worker = true; - out_head->was_fetched_via_foreign_fetch = false; out_head->was_fallback_required_by_service_worker = false; out_head->url_list_via_service_worker = response.url_list; out_head->response_type_via_service_worker = response.response_type;
diff --git a/content/common/service_worker/service_worker_messages.h b/content/common/service_worker/service_worker_messages.h index 9f679ba..724fea4 100644 --- a/content/common/service_worker/service_worker_messages.h +++ b/content/common/service_worker/service_worker_messages.h
@@ -45,9 +45,6 @@ IPC_ENUM_TRAITS_MAX_VALUE(network::mojom::FetchResponseType, network::mojom::FetchResponseType::kLast) -IPC_ENUM_TRAITS_MAX_VALUE(content::ServiceWorkerProviderType, - content::SERVICE_WORKER_PROVIDER_TYPE_LAST) - IPC_ENUM_TRAITS_MAX_VALUE(content::ServiceWorkerFetchType, content::ServiceWorkerFetchType::LAST)
diff --git a/content/common/service_worker/service_worker_provider.mojom b/content/common/service_worker/service_worker_provider.mojom index e86e3f7..44df68c7 100644 --- a/content/common/service_worker/service_worker_provider.mojom +++ b/content/common/service_worker/service_worker_provider.mojom
@@ -5,9 +5,9 @@ module content.mojom; import "content/common/service_worker/service_worker_container.mojom"; -import "content/common/service_worker/service_worker_types.mojom"; import "content/public/common/url_loader_factory.mojom"; import "services/service_manager/public/interfaces/interface_provider.mojom"; +import "third_party/WebKit/common/service_worker/service_worker_provider_type.mojom"; import "third_party/WebKit/public/platform/modules/serviceworker/service_worker_registration.mojom"; // The name of the InterfaceProviderSpec in service manifests used by the @@ -42,7 +42,7 @@ struct ServiceWorkerProviderHostInfo { int32 provider_id; int32 route_id; - ServiceWorkerProviderType type; + blink.mojom.ServiceWorkerProviderType type; bool is_parent_frame_secure; associated ServiceWorkerContainerHost& host_request; associated ServiceWorkerContainer client_ptr_info;
diff --git a/content/common/service_worker/service_worker_provider_host_info.cc b/content/common/service_worker/service_worker_provider_host_info.cc index 610dbb8..f387c1b5 100644 --- a/content/common/service_worker/service_worker_provider_host_info.cc +++ b/content/common/service_worker/service_worker_provider_host_info.cc
@@ -13,7 +13,7 @@ void SetDefaultValues(ServiceWorkerProviderHostInfo* info) { info->provider_id = kInvalidServiceWorkerProviderId; info->route_id = MSG_ROUTING_NONE; - info->type = SERVICE_WORKER_PROVIDER_UNKNOWN; + info->type = blink::mojom::ServiceWorkerProviderType::kUnknown; info->is_parent_frame_secure = false; } @@ -22,7 +22,7 @@ ServiceWorkerProviderHostInfo::ServiceWorkerProviderHostInfo() : provider_id(kInvalidServiceWorkerProviderId), route_id(MSG_ROUTING_NONE), - type(SERVICE_WORKER_PROVIDER_UNKNOWN), + type(blink::mojom::ServiceWorkerProviderType::kUnknown), is_parent_frame_secure(false) {} ServiceWorkerProviderHostInfo::ServiceWorkerProviderHostInfo( @@ -54,7 +54,7 @@ ServiceWorkerProviderHostInfo::ServiceWorkerProviderHostInfo( int provider_id, int route_id, - ServiceWorkerProviderType type, + blink::mojom::ServiceWorkerProviderType type, bool is_parent_frame_secure) : provider_id(provider_id), route_id(route_id),
diff --git a/content/common/service_worker/service_worker_provider_host_info.h b/content/common/service_worker/service_worker_provider_host_info.h index 68b05f9..729eb48 100644 --- a/content/common/service_worker/service_worker_provider_host_info.h +++ b/content/common/service_worker/service_worker_provider_host_info.h
@@ -7,6 +7,7 @@ #include "content/common/service_worker/service_worker_container.mojom.h" #include "content/common/service_worker/service_worker_types.h" +#include "third_party/WebKit/common/service_worker/service_worker_provider_type.mojom.h" namespace content { @@ -22,7 +23,7 @@ mojom::ServiceWorkerContainerAssociatedPtrInfo client_ptr_info); ServiceWorkerProviderHostInfo(int provider_id, int route_id, - ServiceWorkerProviderType type, + blink::mojom::ServiceWorkerProviderType type, bool is_parent_frame_secure); ~ServiceWorkerProviderHostInfo(); @@ -40,9 +41,9 @@ // |route_id| is MSG_ROUTING_NONE. int route_id; - // This identifies whether this provider is for Service Worker controllees - // (documents and Shared Workers) or for controllers (Service Workers). - ServiceWorkerProviderType type; + // This identifies whether this provider is for a service worker or for a + // service worker client (Documents and Shared Workers). + blink::mojom::ServiceWorkerProviderType type; // |is_parent_frame_secure| is false if the provider is created for a document // whose parent frame is not secure from the point of view of the document;
diff --git a/content/common/service_worker/service_worker_provider_struct_traits.cc b/content/common/service_worker/service_worker_provider_struct_traits.cc index a94ecaa..59833f8 100644 --- a/content/common/service_worker/service_worker_provider_struct_traits.cc +++ b/content/common/service_worker/service_worker_provider_struct_traits.cc
@@ -3,7 +3,6 @@ // found in the LICENSE file. #include "content/common/service_worker/service_worker_provider_struct_traits.h" -#include "content/common/service_worker/service_worker_types_struct_traits.h" namespace mojo {
diff --git a/content/common/service_worker/service_worker_provider_struct_traits.h b/content/common/service_worker/service_worker_provider_struct_traits.h index 11de120..f099711a 100644 --- a/content/common/service_worker/service_worker_provider_struct_traits.h +++ b/content/common/service_worker/service_worker_provider_struct_traits.h
@@ -6,6 +6,7 @@ #define CONTENT_COMMON_SERVICE_WORKER_SERVICE_WORKER_PROVIDER_STRUCT_TRAITS_H_ #include "content/common/service_worker/service_worker_provider.mojom.h" +#include "third_party/WebKit/common/service_worker/service_worker_provider_type.mojom.h" namespace mojo { @@ -21,7 +22,7 @@ return info.route_id; } - static content::ServiceWorkerProviderType type( + static blink::mojom::ServiceWorkerProviderType type( const content::ServiceWorkerProviderHostInfo& info) { return info.type; }
diff --git a/content/common/service_worker/service_worker_types.h b/content/common/service_worker/service_worker_types.h index fc67444..4a17b86 100644 --- a/content/common/service_worker/service_worker_types.h +++ b/content/common/service_worker/service_worker_types.h
@@ -59,20 +59,6 @@ static constexpr base::TimeDelta kServiceWorkerScriptMaxCacheAge = base::TimeDelta::FromHours(24); -// ServiceWorker provider type. -enum ServiceWorkerProviderType { - SERVICE_WORKER_PROVIDER_UNKNOWN, - - // For ServiceWorker clients. - SERVICE_WORKER_PROVIDER_FOR_WINDOW, - SERVICE_WORKER_PROVIDER_FOR_SHARED_WORKER, - - // For ServiceWorkers. - SERVICE_WORKER_PROVIDER_FOR_SERVICE_WORKER, - - SERVICE_WORKER_PROVIDER_TYPE_LAST = SERVICE_WORKER_PROVIDER_FOR_SERVICE_WORKER -}; - // Indicates how the service worker handled a fetch event. enum ServiceWorkerFetchEventResult { // Browser should fallback to native fetch.
diff --git a/content/common/service_worker/service_worker_types.mojom b/content/common/service_worker/service_worker_types.mojom deleted file mode 100644 index 09744c8..0000000 --- a/content/common/service_worker/service_worker_types.mojom +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -module content.mojom; - -enum ServiceWorkerProviderType { - SERVICE_WORKER_PROVIDER_UNKNOWN, - - // For ServiceWorker clients. - SERVICE_WORKER_PROVIDER_FOR_WINDOW, - SERVICE_WORKER_PROVIDER_FOR_SHARED_WORKER, - - // For ServiceWorkers. - SERVICE_WORKER_PROVIDER_FOR_SERVICE_WORKER, - - SERVICE_WORKER_PROVIDER_TYPE_LAST = - SERVICE_WORKER_PROVIDER_FOR_SERVICE_WORKER -};
diff --git a/content/common/service_worker/service_worker_types.typemap b/content/common/service_worker/service_worker_types.typemap deleted file mode 100644 index 9e68f09..0000000 --- a/content/common/service_worker/service_worker_types.typemap +++ /dev/null
@@ -1,17 +0,0 @@ -# Copyright 2016 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -mojom = "//content/common/service_worker/service_worker_types.mojom" -public_headers = [ - "//content/common/service_worker/service_worker_client_info.h", - "//content/common/service_worker/service_worker_types.h", -] -traits_headers = [ - "//content/common/service_worker/service_worker_messages.h", - "//content/common/service_worker/service_worker_types_struct_traits.h", -] -sources = [ - "//content/common/service_worker/service_worker_types_struct_traits.cc", -] -type_mappings = [ "content.mojom.ServiceWorkerProviderType=::content::ServiceWorkerProviderType" ]
diff --git a/content/common/service_worker/service_worker_types_struct_traits.cc b/content/common/service_worker/service_worker_types_struct_traits.cc deleted file mode 100644 index 74e57dc..0000000 --- a/content/common/service_worker/service_worker_types_struct_traits.cc +++ /dev/null
@@ -1,54 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/common/service_worker/service_worker_types_struct_traits.h" - -#include "base/logging.h" - -namespace mojo { - -using content::mojom::ServiceWorkerProviderType; - -ServiceWorkerProviderType -EnumTraits<ServiceWorkerProviderType, content::ServiceWorkerProviderType>:: - ToMojom(content::ServiceWorkerProviderType input) { - switch (input) { - case content::SERVICE_WORKER_PROVIDER_UNKNOWN: - return ServiceWorkerProviderType::SERVICE_WORKER_PROVIDER_UNKNOWN; - case content::SERVICE_WORKER_PROVIDER_FOR_WINDOW: - return ServiceWorkerProviderType::SERVICE_WORKER_PROVIDER_FOR_WINDOW; - case content::SERVICE_WORKER_PROVIDER_FOR_SHARED_WORKER: - return ServiceWorkerProviderType:: - SERVICE_WORKER_PROVIDER_FOR_SHARED_WORKER; - case content::SERVICE_WORKER_PROVIDER_FOR_SERVICE_WORKER: - return ServiceWorkerProviderType:: - SERVICE_WORKER_PROVIDER_FOR_SERVICE_WORKER; - } - - NOTREACHED(); - return ServiceWorkerProviderType::SERVICE_WORKER_PROVIDER_UNKNOWN; -} - -bool EnumTraits<ServiceWorkerProviderType, content::ServiceWorkerProviderType>:: - FromMojom(ServiceWorkerProviderType input, - content::ServiceWorkerProviderType* out) { - switch (input) { - case ServiceWorkerProviderType::SERVICE_WORKER_PROVIDER_UNKNOWN: - *out = content::SERVICE_WORKER_PROVIDER_UNKNOWN; - return true; - case ServiceWorkerProviderType::SERVICE_WORKER_PROVIDER_FOR_WINDOW: - *out = content::SERVICE_WORKER_PROVIDER_FOR_WINDOW; - return true; - case ServiceWorkerProviderType::SERVICE_WORKER_PROVIDER_FOR_SHARED_WORKER: - *out = content::SERVICE_WORKER_PROVIDER_FOR_SHARED_WORKER; - return true; - case ServiceWorkerProviderType::SERVICE_WORKER_PROVIDER_FOR_SERVICE_WORKER: - *out = content::SERVICE_WORKER_PROVIDER_FOR_SERVICE_WORKER; - return true; - } - - return false; -} - -} // namespace mojo
diff --git a/content/common/service_worker/service_worker_types_struct_traits.h b/content/common/service_worker/service_worker_types_struct_traits.h deleted file mode 100644 index fb4670de5..0000000 --- a/content/common/service_worker/service_worker_types_struct_traits.h +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_COMMON_SERVICE_WORKER_SERVICE_WORKER_TYPES_STRUCT_TRAITS_H_ -#define CONTENT_COMMON_SERVICE_WORKER_SERVICE_WORKER_TYPES_STRUCT_TRAITS_H_ - -#include "content/common/service_worker/service_worker_types.mojom.h" - -namespace mojo { - -template <> -struct EnumTraits<content::mojom::ServiceWorkerProviderType, - content::ServiceWorkerProviderType> { - static content::mojom::ServiceWorkerProviderType ToMojom( - content::ServiceWorkerProviderType input); - - static bool FromMojom(content::mojom::ServiceWorkerProviderType input, - content::ServiceWorkerProviderType* out); -}; - -} // namespace mojo - -#endif // CONTENT_COMMON_SERVICE_WORKER_SERVICE_WORKER_TYPES_STRUCT_TRAITS_H_
diff --git a/content/common/throttling_url_loader.h b/content/common/throttling_url_loader.h index d0f2b53..dd1138f7 100644 --- a/content/common/throttling_url_loader.h +++ b/content/common/throttling_url_loader.h
@@ -45,8 +45,7 @@ const ResourceRequest& url_request, mojom::URLLoaderClient* client, const net::NetworkTrafficAnnotationTag& traffic_annotation, - scoped_refptr<base::SingleThreadTaskRunner> task_runner = - base::ThreadTaskRunnerHandle::Get()); + scoped_refptr<base::SingleThreadTaskRunner> task_runner); using StartLoaderCallback = base::OnceCallback<void(mojom::URLLoaderRequest request, @@ -62,8 +61,7 @@ const ResourceRequest& url_request, mojom::URLLoaderClient* client, const net::NetworkTrafficAnnotationTag& traffic_annotation, - scoped_refptr<base::SingleThreadTaskRunner> task_runner = - base::ThreadTaskRunnerHandle::Get()); + scoped_refptr<base::SingleThreadTaskRunner> task_runner); ~ThrottlingURLLoader() override;
diff --git a/content/common/throttling_url_loader_unittest.cc b/content/common/throttling_url_loader_unittest.cc index 73de5378..1aea494 100644 --- a/content/common/throttling_url_loader_unittest.cc +++ b/content/common/throttling_url_loader_unittest.cc
@@ -276,7 +276,8 @@ request.url = request_url; loader_ = ThrottlingURLLoader::CreateLoaderAndStart( factory_.factory_ptr().get(), std::move(throttles_), 0, 0, options, - request, &client_, TRAFFIC_ANNOTATION_FOR_TESTS); + request, &client_, TRAFFIC_ANNOTATION_FOR_TESTS, + base::ThreadTaskRunnerHandle::Get()); factory_.factory_ptr().FlushForTesting(); }
diff --git a/content/common/typemaps.gni b/content/common/typemaps.gni index b394ac3..2ff5ab9 100644 --- a/content/common/typemaps.gni +++ b/content/common/typemaps.gni
@@ -16,7 +16,6 @@ "//content/common/service_worker/service_worker_event_dispatcher.typemap", "//content/common/service_worker/service_worker_fetch_request.typemap", "//content/common/service_worker/service_worker_provider.typemap", - "//content/common/service_worker/service_worker_types.typemap", "//content/common/url_loader_factory_bundle.typemap", "//content/common/web_preferences.typemap", "//content/common/media/media_session.typemap",
diff --git a/content/gpu/gpu_child_thread.cc b/content/gpu/gpu_child_thread.cc index 2e2f71c..6752f55 100644 --- a/content/gpu/gpu_child_thread.cc +++ b/content/gpu/gpu_child_thread.cc
@@ -191,7 +191,8 @@ } #endif - AssociatedInterfaceRegistry* associated_registry = &associated_interfaces_; + blink::AssociatedInterfaceRegistry* associated_registry = + &associated_interfaces_; associated_registry->AddInterface(base::Bind( &GpuChildThread::CreateVizMainService, base::Unretained(this)));
diff --git a/content/gpu/gpu_sandbox_hook_linux.cc b/content/gpu/gpu_sandbox_hook_linux.cc index 2f20f8ab5..1ccff94 100644 --- a/content/gpu/gpu_sandbox_hook_linux.cc +++ b/content/gpu/gpu_sandbox_hook_linux.cc
@@ -183,7 +183,7 @@ // For shared memory. permissions->push_back( - BrokerFilePermission::ReadWriteCreateUnlinkRecursive(kDevShm)); + BrokerFilePermission::ReadWriteCreateTemporaryRecursive(kDevShm)); // For DRI cards. for (int i = 0; i <= 9; ++i) { @@ -342,7 +342,9 @@ if (!LoadLibrariesForGpu(options)) return false; - instance->EngageNamespaceSandbox(false /* from_zygote */); + // TODO(tsepez): enable once we can proxy the stat(), readlink() syscalls. + if (!IsChromeOS() || !options.use_amd_specific_policies) + instance->EngageNamespaceSandbox(false /* from_zygote */); errno = 0; return true;
diff --git a/content/network/url_loader.cc b/content/network/url_loader.cc index 45f821c..15fad4d 100644 --- a/content/network/url_loader.cc +++ b/content/network/url_loader.cc
@@ -171,27 +171,22 @@ // A subclass of net::UploadElementReader to read data pipes. class DataPipeElementReader : public net::UploadElementReader { public: - DataPipeElementReader(mojo::ScopedDataPipeConsumerHandle data_pipe, - blink::mojom::SizeGetterPtr size_getter) - : data_pipe_(std::move(data_pipe)), + DataPipeElementReader( + scoped_refptr<ResourceRequestBody> resource_request_body, + network::mojom::DataPipeGetterPtr data_pipe_getter_) + : resource_request_body_(std::move(resource_request_body)), + data_pipe_getter_(std::move(data_pipe_getter_)), handle_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::MANUAL), - size_getter_(std::move(size_getter)), - weak_factory_(this) { - size_getter_->GetSize(base::Bind(&DataPipeElementReader::GetSizeCallback, - weak_factory_.GetWeakPtr())); - handle_watcher_.Watch(data_pipe_.get(), MOJO_HANDLE_SIGNAL_READABLE, - base::Bind(&DataPipeElementReader::OnHandleReadable, - base::Unretained(this))); - } + weak_factory_(this) {} ~DataPipeElementReader() override {} private: - void GetSizeCallback(uint64_t size) { - calculated_size_ = true; - size_ = size; + void ReadCallback(int32_t status, uint64_t size) { + if (status == net::OK) + size_ = size; if (!init_callback_.is_null()) - std::move(init_callback_).Run(net::OK); + std::move(init_callback_).Run(status); } void OnHandleReadable(MojoResult result) { @@ -208,8 +203,24 @@ // net::UploadElementReader implementation: int Init(const net::CompletionCallback& callback) override { - if (calculated_size_) - return net::OK; + // Init rewinds the stream. Throw away current state. + if (!read_callback_.is_null()) + std::move(read_callback_).Run(net::ERR_FAILED); + buf_ = nullptr; + buf_length_ = 0; + handle_watcher_.Cancel(); + size_ = 0; + bytes_read_ = 0; + + // Get a new data pipe and start. + mojo::DataPipe data_pipe; + data_pipe_getter_->Read(std::move(data_pipe.producer_handle), + base::BindOnce(&DataPipeElementReader::ReadCallback, + weak_factory_.GetWeakPtr())); + data_pipe_ = std::move(data_pipe.consumer_handle); + handle_watcher_.Watch(data_pipe_.get(), MOJO_HANDLE_SIGNAL_READABLE, + base::Bind(&DataPipeElementReader::OnHandleReadable, + base::Unretained(this))); init_callback_ = std::move(callback); return net::ERR_IO_PENDING; @@ -244,12 +255,12 @@ return net::ERR_FAILED; } + scoped_refptr<ResourceRequestBody> resource_request_body_; + network::mojom::DataPipeGetterPtr data_pipe_getter_; mojo::ScopedDataPipeConsumerHandle data_pipe_; mojo::SimpleWatcher handle_watcher_; scoped_refptr<net::IOBuffer> buf_; int buf_length_ = 0; - blink::mojom::SizeGetterPtr size_getter_; - bool calculated_size_ = false; uint64_t size_ = 0; uint64_t bytes_read_ = 0; net::CompletionCallback init_callback_; @@ -287,12 +298,9 @@ break; } case ResourceRequestBody::Element::TYPE_DATA_PIPE: { - blink::mojom::SizeGetterPtr size_getter; - mojo::ScopedDataPipeConsumerHandle data_pipe = - const_cast<storage::DataElement*>(&element)->ReleaseDataPipe( - &size_getter); element_readers.push_back(std::make_unique<DataPipeElementReader>( - std::move(data_pipe), std::move(size_getter))); + body, const_cast<storage::DataElement*>(&element) + ->ReleaseDataPipeGetter())); break; } case ResourceRequestBody::Element::TYPE_DISK_CACHE_ENTRY:
diff --git a/content/network/url_loader_unittest.cc b/content/network/url_loader_unittest.cc index 8df8d78..aee0e26 100644 --- a/content/network/url_loader_unittest.cc +++ b/content/network/url_loader_unittest.cc
@@ -28,6 +28,7 @@ #include "content/public/common/resource_request_body.h" #include "content/public/test/controllable_http_response.h" #include "content/public/test/test_url_loader_client.h" +#include "mojo/common/data_pipe_utils.h" #include "mojo/public/c/system/data_pipe.h" #include "mojo/public/cpp/system/wait.h" #include "net/base/io_buffer.h" @@ -60,7 +61,7 @@ url::Origin::Create(url); // ensure initiator is set request.referrer_policy = blink::kWebReferrerPolicyDefault; request.load_flags = 0; - request.origin_pid = 0; + request.plugin_child_id = -1; request.resource_type = type; request.request_context = 0; request.appcache_host_id = kAppCacheNoHostId; @@ -157,6 +158,28 @@ DISALLOW_COPY_AND_ASSIGN(MultipleWritesInterceptor); }; +class SimpleDataPipeGetter : public network::mojom::DataPipeGetter { + public: + SimpleDataPipeGetter(const std::string& str, + network::mojom::DataPipeGetterRequest request) + : str_(str), binding_(this, std::move(request)) {} + ~SimpleDataPipeGetter() override = default; + + // network::mojom::DataPipeGetter implementation: + void Read(mojo::ScopedDataPipeProducerHandle handle, + ReadCallback callback) override { + bool result = mojo::common::BlockingCopyFromString(str_, handle); + ASSERT_TRUE(result); + std::move(callback).Run(net::OK, str_.length()); + } + + private: + std::string str_; + mojo::Binding<network::mojom::DataPipeGetter> binding_; + + DISALLOW_COPY_AND_ASSIGN(SimpleDataPipeGetter); +}; + } // namespace class URLLoaderTest : public testing::Test { @@ -210,6 +233,11 @@ ran_ = true; + if (expect_redirect_) { + client_.RunUntilRedirectReceived(); + loader->FollowRedirect(); + } + if (body) { client_.RunUntilResponseBodyArrived(); *body = ReadBody(); @@ -326,6 +354,10 @@ DCHECK(!ran_); add_custom_accept_header_ = true; } + void set_expect_redirect() { + DCHECK(!ran_); + expect_redirect_ = true; + } void set_resource_type(ResourceType type) { DCHECK(!ran_); resource_type_ = type; @@ -419,11 +451,12 @@ net::EmbeddedTestServer test_server_; std::unique_ptr<NetworkContext> context_; - // Options applied the created request in Load(). + // Options applied to the created request in Load(). bool sniff_ = false; bool send_ssl_with_response_ = false; bool send_ssl_for_cert_error_ = false; bool add_custom_accept_header_ = false; + bool expect_redirect_ = false; ResourceType resource_type_ = RESOURCE_TYPE_MAIN_FRAME; scoped_refptr<ResourceRequestBody> request_body_; @@ -1036,7 +1069,41 @@ EXPECT_EQ(expected_body, response_body); } -// TODO(mmenke): Test using a data pipe to upload data. +// Tests a request body with a data pipe element. +TEST_F(URLLoaderTest, UploadDataPipe) { + const std::string kRequestBody = "Request Body"; + + network::mojom::DataPipeGetterPtr data_pipe_getter_ptr; + auto data_pipe_getter = std::make_unique<SimpleDataPipeGetter>( + kRequestBody, mojo::MakeRequest(&data_pipe_getter_ptr)); + + auto request_body = base::MakeRefCounted<ResourceRequestBody>(); + request_body->AppendDataPipe(std::move(data_pipe_getter_ptr)); + set_request_body(std::move(request_body)); + + std::string response_body; + EXPECT_EQ(net::OK, Load(test_server()->GetURL("/echo"), &response_body)); + EXPECT_EQ(kRequestBody, response_body); +} + +// Same as above and tests that the body is sent after a 307 redirect. +TEST_F(URLLoaderTest, UploadDataPipe_Redirect307) { + const std::string kRequestBody = "Request Body"; + + network::mojom::DataPipeGetterPtr data_pipe_getter_ptr; + auto data_pipe_getter = std::make_unique<SimpleDataPipeGetter>( + kRequestBody, mojo::MakeRequest(&data_pipe_getter_ptr)); + + auto request_body = base::MakeRefCounted<ResourceRequestBody>(); + request_body->AppendDataPipe(std::move(data_pipe_getter_ptr)); + set_request_body(std::move(request_body)); + set_expect_redirect(); + + std::string response_body; + EXPECT_EQ(net::OK, Load(test_server()->GetURL("/redirect307-to-echo"), + &response_body)); + EXPECT_EQ(kRequestBody, response_body); +} TEST_F(URLLoaderTest, UploadDoubleRawFile) { base::FilePath file_path = GetTestFilePath("simple_page.html");
diff --git a/content/public/android/java/src/org/chromium/content/browser/SelectionPopupController.java b/content/public/android/java/src/org/chromium/content/browser/SelectionPopupController.java index 6b786b6f..edbd18c 100644 --- a/content/public/android/java/src/org/chromium/content/browser/SelectionPopupController.java +++ b/content/public/android/java/src/org/chromium/content/browser/SelectionPopupController.java
@@ -321,8 +321,8 @@ public void showActionModeOrClearOnFailure() { if (!isActionModeSupported() || !hasSelection()) return; - // Just refresh the view if action mode already exists. - if (isActionModeValid()) { + // Just refresh non-floating action mode if it already exists to avoid blinking. + if (isActionModeValid() && !isFloatingActionMode()) { // Try/catch necessary for framework bug, crbug.com/446717. try { mActionMode.invalidate(); @@ -333,6 +333,9 @@ return; } + // Reset overflow menu (see crbug.com/700929). + destroyActionModeAndKeepSelection(); + assert mWebContents != null; ActionMode actionMode = supportsFloatingActionMode() ? startFloatingActionMode() @@ -479,7 +482,7 @@ * @param hide whether to hide or show the ActionMode. */ private void hideActionMode(boolean hide) { - if (!canHideActionMode()) return; + if (!isFloatingActionMode()) return; if (mHidden == hide) return; mHidden = hide; if (mHidden) { @@ -495,13 +498,13 @@ * @see ActionMode#hide(long) */ private void hideActionModeTemporarily(long duration) { - assert canHideActionMode(); + assert isFloatingActionMode(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (isActionModeValid()) mActionMode.hide(duration); } } - private boolean canHideActionMode() { + private boolean isFloatingActionMode() { return supportsFloatingActionMode() && isActionModeValid() && mActionMode.getType() == ActionMode.TYPE_FLOATING;
diff --git a/content/public/app/mojo/content_browser_manifest.json b/content/public/app/mojo/content_browser_manifest.json index c2bc477..534e313 100644 --- a/content/public/app/mojo/content_browser_manifest.json +++ b/content/public/app/mojo/content_browser_manifest.json
@@ -35,6 +35,7 @@ "content::mojom::MediaStreamDispatcherHost", "content::mojom::MemoryCoordinatorHandle", "content::mojom::PushMessaging", + "content::mojom::QuotaDispatcherHost", "content::mojom::RendererHost", "content::mojom::ReportingServiceProxy", "content::mojom::ServiceWorkerDispatcherHost", @@ -71,7 +72,7 @@ "content_plugin": [ "browser" ], "content_renderer": [ "browser" ], "content_utility": [ "browser" ], - "data_decoder": [ "image_decoder", "json_parser" ], + "data_decoder": [ "image_decoder", "json_parser", "xml_parser" ], "device": [ "device:battery_monitor", "device:generic_sensor", @@ -127,6 +128,7 @@ "blink::mojom::InsecureInputService", "blink::mojom::KeyboardLockService", "blink::mojom::MediaSessionService", + "blink::mojom::NotificationService", "blink::mojom::PermissionService", "blink::mojom::PresentationService", "blink::mojom::TextSuggestionHost", @@ -175,6 +177,7 @@ "navigation:dedicated_worker": { "provides": { "renderer": [ + "blink::mojom::NotificationService", "blink::mojom::PermissionService", "payments::mojom::PaymentManager", "shape_detection::mojom::BarcodeDetection", @@ -186,6 +189,7 @@ "navigation:service_worker": { "provides": { "renderer": [ + "blink::mojom::NotificationService", "blink::mojom::PermissionService", "blink::mojom::WebSocket", "payments::mojom::PaymentManager", @@ -198,6 +202,7 @@ "navigation:shared_worker": { "provides": { "renderer": [ + "blink::mojom::NotificationService", "blink::mojom::PermissionService", "blink::mojom::WebSocket", "payments::mojom::PaymentManager",
diff --git a/content/public/browser/BUILD.gn b/content/public/browser/BUILD.gn index 46106f4..ab5fdf3 100644 --- a/content/public/browser/BUILD.gn +++ b/content/public/browser/BUILD.gn
@@ -118,6 +118,7 @@ "download_request_utils.h", "download_save_info.cc", "download_save_info.h", + "download_source.h", "download_url_parameters.cc", "download_url_parameters.h", "favicon_status.cc",
diff --git a/content/public/browser/content_browser_client.h b/content/public/browser/content_browser_client.h index 7f91123a..f522e6c 100644 --- a/content/public/browser/content_browser_client.h +++ b/content/public/browser/content_browser_client.h
@@ -19,7 +19,6 @@ #include "build/build_config.h" #include "content/public/browser/certificate_request_result_type.h" #include "content/public/browser/navigation_throttle.h" -#include "content/public/common/associated_interface_registry.h" #include "content/public/common/content_client.h" #include "content/public/common/media_stream_request.h" #include "content/public/common/network_service.mojom.h" @@ -35,6 +34,7 @@ #include "services/service_manager/sandbox/sandbox_type.h" #include "storage/browser/fileapi/file_system_context.h" #include "storage/browser/quota/quota_manager.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_registry.h" #include "third_party/WebKit/common/page/page_visibility_state.mojom.h" #include "third_party/WebKit/public/web/window_features.mojom.h" #include "ui/base/page_transition_types.h" @@ -732,7 +732,7 @@ // task runner is provided. virtual void ExposeInterfacesToRenderer( service_manager::BinderRegistry* registry, - AssociatedInterfaceRegistry* associated_registry, + blink::AssociatedInterfaceRegistry* associated_registry, RenderProcessHost* render_process_host) {} // Called when RenderFrameHostImpl connects to the Media service. Expose
diff --git a/content/public/browser/download_source.h b/content/public/browser/download_source.h new file mode 100644 index 0000000..040fd01 --- /dev/null +++ b/content/public/browser/download_source.h
@@ -0,0 +1,59 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_PUBLIC_BROWSER_DOWNLOAD_SOURCE_H_ +#define CONTENT_PUBLIC_BROWSER_DOWNLOAD_SOURCE_H_ + +namespace content { + +// The source of download. +// Used in UMA metrics and persisted to disk. +// Entries in this enum can only be appended instead of being deleted or reused. +// Any changes here also needs to apply to enums.xml. +enum class DownloadSource { + // The source is unknown. + UNKNOWN = 0, + + // Download is triggered from navigation request. + NAVIGATION = 1, + + // Drag and drop. + DRAG_AND_DROP = 2, + + // User manually resume the download. + MANUAL_RESUMPTION = 3, + + // Auto resumption in download system. + AUTO_RESUMPTION = 4, + + // Renderer initiated download, mostly from Javascript or HTML <a> tag. + FROM_RENDERER = 5, + + // Extension download API. + EXTENSION_API = 6, + + // Extension web store installer. + EXTENSION_INSTALLER = 7, + + // Plugin triggered download. + PLUGIN = 8, + + // Plugin installer download. + PLUGIN_INSTALLER = 9, + + // Download service API background download. + INTERNAL_API = 10, + + // Save package download. + SAVE_PACKAGE = 11, + + // Offline page download. + OFFLINE_PAGE = 12, + + COUNT = 13 +}; + +} // namespace content + +#endif // CONTENT_PUBLIC_BROWSER_DOWNLOAD_SOURCE_H_
diff --git a/content/public/browser/download_url_parameters.cc b/content/public/browser/download_url_parameters.cc index 39665ac..3151376 100644 --- a/content/public/browser/download_url_parameters.cc +++ b/content/public/browser/download_url_parameters.cc
@@ -47,7 +47,8 @@ do_not_prompt_for_login_(false), fetch_error_body_(false), transient_(false), - traffic_annotation_(traffic_annotation) {} + traffic_annotation_(traffic_annotation), + download_source_(DownloadSource::UNKNOWN) {} DownloadUrlParameters::~DownloadUrlParameters() { }
diff --git a/content/public/browser/download_url_parameters.h b/content/public/browser/download_url_parameters.h index e74b084..f1584852 100644 --- a/content/public/browser/download_url_parameters.h +++ b/content/public/browser/download_url_parameters.h
@@ -18,6 +18,7 @@ #include "base/optional.h" #include "content/public/browser/download_interrupt_reasons.h" #include "content/public/browser/download_save_info.h" +#include "content/public/browser/download_source.h" #include "content/public/common/referrer.h" #include "net/traffic_annotation/network_traffic_annotation.h" #include "net/url_request/url_request_context_getter.h" @@ -244,6 +245,11 @@ request_origin_ = origin; } + // Sets the download source, which will be used in metrics recording. + void set_download_source(DownloadSource download_source) { + download_source_ = download_source; + } + const OnStartedCallback& callback() const { return callback_; } bool content_initiated() const { return content_initiated_; } const std::string& last_modified() const { return last_modified_; } @@ -301,6 +307,8 @@ return traffic_annotation_; } + DownloadSource download_source() const { return download_source_; } + private: OnStartedCallback callback_; bool content_initiated_; @@ -328,6 +336,7 @@ std::unique_ptr<storage::BlobDataHandle> blob_data_handle_; const net::NetworkTrafficAnnotationTag traffic_annotation_; std::string request_origin_; + DownloadSource download_source_; DISALLOW_COPY_AND_ASSIGN(DownloadUrlParameters); };
diff --git a/content/public/browser/gpu_utils.cc b/content/public/browser/gpu_utils.cc index baf0ca1..06b7e88 100644 --- a/content/public/browser/gpu_utils.cc +++ b/content/public/browser/gpu_utils.cc
@@ -118,6 +118,8 @@ command_line->HasSwitch(switches::kGLShaderIntermOutput); gpu_preferences.emulate_shader_precision = command_line->HasSwitch(switches::kEmulateShaderPrecision); + gpu_preferences.enable_raster_decoder = + command_line->HasSwitch(switches::kEnableRasterDecoder); gpu_preferences.enable_gpu_service_logging = command_line->HasSwitch(switches::kEnableGPUServiceLogging); gpu_preferences.enable_gpu_service_tracing =
diff --git a/content/public/browser/host_zoom_map.h b/content/public/browser/host_zoom_map.h index 14c960d..c64bbd37c 100644 --- a/content/public/browser/host_zoom_map.h +++ b/content/public/browser/host_zoom_map.h
@@ -194,7 +194,7 @@ virtual std::unique_ptr<Subscription> AddZoomLevelChangedCallback( const ZoomLevelChangedCallback& callback) = 0; - virtual void SetClockForTesting(std::unique_ptr<base::Clock> clock) = 0; + virtual void SetClockForTesting(base::Clock* clock) = 0; protected: virtual ~HostZoomMap() {}
diff --git a/content/public/browser/javascript_dialog_manager.h b/content/public/browser/javascript_dialog_manager.h index 74db785c..734dcf2 100644 --- a/content/public/browser/javascript_dialog_manager.h +++ b/content/public/browser/javascript_dialog_manager.h
@@ -16,6 +16,7 @@ namespace content { +class RenderFrameHost; class WebContents; // An interface consisting of methods that can be called to produce and manage @@ -38,6 +39,7 @@ // Displays a dialog asking the user if they want to leave a page. virtual void RunBeforeUnloadDialog(WebContents* web_contents, + RenderFrameHost* render_frame_host, bool is_reload, DialogClosedCallback callback) = 0;
diff --git a/content/public/browser/render_frame_host.h b/content/public/browser/render_frame_host.h index 73369509..bb3ae9b 100644 --- a/content/public/browser/render_frame_host.h +++ b/content/public/browser/render_frame_host.h
@@ -23,6 +23,7 @@ #include "url/origin.h" namespace blink { +class AssociatedInterfaceProvider; enum class FeaturePolicyFeature; } @@ -45,7 +46,6 @@ namespace content { -class AssociatedInterfaceProvider; class RenderProcessHost; class RenderViewHost; class RenderWidgetHostView; @@ -217,7 +217,8 @@ // Returns the AssociatedInterfaceProvider that this process can use to access // remote frame-specific Channel-associated interfaces for this frame. - virtual AssociatedInterfaceProvider* GetRemoteAssociatedInterfaces() = 0; + virtual blink::AssociatedInterfaceProvider* + GetRemoteAssociatedInterfaces() = 0; // Returns the visibility state of the frame. The different visibility states // of a frame are defined in Blink.
diff --git a/content/public/browser/resource_request_info.h b/content/public/browser/resource_request_info.h index 2655390..374d38e 100644 --- a/content/public/browser/resource_request_info.h +++ b/content/public/browser/resource_request_info.h
@@ -110,9 +110,10 @@ // The globally unique identifier for this request. virtual GlobalRequestID GetGlobalRequestID() const = 0; - // The pid of the originating process, if the request is sent on behalf of a - // another process. Otherwise it is 0. - virtual int GetOriginPID() const = 0; + // The child process unique ID of the originating process, if the request is + // was proxied through a renderer process on behalf of a pepper plugin + // process; -1 otherwise. + virtual int GetPluginChildID() const = 0; // Returns the FrameTreeNode ID for this frame. This ID is browser-global and // uniquely identifies a frame that hosts content.
diff --git a/content/public/common/BUILD.gn b/content/public/common/BUILD.gn index a966ad4..14f9df4 100644 --- a/content/public/common/BUILD.gn +++ b/content/public/common/BUILD.gn
@@ -108,8 +108,6 @@ sources = [ "appcache_info.h", - "associated_interface_provider.h", - "associated_interface_registry.h", "bind_interface_helpers.h", "bindings_policy.h", "browser_controls_state.h",
diff --git a/content/public/common/DEPS b/content/public/common/DEPS index f1958d7..15b058f2 100644 --- a/content/public/common/DEPS +++ b/content/public/common/DEPS
@@ -4,9 +4,6 @@ "+services/network/public/cpp", "+third_party/WebKit/common", ], - "resource_request_body.h": [ - "+third_party/WebKit/common/blob/size_getter.mojom.h", - ], "simple_url_loader\.cc": [ "-content/", "+content/public/common/simple_url_loader\.h",
diff --git a/content/public/common/associated_interface_provider.h b/content/public/common/associated_interface_provider.h deleted file mode 100644 index 6806e74e..0000000 --- a/content/public/common/associated_interface_provider.h +++ /dev/null
@@ -1,53 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_PUBLIC_COMMON_ASSOCIATED_INTERFACE_PROVIDER_H_ -#define CONTENT_PUBLIC_COMMON_ASSOCIATED_INTERFACE_PROVIDER_H_ - -#include <string> - -#include "mojo/public/cpp/bindings/associated_interface_ptr.h" -#include "mojo/public/cpp/bindings/associated_interface_request.h" -#include "mojo/public/cpp/bindings/scoped_interface_endpoint_handle.h" - -namespace content { - -// A helper interface for connecting to remote Channel-associated interfaces. -// -// This is analogous to service_manager::InterfaceProvider in that it provides a -// means of -// binding proxies to remote interfaces, but this is specifically for interfaces -// which must be associated with an IPC::Channel, i.e. retain FIFO message -// ordering with respect to legacy IPC messages. -// -// The Channel with which the remote interfaces are associated depends on -// the configuration of the specific AssociatedInterfaceProvider instance. For -// example, RenderFrameHost exposes an instance of this class for which all -// interfaces are associated with the IPC::ChannelProxy to the render process -// which hosts its corresponding RenderFrame. -class AssociatedInterfaceProvider { - public: - virtual ~AssociatedInterfaceProvider() {} - - // Passes an associated endpoint handle to the remote end to be bound to a - // Channel-associated interface named |name|. - virtual void GetInterface(const std::string& name, - mojo::ScopedInterfaceEndpointHandle handle) = 0; - - // Templated helper for GetInterface(). - template <typename Interface> - void GetInterface(mojo::AssociatedInterfacePtr<Interface>* proxy) { - auto request = mojo::MakeRequest(proxy); - GetInterface(Interface::Name_, request.PassHandle()); - } - - virtual void OverrideBinderForTesting( - const std::string& name, - const base::Callback<void(mojo::ScopedInterfaceEndpointHandle)>& - binder) = 0; -}; - -} // namespace content - -#endif // CONTENT_PUBLIC_COMMON_ASSOCIATED_INTERFACE_PROVIDER_H_
diff --git a/content/public/common/associated_interface_registry.h b/content/public/common/associated_interface_registry.h deleted file mode 100644 index 883438b..0000000 --- a/content/public/common/associated_interface_registry.h +++ /dev/null
@@ -1,62 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_PUBLIC_COMMON_ASSOCIATED_INTERFACE_REGISTRY_H_ -#define CONTENT_PUBLIC_COMMON_ASSOCIATED_INTERFACE_REGISTRY_H_ - -#include <string> - -#include "base/bind.h" -#include "base/callback.h" -#include "mojo/public/cpp/bindings/associated_interface_request.h" -#include "mojo/public/cpp/bindings/scoped_interface_endpoint_handle.h" - -namespace content { - -// An AssociatedInterfaceRegistry is a collection of associated interface- -// binding callbacks mapped by interface name. -// -// This is used to register binding callbacks for interfaces which must be -// associated with some IPC::ChannelProxy, meaning that messages on the -// interface retain FIFO with respect to legacy Chrome IPC messages sent or -// dispatched on the channel. -// -// The channel with which a registered interface is associated depends on the -// configuration of the specific AssociatedInterfaceRegistry instance. For -// example, RenderFrame exposes an instance of this class for which all -// interfaces are associated with the IPC::SyncChannel to the browser. -class AssociatedInterfaceRegistry { - public: - using Binder = base::Callback<void(mojo::ScopedInterfaceEndpointHandle)>; - - virtual ~AssociatedInterfaceRegistry() {} - - // Adds an interface binder to the registry. - virtual void AddInterface(const std::string& name, const Binder& binder) = 0; - - // Removes an interface binder from the registry. - virtual void RemoveInterface(const std::string& name) = 0; - - template <typename Interface> - using InterfaceBinder = - base::Callback<void(mojo::AssociatedInterfaceRequest<Interface>)>; - - // Templated helper for AddInterface() above. - template <typename Interface> - void AddInterface(const InterfaceBinder<Interface>& binder) { - AddInterface(Interface::Name_, - base::Bind(&BindInterface<Interface>, binder)); - } - - private: - template <typename Interface> - static void BindInterface(const InterfaceBinder<Interface>& binder, - mojo::ScopedInterfaceEndpointHandle handle) { - binder.Run(mojo::AssociatedInterfaceRequest<Interface>(std::move(handle))); - } -}; - -} // namespace content - -#endif // CONTENT_PUBLIC_COMMON_ASSOCIATED_INTERFACE_REGISTRY_H_
diff --git a/content/public/common/content_features.cc b/content/public/common/content_features.cc index d7f3ceb5..f3dab5d 100644 --- a/content/public/common/content_features.cc +++ b/content/public/common/content_features.cc
@@ -172,7 +172,7 @@ // Mojo-based Input Event routing. const base::Feature kMojoInputMessages{"MojoInputMessages", - base::FEATURE_DISABLED_BY_DEFAULT}; + base::FEATURE_ENABLED_BY_DEFAULT}; // Mojo-based Session Storage. const base::Feature kMojoSessionStorage{"MojoSessionStorage",
diff --git a/content/public/common/resource_request.h b/content/public/common/resource_request.h index ae6ee85f..cdfd4e1 100644 --- a/content/public/common/resource_request.h +++ b/content/public/common/resource_request.h
@@ -11,6 +11,7 @@ #include "base/memory/ref_counted.h" #include "base/optional.h" #include "content/common/content_export.h" +#include "content/public/common/child_process_host.h" #include "content/public/common/previews_state.h" #include "content/public/common/request_context_frame_type.h" #include "content/public/common/request_context_type.h" @@ -68,9 +69,10 @@ // net::URLRequest load flags (0 by default). int load_flags = 0; - // Process ID from which this request originated, or zero if it originated - // in the renderer itself. - int origin_pid = 0; + // If this request originated from a pepper plugin running in a child + // process, this identifies which process it came from. Otherwise, it + // is zero. + int plugin_child_id = ChildProcessHost::kInvalidUniqueID; // What this resource load is for (main frame, sub-frame, sub-resource, // object).
diff --git a/content/public/common/resource_request_body.cc b/content/public/common/resource_request_body.cc index 1350e0c..579a652 100644 --- a/content/public/common/resource_request_body.cc +++ b/content/public/common/resource_request_body.cc
@@ -81,10 +81,9 @@ } void ResourceRequestBody::AppendDataPipe( - mojo::ScopedDataPipeConsumerHandle handle, - blink::mojom::SizeGetterPtr size_getter) { + network::mojom::DataPipeGetterPtr data_pipe_getter) { elements_.push_back(Element()); - elements_.back().SetToDataPipe(std::move(handle), std::move(size_getter)); + elements_.back().SetToDataPipe(std::move(data_pipe_getter)); } std::vector<base::FilePath> ResourceRequestBody::GetReferencedFiles() const {
diff --git a/content/public/common/resource_request_body.h b/content/public/common/resource_request_body.h index 7f30ccd..ad6c7b1 100644 --- a/content/public/common/resource_request_body.h +++ b/content/public/common/resource_request_body.h
@@ -17,7 +17,6 @@ #include "build/build_config.h" #include "content/common/content_export.h" #include "storage/common/data_element.h" -#include "third_party/WebKit/common/blob/size_getter.mojom.h" #include "url/gurl.h" #if defined(OS_ANDROID) @@ -69,8 +68,7 @@ uint64_t offset, uint64_t length, const base::Time& expected_modification_time); - void AppendDataPipe(mojo::ScopedDataPipeConsumerHandle handle, - blink::mojom::SizeGetterPtr size_getter); + void AppendDataPipe(network::mojom::DataPipeGetterPtr data_pipe_getter); const std::vector<Element>* elements() const { return &elements_; } std::vector<Element>* elements_mutable() { return &elements_; }
diff --git a/content/public/common/resource_response.cc b/content/public/common/resource_response.cc index 1153d380..e3e2a664 100644 --- a/content/public/common/resource_response.cc +++ b/content/public/common/resource_response.cc
@@ -41,8 +41,6 @@ new_response->head.socket_address = head.socket_address; new_response->head.was_fetched_via_service_worker = head.was_fetched_via_service_worker; - new_response->head.was_fetched_via_foreign_fetch = - head.was_fetched_via_foreign_fetch; new_response->head.was_fallback_required_by_service_worker = head.was_fallback_required_by_service_worker; new_response->head.url_list_via_service_worker =
diff --git a/content/public/common/resource_response_info.cc b/content/public/common/resource_response_info.cc index c1e853f2a..8de8efad 100644 --- a/content/public/common/resource_response_info.cc +++ b/content/public/common/resource_response_info.cc
@@ -22,7 +22,6 @@ was_alternate_protocol_available(false), connection_info(net::HttpResponseInfo::CONNECTION_INFO_UNKNOWN), was_fetched_via_service_worker(false), - was_fetched_via_foreign_fetch(false), was_fallback_required_by_service_worker(false), response_type_via_service_worker( network::mojom::FetchResponseType::kDefault),
diff --git a/content/public/common/resource_response_info.h b/content/public/common/resource_response_info.h index 73c50fd..57c5075 100644 --- a/content/public/common/resource_response_info.h +++ b/content/public/common/resource_response_info.h
@@ -115,9 +115,6 @@ // True if the response was fetched by a ServiceWorker. bool was_fetched_via_service_worker; - // True if the response was fetched by a foreign fetch ServiceWorker; - bool was_fetched_via_foreign_fetch; - // True when the request whoes mode is |CORS| or |CORS-with-forced-preflight| // is sent to a ServiceWorker but FetchEvent.respondWith is not called. So the // renderer have to resend the request with skip service worker flag
diff --git a/content/public/common/service_worker_modes.h b/content/public/common/service_worker_modes.h index d6f861ab..6459e17 100644 --- a/content/public/common/service_worker_modes.h +++ b/content/public/common/service_worker_modes.h
@@ -20,24 +20,19 @@ LAST = MANUAL_MODE }; -// Whether this is a regular fetch, or a foreign fetch request. +// Whether this is a regular fetch, or a foreign fetch request (now removed). // Duplicate of blink::mojom::ServiceWorkerFetchType. -enum class ServiceWorkerFetchType { - FETCH, - FOREIGN_FETCH, - LAST = FOREIGN_FETCH -}; +// TODO(falken): Remove this since it's always FETCH. +enum class ServiceWorkerFetchType { FETCH, LAST = FETCH }; -// Indicates which service workers will receive fetch events for this request. +// Indicates whether service workers will receive fetch events for this request. +// TODO(falken): This enum made more sense when there was a foreign fetch mode. +// Find better names or fold this into a boolean. enum class ServiceWorkerMode { - // Relevant local and foreign service workers will get a fetch or - // foreignfetch event for this request. - ALL, - // Only relevant foreign service workers will get a foreignfetch event for - // this request. - FOREIGN, - // Neither local nor foreign service workers will get events for this + // The relevant service worker, if any, will get a fetch event for this // request. + ALL, + // No service worker will get events for this request. NONE, LAST = NONE };
diff --git a/content/public/common/storage_quota_params.h b/content/public/common/storage_quota_params.h index 80c6cf5b..fdc2c3a8 100644 --- a/content/public/common/storage_quota_params.h +++ b/content/public/common/storage_quota_params.h
@@ -19,12 +19,10 @@ struct CONTENT_EXPORT StorageQuotaParams { StorageQuotaParams() : render_frame_id(MSG_ROUTING_NONE), - request_id(-1), storage_type(storage::kStorageTypeTemporary), requested_size(0) {} int render_frame_id; - int request_id; GURL origin_url; storage::StorageType storage_type; uint64_t requested_size;
diff --git a/content/public/renderer/render_frame.h b/content/public/renderer/render_frame.h index adbeb35..229f73c8 100644 --- a/content/public/renderer/render_frame.h +++ b/content/public/renderer/render_frame.h
@@ -25,6 +25,8 @@ #include "third_party/WebKit/public/web/WebTriggeringEventInfo.h" namespace blink { +class AssociatedInterfaceProvider; +class AssociatedInterfaceRegistry; class WebFrame; class WebLocalFrame; class WebPlugin; @@ -51,8 +53,6 @@ } namespace content { -class AssociatedInterfaceProvider; -class AssociatedInterfaceRegistry; class ChildURLLoaderFactoryGetter; class ContextMenuClient; class PluginInstanceThrottler; @@ -167,12 +167,14 @@ // Returns the AssociatedInterfaceRegistry this frame can use to expose // frame-specific Channel-associated interfaces to the remote RenderFrameHost. - virtual AssociatedInterfaceRegistry* GetAssociatedInterfaceRegistry() = 0; + virtual blink::AssociatedInterfaceRegistry* + GetAssociatedInterfaceRegistry() = 0; // Returns the AssociatedInterfaceProvider this frame can use to access // frame-specific Channel-associated interfaces from the remote // RenderFrameHost. - virtual AssociatedInterfaceProvider* GetRemoteAssociatedInterfaces() = 0; + virtual blink::AssociatedInterfaceProvider* + GetRemoteAssociatedInterfaces() = 0; #if BUILDFLAG(ENABLE_PLUGINS) // Registers a plugin that has been marked peripheral. If the origin
diff --git a/content/public/renderer/render_thread_observer.h b/content/public/renderer/render_thread_observer.h index 97af873..35b708e 100644 --- a/content/public/renderer/render_thread_observer.h +++ b/content/public/renderer/render_thread_observer.h
@@ -8,12 +8,15 @@ #include "base/macros.h" #include "content/common/content_export.h" +namespace blink { +class AssociatedInterfaceRegistry; +} + namespace IPC { class Message; } namespace content { -class AssociatedInterfaceRegistry; // Base class for objects that want to filter control IPC messages and get // notified of events. @@ -24,9 +27,9 @@ // Allows handling incoming Mojo requests. virtual void RegisterMojoInterfaces( - AssociatedInterfaceRegistry* associated_interfaces) {} + blink::AssociatedInterfaceRegistry* associated_interfaces) {} virtual void UnregisterMojoInterfaces( - AssociatedInterfaceRegistry* associated_interfaces) {} + blink::AssociatedInterfaceRegistry* associated_interfaces) {} // Allows filtering of control messages. virtual bool OnControlMessageReceived(const IPC::Message& message);
diff --git a/content/public/renderer/renderer_ppapi_host.h b/content/public/renderer/renderer_ppapi_host.h index 068b82a..b376692d 100644 --- a/content/public/renderer/renderer_ppapi_host.h +++ b/content/public/renderer/renderer_ppapi_host.h
@@ -83,10 +83,6 @@ virtual blink::WebPluginContainer* GetContainerForInstance( PP_Instance instance) const = 0; - // Returns the PID of the child process containing the plugin. If running - // in-process, this returns base::kNullProcessId. - virtual base::ProcessId GetPluginPID() const = 0; - // Returns true if the given instance is considered to be currently // processing a user gesture or the plugin module has the "override user // gesture" flag set (in which case it can always do things normally
diff --git a/content/public/test/content_test_suite_base.cc b/content/public/test/content_test_suite_base.cc index 011b2d1..deb8892 100644 --- a/content/public/test/content_test_suite_base.cc +++ b/content/public/test/content_test_suite_base.cc
@@ -50,6 +50,10 @@ gin::V8Initializer::LoadV8Natives(); #endif +#if defined(USE_V8_CONTEXT_SNAPSHOT) + gin::V8Initializer::LoadV8ContextSnapshot(); +#endif + #if defined(OS_ANDROID) && !defined(USE_AURA) content::Compositor::Initialize(); #endif
diff --git a/content/public/test/navigation_simulator.cc b/content/public/test/navigation_simulator.cc index 22cfaf7..f5460ce 100644 --- a/content/public/test/navigation_simulator.cc +++ b/content/public/test/navigation_simulator.cc
@@ -78,11 +78,10 @@ RenderFrameHost* NavigationSimulator::NavigateAndCommitFromBrowser( WebContents* web_contents, const GURL& url) { - NavigationSimulator simulator(url, true /* browser_initiated */, - static_cast<WebContentsImpl*>(web_contents), - nullptr); - simulator.Commit(); - return simulator.GetFinalRenderFrameHost(); + auto simulator = + NavigationSimulator::CreateBrowserInitiated(url, web_contents); + simulator->Commit(); + return simulator->GetFinalRenderFrameHost(); } // static @@ -90,25 +89,40 @@ NavigationEntry* entry = web_contents->GetController().GetLastCommittedEntry(); CHECK(entry); - NavigationSimulator simulator(entry->GetURL(), true /* browser_initiated */, - static_cast<WebContentsImpl*>(web_contents), - nullptr); - simulator.SetReloadType(ReloadType::NORMAL); - simulator.Commit(); - return simulator.GetFinalRenderFrameHost(); + auto simulator = NavigationSimulator::CreateBrowserInitiated(entry->GetURL(), + web_contents); + simulator->SetReloadType(ReloadType::NORMAL); + simulator->Commit(); + return simulator->GetFinalRenderFrameHost(); +} + +// static +RenderFrameHost* NavigationSimulator::GoBack(WebContents* web_contents) { + return GoToOffset(web_contents, -1); +} + +// static +RenderFrameHost* NavigationSimulator::GoForward(WebContents* web_contents) { + return GoToOffset(web_contents, 1); +} + +// static +RenderFrameHost* NavigationSimulator::GoToOffset(WebContents* web_contents, + int offset) { + auto simulator = + NavigationSimulator::CreateHistoryNavigation(offset, web_contents); + simulator->Commit(); + return simulator->GetFinalRenderFrameHost(); } // static RenderFrameHost* NavigationSimulator::NavigateAndCommitFromDocument( const GURL& original_url, RenderFrameHost* render_frame_host) { - NavigationSimulator simulator( - original_url, false /* browser_initiated */, - static_cast<WebContentsImpl*>( - WebContents::FromRenderFrameHost(render_frame_host)), - static_cast<TestRenderFrameHost*>(render_frame_host)); - simulator.Commit(); - return simulator.GetFinalRenderFrameHost(); + auto simulator = NavigationSimulator::CreateRendererInitiated( + original_url, render_frame_host); + simulator->Commit(); + return simulator->GetFinalRenderFrameHost(); } // static @@ -116,14 +130,13 @@ WebContents* web_contents, const GURL& url, int net_error_code) { - NavigationSimulator simulator(url, true /* browser_initiated */, - static_cast<WebContentsImpl*>(web_contents), - nullptr); - simulator.Fail(net_error_code); + auto simulator = + NavigationSimulator::CreateBrowserInitiated(url, web_contents); + simulator->Fail(net_error_code); if (net_error_code == net::ERR_ABORTED) return nullptr; - simulator.CommitErrorPage(); - return simulator.GetFinalRenderFrameHost(); + simulator->CommitErrorPage(); + return simulator->GetFinalRenderFrameHost(); } // static @@ -132,15 +145,34 @@ NavigationEntry* entry = web_contents->GetController().GetLastCommittedEntry(); CHECK(entry); - NavigationSimulator simulator(entry->GetURL(), true /* browser_initiated */, - static_cast<WebContentsImpl*>(web_contents), - nullptr); - simulator.SetReloadType(ReloadType::NORMAL); - simulator.Fail(net_error_code); + auto simulator = NavigationSimulator::CreateBrowserInitiated(entry->GetURL(), + web_contents); + simulator->SetReloadType(ReloadType::NORMAL); + simulator->Fail(net_error_code); if (net_error_code == net::ERR_ABORTED) return nullptr; - simulator.CommitErrorPage(); - return simulator.GetFinalRenderFrameHost(); + simulator->CommitErrorPage(); + return simulator->GetFinalRenderFrameHost(); +} + +// static +RenderFrameHost* NavigationSimulator::GoBackAndFail(WebContents* web_contents, + int net_error_code) { + return GoToOffsetAndFail(web_contents, -1, net_error_code); +} + +// static +RenderFrameHost* NavigationSimulator::GoToOffsetAndFail( + WebContents* web_contents, + int offset, + int net_error_code) { + auto simulator = + NavigationSimulator::CreateHistoryNavigation(offset, web_contents); + simulator->Fail(net_error_code); + if (net_error_code == net::ERR_ABORTED) + return nullptr; + simulator->CommitErrorPage(); + return simulator->GetFinalRenderFrameHost(); } // static @@ -148,16 +180,13 @@ const GURL& original_url, int net_error_code, RenderFrameHost* render_frame_host) { - NavigationSimulator simulator( - original_url, false /* browser_initiated */, - static_cast<WebContentsImpl*>( - WebContents::FromRenderFrameHost(render_frame_host)), - static_cast<TestRenderFrameHost*>(render_frame_host)); - simulator.Fail(net_error_code); + auto simulator = NavigationSimulator::CreateRendererInitiated( + original_url, render_frame_host); + simulator->Fail(net_error_code); if (net_error_code == net::ERR_ABORTED) return nullptr; - simulator.CommitErrorPage(); - return simulator.GetFinalRenderFrameHost(); + simulator->CommitErrorPage(); + return simulator->GetFinalRenderFrameHost(); } // static @@ -171,6 +200,17 @@ // static std::unique_ptr<NavigationSimulator> +NavigationSimulator::CreateHistoryNavigation(int offset, + WebContents* web_contents) { + auto simulator = std::unique_ptr<NavigationSimulator>(new NavigationSimulator( + GURL(), true /* browser_initiated */, + static_cast<WebContentsImpl*>(web_contents), nullptr)); + simulator->SetSessionHistoryOffset(offset); + return simulator; +} + +// static +std::unique_ptr<NavigationSimulator> NavigationSimulator::CreateRendererInitiated( const GURL& original_url, RenderFrameHost* render_frame_host) { @@ -425,10 +465,7 @@ params.referrer = referrer_; params.transition = transition_; params.should_update_history = true; - params.did_create_new_entry = - !ui::PageTransitionCoreTypeIs(transition_, - ui::PAGE_TRANSITION_AUTO_SUBFRAME) && - reload_type_ == ReloadType::NONE; + params.did_create_new_entry = DidCreateNewEntry(); params.gesture = has_user_gesture_ ? NavigationGestureUser : NavigationGestureAuto; params.contents_mime_type = "text/html"; @@ -543,10 +580,7 @@ base::TimeTicks::Now())); FrameHostMsg_DidCommitProvisionalLoad_Params params; params.nav_entry_id = handle_->pending_nav_entry_id(); - params.did_create_new_entry = - !ui::PageTransitionCoreTypeIs(transition_, - ui::PAGE_TRANSITION_AUTO_SUBFRAME) && - reload_type_ == ReloadType::NONE; + params.did_create_new_entry = DidCreateNewEntry(); params.url = navigation_url_; params.referrer = referrer_; params.transition = transition_; @@ -624,6 +658,8 @@ << "The transition cannot be set after the navigation has started"; CHECK_EQ(ReloadType::NONE, reload_type_) << "The transition cannot be specified for reloads"; + CHECK_EQ(0, session_history_offset_) + << "The transition cannot be specified for back/forward navigations"; transition_ = transition; } @@ -638,6 +674,9 @@ "be set after the navigation has started"; CHECK(browser_initiated_) << "The reload_type parameter can only be set for " "browser-intiated navigations"; + CHECK_EQ(0, session_history_offset_) + << "The reload_type parameter cannot be set for " + "session history navigations"; reload_type_ = reload_type; if (reload_type_ != ReloadType::NONE) transition_ = ui::PAGE_TRANSITION_RELOAD; @@ -770,6 +809,8 @@ if (reload_type_ != ReloadType::NONE) { web_contents_->GetController().Reload(reload_type_, false /*check_for_repost */); + } else if (session_history_offset_) { + web_contents_->GetController().GoToOffset(session_history_offset_); } else { web_contents_->GetController().LoadURL(navigation_url_, referrer_, transition_, std::string()); @@ -997,4 +1038,23 @@ replacements); } +bool NavigationSimulator::DidCreateNewEntry() { + if (ui::PageTransitionCoreTypeIs(transition_, + ui::PAGE_TRANSITION_AUTO_SUBFRAME)) + return false; + if (reload_type_ != ReloadType::NONE) + return false; + if (session_history_offset_) + return false; + + return true; +} + +void NavigationSimulator::SetSessionHistoryOffset(int session_history_offset) { + CHECK(session_history_offset); + session_history_offset_ = session_history_offset; + transition_ = + ui::PageTransitionFromInt(transition_ | ui::PAGE_TRANSITION_FORWARD_BACK); +} + } // namespace content
diff --git a/content/public/test/navigation_simulator.h b/content/public/test/navigation_simulator.h index 5997dfa..2b52458 100644 --- a/content/public/test/navigation_simulator.h +++ b/content/public/test/navigation_simulator.h
@@ -31,7 +31,6 @@ // An interface for simulating a navigation in unit tests. Currently this only // supports renderer-initiated navigations. // Note: this should not be used in browser tests. -// TODO(clamy): support browser-initiated navigations. class NavigationSimulator : public WebContentsObserver { public: // Simulates a browser-initiated navigation to |url| started in @@ -45,6 +44,18 @@ // the navigation. static RenderFrameHost* Reload(WebContents* web_contents); + // Simulates a back navigation from start to commit. Returns the + // RenderFrameHost that committed the navigation. + static RenderFrameHost* GoBack(WebContents* web_contents); + + // Simulates a forward navigation from start to commit. Returns the + // RenderFrameHost that committed the navigation. + static RenderFrameHost* GoForward(WebContents* web_contents); + + // Simulates a navigation to the given offset of the web_contents navigation + // controller, from start to finish. + static RenderFrameHost* GoToOffset(WebContents* web_contents, int offset); + // Simulates a renderer-initiated navigation to |url| started in // |render_frame_host| from start to commit. Returns the RenderFramehost that // committed the navigation. @@ -66,6 +77,21 @@ static RenderFrameHost* ReloadAndFail(WebContents* web_contents, int net_error_code); + // Simulates a failed back navigation. Returns the RenderFrameHost that + // committed the error page for the navigation, or nullptr if the navigation + // error did not result in an error page. + static RenderFrameHost* GoBackAndFail(WebContents* web_contents, + int net_error_code); + + // TODO(clamy, ahemery): Add GoForwardAndFail() if it becomes needed. + + // Simulates a failed offset navigation. Returns the RenderFrameHost that + // committed the error page for the navigation, or nullptr if the navigation + // error did not result in an error page. + static RenderFrameHost* GoToOffsetAndFail(WebContents* web_contents, + int offset, + int net_error_code); + // Simulates a failed renderer-initiated navigation to |url| started in // |render_frame_host| from start to commit. Returns the RenderFramehost that // committed the error page for the navigation, or nullptr if the navigation @@ -86,6 +112,13 @@ const GURL& original_url, WebContents* contents); + // Creates a NavigationSimulator that will be used to simulate a history + // navigation to one of the |web_contents|'s navigation controller |offset|. + // E.g. offset -1 for back navigations and 1 for forward navigations. + static std::unique_ptr<NavigationSimulator> CreateHistoryNavigation( + int offset, + WebContents* web_contents); + // Creates a NavigationSimulator that will be used to simulate a // renderer-initiated navigation to |original_url| started by // |render_frame_host|. @@ -268,6 +301,14 @@ // PlzNavigate: only use on renderer-initiated navigations. bool CheckIfSameDocument(); + // Infers from internal parameters whether the navigation created a new + // entry. + bool DidCreateNewEntry(); + + // Set the navigation to be done towards the specified navigation controller + // offset. Typically -1 for back navigations or 1 for forward navigations. + void SetSessionHistoryOffset(int offset); + enum State { INITIALIZATION, STARTED, @@ -297,6 +338,7 @@ Referrer referrer_; ui::PageTransition transition_; ReloadType reload_type_ = ReloadType::NONE; + int session_history_offset_ = 0; bool has_user_gesture_ = true; // These are used to sanity check the content/public/ API calls emitted as
diff --git a/content/public/test/test_launcher.cc b/content/public/test/test_launcher.cc index 631ca213..9b3a480 100644 --- a/content/public/test/test_launcher.cc +++ b/content/public/test/test_launcher.cc
@@ -10,6 +10,7 @@ #include <memory> #include <set> #include <string> +#include <utility> #include <vector> #include "base/bind_helpers.h" @@ -255,6 +256,11 @@ return true; } +bool IsPreTestName(const std::string& test_name) { + return base::StartsWith(test_name, kPreTestPrefix, + base::CompareCase::SENSITIVE); +} + bool WrapperTestLauncherDelegate::ShouldRunTest( const std::string& test_case_name, const std::string& test_name) { @@ -266,8 +272,7 @@ return false; } - if (base::StartsWith(test_name, kPreTestPrefix, - base::CompareCase::SENSITIVE)) { + if (IsPreTestName(test_name)) { // We will actually run PRE_ tests, but to ensure they run on the same shard // as dependent tests, handle all these details internally. return false; @@ -295,8 +300,8 @@ size_t additional_tests_to_run_count = 0; // Compute dependencies of tests to be run. - for (size_t i = 0; i < test_names.size(); i++) { - std::string full_name(test_names[i]); + for (const std::string& test_name : test_names) { + std::string full_name(test_name); std::string pre_test_name(GetPreTestName(full_name)); while (base::ContainsKey(all_test_names_, pre_test_name)) { @@ -313,9 +318,8 @@ } } - for (size_t i = 0; i < test_names.size(); i++) { - std::string full_name(test_names[i]); - + for (const std::string& test_name : test_names) { + std::string full_name(test_name); // Make sure no PRE_ tests were requested explicitly. DCHECK_EQ(full_name, RemoveAnyPrePrefixes(full_name)); @@ -349,31 +353,25 @@ // In the face of PRE_ tests, we need to retry the entire chain of tests, // from the very first one. - for (size_t i = 0; i < test_names.size(); i++) { - std::string test_name(test_names[i]); - while (base::ContainsKey(reverse_dependent_test_map_, test_name)) { - test_name = reverse_dependent_test_map_[test_name]; - test_names_set.insert(test_name); + for (const std::string& test_name : test_names) { + std::string name(test_name); + while (base::ContainsKey(reverse_dependent_test_map_, name)) { + name = reverse_dependent_test_map_[name]; + test_names_set.insert(name); } } // Discard user data directories from any previous runs. Start with // fresh state. - for (UserDataDirMap::const_iterator i = user_data_dir_map_.begin(); - i != user_data_dir_map_.end(); - ++i) { + for (const auto& it : user_data_dir_map_) { // Delete temporary directories now to avoid using too much space in /tmp. - if (!base::DeleteFile(i->second, true)) { - LOG(WARNING) << "Failed to delete " << i->second.value(); + if (!base::DeleteFile(it.second, true)) { + LOG(WARNING) << "Failed to delete " << it.second.value(); } } user_data_dir_map_.clear(); - for (std::set<std::string>::const_iterator i = test_names_set.begin(); - i != test_names_set.end(); - ++i) { - std::string full_name(*i); - + for (const std::string& full_name : test_names_set) { // Make sure PRE_ tests and tests that depend on them share the same // data directory - based it on the test name without prefixes. std::string test_name_no_pre(RemoveAnyPrePrefixes(full_name)); @@ -384,12 +382,7 @@ user_data_dir_map_[test_name_no_pre] = temp_dir; } - size_t dot_pos = full_name.find('.'); - CHECK_NE(dot_pos, std::string::npos); - std::string test_case_name = full_name.substr(0, dot_pos); - std::string test_name = full_name.substr(dot_pos + 1); - std::string pre_test_name( - test_case_name + "." + kPreTestPrefix + test_name); + std::string pre_test_name = GetPreTestName(full_name); if (!base::ContainsKey(test_names_set, pre_test_name)) tests_to_run_now.push_back(full_name); } @@ -676,4 +669,9 @@ return g_params; } +bool IsPreTest() { + auto* test = testing::UnitTest::GetInstance(); + return IsPreTestName(test->current_test_info()->name()); +} + } // namespace content
diff --git a/content/public/test/test_launcher.h b/content/public/test/test_launcher.h index 9445b64..36627bf 100644 --- a/content/public/test/test_launcher.h +++ b/content/public/test/test_launcher.h
@@ -85,6 +85,10 @@ TestLauncherDelegate* GetCurrentTestLauncherDelegate(); ContentMainParams* GetContentMainParams(); +// Returns true if the currently running test has a prefix that indicates it +// should run before a test of the same name without the prefix. +bool IsPreTest(); + } // namespace content #endif // CONTENT_PUBLIC_TEST_TEST_LAUNCHER_H_
diff --git a/content/public/test/unittest_test_suite.cc b/content/public/test/unittest_test_suite.cc index 361236e..d00bde9 100644 --- a/content/public/test/unittest_test_suite.cc +++ b/content/public/test/unittest_test_suite.cc
@@ -4,6 +4,7 @@ #include "content/public/test/unittest_test_suite.h" +#include "base/command_line.h" #include "base/logging.h" #include "base/rand_util.h" #include "base/test/test_suite.h" @@ -12,7 +13,7 @@ #include "third_party/WebKit/public/web/WebKit.h" #if defined(USE_AURA) -#include "ui/aura/env.h" +#include "ui/aura/test/aura_test_suite_setup.h" #endif #if defined(USE_X11) @@ -27,8 +28,7 @@ XInitThreads(); #endif #if defined(USE_AURA) - DCHECK(!aura::Env::GetInstanceDontCreate()); - env_ = aura::Env::CreateInstance(); + aura_test_suite_setup_ = std::make_unique<aura::AuraTestSuiteSetup>(); #endif DCHECK(test_suite); blink_test_support_.reset(new TestBlinkWebUnitTestSupport); @@ -37,7 +37,7 @@ UnitTestTestSuite::~UnitTestTestSuite() { blink_test_support_.reset(); #if defined(USE_AURA) - env_.reset(); + aura_test_suite_setup_.reset(); #endif }
diff --git a/content/public/test/unittest_test_suite.h b/content/public/test/unittest_test_suite.h index 1b97eb9..c84dfe2 100644 --- a/content/public/test/unittest_test_suite.h +++ b/content/public/test/unittest_test_suite.h
@@ -12,7 +12,7 @@ #if defined(USE_AURA) namespace aura { -class Env; +class AuraTestSuiteSetup; } #endif @@ -41,7 +41,7 @@ std::unique_ptr<TestBlinkWebUnitTestSupport> blink_test_support_; #if defined(USE_AURA) - std::unique_ptr<aura::Env> env_; + std::unique_ptr<aura::AuraTestSuiteSetup> aura_test_suite_setup_; #endif DISALLOW_COPY_AND_ASSIGN(UnitTestTestSuite);
diff --git a/content/renderer/BUILD.gn b/content/renderer/BUILD.gn index fe801c0..38ddca8 100644 --- a/content/renderer/BUILD.gn +++ b/content/renderer/BUILD.gn
@@ -385,8 +385,6 @@ "push_messaging/push_provider.h", "quota_dispatcher.cc", "quota_dispatcher.h", - "quota_message_filter.cc", - "quota_message_filter.h", "render_frame_impl.cc", "render_frame_impl.h", "render_frame_proxy.cc", @@ -818,6 +816,8 @@ "media/webrtc/track_observer.cc", "media/webrtc/track_observer.h", "media/webrtc/two_keys_adapter_map.h", + "media/webrtc/video_codec_factory.cc", + "media/webrtc/video_codec_factory.h", "media/webrtc/webrtc_audio_sink.cc", "media/webrtc/webrtc_audio_sink.h", "media/webrtc/webrtc_media_stream_adapter.cc",
diff --git a/content/renderer/accessibility/blink_ax_tree_source.cc b/content/renderer/accessibility/blink_ax_tree_source.cc index 2f4de50..ba5ef66 100644 --- a/content/renderer/accessibility/blink_ax_tree_source.cc +++ b/content/renderer/accessibility/blink_ax_tree_source.cc
@@ -431,13 +431,16 @@ WebAXObject offset_container; WebFloatRect bounds_in_container; SkMatrix44 container_transform; + bool clips_children = false; src.GetRelativeBounds(offset_container, bounds_in_container, - container_transform); + container_transform, &clips_children); dst->location = bounds_in_container; if (!container_transform.isIdentity()) dst->transform = base::WrapUnique(new gfx::Transform(container_transform)); if (!offset_container.IsDetached()) dst->offset_container_id = offset_container.AxID(); + if (clips_children) + dst->AddBoolAttribute(ui::AX_ATTR_CLIPS_CHILDREN, true); AXContentNodeDataSparseAttributeAdapter sparse_attribute_adapter(dst); src.GetSparseAXAttributes(sparse_attribute_adapter);
diff --git a/content/renderer/input/main_thread_event_queue.cc b/content/renderer/input/main_thread_event_queue.cc index 4897af6a..a9efa0c 100644 --- a/content/renderer/input/main_thread_event_queue.cc +++ b/content/renderer/input/main_thread_event_queue.cc
@@ -239,6 +239,7 @@ base::FeatureList::IsEnabled( features::kMainThreadBusyScrollIntervention)), needs_low_latency_(false), + allow_raf_aligned_input_(allow_raf_aligned_input), main_task_runner_(main_task_runner), renderer_scheduler_(renderer_scheduler), use_raf_fallback_timer_(true) { @@ -521,7 +522,8 @@ case blink::WebInputEvent::kMouseMove: case blink::WebInputEvent::kMouseWheel: case blink::WebInputEvent::kTouchMove: - return !needs_low_latency_ && !needs_low_latency_until_pointer_up_; + return allow_raf_aligned_input_ && !needs_low_latency_ && + !needs_low_latency_until_pointer_up_; default: return false; }
diff --git a/content/renderer/input/main_thread_event_queue.h b/content/renderer/input/main_thread_event_queue.h index 7f012f7..509609b 100644 --- a/content/renderer/input/main_thread_event_queue.h +++ b/content/renderer/input/main_thread_event_queue.h
@@ -132,6 +132,7 @@ bool enable_non_blocking_due_to_main_thread_responsiveness_flag_; base::TimeDelta main_thread_responsiveness_threshold_; bool needs_low_latency_; + bool allow_raf_aligned_input_; bool needs_low_latency_until_pointer_up_ = false; // Contains data to be shared between main thread and compositor thread.
diff --git a/content/renderer/input/widget_input_handler_manager.cc b/content/renderer/input/widget_input_handler_manager.cc index abea4623..57976b42 100644 --- a/content/renderer/input/widget_input_handler_manager.cc +++ b/content/renderer/input/widget_input_handler_manager.cc
@@ -150,17 +150,23 @@ const gfx::Vector2dF& current_fling_velocity, const gfx::PointF& causal_event_viewport_point, const cc::ScrollBoundaryBehavior& scroll_boundary_behavior) { + mojom::WidgetInputHandlerHost* host = GetWidgetInputHandlerHost(); + if (!host) + return; ui::DidOverscrollParams params; params.accumulated_overscroll = accumulated_overscroll; params.latest_overscroll_delta = latest_overscroll_delta; params.current_fling_velocity = current_fling_velocity; params.causal_event_viewport_point = causal_event_viewport_point; params.scroll_boundary_behavior = scroll_boundary_behavior; - GetWidgetInputHandlerHost()->DidOverscroll(params); + host->DidOverscroll(params); } void WidgetInputHandlerManager::DidStopFlinging() { - GetWidgetInputHandlerHost()->DidStopFlinging(); + mojom::WidgetInputHandlerHost* host = GetWidgetInputHandlerHost(); + if (!host) + return; + host->DidStopFlinging(); } void WidgetInputHandlerManager::DidAnimateForInput() { @@ -189,17 +195,22 @@ cc::TouchAction touch_action, uint32_t unique_touch_event_id, ui::InputHandlerProxy::EventDisposition event_disposition) { + mojom::WidgetInputHandlerHost* host = GetWidgetInputHandlerHost(); + if (!host) + return; InputEventAckState ack_state = InputEventDispositionToAck(event_disposition); - GetWidgetInputHandlerHost()->SetWhiteListedTouchAction( - touch_action, unique_touch_event_id, ack_state); + host->SetWhiteListedTouchAction(touch_action, unique_touch_event_id, + ack_state); } void WidgetInputHandlerManager::ProcessTouchAction( cc::TouchAction touch_action) { // Cancel the touch timeout on TouchActionNone since it is a good hint // that author doesn't want scrolling. - if (touch_action == cc::TouchAction::kTouchActionNone) - GetWidgetInputHandlerHost()->CancelTouchTimeout(); + if (touch_action == cc::TouchAction::kTouchActionNone) { + if (mojom::WidgetInputHandlerHost* host = GetWidgetInputHandlerHost()) + host->CancelTouchTimeout(); + } } mojom::WidgetInputHandlerHost* @@ -279,8 +290,11 @@ mojom::WidgetInputHandlerAssociatedRequest request) { if (!request.is_pending()) return; + // Don't pass the |input_event_queue_| on if we don't have a + // |compositor_task_runner_| as events might get out of order. WidgetInputHandlerImpl* handler = new WidgetInputHandlerImpl( - this, main_thread_task_runner_, input_event_queue_, render_widget_); + this, main_thread_task_runner_, + compositor_task_runner_ ? input_event_queue_ : nullptr, render_widget_); handler->SetAssociatedBinding(std::move(request)); } @@ -288,8 +302,11 @@ mojom::WidgetInputHandlerRequest request) { if (!request.is_pending()) return; + // Don't pass the |input_event_queue_| on if we don't have a + // |compositor_task_runner_| as events might get out of order. WidgetInputHandlerImpl* handler = new WidgetInputHandlerImpl( - this, main_thread_task_runner_, input_event_queue_, render_widget_); + this, main_thread_task_runner_, + compositor_task_runner_ ? input_event_queue_ : nullptr, render_widget_); handler->SetBinding(std::move(request)); }
diff --git a/content/renderer/loader/resource_dispatcher.cc b/content/renderer/loader/resource_dispatcher.cc index cf2df1c3..0fc8b684 100644 --- a/content/renderer/loader/resource_dispatcher.cc +++ b/content/renderer/loader/resource_dispatcher.cc
@@ -188,8 +188,7 @@ request_info->site_isolation_metadata = SiteIsolationStatsGatherer::OnReceivedResponse( request_info->frame_origin, request_info->response_url, - request_info->resource_type, request_info->origin_pid, - renderer_response_info); + request_info->resource_type, renderer_response_info); request_info->peer->OnReceivedResponse(renderer_response_info); } @@ -208,8 +207,7 @@ void ResourceDispatcher::OnSetDataBuffer(int request_id, base::SharedMemoryHandle shm_handle, - int shm_size, - base::ProcessId renderer_pid) { + int shm_size) { TRACE_EVENT0("loader", "ResourceDispatcher::OnSetDataBuffer"); PendingRequestInfo* request_info = GetPendingRequestInfo(request_id); if (!request_info) @@ -226,10 +224,6 @@ bool ok = request_info->buffer->Map(shm_size); if (!ok) { - // Added to help debug crbug/160401. - base::ProcessId renderer_pid_copy = renderer_pid; - base::debug::Alias(&renderer_pid_copy); - base::SharedMemoryHandle shm_handle_copy = shm_handle; base::debug::Alias(&shm_handle_copy); @@ -484,7 +478,6 @@ std::unique_ptr<RequestPeer> peer, ResourceType resource_type, int render_frame_id, - int origin_pid, const url::Origin& frame_origin, const GURL& request_url, const std::string& method, @@ -493,7 +486,6 @@ : peer(std::move(peer)), resource_type(resource_type), render_frame_id(render_frame_id), - origin_pid(origin_pid), url(request_url), frame_origin(frame_origin), response_url(request_url), @@ -638,8 +630,8 @@ int request_id = MakeRequestID(); pending_requests_[request_id] = std::make_unique<PendingRequestInfo>( std::move(peer), request->resource_type, request->render_frame_id, - request->origin_pid, frame_origin, request->url, request->method, - request->referrer, request->download_to_file); + frame_origin, request->url, request->method, request->referrer, + request->download_to_file); if (resource_scheduling_filter_.get() && loading_task_runner) { resource_scheduling_filter_->SetRequestIdTaskRunner(request_id,
diff --git a/content/renderer/loader/resource_dispatcher.h b/content/renderer/loader/resource_dispatcher.h index dc90cb7..0313783 100644 --- a/content/renderer/loader/resource_dispatcher.h +++ b/content/renderer/loader/resource_dispatcher.h
@@ -181,7 +181,6 @@ PendingRequestInfo(std::unique_ptr<RequestPeer> peer, ResourceType resource_type, int render_frame_id, - int origin_pid, const url::Origin& frame_origin, const GURL& request_url, const std::string& method, @@ -193,10 +192,6 @@ std::unique_ptr<RequestPeer> peer; ResourceType resource_type; int render_frame_id; - // The PID of the original process which issued this request. This gets - // non-zero only for a request proxied by another renderer, particularly - // requests from plugins. - int origin_pid; MessageQueue deferred_message_queue; bool is_deferred = false; // Original requested url. @@ -241,8 +236,7 @@ const ResourceResponseHead& response_head); void OnSetDataBuffer(int request_id, base::SharedMemoryHandle shm_handle, - int shm_size, - base::ProcessId renderer_pid); + int shm_size); void OnReceivedData(int request_id, int data_offset, int data_length,
diff --git a/content/renderer/loader/resource_dispatcher_unittest.cc b/content/renderer/loader/resource_dispatcher_unittest.cc index ec11f4d..1f48a73d 100644 --- a/content/renderer/loader/resource_dispatcher_unittest.cc +++ b/content/renderer/loader/resource_dispatcher_unittest.cc
@@ -173,7 +173,7 @@ shared_memory->handle().Duplicate(); EXPECT_TRUE(duplicate_handle.IsValid()); EXPECT_TRUE(dispatcher_->OnMessageReceived(ResourceMsg_SetDataBuffer( - request_id, duplicate_handle, shared_memory->requested_size(), 0))); + request_id, duplicate_handle, shared_memory->requested_size()))); } void NotifyDataReceived(int request_id, const std::string& data) {
diff --git a/content/renderer/loader/site_isolation_stats_gatherer.cc b/content/renderer/loader/site_isolation_stats_gatherer.cc index a2f27180..49fce4e 100644 --- a/content/renderer/loader/site_isolation_stats_gatherer.cc +++ b/content/renderer/loader/site_isolation_stats_gatherer.cc
@@ -101,19 +101,10 @@ const url::Origin& frame_origin, const GURL& response_url, ResourceType resource_type, - int origin_pid, const ResourceResponseInfo& info) { if (!g_stats_gathering_enabled) return nullptr; - // if |origin_pid| is non-zero, it means that this response is for a plugin - // spawned from this renderer process. We exclude responses for plugins for - // now, but eventually, we're going to make plugin processes directly talk to - // the browser process so that we don't apply cross-site document blocking to - // them. - if (origin_pid) - return nullptr; - UMA_HISTOGRAM_COUNTS("SiteIsolation.AllResponses", 1); // See if this is for navigation. If it is, don't block it, under the
diff --git a/content/renderer/loader/site_isolation_stats_gatherer.h b/content/renderer/loader/site_isolation_stats_gatherer.h index 06a4cf9..5ddf914 100644 --- a/content/renderer/loader/site_isolation_stats_gatherer.h +++ b/content/renderer/loader/site_isolation_stats_gatherer.h
@@ -73,7 +73,6 @@ const url::Origin& frame_origin, const GURL& response_url, ResourceType resource_type, - int origin_pid, const ResourceResponseInfo& info); // Examines the first chunk of network data in case response_url is registered
diff --git a/content/renderer/loader/web_url_loader_impl.cc b/content/renderer/loader/web_url_loader_impl.cc index 27b6dcae..9c4cc86 100644 --- a/content/renderer/loader/web_url_loader_impl.cc +++ b/content/renderer/loader/web_url_loader_impl.cc
@@ -612,10 +612,10 @@ resource_request->headers = GetWebURLRequestHeaders(request); resource_request->load_flags = GetLoadFlagsForWebURLRequest(request); - // origin_pid only needs to be non-zero if the request originates outside - // the render process, so we can use requestorProcessID even for requests - // from in-process plugins. - resource_request->origin_pid = request.RequestorProcessID(); + // |plugin_child_id| only needs to be non-zero if the request originates + // outside the render process, so we can use requestorProcessID even + // for requests from in-process plugins. + resource_request->plugin_child_id = request.GetPluginChildID(); resource_request->resource_type = WebURLRequestToResourceType(request); resource_request->priority = ConvertWebKitPriorityToNetPriority(request.GetPriority()); @@ -1124,7 +1124,6 @@ blink::FilePathToWebString(info.download_file_path)); response->SetWasFetchedViaSPDY(info.was_fetched_via_spdy); response->SetWasFetchedViaServiceWorker(info.was_fetched_via_service_worker); - response->SetWasFetchedViaForeignFetch(info.was_fetched_via_foreign_fetch); response->SetWasFallbackRequiredByServiceWorker( info.was_fallback_required_by_service_worker); response->SetResponseTypeViaServiceWorker(
diff --git a/content/renderer/loader/web_url_request_util.cc b/content/renderer/loader/web_url_request_util.cc index 9337c75..d2ce71c 100644 --- a/content/renderer/loader/web_url_request_util.cc +++ b/content/renderer/loader/web_url_request_util.cc
@@ -16,14 +16,15 @@ #include "content/public/common/content_features.h" #include "content/public/common/service_names.mojom.h" #include "content/renderer/loader/request_extra_data.h" +#include "mojo/public/cpp/bindings/strong_binding.h" #include "net/base/load_flags.h" #include "net/base/net_errors.h" #include "net/http/http_util.h" +#include "services/network/public/interfaces/data_pipe_getter.mojom.h" #include "services/service_manager/public/cpp/connector.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "third_party/WebKit/common/blob/blob.mojom.h" #include "third_party/WebKit/common/blob/blob_registry.mojom.h" -#include "third_party/WebKit/common/blob/size_getter.mojom.h" #include "third_party/WebKit/public/platform/FilePathConversion.h" #include "third_party/WebKit/public/platform/Platform.h" #include "third_party/WebKit/public/platform/WebData.h" @@ -104,77 +105,80 @@ std::string buffer_; }; -// A helper class which allows a holder of a data pipe for a blob to know how -// big the blob is. It will stay alive until either the caller gets the length -// or the size getter pipe is torn down. -class BlobSizeGetter : public blink::mojom::BlobReaderClient, - public blink::mojom::SizeGetter { +// Vends data pipes to read a Blob. It stays alive by StrongBinding to the Mojo +// request. +class DataPipeGetter : public network::mojom::DataPipeGetter { public: - BlobSizeGetter( - blink::mojom::BlobReaderClientRequest blob_reader_client_request, - blink::mojom::SizeGetterRequest size_getter_request) - : blob_reader_client_binding_(this), size_getter_binding_(this) { + DataPipeGetter(blink::mojom::BlobPtr blob, + network::mojom::DataPipeGetterRequest request) { // If a sync XHR is doing the upload, then the main thread will be blocked. - // So we must bind these interfaces on a background thread, otherwise the - // methods below will never be called and the processes will hang. + // So we must bind on a background thread, otherwise the methods below will + // never be called and the process will hang. scoped_refptr<base::SingleThreadTaskRunner> task_runner = base::CreateSingleThreadTaskRunnerWithTraits( {base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); task_runner->PostTask( FROM_HERE, - base::BindOnce(&BlobSizeGetter::BindInternal, base::Unretained(this), - std::move(blob_reader_client_request), - std::move(size_getter_request))); + base::BindOnce(&DataPipeGetter::BindInternal, base::Unretained(this), + blob.PassInterface(), std::move(request))); + } + ~DataPipeGetter() override = default; + + private: + class BlobReaderClient : public blink::mojom::BlobReaderClient { + public: + explicit BlobReaderClient(ReadCallback callback) + : callback_(std::move(callback)) { + DCHECK(!callback_.is_null()); + } + ~BlobReaderClient() override = default; + + // blink::mojom::BlobReaderClient implementation: + void OnCalculatedSize(uint64_t total_size, + uint64_t expected_content_size) override { + // Check if null since it's conceivable OnComplete() was already called + // with error. + if (!callback_.is_null()) + std::move(callback_).Run(net::OK, total_size); + } + void OnComplete(int32_t status, uint64_t data_length) override { + // Check if null since OnCalculatedSize() may have already been called + // and an error occurred later. + if (!callback_.is_null() && status != net::OK) { + // On error, signal failure immediately. On success, OnCalculatedSize() + // is guaranteed to be called, and the result will be signaled from + // there. + std::move(callback_).Run(status, 0); + } + } + + private: + ReadCallback callback_; + + DISALLOW_COPY_AND_ASSIGN(BlobReaderClient); + }; + + void BindInternal(blink::mojom::BlobPtrInfo blob, + network::mojom::DataPipeGetterRequest request) { + mojo::MakeStrongBinding(base::WrapUnique(this), std::move(request)); + blob_.Bind(std::move(blob)); + } + + // network::mojom::DataPipeGetter implementation: + void Read(mojo::ScopedDataPipeProducerHandle handle, + ReadCallback callback) override { + blink::mojom::BlobReaderClientPtr blob_reader_client_ptr; + mojo::MakeStrongBinding( + std::make_unique<BlobReaderClient>(std::move(callback)), + mojo::MakeRequest(&blob_reader_client_ptr)); + blob_->ReadAll(std::move(handle), std::move(blob_reader_client_ptr)); } private: - ~BlobSizeGetter() override {} + blink::mojom::BlobPtr blob_; - void BindInternal( - blink::mojom::BlobReaderClientRequest blob_reader_client_request, - blink::mojom::SizeGetterRequest size_getter_request) { - blob_reader_client_binding_.Bind(std::move(blob_reader_client_request)); - size_getter_binding_.Bind(std::move(size_getter_request)); - size_getter_binding_.set_connection_error_handler(base::BindOnce( - &BlobSizeGetter::OnSizeGetterConnectionError, base::Unretained(this))); - } - - // blink::mojom::BlobReaderClient implementation: - void OnCalculatedSize(uint64_t total_size, - uint64_t expected_content_size) override { - size_ = total_size; - calculated_size_ = true; - if (!callback_.is_null()) { - std::move(callback_).Run(total_size); - delete this; - } else if (!size_getter_binding_.is_bound()) { - delete this; - } - } - - void OnComplete(int32_t status, uint64_t data_length) override {} - - // blink::mojom::SizeGetter implementation: - void GetSize(GetSizeCallback callback) override { - if (calculated_size_) { - std::move(callback).Run(size_); - delete this; - } else { - callback_ = std::move(callback); - } - } - - void OnSizeGetterConnectionError() { - if (calculated_size_) - delete this; - } - - bool calculated_size_ = false; - uint64_t size_ = 0; - mojo::Binding<blink::mojom::BlobReaderClient> blob_reader_client_binding_; - mojo::Binding<blink::mojom::SizeGetter> size_getter_binding_; - GetSizeCallback callback_; + DISALLOW_COPY_AND_ASSIGN(DataPipeGetter); }; } // namespace @@ -474,18 +478,12 @@ blob_registry->GetBlobFromUUID(MakeRequest(&blob_ptr), element.blob_uuid.Utf8()); - blink::mojom::BlobReaderClientPtr blob_reader_client_ptr; - blink::mojom::SizeGetterPtr size_getter_ptr; + network::mojom::DataPipeGetterPtr data_pipe_getter_ptr; // Object deletes itself. - new BlobSizeGetter(MakeRequest(&blob_reader_client_ptr), - MakeRequest(&size_getter_ptr)); + new DataPipeGetter(std::move(blob_ptr), + MakeRequest(&data_pipe_getter_ptr)); - mojo::DataPipe data_pipe; - request_body->AppendDataPipe(std::move(data_pipe.consumer_handle), - std::move(size_getter_ptr)); - - blob_ptr->ReadAll(std::move(data_pipe.producer_handle), - std::move(blob_reader_client_ptr)); + request_body->AppendDataPipe(std::move(data_pipe_getter_ptr)); } else { request_body->AppendBlob(element.blob_uuid.Utf8()); } @@ -623,8 +621,6 @@ STATIC_ASSERT_ENUM(ServiceWorkerMode::NONE, WebURLRequest::ServiceWorkerMode::kNone); -STATIC_ASSERT_ENUM(ServiceWorkerMode::FOREIGN, - WebURLRequest::ServiceWorkerMode::kForeign); STATIC_ASSERT_ENUM(ServiceWorkerMode::ALL, WebURLRequest::ServiceWorkerMode::kAll);
diff --git a/content/renderer/manifest/manifest_manager.cc b/content/renderer/manifest/manifest_manager.cc index ef1345e..e473be9 100644 --- a/content/renderer/manifest/manifest_manager.cc +++ b/content/renderer/manifest/manifest_manager.cc
@@ -8,11 +8,11 @@ #include "base/bind.h" #include "base/strings/nullable_string16.h" -#include "content/public/common/associated_interface_provider.h" #include "content/public/renderer/render_frame.h" #include "content/renderer/fetchers/manifest_fetcher.h" #include "content/renderer/manifest/manifest_parser.h" #include "content/renderer/manifest/manifest_uma_util.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" #include "third_party/WebKit/public/platform/WebURLResponse.h" #include "third_party/WebKit/public/web/WebConsoleMessage.h" #include "third_party/WebKit/public/web/WebDocument.h"
diff --git a/content/renderer/media/gpu/rtc_video_decoder.cc b/content/renderer/media/gpu/rtc_video_decoder.cc index d81d406..311227ae 100644 --- a/content/renderer/media/gpu/rtc_video_decoder.cc +++ b/content/renderer/media/gpu/rtc_video_decoder.cc
@@ -133,12 +133,6 @@ return decoder; } -// static -void RTCVideoDecoder::Destroy(webrtc::VideoDecoder* decoder, - media::GpuVideoAcceleratorFactories* factories) { - factories->GetTaskRunner()->DeleteSoon(FROM_HERE, decoder); -} - int32_t RTCVideoDecoder::InitDecode(const webrtc::VideoCodec* codecSettings, int32_t /*numberOfCores*/) { DVLOG(2) << "InitDecode"; @@ -277,6 +271,10 @@ return WEBRTC_VIDEO_CODEC_OK; } +const char* RTCVideoDecoder::ImplementationName() const { + return "RTCVideoDecoder"; +} + int32_t RTCVideoDecoder::Release() { DVLOG(2) << "Release"; // Do not destroy VDA because WebRTC can call InitDecode and start decoding
diff --git a/content/renderer/media/gpu/rtc_video_decoder.h b/content/renderer/media/gpu/rtc_video_decoder.h index 25a7eba2..23afb14 100644 --- a/content/renderer/media/gpu/rtc_video_decoder.h +++ b/content/renderer/media/gpu/rtc_video_decoder.h
@@ -85,6 +85,8 @@ // this runs. int32_t Release() override; + const char* ImplementationName() const override; + // VideoDecodeAccelerator::Client implementation. void ProvidePictureBuffers(uint32_t count, media::VideoPixelFormat format,
diff --git a/content/renderer/media/gpu/rtc_video_decoder_factory.cc b/content/renderer/media/gpu/rtc_video_decoder_factory.cc index 8df7c448..f1f0b7a 100644 --- a/content/renderer/media/gpu/rtc_video_decoder_factory.cc +++ b/content/renderer/media/gpu/rtc_video_decoder_factory.cc
@@ -6,31 +6,89 @@ #include <memory> +#include "base/memory/ptr_util.h" #include "content/renderer/media/gpu/rtc_video_decoder.h" #include "media/video/gpu_video_accelerator_factories.h" +#include "third_party/webrtc/api/video_codecs/sdp_video_format.h" namespace content { +namespace { + +// This extra indirection is needed so that we can delete the decoder on the +// correct thread. +class ScopedVideoDecoder : public webrtc::VideoDecoder { + public: + ScopedVideoDecoder( + const scoped_refptr<base::SingleThreadTaskRunner>& task_runner, + std::unique_ptr<webrtc::VideoDecoder> decoder) + : task_runner_(task_runner), decoder_(std::move(decoder)) {} + + int32_t InitDecode(const webrtc::VideoCodec* codec_settings, + int32_t number_of_cores) override { + return decoder_->InitDecode(codec_settings, number_of_cores); + } + int32_t RegisterDecodeCompleteCallback( + webrtc::DecodedImageCallback* callback) override { + return decoder_->RegisterDecodeCompleteCallback(callback); + } + int32_t Release() override { return decoder_->Release(); } + int32_t Decode(const webrtc::EncodedImage& input_image, + bool missing_frames, + const webrtc::RTPFragmentationHeader* fragmentation, + const webrtc::CodecSpecificInfo* codec_specific_info, + int64_t render_time_ms) override { + return decoder_->Decode(input_image, missing_frames, fragmentation, + codec_specific_info, render_time_ms); + } + bool PrefersLateDecoding() const override { + return decoder_->PrefersLateDecoding(); + } + const char* ImplementationName() const override { + return decoder_->ImplementationName(); + } + + // Runs on Chrome_libJingle_WorkerThread. The child thread is blocked while + // this runs. + ~ScopedVideoDecoder() override { + task_runner_->DeleteSoon(FROM_HERE, decoder_.release()); + } + + private: + scoped_refptr<base::SingleThreadTaskRunner> task_runner_; + std::unique_ptr<webrtc::VideoDecoder> decoder_; +}; + +} // namespace + RTCVideoDecoderFactory::RTCVideoDecoderFactory( media::GpuVideoAcceleratorFactories* gpu_factories) : gpu_factories_(gpu_factories) { DVLOG(2) << __func__; } +std::vector<webrtc::SdpVideoFormat> +RTCVideoDecoderFactory::GetSupportedFormats() const { + // TODO(magjed): Implement this based on + // gpu_factories_->GetVideoDecodeAcceleratorSupportedProfiles(). This function + // is currently unused by WebRTC. + return std::vector<webrtc::SdpVideoFormat>(); +} + RTCVideoDecoderFactory::~RTCVideoDecoderFactory() { DVLOG(2) << __func__; } -webrtc::VideoDecoder* RTCVideoDecoderFactory::CreateVideoDecoder( - webrtc::VideoCodecType type) { +std::unique_ptr<webrtc::VideoDecoder> +RTCVideoDecoderFactory::CreateVideoDecoder( + const webrtc::SdpVideoFormat& format) { DVLOG(2) << __func__; - return RTCVideoDecoder::Create(type, gpu_factories_).release(); -} - -void RTCVideoDecoderFactory::DestroyVideoDecoder( - webrtc::VideoDecoder* decoder) { - DVLOG(2) << __func__; - RTCVideoDecoder::Destroy(decoder, gpu_factories_); + std::unique_ptr<webrtc::VideoDecoder> decoder = RTCVideoDecoder::Create( + webrtc::PayloadStringToCodecType(format.name), gpu_factories_); + // Make sure the decoder is destructed on the correct thread. + return decoder ? base::MakeUnique<ScopedVideoDecoder>( + gpu_factories_->GetTaskRunner(), std::move(decoder)) + : nullptr; } } // namespace content
diff --git a/content/renderer/media/gpu/rtc_video_decoder_factory.h b/content/renderer/media/gpu/rtc_video_decoder_factory.h index 7a4e45b..e9e0eea 100644 --- a/content/renderer/media/gpu/rtc_video_decoder_factory.h +++ b/content/renderer/media/gpu/rtc_video_decoder_factory.h
@@ -8,7 +8,7 @@ #include "base/macros.h" #include "base/threading/thread.h" #include "content/common/content_export.h" -#include "third_party/webrtc/media/engine/webrtcvideodecoderfactory.h" +#include "third_party/webrtc/api/video_codecs/video_decoder_factory.h" #include "third_party/webrtc/modules/video_coding/include/video_codec_interface.h" namespace webrtc { @@ -23,7 +23,7 @@ // TODO(wuchengli): add unittest. class CONTENT_EXPORT RTCVideoDecoderFactory - : public cricket::WebRtcVideoDecoderFactory { + : public webrtc::VideoDecoderFactory { public: explicit RTCVideoDecoderFactory( media::GpuVideoAcceleratorFactories* gpu_factories); @@ -31,12 +31,10 @@ // Runs on Chrome_libJingle_WorkerThread. The child thread is blocked while // this runs. - webrtc::VideoDecoder* CreateVideoDecoder( - webrtc::VideoCodecType type) override; + std::unique_ptr<webrtc::VideoDecoder> CreateVideoDecoder( + const webrtc::SdpVideoFormat& format) override; - // Runs on Chrome_libJingle_WorkerThread. The child thread is blocked while - // this runs. - void DestroyVideoDecoder(webrtc::VideoDecoder* decoder) override; + std::vector<webrtc::SdpVideoFormat> GetSupportedFormats() const override; private: media::GpuVideoAcceleratorFactories* gpu_factories_;
diff --git a/content/renderer/media/gpu/rtc_video_encoder.cc b/content/renderer/media/gpu/rtc_video_encoder.cc index 8a2a2d3..f7e8366 100644 --- a/content/renderer/media/gpu/rtc_video_encoder.cc +++ b/content/renderer/media/gpu/rtc_video_encoder.cc
@@ -941,4 +941,8 @@ return true; } +const char* RTCVideoEncoder::ImplementationName() const { + return "RTCVideoEncoder"; +} + } // namespace content
diff --git a/content/renderer/media/gpu/rtc_video_encoder.h b/content/renderer/media/gpu/rtc_video_encoder.h index 9612e025..155a3317 100644 --- a/content/renderer/media/gpu/rtc_video_encoder.h +++ b/content/renderer/media/gpu/rtc_video_encoder.h
@@ -59,6 +59,7 @@ int32_t SetChannelParameters(uint32_t packet_loss, int64_t rtt) override; int32_t SetRates(uint32_t new_bit_rate, uint32_t frame_rate) override; bool SupportsNativeHandle() const override; + const char* ImplementationName() const override; private: class Impl;
diff --git a/content/renderer/media/gpu/rtc_video_encoder_factory.cc b/content/renderer/media/gpu/rtc_video_encoder_factory.cc index 152f7104..fc61ac2 100644 --- a/content/renderer/media/gpu/rtc_video_encoder_factory.cc +++ b/content/renderer/media/gpu/rtc_video_encoder_factory.cc
@@ -11,23 +11,24 @@ #include "content/renderer/media/gpu/rtc_video_encoder.h" #include "media/gpu/ipc/client/gpu_video_encode_accelerator_host.h" #include "media/video/gpu_video_accelerator_factories.h" +#include "third_party/webrtc/api/video_codecs/sdp_video_format.h" #include "third_party/webrtc/common_video/h264/profile_level_id.h" +#include "third_party/webrtc/media/base/codec.h" namespace content { namespace { // Translate from media::VideoEncodeAccelerator::SupportedProfile to -// cricket::WebRtcVideoEncoderFactory::VideoCodec, or return nothing if the -// profile isn't supported. -base::Optional<cricket::VideoCodec> VEAToWebRTCCodec( +// webrtc::SdpVideoFormat, or return nothing if the profile isn't supported. +base::Optional<webrtc::SdpVideoFormat> VEAToWebRTCFormat( const media::VideoEncodeAccelerator::SupportedProfile& profile) { DCHECK_EQ(profile.max_framerate_denominator, 1U); if (profile.profile >= media::VP8PROFILE_MIN && profile.profile <= media::VP8PROFILE_MAX) { if (base::FeatureList::IsEnabled(features::kWebRtcHWVP8Encoding)) { - return base::Optional<cricket::VideoCodec>(cricket::VideoCodec("VP8")); + return webrtc::SdpVideoFormat("VP8"); } } else if (profile.profile >= media::H264PROFILE_MIN && profile.profile <= media::H264PROFILE_MAX) { @@ -54,7 +55,7 @@ break; default: // Unsupported H264 profile in WebRTC. - return base::Optional<cricket::VideoCodec>(); + return base::nullopt; } const int width = profile.max_resolution.width(); @@ -67,15 +68,22 @@ const webrtc::H264::ProfileLevelId profile_level_id( h264_profile, h264_level.value_or(webrtc::H264::kLevel1)); - cricket::VideoCodec codec("H264"); - codec.SetParam(cricket::kH264FmtpProfileLevelId, - *webrtc::H264::ProfileLevelIdToString(profile_level_id)); - codec.SetParam(cricket::kH264FmtpLevelAsymmetryAllowed, "1"); - codec.SetParam(cricket::kH264FmtpPacketizationMode, "1"); - return base::Optional<cricket::VideoCodec>(codec); + webrtc::SdpVideoFormat format("H264"); + format.parameters = { + {cricket::kH264FmtpProfileLevelId, + *webrtc::H264::ProfileLevelIdToString(profile_level_id)}, + {cricket::kH264FmtpLevelAsymmetryAllowed, "1"}, + {cricket::kH264FmtpPacketizationMode, "1"}}; + return format; } } - return base::Optional<cricket::VideoCodec>(); + return base::nullopt; +} + +bool IsSameFormat(const webrtc::SdpVideoFormat& format1, + const webrtc::SdpVideoFormat& format2) { + return cricket::IsSameCodec(format1.name, format2.parameters, format2.name, + format2.parameters); } } // anonymous namespace @@ -86,47 +94,45 @@ const media::VideoEncodeAccelerator::SupportedProfiles& profiles = gpu_factories_->GetVideoEncodeAcceleratorSupportedProfiles(); for (const auto& profile : profiles) { - base::Optional<cricket::VideoCodec> codec = VEAToWebRTCCodec(profile); - if (codec) { - supported_codecs_.push_back(std::move(*codec)); + base::Optional<webrtc::SdpVideoFormat> format = VEAToWebRTCFormat(profile); + if (format) { + supported_formats_.push_back(std::move(*format)); profiles_.push_back(profile.profile); } } // There should be a 1:1 mapping between media::VideoCodecProfile and - // cricket::VideoCodec. - CHECK_EQ(profiles_.size(), supported_codecs_.size()); + // webrtc::SdpVideoFormat. + CHECK_EQ(profiles_.size(), supported_formats_.size()); } RTCVideoEncoderFactory::~RTCVideoEncoderFactory() {} -webrtc::VideoEncoder* RTCVideoEncoderFactory::CreateVideoEncoder( - const cricket::VideoCodec& codec) { - for (size_t i = 0; i < supported_codecs_.size(); ++i) { - if (!cricket::CodecNamesEq(codec.name, supported_codecs_[i].name)) - continue; - // Check H264 profile. - using webrtc::H264::ParseSdpProfileLevelId; - if (cricket::CodecNamesEq(codec.name.c_str(), cricket::kH264CodecName) && - ParseSdpProfileLevelId(codec.params)->profile != - ParseSdpProfileLevelId(supported_codecs_[i].params)->profile) { - continue; +std::unique_ptr<webrtc::VideoEncoder> +RTCVideoEncoderFactory::CreateVideoEncoder( + const webrtc::SdpVideoFormat& format) { + for (size_t i = 0; i < supported_formats_.size(); ++i) { + if (IsSameFormat(format, supported_formats_[i])) { + // There should be a 1:1 mapping between media::VideoCodecProfile and + // webrtc::SdpVideoFormat. + CHECK_EQ(profiles_.size(), supported_formats_.size()); + return base::MakeUnique<RTCVideoEncoder>(profiles_[i], gpu_factories_); } - // There should be a 1:1 mapping between media::VideoCodecProfile and - // cricket::VideoCodec. - CHECK_EQ(profiles_.size(), supported_codecs_.size()); - return new RTCVideoEncoder(profiles_[i], gpu_factories_); } return nullptr; } -const std::vector<cricket::VideoCodec>& -RTCVideoEncoderFactory::supported_codecs() const { - return supported_codecs_; +std::vector<webrtc::SdpVideoFormat> +RTCVideoEncoderFactory::GetSupportedFormats() const { + return supported_formats_; } -void RTCVideoEncoderFactory::DestroyVideoEncoder( - webrtc::VideoEncoder* encoder) { - delete encoder; +webrtc::VideoEncoderFactory::CodecInfo +RTCVideoEncoderFactory::QueryVideoEncoder( + const webrtc::SdpVideoFormat& format) const { + CodecInfo info; + info.has_internal_source = false; + info.is_hardware_accelerated = true; + return info; } } // namespace content
diff --git a/content/renderer/media/gpu/rtc_video_encoder_factory.h b/content/renderer/media/gpu/rtc_video_encoder_factory.h index baf30df9..904d82e 100644 --- a/content/renderer/media/gpu/rtc_video_encoder_factory.h +++ b/content/renderer/media/gpu/rtc_video_encoder_factory.h
@@ -12,7 +12,7 @@ #include "base/memory/ref_counted.h" #include "content/common/content_export.h" #include "media/base/video_codecs.h" -#include "third_party/webrtc/media/engine/webrtcvideoencoderfactory.h" +#include "third_party/webrtc/api/video_codecs/video_encoder_factory.h" namespace media { class GpuVideoAcceleratorFactories; @@ -23,26 +23,27 @@ // This class creates RTCVideoEncoder instances (each wrapping a // media::VideoEncodeAccelerator) on behalf of the WebRTC stack. class CONTENT_EXPORT RTCVideoEncoderFactory - : public cricket::WebRtcVideoEncoderFactory { + : public webrtc::VideoEncoderFactory { public: explicit RTCVideoEncoderFactory( media::GpuVideoAcceleratorFactories* gpu_factories); ~RTCVideoEncoderFactory() override; - // cricket::WebRtcVideoEncoderFactory implementation. - webrtc::VideoEncoder* CreateVideoEncoder( - const cricket::VideoCodec& codec) override; - const std::vector<cricket::VideoCodec>& supported_codecs() const override; - void DestroyVideoEncoder(webrtc::VideoEncoder* encoder) override; + // webrtc::VideoEncoderFactory implementation. + std::unique_ptr<webrtc::VideoEncoder> CreateVideoEncoder( + const webrtc::SdpVideoFormat& format) override; + std::vector<webrtc::SdpVideoFormat> GetSupportedFormats() const override; + webrtc::VideoEncoderFactory::CodecInfo QueryVideoEncoder( + const webrtc::SdpVideoFormat& format) const override; private: media::GpuVideoAcceleratorFactories* gpu_factories_; - // List of supported cricket::WebRtcVideoEncoderFactory::VideoCodec. - // |profiles_| and |supported_codecs_| have the same length and the profile - // for |supported_codecs_[i]| is |profiles_[i]|. + // List of supported webrtc::SdpVideoFormat. |profiles_| and + // |supported_formats_| have the same length and the profile for + // |supported_formats_[i]| is |profiles_[i]|. std::vector<media::VideoCodecProfile> profiles_; - std::vector<cricket::VideoCodec> supported_codecs_; + std::vector<webrtc::SdpVideoFormat> supported_formats_; DISALLOW_COPY_AND_ASSIGN(RTCVideoEncoderFactory); };
diff --git a/content/renderer/media/render_media_log.cc b/content/renderer/media/render_media_log.cc index 2972ec7..60201ae1 100644 --- a/content/renderer/media/render_media_log.cc +++ b/content/renderer/media/render_media_log.cc
@@ -42,7 +42,7 @@ RenderMediaLog::RenderMediaLog(const GURL& security_origin) : security_origin_(security_origin), task_runner_(base::ThreadTaskRunnerHandle::Get()), - tick_clock_(new base::DefaultTickClock()), + tick_clock_(base::DefaultTickClock::GetInstance()), last_ipc_send_time_(tick_clock_->NowTicks()), ipc_send_pending_(false), weak_factory_(this) { @@ -182,10 +182,9 @@ RenderThread::Get()->Send(new ViewHostMsg_MediaLogEvents(events_to_send)); } -void RenderMediaLog::SetTickClockForTesting( - std::unique_ptr<base::TickClock> tick_clock) { +void RenderMediaLog::SetTickClockForTesting(base::TickClock* tick_clock) { base::AutoLock auto_lock(lock_); - tick_clock_.swap(tick_clock); + tick_clock_ = tick_clock; last_ipc_send_time_ = tick_clock_->NowTicks(); }
diff --git a/content/renderer/media/render_media_log.h b/content/renderer/media/render_media_log.h index 62c1256..cc27d5c 100644 --- a/content/renderer/media/render_media_log.h +++ b/content/renderer/media/render_media_log.h
@@ -43,7 +43,7 @@ void RecordRapporWithSecurityOrigin(const std::string& metric) override; // Will reset |last_ipc_send_time_| with the value of NowTicks(). - void SetTickClockForTesting(std::unique_ptr<base::TickClock> tick_clock); + void SetTickClockForTesting(base::TickClock* tick_clock); void SetTaskRunnerForTesting( const scoped_refptr<base::SingleThreadTaskRunner>& task_runner); @@ -62,7 +62,7 @@ // sequence for throttled send on |task_runner_| and coherent retrieval by // GetErrorMessage(). mutable base::Lock lock_; - std::unique_ptr<base::TickClock> tick_clock_; + base::TickClock* tick_clock_; base::TimeTicks last_ipc_send_time_; std::vector<media::MediaLogEvent> queued_media_events_;
diff --git a/content/renderer/media/render_media_log_unittest.cc b/content/renderer/media/render_media_log_unittest.cc index 410c8df..d96e5e490 100644 --- a/content/renderer/media/render_media_log_unittest.cc +++ b/content/renderer/media/render_media_log_unittest.cc
@@ -19,9 +19,8 @@ public: RenderMediaLogTest() : log_(GURL("http://foo.com")), - tick_clock_(new base::SimpleTestTickClock()), task_runner_(new base::TestMockTimeTaskRunner()) { - log_.SetTickClockForTesting(std::unique_ptr<base::TickClock>(tick_clock_)); + log_.SetTickClockForTesting(&tick_clock_); log_.SetTaskRunnerForTesting(task_runner_); } @@ -36,7 +35,7 @@ } void Advance(base::TimeDelta delta) { - tick_clock_->Advance(delta); + tick_clock_.Advance(delta); task_runner_->FastForwardBy(delta); } @@ -58,8 +57,8 @@ private: base::MessageLoop message_loop_; MockRenderThread render_thread_; + base::SimpleTestTickClock tick_clock_; RenderMediaLog log_; - base::SimpleTestTickClock* tick_clock_; // Owned by |log_|. scoped_refptr<base::TestMockTimeTaskRunner> task_runner_; DISALLOW_COPY_AND_ASSIGN(RenderMediaLogTest);
diff --git a/content/renderer/media/renderer_webmediaplayer_delegate.cc b/content/renderer/media/renderer_webmediaplayer_delegate.cc index 165f17ab..a22486e 100644 --- a/content/renderer/media/renderer_webmediaplayer_delegate.cc +++ b/content/renderer/media/renderer_webmediaplayer_delegate.cc
@@ -38,8 +38,7 @@ : RenderFrameObserver(render_frame), allow_idle_cleanup_( content::GetContentClient()->renderer()->AllowIdleMediaSuspend()), - default_tick_clock_(new base::DefaultTickClock()), - tick_clock_(default_tick_clock_.get()) { + tick_clock_(base::DefaultTickClock::GetInstance()) { idle_cleanup_interval_ = base::TimeDelta::FromSeconds(5); idle_timeout_ = base::TimeDelta::FromSeconds(15);
diff --git a/content/renderer/media/renderer_webmediaplayer_delegate.h b/content/renderer/media/renderer_webmediaplayer_delegate.h index eaf3ccb..65dea01 100644 --- a/content/renderer/media/renderer_webmediaplayer_delegate.h +++ b/content/renderer/media/renderer_webmediaplayer_delegate.h
@@ -136,7 +136,6 @@ // Clock used for calculating when players have become stale. May be // overridden for testing. - std::unique_ptr<base::DefaultTickClock> default_tick_clock_; base::TickClock* tick_clock_; #if defined(OS_ANDROID)
diff --git a/content/renderer/media/rtc_peer_connection_handler.cc b/content/renderer/media/rtc_peer_connection_handler.cc index 8fc192d5..fd3f94f 100644 --- a/content/renderer/media/rtc_peer_connection_handler.cc +++ b/content/renderer/media/rtc_peer_connection_handler.cc
@@ -981,7 +981,10 @@ base::WeakPtr<RTCPeerConnectionHandler> handler, blink::WebRTCVoidRequest web_request, base::WeakPtr<PeerConnectionTracker> tracker) - : handler_(handler), web_request_(web_request), tracker_(tracker) {} + : handler_(handler), + main_thread_(base::ThreadTaskRunnerHandle::Get()), + web_request_(web_request), + tracker_(tracker) {} void OnSetRemoteDescriptionComplete( webrtc::RTCErrorOr<WebRtcSetRemoteDescriptionObserver::States> @@ -1012,6 +1015,12 @@ removed_receivers.push_back(it->second.get()); } + // Update stream states (which tracks belong to which streams). + for (auto& stream_state : GetStreamStates(states, removed_receivers)) { + stream_state.stream_ref->adapter().SetTracks( + std::move(stream_state.track_refs)); + } + // Process the addition of remote receivers/tracks. for (auto& receiver_state : states.receiver_states) { if (ReceiverWasAdded(receiver_state)) { @@ -1030,13 +1039,39 @@ ""); } } - web_request_.RequestSucceeded(); - web_request_.Reset(); + // Resolve the promise in a post to ensure any events scheduled for + // dispatching will have fired by the time the promise is resolved. + // TODO(hbos): Don't schedule/post to fire events/resolve the promise. + // Instead, do it all synchronously. This must happen as the last step + // before returning so that all effects of SRD have occurred when the event + // executes. https://crbug.com/788558 + main_thread_->PostTask( + FROM_HERE, + base::BindOnce( + &RTCPeerConnectionHandler::WebRtcSetRemoteDescriptionObserverImpl:: + ResolvePromise, + this)); } private: ~WebRtcSetRemoteDescriptionObserverImpl() override {} + // Describes which tracks belong to a stream in terms of AdapterRefs. + struct StreamState { + StreamState( + std::unique_ptr<WebRtcMediaStreamAdapterMap::AdapterRef> stream_ref) + : stream_ref(std::move(stream_ref)) {} + + std::unique_ptr<WebRtcMediaStreamAdapterMap::AdapterRef> stream_ref; + std::vector<std::unique_ptr<WebRtcMediaStreamTrackAdapterMap::AdapterRef>> + track_refs; + }; + + void ResolvePromise() { + web_request_.RequestSucceeded(); + web_request_.Reset(); + } + bool ReceiverWasAdded(const WebRtcReceiverState& receiver_state) { return handler_->rtp_receivers_.find( RTCRtpReceiver::getId(receiver_state.receiver.get())) == @@ -1053,7 +1088,46 @@ return true; } + // Determines the stream states from the current state of receivers and the + // receivers that are about to be removed. Produces a stable order of streams. + std::vector<StreamState> GetStreamStates( + const WebRtcSetRemoteDescriptionObserver::States& states, + const std::vector<RTCRtpReceiver*>& removed_receivers) { + std::vector<StreamState> stream_states; + // The receiver's track belongs to all of its streams. A stream may be + // associated with multiple tracks (multiple receivers). + for (auto& receiver_state : states.receiver_states) { + for (auto& stream_ref : receiver_state.stream_refs) { + auto* stream_state = + GetOrAddStreamStateForStream(*stream_ref, &stream_states); + stream_state->track_refs.push_back(receiver_state.track_ref->Copy()); + } + } + // The track of removed receivers do not belong to any stream. Make sure we + // have a stream state for any streams belonging to receivers about to be + // removed in case it was the last receiver referencing that stream. + for (auto* removed_receiver : removed_receivers) + for (auto& stream_ref : removed_receiver->StreamAdapterRefs()) + GetOrAddStreamStateForStream(*stream_ref, &stream_states); + return stream_states; + } + + StreamState* GetOrAddStreamStateForStream( + const WebRtcMediaStreamAdapterMap::AdapterRef& stream_ref, + std::vector<StreamState>* stream_states) { + auto* webrtc_stream = stream_ref.adapter().webrtc_stream().get(); + for (auto& stream_state : *stream_states) { + if (stream_state.stream_ref->adapter().webrtc_stream().get() == + webrtc_stream) { + return &stream_state; + } + } + stream_states->push_back(StreamState(stream_ref.Copy())); + return &stream_states->back(); + } + base::WeakPtr<RTCPeerConnectionHandler> handler_; + scoped_refptr<base::SequencedTaskRunner> main_thread_; blink::WebRTCVoidRequest web_request_; base::WeakPtr<PeerConnectionTracker> tracker_; };
diff --git a/content/renderer/media/webrtc/peer_connection_dependency_factory.cc b/content/renderer/media/webrtc/peer_connection_dependency_factory.cc index d8e343c..d687fd4f 100644 --- a/content/renderer/media/webrtc/peer_connection_dependency_factory.cc +++ b/content/renderer/media/webrtc/peer_connection_dependency_factory.cc
@@ -31,13 +31,12 @@ #include "content/public/common/renderer_preferences.h" #include "content/public/common/webrtc_ip_handling_policy.h" #include "content/public/renderer/content_renderer_client.h" -#include "content/renderer/media/gpu/rtc_video_decoder_factory.h" -#include "content/renderer/media/gpu/rtc_video_encoder_factory.h" #include "content/renderer/media/media_stream_video_source.h" #include "content/renderer/media/media_stream_video_track.h" #include "content/renderer/media/rtc_peer_connection_handler.h" #include "content/renderer/media/webrtc/audio_codec_factory.h" #include "content/renderer/media/webrtc/stun_field_trial.h" +#include "content/renderer/media/webrtc/video_codec_factory.h" #include "content/renderer/media/webrtc/webrtc_video_capturer_adapter.h" #include "content/renderer/media/webrtc_audio_device_impl.h" #include "content/renderer/media/webrtc_logging.h" @@ -63,18 +62,11 @@ #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" #include "third_party/webrtc/api/mediaconstraintsinterface.h" -#include "third_party/webrtc/api/video_codecs/video_decoder_factory.h" -#include "third_party/webrtc/api/video_codecs/video_encoder_factory.h" #include "third_party/webrtc/api/videosourceproxy.h" -#include "third_party/webrtc/media/engine/convert_legacy_video_factory.h" #include "third_party/webrtc/modules/video_coding/codecs/h264/include/h264.h" #include "third_party/webrtc/rtc_base/refcountedobject.h" #include "third_party/webrtc/rtc_base/ssladapter.h" -#if defined(OS_ANDROID) -#include "media/base/android/media_codec_util.h" -#endif - namespace content { namespace { @@ -238,35 +230,15 @@ socket_factory_.reset( new IpcPacketSocketFactory(p2p_socket_dispatcher_.get())); - std::unique_ptr<cricket::WebRtcVideoDecoderFactory> decoder_factory; - std::unique_ptr<cricket::WebRtcVideoEncoderFactory> encoder_factory; - const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess(); - if (gpu_factories && gpu_factories->IsGpuVideoAcceleratorEnabled()) { - if (!cmd_line->HasSwitch(switches::kDisableWebRtcHWDecoding)) - decoder_factory.reset(new RTCVideoDecoderFactory(gpu_factories)); - if (!cmd_line->HasSwitch(switches::kDisableWebRtcHWEncoding)) { - encoder_factory.reset(new RTCVideoEncoderFactory(gpu_factories)); - } - } - -#if defined(OS_ANDROID) - if (!media::MediaCodecUtil::SupportsSetParameters()) - encoder_factory.reset(); -#endif - - // TODO(magjed): Update RTCVideoEncoderFactory/RTCVideoDecoderFactory to new - // interface and let Chromium be responsible in what order video codecs are - // listed, instead of using - // cricket::ConvertVideoEncoderFactory/cricket::ConvertVideoDecoderFactory. pc_factory_ = webrtc::CreatePeerConnectionFactory( worker_thread_ /* network thread */, worker_thread_, signaling_thread_, audio_device_.get(), CreateWebrtcAudioEncoderFactory(), CreateWebrtcAudioDecoderFactory(), - cricket::ConvertVideoEncoderFactory(std::move(encoder_factory)), - cricket::ConvertVideoDecoderFactory(std::move(decoder_factory)), - nullptr /* audio_mixer */, nullptr /* audio_processing */); + CreateWebrtcVideoEncoderFactory(gpu_factories), + CreateWebrtcVideoDecoderFactory(gpu_factories), nullptr /* audio_mixer */, + nullptr /* audio_processing */); CHECK(pc_factory_.get()); webrtc::PeerConnectionFactoryInterface::Options factory_options;
diff --git a/content/renderer/media/webrtc/video_codec_factory.cc b/content/renderer/media/webrtc/video_codec_factory.cc new file mode 100644 index 0000000..0c48ad2 --- /dev/null +++ b/content/renderer/media/webrtc/video_codec_factory.cc
@@ -0,0 +1,201 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/renderer/media/webrtc/video_codec_factory.h" + +#include "base/base_switches.h" +#include "base/command_line.h" +#include "base/memory/ptr_util.h" +#include "build/build_config.h" +#include "content/public/common/content_switches.h" +#include "content/renderer/media/gpu/rtc_video_decoder_factory.h" +#include "content/renderer/media/gpu/rtc_video_encoder_factory.h" +#include "third_party/webrtc/media/base/codec.h" +#include "third_party/webrtc/media/engine/internaldecoderfactory.h" +#include "third_party/webrtc/media/engine/internalencoderfactory.h" +#include "third_party/webrtc/media/engine/simulcast_encoder_adapter.h" +#include "third_party/webrtc/media/engine/videodecodersoftwarefallbackwrapper.h" +#include "third_party/webrtc/media/engine/videoencodersoftwarefallbackwrapper.h" +#include "third_party/webrtc/media/engine/vp8_encoder_simulcast_proxy.h" + +#if defined(OS_ANDROID) +#include "media/base/android/media_codec_util.h" +#endif + +namespace content { + +namespace { + +bool IsFormatSupported( + const std::vector<webrtc::SdpVideoFormat>& supported_formats, + const webrtc::SdpVideoFormat& format) { + for (const webrtc::SdpVideoFormat& supported_format : supported_formats) { + if (cricket::IsSameCodec(format.name, format.parameters, + supported_format.name, + supported_format.parameters)) { + return true; + } + } + return false; +} + +template <typename Factory> +bool IsFormatSupported(Factory* factory, const webrtc::SdpVideoFormat& format) { + return factory && IsFormatSupported(factory->GetSupportedFormats(), format); +} + +// Merge |formats1| and |formats2|, but avoid adding duplicate formats. +std::vector<webrtc::SdpVideoFormat> MergeFormats( + std::vector<webrtc::SdpVideoFormat> formats1, + std::vector<webrtc::SdpVideoFormat> formats2) { + for (const webrtc::SdpVideoFormat& format : formats2) { + // Don't add same format twice. + if (!IsFormatSupported(formats1, format)) + formats1.push_back(format); + } + return formats1; +} + +std::unique_ptr<webrtc::VideoDecoder> CreateDecoder( + webrtc::VideoDecoderFactory* factory, + const webrtc::SdpVideoFormat& format) { + return IsFormatSupported(factory, format) + ? factory->CreateVideoDecoder(format) + : nullptr; +} + +template <typename SoftwareWrapperClass, typename CoderClass> +std::unique_ptr<CoderClass> Wrap(std::unique_ptr<CoderClass> internal_coder, + std::unique_ptr<CoderClass> external_coder) { + if (internal_coder && external_coder) { + return base::MakeUnique<SoftwareWrapperClass>(std::move(internal_coder), + std::move(external_coder)); + } + return external_coder ? std::move(external_coder) : std::move(internal_coder); +} + +// This class combines an external factory with the internal factory and adds +// internal SW codecs, simulcast, and SW fallback wrappers. +class EncoderAdapter : public webrtc::VideoEncoderFactory { + public: + explicit EncoderAdapter( + std::unique_ptr<webrtc::VideoEncoderFactory> external_encoder_factory) + : external_encoder_factory_(std::move(external_encoder_factory)) {} + + webrtc::VideoEncoderFactory::CodecInfo QueryVideoEncoder( + const webrtc::SdpVideoFormat& format) const override { + const webrtc::VideoEncoderFactory* factory = + IsFormatSupported(external_encoder_factory_.get(), format) + ? external_encoder_factory_.get() + : &internal_encoder_factory_; + return factory->QueryVideoEncoder(format); + } + + std::unique_ptr<webrtc::VideoEncoder> CreateVideoEncoder( + const webrtc::SdpVideoFormat& format) override { + std::unique_ptr<webrtc::VideoEncoder> internal_encoder; + if (IsFormatSupported(internal_encoder_factory_.GetSupportedFormats(), + format)) { + internal_encoder = + cricket::CodecNamesEq(format.name.c_str(), cricket::kVp8CodecName) + ? base::MakeUnique<webrtc::VP8EncoderSimulcastProxy>( + &internal_encoder_factory_) + : internal_encoder_factory_.CreateVideoEncoder(format); + } + + std::unique_ptr<webrtc::VideoEncoder> external_encoder; + if (IsFormatSupported(external_encoder_factory_.get(), format)) { + external_encoder = + cricket::CodecNamesEq(format.name.c_str(), cricket::kVp8CodecName) + ? base::MakeUnique<webrtc::SimulcastEncoderAdapter>( + external_encoder_factory_.get()) + : external_encoder_factory_->CreateVideoEncoder(format); + } + + return Wrap<webrtc::VideoEncoderSoftwareFallbackWrapper>( + std::move(internal_encoder), std::move(external_encoder)); + } + + std::vector<webrtc::SdpVideoFormat> GetSupportedFormats() const override { + std::vector<webrtc::SdpVideoFormat> internal_formats = + internal_encoder_factory_.GetSupportedFormats(); + return external_encoder_factory_ + ? MergeFormats(internal_formats, + external_encoder_factory_->GetSupportedFormats()) + : internal_formats; + } + + private: + webrtc::InternalEncoderFactory internal_encoder_factory_; + const std::unique_ptr<webrtc::VideoEncoderFactory> external_encoder_factory_; +}; + +// This class combines an external factory with the internal factory and adds +// internal SW codecs and SW fallback wrappers. +class DecoderAdapter : public webrtc::VideoDecoderFactory { + public: + explicit DecoderAdapter( + std::unique_ptr<webrtc::VideoDecoderFactory> external_decoder_factory) + : external_decoder_factory_(std::move(external_decoder_factory)) {} + + std::unique_ptr<webrtc::VideoDecoder> CreateVideoDecoder( + const webrtc::SdpVideoFormat& format) override { + std::unique_ptr<webrtc::VideoDecoder> internal_decoder = + CreateDecoder(&internal_decoder_factory_, format); + + std::unique_ptr<webrtc::VideoDecoder> external_decoder = + CreateDecoder(external_decoder_factory_.get(), format); + + return Wrap<webrtc::VideoDecoderSoftwareFallbackWrapper>( + std::move(internal_decoder), std::move(external_decoder)); + } + + std::vector<webrtc::SdpVideoFormat> GetSupportedFormats() const override { + std::vector<webrtc::SdpVideoFormat> internal_formats = + internal_decoder_factory_.GetSupportedFormats(); + return external_decoder_factory_ + ? MergeFormats(internal_formats, + external_decoder_factory_->GetSupportedFormats()) + : internal_formats; + } + + private: + webrtc::InternalDecoderFactory internal_decoder_factory_; + const std::unique_ptr<webrtc::VideoDecoderFactory> external_decoder_factory_; +}; + +} // namespace + +std::unique_ptr<webrtc::VideoEncoderFactory> CreateWebrtcVideoEncoderFactory( + media::GpuVideoAcceleratorFactories* gpu_factories) { + std::unique_ptr<webrtc::VideoEncoderFactory> encoder_factory; + + const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess(); + if (gpu_factories && gpu_factories->IsGpuVideoAcceleratorEnabled() && + !cmd_line->HasSwitch(switches::kDisableWebRtcHWEncoding)) { + encoder_factory.reset(new RTCVideoEncoderFactory(gpu_factories)); + } + +#if defined(OS_ANDROID) + if (!media::MediaCodecUtil::SupportsSetParameters()) + encoder_factory.reset(); +#endif + + return base::MakeUnique<EncoderAdapter>(std::move(encoder_factory)); +} + +std::unique_ptr<webrtc::VideoDecoderFactory> CreateWebrtcVideoDecoderFactory( + media::GpuVideoAcceleratorFactories* gpu_factories) { + std::unique_ptr<webrtc::VideoDecoderFactory> decoder_factory; + + const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess(); + if (gpu_factories && gpu_factories->IsGpuVideoAcceleratorEnabled() && + !cmd_line->HasSwitch(switches::kDisableWebRtcHWDecoding)) { + decoder_factory.reset(new RTCVideoDecoderFactory(gpu_factories)); + } + + return base::MakeUnique<DecoderAdapter>(std::move(decoder_factory)); +} + +} // namespace content
diff --git a/content/renderer/media/webrtc/video_codec_factory.h b/content/renderer/media/webrtc/video_codec_factory.h new file mode 100644 index 0000000..2935358 --- /dev/null +++ b/content/renderer/media/webrtc/video_codec_factory.h
@@ -0,0 +1,21 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_RENDERER_MEDIA_WEBRTC_VIDEO_CODEC_FACTORY_H_ +#define CONTENT_RENDERER_MEDIA_WEBRTC_VIDEO_CODEC_FACTORY_H_ + +#include "media/video/gpu_video_accelerator_factories.h" +#include "third_party/webrtc/api/video_codecs/video_decoder_factory.h" +#include "third_party/webrtc/api/video_codecs/video_encoder_factory.h" + +namespace content { + +std::unique_ptr<webrtc::VideoEncoderFactory> CreateWebrtcVideoEncoderFactory( + media::GpuVideoAcceleratorFactories* gpu_factories); +std::unique_ptr<webrtc::VideoDecoderFactory> CreateWebrtcVideoDecoderFactory( + media::GpuVideoAcceleratorFactories* gpu_factories); + +} // namespace content + +#endif // CONTENT_RENDERER_MEDIA_WEBRTC_VIDEO_CODEC_FACTORY_H_
diff --git a/content/renderer/media/webrtc/webrtc_media_stream_adapter.cc b/content/renderer/media/webrtc/webrtc_media_stream_adapter.cc index edf29991..32040d6f 100644 --- a/content/renderer/media/webrtc/webrtc_media_stream_adapter.cc +++ b/content/renderer/media/webrtc/webrtc_media_stream_adapter.cc
@@ -108,6 +108,11 @@ return web_stream_; } +void LocalWebRtcMediaStreamAdapter::SetTracks( + WebRtcMediaStreamAdapter::TrackAdapterRefs track_refs) { + NOTIMPLEMENTED() << "Not supported for local stream adapters."; +} + void LocalWebRtcMediaStreamAdapter::TrackAdded( const blink::WebMediaStreamTrack& web_track) { DCHECK(adapter_refs_.find(web_track.UniqueId()) == adapter_refs_.end()); @@ -148,81 +153,6 @@ adapter_refs_.erase(it); } -class RemoteWebRtcMediaStreamAdapter::WebRtcStreamObserver - : public webrtc::ObserverInterface, - public base::RefCountedThreadSafe<WebRtcStreamObserver> { - public: - WebRtcStreamObserver( - base::WeakPtr<RemoteWebRtcMediaStreamAdapter> adapter, - scoped_refptr<base::SingleThreadTaskRunner> main_thread, - scoped_refptr<WebRtcMediaStreamTrackAdapterMap> track_adapter_map, - scoped_refptr<webrtc::MediaStreamInterface> webrtc_stream) - : adapter_(adapter), - main_thread_(std::move(main_thread)), - track_adapter_map_(std::move(track_adapter_map)), - webrtc_stream_(std::move(webrtc_stream)) { - webrtc_stream_->RegisterObserver(this); - } - - const scoped_refptr<base::SingleThreadTaskRunner>& main_thread() const { - return main_thread_; - } - - const scoped_refptr<webrtc::MediaStreamInterface>& webrtc_stream() const { - return webrtc_stream_; - } - - void InitializeOnMainThread(const std::string& label, - RemoteAdapterRefs adapter_refs, - size_t audio_track_count, - size_t video_track_count) { - DCHECK(main_thread_->BelongsToCurrentThread()); - if (adapter_) { - adapter_->InitializeOnMainThread(label, std::move(adapter_refs), - audio_track_count, video_track_count); - } - } - - // Uninitializes the observer, unregisters from receiving notifications and - // releases the webrtc stream. Must be called from the main thread before - // releasing the main reference. - void Unregister() { - DCHECK(main_thread_->BelongsToCurrentThread()); - webrtc_stream_->UnregisterObserver(this); - // Since we're guaranteed to not get further notifications, it's safe to - // release the webrtc_stream_ here. - webrtc_stream_ = nullptr; - } - - private: - friend class base::RefCountedThreadSafe<WebRtcStreamObserver>; - - ~WebRtcStreamObserver() override { - DCHECK(!webrtc_stream_.get()) << "Unregister hasn't been called"; - } - - // |webrtc::ObserverInterface| implementation. - void OnChanged() override { - RemoteAdapterRefs new_adapter_refs = - RemoteWebRtcMediaStreamAdapter::GetRemoteAdapterRefsFromWebRtcStream( - track_adapter_map_, webrtc_stream_.get()); - main_thread_->PostTask( - FROM_HERE, base::BindOnce(&WebRtcStreamObserver::OnChangedOnMainThread, - this, base::Passed(&new_adapter_refs))); - } - - void OnChangedOnMainThread(RemoteAdapterRefs new_adapter_refs) { - DCHECK(main_thread_->BelongsToCurrentThread()); - if (adapter_) - adapter_->OnChanged(std::move(new_adapter_refs)); - } - - base::WeakPtr<RemoteWebRtcMediaStreamAdapter> adapter_; - const scoped_refptr<base::SingleThreadTaskRunner> main_thread_; - const scoped_refptr<WebRtcMediaStreamTrackAdapterMap> track_adapter_map_; - scoped_refptr<webrtc::MediaStreamInterface> webrtc_stream_; -}; - // static bool RemoteWebRtcMediaStreamAdapter::RemoteAdapterRefsContainsTrack( const RemoteAdapterRefs& adapter_refs, @@ -267,17 +197,13 @@ weak_factory_(this) { DCHECK(!main_thread_->BelongsToCurrentThread()); DCHECK(track_adapter_map_); - observer_ = new RemoteWebRtcMediaStreamAdapter::WebRtcStreamObserver( - weak_factory_.GetWeakPtr(), main_thread_, track_adapter_map_, - webrtc_stream_); RemoteAdapterRefs adapter_refs = GetRemoteAdapterRefsFromWebRtcStream( track_adapter_map_, webrtc_stream_.get()); main_thread_->PostTask( FROM_HERE, - base::BindOnce(&RemoteWebRtcMediaStreamAdapter::WebRtcStreamObserver:: - InitializeOnMainThread, - observer_, webrtc_stream_->label(), + base::BindOnce(&RemoteWebRtcMediaStreamAdapter::InitializeOnMainThread, + weak_factory_.GetWeakPtr(), webrtc_stream_->label(), base::Passed(&adapter_refs), webrtc_stream_->GetAudioTracks().size(), webrtc_stream_->GetVideoTracks().size())); @@ -285,8 +211,7 @@ RemoteWebRtcMediaStreamAdapter::~RemoteWebRtcMediaStreamAdapter() { DCHECK(main_thread_->BelongsToCurrentThread()); - observer_->Unregister(); - OnChanged(RemoteAdapterRefs()); + SetTracks(RemoteAdapterRefs()); } bool RemoteWebRtcMediaStreamAdapter::is_initialized() const { @@ -333,32 +258,33 @@ web_stream_.Initialize(blink::WebString::FromUTF8(label), web_audio_tracks, web_video_tracks); - webrtc_stream_ = observer_->webrtc_stream(); base::AutoLock scoped_lock(lock_); is_initialized_ = true; } -void RemoteWebRtcMediaStreamAdapter::OnChanged( - RemoteAdapterRefs new_adapter_refs) { +void RemoteWebRtcMediaStreamAdapter::SetTracks( + WebRtcMediaStreamAdapter::TrackAdapterRefs track_refs) { DCHECK(main_thread_->BelongsToCurrentThread()); // Find removed tracks. - for (auto it = adapter_refs_.begin(); it != adapter_refs_.end();) { - if (!RemoteAdapterRefsContainsTrack(new_adapter_refs, - (*it)->webrtc_track())) { - web_stream_.RemoveTrack((*it)->web_track()); - it = adapter_refs_.erase(it); - } else { - ++it; - } - } + base::EraseIf( + adapter_refs_, + [this, &track_refs]( + const std::unique_ptr<WebRtcMediaStreamTrackAdapterMap::AdapterRef>& + track_ref) { + bool erase = !RemoteAdapterRefsContainsTrack(track_refs, + track_ref->webrtc_track()); + if (erase) + web_stream_.RemoveTrack(track_ref->web_track()); + return erase; + }); // Find added tracks. - for (auto& new_adapter_ref : new_adapter_refs) { + for (auto& track_ref : track_refs) { if (!RemoteAdapterRefsContainsTrack(adapter_refs_, - new_adapter_ref->webrtc_track())) { - web_stream_.AddTrack(new_adapter_ref->web_track()); - adapter_refs_.push_back(std::move(new_adapter_ref)); + track_ref->webrtc_track())) { + web_stream_.AddTrack(track_ref->web_track()); + adapter_refs_.push_back(std::move(track_ref)); } } }
diff --git a/content/renderer/media/webrtc/webrtc_media_stream_adapter.h b/content/renderer/media/webrtc/webrtc_media_stream_adapter.h index cd5352fe..85dc842 100644 --- a/content/renderer/media/webrtc/webrtc_media_stream_adapter.h +++ b/content/renderer/media/webrtc/webrtc_media_stream_adapter.h
@@ -34,6 +34,9 @@ // destroyed on the main thread. class CONTENT_EXPORT WebRtcMediaStreamAdapter { public: + using TrackAdapterRefs = std::vector< + std::unique_ptr<WebRtcMediaStreamTrackAdapterMap::AdapterRef>>; + // Creates an adapter for a local media stream. The adapter is already // initialized. Invoked on the main thread. static std::unique_ptr<WebRtcMediaStreamAdapter> CreateLocalStreamAdapter( @@ -60,6 +63,8 @@ (web_stream_.Id() == stream.Id()); } + virtual void SetTracks(TrackAdapterRefs track_refs) = 0; + protected: WebRtcMediaStreamAdapter( scoped_refptr<base::SingleThreadTaskRunner> main_thread, @@ -97,6 +102,7 @@ const scoped_refptr<webrtc::MediaStreamInterface>& webrtc_stream() const override; const blink::WebMediaStream& web_stream() const override; + void SetTracks(TrackAdapterRefs track_refs) override; private: // A map between web track UniqueIDs and references to track adapters. @@ -137,11 +143,11 @@ const scoped_refptr<webrtc::MediaStreamInterface>& webrtc_stream() const override; const blink::WebMediaStream& web_stream() const override; + void SetTracks(TrackAdapterRefs track_refs) override; private: // Track adapters for the remote webrtc tracks of a stream. - using RemoteAdapterRefs = std::vector< - std::unique_ptr<WebRtcMediaStreamTrackAdapterMap::AdapterRef>>; + using RemoteAdapterRefs = WebRtcMediaStreamAdapter::TrackAdapterRefs; static bool RemoteAdapterRefsContainsTrack( const RemoteAdapterRefs& adapter_refs, @@ -154,17 +160,13 @@ const scoped_refptr<WebRtcMediaStreamTrackAdapterMap>& track_adapter_map, webrtc::MediaStreamInterface* webrtc_stream); - class WebRtcStreamObserver; - void InitializeOnMainThread(const std::string& label, RemoteAdapterRefs track_adapter_refs, size_t audio_track_count, size_t video_track_count); - void OnChanged(RemoteAdapterRefs new_adapter_refs); mutable base::Lock lock_; bool is_initialized_; - scoped_refptr<WebRtcStreamObserver> observer_; // Track adapters belonging to this stream. Keeping adapter references alive // ensures the adapters are not disposed by the |track_adapter_map_| as long // as the webrtc layer track is in use by the webrtc layer stream.
diff --git a/content/renderer/media/webrtc/webrtc_media_stream_adapter_map.h b/content/renderer/media/webrtc/webrtc_media_stream_adapter_map.h index 521ca5f..a94d30dd 100644 --- a/content/renderer/media/webrtc/webrtc_media_stream_adapter_map.h +++ b/content/renderer/media/webrtc/webrtc_media_stream_adapter_map.h
@@ -58,6 +58,7 @@ const WebRtcMediaStreamAdapter& adapter() const { return *adapter_entry_->adapter; } + WebRtcMediaStreamAdapter& adapter() { return *adapter_entry_->adapter; } private: friend class WebRtcMediaStreamAdapterMap;
diff --git a/content/renderer/media/webrtc/webrtc_media_stream_adapter_unittest.cc b/content/renderer/media/webrtc/webrtc_media_stream_adapter_unittest.cc index 633f4d17..dbbe22f 100644 --- a/content/renderer/media/webrtc/webrtc_media_stream_adapter_unittest.cc +++ b/content/renderer/media/webrtc/webrtc_media_stream_adapter_unittest.cc
@@ -146,21 +146,33 @@ return adapter; } + // Adds the track and gets the adapters for the stream's resulting tracks. template <typename TrackType> - void AddTrack(webrtc::MediaStreamInterface* webrtc_stream, - TrackType* webrtc_track) { + WebRtcMediaStreamAdapter::TrackAdapterRefs AddTrack( + webrtc::MediaStreamInterface* webrtc_stream, + TrackType* webrtc_track) { typedef bool (webrtc::MediaStreamInterface::*AddTrack)(TrackType*); dependency_factory_->GetWebRtcSignalingThread()->PostTask( FROM_HERE, base::BindOnce(base::IgnoreResult<AddTrack>( &webrtc::MediaStreamInterface::AddTrack), base::Unretained(webrtc_stream), base::Unretained(webrtc_track))); + WebRtcMediaStreamAdapter::TrackAdapterRefs track_refs; + dependency_factory_->GetWebRtcSignalingThread()->PostTask( + FROM_HERE, + base::BindOnce(&RemoteWebRtcMediaStreamAdapterTest:: + GetStreamTrackRefsOnSignalingThread, + base::Unretained(this), base::Unretained(webrtc_stream), + base::Unretained(&track_refs))); RunMessageLoopsUntilIdle(); + return track_refs; } + // Removes the track and gets the adapters for the stream's resulting tracks. template <typename TrackType> - void RemoveTrack(webrtc::MediaStreamInterface* webrtc_stream, - TrackType* webrtc_track) { + WebRtcMediaStreamAdapter::TrackAdapterRefs RemoveTrack( + webrtc::MediaStreamInterface* webrtc_stream, + TrackType* webrtc_track) { typedef bool (webrtc::MediaStreamInterface::*RemoveTrack)(TrackType*); dependency_factory_->GetWebRtcSignalingThread()->PostTask( FROM_HERE, @@ -168,7 +180,15 @@ &webrtc::MediaStreamInterface::RemoveTrack), base::Unretained(webrtc_stream), base::Unretained(webrtc_track))); + WebRtcMediaStreamAdapter::TrackAdapterRefs track_refs; + dependency_factory_->GetWebRtcSignalingThread()->PostTask( + FROM_HERE, + base::BindOnce(&RemoteWebRtcMediaStreamAdapterTest:: + GetStreamTrackRefsOnSignalingThread, + base::Unretained(this), base::Unretained(webrtc_stream), + base::Unretained(&track_refs))); RunMessageLoopsUntilIdle(); + return track_refs; } private: @@ -181,6 +201,21 @@ EXPECT_FALSE((*adapter)->is_initialized()); } + void GetStreamTrackRefsOnSignalingThread( + webrtc::MediaStreamInterface* webrtc_stream, + WebRtcMediaStreamAdapter::TrackAdapterRefs* out_track_refs) { + WebRtcMediaStreamAdapter::TrackAdapterRefs track_refs; + for (auto& audio_track : webrtc_stream->GetAudioTracks()) { + track_refs.push_back( + track_adapter_map_->GetOrCreateRemoteTrackAdapter(audio_track.get())); + } + for (auto& video_track : webrtc_stream->GetVideoTracks()) { + track_refs.push_back( + track_adapter_map_->GetOrCreateRemoteTrackAdapter(video_track.get())); + } + *out_track_refs = std::move(track_refs); + } + // Runs message loops on the webrtc signaling thread and the main thread until // idle. void RunMessageLoopsUntilIdle() { @@ -191,6 +226,7 @@ FROM_HERE, base::BindOnce(&RemoteWebRtcMediaStreamAdapterTest::SignalEvent, base::Unretained(this), &waitable_event)); + // TODO(hbos): Use base::RunLoop instead of WaitableEvent. waitable_event.Wait(); base::RunLoop().RunUntilIdle(); } @@ -335,21 +371,23 @@ // Modify the webrtc layer stream, make sure the web layer stream is updated. rtc::scoped_refptr<webrtc::AudioTrackInterface> webrtc_audio_track = webrtc_stream->GetAudioTracks()[0]; - RemoveTrack(webrtc_stream.get(), webrtc_audio_track.get()); + adapter->SetTracks( + RemoveTrack(webrtc_stream.get(), webrtc_audio_track.get())); adapter->web_stream().AudioTracks(web_audio_tracks); EXPECT_EQ(0u, web_audio_tracks.size()); rtc::scoped_refptr<webrtc::VideoTrackInterface> webrtc_video_track = webrtc_stream->GetVideoTracks()[0]; - RemoveTrack(webrtc_stream.get(), webrtc_video_track.get()); + adapter->SetTracks( + RemoveTrack(webrtc_stream.get(), webrtc_video_track.get())); adapter->web_stream().VideoTracks(web_video_tracks); EXPECT_EQ(0u, web_video_tracks.size()); - AddTrack(webrtc_stream.get(), webrtc_audio_track.get()); + adapter->SetTracks(AddTrack(webrtc_stream.get(), webrtc_audio_track.get())); adapter->web_stream().AudioTracks(web_audio_tracks); EXPECT_EQ(1u, web_audio_tracks.size()); - AddTrack(webrtc_stream.get(), webrtc_video_track.get()); + adapter->SetTracks(AddTrack(webrtc_stream.get(), webrtc_video_track.get())); adapter->web_stream().VideoTracks(web_video_tracks); EXPECT_EQ(1u, web_video_tracks.size()); }
diff --git a/content/renderer/pepper/mock_renderer_ppapi_host.cc b/content/renderer/pepper/mock_renderer_ppapi_host.cc index 7820b7fe..ad9a0df 100644 --- a/content/renderer/pepper/mock_renderer_ppapi_host.cc +++ b/content/renderer/pepper/mock_renderer_ppapi_host.cc
@@ -57,11 +57,6 @@ return nullptr; } -base::ProcessId MockRendererPpapiHost::GetPluginPID() const { - NOTIMPLEMENTED(); - return base::kNullProcessId; -} - bool MockRendererPpapiHost::HasUserGesture(PP_Instance instance) const { return has_user_gesture_; }
diff --git a/content/renderer/pepper/mock_renderer_ppapi_host.h b/content/renderer/pepper/mock_renderer_ppapi_host.h index 503a225..375c212 100644 --- a/content/renderer/pepper/mock_renderer_ppapi_host.h +++ b/content/renderer/pepper/mock_renderer_ppapi_host.h
@@ -39,7 +39,6 @@ RenderView* GetRenderViewForInstance(PP_Instance instance) const override; blink::WebPluginContainer* GetContainerForInstance( PP_Instance instance) const override; - base::ProcessId GetPluginPID() const override; bool HasUserGesture(PP_Instance instance) const override; int GetRoutingIDForWidget(PP_Instance instance) const override; gfx::Point PluginPointToRenderFrame(PP_Instance instance,
diff --git a/content/renderer/pepper/pepper_url_loader_host.cc b/content/renderer/pepper/pepper_url_loader_host.cc index 02a549b..9b01074f 100644 --- a/content/renderer/pepper/pepper_url_loader_host.cc +++ b/content/renderer/pepper/pepper_url_loader_host.cc
@@ -255,7 +255,8 @@ } web_request.SetRequestContext(WebURLRequest::kRequestContextPlugin); - web_request.SetRequestorProcessID(renderer_ppapi_host_->GetPluginPID()); + web_request.SetPluginChildID(renderer_ppapi_host_->GetPluginChildId()); + // The requests from the plugins with private permission which can bypass same // origin must skip the ServiceWorker. web_request.SetServiceWorkerMode(
diff --git a/content/renderer/pepper/renderer_ppapi_host_impl.cc b/content/renderer/pepper/renderer_ppapi_host_impl.cc index 5a2eee6..952ba13 100644 --- a/content/renderer/pepper/renderer_ppapi_host_impl.cc +++ b/content/renderer/pepper/renderer_ppapi_host_impl.cc
@@ -177,12 +177,6 @@ return instance_object->container(); } -base::ProcessId RendererPpapiHostImpl::GetPluginPID() const { - if (dispatcher_) - return dispatcher_->peer_pid(); - return base::kNullProcessId; -} - bool RendererPpapiHostImpl::HasUserGesture(PP_Instance instance) const { PepperPluginInstanceImpl* instance_object = GetAndValidateInstance(instance); if (!instance_object) @@ -287,6 +281,10 @@ content::IsOriginSecure(instance->GetPluginURL()); } +int RendererPpapiHostImpl::GetPluginChildId() const { + return module_->GetPluginChildId(); +} + PepperPluginInstanceImpl* RendererPpapiHostImpl::GetAndValidateInstance( PP_Instance pp_instance) const { PepperPluginInstanceImpl* instance =
diff --git a/content/renderer/pepper/renderer_ppapi_host_impl.h b/content/renderer/pepper/renderer_ppapi_host_impl.h index e87ba2a..d8d6edda 100644 --- a/content/renderer/pepper/renderer_ppapi_host_impl.h +++ b/content/renderer/pepper/renderer_ppapi_host_impl.h
@@ -80,7 +80,6 @@ RenderView* GetRenderViewForInstance(PP_Instance instance) const override; blink::WebPluginContainer* GetContainerForInstance( PP_Instance instance) const override; - base::ProcessId GetPluginPID() const override; bool HasUserGesture(PP_Instance instance) const override; int GetRoutingIDForWidget(PP_Instance instance) const override; gfx::Point PluginPointToRenderFrame(PP_Instance instance, @@ -103,6 +102,13 @@ // Returns whether the plugin is running in a secure context. bool IsSecureContext(PP_Instance pp_instance) const; + // Returns the plugin child process ID if the plugin is running out of + // process. Returns -1 otherwise. This is the ID that the browser process uses + // to idetify the child process for the plugin. This isn't directly useful + // from our process (the renderer) except in messages to the browser to + // disambiguate plugins. + int GetPluginChildId() const; + void set_viewport_to_dip_scale(float viewport_to_dip_scale) { DCHECK_LT(0, viewport_to_dip_scale_); viewport_to_dip_scale_ = viewport_to_dip_scale;
diff --git a/content/renderer/quota_dispatcher.cc b/content/renderer/quota_dispatcher.cc index 30e30d4..daa181a 100644 --- a/content/renderer/quota_dispatcher.cc +++ b/content/renderer/quota_dispatcher.cc
@@ -11,9 +11,9 @@ #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/threading/thread_local.h" -#include "content/child/thread_safe_sender.h" -#include "content/common/quota_messages.h" -#include "content/renderer/quota_message_filter.h" +#include "content/public/common/service_names.mojom.h" +#include "content/public/renderer/render_thread.h" +#include "services/service_manager/public/cpp/connector.h" #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h" #include "third_party/WebKit/public/platform/WebStorageQuotaType.h" #include "url/gurl.h" @@ -59,13 +59,27 @@ return WorkerThread::GetCurrentId(); } +void BindConnectorOnMainThread(mojom::QuotaDispatcherHostRequest request) { + DCHECK(RenderThread::Get()); + RenderThread::Get()->GetConnector()->BindInterface(mojom::kBrowserServiceName, + std::move(request)); +} + } // namespace -QuotaDispatcher::QuotaDispatcher(ThreadSafeSender* thread_safe_sender, - QuotaMessageFilter* quota_message_filter) - : thread_safe_sender_(thread_safe_sender), - quota_message_filter_(quota_message_filter) { +QuotaDispatcher::QuotaDispatcher( + scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner) + : main_thread_task_runner_(main_thread_task_runner) { g_quota_dispatcher_tls.Pointer()->Set(this); + + auto request = mojo::MakeRequest("a_host_); + if (main_thread_task_runner_->BelongsToCurrentThread()) { + BindConnectorOnMainThread(std::move(request)); + } else { + main_thread_task_runner->PostTask( + FROM_HERE, + base::BindOnce(&BindConnectorOnMainThread, std::move(request))); + } } QuotaDispatcher::~QuotaDispatcher() { @@ -80,13 +94,11 @@ } QuotaDispatcher* QuotaDispatcher::ThreadSpecificInstance( - ThreadSafeSender* thread_safe_sender, - QuotaMessageFilter* quota_message_filter) { + scoped_refptr<base::SingleThreadTaskRunner> task_runner) { if (g_quota_dispatcher_tls.Pointer()->Get()) return g_quota_dispatcher_tls.Pointer()->Get(); - QuotaDispatcher* dispatcher = new QuotaDispatcher( - thread_safe_sender, quota_message_filter); + QuotaDispatcher* dispatcher = new QuotaDispatcher(task_runner); if (WorkerThread::GetCurrentId()) WorkerThread::AddObserver(dispatcher); return dispatcher; @@ -96,47 +108,31 @@ delete this; } -void QuotaDispatcher::OnMessageReceived(const IPC::Message& msg) { - bool handled = true; - IPC_BEGIN_MESSAGE_MAP(QuotaDispatcher, msg) - IPC_MESSAGE_HANDLER(QuotaMsg_DidGrantStorageQuota, - DidGrantStorageQuota) - IPC_MESSAGE_HANDLER(QuotaMsg_DidQueryStorageUsageAndQuota, - DidQueryStorageUsageAndQuota); - IPC_MESSAGE_HANDLER(QuotaMsg_DidFail, DidFail); - IPC_MESSAGE_UNHANDLED(handled = false) - IPC_END_MESSAGE_MAP() - DCHECK(handled) << "Unhandled message:" << msg.type(); -} - void QuotaDispatcher::QueryStorageUsageAndQuota( const GURL& origin_url, StorageType type, std::unique_ptr<Callback> callback) { DCHECK(callback); - int request_id = quota_message_filter_->GenerateRequestID(CurrentWorkerId()); - pending_quota_callbacks_.AddWithID(std::move(callback), request_id); - thread_safe_sender_->Send(new QuotaHostMsg_QueryStorageUsageAndQuota( - request_id, origin_url, type)); + int request_id = pending_quota_callbacks_.Add(std::move(callback)); + quota_host_->QueryStorageUsageAndQuota( + origin_url, type, + base::BindOnce(&QuotaDispatcher::DidQueryStorageUsageAndQuota, + base::Unretained(this), request_id)); } void QuotaDispatcher::RequestStorageQuota(int render_frame_id, const GURL& origin_url, StorageType type, - uint64_t requested_size, + int64_t requested_size, std::unique_ptr<Callback> callback) { DCHECK(callback); - DCHECK(CurrentWorkerId() == 0); - int request_id = quota_message_filter_->GenerateRequestID(CurrentWorkerId()); - pending_quota_callbacks_.AddWithID(std::move(callback), request_id); - - StorageQuotaParams params; - params.render_frame_id = render_frame_id; - params.request_id = request_id; - params.origin_url = origin_url; - params.storage_type = type; - params.requested_size = requested_size; - thread_safe_sender_->Send(new QuotaHostMsg_RequestStorageQuota(params)); + DCHECK_EQ(CurrentWorkerId(), 0) + << "Requests may show permission UI and are not allowed from workers."; + int request_id = pending_quota_callbacks_.Add(std::move(callback)); + quota_host_->RequestStorageQuota( + render_frame_id, origin_url, type, requested_size, + base::BindOnce(&QuotaDispatcher::DidGrantStorageQuota, + base::Unretained(this), request_id)); } // static @@ -146,18 +142,31 @@ return std::make_unique<WebStorageQuotaDispatcherCallback>(callbacks); } -void QuotaDispatcher::DidGrantStorageQuota(int request_id, +void QuotaDispatcher::DidGrantStorageQuota(int64_t request_id, + storage::QuotaStatusCode status, int64_t current_usage, int64_t granted_quota) { + if (status != storage::kQuotaStatusOk) { + DidFail(request_id, status); + return; + } + Callback* callback = pending_quota_callbacks_.Lookup(request_id); DCHECK(callback); callback->DidGrantStorageQuota(current_usage, granted_quota); pending_quota_callbacks_.Remove(request_id); } -void QuotaDispatcher::DidQueryStorageUsageAndQuota(int request_id, - int64_t current_usage, - int64_t current_quota) { +void QuotaDispatcher::DidQueryStorageUsageAndQuota( + int64_t request_id, + storage::QuotaStatusCode status, + int64_t current_usage, + int64_t current_quota) { + if (status != storage::kQuotaStatusOk) { + DidFail(request_id, status); + return; + } + Callback* callback = pending_quota_callbacks_.Lookup(request_id); DCHECK(callback); callback->DidQueryStorageUsageAndQuota(current_usage, current_quota);
diff --git a/content/renderer/quota_dispatcher.h b/content/renderer/quota_dispatcher.h index b882c1d..ef1af82 100644 --- a/content/renderer/quota_dispatcher.h +++ b/content/renderer/quota_dispatcher.h
@@ -13,31 +13,26 @@ #include "base/containers/id_map.h" #include "base/macros.h" -#include "base/memory/ref_counted.h" +#include "content/common/quota_dispatcher_host.mojom.h" #include "content/public/renderer/worker_thread.h" -#include "storage/common/quota/quota_types.h" class GURL; -namespace IPC { -class Message; -} - namespace blink { class WebStorageQuotaCallbacks; } namespace content { -class ThreadSafeSender; -class QuotaMessageFilter; - // Dispatches and sends quota related messages sent to/from a child // process from/to the main browser process. There is one instance // per each thread. Thread-specific instance can be obtained by // ThreadSpecificInstance(). +// TODO(sashab): Change this to be per-execution context instead of per-process. class QuotaDispatcher : public WorkerThread::Observer { public: + // TODO(sashab): Remove this wrapper, using lambdas or just the web callback + // itself. class Callback { public: virtual ~Callback() {} @@ -46,28 +41,23 @@ virtual void DidFail(storage::QuotaStatusCode status) = 0; }; - QuotaDispatcher(ThreadSafeSender* thread_safe_sender, - QuotaMessageFilter* quota_message_filter); + explicit QuotaDispatcher( + scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner); ~QuotaDispatcher() override; - // |thread_safe_sender| and |quota_message_filter| are used if - // calling this leads to construction. static QuotaDispatcher* ThreadSpecificInstance( - ThreadSafeSender* thread_safe_sender, - QuotaMessageFilter* quota_message_filter); + scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner); // WorkerThread::Observer implementation. void WillStopCurrentWorkerThread() override; - void OnMessageReceived(const IPC::Message& msg); - void QueryStorageUsageAndQuota(const GURL& gurl, storage::StorageType type, std::unique_ptr<Callback> callback); void RequestStorageQuota(int render_frame_id, const GURL& gurl, storage::StorageType type, - uint64_t requested_size, + int64_t requested_size, std::unique_ptr<Callback> callback); // Creates a new Callback instance for WebStorageQuotaCallbacks. @@ -76,18 +66,23 @@ private: // Message handlers. - void DidQueryStorageUsageAndQuota(int request_id, + void DidQueryStorageUsageAndQuota(int64_t request_id, + storage::QuotaStatusCode status, int64_t current_usage, int64_t current_quota); - void DidGrantStorageQuota(int request_id, + void DidGrantStorageQuota(int64_t request_id, + storage::QuotaStatusCode status, int64_t current_usage, int64_t granted_quota); void DidFail(int request_id, storage::QuotaStatusCode error); - base::IDMap<std::unique_ptr<Callback>> pending_quota_callbacks_; + content::mojom::QuotaDispatcherHostPtr quota_host_; + scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner_; - scoped_refptr<ThreadSafeSender> thread_safe_sender_; - scoped_refptr<QuotaMessageFilter> quota_message_filter_; + // TODO(sashab, nverne): Once default callbacks are available for dropped mojo + // callbacks (crbug.com/775358), use them to call DidFail for them in the + // destructor and remove this. + base::IDMap<std::unique_ptr<Callback>> pending_quota_callbacks_; DISALLOW_COPY_AND_ASSIGN(QuotaDispatcher); };
diff --git a/content/renderer/quota_message_filter.cc b/content/renderer/quota_message_filter.cc deleted file mode 100644 index d6b80d90..0000000 --- a/content/renderer/quota_message_filter.cc +++ /dev/null
@@ -1,60 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/renderer/quota_message_filter.h" - -#include "content/renderer/quota_dispatcher.h" -#include "content/common/quota_messages.h" - -namespace content { - -QuotaMessageFilter::QuotaMessageFilter(ThreadSafeSender* thread_safe_sender) - : WorkerThreadMessageFilter(thread_safe_sender), next_request_id_(0) { -} - -QuotaMessageFilter::~QuotaMessageFilter() {} - -int QuotaMessageFilter::GenerateRequestID(int thread_id) { - base::AutoLock lock(request_id_map_lock_); - request_id_map_[next_request_id_] = thread_id; - return next_request_id_++; -} - -void QuotaMessageFilter::ClearThreadRequests(int thread_id) { - base::AutoLock lock(request_id_map_lock_); - for (RequestIdToThreadId::iterator iter = request_id_map_.begin(); - iter != request_id_map_.end();) { - if (iter->second == thread_id) - request_id_map_.erase(iter++); - else - iter++; - } -} - -bool QuotaMessageFilter::ShouldHandleMessage(const IPC::Message& msg) const { - return IPC_MESSAGE_CLASS(msg) == QuotaMsgStart; -} - -void QuotaMessageFilter::OnFilteredMessageReceived(const IPC::Message& msg) { - QuotaDispatcher::ThreadSpecificInstance(thread_safe_sender(), this) - ->OnMessageReceived(msg); -} - -bool QuotaMessageFilter::GetWorkerThreadIdForMessage(const IPC::Message& msg, - int* ipc_thread_id) { - int request_id = -1; - const bool success = base::PickleIterator(msg).ReadInt(&request_id); - DCHECK(success); - - base::AutoLock lock(request_id_map_lock_); - RequestIdToThreadId::iterator found = request_id_map_.find(request_id); - if (found != request_id_map_.end()) { - *ipc_thread_id = found->second; - request_id_map_.erase(found); - return true; - } - return false; -} - -} // namespace content
diff --git a/content/renderer/quota_message_filter.h b/content/renderer/quota_message_filter.h deleted file mode 100644 index 885629e..0000000 --- a/content/renderer/quota_message_filter.h +++ /dev/null
@@ -1,49 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_RENDERER_QUOTA_MESSAGE_FILTER_H_ -#define CONTENT_RENDERER_QUOTA_MESSAGE_FILTER_H_ - -#include <map> - -#include "base/macros.h" -#include "base/synchronization/lock.h" -#include "content/renderer/worker_thread_message_filter.h" - -namespace content { - -class QuotaMessageFilter : public WorkerThreadMessageFilter { - public: - explicit QuotaMessageFilter(ThreadSafeSender* thread_safe_sender); - - // Generates a new request_id, registers { request_id, thread_id } map to - // the message filter and returns the request_id. - // This method can be called on any thread. - int GenerateRequestID(int thread_id); - - // Clears all requests from the thread_id. - void ClearThreadRequests(int thread_id); - - protected: - ~QuotaMessageFilter() override; - - private: - // WorkerThreadMessageFilter: - bool ShouldHandleMessage(const IPC::Message& msg) const override; - void OnFilteredMessageReceived(const IPC::Message& msg) override; - bool GetWorkerThreadIdForMessage(const IPC::Message& msg, - int* ipc_thread_id) override; - - typedef std::map<int, int> RequestIdToThreadId; - - base::Lock request_id_map_lock_; - RequestIdToThreadId request_id_map_; - int next_request_id_; - - DISALLOW_COPY_AND_ASSIGN(QuotaMessageFilter); -}; - -} // namespace content - -#endif // CONTENT_RENDERER_QUOTA_MESSAGE_FILTER_H_
diff --git a/content/renderer/render_frame_impl.cc b/content/renderer/render_frame_impl.cc index 54bccea1..8f36d317 100644 --- a/content/renderer/render_frame_impl.cc +++ b/content/renderer/render_frame_impl.cc
@@ -65,7 +65,6 @@ #include "content/common/swapped_out_messages.h" #include "content/common/view_messages.h" #include "content/public/common/appcache_info.h" -#include "content/public/common/associated_interface_provider.h" #include "content/public/common/bind_interface_helpers.h" #include "content/public/common/bindings_policy.h" #include "content/public/common/browser_side_navigation_policy.h" @@ -175,6 +174,7 @@ #include "services/service_manager/public/interfaces/interface_provider.mojom.h" #include "services/ui/public/cpp/gpu/context_provider_command_buffer.h" #include "storage/common/data_element.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" #include "third_party/WebKit/common/frame_policy.h" #include "third_party/WebKit/common/page/page_visibility_state.mojom.h" #include "third_party/WebKit/public/platform/FilePathConversion.h" @@ -2901,12 +2901,12 @@ return &remote_interfaces_; } -AssociatedInterfaceRegistry* +blink::AssociatedInterfaceRegistry* RenderFrameImpl::GetAssociatedInterfaceRegistry() { return &associated_interfaces_; } -AssociatedInterfaceProvider* +blink::AssociatedInterfaceProvider* RenderFrameImpl::GetRemoteAssociatedInterfaces() { if (!remote_associated_interfaces_) { ChildThreadImpl* thread = ChildThreadImpl::current(); @@ -3381,6 +3381,11 @@ return &remote_interfaces_; } +blink::AssociatedInterfaceProvider* +RenderFrameImpl::GetRemoteNavigationAssociatedInterfaces() { + return GetRemoteAssociatedInterfaces(); +} + void RenderFrameImpl::DidAccessInitialDocument() { DCHECK(!frame_->Parent()); // NOTE: Do not call back into JavaScript here, since this call is made from a
diff --git a/content/renderer/render_frame_impl.h b/content/renderer/render_frame_impl.h index 0de38de..08e18505 100644 --- a/content/renderer/render_frame_impl.h +++ b/content/renderer/render_frame_impl.h
@@ -462,8 +462,8 @@ const std::string& interface_name, mojo::ScopedMessagePipeHandle interface_pipe) override; service_manager::InterfaceProvider* GetRemoteInterfaces() override; - AssociatedInterfaceRegistry* GetAssociatedInterfaceRegistry() override; - AssociatedInterfaceProvider* GetRemoteAssociatedInterfaces() override; + blink::AssociatedInterfaceRegistry* GetAssociatedInterfaceRegistry() override; + blink::AssociatedInterfaceProvider* GetRemoteAssociatedInterfaces() override; #if BUILDFLAG(ENABLE_PLUGINS) void RegisterPeripheralPlugin( const url::Origin& content_origin, @@ -553,6 +553,8 @@ std::unique_ptr<blink::WebServiceWorkerProvider> CreateServiceWorkerProvider() override; service_manager::InterfaceProvider* GetInterfaceProvider() override; + blink::AssociatedInterfaceProvider* GetRemoteNavigationAssociatedInterfaces() + override; void DidAccessInitialDocument() override; blink::WebLocalFrame* CreateChildFrame( blink::WebLocalFrame* parent,
diff --git a/content/renderer/render_thread_impl.cc b/content/renderer/render_thread_impl.cc index c7ede90..58e7213a 100644 --- a/content/renderer/render_thread_impl.cc +++ b/content/renderer/render_thread_impl.cc
@@ -123,7 +123,6 @@ #include "content/renderer/notifications/notification_dispatcher.h" #include "content/renderer/p2p/socket_dispatcher.h" #include "content/renderer/quota_dispatcher.h" -#include "content/renderer/quota_message_filter.h" #include "content/renderer/render_frame_proxy.h" #include "content/renderer/render_process_impl.h" #include "content/renderer/render_view_impl.h" @@ -186,6 +185,7 @@ #include "third_party/skia/include/core/SkGraphics.h" #include "ui/base/layout.h" #include "ui/base/ui_base_switches.h" +#include "ui/base/ui_base_switches_util.h" #include "ui/display/display_switches.h" #include "ui/gl/gl_switches.h" @@ -330,16 +330,6 @@ histogram->Add(sample); } -bool IsMusHostingViz() { -#if BUILDFLAG(ENABLE_MUS) - const auto* cmdline = base::CommandLine::ForCurrentProcess(); - return cmdline->GetSwitchValueASCII(switches::kMus) == - switches::kMusHostVizValue; -#else - return false; -#endif -} - class FrameFactoryImpl : public mojom::FrameFactory { public: explicit FrameFactoryImpl(const service_manager::BindSourceInfo& source_info) @@ -695,10 +685,11 @@ base::BindRepeating(&CreateSingleSampleMetricsProvider, message_loop()->task_runner(), GetConnector())); - gpu_ = ui::Gpu::Create( - GetConnector(), - IsMusHostingViz() ? ui::mojom::kServiceName : mojom::kBrowserServiceName, - GetIOTaskRunner()); + gpu_ = + ui::Gpu::Create(GetConnector(), + switches::IsMusHostingViz() ? ui::mojom::kServiceName + : mojom::kBrowserServiceName, + GetIOTaskRunner()); viz::mojom::SharedBitmapAllocationNotifierPtr shared_bitmap_allocation_notifier_ptr; @@ -719,12 +710,7 @@ resource_message_filter_ = new ChildResourceMessageFilter(resource_dispatcher_.get()); AddFilter(resource_message_filter_.get()); - quota_message_filter_ = - new QuotaMessageFilter(thread_safe_sender()); - quota_dispatcher_.reset(new QuotaDispatcher(thread_safe_sender(), - quota_message_filter_.get())); - - AddFilter(quota_message_filter_->GetFilter()); + quota_dispatcher_.reset(new QuotaDispatcher(message_loop()->task_runner())); auto registry = std::make_unique<service_manager::BinderRegistry>(); BlinkInterfaceRegistryImpl interface_registry( @@ -2031,7 +2017,7 @@ } #if defined(USE_AURA) - if (IsMusHostingViz()) { + if (switches::IsMusHostingViz()) { if (!RendererWindowTreeClient::Get(routing_id)) { callback.Run(nullptr); return; @@ -2170,7 +2156,7 @@ ¶ms)); } -AssociatedInterfaceRegistry* +blink::AssociatedInterfaceRegistry* RenderThreadImpl::GetAssociatedInterfaceRegistry() { return &associated_interfaces_; }
diff --git a/content/renderer/render_thread_impl.h b/content/renderer/render_thread_impl.h index fd01cea..840324c 100644 --- a/content/renderer/render_thread_impl.h +++ b/content/renderer/render_thread_impl.h
@@ -147,7 +147,6 @@ class PeerConnectionDependencyFactory; class PeerConnectionTracker; class QuotaDispatcher; -class QuotaMessageFilter; class RenderThreadObserver; class RendererBlinkPlatformImpl; class ResourceDispatcher; @@ -297,7 +296,7 @@ const GURL& url, const LayerTreeFrameSinkCallback& callback); - AssociatedInterfaceRegistry* GetAssociatedInterfaceRegistry(); + blink::AssociatedInterfaceRegistry* GetAssociatedInterfaceRegistry(); std::unique_ptr<cc::SwapPromise> RequestCopyOfOutputForLayoutTest( int32_t routing_id, @@ -359,10 +358,6 @@ return quota_dispatcher_.get(); } - QuotaMessageFilter* quota_message_filter() const { - return quota_message_filter_.get(); - } - ResourceDispatcher* resource_dispatcher() const { return resource_dispatcher_.get(); } @@ -664,7 +659,6 @@ scoped_refptr<MidiMessageFilter> midi_message_filter_; scoped_refptr<ServiceWorkerMessageFilter> service_worker_message_filter_; scoped_refptr<ChildResourceMessageFilter> resource_message_filter_; - scoped_refptr<QuotaMessageFilter> quota_message_filter_; std::unique_ptr<BrowserPluginManager> browser_plugin_manager_;
diff --git a/content/renderer/render_view_impl.cc b/content/renderer/render_view_impl.cc index f2663cf3..590c9f9 100644 --- a/content/renderer/render_view_impl.cc +++ b/content/renderer/render_view_impl.cc
@@ -51,7 +51,6 @@ #include "content/common/page_messages.h" #include "content/common/render_message_filter.mojom.h" #include "content/common/view_messages.h" -#include "content/public/common/associated_interface_provider.h" #include "content/public/common/browser_side_navigation_policy.h" #include "content/public/common/content_client.h" #include "content/public/common/content_constants.h" @@ -108,6 +107,7 @@ #include "net/http/http_util.h" #include "ppapi/features/features.h" #include "skia/ext/platform_canvas.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" #include "third_party/WebKit/common/page/page_visibility_state.mojom.h" #include "third_party/WebKit/public/platform/FilePathConversion.h" #include "third_party/WebKit/public/platform/URLConversion.h"
diff --git a/content/renderer/render_widget.cc b/content/renderer/render_widget.cc index 4f791dd..c7998d55 100644 --- a/content/renderer/render_widget.cc +++ b/content/renderer/render_widget.cc
@@ -1133,8 +1133,10 @@ void RenderWidget::OnDidOverscroll(const ui::DidOverscrollParams& params) { if (widget_input_handler_manager_) { - widget_input_handler_manager_->GetWidgetInputHandlerHost()->DidOverscroll( - params); + if (mojom::WidgetInputHandlerHost* host = + widget_input_handler_manager_->GetWidgetInputHandlerHost()) { + host->DidOverscroll(params); + } } else { Send(new InputHostMsg_DidOverscroll(routing_id_, params)); } @@ -1737,8 +1739,10 @@ // process to cancel the input method's ongoing composition session, to make // sure we are in a consistent state. if (widget_input_handler_manager_) { - widget_input_handler_manager_->GetWidgetInputHandlerHost() - ->ImeCancelComposition(); + if (mojom::WidgetInputHandlerHost* host = + widget_input_handler_manager_->GetWidgetInputHandlerHost()) { + host->ImeCancelComposition(); + } } else { Send(new InputHostMsg_ImeCancelComposition(routing_id())); } @@ -2003,9 +2007,11 @@ composition_character_bounds_ = character_bounds; composition_range_ = range; if (widget_input_handler_manager_) { - widget_input_handler_manager_->GetWidgetInputHandlerHost() - ->ImeCompositionRangeChanged(composition_range_, - composition_character_bounds_); + if (mojom::WidgetInputHandlerHost* host = + widget_input_handler_manager_->GetWidgetInputHandlerHost()) { + host->ImeCompositionRangeChanged(composition_range_, + composition_character_bounds_); + } } else { Send(new InputHostMsg_ImeCompositionRangeChanged( routing_id(), composition_range_, composition_character_bounds_));
diff --git a/content/renderer/renderer_blink_platform_impl.cc b/content/renderer/renderer_blink_platform_impl.cc index 1908cdf..3cd99e1 100644 --- a/content/renderer/renderer_blink_platform_impl.cc +++ b/content/renderer/renderer_blink_platform_impl.cc
@@ -72,7 +72,6 @@ #include "content/renderer/notifications/notification_manager.h" #include "content/renderer/push_messaging/push_provider.h" #include "content/renderer/quota_dispatcher.h" -#include "content/renderer/quota_message_filter.h" #include "content/renderer/render_thread_impl.h" #include "content/renderer/storage_util.h" #include "content/renderer/web_database_observer_impl.h" @@ -294,7 +293,6 @@ ->Clone(); sync_message_filter_ = RenderThreadImpl::current()->sync_message_filter(); thread_safe_sender_ = RenderThreadImpl::current()->thread_safe_sender(); - quota_message_filter_ = RenderThreadImpl::current()->quota_message_filter(); shared_bitmap_manager_ = RenderThreadImpl::current()->shared_bitmap_manager(); blob_registry_.reset(new WebBlobRegistryImpl( @@ -1369,13 +1367,9 @@ const blink::WebURL& storage_partition, blink::WebStorageQuotaType type, blink::WebStorageQuotaCallbacks callbacks) { - if (!thread_safe_sender_.get() || !quota_message_filter_.get()) - return; - QuotaDispatcher::ThreadSpecificInstance(thread_safe_sender_.get(), - quota_message_filter_.get()) + QuotaDispatcher::ThreadSpecificInstance(default_task_runner_) ->QueryStorageUsageAndQuota( - storage_partition, - static_cast<storage::StorageType>(type), + storage_partition, static_cast<storage::StorageType>(type), QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks)); }
diff --git a/content/renderer/renderer_blink_platform_impl.h b/content/renderer/renderer_blink_platform_impl.h index 8ab5663..7264910 100644 --- a/content/renderer/renderer_blink_platform_impl.h +++ b/content/renderer/renderer_blink_platform_impl.h
@@ -64,7 +64,6 @@ class LocalStorageCachedAreas; class NotificationDispatcher; class PlatformEventObserverBase; -class QuotaMessageFilter; class ThreadSafeSender; class WebClipboardImpl; class WebDatabaseObserverImpl; @@ -326,7 +325,6 @@ scoped_refptr<base::SingleThreadTaskRunner> default_task_runner_; scoped_refptr<IPC::SyncMessageFilter> sync_message_filter_; scoped_refptr<ThreadSafeSender> thread_safe_sender_; - scoped_refptr<QuotaMessageFilter> quota_message_filter_; viz::ClientSharedBitmapManager* shared_bitmap_manager_; std::unique_ptr<WebDatabaseObserverImpl> web_database_observer_impl_;
diff --git a/content/renderer/screen_orientation/screen_orientation_dispatcher.cc b/content/renderer/screen_orientation/screen_orientation_dispatcher.cc index 94afdea..63f35a80b89 100644 --- a/content/renderer/screen_orientation/screen_orientation_dispatcher.cc +++ b/content/renderer/screen_orientation/screen_orientation_dispatcher.cc
@@ -4,8 +4,8 @@ #include "content/renderer/screen_orientation/screen_orientation_dispatcher.h" -#include "content/public/common/associated_interface_provider.h" #include "content/public/renderer/render_frame.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" namespace content {
diff --git a/content/renderer/service_worker/service_worker_context_client.cc b/content/renderer/service_worker/service_worker_context_client.cc index 420f2e8..31d16c0 100644 --- a/content/renderer/service_worker/service_worker_context_client.cc +++ b/content/renderer/service_worker/service_worker_context_client.cc
@@ -439,8 +439,6 @@ payment_response_callbacks; std::map<int, mojom::ServiceWorkerFetchResponseCallbackPtr> fetch_response_callbacks; - std::map<int, mojom::ServiceWorkerInstallEventMethodsAssociatedPtr> - install_methods_map; // Inflight navigation preload requests. base::IDMap<std::unique_ptr<NavigationPreloadRequest>> preload_requests; @@ -685,10 +683,6 @@ DCHECK(handled); } -blink::WebURL ServiceWorkerContextClient::Scope() const { - return service_worker_scope_; -} - void ServiceWorkerContextClient::GetClient( const blink::WebString& id, std::unique_ptr<blink::WebServiceWorkerClientCallbacks> callbacks) { @@ -984,12 +978,10 @@ int event_id, blink::mojom::ServiceWorkerEventStatus status, double event_dispatch_time) { - if (RunEventCallback(&context_->install_event_callbacks, - context_->timeout_timer.get(), event_id, status, - proxy_->HasFetchEventHandler(), - base::Time::FromDoubleT(event_dispatch_time))) { - context_->install_methods_map.erase(event_id); - } + RunEventCallback(&context_->install_event_callbacks, + context_->timeout_timer.get(), event_id, status, + proxy_->HasFetchEventHandler(), + base::Time::FromDoubleT(event_dispatch_time)); } void ServiceWorkerContextClient::RespondToFetchEventWithNoResponse( @@ -1262,16 +1254,6 @@ Send(new ServiceWorkerHostMsg_ClaimClients(GetRoutingID(), request_id)); } -void ServiceWorkerContextClient::RegisterForeignFetchScopes( - int install_event_id, - const blink::WebVector<blink::WebURL>& sub_scopes, - const blink::WebVector<blink::WebSecurityOrigin>& origins) { - DCHECK(context_->install_methods_map[install_event_id].is_bound()); - context_->install_methods_map[install_event_id]->RegisterForeignFetchScopes( - std::vector<GURL>(sub_scopes.begin(), sub_scopes.end()), - std::vector<url::Origin>(origins.begin(), origins.end())); -} - void ServiceWorkerContextClient::DispatchSyncEvent( const std::string& tag, blink::mojom::BackgroundSyncEventLastChance last_chance, @@ -1455,7 +1437,6 @@ } void ServiceWorkerContextClient::DispatchInstallEvent( - mojom::ServiceWorkerInstallEventMethodsAssociatedPtrInfo client, DispatchInstallEventCallback callback) { TRACE_EVENT0("ServiceWorker", "ServiceWorkerContextClient::DispatchInstallEvent"); @@ -1463,12 +1444,6 @@ int event_id = context_->timeout_timer->StartEvent( CreateInstallEventAbortCallback(&context_->install_event_callbacks)); context_->install_event_callbacks.emplace(event_id, std::move(callback)); - - DCHECK(!context_->install_methods_map.count(event_id)); - mojom::ServiceWorkerInstallEventMethodsAssociatedPtr install_methods; - install_methods.Bind(std::move(client)); - context_->install_methods_map.emplace(event_id, std::move(install_methods)); - proxy_->DispatchInstallEvent(event_id); } @@ -1536,15 +1511,9 @@ } // Dispatch the event to the service worker execution context. - const bool foreign_fetch = - request.fetch_type == ServiceWorkerFetchType::FOREIGN_FETCH; blink::WebServiceWorkerRequest web_request; ToWebServiceWorkerRequest(request, &web_request); - if (foreign_fetch) { - proxy_->DispatchForeignFetchEvent(event_id, web_request); - } else { - proxy_->DispatchFetchEvent(event_id, web_request, navigation_preload_sent); - } + proxy_->DispatchFetchEvent(event_id, web_request, navigation_preload_sent); } // S13nServiceWorker
diff --git a/content/renderer/service_worker/service_worker_context_client.h b/content/renderer/service_worker/service_worker_context_client.h index eab3099..07e243c 100644 --- a/content/renderer/service_worker/service_worker_context_client.h +++ b/content/renderer/service_worker/service_worker_context_client.h
@@ -113,7 +113,6 @@ const IPC::Message& message); // WebServiceWorkerContextClient overrides. - blink::WebURL Scope() const override; void GetClient( const blink::WebString& client_id, std::unique_ptr<blink::WebServiceWorkerClientCallbacks>) override; @@ -249,10 +248,6 @@ callbacks) override; void Claim(std::unique_ptr<blink::WebServiceWorkerClientsClaimCallbacks> callbacks) override; - void RegisterForeignFetchScopes( - int install_event_id, - const blink::WebVector<blink::WebURL>& sub_scopes, - const blink::WebVector<blink::WebSecurityOrigin>& origins) override; private: struct WorkerContextData; @@ -268,7 +263,6 @@ // mojom::ServiceWorkerEventDispatcher void DispatchInstallEvent( - mojom::ServiceWorkerInstallEventMethodsAssociatedPtrInfo client, DispatchInstallEventCallback callback) override; void DispatchActivateEvent(DispatchActivateEventCallback callback) override; void DispatchBackgroundFetchAbortEvent(
diff --git a/content/renderer/service_worker/service_worker_network_provider.cc b/content/renderer/service_worker/service_worker_network_provider.cc index ed56d66..0500acb 100644 --- a/content/renderer/service_worker/service_worker_network_provider.cc +++ b/content/renderer/service_worker/service_worker_network_provider.cc
@@ -66,18 +66,18 @@ request.SetExtraData(extra_data); // If the provider does not have a controller at this point, the renderer - // expects the request to never be handled by a controlling service worker, - // so set the ServiceWorkerMode to skip local workers here. Otherwise, a + // expects the request to never be handled by a service worker, + // so set the ServiceWorkerMode to skip service workers here. Otherwise, a // service worker that is in the process of becoming the controller (i.e., - // via claim()) on the browser-side could handle the request and break - // the assumptions of the renderer. + // via claim()) on the browser-side could handle the request and break the + // assumptions of the renderer. if (request.GetFrameType() != blink::WebURLRequest::kFrameTypeTopLevel && request.GetFrameType() != blink::WebURLRequest::kFrameTypeNested && !provider_->IsControlledByServiceWorker() && request.GetServiceWorkerMode() != blink::WebURLRequest::ServiceWorkerMode::kNone) { request.SetServiceWorkerMode( - blink::WebURLRequest::ServiceWorkerMode::kForeign); + blink::WebURLRequest::ServiceWorkerMode::kNone); } } @@ -186,14 +186,15 @@ if (service_worker_provider_id == kInvalidServiceWorkerProviderId) { network_provider = base::WrapUnique(new ServiceWorkerNetworkProvider( - route_id, SERVICE_WORKER_PROVIDER_FOR_WINDOW, GetNextProviderId(), - is_parent_frame_secure, std::move(default_loader_factory_getter))); + route_id, blink::mojom::ServiceWorkerProviderType::kForWindow, + GetNextProviderId(), is_parent_frame_secure, + std::move(default_loader_factory_getter))); } else { CHECK(browser_side_navigation); DCHECK(ServiceWorkerUtils::IsBrowserAssignedProviderId( service_worker_provider_id)); network_provider = base::WrapUnique(new ServiceWorkerNetworkProvider( - route_id, SERVICE_WORKER_PROVIDER_FOR_WINDOW, + route_id, blink::mojom::ServiceWorkerProviderType::kForWindow, service_worker_provider_id, is_parent_frame_secure, std::move(default_loader_factory_getter))); } @@ -210,8 +211,8 @@ // TODO(kinuko): Provide ChildURLLoaderFactoryGetter associated with // the SharedWorker. return base::WrapUnique(new ServiceWorkerNetworkProvider( - route_id, SERVICE_WORKER_PROVIDER_FOR_SHARED_WORKER, GetNextProviderId(), - true /* is_parent_frame_secure */, + route_id, blink::mojom::ServiceWorkerProviderType::kForSharedWorker, + GetNextProviderId(), true /* is_parent_frame_secure */, nullptr /* default_loader_factory_getter */)); } @@ -258,7 +259,7 @@ // Constructor for service worker clients. ServiceWorkerNetworkProvider::ServiceWorkerNetworkProvider( int route_id, - ServiceWorkerProviderType provider_type, + blink::mojom::ServiceWorkerProviderType provider_type, int browser_provider_id, bool is_parent_frame_secure, scoped_refptr<ChildURLLoaderFactoryGetter> default_loader_factory_getter) { @@ -267,8 +268,9 @@ // We don't support dedicated worker (WORKER) as an independent service // worker client yet. - DCHECK(provider_type == SERVICE_WORKER_PROVIDER_FOR_WINDOW || - provider_type == SERVICE_WORKER_PROVIDER_FOR_SHARED_WORKER); + DCHECK(provider_type == blink::mojom::ServiceWorkerProviderType::kForWindow || + provider_type == + blink::mojom::ServiceWorkerProviderType::kForSharedWorker); ServiceWorkerProviderHostInfo host_info( browser_provider_id, route_id, provider_type, is_parent_frame_secure); @@ -308,7 +310,8 @@ // TODO(kinuko): Split ServiceWorkerProviderContext ctor for // controller and controllee. context_ = base::MakeRefCounted<ServiceWorkerProviderContext>( - info->provider_id, SERVICE_WORKER_PROVIDER_FOR_SERVICE_WORKER, + info->provider_id, + blink::mojom::ServiceWorkerProviderType::kForServiceWorker, std::move(info->client_request), std::move(info->host_ptr_info), nullptr /* loader_factory_getter */); context_->SetRegistrationForServiceWorkerGlobalScope(
diff --git a/content/renderer/service_worker/service_worker_network_provider.h b/content/renderer/service_worker/service_worker_network_provider.h index caaa802b..e52ab07a 100644 --- a/content/renderer/service_worker/service_worker_network_provider.h +++ b/content/renderer/service_worker/service_worker_network_provider.h
@@ -17,6 +17,7 @@ #include "content/common/content_export.h" #include "content/common/service_worker/service_worker.mojom.h" #include "content/common/service_worker/service_worker_provider.mojom.h" +#include "third_party/WebKit/common/service_worker/service_worker_provider_type.mojom.h" namespace blink { class WebLocalFrame; @@ -114,7 +115,7 @@ // e.g. a frame, provides the loading factory getter for default loaders. ServiceWorkerNetworkProvider( int route_id, - ServiceWorkerProviderType type, + blink::mojom::ServiceWorkerProviderType type, int provider_id, bool is_parent_frame_secure, scoped_refptr<ChildURLLoaderFactoryGetter> default_loader_factory_getter);
diff --git a/content/renderer/service_worker/service_worker_provider_context.cc b/content/renderer/service_worker/service_worker_provider_context.cc index 46544a4..90f9474 100644 --- a/content/renderer/service_worker/service_worker_provider_context.cc +++ b/content/renderer/service_worker/service_worker_provider_context.cc
@@ -104,7 +104,7 @@ ServiceWorkerProviderContext::ServiceWorkerProviderContext( int provider_id, - ServiceWorkerProviderType provider_type, + blink::mojom::ServiceWorkerProviderType provider_type, mojom::ServiceWorkerContainerAssociatedRequest request, mojom::ServiceWorkerContainerHostAssociatedPtrInfo host_ptr_info, scoped_refptr<ChildURLLoaderFactoryGetter> default_loader_factory_getter) @@ -114,7 +114,8 @@ binding_(this, std::move(request)), weak_factory_(this) { container_host_.Bind(std::move(host_ptr_info)); - if (provider_type == SERVICE_WORKER_PROVIDER_FOR_SERVICE_WORKER) { + if (provider_type == + blink::mojom::ServiceWorkerProviderType::kForServiceWorker) { state_for_service_worker_ = std::make_unique<ProviderStateForServiceWorker>(); } else { @@ -147,7 +148,8 @@ scoped_refptr<WebServiceWorkerRegistrationImpl> ServiceWorkerProviderContext::TakeRegistrationForServiceWorkerGlobalScope( scoped_refptr<base::SingleThreadTaskRunner> io_task_runner) { - DCHECK_EQ(SERVICE_WORKER_PROVIDER_FOR_SERVICE_WORKER, provider_type_); + DCHECK_EQ(blink::mojom::ServiceWorkerProviderType::kForServiceWorker, + provider_type_); ProviderStateForServiceWorker* state = state_for_service_worker_.get(); DCHECK(state); DCHECK(state->registration); @@ -217,7 +219,8 @@ mojom::ServiceWorkerContainerHost* ServiceWorkerProviderContext::container_host() const { - DCHECK_EQ(SERVICE_WORKER_PROVIDER_FOR_WINDOW, provider_type_); + DCHECK_EQ(blink::mojom::ServiceWorkerProviderType::kForWindow, + provider_type_); return container_host_.get(); } @@ -259,7 +262,8 @@ scoped_refptr<WebServiceWorkerRegistrationImpl> ServiceWorkerProviderContext::GetOrCreateRegistrationForServiceWorkerClient( blink::mojom::ServiceWorkerRegistrationObjectInfoPtr info) { - DCHECK_EQ(SERVICE_WORKER_PROVIDER_FOR_WINDOW, provider_type_); + DCHECK_EQ(blink::mojom::ServiceWorkerProviderType::kForWindow, + provider_type_); DCHECK(state_for_client_); ServiceWorkerDispatcher* dispatcher = ServiceWorkerDispatcher::GetThreadSpecificInstance();
diff --git a/content/renderer/service_worker/service_worker_provider_context.h b/content/renderer/service_worker/service_worker_provider_context.h index fa4b2e8..843ac5f 100644 --- a/content/renderer/service_worker/service_worker_provider_context.h +++ b/content/renderer/service_worker/service_worker_provider_context.h
@@ -14,10 +14,10 @@ #include "content/common/content_export.h" #include "content/common/service_worker/service_worker_container.mojom.h" #include "content/common/service_worker/service_worker_provider.mojom.h" -#include "content/common/service_worker/service_worker_types.h" #include "content/public/renderer/child_url_loader_factory_getter.h" #include "content/renderer/service_worker/web_service_worker_provider_impl.h" #include "mojo/public/cpp/bindings/associated_binding.h" +#include "third_party/WebKit/common/service_worker/service_worker_provider_type.mojom.h" #include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerProviderClient.h" #include "third_party/WebKit/public/platform/modules/serviceworker/service_worker_object.mojom.h" #include "third_party/WebKit/public/platform/modules/serviceworker/service_worker_registration.mojom.h" @@ -67,12 +67,14 @@ // e.g. a frame, provides the default URLLoaderFactoryGetter. ServiceWorkerProviderContext( int provider_id, - ServiceWorkerProviderType provider_type, + blink::mojom::ServiceWorkerProviderType provider_type, mojom::ServiceWorkerContainerAssociatedRequest request, mojom::ServiceWorkerContainerHostAssociatedPtrInfo host_ptr_info, scoped_refptr<ChildURLLoaderFactoryGetter> default_loader_factory_getter); - ServiceWorkerProviderType provider_type() const { return provider_type_; } + blink::mojom::ServiceWorkerProviderType provider_type() const { + return provider_type_; + } int provider_id() const { return provider_id_; } @@ -202,7 +204,7 @@ void RemoveServiceWorkerRegistration(int64_t registration_id); bool ContainsServiceWorkerRegistrationForTesting(int64_t registration_id); - const ServiceWorkerProviderType provider_type_; + const blink::mojom::ServiceWorkerProviderType provider_type_; const int provider_id_; scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner_;
diff --git a/content/renderer/service_worker/service_worker_provider_context_unittest.cc b/content/renderer/service_worker/service_worker_provider_context_unittest.cc index f5857b8..5050aa4 100644 --- a/content/renderer/service_worker/service_worker_provider_context_unittest.cc +++ b/content/renderer/service_worker/service_worker_provider_context_unittest.cc
@@ -22,6 +22,7 @@ #include "ipc/ipc_test_sink.h" #include "mojo/public/cpp/bindings/associated_binding_set.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/WebKit/common/service_worker/service_worker_provider_type.mojom.h" #include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerProviderClient.h" #include "third_party/WebKit/public/platform/modules/serviceworker/service_worker_error_type.mojom.h" #include "third_party/WebKit/public/platform/modules/serviceworker/service_worker_registration.mojom.h" @@ -219,8 +220,8 @@ // Set up ServiceWorkerProviderContext for ServiceWorkerGlobalScope. const int kProviderId = 10; auto provider_context = base::MakeRefCounted<ServiceWorkerProviderContext>( - kProviderId, SERVICE_WORKER_PROVIDER_FOR_SERVICE_WORKER, nullptr, nullptr, - nullptr /* loader_factory_getter */); + kProviderId, blink::mojom::ServiceWorkerProviderType::kForServiceWorker, + nullptr, nullptr, nullptr /* loader_factory_getter */); // The passed references should be adopted and owned by the provider context. provider_context->SetRegistrationForServiceWorkerGlobalScope( @@ -258,7 +259,7 @@ mojom::ServiceWorkerContainerAssociatedRequest container_request = mojo::MakeRequestAssociatedWithDedicatedPipe(&container_ptr); auto provider_context = base::MakeRefCounted<ServiceWorkerProviderContext>( - kProviderId, SERVICE_WORKER_PROVIDER_FOR_WINDOW, + kProviderId, blink::mojom::ServiceWorkerProviderType::kForWindow, std::move(container_request), nullptr /* host_ptr_info */, nullptr /* loader_factory_getter */); @@ -296,7 +297,7 @@ mojom::ServiceWorkerContainerAssociatedRequest container_request = mojo::MakeRequestAssociatedWithDedicatedPipe(&container_ptr); auto provider_context = base::MakeRefCounted<ServiceWorkerProviderContext>( - kProviderId, SERVICE_WORKER_PROVIDER_FOR_WINDOW, + kProviderId, blink::mojom::ServiceWorkerProviderType::kForWindow, std::move(container_request), std::move(host_ptr_info), nullptr /* loader_factory_getter */); auto provider_impl = std::make_unique<WebServiceWorkerProviderImpl>( @@ -330,7 +331,7 @@ mojom::ServiceWorkerContainerAssociatedRequest container_request = mojo::MakeRequestAssociatedWithDedicatedPipe(&container_ptr); auto provider_context = base::MakeRefCounted<ServiceWorkerProviderContext>( - kProviderId, SERVICE_WORKER_PROVIDER_FOR_WINDOW, + kProviderId, blink::mojom::ServiceWorkerProviderType::kForWindow, std::move(container_request), std::move(host_ptr_info), nullptr /* loader_factory_getter */); auto provider_impl = std::make_unique<WebServiceWorkerProviderImpl>( @@ -362,7 +363,7 @@ mojom::ServiceWorkerContainerAssociatedRequest container_request = mojo::MakeRequestAssociatedWithDedicatedPipe(&container_ptr); auto provider_context = base::MakeRefCounted<ServiceWorkerProviderContext>( - kProviderId, SERVICE_WORKER_PROVIDER_FOR_WINDOW, + kProviderId, blink::mojom::ServiceWorkerProviderType::kForWindow, std::move(container_request), std::move(host_ptr_info), nullptr /* loader_factory_getter */); auto provider_impl = base::MakeUnique<WebServiceWorkerProviderImpl>( @@ -399,7 +400,7 @@ mojom::ServiceWorkerContainerAssociatedRequest container_request = mojo::MakeRequestAssociatedWithDedicatedPipe(&container_ptr); auto provider_context = base::MakeRefCounted<ServiceWorkerProviderContext>( - kProviderId, SERVICE_WORKER_PROVIDER_FOR_WINDOW, + kProviderId, blink::mojom::ServiceWorkerProviderType::kForWindow, std::move(container_request), std::move(host_ptr_info), nullptr /* loader_factory_getter */); auto provider_impl = base::MakeUnique<WebServiceWorkerProviderImpl>( @@ -428,8 +429,8 @@ // Set up ServiceWorkerProviderContext for ServiceWorkerGlobalScope. const int kProviderId = 10; auto provider_context = base::MakeRefCounted<ServiceWorkerProviderContext>( - kProviderId, SERVICE_WORKER_PROVIDER_FOR_SERVICE_WORKER, nullptr, nullptr, - nullptr /* loader_factory_getter */); + kProviderId, blink::mojom::ServiceWorkerProviderType::kForServiceWorker, + nullptr, nullptr, nullptr /* loader_factory_getter */); blink::mojom::ServiceWorkerRegistrationObjectInfoPtr info = CreateServiceWorkerRegistrationObjectInfo(); @@ -479,8 +480,8 @@ // Set up ServiceWorkerProviderContext for ServiceWorkerGlobalScope. const int kProviderId = 10; auto provider_context = base::MakeRefCounted<ServiceWorkerProviderContext>( - kProviderId, SERVICE_WORKER_PROVIDER_FOR_WINDOW, nullptr, nullptr, - nullptr /* loader_factory_getter */); + kProviderId, blink::mojom::ServiceWorkerProviderType::kForWindow, nullptr, + nullptr, nullptr /* loader_factory_getter */); { blink::mojom::ServiceWorkerRegistrationObjectInfoPtr info =
diff --git a/content/renderer/service_worker/service_worker_timeout_timer.cc b/content/renderer/service_worker/service_worker_timeout_timer.cc index 25eecd3..48edbd1 100644 --- a/content/renderer/service_worker/service_worker_timeout_timer.cc +++ b/content/renderer/service_worker/service_worker_timeout_timer.cc
@@ -47,27 +47,30 @@ ServiceWorkerTimeoutTimer::~ServiceWorkerTimeoutTimer() { // Abort all callbacks. - for (auto& it : abort_callbacks_) - std::move(it.second).Run(); + for (auto& event : inflight_events_) + std::move(event.abort_callback).Run(); }; int ServiceWorkerTimeoutTimer::StartEvent( base::OnceCallback<void(int /* event_id */)> abort_callback) { idle_time_ = base::TimeTicks(); const int event_id = NextEventId(); - - DCHECK(!base::ContainsKey(abort_callbacks_, event_id)); - abort_callbacks_[event_id] = - base::BindOnce(std::move(abort_callback), event_id); - event_timeout_times_.emplace(tick_clock_->NowTicks() + kEventTimeout, - event_id); + std::set<EventInfo>::iterator iter; + bool is_inserted; + std::tie(iter, is_inserted) = inflight_events_.emplace( + event_id, tick_clock_->NowTicks() + kEventTimeout, + base::BindOnce(std::move(abort_callback), event_id)); + DCHECK(is_inserted); + id_event_map_.emplace(event_id, iter); return event_id; } void ServiceWorkerTimeoutTimer::EndEvent(int event_id) { - DCHECK(base::ContainsKey(abort_callbacks_, event_id)); - abort_callbacks_.erase(event_id); - if (abort_callbacks_.empty()) + auto iter = id_event_map_.find(event_id); + DCHECK(iter != id_event_map_.end()); + inflight_events_.erase(iter->second); + id_event_map_.erase(iter); + if (inflight_events_.empty()) idle_time_ = tick_clock_->NowTicks() + kIdleDelay; } @@ -78,28 +81,38 @@ base::TimeTicks now = tick_clock_->NowTicks(); // Abort all events exceeding |kEventTimeout|. - while (!event_timeout_times_.empty()) { - const auto& p = event_timeout_times_.front(); - if (p.first > now) - break; - int event_id = p.second; - event_timeout_times_.pop(); - // If |event_id| is not found in |abort_callbacks_|, it means the event has - // successfully finished. - auto iter = abort_callbacks_.find(event_id); - if (iter == abort_callbacks_.end()) - continue; - base::OnceClosure callback = std::move(iter->second); - abort_callbacks_.erase(iter); + auto iter = inflight_events_.begin(); + while (iter != inflight_events_.end() && iter->expiration_time <= now) { + int event_id = iter->id; + base::OnceClosure callback = std::move(iter->abort_callback); + iter = inflight_events_.erase(iter); + id_event_map_.erase(event_id); std::move(callback).Run(); } - // If |abort_callbacks_| is empty, the worker is now idle. - if (abort_callbacks_.empty() && idle_time_.is_null()) + // If |inflight_events_| is empty, the worker is now idle. + if (inflight_events_.empty() && idle_time_.is_null()) idle_time_ = tick_clock_->NowTicks() + kIdleDelay; if (!idle_time_.is_null() && idle_time_ < now) idle_callback_.Run(); } +ServiceWorkerTimeoutTimer::EventInfo::EventInfo( + int id, + base::TimeTicks expiration_time, + base::OnceClosure abort_callback) + : id(id), + expiration_time(expiration_time), + abort_callback(std::move(abort_callback)) {} + +ServiceWorkerTimeoutTimer::EventInfo::~EventInfo() = default; + +bool ServiceWorkerTimeoutTimer::EventInfo::operator<( + const EventInfo& other) const { + if (expiration_time == other.expiration_time) + return id < other.id; + return expiration_time < other.expiration_time; +} + } // namespace content
diff --git a/content/renderer/service_worker/service_worker_timeout_timer.h b/content/renderer/service_worker/service_worker_timeout_timer.h index fad23119..be5cbe5 100644 --- a/content/renderer/service_worker/service_worker_timeout_timer.h +++ b/content/renderer/service_worker/service_worker_timeout_timer.h
@@ -6,6 +6,7 @@ #define CONTENT_RENDERER_SERVICE_WORKER_SERVICE_WORKER_TIMEOUT_TIMER_H_ #include <map> +#include <set> #include "base/callback.h" #include "base/containers/queue.h" @@ -70,14 +71,25 @@ // Updates the internal states and fires timeout callbacks if any. void UpdateStatus(); - // For event timeouts. Contains only inflight events. - std::map<int /* event_id */, base::OnceClosure> abort_callbacks_; + struct EventInfo { + EventInfo(int id, + base::TimeTicks expiration_time, + base::OnceClosure abort_callback); + ~EventInfo(); + // Compares |expiration_time|, or |id| if |expiration_time| is the same. + bool operator<(const EventInfo& other) const; - // For long standing event timeouts. Contains both inflight and settled - // events. If an |event_id| does not exist in |abort_callbacks_|, the event - // already finished successfully. - base::queue<std::pair<base::TimeTicks, int /* event_id */>> - event_timeout_times_; + const int id; + const base::TimeTicks expiration_time; + mutable base::OnceClosure abort_callback; + }; + + // For long standing event timeouts. Ordered by expiration time. + std::set<EventInfo> inflight_events_; + + // For long standing event timeouts. This is used to look up an event in + // |inflight_events_| by its id. + std::map<int /* event_id */, std::set<EventInfo>::iterator> id_event_map_; // For idle timeouts. The time the service worker started being considered // idle. This time is null if there are any inflight events.
diff --git a/content/renderer/service_worker/web_service_worker_provider_impl.cc b/content/renderer/service_worker/web_service_worker_provider_impl.cc index 78ccaf26..e97c540 100644 --- a/content/renderer/service_worker/web_service_worker_provider_impl.cc +++ b/content/renderer/service_worker/web_service_worker_provider_impl.cc
@@ -10,7 +10,6 @@ #include "base/strings/utf_string_conversions.h" #include "base/trace_event/trace_event.h" #include "content/child/thread_safe_sender.h" -#include "content/common/service_worker/service_worker_types.h" #include "content/common/service_worker/service_worker_utils.h" #include "content/renderer/service_worker/service_worker_dispatcher.h" #include "content/renderer/service_worker/service_worker_handle_reference.h" @@ -18,6 +17,7 @@ #include "content/renderer/service_worker/web_service_worker_impl.h" #include "content/renderer/service_worker/web_service_worker_registration_impl.h" #include "third_party/WebKit/common/message_port/message_port_channel.h" +#include "third_party/WebKit/common/service_worker/service_worker_provider_type.mojom.h" #include "third_party/WebKit/public/platform/WebURL.h" #include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerProviderClient.h" #include "third_party/WebKit/public/platform/modules/serviceworker/service_worker_registration.mojom.h" @@ -42,15 +42,15 @@ weak_factory_(this) { DCHECK(context_); switch (context_->provider_type()) { - case SERVICE_WORKER_PROVIDER_FOR_WINDOW: + case blink::mojom::ServiceWorkerProviderType::kForWindow: DCHECK(context_->container_host()); context_->SetWebServiceWorkerProvider(weak_factory_.GetWeakPtr()); break; - case SERVICE_WORKER_PROVIDER_FOR_SERVICE_WORKER: + case blink::mojom::ServiceWorkerProviderType::kForServiceWorker: // Do nothing. break; - case SERVICE_WORKER_PROVIDER_FOR_SHARED_WORKER: - case SERVICE_WORKER_PROVIDER_UNKNOWN: + case blink::mojom::ServiceWorkerProviderType::kForSharedWorker: + case blink::mojom::ServiceWorkerProviderType::kUnknown: NOTREACHED() << "Unimplemented type: " << context_->provider_type(); break; }
diff --git a/content/renderer/service_worker/worker_fetch_context_impl.cc b/content/renderer/service_worker/worker_fetch_context_impl.cc index 44f5e5a..da8ec85 100644 --- a/content/renderer/service_worker/worker_fetch_context_impl.cc +++ b/content/renderer/service_worker/worker_fetch_context_impl.cc
@@ -162,8 +162,10 @@ if (!IsControlledByServiceWorker() && request.GetServiceWorkerMode() != blink::WebURLRequest::ServiceWorkerMode::kNone) { + // TODO(falken): Is still this needed? It used to set kForeign for foreign + // fetch. request.SetServiceWorkerMode( - blink::WebURLRequest::ServiceWorkerMode::kForeign); + blink::WebURLRequest::ServiceWorkerMode::kNone); } }
diff --git a/content/renderer/shared_worker/embedded_shared_worker_stub.cc b/content/renderer/shared_worker/embedded_shared_worker_stub.cc index 34cbb5a..aaa0525 100644 --- a/content/renderer/shared_worker/embedded_shared_worker_stub.cc +++ b/content/renderer/shared_worker/embedded_shared_worker_stub.cc
@@ -90,7 +90,7 @@ request.SetExtraData(extra_data.release()); // If the provider does not have a controller at this point, the renderer // expects subresource requests to never be handled by a controlling service - // worker, so set the ServiceWorkerMode to skip local workers here. + // worker, so set the ServiceWorkerMode to skip service workers here. // Otherwise, a service worker that is in the process of becoming the // controller (i.e., via claim()) on the browser-side could handle the // request and break the assumptions of the renderer. @@ -100,7 +100,7 @@ request.GetServiceWorkerMode() != blink::WebURLRequest::ServiceWorkerMode::kNone) { request.SetServiceWorkerMode( - blink::WebURLRequest::ServiceWorkerMode::kForeign); + blink::WebURLRequest::ServiceWorkerMode::kNone); } }
diff --git a/content/renderer/stats_collection_controller.cc b/content/renderer/stats_collection_controller.cc index a3462ec6..ed3fc2e 100644 --- a/content/renderer/stats_collection_controller.cc +++ b/content/renderer/stats_collection_controller.cc
@@ -6,6 +6,7 @@ #include "base/json/json_writer.h" #include "base/memory/ptr_util.h" +#include "base/metrics/histogram_base.h" #include "base/metrics/histogram_macros.h" #include "base/metrics/statistics_recorder.h" #include "base/strings/string_util.h" @@ -121,7 +122,7 @@ if (!histogram) { output = "{}"; } else { - histogram->WriteJSON(&output); + histogram->WriteJSON(&output, base::JSON_VERBOSITY_LEVEL_FULL); } return output; }
diff --git a/content/renderer/webclipboard_impl_browsertest.cc b/content/renderer/webclipboard_impl_browsertest.cc index 0488510..dcf00b5 100644 --- a/content/renderer/webclipboard_impl_browsertest.cc +++ b/content/renderer/webclipboard_impl_browsertest.cc
@@ -22,7 +22,8 @@ ~WebClipboardImplTest() override = default; }; -IN_PROC_BROWSER_TEST_F(WebClipboardImplTest, PasteRTF) { +// crbug.com/789428: started to be super flaky on all bots. +IN_PROC_BROWSER_TEST_F(WebClipboardImplTest, DISABLED_PasteRTF) { BrowserTestClipboardScope clipboard; const std::string rtf_content = "{\\rtf1\\ansi Hello, {\\b world.}}";
diff --git a/content/shell/browser/layout_test/blink_test_controller.cc b/content/shell/browser/layout_test/blink_test_controller.cc index c0c3897..0aecc9c 100644 --- a/content/shell/browser/layout_test/blink_test_controller.cc +++ b/content/shell/browser/layout_test/blink_test_controller.cc
@@ -49,7 +49,6 @@ #include "content/public/browser/service_worker_context.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" -#include "content/public/common/associated_interface_provider.h" #include "content/public/common/bindings_policy.h" #include "content/public/common/content_switches.h" #include "content/public/common/url_constants.h" @@ -68,6 +67,7 @@ #include "content/shell/common/shell_messages.h" #include "content/shell/renderer/layout_test/blink_test_helpers.h" #include "content/shell/test_runner/test_common.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" #include "ui/gfx/codec/png_codec.h" #if defined(OS_MACOSX)
diff --git a/content/shell/browser/layout_test/layout_test_content_browser_client.cc b/content/shell/browser/layout_test/layout_test_content_browser_client.cc index 0b9075787..9c7c931 100644 --- a/content/shell/browser/layout_test/layout_test_content_browser_client.cc +++ b/content/shell/browser/layout_test/layout_test_content_browser_client.cc
@@ -87,7 +87,7 @@ void LayoutTestContentBrowserClient::ExposeInterfacesToRenderer( service_manager::BinderRegistry* registry, - AssociatedInterfaceRegistry* associated_registry, + blink::AssociatedInterfaceRegistry* associated_registry, RenderProcessHost* render_process_host) { scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner = content::BrowserThread::GetTaskRunnerForThread(
diff --git a/content/shell/browser/layout_test/layout_test_content_browser_client.h b/content/shell/browser/layout_test/layout_test_content_browser_client.h index 62b637b..f03fb4fc 100644 --- a/content/shell/browser/layout_test/layout_test_content_browser_client.h +++ b/content/shell/browser/layout_test/layout_test_content_browser_client.h
@@ -30,7 +30,7 @@ void RenderProcessWillLaunch(RenderProcessHost* host) override; void ExposeInterfacesToRenderer( service_manager::BinderRegistry* registry, - AssociatedInterfaceRegistry* associated_registry, + blink::AssociatedInterfaceRegistry* associated_registry, RenderProcessHost* render_process_host) override; void OverrideWebkitPrefs(RenderViewHost* render_view_host, WebPreferences* prefs) override;
diff --git a/content/shell/browser/layout_test/layout_test_javascript_dialog_manager.cc b/content/shell/browser/layout_test/layout_test_javascript_dialog_manager.cc index f32604e..7ee6a24 100644 --- a/content/shell/browser/layout_test/layout_test_javascript_dialog_manager.cc +++ b/content/shell/browser/layout_test/layout_test_javascript_dialog_manager.cc
@@ -35,6 +35,7 @@ void LayoutTestJavaScriptDialogManager::RunBeforeUnloadDialog( WebContents* web_contents, + RenderFrameHost* render_frame_host, bool is_reload, DialogClosedCallback callback) { std::move(callback).Run(true, base::string16());
diff --git a/content/shell/browser/layout_test/layout_test_javascript_dialog_manager.h b/content/shell/browser/layout_test/layout_test_javascript_dialog_manager.h index c09fe83..88973b6 100644 --- a/content/shell/browser/layout_test/layout_test_javascript_dialog_manager.h +++ b/content/shell/browser/layout_test/layout_test_javascript_dialog_manager.h
@@ -29,6 +29,7 @@ bool* did_suppress_message) override; void RunBeforeUnloadDialog(WebContents* web_contents, + RenderFrameHost* render_frame_host, bool is_reload, DialogClosedCallback callback) override;
diff --git a/content/shell/browser/shell_javascript_dialog_manager.cc b/content/shell/browser/shell_javascript_dialog_manager.cc index 606aa0c7..4594f7b 100644 --- a/content/shell/browser/shell_javascript_dialog_manager.cc +++ b/content/shell/browser/shell_javascript_dialog_manager.cc
@@ -62,6 +62,7 @@ void ShellJavaScriptDialogManager::RunBeforeUnloadDialog( WebContents* web_contents, + RenderFrameHost* render_frame_host, bool is_reload, DialogClosedCallback callback) { // During tests, if the BeforeUnload should not proceed automatically, store
diff --git a/content/shell/browser/shell_javascript_dialog_manager.h b/content/shell/browser/shell_javascript_dialog_manager.h index a0125a1..926a14d 100644 --- a/content/shell/browser/shell_javascript_dialog_manager.h +++ b/content/shell/browser/shell_javascript_dialog_manager.h
@@ -32,6 +32,7 @@ bool* did_suppress_message) override; void RunBeforeUnloadDialog(WebContents* web_contents, + RenderFrameHost* render_frame_host, bool is_reload, DialogClosedCallback callback) override;
diff --git a/content/shell/browser/shell_url_request_context_getter.cc b/content/shell/browser/shell_url_request_context_getter.cc index 4ae2996..ea95e19 100644 --- a/content/shell/browser/shell_url_request_context_getter.cc +++ b/content/shell/browser/shell_url_request_context_getter.cc
@@ -54,11 +54,11 @@ IgnoresCTPolicyEnforcer() = default; ~IgnoresCTPolicyEnforcer() override = default; - net::ct::CertPolicyCompliance DoesConformToCertPolicy( + net::ct::CTPolicyCompliance CheckCompliance( net::X509Certificate* cert, const net::SCTList& verified_scts, const net::NetLogWithSource& net_log) override { - return net::ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS; + return net::ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS; } };
diff --git a/content/shell/renderer/layout_test/layout_test_render_frame_observer.cc b/content/shell/renderer/layout_test/layout_test_render_frame_observer.cc index b4193023..764e6d7 100644 --- a/content/shell/renderer/layout_test/layout_test_render_frame_observer.cc +++ b/content/shell/renderer/layout_test/layout_test_render_frame_observer.cc
@@ -6,12 +6,12 @@ #include <string> -#include "content/public/common/associated_interface_registry.h" #include "content/public/renderer/render_frame.h" #include "content/shell/renderer/layout_test/blink_test_runner.h" #include "content/shell/renderer/layout_test/layout_test_render_thread_observer.h" #include "content/shell/test_runner/web_test_interfaces.h" #include "content/shell/test_runner/web_test_runner.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_registry.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" namespace content {
diff --git a/content/shell/test_runner/web_frame_test_client.cc b/content/shell/test_runner/web_frame_test_client.cc index 2c316d6..d3a4a7f 100644 --- a/content/shell/test_runner/web_frame_test_client.cc +++ b/content/shell/test_runner/web_frame_test_client.cc
@@ -452,7 +452,8 @@ void WebFrameTestClient::DidReceiveTitle(const blink::WebString& title, blink::WebTextDirection direction) { - if (test_runner()->shouldDumpFrameLoadCallbacks()) { + if (test_runner()->shouldDumpFrameLoadCallbacks() && + web_frame_test_proxy_base_->web_frame()) { PrintFrameDescription(delegate_, web_frame_test_proxy_base_->web_frame()); delegate_->PrintMessage(std::string(" - didReceiveTitle: ") + title.Utf8() + "\n");
diff --git a/content/test/BUILD.gn b/content/test/BUILD.gn index 3341ffd..9bfcf64 100644 --- a/content/test/BUILD.gn +++ b/content/test/BUILD.gn
@@ -272,6 +272,7 @@ configs += [ "//build/config:precompiled_headers", "//v8:external_startup_data", + "//tools/v8_context_snapshot:use_v8_context_snapshot", ] public_deps = [ @@ -284,6 +285,7 @@ "//media/mojo/interfaces", "//third_party/WebKit/public:blink", "//third_party/WebKit/public:test_support", + "//tools/v8_context_snapshot", ] deps = [ ":content_test_mojo_bindings", @@ -1395,8 +1397,6 @@ "../browser/resolve_proxy_msg_helper_unittest.cc", "../browser/screen_orientation/screen_orientation_provider_unittest.cc", "../browser/service_worker/embedded_worker_instance_unittest.cc", - "../browser/service_worker/foreign_fetch_request_handler_unittest.cc", - "../browser/service_worker/link_header_support_unittest.cc", "../browser/service_worker/service_worker_cache_writer_unittest.cc", "../browser/service_worker/service_worker_context_core_unittest.cc", "../browser/service_worker/service_worker_context_request_handler_unittest.cc",
diff --git a/content/test/content_test_launcher.cc b/content/test/content_test_launcher.cc index de5ba9ed..ed97d02 100644 --- a/content/test/content_test_launcher.cc +++ b/content/test/content_test_launcher.cc
@@ -22,6 +22,8 @@ #include "content/shell/common/shell_switches.h" #include "media/base/media_switches.h" #include "testing/gtest/include/gtest/gtest.h" +#include "ui/base/ui_base_switches.h" +#include "ui/base/ui_features.h" #ifdef V8_USE_EXTERNAL_STARTUP_DATA #include "gin/v8_initializer.h" @@ -50,6 +52,12 @@ public: ContentBrowserTestSuite(int argc, char** argv) : ContentTestSuiteBase(argc, argv) { +#if BUILDFLAG(ENABLE_MUS) + // TODO(786453): This should be removed once mus can run without viz. + auto* cmd = base::CommandLine::ForCurrentProcess(); + if (cmd->HasSwitch(switches::kMus)) + cmd->AppendSwitchASCII(switches::kMus, switches::kMusHostVizValue); +#endif } ~ContentBrowserTestSuite() override {}
diff --git a/content/test/data/accessibility/html/absolute-offscreen-expected-blink.txt b/content/test/data/accessibility/html/absolute-offscreen-expected-blink.txt new file mode 100644 index 0000000..0033ca1 --- /dev/null +++ b/content/test/data/accessibility/html/absolute-offscreen-expected-blink.txt
@@ -0,0 +1,12 @@ +rootWebArea clipsChildren=true +++genericContainer size=(0, 0) +++++staticText name='Visible' +++++++inlineTextBox name='Visible' +++genericContainer size=(0, 0) clipsChildren=true +++++staticText offscreen name='Invisible' +++++++inlineTextBox offscreen name='Invisible' +++genericContainer clipsChildren=true +++++genericContainer offscreen +++++++staticText offscreen name='Invisible' +++++++++inlineTextBox offscreen name='Invisible' +<-- End-of-file --> \ No newline at end of file
diff --git a/content/test/data/accessibility/html/absolute-offscreen.html b/content/test/data/accessibility/html/absolute-offscreen.html new file mode 100644 index 0000000..e94ae95 --- /dev/null +++ b/content/test/data/accessibility/html/absolute-offscreen.html
@@ -0,0 +1,26 @@ +<!-- +@BLINK-ALLOW:offscreen +@BLINK-ALLOW:size=(0, 0) +@BLINK-ALLOW:clipsChildren* +--> +<html> + <body> + <!-- This is like Google Docs visible doc contents --> + <div style="position: absolute; width: 0; height: 0; overflow: visible"> + <span>Visible</span> + </div> + + <!-- This is like a hidden gmail button only for screenreaders --> + <div style="position: absolute; height: 0; width: 0; overflow: hidden;"> + <span>Invisible</span> + </div> + + <!-- If overflow is hidden, should clip its relatively-positioned children --> + <div style="width: 100px; height: 100px; overflow: hidden"> + <div style="position: relative; top: 200px"> + Invisible + </div> + </div> + +</body> +</html>
diff --git a/content/test/test_blink_web_unit_test_support.cc b/content/test/test_blink_web_unit_test_support.cc index 1ff214a..cb545a4 100644 --- a/content/test/test_blink_web_unit_test_support.cc +++ b/content/test/test_blink_web_unit_test_support.cc
@@ -129,11 +129,15 @@ url_loader_factory_ = blink::WebURLLoaderMockFactory::Create(); mock_clipboard_.reset(new MockWebClipboardImpl()); -#ifdef V8_USE_EXTERNAL_STARTUP_DATA +#if defined(V8_USE_EXTERNAL_STARTUP_DATA) gin::V8Initializer::LoadV8Snapshot(); gin::V8Initializer::LoadV8Natives(); #endif +#if defined(USE_V8_CONTEXT_SNAPSHOT) + gin::V8Initializer::LoadV8ContextSnapshot(); +#endif + scoped_refptr<base::SingleThreadTaskRunner> dummy_task_runner; std::unique_ptr<base::ThreadTaskRunnerHandle> dummy_task_runner_handle; if (!base::ThreadTaskRunnerHandle::IsSet()) {
diff --git a/content/test/test_render_frame.cc b/content/test/test_render_frame.cc index 09085c7..60b3802 100644 --- a/content/test/test_render_frame.cc +++ b/content/test/test_render_frame.cc
@@ -8,11 +8,11 @@ #include "base/threading/thread_task_runner_handle.h" #include "content/common/frame_messages.h" #include "content/common/navigation_params.h" -#include "content/public/common/associated_interface_provider.h" #include "content/public/common/browser_side_navigation_policy.h" #include "content/public/common/resource_response.h" #include "content/public/test/mock_render_thread.h" #include "content/renderer/loader/web_url_loader_impl.h" +#include "third_party/WebKit/common/associated_interfaces/associated_interface_provider.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" namespace content {
diff --git a/dbus/bus.cc b/dbus/bus.cc index 76c9612..e62058e 100644 --- a/dbus/bus.cc +++ b/dbus/bus.cc
@@ -151,8 +151,7 @@ connection_type(PRIVATE) { } -Bus::Options::~Options() { -} +Bus::Options::~Options() = default; Bus::Bus(const Options& options) : bus_type_(options.bus_type),
diff --git a/dbus/bus_unittest.cc b/dbus/bus_unittest.cc index 71101e6..f8dfa33 100644 --- a/dbus/bus_unittest.cc +++ b/dbus/bus_unittest.cc
@@ -30,7 +30,7 @@ class RunLoopWithExpectedCount { public: RunLoopWithExpectedCount() : expected_quit_calls_(0), actual_quit_calls_(0) {} - ~RunLoopWithExpectedCount() {} + ~RunLoopWithExpectedCount() = default; void Run(int expected_quit_calls) { DCHECK_EQ(0, expected_quit_calls_);
diff --git a/dbus/dbus_statistics_unittest.cc b/dbus/dbus_statistics_unittest.cc index e39b9b5..164d0b3 100644 --- a/dbus/dbus_statistics_unittest.cc +++ b/dbus/dbus_statistics_unittest.cc
@@ -12,8 +12,7 @@ class DBusStatisticsTest : public testing::Test { public: - DBusStatisticsTest() { - } + DBusStatisticsTest() = default; void SetUp() override { statistics::Initialize(); }
diff --git a/dbus/end_to_end_async_unittest.cc b/dbus/end_to_end_async_unittest.cc index d96ebda..0e2f4a7c 100644 --- a/dbus/end_to_end_async_unittest.cc +++ b/dbus/end_to_end_async_unittest.cc
@@ -589,8 +589,7 @@ class SignalMultipleHandlerTest : public EndToEndAsyncTest { public: - SignalMultipleHandlerTest() { - } + SignalMultipleHandlerTest() = default; void SetUp() override { // Set up base class.
diff --git a/dbus/end_to_end_sync_unittest.cc b/dbus/end_to_end_sync_unittest.cc index d0dafcc..0bc146f 100644 --- a/dbus/end_to_end_sync_unittest.cc +++ b/dbus/end_to_end_sync_unittest.cc
@@ -19,8 +19,7 @@ // operations (i.e. ExportedObject side). class EndToEndSyncTest : public testing::Test { public: - EndToEndSyncTest() { - } + EndToEndSyncTest() = default; void SetUp() override { // Start the test service;
diff --git a/dbus/message.cc b/dbus/message.cc index ec0b2234..13f3235 100644 --- a/dbus/message.cc +++ b/dbus/message.cc
@@ -446,8 +446,7 @@ dbus_message_iter_init_append(message_->raw_message(), &raw_message_iter_); } -MessageWriter::~MessageWriter() { -} +MessageWriter::~MessageWriter() = default; void MessageWriter::AppendByte(uint8_t value) { AppendBasic(DBUS_TYPE_BYTE, &value); @@ -716,9 +715,7 @@ dbus_message_iter_init(message_->raw_message(), &raw_message_iter_); } - -MessageReader::~MessageReader() { -} +MessageReader::~MessageReader() = default; bool MessageReader::HasMoreData() { const int dbus_type = dbus_message_iter_get_arg_type(&raw_message_iter_);
diff --git a/dbus/mock_bus.cc b/dbus/mock_bus.cc index 9e76454..30cffb0 100644 --- a/dbus/mock_bus.cc +++ b/dbus/mock_bus.cc
@@ -11,7 +11,6 @@ MockBus::MockBus(const Bus::Options& options) : Bus(options) { } -MockBus::~MockBus() { -} +MockBus::~MockBus() = default; } // namespace dbus
diff --git a/dbus/mock_exported_object.cc b/dbus/mock_exported_object.cc index ff507dd..f8a6703 100644 --- a/dbus/mock_exported_object.cc +++ b/dbus/mock_exported_object.cc
@@ -11,7 +11,6 @@ : ExportedObject(bus, object_path) { } -MockExportedObject::~MockExportedObject() { -} +MockExportedObject::~MockExportedObject() = default; } // namespace dbus
diff --git a/dbus/mock_object_manager.cc b/dbus/mock_object_manager.cc index dcba78e..3f0c0a1 100644 --- a/dbus/mock_object_manager.cc +++ b/dbus/mock_object_manager.cc
@@ -12,7 +12,6 @@ : ObjectManager(bus, service_name, object_path) { } -MockObjectManager::~MockObjectManager() { -} +MockObjectManager::~MockObjectManager() = default; } // namespace dbus
diff --git a/dbus/mock_object_proxy.cc b/dbus/mock_object_proxy.cc index a1fe0bd..4929486 100644 --- a/dbus/mock_object_proxy.cc +++ b/dbus/mock_object_proxy.cc
@@ -12,8 +12,7 @@ : ObjectProxy(bus, service_name, object_path, DEFAULT_OPTIONS) { } -MockObjectProxy::~MockObjectProxy() { -} +MockObjectProxy::~MockObjectProxy() = default; void MockObjectProxy::CallMethod(MethodCall* method_call, int timeout_ms,
diff --git a/dbus/mock_unittest.cc b/dbus/mock_unittest.cc index f7540ec..34327cd 100644 --- a/dbus/mock_unittest.cc +++ b/dbus/mock_unittest.cc
@@ -28,8 +28,7 @@ class MockTest : public testing::Test { public: - MockTest() { - } + MockTest() = default; void SetUp() override { // Create a mock bus.
diff --git a/dbus/object_manager.cc b/dbus/object_manager.cc index 5ba5c8d..90d7337 100644 --- a/dbus/object_manager.cc +++ b/dbus/object_manager.cc
@@ -26,8 +26,7 @@ : object_proxy(nullptr) { } -ObjectManager::Object::~Object() { -} +ObjectManager::Object::~Object() = default; ObjectManager::ObjectManager(Bus* bus, const std::string& service_name,
diff --git a/dbus/property.cc b/dbus/property.cc index dd3df26..4197589 100644 --- a/dbus/property.cc +++ b/dbus/property.cc
@@ -23,7 +23,7 @@ PropertyBase::PropertyBase() : property_set_(nullptr), is_valid_(false) {} -PropertyBase::~PropertyBase() {} +PropertyBase::~PropertyBase() = default; void PropertyBase::Init(PropertySet* property_set, const std::string& name) { DCHECK(!property_set_); @@ -45,8 +45,7 @@ property_changed_callback_(property_changed_callback), weak_ptr_factory_(this) {} -PropertySet::~PropertySet() { -} +PropertySet::~PropertySet() = default; void PropertySet::RegisterProperty(const std::string& name, PropertyBase* property) {
diff --git a/dbus/property_unittest.cc b/dbus/property_unittest.cc index 9d2c3a2..6c381bb 100644 --- a/dbus/property_unittest.cc +++ b/dbus/property_unittest.cc
@@ -31,7 +31,7 @@ // Property<>. class PropertyTest : public testing::Test { public: - PropertyTest() {} + PropertyTest() = default; struct Properties : public PropertySet { Property<std::string> name;
diff --git a/dbus/test_service.cc b/dbus/test_service.cc index 238d6418..624495de 100644 --- a/dbus/test_service.cc +++ b/dbus/test_service.cc
@@ -40,8 +40,7 @@ : request_ownership_options(Bus::REQUIRE_PRIMARY) { } -TestService::Options::~Options() { -} +TestService::Options::~Options() = default; TestService::TestService(const Options& options) : base::Thread("TestService"),
diff --git a/device/vr/openvr/openvr_render_loop.cc b/device/vr/openvr/openvr_render_loop.cc index 788962d..2b5e3ca6 100644 --- a/device/vr/openvr/openvr_render_loop.cc +++ b/device/vr/openvr/openvr_render_loop.cc
@@ -46,7 +46,8 @@ texture_helper_.SetSourceTexture( base::win::ScopedHandle(reinterpret_cast<HANDLE>(platform_handle.value))); texture_helper_.AllocateBackBuffer(); - if (texture_helper_.CopyTextureToBackBuffer(true)) { + bool copy_successful = texture_helper_.CopyTextureToBackBuffer(true); + if (copy_successful) { vr::Texture_t texture; texture.handle = texture_helper_.GetBackbuffer().Get(); texture.eType = vr::TextureType_DirectX; @@ -72,11 +73,11 @@ return; } vr_compositor_->PostPresentHandoff(); - - // Tell WebVR that we are done with the texture. - submit_client_->OnSubmitFrameTransferred(); - submit_client_->OnSubmitFrameRendered(); } + + // Tell WebVR that we are done with the texture. + submit_client_->OnSubmitFrameTransferred(copy_successful); + submit_client_->OnSubmitFrameRendered(); #endif }
diff --git a/device/vr/vr_service.mojom b/device/vr/vr_service.mojom index 0ebc0422..4c17f7a 100644 --- a/device/vr/vr_service.mojom +++ b/device/vr/vr_service.mojom
@@ -81,8 +81,27 @@ VRDisplayInfo display_info); }; +// After submitting a frame, the VRPresentationProvider will notify the client +// about several stages of the render pipeline. This allows pipelining +// efficiency. Following VRPresentationProvider::Submit*, the submitted frame +// will be transferred (read from, perhaps copied to another texture), and then +// rendered (submitted to the underlying VR API). +// The client lives in the render process, implemented by VRDisplay. interface VRSubmitFrameClient { - OnSubmitFrameTransferred(); + // The VRPresentationProvider calls this to indicate that the submitted frame + // has been transferred, so the backing data (mailbox or GpuMemoryBuffer) can + // be reused or discarded. Note that this is a convenience/optimization + // feature, not a security feature - if a site discards the data early we may + // drop a frame, but nothing will otherwise misbehave. + // When the frame wasn't successfully transferred, the client should create a + // new mailbox/GpuMemoryBuffer rather than reusing an existing one to recover + // for subsequent frames. + OnSubmitFrameTransferred(bool success); + + // The VRPresentationProvider calls this after the frame was handed off to the + // underlying VR API. This allows some pipelining of CPU/GPU work, while + // delaying expensive tasks for a subsequent frame until the current frame has + // completed. OnSubmitFrameRendered(); };
diff --git a/extensions/browser/api/BUILD.gn b/extensions/browser/api/BUILD.gn index 9b1b2a7..9262eb3 100644 --- a/extensions/browser/api/BUILD.gn +++ b/extensions/browser/api/BUILD.gn
@@ -123,6 +123,7 @@ "lock_screen_data/operation_result.h", "media_perception_private/conversion_utils.cc", "media_perception_private/conversion_utils.h", + "media_perception_private/media_perception_api_delegate.h", "media_perception_private/media_perception_api_manager.cc", "media_perception_private/media_perception_api_manager.h", "media_perception_private/media_perception_private_api.cc",
diff --git a/extensions/browser/api/cast_channel/cast_channel_api.cc b/extensions/browser/api/cast_channel/cast_channel_api.cc index 79d00c5..987e946 100644 --- a/extensions/browser/api/cast_channel/cast_channel_api.cc +++ b/extensions/browser/api/cast_channel/cast_channel_api.cc
@@ -19,6 +19,7 @@ #include "base/strings/string_number_conversions.h" #include "base/values.h" #include "components/cast_channel/cast_channel_enum.h" +#include "components/cast_channel/cast_channel_util.h" #include "components/cast_channel/cast_message_util.h" #include "components/cast_channel/cast_socket.h" #include "components/cast_channel/cast_socket_service.h" @@ -110,8 +111,7 @@ } bool IsValidConnectInfoIpAddress(const ConnectInfo& connect_info) { - net::IPAddress ip_address; - return ip_address.AssignFromIPLiteral(connect_info.ip_address); + return cast_channel::IsValidCastIPAddressString(connect_info.ip_address); } } // namespace
diff --git a/extensions/browser/api/extensions_api_client.cc b/extensions/browser/api/extensions_api_client.cc index 0a46302..66f7708 100644 --- a/extensions/browser/api/extensions_api_client.cc +++ b/extensions/browser/api/extensions_api_client.cc
@@ -133,6 +133,11 @@ return nullptr; } +MediaPerceptionAPIDelegate* +ExtensionsAPIClient::GetMediaPerceptionAPIDelegate() { + return nullptr; +} + void ExtensionsAPIClient::SaveImageDataToClipboard( const std::vector<char>& image_data, api::clipboard::ImageType type,
diff --git a/extensions/browser/api/extensions_api_client.h b/extensions/browser/api/extensions_api_client.h index 6b49616..f9ce48e 100644 --- a/extensions/browser/api/extensions_api_client.h +++ b/extensions/browser/api/extensions_api_client.h
@@ -42,6 +42,7 @@ class FeedbackPrivateDelegate; class FileSystemDelegate; class ManagementAPIDelegate; +class MediaPerceptionAPIDelegate; class MessagingDelegate; class MetricsPrivateDelegate; class MimeHandlerViewGuest; @@ -162,6 +163,10 @@ // file systems. virtual NonNativeFileSystemDelegate* GetNonNativeFileSystemDelegate(); + // Returns a delegate for embedder-specific chrome.mediaPerceptionPrivate API + // behavior. + virtual MediaPerceptionAPIDelegate* GetMediaPerceptionAPIDelegate(); + // Saves image data on clipboard. virtual void SaveImageDataToClipboard( const std::vector<char>& image_data,
diff --git a/extensions/browser/api/feedback_private/feedback_private_api.cc b/extensions/browser/api/feedback_private/feedback_private_api.cc index 1ad0b20..4cb484c 100644 --- a/extensions/browser/api/feedback_private/feedback_private_api.cc +++ b/extensions/browser/api/feedback_private/feedback_private_api.cc
@@ -12,6 +12,7 @@ #include "base/logging.h" #include "base/macros.h" #include "base/memory/ptr_util.h" +#include "base/metrics/histogram_base.h" #include "base/metrics/statistics_recorder.h" #include "base/metrics/user_metrics.h" #include "base/strings/string_number_conversions.h" @@ -294,7 +295,8 @@ if (feedback_info.send_histograms) { auto histograms = std::make_unique<std::string>(); - *histograms = base::StatisticsRecorder::ToJSON(std::string()); + *histograms = + base::StatisticsRecorder::ToJSON(base::JSON_VERBOSITY_LEVEL_FULL); if (!histograms->empty()) feedback_data->SetAndCompressHistograms(std::move(histograms)); }
diff --git a/extensions/browser/api/feedback_private/feedback_private_api_unittest_base_chromeos.cc b/extensions/browser/api/feedback_private/feedback_private_api_unittest_base_chromeos.cc index 982b428..1b82a15 100644 --- a/extensions/browser/api/feedback_private/feedback_private_api_unittest_base_chromeos.cc +++ b/extensions/browser/api/feedback_private/feedback_private_api_unittest_base_chromeos.cc
@@ -4,6 +4,8 @@ #include "extensions/browser/api/feedback_private/feedback_private_api_unittest_base_chromeos.h" +#include <memory> + #include "base/bind.h" #include "base/bind_helpers.h" #include "base/location.h" @@ -51,14 +53,14 @@ DCHECK_GT(result.size(), 0U); ++call_count_; - SystemLogsResponse* result_map = new SystemLogsResponse; + auto result_map = std::make_unique<SystemLogsResponse>(); result_map->emplace("", result); // Do not directly pass the result to the callback, because that's not how // log sources actually work. Instead, simulate the asynchronous operation // of a SystemLogsSource by invoking the callback separately. base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::BindOnce(callback, base::Owned(result_map))); + FROM_HERE, base::BindOnce(callback, std::move(result_map))); } private:
diff --git a/extensions/browser/api/feedback_private/log_source_access_manager.cc b/extensions/browser/api/feedback_private/log_source_access_manager.cc index 0bf2729..70c29ad 100644 --- a/extensions/browser/api/feedback_private/log_source_access_manager.cc +++ b/extensions/browser/api/feedback_private/log_source_access_manager.cc
@@ -115,7 +115,7 @@ ResourceId resource_id, bool delete_resource, const ReadLogSourceCallback& callback, - SystemLogsResponse* response) { + std::unique_ptr<SystemLogsResponse> response) { ReadLogSourceResult result; // Always return invalid resource ID if there is a cleanup. result.reader_id = delete_resource ? kInvalidResourceId : resource_id;
diff --git a/extensions/browser/api/feedback_private/log_source_access_manager.h b/extensions/browser/api/feedback_private/log_source_access_manager.h index 375a57d..78a4ca5 100644 --- a/extensions/browser/api/feedback_private/log_source_access_manager.h +++ b/extensions/browser/api/feedback_private/log_source_access_manager.h
@@ -105,11 +105,12 @@ // struct. // - response: Contains the result from an operation to fetch from system // log(s). - void OnFetchComplete(const std::string& extension_id, - ResourceId resource_id, - bool delete_source, - const ReadLogSourceCallback& callback, - system_logs::SystemLogsResponse* response); + void OnFetchComplete( + const std::string& extension_id, + ResourceId resource_id, + bool delete_source, + const ReadLogSourceCallback& callback, + std::unique_ptr<system_logs::SystemLogsResponse> response); // Removes an existing log source handle indicated by |id| from // |open_handles_|.
diff --git a/extensions/browser/api/media_perception_private/conversion_utils.cc b/extensions/browser/api/media_perception_private/conversion_utils.cc index e43c2a01..e222a4da 100644 --- a/extensions/browser/api/media_perception_private/conversion_utils.cc +++ b/extensions/browser/api/media_perception_private/conversion_utils.cc
@@ -77,6 +77,8 @@ return ENTITY_TYPE_PERSON; case mri::Entity::MOTION_REGION: return ENTITY_TYPE_MOTION_REGION; + case mri::Entity::LABELED_REGION: + return ENTITY_TYPE_LABELED_REGION; case mri::Entity::UNSPECIFIED: return ENTITY_TYPE_UNSPECIFIED; } @@ -100,9 +102,29 @@ if (entity.has_depth()) entity_result.depth = DistanceProtoToIdl(entity.depth()); + if (entity.has_label()) + entity_result.entity_label = std::make_unique<std::string>(entity.label()); + return entity_result; } +PacketLatency PacketLatencyProtoToIdl( + const mri::PacketLatency& packet_latency) { + PacketLatency packet_latency_result; + + if (packet_latency.has_label()) { + packet_latency_result.packet_label = + std::make_unique<std::string>(packet_latency.label()); + } + + if (packet_latency.has_latency_usec()) { + packet_latency_result.latency_usec = + std::make_unique<int>(packet_latency.latency_usec()); + } + + return packet_latency_result; +} + FramePerception FramePerceptionProtoToIdl( const mri::FramePerception& frame_perception) { FramePerception frame_perception_result; @@ -127,6 +149,14 @@ for (const auto& entity : frame_perception.entity()) frame_perception_result.entities->emplace_back(EntityProtoToIdl(entity)); } + if (frame_perception.packet_latency_size() > 0) { + frame_perception_result.packet_latency = + std::make_unique<std::vector<PacketLatency>>(); + for (const auto& packet_latency : frame_perception.packet_latency()) { + frame_perception_result.packet_latency->emplace_back( + PacketLatencyProtoToIdl(packet_latency)); + } + } return frame_perception_result; } @@ -196,6 +226,8 @@ return STATUS_SUSPENDED; case mri::State::RESTARTING: return STATUS_RESTARTING; + case mri::State::STOPPED: + return STATUS_STOPPED; case mri::State::STATUS_UNSPECIFIED: return STATUS_NONE; } @@ -215,8 +247,9 @@ return mri::State::SUSPENDED; case STATUS_RESTARTING: return mri::State::RESTARTING; - case STATUS_SERVICE_ERROR: case STATUS_STOPPED: // Process is stopped by MPP. + return mri::State::STOPPED; + case STATUS_SERVICE_ERROR: case STATUS_NONE: return mri::State::STATUS_UNSPECIFIED; }
diff --git a/extensions/browser/api/media_perception_private/conversion_utils_unittest.cc b/extensions/browser/api/media_perception_private/conversion_utils_unittest.cc index f1d8800..4b7f4ec 100644 --- a/extensions/browser/api/media_perception_private/conversion_utils_unittest.cc +++ b/extensions/browser/api/media_perception_private/conversion_utils_unittest.cc
@@ -15,6 +15,9 @@ namespace { const char kTestDeviceContext[] = "Video camera"; +const char kFakePacketLabel1[] = "Packet1"; +const char kFakePacketLabel3[] = "Packet3"; +const char kFakeEntityLabel3[] = "Region3"; void InitializeFakeFramePerception(const int index, mri::FramePerception* frame_perception) { @@ -23,6 +26,20 @@ frame_perception->set_frame_height_in_px(4); frame_perception->set_timestamp(5); + // Add a couple fake packet latency to the frame perception. + mri::PacketLatency* packet_latency_one = + frame_perception->add_packet_latency(); + packet_latency_one->set_label(kFakePacketLabel1); + packet_latency_one->set_latency_usec(10011); + + mri::PacketLatency* packet_latency_two = + frame_perception->add_packet_latency(); + packet_latency_two->set_latency_usec(20011); + + mri::PacketLatency* packet_latency_three = + frame_perception->add_packet_latency(); + packet_latency_three->set_label(kFakePacketLabel3); + // Add a couple fake entities to the frame perception. Note: PERSON // EntityType is currently unused. mri::Entity* entity_one = frame_perception->add_entity(); @@ -50,6 +67,10 @@ bounding_box_two->mutable_top_left()->set_x(14); bounding_box_two->mutable_top_left()->set_y(15); bounding_box_two->set_normalized(true); + + mri::Entity* entity_three = frame_perception->add_entity(); + entity_three->set_type(mri::Entity::LABELED_REGION); + entity_three->set_label(kFakeEntityLabel3); } void ValidateFramePerceptionResult( @@ -64,7 +85,25 @@ ASSERT_TRUE(frame_perception_result.timestamp); EXPECT_EQ(*frame_perception_result.timestamp, 5); - ASSERT_EQ(2u, frame_perception_result.entities->size()); + // Validate packet latency. + ASSERT_EQ(3u, frame_perception_result.packet_latency->size()); + const media_perception::PacketLatency& packet_latency_one = + frame_perception_result.packet_latency->at(0); + EXPECT_EQ(*packet_latency_one.packet_label, kFakePacketLabel1); + EXPECT_EQ(*packet_latency_one.latency_usec, 10011); + + const media_perception::PacketLatency& packet_latency_two = + frame_perception_result.packet_latency->at(1); + EXPECT_FALSE(packet_latency_two.packet_label); + EXPECT_EQ(*packet_latency_two.latency_usec, 20011); + + const media_perception::PacketLatency& packet_latency_three = + frame_perception_result.packet_latency->at(2); + EXPECT_EQ(*packet_latency_three.packet_label, kFakePacketLabel3); + EXPECT_FALSE(packet_latency_three.latency_usec); + + // Validate entities. + ASSERT_EQ(3u, frame_perception_result.entities->size()); const media_perception::Entity& entity_result_one = frame_perception_result.entities->at(0); ASSERT_TRUE(entity_result_one.id); @@ -111,6 +150,13 @@ EXPECT_EQ(*bounding_box_result_two->top_left->y, 15); EXPECT_FALSE(bounding_box_result_two->bottom_right); EXPECT_TRUE(*bounding_box_result_two->normalized); + + const media_perception::Entity& entity_result_three = + frame_perception_result.entities->at(2); + ASSERT_TRUE(entity_result_three.entity_label); + EXPECT_EQ(*entity_result_three.entity_label, kFakeEntityLabel3); + EXPECT_EQ(entity_result_three.type, + media_perception::ENTITY_TYPE_LABELED_REGION); } void InitializeFakeImageFrameData(mri::ImageFrame* image_frame) { @@ -206,6 +252,10 @@ state.set_status(mri::State::RESTARTING); state_result = media_perception::StateProtoToIdl(state); EXPECT_EQ(state_result.status, media_perception::STATUS_RESTARTING); + + state.set_status(mri::State::STOPPED); + state_result = media_perception::StateProtoToIdl(state); + EXPECT_EQ(state_result.status, media_perception::STATUS_STOPPED); } TEST(MediaPerceptionConversionUtilsTest, StateIdlToProto) { @@ -227,7 +277,7 @@ state.status = media_perception::STATUS_STOPPED; state_proto = StateIdlToProto(state); - EXPECT_EQ(mri::State::STATUS_UNSPECIFIED, state_proto.status()); + EXPECT_EQ(mri::State::STOPPED, state_proto.status()); } } // namespace extensions
diff --git a/extensions/browser/api/media_perception_private/media_perception_api_delegate.h b/extensions/browser/api/media_perception_private/media_perception_api_delegate.h new file mode 100644 index 0000000..69d29ce --- /dev/null +++ b/extensions/browser/api/media_perception_private/media_perception_api_delegate.h
@@ -0,0 +1,32 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef EXTENSIONS_BROWSER_API_MEDIA_PERCEPTION_PRIVATE_MEDIA_PERCEPTION_API_DELEGATE_H_ +#define EXTENSIONS_BROWSER_API_MEDIA_PERCEPTION_PRIVATE_MEDIA_PERCEPTION_API_DELEGATE_H_ + +#include "base/callback.h" +#include "extensions/common/api/media_perception_private.h" + +namespace extensions { + +class MediaPerceptionAPIDelegate { + public: + // Callback for loading a CrOS component. |mount_point| will contain a path to + // the loaded component, if installation succeeded. If the component failed to + // install, |mount_point| will be empty. + using LoadCrOSComponentCallback = + base::OnceCallback<void(const std::string& mount_point)>; + + virtual ~MediaPerceptionAPIDelegate() {} + + // Provides an interface through which a media analytics Chrome OS component + // from Component Updater can be loaded and mounted on a device. + virtual void LoadCrOSComponent( + const api::media_perception_private::ComponentType& type, + LoadCrOSComponentCallback load_callback) = 0; +}; + +} // namespace extensions + +#endif // EXTENSIONS_BROWSER_API_MEDIA_PERCEPTION_PRIVATE_MEDIA_PERCEPTION_API_DELEGATE_H_
diff --git a/extensions/browser/api/media_perception_private/media_perception_api_manager.cc b/extensions/browser/api/media_perception_private/media_perception_api_manager.cc index 0729f07..359b63d 100644 --- a/extensions/browser/api/media_perception_private/media_perception_api_manager.cc +++ b/extensions/browser/api/media_perception_private/media_perception_api_manager.cc
@@ -8,7 +8,9 @@ #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/media_analytics_client.h" #include "chromeos/dbus/upstart_client.h" +#include "extensions/browser/api/extensions_api_client.h" #include "extensions/browser/api/media_perception_private/conversion_utils.h" +#include "extensions/browser/api/media_perception_private/media_perception_api_delegate.h" #include "extensions/browser/event_router.h" #include "extensions/browser/extension_function.h" @@ -33,6 +35,13 @@ return diagnostics; } +media_perception::ComponentState GetComponentStateForComponentStatus( + const media_perception::ComponentStatus status) { + media_perception::ComponentState component_state; + component_state.status = status; + return component_state; +} + } // namespace // static @@ -82,7 +91,8 @@ return; } - if (analytics_process_state_ == AnalyticsProcessState::LAUNCHING) { + if (analytics_process_state_ == + AnalyticsProcessState::CHANGING_PROCESS_STATE) { callback.Run(GetStateForServiceError( media_perception::SERVICE_ERROR_SERVICE_BUSY_LAUNCHING)); return; @@ -94,25 +104,82 @@ callback.Run(std::move(state_uninitialized)); } +void MediaPerceptionAPIManager::SetAnalyticsComponent( + const media_perception::Component& component, + APISetAnalyticsComponentCallback callback) { + if (analytics_process_state_ != AnalyticsProcessState::IDLE) { + LOG(WARNING) << "Analytics process is not STOPPED."; + std::move(callback).Run(GetComponentStateForComponentStatus( + media_perception::COMPONENT_STATUS_FAILED_TO_INSTALL)); + return; + } + + MediaPerceptionAPIDelegate* delegate = + ExtensionsAPIClient::Get()->GetMediaPerceptionAPIDelegate(); + if (!delegate) { + LOG(WARNING) << "Could not get MediaPerceptionAPIDelegate."; + std::move(callback).Run(GetComponentStateForComponentStatus( + media_perception::COMPONENT_STATUS_FAILED_TO_INSTALL)); + return; + } + + delegate->LoadCrOSComponent( + component.type, + base::BindOnce(&MediaPerceptionAPIManager::LoadComponentCallback, + weak_ptr_factory_.GetWeakPtr(), std::move(callback))); +} + +void MediaPerceptionAPIManager::LoadComponentCallback( + APISetAnalyticsComponentCallback callback, + const std::string& mount_point) { + media_perception::ComponentState component_state; + if (mount_point.empty()) { + component_state.status = + media_perception::COMPONENT_STATUS_FAILED_TO_INSTALL; + std::move(callback).Run(std::move(component_state)); + return; + } + + // If the new component is loaded, override the mount point. + mount_point_ = mount_point; + component_state.status = media_perception::COMPONENT_STATUS_INSTALLED; + std::move(callback).Run(std::move(component_state)); + return; +} + void MediaPerceptionAPIManager::SetState(const media_perception::State& state, const APIStateCallback& callback) { mri::State state_proto = StateIdlToProto(state); DCHECK(state_proto.status() == mri::State::RUNNING || state_proto.status() == mri::State::SUSPENDED || - state_proto.status() == mri::State::RESTARTING) + state_proto.status() == mri::State::RESTARTING || + state_proto.status() == mri::State::STOPPED) << "Cannot set state to something other than RUNNING, SUSPENDED " - "or RESTARTING."; + "RESTARTING, or STOPPED."; - if (analytics_process_state_ == AnalyticsProcessState::LAUNCHING) { + if (analytics_process_state_ == + AnalyticsProcessState::CHANGING_PROCESS_STATE) { callback.Run(GetStateForServiceError( media_perception::SERVICE_ERROR_SERVICE_BUSY_LAUNCHING)); return; } + // Regardless of the state of the media analytics process, always send an + // upstart stop command if requested. + if (state_proto.status() == mri::State::STOPPED) { + analytics_process_state_ = AnalyticsProcessState::CHANGING_PROCESS_STATE; + chromeos::UpstartClient* dbus_client = + chromeos::DBusThreadManager::Get()->GetUpstartClient(); + dbus_client->StopMediaAnalytics( + base::Bind(&MediaPerceptionAPIManager::UpstartStopCallback, + weak_ptr_factory_.GetWeakPtr(), callback)); + return; + } + // If the media analytics process is running or not and restart is requested, // then send restart upstart command. if (state_proto.status() == mri::State::RESTARTING) { - analytics_process_state_ = AnalyticsProcessState::LAUNCHING; + analytics_process_state_ = AnalyticsProcessState::CHANGING_PROCESS_STATE; chromeos::UpstartClient* dbus_client = chromeos::DBusThreadManager::Get()->GetUpstartClient(); dbus_client->RestartMediaAnalytics( @@ -128,10 +195,23 @@ // Analytics process is in state IDLE. if (state_proto.status() == mri::State::RUNNING) { - analytics_process_state_ = AnalyticsProcessState::LAUNCHING; + analytics_process_state_ = AnalyticsProcessState::CHANGING_PROCESS_STATE; chromeos::UpstartClient* dbus_client = chromeos::DBusThreadManager::Get()->GetUpstartClient(); + std::vector<std::string> upstart_env; + // Check if a component is loaded and add the necessary mount_point + // information to the Upstart start command. If no component is loaded, + // StartMediaAnalytics will likely fail and the client will get an error + // callback. StartMediaAnalytics is still called, however, in the case that + // the old CrOS deployment path for the media analytics process is still in + // use. + // TODO(crbug.com/789376): When the old deployment path is no longer in use, + // only start media analytics if the mount point is set. + if (!mount_point_.empty()) + upstart_env.push_back(std::string("mount_point=") + mount_point_); + dbus_client->StartMediaAnalytics( + upstart_env, base::Bind(&MediaPerceptionAPIManager::UpstartStartCallback, weak_ptr_factory_.GetWeakPtr(), callback, state_proto)); return; @@ -174,6 +254,22 @@ SetStateInternal(callback, state); } +void MediaPerceptionAPIManager::UpstartStopCallback( + const APIStateCallback& callback, + bool succeeded) { + if (!succeeded) { + analytics_process_state_ = AnalyticsProcessState::UNKNOWN; + callback.Run(GetStateForServiceError( + media_perception::SERVICE_ERROR_SERVICE_UNREACHABLE)); + return; + } + analytics_process_state_ = AnalyticsProcessState::IDLE; + // Stopping the process succeeded so fire a callback with status STOPPED. + media_perception::State state_stopped; + state_stopped.status = media_perception::STATUS_STOPPED; + callback.Run(std::move(state_stopped)); +} + void MediaPerceptionAPIManager::UpstartRestartCallback( const APIStateCallback& callback, bool succeeded) {
diff --git a/extensions/browser/api/media_perception_private/media_perception_api_manager.h b/extensions/browser/api/media_perception_private/media_perception_api_manager.h index 52d3d43..b136d01 100644 --- a/extensions/browser/api/media_perception_private/media_perception_api_manager.h +++ b/extensions/browser/api/media_perception_private/media_perception_api_manager.h
@@ -14,6 +14,10 @@ class MediaPerceptionAPIManager : public BrowserContextKeyedAPI { public: + using APISetAnalyticsComponentCallback = base::OnceCallback<void( + extensions::api::media_perception_private::ComponentState + component_state)>; + using APIStateCallback = base::Callback<void( extensions::api::media_perception_private::State state)>; @@ -32,6 +36,9 @@ GetFactoryInstance(); // Public functions for MediaPerceptionPrivateAPI implementation. + void SetAnalyticsComponent( + const extensions::api::media_perception_private::Component& component, + APISetAnalyticsComponentCallback callback); void GetState(const APIStateCallback& callback); void SetState(const extensions::api::media_perception_private::State& state, const APIStateCallback& callback); @@ -48,9 +55,11 @@ IDLE, // The process has been launched via Upstart, but waiting for callback to // confirm. - LAUNCHING, + CHANGING_PROCESS_STATE, // The process is running. - RUNNING + RUNNING, + // The process state is unknown, e.g. when a Upstart Stop request fails. + UNKNOWN }; // Sets the state of the analytics process. @@ -81,12 +90,26 @@ // Callback for Upstart command to restart media analytics process. void UpstartRestartCallback(const APIStateCallback& callback, bool succeeded); + // Callback for Upstart command to stop media analytics process. + void UpstartStopCallback(const APIStateCallback& callback, bool succeeded); + + // Callback with the mount point for a loaded component. + void LoadComponentCallback(APISetAnalyticsComponentCallback callback, + const std::string& mount_point); + + bool ComponentIsLoaded(); + content::BrowserContext* const browser_context_; // Keeps track of whether the analytics process is running so that it can be // started with an Upstart D-Bus method call if necessary. AnalyticsProcessState analytics_process_state_; + // Keeps track of the mount point for the current media analytics process + // component from component updater. If this string is not set, no component + // is set. + std::string mount_point_; + base::WeakPtrFactory<MediaPerceptionAPIManager> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(MediaPerceptionAPIManager);
diff --git a/extensions/browser/api/media_perception_private/media_perception_api_manager_unittest.cc b/extensions/browser/api/media_perception_private/media_perception_api_manager_unittest.cc index 2ddf0e2..88e6401 100644 --- a/extensions/browser/api/media_perception_private/media_perception_api_manager_unittest.cc +++ b/extensions/browser/api/media_perception_private/media_perception_api_manager_unittest.cc
@@ -29,7 +29,8 @@ ~TestUpstartClient() override {} // Overrides behavior to queue start requests. - void StartMediaAnalytics(const UpstartCallback& callback) override { + void StartMediaAnalytics(const std::vector<std::string>& upstart_env, + const UpstartCallback& callback) override { HandleUpstartRequest(callback); } @@ -38,6 +39,11 @@ HandleUpstartRequest(callback); } + // Overrides behavior to queue stop requests. + void StopMediaAnalytics(const UpstartCallback& callback) override { + HandleUpstartRequest(callback); + } + // Triggers the next queue'd start request to succeed or fail. bool HandleNextUpstartRequest(bool should_succeed) { if (pending_upstart_request_callbacks_.empty()) @@ -51,7 +57,8 @@ return true; } - FakeUpstartClient::StartMediaAnalytics(callback); + std::vector<std::string> upstart_env; + FakeUpstartClient::StartMediaAnalytics(upstart_env, callback); return true; } @@ -191,6 +198,26 @@ SetStateAndWaitForResponse(manager_.get(), state)); } +TEST_F(MediaPerceptionAPIManagerTest, UpstartStopFailure) { + upstart_client_->set_enqueue_requests(true); + media_perception::State state; + state.status = media_perception::STATUS_STOPPED; + + base::RunLoop run_loop; + media_perception::ServiceError service_error; + manager_->SetState(state, + base::Bind(&RecordServiceErrorFromStateAndRunClosure, + run_loop.QuitClosure(), &service_error)); + EXPECT_TRUE(upstart_client_->HandleNextUpstartRequest(false)); + run_loop.Run(); + EXPECT_EQ(media_perception::SERVICE_ERROR_SERVICE_UNREACHABLE, service_error); + + // Check that after a failed request, setState STOPPED will go through. + upstart_client_->set_enqueue_requests(false); + EXPECT_EQ(media_perception::SERVICE_ERROR_NONE, + SetStateAndWaitForResponse(manager_.get(), state)); +} + TEST_F(MediaPerceptionAPIManagerTest, UpstartRestartFailure) { upstart_client_->set_enqueue_requests(true); media_perception::State state;
diff --git a/extensions/browser/api/media_perception_private/media_perception_private_api.cc b/extensions/browser/api/media_perception_private/media_perception_private_api.cc index 5667ec8..160e911 100644 --- a/extensions/browser/api/media_perception_private/media_perception_private_api.cc +++ b/extensions/browser/api/media_perception_private/media_perception_private_api.cc
@@ -41,9 +41,11 @@ EXTENSION_FUNCTION_VALIDATE(params.get()); if (params->state.status != media_perception::STATUS_RUNNING && params->state.status != media_perception::STATUS_SUSPENDED && - params->state.status != media_perception::STATUS_RESTARTING) { + params->state.status != media_perception::STATUS_RESTARTING && + params->state.status != media_perception::STATUS_STOPPED) { return RespondNow( - Error("Status can only be set to RUNNING, SUSPENDED or RESTARTING.")); + Error("Status can only be set to RUNNING, SUSPENDED, RESTARTING, or " + "STOPPED.")); } // Check that device context is only provided with SetState RUNNING. @@ -95,7 +97,23 @@ ExtensionFunction::ResponseAction MediaPerceptionPrivateSetAnalyticsComponentFunction::Run() { - return RespondNow(Error("Not implemented.")); + std::unique_ptr<media_perception::SetAnalyticsComponent::Params> params = + media_perception::SetAnalyticsComponent::Params::Create(*args_); + EXTENSION_FUNCTION_VALIDATE(params.get()); + + MediaPerceptionAPIManager* manager = + MediaPerceptionAPIManager::Get(browser_context()); + manager->SetAnalyticsComponent( + params->component, + base::BindOnce(&MediaPerceptionPrivateSetAnalyticsComponentFunction:: + OnAnalyticsComponentSet, + this)); + return RespondLater(); +} + +void MediaPerceptionPrivateSetAnalyticsComponentFunction:: + OnAnalyticsComponentSet(media_perception::ComponentState component_state) { + Respond(OneArgument(component_state.ToValue())); } } // namespace extensions
diff --git a/extensions/browser/api/media_perception_private/media_perception_private_api.h b/extensions/browser/api/media_perception_private/media_perception_private_api.h index e2cc271..8d8bfb58 100644 --- a/extensions/browser/api/media_perception_private/media_perception_private_api.h +++ b/extensions/browser/api/media_perception_private/media_perception_private_api.h
@@ -79,6 +79,10 @@ // ExtensionFunction: ResponseAction Run() override; + void OnAnalyticsComponentSet( + extensions::api::media_perception_private::ComponentState + component_state); + DISALLOW_COPY_AND_ASSIGN(MediaPerceptionPrivateSetAnalyticsComponentFunction); };
diff --git a/extensions/browser/api/media_perception_private/media_perception_private_apitest.cc b/extensions/browser/api/media_perception_private/media_perception_private_apitest.cc index 5442aef..65e8f57 100644 --- a/extensions/browser/api/media_perception_private/media_perception_private_apitest.cc +++ b/extensions/browser/api/media_perception_private/media_perception_private_apitest.cc
@@ -5,19 +5,67 @@ #include "base/auto_reset.h" #include "base/command_line.h" #include "base/memory/ptr_util.h" +#include "base/threading/thread_task_runner_handle.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/fake_media_analytics_client.h" #include "chromeos/dbus/media_analytics_client.h" #include "chromeos/media_perception/media_perception.pb.h" +#include "extensions/browser/api/media_perception_private/media_perception_api_delegate.h" #include "extensions/browser/api/media_perception_private/media_perception_private_api.h" +#include "extensions/common/api/media_perception_private.h" #include "extensions/common/features/feature_session_type.h" #include "extensions/common/switches.h" +#include "extensions/shell/browser/shell_extensions_api_client.h" #include "extensions/shell/test/shell_apitest.h" #include "extensions/test/extension_test_message_listener.h" #include "extensions/test/result_catcher.h" namespace extensions { +namespace media_perception = extensions::api::media_perception_private; + +namespace { + +class TestMediaPerceptionAPIDelegate : public MediaPerceptionAPIDelegate { + public: + void LoadCrOSComponent( + const media_perception::ComponentType& type, + base::OnceCallback<void(const std::string&)> load_callback) override { + // For testing both success and failure cases, test class has the LIGHT + // component succeed install and the others fail. + if (type == media_perception::COMPONENT_TYPE_LIGHT) { + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::BindOnce(std::move(load_callback), + "/run/imageloader/rtanalytics-light")); + return; + } + + // Firing callback with empty string indicates that the installation of the + // component failed. + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::BindOnce(std::move(load_callback), "")); + } +}; + +class TestExtensionsAPIClient : public ShellExtensionsAPIClient { + public: + TestExtensionsAPIClient() : ShellExtensionsAPIClient() {} + + MediaPerceptionAPIDelegate* GetMediaPerceptionAPIDelegate() override { + if (!test_media_perception_api_delegate_) { + test_media_perception_api_delegate_ = + std::make_unique<TestMediaPerceptionAPIDelegate>(); + } + return test_media_perception_api_delegate_.get(); + } + + private: + std::unique_ptr<TestMediaPerceptionAPIDelegate> + test_media_perception_api_delegate_; +}; + +} // namespace + class MediaPerceptionPrivateApiTest : public ShellApiTest { public: MediaPerceptionPrivateApiTest() {} @@ -56,6 +104,15 @@ DISALLOW_COPY_AND_ASSIGN(MediaPerceptionPrivateApiTest); }; +// Verify that we can execute the setAnalyticsComponent API and deal with +// failures. +IN_PROC_BROWSER_TEST_F(MediaPerceptionPrivateApiTest, SetAnalyticsComponent) { + // Constructing a TestExtensionsAPIClient to set the behavior of the + // ExtensionsAPIClient. + TestExtensionsAPIClient test_api_client; + ASSERT_TRUE(RunAppTest("media_perception_private/component")) << message_; +} + // Verify that we can set and get mediaPerception system state. IN_PROC_BROWSER_TEST_F(MediaPerceptionPrivateApiTest, State) { ASSERT_TRUE(RunAppTest("media_perception_private/state")) << message_;
diff --git a/extensions/browser/guest_view/web_view/javascript_dialog_helper.cc b/extensions/browser/guest_view/web_view/javascript_dialog_helper.cc index 63a56a1..4e018f6 100644 --- a/extensions/browser/guest_view/web_view/javascript_dialog_helper.cc +++ b/extensions/browser/guest_view/web_view/javascript_dialog_helper.cc
@@ -69,6 +69,7 @@ void JavaScriptDialogHelper::RunBeforeUnloadDialog( content::WebContents* web_contents, + content::RenderFrameHost* render_frame_host, bool is_reload, DialogClosedCallback callback) { // This is called if the guest has a beforeunload event handler.
diff --git a/extensions/browser/guest_view/web_view/javascript_dialog_helper.h b/extensions/browser/guest_view/web_view/javascript_dialog_helper.h index aad6108..26de5112 100644 --- a/extensions/browser/guest_view/web_view/javascript_dialog_helper.h +++ b/extensions/browser/guest_view/web_view/javascript_dialog_helper.h
@@ -26,6 +26,7 @@ DialogClosedCallback callback, bool* did_suppress_message) override; void RunBeforeUnloadDialog(content::WebContents* web_contents, + content::RenderFrameHost* render_frame_host, bool is_reload, DialogClosedCallback callback) override; bool HandleJavaScriptDialog(content::WebContents* web_contents,
diff --git a/extensions/browser/script_executor.cc b/extensions/browser/script_executor.cc index db2c02da..3e5ef98 100644 --- a/extensions/browser/script_executor.cc +++ b/extensions/browser/script_executor.cc
@@ -261,7 +261,7 @@ params.is_javascript = (script_type == JAVASCRIPT); params.code = code; params.match_about_blank = (about_blank == MATCH_ABOUT_BLANK); - params.run_at = static_cast<int>(run_at); + params.run_at = run_at; params.in_main_world = (world_type == MAIN_WORLD); params.is_web_view = (process_type == WEB_VIEW_PROCESS); params.webview_src = webview_src;
diff --git a/extensions/common/api/_api_features.json b/extensions/common/api/_api_features.json index 605499b..b20f47dc 100644 --- a/extensions/common/api/_api_features.json +++ b/extensions/common/api/_api_features.json
@@ -288,7 +288,6 @@ "3F65507A3B39259B38C8173C6FFA3D12DF64CCE9", // http://crbug.com/371562. "D7986543275120831B39EF28D1327552FC343960", // http://crbug.com/378067 "A291B26E088FA6BA53FFD72F0916F06EBA7C585A", // http://crbug.com/378067 - "62CCAAD339E6451BBF97C4BBDF758E934A05AD0B", // Hotword triggering "07BD6A765FFC289FF755D7CAB2893A40EC337FEC", // http://crbug.com/456214 "896B85CC7E913E11C34892C1425A093C0701D386", // http://crbug.com/456214 "11A01C82EF355E674E4F9728A801F5C3CB40D83F", // http://crbug.com/456214
diff --git a/extensions/common/api/_permission_features.json b/extensions/common/api/_permission_features.json index ccdddbea..19f665e 100644 --- a/extensions/common/api/_permission_features.json +++ b/extensions/common/api/_permission_features.json
@@ -116,8 +116,6 @@ "3F50C3A83839D9C76334BCE81CDEC06174F266AF", "39BE69F11F68E4EED080DA3DC2394F7885B7AFF9", "FF78670081967CE21DB86A04AD94A0498F01E20A", // http://crbug.com/409192 - // Hotword component extension - "62CCAAD339E6451BBF97C4BBDF758E934A05AD0B", "0C0426C12F94156F330FFAF346A976BA8878DE78", // http://crbug.com/496954 "AC4538682FCECD28587C7A0F80849F78F4872BC2", // http://crbug.com/496954 "CCA4D85A67ADD65DA6C02E49EE3C080C54A8211C", // http://crbug.com/496954 @@ -380,7 +378,6 @@ "D2DAA9362153E8A5E3CF593E6DF4666421ABAD21", // http://crbug.com/374965 "D7986543275120831B39EF28D1327552FC343960", // http://crbug.com/378067 "A291B26E088FA6BA53FFD72F0916F06EBA7C585A", // http://crbug.com/378067 - "62CCAAD339E6451BBF97C4BBDF758E934A05AD0B", // Hotword triggering "07BD6A765FFC289FF755D7CAB2893A40EC337FEC", // http://crbug.com/456214 "896B85CC7E913E11C34892C1425A093C0701D386", // http://crbug.com/456214 "11A01C82EF355E674E4F9728A801F5C3CB40D83F", // http://crbug.com/456214 @@ -445,7 +442,8 @@ "E0E94FB0C01FFB9CDC7A5F098C99B5A8D2F95902", // http://crbug.com/610452 "52E0557059A7A28F74ED1D92DDD997E0CCD37806", // http://crbug.com/610452 "61FF4757F9420B62B19BA5C96084649339DB31F5", // http://crbug.com/731941 - "6FB7E1B6C0247B687AC14772E87A117F5F5E4497" // http://crbug.com/731941 + "6FB7E1B6C0247B687AC14772E87A117F5F5E4497", // http://crbug.com/731941 + "9834387FDA1F66A1B5CA06CB442137B556F12F2A" // http://crbug.com/772346 ] }], "networkingPrivate": {
diff --git a/extensions/common/api/media_perception_private.idl b/extensions/common/api/media_perception_private.idl index d1b9107..bce5da9 100644 --- a/extensions/common/api/media_perception_private.idl +++ b/extensions/common/api/media_perception_private.idl
@@ -134,7 +134,8 @@ UNSPECIFIED, FACE, PERSON, - MOTION_REGION + MOTION_REGION, + LABELED_REGION }; dictionary Entity { @@ -144,6 +145,9 @@ EntityType? type; + // Label for this entity. + DOMString? entityLabel; + // Minimum box which captures entire detected entity. BoundingBox? boundingBox; @@ -154,6 +158,14 @@ Distance? depth; }; + dictionary PacketLatency { + // Label for this packet. + DOMString? packetLabel; + + // Packet processing latency in microseconds. + long? latencyUsec; + }; + // The set of computer vision metadata for an image frame. dictionary FramePerception { long? frameId; @@ -167,6 +179,9 @@ // The list of entities detected in this frame. Entity[]? entities; + + // Processing latency for a list of packets. + PacketLatency[]? packetLatency; }; dictionary MediaPerception {
diff --git a/extensions/common/api/networking_private.idl b/extensions/common/api/networking_private.idl index c2c193f..0d707c2d 100644 --- a/extensions/common/api/networking_private.idl +++ b/extensions/common/api/networking_private.idl
@@ -242,6 +242,7 @@ DOMString[]? ServerCAPEMs; DOMString[]? ServerCARefs; DOMString? SubjectMatch; + DOMString? TLSVersionMax; boolean? UseProactiveKeyCaching; boolean? UseSystemCAs; }; @@ -262,6 +263,7 @@ ManagedDOMStringList? ServerCAPEMs; ManagedDOMStringList? ServerCARefs; ManagedDOMString? SubjectMatch; + ManagedDOMString? TLSVersionMax; ManagedBoolean? UseProactiveKeyCaching; ManagedBoolean? UseSystemCAs; };
diff --git a/extensions/common/api/runtime.json b/extensions/common/api/runtime.json index 893ffc0..84476bc 100644 --- a/extensions/common/api/runtime.json +++ b/extensions/common/api/runtime.json
@@ -541,6 +541,7 @@ "name": "onMessageExternal", "type": "function", "nocompile": true, + "options": { "unmanaged": true }, "description": "Fired when a message is sent from another extension/app (by $(ref:runtime.sendMessage)). Cannot be used in a content script.", "parameters": [ {"name": "message", "type": "any", "optional": true, "description": "The message sent by the calling script."},
diff --git a/extensions/common/extension_messages.h b/extensions/common/extension_messages.h index 4ea0d70..f21c902 100644 --- a/extensions/common/extension_messages.h +++ b/extensions/common/extension_messages.h
@@ -160,7 +160,7 @@ IPC_STRUCT_MEMBER(bool, match_about_blank) // When to inject the code. - IPC_STRUCT_MEMBER(int, run_at) + IPC_STRUCT_MEMBER(extensions::UserScript::RunLocation, run_at) // Whether to execute code in the main world (as opposed to an isolated // world).
diff --git a/extensions/renderer/BUILD.gn b/extensions/renderer/BUILD.gn index 79415fb..da4defd 100644 --- a/extensions/renderer/BUILD.gn +++ b/extensions/renderer/BUILD.gn
@@ -65,6 +65,8 @@ "bindings/event_emitter.h", "bindings/exception_handler.cc", "bindings/exception_handler.h", + "bindings/js_runner.cc", + "bindings/js_runner.h", "blob_native_handler.cc", "blob_native_handler.h", "chrome_setting.cc", @@ -102,6 +104,8 @@ "extension_frame_helper.h", "extension_injection_host.cc", "extension_injection_host.h", + "extension_js_runner.cc", + "extension_js_runner.h", "extension_port.cc", "extension_port.h", "extensions_render_frame_observer.cc", @@ -333,6 +337,8 @@ "bindings/api_binding_test.h", "bindings/api_binding_test_util.cc", "bindings/api_binding_test_util.h", + "bindings/test_js_runner.cc", + "bindings/test_js_runner.h", "native_extension_bindings_system_test_base.cc", "native_extension_bindings_system_test_base.h", "send_message_tester.cc",
diff --git a/extensions/renderer/bindings/api_binding.cc b/extensions/renderer/bindings/api_binding.cc index ae235e4a..2ee7691 100644 --- a/extensions/renderer/bindings/api_binding.cc +++ b/extensions/renderer/bindings/api_binding.cc
@@ -367,6 +367,8 @@ } } + binding_hooks_->InitializeInstance(context, object); + return object; }
diff --git a/extensions/renderer/bindings/api_binding_bridge.cc b/extensions/renderer/bindings/api_binding_bridge.cc index 9f4bc91..b5c2af29 100644 --- a/extensions/renderer/bindings/api_binding_bridge.cc +++ b/extensions/renderer/bindings/api_binding_bridge.cc
@@ -6,6 +6,7 @@ #include "base/values.h" #include "extensions/renderer/bindings/api_binding_hooks.h" +#include "extensions/renderer/bindings/js_runner.h" #include "gin/converter.h" #include "gin/object_template_builder.h" @@ -29,11 +30,8 @@ v8::Local<v8::Context> context, v8::Local<v8::Value> api_object, const std::string& extension_id, - const std::string& context_type, - const binding::RunJSFunction& run_js) - : extension_id_(extension_id), - context_type_(context_type), - run_js_(run_js) { + const std::string& context_type) + : extension_id_(extension_id), context_type_(context_type) { v8::Isolate* isolate = context->GetIsolate(); v8::Local<v8::Object> wrapper = GetWrapper(isolate).ToLocalChecked(); v8::Maybe<bool> result = wrapper->SetPrivate( @@ -99,7 +97,8 @@ v8::Local<v8::String> context_type = gin::StringToSymbol(isolate, context_type_); v8::Local<v8::Value> args[] = {hook_object, extension_id, context_type}; - run_js_.Run(function, context, arraysize(args), args); + JSRunner::Get(context)->RunJSFunction(function, context, arraysize(args), + args); } } // namespace extensions
diff --git a/extensions/renderer/bindings/api_binding_bridge.h b/extensions/renderer/bindings/api_binding_bridge.h index 298e15e..baf157a 100644 --- a/extensions/renderer/bindings/api_binding_bridge.h +++ b/extensions/renderer/bindings/api_binding_bridge.h
@@ -8,7 +8,6 @@ #include <string> #include "base/macros.h" -#include "extensions/renderer/bindings/api_binding_types.h" #include "gin/wrappable.h" #include "v8/include/v8.h" @@ -24,8 +23,7 @@ v8::Local<v8::Context> context, v8::Local<v8::Value> api_object, const std::string& extension_id, - const std::string& context_type, - const binding::RunJSFunction& run_js); + const std::string& context_type); ~APIBindingBridge() override; static gin::WrapperInfo kWrapperInfo; @@ -52,9 +50,6 @@ // The type of context this belongs to. std::string context_type_; - // A function to run JS safely. - binding::RunJSFunction run_js_; - DISALLOW_COPY_AND_ASSIGN(APIBindingBridge); };
diff --git a/extensions/renderer/bindings/api_binding_hooks.cc b/extensions/renderer/bindings/api_binding_hooks.cc index c568f77..3e69129 100644 --- a/extensions/renderer/bindings/api_binding_hooks.cc +++ b/extensions/renderer/bindings/api_binding_hooks.cc
@@ -9,6 +9,7 @@ #include "base/supports_user_data.h" #include "extensions/renderer/bindings/api_binding_hooks_delegate.h" #include "extensions/renderer/bindings/api_signature.h" +#include "extensions/renderer/bindings/js_runner.h" #include "gin/arguments.h" #include "gin/handle.h" #include "gin/object_template_builder.h" @@ -204,9 +205,8 @@ APIBindingHooks::RequestResult::RequestResult(const RequestResult& other) = default; -APIBindingHooks::APIBindingHooks(const std::string& api_name, - const binding::RunJSFunctionSync& run_js) - : api_name_(api_name), run_js_(run_js) {} +APIBindingHooks::APIBindingHooks(const std::string& api_name) + : api_name_(api_name) {} APIBindingHooks::~APIBindingHooks() {} APIBindingHooks::RequestResult APIBindingHooks::RunHooks( @@ -298,9 +298,11 @@ return RequestResult(result, custom_callback); } + // Safe to use synchronous JS since it's in direct response to JS calling + // into the binding. v8::Global<v8::Value> global_result = - run_js_.Run(handle_request, context, arguments->size(), - arguments->data()); + JSRunner::Get(context)->RunJSFunctionSync( + handle_request, context, arguments->size(), arguments->data()); if (try_catch.HasCaught()) { try_catch.ReThrow(); return RequestResult(RequestResult::THROWN); @@ -335,7 +337,7 @@ const std::string& event_name, v8::Local<v8::Value>* event_out) { return delegate_ && - delegate_->CreateCustomEvent(context, run_js_, event_name, event_out); + delegate_->CreateCustomEvent(context, event_name, event_out); } void APIBindingHooks::InitializeTemplate( @@ -346,6 +348,12 @@ delegate_->InitializeTemplate(isolate, object_template, type_refs); } +void APIBindingHooks::InitializeInstance(v8::Local<v8::Context> context, + v8::Local<v8::Object> instance) { + if (delegate_) + delegate_->InitializeInstance(context, instance); +} + void APIBindingHooks::SetDelegate( std::unique_ptr<APIBindingHooksDelegate> delegate) { delegate_ = std::move(delegate); @@ -358,8 +366,10 @@ v8::Global<v8::Value> global_result; { v8::TryCatch try_catch(context->GetIsolate()); - global_result = run_js_.Run(function, context, - arguments->size(), arguments->data()); + // Safe to use synchronous JS since it's in direct response to JS calling + // into the binding. + global_result = JSRunner::Get(context)->RunJSFunctionSync( + function, context, arguments->size(), arguments->data()); if (try_catch.HasCaught()) { try_catch.ReThrow(); return false;
diff --git a/extensions/renderer/bindings/api_binding_hooks.h b/extensions/renderer/bindings/api_binding_hooks.h index f29ccb5..a178ff5e 100644 --- a/extensions/renderer/bindings/api_binding_hooks.h +++ b/extensions/renderer/bindings/api_binding_hooks.h
@@ -9,7 +9,6 @@ #include <string> #include "base/macros.h" -#include "extensions/renderer/bindings/api_binding_types.h" #include "v8/include/v8.h" namespace extensions { @@ -48,8 +47,7 @@ std::string error; }; - APIBindingHooks(const std::string& api_name, - const binding::RunJSFunctionSync& run_js); + explicit APIBindingHooks(const std::string& api_name); ~APIBindingHooks(); // Looks for any custom hooks associated with the given request, and, if any @@ -78,6 +76,10 @@ v8::Local<v8::ObjectTemplate> object_template, const APITypeReferenceMap& type_refs); + // Performs any extra initialization on an instance of the API. + void InitializeInstance(v8::Local<v8::Context> context, + v8::Local<v8::Object> instance); + void SetDelegate(std::unique_ptr<APIBindingHooksDelegate> delegate); private: @@ -90,11 +92,6 @@ // The name of the associated API. std::string api_name_; - // We use synchronous JS execution here because at every point we execute JS, - // it's in direct response to JS calling in. There should be no reason that - // script is disabled. - binding::RunJSFunctionSync run_js_; - std::unique_ptr<APIBindingHooksDelegate> delegate_; DISALLOW_COPY_AND_ASSIGN(APIBindingHooks);
diff --git a/extensions/renderer/bindings/api_binding_hooks_delegate.cc b/extensions/renderer/bindings/api_binding_hooks_delegate.cc index 8b954c8..655db8a 100644 --- a/extensions/renderer/bindings/api_binding_hooks_delegate.cc +++ b/extensions/renderer/bindings/api_binding_hooks_delegate.cc
@@ -10,7 +10,6 @@ bool APIBindingHooksDelegate::CreateCustomEvent( v8::Local<v8::Context> context, - const binding::RunJSFunctionSync& run_js_sync, const std::string& event_name, v8::Local<v8::Value>* event_out) { return false;
diff --git a/extensions/renderer/bindings/api_binding_hooks_delegate.h b/extensions/renderer/bindings/api_binding_hooks_delegate.h index 9ab14f9..4c462365 100644 --- a/extensions/renderer/bindings/api_binding_hooks_delegate.h +++ b/extensions/renderer/bindings/api_binding_hooks_delegate.h
@@ -6,7 +6,6 @@ #define EXTENSIONS_RENDERER_BINDINGS_API_BINDING_HOOKS_DELEGATE_H_ #include "extensions/renderer/bindings/api_binding_hooks.h" -#include "extensions/renderer/bindings/api_binding_types.h" #include "v8/include/v8.h" namespace extensions { @@ -21,7 +20,6 @@ // Populates |event_out| and returns true if a custom implementation should // be used, otherwise returns false. virtual bool CreateCustomEvent(v8::Local<v8::Context> context, - const binding::RunJSFunctionSync& run_js_sync, const std::string& event_name, v8::Local<v8::Value>* event_out); @@ -38,6 +36,11 @@ virtual void InitializeTemplate(v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> object_template, const APITypeReferenceMap& type_refs) {} + + // Allows custom implementations to mutate an instance of the API for a + // specific context. + virtual void InitializeInstance(v8::Local<v8::Context> context, + v8::Local<v8::Object> instance) {} }; } // namespace extensions
diff --git a/extensions/renderer/bindings/api_binding_hooks_test_delegate.cc b/extensions/renderer/bindings/api_binding_hooks_test_delegate.cc index fe0ea19..d153e81 100644 --- a/extensions/renderer/bindings/api_binding_hooks_test_delegate.cc +++ b/extensions/renderer/bindings/api_binding_hooks_test_delegate.cc
@@ -11,11 +11,10 @@ bool APIBindingHooksTestDelegate::CreateCustomEvent( v8::Local<v8::Context> context, - const binding::RunJSFunctionSync& run_js_sync, const std::string& event_name, v8::Local<v8::Value>* event_out) { if (!custom_event_.is_null()) { - *event_out = custom_event_.Run(context, run_js_sync, event_name); + *event_out = custom_event_.Run(context, event_name); return true; } return false; @@ -36,6 +35,11 @@ template_initializer_ = initializer; } +void APIBindingHooksTestDelegate::SetInstanceInitializer( + const InstanceInitializer& initializer) { + instance_initializer_ = initializer; +} + APIBindingHooks::RequestResult APIBindingHooksTestDelegate::HandleRequest( const std::string& method_name, const APISignature* signature, @@ -58,4 +62,11 @@ template_initializer_.Run(isolate, object_template, type_refs); } +void APIBindingHooksTestDelegate::InitializeInstance( + v8::Local<v8::Context> context, + v8::Local<v8::Object> instance) { + if (instance_initializer_) + instance_initializer_.Run(context, instance); +} + } // namespace extensions
diff --git a/extensions/renderer/bindings/api_binding_hooks_test_delegate.h b/extensions/renderer/bindings/api_binding_hooks_test_delegate.h index 2ea563bf..c1b7391 100644 --- a/extensions/renderer/bindings/api_binding_hooks_test_delegate.h +++ b/extensions/renderer/bindings/api_binding_hooks_test_delegate.h
@@ -12,7 +12,6 @@ #include "base/macros.h" #include "base/strings/string_piece.h" #include "extensions/renderer/bindings/api_binding_hooks_delegate.h" -#include "extensions/renderer/bindings/api_binding_types.h" #include "v8/include/v8.h" namespace extensions { @@ -25,7 +24,6 @@ using CustomEventFactory = base::Callback<v8::Local<v8::Value>( v8::Local<v8::Context>, - const binding::RunJSFunctionSync& run_js, const std::string& event_name)>; using RequestHandler = base::Callback<APIBindingHooks::RequestResult( @@ -38,6 +36,9 @@ v8::Local<v8::ObjectTemplate>, const APITypeReferenceMap&)>; + using InstanceInitializer = + base::Callback<void(v8::Local<v8::Context>, v8::Local<v8::Object>)>; + // Adds a custom |handler| for the method with the given |name|. void AddHandler(base::StringPiece name, const RequestHandler& handler); @@ -46,9 +47,10 @@ void SetTemplateInitializer(const TemplateInitializer& initializer); + void SetInstanceInitializer(const InstanceInitializer& initializer); + // APIBindingHooksDelegate: bool CreateCustomEvent(v8::Local<v8::Context> context, - const binding::RunJSFunctionSync& run_js_sync, const std::string& event_name, v8::Local<v8::Value>* event_out) override; APIBindingHooks::RequestResult HandleRequest( @@ -60,11 +62,14 @@ void InitializeTemplate(v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> object_template, const APITypeReferenceMap& type_refs) override; + void InitializeInstance(v8::Local<v8::Context> context, + v8::Local<v8::Object> instance) override; private: std::map<std::string, RequestHandler> request_handlers_; CustomEventFactory custom_event_; TemplateInitializer template_initializer_; + InstanceInitializer instance_initializer_; DISALLOW_COPY_AND_ASSIGN(APIBindingHooksTestDelegate); };
diff --git a/extensions/renderer/bindings/api_binding_js_util.cc b/extensions/renderer/bindings/api_binding_js_util.cc index f48637b..6d75855c 100644 --- a/extensions/renderer/bindings/api_binding_js_util.cc +++ b/extensions/renderer/bindings/api_binding_js_util.cc
@@ -12,6 +12,7 @@ #include "extensions/renderer/bindings/api_type_reference_map.h" #include "extensions/renderer/bindings/declarative_event.h" #include "extensions/renderer/bindings/exception_handler.h" +#include "extensions/renderer/bindings/js_runner.h" #include "gin/converter.h" #include "gin/dictionary.h" #include "gin/handle.h" @@ -24,13 +25,11 @@ APIBindingJSUtil::APIBindingJSUtil(APITypeReferenceMap* type_refs, APIRequestHandler* request_handler, APIEventHandler* event_handler, - ExceptionHandler* exception_handler, - const binding::RunJSFunction& run_js) + ExceptionHandler* exception_handler) : type_refs_(type_refs), request_handler_(request_handler), event_handler_(event_handler), - exception_handler_(exception_handler), - run_js_(run_js) {} + exception_handler_(exception_handler) {} APIBindingJSUtil::~APIBindingJSUtil() {} @@ -209,7 +208,7 @@ v8::Local<v8::Context> context = arguments->GetHolderCreationContext(); request_handler_->last_error()->SetError(context, error); - run_js_.Run(callback, context, 0, nullptr); + JSRunner::Get(context)->RunJSFunction(callback, context, 0, nullptr); bool report_if_unchecked = true; request_handler_->last_error()->ClearError(context, report_if_unchecked);
diff --git a/extensions/renderer/bindings/api_binding_js_util.h b/extensions/renderer/bindings/api_binding_js_util.h index 038658e1..e2d3012 100644 --- a/extensions/renderer/bindings/api_binding_js_util.h +++ b/extensions/renderer/bindings/api_binding_js_util.h
@@ -8,7 +8,6 @@ #include <string> #include "base/macros.h" -#include "extensions/renderer/bindings/api_binding_types.h" #include "gin/wrappable.h" #include "v8/include/v8.h" @@ -30,8 +29,7 @@ APIBindingJSUtil(APITypeReferenceMap* type_refs, APIRequestHandler* request_handler, APIEventHandler* event_handler, - ExceptionHandler* exception_handler, - const binding::RunJSFunction& run_js); + ExceptionHandler* exception_handler); ~APIBindingJSUtil() override; static gin::WrapperInfo kWrapperInfo; @@ -114,8 +112,6 @@ // The exception handler. Guaranteed to outlive this object. ExceptionHandler* const exception_handler_; - binding::RunJSFunction run_js_; - DISALLOW_COPY_AND_ASSIGN(APIBindingJSUtil); };
diff --git a/extensions/renderer/bindings/api_binding_js_util_unittest.cc b/extensions/renderer/bindings/api_binding_js_util_unittest.cc index df21db2..c3cb077 100644 --- a/extensions/renderer/bindings/api_binding_js_util_unittest.cc +++ b/extensions/renderer/bindings/api_binding_js_util_unittest.cc
@@ -37,8 +37,7 @@ new APIBindingJSUtil(bindings_system()->type_reference_map(), bindings_system()->request_handler(), bindings_system()->event_handler(), - bindings_system()->exception_handler(), - base::Bind(&RunFunctionOnGlobalAndIgnoreResult))); + bindings_system()->exception_handler())); } v8::Local<v8::Object> GetLastErrorParent(
diff --git a/extensions/renderer/bindings/api_binding_test.cc b/extensions/renderer/bindings/api_binding_test.cc index d886bdd..eeccd5a7 100644 --- a/extensions/renderer/bindings/api_binding_test.cc +++ b/extensions/renderer/bindings/api_binding_test.cc
@@ -21,6 +21,8 @@ } void APIBindingTest::SetUp() { + test_js_runner_ = CreateTestJSRunner(); + // Much of this initialization is stolen from the somewhat-similar // gin::V8Test. #ifdef V8_USE_EXTERNAL_STARTUP_DATA @@ -55,6 +57,8 @@ isolate()->Exit(); isolate_holder_.reset(); + + test_js_runner_.reset(); } void APIBindingTest::DisposeAllContexts() { @@ -132,6 +136,11 @@ } } +std::unique_ptr<TestJSRunner::Scope> APIBindingTest::CreateTestJSRunner() { + return std::make_unique<TestJSRunner::Scope>( + std::make_unique<TestJSRunner>()); +} + v8::Isolate* APIBindingTest::isolate() { return isolate_holder_->isolate(); }
diff --git a/extensions/renderer/bindings/api_binding_test.h b/extensions/renderer/bindings/api_binding_test.h index c296dcb..028d463 100644 --- a/extensions/renderer/bindings/api_binding_test.h +++ b/extensions/renderer/bindings/api_binding_test.h
@@ -10,6 +10,7 @@ #include "base/macros.h" #include "base/test/scoped_task_environment.h" +#include "extensions/renderer/bindings/test_js_runner.h" #include "testing/gtest/include/gtest/gtest.h" #include "v8/include/v8.h" @@ -54,6 +55,9 @@ // Runs V8 garbage collection. void RunGarbageCollection(); + // Returns the TestJSRunner::Scope to use in the test, or null. + virtual std::unique_ptr<TestJSRunner::Scope> CreateTestJSRunner(); + // Returns the associated isolate. Defined out-of-line to avoid the include // for IsolateHolder in the header. v8::Isolate* isolate(); @@ -63,6 +67,7 @@ std::unique_ptr<gin::IsolateHolder> isolate_holder_; std::unique_ptr<gin::ContextHolder> main_context_holder_; + std::unique_ptr<TestJSRunner::Scope> test_js_runner_; std::vector<std::unique_ptr<gin::ContextHolder>> additional_context_holders_; DISALLOW_COPY_AND_ASSIGN(APIBindingTest);
diff --git a/extensions/renderer/bindings/api_binding_types.h b/extensions/renderer/bindings/api_binding_types.h index 87b1b76..37560aa 100644 --- a/extensions/renderer/bindings/api_binding_types.h +++ b/extensions/renderer/bindings/api_binding_types.h
@@ -29,26 +29,6 @@ IO, }; -// A callback to execute the given v8::Function with the provided context and -// arguments. -using RunJSFunction = base::Callback<void(v8::Local<v8::Function>, - v8::Local<v8::Context>, - int argc, - v8::Local<v8::Value>[])>; - -// A callback to execute the given v8::Function synchronously and return the -// result. Note that script can be suspended, so you need to be certain that -// it is not before expected a synchronous result. We use a Global instead of a -// Local because certain implementations need to create a persistent handle in -// order to prevent immediate destruction of the locals. -// TODO(devlin): if we could, using Local here with an EscapableHandleScope -// would be preferable. -using RunJSFunctionSync = - base::Callback<v8::Global<v8::Value>(v8::Local<v8::Function>, - v8::Local<v8::Context>, - int argc, - v8::Local<v8::Value>[])>; - // Adds an error message to the context's console. using AddConsoleError = base::Callback<void(v8::Local<v8::Context>, const std::string& error)>;
diff --git a/extensions/renderer/bindings/api_binding_unittest.cc b/extensions/renderer/bindings/api_binding_unittest.cc index 91ee572..a091816 100644 --- a/extensions/renderer/bindings/api_binding_unittest.cc +++ b/extensions/renderer/bindings/api_binding_unittest.cc
@@ -19,6 +19,7 @@ #include "extensions/renderer/bindings/api_request_handler.h" #include "extensions/renderer/bindings/api_type_reference_map.h" #include "extensions/renderer/bindings/binding_access_checker.h" +#include "extensions/renderer/bindings/test_js_runner.h" #include "gin/arguments.h" #include "gin/converter.h" #include "gin/public/context_holder.h" @@ -104,7 +105,6 @@ APIBindingTest::SetUp(); request_handler_ = std::make_unique<APIRequestHandler>( base::Bind(&APIBindingUnittest::OnFunctionCall, base::Unretained(this)), - base::Bind(&RunFunctionOnGlobalAndIgnoreResult), APILastError(APILastError::GetParent(), binding::AddConsoleError()), nullptr); } @@ -168,10 +168,8 @@ } void InitializeBinding() { - if (!binding_hooks_) { - binding_hooks_ = std::make_unique<APIBindingHooks>( - kBindingName, binding::RunJSFunctionSync()); - } + if (!binding_hooks_) + binding_hooks_ = std::make_unique<APIBindingHooks>(kBindingName); if (binding_hooks_delegate_) binding_hooks_->SetDelegate(std::move(binding_hooks_delegate_)); if (!on_silent_request_) @@ -179,8 +177,6 @@ if (!availability_callback_) availability_callback_ = base::Bind(&AllowAllFeatures); event_handler_ = std::make_unique<APIEventHandler>( - base::Bind(&RunFunctionOnGlobalAndIgnoreResult), - base::Bind(&RunFunctionOnGlobalAndReturnHandle), base::Bind(&OnEventListenersChanged), nullptr); access_checker_ = std::make_unique<BindingAccessChecker>(availability_callback_); @@ -812,8 +808,7 @@ TEST_F(APIBindingUnittest, TestJSCustomHook) { // Register a hook for the test.oneString method. - auto hooks = std::make_unique<APIBindingHooks>( - kBindingName, base::Bind(&RunFunctionOnGlobalAndReturnHandle)); + auto hooks = std::make_unique<APIBindingHooks>(kBindingName); v8::HandleScope handle_scope(isolate()); v8::Local<v8::Context> context = MainContext(); @@ -867,8 +862,7 @@ // Tests the updateArgumentsPreValidate hook. TEST_F(APIBindingUnittest, TestUpdateArgumentsPreValidate) { // Register a hook for the test.oneString method. - auto hooks = std::make_unique<APIBindingHooks>( - kBindingName, base::Bind(&RunFunctionOnGlobalAndReturnHandle)); + auto hooks = std::make_unique<APIBindingHooks>(kBindingName); v8::HandleScope handle_scope(isolate()); v8::Local<v8::Context> context = MainContext(); @@ -914,22 +908,8 @@ // Tests the updateArgumentsPreValidate hook. TEST_F(APIBindingUnittest, TestThrowInUpdateArgumentsPreValidate) { - auto run_js_and_allow_error = [](v8::Local<v8::Function> function, - v8::Local<v8::Context> context, - int argc, - v8::Local<v8::Value> argv[]) { - v8::MaybeLocal<v8::Value> maybe_result = - function->Call(context, context->Global(), argc, argv); - v8::Global<v8::Value> result; - v8::Local<v8::Value> local; - if (maybe_result.ToLocal(&local)) - result.Reset(context->GetIsolate(), local); - return result; - }; - // Register a hook for the test.oneString method. - auto hooks = std::make_unique<APIBindingHooks>( - kBindingName, base::Bind(run_js_and_allow_error)); + auto hooks = std::make_unique<APIBindingHooks>(kBindingName); v8::HandleScope handle_scope(isolate()); v8::Local<v8::Context> context = MainContext(); @@ -957,9 +937,12 @@ FunctionFromString(context, "(function(obj) { return obj.oneString('ping'); })"); v8::Local<v8::Value> args[] = {binding_object}; - RunFunctionAndExpectError(function, context, v8::Undefined(isolate()), - arraysize(args), args, - "Uncaught Error: Custom Hook Error"); + { + TestJSRunner::AllowErrors allow_errors; + RunFunctionAndExpectError(function, context, v8::Undefined(isolate()), + arraysize(args), args, + "Uncaught Error: Custom Hook Error"); + } // Other methods, like stringAndInt(), should behave normally. ExpectPass(binding_object, "obj.stringAndInt('foo', 42);", "['foo',42]", @@ -969,8 +952,7 @@ // Tests that custom JS hooks can return results synchronously. TEST_F(APIBindingUnittest, TestReturningResultFromCustomJSHook) { // Register a hook for the test.oneString method. - auto hooks = std::make_unique<APIBindingHooks>( - kBindingName, base::Bind(&RunFunctionOnGlobalAndReturnHandle)); + auto hooks = std::make_unique<APIBindingHooks>(kBindingName); v8::HandleScope handle_scope(isolate()); v8::Local<v8::Context> context = MainContext(); @@ -1008,29 +990,8 @@ // Tests that JS custom hooks can throw exceptions for bad invocations. TEST_F(APIBindingUnittest, TestThrowingFromCustomJSHook) { - // Our testing handlers for running functions expect a pre-determined success - // or failure. Since we're testing throwing exceptions here, we need a way of - // running that allows exceptions to be thrown, but we still expect most JS - // calls to succeed. - // TODO(devlin): This is a bit clunky. If we need to do this enough, we could - // figure out a different solution, like having a stack object for allowing - // errors/exceptions. But given this is the only place we need it so far, this - // is sufficient. - auto run_js_and_expect_error = [](v8::Local<v8::Function> function, - v8::Local<v8::Context> context, - int argc, - v8::Local<v8::Value> argv[]) { - v8::MaybeLocal<v8::Value> maybe_result = - function->Call(context, context->Global(), argc, argv); - v8::Global<v8::Value> result; - v8::Local<v8::Value> local; - if (maybe_result.ToLocal(&local)) - result.Reset(context->GetIsolate(), local); - return result; - }; // Register a hook for the test.oneString method. - auto hooks = std::make_unique<APIBindingHooks>( - kBindingName, base::Bind(run_js_and_expect_error)); + auto hooks = std::make_unique<APIBindingHooks>(kBindingName); v8::HandleScope handle_scope(isolate()); v8::Local<v8::Context> context = MainContext(); @@ -1058,6 +1019,8 @@ FunctionFromString(context, "(function(obj) { return obj.oneString('ping'); })"); v8::Local<v8::Value> args[] = {binding_object}; + + TestJSRunner::AllowErrors allow_errors; RunFunctionAndExpectError(function, context, v8::Undefined(isolate()), arraysize(args), args, "Uncaught Error: Custom Hook Error"); @@ -1132,8 +1095,7 @@ // Tests the updateArgumentsPostValidate hook. TEST_F(APIBindingUnittest, TestUpdateArgumentsPostValidate) { // Register a hook for the test.oneString method. - auto hooks = std::make_unique<APIBindingHooks>( - kBindingName, base::Bind(&RunFunctionOnGlobalAndReturnHandle)); + auto hooks = std::make_unique<APIBindingHooks>(kBindingName); v8::HandleScope handle_scope(isolate()); v8::Local<v8::Context> context = MainContext(); @@ -1184,8 +1146,7 @@ // See comment in api_binding.cc. TEST_F(APIBindingUnittest, TestUpdateArgumentsPostValidateViolatingSchema) { // Register a hook for the test.oneString method. - auto hooks = std::make_unique<APIBindingHooks>( - kBindingName, base::Bind(&RunFunctionOnGlobalAndReturnHandle)); + auto hooks = std::make_unique<APIBindingHooks>(kBindingName); v8::HandleScope handle_scope(isolate()); v8::Local<v8::Context> context = MainContext(); @@ -1335,6 +1296,55 @@ GetStringPropertyFromObject(binding_object, context, "oneString")); } +TEST_F(APIBindingUnittest, HooksInstanceInitializer) { + SetFunctions(kFunctions); + static constexpr char kHookedProperty[] = "hookedProperty"; + + // Register a hook for the test.oneString method. + auto hooks = std::make_unique<APIBindingHooksTestDelegate>(); + int count = 0; + auto hook = [](int* count, v8::Local<v8::Context> context, + v8::Local<v8::Object> object) { + v8::Isolate* isolate = context->GetIsolate(); + // Add a new property only for the first instance. + if ((*count)++ == 0) { + object + ->Set(context, gin::StringToSymbol(isolate, kHookedProperty), + gin::ConvertToV8(isolate, 42)) + .ToChecked(); + } + }; + + hooks->SetInstanceInitializer(base::Bind(hook, &count)); + SetHooksDelegate(std::move(hooks)); + + InitializeBinding(); + + v8::HandleScope handle_scope(isolate()); + // Create two instances. + v8::Local<v8::Context> context1 = MainContext(); + v8::Local<v8::Object> binding_object1 = binding()->CreateInstance(context1); + + v8::Local<v8::Context> context2 = AddContext(); + v8::Local<v8::Object> binding_object2 = binding()->CreateInstance(context2); + + // We should have run the hooks twice (once per instance). + EXPECT_EQ(2, count); + + // The extra property should be present on the first binding object, but not + // the second. + EXPECT_EQ("42", GetStringPropertyFromObject(binding_object1, context1, + kHookedProperty)); + EXPECT_EQ("undefined", GetStringPropertyFromObject(binding_object2, context2, + kHookedProperty)); + + // Sanity check: other values should still be there. + EXPECT_EQ("function", GetStringPropertyFromObject(binding_object1, context1, + "oneString")); + EXPECT_EQ("function", GetStringPropertyFromObject(binding_object2, context1, + "oneString")); +} + // Test that running hooks returning different results correctly sends requests // or notifies of silent requests. TEST_F(APIBindingUnittest, TestSendingRequestsAndSilentRequestsWithHooks) {
diff --git a/extensions/renderer/bindings/api_bindings_system.cc b/extensions/renderer/bindings/api_bindings_system.cc index 81c27d4..e849670 100644 --- a/extensions/renderer/bindings/api_bindings_system.cc +++ b/extensions/renderer/bindings/api_bindings_system.cc
@@ -13,8 +13,6 @@ namespace extensions { APIBindingsSystem::APIBindingsSystem( - const binding::RunJSFunction& call_js, - const binding::RunJSFunctionSync& call_js_sync, const GetAPISchemaMethod& get_api_schema, const BindingAccessChecker::AvailabilityCallback& is_available, const APIRequestHandler::SendRequestMethod& send_request, @@ -24,18 +22,12 @@ APILastError last_error) : type_reference_map_(base::Bind(&APIBindingsSystem::InitializeType, base::Unretained(this))), - exception_handler_(add_console_error, call_js), + exception_handler_(add_console_error), request_handler_(send_request, - call_js, std::move(last_error), &exception_handler_), - event_handler_(call_js, - call_js_sync, - event_listeners_changed, - &exception_handler_), + event_handler_(event_listeners_changed, &exception_handler_), access_checker_(is_available), - call_js_(call_js), - call_js_sync_(call_js_sync), get_api_schema_(get_api_schema), on_silent_request_(on_silent_request) {} @@ -76,7 +68,7 @@ hooks = std::move(iter->second); binding_hooks_.erase(iter); } else { - hooks = std::make_unique<APIBindingHooks>(api_name, call_js_sync_); + hooks = std::make_unique<APIBindingHooks>(api_name); } return std::make_unique<APIBinding>( @@ -125,7 +117,7 @@ << "Hook registration must happen before creating any binding instances."; std::unique_ptr<APIBindingHooks>& hooks = binding_hooks_[api_name]; if (!hooks) - hooks = std::make_unique<APIBindingHooks>(api_name, call_js_sync_); + hooks = std::make_unique<APIBindingHooks>(api_name); return hooks.get(); }
diff --git a/extensions/renderer/bindings/api_bindings_system.h b/extensions/renderer/bindings/api_bindings_system.h index 4487f34..198ae80 100644 --- a/extensions/renderer/bindings/api_bindings_system.h +++ b/extensions/renderer/bindings/api_bindings_system.h
@@ -45,8 +45,6 @@ const BindingAccessChecker* access_checker)>; APIBindingsSystem( - const binding::RunJSFunction& call_js, - const binding::RunJSFunctionSync& call_js_sync, const GetAPISchemaMethod& get_api_schema, const BindingAccessChecker::AvailabilityCallback& is_available, const APIRequestHandler::SendRequestMethod& send_request, @@ -140,10 +138,6 @@ std::map<std::string, CustomTypeHandler> custom_types_; - binding::RunJSFunction call_js_; - - binding::RunJSFunctionSync call_js_sync_; - // The method to retrieve the DictionaryValue describing a given extension // API. Curried in for testing purposes so we can use fake APIs. GetAPISchemaMethod get_api_schema_;
diff --git a/extensions/renderer/bindings/api_bindings_system_unittest.cc b/extensions/renderer/bindings/api_bindings_system_unittest.cc index 963aa0c..5fd4a06f 100644 --- a/extensions/renderer/bindings/api_bindings_system_unittest.cc +++ b/extensions/renderer/bindings/api_bindings_system_unittest.cc
@@ -118,8 +118,6 @@ binding::AddConsoleError add_console_error(base::Bind( &APIBindingsSystemTest::AddConsoleError, base::Unretained(this))); bindings_system_ = std::make_unique<APIBindingsSystem>( - base::Bind(&RunFunctionOnGlobalAndIgnoreResult), - base::Bind(&RunFunctionOnGlobalAndReturnHandle), base::Bind(&APIBindingsSystemTest::GetAPISchema, base::Unretained(this)), base::Bind(&AllowAllAPIs), base::Bind(&APIBindingsSystemTest::OnAPIRequest, base::Unretained(this)), @@ -446,7 +444,6 @@ v8::Local<v8::Context> context = MainContext(); auto create_custom_event = [](v8::Local<v8::Context> context, - const binding::RunJSFunctionSync& run_js, const std::string& event_name) { v8::Isolate* isolate = context->GetIsolate(); v8::Local<v8::Object> ret = v8::Object::New(isolate);
diff --git a/extensions/renderer/bindings/api_event_handler.cc b/extensions/renderer/bindings/api_event_handler.cc index d7a88357..314062e 100644 --- a/extensions/renderer/bindings/api_event_handler.cc +++ b/extensions/renderer/bindings/api_event_handler.cc
@@ -17,6 +17,7 @@ #include "content/public/renderer/v8_value_converter.h" #include "extensions/renderer/bindings/api_event_listeners.h" #include "extensions/renderer/bindings/event_emitter.h" +#include "extensions/renderer/bindings/js_runner.h" #include "gin/handle.h" #include "gin/per_context_data.h" @@ -107,13 +108,9 @@ } // namespace APIEventHandler::APIEventHandler( - const binding::RunJSFunction& call_js, - const binding::RunJSFunctionSync& call_js_sync, const EventListenersChangedMethod& listeners_changed, ExceptionHandler* exception_handler) - : call_js_(call_js), - call_js_sync_(call_js_sync), - listeners_changed_(listeners_changed), + : listeners_changed_(listeners_changed), exception_handler_(exception_handler) {} APIEventHandler::~APIEventHandler() {} @@ -146,10 +143,10 @@ updated, max_listeners, supports_lazy_listeners); } - gin::Handle<EventEmitter> emitter_handle = gin::CreateHandle( - context->GetIsolate(), - new EventEmitter(supports_filters, std::move(listeners), call_js_, - call_js_sync_, exception_handler_)); + gin::Handle<EventEmitter> emitter_handle = + gin::CreateHandle(context->GetIsolate(), + new EventEmitter(supports_filters, std::move(listeners), + exception_handler_)); CHECK(!emitter_handle.IsEmpty()); v8::Local<v8::Value> emitter_value = emitter_handle.ToV8(); CHECK(emitter_value->IsObject()); @@ -170,10 +167,10 @@ std::make_unique<UnfilteredEventListeners>( base::Bind(&DoNothingOnListenersChanged), binding::kNoListenerMax, false); - gin::Handle<EventEmitter> emitter_handle = gin::CreateHandle( - context->GetIsolate(), - new EventEmitter(supports_filters, std::move(listeners), call_js_, - call_js_sync_, exception_handler_)); + gin::Handle<EventEmitter> emitter_handle = + gin::CreateHandle(context->GetIsolate(), + new EventEmitter(supports_filters, std::move(listeners), + exception_handler_)); CHECK(!emitter_handle.IsEmpty()); v8::Local<v8::Object> emitter_object = emitter_handle.ToV8().As<v8::Object>(); data->anonymous_emitters.push_back( @@ -275,7 +272,8 @@ isolate, &DispatchEvent, gin::StringToSymbol(isolate, event_name)); v8::Local<v8::Value> massager_args[] = {args_array, dispatch_event}; - call_js_.Run(massager, context, arraysize(massager_args), massager_args); + JSRunner::Get(context)->RunJSFunction( + massager, context, arraysize(massager_args), massager_args); } }
diff --git a/extensions/renderer/bindings/api_event_handler.h b/extensions/renderer/bindings/api_event_handler.h index 268614a9..f7d0e711 100644 --- a/extensions/renderer/bindings/api_event_handler.h +++ b/extensions/renderer/bindings/api_event_handler.h
@@ -41,9 +41,7 @@ bool update_lazy_listeners, v8::Local<v8::Context>)>; - APIEventHandler(const binding::RunJSFunction& call_js, - const binding::RunJSFunctionSync& call_js_sync, - const EventListenersChangedMethod& listeners_changed, + APIEventHandler(const EventListenersChangedMethod& listeners_changed, ExceptionHandler* exception_handler); ~APIEventHandler(); @@ -106,10 +104,6 @@ v8::Local<v8::Context> context); private: - // Method to run a given v8::Function. Curried in for testing. - binding::RunJSFunction call_js_; - binding::RunJSFunctionSync call_js_sync_; - EventListenersChangedMethod listeners_changed_; // The associated EventFilter; shared across all contexts and events.
diff --git a/extensions/renderer/bindings/api_event_handler_unittest.cc b/extensions/renderer/bindings/api_event_handler_unittest.cc index dadeb5cb..5d09232 100644 --- a/extensions/renderer/bindings/api_event_handler_unittest.cc +++ b/extensions/renderer/bindings/api_event_handler_unittest.cc
@@ -14,6 +14,7 @@ #include "extensions/renderer/bindings/api_binding_test.h" #include "extensions/renderer/bindings/api_binding_test_util.h" #include "extensions/renderer/bindings/exception_handler.h" +#include "extensions/renderer/bindings/test_js_runner.h" #include "gin/arguments.h" #include "gin/converter.h" #include "gin/public/context_holder.h" @@ -45,8 +46,6 @@ void SetUp() override { APIBindingTest::SetUp(); handler_ = std::make_unique<APIEventHandler>( - base::Bind(&RunFunctionOnGlobalAndIgnoreResult), - base::Bind(&RunFunctionOnGlobalAndReturnHandle), base::Bind(&DoNothingOnEventListenersChanged), nullptr); } @@ -530,30 +529,13 @@ // Test an event listener throwing an exception. TEST_F(APIEventHandlerTest, TestEventListenersThrowingExceptions) { - // The default test util methods (RunFunction*) assume no errors will ever - // be encountered. Instead, use an implementation that allows errors. - auto run_js_and_expect_error = [](v8::Local<v8::Function> function, - v8::Local<v8::Context> context, int argc, - v8::Local<v8::Value> argv[]) { - v8::MaybeLocal<v8::Value> maybe_result = - function->Call(context, context->Global(), argc, argv); - v8::Global<v8::Value> result; - v8::Local<v8::Value> local; - if (maybe_result.ToLocal(&local)) - result.Reset(context->GetIsolate(), local); - }; - auto log_error = [](std::vector<std::string>* errors_out, v8::Local<v8::Context> context, const std::string& error) { errors_out->push_back(error); }; std::vector<std::string> logged_errors; - ExceptionHandler exception_handler( - base::Bind(log_error, &logged_errors), - base::Bind(&RunFunctionOnGlobalAndIgnoreResult)); + ExceptionHandler exception_handler(base::Bind(log_error, &logged_errors)); SetHandler(std::make_unique<APIEventHandler>( - base::Bind(run_js_and_expect_error), - base::Bind(&RunFunctionOnGlobalAndReturnHandle), base::Bind(&DoNothingOnEventListenersChanged), &exception_handler)); v8::HandleScope handle_scope(isolate()); @@ -588,7 +570,11 @@ std::unique_ptr<base::ListValue> event_args = ListValueFromString("[42]"); ASSERT_TRUE(event_args); - handler()->FireEventInContext(kEventName, context, *event_args, nullptr); + + { + TestJSRunner::AllowErrors allow_errors; + handler()->FireEventInContext(kEventName, context, *event_args, nullptr); + } // An exception should have been thrown by the first listener and the second // listener should have recorded the event arguments. @@ -605,10 +591,7 @@ // Tests being notified as listeners are added or removed from events. TEST_F(APIEventHandlerTest, CallbackNotifications) { MockEventChangeHandler change_handler; - SetHandler(std::make_unique<APIEventHandler>( - base::Bind(&RunFunctionOnGlobalAndIgnoreResult), - base::Bind(&RunFunctionOnGlobalAndReturnHandle), change_handler.Get(), - nullptr)); + SetHandler(std::make_unique<APIEventHandler>(change_handler.Get(), nullptr)); v8::HandleScope handle_scope(isolate()); @@ -881,9 +864,7 @@ v8::Local<v8::Context> context = MainContext(); MockEventChangeHandler change_handler; - APIEventHandler handler(base::Bind(&RunFunctionOnGlobalAndIgnoreResult), - base::Bind(&RunFunctionOnGlobalAndReturnHandle), - change_handler.Get(), nullptr); + APIEventHandler handler(change_handler.Get(), nullptr); v8::Local<v8::Object> event = handler.CreateAnonymousEventInstance(context); ASSERT_FALSE(event.IsEmpty()); @@ -930,9 +911,7 @@ v8::Local<v8::Context> context = MainContext(); MockEventChangeHandler change_handler; - APIEventHandler handler(base::Bind(&RunFunctionOnGlobalAndIgnoreResult), - base::Bind(&RunFunctionOnGlobalAndReturnHandle), - change_handler.Get(), nullptr); + APIEventHandler handler(change_handler.Get(), nullptr); v8::Local<v8::Object> event = handler.CreateAnonymousEventInstance(context); ASSERT_FALSE(event.IsEmpty()); @@ -957,9 +936,7 @@ const base::DictionaryValue* filter, bool was_manual, v8::Local<v8::Context> context) { ADD_FAILURE(); }; - APIEventHandler handler(base::Bind(&RunFunctionOnGlobalAndIgnoreResult), - base::Bind(&RunFunctionOnGlobalAndReturnHandle), - base::Bind(fail_on_notified), nullptr); + APIEventHandler handler(base::Bind(fail_on_notified), nullptr); const char kEventName[] = "alpha"; v8::Local<v8::Object> event = handler.CreateEventInstance( @@ -1001,9 +978,7 @@ // Test callback notifications for events that don't support lazy listeners. TEST_F(APIEventHandlerTest, TestEventsWithoutLazyListeners) { MockEventChangeHandler change_handler; - APIEventHandler handler(base::Bind(&RunFunctionOnGlobalAndIgnoreResult), - base::Bind(&RunFunctionOnGlobalAndReturnHandle), - change_handler.Get(), nullptr); + APIEventHandler handler(change_handler.Get(), nullptr); v8::HandleScope handle_scope(isolate()); v8::Local<v8::Context> context = MainContext();
diff --git a/extensions/renderer/bindings/api_request_handler.cc b/extensions/renderer/bindings/api_request_handler.cc index 14ea36d0..e49bd57 100644 --- a/extensions/renderer/bindings/api_request_handler.cc +++ b/extensions/renderer/bindings/api_request_handler.cc
@@ -10,6 +10,7 @@ #include "base/values.h" #include "content/public/renderer/v8_value_converter.h" #include "extensions/renderer/bindings/exception_handler.h" +#include "extensions/renderer/bindings/js_runner.h" #include "gin/converter.h" #include "gin/data_object_builder.h" #include "third_party/WebKit/public/web/WebScopedUserGesture.h" @@ -43,11 +44,9 @@ PendingRequest&&) = default; APIRequestHandler::APIRequestHandler(const SendRequestMethod& send_request, - const CallJSFunction& call_js, APILastError last_error, ExceptionHandler* exception_handler) : send_request_(send_request), - call_js_(call_js), last_error_(std::move(last_error)), exception_handler_(exception_handler) {} @@ -173,8 +172,8 @@ v8::TryCatch try_catch(isolate); // args.size() is converted to int, but args is controlled by chrome and is // never close to std::numeric_limits<int>::max. - call_js_.Run(pending_request.callback.Get(isolate), context, args.size(), - args.data()); + JSRunner::Get(context)->RunJSFunction(pending_request.callback.Get(isolate), + context, args.size(), args.data()); if (try_catch.HasCaught()) { v8::Local<v8::Message> v8_message = try_catch.Message(); base::Optional<std::string> message;
diff --git a/extensions/renderer/bindings/api_request_handler.h b/extensions/renderer/bindings/api_request_handler.h index cb3e80d..53c4d38 100644 --- a/extensions/renderer/bindings/api_request_handler.h +++ b/extensions/renderer/bindings/api_request_handler.h
@@ -48,13 +48,7 @@ using SendRequestMethod = base::Callback<void(std::unique_ptr<Request>, v8::Local<v8::Context>)>; - using CallJSFunction = base::Callback<void(v8::Local<v8::Function>, - v8::Local<v8::Context>, - int argc, - v8::Local<v8::Value>[])>; - APIRequestHandler(const SendRequestMethod& send_request, - const CallJSFunction& call_js, APILastError last_error, ExceptionHandler* exception_handler); ~APIRequestHandler(); @@ -124,12 +118,6 @@ SendRequestMethod send_request_; - // The method to call into a JS with specific arguments. We curry this in - // because the manner we want to do this is a unittest (e.g. - // v8::Function::Call) can be significantly different than in production - // (where we have to deal with e.g. blocking javascript). - CallJSFunction call_js_; - APILastError last_error_; // The exception handler for the bindings system; guaranteed to be valid
diff --git a/extensions/renderer/bindings/api_request_handler_unittest.cc b/extensions/renderer/bindings/api_request_handler_unittest.cc index c12b8a4..fd8f8dc 100644 --- a/extensions/renderer/bindings/api_request_handler_unittest.cc +++ b/extensions/renderer/bindings/api_request_handler_unittest.cc
@@ -12,6 +12,7 @@ #include "extensions/renderer/bindings/api_binding_test.h" #include "extensions/renderer/bindings/api_binding_test_util.h" #include "extensions/renderer/bindings/exception_handler.h" +#include "extensions/renderer/bindings/test_js_runner.h" #include "gin/converter.h" #include "gin/function_template.h" #include "gin/public/context_holder.h" @@ -40,19 +41,9 @@ class APIRequestHandlerTest : public APIBindingTest { public: - // Runs the given |function|. - void RunJS(v8::Local<v8::Function> function, - v8::Local<v8::Context> context, - int argc, - v8::Local<v8::Value> argv[]) { - RunFunctionOnGlobal(function, context, argc, argv); - did_run_js_ = true; - } - std::unique_ptr<APIRequestHandler> CreateRequestHandler() { return std::make_unique<APIRequestHandler>( base::Bind(&DoNothingWithRequest), - base::Bind(&APIRequestHandlerTest::RunJS, base::Unretained(this)), APILastError(APILastError::GetParent(), binding::AddConsoleError()), nullptr); } @@ -61,9 +52,17 @@ APIRequestHandlerTest() {} ~APIRequestHandlerTest() override {} + std::unique_ptr<TestJSRunner::Scope> CreateTestJSRunner() override { + return std::make_unique<TestJSRunner::Scope>( + std::make_unique<TestJSRunner>(base::Bind( + &APIRequestHandlerTest::SetDidRunJS, base::Unretained(this)))); + } + bool did_run_js() const { return did_run_js_; } private: + void SetDidRunJS() { did_run_js_ = true; } + bool did_run_js_ = false; DISALLOW_COPY_AND_ASSIGN(APIRequestHandlerTest); @@ -342,7 +341,6 @@ APIRequestHandler request_handler( base::Bind(on_request, &thread), - base::Bind(&APIRequestHandlerTest::RunJS, base::Unretained(this)), APILastError(APILastError::GetParent(), binding::AddConsoleError()), nullptr); @@ -379,7 +377,6 @@ APIRequestHandler request_handler( base::Bind(&DoNothingWithRequest), - base::Bind(&APIRequestHandlerTest::RunJS, base::Unretained(this)), APILastError(base::Bind(get_parent), base::Bind(log_error, &logged_error)), nullptr); @@ -454,7 +451,6 @@ APIRequestHandler request_handler( base::Bind(handle_request, &dispatched_request), - base::Bind(&APIRequestHandlerTest::RunJS, base::Unretained(this)), APILastError(APILastError::GetParent(), binding::AddConsoleError()), nullptr); @@ -492,22 +488,12 @@ v8::Local<v8::Context> context, const std::string& error) { *error_out = error; }; - // RunFunction* from the test util assert no errors; provide a version that - // allows them. - auto run_function_and_allow_errors = - [](v8::Local<v8::Function> function, v8::Local<v8::Context> context, - int argc, v8::Local<v8::Value> argv[]) { - ignore_result(function->Call(context, context->Global(), argc, argv)); - }; - base::Optional<std::string> logged_error; ExceptionHandler exception_handler( - base::Bind(add_console_error, &logged_error), - base::Bind(&RunFunctionOnGlobalAndIgnoreResult)); + base::Bind(add_console_error, &logged_error)); APIRequestHandler request_handler( base::Bind(&DoNothingWithRequest), - base::Bind(run_function_and_allow_errors), APILastError(APILastError::GetParent(), binding::AddConsoleError()), &exception_handler); @@ -516,7 +502,12 @@ FunctionFromString(context, "(function() { throw new Error('hello'); })"); int request_id = request_handler.AddPendingRequest(context, callback_throwing_error); - request_handler.CompleteRequest(request_id, base::ListValue(), std::string()); + + { + TestJSRunner::AllowErrors allow_errors; + request_handler.CompleteRequest(request_id, base::ListValue(), + std::string()); + } // |outer_try_catch| should not have caught an error. This is important to not // disrupt our bindings code (or other running JS) when asynchronously // returning from an API call. Instead, the error should be caught and handled
diff --git a/extensions/renderer/bindings/declarative_event_unittest.cc b/extensions/renderer/bindings/declarative_event_unittest.cc index e85d5dc..bf7c032 100644 --- a/extensions/renderer/bindings/declarative_event_unittest.cc +++ b/extensions/renderer/bindings/declarative_event_unittest.cc
@@ -93,7 +93,6 @@ request_handler_ = std::make_unique<APIRequestHandler>( base::Bind(&DeclarativeEventTest::OnRequest, base::Unretained(this)), - base::Bind(&RunFunctionOnGlobalAndIgnoreResult), APILastError(APILastError::GetParent(), binding::AddConsoleError()), nullptr); }
diff --git a/extensions/renderer/bindings/event_emitter.cc b/extensions/renderer/bindings/event_emitter.cc index 0abca94..d7cd00c 100644 --- a/extensions/renderer/bindings/event_emitter.cc +++ b/extensions/renderer/bindings/event_emitter.cc
@@ -8,6 +8,7 @@ #include "extensions/renderer/bindings/api_event_listeners.h" #include "extensions/renderer/bindings/exception_handler.h" +#include "extensions/renderer/bindings/js_runner.h" #include "gin/data_object_builder.h" #include "gin/object_template_builder.h" #include "gin/per_context_data.h" @@ -18,13 +19,9 @@ EventEmitter::EventEmitter(bool supports_filters, std::unique_ptr<APIEventListeners> listeners, - const binding::RunJSFunction& run_js, - const binding::RunJSFunctionSync& run_js_sync, ExceptionHandler* exception_handler) : supports_filters_(supports_filters), listeners_(std::move(listeners)), - run_js_(run_js), - run_js_sync_(run_js_sync), exception_handler_(exception_handler) {} EventEmitter::~EventEmitter() {} @@ -181,15 +178,16 @@ v8::Isolate* isolate = context->GetIsolate(); v8::TryCatch try_catch(isolate); + JSRunner* js_runner = JSRunner::Get(context); for (const auto& listener : listeners) { if (run_sync) { DCHECK(out_values); - v8::Global<v8::Value> result = - run_js_sync_.Run(listener, context, args->size(), args->data()); + v8::Global<v8::Value> result = js_runner->RunJSFunctionSync( + listener, context, args->size(), args->data()); if (!result.IsEmpty() && !result.Get(isolate)->IsUndefined()) out_values->push_back(std::move(result)); } else { - run_js_.Run(listener, context, args->size(), args->data()); + js_runner->RunJSFunction(listener, context, args->size(), args->data()); } if (try_catch.HasCaught()) {
diff --git a/extensions/renderer/bindings/event_emitter.h b/extensions/renderer/bindings/event_emitter.h index 1f86961..7f8fbf3d 100644 --- a/extensions/renderer/bindings/event_emitter.h +++ b/extensions/renderer/bindings/event_emitter.h
@@ -7,7 +7,6 @@ #include <vector> -#include "extensions/renderer/bindings/api_binding_types.h" #include "gin/wrappable.h" #include "v8/include/v8.h" @@ -27,8 +26,6 @@ public: EventEmitter(bool supports_filters, std::unique_ptr<APIEventListeners> listeners, - const binding::RunJSFunction& run_js, - const binding::RunJSFunctionSync& run_js_sync, ExceptionHandler* exception_handler); ~EventEmitter() override; @@ -76,9 +73,6 @@ std::unique_ptr<APIEventListeners> listeners_; - binding::RunJSFunction run_js_; - binding::RunJSFunctionSync run_js_sync_; - // The associated exception handler; guaranteed to outlive this object. ExceptionHandler* const exception_handler_;
diff --git a/extensions/renderer/bindings/event_emitter_unittest.cc b/extensions/renderer/bindings/event_emitter_unittest.cc index 55679fb..9088183 100644 --- a/extensions/renderer/bindings/event_emitter_unittest.cc +++ b/extensions/renderer/bindings/event_emitter_unittest.cc
@@ -11,6 +11,7 @@ #include "extensions/renderer/bindings/api_binding_test_util.h" #include "extensions/renderer/bindings/api_event_listeners.h" #include "extensions/renderer/bindings/exception_handler.h" +#include "extensions/renderer/bindings/test_js_runner.h" #include "gin/handle.h" #include "testing/gmock/include/gmock/gmock.h" @@ -33,37 +34,16 @@ auto listeners = std::make_unique<UnfilteredEventListeners>( base::Bind(&DoNothingOnListenerChange), binding::kNoListenerMax, true); - // The test util methods enforce that functions always throw or always don't - // throw, but we test listeners that do both. Provide implementations for - // running functions that don't enforce throw behavior. - auto run_js_sync = [](v8::Local<v8::Function> function, - v8::Local<v8::Context> context, int argc, - v8::Local<v8::Value> argv[]) { - v8::Global<v8::Value> global_result; - v8::Local<v8::Value> result; - if (function->Call(context, context->Global(), argc, argv).ToLocal(&result)) - global_result.Reset(context->GetIsolate(), result); - return global_result; - }; - - auto run_js = [](v8::Local<v8::Function> function, - v8::Local<v8::Context> context, int argc, - v8::Local<v8::Value> argv[]) { - ignore_result(function->Call(context, context->Global(), argc, argv)); - }; - auto log_error = [](std::vector<std::string>* errors, v8::Local<v8::Context> context, const std::string& error) { errors->push_back(error); }; std::vector<std::string> logged_errors; - ExceptionHandler exception_handler(base::Bind(log_error, &logged_errors), - base::Bind(run_js)); + ExceptionHandler exception_handler(base::Bind(log_error, &logged_errors)); gin::Handle<EventEmitter> event = gin::CreateHandle( isolate(), - new EventEmitter(false, std::move(listeners), base::Bind(run_js), - base::Bind(run_js_sync), &exception_handler)); + new EventEmitter(false, std::move(listeners), &exception_handler)); v8::Local<v8::Value> v8_event = event.ToV8(); @@ -113,6 +93,7 @@ " return event.dispatch('arg1', 2);\n" "})"; v8::Local<v8::Value> dispatch_args[] = {v8_event}; + TestJSRunner::AllowErrors allow_errors; v8::Local<v8::Value> dispatch_result = RunFunctionOnGlobal(FunctionFromString(context, kDispatch), context, arraysize(dispatch_args), dispatch_args);
diff --git a/extensions/renderer/bindings/exception_handler.cc b/extensions/renderer/bindings/exception_handler.cc index d371044..8f9bcca 100644 --- a/extensions/renderer/bindings/exception_handler.cc +++ b/extensions/renderer/bindings/exception_handler.cc
@@ -8,6 +8,7 @@ #include "base/memory/ptr_util.h" #include "base/strings/stringprintf.h" #include "base/supports_user_data.h" +#include "extensions/renderer/bindings/js_runner.h" #include "gin/converter.h" #include "gin/per_context_data.h" @@ -44,9 +45,8 @@ } // namespace ExceptionHandler::ExceptionHandler( - const binding::AddConsoleError& add_console_error, - const binding::RunJSFunction& run_js) - : add_console_error_(add_console_error), run_js_(run_js) {} + const binding::AddConsoleError& add_console_error) + : add_console_error_(add_console_error) {} ExceptionHandler::~ExceptionHandler() {} void ExceptionHandler::HandleException(v8::Local<v8::Context> context, @@ -93,7 +93,8 @@ // possible. Handle this gracefully, and log errors normally. v8::TryCatch handler_try_catch(isolate); handler_try_catch.SetVerbose(true); - run_js_.Run(handler, context, arraysize(arguments), arguments); + JSRunner::Get(context)->RunJSFunction(handler, context, + arraysize(arguments), arguments); } else { add_console_error_.Run(context, full_message); }
diff --git a/extensions/renderer/bindings/exception_handler.h b/extensions/renderer/bindings/exception_handler.h index 943a78d..c9e9090 100644 --- a/extensions/renderer/bindings/exception_handler.h +++ b/extensions/renderer/bindings/exception_handler.h
@@ -19,8 +19,7 @@ // execution or event handling. class ExceptionHandler { public: - ExceptionHandler(const binding::AddConsoleError& add_console_error, - const binding::RunJSFunction& run_js); + ExceptionHandler(const binding::AddConsoleError& add_console_error); ~ExceptionHandler(); // Handles an exception in the given |context|. |message| is a message to @@ -48,8 +47,6 @@ binding::AddConsoleError add_console_error_; - binding::RunJSFunction run_js_; - DISALLOW_COPY_AND_ASSIGN(ExceptionHandler); };
diff --git a/extensions/renderer/bindings/exception_handler_unittest.cc b/extensions/renderer/bindings/exception_handler_unittest.cc index 647620371..cf0eb377 100644 --- a/extensions/renderer/bindings/exception_handler_unittest.cc +++ b/extensions/renderer/bindings/exception_handler_unittest.cc
@@ -46,8 +46,7 @@ v8::Local<v8::Context> context = MainContext(); base::Optional<std::string> logged_error; - ExceptionHandler handler(base::Bind(&PopulateError, &logged_error), - base::Bind(&RunFunctionOnGlobalAndIgnoreResult)); + ExceptionHandler handler(base::Bind(&PopulateError, &logged_error)); ThrowException(context, "new Error('some error')", &handler); @@ -61,8 +60,7 @@ v8::Local<v8::Context> context_b = AddContext(); base::Optional<std::string> logged_error; - ExceptionHandler handler(base::Bind(&PopulateError, &logged_error), - base::Bind(&RunFunctionOnGlobalAndIgnoreResult)); + ExceptionHandler handler(base::Bind(&PopulateError, &logged_error)); v8::Local<v8::Function> custom_handler = FunctionFromString( context_a, @@ -109,8 +107,7 @@ v8::Local<v8::Context> context = MainContext(); base::Optional<std::string> logged_error; - ExceptionHandler handler(base::Bind(&PopulateError, &logged_error), - base::Bind(&RunFunctionOnGlobalAndIgnoreResult)); + ExceptionHandler handler(base::Bind(&PopulateError, &logged_error)); ThrowException(context, "'hello'", &handler); ASSERT_TRUE(logged_error); @@ -148,8 +145,7 @@ v8::Local<v8::Context> context = MainContext(); base::Optional<std::string> logged_error; - ExceptionHandler handler(base::Bind(&PopulateError, &logged_error), - base::Bind(&RunFunctionOnGlobalAndIgnoreResult)); + ExceptionHandler handler(base::Bind(&PopulateError, &logged_error)); { v8::TryCatch try_catch(isolate());
diff --git a/extensions/renderer/bindings/js_runner.cc b/extensions/renderer/bindings/js_runner.cc new file mode 100644 index 0000000..2e02cf1 --- /dev/null +++ b/extensions/renderer/bindings/js_runner.cc
@@ -0,0 +1,76 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "extensions/renderer/bindings/js_runner.h" + +#include "base/supports_user_data.h" +#include "gin/per_context_data.h" + +namespace extensions { +namespace { + +constexpr char kExtensionJSRunnerPerContextKey[] = "extension_js_runner"; + +struct JSRunnerPerContextData : public base::SupportsUserData::Data { + explicit JSRunnerPerContextData(std::unique_ptr<JSRunner> js_runner) + : js_runner(std::move(js_runner)) {} + ~JSRunnerPerContextData() override {} + + std::unique_ptr<JSRunner> js_runner; +}; + +JSRunner* g_instance_for_testing = nullptr; + +} // namespace + +// static +JSRunner* JSRunner::Get(v8::Local<v8::Context> context) { + if (g_instance_for_testing) + return g_instance_for_testing; + + gin::PerContextData* per_context_data = gin::PerContextData::From(context); + if (!per_context_data) + return nullptr; + auto* data = static_cast<JSRunnerPerContextData*>( + per_context_data->GetUserData(kExtensionJSRunnerPerContextKey)); + if (!data) + return nullptr; + + return data->js_runner.get(); +} + +void JSRunner::SetInstanceForContext(v8::Local<v8::Context> context, + std::unique_ptr<JSRunner> js_runner) { + gin::PerContextData* per_context_data = gin::PerContextData::From(context); + // We should never try to set an instance for a context that's being torn + // down. + CHECK(per_context_data); + // We should never have an existing instance for this context. + DCHECK(!per_context_data->GetUserData(kExtensionJSRunnerPerContextKey)); + + per_context_data->SetUserData( + kExtensionJSRunnerPerContextKey, + std::make_unique<JSRunnerPerContextData>(std::move(js_runner))); +} + +void JSRunner::ClearInstanceForContext(v8::Local<v8::Context> context) { + gin::PerContextData* per_context_data = gin::PerContextData::From(context); + // We should never try to clear an instance for a context that's being torn + // down. + CHECK(per_context_data); + // We should always have an existing instance for this context. + DCHECK(per_context_data->GetUserData(kExtensionJSRunnerPerContextKey)); + + per_context_data->SetUserData(kExtensionJSRunnerPerContextKey, nullptr); +} + +void JSRunner::SetInstanceForTesting(JSRunner* js_runner) { + g_instance_for_testing = js_runner; +} + +JSRunner* JSRunner::GetInstanceForTesting() { + return g_instance_for_testing; +} + +} // namespace extensions
diff --git a/extensions/renderer/bindings/js_runner.h b/extensions/renderer/bindings/js_runner.h new file mode 100644 index 0000000..dbb05cb --- /dev/null +++ b/extensions/renderer/bindings/js_runner.h
@@ -0,0 +1,59 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef EXTENSIONS_RENDERER_BINDINGS_JS_RUNNER_H_ +#define EXTENSIONS_RENDERER_BINDINGS_JS_RUNNER_H_ + +#include <memory> + +#include "v8/include/v8.h" + +namespace extensions { + +// A helper class to execute JS functions safely. +class JSRunner { + public: + // Returns the instance of the JSRunner for the specified |context|. + static JSRunner* Get(v8::Local<v8::Context> context); + + // Sets the instance for a given |context|. + static void SetInstanceForContext(v8::Local<v8::Context> context, + std::unique_ptr<JSRunner> runner); + // Clears the instance for a given |context|. + static void ClearInstanceForContext(v8::Local<v8::Context> context); + + virtual ~JSRunner() {} + + // Calls the given |function| in the specified |context| and with the provided + // arguments. JS may be executed asynchronously if it has been suspended in + // the context. + virtual void RunJSFunction(v8::Local<v8::Function> function, + v8::Local<v8::Context> context, + int argc, + v8::Local<v8::Value> argv[]) = 0; + + // Executes the given |function| synchronously and returns the result. Note + // this should only be called if you're certain that script is not currently + // suspended in this context; if execution is suspended, this will fail a + // CHECK. We use a Global instead of a Local because certain implementations + // need to create a persistent handle in order to prevent immediate + // destruction of the locals. + // TODO(devlin): if we could, using Local here with an EscapableHandleScope + // would be preferable. + virtual v8::Global<v8::Value> RunJSFunctionSync( + v8::Local<v8::Function> function, + v8::Local<v8::Context> context, + int argc, + v8::Local<v8::Value> argv[]) = 0; + + // Sets a global instance for testing that will be returned instead of the + // per-context version (if any). + static void SetInstanceForTesting(JSRunner* runner); + // Returns the global testing instance. + static JSRunner* GetInstanceForTesting(); +}; + +} // namespace extensions + +#endif // EXTENSIONS_RENDERER_BINDINGS_JS_RUNNER_H_
diff --git a/extensions/renderer/bindings/test_js_runner.cc b/extensions/renderer/bindings/test_js_runner.cc new file mode 100644 index 0000000..a02f6434 --- /dev/null +++ b/extensions/renderer/bindings/test_js_runner.cc
@@ -0,0 +1,79 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "extensions/renderer/bindings/test_js_runner.h" + +#include "base/bind.h" +#include "base/memory/ptr_util.h" +#include "extensions/renderer/bindings/api_binding_test_util.h" + +namespace extensions { + +namespace { + +// NOTE(devlin): This isn't thread-safe. If we have multi-threaded unittests, +// we'll need to expand this. +bool g_allow_errors = false; + +} // namespace + +TestJSRunner::Scope::Scope(std::unique_ptr<JSRunner> runner) + : runner_(std::move(runner)), + old_runner_(JSRunner::GetInstanceForTesting()) { + DCHECK_NE(runner_.get(), old_runner_); + JSRunner::SetInstanceForTesting(runner_.get()); +} + +TestJSRunner::Scope::~Scope() { + DCHECK_EQ(runner_.get(), JSRunner::GetInstanceForTesting()); + JSRunner::SetInstanceForTesting(old_runner_); +} + +TestJSRunner::AllowErrors::AllowErrors() { + DCHECK(!g_allow_errors) << "Nested AllowErrors() blocks are not allowed."; + g_allow_errors = true; +} + +TestJSRunner::AllowErrors::~AllowErrors() { + DCHECK(g_allow_errors); + g_allow_errors = false; +} + +TestJSRunner::TestJSRunner() {} +TestJSRunner::TestJSRunner(const base::Closure& will_call_js) + : will_call_js_(will_call_js) {} +TestJSRunner::~TestJSRunner() {} + +void TestJSRunner::RunJSFunction(v8::Local<v8::Function> function, + v8::Local<v8::Context> context, + int argc, + v8::Local<v8::Value> argv[]) { + if (will_call_js_) + will_call_js_.Run(); + + if (g_allow_errors) + ignore_result(function->Call(context, context->Global(), argc, argv)); + else + RunFunctionOnGlobal(function, context, argc, argv); +} + +v8::Global<v8::Value> TestJSRunner::RunJSFunctionSync( + v8::Local<v8::Function> function, + v8::Local<v8::Context> context, + int argc, + v8::Local<v8::Value> argv[]) { + if (will_call_js_) + will_call_js_.Run(); + + if (g_allow_errors) { + v8::Global<v8::Value> global_result; + v8::Local<v8::Value> result; + if (function->Call(context, context->Global(), argc, argv).ToLocal(&result)) + global_result.Reset(context->GetIsolate(), result); + return global_result; + } + return RunFunctionOnGlobalAndReturnHandle(function, context, argc, argv); +} + +} // namespace extensions
diff --git a/extensions/renderer/bindings/test_js_runner.h b/extensions/renderer/bindings/test_js_runner.h new file mode 100644 index 0000000..5b27e24 --- /dev/null +++ b/extensions/renderer/bindings/test_js_runner.h
@@ -0,0 +1,81 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef EXTENSIONS_RENDERER_BINDINGS_TEST_JS_RUNNER_H_ +#define EXTENSIONS_RENDERER_BINDINGS_TEST_JS_RUNNER_H_ + +#include "base/callback.h" +#include "base/macros.h" +#include "extensions/renderer/bindings/js_runner.h" + +namespace extensions { + +// A JSRunner implementation designed for use in unit tests. Does not handle +// any kind of script suspension. By default, all functions are expected to +// succeed and not throw any exceptions. If running a function is expected to +// result in errors, use a TestJSRunner::AllowErrors object in as narrow a +// scope as possible. +class TestJSRunner : public JSRunner { + public: + // A scoped object that handles setting and resetting the instance for the + // current thread. Note: multiple scopes can be nested, but they must follow + // a LIFO destruction order. That is, the following is safe: + // <begin> // JSRunner::Get() returns the default JSRunner (or none). + // Scope a(); // JSRunner::Get() returns a's JSRunner. + // Scope b(); // JSRunner::Get() returns b's JSRunner. + // ~Scope b(); // JSRunner::Get() returns a's JSRunner. + // ~Scope a(); // JSRunner::Get() returns the default JSRunner (or none). + // But the following will DCHECK: + // Scope a(); + // Scope b(); + // ~Scope a(); // DCHECKs. + // ~Scope b(); + class Scope { + public: + Scope(std::unique_ptr<JSRunner> runner); + ~Scope(); + + private: + std::unique_ptr<JSRunner> runner_; + JSRunner* old_runner_; + + DISALLOW_COPY_AND_ASSIGN(Scope); + }; + + // A scoped object that allows errors to be thrown from running JS functions. + // Note: *not* allowed to be nested; only one can be active at a time. + // Constructing multiple instances at the same time will DCHECK. + class AllowErrors { + public: + AllowErrors(); + ~AllowErrors(); + + private: + DISALLOW_COPY_AND_ASSIGN(AllowErrors); + }; + + TestJSRunner(); + // Provides a callback to be called just before JS will be executed. + explicit TestJSRunner(const base::Closure& will_call_js); + ~TestJSRunner() override; + + // JSRunner: + void RunJSFunction(v8::Local<v8::Function> function, + v8::Local<v8::Context> context, + int argc, + v8::Local<v8::Value> argv[]) override; + v8::Global<v8::Value> RunJSFunctionSync(v8::Local<v8::Function> function, + v8::Local<v8::Context> context, + int argc, + v8::Local<v8::Value> argv[]) override; + + private: + base::Closure will_call_js_; + + DISALLOW_COPY_AND_ASSIGN(TestJSRunner); +}; + +} // namespace extensions + +#endif // EXTENSIONS_RENDERER_BINDINGS_TEST_JS_RUNNER_H_
diff --git a/extensions/renderer/content_setting.cc b/extensions/renderer/content_setting.cc index 25e6d2d..ffce888 100644 --- a/extensions/renderer/content_setting.cc +++ b/extensions/renderer/content_setting.cc
@@ -8,10 +8,12 @@ #include "base/strings/stringprintf.h" #include "base/values.h" #include "content/public/common/console_message_level.h" +#include "extensions/renderer/bindings/api_binding_types.h" #include "extensions/renderer/bindings/api_request_handler.h" #include "extensions/renderer/bindings/api_signature.h" #include "extensions/renderer/bindings/api_type_reference_map.h" #include "extensions/renderer/bindings/binding_access_checker.h" +#include "extensions/renderer/bindings/js_runner.h" #include "extensions/renderer/console.h" #include "extensions/renderer/script_context_set.h" #include "gin/arguments.h" @@ -32,10 +34,10 @@ return std::find(std::begin(kDeprecatedTypes), std::end(kDeprecatedTypes), type) != std::end(kDeprecatedTypes); } -} + +} // namespace v8::Local<v8::Object> ContentSetting::Create( - const binding::RunJSFunction& run_js, v8::Isolate* isolate, const std::string& property_name, const base::ListValue* property_values, @@ -49,19 +51,17 @@ CHECK(property_values->GetDictionary(1u, &value_spec)); gin::Handle<ContentSetting> handle = gin::CreateHandle( - isolate, new ContentSetting(run_js, request_handler, type_refs, - access_checker, pref_name, *value_spec)); + isolate, new ContentSetting(request_handler, type_refs, access_checker, + pref_name, *value_spec)); return handle.ToV8().As<v8::Object>(); } -ContentSetting::ContentSetting(const binding::RunJSFunction& run_js, - APIRequestHandler* request_handler, +ContentSetting::ContentSetting(APIRequestHandler* request_handler, const APITypeReferenceMap* type_refs, const BindingAccessChecker* access_checker, const std::string& pref_name, const base::DictionaryValue& set_value_spec) - : run_js_(run_js), - request_handler_(request_handler), + : request_handler_(request_handler), type_refs_(type_refs), access_checker_(access_checker), pref_name_(pref_name), @@ -167,7 +167,8 @@ CHECK(result.ToChecked()); args.push_back(object); } - run_js_.Run(callback, context, args.size(), args.data()); + JSRunner::Get(context)->RunJSFunction(callback, context, args.size(), + args.data()); } return; }
diff --git a/extensions/renderer/content_setting.h b/extensions/renderer/content_setting.h index 4998fe2..e17e6e5 100644 --- a/extensions/renderer/content_setting.h +++ b/extensions/renderer/content_setting.h
@@ -8,7 +8,6 @@ #include <string> #include "base/macros.h" -#include "extensions/renderer/bindings/api_binding_types.h" #include "extensions/renderer/bindings/argument_spec.h" #include "gin/wrappable.h" #include "v8/include/v8.h" @@ -35,7 +34,6 @@ // Creates a ContentSetting object for the given property. static v8::Local<v8::Object> Create( - const binding::RunJSFunction& run_js, v8::Isolate* isolate, const std::string& property_name, const base::ListValue* property_values, @@ -50,8 +48,7 @@ v8::Isolate* isolate) override; private: - ContentSetting(const binding::RunJSFunction& run_js, - APIRequestHandler* request_handler, + ContentSetting(APIRequestHandler* request_handler, const APITypeReferenceMap* type_refs, const BindingAccessChecker* access_checker, const std::string& pref_name, @@ -67,8 +64,6 @@ void HandleFunction(const std::string& function_name, gin::Arguments* arguments); - binding::RunJSFunction run_js_; - APIRequestHandler* request_handler_; const APITypeReferenceMap* type_refs_;
diff --git a/extensions/renderer/declarative_content_hooks_delegate.h b/extensions/renderer/declarative_content_hooks_delegate.h index 9479a6a8..2ee4e0c 100644 --- a/extensions/renderer/declarative_content_hooks_delegate.h +++ b/extensions/renderer/declarative_content_hooks_delegate.h
@@ -9,6 +9,7 @@ #include <string> #include <vector> +#include "base/callback.h" #include "base/macros.h" #include "extensions/renderer/bindings/api_binding_hooks_delegate.h" #include "v8/include/v8.h"
diff --git a/extensions/renderer/dispatcher.cc b/extensions/renderer/dispatcher.cc index 3a567ea..ce92a98 100644 --- a/extensions/renderer/dispatcher.cc +++ b/extensions/renderer/dispatcher.cc
@@ -74,6 +74,7 @@ #include "extensions/renderer/js_extension_bindings_system.h" #include "extensions/renderer/logging_native_handler.h" #include "extensions/renderer/messaging_bindings.h" +#include "extensions/renderer/messaging_util.h" #include "extensions/renderer/module_system.h" #include "extensions/renderer/native_extension_bindings_system.h" #include "extensions/renderer/process_info_native_handler.h" @@ -1343,9 +1344,7 @@ int manifest_version = extension ? extension->manifest_version() : 1; bool is_component_extension = extension && Manifest::IsComponentLocation(extension->location()); - bool send_request_disabled = - (extension && Manifest::IsUnpackedLocation(extension->location()) && - BackgroundInfo::HasLazyBackgroundPage(extension)); + bool send_request_disabled = messaging_util::IsSendRequestDisabled(context); module_system->RegisterNativeHandler( "process", std::unique_ptr<NativeHandler>(new ProcessInfoNativeHandler(
diff --git a/extensions/renderer/extension_js_runner.cc b/extensions/renderer/extension_js_runner.cc new file mode 100644 index 0000000..e5f6decb --- /dev/null +++ b/extensions/renderer/extension_js_runner.cc
@@ -0,0 +1,53 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "extensions/renderer/extension_js_runner.h" + +#include "content/public/renderer/worker_thread.h" +#include "extensions/renderer/script_context.h" + +namespace extensions { + +ExtensionJSRunner::ExtensionJSRunner(ScriptContext* script_context) + : script_context_(script_context) {} +ExtensionJSRunner::~ExtensionJSRunner() {} + +void ExtensionJSRunner::RunJSFunction(v8::Local<v8::Function> function, + v8::Local<v8::Context> context, + int argc, + v8::Local<v8::Value> argv[]) { + DCHECK(script_context_->v8_context() == context); + + // TODO(devlin): Move ScriptContext::SafeCallFunction() into here? + script_context_->SafeCallFunction(function, argc, argv); +} + +v8::Global<v8::Value> ExtensionJSRunner::RunJSFunctionSync( + v8::Local<v8::Function> function, + v8::Local<v8::Context> context, + int argc, + v8::Local<v8::Value> argv[]) { + DCHECK(script_context_->v8_context() == context); + + bool did_complete = false; + v8::Global<v8::Value> result; + auto callback = base::Bind( + [](v8::Isolate* isolate, bool* did_complete_out, + v8::Global<v8::Value>* result_out, + const std::vector<v8::Local<v8::Value>>& results) { + *did_complete_out = true; + // The locals are released after the callback is executed, so we need to + // grab a persistent handle. + if (!results.empty() && !results[0].IsEmpty()) + result_out->Reset(isolate, results[0]); + }, + base::Unretained(context->GetIsolate()), base::Unretained(&did_complete), + base::Unretained(&result)); + + script_context_->SafeCallFunction(function, argc, argv, callback); + CHECK(did_complete) << "expected script to execute synchronously"; + return result; +} + +} // namespace extensions
diff --git a/extensions/renderer/extension_js_runner.h b/extensions/renderer/extension_js_runner.h new file mode 100644 index 0000000..034800a --- /dev/null +++ b/extensions/renderer/extension_js_runner.h
@@ -0,0 +1,39 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef EXTENSIONS_RENDERER_EXTENSION_JS_RUNNER_H_ +#define EXTENSIONS_RENDERER_EXTENSION_JS_RUNNER_H_ + +#include "base/macros.h" +#include "extensions/renderer/bindings/js_runner.h" + +namespace extensions { +class ScriptContext; + +// Implementation of a JSRunner that handles possible JS suspension. +class ExtensionJSRunner : public JSRunner { + public: + explicit ExtensionJSRunner(ScriptContext* script_context); + ~ExtensionJSRunner() override; + + // JSRunner: + void RunJSFunction(v8::Local<v8::Function> function, + v8::Local<v8::Context> context, + int argc, + v8::Local<v8::Value> argv[]) override; + v8::Global<v8::Value> RunJSFunctionSync(v8::Local<v8::Function> function, + v8::Local<v8::Context> context, + int argc, + v8::Local<v8::Value> argv[]) override; + + private: + // The associated ScriptContext. Guaranteed to outlive this object. + ScriptContext* const script_context_; + + DISALLOW_COPY_AND_ASSIGN(ExtensionJSRunner); +}; + +} // namespace extensions + +#endif // EXTENSIONS_RENDERER_EXTENSION_JS_RUNNER_H_
diff --git a/extensions/renderer/gin_port_unittest.cc b/extensions/renderer/gin_port_unittest.cc index 6012bee..c852f6a 100644 --- a/extensions/renderer/gin_port_unittest.cc +++ b/extensions/renderer/gin_port_unittest.cc
@@ -71,8 +71,6 @@ void SetUp() override { APIBindingTest::SetUp(); event_handler_ = std::make_unique<APIEventHandler>( - base::Bind(&RunFunctionOnGlobalAndIgnoreResult), - base::Bind(&RunFunctionOnGlobalAndReturnHandle), base::Bind(&DoNothingOnEventListenersChanged), nullptr); delegate_ = std::make_unique<testing::StrictMock<TestPortDelegate>>(); }
diff --git a/extensions/renderer/messaging_util.cc b/extensions/renderer/messaging_util.cc index 4401f76..cd8ac41a 100644 --- a/extensions/renderer/messaging_util.cc +++ b/extensions/renderer/messaging_util.cc
@@ -11,6 +11,8 @@ #include "base/strings/stringprintf.h" #include "extensions/common/api/messaging/message.h" #include "extensions/common/extension.h" +#include "extensions/common/manifest.h" +#include "extensions/common/manifest_handlers/background_info.h" #include "extensions/renderer/script_context.h" #include "gin/converter.h" #include "gin/dictionary.h" @@ -292,5 +294,11 @@ *arguments_out = {target_id, message, response_callback}; } +bool IsSendRequestDisabled(ScriptContext* script_context) { + const Extension* extension = script_context->extension(); + return extension && Manifest::IsUnpackedLocation(extension->location()) && + BackgroundInfo::HasLazyBackgroundPage(extension); +} + } // namespace messaging_util } // namespace extensions
diff --git a/extensions/renderer/messaging_util.h b/extensions/renderer/messaging_util.h index bc2d4f1..89dc8cd 100644 --- a/extensions/renderer/messaging_util.h +++ b/extensions/renderer/messaging_util.h
@@ -102,6 +102,10 @@ bool allow_options_argument, std::vector<v8::Local<v8::Value>>* arguments_out); +// Returns true if the sendRequest-related properties are disabled for the given +// |script_context|. +bool IsSendRequestDisabled(ScriptContext* script_context); + } // namespace messaging_util } // namespace extensions
diff --git a/extensions/renderer/native_extension_bindings_system.cc b/extensions/renderer/native_extension_bindings_system.cc index ebe10b5..7daa89f 100644 --- a/extensions/renderer/native_extension_bindings_system.cc +++ b/extensions/renderer/native_extension_bindings_system.cc
@@ -27,6 +27,7 @@ #include "extensions/renderer/declarative_content_hooks_delegate.h" #include "extensions/renderer/easy_unlock_proximity_required_stub.h" #include "extensions/renderer/extension_frame_helper.h" +#include "extensions/renderer/extension_js_runner.h" #include "extensions/renderer/ipc_message_sender.h" #include "extensions/renderer/module_system.h" #include "extensions/renderer/script_context.h" @@ -170,44 +171,6 @@ return script_context; } -// Handler for calling safely into JS. -void CallJsFunction(v8::Local<v8::Function> function, - v8::Local<v8::Context> context, - int argc, - v8::Local<v8::Value> argv[]) { - // TODO(devlin): Is using GetScriptContextChecked() (instead of - // GetScriptContext()) safe? If our custom bindings can continue running after - // contexts are removed from the set, it's likely not, but that's mostly a - // bug. In a perfect world, we *should* be able to do this CHECK. - ScriptContext* script_context = GetScriptContextChecked(context); - script_context->SafeCallFunction(function, argc, argv); -} - -v8::Global<v8::Value> CallJsFunctionSync(v8::Local<v8::Function> function, - v8::Local<v8::Context> context, - int argc, - v8::Local<v8::Value> argv[]) { - bool did_complete = false; - v8::Global<v8::Value> result; - auto callback = base::Bind([]( - v8::Isolate* isolate, - bool* did_complete_out, - v8::Global<v8::Value>* result_out, - const std::vector<v8::Local<v8::Value>>& results) { - *did_complete_out = true; - // The locals are released after the callback is executed, so we need to - // grab a persistent handle. - if (!results.empty() && !results[0].IsEmpty()) - result_out->Reset(isolate, results[0]); - }, base::Unretained(context->GetIsolate()), - base::Unretained(&did_complete), base::Unretained(&result)); - - ScriptContext* script_context = GetScriptContextChecked(context); - script_context->SafeCallFunction(function, argc, argv, callback); - CHECK(did_complete) << "expected script to execute synchronously"; - return result; -} - void AddConsoleError(v8::Local<v8::Context> context, const std::string& error) { ScriptContext* script_context = GetScriptContext(context); // Note: |script_context| may be null. During context tear down, we remove the @@ -252,8 +215,7 @@ context->GetIsolate(), new APIBindingBridge(hooks, context, binding_object, script_context->GetExtensionID(), - script_context->GetContextTypeDescription(), - base::Bind(&CallJsFunction))); + script_context->GetContextTypeDescription())); v8::Local<v8::Value> native_api_bridge = bridge_handle.ToV8(); script_context->module_system()->OnNativeBindingCreated(name, native_api_bridge); @@ -389,8 +351,6 @@ std::unique_ptr<IPCMessageSender> ipc_message_sender) : ipc_message_sender_(std::move(ipc_message_sender)), api_system_( - base::Bind(&CallJsFunction), - base::Bind(&CallJsFunctionSync), base::Bind(&GetAPISchema), base::Bind(&IsAPIFeatureAvailable), base::Bind(&NativeExtensionBindingsSystem::SendRequest, @@ -410,9 +370,8 @@ base::Bind(&EasyUnlockProximityRequiredStub::Create)); api_system_.RegisterCustomType("types.ChromeSetting", base::Bind(&ChromeSetting::Create)); - api_system_.RegisterCustomType( - "contentSettings.ContentSetting", - base::Bind(&ContentSetting::Create, base::Bind(&CallJsFunction))); + api_system_.RegisterCustomType("contentSettings.ContentSetting", + base::Bind(&ContentSetting::Create)); api_system_.GetHooksForAPI("webRequest") ->SetDelegate(std::make_unique<WebRequestHooks>()); api_system_.GetHooksForAPI("declarativeContent") @@ -426,9 +385,14 @@ v8::Isolate* isolate = context->isolate(); v8::HandleScope handle_scope(isolate); v8::Local<v8::Context> v8_context = context->v8_context(); + + JSRunner::SetInstanceForContext(v8_context, + std::make_unique<ExtensionJSRunner>(context)); + gin::PerContextData* per_context_data = gin::PerContextData::From(v8_context); DCHECK(per_context_data); DCHECK(!per_context_data->GetUserData(kBindingsSystemPerContextKey)); + auto data = std::make_unique<BindingsSystemPerContextData>( weak_factory_.GetWeakPtr()); per_context_data->SetUserData(kBindingsSystemPerContextKey, std::move(data)); @@ -454,7 +418,9 @@ void NativeExtensionBindingsSystem::WillReleaseScriptContext( ScriptContext* context) { v8::HandleScope handle_scope(context->isolate()); - api_system_.WillReleaseContext(context->v8_context()); + v8::Local<v8::Context> v8_context = context->v8_context(); + JSRunner::ClearInstanceForContext(v8_context); + api_system_.WillReleaseContext(v8_context); } void NativeExtensionBindingsSystem::UpdateBindingsForContext( @@ -846,8 +812,7 @@ context->GetIsolate(), new APIBindingJSUtil( api_system_.type_reference_map(), api_system_.request_handler(), - api_system_.event_handler(), api_system_.exception_handler(), - base::Bind(&CallJsFunction))); + api_system_.event_handler(), api_system_.exception_handler())); *binding_util_out = handle.ToV8(); }
diff --git a/extensions/renderer/native_extension_bindings_system_test_base.cc b/extensions/renderer/native_extension_bindings_system_test_base.cc index 3088fe6..6250928 100644 --- a/extensions/renderer/native_extension_bindings_system_test_base.cc +++ b/extensions/renderer/native_extension_bindings_system_test_base.cc
@@ -41,10 +41,16 @@ void NativeExtensionBindingsSystemUnittest::SetUp() { render_thread_ = std::make_unique<content::MockRenderThread>(); script_context_set_ = std::make_unique<ScriptContextSet>(&extension_ids_); - auto ipc_message_sender = std::make_unique<TestIPCMessageSender>(); - ipc_message_sender_ = ipc_message_sender.get(); + std::unique_ptr<TestIPCMessageSender> message_sender; + if (UseStrictIPCMessageSender()) { + message_sender = + std::make_unique<testing::StrictMock<TestIPCMessageSender>>(); + } else { + message_sender = std::make_unique<TestIPCMessageSender>(); + } + ipc_message_sender_ = message_sender.get(); bindings_system_ = std::make_unique<NativeExtensionBindingsSystem>( - std::move(ipc_message_sender)); + std::move(message_sender)); APIBindingTest::SetUp(); } @@ -93,6 +99,13 @@ raw_script_contexts_.erase(iter); } +std::unique_ptr<TestJSRunner::Scope> +NativeExtensionBindingsSystemUnittest::CreateTestJSRunner() { + // The NativeExtensionBindingsSystem handles setting the JSRunner for each + // context, so we don't need to fake one. + return nullptr; +} + void NativeExtensionBindingsSystemUnittest::RegisterExtension( scoped_refptr<const Extension> extension) { extension_ids_.insert(extension->id());
diff --git a/extensions/renderer/native_extension_bindings_system_test_base.h b/extensions/renderer/native_extension_bindings_system_test_base.h index 4339c72..6f41a8e 100644 --- a/extensions/renderer/native_extension_bindings_system_test_base.h +++ b/extensions/renderer/native_extension_bindings_system_test_base.h
@@ -115,6 +115,7 @@ void TearDown() override; void OnWillDisposeContext(v8::Local<v8::Context> context) override; v8::ExtensionConfiguration* GetV8ExtensionConfiguration() override; + std::unique_ptr<TestJSRunner::Scope> CreateTestJSRunner() override; ScriptContext* CreateScriptContext(v8::Local<v8::Context> v8_context, Extension* extension,
diff --git a/extensions/renderer/native_extension_bindings_system_unittest.cc b/extensions/renderer/native_extension_bindings_system_unittest.cc index 1d25d85..8352dd6 100644 --- a/extensions/renderer/native_extension_bindings_system_unittest.cc +++ b/extensions/renderer/native_extension_bindings_system_unittest.cc
@@ -14,6 +14,7 @@ #include "extensions/common/value_builder.h" #include "extensions/renderer/bindings/api_binding_test_util.h" #include "extensions/renderer/bindings/api_invocation_errors.h" +#include "extensions/renderer/bindings/test_js_runner.h" #include "extensions/renderer/message_target.h" #include "extensions/renderer/native_extension_bindings_system.h" #include "extensions/renderer/script_context.h" @@ -176,9 +177,13 @@ RunFunctionOnGlobal(add_listeners, context, 0, nullptr); } - bindings_system()->DispatchEventInContext( - "idle.onStateChanged", ListValueFromString("['idle']").get(), nullptr, - script_context); + { + TestJSRunner::AllowErrors allow_errors; + bindings_system()->DispatchEventInContext( + "idle.onStateChanged", ListValueFromString("['idle']").get(), nullptr, + script_context); + } + EXPECT_EQ("\"idle\"", GetStringPropertyFromObject(context->Global(), context, "newState")); EXPECT_EQ("true", GetStringPropertyFromObject(context->Global(), context,
diff --git a/extensions/renderer/programmatic_script_injector.cc b/extensions/renderer/programmatic_script_injector.cc index 9d0603e..0e0b0de 100644 --- a/extensions/renderer/programmatic_script_injector.cc +++ b/extensions/renderer/programmatic_script_injector.cc
@@ -54,13 +54,13 @@ bool ProgrammaticScriptInjector::ShouldInjectJs( UserScript::RunLocation run_location, const std::set<std::string>& executing_scripts) const { - return GetRunLocation() == run_location && params_->is_javascript; + return params_->run_at == run_location && params_->is_javascript; } bool ProgrammaticScriptInjector::ShouldInjectCss( UserScript::RunLocation run_location, const std::set<std::string>& injected_stylesheets) const { - return GetRunLocation() == run_location && !params_->is_javascript; + return params_->run_at == run_location && !params_->is_javascript; } PermissionsData::AccessType ProgrammaticScriptInjector::CanExecuteOnFrame( @@ -100,7 +100,7 @@ UserScript::RunLocation run_location, std::set<std::string>* executing_scripts, size_t* num_injected_js_scripts) const { - DCHECK_EQ(GetRunLocation(), run_location); + DCHECK_EQ(params_->run_at, run_location); DCHECK(params_->is_javascript); return std::vector<blink::WebScriptSource>( @@ -112,7 +112,7 @@ UserScript::RunLocation run_location, std::set<std::string>* injected_stylesheets, size_t* num_injected_stylesheets) const { - DCHECK_EQ(GetRunLocation(), run_location); + DCHECK_EQ(params_->run_at, run_location); DCHECK(!params_->is_javascript); return std::vector<blink::WebString>( @@ -164,10 +164,6 @@ APIPermission::kTab); } -UserScript::RunLocation ProgrammaticScriptInjector::GetRunLocation() const { - return static_cast<UserScript::RunLocation>(params_->run_at); -} - void ProgrammaticScriptInjector::Finish(const std::string& error, content::RenderFrame* render_frame) { DCHECK(!finished_);
diff --git a/extensions/renderer/programmatic_script_injector.h b/extensions/renderer/programmatic_script_injector.h index 673a08ee..d48e6e9 100644 --- a/extensions/renderer/programmatic_script_injector.h +++ b/extensions/renderer/programmatic_script_injector.h
@@ -60,9 +60,6 @@ // Whether it is safe to include information about the URL in error messages. bool CanShowUrlInError() const; - // Return the run location for this injector. - UserScript::RunLocation GetRunLocation() const; - // Notify the browser that the script was injected (or never will be), and // send along any results or errors. void Finish(const std::string& error, content::RenderFrame* render_frame);
diff --git a/extensions/renderer/script_injection_manager.cc b/extensions/renderer/script_injection_manager.cc index 7c3c090..05285c3 100644 --- a/extensions/renderer/script_injection_manager.cc +++ b/extensions/renderer/script_injection_manager.cc
@@ -479,8 +479,7 @@ std::unique_ptr<ScriptInjection> injection(new ScriptInjection( std::unique_ptr<ScriptInjector>(new ProgrammaticScriptInjector(params)), - render_frame, std::move(injection_host), - static_cast<UserScript::RunLocation>(params.run_at), + render_frame, std::move(injection_host), params.run_at, activity_logging_enabled_)); FrameStatusMap::const_iterator iter = frame_statuses_.find(render_frame);
diff --git a/extensions/renderer/web_request_hooks.cc b/extensions/renderer/web_request_hooks.cc index e2f1b4c0..c581f1f 100644 --- a/extensions/renderer/web_request_hooks.cc +++ b/extensions/renderer/web_request_hooks.cc
@@ -8,6 +8,7 @@ #include "content/public/renderer/v8_value_converter.h" #include "extensions/common/extension_api.h" #include "extensions/renderer/bindings/api_binding_hooks.h" +#include "extensions/renderer/bindings/js_runner.h" #include "extensions/renderer/module_system.h" #include "extensions/renderer/script_context.h" #include "extensions/renderer/script_context_set.h" @@ -20,7 +21,6 @@ bool WebRequestHooks::CreateCustomEvent( v8::Local<v8::Context> context, - const binding::RunJSFunctionSync& run_js_sync, const std::string& event_name, v8::Local<v8::Value>* event_out) { v8::Isolate* isolate = context->GetIsolate(); @@ -70,7 +70,9 @@ // opt_eventOptions and opt_webViewInstanceId are ignored. }; *event_out = - run_js_sync.Run(get_event, context, arraysize(args), args).Get(isolate); + JSRunner::Get(context) + ->RunJSFunctionSync(get_event, context, arraysize(args), args) + .Get(isolate); return true; }
diff --git a/extensions/renderer/web_request_hooks.h b/extensions/renderer/web_request_hooks.h index bf947eb9..b8b699ac 100644 --- a/extensions/renderer/web_request_hooks.h +++ b/extensions/renderer/web_request_hooks.h
@@ -9,7 +9,6 @@ #include "base/macros.h" #include "extensions/renderer/bindings/api_binding_hooks_delegate.h" -#include "extensions/renderer/bindings/api_binding_types.h" #include "v8/include/v8.h" namespace extensions { @@ -27,7 +26,6 @@ // It's not impossible, but it's a bit involved. However, as we move more // towards native bindings, it's definitely something we'll want to do. bool CreateCustomEvent(v8::Local<v8::Context> context, - const binding::RunJSFunctionSync& run_js_sync, const std::string& event_name, v8::Local<v8::Value>* event_out) override;
diff --git a/extensions/shell/browser/system_logs/log_sources/basic_log_source.cc b/extensions/shell/browser/system_logs/log_sources/basic_log_source.cc index 10b934c..8b176b09 100644 --- a/extensions/shell/browser/system_logs/log_sources/basic_log_source.cc +++ b/extensions/shell/browser/system_logs/log_sources/basic_log_source.cc
@@ -36,13 +36,12 @@ DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(!callback.is_null()); - std::unique_ptr<SystemLogsResponse> response = - std::make_unique<SystemLogsResponse>(); + auto response = std::make_unique<SystemLogsResponse>(); PopulateVersionStrings(response.get()); PopulateExtensionInfoLogs(response.get()); - callback.Run(response.get()); + callback.Run(std::move(response)); } void BasicLogSource::PopulateVersionStrings(SystemLogsResponse* response) {
diff --git a/extensions/test/data/media_perception_private/component/manifest.json b/extensions/test/data/media_perception_private/component/manifest.json new file mode 100644 index 0000000..2d9501e5 --- /dev/null +++ b/extensions/test/data/media_perception_private/component/manifest.json
@@ -0,0 +1,16 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. +{ + "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC74Vbx3EbhPc/FOvn6+HxCjMSml0HdPMiuRjj5a3b+MnRML1iJ9OAgbKUYJ/u3s25/cGq8pNB0NbyupHGEqvqAE7TcNr1mdgs0PWxh2IOI1GKrxlzxpqzQuFmxq5WHKr5RrwZ4/Xq0t/+e8JkvhZdW0jarz/28Jom0gkM5lorsewIDAQAB", + "manifest_version": 2, + "name": "Test mediaPerceptionPrivate API's setAnalyticsComponent function", + "version": "1.0", + "app": { + "background": { + "scripts": ["runtest.js"] + } + }, + "permissions": ["mediaPerceptionPrivate"], + "kiosk_enabled": true +}
diff --git a/extensions/test/data/media_perception_private/component/runtest.js b/extensions/test/data/media_perception_private/component/runtest.js new file mode 100644 index 0000000..41faa99 --- /dev/null +++ b/extensions/test/data/media_perception_private/component/runtest.js
@@ -0,0 +1,40 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +function setAnalyticsComponentLight() { + chrome.mediaPerceptionPrivate.setAnalyticsComponent({ + type: 'LIGHT', + }, chrome.test.callbackPass(function(component_state) { + chrome.test.assertEq('INSTALLED', component_state.status); + })); +} + +function setAnalyticsComponentFullExpectFailure() { + chrome.mediaPerceptionPrivate.setAnalyticsComponent({ + type: 'FULL', + }, chrome.test.callbackPass(function(component_state) { + chrome.test.assertEq('FAILED_TO_INSTALL', component_state.status); + })); +} + +function setAnalyticsComponentWithProcessRunningFailure() { + chrome.mediaPerceptionPrivate.setState({ + status: 'RUNNING', + deviceContext: 'device_context' + }, chrome.test.callbackPass(function(state) { + chrome.test.assertEq('RUNNING', state.status); + })); + + chrome.mediaPerceptionPrivate.setAnalyticsComponent({ + type: 'LIGHT', + }, chrome.test.callbackPass(function(component_state) { + chrome.test.assertEq('FAILED_TO_INSTALL', component_state.status); + })); +} + +chrome.test.runTests([ + setAnalyticsComponentLight, + setAnalyticsComponentFullExpectFailure, + setAnalyticsComponentWithProcessRunningFailure]); +
diff --git a/extensions/test/data/media_perception_private/state/runtest.js b/extensions/test/data/media_perception_private/state/runtest.js index 031b0a4..3a228155 100644 --- a/extensions/test/data/media_perception_private/state/runtest.js +++ b/extensions/test/data/media_perception_private/state/runtest.js
@@ -26,7 +26,8 @@ } function setStateUnsettable() { - const error = 'Status can only be set to RUNNING, SUSPENDED or RESTARTING.'; + const error = 'Status can only be set to RUNNING, SUSPENDED, ' + + 'RESTARTING, or STOPPED.'; chrome.mediaPerceptionPrivate.setState({ status: 'UNINITIALIZED' }, chrome.test.callbackFail(error)); @@ -53,11 +54,20 @@ })); } +function setStateStopped() { + chrome.mediaPerceptionPrivate.setState({ + status: 'STOPPED', + }, chrome.test.callbackPass(function(state) { + chrome.test.assertEq('STOPPED', state.status); + })); +} + chrome.test.runTests([ getStateUninitialized, setStateRunning, getStateRunning, setStateUnsettable, setStateSuspendedButWithDeviceContextFail, - setStateRestarted]); + setStateRestarted, + setStateStopped]);
diff --git a/gpu/command_buffer/client/client_discardable_manager.cc b/gpu/command_buffer/client/client_discardable_manager.cc index d635306..be06ca7 100644 --- a/gpu/command_buffer/client/client_discardable_manager.cc +++ b/gpu/command_buffer/client/client_discardable_manager.cc
@@ -140,7 +140,11 @@ scoped_refptr<Buffer> buffer; int32_t shm_id; uint32_t offset = 0; - FindAllocation(command_buffer, &buffer, &shm_id, &offset); + if (!FindAllocation(command_buffer, &buffer, &shm_id, &offset)) { + // This can fail if we've lost context, return an invalid Id. + return ClientDiscardableHandle::Id(); + } + DCHECK_LT(offset * element_size_, std::numeric_limits<uint32_t>::max()); uint32_t byte_offset = static_cast<uint32_t>(offset * element_size_); ClientDiscardableHandle handle(std::move(buffer), byte_offset, shm_id); @@ -178,7 +182,7 @@ return found->second; } -void ClientDiscardableManager::FindAllocation(CommandBuffer* command_buffer, +bool ClientDiscardableManager::FindAllocation(CommandBuffer* command_buffer, scoped_refptr<Buffer>* buffer, int32_t* shm_id, uint32_t* offset) { @@ -191,18 +195,21 @@ *offset = allocation->free_offsets.TakeFreeOffset(); *shm_id = allocation->shm_id; *buffer = allocation->buffer; - return; + return true; } // We couldn't find an existing free entry. Allocate more space. auto allocation = std::make_unique<Allocation>(elements_per_allocation_); allocation->buffer = command_buffer->CreateTransferBuffer( allocation_size_, &allocation->shm_id); + if (!allocation->buffer) + return false; *offset = allocation->free_offsets.TakeFreeOffset(); *shm_id = allocation->shm_id; *buffer = allocation->buffer; allocations_.push_back(std::move(allocation)); + return true; } void ClientDiscardableManager::ReturnAllocation(
diff --git a/gpu/command_buffer/client/client_discardable_manager.h b/gpu/command_buffer/client/client_discardable_manager.h index 5b5f718..8ba87d5d 100644 --- a/gpu/command_buffer/client/client_discardable_manager.h +++ b/gpu/command_buffer/client/client_discardable_manager.h
@@ -38,7 +38,7 @@ } private: - void FindAllocation(CommandBuffer* command_buffer, + bool FindAllocation(CommandBuffer* command_buffer, scoped_refptr<Buffer>* buffer, int32_t* shm_id, uint32_t* offset);
diff --git a/gpu/command_buffer/client/client_discardable_texture_manager.cc b/gpu/command_buffer/client/client_discardable_texture_manager.cc index af24382..a8fd1de 100644 --- a/gpu/command_buffer/client/client_discardable_texture_manager.cc +++ b/gpu/command_buffer/client/client_discardable_texture_manager.cc
@@ -16,6 +16,9 @@ texture_id_to_handle_id_.end()); ClientDiscardableHandle::Id handle_id = discardable_manager_.CreateHandle(command_buffer); + if (handle_id.is_null()) + return ClientDiscardableHandle(); + texture_id_to_handle_id_[texture_id] = handle_id; return discardable_manager_.GetHandle(handle_id); }
diff --git a/gpu/command_buffer/client/gles2_implementation.cc b/gpu/command_buffer/client/gles2_implementation.cc index 62f0d501..f3393f1 100644 --- a/gpu/command_buffer/client/gles2_implementation.cc +++ b/gpu/command_buffer/client/gles2_implementation.cc
@@ -7075,6 +7075,9 @@ } ClientDiscardableHandle handle = manager->InitializeTexture(helper_->command_buffer(), texture_id); + if (!handle.IsValid()) + return; + helper_->InitializeDiscardableTextureCHROMIUM(texture_id, handle.shm_id(), handle.byte_offset()); }
diff --git a/gpu/command_buffer/common/discardable_handle.cc b/gpu/command_buffer/common/discardable_handle.cc index 7401471..9f8c94b 100644 --- a/gpu/command_buffer/common/discardable_handle.cc +++ b/gpu/command_buffer/common/discardable_handle.cc
@@ -59,6 +59,9 @@ buffer_->GetDataAddress(byte_offset_, sizeof(base::subtle::Atomic32))); } +ClientDiscardableHandle::ClientDiscardableHandle() + : DiscardableHandleBase(nullptr, 0, 0) {} + ClientDiscardableHandle::ClientDiscardableHandle(scoped_refptr<Buffer> buffer, uint32_t byte_offset, int32_t shm_id)
diff --git a/gpu/command_buffer/common/discardable_handle.h b/gpu/command_buffer/common/discardable_handle.h index 18cf0e8..36747c5 100644 --- a/gpu/command_buffer/common/discardable_handle.h +++ b/gpu/command_buffer/common/discardable_handle.h
@@ -71,6 +71,7 @@ uint64_t, std::numeric_limits<uint64_t>::max()>; + ClientDiscardableHandle(); // Constructs an invalid handle. ClientDiscardableHandle(scoped_refptr<Buffer> buffer, uint32_t byte_offset, int32_t shm_id); @@ -90,6 +91,8 @@ // Gets an Id which uniquely identifies this ClientDiscardableHandle within // the ClientDiscardableManager which created it. Id GetId() const; + + bool IsValid() const { return !GetId().is_null(); } }; // ServiceDiscardableHandle can wrap an existing handle (via the constructor),
diff --git a/gpu/command_buffer/service/gles2_cmd_decoder_passthrough_doers.cc b/gpu/command_buffer/service/gles2_cmd_decoder_passthrough_doers.cc index 393578a6..c18034e 100644 --- a/gpu/command_buffer/service/gles2_cmd_decoder_passthrough_doers.cc +++ b/gpu/command_buffer/service/gles2_cmd_decoder_passthrough_doers.cc
@@ -65,8 +65,13 @@ // Don't pass service IDs of objects with a client ID of 0. They are // emulated and should not be deleteable if (client_id != 0) { - service_ids[ii] = id_map->GetServiceIDOrInvalid(client_id); - id_map->RemoveClientID(client_id); + ServiceType service_id = id_map->GetServiceIDOrInvalid(client_id); + // Don't delete the invalid service ID, if bind-generates-resource is + // enabled then it may be currently used as a placeholder + if (service_id != id_map->invalid_service_id()) { + DCHECK(service_id != 0); + id_map->RemoveClientID(client_id); + } } } @@ -4066,7 +4071,7 @@ } // Only release the image if it is currently bound - if (bound_texture.texture->GetLevelImage(target, 0) != image) { + if (bound_texture.texture->GetLevelImage(target, 0) == image) { image->ReleaseTexImage(target); bound_texture.texture->SetLevelImage(target, 0, nullptr); }
diff --git a/gpu/command_buffer/service/gpu_preferences.h b/gpu/command_buffer/service/gpu_preferences.h index 1feb8e7..ab20cb9 100644 --- a/gpu/command_buffer/service/gpu_preferences.h +++ b/gpu/command_buffer/service/gpu_preferences.h
@@ -135,6 +135,9 @@ // round intermediate values in ANGLE. bool emulate_shader_precision = false; + // Use a dedicated RasterDecoder instead of generic GLES2Decoder. + bool enable_raster_decoder = false; + // =================================== // Settings from //ui/gl/gl_switches.h
diff --git a/gpu/command_buffer/service/gpu_switches.cc b/gpu/command_buffer/service/gpu_switches.cc index 674b2b6..e18e886 100644 --- a/gpu/command_buffer/service/gpu_switches.cc +++ b/gpu/command_buffer/service/gpu_switches.cc
@@ -73,4 +73,7 @@ // tracking. const char kUseCmdDecoder[] = "use-cmd-decoder"; +// Use a dedicated RasterInterfaceDecoder instead of generic GLES2Decoder. +const char kEnableRasterDecoder[] = "enable-raster-decoder"; + } // namespace switches
diff --git a/gpu/command_buffer/service/gpu_switches.h b/gpu/command_buffer/service/gpu_switches.h index 1132f6e..d1c23e6a 100644 --- a/gpu/command_buffer/service/gpu_switches.h +++ b/gpu/command_buffer/service/gpu_switches.h
@@ -36,6 +36,7 @@ GPU_EXPORT extern const char kGLShaderIntermOutput[]; GPU_EXPORT extern const char kEmulateShaderPrecision[]; GPU_EXPORT extern const char kUseCmdDecoder[]; +GPU_EXPORT extern const char kEnableRasterDecoder[]; } // namespace switches
diff --git a/gpu/command_buffer/tests/gl_virtual_contexts_ext_window_rectangles_unittest.cc b/gpu/command_buffer/tests/gl_virtual_contexts_ext_window_rectangles_unittest.cc index 3f12e7a..2083cbf3 100644 --- a/gpu/command_buffer/tests/gl_virtual_contexts_ext_window_rectangles_unittest.cc +++ b/gpu/command_buffer/tests/gl_virtual_contexts_ext_window_rectangles_unittest.cc
@@ -32,12 +32,13 @@ } bool IsApplicable() const { - // If a driver isn't capable of supporting ES3 context, creating - // ContextGroup will fail. - bool have_es3 = gl_real_shared_.decoder() && - gl_real_shared_.decoder()->GetContextGroup(); + // Not applicable for devices not supporting OpenGLES3. + if (!gl_real_shared_.IsInitialized()) { + return false; + } + bool have_ext = GLTestHelper::HasExtension("GL_EXT_window_rectangles"); - return have_es3 && have_ext; + return have_ext; } GLManager gl_real_shared_;
diff --git a/gpu/config/gpu_driver_bug_list.json b/gpu/config/gpu_driver_bug_list.json index 8effe7bf..873db32 100644 --- a/gpu/config/gpu_driver_bug_list.json +++ b/gpu/config/gpu_driver_bug_list.json
@@ -2706,7 +2706,7 @@ "description": "Direct composition causes slow presents on Intel Sandybridge", "cr_bugs": [775898, 785648], "os": { - "type": "windows" + "type": "win" }, "vendor_id": "0x8086", "device_id": ["0x0116"], @@ -2719,7 +2719,7 @@ "description": "Direct composition causes slow presents on old Nvidia GPUs", "cr_bugs": [775898], "os": { - "type": "windows" + "type": "win" }, "vendor_id": "0x10de", "device_id": ["0x10d8"],
diff --git a/gpu/config/process_json.py b/gpu/config/process_json.py index 33dde6b..2500d75c 100755 --- a/gpu/config/process_json.py +++ b/gpu/config/process_json.py
@@ -26,6 +26,15 @@ """ +_OS_TYPE_MAP = { + 'win': 'kOsWin', + 'macosx': 'kOsMacosx', + 'android': 'kOsAndroid', + 'linux': 'kOsLinux', + 'chromeos': 'kOsChromeOS', + '': 'kOsAny', + } + def load_software_rendering_list_features(feature_type_filename): header_file = open(feature_type_filename, 'rb') @@ -286,16 +295,8 @@ def write_os_type(os_type, data_file): - map = { - 'win': 'kOsWin', - 'macosx': 'kOsMacosx', - 'android': 'kOsAndroid', - 'linux': 'kOsLinux', - 'chromeos': 'kOsChromeOS', - '': 'kOsAny', - } - assert map.has_key(os_type) - data_file.write('GpuControlList::%s, // os_type\n' % map[os_type]) + assert _OS_TYPE_MAP.has_key(os_type) + data_file.write('GpuControlList::%s, // os_type\n' % _OS_TYPE_MAP[os_type]) def write_multi_gpu_category(multi_gpu_category, data_file): @@ -618,8 +619,14 @@ entry_id = entry['id'] assert entry_id not in ids ids.append(entry_id) - if os_filter != None and 'os' in entry and entry['os']['type'] != os_filter: - continue + if 'os' in entry: + os_type = entry['os']['type'] + # Check for typos in the .json data + if not _OS_TYPE_MAP.has_key(os_type): + raise Exception('Unknown OS type "%s" for entry %d' % + (os_type, entry_id)) + if os_filter != None and os_type != os_filter: + continue entry_count += 1 write_entry(entry, total_features, feature_tag, data_file, data_helper_file, data_exception_file)
diff --git a/gpu/ipc/common/gpu_preferences.mojom b/gpu/ipc/common/gpu_preferences.mojom index 068b42f..09c7eb3 100644 --- a/gpu/ipc/common/gpu_preferences.mojom +++ b/gpu/ipc/common/gpu_preferences.mojom
@@ -51,6 +51,7 @@ bool enable_threaded_texture_mailboxes; bool gl_shader_interm_output; bool emulate_shader_precision; + bool enable_raster_decoder; bool enable_gpu_service_logging; bool enable_gpu_service_tracing; bool use_passthrough_cmd_decoder;
diff --git a/gpu/ipc/common/gpu_preferences_struct_traits.h b/gpu/ipc/common/gpu_preferences_struct_traits.h index 99e500e..1c95637 100644 --- a/gpu/ipc/common/gpu_preferences_struct_traits.h +++ b/gpu/ipc/common/gpu_preferences_struct_traits.h
@@ -92,6 +92,7 @@ prefs.enable_threaded_texture_mailboxes(); out->gl_shader_interm_output = prefs.gl_shader_interm_output(); out->emulate_shader_precision = prefs.emulate_shader_precision(); + out->enable_raster_decoder = prefs.enable_raster_decoder(); out->enable_gpu_service_logging = prefs.enable_gpu_service_logging(); out->enable_gpu_service_tracing = prefs.enable_gpu_service_tracing(); out->use_passthrough_cmd_decoder = prefs.use_passthrough_cmd_decoder(); @@ -198,6 +199,9 @@ static bool emulate_shader_precision(const gpu::GpuPreferences& prefs) { return prefs.emulate_shader_precision; } + static bool enable_raster_decoder(const gpu::GpuPreferences& prefs) { + return prefs.enable_raster_decoder; + } static bool enable_gpu_service_logging(const gpu::GpuPreferences& prefs) { return prefs.enable_gpu_service_logging; }
diff --git a/gpu/ipc/service/gpu_channel.cc b/gpu/ipc/service/gpu_channel.cc index ceca623..fbfcbf59 100644 --- a/gpu/ipc/service/gpu_channel.cc +++ b/gpu/ipc/service/gpu_channel.cc
@@ -617,6 +617,10 @@ stream_sequences_[stream_id] = sequence_id; } + DVLOG(1) << "Should use raster decoder: " + << (gpu_channel_manager_->gpu_preferences().enable_raster_decoder && + init_params.attribs.enable_oop_rasterization); + auto stub = std::make_unique<GpuCommandBufferStub>( this, init_params, command_buffer_id, sequence_id, stream_id, route_id); auto stub_result =
diff --git a/gpu/ipc/service/gpu_channel_manager_delegate.h b/gpu/ipc/service/gpu_channel_manager_delegate.h index 9201a53..cb1e078 100644 --- a/gpu/ipc/service/gpu_channel_manager_delegate.h +++ b/gpu/ipc/service/gpu_channel_manager_delegate.h
@@ -14,6 +14,9 @@ class GpuChannelManagerDelegate { public: + // Called on any successful context creation. + virtual void DidCreateContextSuccessfully() = 0; + // Tells the delegate that an offscreen context was created for the provided // |active_url|. virtual void DidCreateOffscreenContext(const GURL& active_url) = 0;
diff --git a/gpu/ipc/service/gpu_channel_test_common.cc b/gpu/ipc/service/gpu_channel_test_common.cc index cd36294..67a224ea 100644 --- a/gpu/ipc/service/gpu_channel_test_common.cc +++ b/gpu/ipc/service/gpu_channel_test_common.cc
@@ -28,6 +28,7 @@ // GpuChannelManagerDelegate implementation: void SetActiveURL(const GURL& url) override {} + void DidCreateContextSuccessfully() override {} void DidCreateOffscreenContext(const GURL& active_url) override {} void DidDestroyChannel(int client_id) override {} void DidDestroyOffscreenContext(const GURL& active_url) override {}
diff --git a/gpu/ipc/service/gpu_command_buffer_stub.cc b/gpu/ipc/service/gpu_command_buffer_stub.cc index 33108eb9..5b4ac03 100644 --- a/gpu/ipc/service/gpu_command_buffer_stub.cc +++ b/gpu/ipc/service/gpu_command_buffer_stub.cc
@@ -841,6 +841,7 @@ } } + manager->delegate()->DidCreateContextSuccessfully(); initialized_ = true; return gpu::ContextResult::kSuccess; #endif // defined(OS_FUCHSIA)
diff --git a/headless/app/headless_shell.cc b/headless/app/headless_shell.cc index 77b5514..1c6537d15 100644 --- a/headless/app/headless_shell.cc +++ b/headless/app/headless_shell.cc
@@ -129,7 +129,7 @@ weak_factory_(this) { } -HeadlessShell::~HeadlessShell() {} +HeadlessShell::~HeadlessShell() = default; #if !defined(CHROME_MULTIPLE_DLL_CHILD) void HeadlessShell::OnStart(HeadlessBrowser* browser) {
diff --git a/headless/app/shell_navigation_request.cc b/headless/app/shell_navigation_request.cc index dc5d7c70..3f5344d 100644 --- a/headless/app/shell_navigation_request.cc +++ b/headless/app/shell_navigation_request.cc
@@ -18,7 +18,7 @@ DCHECK_CURRENTLY_ON(content::BrowserThread::UI); } -ShellNavigationRequest::~ShellNavigationRequest() {} +ShellNavigationRequest::~ShellNavigationRequest() = default; void ShellNavigationRequest::StartProcessing(base::Closure done_callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
diff --git a/headless/lib/browser/headless_browser_context_impl.cc b/headless/lib/browser/headless_browser_context_impl.cc index 7837c50..17849e2 100644 --- a/headless/lib/browser/headless_browser_context_impl.cc +++ b/headless/lib/browser/headless_browser_context_impl.cc
@@ -519,13 +519,13 @@ return browser_->CreateBrowserContext(this); } -HeadlessBrowserContext::Builder::MojoBindings::MojoBindings() {} +HeadlessBrowserContext::Builder::MojoBindings::MojoBindings() = default; HeadlessBrowserContext::Builder::MojoBindings::MojoBindings( const std::string& mojom_name, const std::string& js_bindings) : mojom_name(mojom_name), js_bindings(js_bindings) {} -HeadlessBrowserContext::Builder::MojoBindings::~MojoBindings() {} +HeadlessBrowserContext::Builder::MojoBindings::~MojoBindings() = default; } // namespace headless
diff --git a/headless/lib/browser/headless_browser_impl.cc b/headless/lib/browser/headless_browser_impl.cc index 956b3fc..88bede9 100644 --- a/headless/lib/browser/headless_browser_impl.cc +++ b/headless/lib/browser/headless_browser_impl.cc
@@ -77,7 +77,7 @@ agent_host_(nullptr), weak_ptr_factory_(this) {} -HeadlessBrowserImpl::~HeadlessBrowserImpl() {} +HeadlessBrowserImpl::~HeadlessBrowserImpl() = default; HeadlessBrowserContext::Builder HeadlessBrowserImpl::CreateBrowserContextBuilder() {
diff --git a/headless/lib/browser/headless_browser_main_parts.cc b/headless/lib/browser/headless_browser_main_parts.cc index 64e9018..da66fb7 100644 --- a/headless/lib/browser/headless_browser_main_parts.cc +++ b/headless/lib/browser/headless_browser_main_parts.cc
@@ -18,7 +18,7 @@ : browser_(browser) , devtools_http_handler_started_(false) {} -HeadlessBrowserMainParts::~HeadlessBrowserMainParts() {} +HeadlessBrowserMainParts::~HeadlessBrowserMainParts() = default; void HeadlessBrowserMainParts::PreMainMessageLoopRun() { const base::CommandLine* command_line =
diff --git a/headless/lib/browser/headless_clipboard.cc b/headless/lib/browser/headless_clipboard.cc index dcadd4c..9b9fd06 100644 --- a/headless/lib/browser/headless_clipboard.cc +++ b/headless/lib/browser/headless_clipboard.cc
@@ -13,7 +13,7 @@ HeadlessClipboard::HeadlessClipboard() : default_store_type_(ui::CLIPBOARD_TYPE_COPY_PASTE) {} -HeadlessClipboard::~HeadlessClipboard() {} +HeadlessClipboard::~HeadlessClipboard() = default; void HeadlessClipboard::OnPreShutdown() {} @@ -182,7 +182,7 @@ HeadlessClipboard::DataStore::DataStore(const DataStore& other) = default; -HeadlessClipboard::DataStore::~DataStore() {} +HeadlessClipboard::DataStore::~DataStore() = default; void HeadlessClipboard::DataStore::Clear() { data.clear();
diff --git a/headless/lib/browser/headless_content_browser_client.cc b/headless/lib/browser/headless_content_browser_client.cc index 20efdac4..9843462 100644 --- a/headless/lib/browser/headless_content_browser_client.cc +++ b/headless/lib/browser/headless_content_browser_client.cc
@@ -119,7 +119,7 @@ append_command_line_flags_callback_( browser_->options()->append_command_line_flags_callback) {} -HeadlessContentBrowserClient::~HeadlessContentBrowserClient() {} +HeadlessContentBrowserClient::~HeadlessContentBrowserClient() = default; content::BrowserMainParts* HeadlessContentBrowserClient::CreateBrowserMainParts( const content::MainFunctionParams&) {
diff --git a/headless/lib/browser/headless_devtools_client_impl.cc b/headless/lib/browser/headless_devtools_client_impl.cc index 11cb530..9763565c59 100644 --- a/headless/lib/browser/headless_devtools_client_impl.cc +++ b/headless/lib/browser/headless_devtools_client_impl.cc
@@ -72,7 +72,7 @@ content::BrowserThread::UI)), weak_ptr_factory_(this) {} -HeadlessDevToolsClientImpl::~HeadlessDevToolsClientImpl() {} +HeadlessDevToolsClientImpl::~HeadlessDevToolsClientImpl() = default; bool HeadlessDevToolsClientImpl::AttachToHost( content::DevToolsAgentHost* agent_host) { @@ -416,7 +416,7 @@ event_handlers_[method] = callback; } -HeadlessDevToolsClientImpl::Callback::Callback() {} +HeadlessDevToolsClientImpl::Callback::Callback() = default; HeadlessDevToolsClientImpl::Callback::Callback(Callback&& other) = default; @@ -427,7 +427,7 @@ base::Callback<void(const base::Value&)> callback) : callback_with_result(callback) {} -HeadlessDevToolsClientImpl::Callback::~Callback() {} +HeadlessDevToolsClientImpl::Callback::~Callback() = default; HeadlessDevToolsClientImpl::Callback& HeadlessDevToolsClientImpl::Callback:: operator=(Callback&& other) = default;
diff --git a/headless/lib/browser/headless_devtools_manager_delegate.cc b/headless/lib/browser/headless_devtools_manager_delegate.cc index e11c320..553d715 100644 --- a/headless/lib/browser/headless_devtools_manager_delegate.cc +++ b/headless/lib/browser/headless_devtools_manager_delegate.cc
@@ -313,7 +313,7 @@ &HeadlessDevToolsManagerDelegate::BeginFrame, base::Unretained(this)); } -HeadlessDevToolsManagerDelegate::~HeadlessDevToolsManagerDelegate() {} +HeadlessDevToolsManagerDelegate::~HeadlessDevToolsManagerDelegate() = default; bool HeadlessDevToolsManagerDelegate::HandleCommand( content::DevToolsAgentHost* agent_host,
diff --git a/headless/lib/browser/headless_focus_client.cc b/headless/lib/browser/headless_focus_client.cc index 9a4e806..c406c70 100644 --- a/headless/lib/browser/headless_focus_client.cc +++ b/headless/lib/browser/headless_focus_client.cc
@@ -12,7 +12,7 @@ HeadlessFocusClient::HeadlessFocusClient() : focused_window_(NULL), observer_manager_(this) {} -HeadlessFocusClient::~HeadlessFocusClient() {} +HeadlessFocusClient::~HeadlessFocusClient() = default; void HeadlessFocusClient::AddObserver( aura::client::FocusChangeObserver* observer) {
diff --git a/headless/lib/browser/headless_network_conditions.cc b/headless/lib/browser/headless_network_conditions.cc index 3b7c643..208208c90 100644 --- a/headless/lib/browser/headless_network_conditions.cc +++ b/headless/lib/browser/headless_network_conditions.cc
@@ -21,6 +21,6 @@ download_throughput(download_throughput), upload_throughput(upload_throughput) {} -HeadlessNetworkConditions::~HeadlessNetworkConditions() {} +HeadlessNetworkConditions::~HeadlessNetworkConditions() = default; } // namespace headless
diff --git a/headless/lib/browser/headless_permission_manager.cc b/headless/lib/browser/headless_permission_manager.cc index 7e24292..8f0fc66e 100644 --- a/headless/lib/browser/headless_permission_manager.cc +++ b/headless/lib/browser/headless_permission_manager.cc
@@ -14,7 +14,7 @@ content::BrowserContext* browser_context) : browser_context_(browser_context) {} -HeadlessPermissionManager::~HeadlessPermissionManager() {} +HeadlessPermissionManager::~HeadlessPermissionManager() = default; int HeadlessPermissionManager::RequestPermission( content::PermissionType permission,
diff --git a/headless/lib/browser/headless_platform_event_source.cc b/headless/lib/browser/headless_platform_event_source.cc index 7c3100e..598ec80 100644 --- a/headless/lib/browser/headless_platform_event_source.cc +++ b/headless/lib/browser/headless_platform_event_source.cc
@@ -6,8 +6,8 @@ namespace headless { -HeadlessPlatformEventSource::HeadlessPlatformEventSource() {} +HeadlessPlatformEventSource::HeadlessPlatformEventSource() = default; -HeadlessPlatformEventSource::~HeadlessPlatformEventSource() {} +HeadlessPlatformEventSource::~HeadlessPlatformEventSource() = default; } // namespace headless
diff --git a/headless/lib/browser/headless_print_manager.cc b/headless/lib/browser/headless_print_manager.cc index 2213796..e7a816d 100644 --- a/headless/lib/browser/headless_print_manager.cc +++ b/headless/lib/browser/headless_print_manager.cc
@@ -51,7 +51,7 @@ Reset(); } -HeadlessPrintManager::~HeadlessPrintManager() {} +HeadlessPrintManager::~HeadlessPrintManager() = default; // static std::string HeadlessPrintManager::PrintResultToString(PrintResult result) {
diff --git a/headless/lib/browser/headless_quota_permission_context.cc b/headless/lib/browser/headless_quota_permission_context.cc index 618cbe5c..b75f01b 100644 --- a/headless/lib/browser/headless_quota_permission_context.cc +++ b/headless/lib/browser/headless_quota_permission_context.cc
@@ -8,7 +8,7 @@ namespace headless { -HeadlessQuotaPermissionContext::HeadlessQuotaPermissionContext() {} +HeadlessQuotaPermissionContext::HeadlessQuotaPermissionContext() = default; void HeadlessQuotaPermissionContext::RequestQuotaPermission( const content::StorageQuotaParams& params, @@ -24,6 +24,6 @@ callback.Run(QUOTA_PERMISSION_RESPONSE_ALLOW); } -HeadlessQuotaPermissionContext::~HeadlessQuotaPermissionContext() {} +HeadlessQuotaPermissionContext::~HeadlessQuotaPermissionContext() = default; } // namespace headless
diff --git a/headless/lib/browser/headless_resource_dispatcher_host_delegate.cc b/headless/lib/browser/headless_resource_dispatcher_host_delegate.cc index 595a088..d7b4888 100644 --- a/headless/lib/browser/headless_resource_dispatcher_host_delegate.cc +++ b/headless/lib/browser/headless_resource_dispatcher_host_delegate.cc
@@ -7,9 +7,9 @@ namespace headless { HeadlessResourceDispatcherHostDelegate:: - HeadlessResourceDispatcherHostDelegate() {} + HeadlessResourceDispatcherHostDelegate() = default; HeadlessResourceDispatcherHostDelegate:: - ~HeadlessResourceDispatcherHostDelegate() {} + ~HeadlessResourceDispatcherHostDelegate() = default; } // namespace headless
diff --git a/headless/lib/browser/headless_screen.cc b/headless/lib/browser/headless_screen.cc index 1ee6b64a..7ce5366 100644 --- a/headless/lib/browser/headless_screen.cc +++ b/headless/lib/browser/headless_screen.cc
@@ -21,7 +21,7 @@ return new HeadlessScreen(gfx::Rect(size)); } -HeadlessScreen::~HeadlessScreen() {} +HeadlessScreen::~HeadlessScreen() = default; gfx::Point HeadlessScreen::GetCursorScreenPoint() { return aura::Env::GetInstance()->last_mouse_location();
diff --git a/headless/lib/browser/headless_tab_socket_impl.cc b/headless/lib/browser/headless_tab_socket_impl.cc index 05e562c..cbdb7dc 100644 --- a/headless/lib/browser/headless_tab_socket_impl.cc +++ b/headless/lib/browser/headless_tab_socket_impl.cc
@@ -19,7 +19,7 @@ listener_(nullptr), weak_ptr_factory_(this) {} -HeadlessTabSocketImpl::~HeadlessTabSocketImpl() {} +HeadlessTabSocketImpl::~HeadlessTabSocketImpl() = default; // Wrangles the async responses to // HeadlessRenderFrameControllerImpl::InstallTabSocket for which at most one @@ -68,7 +68,7 @@ bool success_; friend class base::RefCounted<TabSocketInstallationController>; - ~TabSocketInstallationController() {} + ~TabSocketInstallationController() = default; }; void HeadlessTabSocketImpl::InstallHeadlessTabSocketBindings(
diff --git a/headless/lib/browser/headless_web_contents_impl.cc b/headless/lib/browser/headless_web_contents_impl.cc index 231fe97..cc0c750 100644 --- a/headless/lib/browser/headless_web_contents_impl.cc +++ b/headless/lib/browser/headless_web_contents_impl.cc
@@ -207,8 +207,8 @@ struct HeadlessWebContentsImpl::PendingFrame { public: - PendingFrame() {} - ~PendingFrame() {} + PendingFrame() = default; + ~PendingFrame() = default; bool MaybeRunCallback() { if (wait_for_copy_result || !display_did_finish_frame) @@ -709,7 +709,7 @@ return browser_context_->CreateWebContents(this); } -HeadlessWebContents::Builder::MojoService::MojoService() {} +HeadlessWebContents::Builder::MojoService::MojoService() = default; HeadlessWebContents::Builder::MojoService::MojoService( const MojoService& other) = default; @@ -719,6 +719,6 @@ const ServiceFactoryCallback& service_factory) : service_name(service_name), service_factory(service_factory) {} -HeadlessWebContents::Builder::MojoService::~MojoService() {} +HeadlessWebContents::Builder::MojoService::~MojoService() = default; } // namespace headless
diff --git a/headless/lib/headless_browser_browsertest.cc b/headless/lib/headless_browser_browsertest.cc index c0fd8a6..0ed54b6 100644 --- a/headless/lib/headless_browser_browsertest.cc +++ b/headless/lib/headless_browser_browsertest.cc
@@ -393,7 +393,7 @@ : public net::URLRequestJobFactory::ProtocolHandler { public: explicit ProtocolHandlerWithCookies(net::CookieList* sent_cookies); - ~ProtocolHandlerWithCookies() override {} + ~ProtocolHandlerWithCookies() override = default; net::URLRequestJob* MaybeCreateJob( net::URLRequest* request, @@ -410,7 +410,7 @@ URLRequestJobWithCookies(net::URLRequest* request, net::NetworkDelegate* network_delegate, net::CookieList* sent_cookies); - ~URLRequestJobWithCookies() override {} + ~URLRequestJobWithCookies() override = default; // net::URLRequestJob implementation: void Start() override; @@ -674,7 +674,7 @@ inspector::ExperimentalObserver { public: CrashReporterTest() : devtools_client_(HeadlessDevToolsClient::Create()) {} - ~CrashReporterTest() override {} + ~CrashReporterTest() override = default; void SetUp() override { base::ThreadRestrictions::SetIOAllowed(true); @@ -784,7 +784,7 @@ class HeadlessBrowserTestWithNetLog : public HeadlessBrowserTest { public: - HeadlessBrowserTestWithNetLog() {} + HeadlessBrowserTestWithNetLog() = default; void SetUp() override { base::ThreadRestrictions::SetIOAllowed(true);
diff --git a/headless/lib/headless_content_client.cc b/headless/lib/headless_content_client.cc index fa06d5a..8de358f 100644 --- a/headless/lib/headless_content_client.cc +++ b/headless/lib/headless_content_client.cc
@@ -12,7 +12,7 @@ HeadlessContentClient::HeadlessContentClient(HeadlessBrowser::Options* options) : options_(options) {} -HeadlessContentClient::~HeadlessContentClient() {} +HeadlessContentClient::~HeadlessContentClient() = default; std::string HeadlessContentClient::GetProduct() const { return options_->product_name_and_version;
diff --git a/headless/lib/headless_web_contents_browsertest.cc b/headless/lib/headless_web_contents_browsertest.cc index 9077cea..41fcdd98 100644 --- a/headless/lib/headless_web_contents_browsertest.cc +++ b/headless/lib/headless_web_contents_browsertest.cc
@@ -66,8 +66,8 @@ MOCK_METHOD2(OnChildContentsCreated, void(HeadlessWebContents*, HeadlessWebContents*)); - MockHeadlessBrowserContextObserver() {} - virtual ~MockHeadlessBrowserContextObserver() {} + MockHeadlessBrowserContextObserver() = default; + virtual ~MockHeadlessBrowserContextObserver() = default; HeadlessWebContents* last_parent; HeadlessWebContents* last_child; @@ -261,7 +261,7 @@ class HeadlessNoDevToolsTabSocketTest : public HeadlessBrowserTest, public HeadlessTabSocket::Listener { public: - HeadlessNoDevToolsTabSocketTest() {} + HeadlessNoDevToolsTabSocketTest() = default; void SetUp() override { options()->mojo_service_names.insert("headless::TabSocket"); @@ -1220,7 +1220,7 @@ class HeadlessWebContentsBeginFrameControlBasicTest : public HeadlessWebContentsBeginFrameControlTest { public: - HeadlessWebContentsBeginFrameControlBasicTest() {} + HeadlessWebContentsBeginFrameControlBasicTest() = default; protected: std::string GetTestHtmlFile() override { @@ -1266,7 +1266,7 @@ class HeadlessWebContentsBeginFrameControlViewportTest : public HeadlessWebContentsBeginFrameControlTest { public: - HeadlessWebContentsBeginFrameControlViewportTest() {} + HeadlessWebContentsBeginFrameControlViewportTest() = default; protected: std::string GetTestHtmlFile() override {
diff --git a/headless/lib/renderer/headless_content_renderer_client.cc b/headless/lib/renderer/headless_content_renderer_client.cc index ce73e4d..edde2666 100644 --- a/headless/lib/renderer/headless_content_renderer_client.cc +++ b/headless/lib/renderer/headless_content_renderer_client.cc
@@ -15,9 +15,9 @@ namespace headless { -HeadlessContentRendererClient::HeadlessContentRendererClient() {} +HeadlessContentRendererClient::HeadlessContentRendererClient() = default; -HeadlessContentRendererClient::~HeadlessContentRendererClient() {} +HeadlessContentRendererClient::~HeadlessContentRendererClient() = default; void HeadlessContentRendererClient::RenderFrameCreated( content::RenderFrame* render_frame) {
diff --git a/headless/lib/renderer/headless_print_render_frame_helper_delegate.cc b/headless/lib/renderer/headless_print_render_frame_helper_delegate.cc index 21dded7..1b0995d 100644 --- a/headless/lib/renderer/headless_print_render_frame_helper_delegate.cc +++ b/headless/lib/renderer/headless_print_render_frame_helper_delegate.cc
@@ -9,10 +9,10 @@ namespace headless { HeadlessPrintRenderFrameHelperDelegate:: - HeadlessPrintRenderFrameHelperDelegate() {} + HeadlessPrintRenderFrameHelperDelegate() = default; HeadlessPrintRenderFrameHelperDelegate:: - ~HeadlessPrintRenderFrameHelperDelegate() {} + ~HeadlessPrintRenderFrameHelperDelegate() = default; bool HeadlessPrintRenderFrameHelperDelegate::CancelPrerender( content::RenderFrame* render_frame) {
diff --git a/headless/lib/renderer/headless_render_frame_controller_impl.cc b/headless/lib/renderer/headless_render_frame_controller_impl.cc index b6761a6..9f695f6 100644 --- a/headless/lib/renderer/headless_render_frame_controller_impl.cc +++ b/headless/lib/renderer/headless_render_frame_controller_impl.cc
@@ -21,7 +21,8 @@ base::Unretained(this))); } -HeadlessRenderFrameControllerImpl::~HeadlessRenderFrameControllerImpl() {} +HeadlessRenderFrameControllerImpl::~HeadlessRenderFrameControllerImpl() = + default; void HeadlessRenderFrameControllerImpl::OnRenderFrameControllerRequest( HeadlessRenderFrameControllerRequest request) {
diff --git a/headless/lib/renderer/headless_tab_socket_bindings.cc b/headless/lib/renderer/headless_tab_socket_bindings.cc index 94198ab..247ed07 100644 --- a/headless/lib/renderer/headless_tab_socket_bindings.cc +++ b/headless/lib/renderer/headless_tab_socket_bindings.cc
@@ -22,7 +22,7 @@ world_id_(world_id), installed_(false) {} -HeadlessTabSocketBindings::~HeadlessTabSocketBindings() {} +HeadlessTabSocketBindings::~HeadlessTabSocketBindings() = default; bool HeadlessTabSocketBindings::InitializeTabSocketBindings() { if (installed_)
diff --git a/headless/lib/utility/headless_content_utility_client.cc b/headless/lib/utility/headless_content_utility_client.cc index a2ddaee..d0e5f19d 100644 --- a/headless/lib/utility/headless_content_utility_client.cc +++ b/headless/lib/utility/headless_content_utility_client.cc
@@ -17,7 +17,7 @@ const std::string& user_agent) : user_agent_(user_agent) {} -HeadlessContentUtilityClient::~HeadlessContentUtilityClient() {} +HeadlessContentUtilityClient::~HeadlessContentUtilityClient() = default; void HeadlessContentUtilityClient::RegisterServices( HeadlessContentUtilityClient::StaticServiceMap* services) {
diff --git a/headless/public/headless_browser.cc b/headless/public/headless_browser.cc index 723babdd60..7e124fc 100644 --- a/headless/public/headless_browser.cc +++ b/headless/public/headless_browser.cc
@@ -49,7 +49,7 @@ Options::Options(Options&& options) = default; -Options::~Options() {} +Options::~Options() = default; Options& Options::operator=(Options&& options) = default; @@ -61,7 +61,7 @@ Builder::Builder() : options_(0, nullptr) {} -Builder::~Builder() {} +Builder::~Builder() = default; Builder& Builder::SetProductNameAndVersion( const std::string& product_name_and_version) {
diff --git a/headless/public/util/black_hole_protocol_handler.cc b/headless/public/util/black_hole_protocol_handler.cc index 3f036c5..31a269b 100644 --- a/headless/public/util/black_hole_protocol_handler.cc +++ b/headless/public/util/black_hole_protocol_handler.cc
@@ -34,7 +34,7 @@ net::NetworkDelegate* network_delegate) : net::URLRequestJob(request, network_delegate), weak_factory_(this) {} -BlackHoleRequestJob::~BlackHoleRequestJob() {} +BlackHoleRequestJob::~BlackHoleRequestJob() = default; void BlackHoleRequestJob::Start() { base::ThreadTaskRunnerHandle::Get()->PostTask( @@ -54,8 +54,8 @@ } } // namespace -BlackHoleProtocolHandler::BlackHoleProtocolHandler() {} -BlackHoleProtocolHandler::~BlackHoleProtocolHandler() {} +BlackHoleProtocolHandler::BlackHoleProtocolHandler() = default; +BlackHoleProtocolHandler::~BlackHoleProtocolHandler() = default; net::URLRequestJob* BlackHoleProtocolHandler::MaybeCreateJob( net::URLRequest* request,
diff --git a/headless/public/util/compositor_controller_unittest.cc b/headless/public/util/compositor_controller_unittest.cc index e5b0e88..33aa032d 100644 --- a/headless/public/util/compositor_controller_unittest.cc +++ b/headless/public/util/compositor_controller_unittest.cc
@@ -33,7 +33,7 @@ public: TestVirtualTimeController(HeadlessDevToolsClient* devtools_client) : VirtualTimeController(devtools_client) {} - ~TestVirtualTimeController() override {} + ~TestVirtualTimeController() override = default; MOCK_METHOD4(GrantVirtualTimeBudget, void(emulation::VirtualTimePolicy policy,
diff --git a/headless/public/util/deterministic_dispatcher.cc b/headless/public/util/deterministic_dispatcher.cc index bfa75e5b..e9507c5 100644 --- a/headless/public/util/deterministic_dispatcher.cc +++ b/headless/public/util/deterministic_dispatcher.cc
@@ -20,7 +20,7 @@ navigation_in_progress_(false), weak_ptr_factory_(this) {} -DeterministicDispatcher::~DeterministicDispatcher() {} +DeterministicDispatcher::~DeterministicDispatcher() = default; void DeterministicDispatcher::JobCreated(ManagedDispatchURLRequestJob* job) { base::AutoLock lock(lock_); @@ -144,7 +144,7 @@ DeterministicDispatcher::Request::Request() = default; DeterministicDispatcher::Request::Request(Request&&) = default; -DeterministicDispatcher::Request::~Request() {} +DeterministicDispatcher::Request::~Request() = default; DeterministicDispatcher::Request::Request( ManagedDispatchURLRequestJob* url_request)
diff --git a/headless/public/util/deterministic_dispatcher_test.cc b/headless/public/util/deterministic_dispatcher_test.cc index 48b30e29..5b769800 100644 --- a/headless/public/util/deterministic_dispatcher_test.cc +++ b/headless/public/util/deterministic_dispatcher_test.cc
@@ -23,8 +23,8 @@ class DeterministicDispatcherTest : public ::testing::Test { protected: - DeterministicDispatcherTest() {} - ~DeterministicDispatcherTest() override {} + DeterministicDispatcherTest() = default; + ~DeterministicDispatcherTest() override = default; void SetUp() override { deterministic_dispatcher_.reset( @@ -135,7 +135,7 @@ explicit NavigationRequestForTest(base::Closure* done_closure) : done_closure_(done_closure) {} - ~NavigationRequestForTest() override {} + ~NavigationRequestForTest() override = default; // NavigationRequest implementation: void StartProcessing(base::Closure done_callback) override {
diff --git a/headless/public/util/deterministic_http_protocol_handler.cc b/headless/public/util/deterministic_http_protocol_handler.cc index 8ff8e37..84cc848 100644 --- a/headless/public/util/deterministic_http_protocol_handler.cc +++ b/headless/public/util/deterministic_http_protocol_handler.cc
@@ -19,8 +19,8 @@ class DeterministicHttpProtocolHandler::NopGenericURLRequestJobDelegate : public GenericURLRequestJob::Delegate { public: - NopGenericURLRequestJobDelegate() {} - ~NopGenericURLRequestJobDelegate() override {} + NopGenericURLRequestJobDelegate() = default; + ~NopGenericURLRequestJobDelegate() override = default; void OnResourceLoadFailed(const Request* request, net::Error error) override { }
diff --git a/headless/public/util/error_reporter.cc b/headless/public/util/error_reporter.cc index ad356c21..7f4df91 100644 --- a/headless/public/util/error_reporter.cc +++ b/headless/public/util/error_reporter.cc
@@ -11,9 +11,9 @@ namespace headless { -ErrorReporter::ErrorReporter() {} +ErrorReporter::ErrorReporter() = default; -ErrorReporter::~ErrorReporter() {} +ErrorReporter::~ErrorReporter() = default; #if DCHECK_IS_ON() void ErrorReporter::Push() {
diff --git a/headless/public/util/expedited_dispatcher.cc b/headless/public/util/expedited_dispatcher.cc index 649321a7..1fe445c 100644 --- a/headless/public/util/expedited_dispatcher.cc +++ b/headless/public/util/expedited_dispatcher.cc
@@ -16,7 +16,7 @@ scoped_refptr<base::SingleThreadTaskRunner> io_thread_task_runner) : io_thread_task_runner_(std::move(io_thread_task_runner)) {} -ExpeditedDispatcher::~ExpeditedDispatcher() {} +ExpeditedDispatcher::~ExpeditedDispatcher() = default; void ExpeditedDispatcher::JobCreated(ManagedDispatchURLRequestJob*) {}
diff --git a/headless/public/util/expedited_dispatcher_test.cc b/headless/public/util/expedited_dispatcher_test.cc index dacc82d..05571f6 100644 --- a/headless/public/util/expedited_dispatcher_test.cc +++ b/headless/public/util/expedited_dispatcher_test.cc
@@ -23,8 +23,8 @@ class ExpeditedDispatcherTest : public ::testing::Test { protected: - ExpeditedDispatcherTest() {} - ~ExpeditedDispatcherTest() override {} + ExpeditedDispatcherTest() = default; + ~ExpeditedDispatcherTest() override = default; void SetUp() override { expedited_dispatcher_.reset(new ExpeditedDispatcher(loop_.task_runner())); @@ -92,7 +92,7 @@ explicit NavigationRequestForTest(base::Closure* done_closure) : done_closure_(done_closure) {} - ~NavigationRequestForTest() override {} + ~NavigationRequestForTest() override = default; // NavigationRequest implementation: void StartProcessing(base::Closure done_callback) override {
diff --git a/headless/public/util/generic_url_request_job.cc b/headless/public/util/generic_url_request_job.cc index a5e63b9..2644666f 100644 --- a/headless/public/util/generic_url_request_job.cc +++ b/headless/public/util/generic_url_request_job.cc
@@ -310,28 +310,9 @@ *dest = value; quit_closure->Run(); } -} // namespace -std::string GenericURLRequestJob::GetPostData() const { - if (!request_->has_upload()) - return ""; - - const net::UploadDataStream* stream = request_->get_upload(); - if (!stream->GetElementReaders()) - return ""; - - if (stream->GetElementReaders()->size() == 0) - return ""; - - DCHECK_EQ(1u, stream->GetElementReaders()->size()); - const std::unique_ptr<net::UploadElementReader>& reader = - (*stream->GetElementReaders())[0]; - // If |reader| is actually an UploadBytesElementReader we can get the data - // directly (should be faster than the horrible stuff below). - const net::UploadBytesElementReader* bytes_reader = reader->AsBytesReader(); - if (bytes_reader) - return std::string(bytes_reader->bytes(), bytes_reader->length()); - +bool ReadAndAppendBytes(const std::unique_ptr<net::UploadElementReader>& reader, + std::string& post_data) { // TODO(alexclarke): Consider changing the interface of // GenericURLRequestJob::GetPostData to use a callback which would let us // avoid the nested run loops below. @@ -348,13 +329,11 @@ } if (init_result != net::OK) - return ""; + return false; } // Read the POST bytes. uint64_t content_length = reader->GetContentLength(); - std::string post_data; - post_data.reserve(content_length); const size_t block_size = 1024; scoped_refptr<net::IOBuffer> read_buffer(new net::IOBuffer(block_size)); while (post_data.size() < content_length) { @@ -371,10 +350,50 @@ // Bail out if an error occured. if (bytes_read < 0) - return ""; + return false; post_data.append(read_buffer->data(), bytes_read); } + return true; +} +} // namespace + +std::string GenericURLRequestJob::GetPostData() const { + if (!request_->has_upload()) + return ""; + + const net::UploadDataStream* stream = request_->get_upload(); + if (!stream->GetElementReaders()) + return ""; + + if (stream->GetElementReaders()->size() == 0) + return ""; + + const std::vector<std::unique_ptr<net::UploadElementReader>>* readers = + stream->GetElementReaders(); + if (!readers) + return ""; + + uint64_t total_content_length = 0; + for (size_t i = 0; i < readers->size(); ++i) { + const std::unique_ptr<net::UploadElementReader>& reader = (*readers)[i]; + total_content_length += reader->GetContentLength(); + } + std::string post_data; + post_data.reserve(total_content_length); + + for (size_t i = 0; i < readers->size(); ++i) { + const std::unique_ptr<net::UploadElementReader>& reader = (*readers)[i]; + // If |reader| is actually an UploadBytesElementReader we can get the data + // directly. + const net::UploadBytesElementReader* bytes_reader = reader->AsBytesReader(); + if (bytes_reader) { + post_data.append(bytes_reader->bytes(), bytes_reader->length()); + } else { + if (!ReadAndAppendBytes(reader, post_data)) + break; // Bail out if something went wrong. + } + } return post_data; }
diff --git a/headless/public/util/generic_url_request_job_test.cc b/headless/public/util/generic_url_request_job_test.cc index 5bd8ff3..5fe9dc7 100644 --- a/headless/public/util/generic_url_request_job_test.cc +++ b/headless/public/util/generic_url_request_job_test.cc
@@ -58,13 +58,15 @@ class MockFetcher : public URLFetcher { public: MockFetcher(base::DictionaryValue* fetch_request, + std::string* recieved_post_data, std::map<std::string, std::string>* json_fetch_reply_map, base::Callback<void(const Request*)>* on_request_callback) : json_fetch_reply_map_(json_fetch_reply_map), fetch_request_(fetch_request), + received_post_data_(recieved_post_data), on_request_callback_(on_request_callback) {} - ~MockFetcher() override {} + ~MockFetcher() override = default; void StartFetch(const Request* request, ResultListener* result_listener) override { @@ -81,9 +83,9 @@ headers->SetString(it.name(), it.value()); } fetch_request_->Set("headers", std::move(headers)); - std::string post_data = request->GetPostData(); - if (!post_data.empty()) - fetch_request_->SetString("post_data", std::move(post_data)); + *received_post_data_ = request->GetPostData(); + if (!received_post_data_->empty() && received_post_data_->size() < 1024) + fetch_request_->SetString("post_data", *received_post_data_); const auto find_it = json_fetch_reply_map_->find(url); if (find_it == json_fetch_reply_map_->end()) { @@ -125,8 +127,9 @@ } private: - std::map<std::string, std::string>* json_fetch_reply_map_; // NOT OWNED - base::DictionaryValue* fetch_request_; // NOT OWNED + std::map<std::string, std::string>* json_fetch_reply_map_; // NOT OWNED + base::DictionaryValue* fetch_request_; // NOT OWNED + std::string* received_post_data_; // NOT OWNED base::Callback<void(const Request*)>* on_request_callback_; // NOT OWNED std::string response_data_; // Here to ensure the required lifetime. }; @@ -136,11 +139,13 @@ // Details of the fetch will be stored in |fetch_request|. // The fetch response will be created from parsing |json_fetch_reply_map|. MockProtocolHandler(base::DictionaryValue* fetch_request, + std::string* recieved_post_data, std::map<std::string, std::string>* json_fetch_reply_map, URLRequestDispatcher* dispatcher, GenericURLRequestJob::Delegate* job_delegate, base::Callback<void(const Request*)>* on_request_callback) : fetch_request_(fetch_request), + received_post_data_(recieved_post_data), json_fetch_reply_map_(json_fetch_reply_map), job_delegate_(job_delegate), dispatcher_(dispatcher), @@ -152,13 +157,15 @@ net::NetworkDelegate* network_delegate) const override { return new GenericURLRequestJob( request, network_delegate, dispatcher_, - base::MakeUnique<MockFetcher>(fetch_request_, json_fetch_reply_map_, + base::MakeUnique<MockFetcher>(fetch_request_, received_post_data_, + json_fetch_reply_map_, on_request_callback_), job_delegate_, nullptr); } private: base::DictionaryValue* fetch_request_; // NOT OWNED + std::string* received_post_data_; // NOT OWNED std::map<std::string, std::string>* json_fetch_reply_map_; // NOT OWNED GenericURLRequestJob::Delegate* job_delegate_; // NOT OWNED URLRequestDispatcher* dispatcher_; // NOT OWNED @@ -171,9 +178,10 @@ public: GenericURLRequestJobTest() : dispatcher_(message_loop_.task_runner()) { url_request_job_factory_.SetProtocolHandler( - "https", base::WrapUnique(new MockProtocolHandler( - &fetch_request_, &json_fetch_reply_map_, &dispatcher_, - &job_delegate_, &on_request_callback_))); + "https", + base::WrapUnique(new MockProtocolHandler( + &fetch_request_, &received_post_data_, &json_fetch_reply_map_, + &dispatcher_, &job_delegate_, &on_request_callback_))); url_request_context_.set_job_factory(&url_request_job_factory_); url_request_context_.set_cookie_store(&cookie_store_); } @@ -220,6 +228,7 @@ MockURLRequestDelegate request_delegate_; base::DictionaryValue fetch_request_; // The request sent to MockFetcher. + std::string received_post_data_; // The POST data (useful if large). std::map<std::string, std::string> json_fetch_reply_map_; // Replies to be sent by MockFetcher. MockDelegate job_delegate_; @@ -305,6 +314,44 @@ EXPECT_THAT(fetch_request_, MatchesJson(expected_request_json)); } +TEST_F(GenericURLRequestJobTest, LargePostData) { + json_fetch_reply_map_["https://example.com/"] = R"( + { + "url": "https://example.com", + "data": "Reply", + "headers": { + "Content-Type": "text/html; charset=UTF-8" + } + })"; + + std::unique_ptr<net::URLRequest> request(url_request_context_.CreateRequest( + GURL("https://example.com"), net::DEFAULT_PRIORITY, &request_delegate_, + TRAFFIC_ANNOTATION_FOR_TESTS)); + request->SetReferrer("https://referrer.example.com"); + request->SetExtraRequestHeaderByName("Extra-Header", "Value", true); + request->SetExtraRequestHeaderByName("User-Agent", "TestBrowser", true); + request->SetExtraRequestHeaderByName("Accept", "text/plain", true); + request->set_method("POST"); + + std::vector<char> post_data(4000000); + for (size_t i = 0; i < post_data.size(); i++) + post_data[i] = i & 127; + + request->set_upload(net::ElementsUploadDataStream::CreateWithReader( + base::MakeUnique<net::UploadBytesElementReader>(&post_data[0], + post_data.size()), + 0)); + request->Start(); + base::RunLoop().RunUntilIdle(); + + // Make sure we captured the expected post. + for (size_t i = 0; i < received_post_data_.size(); i++) { + EXPECT_EQ(static_cast<char>(i & 127), post_data[i]); + } + + EXPECT_EQ(post_data.size(), received_post_data_.size()); +} + TEST_F(GenericURLRequestJobTest, BasicRequestProperties) { std::string reply = R"( { @@ -623,4 +670,42 @@ EXPECT_EQ(post_data_size, post_data.size()); } +TEST_F(GenericURLRequestJobTest, LargePostDataNotByteReader) { + json_fetch_reply_map_["https://example.com/"] = R"( + { + "url": "https://example.com", + "data": "Reply", + "headers": { + "Content-Type": "text/html; charset=UTF-8" + } + })"; + + std::unique_ptr<net::URLRequest> request(url_request_context_.CreateRequest( + GURL("https://example.com"), net::DEFAULT_PRIORITY, &request_delegate_, + TRAFFIC_ANNOTATION_FOR_TESTS)); + request->SetReferrer("https://referrer.example.com"); + request->SetExtraRequestHeaderByName("Extra-Header", "Value", true); + request->SetExtraRequestHeaderByName("User-Agent", "TestBrowser", true); + request->SetExtraRequestHeaderByName("Accept", "text/plain", true); + request->set_method("POST"); + + std::string post_data; + post_data.reserve(4000000); + for (size_t i = 0; i < post_data.size(); i++) + post_data.at(i) = i & 127; + + // TODO(alexclarke) Add a multiple element test too. + request->set_upload(net::ElementsUploadDataStream::CreateWithReader( + base::MakeUnique<ByteAtATimeUploadElementReader>(post_data), 0)); + request->Start(); + base::RunLoop().RunUntilIdle(); + + // Make sure we captured the expected post. + for (size_t i = 0; i < received_post_data_.size(); i++) { + EXPECT_EQ(static_cast<char>(i & 127), post_data[i]); + } + + EXPECT_EQ(post_data.size(), received_post_data_.size()); +} + } // namespace headless
diff --git a/headless/public/util/http_url_fetcher.cc b/headless/public/util/http_url_fetcher.cc index 20e44ea9..0e83ebb 100644 --- a/headless/public/util/http_url_fetcher.cc +++ b/headless/public/util/http_url_fetcher.cc
@@ -116,7 +116,7 @@ request_->Start(); } -HttpURLFetcher::Delegate::~Delegate() {} +HttpURLFetcher::Delegate::~Delegate() = default; void HttpURLFetcher::Delegate::OnAuthRequired( net::URLRequest* request, @@ -228,7 +228,7 @@ const net::URLRequestContext* url_request_context) : url_request_context_(url_request_context) {} -HttpURLFetcher::~HttpURLFetcher() {} +HttpURLFetcher::~HttpURLFetcher() = default; void HttpURLFetcher::StartFetch(const Request* request, ResultListener* result_listener) {
diff --git a/headless/public/util/in_memory_protocol_handler.cc b/headless/public/util/in_memory_protocol_handler.cc index 27c0765..49dd8c01 100644 --- a/headless/public/util/in_memory_protocol_handler.cc +++ b/headless/public/util/in_memory_protocol_handler.cc
@@ -8,8 +8,8 @@ namespace headless { -InMemoryProtocolHandler::InMemoryProtocolHandler() {} -InMemoryProtocolHandler::~InMemoryProtocolHandler() {} +InMemoryProtocolHandler::InMemoryProtocolHandler() = default; +InMemoryProtocolHandler::~InMemoryProtocolHandler() = default; net::URLRequestJob* InMemoryProtocolHandler::MaybeCreateJob( net::URLRequest* request,
diff --git a/headless/public/util/in_memory_request_job.cc b/headless/public/util/in_memory_request_job.cc index 5fa84151..4e94518 100644 --- a/headless/public/util/in_memory_request_job.cc +++ b/headless/public/util/in_memory_request_job.cc
@@ -21,7 +21,7 @@ data_offset_(0), weak_factory_(this) {} -InMemoryRequestJob::~InMemoryRequestJob() {} +InMemoryRequestJob::~InMemoryRequestJob() = default; void InMemoryRequestJob::Start() { // Start reading asynchronously so that all error reporting and data
diff --git a/headless/public/util/testing/generic_url_request_mocks.cc b/headless/public/util/testing/generic_url_request_mocks.cc index 7059310..af3b183 100644 --- a/headless/public/util/testing/generic_url_request_mocks.cc +++ b/headless/public/util/testing/generic_url_request_mocks.cc
@@ -20,7 +20,7 @@ MockGenericURLRequestJobDelegate::MockGenericURLRequestJobDelegate() : main_thread_task_runner_(base::ThreadTaskRunnerHandle::Get()) {} -MockGenericURLRequestJobDelegate::~MockGenericURLRequestJobDelegate() {} +MockGenericURLRequestJobDelegate::~MockGenericURLRequestJobDelegate() = default; void MockGenericURLRequestJobDelegate::OnResourceLoadFailed( const Request* request, @@ -34,8 +34,8 @@ size_t body_size) {} // MockCookieStore -MockCookieStore::MockCookieStore() {} -MockCookieStore::~MockCookieStore() {} +MockCookieStore::MockCookieStore() = default; +MockCookieStore::~MockCookieStore() = default; void MockCookieStore::SetCookieWithOptionsAsync( const GURL& url, @@ -161,8 +161,8 @@ } // MockURLRequestDelegate -MockURLRequestDelegate::MockURLRequestDelegate() {} -MockURLRequestDelegate::~MockURLRequestDelegate() {} +MockURLRequestDelegate::MockURLRequestDelegate() = default; +MockURLRequestDelegate::~MockURLRequestDelegate() = default; void MockURLRequestDelegate::OnResponseStarted(net::URLRequest* request, int net_error) {}
diff --git a/headless/public/util/testing/mock_devtools_agent_host.cc b/headless/public/util/testing/mock_devtools_agent_host.cc index 7895922..683b4f9 100644 --- a/headless/public/util/testing/mock_devtools_agent_host.cc +++ b/headless/public/util/testing/mock_devtools_agent_host.cc
@@ -6,8 +6,8 @@ namespace headless { -MockDevToolsAgentHost::MockDevToolsAgentHost() {} +MockDevToolsAgentHost::MockDevToolsAgentHost() = default; -MockDevToolsAgentHost::~MockDevToolsAgentHost() {} +MockDevToolsAgentHost::~MockDevToolsAgentHost() = default; } // namespace headless
diff --git a/headless/public/util/testing/test_in_memory_protocol_handler.cc b/headless/public/util/testing/test_in_memory_protocol_handler.cc index c0e019d..8883fb1d 100644 --- a/headless/public/util/testing/test_in_memory_protocol_handler.cc +++ b/headless/public/util/testing/test_in_memory_protocol_handler.cc
@@ -15,7 +15,7 @@ public: explicit MockURLFetcher(TestInMemoryProtocolHandler* protocol_handler) : protocol_handler_(protocol_handler) {} - ~MockURLFetcher() override {} + ~MockURLFetcher() override = default; // URLFetcher implementation: void StartFetch(const Request* request, @@ -58,8 +58,8 @@ class TestInMemoryProtocolHandler::TestDelegate : public GenericURLRequestJob::Delegate { public: - TestDelegate() {} - ~TestDelegate() override {} + TestDelegate() = default; + ~TestDelegate() override = default; // GenericURLRequestJob::Delegate implementation: void OnResourceLoadFailed(const Request* request, net::Error error) override { @@ -87,7 +87,7 @@ request_deferrer_(request_deferrer), io_thread_task_runner_(io_thread_task_runner) {} -TestInMemoryProtocolHandler::~TestInMemoryProtocolHandler() {} +TestInMemoryProtocolHandler::~TestInMemoryProtocolHandler() = default; void TestInMemoryProtocolHandler::SetHeadlessBrowserContext( HeadlessBrowserContext* headless_browser_context) {
diff --git a/headless/public/util/throttled_dispatcher.cc b/headless/public/util/throttled_dispatcher.cc index 48efca7..0e76760 100644 --- a/headless/public/util/throttled_dispatcher.cc +++ b/headless/public/util/throttled_dispatcher.cc
@@ -17,7 +17,7 @@ : ExpeditedDispatcher(std::move(io_thread_task_runner)), requests_paused_(false) {} -ThrottledDispatcher::~ThrottledDispatcher() {} +ThrottledDispatcher::~ThrottledDispatcher() = default; void ThrottledDispatcher::PauseRequests() { base::AutoLock lock(lock_);
diff --git a/headless/public/util/throttled_dispatcher_test.cc b/headless/public/util/throttled_dispatcher_test.cc index 5e3ba3f..d37c9fb 100644 --- a/headless/public/util/throttled_dispatcher_test.cc +++ b/headless/public/util/throttled_dispatcher_test.cc
@@ -23,8 +23,8 @@ class ThrottledDispatcherTest : public ::testing::Test { protected: - ThrottledDispatcherTest() {} - ~ThrottledDispatcherTest() override {} + ThrottledDispatcherTest() = default; + ~ThrottledDispatcherTest() override = default; void SetUp() override { throttled_dispatcher_.reset(new ThrottledDispatcher(loop_.task_runner()));
diff --git a/headless/public/util/virtual_time_controller_test.cc b/headless/public/util/virtual_time_controller_test.cc index 217ccd5c..483a99b 100644 --- a/headless/public/util/virtual_time_controller_test.cc +++ b/headless/public/util/virtual_time_controller_test.cc
@@ -34,7 +34,7 @@ controller_ = base::MakeUnique<VirtualTimeController>(&client_, 0); } - ~VirtualTimeControllerTest() override {} + ~VirtualTimeControllerTest() override = default; void GrantVirtualTimeBudget(int budget_ms) { ASSERT_FALSE(set_up_complete_);
diff --git a/headless/test/headless_browser_test.cc b/headless/test/headless_browser_test.cc index 7f4b8843..8695223 100644 --- a/headless/test/headless_browser_test.cc +++ b/headless/test/headless_browser_test.cc
@@ -150,7 +150,7 @@ BrowserTestBase::SetUp(); } -HeadlessBrowserTest::~HeadlessBrowserTest() {} +HeadlessBrowserTest::~HeadlessBrowserTest() = default; void HeadlessBrowserTest::PreRunTestOnMainThread() { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); @@ -215,7 +215,8 @@ browser_devtools_client_(HeadlessDevToolsClient::Create()), render_process_exited_(false) {} -HeadlessAsyncDevTooledBrowserTest::~HeadlessAsyncDevTooledBrowserTest() {} +HeadlessAsyncDevTooledBrowserTest::~HeadlessAsyncDevTooledBrowserTest() = + default; void HeadlessAsyncDevTooledBrowserTest::DevToolsTargetReady() { EXPECT_TRUE(web_contents_->GetDevToolsTarget());
diff --git a/headless/test/headless_render_browsertest.cc b/headless/test/headless_render_browsertest.cc index fdbf8633..714f9a51 100644 --- a/headless/test/headless_render_browsertest.cc +++ b/headless/test/headless_render_browsertest.cc
@@ -21,6 +21,9 @@ class HeadlessRenderBrowserTest##clazz : public clazz {}; \ HEADLESS_ASYNC_DEVTOOLED_TEST_F(HeadlessRenderBrowserTest##clazz) +// TODO(dats): For some reason we are missing all HTTP redirects. +#define DISABLE_HTTP_REDIRECTS_CHECKS + namespace headless { namespace { @@ -32,6 +35,16 @@ using dom_snapshot::GetSnapshotResult; using dom_snapshot::DOMNode; using dom_snapshot::LayoutTreeNode; +using net::test_server::HttpRequest; +using net::test_server::HttpResponse; +using net::test_server::BasicHttpResponse; +using net::test_server::RawHttpResponse; +using page::FrameScheduledNavigationReason; +using testing::ElementsAre; +using testing::UnorderedElementsAre; +using testing::Eq; +using testing::Ne; +using testing::StartsWith; template <typename T, typename V> std::vector<T> ElementsView(const std::vector<std::unique_ptr<V>>& elements, @@ -117,21 +130,27 @@ return arg.relative_url == expected; } -using testing::ElementsAre; -using testing::Eq; -using testing::StartsWith; -using net::test_server::HttpRequest; -using net::test_server::HttpResponse; -using net::test_server::BasicHttpResponse; -using net::test_server::RawHttpResponse; +MATCHER_P(RedirectUrl, expected, "") { + return arg.first == expected; +} +MATCHER_P(RedirectReason, expected, "") { + return arg.second == expected; +} + +const DOMNode* FindTag(const GetSnapshotResult* snapshot, const char* name) { + auto tags = FindTags(snapshot, name); + if (tags.empty()) + return nullptr; + EXPECT_THAT(tags, ElementsAre(NodeName(name))); + return tags[0]; +} } // namespace class HelloWorldTest : public HeadlessRenderTest { private: GURL GetPageUrl(HeadlessDevToolsClient* client) override { - GetProtocolHandler()->InsertResponse(SOME_URL, {R"|( -<!doctype html> + GetProtocolHandler()->InsertResponse(SOME_URL, {R"|(<!doctype html> <h1>Hello headless world!</h1> )|", TEXT_HTML}); @@ -146,6 +165,13 @@ FilterDOM(dom_snapshot, IsText), ElementsAre(NodeValue("Hello headless world!"), NodeValue("\n"))); EXPECT_THAT(TextLayout(dom_snapshot), ElementsAre("Hello headless world!")); + EXPECT_THAT(GetProtocolHandler()->urls_requested(), ElementsAre(SOME_URL)); + EXPECT_FALSE(main_frame_.empty()); + EXPECT_TRUE(unconfirmed_frame_redirects_.empty()); + EXPECT_TRUE(confirmed_frame_redirects_.empty()); + EXPECT_THAT(frames_[main_frame_].size(), Eq(1u)); + const auto& frame = frames_[main_frame_][0]; + EXPECT_THAT(frame->GetUrl(), Eq(SOME_URL)); } }; HEADLESS_RENDER_BROWSERTEST(HelloWorldTest); @@ -187,9 +213,8 @@ } void VerifyDom(GetSnapshotResult* dom_snapshot) override { - auto dom = FindTags(dom_snapshot, "TITLE"); - ASSERT_THAT(dom, ElementsAre(NodeName("TITLE"))); - const DOMNode* value = NextNode(dom_snapshot, dom[0]); + const DOMNode* value = + NextNode(dom_snapshot, FindTag(dom_snapshot, "TITLE")); EXPECT_THAT(value, NodeValue("JavaScript is on")); } }; @@ -204,9 +229,8 @@ } void VerifyDom(GetSnapshotResult* dom_snapshot) override { - auto dom = FindTags(dom_snapshot, "TITLE"); - ASSERT_THAT(dom, ElementsAre(NodeName("TITLE"))); - const DOMNode* value = NextNode(dom_snapshot, dom[0]); + const DOMNode* value = + NextNode(dom_snapshot, FindTag(dom_snapshot, "TITLE")); EXPECT_THAT(value, NodeValue("JavaScript is off")); } }; @@ -312,9 +336,7 @@ FindTags(dom_snapshot), ElementsAre(NodeName("HTML"), NodeName("HEAD"), NodeName("BODY"), NodeName("SCRIPT"), NodeName("DIV"), NodeName("P"))); - auto dom = FindTags(dom_snapshot, "P"); - ASSERT_THAT(dom, ElementsAre(NodeName("P"))); - const DOMNode* value = NextNode(dom_snapshot, dom[0]); + const DOMNode* value = NextNode(dom_snapshot, FindTag(dom_snapshot, "P")); EXPECT_THAT(value, NodeValue("delayed text")); // The page delays output for 3 seconds. Due to virtual time this should // take significantly less actual time. @@ -382,15 +404,371 @@ } void VerifyDom(GetSnapshotResult* dom_snapshot) override { - EXPECT_THAT(GetProtocolHandler()->urls_requested(), - ElementsAre(SOME_HOST + "/", SOME_HOST + "/1", SOME_HOST + "/2", - SOME_HOST + "/3", SOME_HOST + "/pass")); - auto dom = FindTags(dom_snapshot, "TITLE"); - ASSERT_THAT(dom, ElementsAre(NodeName("TITLE"))); - const DOMNode* value = NextNode(dom_snapshot, dom[0]); + EXPECT_THAT( + GetProtocolHandler()->urls_requested(), + ElementsAre("http://www.example.com/", "http://www.example.com/1", + "http://www.example.com/2", "http://www.example.com/3", + "http://www.example.com/pass")); + const DOMNode* value = + NextNode(dom_snapshot, FindTag(dom_snapshot, "TITLE")); EXPECT_THAT(value, NodeValue("Pass")); + EXPECT_THAT( + confirmed_frame_redirects_[main_frame_], + ElementsAre( + RedirectReason(FrameScheduledNavigationReason::META_TAG_REFRESH), + RedirectReason(FrameScheduledNavigationReason::SCRIPT_INITIATED), + RedirectReason(FrameScheduledNavigationReason::SCRIPT_INITIATED))); + EXPECT_THAT(frames_[main_frame_].size(), Eq(4u)); } }; HEADLESS_RENDER_BROWSERTEST(ClientRedirectChain); +class ClientRedirectChain_NoJs : public ClientRedirectChain { + private: + void OverrideWebPreferences(WebPreferences* preferences) override { + ClientRedirectChain::OverrideWebPreferences(preferences); + preferences->javascript_enabled = false; + } + + void VerifyDom(GetSnapshotResult* dom_snapshot) override { + EXPECT_THAT( + GetProtocolHandler()->urls_requested(), + ElementsAre("http://www.example.com/", "http://www.example.com/1")); + const DOMNode* value = + NextNode(dom_snapshot, FindTag(dom_snapshot, "TITLE")); + EXPECT_THAT(value, NodeValue("Hello, World 1")); + EXPECT_THAT(confirmed_frame_redirects_[main_frame_], + ElementsAre(RedirectReason( + FrameScheduledNavigationReason::META_TAG_REFRESH))); + EXPECT_THAT(frames_[main_frame_].size(), Eq(2u)); + } +}; +HEADLESS_RENDER_BROWSERTEST(ClientRedirectChain_NoJs); + +class ServerRedirectChain : public HeadlessRenderTest { + private: + GURL GetPageUrl(HeadlessDevToolsClient* client) override { + GetProtocolHandler()->InsertResponse( + "http://www.example.com/", + {"(HTTP/1.1 302 Moved\r\nLocation: http://www.example.com/1\r\n\r\n"}); + GetProtocolHandler()->InsertResponse( + "http://www.example.com/1", + {"(HTTP/1.1 302 Moved\r\nLocation: http://www.example.com/2\r\n\r\n"}); + GetProtocolHandler()->InsertResponse( + "http://www.example.com/2", + {"(HTTP/1.1 302 Moved\r\nLocation: http://www.example.com/3\r\n\r\n"}); + GetProtocolHandler()->InsertResponse( + "http://www.example.com/3", + {"(HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<p>Pass</p>"}); + return GURL("http://www.example.com/"); + } + + void VerifyDom(GetSnapshotResult* dom_snapshot) override { + EXPECT_THAT( + GetProtocolHandler()->urls_requested(), + ElementsAre("http://www.example.com/", "http://www.example.com/1", + "http://www.example.com/2", "http://www.example.com/3")); + const DOMNode* value = NextNode(dom_snapshot, FindTag(dom_snapshot, "P")); + EXPECT_THAT(value, NodeValue("Pass")); +#ifndef DISABLE_HTTP_REDIRECTS_CHECKS + EXPECT_THAT( + confirmed_frame_redirects_[main_frame_], + ElementsAre( + RedirectReason(FrameScheduledNavigationReason::HTTP_HEADER_REFRESH), + RedirectReason(FrameScheduledNavigationReason::HTTP_HEADER_REFRESH), + RedirectReason( + FrameScheduledNavigationReason::HTTP_HEADER_REFRESH))); + EXPECT_THAT(frames_[main_frame_].size(), Eq(4u)); +#endif // #ifndef DISABLE_HTTP_REDIRECTS_CHECKS + } +}; +HEADLESS_RENDER_BROWSERTEST(ServerRedirectChain); + +class ServerRedirectToFailure : public HeadlessRenderTest { + private: + GURL GetPageUrl(HeadlessDevToolsClient* client) override { + GetProtocolHandler()->InsertResponse( + "http://www.example.com/", + {"(HTTP/1.1 302 Moved\r\nLocation: http://www.example.com/1\r\n\r\n"}); + GetProtocolHandler()->InsertResponse( + "http://www.example.com/1", {"(HTTP/1.1 301 Moved\r\nLocation: " + "http://www.example.com/FAIL\r\n\r\n"}); + return GURL("http://www.example.com/"); + } + + void VerifyDom(GetSnapshotResult* dom_snapshot) override { + EXPECT_THAT( + GetProtocolHandler()->urls_requested(), + ElementsAre("http://www.example.com/", "http://www.example.com/1", + "http://www.example.com/FAIL")); + } +}; +HEADLESS_RENDER_BROWSERTEST(ServerRedirectToFailure); + +class ServerRedirectRelativeChain : public HeadlessRenderTest { + private: + GURL GetPageUrl(HeadlessDevToolsClient* client) override { + GetProtocolHandler()->InsertResponse( + "http://www.example.com/", + {"(HTTP/1.1 302 Moved\r\nLocation: http://www.mysite.com/1\r\n\r\n"}); + GetProtocolHandler()->InsertResponse( + "http://www.mysite.com/1", + {"(HTTP/1.1 301 Moved\r\nLocation: /2\r\n\r\n"}); + GetProtocolHandler()->InsertResponse( + "http://www.mysite.com/2", + {"(HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<p>Pass</p>"}); + return GURL("http://www.example.com/"); + } + + void VerifyDom(GetSnapshotResult* dom_snapshot) override { + EXPECT_THAT( + GetProtocolHandler()->urls_requested(), + ElementsAre("http://www.example.com/", "http://www.mysite.com/1", + "http://www.mysite.com/2")); + const DOMNode* value = NextNode(dom_snapshot, FindTag(dom_snapshot, "P")); + EXPECT_THAT(value, NodeValue("Pass")); + } +}; +HEADLESS_RENDER_BROWSERTEST(ServerRedirectRelativeChain); + +class MixedRedirectChain : public HeadlessRenderTest { + private: + GURL GetPageUrl(HeadlessDevToolsClient* client) override { + GetProtocolHandler()->InsertResponse("http://www.example.com/", + {R"|( + <html> + <head> + <meta http-equiv="refresh" content="0; url=http://www.example.com/1"/> + <title>Hello, World 0</title> + </head> + <body>http://www.example.com/</body> + </html> + )|", + TEXT_HTML}); + GetProtocolHandler()->InsertResponse("http://www.example.com/1", + {R"|( + <html> + <head> + <title>Hello, World 1</title> + <script> + document.location='http://www.example.com/2'; + </script> + </head> + <body>http://www.example.com/1</body> + </html> + )|", + TEXT_HTML}); + GetProtocolHandler()->InsertResponse( + "http://www.example.com/2", + {"(HTTP/1.1 302 Moved\r\nLocation: 3\r\n\r\n"}); + GetProtocolHandler()->InsertResponse( + "http://www.example.com/3", + {"(HTTP/1.1 301 Moved\r\nLocation: http://www.example.com/4\r\n\r\n"}); + GetProtocolHandler()->InsertResponse("http://www.example.com/4", + {"<p>Pass</p>", TEXT_HTML}); + return GURL("http://www.example.com/"); + } + + void VerifyDom(GetSnapshotResult* dom_snapshot) override { + EXPECT_THAT( + GetProtocolHandler()->urls_requested(), + ElementsAre("http://www.example.com/", "http://www.example.com/1", + "http://www.example.com/2", "http://www.example.com/3", + "http://www.example.com/4")); + const DOMNode* value = NextNode(dom_snapshot, FindTag(dom_snapshot, "P")); + EXPECT_THAT(value, NodeValue("Pass")); + } +}; +HEADLESS_RENDER_BROWSERTEST(MixedRedirectChain); + +class FramesRedirectChain : public HeadlessRenderTest { + private: + GURL GetPageUrl(HeadlessDevToolsClient* client) override { + GetProtocolHandler()->InsertResponse( + "http://www.example.com/", + {"HTTP/1.1 302 Moved\r\nLocation: http://www.example.com/1\r\n\r\n"}); + GetProtocolHandler()->InsertResponse("http://www.example.com/1", + {R"|( +<html> + <frameset> + <frame src="http://www.example.com/frameA/"> + <frame src="http://www.example.com/frameB/"> + </frameset> +</html> +)|", + TEXT_HTML}); + + // Frame A + GetProtocolHandler()->InsertResponse("http://www.example.com/frameA/", + {R"|( +<html> + <head> + <script>document.location='http://www.example.com/frameA/1'</script> + </head> + <body>HELLO WORLD 1</body> +</html> +)|", + TEXT_HTML}); + GetProtocolHandler()->InsertResponse( + "http://www.example.com/frameA/1", + {"HTTP/1.1 301 Moved\r\nLocation: /frameA/2\r\n\r\n"}); + GetProtocolHandler()->InsertResponse("http://www.example.com/frameA/2", + {"<p>FRAME A</p>", TEXT_HTML}); + + // Frame B + GetProtocolHandler()->InsertResponse("http://www.example.com/frameB/", + {R"|( +<html> + <head><title>HELLO WORLD 2</title></head> + <body> + <iframe src="http://www.example.com/iframe/"></iframe> + </body> +</html> +)|", + TEXT_HTML}); + GetProtocolHandler()->InsertResponse("http://www.example.com/iframe/", + {R"|( +<html> + <head> + <script>document.location='http://www.example.com/iframe/1'</script> + </head> + <body>HELLO WORLD 1</body> +</html> +)|", + TEXT_HTML}); + GetProtocolHandler()->InsertResponse( + "http://www.example.com/iframe/1", + {"HTTP/1.1 302 Moved\r\nLocation: /iframe/2\r\n\r\n"}); + GetProtocolHandler()->InsertResponse( + "http://www.example.com/iframe/2", + {"HTTP/1.1 301 Moved\r\nLocation: 3\r\n\r\n"}); + GetProtocolHandler()->InsertResponse("http://www.example.com/iframe/3", + {"<p>IFRAME B</p>", TEXT_HTML}); + return GURL("http://www.example.com/"); + } + + void VerifyDom(GetSnapshotResult* dom_snapshot) override { + EXPECT_THAT( + GetProtocolHandler()->urls_requested(), + UnorderedElementsAre( + "http://www.example.com/", "http://www.example.com/1", + "http://www.example.com/frameA/", "http://www.example.com/frameA/1", + "http://www.example.com/frameA/2", "http://www.example.com/frameB/", + "http://www.example.com/iframe/", "http://www.example.com/iframe/1", + "http://www.example.com/iframe/2", + "http://www.example.com/iframe/3")); + auto dom = FindTags(dom_snapshot, "P"); + EXPECT_THAT(dom, ElementsAre(NodeName("P"), NodeName("P"))); + EXPECT_THAT(NextNode(dom_snapshot, dom[0]), NodeValue("FRAME A")); + EXPECT_THAT(NextNode(dom_snapshot, dom[1]), NodeValue("IFRAME B")); + + const page::Frame* main_frame = nullptr; + const page::Frame* a_frame = nullptr; + const page::Frame* b_frame = nullptr; + const page::Frame* i_frame = nullptr; + EXPECT_THAT(frames_.size(), Eq(4u)); + for (const auto& it : frames_) { + if (it.second.back()->GetUrl() == "http://www.example.com/1") + main_frame = it.second.back().get(); + else if (it.second.back()->GetUrl() == "http://www.example.com/frameA/2") + a_frame = it.second.back().get(); + else if (it.second.back()->GetUrl() == "http://www.example.com/frameB/") + b_frame = it.second.back().get(); + else if (it.second.back()->GetUrl() == "http://www.example.com/iframe/3") + i_frame = it.second.back().get(); + else + ADD_FAILURE() << "Unexpected frame URL: " << it.second.back()->GetUrl(); + } + +#ifndef DISABLE_HTTP_REDIRECTS_CHECKS + EXPECT_THAT(frames_[main_frame->GetId()].size(), Eq(2u)); + EXPECT_THAT(frames_[a_frame->GetId()].size(), Eq(3u)); + EXPECT_THAT(frames_[b_frame->GetId()].size(), Eq(1u)); + EXPECT_THAT(frames_[i_frame->GetId()].size(), Eq(4u)); + EXPECT_THAT(confirmed_frame_redirects_[main_frame->GetId()], + ElementsAre(RedirectReason( + FrameScheduledNavigationReason::HTTP_HEADER_REFRESH))); + EXPECT_THAT( + confirmed_frame_redirects_[a_frame->GetId()], + ElementsAre( + RedirectReason(FrameScheduledNavigationReason::SCRIPT_INITIATED), + RedirectReason( + FrameScheduledNavigationReason::HTTP_HEADER_REFRESH))); + EXPECT_THAT( + confirmed_frame_redirects_[i_frame->GetId()], + ElementsAre( + RedirectReason(FrameScheduledNavigationReason::SCRIPT_INITIATED), + RedirectReason(FrameScheduledNavigationReason::HTTP_HEADER_REFRESH), + RedirectReason( + FrameScheduledNavigationReason::HTTP_HEADER_REFRESH))); +#endif // #ifndef DISABLE_HTTP_REDIRECTS_CHECKS + } +}; +HEADLESS_RENDER_BROWSERTEST(FramesRedirectChain); + +class DoubleRedirect : public HeadlessRenderTest { + private: + GURL GetPageUrl(HeadlessDevToolsClient* client) override { + GetProtocolHandler()->InsertResponse("http://www.example.com/", + {R"|( +<html> + <head> + <title>Hello, World 1</title> + <script> + document.location='http://www.example.com/1'; + document.location='http://www.example.com/2'; + </script> + </head> + <body>http://www.example.com/1</body> +</html> +)|", + TEXT_HTML}); + GetProtocolHandler()->InsertResponse("http://www.example.com/2", + {"<p>Pass</p>", TEXT_HTML}); + return GURL("http://www.example.com/"); + } + + void VerifyDom(GetSnapshotResult* dom_snapshot) override { + EXPECT_THAT( + GetProtocolHandler()->urls_requested(), + ElementsAre("http://www.example.com/", "http://www.example.com/2")); + EXPECT_THAT(NextNode(dom_snapshot, FindTag(dom_snapshot, "P")), + NodeValue("Pass")); + EXPECT_THAT(confirmed_frame_redirects_[main_frame_], + ElementsAre(RedirectReason( + FrameScheduledNavigationReason::SCRIPT_INITIATED))); + EXPECT_THAT(frames_[main_frame_].size(), Eq(2u)); + } +}; +HEADLESS_RENDER_BROWSERTEST(DoubleRedirect); + +class RedirectAfterCompletion : public HeadlessRenderTest { + private: + GURL GetPageUrl(HeadlessDevToolsClient* client) override { + GetProtocolHandler()->InsertResponse("http://www.example.com/", + {R"|( +<html> + <head> + <meta http-equiv='refresh' content='120; url=http://www.example.com/1'> + </head> + <body><p>Pass</p></body> +</html> +)|", + TEXT_HTML}); + GetProtocolHandler()->InsertResponse("http://www.example.com/1", + {"<p>Fail</p>", TEXT_HTML}); + return GURL("http://www.example.com/"); + } + + void VerifyDom(GetSnapshotResult* dom_snapshot) override { + EXPECT_THAT(GetProtocolHandler()->urls_requested(), + ElementsAre("http://www.example.com/")); + EXPECT_THAT(NextNode(dom_snapshot, FindTag(dom_snapshot, "P")), + NodeValue("Pass")); + EXPECT_THAT(confirmed_frame_redirects_[main_frame_], ElementsAre()); + EXPECT_THAT(frames_[main_frame_].size(), Eq(1u)); + } +}; +HEADLESS_RENDER_BROWSERTEST(RedirectAfterCompletion); + } // namespace headless
diff --git a/headless/test/headless_render_test.cc b/headless/test/headless_render_test.cc index 80eae96..873f083 100644 --- a/headless/test/headless_render_test.cc +++ b/headless/test/headless_render_test.cc
@@ -23,7 +23,7 @@ HeadlessRenderTest::HeadlessRenderTest() : weak_ptr_factory_(this) {} -HeadlessRenderTest::~HeadlessRenderTest() {} +HeadlessRenderTest::~HeadlessRenderTest() = default; void HeadlessRenderTest::PostRunAsynchronousTest() { // Make sure the test did complete. @@ -109,16 +109,43 @@ } void HeadlessRenderTest::OnFrameStartedLoading( - const page::FrameStartedLoadingParams&) { + const page::FrameStartedLoadingParams& params) { CHECK_NE(INIT, state_); if (state_ == STARTING) { state_ = LOADING; + main_frame_ = params.GetFrameId(); virtual_time_controller_->GrantVirtualTimeBudget( emulation::VirtualTimePolicy::PAUSE_IF_NETWORK_FETCHES_PENDING, base::TimeDelta::FromMilliseconds(5000), base::Closure(), base::Bind(&HeadlessRenderTest::HandleVirtualTimeExhausted, weak_ptr_factory_.GetWeakPtr())); } + + auto it = unconfirmed_frame_redirects_.find(params.GetFrameId()); + if (it != unconfirmed_frame_redirects_.end()) { + confirmed_frame_redirects_[params.GetFrameId()].push_back(it->second); + unconfirmed_frame_redirects_.erase(it); + } +} + +void HeadlessRenderTest::OnFrameScheduledNavigation( + const page::FrameScheduledNavigationParams& params) { + CHECK(unconfirmed_frame_redirects_.find(params.GetFrameId()) == + unconfirmed_frame_redirects_.end()); + unconfirmed_frame_redirects_[params.GetFrameId()] = + Redirect(params.GetUrl(), params.GetReason()); +} + +void HeadlessRenderTest::OnFrameClearedScheduledNavigation( + const page::FrameClearedScheduledNavigationParams& params) { + auto it = unconfirmed_frame_redirects_.find(params.GetFrameId()); + if (it != unconfirmed_frame_redirects_.end()) + unconfirmed_frame_redirects_.erase(it); +} + +void HeadlessRenderTest::OnFrameNavigated( + const page::FrameNavigatedParams& params) { + frames_[params.GetFrame()->GetId()].push_back(params.GetFrame()->Clone()); } void HeadlessRenderTest::OnRequest(const GURL& url,
diff --git a/headless/test/headless_render_test.h b/headless/test/headless_render_test.h index 2f75048..3c42ec1 100644 --- a/headless/test/headless_render_test.h +++ b/headless/test/headless_render_test.h
@@ -34,6 +34,8 @@ public page::ExperimentalObserver, public TestInMemoryProtocolHandler::RequestDeferrer { public: + typedef std::pair<std::string, page::FrameScheduledNavigationReason> Redirect; + void RunDevTooledTest() override; protected: @@ -92,10 +94,20 @@ void OnLoadEventFired(const page::LoadEventFiredParams& params) override; void OnFrameStartedLoading( const page::FrameStartedLoadingParams& params) override; + void OnFrameScheduledNavigation( + const page::FrameScheduledNavigationParams& params) override; + void OnFrameClearedScheduledNavigation( + const page::FrameClearedScheduledNavigationParams& params) override; + void OnFrameNavigated(const page::FrameNavigatedParams& params) override; // TestInMemoryProtocolHandler::RequestDeferrer void OnRequest(const GURL& url, base::Closure complete_request) override; + std::map<std::string, std::vector<Redirect>> confirmed_frame_redirects_; + std::map<std::string, Redirect> unconfirmed_frame_redirects_; + std::map<std::string, std::vector<std::unique_ptr<page::Frame>>> frames_; + std::string main_frame_; + private: void HandleVirtualTimeExhausted(); void OnGetDomSnapshotDone(
diff --git a/headless/test/headless_test_launcher.cc b/headless/test/headless_test_launcher.cc index 17b229a..1ed1896 100644 --- a/headless/test/headless_test_launcher.cc +++ b/headless/test/headless_test_launcher.cc
@@ -32,8 +32,8 @@ class HeadlessTestLauncherDelegate : public content::TestLauncherDelegate { public: - HeadlessTestLauncherDelegate() {} - ~HeadlessTestLauncherDelegate() override {} + HeadlessTestLauncherDelegate() = default; + ~HeadlessTestLauncherDelegate() override = default; // content::TestLauncherDelegate implementation: int RunTestSuite(int argc, char** argv) override {
diff --git a/headless/test/tab_socket_test.cc b/headless/test/tab_socket_test.cc index e994b59..9cca9fd 100644 --- a/headless/test/tab_socket_test.cc +++ b/headless/test/tab_socket_test.cc
@@ -9,8 +9,8 @@ namespace headless { -TabSocketTest::TabSocketTest() {} -TabSocketTest::~TabSocketTest() {} +TabSocketTest::TabSocketTest() = default; +TabSocketTest::~TabSocketTest() = default; void TabSocketTest::SetUp() { options()->mojo_service_names.insert("headless::TabSocket");
diff --git a/headless/test/test_url_request_job.cc b/headless/test/test_url_request_job.cc index bdde8962..46401b1 100644 --- a/headless/test/test_url_request_job.cc +++ b/headless/test/test_url_request_job.cc
@@ -16,7 +16,7 @@ body_(new net::StringIOBuffer(body)), src_buf_(new net::DrainableIOBuffer(body_.get(), body_->size())) {} -TestURLRequestJob::~TestURLRequestJob() {} +TestURLRequestJob::~TestURLRequestJob() = default; void TestURLRequestJob::Start() { NotifyHeadersComplete();
diff --git a/ios/chrome/app/main_controller.mm b/ios/chrome/app/main_controller.mm index fe31ff4e..dff1c58 100644 --- a/ios/chrome/app/main_controller.mm +++ b/ios/chrome/app/main_controller.mm
@@ -32,6 +32,7 @@ #include "components/feature_engagement/public/tracker.h" #include "components/metrics/metrics_pref_names.h" #include "components/metrics/metrics_service.h" +#include "components/ntp_snippets/content_suggestions_service.h" #include "components/payments/core/features.h" #include "components/prefs/pref_change_registrar.h" #include "components/signin/core/browser/signin_manager.h" @@ -83,6 +84,7 @@ #include "ios/chrome/browser/metrics/first_user_action_recorder.h" #import "ios/chrome/browser/metrics/previous_session_info.h" #import "ios/chrome/browser/net/cookie_util.h" +#include "ios/chrome/browser/ntp_snippets/ios_chrome_content_suggestions_service_factory.h" #include "ios/chrome/browser/payments/ios_payment_instrument_launcher.h" #include "ios/chrome/browser/payments/ios_payment_instrument_launcher_factory.h" #import "ios/chrome/browser/payments/payment_request_constants.h" @@ -701,6 +703,12 @@ [MDCTypography setFontLoader:[MDFRobotoFontLoader sharedInstance]]; + if ([PreviousSessionInfo sharedInstance].isFirstSessionAfterLanguageChange) { + IOSChromeContentSuggestionsServiceFactory::GetForBrowserState( + chromeBrowserState) + ->ClearAllCachedSuggestions(); + } + [self createInitialUI:(startInIncognito ? ApplicationMode::INCOGNITO : ApplicationMode::NORMAL)];
diff --git a/ios/chrome/browser/autofill/autofill_controller_js_unittest.mm b/ios/chrome/browser/autofill/autofill_controller_js_unittest.mm index 704d5d1..ba99bb2 100644 --- a/ios/chrome/browser/autofill/autofill_controller_js_unittest.mm +++ b/ios/chrome/browser/autofill/autofill_controller_js_unittest.mm
@@ -1441,7 +1441,7 @@ NSString* actual = ExecuteJavaScriptWithFormat( @"var forms = __gCrWeb.autofill.extractNewForms(%" PRIuS "); %@", - autofill::kRequiredFieldsForPredictionRoutines, + autofill::MinRequiredFieldsForHeuristics(), [verifying_javascripts componentsJoinedByString:@"&&"]); EXPECT_NSEQ(@YES, actual) << base::SysNSStringToUTF8([NSString @@ -1450,7 +1450,7 @@ ExecuteJavaScriptWithFormat( @"var forms = __gCrWeb.autofill.extractNewForms(" "%" PRIuS "); __gCrWeb.stringify(forms)", - autofill::kRequiredFieldsForPredictionRoutines), + autofill::MinRequiredFieldsForHeuristics()), verifying_javascripts]); } @@ -1625,9 +1625,9 @@ ] }; - NSString* result = ExecuteJavaScriptWithFormat( - @"__gCrWeb.autofill.extractForms(%zu)", - autofill::kRequiredFieldsForPredictionRoutines); + NSString* result = + ExecuteJavaScriptWithFormat(@"__gCrWeb.autofill.extractForms(%zu)", + autofill::MinRequiredFieldsForHeuristics()); NSDictionary* resultDict = [NSJSONSerialization JSONObjectWithData:[result dataUsingEncoding:NSUTF8StringEncoding] options:0 @@ -1643,7 +1643,7 @@ result = ExecuteJavaScriptWithFormat( @"Object.prototype.toJSON=function(){return 'abcde';};" "__gCrWeb.autofill.extractForms(%zu)", - autofill::kRequiredFieldsForPredictionRoutines); + autofill::MinRequiredFieldsForHeuristics()); resultDict = [NSJSONSerialization JSONObjectWithData:[result dataUsingEncoding:NSUTF8StringEncoding] options:0 @@ -1659,7 +1659,7 @@ result = ExecuteJavaScriptWithFormat( @"Array.prototype.toJSON=function(){return 'abcde';};" "__gCrWeb.autofill.extractForms(%zu)", - autofill::kRequiredFieldsForPredictionRoutines); + autofill::MinRequiredFieldsForHeuristics()); resultDict = [NSJSONSerialization JSONObjectWithData:[result dataUsingEncoding:NSUTF8StringEncoding] options:0 @@ -1740,7 +1740,7 @@ NSString* result = ExecuteJavaScriptWithFormat(@"__gCrWeb.autofill.extractForms(%zu)", - autofill::kRequiredFieldsForUpload); + autofill::MinRequiredFieldsForHeuristics()); NSDictionary* resultDict = [NSJSONSerialization JSONObjectWithData:[result dataUsingEncoding:NSUTF8StringEncoding] options:0
diff --git a/ios/chrome/browser/autofill/form_structure_browsertest.mm b/ios/chrome/browser/autofill/form_structure_browsertest.mm index f3c18a3..f54dc3f 100644 --- a/ios/chrome/browser/autofill/form_structure_browsertest.mm +++ b/ios/chrome/browser/autofill/form_structure_browsertest.mm
@@ -13,8 +13,10 @@ #include "base/strings/utf_string_conversions.h" #include "base/task_scheduler/task_scheduler.h" #import "base/test/ios/wait_util.h" +#include "base/test/scoped_feature_list.h" #include "components/autofill/core/browser/autofill_manager.h" #include "components/autofill/core/browser/data_driven_test.h" +#include "components/autofill/core/common/autofill_features.h" #import "components/autofill/ios/browser/autofill_agent.h" #include "components/autofill/ios/browser/autofill_driver_ios.h" #import "ios/chrome/browser/autofill/autofill_controller.h" @@ -42,31 +44,32 @@ return dir; } -base::FilePath GetIOSOutputDirectory( - const base::FilePath::StringType& test_name) { +base::FilePath GetIOSInputDirectory() { base::FilePath dir; CHECK(PathService::Get(base::DIR_SOURCE_ROOT, &dir)); - dir = dir.AppendASCII("components") - .AppendASCII("test") - .AppendASCII("data") - .AppendASCII("autofill") - .AppendASCII("heuristics") - .AppendASCII("output"); + return dir.AppendASCII("components") + .AppendASCII("test") + .AppendASCII("data") + .AppendASCII("autofill") + .Append(kTestName) + .AppendASCII("input"); +} - return dir; +base::FilePath GetIOSOutputDirectory() { + base::FilePath dir; + CHECK(PathService::Get(base::DIR_SOURCE_ROOT, &dir)); + + return dir.AppendASCII("components") + .AppendASCII("test") + .AppendASCII("data") + .AppendASCII("autofill") + .Append(kTestName) + .AppendASCII("output"); } const std::vector<base::FilePath> GetTestFiles() { - base::FilePath dir; - CHECK(PathService::Get(base::DIR_SOURCE_ROOT, &dir)); - dir = dir.AppendASCII("components") - .AppendASCII("test") - .AppendASCII("data") - .AppendASCII("autofill") - .AppendASCII("heuristics") - .AppendASCII("input"); - + base::FilePath dir(GetIOSInputDirectory()); base::FileEnumerator input_files(dir, false, base::FileEnumerator::FILES); std::vector<base::FilePath> files; for (base::FilePath input_file = input_files.Next(); !input_file.empty(); @@ -79,6 +82,13 @@ return files; } +const std::set<std::string>& GetFailingTestNames() { + static std::set<std::string>* failing_test_names = new std::set<std::string>{ + "067_register_rei.com.html", "074_register_threadless.com.html", + }; + return *failing_test_names; +} + } // namespace // Test fixture for verifying Autofill heuristics. Each input is an HTML @@ -108,6 +118,7 @@ AutofillController* autofillController_; private: + base::test::ScopedFeatureList feature_list_; DISALLOW_COPY_AND_ASSIGN(FormStructureBrowserTest); }; @@ -116,6 +127,8 @@ void FormStructureBrowserTest::SetUp() { ChromeWebTest::SetUp(); + feature_list_.InitAndDisableFeature( + autofill::features::kAutofillEnforceMinRequiredFieldsForUpload); InfoBarManagerImpl::CreateForWebState(web_state()); AutofillAgent* autofillAgent = [[AutofillAgent alloc] @@ -187,7 +200,10 @@ } TEST_P(FormStructureBrowserTest, DataDrivenHeuristics) { - RunOneDataDrivenTest(GetParam(), GetIOSOutputDirectory(kTestName)); + bool is_expected_to_pass = + !base::ContainsKey(GetFailingTestNames(), GetParam().BaseName().value()); + RunOneDataDrivenTest(GetParam(), GetIOSOutputDirectory(), + is_expected_to_pass); } INSTANTIATE_TEST_CASE_P(AllForms,
diff --git a/ios/chrome/browser/autofill/js_autofill_manager_unittest.mm b/ios/chrome/browser/autofill/js_autofill_manager_unittest.mm index 685c8a5..ea047b9 100644 --- a/ios/chrome/browser/autofill/js_autofill_manager_unittest.mm +++ b/ios/chrome/browser/autofill/js_autofill_manager_unittest.mm
@@ -98,7 +98,7 @@ __block BOOL block_was_called = NO; __block NSString* result; [manager_ fetchFormsWithMinimumRequiredFieldsCount: - autofill::kRequiredFieldsForPredictionRoutines + autofill::MinRequiredFieldsForHeuristics() completionHandler:^(NSString* actualResult) { block_was_called = YES; result = [actualResult copy];
diff --git a/ios/chrome/browser/metrics/ios_chrome_stability_metrics_provider.h b/ios/chrome/browser/metrics/ios_chrome_stability_metrics_provider.h index 44a445a9..d3dfd6bbe 100644 --- a/ios/chrome/browser/metrics/ios_chrome_stability_metrics_provider.h +++ b/ios/chrome/browser/metrics/ios_chrome_stability_metrics_provider.h
@@ -22,8 +22,10 @@ public web::GlobalWebStateObserver { public: // Buckets for the histogram that counts events relevant for counting page - // loads. The *_NAVIGATION events are mutually exclusive. - enum class StabilityMetricEventType { + // loads. These events are mutually exclusive. + // These values are persisted to logs. Entries should not be renumbered and + // numeric values should never be reused. + enum class PageLoadCountNavigationType { // A chrome:// URL navigation. This is not counted for page load. CHROME_URL_NAVIGATION = 0, // A same-document web (i.e. not chrome:// URL) navigation. This is not @@ -32,10 +34,10 @@ // A navigation that is not SAME_DOCUMENT_WEB or CHROME_URL. It is counted // as a page load. PAGE_LOAD_NAVIGATION = 2, - // A loading start event. This is the legacy page load count. - // TODO(crbug.com/786547): Deprecate this counter after page load count cuts - // over to be based on DidStartNavigation. - LOADING_STARTED = 3, + + // OBSOLETE VALUES. DO NOT REUSE. + OBSOLETE_LOADING_STARTED = 3, + COUNT }; @@ -59,7 +61,8 @@ // Records a renderer process crash. void LogRendererCrash(); - static const char kPageLoadCountMigrationEventKey[]; + static const char kPageLoadCountLoadingStartedMetric[]; + static const char kPageLoadCountMetric[]; private: metrics::StabilityMetricsHelper helper_;
diff --git a/ios/chrome/browser/metrics/ios_chrome_stability_metrics_provider.mm b/ios/chrome/browser/metrics/ios_chrome_stability_metrics_provider.mm index cd8e33b5..cf4fb11d 100644 --- a/ios/chrome/browser/metrics/ios_chrome_stability_metrics_provider.mm +++ b/ios/chrome/browser/metrics/ios_chrome_stability_metrics_provider.mm
@@ -13,9 +13,13 @@ #error "This file requires ARC support." #endif +// Name of the UMA enum histogram that counts DidStartNavigation events by type. +const char IOSChromeStabilityMetricsProvider::kPageLoadCountMetric[] = + "IOS.PageLoadCount.Counts"; +// Name of the UMA enum history that counts DidStartLoading events. const char - IOSChromeStabilityMetricsProvider::kPageLoadCountMigrationEventKey[] = - "IOS.PageLoadCountMigration.Counts"; + IOSChromeStabilityMetricsProvider::kPageLoadCountLoadingStartedMetric[] = + "IOS.PageLoadCount.LoadingStarted"; IOSChromeStabilityMetricsProvider::IOSChromeStabilityMetricsProvider( PrefService* local_state) @@ -58,9 +62,7 @@ if (!recording_enabled_) return; - UMA_HISTOGRAM_ENUMERATION(kPageLoadCountMigrationEventKey, - StabilityMetricEventType::LOADING_STARTED, - StabilityMetricEventType::COUNT); + UMA_HISTOGRAM_BOOLEAN(kPageLoadCountLoadingStartedMetric, true); helper_.LogLoadStarted(); } @@ -70,17 +72,17 @@ if (!recording_enabled_) return; - StabilityMetricEventType type = - StabilityMetricEventType::PAGE_LOAD_NAVIGATION; + PageLoadCountNavigationType type = + PageLoadCountNavigationType::PAGE_LOAD_NAVIGATION; if (navigation_context->GetUrl().SchemeIs(kChromeUIScheme)) { - type = StabilityMetricEventType::CHROME_URL_NAVIGATION; + type = PageLoadCountNavigationType::CHROME_URL_NAVIGATION; } else if (navigation_context->IsSameDocument()) { - type = StabilityMetricEventType::SAME_DOCUMENT_WEB_NAVIGATION; + type = PageLoadCountNavigationType::SAME_DOCUMENT_WEB_NAVIGATION; } else { // TODO(crbug.com/786547): Move helper_.LogLoadStarted() here. } - UMA_HISTOGRAM_ENUMERATION(kPageLoadCountMigrationEventKey, type, - StabilityMetricEventType::COUNT); + UMA_HISTOGRAM_ENUMERATION(kPageLoadCountMetric, type, + PageLoadCountNavigationType::COUNT); } void IOSChromeStabilityMetricsProvider::RenderProcessGone(
diff --git a/ios/chrome/browser/metrics/ios_chrome_stability_metrics_provider_unittest.mm b/ios/chrome/browser/metrics/ios_chrome_stability_metrics_provider_unittest.mm index d27528c0..bbff643 100644 --- a/ios/chrome/browser/metrics/ios_chrome_stability_metrics_provider_unittest.mm +++ b/ios/chrome/browser/metrics/ios_chrome_stability_metrics_provider_unittest.mm
@@ -45,8 +45,8 @@ EXPECT_EQ(0, system_profile.stability().page_load_count()); EXPECT_TRUE(histogram_tester_ - .GetTotalCountsForPrefix(IOSChromeStabilityMetricsProvider:: - kPageLoadCountMigrationEventKey) + .GetTotalCountsForPrefix( + IOSChromeStabilityMetricsProvider::kPageLoadCountMetric) .empty()); // A load should increment metrics if recording is enabled. @@ -57,12 +57,8 @@ provider.ProvideStabilityMetrics(&system_profile); EXPECT_EQ(1, system_profile.stability().page_load_count()); - histogram_tester_.ExpectUniqueSample( - IOSChromeStabilityMetricsProvider::kPageLoadCountMigrationEventKey, - static_cast<base::HistogramBase::Sample>( - IOSChromeStabilityMetricsProvider::StabilityMetricEventType:: - LOADING_STARTED), - 1); + histogram_tester_.ExpectTotalCount( + IOSChromeStabilityMetricsProvider::kPageLoadCountLoadingStartedMetric, 1); } TEST_F(IOSChromeStabilityMetricsProviderTest, @@ -75,9 +71,9 @@ provider.WebStateDidStartNavigation(kNullWebState, &context); histogram_tester_.ExpectUniqueSample( - IOSChromeStabilityMetricsProvider::kPageLoadCountMigrationEventKey, + IOSChromeStabilityMetricsProvider::kPageLoadCountMetric, static_cast<base::HistogramBase::Sample>( - IOSChromeStabilityMetricsProvider::StabilityMetricEventType:: + IOSChromeStabilityMetricsProvider::PageLoadCountNavigationType:: SAME_DOCUMENT_WEB_NAVIGATION), 1); @@ -97,9 +93,9 @@ provider.WebStateDidStartNavigation(kNullWebState, &context); histogram_tester_.ExpectUniqueSample( - IOSChromeStabilityMetricsProvider::kPageLoadCountMigrationEventKey, + IOSChromeStabilityMetricsProvider::kPageLoadCountMetric, static_cast<base::HistogramBase::Sample>( - IOSChromeStabilityMetricsProvider::StabilityMetricEventType:: + IOSChromeStabilityMetricsProvider::PageLoadCountNavigationType:: CHROME_URL_NAVIGATION), 1); @@ -119,9 +115,9 @@ provider.WebStateDidStartNavigation(kNullWebState, &context); histogram_tester_.ExpectUniqueSample( - IOSChromeStabilityMetricsProvider::kPageLoadCountMigrationEventKey, + IOSChromeStabilityMetricsProvider::kPageLoadCountMetric, static_cast<base::HistogramBase::Sample>( - IOSChromeStabilityMetricsProvider::StabilityMetricEventType:: + IOSChromeStabilityMetricsProvider::PageLoadCountNavigationType:: CHROME_URL_NAVIGATION), 1); @@ -137,9 +133,9 @@ provider.WebStateDidStartNavigation(kNullWebState, &context); histogram_tester_.ExpectUniqueSample( - IOSChromeStabilityMetricsProvider::kPageLoadCountMigrationEventKey, + IOSChromeStabilityMetricsProvider::kPageLoadCountMetric, static_cast<base::HistogramBase::Sample>( - IOSChromeStabilityMetricsProvider::StabilityMetricEventType:: + IOSChromeStabilityMetricsProvider::PageLoadCountNavigationType:: PAGE_LOAD_NAVIGATION), 1);
diff --git a/ios/chrome/browser/metrics/previous_session_info.h b/ios/chrome/browser/metrics/previous_session_info.h index c98fa13..1e8268c 100644 --- a/ios/chrome/browser/metrics/previous_session_info.h +++ b/ios/chrome/browser/metrics/previous_session_info.h
@@ -26,6 +26,10 @@ // Whether the app was updated between the previous and the current session. @property(nonatomic, assign, readonly) BOOL isFirstSessionAfterUpgrade; +// Whether the language has been changed between the previous and the current +// session. +@property(nonatomic, assign, readonly) BOOL isFirstSessionAfterLanguageChange; + // Singleton PreviousSessionInfo. During the lifetime of the app, the returned // object is the same, and describes the previous session, even after a new // session has started (by calling beginRecordingCurrentSession).
diff --git a/ios/chrome/browser/metrics/previous_session_info.mm b/ios/chrome/browser/metrics/previous_session_info.mm index 30c4c4f..da922ac 100644 --- a/ios/chrome/browser/metrics/previous_session_info.mm +++ b/ios/chrome/browser/metrics/previous_session_info.mm
@@ -19,6 +19,10 @@ // last session. NSString* const kLastRanVersion = @"LastRanVersion"; +// Key in the NSUserDefaults for a string value that stores the language of the +// last session. +NSString* const kLastRanLanguage = @"LastRanLanguage"; + } // namespace namespace previous_session_info_constants { @@ -34,6 +38,7 @@ // Redefined to be read-write. @property(nonatomic, assign) BOOL didSeeMemoryWarningShortlyBeforeTerminating; @property(nonatomic, assign) BOOL isFirstSessionAfterUpgrade; +@property(nonatomic, assign) BOOL isFirstSessionAfterLanguageChange; @end @@ -43,6 +48,8 @@ @synthesize didSeeMemoryWarningShortlyBeforeTerminating = _didSeeMemoryWarningShortlyBeforeTerminating; @synthesize isFirstSessionAfterUpgrade = _isFirstSessionAfterUpgrade; +@synthesize isFirstSessionAfterLanguageChange = + _isFirstSessionAfterLanguageChange; // Singleton PreviousSessionInfo. static PreviousSessionInfo* gSharedInstance = nil; @@ -61,6 +68,11 @@ base::SysUTF8ToNSString(version_info::GetVersionNumber()); gSharedInstance.isFirstSessionAfterUpgrade = ![lastRanVersion isEqualToString:currentVersion]; + + NSString* lastRanLanguage = [defaults stringForKey:kLastRanLanguage]; + NSString* currentLanguage = [[NSLocale preferredLanguages] objectAtIndex:0]; + gSharedInstance.isFirstSessionAfterLanguageChange = + ![lastRanLanguage isEqualToString:currentLanguage]; } return gSharedInstance; } @@ -81,6 +93,10 @@ base::SysUTF8ToNSString(version_info::GetVersionNumber()); [defaults setObject:currentVersion forKey:kLastRanVersion]; + // Set the new language. + NSString* currentLanguage = [[NSLocale preferredLanguages] objectAtIndex:0]; + [defaults setObject:currentLanguage forKey:kLastRanLanguage]; + // Clear the memory warning flag. [defaults removeObjectForKey:previous_session_info_constants::
diff --git a/ios/chrome/browser/metrics/previous_session_info_unittest.mm b/ios/chrome/browser/metrics/previous_session_info_unittest.mm index f991d63..2bdbf4fa 100644 --- a/ios/chrome/browser/metrics/previous_session_info_unittest.mm +++ b/ios/chrome/browser/metrics/previous_session_info_unittest.mm
@@ -25,6 +25,9 @@ // Key in the NSUserDefaults for a string value that stores the version of the // last session. NSString* const kLastRanVersion = @"LastRanVersion"; +// Key in the NSUserDefaults for a string value that stores the language of the +// last session. +NSString* const kLastRanLanguage = @"LastRanLanguage"; using PreviousSessionInfoTest = PlatformTest; @@ -33,6 +36,7 @@ NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults]; [defaults removeObjectForKey:kDidSeeMemoryWarningShortlyBeforeTerminating]; [defaults removeObjectForKey:kLastRanVersion]; + [defaults removeObjectForKey:kLastRanLanguage]; // Instantiate the PreviousSessionInfo sharedInstance. PreviousSessionInfo* sharedInstance = [PreviousSessionInfo sharedInstance]; @@ -40,6 +44,39 @@ // Checks the default values. EXPECT_FALSE([sharedInstance didSeeMemoryWarningShortlyBeforeTerminating]); EXPECT_TRUE([sharedInstance isFirstSessionAfterUpgrade]); + EXPECT_TRUE([sharedInstance isFirstSessionAfterLanguageChange]); +} + +TEST_F(PreviousSessionInfoTest, InitializationWithSameLanguage) { + [PreviousSessionInfo resetSharedInstanceForTesting]; + NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults]; + [defaults removeObjectForKey:kLastRanLanguage]; + + // Set the current language as the last ran language. + NSString* currentVersion = [[NSLocale preferredLanguages] objectAtIndex:0]; + [defaults setObject:currentVersion forKey:kLastRanVersion]; + + // Instantiate the PreviousSessionInfo sharedInstance. + PreviousSessionInfo* sharedInstance = [PreviousSessionInfo sharedInstance]; + + // Checks the values. + EXPECT_TRUE([sharedInstance isFirstSessionAfterLanguageChange]); +} + +TEST_F(PreviousSessionInfoTest, InitializationWithDifferentLanguage) { + [PreviousSessionInfo resetSharedInstanceForTesting]; + NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults]; + [defaults removeObjectForKey:kLastRanLanguage]; + + // Set the current language as the last ran language. + NSString* currentVersion = @"Fake Language"; + [defaults setObject:currentVersion forKey:kLastRanVersion]; + + // Instantiate the PreviousSessionInfo sharedInstance. + PreviousSessionInfo* sharedInstance = [PreviousSessionInfo sharedInstance]; + + // Checks the values. + EXPECT_TRUE([sharedInstance isFirstSessionAfterLanguageChange]); } TEST_F(PreviousSessionInfoTest, InitializationWithSameVersionNoMemoryWarning) {
diff --git a/ios/chrome/browser/payments/payment_request.mm b/ios/chrome/browser/payments/payment_request.mm index 0dfacd4..a34ccd8 100644 --- a/ios/chrome/browser/payments/payment_request.mm +++ b/ios/chrome/browser/payments/payment_request.mm
@@ -89,9 +89,10 @@ web_state_(web_state), personal_data_manager_(personal_data_manager), payment_request_ui_delegate_(payment_request_ui_delegate), + // TODO(crbug.com/788229): Use a factory for the AddressNormalizer. address_normalizer_( GetAddressInputSource( - personal_data_manager_->GetURLRequestContextGetter()), + GetApplicationContext()->GetSystemURLRequestContext()), GetAddressInputStorage(), GetApplicationContext()->GetApplicationLocale()), address_normalization_manager_( @@ -105,7 +106,7 @@ journey_logger_(IsIncognito(), GetLastCommittedURL(), GetUkmRecorder()), payment_instruments_ready_(false), ios_instrument_finder_( - personal_data_manager_->GetURLRequestContextGetter(), + GetApplicationContext()->GetSystemURLRequestContext(), payment_request_ui_delegate_) { PopulateAvailableShippingOptions(); PopulateProfileCache(); @@ -184,7 +185,7 @@ autofill::RegionDataLoader* PaymentRequest::GetRegionDataLoader() { return new autofill::RegionDataLoaderImpl( GetAddressInputSource( - personal_data_manager_->GetURLRequestContextGetter()) + GetApplicationContext()->GetSystemURLRequestContext()) .release(), GetAddressInputStorage().release(), GetApplicationLocale()); }
diff --git a/ios/chrome/browser/ui/authentication/signin_promo_view_mediator.h b/ios/chrome/browser/ui/authentication/signin_promo_view_mediator.h index 771e7c7..1511504 100644 --- a/ios/chrome/browser/ui/authentication/signin_promo_view_mediator.h +++ b/ios/chrome/browser/ui/authentication/signin_promo_view_mediator.h
@@ -95,6 +95,9 @@ // called. - (void)signinPromoViewRemoved; +// Returns YES if the sign-in promo view is |Invalid|, |Closed| or |Invisible|. +- (BOOL)isInvalidClosedOrNeverVisible; + @end #endif // IOS_CHROME_BROWSER_UI_AUTHENTICATION_SIGNIN_PROMO_VIEW_MEDIATOR_H_
diff --git a/ios/chrome/browser/ui/authentication/signin_promo_view_mediator.mm b/ios/chrome/browser/ui/authentication/signin_promo_view_mediator.mm index 74e08fdf..a4b97e9 100644 --- a/ios/chrome/browser/ui/authentication/signin_promo_view_mediator.mm +++ b/ios/chrome/browser/ui/authentication/signin_promo_view_mediator.mm
@@ -48,6 +48,32 @@ } } +void RecordSigninImpressionUserActionForAccessPoint( + signin_metrics::AccessPoint access_point) { + switch (access_point) { + case signin_metrics::AccessPoint::ACCESS_POINT_BOOKMARK_MANAGER: + base::RecordAction( + base::UserMetricsAction("Signin_Impression_FromBookmarkManager")); + break; + case signin_metrics::AccessPoint::ACCESS_POINT_RECENT_TABS: + base::RecordAction( + base::UserMetricsAction("Signin_Impression_FromRecentTabs")); + break; + case signin_metrics::AccessPoint::ACCESS_POINT_SETTINGS: + base::RecordAction( + base::UserMetricsAction("Signin_Impression_FromSettings")); + break; + case signin_metrics::AccessPoint::ACCESS_POINT_TAB_SWITCHER: + base::RecordAction( + base::UserMetricsAction("Signin_Impression_FromTabSwitcher")); + break; + default: + NOTREACHED() << "Unexpected value for access point " + << static_cast<int>(access_point); + break; + } +} + void RecordSigninImpressionWithAccountUserActionForAccessPoint( signin_metrics::AccessPoint access_point) { switch (access_point) { @@ -338,11 +364,6 @@ if (identities.count != 0) { [self selectIdentity:identities[0]]; } - if (_defaultIdentity) { - RecordSigninImpressionWithAccountUserActionForAccessPoint(accessPoint); - } else { - RecordSigninImpressionWithNoAccountUserActionForAccessPoint(accessPoint); - } _identityServiceObserver = base::MakeUnique<ChromeIdentityServiceObserverBridge>(self); _browserProviderObserver = @@ -428,6 +449,12 @@ if (_signinPromoViewState == ios::SigninPromoViewState::NeverVisible) _signinPromoViewState = ios::SigninPromoViewState::Unused; _isSigninPromoViewVisible = YES; + RecordSigninImpressionUserActionForAccessPoint(_accessPoint); + if (_defaultIdentity) { + RecordSigninImpressionWithAccountUserActionForAccessPoint(_accessPoint); + } else { + RecordSigninImpressionWithNoAccountUserActionForAccessPoint(_accessPoint); + } const char* displayedCountPreferenceKey = DisplayedCountPreferenceKey(_accessPoint); if (!displayedCountPreferenceKey)
diff --git a/ios/chrome/browser/ui/bookmarks/bookmark_collection_view.h b/ios/chrome/browser/ui/bookmarks/bookmark_collection_view.h index 1741c1c5..3182afc 100644 --- a/ios/chrome/browser/ui/bookmarks/bookmark_collection_view.h +++ b/ios/chrome/browser/ui/bookmarks/bookmark_collection_view.h
@@ -20,6 +20,8 @@ @class BookmarkCollectionView; class GURL; @protocol SigninPresenter; +@class SigninPromoViewConfigurator; +@class SigninPromoViewMediator; @protocol UrlLoader; namespace bookmarks { @@ -28,6 +30,10 @@ @protocol BookmarkCollectionViewDelegate<NSObject> +// Returns the SigninPromoViewMediator to use for the sign-in promo view in the +// bookmark collection view. +@property(nonatomic, readonly) SigninPromoViewMediator* signinPromoViewMediator; + // This method tells the delegate to add the node and cell // to the list of those being edited. - (void)bookmarkCollectionView:(BookmarkCollectionView*)view @@ -62,12 +68,6 @@ // Returns true if a bookmarks promo cell should be shown. - (BOOL)bookmarkCollectionViewShouldShowPromoCell:(BookmarkCollectionView*)view; -// Shows a sign-in view controller. -- (void)bookmarkCollectionViewShowSignIn:(BookmarkCollectionView*)view; - -// Dismisses the promo. -- (void)bookmarkCollectionViewDismissPromo:(BookmarkCollectionView*)view; - // Tells the delegate that a folder was selected for navigation. - (void)bookmarkCollectionView:(BookmarkCollectionView*)view selectedFolderForNavigation:(const bookmarks::BookmarkNode*)folder; @@ -105,6 +105,12 @@ // Called when something outside the view causes the promo state to change. - (void)promoStateChangedAnimated:(BOOL)animated; +// Configures the sign-in promo view using |configurator|, and reloads the +// collection view if |identityChanged| is YES. +- (void)configureSigninPromoWithConfigurator: + (SigninPromoViewConfigurator*)configurator + identityChanged:(BOOL)identityChanged; + @property(nonatomic, assign, readonly) bookmarks::BookmarkModel* bookmarkModel; @property(nonatomic, weak, readonly) id<UrlLoader> loader; @property(nonatomic, assign, readonly) ios::ChromeBrowserState* browserState;
diff --git a/ios/chrome/browser/ui/bookmarks/bookmark_collection_view.mm b/ios/chrome/browser/ui/bookmarks/bookmark_collection_view.mm index be3b887..3c3b2fac 100644 --- a/ios/chrome/browser/ui/bookmarks/bookmark_collection_view.mm +++ b/ios/chrome/browser/ui/bookmarks/bookmark_collection_view.mm
@@ -26,9 +26,7 @@ #include "ios/chrome/browser/experimental_flags.h" #include "ios/chrome/browser/favicon/ios_chrome_large_icon_service_factory.h" #import "ios/chrome/browser/sync/synced_sessions_bridge.h" -#import "ios/chrome/browser/ui/authentication/signin_promo_view.h" #import "ios/chrome/browser/ui/authentication/signin_promo_view_configurator.h" -#import "ios/chrome/browser/ui/authentication/signin_promo_view_consumer.h" #import "ios/chrome/browser/ui/authentication/signin_promo_view_mediator.h" #import "ios/chrome/browser/ui/bookmarks/bookmark_collection_cells.h" #import "ios/chrome/browser/ui/bookmarks/bookmark_collection_view_background.h" @@ -79,8 +77,7 @@ CGFloat minFaviconSizePt = 16; } -@interface BookmarkCollectionView ()<SigninPromoViewConsumer, - SyncedSessionsObserver, +@interface BookmarkCollectionView ()<SyncedSessionsObserver, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIGestureRecognizerDelegate> { @@ -95,9 +92,6 @@ // True if the loading spinner background is visible. BOOL _spinnerVisible; - // Mediator, helper for the sign-in promo view. - SigninPromoViewMediator* _signinPromoViewMediator; - std::unique_ptr<bookmarks::BookmarkModelBridge> _modelBridge; ios::ChromeBrowserState* _browserState; @@ -231,7 +225,6 @@ } - (void)dealloc { - [_signinPromoViewMediator signinPromoViewRemoved]; _collectionView.dataSource = nil; _collectionView.delegate = nil; UIView* moi = _collectionView; @@ -337,36 +330,53 @@ BOOL shouldShowPromo = (!self.editing && self.folder && self.folder->type() == BookmarkNode::MOBILE && - [self.delegate bookmarkCollectionViewShouldShowPromoCell:self]) || - (_signinPromoViewMediator && _signinPromoViewMediator.signinInProgress); + [self.delegate bookmarkCollectionViewShouldShowPromoCell:self]); if (shouldShowPromo == _promoVisible) return; // This is awful, but until the old code to do the refresh when switching // in and out of edit mode is fixed, this is probably the cleanest thing to // do. _promoVisible = shouldShowPromo; - if (!_promoVisible) { - _signinPromoViewMediator.consumer = nil; - [_signinPromoViewMediator signinPromoViewRemoved]; - _signinPromoViewMediator = nil; - } else { - _signinPromoViewMediator = [[SigninPromoViewMediator alloc] - initWithBrowserState:_browserState - accessPoint:signin_metrics::AccessPoint:: - ACCESS_POINT_BOOKMARK_MANAGER - presenter:self.presenter]; - _signinPromoViewMediator.consumer = self; - [_signinPromoViewMediator signinPromoViewVisible]; + if (_promoVisible) { + [self.delegate.signinPromoViewMediator signinPromoViewVisible]; + } else if (![self.delegate + .signinPromoViewMediator isInvalidClosedOrNeverVisible]) { + // When the sign-in view is closed, the promo state changes, but + // -[SigninPromoViewMediator signinPromoViewHidden] should not be called. + [self.delegate.signinPromoViewMediator signinPromoViewHidden]; } [self.collectionView reloadData]; } +- (void)configureSigninPromoWithConfigurator: + (SigninPromoViewConfigurator*)configurator + identityChanged:(BOOL)identityChanged { + NSIndexPath* indexPath = + [NSIndexPath indexPathForRow:0 inSection:self.promoSection]; + BookmarkSigninPromoCell* signinPromoCell = + static_cast<BookmarkSigninPromoCell*>( + [self.collectionView cellForItemAtIndexPath:indexPath]); + if (!signinPromoCell) + return; + // Should always reconfigure the cell size even if it has to be reloaded. + // -[BookmarkCollectionView cellSizeForIndexPath:] uses the current + // cell to compute its height. + [configurator configureSigninPromoView:signinPromoCell.signinPromoView]; + if (identityChanged) { + // The section should be reload to update the cell height. + NSIndexSet* indexSet = [NSIndexSet indexSetWithIndex:self.promoSection]; + [self.collectionView reloadSections:indexSet]; + } +} + - (void)wasShown { - [_signinPromoViewMediator signinPromoViewVisible]; + if (_promoVisible) + [self.delegate.signinPromoViewMediator signinPromoViewVisible]; } - (void)wasHidden { - [_signinPromoViewMediator signinPromoViewHidden]; + if (![self.delegate.signinPromoViewMediator isInvalidClosedOrNeverVisible]) + [self.delegate.signinPromoViewMediator signinPromoViewHidden]; } #pragma mark - Sections @@ -739,11 +749,10 @@ // the size. There is an issue with iOS 9 to modify the height of the // current cell while being asked for its size. This leads to an infinite // loop. - DCHECK(_signinPromoViewMediator); BookmarkSigninPromoCell* cellToMeasureHeight = [[BookmarkSigninPromoCell alloc] initWithFrame:CGRectMake(0, 0, 1000, 1000)]; - [[_signinPromoViewMediator createConfigurator] + [[self.delegate.signinPromoViewMediator createConfigurator] configureSigninPromoView:cellToMeasureHeight.signinPromoView]; return PreferredCellSizeForWidth(cellToMeasureHeight, CGRectGetWidth(self.bounds)); @@ -789,9 +798,11 @@ dequeueReusableCellWithReuseIdentifier:[BookmarkSigninPromoCell reuseIdentifier] forIndexPath:indexPath]; - signinPromoCell.signinPromoView.delegate = _signinPromoViewMediator; - [[_signinPromoViewMediator createConfigurator] + signinPromoCell.signinPromoView.delegate = + self.delegate.signinPromoViewMediator; + [[self.delegate.signinPromoViewMediator createConfigurator] configureSigninPromoView:signinPromoCell.signinPromoView]; + [self.delegate.signinPromoViewMediator signinPromoViewVisible]; return signinPromoCell; } const BookmarkNode* node = [self nodeAtIndexPath:indexPath]; @@ -834,39 +845,6 @@ return self.sectionCount; } -#pragma mark - SigninPromoViewConsumer - -- (void)configureSigninPromoWithConfigurator: - (SigninPromoViewConfigurator*)configurator - identityChanged:(BOOL)identityChanged { - DCHECK(_signinPromoViewMediator); - NSIndexPath* indexPath = - [NSIndexPath indexPathForRow:0 inSection:self.promoSection]; - BookmarkSigninPromoCell* signinPromoCell = - static_cast<BookmarkSigninPromoCell*>( - [self.collectionView cellForItemAtIndexPath:indexPath]); - if (!signinPromoCell) - return; - // Should always reconfigure the cell size even if it has to be reloaded. - // -[BookmarkCollectionView cellSizeForIndexPath:] uses the current - // cell to compute its height. - [configurator configureSigninPromoView:signinPromoCell.signinPromoView]; - if (identityChanged) { - // The section should be reload to update the cell height. - NSIndexSet* indexSet = [NSIndexSet indexSetWithIndex:self.promoSection]; - [self.collectionView reloadSections:indexSet]; - } -} - -- (void)signinDidFinish { - [self promoStateChangedAnimated:NO]; -} - -- (void)signinPromoViewMediatorCloseButtonWasTapped: - (SigninPromoViewMediator*)mediator { - [_delegate bookmarkCollectionViewDismissPromo:self]; -} - #pragma mark - UIScrollViewDelegate - (void)scrollViewDidScroll:(UIScrollView*)scrollView {
diff --git a/ios/chrome/browser/ui/bookmarks/bookmark_home_view_controller.mm b/ios/chrome/browser/ui/bookmarks/bookmark_home_view_controller.mm index 8b5fa78..fe9ad46 100644 --- a/ios/chrome/browser/ui/bookmarks/bookmark_home_view_controller.mm +++ b/ios/chrome/browser/ui/bookmarks/bookmark_home_view_controller.mm
@@ -309,6 +309,19 @@ } } +- (void)configureSigninPromoWithConfigurator: + (SigninPromoViewConfigurator*)configurator + identityChanged:(BOOL)identityChanged { + if (base::FeatureList::IsEnabled(kBookmarkNewGeneration)) { + [self.bookmarksTableView + configureSigninPromoWithConfigurator:configurator + identityChanged:identityChanged]; + } else { + [self.folderView configureSigninPromoWithConfigurator:configurator + identityChanged:identityChanged]; + } +} + #pragma mark Action sheet callbacks // Enters into edit mode by selecting the given node corresponding to the @@ -449,11 +462,7 @@ } - (BOOL)bookmarkTableViewShouldShowPromoCell:(BookmarkTableView*)tableView { - return self.bookmarkPromoController.promoState; -} - -- (void)bookmarkTableViewDismissPromo:(BookmarkTableView*)view { - [self.bookmarkPromoController hidePromoCell]; + return self.bookmarkPromoController.shouldShowSigninPromo; } - (void)bookmarkTableView:(BookmarkTableView*)view @@ -725,12 +734,12 @@ _editing = editing; if (editing) { - self.bookmarkPromoController.promoState = NO; + self.bookmarkPromoController.shouldShowSigninPromo = NO; } else { // Only reset the editing state when leaving edit mode. This allows // subclasses to add nodes for editing before entering edit mode. [self resetEditNodes]; - [self.bookmarkPromoController updatePromoState]; + [self.bookmarkPromoController updateShouldShowSigninPromo]; } [self updateEditingStateAnimated:animated]; @@ -806,15 +815,7 @@ - (BOOL)bookmarkCollectionViewShouldShowPromoCell: (BookmarkCollectionView*)collectionView { - return self.bookmarkPromoController.promoState; -} - -- (void)bookmarkCollectionViewShowSignIn:(BookmarkCollectionView*)view { - [self.bookmarkPromoController showSignInFromViewController:self]; -} - -- (void)bookmarkCollectionViewDismissPromo:(BookmarkCollectionView*)view { - [self.bookmarkPromoController hidePromoCell]; + return self.bookmarkPromoController.shouldShowSigninPromo; } - (void)bookmarkCollectionView:(BookmarkCollectionView*)view @@ -897,6 +898,10 @@ [self.actionSheetCoordinator start]; } +- (SigninPromoViewMediator*)signinPromoViewMediator { + return self.bookmarkPromoController.signinPromoViewMediator; +} + #pragma mark - BookmarkModelBridgeObserver - (void)bookmarkModelLoaded {
diff --git a/ios/chrome/browser/ui/bookmarks/bookmark_promo_controller.h b/ios/chrome/browser/ui/bookmarks/bookmark_promo_controller.h index 70b4d17..ec8ad69 100644 --- a/ios/chrome/browser/ui/bookmarks/bookmark_promo_controller.h +++ b/ios/chrome/browser/ui/bookmarks/bookmark_promo_controller.h
@@ -8,6 +8,8 @@ #import <UIKit/UIKit.h> @protocol SigninPresenter; +@class SigninPromoViewConfigurator; +@class SigninPromoViewMediator; namespace ios { class ChromeBrowserState; @@ -18,6 +20,12 @@ // Controls the state of the promo. - (void)promoStateChanged:(BOOL)promoEnabled; +// Configures the sign-in promo view using |configurator|, and reloads the view +// needed. +- (void)configureSigninPromoWithConfigurator: + (SigninPromoViewConfigurator*)configurator + identityChanged:(BOOL)identityChanged; + @end // This controller manages the display of the promo cell through its delegate @@ -28,21 +36,20 @@ // Holds the current state of the promo. When the promo state change, it will // call the promoStateChanged: selector on the delegate. -@property(nonatomic, assign) BOOL promoState; +@property(nonatomic) BOOL shouldShowSigninPromo; + +@property(nonatomic, readonly) SigninPromoViewMediator* signinPromoViewMediator; - (instancetype)initWithBrowserState:(ios::ChromeBrowserState*)browserState delegate: (id<BookmarkPromoControllerDelegate>)delegate presenter:(id<SigninPresenter>)presenter; -// Presents the sign-in UI, presenting from |baseViewController|. -- (void)showSignInFromViewController:(UIViewController*)baseViewController; - // Hides the promo cell. It won't be presented again on this profile. - (void)hidePromoCell; -// Updates the promo state based on the sign-in state of the user. -- (void)updatePromoState; +// Updates |shouldShowSigninPromo| based on the sign-in state of the user. +- (void)updateShouldShowSigninPromo; @end
diff --git a/ios/chrome/browser/ui/bookmarks/bookmark_promo_controller.mm b/ios/chrome/browser/ui/bookmarks/bookmark_promo_controller.mm index bd6210a..40e4f98a 100644 --- a/ios/chrome/browser/ui/bookmarks/bookmark_promo_controller.mm +++ b/ios/chrome/browser/ui/bookmarks/bookmark_promo_controller.mm
@@ -10,7 +10,10 @@ #include "components/signin/core/browser/signin_manager.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #include "ios/chrome/browser/signin/signin_manager_factory.h" +#import "ios/chrome/browser/ui/authentication/signin_promo_view_configurator.h" +#import "ios/chrome/browser/ui/authentication/signin_promo_view_consumer.h" #import "ios/chrome/browser/ui/authentication/signin_promo_view_mediator.h" +#import "ios/chrome/browser/ui/commands/application_commands.h" #import "ios/chrome/browser/ui/commands/show_signin_command.h" #import "ios/chrome/browser/ui/signin_interaction/public/signin_presenter.h" @@ -22,19 +25,18 @@ class SignInObserver; } // namespace -@interface BookmarkPromoController () { +@interface BookmarkPromoController ()<SigninPromoViewConsumer> { bool _isIncognito; ios::ChromeBrowserState* _browserState; std::unique_ptr<SignInObserver> _signinObserver; - bool _promoDisplayedRecorded; } // Presenter which can show signin UI. @property(nonatomic, readonly, weak) id<SigninPresenter> presenter; -// Records that the promo was displayed. Can be called several times per -// instance but will effectively record the user action only once per instance. -- (void)recordPromoDisplayed; +// Mediator to use for the sign-in promo view displayed in the bookmark view. +@property(nonatomic, readwrite, strong) + SigninPromoViewMediator* signinPromoViewMediator; // SignInObserver Callbacks @@ -73,8 +75,9 @@ @implementation BookmarkPromoController @synthesize delegate = _delegate; -@synthesize promoState = _promoState; +@synthesize shouldShowSigninPromo = _shouldShowSigninPromo; @synthesize presenter = _presenter; +@synthesize signinPromoViewMediator = _signinPromoViewMediator; - (instancetype)initWithBrowserState:(ios::ChromeBrowserState*)browserState delegate: @@ -93,13 +96,20 @@ SigninManager* signinManager = ios::SigninManagerFactory::GetForBrowserState(_browserState); signinManager->AddObserver(_signinObserver.get()); + _signinPromoViewMediator = [[SigninPromoViewMediator alloc] + initWithBrowserState:_browserState + accessPoint:signin_metrics::AccessPoint:: + ACCESS_POINT_BOOKMARK_MANAGER + presenter:_presenter]; + _signinPromoViewMediator.consumer = self; } - [self updatePromoState]; + [self updateShouldShowSigninPromo]; } return self; } - (void)dealloc { + [_signinPromoViewMediator signinPromoViewRemoved]; if (!_isIncognito) { DCHECK(_browserState); SigninManager* signinManager = @@ -121,18 +131,18 @@ - (void)hidePromoCell { DCHECK(!_isIncognito); DCHECK(_browserState); - self.promoState = NO; + self.shouldShowSigninPromo = NO; } -- (void)setPromoState:(BOOL)promoState { - if (_promoState != promoState) { - _promoState = promoState; - [self.delegate promoStateChanged:promoState]; +- (void)setShouldShowSigninPromo:(BOOL)shouldShowSigninPromo { + if (_shouldShowSigninPromo != shouldShowSigninPromo) { + _shouldShowSigninPromo = shouldShowSigninPromo; + [self.delegate promoStateChanged:shouldShowSigninPromo]; } } -- (void)updatePromoState { - self.promoState = NO; +- (void)updateShouldShowSigninPromo { + self.shouldShowSigninPromo = NO; if (_isIncognito) return; @@ -143,34 +153,41 @@ browserState:_browserState]) { SigninManager* signinManager = ios::SigninManagerFactory::GetForBrowserState(_browserState); - self.promoState = !signinManager->IsAuthenticated(); - if (self.promoState) - [self recordPromoDisplayed]; + self.shouldShowSigninPromo = !signinManager->IsAuthenticated(); } } -#pragma mark - Private - -- (void)recordPromoDisplayed { - if (_promoDisplayedRecorded) - return; - _promoDisplayedRecorded = YES; - base::RecordAction( - base::UserMetricsAction("Signin_Impression_FromBookmarkManager")); -} - #pragma mark - SignInObserver // Called when a user signs into Google services such as sync. - (void)googleSigninSucceededWithAccountId:(const std::string&)account_id username:(const std::string&)username { - self.promoState = NO; + if (!self.signinPromoViewMediator.isSigninInProgress) + self.shouldShowSigninPromo = NO; } // Called when the currently signed-in user for a user has been signed out. - (void)googleSignedOutWithAcountId:(const std::string&)account_id username:(const std::string&)username { - [self updatePromoState]; + [self updateShouldShowSigninPromo]; +} + +#pragma mark - SigninPromoViewConsumer + +- (void)configureSigninPromoWithConfigurator: + (SigninPromoViewConfigurator*)configurator + identityChanged:(BOOL)identityChanged { + [self.delegate configureSigninPromoWithConfigurator:configurator + identityChanged:identityChanged]; +} + +- (void)signinDidFinish { + [self updateShouldShowSigninPromo]; +} + +- (void)signinPromoViewMediatorCloseButtonWasTapped: + (SigninPromoViewMediator*)mediator { + [self updateShouldShowSigninPromo]; } @end
diff --git a/ios/chrome/browser/ui/bookmarks/bookmark_table_view.h b/ios/chrome/browser/ui/bookmarks/bookmark_table_view.h index 6a85553c..b8cd267 100644 --- a/ios/chrome/browser/ui/bookmarks/bookmark_table_view.h +++ b/ios/chrome/browser/ui/bookmarks/bookmark_table_view.h
@@ -10,6 +10,8 @@ class GURL; @protocol SigninPresenter; +@class SigninPromoViewConfigurator; +@class SigninPromoViewMediator; namespace bookmarks { class BookmarkNode; @@ -24,6 +26,11 @@ // Delegate to handle actions on the table. @protocol BookmarkTableViewDelegate<NSObject> + +// Returns the SigninPromoViewMediator to use for the sign-in promo view in the +// bookmark table view. +@property(nonatomic, readonly) SigninPromoViewMediator* signinPromoViewMediator; + // Tells the delegate that a URL was selected for navigation. - (void)bookmarkTableView:(BookmarkTableView*)view selectedUrlForNavigation:(const GURL&)url; @@ -40,9 +47,6 @@ // Returns true if a bookmarks promo cell should be shown. - (BOOL)bookmarkTableViewShouldShowPromoCell:(BookmarkTableView*)view; -// Dismisses the promo. -- (void)bookmarkTableViewDismissPromo:(BookmarkTableView*)view; - // Tells the delegate that nodes were selected in edit mode. - (void)bookmarkTableView:(BookmarkTableView*)view selectedEditNodes: @@ -92,6 +96,12 @@ // Called when something outside the view causes the promo state to change. - (void)promoStateChangedAnimated:(BOOL)animated; +// Configures the sign-in promo view using |configurator|, and reloads the table +// view if |identityChanged| is YES. +- (void)configureSigninPromoWithConfigurator: + (SigninPromoViewConfigurator*)configurator + identityChanged:(BOOL)identityChanged; + // Called when adding a new folder - (void)addNewFolder;
diff --git a/ios/chrome/browser/ui/bookmarks/bookmark_table_view.mm b/ios/chrome/browser/ui/bookmarks/bookmark_table_view.mm index 0c2f928..f88390d 100644 --- a/ios/chrome/browser/ui/bookmarks/bookmark_table_view.mm +++ b/ios/chrome/browser/ui/bookmarks/bookmark_table_view.mm
@@ -52,7 +52,6 @@ @interface BookmarkTableView ()<BookmarkModelBridgeObserver, BookmarkTableCellTitleEditDelegate, - SigninPromoViewConsumer, SyncedSessionsObserver, UIGestureRecognizerDelegate, UITableViewDataSource, @@ -80,9 +79,6 @@ // Task tracker used for async favicon loads. base::CancelableTaskTracker _faviconTaskTracker; - // Mediator, helper for the sign-in promo view. - SigninPromoViewMediator* _signinPromoViewMediator; - // True if the promo is visible. BOOL _promoVisible; @@ -197,7 +193,6 @@ - (void)dealloc { [self removeKeyboardObservers]; - [_signinPromoViewMediator signinPromoViewRemoved]; _tableView.dataSource = nil; _tableView.delegate = nil; _faviconTaskTracker.TryCancelAll(); @@ -210,31 +205,46 @@ // the permanent nodes. BOOL promoVisible = ((_currentRootNode == self.bookmarkModel->root_node()) && - [self.delegate bookmarkTableViewShouldShowPromoCell:self]) || - (_signinPromoViewMediator && _signinPromoViewMediator.signinInProgress); + [self.delegate bookmarkTableViewShouldShowPromoCell:self]); if (promoVisible == _promoVisible) { return; } _promoVisible = promoVisible; - - if (!promoVisible) { - _signinPromoViewMediator.consumer = nil; - [_signinPromoViewMediator signinPromoViewRemoved]; - _signinPromoViewMediator = nil; - } else { - _signinPromoViewMediator = [[SigninPromoViewMediator alloc] - initWithBrowserState:_browserState - accessPoint:signin_metrics::AccessPoint:: - ACCESS_POINT_BOOKMARK_MANAGER - presenter:self.presenter]; - _signinPromoViewMediator.consumer = self; - [_signinPromoViewMediator signinPromoViewVisible]; + if (_promoVisible) { + [self.delegate.signinPromoViewMediator signinPromoViewVisible]; + } else if (![self.delegate + .signinPromoViewMediator isInvalidClosedOrNeverVisible]) { + // When the sign-in view is closed, the promo state changes, but + // -[SigninPromoViewMediator signinPromoViewHidden] should not be called. + [self.delegate.signinPromoViewMediator signinPromoViewHidden]; } [self.tableView reloadData]; } +- (void)configureSigninPromoWithConfigurator: + (SigninPromoViewConfigurator*)configurator + identityChanged:(BOOL)identityChanged { + NSIndexPath* indexPath = + [NSIndexPath indexPathForRow:0 inSection:self.promoSection]; + BookmarkTableSigninPromoCell* signinPromoCell = + static_cast<BookmarkTableSigninPromoCell*>( + [self.tableView cellForRowAtIndexPath:indexPath]); + if (!signinPromoCell) { + return; + } + // Should always reconfigure the cell size even if it has to be reloaded, + // to make sure it has the right size to compute the cell size. + [configurator configureSigninPromoView:signinPromoCell.signinPromoView]; + if (identityChanged) { + // The section should be reload to update the cell height. + NSIndexSet* indexSet = [NSIndexSet indexSetWithIndex:self.promoSection]; + [self.tableView reloadSections:indexSet + withRowAnimation:UITableViewRowAnimationNone]; + } +} + - (void)addNewFolder { [self.editingFolderCell stopEdit]; if (!_currentRootNode) { @@ -342,10 +352,12 @@ signinPromoCell = [[BookmarkTableSigninPromoCell alloc] initWithFrame:CGRectZero]; } - signinPromoCell.signinPromoView.delegate = _signinPromoViewMediator; - [[_signinPromoViewMediator createConfigurator] + signinPromoCell.signinPromoView.delegate = + self.delegate.signinPromoViewMediator; + [[self.delegate.signinPromoViewMediator createConfigurator] configureSigninPromoView:signinPromoCell.signinPromoView]; signinPromoCell.selectionStyle = UITableViewCellSelectionStyleNone; + [self.delegate.signinPromoViewMediator signinPromoViewVisible]; return signinPromoCell; } @@ -477,39 +489,6 @@ } } -#pragma mark - SigninPromoViewConsumer - -- (void)configureSigninPromoWithConfigurator: - (SigninPromoViewConfigurator*)configurator - identityChanged:(BOOL)identityChanged { - DCHECK(_signinPromoViewMediator); - NSIndexPath* indexPath = - [NSIndexPath indexPathForRow:0 inSection:self.promoSection]; - BookmarkTableSigninPromoCell* signinPromoCell = - static_cast<BookmarkTableSigninPromoCell*>( - [self.tableView cellForRowAtIndexPath:indexPath]); - if (!signinPromoCell) { - return; - } - // Should always reconfigure the cell size even if it has to be reloaded. - [configurator configureSigninPromoView:signinPromoCell.signinPromoView]; - if (identityChanged) { - // The section should be reload to update the cell height. - NSIndexSet* indexSet = [NSIndexSet indexSetWithIndex:self.promoSection]; - [self.tableView reloadSections:indexSet - withRowAnimation:UITableViewRowAnimationNone]; - } -} - -- (void)signinDidFinish { - [self promoStateChangedAnimated:NO]; -} - -- (void)signinPromoViewMediatorCloseButtonWasTapped: - (SigninPromoViewMediator*)mediator { - [_delegate bookmarkTableViewDismissPromo:self]; -} - #pragma mark - BookmarkModelBridgeObserver Callbacks // BookmarkModelBridgeObserver Callbacks
diff --git a/ios/chrome/browser/ui/broadcaster/BUILD.gn b/ios/chrome/browser/ui/broadcaster/BUILD.gn index 9c64426..bd83408 100644 --- a/ios/chrome/browser/ui/broadcaster/BUILD.gn +++ b/ios/chrome/browser/ui/broadcaster/BUILD.gn
@@ -5,6 +5,8 @@ source_set("broadcaster") { sources = [ "chrome_broadcast_observer.h", + "chrome_broadcast_observer_bridge.h", + "chrome_broadcast_observer_bridge.mm", "chrome_broadcaster.h", "chrome_broadcaster.mm", ] @@ -19,6 +21,7 @@ source_set("unit_tests") { testonly = true sources = [ + "chrome_broadcast_observer_bridge_unittest.mm", "chrome_broadcaster_unittest.mm", ] deps = [
diff --git a/ios/chrome/browser/ui/broadcaster/chrome_broadcast_observer_bridge.h b/ios/chrome/browser/ui/broadcaster/chrome_broadcast_observer_bridge.h new file mode 100644 index 0000000..4ebc3aa --- /dev/null +++ b/ios/chrome/browser/ui/broadcaster/chrome_broadcast_observer_bridge.h
@@ -0,0 +1,47 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef IOS_CHROME_BROWSER_UI_BROADCASTER_CHROME_BROADCAST_OBSERVER_BRIDGE_H_ +#define IOS_CHROME_BROWSER_UI_BROADCASTER_CHROME_BROADCAST_OBSERVER_BRIDGE_H_ + +#import "ios/chrome/browser/ui/broadcaster/chrome_broadcast_observer.h" + +// Interface for C++ objects that care about broadcasted UI state. +class ChromeBroadcastObserverInterface { + public: + virtual ~ChromeBroadcastObserverInterface(); + + // Invoked by |-broadcastTabStripVisible:|. + virtual void OnTabStripVisbibleBroadcasted(bool visible) {} + + // Invoked by |-broadcastContentScrollOffset:|. + virtual void OnContentScrollOffsetBroadcasted(CGFloat offset) {} + + // Invoked by |-broadcastScrollViewIsScrolling:|. + virtual void OnScrollViewIsScrollingBroadcasted(bool scrolling) {} + + // Invoked by |-broadcastScrollViewIsDragging:|. + virtual void OnScrollViewIsDraggingBroadcasted(bool dragging) {} + + // Invoked by |-broadcastToolbarHeight:|. + virtual void OnToolbarHeightBroadcasted(CGFloat toolbar_height) {} +}; + +// Bridge object that forwards broadcasted UI state to objects that subclass +// ChromeBroadcastObserverInterface. +@interface ChromeBroadcastOberverBridge : NSObject<ChromeBroadcastObserver> + +// The observer being updated. +@property(nonatomic, readonly, nonnull) + ChromeBroadcastObserverInterface* observer; + +// Initializer for a bridge that updates |observer|. +- (nullable instancetype)initWithObserver: + (nonnull ChromeBroadcastObserverInterface*)observer + NS_DESIGNATED_INITIALIZER; +- (nullable instancetype)init NS_UNAVAILABLE; + +@end + +#endif // IOS_CHROME_BROWSER_UI_BROADCASTER_CHROME_BROADCAST_OBSERVER_BRIDGE_H_
diff --git a/ios/chrome/browser/ui/broadcaster/chrome_broadcast_observer_bridge.mm b/ios/chrome/browser/ui/broadcaster/chrome_broadcast_observer_bridge.mm new file mode 100644 index 0000000..a9f34e3 --- /dev/null +++ b/ios/chrome/browser/ui/broadcaster/chrome_broadcast_observer_bridge.mm
@@ -0,0 +1,46 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "ios/chrome/browser/ui/broadcaster/chrome_broadcast_observer_bridge.h" + +#include "base/logging.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +ChromeBroadcastObserverInterface::~ChromeBroadcastObserverInterface() = default; + +@implementation ChromeBroadcastOberverBridge +@synthesize observer = _observer; + +- (instancetype)initWithObserver:(ChromeBroadcastObserverInterface*)observer { + if (self = [super init]) { + _observer = observer; + DCHECK(_observer); + } + return self; +} + +- (void)broadcastTabStripVisible:(BOOL)visible { + self.observer->OnTabStripVisbibleBroadcasted(visible); +} + +- (void)broadcastContentScrollOffset:(CGFloat)offset { + self.observer->OnContentScrollOffsetBroadcasted(offset); +} + +- (void)broadcastScrollViewIsScrolling:(BOOL)scrolling { + self.observer->OnScrollViewIsScrollingBroadcasted(scrolling); +} + +- (void)broadcastScrollViewIsDragging:(BOOL)dragging { + self.observer->OnScrollViewIsDraggingBroadcasted(dragging); +} + +- (void)broadcastToolbarHeight:(CGFloat)height { + self.observer->OnToolbarHeightBroadcasted(height); +} + +@end
diff --git a/ios/chrome/browser/ui/broadcaster/chrome_broadcast_observer_bridge_unittest.mm b/ios/chrome/browser/ui/broadcaster/chrome_broadcast_observer_bridge_unittest.mm new file mode 100644 index 0000000..3c640e3 --- /dev/null +++ b/ios/chrome/browser/ui/broadcaster/chrome_broadcast_observer_bridge_unittest.mm
@@ -0,0 +1,96 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "ios/chrome/browser/ui/broadcaster/chrome_broadcast_observer_bridge.h" + +#include "testing/platform_test.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +// Test implementation of ChromeBroadcastObserverInterface. +class TestChromeBroadcastObserver : public ChromeBroadcastObserverInterface { + public: + // Received broadcast values. + bool tab_strip_visible() const { return tab_strip_visible_; } + CGFloat scroll_offset() const { return scroll_offset_; } + bool scroll_view_scrolling() const { return scroll_view_scrolling_; } + bool scroll_view_dragging() const { return scroll_view_dragging_; } + CGFloat toolbar_height() const { return toolbar_height_; } + + private: + // ChromeBroadcastObserverInterface: + void OnTabStripVisbibleBroadcasted(bool visible) override { + tab_strip_visible_ = visible; + } + void OnContentScrollOffsetBroadcasted(CGFloat offset) override { + scroll_offset_ = offset; + } + void OnScrollViewIsScrollingBroadcasted(bool scrolling) override { + scroll_view_scrolling_ = scrolling; + } + void OnScrollViewIsDraggingBroadcasted(bool dragging) override { + scroll_view_dragging_ = dragging; + } + void OnToolbarHeightBroadcasted(CGFloat toolbar_height) override { + toolbar_height_ = toolbar_height; + } + + bool tab_strip_visible_ = false; + CGFloat scroll_offset_ = 0.0; + bool scroll_view_scrolling_ = false; + bool scroll_view_dragging_ = false; + CGFloat toolbar_height_ = 0.0; +}; + +// Test fixture for ChromeBroadcastOberverBridge. +class ChromeBroadcastObserverBridgeTest : public PlatformTest { + public: + ChromeBroadcastObserverBridgeTest() + : PlatformTest(), + bridge_([[ChromeBroadcastOberverBridge alloc] + initWithObserver:&observer_]) {} + + const TestChromeBroadcastObserver& observer() { return observer_; } + id<ChromeBroadcastObserver> bridge() { return bridge_; } + + private: + TestChromeBroadcastObserver observer_; + __strong ChromeBroadcastOberverBridge* bridge_ = nil; +}; + +// Tests that |-broadcastContentScrollOffset:| is correctly forwarded to the +// observer. +TEST_F(ChromeBroadcastObserverBridgeTest, ContentOffset) { + ASSERT_EQ(observer().scroll_offset(), 0.0); + const CGFloat kOffset = 50.0; + [bridge() broadcastContentScrollOffset:kOffset]; + EXPECT_EQ(observer().scroll_offset(), kOffset); +} + +// Tests that |-broadcastScrollViewIsScrolling:| is correctly forwarded to the +// observer. +TEST_F(ChromeBroadcastObserverBridgeTest, ScrollViewIsScrolling) { + ASSERT_FALSE(observer().scroll_view_scrolling()); + [bridge() broadcastScrollViewIsScrolling:YES]; + EXPECT_TRUE(observer().scroll_view_scrolling()); +} + +// Tests that |-broadcastScrollViewIsDragging:| is correctly forwarded to the +// observer. +TEST_F(ChromeBroadcastObserverBridgeTest, ScrollViewIsDragging) { + ASSERT_FALSE(observer().scroll_view_dragging()); + [bridge() broadcastScrollViewIsDragging:YES]; + EXPECT_TRUE(observer().scroll_view_dragging()); +} + +// Tests that |-broadcastToolbarHeight:| is correctly forwarded to the +// observer. +TEST_F(ChromeBroadcastObserverBridgeTest, ToolbarHeight) { + ASSERT_EQ(observer().toolbar_height(), 0.0); + const CGFloat kHeight = 50.0; + [bridge() broadcastToolbarHeight:kHeight]; + EXPECT_EQ(observer().toolbar_height(), kHeight); +}
diff --git a/ios/chrome/browser/ui/browser_view_controller.mm b/ios/chrome/browser/ui/browser_view_controller.mm index 18e48de..b0306243 100644 --- a/ios/chrome/browser/ui/browser_view_controller.mm +++ b/ios/chrome/browser/ui/browser_view_controller.mm
@@ -118,6 +118,7 @@ #import "ios/chrome/browser/ui/authentication/re_signin_infobar_delegate.h" #import "ios/chrome/browser/ui/background_generator.h" #import "ios/chrome/browser/ui/bookmarks/bookmark_interaction_controller.h" +#include "ios/chrome/browser/ui/bookmarks/bookmark_model_bridge_observer.h" #import "ios/chrome/browser/ui/browser_container_view.h" #import "ios/chrome/browser/ui/browser_view_controller_dependency_factory.h" #import "ios/chrome/browser/ui/bubble/bubble_view_controller_presenter.h" @@ -251,7 +252,6 @@ using base::UserMetricsAction; using bookmarks::BookmarkNode; -class BrowserBookmarkModelBridge; class InfoBarContainerDelegateIOS; namespace { @@ -383,6 +383,7 @@ @interface BrowserViewController ()<ActivityServicePresentation, AppRatingPromptDelegate, + BookmarkModelBridgeObserver, CaptivePortalDetectorTabHelperDelegate, CRWNativeContentProvider, CRWWebStateDelegate, @@ -520,7 +521,7 @@ NSMutableDictionary* _dominantColorCache; // Bridge to register for bookmark changes. - std::unique_ptr<BrowserBookmarkModelBridge> _bookmarkModelBridge; + std::unique_ptr<bookmarks::BookmarkModelBridge> _bookmarkModelBridge; // Cached pointer to the bookmarks model. bookmarks::BookmarkModel* _bookmarkModel; // weak @@ -941,65 +942,6 @@ __weak BrowserViewController* controller_; }; -// Called from the BrowserBookmarkModelBridge from C++ -> ObjC. -@interface BrowserViewController (BookmarkBridgeMethods) -// If a bookmark matching the currentTab url is added or moved, update the -// toolbar state so the star highlight is in sync. -- (void)bookmarkNodeModified:(const BookmarkNode*)node; -- (void)allBookmarksRemoved; -@end - -// Handle notification that bookmarks has been removed changed so we can update -// the bookmarked star icon. -class BrowserBookmarkModelBridge : public bookmarks::BookmarkModelObserver { - public: - explicit BrowserBookmarkModelBridge(BrowserViewController* owner) - : owner_(owner) {} - - ~BrowserBookmarkModelBridge() override {} - - void BookmarkNodeRemoved(bookmarks::BookmarkModel* model, - const BookmarkNode* parent, - int old_index, - const BookmarkNode* node, - const std::set<GURL>& removed_urls) override { - [owner_ bookmarkNodeModified:node]; - } - - void BookmarkModelLoaded(bookmarks::BookmarkModel* model, - bool ids_reassigned) override {} - - void BookmarkNodeMoved(bookmarks::BookmarkModel* model, - const BookmarkNode* old_parent, - int old_index, - const BookmarkNode* new_parent, - int new_index) override {} - - void BookmarkNodeAdded(bookmarks::BookmarkModel* model, - const BookmarkNode* parent, - int index) override { - [owner_ bookmarkNodeModified:parent->GetChild(index)]; - } - - void BookmarkNodeChanged(bookmarks::BookmarkModel* model, - const BookmarkNode* node) override {} - - void BookmarkNodeFaviconChanged(bookmarks::BookmarkModel* model, - const BookmarkNode* node) override {} - - void BookmarkNodeChildrenReordered(bookmarks::BookmarkModel* model, - const BookmarkNode* node) override {} - - void BookmarkAllUserNodesRemoved( - bookmarks::BookmarkModel* model, - const std::set<GURL>& removed_urls) override { - [owner_ allBookmarksRemoved]; - } - - private: - __weak BrowserViewController* owner_; -}; - @implementation BrowserViewController @synthesize contentArea = _contentArea; @@ -1867,8 +1809,8 @@ // during testing, so explicitly support this). _bookmarkModel = ios::BookmarkModelFactory::GetForBrowserState(_browserState); if (_bookmarkModel) { - _bookmarkModelBridge.reset(new BrowserBookmarkModelBridge(self)); - _bookmarkModel->AddObserver(_bookmarkModelBridge.get()); + _bookmarkModelBridge.reset( + new bookmarks::BookmarkModelBridge(self, _bookmarkModel)); } } @@ -2662,8 +2604,7 @@ self.tabStripView = nil; _infoBarContainer = nil; _readingListMenuNotifier = nil; - if (_bookmarkModel) - _bookmarkModel->RemoveObserver(_bookmarkModelBridge.get()); + _bookmarkModelBridge.reset(); [_model removeObserver:self]; [[UpgradeCenter sharedInstance] unregisterClient:self]; [[NSNotificationCenter defaultCenter] removeObserver:self]; @@ -3395,19 +3336,9 @@ case OverscrollAction::CLOSE_TAB: [self.dispatcher closeCurrentTab]; break; - case OverscrollAction::REFRESH: { - web::WebState* webState = [_model currentTab].webState; - if (webState) { - if (webState->IsLoading()) { - webState->Stop(); - } - // |check_for_repost| is true because the reload is explicitly initiated - // by the user. - webState->GetNavigationManager()->Reload(web::ReloadType::NORMAL, - true /* check_for_repost */); - } + case OverscrollAction::REFRESH: + [self reload]; break; - } case OverscrollAction::NONE: NOTREACHED(); break; @@ -5150,23 +5081,44 @@ return [self hasControllerForURL:url]; } -#pragma mark - BookmarkBridgeMethods +// TODO(crbug.com/788705): BVC doesn't need to implement +// BookmarkModelBridgeObserver once the new toolbar is turned on. +#pragma mark - BookmarkModelBridgeObserver // If an added or removed bookmark is the same as the current url, update the // toolbar so the star highlight is kept in sync. -- (void)bookmarkNodeModified:(const BookmarkNode*)node { - if ([_model currentTab].webState && - node->url() == [_model currentTab].webState->GetLastCommittedURL()) { - [self updateToolbar]; - } +- (void)bookmarkNodeChildrenChanged:(const BookmarkNode*)bookmarkNode { + [self updateToolbar]; } // If all bookmarks are removed, update the toolbar so the star highlight is // kept in sync. -- (void)allBookmarksRemoved { +- (void)bookmarkModelRemovedAllNodes { [self updateToolbar]; } +// In case we are on a bookmarked page before the model is loaded. +- (void)bookmarkModelLoaded { + [self updateToolbar]; +} + +- (void)bookmarkNodeChanged:(const BookmarkNode*)bookmarkNode { + // No-op -- required by BookmarkModelBridgeObserver but not used. +} + +- (void)bookmarkNode:(const BookmarkNode*)bookmarkNode + movedFromParent:(const BookmarkNode*)oldParent + toParent:(const BookmarkNode*)newParent { + // No-op -- required by BookmarkModelBridgeObserver but not used. +} + +- (void)bookmarkNodeDeleted:(const BookmarkNode*)node + fromFolder:(const BookmarkNode*)folder { + // No-op -- required by BookmarkModelBridgeObserver but not used. +} + +#pragma mark - Alerts + - (void)showErrorAlertWithStringTitle:(NSString*)title message:(NSString*)message { // Dismiss current alert.
diff --git a/ios/chrome/browser/ui/ntp/recent_tabs/recent_tabs_table_view_controller.mm b/ios/chrome/browser/ui/ntp/recent_tabs/recent_tabs_table_view_controller.mm index 71963fb8..bc3a9a7 100644 --- a/ios/chrome/browser/ui/ntp/recent_tabs/recent_tabs_table_view_controller.mm +++ b/ios/chrome/browser/ui/ntp/recent_tabs/recent_tabs_table_view_controller.mm
@@ -832,8 +832,7 @@ [configurator configureSigninPromoView:signinPromoView]; subview = signinPromoView; [cell setSelectionStyle:UITableViewCellSelectionStyleNone]; - base::RecordAction( - base::UserMetricsAction("Signin_Impression_FromRecentTabs")); + [_signinPromoViewMediator signinPromoViewVisible]; break; } case CELL_OTHER_DEVICES_SYNC_IN_PROGRESS:
diff --git a/ios/chrome/browser/ui/omnibox/BUILD.gn b/ios/chrome/browser/ui/omnibox/BUILD.gn index 1a2c9be..ca010ce 100644 --- a/ios/chrome/browser/ui/omnibox/BUILD.gn +++ b/ios/chrome/browser/ui/omnibox/BUILD.gn
@@ -42,6 +42,8 @@ "image_retriever.h", "location_bar_controller_impl.h", "location_bar_controller_impl.mm", + "location_bar_view.h", + "location_bar_view.mm", "omnibox_popup_mediator.h", "omnibox_popup_mediator.mm", "omnibox_popup_positioner.h",
diff --git a/ios/chrome/browser/ui/omnibox/location_bar_controller_impl.mm b/ios/chrome/browser/ui/omnibox/location_bar_controller_impl.mm index 1e1947d..a2efe44 100644 --- a/ios/chrome/browser/ui/omnibox/location_bar_controller_impl.mm +++ b/ios/chrome/browser/ui/omnibox/location_bar_controller_impl.mm
@@ -21,6 +21,7 @@ #include "ios/chrome/browser/experimental_flags.h" #import "ios/chrome/browser/ui/commands/browser_commands.h" #include "ios/chrome/browser/ui/omnibox/location_bar_delegate.h" +#import "ios/chrome/browser/ui/omnibox/location_bar_view.h" #include "ios/chrome/browser/ui/omnibox/omnibox_popup_view_ios.h" #import "ios/chrome/browser/ui/omnibox/omnibox_text_field_ios.h" #include "ios/chrome/browser/ui/ui_util.h"
diff --git a/ios/chrome/browser/ui/omnibox/location_bar_view.h b/ios/chrome/browser/ui/omnibox/location_bar_view.h new file mode 100644 index 0000000..5e71bbfc --- /dev/null +++ b/ios/chrome/browser/ui/omnibox/location_bar_view.h
@@ -0,0 +1,68 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef IOS_CHROME_BROWSER_UI_OMNIBOX_LOCATION_BAR_VIEW_H_ +#define IOS_CHROME_BROWSER_UI_OMNIBOX_LOCATION_BAR_VIEW_H_ + +#import <UIKit/UIKit.h> + +@class OmniboxTextFieldIOS; + +// The location bar view is the view that is displayed in the visible "address +// bar" space of the toolbar. Everything that's located in the white rectangle +// is the location bar: the button on the left, the buttons on the right, the +// omnibox textfield. +@interface LocationBarView : UIView + +// Initialize the location bar with the given frame, font, text color, and tint +// color for omnibox. +- (instancetype)initWithFrame:(CGRect)frame + font:(UIFont*)font + textColor:(UIColor*)textColor + tintColor:(UIColor*)tintColor NS_DESIGNATED_INITIALIZER; + +- (instancetype)initWithFrame:(CGRect)frame NS_UNAVAILABLE; + +- (instancetype)initWithCoder:(NSCoder*)aDecoder NS_UNAVAILABLE; + +// The containted omnibox textfield. +@property(nonatomic, strong) OmniboxTextFieldIOS* textField; + +// The leading button, such as the security status icon. +@property(nonatomic, strong) UIButton* leadingButton; + +// Incognito status of the location bar changes the appearance, such as text +// and icon colors. +@property(nonatomic, assign) BOOL incognito; + +// Hides and shows the leading button, without animation. +- (void)setLeadingButtonHidden:(BOOL)hidden; +// Enables or disables the leading button for user interaction. +- (void)setLeadingButtonEnabled:(BOOL)enabled; + +// Sets the leading button's image by resource id. +- (void)setPlaceholderImage:(int)imageID; + +// Perform an animation of |leadingButton| fading in and sliding in from the +// leading edge. +- (void)fadeInLeadingButton; +// Perform an animation of |leadingButton| sliding out and fading out towards +// the leading edge. +- (void)fadeOutLeadingButton; + +// Perform animations for expanding the omnibox. This animation can be seen on +// an iPhone when the omnibox is focused. It involves sliding the leading button +// out and fading its alpha. +- (void)addExpandOmniboxAnimations:(UIViewPropertyAnimator*)animator + API_AVAILABLE(ios(10.0)); + +// Perform animations for expanding the omnibox. This animation can be seen on +// an iPhone when the omnibox is defocused. It involves sliding the leading +// button in and fading its alpha. +- (void)addContractOmniboxAnimations:(UIViewPropertyAnimator*)animator + API_AVAILABLE(ios(10.0)); + +@end + +#endif // IOS_CHROME_BROWSER_UI_OMNIBOX_LOCATION_BAR_VIEW_H_
diff --git a/ios/chrome/browser/ui/omnibox/location_bar_view.mm b/ios/chrome/browser/ui/omnibox/location_bar_view.mm new file mode 100644 index 0000000..b812b9f3 --- /dev/null +++ b/ios/chrome/browser/ui/omnibox/location_bar_view.mm
@@ -0,0 +1,304 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "ios/chrome/browser/ui/omnibox/location_bar_view.h" + +#import "ios/chrome/browser/ui/animation_util.h" +#import "ios/chrome/browser/ui/omnibox/omnibox_text_field_ios.h" +#import "ios/chrome/browser/ui/toolbar/public/web_toolbar_controller_constants.h" +#include "ios/chrome/browser/ui/ui_util.h" +#import "ios/chrome/browser/ui/uikit_ui_util.h" +#import "ios/chrome/common/material_timing.h" +#include "ios/chrome/grit/ios_strings.h" +#include "ios/chrome/grit/ios_theme_resources.h" +#include "skia/ext/skia_utils_ios.h" +#include "ui/gfx/color_palette.h" +#include "ui/gfx/image/image.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +namespace { +const CGFloat kLeadingButtonEdgeOffset = 9; +} // namespace + +@interface OmniboxTextFieldIOS () + +// Gets the bounds of the rect covering the URL. +- (CGRect)preEditLabelRectForBounds:(CGRect)bounds; +// Creates the UILabel if it doesn't already exist and adds it as a +// subview. +- (void)createSelectionViewIfNecessary; +// Helper method used to set the text of this field. Updates the selection view +// to contain the correct inline autocomplete text. +- (void)setTextInternal:(NSAttributedString*)text + autocompleteLength:(NSUInteger)autocompleteLength; +// Override deleteBackward so that backspace can clear query refinement chips. +- (void)deleteBackward; +// Returns the layers affected by animations added by |-animateFadeWithStyle:|. +- (NSArray*)fadeAnimationLayers; +// Returns the text that is displayed in the field, including any inline +// autocomplete text that may be present as an NSString. Returns the same +// value as -|displayedText| but prefer to use this to avoid unnecessary +// conversion from NSString to base::string16 if possible. +- (NSString*)nsDisplayedText; + +@end + +#pragma mark - LocationBarView + +@interface LocationBarView () +// Constraints the leading textfield side to the leading of |self|. +// Active when the |leadingView| is nil or hidden. +@property(nonatomic, strong) NSLayoutConstraint* leadingTextfieldConstraint; +// When the |leadingButton| is not hidden, this is a constraint that links the +// leading edge of the button to self leading edge. Used for animations. +@property(nonatomic, strong) NSLayoutConstraint* leadingButtonLeadingConstraint; +@end + +@implementation LocationBarView +@synthesize textField = _textField; +@synthesize leadingButton = _leadingButton; +@synthesize leadingTextfieldConstraint = _leadingTextfieldConstraint; +@synthesize incognito = _incognito; +@synthesize leadingButtonLeadingConstraint = _leadingButtonLeadingConstraint; + +#pragma mark - Public properties + +- (void)setLeadingButton:(UIButton*)leadingButton { + _leadingButton = leadingButton; + _leadingButton.translatesAutoresizingMaskIntoConstraints = NO; + [_leadingButton + setContentCompressionResistancePriority:UILayoutPriorityRequired + forAxis:UILayoutConstraintAxisHorizontal]; + [_leadingButton + setContentCompressionResistancePriority:UILayoutPriorityRequired + forAxis:UILayoutConstraintAxisVertical]; + [_leadingButton setContentHuggingPriority:UILayoutPriorityRequired + forAxis:UILayoutConstraintAxisHorizontal]; + [_leadingButton setContentHuggingPriority:UILayoutPriorityRequired + forAxis:UILayoutConstraintAxisVertical]; +} + +#pragma mark - Public methods + +- (instancetype)initWithFrame:(CGRect)frame + font:(UIFont*)font + textColor:(UIColor*)textColor + tintColor:(UIColor*)tintColor { + self = [super initWithFrame:frame]; + if (self) { + _textField = [[OmniboxTextFieldIOS alloc] initWithFrame:frame + font:font + textColor:textColor + tintColor:tintColor]; + [self addSubview:_textField]; + + _leadingTextfieldConstraint = + [_textField.leadingAnchor constraintEqualToAnchor:self.leadingAnchor]; + + [NSLayoutConstraint activateConstraints:@[ + [_textField.trailingAnchor constraintEqualToAnchor:self.trailingAnchor], + [_textField.topAnchor constraintEqualToAnchor:self.topAnchor], + [_textField.bottomAnchor constraintEqualToAnchor:self.bottomAnchor], + _leadingTextfieldConstraint, + ]]; + + _textField.translatesAutoresizingMaskIntoConstraints = NO; + } + return self; +} + +- (void)setLeadingButtonHidden:(BOOL)hidden { + if (!_leadingButton) { + return; + } + + if (hidden) { + [_leadingButton removeFromSuperview]; + self.leadingTextfieldConstraint.active = YES; + } else { + [self addSubview:_leadingButton]; + self.leadingTextfieldConstraint.active = NO; + self.leadingButtonLeadingConstraint = [self.leadingAnchor + constraintEqualToAnchor:self.leadingButton.leadingAnchor + constant:-kLeadingButtonEdgeOffset]; + [NSLayoutConstraint activateConstraints:@[ + [_leadingButton.centerYAnchor constraintEqualToAnchor:self.centerYAnchor], + self.leadingButtonLeadingConstraint, + [self.leadingButton.trailingAnchor + constraintEqualToAnchor:self.textField.leadingAnchor], + ]]; + } +} + +- (void)setLeadingButtonEnabled:(BOOL)enabled { + _leadingButton.enabled = enabled; +} + +- (void)setPlaceholderImage:(int)imageID { + [self.leadingButton setImage:[self placeholderImageWithId:imageID] + forState:UIControlStateNormal]; + [self.leadingButton setTintColor:[self tintColorForLeftImageWithID:imageID]]; + + // TODO(crbug.com/774121): This should not be done like this; instead the + // responder status of the textfield should be broadcasted and observed + // by the mediator of location bar, that would then show/hide the + // leading button. + BOOL hidden = (!IsIPadIdiom() && [self.textField isFirstResponder]); + [self setLeadingButtonHidden:hidden]; +} + +- (void)fadeInLeadingButton { + self.leadingButton.alpha = 0; + // Instead of passing a delay into -fadeInView:, wait to call -fadeInView:. + // The CABasicAnimation's start and end positions are calculated immediately + // instead of after the animation's delay, but the omnibox's layer isn't set + // yet to its final state and as a result the start and end positions will not + // be correct. + dispatch_time_t delay = dispatch_time( + DISPATCH_TIME_NOW, ios::material::kDuration2 * NSEC_PER_SEC); + dispatch_after(delay, dispatch_get_main_queue(), ^(void) { + UIView* view = self.leadingButton; + LayoutOffset leadingOffset = kPositionAnimationLeadingOffset; + NSTimeInterval duration = ios::material::kDuration1; + NSTimeInterval delay = 0; + + [CATransaction begin]; + [CATransaction setDisableActions:YES]; + [CATransaction setCompletionBlock:^{ + [view.layer removeAnimationForKey:@"fadeIn"]; + }]; + view.alpha = 1.0; + + // Animate the position of |view| |leadingOffset| pixels after |delay|. + CGRect shiftedFrame = CGRectLayoutOffset(view.frame, leadingOffset); + CAAnimation* shiftAnimation = + FrameAnimationMake(view.layer, shiftedFrame, view.frame); + shiftAnimation.duration = duration; + shiftAnimation.beginTime = delay; + shiftAnimation.timingFunction = + TimingFunction(ios::material::CurveEaseInOut); + + // Animate the opacity of |view| to 1 after |delay|. + CAAnimation* fadeAnimation = OpacityAnimationMake(0.0, 1.0); + fadeAnimation.duration = duration; + fadeAnimation.beginTime = delay; + shiftAnimation.timingFunction = + TimingFunction(ios::material::CurveEaseInOut); + + // Add group animation to layer. + CAAnimation* group = AnimationGroupMake(@[ shiftAnimation, fadeAnimation ]); + [view.layer addAnimation:group forKey:@"fadeIn"]; + + [CATransaction commit]; + }); +} + +- (void)fadeOutLeadingButton { + [self setLeadingButtonHidden:NO]; + + UIView* leadingView = [self leadingButton]; + + // Move the leadingButton outside of the bounds; this constraint will be + // created from scratch when the button is shown. + self.leadingButtonLeadingConstraint.constant = leadingView.frame.size.width; + [UIView animateWithDuration:ios::material::kDuration2 + delay:0 + options:UIViewAnimationOptionCurveEaseInOut + animations:^{ + // Fade out the alpha and apply the constraint change above. + leadingView.alpha = 0; + [self setNeedsLayout]; + [self layoutIfNeeded]; + } + completion:^(BOOL finished) { + // Restore alpha and update the hidden state. + leadingView.alpha = 1; + [self setLeadingButtonHidden:YES]; + }]; +} + +- (void)addExpandOmniboxAnimations:(UIViewPropertyAnimator*)animator + API_AVAILABLE(ios(10.0)) { + UIView* leadingView = [self leadingButton]; + leadingView.alpha = 1; + self.leadingButtonLeadingConstraint.constant = -100; + [animator addAnimations:^{ + leadingView.alpha = 0; + + [self setNeedsLayout]; + [self layoutIfNeeded]; + }]; + + [animator addCompletion:^(UIViewAnimatingPosition finalPosition) { + [self setLeadingButtonHidden:YES]; + [self setNeedsLayout]; + [self layoutIfNeeded]; + }]; + + [self.textField addExpandOmniboxAnimations:animator]; +} + +- (void)addContractOmniboxAnimations:(UIViewPropertyAnimator*)animator + API_AVAILABLE(ios(10.0)) { + [self setLeadingButtonHidden:NO]; + + UIView* leadingView = [self leadingButton]; + + // Move the leadingButton outside of the bounds; this constraint will be + // created from scratch when the button is shown. + self.leadingButtonLeadingConstraint.constant = leadingView.frame.size.width; + leadingView.alpha = 0; + + [animator addAnimations:^{ + // Fade out the alpha and apply the constraint change above. + leadingView.alpha = 1; + [self setNeedsLayout]; + [self layoutIfNeeded]; + } + delayFactor:ios::material::kDuration2]; + [animator addCompletion:^(UIViewAnimatingPosition finalPosition) { + [self setLeadingButtonHidden:NO]; + }]; + + [self.textField addContractOmniboxAnimations:animator]; +} + +#pragma mark - Private methods + +// Retrieves a resource image by ID and returns it as UIImage. +- (UIImage*)placeholderImageWithId:(int)imageID { + return [NativeImage(imageID) + imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; +} + +// Returns the tint color for the left image. This is necessary because the +// resource images are stored as templates, but in non-incognito the securtiy +// indicator needs to have a color depending on security status. +- (UIColor*)tintColorForLeftImageWithID:(int)imageID { + UIColor* tint = [UIColor whiteColor]; + if (!self.incognito) { + switch (imageID) { + case IDR_IOS_LOCATION_BAR_HTTP: + tint = [UIColor darkGrayColor]; + break; + case IDR_IOS_OMNIBOX_HTTPS_VALID: + tint = skia::UIColorFromSkColor(gfx::kGoogleGreen700); + break; + case IDR_IOS_OMNIBOX_HTTPS_POLICY_WARNING: + tint = skia::UIColorFromSkColor(gfx::kGoogleYellow700); + break; + case IDR_IOS_OMNIBOX_HTTPS_INVALID: + tint = skia::UIColorFromSkColor(gfx::kGoogleRed700); + break; + default: + tint = [UIColor darkGrayColor]; + } + } + return tint; +} + +@end
diff --git a/ios/chrome/browser/ui/omnibox/omnibox_text_field_ios.h b/ios/chrome/browser/ui/omnibox/omnibox_text_field_ios.h index 1183d8af..b19c6991 100644 --- a/ios/chrome/browser/ui/omnibox/omnibox_text_field_ios.h +++ b/ios/chrome/browser/ui/omnibox/omnibox_text_field_ios.h
@@ -7,7 +7,6 @@ #import <UIKit/UIKit.h> -#include "base/mac/scoped_nsobject.h" #include "base/strings/string16.h" #import "ios/chrome/browser/ui/omnibox/omnibox_text_field_delegate.h" @@ -17,54 +16,6 @@ OMNIBOX_TEXT_FIELD_FADE_STYLE_OUT } OmniboxTextFieldFadeStyle; -@class OmniboxTextFieldIOS; - -@interface LocationBarView : UIView - -// Initialize the location bar with the given frame, font, text color, and tint -// color for omnibox. -- (instancetype)initWithFrame:(CGRect)frame - font:(UIFont*)font - textColor:(UIColor*)textColor - tintColor:(UIColor*)tintColor NS_DESIGNATED_INITIALIZER; - -- (instancetype)initWithFrame:(CGRect)frame NS_UNAVAILABLE; - -- (instancetype)initWithCoder:(NSCoder*)aDecoder NS_UNAVAILABLE; - -// The containted omnibox textfield. -@property(nonatomic, strong) OmniboxTextFieldIOS* textField; - -// The leading button, such as the security status icon. -@property(nonatomic, strong) UIButton* leadingButton; - -// Incognito status of the location bar changes the appearance, such as text -// and icon colors. -@property(nonatomic, assign) BOOL incognito; - -// Hides and shows the leading button, without animation. -- (void)setLeadingButtonHidden:(BOOL)hidden; -// Enables or disables the leading button for user interaction. -- (void)setLeadingButtonEnabled:(BOOL)enabled; - -// Sets the leading button's image by resource id. -- (void)setPlaceholderImage:(int)imageID; - -// Perform an animation of |leadingButton| fading in and sliding in from the -// leading edge. -- (void)fadeInLeadingButton; -// Perform an animation of |leadingButton| sliding out and fading out towards -// the leading edge. -- (void)fadeOutLeadingButton; - -- (void)addExpandOmniboxAnimations:(UIViewPropertyAnimator*)animator - API_AVAILABLE(ios(10.0)); - -- (void)addContractOmniboxAnimations:(UIViewPropertyAnimator*)animator - API_AVAILABLE(ios(10.0)); - -@end - // UITextField subclass to allow for adjusting borders. @interface OmniboxTextFieldIOS : UITextField
diff --git a/ios/chrome/browser/ui/omnibox/omnibox_text_field_ios.mm b/ios/chrome/browser/ui/omnibox/omnibox_text_field_ios.mm index a015fc9..3d13c059 100644 --- a/ios/chrome/browser/ui/omnibox/omnibox_text_field_ios.mm +++ b/ios/chrome/browser/ui/omnibox/omnibox_text_field_ios.mm
@@ -52,8 +52,6 @@ // omnibox border. const CGFloat kTextAreaLeadingOffset = -2; -const CGFloat kLeadingButtonEdgeOffset = 9; - const CGFloat kStarButtonWidth = 36; const CGFloat kVoiceSearchButtonWidth = 36.0; @@ -89,257 +87,6 @@ @end -#pragma mark - LocationBarView - -@interface LocationBarView () -// Constraints the leading textfield side to the leading of |self|. -// Active when the |leadingView| is nil or hidden. -@property(nonatomic, strong) NSLayoutConstraint* leadingTextfieldConstraint; -// When the |leadingButton| is not hidden, this is a constraint that links the -// leading edge of the button to self leading edge. Used for animations. -@property(nonatomic, strong) NSLayoutConstraint* leadingButtonLeadingConstraint; -@end - -@implementation LocationBarView -@synthesize textField = _textField; -@synthesize leadingButton = _leadingButton; -@synthesize leadingTextfieldConstraint = _leadingTextfieldConstraint; -@synthesize incognito = _incognito; -@synthesize leadingButtonLeadingConstraint = _leadingButtonLeadingConstraint; - -- (instancetype)initWithFrame:(CGRect)frame - font:(UIFont*)font - textColor:(UIColor*)textColor - tintColor:(UIColor*)tintColor { - self = [super initWithFrame:frame]; - if (self) { - _textField = [[OmniboxTextFieldIOS alloc] initWithFrame:frame - font:font - textColor:textColor - tintColor:tintColor]; - [self addSubview:_textField]; - - _leadingTextfieldConstraint = - [_textField.leadingAnchor constraintEqualToAnchor:self.leadingAnchor]; - - [NSLayoutConstraint activateConstraints:@[ - [_textField.trailingAnchor constraintEqualToAnchor:self.trailingAnchor], - [_textField.topAnchor constraintEqualToAnchor:self.topAnchor], - [_textField.bottomAnchor constraintEqualToAnchor:self.bottomAnchor], - _leadingTextfieldConstraint, - ]]; - - _textField.translatesAutoresizingMaskIntoConstraints = NO; - } - return self; -} - -- (void)setLeadingButtonEnabled:(BOOL)enabled { - _leadingButton.enabled = enabled; -} - -- (void)setLeadingButtonHidden:(BOOL)hidden { - if (!_leadingButton) { - return; - } - - if (hidden) { - [_leadingButton removeFromSuperview]; - self.leadingTextfieldConstraint.active = YES; - } else { - [self addSubview:_leadingButton]; - self.leadingTextfieldConstraint.active = NO; - self.leadingButtonLeadingConstraint = [self.leadingAnchor - constraintEqualToAnchor:self.leadingButton.leadingAnchor - constant:-kLeadingButtonEdgeOffset]; - [NSLayoutConstraint activateConstraints:@[ - [_leadingButton.centerYAnchor constraintEqualToAnchor:self.centerYAnchor], - self.leadingButtonLeadingConstraint, - [self.leadingButton.trailingAnchor - constraintEqualToAnchor:self.textField.leadingAnchor], - ]]; - } -} - -- (void)setLeadingButton:(UIButton*)leadingButton { - _leadingButton = leadingButton; - _leadingButton.translatesAutoresizingMaskIntoConstraints = NO; - [_leadingButton - setContentCompressionResistancePriority:UILayoutPriorityRequired - forAxis:UILayoutConstraintAxisHorizontal]; - [_leadingButton - setContentCompressionResistancePriority:UILayoutPriorityRequired - forAxis:UILayoutConstraintAxisVertical]; - [_leadingButton setContentHuggingPriority:UILayoutPriorityRequired - forAxis:UILayoutConstraintAxisHorizontal]; - [_leadingButton setContentHuggingPriority:UILayoutPriorityRequired - forAxis:UILayoutConstraintAxisVertical]; -} - -- (void)setPlaceholderImage:(int)imageID { - [self.leadingButton setImage:[self placeholderImageWithID:imageID] - forState:UIControlStateNormal]; - [self.leadingButton setTintColor:[self tintColorForLeftImageWithId:imageID]]; - - // TODO(crbug.com/774121): This should not be done like this; instead the - // responder status of the textfield should be broadcasted and observed - // by the mediator of location bar, that would then show/hide the - // leading button. - BOOL hidden = (!IsIPadIdiom() && [self.textField isFirstResponder]); - [self setLeadingButtonHidden:hidden]; -} - -- (void)fadeInLeadingButton { - self.leadingButton.alpha = 0; - // Instead of passing a delay into -fadeInView:, wait to call -fadeInView:. - // The CABasicAnimation's start and end positions are calculated immediately - // instead of after the animation's delay, but the omnibox's layer isn't set - // yet to its final state and as a result the start and end positions will not - // be correct. - dispatch_time_t delay = dispatch_time( - DISPATCH_TIME_NOW, ios::material::kDuration2 * NSEC_PER_SEC); - dispatch_after(delay, dispatch_get_main_queue(), ^(void) { - UIView* view = self.leadingButton; - LayoutOffset leadingOffset = kPositionAnimationLeadingOffset; - NSTimeInterval duration = ios::material::kDuration1; - NSTimeInterval delay = 0; - - [CATransaction begin]; - [CATransaction setDisableActions:YES]; - [CATransaction setCompletionBlock:^{ - [view.layer removeAnimationForKey:@"fadeIn"]; - }]; - view.alpha = 1.0; - - // Animate the position of |view| |leadingOffset| pixels after |delay|. - CGRect shiftedFrame = CGRectLayoutOffset(view.frame, leadingOffset); - CAAnimation* shiftAnimation = - FrameAnimationMake(view.layer, shiftedFrame, view.frame); - shiftAnimation.duration = duration; - shiftAnimation.beginTime = delay; - shiftAnimation.timingFunction = - TimingFunction(ios::material::CurveEaseInOut); - - // Animate the opacity of |view| to 1 after |delay|. - CAAnimation* fadeAnimation = OpacityAnimationMake(0.0, 1.0); - fadeAnimation.duration = duration; - fadeAnimation.beginTime = delay; - shiftAnimation.timingFunction = - TimingFunction(ios::material::CurveEaseInOut); - - // Add group animation to layer. - CAAnimation* group = AnimationGroupMake(@[ shiftAnimation, fadeAnimation ]); - [view.layer addAnimation:group forKey:@"fadeIn"]; - - [CATransaction commit]; - }); -} - -- (void)fadeOutLeadingButton { - [self setLeadingButtonHidden:NO]; - - UIView* leadingView = [self leadingButton]; - - // Move the leadingButton outside of the bounds; this constraint will be - // created from scratch when the button is shown. - self.leadingButtonLeadingConstraint.constant = leadingView.frame.size.width; - [UIView animateWithDuration:ios::material::kDuration2 - delay:0 - options:UIViewAnimationOptionCurveEaseInOut - animations:^{ - // Fade out the alpha and apply the constraint change above. - leadingView.alpha = 0; - [self setNeedsLayout]; - [self layoutIfNeeded]; - } - completion:^(BOOL finished) { - // Restore alpha and update the hidden state. - leadingView.alpha = 1; - [self setLeadingButtonHidden:YES]; - }]; -} - -- (void)addExpandOmniboxAnimations:(UIViewPropertyAnimator*)animator - API_AVAILABLE(ios(10.0)) { - UIView* leadingView = [self leadingButton]; - leadingView.alpha = 1; - self.leadingButtonLeadingConstraint.constant = -100; - [animator addAnimations:^{ - leadingView.alpha = 0; - - [self setNeedsLayout]; - [self layoutIfNeeded]; - }]; - - [animator addCompletion:^(UIViewAnimatingPosition finalPosition) { - [self setLeadingButtonHidden:YES]; - [self setNeedsLayout]; - [self layoutIfNeeded]; - }]; - - [self.textField addExpandOmniboxAnimations:animator]; -} - -- (void)addContractOmniboxAnimations:(UIViewPropertyAnimator*)animator - API_AVAILABLE(ios(10.0)) { - [self setLeadingButtonHidden:NO]; - - UIView* leadingView = [self leadingButton]; - - // Move the leadingButton outside of the bounds; this constraint will be - // created from scratch when the button is shown. - self.leadingButtonLeadingConstraint.constant = leadingView.frame.size.width; - leadingView.alpha = 0; - - [animator addAnimations:^{ - // Fade out the alpha and apply the constraint change above. - leadingView.alpha = 1; - [self setNeedsLayout]; - [self layoutIfNeeded]; - } - delayFactor:ios::material::kDuration2]; - [animator addCompletion:^(UIViewAnimatingPosition finalPosition) { - [self setLeadingButtonHidden:NO]; - }]; - - [self.textField addContractOmniboxAnimations:animator]; -} - -#pragma mark - private - -- (UIImage*)placeholderImageWithID:(int)imageID { - return [NativeImage(imageID) - imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; -} - -- (UIColor*)tintColorForLeftImageWithId:(int)imageID { - UIColor* tint = [UIColor whiteColor]; - if (!self.incognito) { - switch (imageID) { - case IDR_IOS_LOCATION_BAR_HTTP: - tint = [UIColor darkGrayColor]; - break; - case IDR_IOS_OMNIBOX_HTTPS_VALID: - tint = skia::UIColorFromSkColor(gfx::kGoogleGreen700); - break; - case IDR_IOS_OMNIBOX_HTTPS_POLICY_WARNING: - tint = skia::UIColorFromSkColor(gfx::kGoogleYellow700); - break; - case IDR_IOS_OMNIBOX_HTTPS_INVALID: - tint = skia::UIColorFromSkColor(gfx::kGoogleRed700); - break; - default: - tint = [UIColor darkGrayColor]; - } - } - return tint; -} - -@end - -#pragma mark - -#pragma mark OmniboxTextFieldIOS - @implementation OmniboxTextFieldIOS { UILabel* _selection; UILabel* _preEditStaticLabel;
diff --git a/ios/chrome/browser/ui/omnibox/omnibox_view_ios.mm b/ios/chrome/browser/ui/omnibox/omnibox_view_ios.mm index 8b7ee12b..47c890a 100644 --- a/ios/chrome/browser/ui/omnibox/omnibox_view_ios.mm +++ b/ios/chrome/browser/ui/omnibox/omnibox_view_ios.mm
@@ -24,6 +24,7 @@ #include "ios/chrome/browser/autocomplete/autocomplete_scheme_classifier_impl.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #include "ios/chrome/browser/ui/omnibox/chrome_omnibox_client_ios.h" +#import "ios/chrome/browser/ui/omnibox/location_bar_view.h" #include "ios/chrome/browser/ui/omnibox/omnibox_text_field_paste_delegate.h" #include "ios/chrome/browser/ui/omnibox/omnibox_util.h" #include "ios/chrome/browser/ui/omnibox/web_omnibox_edit_controller.h"
diff --git a/ios/chrome/browser/ui/settings/settings_collection_view_controller.mm b/ios/chrome/browser/ui/settings/settings_collection_view_controller.mm index f34d58e4..1579436 100644 --- a/ios/chrome/browser/ui/settings/settings_collection_view_controller.mm +++ b/ios/chrome/browser/ui/settings/settings_collection_view_controller.mm
@@ -336,13 +336,6 @@ AuthenticationService* authService = AuthenticationServiceFactory::GetForBrowserState(_browserState); if (!authService->IsAuthenticated()) { - if (!_hasRecordedSigninImpression) { - // Once the Settings are open, this button impression will at most be - // recorded once until they are closed. - base::RecordAction( - base::UserMetricsAction("Signin_Impression_FromSettings")); - _hasRecordedSigninImpression = YES; - } if ([SigninPromoViewMediator shouldDisplaySigninPromoViewWithAccessPoint: signin_metrics::AccessPoint::ACCESS_POINT_SETTINGS @@ -362,6 +355,7 @@ [model addItem:[self signInTextItem] toSectionWithIdentifier:SectionIdentifierSignIn]; } else { + _hasRecordedSigninImpression = NO; [_signinPromoViewMediator signinPromoViewRemoved]; _signinPromoViewMediator = nil; [model addItem:[self accountCellItem] @@ -449,6 +443,13 @@ [_signinPromoViewMediator signinPromoViewVisible]; return signinPromoItem; } + if (!_hasRecordedSigninImpression) { + // Once the Settings are open, this button impression will at most be + // recorded once until they are closed. + base::RecordAction( + base::UserMetricsAction("Signin_Impression_FromSettings")); + _hasRecordedSigninImpression = YES; + } AccountSignInItem* signInTextItem = [[AccountSignInItem alloc] initWithType:ItemTypeSignInButton]; signInTextItem.accessibilityIdentifier = kSettingsSignInCellId;
diff --git a/ios/chrome/browser/ui/tab_switcher/tab_switcher_controller.mm b/ios/chrome/browser/ui/tab_switcher/tab_switcher_controller.mm index 81b827b..427e5b2 100644 --- a/ios/chrome/browser/ui/tab_switcher/tab_switcher_controller.mm +++ b/ios/chrome/browser/ui/tab_switcher/tab_switcher_controller.mm
@@ -392,6 +392,7 @@ tabSwitcherPresentationAnimationDidEnd:self]; [self.delegate tabSwitcherPresentationTransitionDidEnd:self]; + [_tabSwitcherView wasShown]; }]; } @@ -855,6 +856,7 @@ [self.animationDelegate tabSwitcherDismissalAnimationDidEnd:self]; [self.delegate tabSwitcherDismissTransitionDidEnd:self]; + [_tabSwitcherView wasHidden]; }]; }
diff --git a/ios/chrome/browser/ui/tab_switcher/tab_switcher_panel_overlay_view.h b/ios/chrome/browser/ui/tab_switcher/tab_switcher_panel_overlay_view.h index 10edc65..6ea09e80 100644 --- a/ios/chrome/browser/ui/tab_switcher/tab_switcher_panel_overlay_view.h +++ b/ios/chrome/browser/ui/tab_switcher/tab_switcher_panel_overlay_view.h
@@ -44,6 +44,12 @@ presenter:(id<SigninPresenter, SyncPresenter>)presenter dispatcher: (id<ApplicationCommands, BrowserCommands>)dispatcher; + +// Should be called when the tab switcher was shown. +- (void)wasShown; +// Should be called when the tab switcher was hidden. +- (void)wasHidden; + @end #endif // IOS_CHROME_BROWSER_UI_TAB_SWITCHER_TAB_SWITCHER_PANEL_OVERLAY_VIEW_H_
diff --git a/ios/chrome/browser/ui/tab_switcher/tab_switcher_panel_overlay_view.mm b/ios/chrome/browser/ui/tab_switcher/tab_switcher_panel_overlay_view.mm index 3f48c02b..bf4ceac 100644 --- a/ios/chrome/browser/ui/tab_switcher/tab_switcher_panel_overlay_view.mm +++ b/ios/chrome/browser/ui/tab_switcher/tab_switcher_panel_overlay_view.mm
@@ -225,6 +225,14 @@ } } +- (void)wasShown { + [_signinPromoViewMediator signinPromoViewVisible]; +} + +- (void)wasHidden { + [_signinPromoViewMediator signinPromoViewHidden]; +} + #pragma mark - Private // Creates the sign-in view and its mediator if it doesn't exist.
diff --git a/ios/chrome/browser/ui/tab_switcher/tab_switcher_view.h b/ios/chrome/browser/ui/tab_switcher/tab_switcher_view.h index cd33773..a6f680f2f 100644 --- a/ios/chrome/browser/ui/tab_switcher/tab_switcher_view.h +++ b/ios/chrome/browser/ui/tab_switcher/tab_switcher_view.h
@@ -46,6 +46,10 @@ // Overlay buttons are the top right dismiss button and the bottom right new tab // button. - (void)updateOverlayButtonState; +// Should be called when the tab switcher was shown. +- (void)wasShown; +// Should be called when the tab switcher was hidden. +- (void)wasHidden; @end
diff --git a/ios/chrome/browser/ui/tab_switcher/tab_switcher_view.mm b/ios/chrome/browser/ui/tab_switcher/tab_switcher_view.mm index 177f706..b4ad5b6c 100644 --- a/ios/chrome/browser/ui/tab_switcher/tab_switcher_view.mm +++ b/ios/chrome/browser/ui/tab_switcher/tab_switcher_view.mm
@@ -130,6 +130,14 @@ [UIView commitAnimations]; } +- (void)wasShown { + [self currentPanelWasShown]; +} + +- (void)wasHidden { + [self panelWasHiddenAtIndex:self.currentPageIndex]; +} + #pragma mark - Private - (void)selectPanelAtIndex:(NSInteger)index animated:(BOOL)animated { @@ -320,18 +328,26 @@ [self updateOverlayButtonState]; NSInteger panelIndex = [self currentPanelIndex]; - TabSwitcherPanelOverlayView* overlayView = - base::mac::ObjCCast<TabSwitcherPanelOverlayView>( - [_panels objectAtIndex:panelIndex]); - if (panelIndex != _previousPanelIndex && overlayView && - [overlayView overlayType] == - TabSwitcherPanelOverlayType::OVERLAY_PANEL_USER_SIGNED_OUT) { - base::RecordAction( - base::UserMetricsAction("Signin_Impression_FromTabSwitcher")); + if (panelIndex != _previousPanelIndex) { + if (_previousPanelIndex != -1) + [self panelWasHiddenAtIndex:_previousPanelIndex]; + [self currentPanelWasShown]; } _previousPanelIndex = panelIndex; } +- (void)panelWasHiddenAtIndex:(NSInteger)index { + id panel = [_panels objectAtIndex:index]; + if ([panel respondsToSelector:@selector(wasHidden)]) + [panel wasHidden]; +} + +- (void)currentPanelWasShown { + id panel = [_panels objectAtIndex:self.currentPanelIndex]; + if ([panel respondsToSelector:@selector(wasShown)]) + [panel wasShown]; +} + #pragma mark - UIScrollViewAccessibilityDelegate - (NSString*)accessibilityScrollStatusForScrollView:(UIScrollView*)scrollView {
diff --git a/ios/chrome/browser/ui/toolbar/clean/BUILD.gn b/ios/chrome/browser/ui/toolbar/clean/BUILD.gn index fa765eb..454be0f 100644 --- a/ios/chrome/browser/ui/toolbar/clean/BUILD.gn +++ b/ios/chrome/browser/ui/toolbar/clean/BUILD.gn
@@ -27,6 +27,7 @@ "//ios/chrome/browser/reading_list", "//ios/chrome/browser/search_engines", "//ios/chrome/browser/ui", + "//ios/chrome/browser/ui/bookmarks", "//ios/chrome/browser/ui/broadcaster", "//ios/chrome/browser/ui/browser_list", "//ios/chrome/browser/ui/commands", @@ -116,11 +117,16 @@ ":toolbar_ui", "//base", "//base/test:test_support", + "//components/bookmarks/browser", + "//components/bookmarks/test", + "//ios/chrome/browser/bookmarks", + "//ios/chrome/browser/browser_state:test_support", "//ios/chrome/browser/ui/toolbar/test", "//ios/chrome/browser/web_state_list", "//ios/chrome/browser/web_state_list:test_support", "//ios/public/provider/chrome/browser/voice", "//ios/web", + "//ios/web/public/test", "//ios/web/public/test/fakes", "//testing/gtest", "//third_party/ocmock",
diff --git a/ios/chrome/browser/ui/toolbar/clean/toolbar_consumer.h b/ios/chrome/browser/ui/toolbar/clean/toolbar_consumer.h index feef29a9..eae32c7 100644 --- a/ios/chrome/browser/ui/toolbar/clean/toolbar_consumer.h +++ b/ios/chrome/browser/ui/toolbar/clean/toolbar_consumer.h
@@ -23,6 +23,8 @@ - (void)setPageBookmarked:(BOOL)bookmarked; // Sets whether the voice search is enabled or not. - (void)setVoiceSearchEnabled:(BOOL)enabled; +// Sets whether the share menu is enabled. +- (void)setShareMenuEnabled:(BOOL)enabled; @end #endif // IOS_CHROME_BROWSER_UI_TOOLBAR_CLEAN_TOOLBAR_CONSUMER_H_
diff --git a/ios/chrome/browser/ui/toolbar/clean/toolbar_coordinator.mm b/ios/chrome/browser/ui/toolbar/clean/toolbar_coordinator.mm index 0d81fa3..b24d5b4 100644 --- a/ios/chrome/browser/ui/toolbar/clean/toolbar_coordinator.mm +++ b/ios/chrome/browser/ui/toolbar/clean/toolbar_coordinator.mm
@@ -23,6 +23,7 @@ #include "ios/chrome/browser/ui/omnibox/location_bar_controller.h" #include "ios/chrome/browser/ui/omnibox/location_bar_controller_impl.h" #include "ios/chrome/browser/ui/omnibox/location_bar_delegate.h" +#include "ios/chrome/browser/ui/omnibox/location_bar_view.h" #import "ios/chrome/browser/ui/omnibox/omnibox_popup_positioner.h" #include "ios/chrome/browser/ui/omnibox/omnibox_popup_view_ios.h" #import "ios/chrome/browser/ui/omnibox/omnibox_text_field_ios.h"
diff --git a/ios/chrome/browser/ui/toolbar/clean/toolbar_mediator.mm b/ios/chrome/browser/ui/toolbar/clean/toolbar_mediator.mm index a30e71d4..d93ea3c 100644 --- a/ios/chrome/browser/ui/toolbar/clean/toolbar_mediator.mm +++ b/ios/chrome/browser/ui/toolbar/clean/toolbar_mediator.mm
@@ -8,11 +8,13 @@ #include "base/scoped_observer.h" #include "base/strings/sys_string_conversions.h" #include "components/bookmarks/browser/bookmark_model.h" +#include "ios/chrome/browser/ui/bookmarks/bookmark_model_bridge_observer.h" #import "ios/chrome/browser/ui/toolbar/clean/toolbar_consumer.h" #import "ios/chrome/browser/web_state_list/web_state_list.h" #import "ios/chrome/browser/web_state_list/web_state_list_observer_bridge.h" #import "ios/public/provider/chrome/browser/voice/voice_search_provider.h" #import "ios/web/public/navigation_manager.h" +#import "ios/web/public/web_client.h" #include "ios/web/public/web_state/web_state.h" #import "ios/web/public/web_state/web_state_observer_bridge.h" @@ -20,7 +22,9 @@ #error "This file requires ARC support." #endif -@interface ToolbarMediator ()<CRWWebStateObserver, WebStateListObserving> +@interface ToolbarMediator ()<BookmarkModelBridgeObserver, + CRWWebStateObserver, + WebStateListObserving> // The current web state associated with the toolbar. @property(nonatomic, assign) web::WebState* webState; @@ -30,6 +34,8 @@ @implementation ToolbarMediator { std::unique_ptr<web::WebStateObserverBridge> _webStateObserver; std::unique_ptr<WebStateListObserverBridge> _webStateListObserver; + // Bridge to register for bookmark changes. + std::unique_ptr<bookmarks::BookmarkModelBridge> _bookmarkModelBridge; } @synthesize bookmarkModel = _bookmarkModel; @@ -69,6 +75,7 @@ _webStateObserver.reset(); _webState = nullptr; } + _bookmarkModelBridge.reset(); } #pragma mark - CRWWebStateObserver @@ -202,6 +209,11 @@ if (self.webState && self.consumer) { [self updateConsumer]; } + _bookmarkModelBridge.reset(); + if (bookmarkModel) { + _bookmarkModelBridge = + std::make_unique<bookmarks::BookmarkModelBridge>(self, bookmarkModel); + } } #pragma mark - Helper methods @@ -212,9 +224,8 @@ DCHECK(self.consumer); [self updateConsumerForWebState:self.webState]; [self.consumer setIsLoading:self.webState->IsLoading()]; - [self.consumer setPageBookmarked:self.bookmarkModel && - self.bookmarkModel->IsBookmarked( - self.webState->GetLastCommittedURL())]; + [self updateBookmarks]; + [self updateShareMenu]; } // Updates the consumer with the new forward and back states. @@ -226,4 +237,54 @@ [self.consumer setCanGoBack:webState->GetNavigationManager()->CanGoBack()]; } +// Updates the bookmark state of the consumer. +- (void)updateBookmarks { + if (self.webState) { + GURL URL = self.webState->GetVisibleURL(); + [self.consumer setPageBookmarked:self.bookmarkModel && + self.bookmarkModel->IsBookmarked(URL)]; + } +} + +// Uodates the Share Menu button of the consumer. +- (void)updateShareMenu { + const GURL& URL = self.webState->GetLastCommittedURL(); + BOOL shareMenuEnabled = + URL.is_valid() && !web::GetWebClient()->IsAppSpecificURL(URL); + [self.consumer setShareMenuEnabled:shareMenuEnabled]; +} + +#pragma mark - BookmarkModelBridgeObserver + +// If an added or removed bookmark is the same as the current url, update the +// toolbar so the star highlight is kept in sync. +- (void)bookmarkNodeChildrenChanged: + (const bookmarks::BookmarkNode*)bookmarkNode { + [self updateBookmarks]; +} + +// If all bookmarks are removed, update the toolbar so the star highlight is +// kept in sync. +- (void)bookmarkModelRemovedAllNodes { + [self updateBookmarks]; +} + +// In case we are on a bookmarked page before the model is loaded. +- (void)bookmarkModelLoaded { + [self updateBookmarks]; +} + +- (void)bookmarkNodeChanged:(const bookmarks::BookmarkNode*)bookmarkNode { + // No-op -- required by BookmarkModelBridgeObserver but not used. +} +- (void)bookmarkNode:(const bookmarks::BookmarkNode*)bookmarkNode + movedFromParent:(const bookmarks::BookmarkNode*)oldParent + toParent:(const bookmarks::BookmarkNode*)newParent { + // No-op -- required by BookmarkModelBridgeObserver but not used. +} +- (void)bookmarkNodeDeleted:(const bookmarks::BookmarkNode*)node + fromFolder:(const bookmarks::BookmarkNode*)folder { + // No-op -- required by BookmarkModelBridgeObserver but not used. +} + @end
diff --git a/ios/chrome/browser/ui/toolbar/clean/toolbar_mediator_unittest.mm b/ios/chrome/browser/ui/toolbar/clean/toolbar_mediator_unittest.mm index 7bb5221..cc74a99 100644 --- a/ios/chrome/browser/ui/toolbar/clean/toolbar_mediator_unittest.mm +++ b/ios/chrome/browser/ui/toolbar/clean/toolbar_mediator_unittest.mm
@@ -5,6 +5,12 @@ #import "ios/chrome/browser/ui/toolbar/clean/toolbar_mediator.h" #include "base/memory/ptr_util.h" +#include "base/strings/sys_string_conversions.h" +#include "components/bookmarks/browser/bookmark_model.h" +#include "components/bookmarks/browser/bookmark_node.h" +#include "components/bookmarks/test/bookmark_test_helpers.h" +#include "ios/chrome/browser/bookmarks/bookmark_model_factory.h" +#include "ios/chrome/browser/browser_state/test_chrome_browser_state.h" #import "ios/chrome/browser/ui/toolbar/clean/toolbar_consumer.h" #import "ios/chrome/browser/ui/toolbar/test/toolbar_test_navigation_manager.h" #import "ios/chrome/browser/ui/toolbar/test/toolbar_test_web_state.h" @@ -15,6 +21,7 @@ #import "ios/public/provider/chrome/browser/voice/voice_search_provider.h" #import "ios/web/public/test/fakes/test_navigation_manager.h" #import "ios/web/public/test/fakes/test_web_state.h" +#include "ios/web/public/test/test_web_thread_bundle.h" #import "ios/web/public/web_state/web_state_observer_bridge.h" #include "testing/platform_test.h" #import "third_party/ocmock/OCMock/OCMock.h" @@ -24,6 +31,9 @@ #error "This file requires ARC support." #endif +using bookmarks::BookmarkNode; +using bookmarks::BookmarkModel; + namespace { class MockEnabledVoiceSearchProvider : public VoiceSearchProvider { bool IsVoiceSearchEnabled() const override { return true; } @@ -41,10 +51,17 @@ static const int kNumberOfWebStates = 3; static const char kTestUrl[] = "http://www.chromium.org"; +static const char kTestUrl2[] = "http://www.notChromium.org"; class ToolbarMediatorTest : public PlatformTest { public: ToolbarMediatorTest() { + TestChromeBrowserState::Builder test_cbs_builder; + chrome_browser_state_ = test_cbs_builder.Build(); + chrome_browser_state_->CreateBookmarkModel(false); + bookmark_model_ = ios::BookmarkModelFactory::GetForBrowserState( + chrome_browser_state_.get()); + bookmarks::test::WaitForBookmarkModelToLoad(bookmark_model_); std::unique_ptr<ToolbarTestNavigationManager> navigation_manager = base::MakeUnique<ToolbarTestNavigationManager>(); navigation_manager_ = navigation_manager.get(); @@ -54,6 +71,7 @@ web_state_ = test_web_state_.get(); mediator_ = [[TestToolbarMediator alloc] init]; consumer_ = OCMProtocolMock(@protocol(ToolbarConsumer)); + strict_consumer_ = OCMStrictProtocolMock(@protocol(ToolbarConsumer)); SetUpWebStateList(); } @@ -62,6 +80,7 @@ ~ToolbarMediatorTest() override { [mediator_ disconnect]; } protected: + web::TestWebThreadBundle thread_bundle_; void SetUpWebStateList() { web_state_list_ = base::MakeUnique<WebStateList>(&web_state_list_delegate_); web_state_list_->InsertWebState(0, std::move(test_web_state_), @@ -72,6 +91,15 @@ } } + void SetUpBookmarks() { + bookmark_model_ = ios::BookmarkModelFactory::GetForBrowserState( + chrome_browser_state_.get()); + GURL URL = GURL(kTestUrl); + const BookmarkNode* defaultFolder = bookmark_model_->mobile_node(); + bookmark_model_->AddURL(defaultFolder, defaultFolder->child_count(), + base::SysNSStringToUTF16(@"Test bookmark 1"), URL); + } + void InsertNewWebState(int index) { auto web_state = base::MakeUnique<web::TestWebState>(); GURL url("http://test/" + std::to_string(index)); @@ -89,11 +117,126 @@ std::unique_ptr<WebStateList> web_state_list_; FakeWebStateListDelegate web_state_list_delegate_; id consumer_; + id strict_consumer_; + std::unique_ptr<TestChromeBrowserState> chrome_browser_state_; + BookmarkModel* bookmark_model_; private: std::unique_ptr<ToolbarTestWebState> test_web_state_; }; +// Test that the consumer bookmarks status is only updated when the page is +// added to the bookmark model. +TEST_F(ToolbarMediatorTest, TestToolbarAddedToBookmarks) { + web_state_->SetCurrentURL(GURL(kTestUrl)); + mediator_.webStateList = web_state_list_.get(); + SetUpActiveWebState(); + mediator_.consumer = consumer_; + mediator_.bookmarkModel = bookmark_model_; + + // Add a different bookmark and verify it is not set as bookmarked. + OCMExpect([consumer_ setPageBookmarked:NO]); + bookmark_model_ = ios::BookmarkModelFactory::GetForBrowserState( + chrome_browser_state_.get()); + GURL URL = GURL(kTestUrl2); + const BookmarkNode* defaultFolder = bookmark_model_->mobile_node(); + bookmark_model_->AddURL(defaultFolder, defaultFolder->child_count(), + base::SysNSStringToUTF16(@"Test bookmark 1"), URL); + EXPECT_OCMOCK_VERIFY(consumer_); + + // Bookmark the page and check it is set. + OCMExpect([consumer_ setPageBookmarked:YES]); + bookmark_model_ = ios::BookmarkModelFactory::GetForBrowserState( + chrome_browser_state_.get()); + URL = GURL(kTestUrl); + bookmark_model_->AddURL(defaultFolder, defaultFolder->child_count(), + base::SysNSStringToUTF16(@"Test bookmark 2"), URL); + + EXPECT_OCMOCK_VERIFY(consumer_); + bookmark_model_->RemoveAllUserBookmarks(); +} + +// Test that the consumer bookmarks status is only updated when the page is +// removed from the bookmark model. +TEST_F(ToolbarMediatorTest, TestToolbarRemovedFromBookmarks) { + SetUpBookmarks(); + bookmark_model_ = ios::BookmarkModelFactory::GetForBrowserState( + chrome_browser_state_.get()); + GURL URL = GURL(kTestUrl2); + const BookmarkNode* defaultFolder = bookmark_model_->mobile_node(); + bookmark_model_->AddURL(defaultFolder, defaultFolder->child_count(), + base::SysNSStringToUTF16(@"Test bookmark 1"), URL); + web_state_->SetCurrentURL(GURL(kTestUrl)); + mediator_.webStateList = web_state_list_.get(); + SetUpActiveWebState(); + mediator_.consumer = consumer_; + mediator_.bookmarkModel = bookmark_model_; + + // Removes another bookmark and check it is still bookmarked. + OCMExpect([consumer_ setPageBookmarked:YES]); + std::vector<const BookmarkNode*> vec; + bookmark_model_->GetNodesByURL(GURL(kTestUrl2), &vec); + bookmark_model_->Remove(vec.front()); + EXPECT_OCMOCK_VERIFY(consumer_); + vec.clear(); + + // Removes the page from the bookmarks and check it is updated. + OCMExpect([consumer_ setPageBookmarked:NO]); + bookmark_model_->GetNodesByURL(GURL(kTestUrl), &vec); + bookmark_model_->Remove(vec.front()); + EXPECT_OCMOCK_VERIFY(consumer_); + bookmark_model_->RemoveAllUserBookmarks(); +} + +// Test that the consumer bookmarks status is updated when the page is +// bookmarked. +TEST_F(ToolbarMediatorTest, TestToolbarBookmarked) { + SetUpBookmarks(); + OCMExpect([consumer_ setPageBookmarked:YES]); + + web_state_->SetCurrentURL(GURL(kTestUrl)); + mediator_.bookmarkModel = bookmark_model_; + mediator_.webStateList = web_state_list_.get(); + SetUpActiveWebState(); + mediator_.consumer = consumer_; + + EXPECT_OCMOCK_VERIFY(consumer_); + bookmark_model_->RemoveAllUserBookmarks(); +} + +// Test that the consumer bookmarks status is updated when the page is +// bookmarked, when the bookmarkModel is set last. +TEST_F(ToolbarMediatorTest, TestToolbarBookmarkedModelSetLast) { + SetUpBookmarks(); + OCMExpect([consumer_ setPageBookmarked:NO]); + OCMExpect([consumer_ setShareMenuEnabled:YES]); + + web_state_->SetCurrentURL(GURL(kTestUrl)); + mediator_.webStateList = web_state_list_.get(); + SetUpActiveWebState(); + mediator_.consumer = consumer_; + mediator_.bookmarkModel = bookmark_model_; + + EXPECT_OCMOCK_VERIFY(consumer_); + bookmark_model_->RemoveAllUserBookmarks(); +} + +// Test that the consumer bookmarks status is updated when the page is +// NOT bookmarked. +TEST_F(ToolbarMediatorTest, TestToolbarNotBookmarked) { + SetUpBookmarks(); + OCMExpect([consumer_ setPageBookmarked:NO]); + + web_state_->SetCurrentURL(GURL(kTestUrl2)); + mediator_.bookmarkModel = bookmark_model_; + mediator_.webStateList = web_state_list_.get(); + SetUpActiveWebState(); + mediator_.consumer = consumer_; + + EXPECT_OCMOCK_VERIFY(consumer_); + bookmark_model_->RemoveAllUserBookmarks(); +} + // Test no setup is being done on the Toolbar if there's no Webstate. TEST_F(ToolbarMediatorTest, TestToolbarSetupWithNoWebstate) { mediator_.consumer = consumer_; @@ -105,12 +248,15 @@ // Test no setup is being done on the Toolbar if there's no active Webstate. TEST_F(ToolbarMediatorTest, TestToolbarSetupWithNoActiveWebstate) { + SetUpBookmarks(); mediator_.webStateList = web_state_list_.get(); mediator_.consumer = consumer_; + mediator_.bookmarkModel = bookmark_model_; [[consumer_ reject] setCanGoForward:NO]; [[consumer_ reject] setCanGoBack:NO]; [[consumer_ reject] setIsLoading:YES]; + [[consumer_ reject] setPageBookmarked:NO]; } // Test no WebstateList related setup is being done on the Toolbar if there's no @@ -131,6 +277,7 @@ [[consumer_ verify] setCanGoForward:NO]; [[consumer_ verify] setCanGoBack:NO]; [[consumer_ verify] setIsLoading:YES]; + [[consumer_ verify] setShareMenuEnabled:NO]; } // Test the Toolbar Setup gets called when the mediator's WebState and Consumer @@ -143,6 +290,7 @@ [[consumer_ verify] setCanGoForward:NO]; [[consumer_ verify] setCanGoBack:NO]; [[consumer_ verify] setIsLoading:YES]; + [[consumer_ verify] setShareMenuEnabled:NO]; } // Test the WebstateList related setup gets called when the mediator's WebState @@ -191,9 +339,11 @@ // Test the Toolbar is updated when the Webstate observer method // DidLoadPageWithSuccess is triggered by OnPageLoaded. TEST_F(ToolbarMediatorTest, TestDidLoadPageWithSucess) { + SetUpBookmarks(); mediator_.webStateList = web_state_list_.get(); SetUpActiveWebState(); mediator_.consumer = consumer_; + mediator_.bookmarkModel = bookmark_model_; navigation_manager_->set_can_go_forward(true); navigation_manager_->set_can_go_back(true); @@ -203,6 +353,8 @@ [[consumer_ verify] setCanGoForward:YES]; [[consumer_ verify] setCanGoBack:YES]; + [[consumer_ verify] setPageBookmarked:YES]; + [[consumer_ verify] setShareMenuEnabled:YES]; } // Test the Toolbar is updated when the Webstate observer method
diff --git a/ios/chrome/browser/ui/toolbar/clean/toolbar_view_controller.mm b/ios/chrome/browser/ui/toolbar/clean/toolbar_view_controller.mm index bde5f7c..2be87a2 100644 --- a/ios/chrome/browser/ui/toolbar/clean/toolbar_view_controller.mm +++ b/ios/chrome/browser/ui/toolbar/clean/toolbar_view_controller.mm
@@ -461,6 +461,10 @@ } } +- (void)setShareMenuEnabled:(BOOL)enabled { + self.shareButton.enabled = enabled; +} + #pragma mark - ActivityServicePositioner - (UIView*)shareButtonView {
diff --git a/ios/chrome/browser/ui/toolbar/toolbar_adapter.mm b/ios/chrome/browser/ui/toolbar/toolbar_adapter.mm index 6ae040d8..80e776b9 100644 --- a/ios/chrome/browser/ui/toolbar/toolbar_adapter.mm +++ b/ios/chrome/browser/ui/toolbar/toolbar_adapter.mm
@@ -94,7 +94,7 @@ #pragma mark - Abstract Toolbar - (void)setShareButtonEnabled:(BOOL)enabled { - return; + // No op. } - (void)triggerToolsMenuButtonAnimation {
diff --git a/ios/chrome/browser/ui/toolbar/web_toolbar_controller.mm b/ios/chrome/browser/ui/toolbar/web_toolbar_controller.mm index 62d7b09c..2e9a0468 100644 --- a/ios/chrome/browser/ui/toolbar/web_toolbar_controller.mm +++ b/ios/chrome/browser/ui/toolbar/web_toolbar_controller.mm
@@ -48,6 +48,7 @@ #include "ios/chrome/browser/ui/omnibox/location_bar_controller.h" #include "ios/chrome/browser/ui/omnibox/location_bar_controller_impl.h" #include "ios/chrome/browser/ui/omnibox/location_bar_delegate.h" +#include "ios/chrome/browser/ui/omnibox/location_bar_view.h" #include "ios/chrome/browser/ui/omnibox/omnibox_popup_view_ios.h" #include "ios/chrome/browser/ui/omnibox/omnibox_view_ios.h" #import "ios/chrome/browser/ui/popup_menu/popup_menu_view.h"
diff --git a/ios/chrome/browser/web/progress_indicator_egtest.mm b/ios/chrome/browser/web/progress_indicator_egtest.mm index 00d1263..08dc876 100644 --- a/ios/chrome/browser/web/progress_indicator_egtest.mm +++ b/ios/chrome/browser/web/progress_indicator_egtest.mm
@@ -72,7 +72,7 @@ } // Response provider that serves the page which never finishes loading. -// TODO(crbug.com/638674): Evaluate if this can move to shared code. +// TODO(crbug.com/708307): Convert this to Embedded Test Server. class InfinitePendingResponseProvider : public HtmlResponseProvider { public: explicit InfinitePendingResponseProvider(const GURL& url)
diff --git a/ios/chrome/browser/web/resources/payment_request.js b/ios/chrome/browser/web/resources/payment_request.js index d0c55a6..b36821d1 100644 --- a/ios/chrome/browser/web/resources/payment_request.js +++ b/ios/chrome/browser/web/resources/payment_request.js
@@ -180,15 +180,13 @@ */ __gCrWeb['paymentRequestManager'].validatePaymentCurrencyAmount = function( amount, amountName) { - if (typeof amount.value !== 'string') - throw new TypeError(amountName + ' value must be a string'); - if (amount.value.length > - __gCrWeb['paymentRequestManager'].MAX_STRING_LENGTH) { + var value = String(amount.value); + if (value > __gCrWeb['paymentRequestManager'].MAX_STRING_LENGTH) { throw new TypeError( amountName + ' value cannot be longer than ' + __gCrWeb['paymentRequestManager'].MAX_STRING_LENGTH + ' characters'); } - if (!/^-?[0-9]+(\.[0-9]+)?$/.test(amount.value)) { + if (!/^-?[0-9]+(\.[0-9]+)?$/.test(value)) { throw new TypeError( amountName + ' value is not a valid decimal monetary value'); } @@ -402,7 +400,7 @@ if (typeof modifiers[i].total !== 'undefined') { __gCrWeb['paymentRequestManager'].validatePaymentItem( modifiers[i].total, 'Modifier total'); - if (modifiers[i].total.amount.value[0] == '-') + if (String(modifiers[i].total.amount.value)[0] == '-') throw new TypeError('Modifier total value should be non-negative'); } @@ -531,7 +529,7 @@ throw new TypeError('Total is missing.'); __gCrWeb['paymentRequestManager'].validatePaymentItem( details.total, 'Total'); - if (details.total.amount.value[0] == '-') + if (String(details.total.amount.value)[0] == '-') throw new TypeError('Total value should be non-negative'); return __gCrWeb['paymentRequestManager'].validatePaymentDetailsBase( @@ -552,7 +550,7 @@ if (details.total) { __gCrWeb['paymentRequestManager'].validatePaymentItem( details.total, 'Total'); - if (details.total.amount.value[0] == '-') + if (String(details.total.amount.value)[0] == '-') throw new TypeError('Total value should be non-negative'); }
diff --git a/ios/chrome/browser/web/stop_loading_egtest.mm b/ios/chrome/browser/web/stop_loading_egtest.mm index 889ff28..72cba25 100644 --- a/ios/chrome/browser/web/stop_loading_egtest.mm +++ b/ios/chrome/browser/web/stop_loading_egtest.mm
@@ -30,6 +30,7 @@ const char kPageText[] = "Navigation testing page"; // Response provider that serves the page which never finishes loading. +// TODO(crbug.com/708307): Convert this to Embedded Test Server. class InfinitePendingResponseProvider : public HtmlResponseProvider { public: explicit InfinitePendingResponseProvider(const GURL& url) : url_(url) {}
diff --git a/ios/chrome/test/earl_grey/device_check_egtest.mm b/ios/chrome/test/earl_grey/device_check_egtest.mm index c71fd61..e9f596f 100644 --- a/ios/chrome/test/earl_grey/device_check_egtest.mm +++ b/ios/chrome/test/earl_grey/device_check_egtest.mm
@@ -20,9 +20,6 @@ // Verifies Internet connectivity by navigating to browsingtest.appspot.com. - (void)testNetworkConnection { - // TODO(crbug.com/763582) Remove EARL_GREY_TEST_DISABLED if - // wifi tests running. - EARL_GREY_TEST_DISABLED(@"Test disabled due to Wifi issue."); [ChromeEarlGrey loadURL:GURL("http://browsingtest.appspot.com")]; [ChromeEarlGrey waitForWebViewContainingText:"Window1"]; }
diff --git a/ios/web/web_state/crw_pass_kit_downloader.h b/ios/web/web_state/crw_pass_kit_downloader.h index 674bb22..290525c 100644 --- a/ios/web/web_state/crw_pass_kit_downloader.h +++ b/ios/web/web_state/crw_pass_kit_downloader.h
@@ -25,6 +25,7 @@ // CRWPassKitDownloader downloads PassKit data and passes it to a completion // handler. +// DEPRECATED - Do not use this class. http://crbug.com/787943 @interface CRWPassKitDownloader : NSObject // Initializes the CRWPassKitDownloader. |getter| must not be null and
diff --git a/ios/web/web_state/crw_pass_kit_downloader.mm b/ios/web/web_state/crw_pass_kit_downloader.mm index f07ce29..779e70f 100644 --- a/ios/web/web_state/crw_pass_kit_downloader.mm +++ b/ios/web/web_state/crw_pass_kit_downloader.mm
@@ -6,10 +6,12 @@ #include <memory> +#include "base/feature_list.h" #include "base/mac/scoped_block.h" #include "base/macros.h" #include "base/metrics/histogram_macros.h" #include "base/strings/sys_string_conversions.h" +#include "ios/web/public/features.h" #include "net/http/http_response_headers.h" #include "net/url_request/url_fetcher.h" #include "net/url_request/url_fetcher_delegate.h" @@ -97,6 +99,7 @@ - (instancetype)initWithContextGetter:(net::URLRequestContextGetter*)getter completionHandler:(web::PassKitCompletionHandler)handler { + DCHECK(!base::FeatureList::IsEnabled(web::features::kNewPassKitDownload)); self = [super init]; if (self) { DCHECK(getter);
diff --git a/ios/web/web_state/ui/crw_web_controller.mm b/ios/web/web_state/ui/crw_web_controller.mm index 48c7b3b4..637bad52 100644 --- a/ios/web/web_state/ui/crw_web_controller.mm +++ b/ios/web/web_state/ui/crw_web_controller.mm
@@ -16,6 +16,7 @@ #include "base/callback.h" #include "base/containers/mru_cache.h" +#include "base/feature_list.h" #import "base/ios/block_types.h" #include "base/ios/ios_util.h" #import "base/ios/ns_error_util.h" @@ -49,6 +50,7 @@ #include "ios/web/public/browser_state.h" #import "ios/web/public/download/download_controller.h" #include "ios/web/public/favicon_url.h" +#include "ios/web/public/features.h" #import "ios/web/public/java_script_dialog_presenter.h" #import "ios/web/public/navigation_item.h" #import "ios/web/public/navigation_manager.h" @@ -429,6 +431,7 @@ // changed. @property(weak, nonatomic, readonly) NSDictionary* WKWebViewObservers; // Downloader for PassKit files. Lazy initialized. +// DEPRECATED - Do not use this property. http://crbug.com/787943 @property(weak, nonatomic, readonly) CRWPassKitDownloader* passKitDownloader; // The web view's view of the current URL. During page transitions @@ -1941,7 +1944,9 @@ } - (void)loadCancelled { - [_passKitDownloader cancelPendingDownload]; + if (!base::FeatureList::IsEnabled(web::features::kNewPassKitDownload)) { + [_passKitDownloader cancelPendingDownload]; + } if (_loadPhase != web::PAGE_LOADED) { _loadPhase = web::PAGE_LOADED; if (!_isHalted) { @@ -2123,6 +2128,7 @@ } - (CRWPassKitDownloader*)passKitDownloader { + DCHECK(!base::FeatureList::IsEnabled(web::features::kNewPassKitDownload)); if (_passKitDownloader) { return _passKitDownloader; } @@ -2908,8 +2914,10 @@ - (void)handleLoadError:(NSError*)error forNavigation:(WKNavigation*)navigation { NSString* MIMEType = [_pendingNavigationInfo MIMEType]; - if ([_passKitDownloader isMIMETypePassKitType:MIMEType]) + if (!base::FeatureList::IsEnabled(web::features::kNewPassKitDownload) && + [_passKitDownloader isMIMETypePassKitType:MIMEType]) { return; + } if ([error code] == NSURLErrorUnsupportedURL) return; // In cases where a Plug-in handles the load do not take any further action. @@ -2936,34 +2944,47 @@ [_navigationStates contextForNavigation:navigation]; navigationContext->SetError(error); - // Handles Frame Load Interrupted errors from WebView. if ([error.domain isEqual:base::SysUTF8ToNSString(web::kWebKitErrorDomain)] && error.code == web::kWebKitErrorFrameLoadInterruptedByPolicyChange) { + // Handle Frame Load Interrupted errors from WebView. This block is executed + // when web controller rejected the load inside + // decidePolicyForNavigationAction: or decidePolicyForNavigationResponse:. + // Load rejection may happen if embedder denied the load via + // WebStatePolicyDecider or the navigation was a download navigation. NSString* errorURLSpec = error.userInfo[NSURLErrorFailingURLStringErrorKey]; NSURL* errorURL = [NSURL URLWithString:errorURLSpec]; - const GURL errorGURL = net::GURLWithNSURL(errorURL); - - // See if the delegate wants to handle this case. - if (errorGURL.is_valid() && - [_delegate - respondsToSelector:@selector( - controllerForUnhandledContentAtURL:)]) { - id<CRWNativeContent> controller = - [_delegate controllerForUnhandledContentAtURL:errorGURL]; - if (controller) { - [self loadCompleteWithSuccess:NO forNavigation:navigation]; - [self removeWebView]; - [self setNativeController:controller]; - [self loadNativeViewWithSuccess:YES - navigationContext:navigationContext]; - return; + if (!base::FeatureList::IsEnabled(web::features::kNewFileDownload) && + ![MIMEType isEqualToString:@"application/vnd.apple.pkpass"]) { + // This block is executed to handle legacy download navigation. + const GURL errorGURL = net::GURLWithNSURL(errorURL); + if (errorGURL.is_valid() && + [_delegate respondsToSelector:@selector + (controllerForUnhandledContentAtURL:)]) { + id<CRWNativeContent> controller = + [_delegate controllerForUnhandledContentAtURL:errorGURL]; + if (controller) { + [self loadCompleteWithSuccess:NO forNavigation:navigation]; + [self removeWebView]; + [self setNativeController:controller]; + [self loadNativeViewWithSuccess:YES + navigationContext:navigationContext]; + return; + } } } - // Ignore errors that originate from URLs that are opened in external apps. + // The load was rejected, because embedder launched an external application. if ([_openedApplicationURL containsObject:errorURL]) return; + if (base::FeatureList::IsEnabled(web::features::kNewPassKitDownload) || + base::FeatureList::IsEnabled(web::features::kNewFileDownload)) { + // This navigation was a download navigation and embedder now has a chance + // to start the download task. + _webStateImpl->SetIsLoading(false); + return; + } + // The wrapper error uses the URL of the error and not the requested URL // (which can be different in case of a redirect) to match desktop Chrome // behavior. @@ -4285,24 +4306,32 @@ ->CreateDownloadTask(_webStateImpl, [NSUUID UUID].UUIDString, responseURL, contentDisposition, contentLength, base::SysNSStringToUTF8(MIMEType)); - } - if ([self.passKitDownloader isMIMETypePassKitType:MIMEType]) { - [self.passKitDownloader downloadPassKitFileWithURL:responseURL]; - allowNavigation = NO; - // Discard the pending PassKit entry to ensure that the current URL is not - // different from what is displayed on the view. If there is no previous - // committed URL, which can happen when a link is opened in a new tab via a - // context menu or window.open, the pending entry should not be - // discarded so that the NavigationManager is never empty. Also, URLs loaded - // in a native view should be excluded to avoid an ugly animation where the - // web view is inserted and quickly removed. - GURL lastCommittedURL = self.webState->GetLastCommittedURL(); - BOOL isFirstLoad = lastCommittedURL.is_empty(); - BOOL previousItemWasLoadedInNativeView = - [self shouldLoadURLInNativeView:lastCommittedURL]; - if (!isFirstLoad && !previousItemWasLoadedInNativeView) - self.navigationManagerImpl->DiscardNonCommittedItems(); + BOOL downloadItem = + (base::FeatureList::IsEnabled(web::features::kNewPassKitDownload) || + base::FeatureList::IsEnabled(web::features::kNewFileDownload)); + + if (!base::FeatureList::IsEnabled(web::features::kNewPassKitDownload) && + [self.passKitDownloader isMIMETypePassKitType:MIMEType]) { + [self.passKitDownloader downloadPassKitFileWithURL:responseURL]; + downloadItem = YES; + } + + if (downloadItem) { + // Discard the pending item to ensure that the current URL is not + // different from what is displayed on the view. If there is no previous + // committed URL, which can happen when a link is opened in a new tab via + // a context menu or window.open, the pending entry should not be + // discarded so that the NavigationManager is never empty. Also, URLs + // loaded in a native view should be excluded to avoid an ugly animation + // where the web view is inserted and quickly removed. + GURL lastCommittedURL = self.webState->GetLastCommittedURL(); + BOOL isFirstLoad = lastCommittedURL.is_empty(); + BOOL previousItemWasLoadedInNativeView = + [self shouldLoadURLInNativeView:lastCommittedURL]; + if (!isFirstLoad && !previousItemWasLoadedInNativeView) + self.navigationManagerImpl->DiscardNonCommittedItems(); + } } handler(allowNavigation ? WKNavigationResponsePolicyAllow
diff --git a/ios/web/webui/web_ui_ios_data_source_impl.mm b/ios/web/webui/web_ui_ios_data_source_impl.mm index 4acc85f..0deec0e 100644 --- a/ios/web/webui/web_ui_ios_data_source_impl.mm +++ b/ios/web/webui/web_ui_ios_data_source_impl.mm
@@ -57,7 +57,8 @@ return parent_->deny_xframe_options_; } bool IsGzipped(const std::string& path) const override { - return parent_->use_gzip_; + return parent_->use_gzip_ && + (parent_->json_path_.empty() || path != parent_->json_path_); } private:
diff --git a/jingle/notifier/communicator/login.cc b/jingle/notifier/communicator/login.cc index 35b7f1f..5e5d0b3b 100644 --- a/jingle/notifier/communicator/login.cc +++ b/jingle/notifier/communicator/login.cc
@@ -38,15 +38,13 @@ servers, try_ssltcp_first, auth_mechanism) { - net::NetworkChangeNotifier::AddIPAddressObserver(this); - net::NetworkChangeNotifier::AddConnectionTypeObserver(this); + net::NetworkChangeNotifier::AddNetworkChangeObserver(this); // TODO(akalin): Add as DNSObserver once bug 130610 is fixed. ResetReconnectState(); } Login::~Login() { - net::NetworkChangeNotifier::RemoveConnectionTypeObserver(this); - net::NetworkChangeNotifier::RemoveIPAddressObserver(this); + net::NetworkChangeNotifier::RemoveNetworkChangeObserver(this); } void Login::StartConnection() { @@ -90,14 +88,8 @@ delegate_->OnTransientDisconnection(); } -void Login::OnIPAddressChanged() { - DVLOG(1) << "IP address changed"; - OnNetworkEvent(); -} - -void Login::OnConnectionTypeChanged( - net::NetworkChangeNotifier::ConnectionType type) { - DVLOG(1) << "Connection type changed"; +void Login::OnNetworkChanged(net::NetworkChangeNotifier::ConnectionType type) { + DVLOG(1) << "Network changed"; OnNetworkEvent(); }
diff --git a/jingle/notifier/communicator/login.h b/jingle/notifier/communicator/login.h index 06c06ac0..7ce68c8 100644 --- a/jingle/notifier/communicator/login.h +++ b/jingle/notifier/communicator/login.h
@@ -38,8 +38,7 @@ // to take on the various errors that may occur. // // TODO(akalin): Make this observe proxy config changes also. -class Login : public net::NetworkChangeNotifier::IPAddressObserver, - public net::NetworkChangeNotifier::ConnectionTypeObserver, +class Login : public net::NetworkChangeNotifier::NetworkChangeObserver, public net::NetworkChangeNotifier::DNSObserver, public SingleLoginAttempt::Delegate { public: @@ -82,11 +81,8 @@ // StartConnection()). void UpdateXmppSettings(const buzz::XmppClientSettings& user_settings); - // net::NetworkChangeNotifier::IPAddressObserver implementation. - void OnIPAddressChanged() override; - - // net::NetworkChangeNotifier::ConnectionTypeObserver implementation. - void OnConnectionTypeChanged( + // net::NetworkChangeNotifier::NetworkChangeObserver implementation. + void OnNetworkChanged( net::NetworkChangeNotifier::ConnectionType type) override; // net::NetworkChangeNotifier::DNSObserver implementation.
diff --git a/mash/test/mash_test_suite.cc b/mash/test/mash_test_suite.cc index f5af4db..660adf6 100644 --- a/mash/test/mash_test_suite.cc +++ b/mash/test/mash_test_suite.cc
@@ -16,6 +16,7 @@ #include "ui/aura/env.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/ui_base_paths.h" +#include "ui/base/ui_base_switches.h" #include "ui/compositor/compositor.h" #include "ui/compositor/reflector.h" #include "ui/compositor/test/fake_context_factory.h" @@ -36,6 +37,8 @@ base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kOverrideUseSoftwareGLForTests); + base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( + switches::kMus, switches::kMusHostVizValue); // Load ash mus strings and resources; not 'common' (Chrome) resources. base::FilePath resources;
diff --git a/media/audio/audio_output_device.cc b/media/audio/audio_output_device.cc index 3789f45..16b60da 100644 --- a/media/audio/audio_output_device.cc +++ b/media/audio/audio_output_device.cc
@@ -11,8 +11,10 @@ #include <utility> #include "base/callback_helpers.h" +#include "base/format_macros.h" #include "base/macros.h" #include "base/metrics/histogram_macros.h" +#include "base/strings/stringprintf.h" #include "base/threading/thread_restrictions.h" #include "base/timer/timer.h" #include "base/trace_event/trace_event.h" @@ -480,15 +482,6 @@ // Called whenever we receive notifications about pending data. void AudioOutputDevice::AudioThreadCallback::Process(uint32_t control_signal) { callback_num_++; - TRACE_EVENT1("audio", "AudioOutputDevice::FireRenderCallback", - "callback_num", callback_num_); - - // When playback starts, we get an immediate callback to Process to make sure - // that we have some data, we'll get another one after the device is awake and - // ingesting data, which is what we want to track with this trace. - if (callback_num_ == 2) { - TRACE_EVENT_ASYNC_END0("audio", "StartingPlayback", this); - } // Read and reset the number of frames skipped. AudioOutputBuffer* buffer = @@ -503,9 +496,22 @@ base::TimeTicks() + base::TimeDelta::FromMicroseconds(buffer->params.delay_timestamp); + TRACE_EVENT2( + "audio", "AudioOutputDevice::FireRenderCallback", "callback_num", + callback_num_, "delay_info", + base::StringPrintf("Timestamp: %" PRId64 "us, Delay: %" PRId64 + "us, Skip: %u frames", + (delay_timestamp - base::TimeTicks()).InMicroseconds(), + delay.InMicroseconds(), frames_skipped)); DVLOG(4) << __func__ << " delay:" << delay << " delay_timestamp:" << delay << " frames_skipped:" << frames_skipped; + // When playback starts, we get an immediate callback to Process to make sure + // that we have some data, we'll get another one after the device is awake and + // ingesting data, which is what we want to track with this trace. + if (callback_num_ == 2) + TRACE_EVENT_ASYNC_END0("audio", "StartingPlayback", this); + // Update the audio-delay measurement, inform about the number of skipped // frames, and ask client to render audio. Since |output_bus_| is wrapping // the shared memory the Render() call is writing directly into the shared
diff --git a/media/base/android/java/src/org/chromium/media/MediaCodecBridge.java b/media/base/android/java/src/org/chromium/media/MediaCodecBridge.java index 708bb2f..a507f7a0 100644 --- a/media/base/android/java/src/org/chromium/media/MediaCodecBridge.java +++ b/media/base/android/java/src/org/chromium/media/MediaCodecBridge.java
@@ -453,6 +453,11 @@ Log.e(TAG, "Failed to queue secure input buffer, CryptoException with error code " + e.getErrorCode()); return MediaCodecStatus.ERROR; + } catch (IllegalArgumentException e) { + // IllegalArgumentException can occur when release() is called on the MediaCrypto + // object, but the MediaCodecBridge is unaware of the change. + Log.e(TAG, "Failed to queue secure input buffer, IllegalArgumentException " + e); + return MediaCodecStatus.ERROR; } catch (IllegalStateException e) { Log.e(TAG, "Failed to queue secure input buffer, IllegalStateException " + e); return MediaCodecStatus.ERROR;
diff --git a/media/base/android/java/src/org/chromium/media/MediaDrmBridge.java b/media/base/android/java/src/org/chromium/media/MediaDrmBridge.java index 6b121e6..c36987d 100644 --- a/media/base/android/java/src/org/chromium/media/MediaDrmBridge.java +++ b/media/base/android/java/src/org/chromium/media/MediaDrmBridge.java
@@ -74,6 +74,7 @@ private static final byte[] UNPROVISION = "unprovision".getBytes(); private MediaDrm mMediaDrm; + private MediaCrypto mMediaCrypto; private long mNativeMediaDrmBridge; private UUID mSchemeUUID; @@ -306,9 +307,9 @@ // Create MediaCrypto object. try { if (MediaCrypto.isCryptoSchemeSupported(mSchemeUUID)) { - MediaCrypto mediaCrypto = new MediaCrypto(mSchemeUUID, mMediaCryptoSession.drmId()); + mMediaCrypto = new MediaCrypto(mSchemeUUID, mMediaCryptoSession.drmId()); Log.d(TAG, "MediaCrypto successfully created!"); - onMediaCryptoReady(mediaCrypto); + onMediaCryptoReady(mMediaCrypto); return true; } else { Log.e(TAG, "Cannot create MediaCrypto for unsupported scheme."); @@ -601,6 +602,11 @@ mMediaDrm.release(); mMediaDrm = null; } + + if (mMediaCrypto != null) { + mMediaCrypto.release(); + mMediaCrypto = null; + } } /**
diff --git a/media/base/media_observer.h b/media/base/media_observer.h index 4073e03..e1ca88f 100644 --- a/media/base/media_observer.h +++ b/media/base/media_observer.h
@@ -30,11 +30,8 @@ // playback. virtual void UpdateRemotePlaybackCompatibility(bool is_compatible) = 0; - // Gets the number of audio/video bytes/video frames decoded so far from the - // media pipeline. All the counts keep increasing and will not be reset during - // seek. - virtual size_t AudioDecodedByteCount() const = 0; - virtual size_t VideoDecodedByteCount() const = 0; + // Gets the number of video frames decoded so far from the media pipeline. + // All the counts keep increasing and will not be reset during seek. virtual unsigned DecodedFrameCount() const = 0; // Gets the media duration in seconds. Returns
diff --git a/media/base/pipeline_impl.cc b/media/base/pipeline_impl.cc index f83d6ea..23cbca1 100644 --- a/media/base/pipeline_impl.cc +++ b/media/base/pipeline_impl.cc
@@ -1042,11 +1042,7 @@ if (media_task_runner_->BelongsToCurrentThread()) { // This path is executed by unittests that share media and main threads. - base::Closure stop_cb = base::Bind(&base::DoNothing); - media_task_runner_->PostTask( - FROM_HERE, - base::Bind(&RendererWrapper::Stop, - base::Unretained(renderer_wrapper_.get()), stop_cb)); + renderer_wrapper_->Stop(base::Bind(&base::DoNothing)); } else { // This path is executed by production code where the two task runners - // main and media - live on different threads.
diff --git a/media/base/pipeline_impl_unittest.cc b/media/base/pipeline_impl_unittest.cc index 9db941b9..89bbd4b 100644 --- a/media/base/pipeline_impl_unittest.cc +++ b/media/base/pipeline_impl_unittest.cc
@@ -56,6 +56,11 @@ pipeline->Stop(); } +ACTION_P(PostStop, pipeline) { + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::Bind(&Pipeline::Stop, base::Unretained(pipeline))); +} + ACTION_P2(SetError, renderer_client, status) { (*renderer_client)->OnError(status); } @@ -929,7 +934,7 @@ if (stop_or_error == kStop) { EXPECT_CALL(*demuxer_, Initialize(_, _, _)) .WillOnce( - DoAll(Stop(pipeline_.get()), PostCallback<1>(PIPELINE_OK))); + DoAll(PostStop(pipeline_.get()), PostCallback<1>(PIPELINE_OK))); // Note: OnStart callback is not called after pipeline is stopped. } else { EXPECT_CALL(*demuxer_, Initialize(_, _, _)) @@ -953,7 +958,7 @@ if (stop_or_error == kStop) { EXPECT_CALL(*renderer_, Initialize(_, _, _)) .WillOnce( - DoAll(Stop(pipeline_.get()), PostCallback<2>(PIPELINE_OK))); + DoAll(PostStop(pipeline_.get()), PostCallback<2>(PIPELINE_OK))); // Note: OnStart is not callback after pipeline is stopped. } else { EXPECT_CALL(*renderer_, Initialize(_, _, _)) @@ -1026,7 +1031,7 @@ if (stop_or_error == kStop) { EXPECT_CALL(*demuxer_, Seek(_, _)) .WillOnce( - DoAll(Stop(pipeline_.get()), RunCallback<1>(PIPELINE_OK))); + DoAll(PostStop(pipeline_.get()), RunCallback<1>(PIPELINE_OK))); // Note: OnSeek callback is not called after pipeline is stopped. } else { EXPECT_CALL(*demuxer_, Seek(_, _)) @@ -1067,7 +1072,7 @@ if (stop_or_error == kStop) { EXPECT_CALL(*demuxer_, Seek(_, _)) .WillOnce( - DoAll(Stop(pipeline_.get()), RunCallback<1>(PIPELINE_OK))); + DoAll(PostStop(pipeline_.get()), RunCallback<1>(PIPELINE_OK))); // Note: OnResume callback is not called after pipeline is stopped. } else { EXPECT_CALL(*demuxer_, Seek(_, _))
diff --git a/media/filters/ffmpeg_demuxer.cc b/media/filters/ffmpeg_demuxer.cc index 6e673cf..1e0b383 100644 --- a/media/filters/ffmpeg_demuxer.cc +++ b/media/filters/ffmpeg_demuxer.cc
@@ -1283,6 +1283,11 @@ const AVCodecParameters* codec_parameters = stream->codecpar; const AVMediaType codec_type = codec_parameters->codec_type; const AVCodecID codec_id = codec_parameters->codec_id; + // Skip streams which are not properly detected. + if (codec_id == AV_CODEC_ID_NONE) { + stream->discard = AVDISCARD_ALL; + continue; + } if (codec_type == AVMEDIA_TYPE_AUDIO) { // Log the codec detected, whether it is supported or not, and whether or
diff --git a/media/filters/video_renderer_algorithm.cc b/media/filters/video_renderer_algorithm.cc index 591ea49e..976151f 100644 --- a/media/filters/video_renderer_algorithm.cc +++ b/media/filters/video_renderer_algorithm.cc
@@ -387,11 +387,31 @@ // the new frame; this allows EffectiveFramesQueued() to be relatively correct // immediately after a new frame is queued. std::vector<base::TimeDelta> media_timestamps(1, frame->timestamp()); + + // If there are not enough frames to estimate duration based on end time, ask + // the WallClockTimeCB to convert the estimated frame duration into wall clock + // time. + // + // Note: This duration value is not compensated for playback rate and + // thus is different than |average_frame_duration_| which is compensated. + // + // Note: Not all frames have duration. E.g., this class is used with WebRTC + // which does not provide duration information for its frames. + base::TimeDelta metadata_frame_duration; + if (!frame_duration_calculator_.count() && + frame->metadata()->GetTimeDelta(VideoFrameMetadata::FRAME_DURATION, + &metadata_frame_duration) && + metadata_frame_duration > base::TimeDelta()) { + media_timestamps.push_back(frame->timestamp() + metadata_frame_duration); + } + std::vector<base::TimeTicks> wall_clock_times; wall_clock_time_cb_.Run(media_timestamps, &wall_clock_times); ready_frame.start_time = wall_clock_times[0]; if (frame_duration_calculator_.count()) ready_frame.end_time = ready_frame.start_time + average_frame_duration_; + else if (wall_clock_times.size() > 1u) + ready_frame.end_time = wall_clock_times[1]; // The vast majority of cases should always append to the back, but in rare // circumstance we get out of order timestamps, http://crbug.com/386551. @@ -464,34 +484,69 @@ for (const auto& ready_frame : frame_queue_) media_timestamps.push_back(ready_frame.frame->timestamp()); + // If there are not enough frames to estimate duration based on end time, ask + // the WallClockTimeCB to convert the estimated frame duration into wall clock + // time. + // + // Note: This duration value is not compensated for playback rate and + // thus is different than |average_frame_duration_| which is compensated. + // + // Note: Not all frames have duration. E.g., this class is used with WebRTC + // which does not provide duration information for its frames. + base::TimeDelta metadata_frame_duration; + const bool use_frame_duration_metadata = + !frame_duration_calculator_.count() && frame_queue_.size() == 1u && + frame_queue_.front().frame->metadata()->GetTimeDelta( + VideoFrameMetadata::FRAME_DURATION, &metadata_frame_duration) && + metadata_frame_duration > base::TimeDelta(); + if (use_frame_duration_metadata) { + media_timestamps.push_back(frame_queue_.front().frame->timestamp() + + metadata_frame_duration); + } + std::vector<base::TimeTicks> wall_clock_times; was_time_moving_ = wall_clock_time_cb_.Run(media_timestamps, &wall_clock_times); - // Transfer the converted wall clock times into our frame queue. - DCHECK_EQ(wall_clock_times.size(), frame_queue_.size()); - for (size_t i = 0; i < frame_queue_.size() - 1; ++i) { - ReadyFrame& frame = frame_queue_[i]; - const bool new_sample = frame.has_estimated_end_time; - frame.start_time = wall_clock_times[i]; - frame.end_time = wall_clock_times[i + 1]; - frame.has_estimated_end_time = false; - if (new_sample) - frame_duration_calculator_.AddSample(frame.end_time - frame.start_time); + base::TimeDelta deviation; + if (!use_frame_duration_metadata) { + // Transfer the converted wall clock times into our frame queue. + DCHECK_EQ(wall_clock_times.size(), frame_queue_.size()); + for (size_t i = 0; i < frame_queue_.size() - 1; ++i) { + ReadyFrame& frame = frame_queue_[i]; + const bool new_sample = frame.has_estimated_end_time; + frame.start_time = wall_clock_times[i]; + frame.end_time = wall_clock_times[i + 1]; + frame.has_estimated_end_time = false; + if (new_sample) + frame_duration_calculator_.AddSample(frame.end_time - frame.start_time); + } + frame_queue_.back().start_time = wall_clock_times.back(); + + if (!frame_duration_calculator_.count()) + return; + + // Compute |average_frame_duration_|, a moving average of the last few + // frames; see kMovingAverageSamples for the exact number. + average_frame_duration_ = frame_duration_calculator_.Average(); + deviation = frame_duration_calculator_.Deviation(); + + // Update the frame end time for the last frame based on the average. + frame_queue_.back().end_time = + frame_queue_.back().start_time + average_frame_duration_; + } else { + DCHECK_EQ(frame_duration_calculator_.count(), 0u); + DCHECK_EQ(wall_clock_times.size(), 2u); + + ReadyFrame& frame = frame_queue_.front(); + frame.start_time = wall_clock_times[0]; + frame.end_time = wall_clock_times[1]; + frame.has_estimated_end_time = true; + + // Note: This may be called multiple times, so we don't want to update the + // frame duration calculator with our estimate. + average_frame_duration_ = frame.end_time - frame.start_time; } - frame_queue_.back().start_time = wall_clock_times.back(); - - if (!frame_duration_calculator_.count()) - return; - - // Compute |average_frame_duration_|, a moving average of the last few frames; - // see kMovingAverageSamples for the exact number. - average_frame_duration_ = frame_duration_calculator_.Average(); - const base::TimeDelta deviation = frame_duration_calculator_.Deviation(); - - // Update the frame end time for the last frame based on the average. - frame_queue_.back().end_time = - frame_queue_.back().start_time + average_frame_duration_; // ITU-R BR.265 recommends a maximum acceptable drift of +/- half of the frame // duration; there are other asymmetric, more lenient measures, that we're
diff --git a/media/filters/video_renderer_algorithm.h b/media/filters/video_renderer_algorithm.h index 5d0e146..64bcf3a6 100644 --- a/media/filters/video_renderer_algorithm.h +++ b/media/filters/video_renderer_algorithm.h
@@ -100,8 +100,9 @@ // rendered yet. If it has been rendered, the new frame will be dropped. // // EnqueueFrame() will compute the current start time and an estimated end - // time of the frame based on previous frames so that EffectiveFramesQueued() - // is relatively accurate immediately after this call. + // time of the frame based on previous frames or the value of + // VideoFrameMetadata::FRAME_DURATION if no previous frames, so that + // EffectiveFramesQueued() is relatively accurate immediately after this call. void EnqueueFrame(const scoped_refptr<VideoFrame>& frame); // Removes all frames from the |frame_queue_| and clears predictors. The
diff --git a/media/filters/video_renderer_algorithm_unittest.cc b/media/filters/video_renderer_algorithm_unittest.cc index 4e8ca341..de025f7 100644 --- a/media/filters/video_renderer_algorithm_unittest.cc +++ b/media/filters/video_renderer_algorithm_unittest.cc
@@ -1216,6 +1216,34 @@ ASSERT_EQ("[60]", GetCadence(1, NTSC(60))); } +TEST_F(VideoRendererAlgorithmTest, RemoveExpiredFramesWithoutRendering) { + TickGenerator tg(tick_clock_->NowTicks(), 50); + + // Removing expired frames before anything is enqueued should do nothing. + ASSERT_EQ(0u, algorithm_.RemoveExpiredFrames(tg.current())); + + // First verify that frames without a duration are always effective when only + // one frame is present in the queue. + algorithm_.EnqueueFrame(CreateFrame(tg.interval(0))); + ASSERT_EQ(0u, algorithm_.RemoveExpiredFrames(tg.current())); + EXPECT_EQ(1u, EffectiveFramesQueued()); + + ASSERT_EQ(0u, algorithm_.RemoveExpiredFrames(tg.current() + tg.interval(3))); + EXPECT_EQ(1u, EffectiveFramesQueued()); + + algorithm_.Reset(); + + // Now try a frame with duration information, this frame should not be counted + // as effective since we know the duration of it. It is not removed since we + // only have one frame in the queue though. + auto frame = CreateFrame(tg.interval(0)); + frame->metadata()->SetTimeDelta(VideoFrameMetadata::FRAME_DURATION, + tg.interval(1)); + algorithm_.EnqueueFrame(frame); + ASSERT_EQ(0u, algorithm_.RemoveExpiredFrames(tg.current() + tg.interval(3))); + EXPECT_EQ(0u, EffectiveFramesQueued()); +} + TEST_F(VideoRendererAlgorithmTest, RemoveExpiredFrames) { TickGenerator tg(tick_clock_->NowTicks(), 50);
diff --git a/media/gpu/format_utils.cc b/media/gpu/format_utils.cc index 7074536..72d5d626 100644 --- a/media/gpu/format_utils.cc +++ b/media/gpu/format_utils.cc
@@ -15,6 +15,14 @@ case gfx::BufferFormat::BGRA_8888: return PIXEL_FORMAT_ARGB; + // There is no PIXEL_FORMAT_XBGR which would have been the right mapping. + // See ui/ozone drm_util.cc::GetFourCCFormatFromBufferFormat as reference. + // But here it is only about indicating to not consider the alpha channel. + // Useful for the compositor to avoid drawing behind as mentioned in + // https://chromium-review.googlesource.com/590772. + case gfx::BufferFormat::RGBX_8888: + return PIXEL_FORMAT_XRGB; + case gfx::BufferFormat::YVU_420: return PIXEL_FORMAT_YV12;
diff --git a/media/gpu/vaapi/vaapi_drm_picture.cc b/media/gpu/vaapi/vaapi_drm_picture.cc index d762d69..10876fc 100644 --- a/media/gpu/vaapi/vaapi_drm_picture.cc +++ b/media/gpu/vaapi/vaapi_drm_picture.cc
@@ -25,6 +25,7 @@ static unsigned BufferFormatToInternalFormat(gfx::BufferFormat format) { switch (format) { case gfx::BufferFormat::BGRX_8888: + case gfx::BufferFormat::RGBX_8888: return GL_RGB; case gfx::BufferFormat::BGRA_8888:
diff --git a/media/gpu/vaapi/vaapi_picture_factory.cc b/media/gpu/vaapi/vaapi_picture_factory.cc index 3c5abad..9a0e20b 100644 --- a/media/gpu/vaapi/vaapi_picture_factory.cc +++ b/media/gpu/vaapi/vaapi_picture_factory.cc
@@ -88,4 +88,16 @@ #endif } +gfx::BufferFormat VaapiPictureFactory::GetBufferFormatForAllocateMode() { +#if defined(USE_OZONE) + return gfx::BufferFormat::BGRX_8888; +#else + return gfx::BufferFormat::RGBX_8888; +#endif +} + +gfx::BufferFormat VaapiPictureFactory::GetBufferFormatForImportMode() { + return gfx::BufferFormat::YVU_420; +} + } // namespace media
diff --git a/media/gpu/vaapi/vaapi_picture_factory.h b/media/gpu/vaapi/vaapi_picture_factory.h index 5123e693..03f80776 100644 --- a/media/gpu/vaapi/vaapi_picture_factory.h +++ b/media/gpu/vaapi/vaapi_picture_factory.h
@@ -49,6 +49,11 @@ // or GL_TEXTURE_EXTERNAL_OES on DRM). uint32_t GetGLTextureTarget(); + // Buffer format to use for output buffers backing PictureBuffers. This is + // the format decoded frames in VASurfaces are converted into. + gfx::BufferFormat GetBufferFormatForAllocateMode(); + gfx::BufferFormat GetBufferFormatForImportMode(); + private: DISALLOW_COPY_AND_ASSIGN(VaapiPictureFactory); };
diff --git a/media/gpu/vaapi_video_decode_accelerator.cc b/media/gpu/vaapi_video_decode_accelerator.cc index ce96ced..b31925d 100644 --- a/media/gpu/vaapi_video_decode_accelerator.cc +++ b/media/gpu/vaapi_video_decode_accelerator.cc
@@ -55,11 +55,6 @@ 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63}; - -// Buffer format to use for output buffers backing PictureBuffers. This is the -// format decoded frames in VASurfaces are converted into. -const gfx::BufferFormat kAllocatePictureFormat = gfx::BufferFormat::BGRX_8888; -const gfx::BufferFormat kImportPictureFormat = gfx::BufferFormat::YVU_420; } static void ReportToUMA(VAVDADecoderFailure failure) { @@ -340,7 +335,7 @@ finish_flush_pending_(false), awaiting_va_surfaces_recycle_(false), requested_num_pics_(0), - output_format_(kAllocatePictureFormat), + output_format_(gfx::BufferFormat::BGRX_8888), make_context_current_cb_(make_context_current_cb), bind_image_cb_(bind_image_cb), weak_this_factory_(this) { @@ -364,11 +359,11 @@ switch (config.output_mode) { case Config::OutputMode::ALLOCATE: - output_format_ = kAllocatePictureFormat; + output_format_ = vaapi_picture_factory_->GetBufferFormatForAllocateMode(); break; case Config::OutputMode::IMPORT: - output_format_ = kImportPictureFormat; + output_format_ = vaapi_picture_factory_->GetBufferFormatForImportMode(); break; default:
diff --git a/media/gpu/vaapi_video_decode_accelerator_unittest.cc b/media/gpu/vaapi_video_decode_accelerator_unittest.cc index 443c962..34d429aa 100644 --- a/media/gpu/vaapi_video_decode_accelerator_unittest.cc +++ b/media/gpu/vaapi_video_decode_accelerator_unittest.cc
@@ -9,6 +9,7 @@ #include "base/run_loop.h" #include "base/test/scoped_task_environment.h" #include "media/gpu/accelerated_video_decoder.h" +#include "media/gpu/format_utils.h" #include "media/gpu/vaapi/vaapi_picture.h" #include "media/gpu/vaapi/vaapi_picture_factory.h" #include "media/gpu/vaapi_wrapper.h" @@ -338,6 +339,27 @@ #endif } +// Verifies the expected buffer format for each output mode. +TEST_P(VaapiVideoDecodeAcceleratorTest, PictureBufferFormat) { + gfx::BufferFormat allocate_format = + mock_vaapi_picture_factory_->GetBufferFormatForAllocateMode(); + gfx::BufferFormat import_format = + mock_vaapi_picture_factory_->GetBufferFormatForImportMode(); + +#if defined(USE_OZONE) + EXPECT_EQ(gfx::BufferFormat::BGRX_8888, allocate_format); +#else + EXPECT_EQ(gfx::BufferFormat::RGBX_8888, allocate_format); +#endif // USE_OZONE + + EXPECT_EQ(gfx::BufferFormat::YVU_420, import_format); + + EXPECT_EQ(PIXEL_FORMAT_XRGB, + GfxBufferFormatToVideoPixelFormat(allocate_format)); + EXPECT_EQ(PIXEL_FORMAT_YV12, + GfxBufferFormatToVideoPixelFormat(import_format)); +} + INSTANTIATE_TEST_CASE_P(/* No prefix. */, VaapiVideoDecodeAcceleratorTest, ValuesIn(kCodecProfiles));
diff --git a/media/gpu/vaapi_wrapper.cc b/media/gpu/vaapi_wrapper.cc index c9e57d37be..807fd3bd 100644 --- a/media/gpu/vaapi_wrapper.cc +++ b/media/gpu/vaapi_wrapper.cc
@@ -77,6 +77,8 @@ return VA_FOURCC_BGRX; case gfx::BufferFormat::BGRA_8888: return VA_FOURCC_BGRA; + case gfx::BufferFormat::RGBX_8888: + return VA_FOURCC_RGBX; case gfx::BufferFormat::UYVY_422: return VA_FOURCC_UYVY; case gfx::BufferFormat::YVU_420: @@ -93,6 +95,7 @@ return VA_RT_FORMAT_YUV422; case gfx::BufferFormat::BGRX_8888: case gfx::BufferFormat::BGRA_8888: + case gfx::BufferFormat::RGBX_8888: return VA_RT_FORMAT_RGB32; case gfx::BufferFormat::YVU_420: return VA_RT_FORMAT_YUV420; @@ -149,8 +152,6 @@ // Initialize static data before sandbox is enabled. static void PreSandboxInitialization(); - // Returns false on init failure. - static bool PostSandboxInitialization(); VADisplayState(); ~VADisplayState() = delete; @@ -165,6 +166,9 @@ void SetDrmFd(base::PlatformFile fd) { drm_fd_.reset(HANDLE_EINTR(dup(fd))); } private: + // Returns false on init failure. + static bool PostSandboxInitialization(); + // Protected by |va_lock_|. int refcount_; @@ -231,6 +235,11 @@ bool VADisplayState::Initialize() { va_lock_.AssertAcquired(); + + static bool result = PostSandboxInitialization(); + if (!result) + return false; + if (refcount_++ > 0) return true; @@ -411,10 +420,6 @@ report_error_to_uma_cb_(base::Bind(&base::DoNothing)) { static_assert(arraysize(supported_profiles_) == VaapiWrapper::kCodecModeMax, "The array size of supported profile is incorrect."); - - static bool result = VADisplayState::PostSandboxInitialization(); - if (!result) - return; { base::AutoLock auto_lock(*va_lock_); if (!VADisplayState::Get()->Initialize())
diff --git a/media/remoting/metrics.cc b/media/remoting/metrics.cc index ffdc450..c2a7486 100644 --- a/media/remoting/metrics.cc +++ b/media/remoting/metrics.cc
@@ -171,23 +171,6 @@ remote_playback_is_disabled_ = disabled; } -void SessionMetricsRecorder::RecordMediaBitrateVersusCapacity( - double kilobits_per_second, - double capacity) { - UMA_HISTOGRAM_CUSTOM_COUNTS("Media.Remoting.StartMediaBitrate", - kilobits_per_second, 1, 16 * 1024, 50); - UMA_HISTOGRAM_CUSTOM_COUNTS("Media.Remoting.TransmissionCapacity", capacity, - 1, 16 * 1024, 50); - double remaining = capacity - kilobits_per_second; - if (remaining >= 0) { - UMA_HISTOGRAM_CUSTOM_COUNTS("Media.Remoting.CapacityOverMediaBitrate", - remaining, 1, 16 * 1024, 50); - } else { - UMA_HISTOGRAM_CUSTOM_COUNTS("Media.Remoting.MediaBitrateOverCapacity", - -remaining, 1, 16 * 1024, 50); - } -} - void SessionMetricsRecorder::RecordAudioConfiguration() { UMA_HISTOGRAM_ENUMERATION("Media.Remoting.AudioCodec", last_audio_codec_, kAudioCodecMax + 1);
diff --git a/media/remoting/metrics.h b/media/remoting/metrics.h index e52b2ae..db7f3a6d 100644 --- a/media/remoting/metrics.h +++ b/media/remoting/metrics.h
@@ -31,8 +31,6 @@ // These may be called before, during, or after a remoting session. void OnPipelineMetadataChanged(const PipelineMetadata& metadata); void OnRemotePlaybackDisabled(bool disabled); - void RecordMediaBitrateVersusCapacity(double kilobits_per_second, - double capacity); private: // Whether audio only, video only, or both were played during the session.
diff --git a/media/remoting/renderer_controller.cc b/media/remoting/renderer_controller.cc index 8b31de2..54c2910 100644 --- a/media/remoting/renderer_controller.cc +++ b/media/remoting/renderer_controller.cc
@@ -29,10 +29,6 @@ // are held stable before switching to media remoting. constexpr base::TimeDelta kDelayedStart = base::TimeDelta::FromSeconds(5); -// The maximum fraction of the transmission capacity that can safely be used by -// Media Remoting to deliver the media contents. -constexpr double kMaxMediaBitrateCapacityFraction = 0.9; - constexpr int kPixelPerSec4K = 3840 * 2160 * 30; // 4k 30fps. constexpr int kPixelPerSec2K = 1920 * 1080 * 30; // 1080p 30fps. @@ -422,25 +418,17 @@ DCHECK(!is_encrypted_); delayed_start_stability_timer_.Start( FROM_HERE, kDelayedStart, - base::Bind( - &RendererController::OnDelayedStartTimerFired, base::Unretained(this), - start_trigger, - client_->AudioDecodedByteCount() + client_->VideoDecodedByteCount(), - client_->DecodedFrameCount(), clock_->NowTicks())); - - session_->EstimateTransmissionCapacity( - base::BindOnce(&RendererController::OnReceivedTransmissionCapacity, - weak_factory_.GetWeakPtr())); + base::Bind(&RendererController::OnDelayedStartTimerFired, + base::Unretained(this), start_trigger, + client_->DecodedFrameCount(), clock_->NowTicks())); } void RendererController::CancelDelayedStart() { delayed_start_stability_timer_.Stop(); - transmission_capacity_ = 0; } void RendererController::OnDelayedStartTimerFired( StartTrigger start_trigger, - size_t decoded_bytes_before_delay, unsigned decoded_frame_count_before_delay, base::TimeTicks delayed_start_time) { DCHECK(is_dominant_content_); @@ -449,14 +437,6 @@ base::TimeDelta elapsed = clock_->NowTicks() - delayed_start_time; DCHECK(!elapsed.is_zero()); - double kilobits_per_second = - (client_->AudioDecodedByteCount() + client_->VideoDecodedByteCount() - - decoded_bytes_before_delay) * - 8.0 / elapsed.InSecondsF() / 1000.0; - DCHECK_GE(kilobits_per_second, 0); - const double capacity_kbps = transmission_capacity_ * 8.0 / 1000.0; - metrics_recorder_.RecordMediaBitrateVersusCapacity(kilobits_per_second, - capacity_kbps); if (has_video()) { const double frame_rate = (client_->DecodedFrameCount() - decoded_frame_count_before_delay) / @@ -474,14 +454,7 @@ } } - if (kilobits_per_second <= kMaxMediaBitrateCapacityFraction * capacity_kbps) { - StartRemoting(start_trigger); - } else { - VLOG(1) << "Media remoting is not supported: bitrate(kbps)=" - << kilobits_per_second - << " transmission_capacity(kbps)=" << capacity_kbps; - encountered_renderer_fatal_error_ = true; - } + StartRemoting(start_trigger); } void RendererController::StartRemoting(StartTrigger start_trigger) { @@ -498,11 +471,6 @@ session_->StartRemoting(this); } -void RendererController::OnReceivedTransmissionCapacity(double rate) { - DCHECK_GE(rate, 0); - transmission_capacity_ = rate; -} - void RendererController::OnRendererFatalError(StopTrigger stop_trigger) { DCHECK(thread_checker_.CalledOnValidThread());
diff --git a/media/remoting/renderer_controller.h b/media/remoting/renderer_controller.h index 53ff0477..99adaf0 100644 --- a/media/remoting/renderer_controller.h +++ b/media/remoting/renderer_controller.h
@@ -125,20 +125,16 @@ void WaitForStabilityBeforeStart(StartTrigger start_trigger); // Cancel the start of remoting. void CancelDelayedStart(); - // Called when the delayed start ends. |decoded_bytes_before_delay| is the - // total number of audio and video bytes decoded before the delayed start - // began. |delayed_start_time| is the time that the delayed start began. + // Called when the delayed start ends. |decoded_frame_count_before_delay| is + // the total number of frames decoded before the delayed start began. + // |delayed_start_time| is the time that the delayed start began. void OnDelayedStartTimerFired(StartTrigger start_trigger, - size_t decoded_bytes_before_delay, unsigned decoded_frame_count_before_delay, base::TimeTicks delayed_start_time); // Helper to request the media pipeline switch to the remoting renderer. void StartRemoting(StartTrigger start_trigger); - // Callback to get the estimated transmission capacity from Remoter. - void OnReceivedTransmissionCapacity(double rate); - // Indicates whether remoting is started. bool remote_rendering_started_ = false; @@ -198,9 +194,6 @@ std::unique_ptr<base::TickClock> clock_; - // The estimated transmission capacity (bytes/s) from Remoter. - double transmission_capacity_ = 0; - base::WeakPtrFactory<RendererController> weak_factory_; DISALLOW_COPY_AND_ASSIGN(RendererController);
diff --git a/media/remoting/renderer_controller_unittest.cc b/media/remoting/renderer_controller_unittest.cc index dc5b8fb..3d455a7 100644 --- a/media/remoting/renderer_controller_unittest.cc +++ b/media/remoting/renderer_controller_unittest.cc
@@ -64,8 +64,6 @@ constexpr base::TimeDelta kDelayedStartDuration = base::TimeDelta::FromSeconds(5); -constexpr double kNormalSpeedBitsPerSecond = 5000000; -constexpr double kHighSpeedBitsPerSecond = 15000000; } // namespace @@ -99,10 +97,6 @@ double Duration() const override { return duration_in_sec_; } - size_t VideoDecodedByteCount() const override { return decoded_bytes_; } - - size_t AudioDecodedByteCount() const override { return 0; } - unsigned DecodedFrameCount() const override { return decoded_frames_; } void UpdateRemotePlaybackCompatibility(bool is_compatibe) override {} @@ -148,15 +142,8 @@ return controller_->delayed_start_stability_timer_.IsRunning(); } - void DelayedStartEnds(bool too_high_bitrate, double frame_rate = 30) { + void DelayedStartEnds(double frame_rate = 30) { EXPECT_TRUE(IsInDelayedStart()); - if (too_high_bitrate) { - decoded_bytes_ = - kHighSpeedBitsPerSecond * kDelayedStartDuration.InSeconds() / 8.0; - } else { - decoded_bytes_ = - kNormalSpeedBitsPerSecond * kDelayedStartDuration.InSeconds() / 8.0; - } decoded_frames_ = frame_rate * kDelayedStartDuration.InSeconds(); clock_->Advance(kDelayedStartDuration); RunUntilIdle(); @@ -213,7 +200,7 @@ InitializeControllerAndBecomeDominant(shared_session, DefaultMetadata(VideoCodec::kCodecVP8), GetDefaultSinkMetadata(true)); - DelayedStartEnds(false); + DelayedStartEnds(); RunUntilIdle(); ExpectInRemoting(); // All requirements now satisfied. @@ -223,21 +210,6 @@ ExpectInLocalRendering(); } -TEST_F(RendererControllerTest, StartFailedWithTooHighBitrate) { - const scoped_refptr<SharedSession> shared_session = - FakeRemoterFactory::CreateSharedSession(false); - InitializeControllerAndBecomeDominant(shared_session, - DefaultMetadata(VideoCodec::kCodecVP8), - GetDefaultSinkMetadata(true)); - EXPECT_FALSE(is_rendering_remotely_); - EXPECT_TRUE(IsInDelayedStart()); - DelayedStartEnds(true); - RunUntilIdle(); - EXPECT_TRUE(activate_viewport_intersection_monitoring_); - EXPECT_FALSE(is_rendering_remotely_); - EXPECT_FALSE(disable_pipeline_suspend_); -} - TEST_F(RendererControllerTest, ToggleRendererOnSinkCapabilities) { const scoped_refptr<SharedSession> shared_session = FakeRemoterFactory::CreateSharedSession(false); @@ -259,7 +231,7 @@ controller_->OnBecameDominantVisibleContent(true); RunUntilIdle(); ExpectInDelayedStart(); - DelayedStartEnds(false); + DelayedStartEnds(); RunUntilIdle(); ExpectInRemoting(); // All requirements now satisfied. } @@ -272,7 +244,7 @@ DefaultMetadata(VideoCodec::kCodecVP8), GetDefaultSinkMetadata(true)); ExpectInDelayedStart(); - DelayedStartEnds(false); + DelayedStartEnds(); RunUntilIdle(); ExpectInRemoting(); // All requirements now satisfied. @@ -314,7 +286,7 @@ shared_session->OnSinkAvailable(sink_metadata.Clone()); RunUntilIdle(); ExpectInDelayedStart(); - DelayedStartEnds(false); + DelayedStartEnds(); RunUntilIdle(); ExpectInRemoting(); // All requirements now satisfied. } @@ -340,7 +312,7 @@ shared_session->OnSinkAvailable(sink_metadata.Clone()); RunUntilIdle(); ExpectInDelayedStart(); - DelayedStartEnds(false); + DelayedStartEnds(); RunUntilIdle(); ExpectInRemoting(); // All requirements now satisfied. } @@ -370,7 +342,7 @@ shared_session->OnSinkAvailable(sink_metadata.Clone()); RunUntilIdle(); ExpectInDelayedStart(); - DelayedStartEnds(false); + DelayedStartEnds(); RunUntilIdle(); ExpectInRemoting(); // All requirements now satisfied. } @@ -399,7 +371,7 @@ shared_session->OnSinkAvailable(sink_metadata.Clone()); RunUntilIdle(); ExpectInDelayedStart(); - DelayedStartEnds(false); + DelayedStartEnds(); RunUntilIdle(); ExpectInRemoting(); // All requirements now satisfied. } @@ -412,7 +384,7 @@ GetDefaultSinkMetadata(true)); RunUntilIdle(); ExpectInDelayedStart(); - DelayedStartEnds(false, 60); + DelayedStartEnds(60); RunUntilIdle(); ExpectInLocalRendering(); } @@ -427,7 +399,7 @@ shared_session, DefaultMetadata(VideoCodec::kCodecVP8), sink_metadata); RunUntilIdle(); ExpectInDelayedStart(); - DelayedStartEnds(false, 60); + DelayedStartEnds(60); RunUntilIdle(); ExpectInRemoting(); } @@ -442,7 +414,7 @@ GetDefaultSinkMetadata(true)); RunUntilIdle(); ExpectInDelayedStart(); - DelayedStartEnds(false); + DelayedStartEnds(); RunUntilIdle(); ExpectInLocalRendering(); }
diff --git a/media/renderers/video_renderer_impl.cc b/media/renderers/video_renderer_impl.cc index d8e8c5e0..ab0581e 100644 --- a/media/renderers/video_renderer_impl.cc +++ b/media/renderers/video_renderer_impl.cc
@@ -518,12 +518,16 @@ UMA_HISTOGRAM_ENUMERATION("Media.VideoFrame.ColorSpace", ColorSpaceUMAHelper(frame->ColorSpace()), static_cast<int>(VideoFrameColorSpaceUMA::MAX) + 1); + const bool is_eos = + frame->metadata()->IsTrue(VideoFrameMetadata::END_OF_STREAM); + const bool is_before_start_time = + !is_eos && IsBeforeStartTime(frame->timestamp()); + const bool cant_read = !video_frame_stream_->CanReadWithoutStalling(); - if (frame->metadata()->IsTrue(VideoFrameMetadata::END_OF_STREAM)) { + if (is_eos) { DCHECK(!received_end_of_stream_); received_end_of_stream_ = true; - } else if ((low_delay_ || !video_frame_stream_->CanReadWithoutStalling()) && - IsBeforeStartTime(frame->timestamp())) { + } else if ((low_delay_ || cant_read) && is_before_start_time) { // Don't accumulate frames that are earlier than the start time if we // won't have a chance for a better frame, otherwise we could declare // HAVE_ENOUGH_DATA and start playback prematurely. @@ -543,6 +547,16 @@ has_playback_met_watch_time_duration_requirement_ = true; } + // Provide frame duration information so that even if we only have one frame + // in the queue we can properly estimate duration. This allows the call to + // RemoveFramesForUnderflowOrBackgroundRendering() below to actually expire + // this frame if it's too far behind the current media time. Without this, + // we may resume too soon after a track change in the low delay case. + if (!frame->metadata()->HasKey(VideoFrameMetadata::FRAME_DURATION)) { + frame->metadata()->SetTimeDelta(VideoFrameMetadata::FRAME_DURATION, + video_frame_stream_->AverageDuration()); + } + AddReadyFrame_Locked(frame); UpdateMaxBufferedFrames(); } @@ -559,62 +573,32 @@ // Paint the first frame if possible and necessary. Paint ahead of // HAVE_ENOUGH_DATA to ensure the user sees the frame as early as possible. - bool just_painted_first_frame = false; - if (!sink_started_ && algorithm_->frames_queued() && !painted_first_frame_) { - // We want to paint the first frame under two conditions: Either (1) we have - // enough frames to know it's definitely the first frame or (2) there may be - // no more frames coming (sometimes unless we paint one of them). - // - // For the first condition, we need at least two effective frames, since - // otherwise we may be prerolling frames before the actual start time that - // will be dropped. - bool should_paint_first_frame = - algorithm_->effective_frames_queued() > 1 || received_end_of_stream_ || - !video_frame_stream_->CanReadWithoutStalling(); - - // For the very first frame (i.e. not after seeks), we want to paint as fast - // as possible to ensure users don't abandon the playback. For live streams - // with long duration frames, waiting for a second frame may take seconds. - // - // Before time starts progressing we may not know if frames are effective or - // not, so the first frame must check if timestamp >= |start_timestamp_|. - // - // We only do this for the very first frame ever painted, since later frames - // risk being wrong due to the lack of duration on the first frame. This - // avoids any fast-forward or frame-flipping type effects as we try to - // resume after a seek. - if (!have_renderered_frames_ && !should_paint_first_frame) { - should_paint_first_frame = - frame->timestamp() >= start_timestamp_ || low_delay_; - } - - if (should_paint_first_frame) { - scoped_refptr<VideoFrame> first_frame = - algorithm_->Render(base::TimeTicks(), base::TimeTicks(), nullptr); - CheckForMetadataChanges(first_frame->format(), - first_frame->natural_size()); - sink_->PaintSingleFrame(first_frame); - just_painted_first_frame = painted_first_frame_ = true; - } + // + // We want to paint the first frame under two conditions: Either (1) we have + // enough frames to know it's definitely the first frame or (2) there may be + // no more frames coming (sometimes unless we paint one of them). + // + // We have to check both effective_frames_queued() and |is_before_start_time| + // since prior to the clock starting effective_frames_queued() is a guess. + if (!sink_started_ && !painted_first_frame_ && algorithm_->frames_queued() && + (received_end_of_stream_ || cant_read || + (algorithm_->effective_frames_queued() && !is_before_start_time))) { + scoped_refptr<VideoFrame> first_frame = + algorithm_->Render(base::TimeTicks(), base::TimeTicks(), nullptr); + CheckForMetadataChanges(first_frame->format(), first_frame->natural_size()); + sink_->PaintSingleFrame(first_frame); + painted_first_frame_ = true; } // Signal buffering state if we've met our conditions. - // - // If we've just painted the first frame, require the standard 1 frame for low - // latency playback. If we're resuming after a Flush(), wait until we have two - // frames even in low delay mode to avoid any kind of fast-forward or frame - // flipping effect while we attempt to find the best frame. - if (buffering_state_ == BUFFERING_HAVE_NOTHING && - HaveEnoughData_Locked(just_painted_first_frame ? 1u : 2u)) { + if (buffering_state_ == BUFFERING_HAVE_NOTHING && HaveEnoughData_Locked()) TransitionToHaveEnough_Locked(); - } // Always request more decoded video if we have capacity. AttemptRead_Locked(); } -bool VideoRendererImpl::HaveEnoughData_Locked( - size_t low_latency_frames_required) const { +bool VideoRendererImpl::HaveEnoughData_Locked() const { DCHECK_EQ(state_, kPlaying); lock_.AssertAcquired(); @@ -631,16 +615,13 @@ if (was_background_rendering_ && frames_decoded_) return true; + if (!low_delay_ && video_frame_stream_->CanReadWithoutStalling()) + return false; + // Note: We still require an effective frame in the stalling case since this // method is also used to inform TransitionToHaveNothing_Locked() and thus // would never pause and rebuffer if we always return true here. - if (!video_frame_stream_->CanReadWithoutStalling()) - return algorithm_->effective_frames_queued() > 0u; - - if (!low_delay_) - return false; - - return algorithm_->effective_frames_queued() >= low_latency_frames_required; + return algorithm_->effective_frames_queued() > 0u; } void VideoRendererImpl::TransitionToHaveEnough_Locked() {
diff --git a/media/renderers/video_renderer_impl.h b/media/renderers/video_renderer_impl.h index 66c275b..acbf658 100644 --- a/media/renderers/video_renderer_impl.h +++ b/media/renderers/video_renderer_impl.h
@@ -139,12 +139,7 @@ // Returns true if the renderer has enough data for playback purposes. // Note that having enough data may be due to reaching end of stream. - // - // |low_latency_frames_required| indicates the required number of frame for - // have enough with a low latency playback. By default it's one frame, but - // during resume after a Flush() we may wait for 2 frames to ensure we have - // effective frames. - bool HaveEnoughData_Locked(size_t low_latency_frames_required = 1u) const; + bool HaveEnoughData_Locked() const; void TransitionToHaveEnough_Locked(); void TransitionToHaveNothing(); void TransitionToHaveNothing_Locked();
diff --git a/mojo/edk/system/broker_win.cc b/mojo/edk/system/broker_win.cc index 64700a1..6cfdc02 100644 --- a/mojo/edk/system/broker_win.cc +++ b/mojo/edk/system/broker_win.cc
@@ -65,7 +65,6 @@ base::debug::Alias(&buffer[0]); base::debug::Alias(&bytes_read); - base::debug::Alias(message.get()); CHECK(false); return nullptr; } @@ -77,7 +76,6 @@ base::debug::Alias(&buffer[0]); base::debug::Alias(&bytes_read); - base::debug::Alias(message.get()); CHECK(false); return nullptr; }
diff --git a/mojo/public/tools/bindings/chromium_bindings_configuration.gni b/mojo/public/tools/bindings/chromium_bindings_configuration.gni index 4c42468..47f31b8 100644 --- a/mojo/public/tools/bindings/chromium_bindings_configuration.gni +++ b/mojo/public/tools/bindings/chromium_bindings_configuration.gni
@@ -40,6 +40,7 @@ "//services/viz/privileged/interfaces/compositing/typemaps.gni", "//services/viz/public/cpp/compositing/typemaps.gni", "//skia/public/interfaces/typemaps.gni", + "//storage/common/typemaps.gni", "//third_party/WebKit/common/typemaps.gni", "//third_party/WebKit/public/public_typemaps.gni", "//ui/base/clipboard/mojom/typemaps.gni",
diff --git a/mojo/public/tools/bindings/generators/cpp_templates/interface_definition.tmpl b/mojo/public/tools/bindings/generators/cpp_templates/interface_definition.tmpl index b4538f8..4510c4f 100644 --- a/mojo/public/tools/bindings/generators/cpp_templates/interface_definition.tmpl +++ b/mojo/public/tools/bindings/generators/cpp_templates/interface_definition.tmpl
@@ -216,7 +216,9 @@ // Is the Service destroying the callback without running it // and without first closing the pipe? responder_->DCheckInvalid("The callback passed to " - "{{class_name}}::{{method.name}}() was never run."); + "{{class_name}}::{{method.name}}() was never run. It should either " + "be run before destruction, or else destroyed after first closing " + "the pipe."); } #endif // If the Callback was dropped then deleting the responder will close
diff --git a/net/BUILD.gn b/net/BUILD.gn index 9c4bef5..cda37cb 100644 --- a/net/BUILD.gn +++ b/net/BUILD.gn
@@ -1391,6 +1391,50 @@ "quic/core/tls_handshaker.h", "quic/core/tls_server_handshaker.cc", "quic/core/tls_server_handshaker.h", + "quic/http/decoder/payload_decoders/quic_http_altsvc_payload_decoder.cc", + "quic/http/decoder/payload_decoders/quic_http_altsvc_payload_decoder.h", + "quic/http/decoder/payload_decoders/quic_http_continuation_payload_decoder.cc", + "quic/http/decoder/payload_decoders/quic_http_continuation_payload_decoder.h", + "quic/http/decoder/payload_decoders/quic_http_data_payload_decoder.cc", + "quic/http/decoder/payload_decoders/quic_http_data_payload_decoder.h", + "quic/http/decoder/payload_decoders/quic_http_goaway_payload_decoder.cc", + "quic/http/decoder/payload_decoders/quic_http_goaway_payload_decoder.h", + "quic/http/decoder/payload_decoders/quic_http_headers_payload_decoder.cc", + "quic/http/decoder/payload_decoders/quic_http_headers_payload_decoder.h", + "quic/http/decoder/payload_decoders/quic_http_ping_payload_decoder.cc", + "quic/http/decoder/payload_decoders/quic_http_ping_payload_decoder.h", + "quic/http/decoder/payload_decoders/quic_http_priority_payload_decoder.cc", + "quic/http/decoder/payload_decoders/quic_http_priority_payload_decoder.h", + "quic/http/decoder/payload_decoders/quic_http_push_promise_payload_decoder.cc", + "quic/http/decoder/payload_decoders/quic_http_push_promise_payload_decoder.h", + "quic/http/decoder/payload_decoders/quic_http_rst_stream_payload_decoder.cc", + "quic/http/decoder/payload_decoders/quic_http_rst_stream_payload_decoder.h", + "quic/http/decoder/payload_decoders/quic_http_settings_payload_decoder.cc", + "quic/http/decoder/payload_decoders/quic_http_settings_payload_decoder.h", + "quic/http/decoder/payload_decoders/quic_http_unknown_payload_decoder.cc", + "quic/http/decoder/payload_decoders/quic_http_unknown_payload_decoder.h", + "quic/http/decoder/payload_decoders/quic_http_window_update_payload_decoder.cc", + "quic/http/decoder/payload_decoders/quic_http_window_update_payload_decoder.h", + "quic/http/decoder/quic_http_decode_buffer.cc", + "quic/http/decoder/quic_http_decode_buffer.h", + "quic/http/decoder/quic_http_decode_status.cc", + "quic/http/decoder/quic_http_decode_status.h", + "quic/http/decoder/quic_http_decode_structures.cc", + "quic/http/decoder/quic_http_decode_structures.h", + "quic/http/decoder/quic_http_frame_decoder.cc", + "quic/http/decoder/quic_http_frame_decoder.h", + "quic/http/decoder/quic_http_frame_decoder_adapter.cc", + "quic/http/decoder/quic_http_frame_decoder_adapter.h", + "quic/http/decoder/quic_http_frame_decoder_listener.cc", + "quic/http/decoder/quic_http_frame_decoder_listener.h", + "quic/http/decoder/quic_http_frame_decoder_state.cc", + "quic/http/decoder/quic_http_frame_decoder_state.h", + "quic/http/decoder/quic_http_structure_decoder.cc", + "quic/http/decoder/quic_http_structure_decoder.h", + "quic/http/quic_http_constants.cc", + "quic/http/quic_http_constants.h", + "quic/http/quic_http_structures.cc", + "quic/http/quic_http_structures.h", "quic/platform/api/quic_aligned.h", "quic/platform/api/quic_bug_tracker.h", "quic/platform/api/quic_clock.cc", @@ -1413,13 +1457,16 @@ "quic/platform/api/quic_mem_slice_span.h", "quic/platform/api/quic_mutex.cc", "quic/platform/api/quic_mutex.h", + "quic/platform/api/quic_optional.h", "quic/platform/api/quic_pcc_sender.h", "quic/platform/api/quic_ptr_util.h", + "quic/platform/api/quic_reconstruct_object.h", "quic/platform/api/quic_reference_counted.h", "quic/platform/api/quic_socket_address.cc", "quic/platform/api/quic_socket_address.h", "quic/platform/api/quic_stack_trace.h", "quic/platform/api/quic_str_cat.h", + "quic/platform/api/quic_string.h", "quic/platform/api/quic_string_piece.h", "quic/platform/api/quic_text_utils.h", "quic/platform/api/quic_url.cc", @@ -1450,13 +1497,16 @@ "quic/platform/impl/quic_mem_slice_span_impl.h", "quic/platform/impl/quic_mutex_impl.cc", "quic/platform/impl/quic_mutex_impl.h", + "quic/platform/impl/quic_optional_impl.h", "quic/platform/impl/quic_pcc_sender_impl.h", "quic/platform/impl/quic_ptr_util_impl.h", + "quic/platform/impl/quic_reconstruct_object_impl.h", "quic/platform/impl/quic_reference_counted_impl.h", "quic/platform/impl/quic_socket_address_impl.cc", "quic/platform/impl/quic_socket_address_impl.h", "quic/platform/impl/quic_stack_trace_impl.h", "quic/platform/impl/quic_str_cat_impl.h", + "quic/platform/impl/quic_string_impl.h", "quic/platform/impl/quic_string_piece_impl.h", "quic/platform/impl/quic_text_utils_impl.h", "quic/platform/impl/quic_url_impl.cc", @@ -5065,6 +5115,47 @@ "quic/core/quic_header_list_test.cc", "quic/core/quic_headers_stream_test.cc", "quic/core/tls_handshaker_test.cc", + "quic/http/decoder/payload_decoders/quic_http_altsvc_payload_decoder_test.cc", + "quic/http/decoder/payload_decoders/quic_http_continuation_payload_decoder_test.cc", + "quic/http/decoder/payload_decoders/quic_http_data_payload_decoder_test.cc", + "quic/http/decoder/payload_decoders/quic_http_goaway_payload_decoder_test.cc", + "quic/http/decoder/payload_decoders/quic_http_headers_payload_decoder_test.cc", + "quic/http/decoder/payload_decoders/quic_http_payload_decoder_base_test_util.cc", + "quic/http/decoder/payload_decoders/quic_http_payload_decoder_base_test_util.h", + "quic/http/decoder/payload_decoders/quic_http_ping_payload_decoder_test.cc", + "quic/http/decoder/payload_decoders/quic_http_priority_payload_decoder_test.cc", + "quic/http/decoder/payload_decoders/quic_http_push_promise_payload_decoder_test.cc", + "quic/http/decoder/payload_decoders/quic_http_rst_stream_payload_decoder_test.cc", + "quic/http/decoder/payload_decoders/quic_http_settings_payload_decoder_test.cc", + "quic/http/decoder/payload_decoders/quic_http_unknown_payload_decoder_test.cc", + "quic/http/decoder/payload_decoders/quic_http_window_update_payload_decoder_test.cc", + "quic/http/decoder/quic_http_decode_buffer_test.cc", + "quic/http/decoder/quic_http_frame_decoder_listener_test_util.cc", + "quic/http/decoder/quic_http_frame_decoder_listener_test_util.h", + "quic/http/decoder/quic_http_frame_decoder_state_test_util.cc", + "quic/http/decoder/quic_http_frame_decoder_state_test_util.h", + "quic/http/decoder/quic_http_frame_decoder_test.cc", + "quic/http/decoder/quic_http_structure_decoder_test.cc", + "quic/http/decoder/quic_http_structure_decoder_test_util.cc", + "quic/http/decoder/quic_http_structure_decoder_test_util.h", + "quic/http/quic_http_constants_test.cc", + "quic/http/quic_http_constants_test_util.cc", + "quic/http/quic_http_constants_test_util.h", + "quic/http/quic_http_structures_test.cc", + "quic/http/quic_http_structures_test_util.cc", + "quic/http/quic_http_structures_test_util.h", + "quic/http/test_tools/quic_http_frame_parts.cc", + "quic/http/test_tools/quic_http_frame_parts.h", + "quic/http/test_tools/quic_http_frame_parts_collector.cc", + "quic/http/test_tools/quic_http_frame_parts_collector.h", + "quic/http/test_tools/quic_http_frame_parts_collector_listener.cc", + "quic/http/test_tools/quic_http_frame_parts_collector_listener.h", + "quic/http/tools/quic_http_frame_builder.cc", + "quic/http/tools/quic_http_frame_builder.h", + "quic/http/tools/quic_http_random_decoder_test.cc", + "quic/http/tools/quic_http_random_decoder_test.h", + "quic/http/tools/quic_http_random_util.cc", + "quic/http/tools/quic_http_random_util.h", "quic/test_tools/quic_test_utils_test.cc", "quic/test_tools/simulator/quic_endpoint_test.cc", "quic/test_tools/simulator/simulator_test.cc", @@ -5102,9 +5193,12 @@ "quic/platform/api/quic_mem_slice_test.cc", "quic/platform/api/quic_reference_counted_test.cc", "quic/platform/api/quic_str_cat_test.cc", + "quic/platform/api/quic_test_random.h", "quic/platform/api/quic_text_utils_test.cc", "quic/platform/api/quic_url_test.cc", "quic/platform/impl/quic_chromium_clock_test.cc", + "quic/platform/impl/quic_test_random_impl.cc", + "quic/platform/impl/quic_test_random_impl.h", "quic/quartc/quartc_session_test.cc", "quic/quartc/quartc_stream_test.cc", "quic/test_tools/crypto_test_utils_test.cc",
diff --git a/net/cert/ct_policy_enforcer.cc b/net/cert/ct_policy_enforcer.cc index 61d169c..0f77780 100644 --- a/net/cert/ct_policy_enforcer.cc +++ b/net/cert/ct_policy_enforcer.cc
@@ -75,17 +75,18 @@ *rounded_months_difference = month_diff; } -const char* CertPolicyComplianceToString(ct::CertPolicyCompliance status) { +const char* CTPolicyComplianceToString(ct::CTPolicyCompliance status) { switch (status) { - case ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS: + case ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS: return "COMPLIES_VIA_SCTS"; - case ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS: + case ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS: return "NOT_ENOUGH_SCTS"; - case ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS: + case ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS: return "NOT_DIVERSE_SCTS"; - case ct::CertPolicyCompliance::CERT_POLICY_BUILD_NOT_TIMELY: + case ct::CTPolicyCompliance::CT_POLICY_BUILD_NOT_TIMELY: return "BUILD_NOT_TIMELY"; - case ct::CertPolicyCompliance::CERT_POLICY_MAX: + case ct::CTPolicyCompliance::CT_POLICY_COMPLIANCE_DETAILS_NOT_AVAILABLE: + case ct::CTPolicyCompliance::CT_POLICY_MAX: NOTREACHED(); return "unknown"; } @@ -97,25 +98,25 @@ std::unique_ptr<base::Value> NetLogCertComplianceCheckResultCallback( X509Certificate* cert, bool build_timely, - ct::CertPolicyCompliance compliance, + ct::CTPolicyCompliance compliance, NetLogCaptureMode capture_mode) { std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); dict->Set("certificate", NetLogX509CertificateCallback(cert, capture_mode)); dict->SetBoolean("build_timely", build_timely); dict->SetString("ct_compliance_status", - CertPolicyComplianceToString(compliance)); + CTPolicyComplianceToString(compliance)); return std::move(dict); } // Evaluates against the policy specified at // https://sites.google.com/a/chromium.org/dev/Home/chromium-security/root-ca-policy/EVCTPlanMay2015edition.pdf?attredirects=0 -ct::CertPolicyCompliance CheckCertPolicyCompliance( +ct::CTPolicyCompliance CheckCTPolicyCompliance( const X509Certificate& cert, const ct::SCTList& verified_scts) { // Cert is outside the bounds of parsable; reject it. if (cert.valid_start().is_null() || cert.valid_expiry().is_null() || cert.valid_start().is_max() || cert.valid_expiry().is_max()) { - return ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS; + return ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS; } // Scan for the earliest SCT. This is used to determine whether to enforce @@ -191,7 +192,7 @@ // accomodated. if (has_valid_nonembedded_sct && has_valid_google_sct && has_valid_nongoogle_sct) { - return ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS; + return ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS; } // Note: If has_valid_nonembedded_sct was true, but Option 2 isn't met, // then the result will be that there weren't diverse enough SCTs, as that @@ -207,8 +208,8 @@ // Option 1, there weren't diverse enough SCTs. Try to signal the error // that is most easily fixed. return has_valid_nonembedded_sct - ? ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS - : ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS; + ? ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS + : ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS; } // ... AND there is at least one embedded SCT from a Google Log once or @@ -228,7 +229,7 @@ !(has_embedded_google_sct && has_embedded_nongoogle_sct)) { // Note: This also covers the case for non-embedded SCTs, as it's only // possible to reach here if both sets are not diverse enough. - return ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS; + return ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS; } size_t lifetime_in_months = 0; @@ -262,19 +263,19 @@ std::distance(embedded_log_ids.begin(), sorted_end); if (num_embedded_scts >= num_required_embedded_scts) - return ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS; + return ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS; // Under Option 2, there weren't enough SCTs, and potentially under Option // 1, there weren't diverse enough SCTs. Try to signal the error that is // most easily fixed. return has_valid_nonembedded_sct - ? ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS - : ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS; + ? ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS + : ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS; } } // namespace -ct::CertPolicyCompliance CTPolicyEnforcer::DoesConformToCertPolicy( +ct::CTPolicyCompliance CTPolicyEnforcer::CheckCompliance( X509Certificate* cert, const ct::SCTList& verified_scts, const NetLogWithSource& net_log) { @@ -284,11 +285,11 @@ // needs up-to-date information about logs to consider certificates to // be compliant with policy. bool build_timely = IsBuildTimely(); - ct::CertPolicyCompliance compliance; + ct::CTPolicyCompliance compliance; if (!build_timely) { - compliance = ct::CertPolicyCompliance::CERT_POLICY_BUILD_NOT_TIMELY; + compliance = ct::CTPolicyCompliance::CT_POLICY_BUILD_NOT_TIMELY; } else { - compliance = CheckCertPolicyCompliance(*cert, verified_scts); + compliance = CheckCTPolicyCompliance(*cert, verified_scts); } NetLogParametersCallback net_log_callback =
diff --git a/net/cert/ct_policy_enforcer.h b/net/cert/ct_policy_enforcer.h index b594cba..fb6f4847 100644 --- a/net/cert/ct_policy_enforcer.h +++ b/net/cert/ct_policy_enforcer.h
@@ -17,7 +17,7 @@ namespace ct { -enum class CertPolicyCompliance; +enum class CTPolicyCompliance; } // namespace ct @@ -38,7 +38,7 @@ // ||verified_scts| contains any/all SCTs associated with |cert| that // |have been verified (well-formed, issued by known logs, and // |applying to |cert|). - virtual ct::CertPolicyCompliance DoesConformToCertPolicy( + virtual ct::CTPolicyCompliance CheckCompliance( X509Certificate* cert, const SCTList& verified_scts, const NetLogWithSource& net_log);
diff --git a/net/cert/ct_policy_enforcer_unittest.cc b/net/cert/ct_policy_enforcer_unittest.cc index 81421e7..d39017f 100644 --- a/net/cert/ct_policy_enforcer_unittest.cc +++ b/net/cert/ct_policy_enforcer_unittest.cc
@@ -138,9 +138,9 @@ ct::SignedCertificateTimestamp::SCT_FROM_TLS_EXTENSION, desired_log_ids.size(), desired_log_ids, true, &scts); - EXPECT_EQ(ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS, - policy_enforcer_->DoesConformToCertPolicy(chain_.get(), scts, - NetLogWithSource())); + EXPECT_EQ(ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS, + policy_enforcer_->CheckCompliance(chain_.get(), scts, + NetLogWithSource())); } TEST_F(CTPolicyEnforcerTest, @@ -152,9 +152,9 @@ ct::SignedCertificateTimestamp::SCT_FROM_TLS_EXTENSION, desired_log_ids.size(), desired_log_ids, true, &scts); - EXPECT_EQ(ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS, - policy_enforcer_->DoesConformToCertPolicy(chain_.get(), scts, - NetLogWithSource())); + EXPECT_EQ(ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS, + policy_enforcer_->CheckCompliance(chain_.get(), scts, + NetLogWithSource())); } TEST_F(CTPolicyEnforcerTest, ConformsToCTPolicyIfSCTBeforeEnforcementDate) { @@ -164,9 +164,9 @@ FillListWithSCTsOfOrigin(ct::SignedCertificateTimestamp::SCT_EMBEDDED, 5, std::vector<std::string>(), false, &scts); - EXPECT_EQ(ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS, - policy_enforcer_->DoesConformToCertPolicy(chain_.get(), scts, - NetLogWithSource())); + EXPECT_EQ(ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS, + policy_enforcer_->CheckCompliance(chain_.get(), scts, + NetLogWithSource())); } TEST_F(CTPolicyEnforcerTest, ConformsToCTPolicyWithNonEmbeddedSCTs) { @@ -174,9 +174,9 @@ FillListWithSCTsOfOrigin( ct::SignedCertificateTimestamp::SCT_FROM_TLS_EXTENSION, 2, &scts); - EXPECT_EQ(ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS, - policy_enforcer_->DoesConformToCertPolicy(chain_.get(), scts, - NetLogWithSource())); + EXPECT_EQ(ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS, + policy_enforcer_->CheckCompliance(chain_.get(), scts, + NetLogWithSource())); } TEST_F(CTPolicyEnforcerTest, ConformsToCTPolicyWithEmbeddedSCTs) { @@ -185,9 +185,9 @@ FillListWithSCTsOfOrigin(ct::SignedCertificateTimestamp::SCT_EMBEDDED, 5, &scts); - EXPECT_EQ(ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS, - policy_enforcer_->DoesConformToCertPolicy(chain_.get(), scts, - NetLogWithSource())); + EXPECT_EQ(ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS, + policy_enforcer_->CheckCompliance(chain_.get(), scts, + NetLogWithSource())); } TEST_F(CTPolicyEnforcerTest, ConformsToCTPolicyWithPooledNonEmbeddedSCTs) { @@ -208,9 +208,9 @@ ct::SignedCertificateTimestamp::SCT_FROM_TLS_EXTENSION, desired_logs.size(), desired_logs, true, &scts); - EXPECT_EQ(ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS, - policy_enforcer_->DoesConformToCertPolicy(chain_.get(), scts, - NetLogWithSource())); + EXPECT_EQ(ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS, + policy_enforcer_->CheckCompliance(chain_.get(), scts, + NetLogWithSource())); } TEST_F(CTPolicyEnforcerTest, ConformsToCTPolicyWithPooledEmbeddedSCTs) { @@ -230,9 +230,9 @@ ct::SignedCertificateTimestamp::SCT_FROM_OCSP_RESPONSE, desired_logs.size(), desired_logs, true, &scts); - EXPECT_EQ(ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS, - policy_enforcer_->DoesConformToCertPolicy(chain_.get(), scts, - NetLogWithSource())); + EXPECT_EQ(ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS, + policy_enforcer_->CheckCompliance(chain_.get(), scts, + NetLogWithSource())); } TEST_F(CTPolicyEnforcerTest, DoesNotConformToCTPolicyNotEnoughSCTs) { @@ -241,9 +241,9 @@ FillListWithSCTsOfOrigin(ct::SignedCertificateTimestamp::SCT_EMBEDDED, 2, &scts); - EXPECT_EQ(ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS, - policy_enforcer_->DoesConformToCertPolicy(chain_.get(), scts, - NetLogWithSource())); + EXPECT_EQ(ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS, + policy_enforcer_->CheckCompliance(chain_.get(), scts, + NetLogWithSource())); } TEST_F(CTPolicyEnforcerTest, DoesNotConformToCTPolicyNotEnoughFreshSCTs) { @@ -258,9 +258,9 @@ ct::SignedCertificateTimestamp::SCT_FROM_TLS_EXTENSION, 1, &scts); AddDisqualifiedLogSCT(ct::SignedCertificateTimestamp::SCT_FROM_TLS_EXTENSION, false, &scts); - EXPECT_EQ(ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS, - policy_enforcer_->DoesConformToCertPolicy(chain_.get(), scts, - NetLogWithSource())); + EXPECT_EQ(ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS, + policy_enforcer_->CheckCompliance(chain_.get(), scts, + NetLogWithSource())); // SCT from after disqualification. scts.clear(); @@ -268,9 +268,9 @@ ct::SignedCertificateTimestamp::SCT_FROM_TLS_EXTENSION, 1, &scts); AddDisqualifiedLogSCT(ct::SignedCertificateTimestamp::SCT_FROM_TLS_EXTENSION, true, &scts); - EXPECT_EQ(ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS, - policy_enforcer_->DoesConformToCertPolicy(chain_.get(), scts, - NetLogWithSource())); + EXPECT_EQ(ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS, + policy_enforcer_->CheckCompliance(chain_.get(), scts, + NetLogWithSource())); // Embedded SCT from before disqualification. scts.clear(); @@ -278,9 +278,9 @@ ct::SignedCertificateTimestamp::SCT_FROM_TLS_EXTENSION, 1, &scts); AddDisqualifiedLogSCT(ct::SignedCertificateTimestamp::SCT_EMBEDDED, false, &scts); - EXPECT_EQ(ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS, - policy_enforcer_->DoesConformToCertPolicy(chain_.get(), scts, - NetLogWithSource())); + EXPECT_EQ(ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS, + policy_enforcer_->CheckCompliance(chain_.get(), scts, + NetLogWithSource())); // Embedded SCT from after disqualification. scts.clear(); @@ -288,9 +288,9 @@ ct::SignedCertificateTimestamp::SCT_FROM_TLS_EXTENSION, 1, &scts); AddDisqualifiedLogSCT(ct::SignedCertificateTimestamp::SCT_EMBEDDED, true, &scts); - EXPECT_EQ(ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS, - policy_enforcer_->DoesConformToCertPolicy(chain_.get(), scts, - NetLogWithSource())); + EXPECT_EQ(ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS, + policy_enforcer_->CheckCompliance(chain_.get(), scts, + NetLogWithSource())); } TEST_F(CTPolicyEnforcerTest, @@ -302,9 +302,9 @@ &scts); // |chain_| is valid for 10 years - over 121 months - so requires 5 SCTs. - EXPECT_EQ(ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS, - policy_enforcer_->DoesConformToCertPolicy(chain_.get(), scts, - NetLogWithSource())); + EXPECT_EQ(ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS, + policy_enforcer_->CheckCompliance(chain_.get(), scts, + NetLogWithSource())); } TEST_F(CTPolicyEnforcerTest, @@ -316,9 +316,9 @@ &scts); // |chain_| is valid for 10 years - over 121 months - so requires 5 SCTs. - EXPECT_EQ(ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS, - policy_enforcer_->DoesConformToCertPolicy(chain_.get(), scts, - NetLogWithSource())); + EXPECT_EQ(ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS, + policy_enforcer_->CheckCompliance(chain_.get(), scts, + NetLogWithSource())); } TEST_F(CTPolicyEnforcerTest, @@ -333,9 +333,9 @@ scts[i]->timestamp = scts[0]->timestamp; // |chain_| is valid for 10 years - over 121 months - so requires 5 SCTs. - EXPECT_EQ(ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS, - policy_enforcer_->DoesConformToCertPolicy(chain_.get(), scts, - NetLogWithSource())); + EXPECT_EQ(ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS, + policy_enforcer_->CheckCompliance(chain_.get(), scts, + NetLogWithSource())); } TEST_F(CTPolicyEnforcerTest, @@ -365,9 +365,9 @@ // |chain_| is valid for 10 years - over 121 months - so requires 5 SCTs. // However, there are only 4 SCTs are from distinct logs. - EXPECT_EQ(ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS, - policy_enforcer_->DoesConformToCertPolicy(chain_.get(), scts, - NetLogWithSource())); + EXPECT_EQ(ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS, + policy_enforcer_->CheckCompliance(chain_.get(), scts, + NetLogWithSource())); } TEST_F(CTPolicyEnforcerTest, @@ -441,9 +441,9 @@ ct::SCTList scts; FillListWithSCTsOfOrigin(ct::SignedCertificateTimestamp::SCT_EMBEDDED, i, std::vector<std::string>(), false, &scts); - EXPECT_EQ(ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS, - policy_enforcer_->DoesConformToCertPolicy(cert.get(), scts, - NetLogWithSource())) + EXPECT_EQ(ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS, + policy_enforcer_->CheckCompliance(cert.get(), scts, + NetLogWithSource())) << " for: " << (end - start).InDays() << " and " << required_scts << " scts=" << scts.size() << " i=" << i; } @@ -451,9 +451,9 @@ FillListWithSCTsOfOrigin(ct::SignedCertificateTimestamp::SCT_EMBEDDED, required_scts, std::vector<std::string>(), false, &scts); - EXPECT_EQ(ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS, - policy_enforcer_->DoesConformToCertPolicy(cert.get(), scts, - NetLogWithSource())) + EXPECT_EQ( + ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS, + policy_enforcer_->CheckCompliance(cert.get(), scts, NetLogWithSource())) << " for: " << (end - start).InDays() << " and " << required_scts << " scts=" << scts.size(); }
diff --git a/net/cert/ct_policy_status.h b/net/cert/ct_policy_status.h index ee6142c..eb167b61 100644 --- a/net/cert/ct_policy_status.h +++ b/net/cert/ct_policy_status.h
@@ -9,22 +9,25 @@ namespace ct { -// Information about the connection's compliance with the CT -// certificate policy. This value is histogrammed, so do not re-order or change -// values, and add new values at the end. -enum class CertPolicyCompliance { +// Information about the connection's compliance with the CT policy. This value +// is histogrammed, so do not re-order or change values, and add new values at +// the end. +enum class CTPolicyCompliance { // The connection complied with the certificate policy by // including SCTs that satisfy the policy. - CERT_POLICY_COMPLIES_VIA_SCTS = 0, + CT_POLICY_COMPLIES_VIA_SCTS = 0, // The connection did not have enough SCTs to comply. - CERT_POLICY_NOT_ENOUGH_SCTS = 1, + CT_POLICY_NOT_ENOUGH_SCTS = 1, // The connection did not have diverse enough SCTs to comply. - CERT_POLICY_NOT_DIVERSE_SCTS = 2, + CT_POLICY_NOT_DIVERSE_SCTS = 2, // The connection cannot be considered compliant because the build // isn't timely and therefore log information might be out of date // (for example a log might no longer be considered trustworthy). - CERT_POLICY_BUILD_NOT_TIMELY = 3, - CERT_POLICY_MAX + CT_POLICY_BUILD_NOT_TIMELY = 3, + // Compliance details for the connection are not available, e.g. because a + // resource was loaded from disk cache. + CT_POLICY_COMPLIANCE_DETAILS_NOT_AVAILABLE = 4, + CT_POLICY_MAX }; } // namespace ct
diff --git a/net/cert/ct_verify_result.cc b/net/cert/ct_verify_result.cc index 90b3716d1..b376241f 100644 --- a/net/cert/ct_verify_result.cc +++ b/net/cert/ct_verify_result.cc
@@ -11,9 +11,8 @@ namespace ct { CTVerifyResult::CTVerifyResult() - : ct_policies_applied(false), - cert_policy_compliance( - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS), + : policy_compliance( + ct::CTPolicyCompliance::CT_POLICY_COMPLIANCE_DETAILS_NOT_AVAILABLE), policy_compliance_required(false) {} CTVerifyResult::CTVerifyResult(const CTVerifyResult& other) = default;
diff --git a/net/cert/ct_verify_result.h b/net/cert/ct_verify_result.h index 0353b38d..4d7ad4f 100644 --- a/net/cert/ct_verify_result.h +++ b/net/cert/ct_verify_result.h
@@ -15,7 +15,7 @@ namespace ct { -enum class CertPolicyCompliance; +enum class CTPolicyCompliance; typedef std::vector<scoped_refptr<SignedCertificateTimestamp> > SCTList; @@ -30,13 +30,12 @@ // All SCTs and their statuses SignedCertificateTimestampAndStatusList scts; - // True if any CT policies were applied on this connection. - bool ct_policies_applied; // The result of evaluating whether the connection complies with the // CT certificate policy. - CertPolicyCompliance cert_policy_compliance; + CTPolicyCompliance policy_compliance; // True if the connection was required to comply with the CT certificate - // policy. This value is only meaningful if |ct_policies_applied| is true. + // policy. This value is not meaningful if |policy_compliance| is + // COMPLIANCE_DETAILS_NOT_AVAILABLE. bool policy_compliance_required; };
diff --git a/net/http/http_stream_factory_impl_job_controller.cc b/net/http/http_stream_factory_impl_job_controller.cc index 859e5043..94e72c27 100644 --- a/net/http/http_stream_factory_impl_job_controller.cc +++ b/net/http/http_stream_factory_impl_job_controller.cc
@@ -1316,6 +1316,8 @@ // Abandon all Jobs and start over. job_bound_ = false; bound_job_ = nullptr; + main_job_is_resumed_ = false; + main_job_is_blocked_ = false; alternative_job_.reset(); main_job_.reset(); next_state_ = STATE_RESOLVE_PROXY_COMPLETE;
diff --git a/net/http/http_stream_factory_impl_job_controller_unittest.cc b/net/http/http_stream_factory_impl_job_controller_unittest.cc index 4d9e394..43c03f7f 100644 --- a/net/http/http_stream_factory_impl_job_controller_unittest.cc +++ b/net/http/http_stream_factory_impl_job_controller_unittest.cc
@@ -556,6 +556,151 @@ EXPECT_TRUE(HttpStreamFactoryImplPeer::IsJobControllerDeleted(factory_)); } +// Tests that the main (HTTP) job is started after the alternative +// proxy server job has failed. There are 3 jobs in total that are run +// in the following sequence: alternative proxy server job, +// delayed HTTP job with the first proxy server, HTTP job with +// the second proxy configuration. The result of the last job (OK) +// should be returned to the delegate. +TEST_F(JobControllerReconsiderProxyAfterErrorTest, + SecondMainJobIsStartedAfterAltProxyServerJobFailed) { + // Configure the proxies and initialize the test. + std::unique_ptr<ProxyService> proxy_service = + ProxyService::CreateFixedFromPacResult("HTTPS myproxy.org:443; DIRECT"); + + auto test_proxy_delegate = std::make_unique<TestProxyDelegate>(); + test_proxy_delegate->set_alternative_proxy_server( + ProxyServer::FromPacString("QUIC myproxy.org:443")); + + Initialize(std::move(proxy_service), std::move(test_proxy_delegate)); + + // Enable delayed TCP and set time delay for waiting job. + QuicStreamFactory* quic_stream_factory = session_->quic_stream_factory(); + quic_stream_factory->set_require_confirmation(false); + ServerNetworkStats stats1; + stats1.srtt = base::TimeDelta::FromSeconds(100); + session_->http_server_properties()->SetServerNetworkStats( + url::SchemeHostPort(GURL("http://www.example.com")), stats1); + + // Prepare the mocked data. + MockQuicData quic_data; + quic_data.AddRead(ASYNC, ERR_QUIC_PROTOCOL_ERROR); + quic_data.AddWrite(ASYNC, OK); + quic_data.AddSocketDataToFactory(session_deps_.socket_factory.get()); + + StaticSocketDataProvider tcp_data_1; + tcp_data_1.set_connect_data(MockConnect(SYNCHRONOUS, ERR_CONNECTION_REFUSED)); + session_deps_.socket_factory->AddSocketDataProvider(&tcp_data_1); + + StaticSocketDataProvider tcp_data_2; + tcp_data_2.set_connect_data(MockConnect(SYNCHRONOUS, OK)); + session_deps_.socket_factory->AddSocketDataProvider(&tcp_data_2); + SSLSocketDataProvider ssl_data(SYNCHRONOUS, OK); + session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data); + + // Create a request. + HttpRequestInfo request_info; + request_info.method = "GET"; + request_info.url = GURL("http://www.example.com"); + AlternativeService alternative_service(kProtoQUIC, "www.example.com", 80); + SetAlternativeService(request_info, alternative_service); + + EXPECT_CALL(request_delegate_, OnStreamReadyImpl(_, _, _)).Times(1); + EXPECT_CALL(request_delegate_, OnStreamFailed(_, _, _)).Times(0); + + // Create the job controller. + std::unique_ptr<HttpStreamRequest> request = + CreateJobController(request_info); + + base::RunLoop().RunUntilIdle(); + + EXPECT_TRUE(quic_data.AllReadDataConsumed()); + EXPECT_TRUE(quic_data.AllWriteDataConsumed()); + EXPECT_TRUE(tcp_data_1.AllReadDataConsumed()); + EXPECT_TRUE(tcp_data_1.AllWriteDataConsumed()); + EXPECT_TRUE(tcp_data_2.AllReadDataConsumed()); + EXPECT_TRUE(tcp_data_2.AllWriteDataConsumed()); +} + +// Tests that the second main (HTTP) job is resumed after change in proxy +// configuration. When the proxy configuration changes, the job controller +// retries the previously failed jobs with the new configuration. Since there is +// an alternative job, the first and the second main jobs are delayed. The test +// verifies that the jobs are resumed after the alternative jobs failed. +// The result (OK) of the second main job should be returned to the delegate. +// Regression test for crbug.com/787148. +TEST_F(JobControllerReconsiderProxyAfterErrorTest, + SecondMainJobIsResumedAfterProxyConfigChange) { + // Initialize the test with direct connection. + std::unique_ptr<ProxyService> proxy_service = ProxyService::CreateDirect(); + ProxyService* proxy_service_raw = proxy_service.get(); + session_deps_.proxy_service = std::move(proxy_service); + + // Create a request. + HttpRequestInfo request_info; + request_info.method = "GET"; + request_info.url = GURL("https://www.example.com:443"); + + HttpStreamFactoryImplJobControllerTest::Initialize(request_info); + + // Add QUIC hint. + AlternativeService alternative_service(kProtoQUIC, "www.example.com", 443); + SetAlternativeService(request_info, alternative_service); + + // Enable delayed TCP and set time delay for waiting job. + QuicStreamFactory* quic_stream_factory = session_->quic_stream_factory(); + quic_stream_factory->set_require_confirmation(false); + ServerNetworkStats stats1; + stats1.srtt = base::TimeDelta::FromSeconds(100); + session_->http_server_properties()->SetServerNetworkStats( + url::SchemeHostPort(GURL("https://www.example.com:443")), stats1); + + // Prepare the mocked data. + crypto_client_stream_factory_.set_handshake_mode( + MockCryptoClientStream::COLD_START); + MockQuicData quic_data_1; + quic_data_1.AddRead(ASYNC, ERR_QUIC_PROTOCOL_ERROR); + quic_data_1.AddSocketDataToFactory(session_deps_.socket_factory.get()); + + StaticSocketDataProvider tcp_data_1; + tcp_data_1.set_connect_data(MockConnect(SYNCHRONOUS, ERR_CONNECTION_REFUSED)); + session_deps_.socket_factory->AddSocketDataProvider(&tcp_data_1); + + MockQuicData quic_data_2; + quic_data_2.AddRead(ASYNC, ERR_QUIC_PROTOCOL_ERROR); + quic_data_2.AddSocketDataToFactory(session_deps_.socket_factory.get()); + + StaticSocketDataProvider tcp_data_2; + tcp_data_2.set_connect_data(MockConnect(SYNCHRONOUS, OK)); + session_deps_.socket_factory->AddSocketDataProvider(&tcp_data_2); + SSLSocketDataProvider ssl_data(SYNCHRONOUS, OK); + session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data); + + EXPECT_CALL(request_delegate_, OnStreamReadyImpl(_, _, _)).Times(1); + EXPECT_CALL(request_delegate_, OnStreamFailed(_, _, _)).Times(0); + + // Create the job controller. + std::unique_ptr<HttpStreamRequest> request = + CreateJobController(request_info); + + // Calling ForceReloadProxyConfig will cause the proxy configuration to + // change. It will still be the direct connection but the configuration + // version will be bumped. That is enough for the job controller to restart + // the jobs. + proxy_service_raw->ForceReloadProxyConfig(); + + base::RunLoop().RunUntilIdle(); + + EXPECT_TRUE(quic_data_1.AllReadDataConsumed()); + EXPECT_TRUE(quic_data_1.AllWriteDataConsumed()); + EXPECT_TRUE(quic_data_2.AllReadDataConsumed()); + EXPECT_TRUE(quic_data_2.AllWriteDataConsumed()); + EXPECT_TRUE(tcp_data_1.AllReadDataConsumed()); + EXPECT_TRUE(tcp_data_1.AllWriteDataConsumed()); + EXPECT_TRUE(tcp_data_2.AllReadDataConsumed()); + EXPECT_TRUE(tcp_data_2.AllWriteDataConsumed()); +} + // Regression test for crbug.com/723589. TEST_P(JobControllerReconsiderProxyAfterErrorTest, ProxyResolutionSucceedsOnReconsiderAsync) {
diff --git a/net/http/http_util.cc b/net/http/http_util.cc index 52ff4a87..0bf40c3 100644 --- a/net/http/http_util.cc +++ b/net/http/http_util.cc
@@ -32,13 +32,12 @@ while (*begin < *end && HttpUtil::IsLWS((*end)[-1])) --(*end); } -} // namespace // Helpers -------------------------------------------------------------------- // Returns the index of the closing quote of the string, if any. |start| points // at the opening quote. -static size_t FindStringEnd(const std::string& line, size_t start, char delim) { +size_t FindStringEnd(const std::string& line, size_t start, char delim) { DCHECK_LT(start, line.length()); DCHECK_EQ(line[start], delim); DCHECK((delim == '"') || (delim == '\'')); @@ -51,7 +50,7 @@ } return line.length(); } - +} // namespace // HttpUtil ------------------------------------------------------------------- @@ -439,12 +438,6 @@ return base::StringPiece(begin, end - begin); } -bool HttpUtil::IsQuote(char c) { - // Single quote mark isn't actually part of quoted-text production, - // but apparently some servers rely on this. - return c == '"' || c == '\''; -} - bool HttpUtil::IsTokenChar(char c) { return !(c >= 0x7F || c <= 0x20 || c == '(' || c == ')' || c == '<' || c == '>' || c == '@' || c == ',' || c == ';' || c == ':' || @@ -477,6 +470,12 @@ } namespace { +bool IsQuote(char c) { + // Single quote mark isn't actually part of quoted-text production, + // but apparently some servers rely on this. + return c == '"' || c == '\''; +} + bool UnquoteImpl(std::string::const_iterator begin, std::string::const_iterator end, bool strict_quotes, @@ -486,7 +485,7 @@ return false; // Nothing to unquote. - if (!HttpUtil::IsQuote(*begin)) + if (!IsQuote(*begin)) return false; // Anything other than double quotes in strict mode. @@ -1058,7 +1057,10 @@ bool HttpUtil::NameValuePairsIterator::IsQuote(char c) const { if (strict_quotes_) return c == '"'; - return HttpUtil::IsQuote(c); + + // The call to the file-scoped IsQuote must be qualified to avoid re-entrantly + // calling NameValuePairsIterator::IsQuote again. + return net::IsQuote(c); } bool HttpUtil::ParseAcceptEncoding(const std::string& accept_encoding,
diff --git a/net/http/http_util.h b/net/http/http_util.h index 8f84ce1..a46a208a 100644 --- a/net/http/http_util.h +++ b/net/http/http_util.h
@@ -113,9 +113,6 @@ std::string::const_iterator* end); static base::StringPiece TrimLWS(const base::StringPiece& string); - // Whether the character is the start of a quotation mark. - static bool IsQuote(char c); - // Whether the character is a valid |tchar| as defined in RFC 7230 Sec 3.2.6. static bool IsTokenChar(char c); // Whether the string is a valid |token| as defined in RFC 7230 Sec 3.2.6.
diff --git a/net/http/transport_security_state.cc b/net/http/transport_security_state.cc index da9d3c4..425b387 100644 --- a/net/http/transport_security_state.cc +++ b/net/http/transport_security_state.cc
@@ -883,15 +883,18 @@ const SignedCertificateTimestampAndStatusList& signed_certificate_timestamps, const ExpectCTReportStatus report_status, - ct::CertPolicyCompliance cert_policy_compliance) { + ct::CTPolicyCompliance policy_compliance) { using CTRequirementLevel = RequireCTDelegate::CTRequirementLevel; std::string hostname = host_port_pair.host(); + // A connection is considered compliant if it has sufficient SCTs or if the + // build is outdated. Other statuses are not considered compliant; this + // includes COMPLIANCE_DETAILS_NOT_AVAILABLE because compliance must have been + // evaluated in order to determine that the connection is compliant. bool complies = - (cert_policy_compliance == - ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS || - cert_policy_compliance == - ct::CertPolicyCompliance::CERT_POLICY_BUILD_NOT_TIMELY); + (policy_compliance == + ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS || + policy_compliance == ct::CTPolicyCompliance::CT_POLICY_BUILD_NOT_TIMELY); // Check Expect-CT first so that other CT requirements do not prevent // Expect-CT reports from being sent. @@ -1469,12 +1472,13 @@ return; if (!ssl_info.is_issued_by_known_root) return; - if (!ssl_info.ct_compliance_details_available) - return; - if (ssl_info.ct_cert_policy_compliance == - ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS || - ssl_info.ct_cert_policy_compliance == - ct::CertPolicyCompliance::CERT_POLICY_BUILD_NOT_TIMELY) { + if (ssl_info.ct_policy_compliance == + ct::CTPolicyCompliance:: + CT_POLICY_COMPLIANCE_DETAILS_NOT_AVAILABLE || + ssl_info.ct_policy_compliance == + ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS || + ssl_info.ct_policy_compliance == + ct::CTPolicyCompliance::CT_POLICY_BUILD_NOT_TIMELY) { return; } ExpectCTState state; @@ -1503,10 +1507,8 @@ // public root or did not comply with CT policy. if (!ssl_info.is_issued_by_known_root) return; - if (!ssl_info.ct_compliance_details_available) - return; - if (ssl_info.ct_cert_policy_compliance != - ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS) { + if (ssl_info.ct_policy_compliance != + ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS) { // If an Expect-CT header is observed over a non-compliant connection, the // site owner should be notified about the misconfiguration. If the site was // already opted in to Expect-CT, this report would have been sent at @@ -1514,10 +1516,13 @@ // however, the lack of CT compliance would not have been evaluated/reported // at connection setup time, so it needs to be reported here while // processing the header. - if (ssl_info.ct_cert_policy_compliance == - ct::CertPolicyCompliance::CERT_POLICY_BUILD_NOT_TIMELY) { + if (ssl_info.ct_policy_compliance == + ct::CTPolicyCompliance::CT_POLICY_BUILD_NOT_TIMELY || + ssl_info.ct_policy_compliance == + ct::CTPolicyCompliance:: + CT_POLICY_COMPLIANCE_DETAILS_NOT_AVAILABLE) { // Only send reports for truly non-compliant connections, not those for - // which compliance wasn't checked due to an out-of-date build. + // which compliance wasn't checked. return; } ExpectCTState state;
diff --git a/net/http/transport_security_state.h b/net/http/transport_security_state.h index 92bb51d..79d3a1c 100644 --- a/net/http/transport_security_state.h +++ b/net/http/transport_security_state.h
@@ -27,7 +27,7 @@ namespace net { namespace ct { -enum class CertPolicyCompliance; +enum class CTPolicyCompliance; }; class HostPortPair; @@ -392,7 +392,7 @@ // requirements: that is, if a connection to |host|, using the validated // certificate |validated_certificate_chain|, is expected to be accompanied // with valid Certificate Transparency information that complies with the - // connection's CTPolicyEnforcer and |cert_policy_compliance| indicates that + // connection's CTPolicyEnforcer and |policy_compliance| indicates that // the connection does not comply. // // The behavior may be further be altered by setting a RequireCTDelegate @@ -411,7 +411,7 @@ const SignedCertificateTimestampAndStatusList& signed_certificate_timestamps, const ExpectCTReportStatus report_status, - ct::CertPolicyCompliance cert_policy_compliance); + ct::CTPolicyCompliance policy_compliance); // Assign a |Delegate| for persisting the transport security state. If // |NULL|, state will not be persisted. The caller retains
diff --git a/net/http/transport_security_state_unittest.cc b/net/http/transport_security_state_unittest.cc index 6c4cc15..373e176 100644 --- a/net/http/transport_security_state_unittest.cc +++ b/net/http/transport_security_state_unittest.cc
@@ -1447,9 +1447,8 @@ TEST_F(TransportSecurityStateTest, InvalidExpectCTHeader) { HostPortPair host_port(kExpectCTStaticHostname, 443); SSLInfo ssl_info; - ssl_info.ct_compliance_details_available = true; - ssl_info.ct_cert_policy_compliance = - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS; + ssl_info.ct_policy_compliance = + ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS; ssl_info.is_issued_by_known_root = true; scoped_refptr<X509Certificate> cert1 = ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"); @@ -1479,9 +1478,8 @@ TEST_F(TransportSecurityStateTest, ExpectCTNonPublicRoot) { HostPortPair host_port(kExpectCTStaticHostname, 443); SSLInfo ssl_info; - ssl_info.ct_compliance_details_available = true; - ssl_info.ct_cert_policy_compliance = - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS; + ssl_info.ct_policy_compliance = + ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS; ssl_info.is_issued_by_known_root = false; scoped_refptr<X509Certificate> cert1 = ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"); @@ -1509,9 +1507,8 @@ TEST_F(TransportSecurityStateTest, ExpectCTComplianceNotAvailable) { HostPortPair host_port(kExpectCTStaticHostname, 443); SSLInfo ssl_info; - ssl_info.ct_compliance_details_available = false; - ssl_info.ct_cert_policy_compliance = - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS; + ssl_info.ct_policy_compliance = + ct::CTPolicyCompliance::CT_POLICY_COMPLIANCE_DETAILS_NOT_AVAILABLE; ssl_info.is_issued_by_known_root = true; scoped_refptr<X509Certificate> cert1 = ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"); @@ -1529,7 +1526,8 @@ state.ProcessExpectCTHeader("preload", host_port, ssl_info); EXPECT_EQ(0u, reporter.num_failures()); - ssl_info.ct_compliance_details_available = true; + ssl_info.ct_policy_compliance = + ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS; state.ProcessExpectCTHeader("preload", host_port, ssl_info); EXPECT_EQ(1u, reporter.num_failures()); } @@ -1539,9 +1537,8 @@ TEST_F(TransportSecurityStateTest, ExpectCTCompliantCert) { HostPortPair host_port(kExpectCTStaticHostname, 443); SSLInfo ssl_info; - ssl_info.ct_compliance_details_available = true; - ssl_info.ct_cert_policy_compliance = - ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS; + ssl_info.ct_policy_compliance = + ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS; ssl_info.is_issued_by_known_root = true; scoped_refptr<X509Certificate> cert1 = ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"); @@ -1559,8 +1556,8 @@ state.ProcessExpectCTHeader("preload", host_port, ssl_info); EXPECT_EQ(0u, reporter.num_failures()); - ssl_info.ct_cert_policy_compliance = - ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS; + ssl_info.ct_policy_compliance = + ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS; state.ProcessExpectCTHeader("preload", host_port, ssl_info); EXPECT_EQ(1u, reporter.num_failures()); } @@ -1570,9 +1567,8 @@ TEST_F(TransportSecurityStateTest, PreloadedExpectCTBuildNotTimely) { HostPortPair host_port(kExpectCTStaticHostname, 443); SSLInfo ssl_info; - ssl_info.ct_compliance_details_available = true; - ssl_info.ct_cert_policy_compliance = - ct::CertPolicyCompliance::CERT_POLICY_BUILD_NOT_TIMELY; + ssl_info.ct_policy_compliance = + ct::CTPolicyCompliance::CT_POLICY_BUILD_NOT_TIMELY; ssl_info.is_issued_by_known_root = true; scoped_refptr<X509Certificate> cert1 = ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"); @@ -1592,8 +1588,8 @@ // Sanity-check that the reporter is notified if the build is timely and the // connection is not compliant. - ssl_info.ct_cert_policy_compliance = - ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS; + ssl_info.ct_policy_compliance = + ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS; state.ProcessExpectCTHeader("preload", host_port, ssl_info); EXPECT_EQ(1u, reporter.num_failures()); } @@ -1603,9 +1599,8 @@ TEST_F(TransportSecurityStateTest, DynamicExpectCTBuildNotTimely) { HostPortPair host_port("example.test", 443); SSLInfo ssl_info; - ssl_info.ct_compliance_details_available = true; - ssl_info.ct_cert_policy_compliance = - ct::CertPolicyCompliance::CERT_POLICY_BUILD_NOT_TIMELY; + ssl_info.ct_policy_compliance = + ct::CTPolicyCompliance::CT_POLICY_BUILD_NOT_TIMELY; ssl_info.is_issued_by_known_root = true; scoped_refptr<X509Certificate> cert1 = ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"); @@ -1629,8 +1624,8 @@ // Sanity-check that the reporter is notified if the build is timely and the // connection is not compliant. - ssl_info.ct_cert_policy_compliance = - ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS; + ssl_info.ct_policy_compliance = + ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS; state.ProcessExpectCTHeader(kHeader, host_port, ssl_info); EXPECT_EQ(1u, reporter.num_failures()); } @@ -1640,9 +1635,8 @@ TEST_F(TransportSecurityStateTest, ExpectCTNotPreloaded) { HostPortPair host_port("not-expect-ct-preloaded.test", 443); SSLInfo ssl_info; - ssl_info.ct_compliance_details_available = true; - ssl_info.ct_cert_policy_compliance = - ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS; + ssl_info.ct_policy_compliance = + ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS; ssl_info.is_issued_by_known_root = true; scoped_refptr<X509Certificate> cert1 = ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"); @@ -1670,9 +1664,8 @@ TEST_F(TransportSecurityStateTest, ExpectCTReporter) { HostPortPair host_port(kExpectCTStaticHostname, 443); SSLInfo ssl_info; - ssl_info.ct_compliance_details_available = true; - ssl_info.ct_cert_policy_compliance = - ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS; + ssl_info.ct_policy_compliance = + ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS; ssl_info.is_issued_by_known_root = true; scoped_refptr<X509Certificate> cert1 = ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"); @@ -1712,9 +1705,8 @@ TEST_F(TransportSecurityStateTest, RepeatedExpectCTReportsForStaticExpectCT) { HostPortPair host_port(kExpectCTStaticHostname, 443); SSLInfo ssl_info; - ssl_info.ct_compliance_details_available = true; - ssl_info.ct_cert_policy_compliance = - ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS; + ssl_info.ct_policy_compliance = + ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS; ssl_info.is_issued_by_known_root = true; scoped_refptr<X509Certificate> cert1 = ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"); @@ -2238,7 +2230,7 @@ HostPortPair("www.example.com", 443), true, hashes, cert.get(), cert.get(), SignedCertificateTimestampAndStatusList(), TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS); + ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS); MockRequireCTDelegate always_require_delegate; EXPECT_CALL(always_require_delegate, IsCTRequiredForHost(_)) @@ -2250,28 +2242,28 @@ HostPortPair("www.example.com", 443), true, hashes, cert.get(), cert.get(), SignedCertificateTimestampAndStatusList(), TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS)); + ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS)); EXPECT_EQ( TransportSecurityState::CT_REQUIREMENTS_NOT_MET, state.CheckCTRequirements( HostPortPair("www.example.com", 443), true, hashes, cert.get(), cert.get(), SignedCertificateTimestampAndStatusList(), TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS)); + ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS)); EXPECT_EQ( TransportSecurityState::CT_REQUIREMENTS_MET, state.CheckCTRequirements( HostPortPair("www.example.com", 443), true, hashes, cert.get(), cert.get(), SignedCertificateTimestampAndStatusList(), TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS)); + ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS)); EXPECT_EQ( TransportSecurityState::CT_REQUIREMENTS_MET, state.CheckCTRequirements( HostPortPair("www.example.com", 443), true, hashes, cert.get(), cert.get(), SignedCertificateTimestampAndStatusList(), TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_BUILD_NOT_TIMELY)); + ct::CTPolicyCompliance::CT_POLICY_BUILD_NOT_TIMELY)); state.SetRequireCTDelegate(nullptr); EXPECT_EQ( @@ -2280,7 +2272,7 @@ HostPortPair("www.example.com", 443), true, hashes, cert.get(), cert.get(), SignedCertificateTimestampAndStatusList(), TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS)); + ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS)); } { @@ -2290,7 +2282,7 @@ HostPortPair("www.example.com", 443), true, hashes, cert.get(), cert.get(), SignedCertificateTimestampAndStatusList(), TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS); + ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS); MockRequireCTDelegate never_require_delegate; EXPECT_CALL(never_require_delegate, IsCTRequiredForHost(_)) @@ -2302,14 +2294,14 @@ HostPortPair("www.example.com", 443), true, hashes, cert.get(), cert.get(), SignedCertificateTimestampAndStatusList(), TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS)); + ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS)); EXPECT_EQ( TransportSecurityState::CT_NOT_REQUIRED, state.CheckCTRequirements( HostPortPair("www.example.com", 443), true, hashes, cert.get(), cert.get(), SignedCertificateTimestampAndStatusList(), TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS)); + ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS)); state.SetRequireCTDelegate(nullptr); EXPECT_EQ( @@ -2318,7 +2310,7 @@ HostPortPair("www.example.com", 443), true, hashes, cert.get(), cert.get(), SignedCertificateTimestampAndStatusList(), TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS)); + ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS)); } { @@ -2328,7 +2320,7 @@ HostPortPair("www.example.com", 443), true, hashes, cert.get(), cert.get(), SignedCertificateTimestampAndStatusList(), TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS); + ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS); MockRequireCTDelegate default_require_ct_delegate; EXPECT_CALL(default_require_ct_delegate, IsCTRequiredForHost(_)) @@ -2340,7 +2332,7 @@ HostPortPair("www.example.com", 443), true, hashes, cert.get(), cert.get(), SignedCertificateTimestampAndStatusList(), TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS)); + ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS)); state.SetRequireCTDelegate(nullptr); EXPECT_EQ( @@ -2349,7 +2341,7 @@ HostPortPair("www.example.com", 443), true, hashes, cert.get(), cert.get(), SignedCertificateTimestampAndStatusList(), TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS)); + ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS)); } } @@ -2387,7 +2379,7 @@ HostPortPair("www.example.com", 443), true, hashes, before_cert.get(), before_cert.get(), SignedCertificateTimestampAndStatusList(), TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS)); + ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS)); // ... but certificates issued after 1 June 2016 are required to be... EXPECT_EQ( @@ -2396,28 +2388,28 @@ HostPortPair("www.example.com", 443), true, hashes, after_cert.get(), after_cert.get(), SignedCertificateTimestampAndStatusList(), TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS)); + ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS)); EXPECT_EQ( TransportSecurityState::CT_REQUIREMENTS_NOT_MET, state.CheckCTRequirements( HostPortPair("www.example.com", 443), true, hashes, after_cert.get(), after_cert.get(), SignedCertificateTimestampAndStatusList(), TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS)); + ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS)); EXPECT_EQ( TransportSecurityState::CT_REQUIREMENTS_MET, state.CheckCTRequirements( HostPortPair("www.example.com", 443), true, hashes, after_cert.get(), after_cert.get(), SignedCertificateTimestampAndStatusList(), TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_BUILD_NOT_TIMELY)); + ct::CTPolicyCompliance::CT_POLICY_BUILD_NOT_TIMELY)); EXPECT_EQ( TransportSecurityState::CT_REQUIREMENTS_MET, state.CheckCTRequirements( HostPortPair("www.example.com", 443), true, hashes, after_cert.get(), after_cert.get(), SignedCertificateTimestampAndStatusList(), TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS)); + ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS)); // ... unless they were issued by an excluded intermediate. hashes.push_back(HashValue(google_hash_value)); @@ -2427,14 +2419,14 @@ HostPortPair("www.example.com", 443), true, hashes, before_cert.get(), before_cert.get(), SignedCertificateTimestampAndStatusList(), TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS)); + ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS)); EXPECT_EQ( TransportSecurityState::CT_NOT_REQUIRED, state.CheckCTRequirements( HostPortPair("www.example.com", 443), true, hashes, after_cert.get(), after_cert.get(), SignedCertificateTimestampAndStatusList(), TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS)); + ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS)); // And other certificates should remain unaffected. SHA256HashValue unrelated_hash_value = {{0x01, 0x02}}; @@ -2447,14 +2439,14 @@ before_cert.get(), before_cert.get(), SignedCertificateTimestampAndStatusList(), TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS)); + ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS)); EXPECT_EQ(TransportSecurityState::CT_NOT_REQUIRED, state.CheckCTRequirements( HostPortPair("www.example.com", 443), true, unrelated_hashes, after_cert.get(), after_cert.get(), SignedCertificateTimestampAndStatusList(), TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS)); + ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS)); // And the emergency field trial should disable the requirement, if // necessary. @@ -2471,14 +2463,14 @@ HostPortPair("www.example.com", 443), true, hashes, before_cert.get(), before_cert.get(), SignedCertificateTimestampAndStatusList(), TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS)); + ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS)); EXPECT_EQ( TransportSecurityState::CT_NOT_REQUIRED, state.CheckCTRequirements( HostPortPair("www.example.com", 443), true, hashes, after_cert.get(), after_cert.get(), SignedCertificateTimestampAndStatusList(), TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS)); + ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS)); } // Tests that dynamic Expect-CT state is cleared from ClearDynamicData(). @@ -2541,9 +2533,8 @@ const char kHeader[] = "max-age=123,enforce,report-uri=\"http://foo.test\""; SSLInfo ssl; ssl.is_issued_by_known_root = true; - ssl.ct_compliance_details_available = true; - ssl.ct_cert_policy_compliance = - ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS; + ssl.ct_policy_compliance = + ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS; scoped_refptr<X509Certificate> cert1 = ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"); @@ -2578,7 +2569,7 @@ HostPortPair("example.test", 443), true, HashValueVector(), cert1.get(), cert2.get(), sct_list, TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS)); + ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS)); EXPECT_EQ(1u, reporter.num_failures()); // The second time it fails to meet CT requirements, a report should not be @@ -2588,7 +2579,7 @@ HostPortPair("example.test", 443), true, HashValueVector(), cert1.get(), cert2.get(), sct_list, TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS)); + ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS)); EXPECT_EQ(1u, reporter.num_failures()); } @@ -2598,9 +2589,8 @@ const char kHeader[] = "max-age=123,report-uri=\"http://foo.test\""; SSLInfo ssl; ssl.is_issued_by_known_root = true; - ssl.ct_compliance_details_available = true; - ssl.ct_cert_policy_compliance = - ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS; + ssl.ct_policy_compliance = + ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS; scoped_refptr<X509Certificate> cert1 = ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"); @@ -2627,7 +2617,7 @@ HostPortPair("example.test", 443), true, HashValueVector(), cert1.get(), cert2.get(), sct_list, TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS)); + ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS)); EXPECT_EQ(0u, reporter.num_failures()); } @@ -2637,9 +2627,7 @@ const char kHeader[] = "max-age=123,enforce,report-uri=\"http://foo.test\""; SSLInfo ssl; ssl.is_issued_by_known_root = true; - ssl.ct_compliance_details_available = true; - ssl.ct_cert_policy_compliance = - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS; + ssl.ct_policy_compliance = ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS; base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature( @@ -2681,9 +2669,8 @@ const char kHeader[] = "max-age=123,enforce,report-uri=\"http://foo.test\""; SSLInfo ssl; ssl.is_issued_by_known_root = true; - ssl.ct_compliance_details_available = true; - ssl.ct_cert_policy_compliance = - ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS; + ssl.ct_policy_compliance = + ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS; // First test that the header is not processed when the feature is disabled. { @@ -2726,9 +2713,7 @@ const char kHeader[] = "max-age=123,enforce,report-uri=\"http://foo.test\""; SSLInfo ssl; ssl.is_issued_by_known_root = false; - ssl.ct_compliance_details_available = true; - ssl.ct_cert_policy_compliance = - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS; + ssl.ct_policy_compliance = ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS; base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature( @@ -2748,9 +2733,8 @@ const char kHeader[] = "max-age=123,enforce,report-uri=\"http://foo.test\""; SSLInfo ssl; ssl.is_issued_by_known_root = true; - ssl.ct_compliance_details_available = false; - ssl.ct_cert_policy_compliance = - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS; + ssl.ct_policy_compliance = + ct::CTPolicyCompliance::CT_POLICY_COMPLIANCE_DETAILS_NOT_AVAILABLE; scoped_refptr<X509Certificate> cert1 = ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"); @@ -2780,9 +2764,7 @@ const char kHeader[] = "max-age=123,enforce,report-uri=\"http://foo.test\""; SSLInfo ssl; ssl.is_issued_by_known_root = true; - ssl.ct_compliance_details_available = true; - ssl.ct_cert_policy_compliance = - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS; + ssl.ct_policy_compliance = ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS; scoped_refptr<X509Certificate> cert1 = ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"); @@ -2856,13 +2838,13 @@ HostPortPair("example2.test", 443), true, HashValueVector(), cert1.get(), cert2.get(), sct_list, TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS)); + ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS)); EXPECT_EQ(TransportSecurityState::CT_NOT_REQUIRED, state.CheckCTRequirements( HostPortPair("example2.test", 443), true, HashValueVector(), cert1.get(), cert2.get(), sct_list, TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS)); + ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS)); EXPECT_EQ(0u, reporter.num_failures()); // A connection to an Expect-CT host should be closed and reported. @@ -2871,7 +2853,7 @@ HostPortPair("example.test", 443), true, HashValueVector(), cert1.get(), cert2.get(), sct_list, TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS)); + ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS)); EXPECT_EQ(1u, reporter.num_failures()); EXPECT_EQ("example.test", reporter.host_port_pair().host()); EXPECT_EQ(443, reporter.host_port_pair().port()); @@ -2890,14 +2872,14 @@ HostPortPair("example.test", 443), true, HashValueVector(), cert1.get(), cert2.get(), sct_list, TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS)); + ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS)); EXPECT_EQ(1u, reporter.num_failures()); EXPECT_EQ(TransportSecurityState::CT_REQUIREMENTS_MET, state.CheckCTRequirements( HostPortPair("example.test", 443), true, HashValueVector(), cert1.get(), cert2.get(), sct_list, TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_BUILD_NOT_TIMELY)); + ct::CTPolicyCompliance::CT_POLICY_BUILD_NOT_TIMELY)); EXPECT_EQ(1u, reporter.num_failures()); // A connection to a report-only host should be reported only. @@ -2906,7 +2888,7 @@ HostPortPair("example-report-only.test", 443), true, HashValueVector(), cert1.get(), cert2.get(), sct_list, TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS)); + ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS)); EXPECT_EQ(2u, reporter.num_failures()); EXPECT_EQ("example-report-only.test", reporter.host_port_pair().host()); EXPECT_EQ(443, reporter.host_port_pair().port()); @@ -2923,7 +2905,7 @@ HostPortPair("example-enforce-only.test", 443), true, HashValueVector(), cert1.get(), cert2.get(), sct_list, TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS)); + ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS)); EXPECT_EQ(2u, reporter.num_failures()); // A connection with a private root should be neither enforced nor reported. @@ -2932,7 +2914,7 @@ HostPortPair("example.test", 443), false, HashValueVector(), cert1.get(), cert2.get(), sct_list, TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS)); + ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS)); EXPECT_EQ(2u, reporter.num_failures()); // A connection with DISABLE_EXPECT_CT_REPORTS should not send a report. @@ -2941,7 +2923,7 @@ HostPortPair("example.test", 443), true, HashValueVector(), cert1.get(), cert2.get(), sct_list, TransportSecurityState::DISABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS)); + ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS)); EXPECT_EQ(2u, reporter.num_failures()); } @@ -2987,7 +2969,7 @@ HostPortPair("example.test", 443), true, HashValueVector(), cert1.get(), cert2.get(), sct_list, TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS)); + ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS)); EXPECT_EQ(1u, reporter.num_failures()); EXPECT_EQ("example.test", reporter.host_port_pair().host()); EXPECT_EQ(443, reporter.host_port_pair().port()); @@ -3005,9 +2987,8 @@ const char kHistogramName[] = "Net.ExpectCTHeader.ParseSuccess"; SSLInfo ssl; ssl.is_issued_by_known_root = true; - ssl.ct_compliance_details_available = true; - ssl.ct_cert_policy_compliance = - ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS; + ssl.ct_policy_compliance = + ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS; base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature(
diff --git a/net/http2/hpack/decoder/hpack_decoder_tables.h b/net/http2/hpack/decoder/hpack_decoder_tables.h index 6a351168..1de2814 100644 --- a/net/http2/hpack/decoder/hpack_decoder_tables.h +++ b/net/http2/hpack/decoder/hpack_decoder_tables.h
@@ -23,7 +23,7 @@ #include "base/containers/circular_deque.h" #include "base/macros.h" #include "net/http2/hpack/hpack_string.h" -#include "net/http2/http2_constants.h" +//#include "net/http2/http2_constants.h" #include "net/http2/platform/api/http2_export.h" namespace net { @@ -132,7 +132,7 @@ // The last received DynamicTableSizeUpdate value, initialized to // SETTINGS_HEADER_TABLE_SIZE. - size_t size_limit_ = Http2SettingsInfo::DefaultHeaderTableSize(); + size_t size_limit_ = 4096; // Http2SettingsInfo::DefaultHeaderTableSize(); size_t current_size_ = 0;
diff --git a/net/log/net_log_event_type_list.h b/net/log/net_log_event_type_list.h index ca31d64..55195316 100644 --- a/net/log/net_log_event_type_list.h +++ b/net/log/net_log_event_type_list.h
@@ -2237,9 +2237,7 @@ // // The BEGIN phase consists of the following parameters: // { -// "event_type": A string indicating the type of fetch event. Generally it is -// either a fetch or foreignfetch event; fetch events are additionally -// categorized by resource type. +// "event_type": A string indicating the resource type being fetched. // } // // For the END phase, the following parameters are attached. No parameters are
diff --git a/net/quic/chromium/crypto/proof_verifier_chromium.cc b/net/quic/chromium/crypto/proof_verifier_chromium.cc index 84051c0f..22402263 100644 --- a/net/quic/chromium/crypto/proof_verifier_chromium.cc +++ b/net/quic/chromium/crypto/proof_verifier_chromium.cc
@@ -391,16 +391,15 @@ if (enforce_policy_checking_ && (result == OK || (IsCertificateError(result) && IsCertStatusMinorError(cert_status)))) { - verify_details_->ct_verify_result.ct_policies_applied = true; SCTList verified_scts = ct::SCTsMatchingStatus( verify_details_->ct_verify_result.scts, ct::SCT_STATUS_OK); - verify_details_->ct_verify_result.cert_policy_compliance = - policy_enforcer_->DoesConformToCertPolicy( + verify_details_->ct_verify_result.policy_compliance = + policy_enforcer_->CheckCompliance( cert_verify_result.verified_cert.get(), verified_scts, net_log_); if (verify_details_->cert_verify_result.cert_status & CERT_STATUS_IS_EV) { - if (verify_details_->ct_verify_result.cert_policy_compliance != - ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS) { + if (verify_details_->ct_verify_result.policy_compliance != + ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS) { verify_details_->cert_verify_result.cert_status |= CERT_STATUS_CT_COMPLIANCE_FAILED; verify_details_->cert_verify_result.cert_status &= ~CERT_STATUS_IS_EV; @@ -411,16 +410,16 @@ // compliance. UMA_HISTOGRAM_ENUMERATION( "Net.CertificateTransparency.EVCompliance.QUIC", - verify_details_->ct_verify_result.cert_policy_compliance, - ct::CertPolicyCompliance::CERT_POLICY_MAX); + verify_details_->ct_verify_result.policy_compliance, + ct::CTPolicyCompliance::CT_POLICY_MAX); } // Record the CT compliance of every connection to get an overall picture of // how many connections are CT-compliant. UMA_HISTOGRAM_ENUMERATION( "Net.CertificateTransparency.ConnectionComplianceStatus.QUIC", - verify_details_->ct_verify_result.cert_policy_compliance, - ct::CertPolicyCompliance::CERT_POLICY_MAX); + verify_details_->ct_verify_result.policy_compliance, + ct::CTPolicyCompliance::CT_POLICY_MAX); int ct_result = OK; TransportSecurityState::CTRequirementsStatus ct_requirement_status = @@ -431,7 +430,7 @@ cert_verify_result.verified_cert.get(), cert_.get(), verify_details_->ct_verify_result.scts, TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - verify_details_->ct_verify_result.cert_policy_compliance); + verify_details_->ct_verify_result.policy_compliance); if (ct_requirement_status != TransportSecurityState::CT_NOT_REQUIRED) { verify_details_->ct_verify_result.policy_compliance_required = true; // Record the CT compliance of connections for which compliance is @@ -440,8 +439,8 @@ UMA_HISTOGRAM_ENUMERATION( "Net.CertificateTransparency.CTRequiredConnectionComplianceStatus." "QUIC", - verify_details_->ct_verify_result.cert_policy_compliance, - ct::CertPolicyCompliance::CERT_POLICY_MAX); + verify_details_->ct_verify_result.policy_compliance, + ct::CTPolicyCompliance::CT_POLICY_MAX); } else { verify_details_->ct_verify_result.policy_compliance_required = false; }
diff --git a/net/quic/chromium/crypto/proof_verifier_chromium_test.cc b/net/quic/chromium/crypto/proof_verifier_chromium_test.cc index 12dbc1f..ab92045 100644 --- a/net/quic/chromium/crypto/proof_verifier_chromium_test.cc +++ b/net/quic/chromium/crypto/proof_verifier_chromium_test.cc
@@ -53,10 +53,10 @@ // A mock CTPolicyEnforcer that returns a custom verification result. class MockCTPolicyEnforcer : public CTPolicyEnforcer { public: - MOCK_METHOD3(DoesConformToCertPolicy, - ct::CertPolicyCompliance(X509Certificate* cert, - const ct::SCTList&, - const NetLogWithSource&)); + MOCK_METHOD3(CheckCompliance, + ct::CTPolicyCompliance(X509Certificate* cert, + const ct::SCTList&, + const NetLogWithSource&)); }; class MockRequireCTDelegate : public TransportSecurityState::RequireCTDelegate { @@ -109,9 +109,9 @@ NetLogWithSource())) {} void SetUp() override { - EXPECT_CALL(ct_policy_enforcer_, DoesConformToCertPolicy(_, _, _)) + EXPECT_CALL(ct_policy_enforcer_, CheckCompliance(_, _, _)) .WillRepeatedly( - Return(ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS)); + Return(ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS)); scoped_refptr<const CTLogVerifier> log( CTLogVerifier::Create(ct::GetTestPublicKey(), kLogDescription, @@ -286,9 +286,9 @@ MockCertVerifier dummy_verifier; dummy_verifier.AddResultForCert(test_cert.get(), dummy_result, OK); - EXPECT_CALL(ct_policy_enforcer_, DoesConformToCertPolicy(_, _, _)) + EXPECT_CALL(ct_policy_enforcer_, CheckCompliance(_, _, _)) .WillRepeatedly( - Return(ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS)); + Return(ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS)); ProofVerifierChromium proof_verifier(&dummy_verifier, &ct_policy_enforcer_, &transport_security_state_, @@ -322,9 +322,9 @@ MockCertVerifier dummy_verifier; dummy_verifier.AddResultForCert(test_cert.get(), dummy_result, OK); - EXPECT_CALL(ct_policy_enforcer_, DoesConformToCertPolicy(_, _, _)) + EXPECT_CALL(ct_policy_enforcer_, CheckCompliance(_, _, _)) .WillRepeatedly( - Return(ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS)); + Return(ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS)); ProofVerifierChromium proof_verifier(&dummy_verifier, &ct_policy_enforcer_, &transport_security_state_, @@ -362,9 +362,9 @@ MockCertVerifier dummy_verifier; dummy_verifier.AddResultForCert(test_cert.get(), dummy_result, OK); - EXPECT_CALL(ct_policy_enforcer_, DoesConformToCertPolicy(_, _, _)) + EXPECT_CALL(ct_policy_enforcer_, CheckCompliance(_, _, _)) .WillRepeatedly( - Return(ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS)); + Return(ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS)); ProofVerifierChromium proof_verifier(&dummy_verifier, &ct_policy_enforcer_, &transport_security_state_, @@ -387,8 +387,7 @@ histograms.ExpectUniqueSample( kHistogramName, - static_cast<int>(ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS), - 1); + static_cast<int>(ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS), 1); } // Tests that when a connection is CT-compliant and its EV status is preserved, @@ -407,9 +406,9 @@ MockCertVerifier dummy_verifier; dummy_verifier.AddResultForCert(test_cert.get(), dummy_result, OK); - EXPECT_CALL(ct_policy_enforcer_, DoesConformToCertPolicy(_, _, _)) + EXPECT_CALL(ct_policy_enforcer_, CheckCompliance(_, _, _)) .WillRepeatedly( - Return(ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS)); + Return(ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS)); ProofVerifierChromium proof_verifier(&dummy_verifier, &ct_policy_enforcer_, &transport_security_state_, @@ -431,8 +430,7 @@ histograms.ExpectUniqueSample( kHistogramName, - static_cast<int>(ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS), - 1); + static_cast<int>(ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS), 1); } HashValueVector MakeHashValueVector(uint8_t tag) { @@ -545,9 +543,9 @@ EXPECT_CALL(require_ct_delegate, IsCTRequiredForHost(kTestHostname)) .WillRepeatedly(Return(TransportSecurityState::RequireCTDelegate:: CTRequirementLevel::REQUIRED)); - EXPECT_CALL(ct_policy_enforcer_, DoesConformToCertPolicy(_, _, _)) + EXPECT_CALL(ct_policy_enforcer_, CheckCompliance(_, _, _)) .WillRepeatedly( - Return(ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS)); + Return(ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS)); ProofVerifierChromium proof_verifier(&dummy_verifier, &ct_policy_enforcer_, &transport_security_state_, @@ -597,9 +595,9 @@ EXPECT_CALL(require_ct_delegate, IsCTRequiredForHost(kTestHostname)) .WillRepeatedly(Return(TransportSecurityState::RequireCTDelegate:: CTRequirementLevel::REQUIRED)); - EXPECT_CALL(ct_policy_enforcer_, DoesConformToCertPolicy(_, _, _)) + EXPECT_CALL(ct_policy_enforcer_, CheckCompliance(_, _, _)) .WillRepeatedly( - Return(ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS)); + Return(ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS)); ProofVerifierChromium proof_verifier(&dummy_verifier, &ct_policy_enforcer_, &transport_security_state_, @@ -615,8 +613,7 @@ histograms.ExpectUniqueSample( kHistogramName, - static_cast<int>(ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS), - 1); + static_cast<int>(ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS), 1); } // Test that when CT is required (in this case, by the delegate) and CT @@ -648,9 +645,9 @@ EXPECT_CALL(require_ct_delegate, IsCTRequiredForHost(kTestHostname)) .WillRepeatedly(Return(TransportSecurityState::RequireCTDelegate:: CTRequirementLevel::REQUIRED)); - EXPECT_CALL(ct_policy_enforcer_, DoesConformToCertPolicy(_, _, _)) + EXPECT_CALL(ct_policy_enforcer_, CheckCompliance(_, _, _)) .WillRepeatedly( - Return(ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS)); + Return(ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS)); ProofVerifierChromium proof_verifier(&dummy_verifier, &ct_policy_enforcer_, &transport_security_state_, @@ -666,8 +663,7 @@ histograms.ExpectUniqueSample( kHistogramName, - static_cast<int>(ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS), - 1); + static_cast<int>(ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS), 1); } // Test that when CT is not required (because of a private root, in this case), @@ -733,9 +729,9 @@ EXPECT_CALL(require_ct_delegate, IsCTRequiredForHost(kTestHostname)) .WillRepeatedly(Return(TransportSecurityState::RequireCTDelegate:: CTRequirementLevel::REQUIRED)); - EXPECT_CALL(ct_policy_enforcer_, DoesConformToCertPolicy(_, _, _)) + EXPECT_CALL(ct_policy_enforcer_, CheckCompliance(_, _, _)) .WillRepeatedly( - Return(ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS)); + Return(ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS)); ProofVerifierChromium proof_verifier(&dummy_verifier, &ct_policy_enforcer_, &transport_security_state_, @@ -776,9 +772,9 @@ dummy_verifier.AddResultForCert(test_cert.get(), dummy_result, OK); // Set up CT. - EXPECT_CALL(ct_policy_enforcer_, DoesConformToCertPolicy(_, _, _)) + EXPECT_CALL(ct_policy_enforcer_, CheckCompliance(_, _, _)) .WillRepeatedly( - Return(ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS)); + Return(ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS)); ProofVerifierChromium proof_verifier(&dummy_verifier, &ct_policy_enforcer_, &transport_security_state_, @@ -795,8 +791,7 @@ // The histogram should have been recorded with the CT compliance status. histograms.ExpectUniqueSample( kHistogramName, - static_cast<int>(ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS), - 1); + static_cast<int>(ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS), 1); } // Tests that when CT is required but the connection is not compliant, the @@ -819,9 +814,9 @@ EXPECT_CALL(require_ct_delegate, IsCTRequiredForHost(_)) .WillRepeatedly(Return(TransportSecurityState::RequireCTDelegate:: CTRequirementLevel::REQUIRED)); - EXPECT_CALL(ct_policy_enforcer_, DoesConformToCertPolicy(_, _, _)) + EXPECT_CALL(ct_policy_enforcer_, CheckCompliance(_, _, _)) .WillRepeatedly( - Return(ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS)); + Return(ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS)); ProofVerifierChromium proof_verifier(&dummy_verifier, &ct_policy_enforcer_, &transport_security_state_, @@ -861,9 +856,9 @@ EXPECT_CALL(require_ct_delegate, IsCTRequiredForHost(_)) .WillRepeatedly(Return(TransportSecurityState::RequireCTDelegate:: CTRequirementLevel::REQUIRED)); - EXPECT_CALL(ct_policy_enforcer_, DoesConformToCertPolicy(_, _, _)) + EXPECT_CALL(ct_policy_enforcer_, CheckCompliance(_, _, _)) .WillRepeatedly( - Return(ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS)); + Return(ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS)); ProofVerifierChromium proof_verifier(&dummy_verifier, &ct_policy_enforcer_, &transport_security_state_,
diff --git a/net/quic/core/quic_flags_list.h b/net/quic/core/quic_flags_list.h index 5129890..a3633cb 100644 --- a/net/quic/core/quic_flags_list.h +++ b/net/quic/core/quic_flags_list.h
@@ -209,3 +209,12 @@ QUIC_FLAG(bool, FLAGS_quic_reloadable_flag_quic_allow_multiple_acks_for_data2, false) + +// If true, calculate stream sequencer buffer block count in a way that +// guaranteed to be 2048. +QUIC_FLAG(bool, + FLAGS_quic_reloadable_flag_quic_fix_sequencer_buffer_block_count2, + false) + +// If true, use deframer from net/quic/http instead of net/http2. +QUIC_FLAG(bool, FLAGS_quic_reloadable_flag_quic_enable_hq_deframer, true)
diff --git a/net/quic/core/quic_spdy_session.cc b/net/quic/core/quic_spdy_session.cc index d41d49ca..6679b105 100644 --- a/net/quic/core/quic_spdy_session.cc +++ b/net/quic/core/quic_spdy_session.cc
@@ -14,6 +14,7 @@ #include "net/quic/platform/api/quic_flag_utils.h" #include "net/quic/platform/api/quic_flags.h" #include "net/quic/platform/api/quic_logging.h" +#include "net/quic/platform/api/quic_ptr_util.h" #include "net/quic/platform/api/quic_str_cat.h" #include "net/quic/platform/api/quic_text_utils.h" #include "net/spdy/core/http2_frame_decoder_adapter.h" @@ -295,10 +296,16 @@ supports_push_promise_(perspective() == Perspective::IS_CLIENT), cur_max_timestamp_(QuicTime::Zero()), prev_max_timestamp_(QuicTime::Zero()), + use_hq_deframer_(FLAGS_quic_reloadable_flag_quic_enable_hq_deframer), spdy_framer_(SpdyFramer::ENABLE_COMPRESSION), spdy_framer_visitor_(new SpdyFramerVisitor(this)) { - h2_deframer_.set_visitor(spdy_framer_visitor_.get()); - h2_deframer_.set_debug_visitor(spdy_framer_visitor_.get()); + if (use_hq_deframer_) { + hq_deframer_.set_visitor(spdy_framer_visitor_.get()); + hq_deframer_.set_debug_visitor(spdy_framer_visitor_.get()); + } else { + h2_deframer_.set_visitor(spdy_framer_visitor_.get()); + h2_deframer_.set_debug_visitor(spdy_framer_visitor_.get()); + } } QuicSpdySession::~QuicSpdySession() { @@ -381,8 +388,10 @@ QuicTime timestamp) { DCHECK(timestamp.IsInitialized()); UpdateCurMaxTimeStamp(timestamp); - return h2_deframer_.ProcessInput(static_cast<char*>(iov.iov_base), - iov.iov_len); + return use_hq_deframer_ ? hq_deframer_.ProcessInput( + static_cast<char*>(iov.iov_base), iov.iov_len) + : h2_deframer_.ProcessInput( + static_cast<char*>(iov.iov_base), iov.iov_len); } size_t QuicSpdySession::WriteHeaders( @@ -578,9 +587,15 @@ void QuicSpdySession::SetHpackDecoderDebugVisitor( std::unique_ptr<QuicHpackDebugVisitor> visitor) { - h2_deframer_.SetDecoderHeaderTableDebugVisitor( - std::unique_ptr<HeaderTableDebugVisitor>(new HeaderTableDebugVisitor( - connection()->helper()->GetClock(), std::move(visitor)))); + if (use_hq_deframer_) { + hq_deframer_.SetDecoderHeaderTableDebugVisitor( + std::unique_ptr<HeaderTableDebugVisitor>(new HeaderTableDebugVisitor( + connection()->helper()->GetClock(), std::move(visitor)))); + } else { + h2_deframer_.SetDecoderHeaderTableDebugVisitor( + std::unique_ptr<HeaderTableDebugVisitor>(new HeaderTableDebugVisitor( + connection()->helper()->GetClock(), std::move(visitor)))); + } } void QuicSpdySession::UpdateHeaderEncoderTableSize(uint32_t value) {
diff --git a/net/quic/core/quic_spdy_session.h b/net/quic/core/quic_spdy_session.h index bbcca3a..a2a4c3ce 100644 --- a/net/quic/core/quic_spdy_session.h +++ b/net/quic/core/quic_spdy_session.h
@@ -13,6 +13,7 @@ #include "net/quic/core/quic_headers_stream.h" #include "net/quic/core/quic_session.h" #include "net/quic/core/quic_spdy_stream.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_adapter.h" #include "net/quic/platform/api/quic_export.h" #include "net/quic/platform/api/quic_string_piece.h" #include "net/spdy/core/http2_frame_decoder_adapter.h" @@ -181,8 +182,13 @@ // Sets how much encoded data the hpack decoder of h2_deframer_ is willing to // buffer. void set_max_decode_buffer_size_bytes(size_t max_decode_buffer_size_bytes) { - h2_deframer_.GetHpackDecoder()->set_max_decode_buffer_size_bytes( - max_decode_buffer_size_bytes); + if (use_hq_deframer_) { + hq_deframer_.GetHpackDecoder()->set_max_decode_buffer_size_bytes( + max_decode_buffer_size_bytes); + } else { + h2_deframer_.GetHpackDecoder()->set_max_decode_buffer_size_bytes( + max_decode_buffer_size_bytes); + } } void set_max_uncompressed_header_bytes( @@ -250,8 +256,12 @@ QuicTime cur_max_timestamp_; QuicTime prev_max_timestamp_; + // TODO(ckrasic): remove |use_hq_deframer_| and |h2_deframer_| when + // FLAGS_quic_reloadable_flag_quic_enable_hq_deframer is deprecated. + bool use_hq_deframer_; SpdyFramer spdy_framer_; Http2DecoderAdapter h2_deframer_; + QuicHttpDecoderAdapter hq_deframer_; std::unique_ptr<SpdyFramerVisitor> spdy_framer_visitor_; DISALLOW_COPY_AND_ASSIGN(QuicSpdySession);
diff --git a/net/quic/core/quic_stream_sequencer_buffer.cc b/net/quic/core/quic_stream_sequencer_buffer.cc index 46defd06..befb4f3 100644 --- a/net/quic/core/quic_stream_sequencer_buffer.cc +++ b/net/quic/core/quic_stream_sequencer_buffer.cc
@@ -7,6 +7,7 @@ #include "base/format_macros.h" #include "net/quic/core/quic_constants.h" #include "net/quic/platform/api/quic_bug_tracker.h" +#include "net/quic/platform/api/quic_flag_utils.h" #include "net/quic/platform/api/quic_flags.h" #include "net/quic/platform/api/quic_logging.h" #include "net/quic/platform/api/quic_str_cat.h" @@ -16,6 +17,18 @@ namespace net { namespace { +size_t CalculateBlockCount(size_t max_capacity_bytes) { + if (FLAGS_quic_reloadable_flag_quic_fix_sequencer_buffer_block_count2) { + QUIC_FLAG_COUNT( + quic_reloadable_flag_quic_fix_sequencer_buffer_block_count2); + return (max_capacity_bytes + QuicStreamSequencerBuffer::kBlockSizeBytes - + 1) / + QuicStreamSequencerBuffer::kBlockSizeBytes; + } + return ceil(static_cast<double>(max_capacity_bytes) / + QuicStreamSequencerBuffer::kBlockSizeBytes); +} + // Upper limit of how many gaps allowed in buffer, which ensures a reasonable // number of iterations needed to find the right gap to fill when a frame // arrives. @@ -36,8 +49,7 @@ QuicStreamSequencerBuffer::QuicStreamSequencerBuffer(size_t max_capacity_bytes) : max_buffer_capacity_bytes_(max_capacity_bytes), - blocks_count_( - ceil(static_cast<double>(max_capacity_bytes) / kBlockSizeBytes)), + blocks_count_(CalculateBlockCount(max_capacity_bytes)), total_bytes_read_(0), blocks_(nullptr), destruction_indicator_(123456) {
diff --git a/net/quic/core/quic_stream_sequencer_buffer_test.cc b/net/quic/core/quic_stream_sequencer_buffer_test.cc index 344ca583..168debd 100644 --- a/net/quic/core/quic_stream_sequencer_buffer_test.cc +++ b/net/quic/core/quic_stream_sequencer_buffer_test.cc
@@ -83,6 +83,17 @@ string error_details_; }; +TEST_F(QuicStreamSequencerBufferTest, InitializeWithMaxRecvWindowSize) { + if (!FLAGS_quic_reloadable_flag_quic_fix_sequencer_buffer_block_count2) { + return; + } + ResetMaxCapacityBytes(16 * 1024 * 1024); // 16MB + EXPECT_EQ(2 * 1024u, // 16MB / 8KB = 2K + helper_->block_count()); + EXPECT_EQ(max_capacity_bytes_, helper_->max_buffer_capacity()); + EXPECT_TRUE(helper_->CheckInitialState()); +} + TEST_F(QuicStreamSequencerBufferTest, InitializationWithDifferentSizes) { const size_t kCapacity = 2 * QuicStreamSequencerBuffer::kBlockSizeBytes; ResetMaxCapacityBytes(kCapacity);
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_altsvc_payload_decoder.cc b/net/quic/http/decoder/payload_decoders/quic_http_altsvc_payload_decoder.cc new file mode 100644 index 0000000..f395914 --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_altsvc_payload_decoder.cc
@@ -0,0 +1,154 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/payload_decoders/quic_http_altsvc_payload_decoder.h" + +#include <stddef.h> + +#include "base/logging.h" +#include "base/macros.h" +#include "net/quic/http/decoder/quic_http_decode_buffer.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_listener.h" +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/quic_http_structures.h" +#include "net/quic/platform/api/quic_bug_tracker.h" + +namespace net { + +std::ostream& operator<<(std::ostream& out, + QuicHttpAltSvcQuicHttpPayloadDecoder::PayloadState v) { + switch (v) { + case QuicHttpAltSvcQuicHttpPayloadDecoder::PayloadState:: + kStartDecodingStruct: + return out << "kStartDecodingStruct"; + case QuicHttpAltSvcQuicHttpPayloadDecoder::PayloadState:: + kMaybeDecodedStruct: + return out << "kMaybeDecodedStruct"; + case QuicHttpAltSvcQuicHttpPayloadDecoder::PayloadState::kDecodingStrings: + return out << "kDecodingStrings"; + case QuicHttpAltSvcQuicHttpPayloadDecoder::PayloadState:: + kResumeDecodingStruct: + return out << "kResumeDecodingStruct"; + } + // Since the value doesn't come over the wire, only a programming bug should + // result in reaching this point. + int unknown = static_cast<int>(v); + QUIC_BUG << "Invalid QuicHttpAltSvcQuicHttpPayloadDecoder::PayloadState: " + << unknown; + return out << "QuicHttpAltSvcQuicHttpPayloadDecoder::PayloadState(" << unknown + << ")"; +} + +QuicHttpDecodeStatus QuicHttpAltSvcQuicHttpPayloadDecoder::StartDecodingPayload( + QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db) { + DVLOG(2) << "QuicHttpAltSvcQuicHttpPayloadDecoder::StartDecodingPayload: " + << state->frame_header(); + DCHECK_EQ(QuicHttpFrameType::ALTSVC, state->frame_header().type); + DCHECK_LE(db->Remaining(), state->frame_header().payload_length); + DCHECK_EQ(0, state->frame_header().flags); + + state->InitializeRemainders(); + payload_state_ = PayloadState::kStartDecodingStruct; + + return ResumeDecodingPayload(state, db); +} + +QuicHttpDecodeStatus +QuicHttpAltSvcQuicHttpPayloadDecoder::ResumeDecodingPayload( + QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db) { + const QuicHttpFrameHeader& frame_header = state->frame_header(); + DVLOG(2) << "QuicHttpAltSvcQuicHttpPayloadDecoder::ResumeDecodingPayload: " + << frame_header; + DCHECK_EQ(QuicHttpFrameType::ALTSVC, frame_header.type); + DCHECK_LE(state->remaining_payload(), frame_header.payload_length); + DCHECK_LE(db->Remaining(), state->remaining_payload()); + DCHECK_NE(PayloadState::kMaybeDecodedStruct, payload_state_); + QuicHttpDecodeStatus status = QuicHttpDecodeStatus::kDecodeError; + while (true) { + DVLOG(2) << "QuicHttpAltSvcQuicHttpPayloadDecoder::ResumeDecodingPayload " + "payload_state_=" + << payload_state_; + switch (payload_state_) { + case PayloadState::kStartDecodingStruct: + status = state->StartDecodingStructureInPayload(&altsvc_fields_, db); + // FALLTHROUGH_INTENDED; + + case PayloadState::kMaybeDecodedStruct: + if (status == QuicHttpDecodeStatus::kDecodeDone && + altsvc_fields_.origin_length <= state->remaining_payload()) { + size_t origin_length = altsvc_fields_.origin_length; + size_t value_length = state->remaining_payload() - origin_length; + state->listener()->OnAltSvcStart(frame_header, origin_length, + value_length); + } else if (status != QuicHttpDecodeStatus::kDecodeDone) { + DCHECK(state->remaining_payload() > 0 || + status == QuicHttpDecodeStatus::kDecodeError) + << "\nremaining_payload: " << state->remaining_payload() + << "\nstatus: " << status << "\nheader: " << frame_header; + // Assume in progress. + payload_state_ = PayloadState::kResumeDecodingStruct; + return status; + } else { + // The origin's length is longer than the remaining payload. + DCHECK_GT(altsvc_fields_.origin_length, state->remaining_payload()); + return state->ReportFrameSizeError(); + } + // FALLTHROUGH_INTENDED; + + case PayloadState::kDecodingStrings: + return DecodeStrings(state, db); + + case PayloadState::kResumeDecodingStruct: + status = state->ResumeDecodingStructureInPayload(&altsvc_fields_, db); + payload_state_ = PayloadState::kMaybeDecodedStruct; + continue; + } + QUIC_BUG << "PayloadState: " << payload_state_; + } +} + +QuicHttpDecodeStatus QuicHttpAltSvcQuicHttpPayloadDecoder::DecodeStrings( + QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db) { + DVLOG(2) << "QuicHttpAltSvcQuicHttpPayloadDecoder::DecodeStrings " + "remaining_payload=" + << state->remaining_payload() + << ", db->Remaining=" << db->Remaining(); + // Note that we don't explicitly keep track of exactly how far through the + // origin; instead we compute it from how much is left of the original + // payload length and the decoded total length of the origin. + size_t origin_length = altsvc_fields_.origin_length; + size_t value_length = state->frame_header().payload_length - origin_length - + QuicHttpAltSvcFields::EncodedSize(); + if (state->remaining_payload() > value_length) { + size_t remaining_origin_length = state->remaining_payload() - value_length; + size_t avail = db->MinLengthRemaining(remaining_origin_length); + state->listener()->OnAltSvcOriginData(db->cursor(), avail); + db->AdvanceCursor(avail); + state->ConsumePayload(avail); + if (remaining_origin_length > avail) { + payload_state_ = PayloadState::kDecodingStrings; + return QuicHttpDecodeStatus::kDecodeInProgress; + } + } + // All that is left is the value string. + DCHECK_LE(state->remaining_payload(), value_length); + DCHECK_LE(db->Remaining(), state->remaining_payload()); + if (db->HasData()) { + size_t avail = db->Remaining(); + state->listener()->OnAltSvcValueData(db->cursor(), avail); + db->AdvanceCursor(avail); + state->ConsumePayload(avail); + } + if (state->remaining_payload() == 0) { + state->listener()->OnAltSvcEnd(); + return QuicHttpDecodeStatus::kDecodeDone; + } + payload_state_ = PayloadState::kDecodingStrings; + return QuicHttpDecodeStatus::kDecodeInProgress; +} + +} // namespace net
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_altsvc_payload_decoder.h b/net/quic/http/decoder/payload_decoders/quic_http_altsvc_payload_decoder.h new file mode 100644 index 0000000..73b49a1 --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_altsvc_payload_decoder.h
@@ -0,0 +1,70 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_ALTSVC_PAYLOAD_DECODER_H_ +#define NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_ALTSVC_PAYLOAD_DECODER_H_ + +// Decodes the payload of a ALTSVC frame. +// See http://g3doc/gfe/quic/http/decoder/payload_decoders/README.md for info +// about payload decoders. + +#include "net/quic/http/decoder/quic_http_decode_buffer.h" +#include "net/quic/http/decoder/quic_http_decode_status.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_state.h" +#include "net/quic/http/quic_http_structures.h" +#include "net/quic/platform/api/quic_export.h" + +namespace net { +namespace test { +class QuicHttpAltSvcQuicHttpPayloadDecoderPeer; +} // namespace test + +class QUIC_EXPORT_PRIVATE QuicHttpAltSvcQuicHttpPayloadDecoder { + public: + // States during decoding of a ALTSVC frame. + enum class PayloadState { + // Start decoding the fixed size structure at the start of an ALTSVC + // frame (QuicHttpAltSvcFields). + kStartDecodingStruct, + + // Handle the QuicHttpDecodeStatus returned from starting or resuming the + // decoding of QuicHttpAltSvcFields. If complete, calls OnAltSvcStart. + kMaybeDecodedStruct, + + // Reports the value of the std::strings (origin and value) of an ALTSVC + // frame + // to the listener. + kDecodingStrings, + + // The initial decode buffer wasn't large enough for the + // QuicHttpAltSvcFields, + // so this state resumes the decoding when ResumeDecodingPayload is called + // later with a new QuicHttpDecodeBuffer. + kResumeDecodingStruct, + }; + + // Starts the decoding of a ALTSVC frame's payload, and completes it if the + // entire payload is in the provided decode buffer. + QuicHttpDecodeStatus StartDecodingPayload(QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db); + + // Resumes decoding a ALTSVC frame's payload that has been split across + // decode buffers. + QuicHttpDecodeStatus ResumeDecodingPayload(QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db); + + private: + friend class test::QuicHttpAltSvcQuicHttpPayloadDecoderPeer; + + // Implements state kDecodingStrings. + QuicHttpDecodeStatus DecodeStrings(QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db); + + QuicHttpAltSvcFields altsvc_fields_; + PayloadState payload_state_; +}; + +} // namespace net + +#endif // NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_ALTSVC_PAYLOAD_DECODER_H_
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_altsvc_payload_decoder_test.cc b/net/quic/http/decoder/payload_decoders/quic_http_altsvc_payload_decoder_test.cc new file mode 100644 index 0000000..2e64293 --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_altsvc_payload_decoder_test.cc
@@ -0,0 +1,136 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/payload_decoders/quic_http_altsvc_payload_decoder.h" + +#include <stddef.h> + +#include <cstdint> + +#include "base/logging.h" +#include "net/quic/http/decoder/payload_decoders/quic_http_payload_decoder_base_test_util.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_listener.h" +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/quic_http_structures_test_util.h" +#include "net/quic/http/test_tools/quic_http_frame_parts.h" +#include "net/quic/http/test_tools/quic_http_frame_parts_collector.h" +#include "net/quic/http/tools/quic_http_frame_builder.h" +#include "net/quic/http/tools/quic_http_random_decoder_test.h" +#include "net/quic/platform/api/quic_string.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace net { +namespace test { + +// Provides friend access to an instance of the payload decoder, and also +// provides info to aid in testing. +class QuicHttpAltSvcQuicHttpPayloadDecoderPeer { + public: + static constexpr QuicHttpFrameType FrameType() { + return QuicHttpFrameType::ALTSVC; + } + + // Returns the mask of flags that affect the decoding of the payload (i.e. + // flags that that indicate the presence of certain fields or padding). + static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; } + + static void Randomize(QuicHttpAltSvcQuicHttpPayloadDecoder* p, + QuicTestRandomBase* rng) { + CorruptEnum(&p->payload_state_, rng); + test::Randomize(&p->altsvc_fields_, rng); + VLOG(1) + << "QuicHttpAltSvcQuicHttpPayloadDecoderPeer::Randomize altsvc_fields_=" + << p->altsvc_fields_; + } +}; + +namespace { + +struct Listener : public QuicHttpFramePartsCollector { + void OnAltSvcStart(const QuicHttpFrameHeader& header, + size_t origin_length, + size_t value_length) override { + VLOG(1) << "OnAltSvcStart header: " << header + << "; origin_length=" << origin_length + << "; value_length=" << value_length; + StartFrame(header)->OnAltSvcStart(header, origin_length, value_length); + } + + void OnAltSvcOriginData(const char* data, size_t len) override { + VLOG(1) << "OnAltSvcOriginData: len=" << len; + CurrentFrame()->OnAltSvcOriginData(data, len); + } + + void OnAltSvcValueData(const char* data, size_t len) override { + VLOG(1) << "OnAltSvcValueData: len=" << len; + CurrentFrame()->OnAltSvcValueData(data, len); + } + + void OnAltSvcEnd() override { + VLOG(1) << "OnAltSvcEnd"; + EndFrame()->OnAltSvcEnd(); + } + + void OnFrameSizeError(const QuicHttpFrameHeader& header) override { + VLOG(1) << "OnFrameSizeError: " << header; + FrameError(header)->OnFrameSizeError(header); + } +}; + +class QuicHttpAltSvcQuicHttpPayloadDecoderTest + : public AbstractQuicHttpPayloadDecoderTest< + QuicHttpAltSvcQuicHttpPayloadDecoder, + QuicHttpAltSvcQuicHttpPayloadDecoderPeer, + Listener> {}; + +// Confirm we get an error if the payload is not long enough to hold +// QuicHttpAltSvcFields and the indicated length of origin. +TEST_F(QuicHttpAltSvcQuicHttpPayloadDecoderTest, Truncated) { + QuicHttpFrameBuilder fb; + fb.Append( + QuicHttpAltSvcFields{0xffff}); // The longest possible origin length. + fb.Append("Too little origin!"); + EXPECT_TRUE( + VerifyDetectsFrameSizeError(0, fb.buffer(), /*approve_size*/ nullptr)); +} + +class QuicHttpAltSvcPayloadLengthTests + : public QuicHttpAltSvcQuicHttpPayloadDecoderTest, + public ::testing::WithParamInterface< + ::testing::tuple<uint16_t, uint32_t>> { + protected: + QuicHttpAltSvcPayloadLengthTests() + : origin_length_(::testing::get<0>(GetParam())), + value_length_(::testing::get<1>(GetParam())) { + VLOG(1) << "################ origin_length_=" << origin_length_ + << " value_length_=" << value_length_ << " ################"; + } + + const uint16_t origin_length_; + const uint32_t value_length_; +}; + +INSTANTIATE_TEST_CASE_P(VariousOriginAndValueLengths, + QuicHttpAltSvcPayloadLengthTests, + ::testing::Combine(::testing::Values(0, 1, 3, 65535), + ::testing::Values(0, 1, 3, 65537))); + +TEST_P(QuicHttpAltSvcPayloadLengthTests, ValidOriginAndValueLength) { + QuicString origin = Random().RandString(origin_length_); + QuicString value = Random().RandString(value_length_); + QuicHttpFrameBuilder fb; + fb.Append(QuicHttpAltSvcFields{origin_length_}); + fb.Append(origin); + fb.Append(value); + QuicHttpFrameHeader header(fb.size(), QuicHttpFrameType::ALTSVC, RandFlags(), + RandStreamId()); + set_frame_header(header); + QuicHttpFrameParts expected(header); + expected.SetAltSvcExpected(origin, value); + ASSERT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected)); +} + +} // namespace +} // namespace test +} // namespace net
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_continuation_payload_decoder.cc b/net/quic/http/decoder/payload_decoders/quic_http_continuation_payload_decoder.cc new file mode 100644 index 0000000..65ef20b2 --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_continuation_payload_decoder.cc
@@ -0,0 +1,65 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/payload_decoders/quic_http_continuation_payload_decoder.h" + +#include <stddef.h> + +#include <cstdint> + +#include "base/logging.h" +#include "net/quic/http/decoder/quic_http_decode_buffer.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_listener.h" +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/quic_http_structures.h" + +namespace net { + +QuicHttpDecodeStatus +QuicHttpContinuationQuicHttpPayloadDecoder::StartDecodingPayload( + QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db) { + const QuicHttpFrameHeader& frame_header = state->frame_header(); + const uint32_t total_length = frame_header.payload_length; + + DVLOG(2) + << "QuicHttpContinuationQuicHttpPayloadDecoder::StartDecodingPayload: " + << frame_header; + DCHECK_EQ(QuicHttpFrameType::CONTINUATION, frame_header.type); + DCHECK_LE(db->Remaining(), total_length); + DCHECK_EQ(0, + frame_header.flags & ~(QuicHttpFrameFlag::QUIC_HTTP_END_HEADERS)); + + state->InitializeRemainders(); + state->listener()->OnContinuationStart(frame_header); + return ResumeDecodingPayload(state, db); +} + +QuicHttpDecodeStatus +QuicHttpContinuationQuicHttpPayloadDecoder::ResumeDecodingPayload( + QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db) { + DVLOG(2) + << "QuicHttpContinuationQuicHttpPayloadDecoder::ResumeDecodingPayload" + << " remaining_payload=" << state->remaining_payload() + << " db->Remaining=" << db->Remaining(); + DCHECK_EQ(QuicHttpFrameType::CONTINUATION, state->frame_header().type); + DCHECK_LE(state->remaining_payload(), state->frame_header().payload_length); + DCHECK_LE(db->Remaining(), state->remaining_payload()); + + size_t avail = db->Remaining(); + DCHECK_LE(avail, state->remaining_payload()); + if (avail > 0) { + state->listener()->OnHpackFragment(db->cursor(), avail); + db->AdvanceCursor(avail); + state->ConsumePayload(avail); + } + if (state->remaining_payload() == 0) { + state->listener()->OnContinuationEnd(); + return QuicHttpDecodeStatus::kDecodeDone; + } + return QuicHttpDecodeStatus::kDecodeInProgress; +} + +} // namespace net
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_continuation_payload_decoder.h b/net/quic/http/decoder/payload_decoders/quic_http_continuation_payload_decoder.h new file mode 100644 index 0000000..be968ac --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_continuation_payload_decoder.h
@@ -0,0 +1,34 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_CONTINUATION_PAYLOAD_DECODER_H_ +#define NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_CONTINUATION_PAYLOAD_DECODER_H_ + +// Decodes the payload of a CONTINUATION frame. +// See http://g3doc/gfe/quic/http/decoder/payload_decoders/README.md for info +// about payload decoders. + +#include "net/quic/http/decoder/quic_http_decode_buffer.h" +#include "net/quic/http/decoder/quic_http_decode_status.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_state.h" +#include "net/quic/platform/api/quic_export.h" + +namespace net { + +class QUIC_EXPORT_PRIVATE QuicHttpContinuationQuicHttpPayloadDecoder { + public: + // Starts the decoding of a CONTINUATION frame's payload, and completes + // it if the entire payload is in the provided decode buffer. + QuicHttpDecodeStatus StartDecodingPayload(QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db); + + // Resumes decoding a CONTINUATION frame's payload that has been split across + // decode buffers. + QuicHttpDecodeStatus ResumeDecodingPayload(QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db); +}; + +} // namespace net + +#endif // NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_CONTINUATION_PAYLOAD_DECODER_H_
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_continuation_payload_decoder_test.cc b/net/quic/http/decoder/payload_decoders/quic_http_continuation_payload_decoder_test.cc new file mode 100644 index 0000000..92617c2 --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_continuation_payload_decoder_test.cc
@@ -0,0 +1,97 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/payload_decoders/quic_http_continuation_payload_decoder.h" + +#include <stddef.h> + +#include <cstdint> +#include <type_traits> + +#include "base/logging.h" +#include "net/quic/http/decoder/payload_decoders/quic_http_payload_decoder_base_test_util.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_listener.h" +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/quic_http_structures.h" +#include "net/quic/http/test_tools/quic_http_frame_parts.h" +#include "net/quic/http/test_tools/quic_http_frame_parts_collector.h" +#include "net/quic/http/tools/quic_http_random_decoder_test.h" +#include "net/quic/platform/api/quic_string.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace net { +namespace test { + +// Provides friend access to an instance of the payload decoder, and also +// provides info to aid in testing. +class QuicHttpContinuationQuicHttpPayloadDecoderPeer { + public: + static constexpr QuicHttpFrameType FrameType() { + return QuicHttpFrameType::CONTINUATION; + } + + // Returns the mask of flags that affect the decoding of the payload (i.e. + // flags that that indicate the presence of certain fields or padding). + static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; } + + static void Randomize(QuicHttpContinuationQuicHttpPayloadDecoder* p, + QuicTestRandomBase* rng) { + // QuicHttpContinuationQuicHttpPayloadDecoder has no fields, + // so there is nothing to randomize. + static_assert( + std::is_empty<QuicHttpContinuationQuicHttpPayloadDecoder>::value, + "Need to randomize fields of " + "QuicHttpContinuationQuicHttpPayloadDecoder"); + } +}; + +namespace { + +struct Listener : public QuicHttpFramePartsCollector { + void OnContinuationStart(const QuicHttpFrameHeader& header) override { + VLOG(1) << "OnContinuationStart: " << header; + StartFrame(header)->OnContinuationStart(header); + } + + void OnHpackFragment(const char* data, size_t len) override { + VLOG(1) << "OnHpackFragment: len=" << len; + CurrentFrame()->OnHpackFragment(data, len); + } + + void OnContinuationEnd() override { + VLOG(1) << "OnContinuationEnd"; + EndFrame()->OnContinuationEnd(); + } +}; + +class QuicHttpContinuationQuicHttpPayloadDecoderTest + : public AbstractQuicHttpPayloadDecoderTest< + QuicHttpContinuationQuicHttpPayloadDecoder, + QuicHttpContinuationQuicHttpPayloadDecoderPeer, + Listener>, + public ::testing::WithParamInterface<uint32_t> { + protected: + QuicHttpContinuationQuicHttpPayloadDecoderTest() : length_(GetParam()) { + VLOG(1) << "################ length_=" << length_ << " ################"; + } + + const uint32_t length_; +}; + +INSTANTIATE_TEST_CASE_P(VariousLengths, + QuicHttpContinuationQuicHttpPayloadDecoderTest, + ::testing::Values(0, 1, 2, 3, 4, 5, 6)); + +TEST_P(QuicHttpContinuationQuicHttpPayloadDecoderTest, ValidLength) { + QuicString hpack_payload = Random().RandString(length_); + QuicHttpFrameHeader frame_header(length_, QuicHttpFrameType::CONTINUATION, + RandFlags(), RandStreamId()); + set_frame_header(frame_header); + QuicHttpFrameParts expected(frame_header, hpack_payload); + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(hpack_payload, expected)); +} + +} // namespace +} // namespace test +} // namespace net
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_data_payload_decoder.cc b/net/quic/http/decoder/payload_decoders/quic_http_data_payload_decoder.cc new file mode 100644 index 0000000..d6410b2 --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_data_payload_decoder.cc
@@ -0,0 +1,134 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/payload_decoders/quic_http_data_payload_decoder.h" + +#include <stddef.h> + +#include <cstdint> + +#include "base/logging.h" +#include "base/macros.h" +#include "net/quic/http/decoder/quic_http_decode_buffer.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_listener.h" +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/quic_http_structures.h" +#include "net/quic/platform/api/quic_bug_tracker.h" + +namespace net { + +std::ostream& operator<<(std::ostream& out, + QuicHttpDataQuicHttpPayloadDecoder::PayloadState v) { + switch (v) { + case QuicHttpDataQuicHttpPayloadDecoder::PayloadState::kReadPadLength: + return out << "kReadPadLength"; + case QuicHttpDataQuicHttpPayloadDecoder::PayloadState::kReadPayload: + return out << "kReadPayload"; + case QuicHttpDataQuicHttpPayloadDecoder::PayloadState::kSkipPadding: + return out << "kSkipPadding"; + } + // Since the value doesn't come over the wire, only a programming bug should + // result in reaching this point. + int unknown = static_cast<int>(v); + QUIC_BUG << "Invalid QuicHttpDataQuicHttpPayloadDecoder::PayloadState: " + << unknown; + return out << "QuicHttpDataQuicHttpPayloadDecoder::PayloadState(" << unknown + << ")"; +} + +QuicHttpDecodeStatus QuicHttpDataQuicHttpPayloadDecoder::StartDecodingPayload( + QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db) { + const QuicHttpFrameHeader& frame_header = state->frame_header(); + const uint32_t total_length = frame_header.payload_length; + + DVLOG(2) << "QuicHttpDataQuicHttpPayloadDecoder::StartDecodingPayload: " + << frame_header; + DCHECK_EQ(QuicHttpFrameType::DATA, frame_header.type); + DCHECK_LE(db->Remaining(), total_length); + DCHECK_EQ(0, frame_header.flags & ~(QuicHttpFrameFlag::QUIC_HTTP_END_STREAM | + QuicHttpFrameFlag::QUIC_HTTP_PADDED)); + + // Special case for the hoped for common case: unpadded and fits fully into + // the decode buffer. TO BE SEEN if that is true. It certainly requires that + // the transport buffers be large (e.g. >> 16KB typically). + // TODO(jamessynge) Add counters. + DVLOG(2) << "StartDecodingPayload total_length=" << total_length; + if (!frame_header.IsPadded()) { + DVLOG(2) << "StartDecodingPayload !IsPadded"; + if (db->Remaining() == total_length) { + DVLOG(2) << "StartDecodingPayload all present"; + // Note that we don't cache the listener field so that the callee can + // replace it if the frame is bad. + // If this case is common enough, consider combining the 3 callbacks + // into one. + state->listener()->OnDataStart(frame_header); + if (total_length > 0) { + state->listener()->OnDataPayload(db->cursor(), total_length); + db->AdvanceCursor(total_length); + } + state->listener()->OnDataEnd(); + return QuicHttpDecodeStatus::kDecodeDone; + } + payload_state_ = PayloadState::kReadPayload; + } else { + payload_state_ = PayloadState::kReadPadLength; + } + state->InitializeRemainders(); + state->listener()->OnDataStart(frame_header); + return ResumeDecodingPayload(state, db); +} + +QuicHttpDecodeStatus QuicHttpDataQuicHttpPayloadDecoder::ResumeDecodingPayload( + QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db) { + DVLOG(2) << "QuicHttpDataQuicHttpPayloadDecoder::ResumeDecodingPayload " + "payload_state_=" + << payload_state_; + const QuicHttpFrameHeader& frame_header = state->frame_header(); + DCHECK_EQ(QuicHttpFrameType::DATA, frame_header.type); + DCHECK_LE(state->remaining_payload_and_padding(), + frame_header.payload_length); + DCHECK_LE(db->Remaining(), state->remaining_payload_and_padding()); + QuicHttpDecodeStatus status; + size_t avail; + switch (payload_state_) { + case PayloadState::kReadPadLength: + // ReadPadLength handles the OnPadLength callback, and updating the + // remaining_payload and remaining_padding fields. If the amount of + // padding is too large to fit in the frame's payload, ReadPadLength + // instead calls OnPaddingTooLong and returns kDecodeError. + status = state->ReadPadLength(db, /*report_pad_length*/ true); + if (status != QuicHttpDecodeStatus::kDecodeDone) { + return status; + } + // FALLTHROUGH_INTENDED; + + case PayloadState::kReadPayload: + avail = state->AvailablePayload(db); + if (avail > 0) { + state->listener()->OnDataPayload(db->cursor(), avail); + db->AdvanceCursor(avail); + state->ConsumePayload(avail); + } + if (state->remaining_payload() > 0) { + payload_state_ = PayloadState::kReadPayload; + return QuicHttpDecodeStatus::kDecodeInProgress; + } + // FALLTHROUGH_INTENDED; + + case PayloadState::kSkipPadding: + // SkipPadding handles the OnPadding callback. + if (state->SkipPadding(db)) { + state->listener()->OnDataEnd(); + return QuicHttpDecodeStatus::kDecodeDone; + } + payload_state_ = PayloadState::kSkipPadding; + return QuicHttpDecodeStatus::kDecodeInProgress; + } + QUIC_BUG << "PayloadState: " << payload_state_; + return QuicHttpDecodeStatus::kDecodeError; +} + +} // namespace net
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_data_payload_decoder.h b/net/quic/http/decoder/payload_decoders/quic_http_data_payload_decoder.h new file mode 100644 index 0000000..2436ee6 --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_data_payload_decoder.h
@@ -0,0 +1,57 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_DATA_PAYLOAD_DECODER_H_ +#define NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_DATA_PAYLOAD_DECODER_H_ + +// Decodes the payload of a DATA frame. +// See http://g3doc/gfe/quic/http/decoder/payload_decoders/README.md for info +// about payload decoders. + +#include "net/quic/http/decoder/quic_http_decode_buffer.h" +#include "net/quic/http/decoder/quic_http_decode_status.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_state.h" +#include "net/quic/platform/api/quic_export.h" + +namespace net { +namespace test { +class QuicHttpDataQuicHttpPayloadDecoderPeer; +} // namespace test + +class QUIC_EXPORT_PRIVATE QuicHttpDataQuicHttpPayloadDecoder { + public: + // States during decoding of a DATA frame. + enum class PayloadState { + // The frame is padded and we need to read the PAD_LENGTH field (1 byte), + // and then call OnPadLength + kReadPadLength, + + // Report the non-padding portion of the payload to the listener's + // OnDataPayload method. + kReadPayload, + + // The decoder has finished with the non-padding portion of the payload, + // and is now ready to skip the trailing padding, if the frame has any. + kSkipPadding, + }; + + // Starts decoding a DATA frame's payload, and completes it if + // the entire payload is in the provided decode buffer. + QuicHttpDecodeStatus StartDecodingPayload(QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db); + + // Resumes decoding a DATA frame's payload that has been split across + // decode buffers. + QuicHttpDecodeStatus ResumeDecodingPayload(QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db); + + private: + friend class test::QuicHttpDataQuicHttpPayloadDecoderPeer; + + PayloadState payload_state_; +}; + +} // namespace net + +#endif // NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_DATA_PAYLOAD_DECODER_H_
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_data_payload_decoder_test.cc b/net/quic/http/decoder/payload_decoders/quic_http_data_payload_decoder_test.cc new file mode 100644 index 0000000..b2994bc3 --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_data_payload_decoder_test.cc
@@ -0,0 +1,126 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/payload_decoders/quic_http_data_payload_decoder.h" + +#include <stddef.h> + +#include <cstdint> + +#include "base/logging.h" +#include "net/quic/http/decoder/payload_decoders/quic_http_payload_decoder_base_test_util.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_listener.h" +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/quic_http_structures.h" +#include "net/quic/http/quic_http_structures_test_util.h" +#include "net/quic/http/test_tools/quic_http_frame_parts.h" +#include "net/quic/http/test_tools/quic_http_frame_parts_collector.h" +#include "net/quic/http/tools/quic_http_frame_builder.h" +#include "net/quic/http/tools/quic_http_random_decoder_test.h" +#include "net/quic/platform/api/quic_string.h" +#include "testing/gtest/include/gtest/gtest.h" + +using ::testing::AssertionResult; + +namespace net { +namespace test { + +// Provides friend access to an instance of the payload decoder, and also +// provides info to aid in testing. +class QuicHttpDataQuicHttpPayloadDecoderPeer { + public: + static constexpr QuicHttpFrameType FrameType() { + return QuicHttpFrameType::DATA; + } + + // Returns the mask of flags that affect the decoding of the payload (i.e. + // flags that that indicate the presence of certain fields or padding). + static constexpr uint8_t FlagsAffectingPayloadDecoding() { + return QuicHttpFrameFlag::QUIC_HTTP_PADDED; + } + + static void Randomize(QuicHttpDataQuicHttpPayloadDecoder* p, + QuicTestRandomBase* rng) { + VLOG(1) << "QuicHttpDataQuicHttpPayloadDecoderPeer::Randomize"; + CorruptEnum(&p->payload_state_, rng); + } +}; + +namespace { + +struct Listener : public QuicHttpFramePartsCollector { + void OnDataStart(const QuicHttpFrameHeader& header) override { + VLOG(1) << "OnDataStart: " << header; + StartFrame(header)->OnDataStart(header); + } + + void OnDataPayload(const char* data, size_t len) override { + VLOG(1) << "OnDataPayload: len=" << len; + CurrentFrame()->OnDataPayload(data, len); + } + + void OnDataEnd() override { + VLOG(1) << "OnDataEnd"; + EndFrame()->OnDataEnd(); + } + + void OnPadLength(size_t pad_length) override { + VLOG(1) << "OnPadLength: " << pad_length; + CurrentFrame()->OnPadLength(pad_length); + } + + void OnPadding(const char* padding, size_t skipped_length) override { + VLOG(1) << "OnPadding: " << skipped_length; + CurrentFrame()->OnPadding(padding, skipped_length); + } + + void OnPaddingTooLong(const QuicHttpFrameHeader& header, + size_t missing_length) override { + VLOG(1) << "OnPaddingTooLong: " << header + << " missing_length: " << missing_length; + EndFrame()->OnPaddingTooLong(header, missing_length); + } +}; + +class QuicHttpDataQuicHttpPayloadDecoderTest + : public AbstractPaddableQuicHttpPayloadDecoderTest< + QuicHttpDataQuicHttpPayloadDecoder, + QuicHttpDataQuicHttpPayloadDecoderPeer, + Listener> { + protected: + AssertionResult CreateAndDecodeDataOfSize(size_t data_size) { + Reset(); + // Boost logging when the data and *trailing* padding are both 3 bytes long, + // as this size of a string has both a beginning, middle and end when + // segmented into 1 byte long buffers, so should exercise all the paths. + // But we don't want to do extra logging all the time as it is expensive. + uint8_t flags = RandFlags(); + + QuicString data_payload = Random().RandString(data_size); + frame_builder_.Append(data_payload); + MaybeAppendTrailingPadding(); + + QuicHttpFrameHeader frame_header( + frame_builder_.size(), QuicHttpFrameType::DATA, flags, RandStreamId()); + set_frame_header(frame_header); + ScrubFlagsOfHeader(&frame_header); + QuicHttpFrameParts expected(frame_header, data_payload, total_pad_length_); + VERIFY_AND_RETURN_SUCCESS( + DecodePayloadAndValidateSeveralWays(frame_builder_.buffer(), expected)); + } +}; + +INSTANTIATE_TEST_CASE_P(VariousPadLengths, + QuicHttpDataQuicHttpPayloadDecoderTest, + ::testing::Values(0, 1, 2, 3, 4, 254, 255, 256)); + +TEST_P(QuicHttpDataQuicHttpPayloadDecoderTest, VariousDataPayloadSizes) { + for (size_t data_size : {0, 1, 2, 3, 255, 256, 1024}) { + EXPECT_TRUE(CreateAndDecodeDataOfSize(data_size)); + } +} + +} // namespace +} // namespace test +} // namespace net
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_goaway_payload_decoder.cc b/net/quic/http/decoder/payload_decoders/quic_http_goaway_payload_decoder.cc new file mode 100644 index 0000000..4ec4176f --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_goaway_payload_decoder.cc
@@ -0,0 +1,125 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/payload_decoders/quic_http_goaway_payload_decoder.h" + +#include <stddef.h> + +#include "base/logging.h" +#include "base/macros.h" +#include "net/quic/http/decoder/quic_http_decode_buffer.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_listener.h" +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/quic_http_structures.h" +#include "net/quic/platform/api/quic_bug_tracker.h" + +namespace net { + +std::ostream& operator<<(std::ostream& out, + QuicHttpGoAwayQuicHttpPayloadDecoder::PayloadState v) { + switch (v) { + case QuicHttpGoAwayQuicHttpPayloadDecoder::PayloadState:: + kStartDecodingFixedFields: + return out << "kStartDecodingFixedFields"; + case QuicHttpGoAwayQuicHttpPayloadDecoder::PayloadState:: + kHandleFixedFieldsStatus: + return out << "kHandleFixedFieldsStatus"; + case QuicHttpGoAwayQuicHttpPayloadDecoder::PayloadState::kReadOpaqueData: + return out << "kReadOpaqueData"; + case QuicHttpGoAwayQuicHttpPayloadDecoder::PayloadState:: + kResumeDecodingFixedFields: + return out << "kResumeDecodingFixedFields"; + } + // Since the value doesn't come over the wire, only a programming bug should + // result in reaching this point. + int unknown = static_cast<int>(v); + QUIC_BUG << "Invalid QuicHttpGoAwayQuicHttpPayloadDecoder::PayloadState: " + << unknown; + return out << "QuicHttpGoAwayQuicHttpPayloadDecoder::PayloadState(" << unknown + << ")"; +} + +QuicHttpDecodeStatus QuicHttpGoAwayQuicHttpPayloadDecoder::StartDecodingPayload( + QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db) { + DVLOG(2) << "QuicHttpGoAwayQuicHttpPayloadDecoder::StartDecodingPayload: " + << state->frame_header(); + DCHECK_EQ(QuicHttpFrameType::GOAWAY, state->frame_header().type); + DCHECK_LE(db->Remaining(), state->frame_header().payload_length); + DCHECK_EQ(0, state->frame_header().flags); + + state->InitializeRemainders(); + payload_state_ = PayloadState::kStartDecodingFixedFields; + return ResumeDecodingPayload(state, db); +} + +QuicHttpDecodeStatus +QuicHttpGoAwayQuicHttpPayloadDecoder::ResumeDecodingPayload( + QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db) { + DVLOG(2) << "QuicHttpGoAwayQuicHttpPayloadDecoder::ResumeDecodingPayload: " + "remaining_payload=" + << state->remaining_payload() + << ", db->Remaining=" << db->Remaining(); + + const QuicHttpFrameHeader& frame_header = state->frame_header(); + DCHECK_EQ(QuicHttpFrameType::GOAWAY, frame_header.type); + DCHECK_LE(db->Remaining(), frame_header.payload_length); + DCHECK_NE(PayloadState::kHandleFixedFieldsStatus, payload_state_); + + QuicHttpDecodeStatus status = QuicHttpDecodeStatus::kDecodeError; + size_t avail; + while (true) { + DVLOG(2) << "QuicHttpGoAwayQuicHttpPayloadDecoder::ResumeDecodingPayload " + "payload_state_=" + << payload_state_; + switch (payload_state_) { + case PayloadState::kStartDecodingFixedFields: + status = state->StartDecodingStructureInPayload(&goaway_fields_, db); + // FALLTHROUGH_INTENDED; + + case PayloadState::kHandleFixedFieldsStatus: + if (status == QuicHttpDecodeStatus::kDecodeDone) { + state->listener()->OnGoAwayStart(frame_header, goaway_fields_); + } else { + // Not done decoding the structure. Either we've got more payload + // to decode, or we've run out because the payload is too short, + // in which case OnFrameSizeError will have already been called. + DCHECK((status == QuicHttpDecodeStatus::kDecodeInProgress && + state->remaining_payload() > 0) || + (status == QuicHttpDecodeStatus::kDecodeError && + state->remaining_payload() == 0)) + << "\n status=" << status + << "; remaining_payload=" << state->remaining_payload(); + payload_state_ = PayloadState::kResumeDecodingFixedFields; + return status; + } + // FALLTHROUGH_INTENDED; + + case PayloadState::kReadOpaqueData: + // The opaque data is all the remains to be decoded, so anything left + // in the decode buffer is opaque data. + avail = db->Remaining(); + if (avail > 0) { + state->listener()->OnGoAwayOpaqueData(db->cursor(), avail); + db->AdvanceCursor(avail); + state->ConsumePayload(avail); + } + if (state->remaining_payload() > 0) { + payload_state_ = PayloadState::kReadOpaqueData; + return QuicHttpDecodeStatus::kDecodeInProgress; + } + state->listener()->OnGoAwayEnd(); + return QuicHttpDecodeStatus::kDecodeDone; + + case PayloadState::kResumeDecodingFixedFields: + status = state->ResumeDecodingStructureInPayload(&goaway_fields_, db); + payload_state_ = PayloadState::kHandleFixedFieldsStatus; + continue; + } + QUIC_BUG << "PayloadState: " << payload_state_; + } +} + +} // namespace net
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_goaway_payload_decoder.h b/net/quic/http/decoder/payload_decoders/quic_http_goaway_payload_decoder.h new file mode 100644 index 0000000..1f8c3fd --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_goaway_payload_decoder.h
@@ -0,0 +1,69 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_GOAWAY_PAYLOAD_DECODER_H_ +#define NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_GOAWAY_PAYLOAD_DECODER_H_ + +// Decodes the payload of a GOAWAY frame. +// See http://g3doc/gfe/quic/http/decoder/payload_decoders/README.md for info +// about payload decoders. + +// TODO(jamessynge): Sweep through all payload decoders, changing the names of +// the PayloadState enums so that they are really states, and not actions. + +#include "net/quic/http/decoder/quic_http_decode_buffer.h" +#include "net/quic/http/decoder/quic_http_decode_status.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_state.h" +#include "net/quic/http/quic_http_structures.h" +#include "net/quic/platform/api/quic_export.h" + +namespace net { +namespace test { +class QuicHttpGoAwayQuicHttpPayloadDecoderPeer; +} // namespace test + +class QUIC_EXPORT_PRIVATE QuicHttpGoAwayQuicHttpPayloadDecoder { + public: + // States during decoding of a GOAWAY frame. + enum class PayloadState { + // At the start of the GOAWAY frame payload, ready to start decoding the + // fixed size fields into goaway_fields_. + kStartDecodingFixedFields, + + // Handle the QuicHttpDecodeStatus returned from starting or resuming the + // decoding of QuicHttpGoAwayFields into goaway_fields_. If complete, + // calls OnGoAwayStart. + kHandleFixedFieldsStatus, + + // Report the Opaque Data portion of the payload to the listener's + // OnGoAwayOpaqueData method, and call OnGoAwayEnd when the end of the + // payload is reached. + kReadOpaqueData, + + // The fixed size fields weren't all available when the decoder first + // tried to decode them (state kStartDecodingFixedFields); this state + // resumes the decoding when ResumeDecodingPayload is called later. + kResumeDecodingFixedFields, + }; + + // Starts the decoding of a GOAWAY frame's payload, and completes it if + // the entire payload is in the provided decode buffer. + QuicHttpDecodeStatus StartDecodingPayload(QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db); + + // Resumes decoding a GOAWAY frame's payload that has been split across + // decode buffers. + QuicHttpDecodeStatus ResumeDecodingPayload(QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db); + + private: + friend class test::QuicHttpGoAwayQuicHttpPayloadDecoderPeer; + + QuicHttpGoAwayFields goaway_fields_; + PayloadState payload_state_; +}; + +} // namespace net + +#endif // NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_GOAWAY_PAYLOAD_DECODER_H_
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_goaway_payload_decoder_test.cc b/net/quic/http/decoder/payload_decoders/quic_http_goaway_payload_decoder_test.cc new file mode 100644 index 0000000..aa896b7 --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_goaway_payload_decoder_test.cc
@@ -0,0 +1,120 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/payload_decoders/quic_http_goaway_payload_decoder.h" + +#include <stddef.h> + +#include <cstdint> + +#include "base/logging.h" +#include "net/quic/http/decoder/payload_decoders/quic_http_payload_decoder_base_test_util.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_listener.h" +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/quic_http_structures_test_util.h" +#include "net/quic/http/test_tools/quic_http_frame_parts.h" +#include "net/quic/http/test_tools/quic_http_frame_parts_collector.h" +#include "net/quic/http/tools/quic_http_frame_builder.h" +#include "net/quic/http/tools/quic_http_random_decoder_test.h" +#include "net/quic/platform/api/quic_string.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace net { +namespace test { + +class QuicHttpGoAwayQuicHttpPayloadDecoderPeer { + public: + static constexpr QuicHttpFrameType FrameType() { + return QuicHttpFrameType::GOAWAY; + } + + // Returns the mask of flags that affect the decoding of the payload (i.e. + // flags that that indicate the presence of certain fields or padding). + static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; } + + static void Randomize(QuicHttpGoAwayQuicHttpPayloadDecoder* p, + QuicTestRandomBase* rng) { + CorruptEnum(&p->payload_state_, rng); + test::Randomize(&p->goaway_fields_, rng); + VLOG(1) + << "QuicHttpGoAwayQuicHttpPayloadDecoderPeer::Randomize goaway_fields: " + << p->goaway_fields_; + } +}; + +namespace { + +struct Listener : public QuicHttpFramePartsCollector { + void OnGoAwayStart(const QuicHttpFrameHeader& header, + const QuicHttpGoAwayFields& goaway) override { + VLOG(1) << "OnGoAwayStart header: " << header << "; goaway: " << goaway; + StartFrame(header)->OnGoAwayStart(header, goaway); + } + + void OnGoAwayOpaqueData(const char* data, size_t len) override { + VLOG(1) << "OnGoAwayOpaqueData: len=" << len; + CurrentFrame()->OnGoAwayOpaqueData(data, len); + } + + void OnGoAwayEnd() override { + VLOG(1) << "OnGoAwayEnd"; + EndFrame()->OnGoAwayEnd(); + } + + void OnFrameSizeError(const QuicHttpFrameHeader& header) override { + VLOG(1) << "OnFrameSizeError: " << header; + FrameError(header)->OnFrameSizeError(header); + } +}; + +class QuicHttpGoAwayQuicHttpPayloadDecoderTest + : public AbstractQuicHttpPayloadDecoderTest< + QuicHttpGoAwayQuicHttpPayloadDecoder, + QuicHttpGoAwayQuicHttpPayloadDecoderPeer, + Listener> {}; + +// Confirm we get an error if the payload is not long enough to hold +// QuicHttpGoAwayFields. +TEST_F(QuicHttpGoAwayQuicHttpPayloadDecoderTest, Truncated) { + auto approve_size = [](size_t size) { + return size != QuicHttpGoAwayFields::EncodedSize(); + }; + QuicHttpFrameBuilder fb; + fb.Append(QuicHttpGoAwayFields(123, QuicHttpErrorCode::ENHANCE_YOUR_CALM)); + EXPECT_TRUE(VerifyDetectsFrameSizeError(0, fb.buffer(), approve_size)); +} + +class QuicHttpGoAwayOpaqueDataLengthTests + : public QuicHttpGoAwayQuicHttpPayloadDecoderTest, + public ::testing::WithParamInterface<uint32_t> { + protected: + QuicHttpGoAwayOpaqueDataLengthTests() : length_(GetParam()) { + VLOG(1) << "################ length_=" << length_ << " ################"; + } + + const uint32_t length_; +}; + +INSTANTIATE_TEST_CASE_P(VariousLengths, + QuicHttpGoAwayOpaqueDataLengthTests, + ::testing::Values(0, 1, 2, 3, 4, 5, 6)); + +TEST_P(QuicHttpGoAwayOpaqueDataLengthTests, ValidLength) { + QuicHttpGoAwayFields goaway; + Randomize(&goaway, RandomPtr()); + QuicString opaque_bytes = Random().RandString(length_); + QuicHttpFrameBuilder fb; + fb.Append(goaway); + fb.Append(opaque_bytes); + QuicHttpFrameHeader header(fb.size(), QuicHttpFrameType::GOAWAY, RandFlags(), + RandStreamId()); + set_frame_header(header); + QuicHttpFrameParts expected(header, opaque_bytes); + expected.opt_goaway = goaway; + ASSERT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected)); +} + +} // namespace +} // namespace test +} // namespace net
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_headers_payload_decoder.cc b/net/quic/http/decoder/payload_decoders/quic_http_headers_payload_decoder.cc new file mode 100644 index 0000000..b0025e0 --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_headers_payload_decoder.cc
@@ -0,0 +1,187 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/payload_decoders/quic_http_headers_payload_decoder.h" + +#include <stddef.h> + +#include <cstdint> + +#include "base/logging.h" +#include "base/macros.h" +#include "net/quic/http/decoder/quic_http_decode_buffer.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_listener.h" +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/quic_http_structures.h" +#include "net/quic/platform/api/quic_bug_tracker.h" + +namespace net { + +std::ostream& operator<<( + std::ostream& out, + QuicHttpHeadersQuicHttpPayloadDecoder::PayloadState v) { + switch (v) { + case QuicHttpHeadersQuicHttpPayloadDecoder::PayloadState::kReadPadLength: + return out << "kReadPadLength"; + case QuicHttpHeadersQuicHttpPayloadDecoder::PayloadState:: + kStartDecodingPriorityFields: + return out << "kStartDecodingPriorityFields"; + case QuicHttpHeadersQuicHttpPayloadDecoder::PayloadState:: + kResumeDecodingPriorityFields: + return out << "kResumeDecodingPriorityFields"; + case QuicHttpHeadersQuicHttpPayloadDecoder::PayloadState::kReadPayload: + return out << "kReadPayload"; + case QuicHttpHeadersQuicHttpPayloadDecoder::PayloadState::kSkipPadding: + return out << "kSkipPadding"; + } + // Since the value doesn't come over the wire, only a programming bug should + // result in reaching this point. + int unknown = static_cast<int>(v); + QUIC_BUG << "Invalid QuicHttpHeadersQuicHttpPayloadDecoder::PayloadState: " + << unknown; + return out << "QuicHttpHeadersQuicHttpPayloadDecoder::PayloadState(" + << unknown << ")"; +} + +QuicHttpDecodeStatus +QuicHttpHeadersQuicHttpPayloadDecoder::StartDecodingPayload( + QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db) { + const QuicHttpFrameHeader& frame_header = state->frame_header(); + const uint32_t total_length = frame_header.payload_length; + + DVLOG(2) << "QuicHttpHeadersQuicHttpPayloadDecoder::StartDecodingPayload: " + << frame_header; + + DCHECK_EQ(QuicHttpFrameType::HEADERS, frame_header.type); + DCHECK_LE(db->Remaining(), total_length); + DCHECK_EQ(0, frame_header.flags & ~(QuicHttpFrameFlag::QUIC_HTTP_END_STREAM | + QuicHttpFrameFlag::QUIC_HTTP_END_HEADERS | + QuicHttpFrameFlag::QUIC_HTTP_PADDED | + QuicHttpFrameFlag::QUIC_HTTP_PRIORITY)); + + // Special case for HEADERS frames that contain only the HPQUIC_HTTP_ACK block + // (fragment or whole) and that fit fully into the decode buffer. + // Why? Unencoded browser GET requests are typically under 1K and + // HPQUIC_HTTP_ACK commonly shrinks request headers by 80%, so we can expect + // this to be common. + // TODO(jamessynge) Add counters here and to Spdy for determining how + // common this situation is. A possible approach is to create a + // QuicHttpFrameDecoderListener that counts the callbacks and then forwards + // them on to another listener, which makes it easy to add and remove + // counting on a connection or even frame basis. + + // QUIC_HTTP_PADDED and QUIC_HTTP_PRIORITY both extra steps to decode, but if + // neither flag is set then we can decode faster. + const auto payload_flags = QuicHttpFrameFlag::QUIC_HTTP_PADDED | + QuicHttpFrameFlag::QUIC_HTTP_PRIORITY; + if (!frame_header.HasAnyFlags(payload_flags)) { + DVLOG(2) << "StartDecodingPayload !IsPadded && !HasPriority"; + if (db->Remaining() == total_length) { + DVLOG(2) << "StartDecodingPayload all present"; + // Note that we don't cache the listener field so that the callee can + // replace it if the frame is bad. + // If this case is common enough, consider combining the 3 callbacks + // into one, especially if QUIC_HTTP_END_HEADERS is also set. + state->listener()->OnHeadersStart(frame_header); + if (total_length > 0) { + state->listener()->OnHpackFragment(db->cursor(), total_length); + db->AdvanceCursor(total_length); + } + state->listener()->OnHeadersEnd(); + return QuicHttpDecodeStatus::kDecodeDone; + } + payload_state_ = PayloadState::kReadPayload; + } else if (frame_header.IsPadded()) { + payload_state_ = PayloadState::kReadPadLength; + } else { + DCHECK(frame_header.HasPriority()) << frame_header; + payload_state_ = PayloadState::kStartDecodingPriorityFields; + } + state->InitializeRemainders(); + state->listener()->OnHeadersStart(frame_header); + return ResumeDecodingPayload(state, db); +} + +QuicHttpDecodeStatus +QuicHttpHeadersQuicHttpPayloadDecoder::ResumeDecodingPayload( + QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db) { + DVLOG(2) << "QuicHttpHeadersQuicHttpPayloadDecoder::ResumeDecodingPayload " + << "remaining_payload=" << state->remaining_payload() + << "; db->Remaining=" << db->Remaining(); + + const QuicHttpFrameHeader& frame_header = state->frame_header(); + + DCHECK_EQ(QuicHttpFrameType::HEADERS, frame_header.type); + DCHECK_LE(state->remaining_payload_and_padding(), + frame_header.payload_length); + DCHECK_LE(db->Remaining(), state->remaining_payload_and_padding()); + QuicHttpDecodeStatus status; + size_t avail; + while (true) { + DVLOG(2) << "QuicHttpHeadersQuicHttpPayloadDecoder::ResumeDecodingPayload " + "payload_state_=" + << payload_state_; + switch (payload_state_) { + case PayloadState::kReadPadLength: + // ReadPadLength handles the OnPadLength callback, and updating the + // remaining_payload and remaining_padding fields. If the amount of + // padding is too large to fit in the frame's payload, ReadPadLength + // instead calls OnPaddingTooLong and returns kDecodeError. + status = state->ReadPadLength(db, /*report_pad_length*/ true); + if (status != QuicHttpDecodeStatus::kDecodeDone) { + return status; + } + if (!frame_header.HasPriority()) { + payload_state_ = PayloadState::kReadPayload; + continue; + } + // FALLTHROUGH_INTENDED; + + case PayloadState::kStartDecodingPriorityFields: + status = state->StartDecodingStructureInPayload(&priority_fields_, db); + if (status != QuicHttpDecodeStatus::kDecodeDone) { + payload_state_ = PayloadState::kResumeDecodingPriorityFields; + return status; + } + state->listener()->OnHeadersPriority(priority_fields_); + // FALLTHROUGH_INTENDED; + + case PayloadState::kReadPayload: + avail = state->AvailablePayload(db); + if (avail > 0) { + state->listener()->OnHpackFragment(db->cursor(), avail); + db->AdvanceCursor(avail); + state->ConsumePayload(avail); + } + if (state->remaining_payload() > 0) { + payload_state_ = PayloadState::kReadPayload; + return QuicHttpDecodeStatus::kDecodeInProgress; + } + // FALLTHROUGH_INTENDED; + + case PayloadState::kSkipPadding: + // SkipPadding handles the OnPadding callback. + if (state->SkipPadding(db)) { + state->listener()->OnHeadersEnd(); + return QuicHttpDecodeStatus::kDecodeDone; + } + payload_state_ = PayloadState::kSkipPadding; + return QuicHttpDecodeStatus::kDecodeInProgress; + + case PayloadState::kResumeDecodingPriorityFields: + status = state->ResumeDecodingStructureInPayload(&priority_fields_, db); + if (status != QuicHttpDecodeStatus::kDecodeDone) { + return status; + } + state->listener()->OnHeadersPriority(priority_fields_); + payload_state_ = PayloadState::kReadPayload; + continue; + } + QUIC_BUG << "PayloadState: " << payload_state_; + } +} + +} // namespace net
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_headers_payload_decoder.h b/net/quic/http/decoder/payload_decoders/quic_http_headers_payload_decoder.h new file mode 100644 index 0000000..36e7f90 --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_headers_payload_decoder.h
@@ -0,0 +1,74 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_HEADERS_PAYLOAD_DECODER_H_ +#define NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_HEADERS_PAYLOAD_DECODER_H_ + +// Decodes the payload of a HEADERS frame. +// See http://g3doc/gfe/quic/http/decoder/payload_decoders/README.md for info +// about payload decoders. + +#include "net/quic/http/decoder/quic_http_decode_buffer.h" +#include "net/quic/http/decoder/quic_http_decode_status.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_state.h" +#include "net/quic/http/quic_http_structures.h" +#include "net/quic/platform/api/quic_export.h" + +namespace net { +namespace test { +class QuicHttpHeadersQuicHttpPayloadDecoderPeer; +} // namespace test + +class QUIC_EXPORT_PRIVATE QuicHttpHeadersQuicHttpPayloadDecoder { + public: + // States during decoding of a HEADERS frame, unless the fast path kicks + // in, in which case the state machine will be bypassed. + enum class PayloadState { + // The QUIC_HTTP_PADDED flag is set, and we now need to read the Pad Length + // field + // (the first byte of the payload, after the common frame header). + kReadPadLength, + + // The QUIC_HTTP_PRIORITY flag is set, and we now need to read the fixed + // size priority + // fields (E, Stream Dependency, Weight) into priority_fields_. Calls on + // OnHeadersPriority if completely decodes those fields. + kStartDecodingPriorityFields, + + // The decoder passes the non-padding portion of the remaining payload + // (i.e. the HPQUIC_HTTP_ACK block fragment) to the listener's + // OnHpackFragment method. + kReadPayload, + + // The decoder has finished with the HPQUIC_HTTP_ACK block fragment, and is + // now + // ready to skip the trailing padding, if the frame has any. + kSkipPadding, + + // The fixed size fields weren't all available when the decoder first tried + // to decode them (state kStartDecodingPriorityFields); this state resumes + // the decoding when ResumeDecodingPayload is called later. + kResumeDecodingPriorityFields, + }; + + // Starts the decoding of a HEADERS frame's payload, and completes it if + // the entire payload is in the provided decode buffer. + QuicHttpDecodeStatus StartDecodingPayload(QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db); + + // Resumes decoding a HEADERS frame's payload that has been split across + // decode buffers. + QuicHttpDecodeStatus ResumeDecodingPayload(QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db); + + private: + friend class test::QuicHttpHeadersQuicHttpPayloadDecoderPeer; + + PayloadState payload_state_; + QuicHttpPriorityFields priority_fields_; +}; + +} // namespace net + +#endif // NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_HEADERS_PAYLOAD_DECODER_H_
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_headers_payload_decoder_test.cc b/net/quic/http/decoder/payload_decoders/quic_http_headers_payload_decoder_test.cc new file mode 100644 index 0000000..8cb00d2 --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_headers_payload_decoder_test.cc
@@ -0,0 +1,172 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/payload_decoders/quic_http_headers_payload_decoder.h" + +#include <stddef.h> + +#include <cstdint> + +#include "base/logging.h" +#include "net/quic/http/decoder/payload_decoders/quic_http_payload_decoder_base_test_util.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_listener.h" +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/quic_http_structures_test_util.h" +#include "net/quic/http/test_tools/quic_http_frame_parts.h" +#include "net/quic/http/test_tools/quic_http_frame_parts_collector.h" +#include "net/quic/http/tools/quic_http_frame_builder.h" +#include "net/quic/http/tools/quic_http_random_decoder_test.h" +#include "net/quic/platform/api/quic_string.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace net { +namespace test { + +class QuicHttpHeadersQuicHttpPayloadDecoderPeer { + public: + static constexpr QuicHttpFrameType FrameType() { + return QuicHttpFrameType::HEADERS; + } + + // Returns the mask of flags that affect the decoding of the payload (i.e. + // flags that that indicate the presence of certain fields or padding). + static constexpr uint8_t FlagsAffectingPayloadDecoding() { + return QuicHttpFrameFlag::QUIC_HTTP_PADDED | + QuicHttpFrameFlag::QUIC_HTTP_PRIORITY; + } + + static void Randomize(QuicHttpHeadersQuicHttpPayloadDecoder* p, + QuicTestRandomBase* rng) { + CorruptEnum(&p->payload_state_, rng); + test::Randomize(&p->priority_fields_, rng); + VLOG(1) << "QuicHttpHeadersQuicHttpPayloadDecoderPeer::Randomize " + "priority_fields_: " + << p->priority_fields_; + } +}; + +namespace { + +// Listener handles all On* methods that are expected to be called. If any other +// On* methods of QuicHttpFrameDecoderListener is called then the test fails; +// this is achieved by way of FailingQuicHttpFrameDecoderListener, the base +// class of QuicHttpFramePartsCollector. These On* methods make use of +// StartFrame, EndFrame, etc. of the base class to create and access to +// QuicHttpFrameParts instance(s) that will record the details. After decoding, +// the test validation code can access the FramePart instance(s) via the public +// methods of QuicHttpFramePartsCollector. +struct Listener : public QuicHttpFramePartsCollector { + void OnHeadersStart(const QuicHttpFrameHeader& header) override { + VLOG(1) << "OnHeadersStart: " << header; + StartFrame(header)->OnHeadersStart(header); + } + + void OnHeadersPriority(const QuicHttpPriorityFields& priority) override { + VLOG(1) << "OnHeadersPriority: " << priority; + CurrentFrame()->OnHeadersPriority(priority); + } + + void OnHpackFragment(const char* data, size_t len) override { + VLOG(1) << "OnHpackFragment: len=" << len; + CurrentFrame()->OnHpackFragment(data, len); + } + + void OnHeadersEnd() override { + VLOG(1) << "OnHeadersEnd"; + EndFrame()->OnHeadersEnd(); + } + + void OnPadLength(size_t pad_length) override { + VLOG(1) << "OnPadLength: " << pad_length; + CurrentFrame()->OnPadLength(pad_length); + } + + void OnPadding(const char* padding, size_t skipped_length) override { + VLOG(1) << "OnPadding: " << skipped_length; + CurrentFrame()->OnPadding(padding, skipped_length); + } + + void OnPaddingTooLong(const QuicHttpFrameHeader& header, + size_t missing_length) override { + VLOG(1) << "OnPaddingTooLong: " << header + << "; missing_length: " << missing_length; + FrameError(header)->OnPaddingTooLong(header, missing_length); + } + + void OnFrameSizeError(const QuicHttpFrameHeader& header) override { + VLOG(1) << "OnFrameSizeError: " << header; + FrameError(header)->OnFrameSizeError(header); + } +}; + +class QuicHttpHeadersQuicHttpPayloadDecoderTest + : public AbstractPaddableQuicHttpPayloadDecoderTest< + QuicHttpHeadersQuicHttpPayloadDecoder, + QuicHttpHeadersQuicHttpPayloadDecoderPeer, + Listener> {}; + +INSTANTIATE_TEST_CASE_P(VariousPadLengths, + QuicHttpHeadersQuicHttpPayloadDecoderTest, + ::testing::Values(0, 1, 2, 3, 4, 254, 255, 256)); + +// Decode various sizes of (fake) HPQUIC_HTTP_ACK payload, both with and without +// the QUIC_HTTP_PRIORITY flag set. +TEST_P(QuicHttpHeadersQuicHttpPayloadDecoderTest, VariousHpackPayloadSizes) { + for (size_t hpack_size : {0, 1, 2, 3, 255, 256, 1024}) { + LOG(INFO) << "########### hpack_size = " << hpack_size << " ###########"; + QuicHttpPriorityFields priority(RandStreamId(), 1 + Random().Rand8(), + Random().OneIn(2)); + + for (bool has_priority : {false, true}) { + Reset(); + ASSERT_EQ(IsPadded() ? 1u : 0u, frame_builder_.size()); + uint8_t flags = RandFlags(); + if (has_priority) { + flags |= QuicHttpFrameFlag::QUIC_HTTP_PRIORITY; + frame_builder_.Append(priority); + } + + QuicString hpack_payload = Random().RandString(hpack_size); + frame_builder_.Append(hpack_payload); + + MaybeAppendTrailingPadding(); + QuicHttpFrameHeader frame_header(frame_builder_.size(), + QuicHttpFrameType::HEADERS, flags, + RandStreamId()); + set_frame_header(frame_header); + ScrubFlagsOfHeader(&frame_header); + QuicHttpFrameParts expected(frame_header, hpack_payload, + total_pad_length_); + if (has_priority) { + expected.opt_priority = priority; + } + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(frame_builder_.buffer(), + expected)); + } + } +} + +// Confirm we get an error if the QUIC_HTTP_PRIORITY flag is set but the payload +// is not long enough, regardless of the amount of (valid) padding. +TEST_P(QuicHttpHeadersQuicHttpPayloadDecoderTest, Truncated) { + auto approve_size = [](size_t size) { + return size != QuicHttpPriorityFields::EncodedSize(); + }; + QuicHttpFrameBuilder fb; + fb.Append(QuicHttpPriorityFields(RandStreamId(), 1 + Random().Rand8(), + Random().OneIn(2))); + EXPECT_TRUE(VerifyDetectsMultipleFrameSizeErrors( + QuicHttpFrameFlag::QUIC_HTTP_PRIORITY, fb.buffer(), approve_size, + total_pad_length_)); +} + +// Confirm we get an error if the QUIC_HTTP_PADDED flag is set but the payload +// is not long enough to hold even the Pad Length amount of padding. +TEST_P(QuicHttpHeadersQuicHttpPayloadDecoderTest, PaddingTooLong) { + EXPECT_TRUE(VerifyDetectsPaddingTooLong()); +} + +} // namespace +} // namespace test +} // namespace net
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_payload_decoder_base_test_util.cc b/net/quic/http/decoder/payload_decoders/quic_http_payload_decoder_base_test_util.cc new file mode 100644 index 0000000..bc516a73 --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_payload_decoder_base_test_util.cc
@@ -0,0 +1,105 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/payload_decoders/quic_http_payload_decoder_base_test_util.h" + +#include "base/logging.h" +#include "net/quic/http/decoder/quic_http_decode_buffer.h" +#include "net/quic/http/decoder/quic_http_decode_status.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_state_test_util.h" +#include "net/quic/http/quic_http_structures.h" +#include "net/quic/http/quic_http_structures_test_util.h" +#include "net/quic/http/tools/quic_http_random_decoder_test.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace net { +namespace test { +QuicHttpPayloadDecoderBaseTest::QuicHttpPayloadDecoderBaseTest() { + // If the test adds more data after the frame payload, + // stop as soon as the payload is decoded. + stop_decode_on_done_ = true; + frame_header_is_set_ = false; + Randomize(&frame_header_, RandomPtr()); +} + +QuicHttpDecodeStatus QuicHttpPayloadDecoderBaseTest::StartDecoding( + QuicHttpDecodeBuffer* db) { + DVLOG(2) << "StartDecoding, db->Remaining=" << db->Remaining(); + // Make sure sub-class has set frame_header_ so that we can inject it + // into the payload decoder below. + if (!frame_header_is_set_) { + ADD_FAILURE() << "frame_header_ is not set"; + return QuicHttpDecodeStatus::kDecodeError; + } + // The contract with the payload decoders is that they won't receive a + // decode buffer that extends beyond the end of the frame. + if (db->Remaining() > frame_header_.payload_length) { + ADD_FAILURE() << "QuicHttpDecodeBuffer has too much data: " + << db->Remaining() << " > " << frame_header_.payload_length; + return QuicHttpDecodeStatus::kDecodeError; + } + + // Prepare the payload decoder. + PrepareQuicHttpPayloadDecoder(); + + // Reconstruct the QuicHttpFrameDecoderState, prepare the listener, and add it + // to the QuicHttpFrameDecoderState. + QuicReconstructObject(&frame_decoder_state_, RandomPtr()); + frame_decoder_state_.set_listener(PrepareListener()); + + // Make sure that a listener was provided. + if (frame_decoder_state_.listener() == nullptr) { + ADD_FAILURE() << "PrepareListener must return a listener."; + return QuicHttpDecodeStatus::kDecodeError; + } + + // Now that nothing in the payload decoder should be valid, inject the + // QuicHttpFrameHeader whose payload we're about to decode. That header is the + // only state that a payload decoder should expect is valid when its Start + // method is called. + QuicHttpFrameDecoderStatePeer::set_frame_header(frame_header_, + &frame_decoder_state_); + QuicHttpDecodeStatus status = StartDecodingPayload(db); + if (status != QuicHttpDecodeStatus::kDecodeInProgress) { + // Keep track of this so that a concrete test can verify that both fast + // and slow decoding paths have been tested. + ++fast_decode_count_; + } + return status; +} + +QuicHttpDecodeStatus QuicHttpPayloadDecoderBaseTest::ResumeDecoding( + QuicHttpDecodeBuffer* db) { + DVLOG(2) << "ResumeDecoding, db->Remaining=" << db->Remaining(); + QuicHttpDecodeStatus status = ResumeDecodingPayload(db); + if (status != QuicHttpDecodeStatus::kDecodeInProgress) { + // Keep track of this so that a concrete test can verify that both fast + // and slow decoding paths have been tested. + ++slow_decode_count_; + } + return status; +} + +::testing::AssertionResult +QuicHttpPayloadDecoderBaseTest::DecodePayloadAndValidateSeveralWays( + QuicStringPiece payload, + const Validator& validator) { + VERIFY_TRUE(frame_header_is_set_); + // Cap the payload to be decoded at the declared payload length. This is + // required by the decoders' preconditions; they are designed on the + // assumption that they're never passed more than they're permitted to + // consume. + // Note that it is OK if the payload is too short; the validator may be + // designed to check for that. + if (payload.size() > frame_header_.payload_length) { + payload = QuicStringPiece(payload.data(), frame_header_.payload_length); + } + QuicHttpDecodeBuffer db(payload); + ResetDecodeSpeedCounters(); + const bool kMayReturnZeroOnFirst = false; + return DecodeAndValidateSeveralWays(&db, kMayReturnZeroOnFirst, validator); +} + +} // namespace test +} // namespace net
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_payload_decoder_base_test_util.h b/net/quic/http/decoder/payload_decoders/quic_http_payload_decoder_base_test_util.h new file mode 100644 index 0000000..cac831b --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_payload_decoder_base_test_util.h
@@ -0,0 +1,473 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_PAYLOAD_DECODER_BASE_TEST_UTIL_H_ +#define NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_PAYLOAD_DECODER_BASE_TEST_UTIL_H_ + +// Base class for testing concrete payload decoder classes. + +#include <stddef.h> + +#include "base/logging.h" +#include "net/quic/http/decoder/quic_http_decode_buffer.h" +#include "net/quic/http/decoder/quic_http_decode_status.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_listener.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_state.h" +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/quic_http_constants_test_util.h" +#include "net/quic/http/quic_http_structures.h" +#include "net/quic/http/test_tools/quic_http_frame_parts.h" +#include "net/quic/http/tools/quic_http_frame_builder.h" +#include "net/quic/http/tools/quic_http_random_decoder_test.h" +#include "net/quic/platform/api/quic_reconstruct_object.h" +#include "net/quic/platform/api/quic_string.h" +#include "net/quic/platform/api/quic_string_piece.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace net { +namespace test { + +// Base class for tests of payload decoders. Below this there is a templated +// sub-class that adds a bunch of type specific features. +class QuicHttpPayloadDecoderBaseTest : public QuicHttpRandomDecoderTest { + protected: + QuicHttpPayloadDecoderBaseTest(); + + // Virtual functions to be implemented by the test classes for the individual + // payload decoders... + + // Start decoding the payload. + virtual QuicHttpDecodeStatus StartDecodingPayload( + QuicHttpDecodeBuffer* db) = 0; + + // Resume decoding the payload. + virtual QuicHttpDecodeStatus ResumeDecodingPayload( + QuicHttpDecodeBuffer* db) = 0; + + // In support of ensuring that we're really accessing and updating the + // decoder, prepare the decoder by, for example, overwriting the decoder. + virtual void PrepareQuicHttpPayloadDecoder() = 0; + + // Get the listener to be inserted into the QuicHttpFrameDecoderState, ready + // for listening (e.g. reset if it is a QuicHttpFramePartsCollector). + virtual QuicHttpFrameDecoderListener* PrepareListener() = 0; + + // Record a frame header for use on each call to StartDecoding. + void set_frame_header(const QuicHttpFrameHeader& header) { + EXPECT_EQ(0, InvalidFlagMaskForFrameType(header.type) & header.flags); + if (!frame_header_is_set_ || frame_header_ != header) { + VLOG(2) << "set_frame_header: " << frame_header_; + } + frame_header_ = header; + frame_header_is_set_ = true; + } + + const QuicHttpFrameHeader& frame_header() const { + CHECK(frame_header_is_set_); + return frame_header_; + } + + QuicHttpFrameDecoderState* mutable_state() { return &frame_decoder_state_; } + + // Randomize the payload decoder, sets the payload decoder's frame_header_, + // then start decoding the payload. Called by QuicHttpRandomDecoderTest. This + // method is final so that we can always perform certain actions when + // QuicHttpRandomDecoderTest starts the decoding of a payload, such as + // randomizing the the payload decoder, injecting the frame header and + // counting fast decoding cases. Sub-classes must implement + // StartDecodingPayload to perform their initial decoding of a frame's + // payload. + QuicHttpDecodeStatus StartDecoding(QuicHttpDecodeBuffer* db) final; + + // Called by QuicHttpRandomDecoderTest. This method is final so that we can + // always perform certain actions when QuicHttpRandomDecoderTest calls it, + // such as counting slow decode cases. Sub-classes must implement + // ResumeDecodingPayload to continue decoding the frame's payload, which must + // not all be in one buffer. + QuicHttpDecodeStatus ResumeDecoding(QuicHttpDecodeBuffer* db) final; + + // Given the specified payload (without the common frame header), decode + // it with several partitionings of the payload. + ::testing::AssertionResult DecodePayloadAndValidateSeveralWays( + QuicStringPiece payload, + const Validator& validator); + + // TODO(jamessynge): Add helper method for verifying these are both non-zero, + // and call the new method from tests that expect successful decoding. + void ResetDecodeSpeedCounters() { + fast_decode_count_ = 0; + slow_decode_count_ = 0; + } + + // Count of payloads that are full decoded by StartDecodingPayload, or that + // an error was detected by StartDecodingPayload. + size_t fast_decode_count_ = 0; + + // Count of payloads that require calling ResumeDecodingPayload in order to + // decode them completely (or to detect an error during decoding). + size_t slow_decode_count_ = 0; + + private: + bool frame_header_is_set_ = false; + QuicHttpFrameHeader frame_header_; + QuicHttpFrameDecoderState frame_decoder_state_; +}; + +// Base class for payload decoders of type Decoder, with corresponding test +// peer of type DecoderPeer, and using class Listener as the implementation +// of QuicHttpFrameDecoderListenerInterface to be used during decoding. +// Typically Listener is a sub-class of QuicHttpFramePartsCollector. +// SupportedFrameType is set to false only for +// QuicHttpUnknownQuicHttpPayloadDecoder. +template <class Decoder, + class DecoderPeer, + class Listener, + bool SupportedFrameType = true> +class AbstractQuicHttpPayloadDecoderTest + : public QuicHttpPayloadDecoderBaseTest { + protected: + // An ApproveSize function returns true to approve decoding the specified + // size of payload, else false to skip that size. Typically used for negative + // tests; for example, decoding a SETTINGS frame at all sizes except for + // multiples of 6. + typedef std::function<bool(size_t size)> ApproveSize; + + AbstractQuicHttpPayloadDecoderTest() {} + + // These tests are in setup rather than the constructor for two reasons: + // 1) Constructors are not allowed to fail, so gUnit documents that EXPECT_* + // and ASSERT_* are not allowed in constructors, and should instead be in + // SetUp if they are needed before the body of the test is executed. + // 2) To allow the sub-class constructor to make any desired modifications to + // the DecoderPeer before these tests are executed; in particular, + // QuicHttpUnknownQuicHttpPayloadDecoderPeer has not got a fixed frame + // type, but it is instead set during the test's constructor. + void SetUp() override { + QuicHttpPayloadDecoderBaseTest::SetUp(); + + // Confirm that DecoderPeer et al returns sensible values. Using auto as the + // variable type so that no (narrowing) conversions take place that hide + // problems; i.e. if someone changes KnownFlagsMaskForFrameType so that it + // doesn't return a uint8, and has bits above the low-order 8 bits set, this + // bit of paranoia should detect the problem before we get too far. + auto frame_type = DecoderPeer::FrameType(); + if (SupportedFrameType) { + EXPECT_TRUE(IsSupportedQuicHttpFrameType(frame_type)) << frame_type; + } else { + EXPECT_FALSE(IsSupportedQuicHttpFrameType(frame_type)) << frame_type; + } + + auto known_flags = KnownFlagsMaskForFrameType(frame_type); + EXPECT_EQ(known_flags, known_flags & 0xff); + + auto flags_to_avoid = DecoderPeer::FlagsAffectingPayloadDecoding(); + EXPECT_EQ(flags_to_avoid, flags_to_avoid & known_flags); + } + + void PrepareQuicHttpPayloadDecoder() override { + QuicDefaultReconstructObject(&payload_decoder_, RandomPtr()); + } + + QuicHttpFrameDecoderListener* PrepareListener() override { + listener_.Reset(); + return &listener_; + } + + // Returns random flags, but only those valid for the frame type, yet not + // those that the DecoderPeer says will affect the decoding of the payload + // (e.g. the PRIORTY flag on a HEADERS frame or QUIC_HTTP_PADDED on DATA + // frames). + uint8_t RandFlags() { + return Random().Rand8() & + KnownFlagsMaskForFrameType(DecoderPeer::FrameType()) & + ~DecoderPeer::FlagsAffectingPayloadDecoding(); + } + + // Start decoding the payload. + QuicHttpDecodeStatus StartDecodingPayload(QuicHttpDecodeBuffer* db) override { + DVLOG(2) << "StartDecodingPayload, db->Remaining=" << db->Remaining(); + return payload_decoder_.StartDecodingPayload(mutable_state(), db); + } + + // Resume decoding the payload. + QuicHttpDecodeStatus ResumeDecodingPayload( + QuicHttpDecodeBuffer* db) override { + DVLOG(2) << "ResumeDecodingPayload, db->Remaining=" << db->Remaining(); + return payload_decoder_.ResumeDecodingPayload(mutable_state(), db); + } + + // Decode one frame's payload and confirm that the listener recorded the + // expected QuicHttpFrameParts instance, and only QuicHttpFrameParts instance. + // The payload will be decoded several times with different partitionings of + // the payload, and after each the validator will be called. + AssertionResult DecodePayloadAndValidateSeveralWays( + QuicStringPiece payload, + const QuicHttpFrameParts& expected) { + auto validator = [&expected, this]() -> AssertionResult { + VERIFY_FALSE(listener_.IsInProgress()); + VERIFY_EQ(1u, listener_.size()); + VERIFY_AND_RETURN_SUCCESS(expected.VerifyEquals(*listener_.frame(0))); + }; + return QuicHttpPayloadDecoderBaseTest::DecodePayloadAndValidateSeveralWays( + payload, ValidateDoneAndEmpty(validator)); + } + + // Decode one frame's payload, expecting that the final status will be + // kDecodeError, and that OnFrameSizeError will have been called on the + // listener. The payload will be decoded several times with different + // partitionings of the payload. The type WrappedValidator is either + // QuicHttpRandomDecoderTest::Validator, + // QuicHttpRandomDecoderTest::NoArgValidator or std::nullptr_t (not extra + // validation). + template <typename WrappedValidator> + ::testing::AssertionResult VerifyDetectsFrameSizeError( + QuicStringPiece payload, + const QuicHttpFrameHeader& header, + WrappedValidator wrapped_validator) { + set_frame_header(header); + // If wrapped_validator is not a QuicHttpRandomDecoderTest::Validator, make + // it so. + Validator validator = ToValidator(wrapped_validator); + // And wrap that validator in another which will check that we've reached + // the expected state of kDecodeError with OnFrameSizeError having been + // called by the payload decoder. + validator = [header, validator, this]( + const QuicHttpDecodeBuffer& input, + QuicHttpDecodeStatus status) -> ::testing::AssertionResult { + DVLOG(2) << "VerifyDetectsFrameSizeError validator; status=" << status + << "; input.Remaining=" << input.Remaining(); + VERIFY_EQ(QuicHttpDecodeStatus::kDecodeError, status); + VERIFY_FALSE(listener_.IsInProgress()); + VERIFY_EQ(1u, listener_.size()); + const QuicHttpFrameParts* frame = listener_.frame(0); + VERIFY_EQ(header, frame->frame_header); + VERIFY_TRUE(frame->has_frame_size_error); + // Verify did not get OnPaddingTooLong, as we should only ever produce + // one of these two errors for a single frame. + VERIFY_FALSE(frame->opt_missing_length); + return validator(input, status); + }; + VERIFY_AND_RETURN_SUCCESS( + QuicHttpPayloadDecoderBaseTest::DecodePayloadAndValidateSeveralWays( + payload, validator)); + } + + // Confirm that we get OnFrameSizeError when trying to decode unpadded_payload + // at all sizes from zero to unpadded_payload.size(), except those sizes not + // approved by approve_size. + // If total_pad_length is greater than zero, then that amount of padding + // is added to the payload (including the Pad Length field). + // The flags will be required_flags, QUIC_HTTP_PADDED if total_pad_length > 0, + // and some randomly selected flag bits not excluded by + // FlagsAffectingPayloadDecoding. + ::testing::AssertionResult VerifyDetectsMultipleFrameSizeErrors( + uint8_t required_flags, + QuicStringPiece unpadded_payload, + const ApproveSize& approve_size, + int total_pad_length) { + // required_flags should come from those that are defined for the frame + // type AND are those that affect the decoding of the payload (otherwise, + // the flag shouldn't be required). + QuicHttpFrameType frame_type = DecoderPeer::FrameType(); + VERIFY_EQ(required_flags, + required_flags & KnownFlagsMaskForFrameType(frame_type)); + VERIFY_EQ(required_flags, + required_flags & DecoderPeer::FlagsAffectingPayloadDecoding()); + + if (0 != (QuicHttpFrameFlag::QUIC_HTTP_PADDED & + KnownFlagsMaskForFrameType(frame_type))) { + // Frame type supports padding. + if (total_pad_length == 0) { + required_flags &= ~QuicHttpFrameFlag::QUIC_HTTP_PADDED; + } else { + required_flags |= QuicHttpFrameFlag::QUIC_HTTP_PADDED; + } + } else { + VERIFY_EQ(0, total_pad_length); + } + + bool validated = false; + for (size_t real_payload_size = 0; + real_payload_size <= unpadded_payload.size(); ++real_payload_size) { + if (approve_size != nullptr && !approve_size(real_payload_size)) { + continue; + } + VLOG(1) << "real_payload_size=" << real_payload_size; + uint8_t flags = required_flags | RandFlags(); + QuicHttpFrameBuilder fb; + if (total_pad_length > 0) { + // total_pad_length_ includes the size of the Pad Length field, and thus + // ranges from 0 (no QUIC_HTTP_PADDED flag) to 256 (Pad Length == 255). + fb.AppendUInt8(total_pad_length - 1); + } + // Append a subset of the unpadded_payload, which the decoder should + // determine is not a valid amount. + fb.Append(unpadded_payload.substr(0, real_payload_size)); + if (total_pad_length > 0) { + fb.AppendZeroes(total_pad_length - 1); + } + // We choose a random stream id because the payload decoders aren't + // checking stream ids. + uint32_t stream_id = RandStreamId(); + QuicHttpFrameHeader header(fb.size(), frame_type, flags, stream_id); + VERIFY_SUCCESS(VerifyDetectsFrameSizeError(fb.buffer(), header, nullptr)); + validated = true; + } + VERIFY_TRUE(validated); + return ::testing::AssertionSuccess(); + } + + // As above, but for frames without padding. + ::testing::AssertionResult VerifyDetectsFrameSizeError( + uint8_t required_flags, + QuicStringPiece unpadded_payload, + const ApproveSize& approve_size) { + QuicHttpFrameType frame_type = DecoderPeer::FrameType(); + uint8_t known_flags = KnownFlagsMaskForFrameType(frame_type); + VERIFY_EQ(0, known_flags & QuicHttpFrameFlag::QUIC_HTTP_PADDED); + VERIFY_EQ(0, required_flags & QuicHttpFrameFlag::QUIC_HTTP_PADDED); + VERIFY_AND_RETURN_SUCCESS(VerifyDetectsMultipleFrameSizeErrors( + required_flags, unpadded_payload, approve_size, 0)); + } + + Listener listener_; + union { + // Confirm at compile time that Decoder can be in an anonymous union, + // i.e. complain loudly if Decoder has members that prevent this, as it + // becomes annoying and possibly difficult to deal with non-anonymous + // unions and such union members. + Decoder payload_decoder_; + }; +}; + +// A base class for tests parameterized by the total number of bytes of +// padding, including the Pad Length field (i.e. a total_pad_length of 0 +// means unpadded as there is then no room for the Pad Length field). +// The frame type must support padding. +template <class Decoder, class DecoderPeer, class Listener> +class AbstractPaddableQuicHttpPayloadDecoderTest + : public AbstractQuicHttpPayloadDecoderTest<Decoder, DecoderPeer, Listener>, + public ::testing::WithParamInterface<int> { + typedef AbstractQuicHttpPayloadDecoderTest<Decoder, DecoderPeer, Listener> + Base; + + protected: + using Base::RandStreamId; + using Base::Random; + using Base::listener_; + using Base::set_frame_header; + typedef typename Base::Validator Validator; + + AbstractPaddableQuicHttpPayloadDecoderTest() : total_pad_length_(GetParam()) { + LOG(INFO) << "total_pad_length_ = " << total_pad_length_; + } + + // Note that total_pad_length_ includes the size of the Pad Length field, + // and thus ranges from 0 (no QUIC_HTTP_PADDED flag) to 256 (Pad Length == + // 255). + bool IsPadded() const { return total_pad_length_ > 0; } + + // Value of the Pad Length field. Only call if IsPadded. + size_t pad_length() const { + EXPECT_TRUE(IsPadded()); + return total_pad_length_ - 1; + } + + // Clear the frame builder and add the Pad Length field if appropriate. + void Reset() { + frame_builder_ = QuicHttpFrameBuilder(); + if (IsPadded()) { + frame_builder_.AppendUInt8(pad_length()); + } + } + + void MaybeAppendTrailingPadding() { + if (IsPadded()) { + frame_builder_.AppendZeroes(pad_length()); + } + } + + uint8_t RandFlags() { + uint8_t flags = Base::RandFlags(); + if (IsPadded()) { + flags |= QuicHttpFrameFlag::QUIC_HTTP_PADDED; + } else { + flags &= ~QuicHttpFrameFlag::QUIC_HTTP_PADDED; + } + return flags; + } + + // Verify that we get OnPaddingTooLong when decoding payload, and that the + // amount of missing padding is as specified. header.IsPadded must be true, + // and the payload must be empty or the PadLength field must be too large. + ::testing::AssertionResult VerifyDetectsPaddingTooLong( + QuicStringPiece payload, + const QuicHttpFrameHeader& header, + size_t expected_missing_length) { + set_frame_header(header); + auto& listener = listener_; + Validator validator = + [header, expected_missing_length, &listener]( + const QuicHttpDecodeBuffer& input, + QuicHttpDecodeStatus status) -> ::testing::AssertionResult { + VERIFY_EQ(QuicHttpDecodeStatus::kDecodeError, status); + VERIFY_FALSE(listener.IsInProgress()); + VERIFY_EQ(1u, listener.size()); + const QuicHttpFrameParts* frame = listener.frame(0); + VERIFY_EQ(header, frame->frame_header); + VERIFY_TRUE(frame->opt_missing_length); + VERIFY_EQ(expected_missing_length, frame->opt_missing_length.value()); + // Verify did not get OnFrameSizeError. + VERIFY_FALSE(frame->has_frame_size_error); + return ::testing::AssertionSuccess(); + }; + VERIFY_AND_RETURN_SUCCESS( + QuicHttpPayloadDecoderBaseTest::DecodePayloadAndValidateSeveralWays( + payload, validator)); + } + + // Verifies that we get OnPaddingTooLong for a padded frame payload whose + // (randomly selected) payload length is less than total_pad_length_. + // Flags will be selected at random, except QUIC_HTTP_PADDED will be set and + // flags_to_avoid will not be set. The stream id is selected at random. + ::testing::AssertionResult VerifyDetectsPaddingTooLong() { + uint8_t flags = RandFlags() | QuicHttpFrameFlag::QUIC_HTTP_PADDED; + + // Create an all padding payload for total_pad_length_. + int payload_length = 0; + QuicHttpFrameBuilder fb; + if (IsPadded()) { + fb.AppendUInt8(pad_length()); + fb.AppendZeroes(pad_length()); + VLOG(1) << "fb.size=" << fb.size(); + // Pick a random length for the payload that is shorter than neccesary. + payload_length = Random().Uniform(fb.size()); + } + + VLOG(1) << "payload_length=" << payload_length; + QuicString payload = fb.buffer().substr(0, payload_length); + + // The missing length is the amount we cut off the end, unless + // payload_length is zero, in which case the decoder knows only that 1 + // byte, the Pad Length field, is missing. + size_t missing_length = + payload_length == 0 ? 1 : fb.size() - payload_length; + VLOG(1) << "missing_length=" << missing_length; + + const QuicHttpFrameHeader header(payload_length, DecoderPeer::FrameType(), + flags, RandStreamId()); + VERIFY_AND_RETURN_SUCCESS( + VerifyDetectsPaddingTooLong(payload, header, missing_length)); + } + + // total_pad_length_ includes the size of the Pad Length field, and thus + // ranges from 0 (no QUIC_HTTP_PADDED flag) to 256 (Pad Length == 255). + const size_t total_pad_length_; + QuicHttpFrameBuilder frame_builder_; +}; + +} // namespace test +} // namespace net + +#endif // NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_PAYLOAD_DECODER_BASE_TEST_UTIL_H_
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_ping_payload_decoder.cc b/net/quic/http/decoder/payload_decoders/quic_http_ping_payload_decoder.cc new file mode 100644 index 0000000..3d691df --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_ping_payload_decoder.cc
@@ -0,0 +1,95 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/payload_decoders/quic_http_ping_payload_decoder.h" + +#include <cstdint> + +#include "base/logging.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_listener.h" +#include "net/quic/http/quic_http_constants.h" + +namespace net { +namespace { +constexpr auto kOpaqueSize = QuicHttpPingFields::EncodedSize(); +} + +QuicHttpDecodeStatus QuicHttpPingQuicHttpPayloadDecoder::StartDecodingPayload( + QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db) { + const QuicHttpFrameHeader& frame_header = state->frame_header(); + const uint32_t total_length = frame_header.payload_length; + + DVLOG(2) << "QuicHttpPingQuicHttpPayloadDecoder::StartDecodingPayload: " + << frame_header; + DCHECK_EQ(QuicHttpFrameType::PING, frame_header.type); + DCHECK_LE(db->Remaining(), total_length); + DCHECK_EQ(0, frame_header.flags & ~(QuicHttpFrameFlag::QUIC_HTTP_ACK)); + + // Is the payload entirely in the decode buffer and is it the correct size? + // Given the size of the header and payload (17 bytes total), this is most + // likely the case the vast majority of the time. + if (db->Remaining() == kOpaqueSize && total_length == kOpaqueSize) { + // Special case this situation as it allows us to avoid any copying; + // the other path makes two copies, first into the buffer in + // QuicHttpStructureDecoder as it accumulates the 8 bytes of opaque data, + // and a second copy into the QuicHttpPingFields member of in this class. + // This supports the claim that this decoder is (mostly) non-buffering. + static_assert(sizeof(QuicHttpPingFields) == kOpaqueSize, + "If not, then can't enter this block!"); + auto* ping = reinterpret_cast<const QuicHttpPingFields*>(db->cursor()); + if (frame_header.IsAck()) { + state->listener()->OnPingAck(frame_header, *ping); + } else { + state->listener()->OnPing(frame_header, *ping); + } + db->AdvanceCursor(kOpaqueSize); + return QuicHttpDecodeStatus::kDecodeDone; + } + state->InitializeRemainders(); + return HandleStatus( + state, state->StartDecodingStructureInPayload(&ping_fields_, db)); +} + +QuicHttpDecodeStatus QuicHttpPingQuicHttpPayloadDecoder::ResumeDecodingPayload( + QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db) { + DVLOG(2) << "ResumeDecodingPayload: remaining_payload=" + << state->remaining_payload(); + DCHECK_EQ(QuicHttpFrameType::PING, state->frame_header().type); + DCHECK_LE(db->Remaining(), state->frame_header().payload_length); + return HandleStatus( + state, state->ResumeDecodingStructureInPayload(&ping_fields_, db)); +} + +QuicHttpDecodeStatus QuicHttpPingQuicHttpPayloadDecoder::HandleStatus( + QuicHttpFrameDecoderState* state, + QuicHttpDecodeStatus status) { + DVLOG(2) << "HandleStatus: status=" << status + << "; remaining_payload=" << state->remaining_payload(); + if (status == QuicHttpDecodeStatus::kDecodeDone) { + if (state->remaining_payload() == 0) { + const QuicHttpFrameHeader& frame_header = state->frame_header(); + if (frame_header.IsAck()) { + state->listener()->OnPingAck(frame_header, ping_fields_); + } else { + state->listener()->OnPing(frame_header, ping_fields_); + } + return QuicHttpDecodeStatus::kDecodeDone; + } + // Payload is too long. + return state->ReportFrameSizeError(); + } + // Not done decoding the structure. Either we've got more payload to decode, + // or we've run out because the payload is too short. + DCHECK((status == QuicHttpDecodeStatus::kDecodeInProgress && + state->remaining_payload() > 0) || + (status == QuicHttpDecodeStatus::kDecodeError && + state->remaining_payload() == 0)) + << "\n status=" << status + << "; remaining_payload=" << state->remaining_payload(); + return status; +} + +} // namespace net
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_ping_payload_decoder.h b/net/quic/http/decoder/payload_decoders/quic_http_ping_payload_decoder.h new file mode 100644 index 0000000..0dce000 --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_ping_payload_decoder.h
@@ -0,0 +1,48 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_PING_PAYLOAD_DECODER_H_ +#define NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_PING_PAYLOAD_DECODER_H_ + +// Decodes the payload of a PING frame; for the RFC, see: +// http://httpwg.org/specs/rfc7540.html#PING +// +// For info about payload decoders, see: +// http://g3doc/gfe/quic/http/decoder/payload_decoders/README.md + +#include "net/quic/http/decoder/quic_http_decode_buffer.h" +#include "net/quic/http/decoder/quic_http_decode_status.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_state.h" +#include "net/quic/http/quic_http_structures.h" +#include "net/quic/platform/api/quic_export.h" + +namespace net { +namespace test { +class QuicHttpPingQuicHttpPayloadDecoderPeer; +} // namespace test + +class QUIC_EXPORT_PRIVATE QuicHttpPingQuicHttpPayloadDecoder { + public: + // Starts the decoding of a PING frame's payload, and completes it if the + // entire payload is in the provided decode buffer. + QuicHttpDecodeStatus StartDecodingPayload(QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db); + + // Resumes decoding a PING frame's payload that has been split across + // decode buffers. + QuicHttpDecodeStatus ResumeDecodingPayload(QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db); + + private: + friend class test::QuicHttpPingQuicHttpPayloadDecoderPeer; + + QuicHttpDecodeStatus HandleStatus(QuicHttpFrameDecoderState* state, + QuicHttpDecodeStatus status); + + QuicHttpPingFields ping_fields_; +}; + +} // namespace net + +#endif // NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_PING_PAYLOAD_DECODER_H_
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_ping_payload_decoder_test.cc b/net/quic/http/decoder/payload_decoders/quic_http_ping_payload_decoder_test.cc new file mode 100644 index 0000000..2c02e02 --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_ping_payload_decoder_test.cc
@@ -0,0 +1,122 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/payload_decoders/quic_http_ping_payload_decoder.h" + +#include <stddef.h> + +#include <cstdint> + +#include "base/logging.h" +#include "net/quic/http/decoder/payload_decoders/quic_http_payload_decoder_base_test_util.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_listener.h" +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/quic_http_structures_test_util.h" +#include "net/quic/http/test_tools/quic_http_frame_parts.h" +#include "net/quic/http/test_tools/quic_http_frame_parts_collector.h" +#include "net/quic/http/tools/quic_http_frame_builder.h" +#include "net/quic/http/tools/quic_http_random_decoder_test.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace net { +namespace test { + +class QuicHttpPingQuicHttpPayloadDecoderPeer { + public: + static constexpr QuicHttpFrameType FrameType() { + return QuicHttpFrameType::PING; + } + + // Returns the mask of flags that affect the decoding of the payload (i.e. + // flags that that indicate the presence of certain fields or padding). + static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; } + + static void Randomize(QuicHttpPingQuicHttpPayloadDecoder* p, + QuicTestRandomBase* rng) { + VLOG(1) << "QuicHttpPingQuicHttpPayloadDecoderPeer::Randomize"; + test::Randomize(&p->ping_fields_, rng); + } +}; + +namespace { + +struct Listener : public QuicHttpFramePartsCollector { + void OnPing(const QuicHttpFrameHeader& header, + const QuicHttpPingFields& ping) override { + VLOG(1) << "OnPing: " << header << "; " << ping; + StartAndEndFrame(header)->OnPing(header, ping); + } + + void OnPingAck(const QuicHttpFrameHeader& header, + const QuicHttpPingFields& ping) override { + VLOG(1) << "OnPingAck: " << header << "; " << ping; + StartAndEndFrame(header)->OnPingAck(header, ping); + } + + void OnFrameSizeError(const QuicHttpFrameHeader& header) override { + VLOG(1) << "OnFrameSizeError: " << header; + FrameError(header)->OnFrameSizeError(header); + } +}; + +class QuicHttpPingQuicHttpPayloadDecoderTest + : public AbstractQuicHttpPayloadDecoderTest< + QuicHttpPingQuicHttpPayloadDecoder, + QuicHttpPingQuicHttpPayloadDecoderPeer, + Listener> { + protected: + QuicHttpPingFields RandPingFields() { + QuicHttpPingFields fields; + test::Randomize(&fields, RandomPtr()); + return fields; + } +}; + +// Confirm we get an error if the payload is not the correct size to hold +// exactly one QuicHttpPingFields. +TEST_F(QuicHttpPingQuicHttpPayloadDecoderTest, WrongSize) { + auto approve_size = [](size_t size) { + return size != QuicHttpPingFields::EncodedSize(); + }; + QuicHttpFrameBuilder fb; + fb.Append(RandPingFields()); + fb.Append(RandPingFields()); + fb.Append(RandPingFields()); + EXPECT_TRUE(VerifyDetectsFrameSizeError(0, fb.buffer(), approve_size)); +} + +TEST_F(QuicHttpPingQuicHttpPayloadDecoderTest, Ping) { + for (int n = 0; n < 100; ++n) { + QuicHttpPingFields fields = RandPingFields(); + QuicHttpFrameBuilder fb; + fb.Append(fields); + QuicHttpFrameHeader header(fb.size(), QuicHttpFrameType::PING, + RandFlags() & ~QuicHttpFrameFlag::QUIC_HTTP_ACK, + RandStreamId()); + set_frame_header(header); + QuicHttpFrameParts expected(header); + expected.opt_ping = fields; + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected)); + } +} + +TEST_F(QuicHttpPingQuicHttpPayloadDecoderTest, PingAck) { + for (int n = 0; n < 100; ++n) { + QuicHttpPingFields fields; + Randomize(&fields, RandomPtr()); + QuicHttpFrameBuilder fb; + fb.Append(fields); + QuicHttpFrameHeader header(fb.size(), QuicHttpFrameType::PING, + RandFlags() | QuicHttpFrameFlag::QUIC_HTTP_ACK, + RandStreamId()); + set_frame_header(header); + QuicHttpFrameParts expected(header); + expected.opt_ping = fields; + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected)); + } +} + +} // namespace +} // namespace test +} // namespace net
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_priority_payload_decoder.cc b/net/quic/http/decoder/payload_decoders/quic_http_priority_payload_decoder.cc new file mode 100644 index 0000000..74e6819 --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_priority_payload_decoder.cc
@@ -0,0 +1,67 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/payload_decoders/quic_http_priority_payload_decoder.h" + +#include "base/logging.h" +#include "net/quic/http/decoder/quic_http_decode_buffer.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_listener.h" +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/quic_http_structures.h" + +namespace net { + +QuicHttpDecodeStatus +QuicHttpPriorityQuicHttpPayloadDecoder::StartDecodingPayload( + QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db) { + DVLOG(2) << "QuicHttpPriorityQuicHttpPayloadDecoder::StartDecodingPayload: " + << state->frame_header(); + DCHECK_EQ(QuicHttpFrameType::QUIC_HTTP_PRIORITY, state->frame_header().type); + DCHECK_LE(db->Remaining(), state->frame_header().payload_length); + // QUIC_HTTP_PRIORITY frames have no flags. + DCHECK_EQ(0, state->frame_header().flags); + state->InitializeRemainders(); + return HandleStatus( + state, state->StartDecodingStructureInPayload(&priority_fields_, db)); +} + +QuicHttpDecodeStatus +QuicHttpPriorityQuicHttpPayloadDecoder::ResumeDecodingPayload( + QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db) { + DVLOG(2) << "QuicHttpPriorityQuicHttpPayloadDecoder::ResumeDecodingPayload" + << " remaining_payload=" << state->remaining_payload() + << " db->Remaining=" << db->Remaining(); + DCHECK_EQ(QuicHttpFrameType::QUIC_HTTP_PRIORITY, state->frame_header().type); + DCHECK_LE(db->Remaining(), state->frame_header().payload_length); + return HandleStatus( + state, state->ResumeDecodingStructureInPayload(&priority_fields_, db)); +} + +QuicHttpDecodeStatus QuicHttpPriorityQuicHttpPayloadDecoder::HandleStatus( + QuicHttpFrameDecoderState* state, + QuicHttpDecodeStatus status) { + if (status == QuicHttpDecodeStatus::kDecodeDone) { + if (state->remaining_payload() == 0) { + state->listener()->OnPriorityFrame(state->frame_header(), + priority_fields_); + return QuicHttpDecodeStatus::kDecodeDone; + } + // Payload is too long. + return state->ReportFrameSizeError(); + } + // Not done decoding the structure. Either we've got more payload to decode, + // or we've run out because the payload is too short, in which case + // OnFrameSizeError will have already been called. + DCHECK((status == QuicHttpDecodeStatus::kDecodeInProgress && + state->remaining_payload() > 0) || + (status == QuicHttpDecodeStatus::kDecodeError && + state->remaining_payload() == 0)) + << "\n status=" << status + << "; remaining_payload=" << state->remaining_payload(); + return status; +} + +} // namespace net
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_priority_payload_decoder.h b/net/quic/http/decoder/payload_decoders/quic_http_priority_payload_decoder.h new file mode 100644 index 0000000..6ea757f --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_priority_payload_decoder.h
@@ -0,0 +1,48 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_QUIC_HTTP_PRIORITY_PAYLOAD_DECODER_H_ +#define NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_QUIC_HTTP_PRIORITY_PAYLOAD_DECODER_H_ + +// Decodes the payload of a QUIC_HTTP_PRIORITY frame. +// See http://g3doc/gfe/quic/http/decoder/payload_decoders/README.md for info +// about payload decoders. + +#include "net/quic/http/decoder/quic_http_decode_buffer.h" +#include "net/quic/http/decoder/quic_http_decode_status.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_state.h" +#include "net/quic/http/quic_http_structures.h" +#include "net/quic/platform/api/quic_export.h" + +namespace net { +namespace test { +class QuicHttpPriorityQuicHttpPayloadDecoderPeer; +} // namespace test + +class QUIC_EXPORT_PRIVATE QuicHttpPriorityQuicHttpPayloadDecoder { + public: + // Starts the decoding of a QUIC_HTTP_PRIORITY frame's payload, and completes + // it if the entire payload is in the provided decode buffer. + QuicHttpDecodeStatus StartDecodingPayload(QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db); + + // Resumes decoding a QUIC_HTTP_PRIORITY frame that has been split across + // decode buffers. + QuicHttpDecodeStatus ResumeDecodingPayload(QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db); + + private: + friend class test::QuicHttpPriorityQuicHttpPayloadDecoderPeer; + + // Determines whether to report the QUIC_HTTP_PRIORITY to the listener, wait + // for more input, or to report a Frame Size Error. + QuicHttpDecodeStatus HandleStatus(QuicHttpFrameDecoderState* state, + QuicHttpDecodeStatus status); + + QuicHttpPriorityFields priority_fields_; +}; + +} // namespace net + +#endif // NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_QUIC_HTTP_PRIORITY_PAYLOAD_DECODER_H_
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_priority_payload_decoder_test.cc b/net/quic/http/decoder/payload_decoders/quic_http_priority_payload_decoder_test.cc new file mode 100644 index 0000000..edfb289 --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_priority_payload_decoder_test.cc
@@ -0,0 +1,98 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/payload_decoders/quic_http_priority_payload_decoder.h" + +#include <stddef.h> + +#include <cstdint> + +#include "base/logging.h" +#include "net/quic/http/decoder/payload_decoders/quic_http_payload_decoder_base_test_util.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_listener.h" +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/quic_http_structures_test_util.h" +#include "net/quic/http/test_tools/quic_http_frame_parts.h" +#include "net/quic/http/test_tools/quic_http_frame_parts_collector.h" +#include "net/quic/http/tools/quic_http_frame_builder.h" +#include "net/quic/http/tools/quic_http_random_decoder_test.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace net { +namespace test { + +class QuicHttpPriorityQuicHttpPayloadDecoderPeer { + public: + static constexpr QuicHttpFrameType FrameType() { + return QuicHttpFrameType::QUIC_HTTP_PRIORITY; + } + + // Returns the mask of flags that affect the decoding of the payload (i.e. + // flags that that indicate the presence of certain fields or padding). + static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; } + + static void Randomize(QuicHttpPriorityQuicHttpPayloadDecoder* p, + QuicTestRandomBase* rng) { + VLOG(1) << "QuicHttpPriorityQuicHttpPayloadDecoderPeer::Randomize"; + test::Randomize(&p->priority_fields_, rng); + } +}; + +namespace { + +struct Listener : public QuicHttpFramePartsCollector { + void OnPriorityFrame(const QuicHttpFrameHeader& header, + const QuicHttpPriorityFields& priority_fields) override { + VLOG(1) << "OnPriority: " << header << "; " << priority_fields; + StartAndEndFrame(header)->OnPriorityFrame(header, priority_fields); + } + + void OnFrameSizeError(const QuicHttpFrameHeader& header) override { + VLOG(1) << "OnFrameSizeError: " << header; + FrameError(header)->OnFrameSizeError(header); + } +}; + +class QuicHttpPriorityQuicHttpPayloadDecoderTest + : public AbstractQuicHttpPayloadDecoderTest< + QuicHttpPriorityQuicHttpPayloadDecoder, + QuicHttpPriorityQuicHttpPayloadDecoderPeer, + Listener> { + protected: + QuicHttpPriorityFields RandPriorityFields() { + QuicHttpPriorityFields fields; + test::Randomize(&fields, RandomPtr()); + return fields; + } +}; + +// Confirm we get an error if the payload is not the correct size to hold +// exactly one QuicHttpPriorityFields. +TEST_F(QuicHttpPriorityQuicHttpPayloadDecoderTest, WrongSize) { + auto approve_size = [](size_t size) { + return size != QuicHttpPriorityFields::EncodedSize(); + }; + QuicHttpFrameBuilder fb; + fb.Append(RandPriorityFields()); + fb.Append(RandPriorityFields()); + EXPECT_TRUE(VerifyDetectsFrameSizeError(0, fb.buffer(), approve_size)); +} + +TEST_F(QuicHttpPriorityQuicHttpPayloadDecoderTest, VariousPayloads) { + for (int n = 0; n < 100; ++n) { + QuicHttpPriorityFields fields = RandPriorityFields(); + QuicHttpFrameBuilder fb; + fb.Append(fields); + QuicHttpFrameHeader header(fb.size(), QuicHttpFrameType::QUIC_HTTP_PRIORITY, + RandFlags(), RandStreamId()); + set_frame_header(header); + QuicHttpFrameParts expected(header); + expected.opt_priority = fields; + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected)); + } +} + +} // namespace +} // namespace test +} // namespace net
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_push_promise_payload_decoder.cc b/net/quic/http/decoder/payload_decoders/quic_http_push_promise_payload_decoder.cc new file mode 100644 index 0000000..72e144e --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_push_promise_payload_decoder.cc
@@ -0,0 +1,179 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/payload_decoders/quic_http_push_promise_payload_decoder.h" + +#include <stddef.h> + +#include <cstdint> + +#include "base/logging.h" +#include "base/macros.h" +#include "net/quic/http/decoder/quic_http_decode_buffer.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_listener.h" +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/quic_http_structures.h" +#include "net/quic/platform/api/quic_bug_tracker.h" + +namespace net { + +std::ostream& operator<<( + std::ostream& out, + QuicHttpPushPromiseQuicHttpPayloadDecoder::PayloadState v) { + switch (v) { + case QuicHttpPushPromiseQuicHttpPayloadDecoder::PayloadState:: + kReadPadLength: + return out << "kReadPadLength"; + case QuicHttpPushPromiseQuicHttpPayloadDecoder::PayloadState:: + kStartDecodingPushPromiseFields: + return out << "kStartDecodingPushPromiseFields"; + case QuicHttpPushPromiseQuicHttpPayloadDecoder::PayloadState::kReadPayload: + return out << "kReadPayload"; + case QuicHttpPushPromiseQuicHttpPayloadDecoder::PayloadState::kSkipPadding: + return out << "kSkipPadding"; + case QuicHttpPushPromiseQuicHttpPayloadDecoder::PayloadState:: + kResumeDecodingPushPromiseFields: + return out << "kResumeDecodingPushPromiseFields"; + } + return out << static_cast<int>(v); +} + +QuicHttpDecodeStatus +QuicHttpPushPromiseQuicHttpPayloadDecoder::StartDecodingPayload( + QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db) { + const QuicHttpFrameHeader& frame_header = state->frame_header(); + const uint32_t total_length = frame_header.payload_length; + + DVLOG(2) + << "QuicHttpPushPromiseQuicHttpPayloadDecoder::StartDecodingPayload: " + << frame_header; + + DCHECK_EQ(QuicHttpFrameType::PUSH_PROMISE, frame_header.type); + DCHECK_LE(db->Remaining(), total_length); + DCHECK_EQ(0, frame_header.flags & ~(QuicHttpFrameFlag::QUIC_HTTP_END_HEADERS | + QuicHttpFrameFlag::QUIC_HTTP_PADDED)); + + if (!frame_header.IsPadded()) { + // If it turns out that PUSH_PROMISE frames without padding are sufficiently + // common, and that they are usually short enough that they fit entirely + // into one QuicHttpDecodeBuffer, we can detect that here and implement a + // special case, avoiding the state machine in ResumeDecodingPayload. + payload_state_ = PayloadState::kStartDecodingPushPromiseFields; + } else { + payload_state_ = PayloadState::kReadPadLength; + } + state->InitializeRemainders(); + return ResumeDecodingPayload(state, db); +} + +QuicHttpDecodeStatus +QuicHttpPushPromiseQuicHttpPayloadDecoder::ResumeDecodingPayload( + QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db) { + DVLOG(2) << "QuicHttpUnknownQuicHttpPayloadDecoder::ResumeDecodingPayload" + << " remaining_payload=" << state->remaining_payload() + << " db->Remaining=" << db->Remaining(); + + const QuicHttpFrameHeader& frame_header = state->frame_header(); + DCHECK_EQ(QuicHttpFrameType::PUSH_PROMISE, frame_header.type); + DCHECK_LE(state->remaining_payload(), frame_header.payload_length); + DCHECK_LE(db->Remaining(), frame_header.payload_length); + + QuicHttpDecodeStatus status; + while (true) { + DVLOG(2) << "QuicHttpPushPromiseQuicHttpPayloadDecoder::" + "ResumeDecodingPayload payload_state_=" + << payload_state_; + switch (payload_state_) { + case PayloadState::kReadPadLength: + DCHECK_EQ(state->remaining_payload(), frame_header.payload_length); + // ReadPadLength handles the OnPadLength callback, and updating the + // remaining_payload and remaining_padding fields. If the amount of + // padding is too large to fit in the frame's payload, ReadPadLength + // instead calls OnPaddingTooLong and returns kDecodeError. + // Suppress the call to OnPadLength because we haven't yet called + // OnPushPromiseStart, which needs to wait until we've decoded the + // Promised Stream ID. + status = state->ReadPadLength(db, /*report_pad_length*/ false); + if (status != QuicHttpDecodeStatus::kDecodeDone) { + payload_state_ = PayloadState::kReadPadLength; + return status; + } + // FALLTHROUGH_INTENDED; + + case PayloadState::kStartDecodingPushPromiseFields: + status = + state->StartDecodingStructureInPayload(&push_promise_fields_, db); + if (status != QuicHttpDecodeStatus::kDecodeDone) { + payload_state_ = PayloadState::kResumeDecodingPushPromiseFields; + return status; + } + // Finished decoding the Promised Stream ID. Can now tell the listener + // that we're starting to decode a PUSH_PROMISE frame. + ReportPushPromise(state); + // FALLTHROUGH_INTENDED; + + case PayloadState::kReadPayload: + DCHECK_LT(state->remaining_payload(), frame_header.payload_length); + DCHECK_LE(state->remaining_payload(), + frame_header.payload_length - + QuicHttpPushPromiseFields::EncodedSize()); + DCHECK_LE( + state->remaining_payload(), + frame_header.payload_length - + QuicHttpPushPromiseFields::EncodedSize() - + (frame_header.IsPadded() ? (1 + state->remaining_padding()) + : 0)); + { + size_t avail = state->AvailablePayload(db); + state->listener()->OnHpackFragment(db->cursor(), avail); + db->AdvanceCursor(avail); + state->ConsumePayload(avail); + } + if (state->remaining_payload() > 0) { + payload_state_ = PayloadState::kReadPayload; + return QuicHttpDecodeStatus::kDecodeInProgress; + } + // FALLTHROUGH_INTENDED; + + case PayloadState::kSkipPadding: + // SkipPadding handles the OnPadding callback. + if (state->SkipPadding(db)) { + state->listener()->OnPushPromiseEnd(); + return QuicHttpDecodeStatus::kDecodeDone; + } + payload_state_ = PayloadState::kSkipPadding; + return QuicHttpDecodeStatus::kDecodeInProgress; + + case PayloadState::kResumeDecodingPushPromiseFields: + status = + state->ResumeDecodingStructureInPayload(&push_promise_fields_, db); + if (status == QuicHttpDecodeStatus::kDecodeDone) { + // Finished decoding the Promised Stream ID. Can now tell the listener + // that we're starting to decode a PUSH_PROMISE frame. + ReportPushPromise(state); + payload_state_ = PayloadState::kReadPayload; + continue; + } + payload_state_ = PayloadState::kResumeDecodingPushPromiseFields; + return status; + } + QUIC_BUG << "PayloadState: " << payload_state_; + } +} + +void QuicHttpPushPromiseQuicHttpPayloadDecoder::ReportPushPromise( + QuicHttpFrameDecoderState* state) { + const QuicHttpFrameHeader& frame_header = state->frame_header(); + if (frame_header.IsPadded()) { + state->listener()->OnPushPromiseStart(frame_header, push_promise_fields_, + 1 + state->remaining_padding()); + } else { + state->listener()->OnPushPromiseStart(frame_header, push_promise_fields_, + 0); + } +} + +} // namespace net
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_push_promise_payload_decoder.h b/net/quic/http/decoder/payload_decoders/quic_http_push_promise_payload_decoder.h new file mode 100644 index 0000000..2a122dd2 --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_push_promise_payload_decoder.h
@@ -0,0 +1,71 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_PUSH_PROMISE_PAYLOAD_DECODER_H_ +#define NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_PUSH_PROMISE_PAYLOAD_DECODER_H_ + +// Decodes the payload of a PUSH_PROMISE frame. +// See http://g3doc/gfe/quic/http/decoder/payload_decoders/README.md for info +// about payload decoders. + +#include "net/quic/http/decoder/quic_http_decode_buffer.h" +#include "net/quic/http/decoder/quic_http_decode_status.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_state.h" +#include "net/quic/http/quic_http_structures.h" +#include "net/quic/platform/api/quic_export.h" + +namespace net { +namespace test { +class QuicHttpPushPromiseQuicHttpPayloadDecoderPeer; +} // namespace test + +class QUIC_EXPORT_PRIVATE QuicHttpPushPromiseQuicHttpPayloadDecoder { + public: + // States during decoding of a PUSH_PROMISE frame. + enum class PayloadState { + // The frame is padded and we need to read the PAD_LENGTH field (1 byte). + kReadPadLength, + + // Ready to start decoding the fixed size fields of the PUSH_PROMISE + // frame into push_promise_fields_. + kStartDecodingPushPromiseFields, + + // The decoder has already called OnPushPromiseStart, and is now reporting + // the HPQUIC_HTTP_ACK block fragment to the listener's OnHpackFragment + // method. + kReadPayload, + + // The decoder has finished with the HPQUIC_HTTP_ACK block fragment, and is + // now + // ready to skip the trailing padding, if the frame has any. + kSkipPadding, + + // The fixed size fields weren't all available when the decoder first tried + // to decode them (state kStartDecodingPushPromiseFields); this state + // resumes the decoding when ResumeDecodingPayload is called later. + kResumeDecodingPushPromiseFields, + }; + + // Starts the decoding of a PUSH_PROMISE frame's payload, and completes it if + // the entire payload is in the provided decode buffer. + QuicHttpDecodeStatus StartDecodingPayload(QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db); + + // Resumes decoding a PUSH_PROMISE frame's payload that has been split across + // decode buffers. + QuicHttpDecodeStatus ResumeDecodingPayload(QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db); + + private: + friend class test::QuicHttpPushPromiseQuicHttpPayloadDecoderPeer; + + void ReportPushPromise(QuicHttpFrameDecoderState* state); + + PayloadState payload_state_; + QuicHttpPushPromiseFields push_promise_fields_; +}; + +} // namespace net + +#endif // NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_PUSH_PROMISE_PAYLOAD_DECODER_H_
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_push_promise_payload_decoder_test.cc b/net/quic/http/decoder/payload_decoders/quic_http_push_promise_payload_decoder_test.cc new file mode 100644 index 0000000..7c63942 --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_push_promise_payload_decoder_test.cc
@@ -0,0 +1,147 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/payload_decoders/quic_http_push_promise_payload_decoder.h" + +#include <stddef.h> + +#include <cstdint> + +#include "base/logging.h" +#include "net/quic/http/decoder/payload_decoders/quic_http_payload_decoder_base_test_util.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_listener.h" +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/quic_http_structures_test_util.h" +#include "net/quic/http/test_tools/quic_http_frame_parts.h" +#include "net/quic/http/test_tools/quic_http_frame_parts_collector.h" +#include "net/quic/http/tools/quic_http_frame_builder.h" +#include "net/quic/http/tools/quic_http_random_decoder_test.h" +#include "net/quic/platform/api/quic_string.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace net { +namespace test { + +// Provides friend access to an instance of the payload decoder, and also +// provides info to aid in testing. +class QuicHttpPushPromiseQuicHttpPayloadDecoderPeer { + public: + static constexpr QuicHttpFrameType FrameType() { + return QuicHttpFrameType::PUSH_PROMISE; + } + + // Returns the mask of flags that affect the decoding of the payload (i.e. + // flags that that indicate the presence of certain fields or padding). + static constexpr uint8_t FlagsAffectingPayloadDecoding() { + return QuicHttpFrameFlag::QUIC_HTTP_PADDED; + } + + static void Randomize(QuicHttpPushPromiseQuicHttpPayloadDecoder* p, + QuicTestRandomBase* rng) { + VLOG(1) << "QuicHttpPushPromiseQuicHttpPayloadDecoderPeer::Randomize"; + CorruptEnum(&p->payload_state_, rng); + test::Randomize(&p->push_promise_fields_, rng); + } +}; + +namespace { + +// Listener listens for only those methods expected by the payload decoder +// under test, and forwards them onto the QuicHttpFrameParts instance for the +// current frame. +struct Listener : public QuicHttpFramePartsCollector { + void OnPushPromiseStart(const QuicHttpFrameHeader& header, + const QuicHttpPushPromiseFields& promise, + size_t total_padding_length) override { + VLOG(1) << "OnPushPromiseStart header: " << header + << " promise: " << promise + << " total_padding_length: " << total_padding_length; + EXPECT_EQ(QuicHttpFrameType::PUSH_PROMISE, header.type); + StartFrame(header)->OnPushPromiseStart(header, promise, + total_padding_length); + } + + void OnHpackFragment(const char* data, size_t len) override { + VLOG(1) << "OnHpackFragment: len=" << len; + CurrentFrame()->OnHpackFragment(data, len); + } + + void OnPushPromiseEnd() override { + VLOG(1) << "OnPushPromiseEnd"; + EndFrame()->OnPushPromiseEnd(); + } + + void OnPadding(const char* padding, size_t skipped_length) override { + VLOG(1) << "OnPadding: " << skipped_length; + CurrentFrame()->OnPadding(padding, skipped_length); + } + + void OnPaddingTooLong(const QuicHttpFrameHeader& header, + size_t missing_length) override { + VLOG(1) << "OnPaddingTooLong: " << header + << "; missing_length: " << missing_length; + FrameError(header)->OnPaddingTooLong(header, missing_length); + } + + void OnFrameSizeError(const QuicHttpFrameHeader& header) override { + VLOG(1) << "OnFrameSizeError: " << header; + FrameError(header)->OnFrameSizeError(header); + } +}; + +class QuicHttpPushPromiseQuicHttpPayloadDecoderTest + : public AbstractPaddableQuicHttpPayloadDecoderTest< + QuicHttpPushPromiseQuicHttpPayloadDecoder, + QuicHttpPushPromiseQuicHttpPayloadDecoderPeer, + Listener> {}; + +INSTANTIATE_TEST_CASE_P(VariousPadLengths, + QuicHttpPushPromiseQuicHttpPayloadDecoderTest, + ::testing::Values(0, 1, 2, 3, 4, 254, 255, 256)); + +// Payload contains the required QuicHttpPushPromiseFields, followed by some +// (fake) HPQUIC_HTTP_ACK payload. +TEST_P(QuicHttpPushPromiseQuicHttpPayloadDecoderTest, + VariousHpackPayloadSizes) { + for (size_t hpack_size : {0, 1, 2, 3, 255, 256, 1024}) { + LOG(INFO) << "########### hpack_size = " << hpack_size << " ###########"; + Reset(); + QuicString hpack_payload = Random().RandString(hpack_size); + QuicHttpPushPromiseFields push_promise{RandStreamId()}; + frame_builder_.Append(push_promise); + frame_builder_.Append(hpack_payload); + MaybeAppendTrailingPadding(); + QuicHttpFrameHeader frame_header(frame_builder_.size(), + QuicHttpFrameType::PUSH_PROMISE, + RandFlags(), RandStreamId()); + set_frame_header(frame_header); + QuicHttpFrameParts expected(frame_header, hpack_payload, total_pad_length_); + expected.opt_push_promise = push_promise; + EXPECT_TRUE( + DecodePayloadAndValidateSeveralWays(frame_builder_.buffer(), expected)); + } +} + +// Confirm we get an error if the payload is not long enough for the required +// portion of the payload, regardless of the amount of (valid) padding. +TEST_P(QuicHttpPushPromiseQuicHttpPayloadDecoderTest, Truncated) { + auto approve_size = [](size_t size) { + return size != QuicHttpPushPromiseFields::EncodedSize(); + }; + QuicHttpPushPromiseFields push_promise{RandStreamId()}; + QuicHttpFrameBuilder fb; + fb.Append(push_promise); + EXPECT_TRUE(VerifyDetectsMultipleFrameSizeErrors(0, fb.buffer(), approve_size, + total_pad_length_)); +} + +// Confirm we get an error if the QUIC_HTTP_PADDED flag is set but the payload +// is not long enough to hold even the Pad Length amount of padding. +TEST_P(QuicHttpPushPromiseQuicHttpPayloadDecoderTest, PaddingTooLong) { + EXPECT_TRUE(VerifyDetectsPaddingTooLong()); +} + +} // namespace +} // namespace test +} // namespace net
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_rst_stream_payload_decoder.cc b/net/quic/http/decoder/payload_decoders/quic_http_rst_stream_payload_decoder.cc new file mode 100644 index 0000000..44e9c1f --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_rst_stream_payload_decoder.cc
@@ -0,0 +1,70 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/payload_decoders/quic_http_rst_stream_payload_decoder.h" + +#include "base/logging.h" +#include "net/quic/http/decoder/quic_http_decode_buffer.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_listener.h" +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/quic_http_structures.h" + +namespace net { + +QuicHttpDecodeStatus +QuicHttpRstStreamQuicHttpPayloadDecoder::StartDecodingPayload( + QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db) { + DVLOG(2) << "QuicHttpRstStreamQuicHttpPayloadDecoder::StartDecodingPayload: " + << state->frame_header(); + DCHECK_EQ(QuicHttpFrameType::RST_STREAM, state->frame_header().type); + DCHECK_LE(db->Remaining(), state->frame_header().payload_length); + // RST_STREAM has no flags. + DCHECK_EQ(0, state->frame_header().flags); + state->InitializeRemainders(); + return HandleStatus( + state, state->StartDecodingStructureInPayload(&rst_stream_fields_, db)); +} + +QuicHttpDecodeStatus +QuicHttpRstStreamQuicHttpPayloadDecoder::ResumeDecodingPayload( + QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db) { + DVLOG(2) << "QuicHttpRstStreamQuicHttpPayloadDecoder::ResumeDecodingPayload" + << " remaining_payload=" << state->remaining_payload() + << " db->Remaining=" << db->Remaining(); + DCHECK_EQ(QuicHttpFrameType::RST_STREAM, state->frame_header().type); + DCHECK_LE(db->Remaining(), state->frame_header().payload_length); + return HandleStatus( + state, state->ResumeDecodingStructureInPayload(&rst_stream_fields_, db)); +} + +QuicHttpDecodeStatus QuicHttpRstStreamQuicHttpPayloadDecoder::HandleStatus( + QuicHttpFrameDecoderState* state, + QuicHttpDecodeStatus status) { + DVLOG(2) << "HandleStatus: status=" << status + << "; remaining_payload=" << state->remaining_payload(); + if (status == QuicHttpDecodeStatus::kDecodeDone) { + if (state->remaining_payload() == 0) { + state->listener()->OnRstStream(state->frame_header(), + rst_stream_fields_.error_code); + return QuicHttpDecodeStatus::kDecodeDone; + } + // Payload is too long. + return state->ReportFrameSizeError(); + } + // Not done decoding the structure. Either we've got more payload to decode, + // or we've run out because the payload is too short, in which case + // OnFrameSizeError will have already been called by the + // QuicHttpFrameDecoderState. + DCHECK((status == QuicHttpDecodeStatus::kDecodeInProgress && + state->remaining_payload() > 0) || + (status == QuicHttpDecodeStatus::kDecodeError && + state->remaining_payload() == 0)) + << "\n status=" << status + << "; remaining_payload=" << state->remaining_payload(); + return status; +} + +} // namespace net
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_rst_stream_payload_decoder.h b/net/quic/http/decoder/payload_decoders/quic_http_rst_stream_payload_decoder.h new file mode 100644 index 0000000..3b83b65 --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_rst_stream_payload_decoder.h
@@ -0,0 +1,46 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_RST_STREAM_PAYLOAD_DECODER_H_ +#define NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_RST_STREAM_PAYLOAD_DECODER_H_ + +// Decodes the payload of a RST_STREAM frame. +// See http://g3doc/gfe/quic/http/decoder/payload_decoders/README.md for info +// about payload decoders. + +#include "net/quic/http/decoder/quic_http_decode_buffer.h" +#include "net/quic/http/decoder/quic_http_decode_status.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_state.h" +#include "net/quic/http/quic_http_structures.h" +#include "net/quic/platform/api/quic_export.h" + +namespace net { +namespace test { +class QuicHttpRstStreamQuicHttpPayloadDecoderPeer; +} // namespace test + +class QUIC_EXPORT_PRIVATE QuicHttpRstStreamQuicHttpPayloadDecoder { + public: + // Starts the decoding of a RST_STREAM frame's payload, and completes it if + // the entire payload is in the provided decode buffer. + QuicHttpDecodeStatus StartDecodingPayload(QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db); + + // Resumes decoding a RST_STREAM frame's payload that has been split across + // decode buffers. + QuicHttpDecodeStatus ResumeDecodingPayload(QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db); + + private: + friend class test::QuicHttpRstStreamQuicHttpPayloadDecoderPeer; + + QuicHttpDecodeStatus HandleStatus(QuicHttpFrameDecoderState* state, + QuicHttpDecodeStatus status); + + QuicHttpRstStreamFields rst_stream_fields_; +}; + +} // namespace net + +#endif // NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_RST_STREAM_PAYLOAD_DECODER_H_
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_rst_stream_payload_decoder_test.cc b/net/quic/http/decoder/payload_decoders/quic_http_rst_stream_payload_decoder_test.cc new file mode 100644 index 0000000..c522257 --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_rst_stream_payload_decoder_test.cc
@@ -0,0 +1,100 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/payload_decoders/quic_http_rst_stream_payload_decoder.h" + +#include <stddef.h> + +#include <cstdint> + +#include "base/logging.h" +#include "net/quic/http/decoder/payload_decoders/quic_http_payload_decoder_base_test_util.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_listener.h" +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/quic_http_constants_test_util.h" +#include "net/quic/http/quic_http_structures_test_util.h" +#include "net/quic/http/test_tools/quic_http_frame_parts.h" +#include "net/quic/http/test_tools/quic_http_frame_parts_collector.h" +#include "net/quic/http/tools/quic_http_frame_builder.h" +#include "net/quic/http/tools/quic_http_random_decoder_test.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace net { +namespace test { + +class QuicHttpRstStreamQuicHttpPayloadDecoderPeer { + public: + static constexpr QuicHttpFrameType FrameType() { + return QuicHttpFrameType::RST_STREAM; + } + + // Returns the mask of flags that affect the decoding of the payload (i.e. + // flags that that indicate the presence of certain fields or padding). + static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; } + + static void Randomize(QuicHttpRstStreamQuicHttpPayloadDecoder* p, + QuicTestRandomBase* rng) { + VLOG(1) << "QuicHttpRstStreamQuicHttpPayloadDecoderPeer::Randomize"; + test::Randomize(&p->rst_stream_fields_, rng); + } +}; + +namespace { + +struct Listener : public QuicHttpFramePartsCollector { + void OnRstStream(const QuicHttpFrameHeader& header, + QuicHttpErrorCode error_code) override { + VLOG(1) << "OnRstStream: " << header << "; error_code=" << error_code; + StartAndEndFrame(header)->OnRstStream(header, error_code); + } + + void OnFrameSizeError(const QuicHttpFrameHeader& header) override { + VLOG(1) << "OnFrameSizeError: " << header; + FrameError(header)->OnFrameSizeError(header); + } +}; + +class QuicHttpRstStreamQuicHttpPayloadDecoderTest + : public AbstractQuicHttpPayloadDecoderTest< + QuicHttpRstStreamQuicHttpPayloadDecoder, + QuicHttpRstStreamQuicHttpPayloadDecoderPeer, + Listener> { + protected: + QuicHttpRstStreamFields RandRstStreamFields() { + QuicHttpRstStreamFields fields; + test::Randomize(&fields, RandomPtr()); + return fields; + } +}; + +// Confirm we get an error if the payload is not the correct size to hold +// exactly one QuicHttpRstStreamFields. +TEST_F(QuicHttpRstStreamQuicHttpPayloadDecoderTest, WrongSize) { + auto approve_size = [](size_t size) { + return size != QuicHttpRstStreamFields::EncodedSize(); + }; + QuicHttpFrameBuilder fb; + fb.Append(RandRstStreamFields()); + fb.Append(RandRstStreamFields()); + fb.Append(RandRstStreamFields()); + EXPECT_TRUE(VerifyDetectsFrameSizeError(0, fb.buffer(), approve_size)); +} + +TEST_F(QuicHttpRstStreamQuicHttpPayloadDecoderTest, AllErrors) { + for (auto error_code : AllQuicHttpErrorCodes()) { + QuicHttpRstStreamFields fields{error_code}; + QuicHttpFrameBuilder fb; + fb.Append(fields); + QuicHttpFrameHeader header(fb.size(), QuicHttpFrameType::RST_STREAM, + RandFlags(), RandStreamId()); + set_frame_header(header); + QuicHttpFrameParts expected(header); + expected.opt_rst_stream_error_code = error_code; + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected)); + } +} + +} // namespace +} // namespace test +} // namespace net
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_settings_payload_decoder.cc b/net/quic/http/decoder/payload_decoders/quic_http_settings_payload_decoder.cc new file mode 100644 index 0000000..6da43fb --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_settings_payload_decoder.cc
@@ -0,0 +1,110 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/payload_decoders/quic_http_settings_payload_decoder.h" + +#include <cstdint> + +#include "base/logging.h" +#include "net/quic/http/decoder/quic_http_decode_buffer.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_listener.h" +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/quic_http_structures.h" + +namespace net { + +QuicHttpDecodeStatus +QuicHttpQuicHttpSettingsQuicHttpPayloadDecoder::StartDecodingPayload( + QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db) { + const QuicHttpFrameHeader& frame_header = state->frame_header(); + const uint32_t total_length = frame_header.payload_length; + + DVLOG(2) << "QuicHttpQuicHttpSettingsQuicHttpPayloadDecoder::" + "StartDecodingPayload: " + << frame_header; + DCHECK_EQ(QuicHttpFrameType::SETTINGS, frame_header.type); + DCHECK_LE(db->Remaining(), total_length); + DCHECK_EQ(0, frame_header.flags & ~(QuicHttpFrameFlag::QUIC_HTTP_ACK)); + + if (frame_header.IsAck()) { + if (total_length == 0) { + state->listener()->OnSettingsAck(frame_header); + return QuicHttpDecodeStatus::kDecodeDone; + } else { + state->InitializeRemainders(); + return state->ReportFrameSizeError(); + } + } else { + state->InitializeRemainders(); + state->listener()->OnSettingsStart(frame_header); + return StartDecodingSettings(state, db); + } +} + +QuicHttpDecodeStatus +QuicHttpQuicHttpSettingsQuicHttpPayloadDecoder::ResumeDecodingPayload( + QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db) { + DVLOG(2) + << "QuicHttpQuicHttpSettingsQuicHttpPayloadDecoder::ResumeDecodingPayload" + << " remaining_payload=" << state->remaining_payload() + << " db->Remaining=" << db->Remaining(); + DCHECK_EQ(QuicHttpFrameType::SETTINGS, state->frame_header().type); + DCHECK_LE(db->Remaining(), state->frame_header().payload_length); + + QuicHttpDecodeStatus status = + state->ResumeDecodingStructureInPayload(&setting_fields_, db); + if (status == QuicHttpDecodeStatus::kDecodeDone) { + state->listener()->OnSetting(setting_fields_); + return StartDecodingSettings(state, db); + } + return HandleNotDone(state, db, status); +} + +QuicHttpDecodeStatus +QuicHttpQuicHttpSettingsQuicHttpPayloadDecoder::StartDecodingSettings( + QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db) { + DVLOG(2) + << "QuicHttpQuicHttpSettingsQuicHttpPayloadDecoder::StartDecodingSettings" + << " remaining_payload=" << state->remaining_payload() + << " db->Remaining=" << db->Remaining(); + while (state->remaining_payload() > 0) { + QuicHttpDecodeStatus status = + state->StartDecodingStructureInPayload(&setting_fields_, db); + if (status == QuicHttpDecodeStatus::kDecodeDone) { + state->listener()->OnSetting(setting_fields_); + continue; + } + return HandleNotDone(state, db, status); + } + DVLOG(2) << "LEAVING " + "QuicHttpQuicHttpSettingsQuicHttpPayloadDecoder::" + "StartDecodingSettings" + << "\n\tdb->Remaining=" << db->Remaining() + << "\n\t remaining_payload=" << state->remaining_payload(); + state->listener()->OnSettingsEnd(); + return QuicHttpDecodeStatus::kDecodeDone; +} + +QuicHttpDecodeStatus +QuicHttpQuicHttpSettingsQuicHttpPayloadDecoder::HandleNotDone( + QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db, + QuicHttpDecodeStatus status) { + // Not done decoding the structure. Either we've got more payload to decode, + // or we've run out because the payload is too short, in which case + // OnFrameSizeError will have already been called. + DCHECK((status == QuicHttpDecodeStatus::kDecodeInProgress && + state->remaining_payload() > 0) || + (status == QuicHttpDecodeStatus::kDecodeError && + state->remaining_payload() == 0)) + << "\n status=" << status + << "; remaining_payload=" << state->remaining_payload() + << "; db->Remaining=" << db->Remaining(); + return status; +} + +} // namespace net
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_settings_payload_decoder.h b/net/quic/http/decoder/payload_decoders/quic_http_settings_payload_decoder.h new file mode 100644 index 0000000..f9c1154 --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_settings_payload_decoder.h
@@ -0,0 +1,58 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_SETTINGS_PAYLOAD_DECODER_H_ +#define NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_SETTINGS_PAYLOAD_DECODER_H_ + +// Decodes the payload of a SETTINGS frame; for the RFC, see: +// http://httpwg.org/specs/rfc7540.html#SETTINGS +// +// For info about payload decoders, see: +// http://g3doc/gfe/quic/http/decoder/payload_decoders/README.md + +#include "net/quic/http/decoder/quic_http_decode_buffer.h" +#include "net/quic/http/decoder/quic_http_decode_status.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_state.h" +#include "net/quic/http/quic_http_structures.h" +#include "net/quic/platform/api/quic_export.h" + +namespace net { +namespace test { +class QuicHttpQuicHttpSettingsQuicHttpPayloadDecoderPeer; +} // namespace test + +class QUIC_EXPORT_PRIVATE QuicHttpQuicHttpSettingsQuicHttpPayloadDecoder { + public: + // Starts the decoding of a SETTINGS frame's payload, and completes it if + // the entire payload is in the provided decode buffer. + QuicHttpDecodeStatus StartDecodingPayload(QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db); + + // Resumes decoding a SETTINGS frame that has been split across decode + // buffers. + QuicHttpDecodeStatus ResumeDecodingPayload(QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db); + + private: + friend class test::QuicHttpQuicHttpSettingsQuicHttpPayloadDecoderPeer; + + // Decodes as many settings as are available in the decode buffer, starting at + // the first byte of one setting; if a single setting is split across buffers, + // ResumeDecodingPayload will handle starting from where the previous call + // left off, and then will call StartDecodingSettings. + QuicHttpDecodeStatus StartDecodingSettings(QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db); + + // Decoding a single SETTING returned a status other than kDecodeDone; this + // method just brings together the DCHECKs to reduce duplication. + QuicHttpDecodeStatus HandleNotDone(QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db, + QuicHttpDecodeStatus status); + + QuicHttpSettingFields setting_fields_; +}; + +} // namespace net + +#endif // NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_SETTINGS_PAYLOAD_DECODER_H_
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_settings_payload_decoder_test.cc b/net/quic/http/decoder/payload_decoders/quic_http_settings_payload_decoder_test.cc new file mode 100644 index 0000000..596c3e1 --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_settings_payload_decoder_test.cc
@@ -0,0 +1,170 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/payload_decoders/quic_http_settings_payload_decoder.h" + +#include <stddef.h> + +#include <cstdint> +#include <vector> + +#include "base/logging.h" +#include "net/quic/http/decoder/payload_decoders/quic_http_payload_decoder_base_test_util.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_listener.h" +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/quic_http_constants_test_util.h" +#include "net/quic/http/quic_http_structures_test_util.h" +#include "net/quic/http/test_tools/quic_http_frame_parts.h" +#include "net/quic/http/test_tools/quic_http_frame_parts_collector.h" +#include "net/quic/http/tools/quic_http_frame_builder.h" +#include "net/quic/http/tools/quic_http_random_decoder_test.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace net { +namespace test { + +class QuicHttpQuicHttpSettingsQuicHttpPayloadDecoderPeer { + public: + static constexpr QuicHttpFrameType FrameType() { + return QuicHttpFrameType::SETTINGS; + } + + // Returns the mask of flags that affect the decoding of the payload (i.e. + // flags that that indicate the presence of certain fields or padding). + static constexpr uint8_t FlagsAffectingPayloadDecoding() { + return QuicHttpFrameFlag::QUIC_HTTP_ACK; + } + + static void Randomize(QuicHttpQuicHttpSettingsQuicHttpPayloadDecoder* p, + QuicTestRandomBase* rng) { + VLOG(1) << "QuicHttpQuicHttpSettingsQuicHttpPayloadDecoderPeer::Randomize"; + test::Randomize(&p->setting_fields_, rng); + } +}; + +namespace { + +struct Listener : public QuicHttpFramePartsCollector { + void OnSettingsStart(const QuicHttpFrameHeader& header) override { + VLOG(1) << "OnSettingsStart: " << header; + EXPECT_EQ(QuicHttpFrameType::SETTINGS, header.type) << header; + EXPECT_EQ(QuicHttpFrameFlag(), header.flags) << header; + StartFrame(header)->OnSettingsStart(header); + } + + void OnSetting(const QuicHttpSettingFields& setting_fields) override { + VLOG(1) << "QuicHttpSettingFields: setting_fields=" << setting_fields; + CurrentFrame()->OnSetting(setting_fields); + } + + void OnSettingsEnd() override { + VLOG(1) << "OnSettingsEnd"; + EndFrame()->OnSettingsEnd(); + } + + void OnSettingsAck(const QuicHttpFrameHeader& header) override { + VLOG(1) << "OnSettingsAck: " << header; + StartAndEndFrame(header)->OnSettingsAck(header); + } + + void OnFrameSizeError(const QuicHttpFrameHeader& header) override { + VLOG(1) << "OnFrameSizeError: " << header; + FrameError(header)->OnFrameSizeError(header); + } +}; + +class QuicHttpQuicHttpSettingsQuicHttpPayloadDecoderTest + : public AbstractQuicHttpPayloadDecoderTest< + QuicHttpQuicHttpSettingsQuicHttpPayloadDecoder, + QuicHttpQuicHttpSettingsQuicHttpPayloadDecoderPeer, + Listener> { + protected: + QuicHttpSettingFields RandSettingsFields() { + QuicHttpSettingFields fields; + test::Randomize(&fields, RandomPtr()); + return fields; + } +}; + +// Confirm we get an error if the SETTINGS payload is not the correct size +// to hold exactly zero or more whole QuicHttpSettingFields. +TEST_F(QuicHttpQuicHttpSettingsQuicHttpPayloadDecoderTest, SettingsWrongSize) { + auto approve_size = [](size_t size) { + // Should get an error if size is not an integral multiple of the size + // of one setting. + return 0 != (size % QuicHttpSettingFields::EncodedSize()); + }; + QuicHttpFrameBuilder fb; + fb.Append(RandSettingsFields()); + fb.Append(RandSettingsFields()); + fb.Append(RandSettingsFields()); + EXPECT_TRUE(VerifyDetectsFrameSizeError(0, fb.buffer(), approve_size)); +} + +// Confirm we get an error if the SETTINGS QUIC_HTTP_ACK payload is not empty. +TEST_F(QuicHttpQuicHttpSettingsQuicHttpPayloadDecoderTest, + SettingsAkcWrongSize) { + auto approve_size = [](size_t size) { return size != 0; }; + QuicHttpFrameBuilder fb; + fb.Append(RandSettingsFields()); + fb.Append(RandSettingsFields()); + fb.Append(RandSettingsFields()); + EXPECT_TRUE(VerifyDetectsFrameSizeError(QuicHttpFrameFlag::QUIC_HTTP_ACK, + fb.buffer(), approve_size)); +} + +// SETTINGS must have stream_id==0, but the payload decoder doesn't check that. +TEST_F(QuicHttpQuicHttpSettingsQuicHttpPayloadDecoderTest, SettingsAck) { + for (int stream_id = 0; stream_id < 3; ++stream_id) { + QuicHttpFrameHeader header(0, QuicHttpFrameType::SETTINGS, + RandFlags() | QuicHttpFrameFlag::QUIC_HTTP_ACK, + stream_id); + set_frame_header(header); + QuicHttpFrameParts expected(header); + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays("", expected)); + } +} + +// Try several values of each known SETTINGS parameter. +TEST_F(QuicHttpQuicHttpSettingsQuicHttpPayloadDecoderTest, OneRealSetting) { + std::vector<uint32_t> values = {0, 1, 0xffffffff, Random().Rand32()}; + for (auto param : AllQuicHttpSettingsParameters()) { + for (uint32_t value : values) { + QuicHttpSettingFields fields(param, value); + QuicHttpFrameBuilder fb; + fb.Append(fields); + QuicHttpFrameHeader header(fb.size(), QuicHttpFrameType::SETTINGS, + RandFlags(), RandStreamId()); + set_frame_header(header); + QuicHttpFrameParts expected(header); + expected.settings.push_back(fields); + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected)); + } + } +} + +// Decode a SETTINGS frame with lots of fields. +TEST_F(QuicHttpQuicHttpSettingsQuicHttpPayloadDecoderTest, ManySettings) { + const size_t num_settings = 100; + const size_t size = QuicHttpSettingFields::EncodedSize() * num_settings; + QuicHttpFrameHeader header( + size, QuicHttpFrameType::SETTINGS, + RandFlags(), // & ~QuicHttpFrameFlag::QUIC_HTTP_ACK, + RandStreamId()); + set_frame_header(header); + QuicHttpFrameParts expected(header); + QuicHttpFrameBuilder fb; + for (size_t n = 0; n < num_settings; ++n) { + QuicHttpSettingFields fields(static_cast<QuicHttpSettingsParameter>(n), + Random().Rand32()); + fb.Append(fields); + expected.settings.push_back(fields); + } + ASSERT_EQ(size, fb.size()); + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected)); +} + +} // namespace +} // namespace test +} // namespace net
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_unknown_payload_decoder.cc b/net/quic/http/decoder/payload_decoders/quic_http_unknown_payload_decoder.cc new file mode 100644 index 0000000..fb36c53 --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_unknown_payload_decoder.cc
@@ -0,0 +1,58 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/payload_decoders/quic_http_unknown_payload_decoder.h" + +#include <stddef.h> + +#include "base/logging.h" +#include "net/quic/http/decoder/quic_http_decode_buffer.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_listener.h" +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/quic_http_structures.h" + +namespace net { + +QuicHttpDecodeStatus +QuicHttpUnknownQuicHttpPayloadDecoder::StartDecodingPayload( + QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db) { + const QuicHttpFrameHeader& frame_header = state->frame_header(); + + DVLOG(2) << "QuicHttpUnknownQuicHttpPayloadDecoder::StartDecodingPayload: " + << frame_header; + DCHECK(!IsSupportedQuicHttpFrameType(frame_header.type)) << frame_header; + DCHECK_LE(db->Remaining(), frame_header.payload_length); + + state->InitializeRemainders(); + state->listener()->OnUnknownStart(frame_header); + return ResumeDecodingPayload(state, db); +} + +QuicHttpDecodeStatus +QuicHttpUnknownQuicHttpPayloadDecoder::ResumeDecodingPayload( + QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db) { + DVLOG(2) << "QuicHttpUnknownQuicHttpPayloadDecoder::ResumeDecodingPayload " + << "remaining_payload=" << state->remaining_payload() + << "; db->Remaining=" << db->Remaining(); + DCHECK(!IsSupportedQuicHttpFrameType(state->frame_header().type)) + << state->frame_header(); + DCHECK_LE(state->remaining_payload(), state->frame_header().payload_length); + DCHECK_LE(db->Remaining(), state->remaining_payload()); + + size_t avail = db->Remaining(); + if (avail > 0) { + state->listener()->OnUnknownPayload(db->cursor(), avail); + db->AdvanceCursor(avail); + state->ConsumePayload(avail); + } + if (state->remaining_payload() == 0) { + state->listener()->OnUnknownEnd(); + return QuicHttpDecodeStatus::kDecodeDone; + } + return QuicHttpDecodeStatus::kDecodeInProgress; +} + +} // namespace net
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_unknown_payload_decoder.h b/net/quic/http/decoder/payload_decoders/quic_http_unknown_payload_decoder.h new file mode 100644 index 0000000..a8121a8 --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_unknown_payload_decoder.h
@@ -0,0 +1,37 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_UNKNOWN_PAYLOAD_DECODER_H_ +#define NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_UNKNOWN_PAYLOAD_DECODER_H_ + +// Decodes the payload of a frame whose type unknown. According to the HTTP/2 +// specification (http://httpwg.org/specs/rfc7540.html#FrameHeader): +// Implementations MUST ignore and discard any frame that has +// a type that is unknown. +// +// See http://g3doc/gfe/quic/http/decoder/payload_decoders/README.md for info +// about payload decoders. + +#include "net/quic/http/decoder/quic_http_decode_buffer.h" +#include "net/quic/http/decoder/quic_http_decode_status.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_state.h" +#include "net/quic/platform/api/quic_export.h" + +namespace net { + +class QUIC_EXPORT_PRIVATE QuicHttpUnknownQuicHttpPayloadDecoder { + public: + // Starts decoding a payload of unknown type; just passes it to the listener. + QuicHttpDecodeStatus StartDecodingPayload(QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db); + + // Resumes decoding a payload of unknown type that has been split across + // decode buffers. + QuicHttpDecodeStatus ResumeDecodingPayload(QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db); +}; + +} // namespace net + +#endif // NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_UNKNOWN_PAYLOAD_DECODER_H_
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_unknown_payload_decoder_test.cc b/net/quic/http/decoder/payload_decoders/quic_http_unknown_payload_decoder_test.cc new file mode 100644 index 0000000..ff2a8fd --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_unknown_payload_decoder_test.cc
@@ -0,0 +1,110 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/payload_decoders/quic_http_unknown_payload_decoder.h" + +#include <stddef.h> + +#include <cstdint> +#include <type_traits> + +#include "base/logging.h" +#include "net/quic/http/decoder/payload_decoders/quic_http_payload_decoder_base_test_util.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_listener.h" +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/quic_http_structures.h" +#include "net/quic/http/test_tools/quic_http_frame_parts.h" +#include "net/quic/http/test_tools/quic_http_frame_parts_collector.h" +#include "net/quic/http/tools/quic_http_random_decoder_test.h" +#include "net/quic/platform/api/quic_string.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace net { +namespace test { +namespace { +QuicHttpFrameType g_unknown_frame_type; +} // namespace + +// Provides friend access to an instance of the payload decoder, and also +// provides info to aid in testing. +class QuicHttpUnknownQuicHttpPayloadDecoderPeer { + public: + static QuicHttpFrameType FrameType() { return g_unknown_frame_type; } + + // Returns the mask of flags that affect the decoding of the payload (i.e. + // flags that that indicate the presence of certain fields or padding). + static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; } + + static void Randomize(QuicHttpUnknownQuicHttpPayloadDecoder* p, + QuicTestRandomBase* rng) { + // QuicHttpUnknownQuicHttpPayloadDecoder has no fields, so there is nothing + // to randomize. + static_assert( + std::is_empty<QuicHttpUnknownQuicHttpPayloadDecoder>::value, + "Need to randomize fields of QuicHttpUnknownQuicHttpPayloadDecoder"); + } +}; + +namespace { + +struct Listener : public QuicHttpFramePartsCollector { + void OnUnknownStart(const QuicHttpFrameHeader& header) override { + VLOG(1) << "OnUnknownStart: " << header; + StartFrame(header)->OnUnknownStart(header); + } + + void OnUnknownPayload(const char* data, size_t len) override { + VLOG(1) << "OnUnknownPayload: len=" << len; + CurrentFrame()->OnUnknownPayload(data, len); + } + + void OnUnknownEnd() override { + VLOG(1) << "OnUnknownEnd"; + EndFrame()->OnUnknownEnd(); + } +}; + +constexpr bool SupportedFrameType = false; + +class QuicHttpUnknownQuicHttpPayloadDecoderTest + : public AbstractQuicHttpPayloadDecoderTest< + QuicHttpUnknownQuicHttpPayloadDecoder, + QuicHttpUnknownQuicHttpPayloadDecoderPeer, + Listener, + SupportedFrameType>, + public ::testing::WithParamInterface<uint32_t> { + protected: + QuicHttpUnknownQuicHttpPayloadDecoderTest() : length_(GetParam()) { + VLOG(1) << "################ length_=" << length_ << " ################"; + + // Each test case will choose a random frame type that isn't supported. + do { + g_unknown_frame_type = static_cast<QuicHttpFrameType>(Random().Rand8()); + } while (IsSupportedQuicHttpFrameType(g_unknown_frame_type)); + } + + const uint32_t length_; +}; + +INSTANTIATE_TEST_CASE_P(VariousLengths, + QuicHttpUnknownQuicHttpPayloadDecoderTest, + ::testing::Values(0, 1, 2, 3, 255, 256)); + +TEST_P(QuicHttpUnknownQuicHttpPayloadDecoderTest, ValidLength) { + QuicString unknown_payload = Random().RandString(length_); + QuicHttpFrameHeader frame_header(length_, g_unknown_frame_type, + Random().Rand8(), RandStreamId()); + set_frame_header(frame_header); + QuicHttpFrameParts expected(frame_header, unknown_payload); + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(unknown_payload, expected)); + // TODO(jamessynge): Check here (and in other such tests) that the fast + // and slow decode counts are both non-zero. Perhaps also add some kind of + // test for the listener having been called. That could simply be a test + // that there is a single collected QuicHttpFrameParts instance, and that it + // matches expected. +} + +} // namespace +} // namespace test +} // namespace net
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_window_update_payload_decoder.cc b/net/quic/http/decoder/payload_decoders/quic_http_window_update_payload_decoder.cc new file mode 100644 index 0000000..a6564f7 --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_window_update_payload_decoder.cc
@@ -0,0 +1,88 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/payload_decoders/quic_http_window_update_payload_decoder.h" + +#include <cstdint> + +#include "base/logging.h" +#include "net/quic/http/decoder/quic_http_decode_buffer.h" +#include "net/quic/http/decoder/quic_http_decode_structures.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_listener.h" +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/quic_http_structures.h" + +namespace net { + +QuicHttpDecodeStatus +QuicHttpWindowUpdateQuicHttpPayloadDecoder::StartDecodingPayload( + QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db) { + const QuicHttpFrameHeader& frame_header = state->frame_header(); + const uint32_t total_length = frame_header.payload_length; + + DVLOG(2) + << "QuicHttpWindowUpdateQuicHttpPayloadDecoder::StartDecodingPayload: " + << frame_header; + + DCHECK_EQ(QuicHttpFrameType::WINDOW_UPDATE, frame_header.type); + DCHECK_LE(db->Remaining(), total_length); + + // WINDOW_UPDATE frames have no flags. + DCHECK_EQ(0, frame_header.flags); + + // Special case for when the payload is the correct size and entirely in + // the buffer. + if (db->Remaining() == QuicHttpWindowUpdateFields::EncodedSize() && + total_length == QuicHttpWindowUpdateFields::EncodedSize()) { + DoDecode(&window_update_fields_, db); + state->listener()->OnWindowUpdate( + frame_header, window_update_fields_.window_size_increment); + return QuicHttpDecodeStatus::kDecodeDone; + } + state->InitializeRemainders(); + return HandleStatus(state, state->StartDecodingStructureInPayload( + &window_update_fields_, db)); +} + +QuicHttpDecodeStatus +QuicHttpWindowUpdateQuicHttpPayloadDecoder::ResumeDecodingPayload( + QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db) { + DVLOG(2) << "ResumeDecodingPayload: remaining_payload=" + << state->remaining_payload() + << "; db->Remaining=" << db->Remaining(); + DCHECK_EQ(QuicHttpFrameType::WINDOW_UPDATE, state->frame_header().type); + DCHECK_LE(db->Remaining(), state->frame_header().payload_length); + return HandleStatus(state, state->ResumeDecodingStructureInPayload( + &window_update_fields_, db)); +} + +QuicHttpDecodeStatus QuicHttpWindowUpdateQuicHttpPayloadDecoder::HandleStatus( + QuicHttpFrameDecoderState* state, + QuicHttpDecodeStatus status) { + DVLOG(2) << "HandleStatus: status=" << status + << "; remaining_payload=" << state->remaining_payload(); + if (status == QuicHttpDecodeStatus::kDecodeDone) { + if (state->remaining_payload() == 0) { + state->listener()->OnWindowUpdate( + state->frame_header(), window_update_fields_.window_size_increment); + return QuicHttpDecodeStatus::kDecodeDone; + } + // Payload is too long. + return state->ReportFrameSizeError(); + } + // Not done decoding the structure. Either we've got more payload to decode, + // or we've run out because the payload is too short, in which case + // OnFrameSizeError will have already been called. + DCHECK((status == QuicHttpDecodeStatus::kDecodeInProgress && + state->remaining_payload() > 0) || + (status == QuicHttpDecodeStatus::kDecodeError && + state->remaining_payload() == 0)) + << "\n status=" << status + << "; remaining_payload=" << state->remaining_payload(); + return status; +} + +} // namespace net
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_window_update_payload_decoder.h b/net/quic/http/decoder/payload_decoders/quic_http_window_update_payload_decoder.h new file mode 100644 index 0000000..317400f --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_window_update_payload_decoder.h
@@ -0,0 +1,46 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_WINDOW_UPDATE_PAYLOAD_DECODER_H_ +#define NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_WINDOW_UPDATE_PAYLOAD_DECODER_H_ + +// Decodes the payload of a WINDOW_UPDATE frame. +// See http://g3doc/gfe/quic/http/decoder/payload_decoders/README.md for info +// about payload decoders. + +#include "net/quic/http/decoder/quic_http_decode_buffer.h" +#include "net/quic/http/decoder/quic_http_decode_status.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_state.h" +#include "net/quic/http/quic_http_structures.h" +#include "net/quic/platform/api/quic_export.h" + +namespace net { +namespace test { +class QuicHttpWindowUpdateQuicHttpPayloadDecoderPeer; +} // namespace test + +class QUIC_EXPORT_PRIVATE QuicHttpWindowUpdateQuicHttpPayloadDecoder { + public: + // Starts decoding a WINDOW_UPDATE frame's payload, and completes it if + // the entire payload is in the provided decode buffer. + QuicHttpDecodeStatus StartDecodingPayload(QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db); + + // Resumes decoding a WINDOW_UPDATE frame's payload that has been split across + // decode buffers. + QuicHttpDecodeStatus ResumeDecodingPayload(QuicHttpFrameDecoderState* state, + QuicHttpDecodeBuffer* db); + + private: + friend class test::QuicHttpWindowUpdateQuicHttpPayloadDecoderPeer; + + QuicHttpDecodeStatus HandleStatus(QuicHttpFrameDecoderState* state, + QuicHttpDecodeStatus status); + + QuicHttpWindowUpdateFields window_update_fields_; +}; + +} // namespace net + +#endif // NET_QUIC_HTTP_DECODER_PAYLOAD_DECODERS_QUIC_HTTP_WINDOW_UPDATE_PAYLOAD_DECODER_H_
diff --git a/net/quic/http/decoder/payload_decoders/quic_http_window_update_payload_decoder_test.cc b/net/quic/http/decoder/payload_decoders/quic_http_window_update_payload_decoder_test.cc new file mode 100644 index 0000000..9e2734e --- /dev/null +++ b/net/quic/http/decoder/payload_decoders/quic_http_window_update_payload_decoder_test.cc
@@ -0,0 +1,104 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/payload_decoders/quic_http_window_update_payload_decoder.h" + +#include <stddef.h> + +#include <cstdint> + +#include "base/logging.h" +#include "net/quic/http/decoder/payload_decoders/quic_http_payload_decoder_base_test_util.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_listener.h" +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/quic_http_structures_test_util.h" +#include "net/quic/http/test_tools/quic_http_frame_parts.h" +#include "net/quic/http/test_tools/quic_http_frame_parts_collector.h" +#include "net/quic/http/tools/quic_http_frame_builder.h" +#include "net/quic/http/tools/quic_http_random_decoder_test.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace net { +namespace test { + +class QuicHttpWindowUpdateQuicHttpPayloadDecoderPeer { + public: + static constexpr QuicHttpFrameType FrameType() { + return QuicHttpFrameType::WINDOW_UPDATE; + } + + // Returns the mask of flags that affect the decoding of the payload (i.e. + // flags that that indicate the presence of certain fields or padding). + static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; } + + static void Randomize(QuicHttpWindowUpdateQuicHttpPayloadDecoder* p, + QuicTestRandomBase* rng) { + test::Randomize(&p->window_update_fields_, rng); + VLOG(1) << "QuicHttpWindowUpdateQuicHttpPayloadDecoderPeer::Randomize " + << "window_update_fields_: " << p->window_update_fields_; + } +}; + +namespace { + +struct Listener : public QuicHttpFramePartsCollector { + void OnWindowUpdate(const QuicHttpFrameHeader& header, + uint32_t window_size_increment) override { + VLOG(1) << "OnWindowUpdate: " << header + << "; window_size_increment=" << window_size_increment; + EXPECT_EQ(QuicHttpFrameType::WINDOW_UPDATE, header.type); + StartAndEndFrame(header)->OnWindowUpdate(header, window_size_increment); + } + + void OnFrameSizeError(const QuicHttpFrameHeader& header) override { + VLOG(1) << "OnFrameSizeError: " << header; + FrameError(header)->OnFrameSizeError(header); + } +}; + +class QuicHttpWindowUpdateQuicHttpPayloadDecoderTest + : public AbstractQuicHttpPayloadDecoderTest< + QuicHttpWindowUpdateQuicHttpPayloadDecoder, + QuicHttpWindowUpdateQuicHttpPayloadDecoderPeer, + Listener> { + protected: + QuicHttpWindowUpdateFields RandWindowUpdateFields() { + QuicHttpWindowUpdateFields fields; + test::Randomize(&fields, RandomPtr()); + VLOG(3) << "RandWindowUpdateFields: " << fields; + return fields; + } +}; + +// Confirm we get an error if the payload is not the correct size to hold +// exactly one QuicHttpWindowUpdateFields. +TEST_F(QuicHttpWindowUpdateQuicHttpPayloadDecoderTest, WrongSize) { + auto approve_size = [](size_t size) { + return size != QuicHttpWindowUpdateFields::EncodedSize(); + }; + QuicHttpFrameBuilder fb; + fb.Append(RandWindowUpdateFields()); + fb.Append(RandWindowUpdateFields()); + fb.Append(RandWindowUpdateFields()); + EXPECT_TRUE(VerifyDetectsFrameSizeError(0, fb.buffer(), approve_size)); +} + +TEST_F(QuicHttpWindowUpdateQuicHttpPayloadDecoderTest, VariousPayloads) { + for (int n = 0; n < 100; ++n) { + uint32_t stream_id = n == 0 ? 0 : RandStreamId(); + QuicHttpWindowUpdateFields fields = RandWindowUpdateFields(); + QuicHttpFrameBuilder fb; + fb.Append(fields); + QuicHttpFrameHeader header(fb.size(), QuicHttpFrameType::WINDOW_UPDATE, + RandFlags(), stream_id); + set_frame_header(header); + QuicHttpFrameParts expected(header); + expected.opt_window_update_increment = fields.window_size_increment; + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected)); + } +} + +} // namespace +} // namespace test +} // namespace net
diff --git a/net/quic/http/decoder/quic_http_decode_buffer.cc b/net/quic/http/decoder/quic_http_decode_buffer.cc new file mode 100644 index 0000000..c444f72 --- /dev/null +++ b/net/quic/http/decoder/quic_http_decode_buffer.cc
@@ -0,0 +1,60 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/quic_http_decode_buffer.h" + +namespace net { + +#ifndef NDEBUG +// These are part of validating during tests that there is at most one +// QuicHttpDecodeBufferSubset instance at a time for any DecodeBuffer instance. +void QuicHttpDecodeBuffer::set_subset_of_base( + QuicHttpDecodeBuffer* base, + const QuicHttpDecodeBufferSubset* subset) { + DCHECK_EQ(this, subset); + base->set_subset(subset); +} +void QuicHttpDecodeBuffer::clear_subset_of_base( + QuicHttpDecodeBuffer* base, + const QuicHttpDecodeBufferSubset* subset) { + DCHECK_EQ(this, subset); + base->clear_subset(subset); +} +void QuicHttpDecodeBuffer::set_subset( + const QuicHttpDecodeBufferSubset* subset) { + DCHECK(subset != nullptr); + DCHECK_EQ(subset_, nullptr) << "There is already a subset"; + subset_ = subset; +} +void QuicHttpDecodeBuffer::clear_subset( + const QuicHttpDecodeBufferSubset* subset) { + DCHECK(subset != nullptr); + DCHECK_EQ(subset_, subset); + subset_ = nullptr; +} +void QuicHttpDecodeBufferSubset::DebugSetup() { + start_base_offset_ = base_buffer_->Offset(); + max_base_offset_ = start_base_offset_ + FullSize(); + DCHECK_LE(max_base_offset_, base_buffer_->FullSize()); + + // Ensure that there is only one QuicHttpDecodeBufferSubset at a time for a + // base. + set_subset_of_base(base_buffer_, this); +} +void QuicHttpDecodeBufferSubset::DebugTearDown() { + // Ensure that the base hasn't been modified. + DCHECK_EQ(start_base_offset_, base_buffer_->Offset()) + << "The base buffer was modified"; + + // Ensure that we haven't gone beyond the maximum allowed offset. + size_t offset = Offset(); + DCHECK_LE(offset, FullSize()); + DCHECK_LE(start_base_offset_ + offset, max_base_offset_); + DCHECK_LE(max_base_offset_, base_buffer_->FullSize()); + + clear_subset_of_base(base_buffer_, this); +} +#endif + +} // namespace net
diff --git a/net/quic/http/decoder/quic_http_decode_buffer.h b/net/quic/http/decoder/quic_http_decode_buffer.h new file mode 100644 index 0000000..1a65991 --- /dev/null +++ b/net/quic/http/decoder/quic_http_decode_buffer.h
@@ -0,0 +1,202 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_HTTP_DECODER_QUIC_HTTP_DECODE_BUFFER_H_ +#define NET_QUIC_HTTP_DECODER_QUIC_HTTP_DECODE_BUFFER_H_ + +// QuicHttpDecodeBuffer provides primitives for decoding various integer types +// found in HTTP/2 frames. It wraps a byte array from which we can read and +// decode serialized HTTP/2 frames, or parts thereof. QuicHttpDecodeBuffer is +// intended only for stack allocation, where the caller is typically going to +// use the QuicHttpDecodeBuffer instance as part of decoding the entire buffer +// before returning to its own caller. + +#include <stddef.h> +#include <stdint.h> + +#include <algorithm> + +#include "base/logging.h" +#include "base/macros.h" +#include "net/quic/platform/api/quic_export.h" +#include "net/quic/platform/api/quic_string_piece.h" + +namespace net { +class QuicHttpDecodeBufferSubset; + +class QUIC_EXPORT_PRIVATE QuicHttpDecodeBuffer { + public: + QuicHttpDecodeBuffer(const char* buffer, size_t len) + : buffer_(buffer), cursor_(buffer), beyond_(buffer + len) { + DCHECK(buffer != nullptr); + DCHECK_LE(len, MaxQuicHttpDecodeBufferLength()); + } + explicit QuicHttpDecodeBuffer(QuicStringPiece s) + : QuicHttpDecodeBuffer(s.data(), s.size()) {} + // Constructor for character arrays, typically in tests. For example: + // const char input[] = { 0x11 }; + // QuicHttpDecodeBuffer b(input); + template <size_t N> + explicit QuicHttpDecodeBuffer(const char (&buf)[N]) + : QuicHttpDecodeBuffer(buf, N) {} + + bool Empty() const { return cursor_ >= beyond_; } + bool HasData() const { return cursor_ < beyond_; } + size_t Remaining() const { + DCHECK_LE(cursor_, beyond_); + return beyond_ - cursor_; + } + size_t Offset() const { return cursor_ - buffer_; } + size_t FullSize() const { return beyond_ - buffer_; } + + // Returns the minimum of the number of bytes remaining in this + // QuicHttpDecodeBuffer and |length|, in support of determining how much of + // some structure/quic_http_payload is in this QuicHttpDecodeBuffer. + size_t MinLengthRemaining(size_t length) const { + return std::min(length, Remaining()); + } + + // For std::string decoding, returns a pointer to the next byte/char to be + // decoded. + const char* cursor() const { return cursor_; } + // Advances the cursor (pointer to the next byte/char to be decoded). + void AdvanceCursor(size_t amount) { + DCHECK_LE(amount, Remaining()); // Need at least that much remaining. + DCHECK_EQ(subset_, nullptr) << "Access via subset only when present."; + cursor_ += amount; + } + + // Only call methods starting "Decode" when there is enough input remaining. + char DecodeChar() { + DCHECK_LE(1u, Remaining()); // Need at least one byte remaining. + DCHECK_EQ(subset_, nullptr) << "Access via subset only when present."; + return *cursor_++; + } + + uint8_t DecodeUInt8() { return static_cast<uint8_t>(DecodeChar()); } + + uint16_t DecodeUInt16() { + DCHECK_LE(2u, Remaining()); + const uint8_t b1 = DecodeUInt8(); + const uint8_t b2 = DecodeUInt8(); + // Note that chars are automatically promoted to ints during arithmetic, + // so the b1 << 8 doesn't end up as zero before being or-ed with b2. + // And the left-shift operator has higher precedence than the or operator. + return b1 << 8 | b2; + } + + uint32_t DecodeUInt24() { + DCHECK_LE(3u, Remaining()); + const uint8_t b1 = DecodeUInt8(); + const uint8_t b2 = DecodeUInt8(); + const uint8_t b3 = DecodeUInt8(); + return b1 << 16 | b2 << 8 | b3; + } + + // For 31-bit unsigned integers, where the 32nd bit is reserved for future + // use (i.e. the high-bit of the first byte of the encoding); examples: + // the Stream Id in a frame header or the Window Size Increment in a + // WINDOW_UPDATE frame. + uint32_t DecodeUInt31() { + DCHECK_LE(4u, Remaining()); + const uint8_t b1 = DecodeUInt8() & 0x7f; // Mask out the high order bit. + const uint8_t b2 = DecodeUInt8(); + const uint8_t b3 = DecodeUInt8(); + const uint8_t b4 = DecodeUInt8(); + return b1 << 24 | b2 << 16 | b3 << 8 | b4; + } + + uint32_t DecodeUInt32() { + DCHECK_LE(4u, Remaining()); + const uint8_t b1 = DecodeUInt8(); + const uint8_t b2 = DecodeUInt8(); + const uint8_t b3 = DecodeUInt8(); + const uint8_t b4 = DecodeUInt8(); + return b1 << 24 | b2 << 16 | b3 << 8 | b4; + } + + // We assume the decode buffers will typically be modest in size (i.e. often a + // few KB, perhaps as high as 100KB). Let's make sure during testing that we + // don't go very high, with 32MB selected rather arbitrarily. + static constexpr size_t MaxQuicHttpDecodeBufferLength() { return 1 << 25; } + + protected: +#ifndef NDEBUG + // These are part of validating during tests that there is at most one + // QuicHttpDecodeBufferSubset instance at a time for any DecodeBuffer + // instance. + void set_subset_of_base(QuicHttpDecodeBuffer* base, + const QuicHttpDecodeBufferSubset* subset); + void clear_subset_of_base(QuicHttpDecodeBuffer* base, + const QuicHttpDecodeBufferSubset* subset); +#endif + + private: +#ifndef NDEBUG + void set_subset(const QuicHttpDecodeBufferSubset* subset); + void clear_subset(const QuicHttpDecodeBufferSubset* subset); +#endif + + // Prevent heap allocation of QuicHttpDecodeBuffer. + static void* operator new(size_t s); + static void* operator new[](size_t s); + static void operator delete(void* p); + static void operator delete[](void* p); + + const char* const buffer_; + const char* cursor_; + const char* const beyond_; + const QuicHttpDecodeBufferSubset* subset_ = nullptr; // Used for DCHECKs. + + DISALLOW_COPY_AND_ASSIGN(QuicHttpDecodeBuffer); +}; + +// QuicHttpDecodeBufferSubset is used when decoding a known sized chunk of data, +// which starts at base->cursor(), and continues for subset_len, which may be +// entirely in |base|, or may extend beyond it (hence the MinLengthRemaining +// in the constructor). +// There are two benefits to using QuicHttpDecodeBufferSubset: it ensures that +// the cursor of |base| is advanced when the subset's destructor runs, and it +// ensures that the consumer of the subset can't go beyond the subset which +// it is intended to decode. +// There must be only a single QuicHttpDecodeBufferSubset at a time for a base +// QuicHttpDecodeBuffer, though they can be nested (i.e. a DecodeBufferSubset's +// base may itself be a QuicHttpDecodeBufferSubset). This avoids the +// AdvanceCursor being called erroneously. +class QUIC_EXPORT_PRIVATE QuicHttpDecodeBufferSubset + : public QuicHttpDecodeBuffer { + public: + QuicHttpDecodeBufferSubset(QuicHttpDecodeBuffer* base, size_t subset_len) + : QuicHttpDecodeBuffer(base->cursor(), + base->MinLengthRemaining(subset_len)), + base_buffer_(base) { +#ifndef NDEBUG + DebugSetup(); +#endif + } + + ~QuicHttpDecodeBufferSubset() { + size_t offset = Offset(); +#ifndef NDEBUG + DebugTearDown(); +#endif + base_buffer_->AdvanceCursor(offset); + } + + private: + QuicHttpDecodeBuffer* const base_buffer_; +#ifndef NDEBUG + size_t start_base_offset_; // Used for DCHECKs. + size_t max_base_offset_; // Used for DCHECKs. + + void DebugSetup(); + void DebugTearDown(); +#endif + + DISALLOW_COPY_AND_ASSIGN(QuicHttpDecodeBufferSubset); +}; + +} // namespace net + +#endif // NET_QUIC_HTTP_DECODER_QUIC_HTTP_DECODE_BUFFER_H_
diff --git a/net/quic/http/decoder/quic_http_decode_buffer_test.cc b/net/quic/http/decoder/quic_http_decode_buffer_test.cc new file mode 100644 index 0000000..4a6809c --- /dev/null +++ b/net/quic/http/decoder/quic_http_decode_buffer_test.cc
@@ -0,0 +1,209 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/quic_http_decode_buffer.h" + +#include "base/logging.h" +#include "net/quic/platform/api/quic_test_random.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace net { +namespace test { +namespace { + +enum class TestEnumClass32 { + kValue1 = 1, + kValue99 = 99, + kValue1M = 1000000, +}; + +enum class TestEnumClass8 { + kValue1 = 1, + kValue2 = 1, + kValue99 = 99, + kValue255 = 255, +}; + +enum TestEnum8 { + kMaskLo = 0x01, + kMaskHi = 0x80, +}; + +struct TestStruct { + uint8_t f1; + uint16_t f2; + uint32_t f3; // Decoded as a uint24 + uint32_t f4; + uint32_t f5; // Decoded as if uint31 + TestEnumClass32 f6; + TestEnumClass8 f7; + TestEnum8 f8; +}; + +class QuicHttpDecodeBufferTest : public ::testing::Test { + public: + QuicHttpDecodeBufferTest() { + LOG(INFO) << "Random seed (--test_random_seed): " + << testing::FLAGS_gtest_random_seed; + } + + protected: + QuicTestRandom random_; + uint32_t decode_offset_; +}; + +TEST_F(QuicHttpDecodeBufferTest, DecodesFixedInts) { + const char data[] = "\x01\x12\x23\x34\x45\x56\x67\x78\x89\x9a"; + QuicHttpDecodeBuffer b1(data, strlen(data)); + EXPECT_EQ(1, b1.DecodeUInt8()); + EXPECT_EQ(0x1223u, b1.DecodeUInt16()); + EXPECT_EQ(0x344556u, b1.DecodeUInt24()); + EXPECT_EQ(0x6778899au, b1.DecodeUInt32()); +} + +// Make sure that QuicHttpDecodeBuffer is not copying input, just pointing into +// provided input buffer. +TEST_F(QuicHttpDecodeBufferTest, HasNotCopiedInput) { + const char data[] = "ab"; + QuicHttpDecodeBuffer b1(data, 2); + + EXPECT_EQ(2u, b1.Remaining()); + EXPECT_EQ(0u, b1.Offset()); + EXPECT_FALSE(b1.Empty()); + EXPECT_EQ(data, b1.cursor()); // cursor points to input buffer + EXPECT_TRUE(b1.HasData()); + + b1.AdvanceCursor(1); + + EXPECT_EQ(1u, b1.Remaining()); + EXPECT_EQ(1u, b1.Offset()); + EXPECT_FALSE(b1.Empty()); + EXPECT_EQ(&data[1], b1.cursor()); + EXPECT_TRUE(b1.HasData()); + + b1.AdvanceCursor(1); + + EXPECT_EQ(0u, b1.Remaining()); + EXPECT_EQ(2u, b1.Offset()); + EXPECT_TRUE(b1.Empty()); + EXPECT_EQ(&data[2], b1.cursor()); + EXPECT_FALSE(b1.HasData()); + + QuicHttpDecodeBuffer b2(data, 0); + + EXPECT_EQ(0u, b2.Remaining()); + EXPECT_EQ(0u, b2.Offset()); + EXPECT_TRUE(b2.Empty()); + EXPECT_EQ(data, b2.cursor()); + EXPECT_FALSE(b2.HasData()); +} + +// QuicHttpDecodeBufferSubset can't go beyond the end of the base buffer. +TEST_F(QuicHttpDecodeBufferTest, DecodeBufferSubsetLimited) { + const char data[] = "abc"; + QuicHttpDecodeBuffer base(data, 3); + base.AdvanceCursor(1); + QuicHttpDecodeBufferSubset subset(&base, 100); + EXPECT_EQ(2u, subset.FullSize()); +} + +// QuicHttpDecodeBufferSubset advances the cursor of its base upon destruction. +TEST_F(QuicHttpDecodeBufferTest, DecodeBufferSubsetAdvancesCursor) { + const char data[] = "abc"; + const size_t size = sizeof(data) - 1; + EXPECT_EQ(3u, size); + QuicHttpDecodeBuffer base(data, size); + { + // First no change to the cursor. + QuicHttpDecodeBufferSubset subset(&base, size + 100); + EXPECT_EQ(size, subset.FullSize()); + EXPECT_EQ(base.FullSize(), subset.FullSize()); + EXPECT_EQ(0u, subset.Offset()); + } + EXPECT_EQ(0u, base.Offset()); + EXPECT_EQ(size, base.Remaining()); +} + +// Make sure that QuicHttpDecodeBuffer ctor complains about bad args. +#if GTEST_HAS_DEATH_TEST && !defined(NDEBUG) +TEST(QuicHttpDecodeBufferDeathTest, NonNullBufferRequired) { + EXPECT_DEBUG_DEATH({ QuicHttpDecodeBuffer b(nullptr, 3); }, "nullptr"); +} + +// Make sure that QuicHttpDecodeBuffer ctor complains about bad args. +TEST(QuicHttpDecodeBufferDeathTest, ModestBufferSizeRequired) { + EXPECT_DEBUG_DEATH( + { + const char data[] = "abc"; + size_t len = 0; + QuicHttpDecodeBuffer b(data, ~len); + }, + "Max.*Length"); +} + +// Make sure that QuicHttpDecodeBuffer detects advance beyond end, in debug +// mode. +TEST(QuicHttpDecodeBufferDeathTest, LimitedAdvance) { + { + // Advance right up to end is OK. + const char data[] = "abc"; + QuicHttpDecodeBuffer b(data, 3); + b.AdvanceCursor(3); // OK + EXPECT_TRUE(b.Empty()); + } + EXPECT_DEBUG_DEATH( + { + // Going beyond is not OK. + const char data[] = "abc"; + QuicHttpDecodeBuffer b(data, 3); + b.AdvanceCursor(4); + }, + "4 vs. 3"); +} + +// Make sure that QuicHttpDecodeBuffer detects decode beyond end, in debug mode. +TEST(QuicHttpDecodeBufferDeathTest, DecodeUInt8PastEnd) { + const char data[] = {0x12, 0x23}; + QuicHttpDecodeBuffer b(data, sizeof data); + EXPECT_EQ(2u, b.FullSize()); + EXPECT_EQ(0x1223u, b.DecodeUInt16()); + EXPECT_DEBUG_DEATH({ b.DecodeUInt8(); }, "1 vs. 0"); +} + +// Make sure that QuicHttpDecodeBuffer detects decode beyond end, in debug mode. +TEST(QuicHttpDecodeBufferDeathTest, DecodeUInt16OverEnd) { + const char data[] = {0x12, 0x23, 0x34}; + QuicHttpDecodeBuffer b(data, sizeof data); + EXPECT_EQ(3u, b.FullSize()); + EXPECT_EQ(0x1223u, b.DecodeUInt16()); + EXPECT_DEBUG_DEATH({ b.DecodeUInt16(); }, "2 vs. 1"); +} + +// Make sure that QuicHttpDecodeBuffer doesn't agree with having two subsets. +TEST(QuicHttpDecodeBufferSubsetDeathTest, TwoSubsets) { + const char data[] = "abc"; + QuicHttpDecodeBuffer base(data, 3); + QuicHttpDecodeBufferSubset subset1(&base, 1); + EXPECT_DEBUG_DEATH({ QuicHttpDecodeBufferSubset subset2(&base, 1); }, + "There is already a subset"); +} + +// Make sure that QuicHttpDecodeBufferSubset notices when the base's cursor has +// moved. +TEST(QuicHttpDecodeBufferSubsetDeathTest, BaseCursorAdvanced) { + const char data[] = "abc"; + QuicHttpDecodeBuffer base(data, 3); + base.AdvanceCursor(1); + EXPECT_DEBUG_DEATH( + { + QuicHttpDecodeBufferSubset subset1(&base, 2); + base.AdvanceCursor(1); + }, + "Access via subset only when present"); +} +#endif // GTEST_HAS_DEATH_TEST && !defined(NDEBUG) + +} // namespace +} // namespace test +} // namespace net
diff --git a/net/quic/http/decoder/quic_http_decode_status.cc b/net/quic/http/decoder/quic_http_decode_status.cc new file mode 100644 index 0000000..e027b4c --- /dev/null +++ b/net/quic/http/decoder/quic_http_decode_status.cc
@@ -0,0 +1,28 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/quic_http_decode_status.h" + +#include "base/logging.h" +#include "net/quic/platform/api/quic_bug_tracker.h" + +namespace net { + +std::ostream& operator<<(std::ostream& out, QuicHttpDecodeStatus v) { + switch (v) { + case QuicHttpDecodeStatus::kDecodeDone: + return out << "DecodeDone"; + case QuicHttpDecodeStatus::kDecodeInProgress: + return out << "DecodeInProgress"; + case QuicHttpDecodeStatus::kDecodeError: + return out << "DecodeError"; + } + // Since the value doesn't come over the wire, only a programming bug should + // result in reaching this point. + int unknown = static_cast<int>(v); + QUIC_BUG << "Unknown QuicHttpDecodeStatus " << unknown; + return out << "QuicHttpDecodeStatus(" << unknown << ")"; +} + +} // namespace net
diff --git a/net/quic/http/decoder/quic_http_decode_status.h b/net/quic/http/decoder/quic_http_decode_status.h new file mode 100644 index 0000000..81f743b --- /dev/null +++ b/net/quic/http/decoder/quic_http_decode_status.h
@@ -0,0 +1,34 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_HTTP_DECODER_QUIC_HTTP_DECODE_STATUS_H_ +#define NET_QUIC_HTTP_DECODER_QUIC_HTTP_DECODE_STATUS_H_ + +// Enum QuicHttpDecodeStatus is used to report the status of decoding of many +// types of HTTP/2 and HPQUIC_HTTP_ACK objects. + +#include <ostream> + +#include "net/quic/platform/api/quic_export.h" + +namespace net { + +enum class QuicHttpDecodeStatus { + // Decoding is done. + kDecodeDone, + + // Decoder needs more input to be able to make progress. + kDecodeInProgress, + + // Decoding failed (e.g. HPQUIC_HTTP_ACK variable length integer is too large, + // or + // an HTTP/2 frame has padding declared to be larger than the payload). + kDecodeError, +}; +QUIC_EXPORT_PRIVATE std::ostream& operator<<(std::ostream& out, + QuicHttpDecodeStatus v); + +} // namespace net + +#endif // NET_QUIC_HTTP_DECODER_QUIC_HTTP_DECODE_STATUS_H_
diff --git a/net/quic/http/decoder/quic_http_decode_structures.cc b/net/quic/http/decoder/quic_http_decode_structures.cc new file mode 100644 index 0000000..96f713f0 --- /dev/null +++ b/net/quic/http/decoder/quic_http_decode_structures.cc
@@ -0,0 +1,111 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/quic_http_decode_structures.h" + +#include <cstdint> + +#include "base/logging.h" +#include "net/quic/http/decoder/quic_http_decode_buffer.h" +#include "net/quic/http/quic_http_constants.h" + +namespace net { + +// QuicHttpFrameHeader decoding: + +void DoDecode(QuicHttpFrameHeader* out, QuicHttpDecodeBuffer* b) { + DCHECK_NE(nullptr, out); + DCHECK_NE(nullptr, b); + DCHECK_LE(QuicHttpFrameHeader::EncodedSize(), b->Remaining()); + out->payload_length = b->DecodeUInt24(); + out->type = static_cast<QuicHttpFrameType>(b->DecodeUInt8()); + out->flags = static_cast<QuicHttpFrameFlag>(b->DecodeUInt8()); + out->stream_id = b->DecodeUInt31(); +} + +// QuicHttpPriorityFields decoding: + +void DoDecode(QuicHttpPriorityFields* out, QuicHttpDecodeBuffer* b) { + DCHECK_NE(nullptr, out); + DCHECK_NE(nullptr, b); + DCHECK_LE(QuicHttpPriorityFields::EncodedSize(), b->Remaining()); + uint32_t stream_id_and_flag = b->DecodeUInt32(); + out->stream_dependency = stream_id_and_flag & QuicHttpStreamIdMask(); + if (out->stream_dependency == stream_id_and_flag) { + out->is_exclusive = false; + } else { + out->is_exclusive = true; + } + // Note that chars are automatically promoted to ints during arithmetic, + // so 255 + 1 doesn't end up as zero. + out->weight = b->DecodeUInt8() + 1; +} + +// QuicHttpRstStreamFields decoding: + +void DoDecode(QuicHttpRstStreamFields* out, QuicHttpDecodeBuffer* b) { + DCHECK_NE(nullptr, out); + DCHECK_NE(nullptr, b); + DCHECK_LE(QuicHttpRstStreamFields::EncodedSize(), b->Remaining()); + out->error_code = static_cast<QuicHttpErrorCode>(b->DecodeUInt32()); +} + +// QuicHttpSettingFields decoding: + +void DoDecode(QuicHttpSettingFields* out, QuicHttpDecodeBuffer* b) { + DCHECK_NE(nullptr, out); + DCHECK_NE(nullptr, b); + DCHECK_LE(QuicHttpSettingFields::EncodedSize(), b->Remaining()); + out->parameter = static_cast<QuicHttpSettingsParameter>(b->DecodeUInt16()); + out->value = b->DecodeUInt32(); +} + +// QuicHttpPushPromiseFields decoding: + +void DoDecode(QuicHttpPushPromiseFields* out, QuicHttpDecodeBuffer* b) { + DCHECK_NE(nullptr, out); + DCHECK_NE(nullptr, b); + DCHECK_LE(QuicHttpPushPromiseFields::EncodedSize(), b->Remaining()); + out->promised_stream_id = b->DecodeUInt31(); +} + +// QuicHttpPingFields decoding: + +void DoDecode(QuicHttpPingFields* out, QuicHttpDecodeBuffer* b) { + DCHECK_NE(nullptr, out); + DCHECK_NE(nullptr, b); + DCHECK_LE(QuicHttpPingFields::EncodedSize(), b->Remaining()); + memcpy(out->opaque_bytes, b->cursor(), QuicHttpPingFields::EncodedSize()); + b->AdvanceCursor(QuicHttpPingFields::EncodedSize()); +} + +// QuicHttpGoAwayFields decoding: + +void DoDecode(QuicHttpGoAwayFields* out, QuicHttpDecodeBuffer* b) { + DCHECK_NE(nullptr, out); + DCHECK_NE(nullptr, b); + DCHECK_LE(QuicHttpGoAwayFields::EncodedSize(), b->Remaining()); + out->last_stream_id = b->DecodeUInt31(); + out->error_code = static_cast<QuicHttpErrorCode>(b->DecodeUInt32()); +} + +// QuicHttpWindowUpdateFields decoding: + +void DoDecode(QuicHttpWindowUpdateFields* out, QuicHttpDecodeBuffer* b) { + DCHECK_NE(nullptr, out); + DCHECK_NE(nullptr, b); + DCHECK_LE(QuicHttpWindowUpdateFields::EncodedSize(), b->Remaining()); + out->window_size_increment = b->DecodeUInt31(); +} + +// QuicHttpAltSvcFields decoding: + +void DoDecode(QuicHttpAltSvcFields* out, QuicHttpDecodeBuffer* b) { + DCHECK_NE(nullptr, out); + DCHECK_NE(nullptr, b); + DCHECK_LE(QuicHttpAltSvcFields::EncodedSize(), b->Remaining()); + out->origin_length = b->DecodeUInt16(); +} + +} // namespace net
diff --git a/net/quic/http/decoder/quic_http_decode_structures.h b/net/quic/http/decoder/quic_http_decode_structures.h new file mode 100644 index 0000000..8be2c9b --- /dev/null +++ b/net/quic/http/decoder/quic_http_decode_structures.h
@@ -0,0 +1,42 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_HTTP_DECODER_QUIC_HTTP_DECODE_STRUCTURES_H_ +#define NET_QUIC_HTTP_DECODER_QUIC_HTTP_DECODE_STRUCTURES_H_ + +// Provides functions for decoding the fixed size structures in the HTTP/2 spec. + +#include "net/quic/http/decoder/quic_http_decode_buffer.h" +#include "net/quic/http/quic_http_structures.h" +#include "net/quic/platform/api/quic_export.h" + +namespace net { + +// DoDecode(STRUCTURE* out, QuicHttpDecodeBuffer* b) decodes the structure from +// start to end, advancing the cursor by STRUCTURE::EncodedSize(). The decode +// buffer must be large enough (i.e. b->Remaining() >= +// STRUCTURE::EncodedSize()). + +QUIC_EXPORT_PRIVATE void DoDecode(QuicHttpFrameHeader* out, + QuicHttpDecodeBuffer* b); +QUIC_EXPORT_PRIVATE void DoDecode(QuicHttpPriorityFields* out, + QuicHttpDecodeBuffer* b); +QUIC_EXPORT_PRIVATE void DoDecode(QuicHttpRstStreamFields* out, + QuicHttpDecodeBuffer* b); +QUIC_EXPORT_PRIVATE void DoDecode(QuicHttpSettingFields* out, + QuicHttpDecodeBuffer* b); +QUIC_EXPORT_PRIVATE void DoDecode(QuicHttpPushPromiseFields* out, + QuicHttpDecodeBuffer* b); +QUIC_EXPORT_PRIVATE void DoDecode(QuicHttpPingFields* out, + QuicHttpDecodeBuffer* b); +QUIC_EXPORT_PRIVATE void DoDecode(QuicHttpGoAwayFields* out, + QuicHttpDecodeBuffer* b); +QUIC_EXPORT_PRIVATE void DoDecode(QuicHttpWindowUpdateFields* out, + QuicHttpDecodeBuffer* b); +QUIC_EXPORT_PRIVATE void DoDecode(QuicHttpAltSvcFields* out, + QuicHttpDecodeBuffer* b); + +} // namespace net + +#endif // NET_QUIC_HTTP_DECODER_QUIC_HTTP_DECODE_STRUCTURES_H_
diff --git a/net/quic/http/decoder/quic_http_frame_decoder.cc b/net/quic/http/decoder/quic_http_frame_decoder.cc new file mode 100644 index 0000000..43480c6 --- /dev/null +++ b/net/quic/http/decoder/quic_http_frame_decoder.cc
@@ -0,0 +1,455 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/quic_http_frame_decoder.h" + +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/platform/api/quic_bug_tracker.h" +#include "net/quic/platform/api/quic_logging.h" + +namespace net { + +std::ostream& operator<<(std::ostream& out, QuicHttpFrameDecoder::State v) { + switch (v) { + case QuicHttpFrameDecoder::State::kStartDecodingHeader: + return out << "kStartDecodingHeader"; + case QuicHttpFrameDecoder::State::kResumeDecodingHeader: + return out << "kResumeDecodingHeader"; + case QuicHttpFrameDecoder::State::kResumeDecodingPayload: + return out << "kResumeDecodingPayload"; + case QuicHttpFrameDecoder::State::kDiscardPayload: + return out << "kDiscardPayload"; + } + // Since the value doesn't come over the wire, only a programming bug should + // result in reaching this point. + int unknown = static_cast<int>(v); + QUIC_BUG << "QuicHttpFrameDecoder::State " << unknown; + return out << "QuicHttpFrameDecoder::State(" << unknown << ")"; +} + +QuicHttpFrameDecoder::QuicHttpFrameDecoder( + QuicHttpFrameDecoderListener* listener) + : state_(State::kStartDecodingHeader), + maximum_payload_size_(QuicHttpSettingsInfo::DefaultMaxFrameSize()) { + set_listener(listener); +} + +void QuicHttpFrameDecoder::set_listener( + QuicHttpFrameDecoderListener* listener) { + if (listener == nullptr) { + listener = &no_op_listener_; + } + frame_decoder_state_.set_listener(listener); +} + +QuicHttpFrameDecoderListener* QuicHttpFrameDecoder::listener() const { + return frame_decoder_state_.listener(); +} + +QuicHttpDecodeStatus QuicHttpFrameDecoder::DecodeFrame( + QuicHttpDecodeBuffer* db) { + DVLOG(2) << "QuicHttpFrameDecoder::DecodeFrame state=" << state_; + switch (state_) { + case State::kStartDecodingHeader: + if (frame_decoder_state_.StartDecodingFrameHeader(db)) { + return StartDecodingPayload(db); + } + state_ = State::kResumeDecodingHeader; + return QuicHttpDecodeStatus::kDecodeInProgress; + + case State::kResumeDecodingHeader: + if (frame_decoder_state_.ResumeDecodingFrameHeader(db)) { + return StartDecodingPayload(db); + } + return QuicHttpDecodeStatus::kDecodeInProgress; + + case State::kResumeDecodingPayload: + return ResumeDecodingPayload(db); + + case State::kDiscardPayload: + return DiscardPayload(db); + } + + QUIC_NOTREACHED(); + return QuicHttpDecodeStatus::kDecodeError; +} + +size_t QuicHttpFrameDecoder::remaining_payload() const { + return frame_decoder_state_.remaining_payload(); +} + +uint32_t QuicHttpFrameDecoder::remaining_padding() const { + return frame_decoder_state_.remaining_padding(); +} + +QuicHttpDecodeStatus QuicHttpFrameDecoder::StartDecodingPayload( + QuicHttpDecodeBuffer* db) { + const QuicHttpFrameHeader& header = frame_header(); + + // TODO(jamessynge): Remove OnFrameHeader once done with supporting + // SpdyFramer's exact states. + if (!listener()->OnFrameHeader(header)) { + DVLOG(2) << "OnFrameHeader rejected the frame, will discard; header: " + << header; + state_ = State::kDiscardPayload; + frame_decoder_state_.InitializeRemainders(); + return QuicHttpDecodeStatus::kDecodeError; + } + + if (header.payload_length > maximum_payload_size_) { + DVLOG(2) << "Payload length is greater than allowed: " + << header.payload_length << " > " << maximum_payload_size_ + << "\n header: " << header; + state_ = State::kDiscardPayload; + frame_decoder_state_.InitializeRemainders(); + listener()->OnFrameSizeError(header); + return QuicHttpDecodeStatus::kDecodeError; + } + + // The decode buffer can extend across many frames. Make sure that the + // buffer we pass to the start method that is specific to the frame type + // does not exend beyond this frame. + QuicHttpDecodeBufferSubset subset(db, header.payload_length); + QuicHttpDecodeStatus status; + switch (header.type) { + case QuicHttpFrameType::DATA: + status = StartDecodingDataPayload(&subset); + break; + + case QuicHttpFrameType::HEADERS: + status = StartDecodingHeadersPayload(&subset); + break; + + case QuicHttpFrameType::QUIC_HTTP_PRIORITY: + status = StartDecodingPriorityPayload(&subset); + break; + + case QuicHttpFrameType::RST_STREAM: + status = StartDecodingRstStreamPayload(&subset); + break; + + case QuicHttpFrameType::SETTINGS: + status = StartDecodingSettingsPayload(&subset); + break; + + case QuicHttpFrameType::PUSH_PROMISE: + status = StartDecodingPushPromisePayload(&subset); + break; + + case QuicHttpFrameType::PING: + status = StartDecodingPingPayload(&subset); + break; + + case QuicHttpFrameType::GOAWAY: + status = StartDecodingGoAwayPayload(&subset); + break; + + case QuicHttpFrameType::WINDOW_UPDATE: + status = StartDecodingWindowUpdatePayload(&subset); + break; + + case QuicHttpFrameType::CONTINUATION: + status = StartDecodingContinuationPayload(&subset); + break; + + case QuicHttpFrameType::ALTSVC: + status = StartDecodingAltSvcPayload(&subset); + break; + + default: + status = StartDecodingUnknownPayload(&subset); + break; + } + + if (status == QuicHttpDecodeStatus::kDecodeDone) { + state_ = State::kStartDecodingHeader; + return status; + } else if (status == QuicHttpDecodeStatus::kDecodeInProgress) { + state_ = State::kResumeDecodingPayload; + return status; + } else { + state_ = State::kDiscardPayload; + return status; + } +} + +QuicHttpDecodeStatus QuicHttpFrameDecoder::ResumeDecodingPayload( + QuicHttpDecodeBuffer* db) { + // The decode buffer can extend across many frames. Make sure that the + // buffer we pass to the start method that is specific to the frame type + // does not exend beyond this frame. + size_t remaining = frame_decoder_state_.remaining_total_payload(); + DCHECK_LE(remaining, frame_header().payload_length); + QuicHttpDecodeBufferSubset subset(db, remaining); + QuicHttpDecodeStatus status; + switch (frame_header().type) { + case QuicHttpFrameType::DATA: + status = ResumeDecodingDataPayload(&subset); + break; + + case QuicHttpFrameType::HEADERS: + status = ResumeDecodingHeadersPayload(&subset); + break; + + case QuicHttpFrameType::QUIC_HTTP_PRIORITY: + status = ResumeDecodingPriorityPayload(&subset); + break; + + case QuicHttpFrameType::RST_STREAM: + status = ResumeDecodingRstStreamPayload(&subset); + break; + + case QuicHttpFrameType::SETTINGS: + status = ResumeDecodingSettingsPayload(&subset); + break; + + case QuicHttpFrameType::PUSH_PROMISE: + status = ResumeDecodingPushPromisePayload(&subset); + break; + + case QuicHttpFrameType::PING: + status = ResumeDecodingPingPayload(&subset); + break; + + case QuicHttpFrameType::GOAWAY: + status = ResumeDecodingGoAwayPayload(&subset); + break; + + case QuicHttpFrameType::WINDOW_UPDATE: + status = ResumeDecodingWindowUpdatePayload(&subset); + break; + + case QuicHttpFrameType::CONTINUATION: + status = ResumeDecodingContinuationPayload(&subset); + break; + + case QuicHttpFrameType::ALTSVC: + status = ResumeDecodingAltSvcPayload(&subset); + break; + + default: + status = ResumeDecodingUnknownPayload(&subset); + break; + } + + if (status == QuicHttpDecodeStatus::kDecodeDone) { + state_ = State::kStartDecodingHeader; + return status; + } else if (status == QuicHttpDecodeStatus::kDecodeInProgress) { + return status; + } else { + state_ = State::kDiscardPayload; + return status; + } +} + +// Clear any of the flags in the frame header that aren't set in valid_flags. +void QuicHttpFrameDecoder::RetainFlags(uint8_t valid_flags) { + frame_decoder_state_.RetainFlags(valid_flags); +} + +// Clear all of the flags in the frame header; for use with frame types that +// don't define any flags, such as WINDOW_UPDATE. +void QuicHttpFrameDecoder::ClearFlags() { + frame_decoder_state_.ClearFlags(); +} + +QuicHttpDecodeStatus QuicHttpFrameDecoder::StartDecodingAltSvcPayload( + QuicHttpDecodeBuffer* db) { + ClearFlags(); + return altsvc_payload_decoder_.StartDecodingPayload(&frame_decoder_state_, + db); +} +QuicHttpDecodeStatus QuicHttpFrameDecoder::ResumeDecodingAltSvcPayload( + QuicHttpDecodeBuffer* db) { + // The frame is not paddable. + DCHECK_EQ(frame_decoder_state_.remaining_total_payload(), + frame_decoder_state_.remaining_payload()); + return altsvc_payload_decoder_.ResumeDecodingPayload(&frame_decoder_state_, + db); +} + +QuicHttpDecodeStatus QuicHttpFrameDecoder::StartDecodingContinuationPayload( + QuicHttpDecodeBuffer* db) { + RetainFlags(QuicHttpFrameFlag::QUIC_HTTP_END_HEADERS); + return continuation_payload_decoder_.StartDecodingPayload( + &frame_decoder_state_, db); +} +QuicHttpDecodeStatus QuicHttpFrameDecoder::ResumeDecodingContinuationPayload( + QuicHttpDecodeBuffer* db) { + // The frame is not paddable. + DCHECK_EQ(frame_decoder_state_.remaining_total_payload(), + frame_decoder_state_.remaining_payload()); + return continuation_payload_decoder_.ResumeDecodingPayload( + &frame_decoder_state_, db); +} + +QuicHttpDecodeStatus QuicHttpFrameDecoder::StartDecodingDataPayload( + QuicHttpDecodeBuffer* db) { + RetainFlags(QuicHttpFrameFlag::QUIC_HTTP_END_STREAM | + QuicHttpFrameFlag::QUIC_HTTP_PADDED); + return data_payload_decoder_.StartDecodingPayload(&frame_decoder_state_, db); +} +QuicHttpDecodeStatus QuicHttpFrameDecoder::ResumeDecodingDataPayload( + QuicHttpDecodeBuffer* db) { + return data_payload_decoder_.ResumeDecodingPayload(&frame_decoder_state_, db); +} + +QuicHttpDecodeStatus QuicHttpFrameDecoder::StartDecodingGoAwayPayload( + QuicHttpDecodeBuffer* db) { + ClearFlags(); + return goaway_payload_decoder_.StartDecodingPayload(&frame_decoder_state_, + db); +} +QuicHttpDecodeStatus QuicHttpFrameDecoder::ResumeDecodingGoAwayPayload( + QuicHttpDecodeBuffer* db) { + // The frame is not paddable. + DCHECK_EQ(frame_decoder_state_.remaining_total_payload(), + frame_decoder_state_.remaining_payload()); + return goaway_payload_decoder_.ResumeDecodingPayload(&frame_decoder_state_, + db); +} + +QuicHttpDecodeStatus QuicHttpFrameDecoder::StartDecodingHeadersPayload( + QuicHttpDecodeBuffer* db) { + RetainFlags(QuicHttpFrameFlag::QUIC_HTTP_END_STREAM | + QuicHttpFrameFlag::QUIC_HTTP_END_HEADERS | + QuicHttpFrameFlag::QUIC_HTTP_PADDED | + QuicHttpFrameFlag::QUIC_HTTP_PRIORITY); + return headers_payload_decoder_.StartDecodingPayload(&frame_decoder_state_, + db); +} +QuicHttpDecodeStatus QuicHttpFrameDecoder::ResumeDecodingHeadersPayload( + QuicHttpDecodeBuffer* db) { + DCHECK_LE(frame_decoder_state_.remaining_payload_and_padding(), + frame_header().payload_length); + return headers_payload_decoder_.ResumeDecodingPayload(&frame_decoder_state_, + db); +} + +QuicHttpDecodeStatus QuicHttpFrameDecoder::StartDecodingPingPayload( + QuicHttpDecodeBuffer* db) { + RetainFlags(QuicHttpFrameFlag::QUIC_HTTP_ACK); + return ping_payload_decoder_.StartDecodingPayload(&frame_decoder_state_, db); +} +QuicHttpDecodeStatus QuicHttpFrameDecoder::ResumeDecodingPingPayload( + QuicHttpDecodeBuffer* db) { + // The frame is not paddable. + DCHECK_EQ(frame_decoder_state_.remaining_total_payload(), + frame_decoder_state_.remaining_payload()); + return ping_payload_decoder_.ResumeDecodingPayload(&frame_decoder_state_, db); +} + +QuicHttpDecodeStatus QuicHttpFrameDecoder::StartDecodingPriorityPayload( + QuicHttpDecodeBuffer* db) { + ClearFlags(); + return priority_payload_decoder_.StartDecodingPayload(&frame_decoder_state_, + db); +} +QuicHttpDecodeStatus QuicHttpFrameDecoder::ResumeDecodingPriorityPayload( + QuicHttpDecodeBuffer* db) { + // The frame is not paddable. + DCHECK_EQ(frame_decoder_state_.remaining_total_payload(), + frame_decoder_state_.remaining_payload()); + return priority_payload_decoder_.ResumeDecodingPayload(&frame_decoder_state_, + db); +} + +QuicHttpDecodeStatus QuicHttpFrameDecoder::StartDecodingPushPromisePayload( + QuicHttpDecodeBuffer* db) { + RetainFlags(QuicHttpFrameFlag::QUIC_HTTP_END_HEADERS | + QuicHttpFrameFlag::QUIC_HTTP_PADDED); + return push_promise_payload_decoder_.StartDecodingPayload( + &frame_decoder_state_, db); +} +QuicHttpDecodeStatus QuicHttpFrameDecoder::ResumeDecodingPushPromisePayload( + QuicHttpDecodeBuffer* db) { + DCHECK_LE(frame_decoder_state_.remaining_payload_and_padding(), + frame_header().payload_length); + return push_promise_payload_decoder_.ResumeDecodingPayload( + &frame_decoder_state_, db); +} + +QuicHttpDecodeStatus QuicHttpFrameDecoder::StartDecodingRstStreamPayload( + QuicHttpDecodeBuffer* db) { + ClearFlags(); + return rst_stream_payload_decoder_.StartDecodingPayload(&frame_decoder_state_, + db); +} +QuicHttpDecodeStatus QuicHttpFrameDecoder::ResumeDecodingRstStreamPayload( + QuicHttpDecodeBuffer* db) { + // The frame is not paddable. + DCHECK_EQ(frame_decoder_state_.remaining_total_payload(), + frame_decoder_state_.remaining_payload()); + return rst_stream_payload_decoder_.ResumeDecodingPayload( + &frame_decoder_state_, db); +} + +QuicHttpDecodeStatus QuicHttpFrameDecoder::StartDecodingSettingsPayload( + QuicHttpDecodeBuffer* db) { + RetainFlags(QuicHttpFrameFlag::QUIC_HTTP_ACK); + return settings_payload_decoder_.StartDecodingPayload(&frame_decoder_state_, + db); +} +QuicHttpDecodeStatus QuicHttpFrameDecoder::ResumeDecodingSettingsPayload( + QuicHttpDecodeBuffer* db) { + // The frame is not paddable. + DCHECK_EQ(frame_decoder_state_.remaining_total_payload(), + frame_decoder_state_.remaining_payload()); + return settings_payload_decoder_.ResumeDecodingPayload(&frame_decoder_state_, + db); +} + +QuicHttpDecodeStatus QuicHttpFrameDecoder::StartDecodingUnknownPayload( + QuicHttpDecodeBuffer* db) { + // We don't known what type of frame this is, so we don't know which flags + // are valid, so we don't touch them. + return unknown_payload_decoder_.StartDecodingPayload(&frame_decoder_state_, + db); +} +QuicHttpDecodeStatus QuicHttpFrameDecoder::ResumeDecodingUnknownPayload( + QuicHttpDecodeBuffer* db) { + // We don't known what type of frame this is, so we treat it as not paddable. + DCHECK_EQ(frame_decoder_state_.remaining_total_payload(), + frame_decoder_state_.remaining_payload()); + return unknown_payload_decoder_.ResumeDecodingPayload(&frame_decoder_state_, + db); +} + +QuicHttpDecodeStatus QuicHttpFrameDecoder::StartDecodingWindowUpdatePayload( + QuicHttpDecodeBuffer* db) { + ClearFlags(); + return window_update_payload_decoder_.StartDecodingPayload( + &frame_decoder_state_, db); +} +QuicHttpDecodeStatus QuicHttpFrameDecoder::ResumeDecodingWindowUpdatePayload( + QuicHttpDecodeBuffer* db) { + // The frame is not paddable. + DCHECK_EQ(frame_decoder_state_.remaining_total_payload(), + frame_decoder_state_.remaining_payload()); + return window_update_payload_decoder_.ResumeDecodingPayload( + &frame_decoder_state_, db); +} + +QuicHttpDecodeStatus QuicHttpFrameDecoder::DiscardPayload( + QuicHttpDecodeBuffer* db) { + DVLOG(2) << "remaining_payload=" << frame_decoder_state_.remaining_payload_ + << "; remaining_padding=" << frame_decoder_state_.remaining_padding_; + frame_decoder_state_.remaining_payload_ += + frame_decoder_state_.remaining_padding_; + frame_decoder_state_.remaining_padding_ = 0; + const size_t avail = frame_decoder_state_.AvailablePayload(db); + DVLOG(2) << "avail=" << avail; + if (avail > 0) { + frame_decoder_state_.ConsumePayload(avail); + db->AdvanceCursor(avail); + } + if (frame_decoder_state_.remaining_payload_ == 0) { + state_ = State::kStartDecodingHeader; + return QuicHttpDecodeStatus::kDecodeDone; + } + return QuicHttpDecodeStatus::kDecodeInProgress; +} + +} // namespace net
diff --git a/net/quic/http/decoder/quic_http_frame_decoder.h b/net/quic/http/decoder/quic_http_frame_decoder.h new file mode 100644 index 0000000..3d76538 --- /dev/null +++ b/net/quic/http/decoder/quic_http_frame_decoder.h
@@ -0,0 +1,211 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_HTTP_DECODER_QUIC_HTTP_FRAME_DECODER_H_ +#define NET_QUIC_HTTP_DECODER_QUIC_HTTP_FRAME_DECODER_H_ + +// QuicHttpFrameDecoder decodes the available input until it reaches the end of +// the input or it reaches the end of the first frame in the input. +// Note that QuicHttpFrameDecoder does only minimal validation; for example, +// stream ids are not checked, nor is the sequence of frames such as +// CONTINUATION frame placement. +// +// QuicHttpFrameDecoder enters state kError once it has called the listener's +// OnFrameSizeError or OnPaddingTooLong methods, and at this time has no +// provision for leaving that state. While the HTTP/2 spec (RFC7540) allows +// for some such errors to be considered as just stream errors in some cases, +// this implementation treats them all as connection errors. + +#include <stddef.h> + +#include <cstdint> + +#include "base/logging.h" +#include "base/macros.h" +#include "net/quic/http/decoder/payload_decoders/quic_http_altsvc_payload_decoder.h" +#include "net/quic/http/decoder/payload_decoders/quic_http_continuation_payload_decoder.h" +#include "net/quic/http/decoder/payload_decoders/quic_http_data_payload_decoder.h" +#include "net/quic/http/decoder/payload_decoders/quic_http_goaway_payload_decoder.h" +#include "net/quic/http/decoder/payload_decoders/quic_http_headers_payload_decoder.h" +#include "net/quic/http/decoder/payload_decoders/quic_http_ping_payload_decoder.h" +#include "net/quic/http/decoder/payload_decoders/quic_http_priority_payload_decoder.h" +#include "net/quic/http/decoder/payload_decoders/quic_http_push_promise_payload_decoder.h" +#include "net/quic/http/decoder/payload_decoders/quic_http_rst_stream_payload_decoder.h" +#include "net/quic/http/decoder/payload_decoders/quic_http_settings_payload_decoder.h" +#include "net/quic/http/decoder/payload_decoders/quic_http_unknown_payload_decoder.h" +#include "net/quic/http/decoder/payload_decoders/quic_http_window_update_payload_decoder.h" +#include "net/quic/http/decoder/quic_http_decode_buffer.h" +#include "net/quic/http/decoder/quic_http_decode_status.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_listener.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_state.h" +#include "net/quic/http/quic_http_structures.h" +#include "net/quic/platform/api/quic_export.h" + +namespace net { +namespace test { +class QuicHttpFrameDecoderPeer; +} // namespace test + +class QUIC_EXPORT_PRIVATE QuicHttpFrameDecoder { + public: + explicit QuicHttpFrameDecoder(QuicHttpFrameDecoderListener* listener); + QuicHttpFrameDecoder() : QuicHttpFrameDecoder(nullptr) {} + + // The decoder will call the listener's methods as it decodes a frame. + void set_listener(QuicHttpFrameDecoderListener* listener); + QuicHttpFrameDecoderListener* listener() const; + + // The decoder will reject frame's whose payload + // length field exceeds the maximum payload size. + void set_maximum_payload_size(size_t v) { maximum_payload_size_ = v; } + size_t maximum_payload_size() const { return maximum_payload_size_; } + + // Decodes the input up to the next frame boundary (i.e. at most one frame). + // + // Returns kDecodeDone if it decodes the final byte of a frame, OR if there + // is no input and it is awaiting the start of a new frame (e.g. if this + // is the first call to DecodeFrame, or if the previous call returned + // kDecodeDone). + // + // Returns kDecodeInProgress if it decodes all of the decode buffer, but has + // not reached the end of the frame. + // + // Returns kDecodeError if the frame's padding or length wasn't valid (i.e. if + // the decoder called either the listener's OnPaddingTooLong or + // OnFrameSizeError method). + QuicHttpDecodeStatus DecodeFrame(QuicHttpDecodeBuffer* db); + + ////////////////////////////////////////////////////////////////////////////// + // Methods that support QuicHttpFrameDecoderAdapter. + + // Is the remainder of the frame's payload being discarded? + bool IsDiscardingPayload() const { return state_ == State::kDiscardPayload; } + + // Returns the number of bytes of the frame's payload that remain to be + // decoded, excluding any trailing padding. This method must only be called + // after the frame header has been decoded AND DecodeFrame has returned + // kDecodeInProgress. + size_t remaining_payload() const; + + // Returns the number of bytes of trailing padding after the payload that + // remain to be decoded. This method must only be called if the frame type + // allows padding, and after the frame header has been decoded AND + // DecodeFrame has returned. Will return 0 if the Pad Length field has not + // yet been decoded. + uint32_t remaining_padding() const; + + private: + enum class State { + // Ready to start decoding a new frame's header. + kStartDecodingHeader, + // Was in state kStartDecodingHeader, but unable to read the entire frame + // header, so needs more input to complete decoding the header. + kResumeDecodingHeader, + + // Have decoded the frame header, and started decoding the available bytes + // of the frame's payload, but need more bytes to finish the job. + kResumeDecodingPayload, + + // Decoding of the most recently started frame resulted in an error: + // OnPaddingTooLong or OnFrameSizeError was called to indicate that the + // decoder detected a problem, or OnFrameHeader returned false, indicating + // that the listener detected a problem. Regardless of which, the decoder + // will stay in state kDiscardPayload until it has been passed the rest + // of the bytes of the frame's payload that it hasn't yet seen, after + // which it will be ready to decode another frame. + kDiscardPayload, + }; + + friend class test::QuicHttpFrameDecoderPeer; + friend std::ostream& operator<<(std::ostream& out, State v); + + QuicHttpDecodeStatus StartDecodingPayload(QuicHttpDecodeBuffer* db); + QuicHttpDecodeStatus ResumeDecodingPayload(QuicHttpDecodeBuffer* db); + QuicHttpDecodeStatus DiscardPayload(QuicHttpDecodeBuffer* db); + + const QuicHttpFrameHeader& frame_header() const { + return frame_decoder_state_.frame_header(); + } + + // Clear any of the flags in the frame header that aren't set in valid_flags. + void RetainFlags(uint8_t valid_flags); + + // Clear all of the flags in the frame header; for use with frame types that + // don't define any flags, such as WINDOW_UPDATE. + void ClearFlags(); + + // These methods call the StartDecodingPayload() method of the frame type's + // payload decoder, after first clearing invalid flags in the header. The + // caller must ensure that the decode buffer does not extend beyond the + // end of the payload (handled by QuicHttpFrameDecoder::StartDecodingPayload). + QuicHttpDecodeStatus StartDecodingAltSvcPayload(QuicHttpDecodeBuffer* db); + QuicHttpDecodeStatus StartDecodingContinuationPayload( + QuicHttpDecodeBuffer* db); + QuicHttpDecodeStatus StartDecodingDataPayload(QuicHttpDecodeBuffer* db); + QuicHttpDecodeStatus StartDecodingGoAwayPayload(QuicHttpDecodeBuffer* db); + QuicHttpDecodeStatus StartDecodingHeadersPayload(QuicHttpDecodeBuffer* db); + QuicHttpDecodeStatus StartDecodingPingPayload(QuicHttpDecodeBuffer* db); + QuicHttpDecodeStatus StartDecodingPriorityPayload(QuicHttpDecodeBuffer* db); + QuicHttpDecodeStatus StartDecodingPushPromisePayload( + QuicHttpDecodeBuffer* db); + QuicHttpDecodeStatus StartDecodingRstStreamPayload(QuicHttpDecodeBuffer* db); + QuicHttpDecodeStatus StartDecodingSettingsPayload(QuicHttpDecodeBuffer* db); + QuicHttpDecodeStatus StartDecodingUnknownPayload(QuicHttpDecodeBuffer* db); + QuicHttpDecodeStatus StartDecodingWindowUpdatePayload( + QuicHttpDecodeBuffer* db); + + // These methods call the ResumeDecodingPayload() method of the frame type's + // payload decoder; they are called only if the preceding call to the + // corresponding Start method (above) returned kDecodeInProgress, as did any + // subsequent calls to the resume method. + // Unlike the Start methods, the decode buffer may extend beyond the + // end of the payload, so the method will create a QuicHttpDecodeBufferSubset + // before calling the ResumeDecodingPayload method of the frame type's + // payload decoder. + QuicHttpDecodeStatus ResumeDecodingAltSvcPayload(QuicHttpDecodeBuffer* db); + QuicHttpDecodeStatus ResumeDecodingContinuationPayload( + QuicHttpDecodeBuffer* db); + QuicHttpDecodeStatus ResumeDecodingDataPayload(QuicHttpDecodeBuffer* db); + QuicHttpDecodeStatus ResumeDecodingGoAwayPayload(QuicHttpDecodeBuffer* db); + QuicHttpDecodeStatus ResumeDecodingHeadersPayload(QuicHttpDecodeBuffer* db); + QuicHttpDecodeStatus ResumeDecodingPingPayload(QuicHttpDecodeBuffer* db); + QuicHttpDecodeStatus ResumeDecodingPriorityPayload(QuicHttpDecodeBuffer* db); + QuicHttpDecodeStatus ResumeDecodingPushPromisePayload( + QuicHttpDecodeBuffer* db); + QuicHttpDecodeStatus ResumeDecodingRstStreamPayload(QuicHttpDecodeBuffer* db); + QuicHttpDecodeStatus ResumeDecodingSettingsPayload(QuicHttpDecodeBuffer* db); + QuicHttpDecodeStatus ResumeDecodingUnknownPayload(QuicHttpDecodeBuffer* db); + QuicHttpDecodeStatus ResumeDecodingWindowUpdatePayload( + QuicHttpDecodeBuffer* db); + + QuicHttpFrameDecoderState frame_decoder_state_; + + // We only need one payload decoder at a time, so they share the same storage. + union { + QuicHttpAltSvcQuicHttpPayloadDecoder altsvc_payload_decoder_; + QuicHttpContinuationQuicHttpPayloadDecoder continuation_payload_decoder_; + QuicHttpDataQuicHttpPayloadDecoder data_payload_decoder_; + QuicHttpGoAwayQuicHttpPayloadDecoder goaway_payload_decoder_; + QuicHttpHeadersQuicHttpPayloadDecoder headers_payload_decoder_; + QuicHttpPingQuicHttpPayloadDecoder ping_payload_decoder_; + QuicHttpPriorityQuicHttpPayloadDecoder priority_payload_decoder_; + QuicHttpPushPromiseQuicHttpPayloadDecoder push_promise_payload_decoder_; + QuicHttpRstStreamQuicHttpPayloadDecoder rst_stream_payload_decoder_; + QuicHttpQuicHttpSettingsQuicHttpPayloadDecoder settings_payload_decoder_; + QuicHttpUnknownQuicHttpPayloadDecoder unknown_payload_decoder_; + QuicHttpWindowUpdateQuicHttpPayloadDecoder window_update_payload_decoder_; + }; + + State state_; + size_t maximum_payload_size_; + + // Listener used whenever caller passes nullptr to set_listener. + QuicHttpFrameDecoderNoOpListener no_op_listener_; + + DISALLOW_COPY_AND_ASSIGN(QuicHttpFrameDecoder); +}; + +} // namespace net + +#endif // NET_QUIC_HTTP_DECODER_QUIC_HTTP_FRAME_DECODER_H_
diff --git a/net/quic/http/decoder/quic_http_frame_decoder_adapter.cc b/net/quic/http/decoder/quic_http_frame_decoder_adapter.cc new file mode 100644 index 0000000..4dae7e3 --- /dev/null +++ b/net/quic/http/decoder/quic_http_frame_decoder_adapter.cc
@@ -0,0 +1,982 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/quic_http_frame_decoder_adapter.h" + +// Logging policy: If an error in the input is detected, VLOG(n) is used so that +// the option exists to debug the situation. Otherwise, this code mostly uses +// DVLOG so that the logging does not slow down production code when things are +// working OK. + +#include <stddef.h> + +#include <cstdint> +#include <cstring> +#include <utility> + +#include "base/logging.h" +#include "net/quic/http/decoder/quic_http_decode_buffer.h" +#include "net/quic/http/decoder/quic_http_decode_status.h" +#include "net/quic/http/decoder/quic_http_frame_decoder.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_listener.h" +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/quic_http_structures.h" +#include "net/quic/platform/api/quic_ptr_util.h" +#include "net/quic/platform/api/quic_string_utils.h" +#include "net/spdy/core/hpack/hpack_decoder_adapter.h" +#include "net/spdy/core/hpack/hpack_header_table.h" +#include "net/spdy/core/http2_frame_decoder_adapter.h" +#include "net/spdy/core/spdy_alt_svc_wire_format.h" +#include "net/spdy/core/spdy_bug_tracker.h" +#include "net/spdy/core/spdy_header_block.h" +#include "net/spdy/core/spdy_headers_handler_interface.h" +#include "net/spdy/core/spdy_protocol.h" + +#if 0 +using ::ExtensionVisitorInterface; +using ::HpackDecoderAdapter; +using ::HpackHeaderTable; +using ::ParseErrorCode; +using ::ParseFrameType; +using ::SpdyAltSvcWireFormat; +using ::SpdyErrorCode; +using ::SpdyFrameType; +using ::SpdyFramerDebugVisitorInterface; +using ::SpdyFramerVisitorInterface; +using ::SpdyHeadersHandlerInterface; +using ::SpdySettingsIds; +#endif +using base::nullopt; + +namespace net { + +using SpdyFramerError = Http2DecoderAdapter::SpdyFramerError; + +namespace { + +const bool kHasPriorityFields = true; +const bool kNotHasPriorityFields = false; + +bool IsPaddable(QuicHttpFrameType type) { + return type == QuicHttpFrameType::DATA || + type == QuicHttpFrameType::HEADERS || + type == QuicHttpFrameType::PUSH_PROMISE; +} + +SpdyFrameType ToSpdyFrameType(QuicHttpFrameType type) { + return ParseFrameType(static_cast<uint8_t>(type)); +} + +uint64_t ToSpdyPingId(const QuicHttpPingFields& ping) { + uint64_t v; + std::memcpy(&v, ping.opaque_bytes, QuicHttpPingFields::EncodedSize()); + return base::NetToHost64(v); +} + +// Overwrites the fields of the header with invalid values, for the purpose +// of identifying reading of unset fields. Only takes effect for debug builds. +// In Address Sanatizer builds, it also marks the fields as un-readable. +void CorruptFrameHeader(QuicHttpFrameHeader* header) { +#ifndef NDEBUG + // Beyond a valid payload length, which is 2^24 - 1. + header->payload_length = 0x1010dead; + // An unsupported frame type. + header->type = QuicHttpFrameType(0x80); + DCHECK(!IsSupportedQuicHttpFrameType(header->type)); + // Frame flag bits that aren't used by any supported frame type. + header->flags = QuicHttpFrameFlag(0xd2); + // A stream id with the reserved high-bit (R in the RFC) set. + // 2129510127 when the high-bit is cleared. + header->stream_id = 0xfeedbeef; +#endif +} + +} // namespace + +const char* QuicHttpDecoderAdapter::StateToString(int state) { + switch (state) { + case SPDY_ERROR: + return "ERROR"; + case SPDY_FRAME_COMPLETE: + return "FRAME_COMPLETE"; + case SPDY_READY_FOR_FRAME: + return "READY_FOR_FRAME"; + case SPDY_READING_COMMON_HEADER: + return "READING_COMMON_HEADER"; + case SPDY_CONTROL_FRAME_PAYLOAD: + return "CONTROL_FRAME_PAYLOAD"; + case SPDY_READ_DATA_FRAME_PADDING_LENGTH: + return "SPDY_READ_DATA_FRAME_PADDING_LENGTH"; + case SPDY_CONSUME_PADDING: + return "SPDY_CONSUME_PADDING"; + case SPDY_IGNORE_REMAINING_PAYLOAD: + return "IGNORE_REMAINING_PAYLOAD"; + case SPDY_FORWARD_STREAM_FRAME: + return "FORWARD_STREAM_FRAME"; + case SPDY_CONTROL_FRAME_BEFORE_HEADER_BLOCK: + return "SPDY_CONTROL_FRAME_BEFORE_HEADER_BLOCK"; + case SPDY_CONTROL_FRAME_HEADER_BLOCK: + return "SPDY_CONTROL_FRAME_HEADER_BLOCK"; + case SPDY_GOAWAY_FRAME_PAYLOAD: + return "SPDY_GOAWAY_FRAME_PAYLOAD"; + case SPDY_SETTINGS_FRAME_HEADER: + return "SPDY_SETTINGS_FRAME_HEADER"; + case SPDY_SETTINGS_FRAME_PAYLOAD: + return "SPDY_SETTINGS_FRAME_PAYLOAD"; + case SPDY_ALTSVC_FRAME_PAYLOAD: + return "SPDY_ALTSVC_FRAME_PAYLOAD"; + } + return "UNKNOWN_STATE"; +} + +QuicHttpDecoderAdapter::QuicHttpDecoderAdapter() { + DVLOG(1) << "QuicHttpDecoderAdapter ctor"; + ResetInternal(); +} + +QuicHttpDecoderAdapter::~QuicHttpDecoderAdapter() {} + +void QuicHttpDecoderAdapter::set_visitor(SpdyFramerVisitorInterface* visitor) { + visitor_ = visitor; +} + +void QuicHttpDecoderAdapter::set_debug_visitor( + SpdyFramerDebugVisitorInterface* debug_visitor) { + debug_visitor_ = debug_visitor; +} + +void QuicHttpDecoderAdapter::set_process_single_input_frame(bool v) { + process_single_input_frame_ = v; +} + +void QuicHttpDecoderAdapter::set_extension_visitor( + ExtensionVisitorInterface* visitor) { + extension_ = visitor; +} + +// Passes the call on to the HPQUIC_HTTP_ACK decoder. +void QuicHttpDecoderAdapter::SetDecoderHeaderTableDebugVisitor( + std::unique_ptr<HpackHeaderTable::DebugVisitorInterface> visitor) { + GetHpackDecoder()->SetHeaderTableDebugVisitor(std::move(visitor)); +} + +size_t QuicHttpDecoderAdapter::ProcessInput(const char* data, size_t len) { + size_t limit = recv_frame_size_limit_; + frame_decoder_->set_maximum_payload_size(limit); + + size_t total_processed = 0; + while (len > 0 && spdy_state_ != SPDY_ERROR) { + // Process one at a time so that we update the adapter's internal + // state appropriately. + const size_t processed = ProcessInputFrame(data, len); + + // We had some data, and weren't in an error state, so should have + // processed/consumed at least one byte of it, even if we then ended up + // in an error state. + DCHECK(processed > 0) << "processed=" << processed + << " spdy_state_=" << spdy_state_ + << " spdy_framer_error_=" << spdy_framer_error_; + + data += processed; + len -= processed; + total_processed += processed; + if (process_single_input_frame() || processed == 0) { + break; + } + } + return total_processed; +} + +void QuicHttpDecoderAdapter::Reset() { + ResetInternal(); +} + +QuicHttpDecoderAdapter::SpdyState QuicHttpDecoderAdapter::state() const { + return spdy_state_; +} + +SpdyFramerError QuicHttpDecoderAdapter::spdy_framer_error() const { + return spdy_framer_error_; +} + +bool QuicHttpDecoderAdapter::probable_http_response() const { + return latched_probable_http_response_; +} + +// =========================================================================== +// Implementations of the methods declared by QuicHttpFrameDecoderListener. + +// Called once the common frame header has been decoded for any frame. +// This function is largely based on QuicHttpDecoderAdapter::ValidateFrameHeader +// and some parts of QuicHttpDecoderAdapter::ProcessCommonHeader. +bool QuicHttpDecoderAdapter::OnFrameHeader(const QuicHttpFrameHeader& header) { + DVLOG(1) << "OnFrameHeader: " << header; + decoded_frame_header_ = true; + if (!latched_probable_http_response_) { + latched_probable_http_response_ = header.IsProbableHttpResponse(); + } + const uint8_t raw_frame_type = static_cast<uint8_t>(header.type); + visitor()->OnCommonHeader(header.stream_id, header.payload_length, + raw_frame_type, header.flags); + if (has_expected_frame_type_ && header.type != expected_frame_type_) { + // Report an unexpected frame error and close the connection if we + // expect a known frame type (probably CONTINUATION) and receive an + // unknown frame. + VLOG(1) << "The framer was expecting to receive a " << expected_frame_type_ + << " frame, but instead received an unknown frame of type " + << header.type; + SetSpdyErrorAndNotify(SpdyFramerError::SPDY_UNEXPECTED_FRAME); + return false; + } + if (!IsSupportedQuicHttpFrameType(header.type)) { + if (extension_ != nullptr) { + // Unknown frames will be passed to the registered extension. + return true; + } + // In HTTP2 we ignore unknown frame types for extensibility, as long as + // the rest of the control frame header is valid. + // We rely on the visitor to check validity of stream_id. + bool valid_stream = + visitor()->OnUnknownFrame(header.stream_id, raw_frame_type); + if (!valid_stream) { + // Report an invalid frame error if the stream_id is not valid. + VLOG(1) << "Unknown control frame type " << header.type + << " received on invalid stream " << header.stream_id; + SetSpdyErrorAndNotify(SpdyFramerError::SPDY_INVALID_CONTROL_FRAME); + return false; + } else { + DVLOG(1) << "Ignoring unknown frame type " << header.type; + return true; + } + } + + SpdyFrameType frame_type = ToSpdyFrameType(header.type); + if (!IsValidHTTP2FrameStreamId(header.stream_id, frame_type)) { + VLOG(1) << "The framer received an invalid streamID of " << header.stream_id + << " for a frame of type " << header.type; + SetSpdyErrorAndNotify(SpdyFramerError::SPDY_INVALID_STREAM_ID); + return false; + } + + if (has_expected_frame_type_ && header.type != expected_frame_type_) { + VLOG(1) << "Expected frame type " << expected_frame_type_ << ", not " + << header.type; + SetSpdyErrorAndNotify(SpdyFramerError::SPDY_UNEXPECTED_FRAME); + return false; + } + + if (!has_expected_frame_type_ && + header.type == QuicHttpFrameType::CONTINUATION) { + VLOG(1) << "Got CONTINUATION frame when not expected."; + SetSpdyErrorAndNotify(SpdyFramerError::SPDY_UNEXPECTED_FRAME); + return false; + } + + if (header.type == QuicHttpFrameType::DATA) { + // For some reason SpdyFramer still rejects invalid DATA frame flags. + uint8_t valid_flags = QuicHttpFrameFlag::QUIC_HTTP_PADDED | + QuicHttpFrameFlag::QUIC_HTTP_END_STREAM; + if (header.HasAnyFlags(~valid_flags)) { + SetSpdyErrorAndNotify(SpdyFramerError::SPDY_INVALID_DATA_FRAME_FLAGS); + return false; + } + } + + return true; +} + +void QuicHttpDecoderAdapter::OnDataStart(const QuicHttpFrameHeader& header) { + DVLOG(1) << "OnDataStart: " << header; + + if (IsOkToStartFrame(header) && HasRequiredStreamId(header)) { + frame_header_ = header; + has_frame_header_ = true; + visitor()->OnDataFrameHeader(header.stream_id, header.payload_length, + header.IsEndStream()); + } +} + +void QuicHttpDecoderAdapter::OnDataPayload(const char* data, size_t len) { + DVLOG(1) << "OnDataPayload: len=" << len; + DCHECK(has_frame_header_); + DCHECK_EQ(frame_header_.type, QuicHttpFrameType::DATA); + visitor()->OnStreamFrameData(frame_header().stream_id, data, len); +} + +void QuicHttpDecoderAdapter::OnDataEnd() { + DVLOG(1) << "OnDataEnd"; + DCHECK(has_frame_header_); + DCHECK_EQ(frame_header_.type, QuicHttpFrameType::DATA); + if (frame_header().IsEndStream()) { + visitor()->OnStreamEnd(frame_header().stream_id); + } + opt_pad_length_ = nullopt; +} + +void QuicHttpDecoderAdapter::OnHeadersStart(const QuicHttpFrameHeader& header) { + DVLOG(1) << "OnHeadersStart: " << header; + if (IsOkToStartFrame(header) && HasRequiredStreamId(header)) { + frame_header_ = header; + has_frame_header_ = true; + if (header.HasPriority()) { + // Once we've got the priority fields, then we can report the arrival + // of this HEADERS frame. + on_headers_called_ = false; + return; + } + on_headers_called_ = true; + ReportReceiveCompressedFrame(header); + visitor()->OnHeaders(header.stream_id, kNotHasPriorityFields, + 0, // priority + 0, // parent_stream_id + false, // exclusive + header.IsEndStream(), header.IsEndHeaders()); + CommonStartHpackBlock(); + } +} + +void QuicHttpDecoderAdapter::OnHeadersPriority( + const QuicHttpPriorityFields& priority) { + DVLOG(1) << "OnHeadersPriority: " << priority; + DCHECK(has_frame_header_); + DCHECK_EQ(frame_type(), QuicHttpFrameType::HEADERS) << frame_header_; + DCHECK(frame_header_.HasPriority()); + DCHECK(!on_headers_called_); + on_headers_called_ = true; + ReportReceiveCompressedFrame(frame_header_); + visitor()->OnHeaders(frame_header_.stream_id, kHasPriorityFields, + priority.weight, priority.stream_dependency, + priority.is_exclusive, frame_header_.IsEndStream(), + frame_header_.IsEndHeaders()); + CommonStartHpackBlock(); +} + +void QuicHttpDecoderAdapter::OnHpackFragment(const char* data, size_t len) { + DVLOG(1) << "OnHpackFragment: len=" << len; + on_hpack_fragment_called_ = true; + if (!GetHpackDecoder()->HandleControlFrameHeadersData(data, len)) { + SetSpdyErrorAndNotify(SpdyFramerError::SPDY_DECOMPRESS_FAILURE); + return; + } +} + +void QuicHttpDecoderAdapter::OnHeadersEnd() { + DVLOG(1) << "OnHeadersEnd"; + CommonHpackFragmentEnd(); + opt_pad_length_ = nullopt; +} + +void QuicHttpDecoderAdapter::OnPriorityFrame( + const QuicHttpFrameHeader& header, + const QuicHttpPriorityFields& priority) { + DVLOG(1) << "OnPriorityFrame: " << header << "; priority: " << priority; + if (IsOkToStartFrame(header) && HasRequiredStreamId(header)) { + visitor()->OnPriority(header.stream_id, priority.stream_dependency, + priority.weight, priority.is_exclusive); + } +} + +void QuicHttpDecoderAdapter::OnContinuationStart( + const QuicHttpFrameHeader& header) { + DVLOG(1) << "OnContinuationStart: " << header; + if (IsOkToStartFrame(header) && HasRequiredStreamId(header)) { + DCHECK(has_hpack_first_frame_header_); + if (header.stream_id != hpack_first_frame_header_.stream_id) { + SetSpdyErrorAndNotify(SpdyFramerError::SPDY_UNEXPECTED_FRAME); + return; + } + frame_header_ = header; + has_frame_header_ = true; + ReportReceiveCompressedFrame(header); + visitor()->OnContinuation(header.stream_id, header.IsEndHeaders()); + } +} + +void QuicHttpDecoderAdapter::OnContinuationEnd() { + DVLOG(1) << "OnContinuationEnd"; + CommonHpackFragmentEnd(); +} + +void QuicHttpDecoderAdapter::OnPadLength(size_t trailing_length) { + DVLOG(1) << "OnPadLength: " << trailing_length; + opt_pad_length_ = trailing_length; + if (frame_header_.type == QuicHttpFrameType::DATA) { + visitor()->OnStreamPadding(stream_id(), 1); + } else if (frame_header_.type == QuicHttpFrameType::HEADERS) { + CHECK_LT(trailing_length, 256u); + } +} + +void QuicHttpDecoderAdapter::OnPadding(const char* padding, + size_t skipped_length) { + DVLOG(1) << "OnPadding: " << skipped_length; + if (frame_header_.type == QuicHttpFrameType::DATA) { + visitor()->OnStreamPadding(stream_id(), skipped_length); + } else { + MaybeAnnounceEmptyFirstHpackFragment(); + } +} + +void QuicHttpDecoderAdapter::OnRstStream(const QuicHttpFrameHeader& header, + QuicHttpErrorCode http2_error_code) { + DVLOG(1) << "OnRstStream: " << header << "; code=" << http2_error_code; + if (IsOkToStartFrame(header) && HasRequiredStreamId(header)) { + SpdyErrorCode error_code = + ParseErrorCode(static_cast<uint32_t>(http2_error_code)); + visitor()->OnRstStream(header.stream_id, error_code); + } +} + +void QuicHttpDecoderAdapter::OnSettingsStart( + const QuicHttpFrameHeader& header) { + DVLOG(1) << "OnSettingsStart: " << header; + if (IsOkToStartFrame(header) && HasRequiredStreamIdZero(header)) { + frame_header_ = header; + has_frame_header_ = true; + visitor()->OnSettings(); + } +} + +void QuicHttpDecoderAdapter::OnSetting( + const QuicHttpSettingFields& setting_fields) { + DVLOG(1) << "OnSetting: " << setting_fields; + const uint16_t parameter = static_cast<uint16_t>(setting_fields.parameter); + SpdySettingsIds setting_id; + if (!ParseSettingsId(parameter, &setting_id)) { + if (extension_ == nullptr) { + DVLOG(1) << "Ignoring unknown setting id: " << setting_fields; + } else { + extension_->OnSetting(parameter, setting_fields.value); + } + return; + } + visitor()->OnSetting(setting_id, setting_fields.value); +} + +void QuicHttpDecoderAdapter::OnSettingsEnd() { + DVLOG(1) << "OnSettingsEnd"; + visitor()->OnSettingsEnd(); +} + +void QuicHttpDecoderAdapter::OnSettingsAck(const QuicHttpFrameHeader& header) { + DVLOG(1) << "OnSettingsAck: " << header; + if (IsOkToStartFrame(header) && HasRequiredStreamIdZero(header)) { + visitor()->OnSettingsAck(); + } +} + +void QuicHttpDecoderAdapter::OnPushPromiseStart( + const QuicHttpFrameHeader& header, + const QuicHttpPushPromiseFields& promise, + size_t total_padding_length) { + DVLOG(1) << "OnPushPromiseStart: " << header << "; promise: " << promise + << "; total_padding_length: " << total_padding_length; + if (IsOkToStartFrame(header) && HasRequiredStreamId(header)) { + if (promise.promised_stream_id == 0) { + SetSpdyErrorAndNotify(SpdyFramerError::SPDY_INVALID_CONTROL_FRAME); + return; + } + frame_header_ = header; + has_frame_header_ = true; + ReportReceiveCompressedFrame(header); + visitor()->OnPushPromise(header.stream_id, promise.promised_stream_id, + header.IsEndHeaders()); + CommonStartHpackBlock(); + } +} + +void QuicHttpDecoderAdapter::OnPushPromiseEnd() { + DVLOG(1) << "OnPushPromiseEnd"; + CommonHpackFragmentEnd(); + opt_pad_length_ = nullopt; +} + +void QuicHttpDecoderAdapter::OnPing(const QuicHttpFrameHeader& header, + const QuicHttpPingFields& ping) { + DVLOG(1) << "OnPing: " << header << "; ping: " << ping; + if (IsOkToStartFrame(header) && HasRequiredStreamIdZero(header)) { + visitor()->OnPing(ToSpdyPingId(ping), false); + } +} + +void QuicHttpDecoderAdapter::OnPingAck(const QuicHttpFrameHeader& header, + const QuicHttpPingFields& ping) { + DVLOG(1) << "OnPingAck: " << header << "; ping: " << ping; + if (IsOkToStartFrame(header) && HasRequiredStreamIdZero(header)) { + visitor()->OnPing(ToSpdyPingId(ping), true); + } +} + +void QuicHttpDecoderAdapter::OnGoAwayStart(const QuicHttpFrameHeader& header, + const QuicHttpGoAwayFields& goaway) { + DVLOG(1) << "OnGoAwayStart: " << header << "; goaway: " << goaway; + if (IsOkToStartFrame(header) && HasRequiredStreamIdZero(header)) { + frame_header_ = header; + has_frame_header_ = true; + SpdyErrorCode error_code = + ParseErrorCode(static_cast<uint32_t>(goaway.error_code)); + visitor()->OnGoAway(goaway.last_stream_id, error_code); + } +} + +void QuicHttpDecoderAdapter::OnGoAwayOpaqueData(const char* data, size_t len) { + DVLOG(1) << "OnGoAwayOpaqueData: len=" << len; + visitor()->OnGoAwayFrameData(data, len); +} + +void QuicHttpDecoderAdapter::OnGoAwayEnd() { + DVLOG(1) << "OnGoAwayEnd"; + visitor()->OnGoAwayFrameData(nullptr, 0); +} + +void QuicHttpDecoderAdapter::OnWindowUpdate(const QuicHttpFrameHeader& header, + uint32_t increment) { + DVLOG(1) << "OnWindowUpdate: " << header << "; increment=" << increment; + if (IsOkToStartFrame(header)) { + visitor()->OnWindowUpdate(header.stream_id, increment); + } +} + +// Per RFC7838, an ALTSVC frame on stream 0 with origin_length == 0, or one on +// a stream other than stream 0 with origin_length != 0 MUST be ignored. All +// frames are decoded by QuicHttpDecoderAdapter, and it is left to the consumer +// (listener) to implement this behavior. +void QuicHttpDecoderAdapter::OnAltSvcStart(const QuicHttpFrameHeader& header, + size_t origin_length, + size_t value_length) { + DVLOG(1) << "OnAltSvcStart: " << header + << "; origin_length: " << origin_length + << "; value_length: " << value_length; + if (!IsOkToStartFrame(header)) { + return; + } + frame_header_ = header; + has_frame_header_ = true; + alt_svc_origin_.clear(); + alt_svc_value_.clear(); +} + +void QuicHttpDecoderAdapter::OnAltSvcOriginData(const char* data, size_t len) { + DVLOG(1) << "OnAltSvcOriginData: len=" << len; + alt_svc_origin_.append(data, len); +} + +// Called when decoding the Alt-Svc-Field-Value of an ALTSVC; +// the field is uninterpreted. +void QuicHttpDecoderAdapter::OnAltSvcValueData(const char* data, size_t len) { + DVLOG(1) << "OnAltSvcValueData: len=" << len; + alt_svc_value_.append(data, len); +} + +void QuicHttpDecoderAdapter::OnAltSvcEnd() { + DVLOG(1) << "OnAltSvcEnd: origin.size(): " << alt_svc_origin_.size() + << "; value.size(): " << alt_svc_value_.size(); + SpdyAltSvcWireFormat::AlternativeServiceVector altsvc_vector; + if (!SpdyAltSvcWireFormat::ParseHeaderFieldValue(alt_svc_value_, + &altsvc_vector)) { + DLOG(ERROR) << "SpdyAltSvcWireFormat::ParseHeaderFieldValue failed."; + SetSpdyErrorAndNotify(SpdyFramerError::SPDY_INVALID_CONTROL_FRAME); + return; + } + visitor()->OnAltSvc(frame_header_.stream_id, alt_svc_origin_, altsvc_vector); + // We assume that ALTSVC frames are rare, so get rid of the storage. + alt_svc_origin_.clear(); + alt_svc_origin_.shrink_to_fit(); + alt_svc_value_.clear(); + alt_svc_value_.shrink_to_fit(); +} + +// Except for BLOCKED frames, all other unknown frames are either dropped or +// passed to a registered extension. +void QuicHttpDecoderAdapter::OnUnknownStart(const QuicHttpFrameHeader& header) { + DVLOG(1) << "OnUnknownStart: " << header; + if (IsOkToStartFrame(header)) { + if (extension_ != nullptr) { + const uint8_t type = static_cast<uint8_t>(header.type); + const uint8_t flags = static_cast<uint8_t>(header.flags); + handling_extension_payload_ = extension_->OnFrameHeader( + header.stream_id, header.payload_length, type, flags); + } + } +} + +void QuicHttpDecoderAdapter::OnUnknownPayload(const char* data, size_t len) { + if (handling_extension_payload_) { + extension_->OnFramePayload(data, len); + } else { + DVLOG(1) << "OnUnknownPayload: len=" << len; + } +} + +void QuicHttpDecoderAdapter::OnUnknownEnd() { + DVLOG(1) << "OnUnknownEnd"; + handling_extension_payload_ = false; +} + +void QuicHttpDecoderAdapter::OnPaddingTooLong(const QuicHttpFrameHeader& header, + size_t missing_length) { + DVLOG(1) << "OnPaddingTooLong: " << header + << "; missing_length: " << missing_length; + if (header.type == QuicHttpFrameType::DATA) { + if (header.payload_length == 0) { + DCHECK_EQ(1u, missing_length); + SetSpdyErrorAndNotify(SpdyFramerError::SPDY_INVALID_DATA_FRAME_FLAGS); + return; + } + visitor()->OnStreamPadding(header.stream_id, 1); + } + SetSpdyErrorAndNotify(SpdyFramerError::SPDY_INVALID_PADDING); +} + +void QuicHttpDecoderAdapter::OnFrameSizeError( + const QuicHttpFrameHeader& header) { + DVLOG(1) << "OnFrameSizeError: " << header; + size_t recv_limit = recv_frame_size_limit_; + if (header.payload_length > recv_limit) { + SetSpdyErrorAndNotify(SpdyFramerError::SPDY_OVERSIZED_PAYLOAD); + return; + } + if (header.type != QuicHttpFrameType::DATA && + header.payload_length > recv_limit) { + SetSpdyErrorAndNotify(SpdyFramerError::SPDY_CONTROL_PAYLOAD_TOO_LARGE); + return; + } + switch (header.type) { + case QuicHttpFrameType::GOAWAY: + case QuicHttpFrameType::ALTSVC: + SetSpdyErrorAndNotify(SpdyFramerError::SPDY_INVALID_CONTROL_FRAME); + break; + default: + SetSpdyErrorAndNotify(SpdyFramerError::SPDY_INVALID_CONTROL_FRAME_SIZE); + } +} + +// Decodes the input up to the next frame boundary (i.e. at most one frame), +// stopping early if an error is detected. +size_t QuicHttpDecoderAdapter::ProcessInputFrame(const char* data, size_t len) { + DCHECK_NE(spdy_state_, SpdyState::SPDY_ERROR); + QuicHttpDecodeBuffer db(data, len); + QuicHttpDecodeStatus status = frame_decoder_->DecodeFrame(&db); + if (spdy_state_ != SpdyState::SPDY_ERROR) { + DetermineSpdyState(status); + } else { + VLOG(1) << "ProcessInputFrame spdy_framer_error_=" + << Http2DecoderAdapter::SpdyFramerErrorToString(spdy_framer_error_); + if (spdy_framer_error_ == SpdyFramerError::SPDY_INVALID_PADDING && + has_frame_header_ && frame_type() != QuicHttpFrameType::DATA) { + // spdy_framer_test checks that all of the available frame payload + // has been consumed, so do that. + size_t total = remaining_total_payload(); + if (total <= frame_header().payload_length) { + size_t avail = db.MinLengthRemaining(total); + VLOG(1) << "Skipping past " << avail << " bytes, of " << total + << " total remaining in the frame's payload."; + db.AdvanceCursor(avail); + } else { + SPDY_BUG << "Total remaining (" << total + << ") should not be greater than the payload length; " + << frame_header(); + } + } + } + return db.Offset(); +} + +// After decoding, determine the next SpdyState. Only called if the current +// state is NOT SpdyState::SPDY_ERROR (i.e. if none of the callback methods +// detected an error condition), because otherwise we assume that the callback +// method has set spdy_framer_error_ appropriately. +void QuicHttpDecoderAdapter::DetermineSpdyState(QuicHttpDecodeStatus status) { + DCHECK_EQ(spdy_framer_error_, SpdyFramerError::SPDY_NO_ERROR); + DCHECK(!HasError()) << spdy_framer_error_; + switch (status) { + case QuicHttpDecodeStatus::kDecodeDone: + DVLOG(1) << "ProcessInputFrame -> QuicHttpDecodeStatus::kDecodeDone"; + ResetBetweenFrames(); + break; + case QuicHttpDecodeStatus::kDecodeInProgress: + DVLOG(1) + << "ProcessInputFrame -> QuicHttpDecodeStatus::kDecodeInProgress"; + if (decoded_frame_header_) { + if (IsDiscardingPayload()) { + set_spdy_state(SpdyState::SPDY_IGNORE_REMAINING_PAYLOAD); + } else if (has_frame_header_ && + frame_type() == QuicHttpFrameType::DATA) { + if (IsReadingPaddingLength()) { + set_spdy_state(SpdyState::SPDY_READ_DATA_FRAME_PADDING_LENGTH); + } else if (IsSkippingPadding()) { + set_spdy_state(SpdyState::SPDY_CONSUME_PADDING); + } else { + set_spdy_state(SpdyState::SPDY_FORWARD_STREAM_FRAME); + } + } else { + set_spdy_state(SpdyState::SPDY_CONTROL_FRAME_PAYLOAD); + } + } else { + set_spdy_state(SpdyState::SPDY_READING_COMMON_HEADER); + } + break; + case QuicHttpDecodeStatus::kDecodeError: + VLOG(1) << "ProcessInputFrame -> QuicHttpDecodeStatus::kDecodeError"; + if (IsDiscardingPayload()) { + if (remaining_total_payload() == 0) { + // Push the QuicHttpFrameDecoder out of state kDiscardPayload now + // since doing so requires no input. + QuicHttpDecodeBuffer tmp("", 0); + QuicHttpDecodeStatus status = frame_decoder_->DecodeFrame(&tmp); + if (status != QuicHttpDecodeStatus::kDecodeDone) { + SPDY_BUG << "Expected to be done decoding the frame, not " + << status; + SetSpdyErrorAndNotify(SpdyFramerError::SPDY_INTERNAL_FRAMER_ERROR); + } else if (spdy_framer_error_ != SpdyFramerError::SPDY_NO_ERROR) { + SPDY_BUG << "Expected to have no error, not " + << Http2DecoderAdapter::SpdyFramerErrorToString( + spdy_framer_error_); + } else { + ResetBetweenFrames(); + } + } else { + set_spdy_state(SpdyState::SPDY_IGNORE_REMAINING_PAYLOAD); + } + } else { + SetSpdyErrorAndNotify(SpdyFramerError::SPDY_INVALID_CONTROL_FRAME); + } + break; + } +} + +void QuicHttpDecoderAdapter::ResetBetweenFrames() { + CorruptFrameHeader(&frame_header_); + decoded_frame_header_ = false; + has_frame_header_ = false; + set_spdy_state(SpdyState::SPDY_READY_FOR_FRAME); +} + +// ResetInternal is called from the constructor, and during tests, but not +// otherwise (i.e. not between every frame). +void QuicHttpDecoderAdapter::ResetInternal() { + set_spdy_state(SpdyState::SPDY_READY_FOR_FRAME); + spdy_framer_error_ = SpdyFramerError::SPDY_NO_ERROR; + + decoded_frame_header_ = false; + has_frame_header_ = false; + on_headers_called_ = false; + on_hpack_fragment_called_ = false; + latched_probable_http_response_ = false; + has_expected_frame_type_ = false; + + CorruptFrameHeader(&frame_header_); + CorruptFrameHeader(&hpack_first_frame_header_); + + frame_decoder_.reset(new QuicHttpFrameDecoder(this)); + hpack_decoder_ = nullptr; +} + +void QuicHttpDecoderAdapter::set_spdy_state(SpdyState v) { + DVLOG(2) << "set_spdy_state(" << StateToString(v) << ")"; + spdy_state_ = v; +} + +void QuicHttpDecoderAdapter::SetSpdyErrorAndNotify(SpdyFramerError error) { + if (HasError()) { + DCHECK_EQ(spdy_state_, SpdyState::SPDY_ERROR); + } else { + VLOG(2) << "SetSpdyErrorAndNotify(" + << Http2DecoderAdapter::SpdyFramerErrorToString(error) << ")"; + DCHECK_NE(error, SpdyFramerError::SPDY_NO_ERROR); + spdy_framer_error_ = error; + set_spdy_state(SpdyState::SPDY_ERROR); + frame_decoder_->set_listener(&no_op_listener_); + visitor()->OnError(error); + } +} + +bool QuicHttpDecoderAdapter::HasError() const { + if (spdy_state_ == SpdyState::SPDY_ERROR) { + DCHECK_NE(spdy_framer_error(), SpdyFramerError::SPDY_NO_ERROR); + return true; + } else { + DCHECK_EQ(spdy_framer_error(), SpdyFramerError::SPDY_NO_ERROR); + return false; + } +} + +const QuicHttpFrameHeader& QuicHttpDecoderAdapter::frame_header() const { + DCHECK(has_frame_header_); + return frame_header_; +} + +uint32_t QuicHttpDecoderAdapter::stream_id() const { + return frame_header().stream_id; +} + +QuicHttpFrameType QuicHttpDecoderAdapter::frame_type() const { + return frame_header().type; +} + +size_t QuicHttpDecoderAdapter::remaining_total_payload() const { + DCHECK(has_frame_header_); + size_t remaining = frame_decoder_->remaining_payload(); + if (IsPaddable(frame_type()) && frame_header_.IsPadded()) { + remaining += frame_decoder_->remaining_padding(); + } + return remaining; +} + +bool QuicHttpDecoderAdapter::IsReadingPaddingLength() { + bool result = frame_header_.IsPadded() && !opt_pad_length_; + DVLOG(2) << "QuicHttpDecoderAdapter::IsReadingPaddingLength: " << result; + return result; +} +bool QuicHttpDecoderAdapter::IsSkippingPadding() { + bool result = frame_header_.IsPadded() && opt_pad_length_ && + frame_decoder_->remaining_payload() == 0 && + frame_decoder_->remaining_padding() > 0; + DVLOG(2) << "QuicHttpDecoderAdapter::IsSkippingPadding: " << result; + return result; +} +bool QuicHttpDecoderAdapter::IsDiscardingPayload() { + bool result = decoded_frame_header_ && frame_decoder_->IsDiscardingPayload(); + DVLOG(2) << "QuicHttpDecoderAdapter::IsDiscardingPayload: " << result; + return result; +} +// Called from OnXyz or OnXyzStart methods to decide whether it is OK to +// handle the callback. +bool QuicHttpDecoderAdapter::IsOkToStartFrame( + const QuicHttpFrameHeader& header) { + DVLOG(3) << "IsOkToStartFrame"; + if (HasError()) { + VLOG(2) << "HasError()"; + return false; + } + DCHECK(!has_frame_header_); + if (has_expected_frame_type_ && header.type != expected_frame_type_) { + VLOG(1) << "Expected frame type " << expected_frame_type_ << ", not " + << header.type; + SetSpdyErrorAndNotify(SpdyFramerError::SPDY_UNEXPECTED_FRAME); + return false; + } + + return true; +} + +bool QuicHttpDecoderAdapter::HasRequiredStreamId(uint32_t stream_id) { + DVLOG(3) << "HasRequiredStreamId: " << stream_id; + if (HasError()) { + VLOG(2) << "HasError()"; + return false; + } + if (stream_id != 0) { + return true; + } + VLOG(1) << "Stream Id is required, but zero provided"; + SetSpdyErrorAndNotify(SpdyFramerError::SPDY_INVALID_STREAM_ID); + return false; +} + +bool QuicHttpDecoderAdapter::HasRequiredStreamId( + const QuicHttpFrameHeader& header) { + return HasRequiredStreamId(header.stream_id); +} + +bool QuicHttpDecoderAdapter::HasRequiredStreamIdZero(uint32_t stream_id) { + DVLOG(3) << "HasRequiredStreamIdZero: " << stream_id; + if (HasError()) { + VLOG(2) << "HasError()"; + return false; + } + if (stream_id == 0) { + return true; + } + VLOG(1) << "Stream Id was not zero, as required: " << stream_id; + SetSpdyErrorAndNotify(SpdyFramerError::SPDY_INVALID_STREAM_ID); + return false; +} + +bool QuicHttpDecoderAdapter::HasRequiredStreamIdZero( + const QuicHttpFrameHeader& header) { + return HasRequiredStreamIdZero(header.stream_id); +} + +void QuicHttpDecoderAdapter::ReportReceiveCompressedFrame( + const QuicHttpFrameHeader& header) { + if (debug_visitor() != nullptr) { + size_t total = header.payload_length + QuicHttpFrameHeader::EncodedSize(); + debug_visitor()->OnReceiveCompressedFrame( + header.stream_id, ToSpdyFrameType(header.type), total); + } +} + +HpackDecoderAdapter* QuicHttpDecoderAdapter::GetHpackDecoder() { + if (hpack_decoder_ == nullptr) { + hpack_decoder_ = SpdyMakeUnique<HpackDecoderAdapter>(); + } + return hpack_decoder_.get(); +} + +void QuicHttpDecoderAdapter::CommonStartHpackBlock() { + DVLOG(1) << "CommonStartHpackBlock"; + DCHECK(!has_hpack_first_frame_header_); + if (!frame_header_.IsEndHeaders()) { + hpack_first_frame_header_ = frame_header_; + has_hpack_first_frame_header_ = true; + } else { + CorruptFrameHeader(&hpack_first_frame_header_); + } + on_hpack_fragment_called_ = false; + SpdyHeadersHandlerInterface* handler = + visitor()->OnHeaderFrameStart(stream_id()); + if (handler == nullptr) { + SPDY_BUG << "visitor_->OnHeaderFrameStart returned nullptr"; + SetSpdyErrorAndNotify(SpdyFramerError::SPDY_INTERNAL_FRAMER_ERROR); + return; + } + GetHpackDecoder()->HandleControlFrameHeadersStart(handler); +} + +// SpdyFramer calls HandleControlFrameHeadersData even if there are zero +// fragment bytes in the first frame, so do the same. +void QuicHttpDecoderAdapter::MaybeAnnounceEmptyFirstHpackFragment() { + if (!on_hpack_fragment_called_) { + OnHpackFragment(nullptr, 0); + DCHECK(on_hpack_fragment_called_); + } +} + +void QuicHttpDecoderAdapter::CommonHpackFragmentEnd() { + DVLOG(1) << "CommonHpackFragmentEnd: stream_id=" << stream_id(); + if (HasError()) { + VLOG(1) << "HasError(), returning"; + return; + } + DCHECK(has_frame_header_); + MaybeAnnounceEmptyFirstHpackFragment(); + if (frame_header_.IsEndHeaders()) { + DCHECK_EQ(has_hpack_first_frame_header_, + frame_type() == QuicHttpFrameType::CONTINUATION) + << frame_header(); + has_expected_frame_type_ = false; + if (GetHpackDecoder()->HandleControlFrameHeadersComplete(nullptr)) { + visitor()->OnHeaderFrameEnd(stream_id()); + } else { + SetSpdyErrorAndNotify(SpdyFramerError::SPDY_DECOMPRESS_FAILURE); + return; + } + const QuicHttpFrameHeader& first = + frame_type() == QuicHttpFrameType::CONTINUATION + ? hpack_first_frame_header_ + : frame_header_; + if (first.type == QuicHttpFrameType::HEADERS && first.IsEndStream()) { + visitor()->OnStreamEnd(first.stream_id); + } + has_hpack_first_frame_header_ = false; + CorruptFrameHeader(&hpack_first_frame_header_); + } else { + DCHECK(has_hpack_first_frame_header_); + has_expected_frame_type_ = true; + expected_frame_type_ = QuicHttpFrameType::CONTINUATION; + } +} + +} // namespace net
diff --git a/net/quic/http/decoder/quic_http_frame_decoder_adapter.h b/net/quic/http/decoder/quic_http_frame_decoder_adapter.h new file mode 100644 index 0000000..aa96f34 --- /dev/null +++ b/net/quic/http/decoder/quic_http_frame_decoder_adapter.h
@@ -0,0 +1,297 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_HTTP_DECODER_QUIC_HTTP_FRAME_DECODER_ADAPTER_H_ +#define NET_QUIC_HTTP_DECODER_QUIC_HTTP_FRAME_DECODER_ADAPTER_H_ + +#include <stddef.h> + +#include <cstdint> +#include <memory> + +#include "net/quic/http/decoder/quic_http_frame_decoder.h" +#include "net/quic/platform/api/quic_optional.h" +#include "net/quic/platform/api/quic_string_piece.h" +#include "net/spdy/core/hpack/hpack_decoder_adapter.h" +#include "net/spdy/core/hpack/hpack_header_table.h" +#include "net/spdy/core/http2_frame_decoder_adapter.h" +#include "net/spdy/core/spdy_alt_svc_wire_format.h" +#include "net/spdy/core/spdy_framer.h" +#include "net/spdy/core/spdy_headers_handler_interface.h" +#include "net/spdy/core/spdy_protocol.h" + +namespace net { + +class SpdyFramerVisitorInterface; +class ExtensionVisitorInterface; + +// Adapts SpdyFramer interface to use QuicHttpFrameDecoder. +class SPDY_EXPORT_PRIVATE QuicHttpDecoderAdapter + : public QuicHttpFrameDecoderListener { + public: + // HTTP2 states. + enum SpdyState { + SPDY_ERROR, + SPDY_READY_FOR_FRAME, // Framer is ready for reading the next frame. + SPDY_FRAME_COMPLETE, // Framer has finished reading a frame, need to reset. + SPDY_READING_COMMON_HEADER, + SPDY_CONTROL_FRAME_PAYLOAD, + SPDY_READ_DATA_FRAME_PADDING_LENGTH, + SPDY_CONSUME_PADDING, + SPDY_IGNORE_REMAINING_PAYLOAD, + SPDY_FORWARD_STREAM_FRAME, + SPDY_CONTROL_FRAME_BEFORE_HEADER_BLOCK, + SPDY_CONTROL_FRAME_HEADER_BLOCK, + SPDY_GOAWAY_FRAME_PAYLOAD, + SPDY_SETTINGS_FRAME_HEADER, + SPDY_SETTINGS_FRAME_PAYLOAD, + SPDY_ALTSVC_FRAME_PAYLOAD, + SPDY_EXTENSION_FRAME_PAYLOAD, + }; + + // For debugging. + static const char* StateToString(int state); + + QuicHttpDecoderAdapter(); + ~QuicHttpDecoderAdapter() override; + + // Set callbacks to be called from the framer. A visitor must be set, or + // else the framer will likely crash. It is acceptable for the visitor + // to do nothing. If this is called multiple times, only the last visitor + // will be used. + void set_visitor(SpdyFramerVisitorInterface* visitor); + SpdyFramerVisitorInterface* visitor() const { return visitor_; } + + // Set extension callbacks to be called from the framer or decoder. Optional. + // If called multiple times, only the last visitor will be used. + void set_extension_visitor(ExtensionVisitorInterface* visitor); + + // Set debug callbacks to be called from the framer. The debug visitor is + // completely optional and need not be set in order for normal operation. + // If this is called multiple times, only the last visitor will be used. + void set_debug_visitor(SpdyFramerDebugVisitorInterface* debug_visitor); + SpdyFramerDebugVisitorInterface* debug_visitor() const { + return debug_visitor_; + } + + // Set debug callbacks to be called from the HPQUIC_HTTP_ACK decoder. + void SetDecoderHeaderTableDebugVisitor( + std::unique_ptr<HpackHeaderTable::DebugVisitorInterface> visitor); + + // Sets whether or not ProcessInput returns after finishing a frame, or + // continues processing additional frames. Normally ProcessInput processes + // all input, but this method enables the caller (and visitor) to work with + // a single frame at a time (or that portion of the frame which is provided + // as input). Reset() does not change the value of this flag. + void set_process_single_input_frame(bool v); + bool process_single_input_frame() const { + return process_single_input_frame_; + } + + // Decode the |len| bytes of encoded HTTP/2 starting at |*data|. Returns + // the number of bytes consumed. It is safe to pass more bytes in than + // may be consumed. Should process (or otherwise buffer) as much as + // available, unless process_single_input_frame is true. + size_t ProcessInput(const char* data, size_t len); + + // Reset the decoder (used just for tests at this time). + void Reset(); + + // Current state of the decoder. + SpdyState state() const; + + // Current error code (NO_ERROR if state != ERROR). + Http2DecoderAdapter::SpdyFramerError spdy_framer_error() const; + + // Has any frame header looked like the start of an HTTP/1.1 (or earlier) + // response? Used to detect if a backend/server that we sent a request to + // has responded with an HTTP/1.1 (or earlier) response. + bool probable_http_response() const; + + HpackDecoderAdapter* GetHpackDecoder(); + + bool HasError() const; + + private: + bool OnFrameHeader(const QuicHttpFrameHeader& header) override; + void OnDataStart(const QuicHttpFrameHeader& header) override; + void OnDataPayload(const char* data, size_t len) override; + void OnDataEnd() override; + void OnHeadersStart(const QuicHttpFrameHeader& header) override; + void OnHeadersPriority(const QuicHttpPriorityFields& priority) override; + void OnHpackFragment(const char* data, size_t len) override; + void OnHeadersEnd() override; + void OnPriorityFrame(const QuicHttpFrameHeader& header, + const QuicHttpPriorityFields& priority) override; + void OnContinuationStart(const QuicHttpFrameHeader& header) override; + void OnContinuationEnd() override; + void OnPadLength(size_t trailing_length) override; + void OnPadding(const char* padding, size_t skipped_length) override; + void OnRstStream(const QuicHttpFrameHeader& header, + QuicHttpErrorCode http2_error_code) override; + void OnSettingsStart(const QuicHttpFrameHeader& header) override; + void OnSetting(const QuicHttpSettingFields& setting_fields) override; + void OnSettingsEnd() override; + void OnSettingsAck(const QuicHttpFrameHeader& header) override; + void OnPushPromiseStart(const QuicHttpFrameHeader& header, + const QuicHttpPushPromiseFields& promise, + size_t total_padding_length) override; + void OnPushPromiseEnd() override; + void OnPing(const QuicHttpFrameHeader& header, + const QuicHttpPingFields& ping) override; + void OnPingAck(const QuicHttpFrameHeader& header, + const QuicHttpPingFields& ping) override; + void OnGoAwayStart(const QuicHttpFrameHeader& header, + const QuicHttpGoAwayFields& goaway) override; + void OnGoAwayOpaqueData(const char* data, size_t len) override; + void OnGoAwayEnd() override; + void OnWindowUpdate(const QuicHttpFrameHeader& header, + uint32_t increment) override; + void OnAltSvcStart(const QuicHttpFrameHeader& header, + size_t origin_length, + size_t value_length) override; + void OnAltSvcOriginData(const char* data, size_t len) override; + void OnAltSvcValueData(const char* data, size_t len) override; + void OnAltSvcEnd() override; + void OnUnknownStart(const QuicHttpFrameHeader& header) override; + void OnUnknownPayload(const char* data, size_t len) override; + void OnUnknownEnd() override; + void OnPaddingTooLong(const QuicHttpFrameHeader& header, + size_t missing_length) override; + void OnFrameSizeError(const QuicHttpFrameHeader& header) override; + + size_t ProcessInputFrame(const char* data, size_t len); + + void DetermineSpdyState(QuicHttpDecodeStatus status); + void ResetBetweenFrames(); + + // ResetInternal is called from the constructor, and during tests, but not + // otherwise (i.e. not between every frame). + void ResetInternal(); + + void set_spdy_state(SpdyState v); + + void SetSpdyErrorAndNotify(Http2DecoderAdapter::SpdyFramerError error); + + const QuicHttpFrameHeader& frame_header() const; + + uint32_t stream_id() const; + QuicHttpFrameType frame_type() const; + + size_t remaining_total_payload() const; + + bool IsReadingPaddingLength(); + bool IsSkippingPadding(); + bool IsDiscardingPayload(); + // Called from OnXyz or OnXyzStart methods to decide whether it is OK to + // handle the callback. + bool IsOkToStartFrame(const QuicHttpFrameHeader& header); + bool HasRequiredStreamId(uint32_t stream_id); + + bool HasRequiredStreamId(const QuicHttpFrameHeader& header); + + bool HasRequiredStreamIdZero(uint32_t stream_id); + + bool HasRequiredStreamIdZero(const QuicHttpFrameHeader& header); + + void ReportReceiveCompressedFrame(const QuicHttpFrameHeader& header); + + void CommonStartHpackBlock(); + + // SpdyFramer calls HandleControlFrameHeadersData even if there are zero + // fragment bytes in the first frame, so do the same. + void MaybeAnnounceEmptyFirstHpackFragment(); + void CommonHpackFragmentEnd(); + + // The most recently decoded frame header; invalid after we reached the end + // of that frame. + QuicHttpFrameHeader frame_header_; + + // If decoding an HPQUIC_HTTP_ACK block that is split across multiple frames, + // this holds the frame header of the HEADERS or PUSH_PROMISE that started the + // block. + QuicHttpFrameHeader hpack_first_frame_header_; + + // Amount of trailing padding. Currently used just as an indicator of whether + // OnPadLength has been called. + QuicOptional<size_t> opt_pad_length_; + + // Temporary buffers for the AltSvc fields. + QuicString alt_svc_origin_; + QuicString alt_svc_value_; + + // Listener used if we transition to an error state; the listener ignores all + // the callbacks. + QuicHttpFrameDecoderNoOpListener no_op_listener_; + + SpdyFramerVisitorInterface* visitor_ = nullptr; + SpdyFramerDebugVisitorInterface* debug_visitor_ = nullptr; + + // If non-null, unknown frames and settings are passed to the extension. + ExtensionVisitorInterface* extension_ = nullptr; + + // The HPQUIC_HTTP_ACK decoder to be used for this adapter. User is + // responsible for clearing if the adapter is to be used for another + // connection. + std::unique_ptr<HpackDecoderAdapter> hpack_decoder_ = nullptr; + + // The HTTP/2 frame decoder. Accessed via a unique_ptr to allow replacement + // (e.g. in tests) when Reset() is called. + std::unique_ptr<QuicHttpFrameDecoder> frame_decoder_; + + // Next frame type expected. Currently only used for CONTINUATION frames, + // but could be used for detecting whether the first frame is a SETTINGS + // frame. + // TODO(jamessyng): Provide means to indicate that decoder should require + // SETTINGS frame as the first frame. + QuicHttpFrameType expected_frame_type_; + + // Attempt to duplicate the SpdyState and SpdyFramer::Error values that + // SpdyFramer sets. Values determined by getting tests to pass. + SpdyState spdy_state_; + Http2DecoderAdapter::SpdyFramerError spdy_framer_error_; + + // The limit on the size of received HTTP/2 payloads as specified in the + // SETTINGS_MAX_FRAME_SIZE advertised to peer. + size_t recv_frame_size_limit_ = kHttp2DefaultFramePayloadLimit; + + // Has OnFrameHeader been called? + bool decoded_frame_header_ = false; + + // Have we recorded an QuicHttpFrameHeader for the current frame? + // We only do so if the decoder will make multiple callbacks for + // the frame; for example, for PING frames we don't make record + // the frame header, but for ALTSVC we do. + bool has_frame_header_ = false; + + // Have we recorded an QuicHttpFrameHeader for the current HPQUIC_HTTP_ACK + // block? True only for multi-frame HPQUIC_HTTP_ACK blocks. + bool has_hpack_first_frame_header_ = false; + + // Has OnHeaders() already been called for current HEADERS block? Only + // meaningful between OnHeadersStart and OnHeadersPriority. + bool on_headers_called_; + + // Has OnHpackFragment() already been called for current HPQUIC_HTTP_ACK + // block? SpdyFramer will pass an empty buffer to the HPQUIC_HTTP_ACK decoder + // if a HEADERS or PUSH_PROMISE has no HPQUIC_HTTP_ACK data in it (e.g. a + // HEADERS frame with only padding). Detect that condition and replicate the + // behavior using this field. + bool on_hpack_fragment_called_; + + // Have we seen a frame header that appears to be an HTTP/1 response? + bool latched_probable_http_response_ = false; + + // Is expected_frame_type_ set? + bool has_expected_frame_type_ = false; + + // Is the current frame payload destined for |extension_|? + bool handling_extension_payload_ = false; + + bool process_single_input_frame_ = false; +}; + +} // namespace net + +#endif // NET_QUIC_HTTP_DECODER_QUIC_HTTP_FRAME_DECODER_ADAPTER_H_
diff --git a/net/quic/http/decoder/quic_http_frame_decoder_listener.cc b/net/quic/http/decoder/quic_http_frame_decoder_listener.cc new file mode 100644 index 0000000..e41242f --- /dev/null +++ b/net/quic/http/decoder/quic_http_frame_decoder_listener.cc
@@ -0,0 +1,14 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/quic_http_frame_decoder_listener.h" + +namespace net { + +bool QuicHttpFrameDecoderNoOpListener::OnFrameHeader( + const QuicHttpFrameHeader& header) { + return true; +} + +} // namespace net
diff --git a/net/quic/http/decoder/quic_http_frame_decoder_listener.h b/net/quic/http/decoder/quic_http_frame_decoder_listener.h new file mode 100644 index 0000000..3f32034 --- /dev/null +++ b/net/quic/http/decoder/quic_http_frame_decoder_listener.h
@@ -0,0 +1,364 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_HTTP_DECODER_QUIC_HTTP_FRAME_DECODER_LISTENER_H_ +#define NET_QUIC_HTTP_DECODER_QUIC_HTTP_FRAME_DECODER_LISTENER_H_ + +// QuicHttpFrameDecoderListener is the interface which the HTTP/2 decoder uses +// to report the decoded frames to a listener. +// +// The general design is to assume that the listener will copy the data it needs +// (e.g. frame headers) and will keep track of the implicit state of the +// decoding process (i.e. the decoder maintains just the information it needs in +// order to perform the decoding). Therefore, the parameters are just those with +// (potentially) new data, not previously provided info about the current frame. +// +// The calls are described as if they are made in quick succession, i.e. one +// after another, but of course the decoder needs input to decode, and the +// decoder will only call the listener once the necessary input has been +// provided. For example: OnDataStart can only be called once the 9 bytes of +// of an HTTP/2 common frame header have been received. The decoder will call +// the listener methods as soon as possible to avoid almost all buffering. +// +// The listener interface is designed so that it is possible to exactly +// reconstruct the serialized frames, with the exception of reserved bits, +// including in the frame header's flags and stream_id fields, which will have +// been cleared before the methods below are called. + +#include <stddef.h> + +#include <cstdint> +#include <type_traits> + +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/quic_http_structures.h" + +namespace net { + +// TODO(jamessynge): Consider sorting the methods by frequency of call, if that +// helps at all. +class QuicHttpFrameDecoderListener { + public: + QuicHttpFrameDecoderListener() {} + virtual ~QuicHttpFrameDecoderListener() {} + + // Called once the common frame header has been decoded for any frame, and + // before any of the methods below, which will also be called. This method is + // included in this interface only for the purpose of supporting SpdyFramer + // semantics via an adapter. This is the only method that has a non-void + // return type, and this is just so that QuicHttpFrameDecoderAdapter (called + // from SpdyFramer) can more readily pass existing tests that expect decoding + // to stop if the headers alone indicate an error. Return false to stop + // decoding just after decoding the header, else return true to continue + // decoding. + // TODO(jamessynge): Remove OnFrameHeader once done with supporting + // SpdyFramer's exact states. + virtual bool OnFrameHeader(const QuicHttpFrameHeader& header) = 0; + + ////////////////////////////////////////////////////////////////////////////// + + // Called once the common frame header has been decoded for a DATA frame, + // before examining the frame's payload, after which: + // OnPadLength will be called if header.IsPadded() is true, i.e. if the + // QUIC_HTTP_PADDED flag is set; + // OnDataPayload will be called as the non-padding portion of the payload + // is available until all of it has been provided; + // OnPadding will be called if the frame is padded AND the Pad Length field + // is greater than zero; + // OnDataEnd will be called last. If the frame is unpadded and has no + // payload, then this will be called immediately after OnDataStart. + virtual void OnDataStart(const QuicHttpFrameHeader& header) = 0; + + // Called when the next non-padding portion of a DATA frame's payload is + // received. + // |data| The start of |len| bytes of data. + // |len| The length of the data buffer. Maybe zero in some cases, which does + // not mean anything special. + virtual void OnDataPayload(const char* data, size_t len) = 0; + + // Called after an entire DATA frame has been received. + // If header.IsEndStream() == true, this is the last data for the stream. + virtual void OnDataEnd() = 0; + + // Called once the common frame header has been decoded for a HEADERS frame, + // before examining the frame's payload, after which: + // OnPadLength will be called if header.IsPadded() is true, i.e. if the + // QUIC_HTTP_PADDED flag is set; + // OnHeadersPriority will be called if header.HasPriority() is true, i.e. if + // the frame has the QUIC_HTTP_PRIORITY flag; + // OnHpackFragment as the remainder of the non-padding payload is available + // until all if has been provided; + // OnPadding will be called if the frame is padded AND the Pad Length field + // is greater than zero; + // OnHeadersEnd will be called last; If the frame is unpadded and has no + // payload, then this will be called immediately after OnHeadersStart; + // OnHeadersEnd indicates the end of the HPQUIC_HTTP_ACK block only if the + // frame header had the QUIC_HTTP_END_HEADERS flag set, else the + // QUIC_HTTP_END_HEADERS should be looked for on a subsequent CONTINUATION + // frame. + virtual void OnHeadersStart(const QuicHttpFrameHeader& header) = 0; + + // Called when a HEADERS frame is received with the QUIC_HTTP_PRIORITY flag + // set and the priority fields have been decoded. + virtual void OnHeadersPriority( + const QuicHttpPriorityFields& priority_fields) = 0; + + // Called when a fragment (i.e. some or all of an HPQUIC_HTTP_ACK Block) is + // received; this may be part of a HEADERS, PUSH_PROMISE or CONTINUATION + // frame. |data| The start of |len| bytes of data. |len| The length of the + // data buffer. Maybe zero in some cases, which does + // not mean anything special, except that it simplified the decoder. + virtual void OnHpackFragment(const char* data, size_t len) = 0; + + // Called after an entire HEADERS frame has been received. The frame is the + // end of the HEADERS if the QUIC_HTTP_END_HEADERS flag is set; else there + // should be CONTINUATION frames after this frame. + virtual void OnHeadersEnd() = 0; + + // Called when an entire QUIC_HTTP_PRIORITY frame has been decoded. + virtual void OnPriorityFrame( + const QuicHttpFrameHeader& header, + const QuicHttpPriorityFields& priority_fields) = 0; + + // Called once the common frame header has been decoded for a CONTINUATION + // frame, before examining the frame's payload, after which: + // OnHpackFragment as the frame's payload is available until all of it + // has been provided; + // OnContinuationEnd will be called last; If the frame has no payload, + // then this will be called immediately after OnContinuationStart; + // the HPQUIC_HTTP_ACK block is at an end if and only if the frame header + // passed to OnContinuationStart had the QUIC_HTTP_END_HEADERS flag set. + virtual void OnContinuationStart(const QuicHttpFrameHeader& header) = 0; + + // Called after an entire CONTINUATION frame has been received. The frame is + // the end of the HEADERS if the QUIC_HTTP_END_HEADERS flag is set. + virtual void OnContinuationEnd() = 0; + + // Called when Pad Length field has been read. Applies to DATA and HEADERS + // frames. For PUSH_PROMISE frames, the Pad Length + 1 is provided in the + // OnPushPromiseStart call as total_padding_length. + virtual void OnPadLength(size_t pad_length) = 0; + + // Called when padding is skipped over. + virtual void OnPadding(const char* padding, size_t skipped_length) = 0; + + // Called when an entire RST_STREAM frame has been decoded. + // This is the only callback for RST_STREAM frames. + virtual void OnRstStream(const QuicHttpFrameHeader& header, + QuicHttpErrorCode error_code) = 0; + + // Called once the common frame header has been decoded for a SETTINGS frame + // without the QUIC_HTTP_ACK flag, before examining the frame's payload, after + // which: + // OnSetting will be called in turn for each pair of settings parameter and + // value found in the payload; + // OnSettingsEnd will be called last; If the frame has no payload, + // then this will be called immediately after OnSettingsStart. + // The frame header is passed so that the caller can check the stream_id, + // which should be zero, but that hasn't been checked by the decoder. + virtual void OnSettingsStart(const QuicHttpFrameHeader& header) = 0; + + // Called for each setting parameter and value within a SETTINGS frame. + virtual void OnSetting(const QuicHttpSettingFields& setting_fields) = 0; + + // Called after parsing the complete payload of SETTINGS frame + // (non-QUIC_HTTP_ACK). + virtual void OnSettingsEnd() = 0; + + // Called when an entire SETTINGS frame, with the QUIC_HTTP_ACK flag, has been + // decoded. + virtual void OnSettingsAck(const QuicHttpFrameHeader& header) = 0; + + // Called just before starting to process the HPQUIC_HTTP_ACK block of a + // PUSH_PROMISE frame. The Pad Length field has already been decoded at this + // point, so OnPadLength will not be called; note that total_padding_length is + // Pad Length + 1. After OnPushPromiseStart: + // OnHpackFragment as the remainder of the non-padding payload is available + // until all if has been provided; + // OnPadding will be called if the frame is padded AND the Pad Length field + // is greater than zero (i.e. total_padding_length > 1); + // OnPushPromiseEnd will be called last; If the frame is unpadded and has no + // payload, then this will be called immediately after OnPushPromiseStart. + virtual void OnPushPromiseStart(const QuicHttpFrameHeader& header, + const QuicHttpPushPromiseFields& promise, + size_t total_padding_length) = 0; + + // Called after all of the HPQUIC_HTTP_ACK block fragment and padding of a + // PUSH_PROMISE has been decoded and delivered to the listener. This call + // indicates the end of the HPQUIC_HTTP_ACK block if and only if the frame + // header had the QUIC_HTTP_END_HEADERS flag set (i.e. header.IsEndHeaders() + // is true); otherwise the next block must be a CONTINUATION frame with the + // same stream id (not the same promised stream id). + virtual void OnPushPromiseEnd() = 0; + + // Called when an entire PING frame, without the QUIC_HTTP_ACK flag, has been + // decoded. + virtual void OnPing(const QuicHttpFrameHeader& header, + const QuicHttpPingFields& ping) = 0; + + // Called when an entire PING frame, with the QUIC_HTTP_ACK flag, has been + // decoded. + virtual void OnPingAck(const QuicHttpFrameHeader& header, + const QuicHttpPingFields& ping) = 0; + + // Called after parsing a GOAWAY frame's header and fixed size fields, after + // which: + // OnGoAwayOpaqueData will be called as opaque data of the payload becomes + // available to the decoder, until all of it has been provided to the + // listener; + // OnGoAwayEnd will be called last, after all the opaque data has been + // provided to the listener; if there is no opaque data, then OnGoAwayEnd + // will be called immediately after OnGoAwayStart. + virtual void OnGoAwayStart(const QuicHttpFrameHeader& header, + const QuicHttpGoAwayFields& goaway) = 0; + + // Called when the next portion of a GOAWAY frame's payload is received. + // |data| The start of |len| bytes of opaque data. + // |len| The length of the opaque data buffer. Maybe zero in some cases, + // which does not mean anything special. + virtual void OnGoAwayOpaqueData(const char* data, size_t len) = 0; + + // Called after finishing decoding all of a GOAWAY frame. + virtual void OnGoAwayEnd() = 0; + + // Called when an entire WINDOW_UPDATE frame has been decoded. The + // window_size_increment is required to be non-zero, but that has not been + // checked. If header.stream_id==0, the connection's flow control window is + // being increased, else the specified stream's flow control is being + // increased. + virtual void OnWindowUpdate(const QuicHttpFrameHeader& header, + uint32_t window_size_increment) = 0; + + // Called when an ALTSVC frame header and origin length have been parsed. + // Either or both lengths may be zero. After OnAltSvcStart: + // OnAltSvcOriginData will be called until all of the (optional) Origin + // has been provided; + // OnAltSvcValueData will be called until all of the Alt-Svc-Field-Value + // has been provided; + // OnAltSvcEnd will called last, after all of the origin and + // Alt-Svc-Field-Value have been delivered to the listener. + virtual void OnAltSvcStart(const QuicHttpFrameHeader& header, + size_t origin_length, + size_t value_length) = 0; + + // Called when decoding the (optional) origin of an ALTSVC; + // the field is uninterpreted. + virtual void OnAltSvcOriginData(const char* data, size_t len) = 0; + + // Called when decoding the Alt-Svc-Field-Value of an ALTSVC; + // the field is uninterpreted. + virtual void OnAltSvcValueData(const char* data, size_t len) = 0; + + // Called after decoding all of a ALTSVC frame and providing to the listener + // via the above methods. + virtual void OnAltSvcEnd() = 0; + + // Called when the common frame header has been decoded, but the frame type + // is unknown, after which: + // OnUnknownPayload is called as the payload of the frame is provided to the + // decoder, until all of the payload has been decoded; + // OnUnknownEnd will called last, after the entire frame of the unknown type + // has been decoded and provided to the listener. + virtual void OnUnknownStart(const QuicHttpFrameHeader& header) = 0; + + // Called when the payload of an unknown frame type is received. + // |data| A buffer containing the data received. + // |len| The length of the data buffer. + virtual void OnUnknownPayload(const char* data, size_t len) = 0; + + // Called after decoding all of the payload of an unknown frame type. + virtual void OnUnknownEnd() = 0; + + ////////////////////////////////////////////////////////////////////////////// + // Below here are events indicating a problem has been detected during + // decoding (i.e. the received frames are malformed in some way). + + // Padding field (uint8) has a value that is too large (i.e. the amount of + // padding is greater than the remainder of the payload that isn't required). + // From RFC Section 6.1, DATA: + // If the length of the padding is the length of the frame payload or + // greater, the recipient MUST treat this as a connection error + // (Section 5.4.1) of type PROTOCOL_ERROR. + // The same is true for HEADERS and PUSH_PROMISE. + virtual void OnPaddingTooLong(const QuicHttpFrameHeader& header, + size_t missing_length) = 0; + + // Frame size error. Depending upon the effected frame, this may or may not + // require terminating the connection, though that is probably the best thing + // to do. + // From RFC Section 4.2, Frame Size: + // An endpoint MUST send an error code of FRAME_SIZE_ERROR if a frame + // exceeds the size defined in SETTINGS_MAX_FRAME_SIZE, exceeds any limit + // defined for the frame type, or is too small to contain mandatory frame + // data. A frame size error in a frame that could alter the state of the + // the entire connection MUST be treated as a connection error + // (Section 5.4.1); this includes any frame carrying a header block + // (Section 4.3) (that is, HEADERS, PUSH_PROMISE, and CONTINUATION), + // SETTINGS, and any frame with a stream identifier of 0. + virtual void OnFrameSizeError(const QuicHttpFrameHeader& header) = 0; +}; + +// Do nothing for each call. Useful for ignoring a frame that is invalid. +class QuicHttpFrameDecoderNoOpListener : public QuicHttpFrameDecoderListener { + public: + QuicHttpFrameDecoderNoOpListener() {} + ~QuicHttpFrameDecoderNoOpListener() override {} + + // TODO(jamessynge): Remove OnFrameHeader once done with supporting + // SpdyFramer's exact states. + bool OnFrameHeader(const QuicHttpFrameHeader& header) override; + + void OnDataStart(const QuicHttpFrameHeader& header) override {} + void OnDataPayload(const char* data, size_t len) override {} + void OnDataEnd() override {} + void OnHeadersStart(const QuicHttpFrameHeader& header) override {} + void OnHeadersPriority(const QuicHttpPriorityFields& priority) override {} + void OnHpackFragment(const char* data, size_t len) override {} + void OnHeadersEnd() override {} + void OnPriorityFrame(const QuicHttpFrameHeader& header, + const QuicHttpPriorityFields& priority) override {} + void OnContinuationStart(const QuicHttpFrameHeader& header) override {} + void OnContinuationEnd() override {} + void OnPadLength(size_t trailing_length) override {} + void OnPadding(const char* padding, size_t skipped_length) override {} + void OnRstStream(const QuicHttpFrameHeader& header, + QuicHttpErrorCode error_code) override {} + void OnSettingsStart(const QuicHttpFrameHeader& header) override {} + void OnSetting(const QuicHttpSettingFields& setting_fields) override {} + void OnSettingsEnd() override {} + void OnSettingsAck(const QuicHttpFrameHeader& header) override {} + void OnPushPromiseStart(const QuicHttpFrameHeader& header, + const QuicHttpPushPromiseFields& promise, + size_t total_padding_length) override {} + void OnPushPromiseEnd() override {} + void OnPing(const QuicHttpFrameHeader& header, + const QuicHttpPingFields& ping) override {} + void OnPingAck(const QuicHttpFrameHeader& header, + const QuicHttpPingFields& ping) override {} + void OnGoAwayStart(const QuicHttpFrameHeader& header, + const QuicHttpGoAwayFields& goaway) override {} + void OnGoAwayOpaqueData(const char* data, size_t len) override {} + void OnGoAwayEnd() override {} + void OnWindowUpdate(const QuicHttpFrameHeader& header, + uint32_t increment) override {} + void OnAltSvcStart(const QuicHttpFrameHeader& header, + size_t origin_length, + size_t value_length) override {} + void OnAltSvcOriginData(const char* data, size_t len) override {} + void OnAltSvcValueData(const char* data, size_t len) override {} + void OnAltSvcEnd() override {} + void OnUnknownStart(const QuicHttpFrameHeader& header) override {} + void OnUnknownPayload(const char* data, size_t len) override {} + void OnUnknownEnd() override {} + void OnPaddingTooLong(const QuicHttpFrameHeader& header, + size_t missing_length) override {} + void OnFrameSizeError(const QuicHttpFrameHeader& header) override {} +}; + +static_assert(!std::is_abstract<QuicHttpFrameDecoderNoOpListener>(), + "QuicHttpFrameDecoderNoOpListener ought to be concrete."); + +} // namespace net + +#endif // NET_QUIC_HTTP_DECODER_QUIC_HTTP_FRAME_DECODER_LISTENER_H_
diff --git a/net/quic/http/decoder/quic_http_frame_decoder_listener_test_util.cc b/net/quic/http/decoder/quic_http_frame_decoder_listener_test_util.cc new file mode 100644 index 0000000..e12fedb2 --- /dev/null +++ b/net/quic/http/decoder/quic_http_frame_decoder_listener_test_util.cc
@@ -0,0 +1,492 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/quic_http_frame_decoder_listener_test_util.h" + +#include "base/logging.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_listener.h" +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/quic_http_structures.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace net { + +FailingQuicHttpFrameDecoderListener::FailingQuicHttpFrameDecoderListener() {} +FailingQuicHttpFrameDecoderListener::~FailingQuicHttpFrameDecoderListener() {} + +bool FailingQuicHttpFrameDecoderListener::OnFrameHeader( + const QuicHttpFrameHeader& header) { + ADD_FAILURE() << "OnFrameHeader: " << header; + return false; +} + +void FailingQuicHttpFrameDecoderListener::OnDataStart( + const QuicHttpFrameHeader& header) { + FAIL() << "OnDataStart: " << header; +} + +void FailingQuicHttpFrameDecoderListener::OnDataPayload(const char* data, + size_t len) { + FAIL() << "OnDataPayload: len=" << len; +} + +void FailingQuicHttpFrameDecoderListener::OnDataEnd() { + FAIL() << "OnDataEnd"; +} + +void FailingQuicHttpFrameDecoderListener::OnHeadersStart( + const QuicHttpFrameHeader& header) { + FAIL() << "OnHeadersStart: " << header; +} + +void FailingQuicHttpFrameDecoderListener::OnHeadersPriority( + const QuicHttpPriorityFields& priority) { + FAIL() << "OnHeadersPriority: " << priority; +} + +void FailingQuicHttpFrameDecoderListener::OnHpackFragment(const char* data, + size_t len) { + FAIL() << "OnHpackFragment: len=" << len; +} + +void FailingQuicHttpFrameDecoderListener::OnHeadersEnd() { + FAIL() << "OnHeadersEnd"; +} + +void FailingQuicHttpFrameDecoderListener::OnPriorityFrame( + const QuicHttpFrameHeader& header, + const QuicHttpPriorityFields& priority) { + FAIL() << "OnPriorityFrame: " << header << "; priority: " << priority; +} + +void FailingQuicHttpFrameDecoderListener::OnContinuationStart( + const QuicHttpFrameHeader& header) { + FAIL() << "OnContinuationStart: " << header; +} + +void FailingQuicHttpFrameDecoderListener::OnContinuationEnd() { + FAIL() << "OnContinuationEnd"; +} + +void FailingQuicHttpFrameDecoderListener::OnPadLength(size_t trailing_length) { + FAIL() << "OnPadLength: trailing_length=" << trailing_length; +} + +void FailingQuicHttpFrameDecoderListener::OnPadding(const char* padding, + size_t skipped_length) { + FAIL() << "OnPadding: skipped_length=" << skipped_length; +} + +void FailingQuicHttpFrameDecoderListener::OnRstStream( + const QuicHttpFrameHeader& header, + QuicHttpErrorCode error_code) { + FAIL() << "OnRstStream: " << header << "; code=" << error_code; +} + +void FailingQuicHttpFrameDecoderListener::OnSettingsStart( + const QuicHttpFrameHeader& header) { + FAIL() << "OnSettingsStart: " << header; +} + +void FailingQuicHttpFrameDecoderListener::OnSetting( + const QuicHttpSettingFields& setting_fields) { + FAIL() << "OnSetting: " << setting_fields; +} + +void FailingQuicHttpFrameDecoderListener::OnSettingsEnd() { + FAIL() << "OnSettingsEnd"; +} + +void FailingQuicHttpFrameDecoderListener::OnSettingsAck( + const QuicHttpFrameHeader& header) { + FAIL() << "OnSettingsAck: " << header; +} + +void FailingQuicHttpFrameDecoderListener::OnPushPromiseStart( + const QuicHttpFrameHeader& header, + const QuicHttpPushPromiseFields& promise, + size_t total_padding_length) { + FAIL() << "OnPushPromiseStart: " << header << "; promise: " << promise + << "; total_padding_length: " << total_padding_length; +} + +void FailingQuicHttpFrameDecoderListener::OnPushPromiseEnd() { + FAIL() << "OnPushPromiseEnd"; +} + +void FailingQuicHttpFrameDecoderListener::OnPing( + const QuicHttpFrameHeader& header, + const QuicHttpPingFields& ping) { + FAIL() << "OnPing: " << header << "; ping: " << ping; +} + +void FailingQuicHttpFrameDecoderListener::OnPingAck( + const QuicHttpFrameHeader& header, + const QuicHttpPingFields& ping) { + FAIL() << "OnPingAck: " << header << "; ping: " << ping; +} + +void FailingQuicHttpFrameDecoderListener::OnGoAwayStart( + const QuicHttpFrameHeader& header, + const QuicHttpGoAwayFields& goaway) { + FAIL() << "OnGoAwayStart: " << header << "; goaway: " << goaway; +} + +void FailingQuicHttpFrameDecoderListener::OnGoAwayOpaqueData(const char* data, + size_t len) { + FAIL() << "OnGoAwayOpaqueData: len=" << len; +} + +void FailingQuicHttpFrameDecoderListener::OnGoAwayEnd() { + FAIL() << "OnGoAwayEnd"; +} + +void FailingQuicHttpFrameDecoderListener::OnWindowUpdate( + const QuicHttpFrameHeader& header, + uint32_t increment) { + FAIL() << "OnWindowUpdate: " << header << "; increment=" << increment; +} + +void FailingQuicHttpFrameDecoderListener::OnAltSvcStart( + const QuicHttpFrameHeader& header, + size_t origin_length, + size_t value_length) { + FAIL() << "OnAltSvcStart: " << header << "; origin_length: " << origin_length + << "; value_length: " << value_length; +} + +void FailingQuicHttpFrameDecoderListener::OnAltSvcOriginData(const char* data, + size_t len) { + FAIL() << "OnAltSvcOriginData: len=" << len; +} + +void FailingQuicHttpFrameDecoderListener::OnAltSvcValueData(const char* data, + size_t len) { + FAIL() << "OnAltSvcValueData: len=" << len; +} + +void FailingQuicHttpFrameDecoderListener::OnAltSvcEnd() { + FAIL() << "OnAltSvcEnd"; +} + +void FailingQuicHttpFrameDecoderListener::OnUnknownStart( + const QuicHttpFrameHeader& header) { + FAIL() << "OnUnknownStart: " << header; +} + +void FailingQuicHttpFrameDecoderListener::OnUnknownPayload(const char* data, + size_t len) { + FAIL() << "OnUnknownPayload: len=" << len; +} + +void FailingQuicHttpFrameDecoderListener::OnUnknownEnd() { + FAIL() << "OnUnknownEnd"; +} + +void FailingQuicHttpFrameDecoderListener::OnPaddingTooLong( + const QuicHttpFrameHeader& header, + size_t missing_length) { + FAIL() << "OnPaddingTooLong: " << header + << "; missing_length: " << missing_length; +} + +void FailingQuicHttpFrameDecoderListener::OnFrameSizeError( + const QuicHttpFrameHeader& header) { + FAIL() << "OnFrameSizeError: " << header; +} + +LoggingQuicHttpFrameDecoderListener::LoggingQuicHttpFrameDecoderListener() + : wrapped_(nullptr) {} +LoggingQuicHttpFrameDecoderListener::LoggingQuicHttpFrameDecoderListener( + QuicHttpFrameDecoderListener* wrapped) + : wrapped_(wrapped) {} +LoggingQuicHttpFrameDecoderListener::~LoggingQuicHttpFrameDecoderListener() {} + +bool LoggingQuicHttpFrameDecoderListener::OnFrameHeader( + const QuicHttpFrameHeader& header) { + VLOG(1) << "OnFrameHeader: " << header; + if (wrapped_ != nullptr) { + return wrapped_->OnFrameHeader(header); + } + return true; +} + +void LoggingQuicHttpFrameDecoderListener::OnDataStart( + const QuicHttpFrameHeader& header) { + VLOG(1) << "OnDataStart: " << header; + if (wrapped_ != nullptr) { + wrapped_->OnDataStart(header); + } +} + +void LoggingQuicHttpFrameDecoderListener::OnDataPayload(const char* data, + size_t len) { + VLOG(1) << "OnDataPayload: len=" << len; + if (wrapped_ != nullptr) { + wrapped_->OnDataPayload(data, len); + } +} + +void LoggingQuicHttpFrameDecoderListener::OnDataEnd() { + VLOG(1) << "OnDataEnd"; + if (wrapped_ != nullptr) { + wrapped_->OnDataEnd(); + } +} + +void LoggingQuicHttpFrameDecoderListener::OnHeadersStart( + const QuicHttpFrameHeader& header) { + VLOG(1) << "OnHeadersStart: " << header; + if (wrapped_ != nullptr) { + wrapped_->OnHeadersStart(header); + } +} + +void LoggingQuicHttpFrameDecoderListener::OnHeadersPriority( + const QuicHttpPriorityFields& priority) { + VLOG(1) << "OnHeadersPriority: " << priority; + if (wrapped_ != nullptr) { + wrapped_->OnHeadersPriority(priority); + } +} + +void LoggingQuicHttpFrameDecoderListener::OnHpackFragment(const char* data, + size_t len) { + VLOG(1) << "OnHpackFragment: len=" << len; + if (wrapped_ != nullptr) { + wrapped_->OnHpackFragment(data, len); + } +} + +void LoggingQuicHttpFrameDecoderListener::OnHeadersEnd() { + VLOG(1) << "OnHeadersEnd"; + if (wrapped_ != nullptr) { + wrapped_->OnHeadersEnd(); + } +} + +void LoggingQuicHttpFrameDecoderListener::OnPriorityFrame( + const QuicHttpFrameHeader& header, + const QuicHttpPriorityFields& priority) { + VLOG(1) << "OnPriorityFrame: " << header << "; priority: " << priority; + if (wrapped_ != nullptr) { + wrapped_->OnPriorityFrame(header, priority); + } +} + +void LoggingQuicHttpFrameDecoderListener::OnContinuationStart( + const QuicHttpFrameHeader& header) { + VLOG(1) << "OnContinuationStart: " << header; + if (wrapped_ != nullptr) { + wrapped_->OnContinuationStart(header); + } +} + +void LoggingQuicHttpFrameDecoderListener::OnContinuationEnd() { + VLOG(1) << "OnContinuationEnd"; + if (wrapped_ != nullptr) { + wrapped_->OnContinuationEnd(); + } +} + +void LoggingQuicHttpFrameDecoderListener::OnPadLength(size_t trailing_length) { + VLOG(1) << "OnPadLength: trailing_length=" << trailing_length; + if (wrapped_ != nullptr) { + wrapped_->OnPadLength(trailing_length); + } +} + +void LoggingQuicHttpFrameDecoderListener::OnPadding(const char* padding, + size_t skipped_length) { + VLOG(1) << "OnPadding: skipped_length=" << skipped_length; + if (wrapped_ != nullptr) { + wrapped_->OnPadding(padding, skipped_length); + } +} + +void LoggingQuicHttpFrameDecoderListener::OnRstStream( + const QuicHttpFrameHeader& header, + QuicHttpErrorCode error_code) { + VLOG(1) << "OnRstStream: " << header << "; code=" << error_code; + if (wrapped_ != nullptr) { + wrapped_->OnRstStream(header, error_code); + } +} + +void LoggingQuicHttpFrameDecoderListener::OnSettingsStart( + const QuicHttpFrameHeader& header) { + VLOG(1) << "OnSettingsStart: " << header; + if (wrapped_ != nullptr) { + wrapped_->OnSettingsStart(header); + } +} + +void LoggingQuicHttpFrameDecoderListener::OnSetting( + const QuicHttpSettingFields& setting_fields) { + VLOG(1) << "OnSetting: " << setting_fields; + if (wrapped_ != nullptr) { + wrapped_->OnSetting(setting_fields); + } +} + +void LoggingQuicHttpFrameDecoderListener::OnSettingsEnd() { + VLOG(1) << "OnSettingsEnd"; + if (wrapped_ != nullptr) { + wrapped_->OnSettingsEnd(); + } +} + +void LoggingQuicHttpFrameDecoderListener::OnSettingsAck( + const QuicHttpFrameHeader& header) { + VLOG(1) << "OnSettingsAck: " << header; + if (wrapped_ != nullptr) { + wrapped_->OnSettingsAck(header); + } +} + +void LoggingQuicHttpFrameDecoderListener::OnPushPromiseStart( + const QuicHttpFrameHeader& header, + const QuicHttpPushPromiseFields& promise, + size_t total_padding_length) { + VLOG(1) << "OnPushPromiseStart: " << header << "; promise: " << promise + << "; total_padding_length: " << total_padding_length; + if (wrapped_ != nullptr) { + wrapped_->OnPushPromiseStart(header, promise, total_padding_length); + } +} + +void LoggingQuicHttpFrameDecoderListener::OnPushPromiseEnd() { + VLOG(1) << "OnPushPromiseEnd"; + if (wrapped_ != nullptr) { + wrapped_->OnPushPromiseEnd(); + } +} + +void LoggingQuicHttpFrameDecoderListener::OnPing( + const QuicHttpFrameHeader& header, + const QuicHttpPingFields& ping) { + VLOG(1) << "OnPing: " << header << "; ping: " << ping; + if (wrapped_ != nullptr) { + wrapped_->OnPing(header, ping); + } +} + +void LoggingQuicHttpFrameDecoderListener::OnPingAck( + const QuicHttpFrameHeader& header, + const QuicHttpPingFields& ping) { + VLOG(1) << "OnPingAck: " << header << "; ping: " << ping; + if (wrapped_ != nullptr) { + wrapped_->OnPingAck(header, ping); + } +} + +void LoggingQuicHttpFrameDecoderListener::OnGoAwayStart( + const QuicHttpFrameHeader& header, + const QuicHttpGoAwayFields& goaway) { + VLOG(1) << "OnGoAwayStart: " << header << "; goaway: " << goaway; + if (wrapped_ != nullptr) { + wrapped_->OnGoAwayStart(header, goaway); + } +} + +void LoggingQuicHttpFrameDecoderListener::OnGoAwayOpaqueData(const char* data, + size_t len) { + VLOG(1) << "OnGoAwayOpaqueData: len=" << len; + if (wrapped_ != nullptr) { + wrapped_->OnGoAwayOpaqueData(data, len); + } +} + +void LoggingQuicHttpFrameDecoderListener::OnGoAwayEnd() { + VLOG(1) << "OnGoAwayEnd"; + if (wrapped_ != nullptr) { + wrapped_->OnGoAwayEnd(); + } +} + +void LoggingQuicHttpFrameDecoderListener::OnWindowUpdate( + const QuicHttpFrameHeader& header, + uint32_t increment) { + VLOG(1) << "OnWindowUpdate: " << header << "; increment=" << increment; + if (wrapped_ != nullptr) { + wrapped_->OnWindowUpdate(header, increment); + } +} + +void LoggingQuicHttpFrameDecoderListener::OnAltSvcStart( + const QuicHttpFrameHeader& header, + size_t origin_length, + size_t value_length) { + VLOG(1) << "OnAltSvcStart: " << header << "; origin_length: " << origin_length + << "; value_length: " << value_length; + if (wrapped_ != nullptr) { + wrapped_->OnAltSvcStart(header, origin_length, value_length); + } +} + +void LoggingQuicHttpFrameDecoderListener::OnAltSvcOriginData(const char* data, + size_t len) { + VLOG(1) << "OnAltSvcOriginData: len=" << len; + if (wrapped_ != nullptr) { + wrapped_->OnAltSvcOriginData(data, len); + } +} + +void LoggingQuicHttpFrameDecoderListener::OnAltSvcValueData(const char* data, + size_t len) { + VLOG(1) << "OnAltSvcValueData: len=" << len; + if (wrapped_ != nullptr) { + wrapped_->OnAltSvcValueData(data, len); + } +} + +void LoggingQuicHttpFrameDecoderListener::OnAltSvcEnd() { + VLOG(1) << "OnAltSvcEnd"; + if (wrapped_ != nullptr) { + wrapped_->OnAltSvcEnd(); + } +} + +void LoggingQuicHttpFrameDecoderListener::OnUnknownStart( + const QuicHttpFrameHeader& header) { + VLOG(1) << "OnUnknownStart: " << header; + if (wrapped_ != nullptr) { + wrapped_->OnUnknownStart(header); + } +} + +void LoggingQuicHttpFrameDecoderListener::OnUnknownPayload(const char* data, + size_t len) { + VLOG(1) << "OnUnknownPayload: len=" << len; + if (wrapped_ != nullptr) { + wrapped_->OnUnknownPayload(data, len); + } +} + +void LoggingQuicHttpFrameDecoderListener::OnUnknownEnd() { + VLOG(1) << "OnUnknownEnd"; + if (wrapped_ != nullptr) { + wrapped_->OnUnknownEnd(); + } +} + +void LoggingQuicHttpFrameDecoderListener::OnPaddingTooLong( + const QuicHttpFrameHeader& header, + size_t missing_length) { + VLOG(1) << "OnPaddingTooLong: " << header + << "; missing_length: " << missing_length; + if (wrapped_ != nullptr) { + wrapped_->OnPaddingTooLong(header, missing_length); + } +} + +void LoggingQuicHttpFrameDecoderListener::OnFrameSizeError( + const QuicHttpFrameHeader& header) { + VLOG(1) << "OnFrameSizeError: " << header; + if (wrapped_ != nullptr) { + wrapped_->OnFrameSizeError(header); + } +} + +} // namespace net
diff --git a/net/quic/http/decoder/quic_http_frame_decoder_listener_test_util.h b/net/quic/http/decoder/quic_http_frame_decoder_listener_test_util.h new file mode 100644 index 0000000..54a9c26 --- /dev/null +++ b/net/quic/http/decoder/quic_http_frame_decoder_listener_test_util.h
@@ -0,0 +1,146 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_HTTP_DECODER_QUIC_HTTP_FRAME_DECODER_LISTENER_TEST_UTIL_H_ +#define NET_QUIC_HTTP_DECODER_QUIC_HTTP_FRAME_DECODER_LISTENER_TEST_UTIL_H_ + +#include <stddef.h> + +#include <cstdint> + +#include "net/quic/http/decoder/quic_http_frame_decoder_listener.h" +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/quic_http_structures.h" + +namespace net { + +// Fail if any of the methods are called. Allows a test to override only the +// expected calls. +class FailingQuicHttpFrameDecoderListener + : public QuicHttpFrameDecoderListener { + public: + FailingQuicHttpFrameDecoderListener(); + ~FailingQuicHttpFrameDecoderListener() override; + + // TODO(jamessynge): Remove OnFrameHeader once done with supporting + // SpdyFramer's exact states. + bool OnFrameHeader(const QuicHttpFrameHeader& header) override; + void OnDataStart(const QuicHttpFrameHeader& header) override; + void OnDataPayload(const char* data, size_t len) override; + void OnDataEnd() override; + void OnHeadersStart(const QuicHttpFrameHeader& header) override; + void OnHeadersPriority(const QuicHttpPriorityFields& priority) override; + void OnHpackFragment(const char* data, size_t len) override; + void OnHeadersEnd() override; + void OnPriorityFrame(const QuicHttpFrameHeader& header, + const QuicHttpPriorityFields& priority) override; + void OnContinuationStart(const QuicHttpFrameHeader& header) override; + void OnContinuationEnd() override; + void OnPadLength(size_t trailing_length) override; + void OnPadding(const char* padding, size_t skipped_length) override; + void OnRstStream(const QuicHttpFrameHeader& header, + QuicHttpErrorCode error_code) override; + void OnSettingsStart(const QuicHttpFrameHeader& header) override; + void OnSetting(const QuicHttpSettingFields& setting_fields) override; + void OnSettingsEnd() override; + void OnSettingsAck(const QuicHttpFrameHeader& header) override; + void OnPushPromiseStart(const QuicHttpFrameHeader& header, + const QuicHttpPushPromiseFields& promise, + size_t total_padding_length) override; + void OnPushPromiseEnd() override; + void OnPing(const QuicHttpFrameHeader& header, + const QuicHttpPingFields& ping) override; + void OnPingAck(const QuicHttpFrameHeader& header, + const QuicHttpPingFields& ping) override; + void OnGoAwayStart(const QuicHttpFrameHeader& header, + const QuicHttpGoAwayFields& goaway) override; + void OnGoAwayOpaqueData(const char* data, size_t len) override; + void OnGoAwayEnd() override; + void OnWindowUpdate(const QuicHttpFrameHeader& header, + uint32_t increment) override; + void OnAltSvcStart(const QuicHttpFrameHeader& header, + size_t origin_length, + size_t value_length) override; + void OnAltSvcOriginData(const char* data, size_t len) override; + void OnAltSvcValueData(const char* data, size_t len) override; + void OnAltSvcEnd() override; + void OnUnknownStart(const QuicHttpFrameHeader& header) override; + void OnUnknownPayload(const char* data, size_t len) override; + void OnUnknownEnd() override; + void OnPaddingTooLong(const QuicHttpFrameHeader& header, + size_t missing_length) override; + void OnFrameSizeError(const QuicHttpFrameHeader& header) override; + + private: + void EnsureNotAbstract() { FailingQuicHttpFrameDecoderListener instance; } +}; + +// VLOG's all the calls it receives, and forwards those calls to an optional +// listener. +class LoggingQuicHttpFrameDecoderListener + : public QuicHttpFrameDecoderListener { + public: + LoggingQuicHttpFrameDecoderListener(); + explicit LoggingQuicHttpFrameDecoderListener( + QuicHttpFrameDecoderListener* wrapped); + ~LoggingQuicHttpFrameDecoderListener() override; + + // TODO(jamessynge): Remove OnFrameHeader once done with supporting + // SpdyFramer's exact states. + bool OnFrameHeader(const QuicHttpFrameHeader& header) override; + void OnDataStart(const QuicHttpFrameHeader& header) override; + void OnDataPayload(const char* data, size_t len) override; + void OnDataEnd() override; + void OnHeadersStart(const QuicHttpFrameHeader& header) override; + void OnHeadersPriority(const QuicHttpPriorityFields& priority) override; + void OnHpackFragment(const char* data, size_t len) override; + void OnHeadersEnd() override; + void OnPriorityFrame(const QuicHttpFrameHeader& header, + const QuicHttpPriorityFields& priority) override; + void OnContinuationStart(const QuicHttpFrameHeader& header) override; + void OnContinuationEnd() override; + void OnPadLength(size_t trailing_length) override; + void OnPadding(const char* padding, size_t skipped_length) override; + void OnRstStream(const QuicHttpFrameHeader& header, + QuicHttpErrorCode error_code) override; + void OnSettingsStart(const QuicHttpFrameHeader& header) override; + void OnSetting(const QuicHttpSettingFields& setting_fields) override; + void OnSettingsEnd() override; + void OnSettingsAck(const QuicHttpFrameHeader& header) override; + void OnPushPromiseStart(const QuicHttpFrameHeader& header, + const QuicHttpPushPromiseFields& promise, + size_t total_padding_length) override; + void OnPushPromiseEnd() override; + void OnPing(const QuicHttpFrameHeader& header, + const QuicHttpPingFields& ping) override; + void OnPingAck(const QuicHttpFrameHeader& header, + const QuicHttpPingFields& ping) override; + void OnGoAwayStart(const QuicHttpFrameHeader& header, + const QuicHttpGoAwayFields& goaway) override; + void OnGoAwayOpaqueData(const char* data, size_t len) override; + void OnGoAwayEnd() override; + void OnWindowUpdate(const QuicHttpFrameHeader& header, + uint32_t increment) override; + void OnAltSvcStart(const QuicHttpFrameHeader& header, + size_t origin_length, + size_t value_length) override; + void OnAltSvcOriginData(const char* data, size_t len) override; + void OnAltSvcValueData(const char* data, size_t len) override; + void OnAltSvcEnd() override; + void OnUnknownStart(const QuicHttpFrameHeader& header) override; + void OnUnknownPayload(const char* data, size_t len) override; + void OnUnknownEnd() override; + void OnPaddingTooLong(const QuicHttpFrameHeader& header, + size_t missing_length) override; + void OnFrameSizeError(const QuicHttpFrameHeader& header) override; + + private: + void EnsureNotAbstract() { LoggingQuicHttpFrameDecoderListener instance; } + + QuicHttpFrameDecoderListener* wrapped_; +}; + +} // namespace net + +#endif // NET_QUIC_HTTP_DECODER_QUIC_HTTP_FRAME_DECODER_LISTENER_TEST_UTIL_H_
diff --git a/net/quic/http/decoder/quic_http_frame_decoder_state.cc b/net/quic/http/decoder/quic_http_frame_decoder_state.cc new file mode 100644 index 0000000..56c416ed --- /dev/null +++ b/net/quic/http/decoder/quic_http_frame_decoder_state.cc
@@ -0,0 +1,82 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/quic_http_frame_decoder_state.h" + +namespace net { + +QuicHttpDecodeStatus QuicHttpFrameDecoderState::ReadPadLength( + QuicHttpDecodeBuffer* db, + bool report_pad_length) { + DVLOG(2) << "ReadPadLength db->Remaining=" << db->Remaining() + << "; payload_length=" << frame_header().payload_length; + DCHECK(IsPaddable()); + DCHECK(frame_header().IsPadded()); + + // Pad Length is always at the start of the frame, so remaining_payload_ + // should equal payload_length at this point. + const uint32_t total_payload = frame_header().payload_length; + DCHECK_EQ(total_payload, remaining_payload_); + DCHECK_EQ(0u, remaining_padding_); + + if (db->HasData()) { + const uint32_t pad_length = db->DecodeUInt8(); + const uint32_t total_padding = pad_length + 1; + if (total_padding <= total_payload) { + remaining_padding_ = pad_length; + remaining_payload_ = total_payload - total_padding; + if (report_pad_length) { + listener()->OnPadLength(pad_length); + } + return QuicHttpDecodeStatus::kDecodeDone; + } + const uint32_t missing_length = total_padding - total_payload; + // To allow for the possibility of recovery, record the number of + // remaining bytes of the frame's payload (invalid though it is) + // in remaining_payload_. + remaining_payload_ = total_payload - 1; // 1 for sizeof(Pad Length). + remaining_padding_ = 0; + listener()->OnPaddingTooLong(frame_header(), missing_length); + return QuicHttpDecodeStatus::kDecodeError; + } + + if (total_payload == 0) { + remaining_payload_ = 0; + remaining_padding_ = 0; + listener()->OnPaddingTooLong(frame_header(), 1); + return QuicHttpDecodeStatus::kDecodeError; + } + // Need to wait for another buffer. + return QuicHttpDecodeStatus::kDecodeInProgress; +} + +bool QuicHttpFrameDecoderState::SkipPadding(QuicHttpDecodeBuffer* db) { + DVLOG(2) << "SkipPadding remaining_padding_=" << remaining_padding_ + << ", db->Remaining=" << db->Remaining() + << ", header: " << frame_header(); + DCHECK_EQ(remaining_payload_, 0u); + DCHECK(IsPaddable()) << "header: " << frame_header(); + DCHECK_GE(remaining_padding_, 0u); + DCHECK(remaining_padding_ == 0 || frame_header().IsPadded()) + << "remaining_padding_=" << remaining_padding_ + << ", header: " << frame_header(); + const size_t avail = AvailablePadding(db); + if (avail > 0) { + listener()->OnPadding(db->cursor(), avail); + db->AdvanceCursor(avail); + remaining_padding_ -= avail; + } + return remaining_padding_ == 0; +} + +QuicHttpDecodeStatus QuicHttpFrameDecoderState::ReportFrameSizeError() { + DVLOG(2) << "QuicHttpFrameDecoderState::ReportFrameSizeError: " + << " remaining_payload_=" << remaining_payload_ + << "; remaining_padding_=" << remaining_padding_ + << ", header: " << frame_header(); + listener()->OnFrameSizeError(frame_header()); + return QuicHttpDecodeStatus::kDecodeError; +} + +} // namespace net
diff --git a/net/quic/http/decoder/quic_http_frame_decoder_state.h b/net/quic/http/decoder/quic_http_frame_decoder_state.h new file mode 100644 index 0000000..beaa39d --- /dev/null +++ b/net/quic/http/decoder/quic_http_frame_decoder_state.h
@@ -0,0 +1,259 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_HTTP_DECODER_QUIC_HTTP_FRAME_DECODER_STATE_H_ +#define NET_QUIC_HTTP_DECODER_QUIC_HTTP_FRAME_DECODER_STATE_H_ + +// QuicHttpFrameDecoderState provides state and behaviors in support of decoding +// the common frame header and the payload of all frame types. +// It is an input to all of the payload decoders. + +// TODO(jamessynge): Since QuicHttpFrameDecoderState has far more than state in +// it, rename to FrameDecoderHelper, or similar. + +#include <stddef.h> + +#include <cstdint> + +#include "base/logging.h" +#include "net/quic/http/decoder/quic_http_decode_buffer.h" +#include "net/quic/http/decoder/quic_http_decode_status.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_listener.h" +#include "net/quic/http/decoder/quic_http_structure_decoder.h" +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/quic_http_structures.h" +#include "net/quic/platform/api/quic_export.h" + +namespace net { +namespace test { +class QuicHttpFrameDecoderStatePeer; +} // namespace test + +class QUIC_EXPORT_PRIVATE QuicHttpFrameDecoderState { + public: + QuicHttpFrameDecoderState() {} + + // Sets the listener which the decoders should call as they decode HTTP/2 + // frames. The listener can be changed at any time, which allows for replacing + // it with a no-op listener when an error is detected, either by the payload + // decoder (OnPaddingTooLong or OnFrameSizeError) or by the "real" listener. + // That in turn allows us to define QuicHttpFrameDecoderListener such that all + // methods have return type void, with no direct way to indicate whether the + // decoder should stop, and to eliminate from the decoder all checks of the + // return value. Instead the listener/caller can simply replace the current + // listener with a no-op listener implementation. + // TODO(jamessynge): Make set_listener private as only QuicHttpFrameDecoder + // and tests need to set it, so it doesn't need to be public. + void set_listener(QuicHttpFrameDecoderListener* listener) { + listener_ = listener; + } + QuicHttpFrameDecoderListener* listener() const { return listener_; } + + // The most recently decoded frame header. + const QuicHttpFrameHeader& frame_header() const { return frame_header_; } + + // Decode a structure in the payload, adjusting remaining_payload_ to account + // for the consumed portion of the payload. Returns kDecodeDone when fully + // decoded, kDecodeError if it ran out of payload before decoding completed, + // and kDecodeInProgress if the decode buffer didn't have enough of the + // remaining payload. + template <class S> + QuicHttpDecodeStatus StartDecodingStructureInPayload( + S* out, + QuicHttpDecodeBuffer* db) { + DVLOG(2) << __func__ << "\n\tdb->Remaining=" << db->Remaining() + << "\n\tremaining_payload_=" << remaining_payload_ + << "\n\tneed=" << S::EncodedSize(); + QuicHttpDecodeStatus status = + structure_decoder_.Start(out, db, &remaining_payload_); + if (status != QuicHttpDecodeStatus::kDecodeError) { + return status; + } + DVLOG(2) << "StartDecodingStructureInPayload: detected frame size error"; + return ReportFrameSizeError(); + } + + // Resume decoding of a structure that has been split across buffers, + // adjusting remaining_payload_ to account for the consumed portion of + // the payload. Returns values are as for StartDecodingStructureInPayload. + template <class S> + QuicHttpDecodeStatus ResumeDecodingStructureInPayload( + S* out, + QuicHttpDecodeBuffer* db) { + DVLOG(2) << __func__ << "\n\tdb->Remaining=" << db->Remaining() + << "\n\tremaining_payload_=" << remaining_payload_; + if (structure_decoder_.Resume(out, db, &remaining_payload_)) { + return QuicHttpDecodeStatus::kDecodeDone; + } else if (remaining_payload_ > 0) { + return QuicHttpDecodeStatus::kDecodeInProgress; + } else { + DVLOG(2) << "ResumeDecodingStructureInPayload: detected frame size error"; + return ReportFrameSizeError(); + } + } + + // Initializes the two remaining* fields, which is needed if the frame's + // payload is split across buffers, or the decoder calls ReadPadLength or + // StartDecodingStructureInPayload, and of course the methods below which + // read those fields, as their names imply. + void InitializeRemainders() { + remaining_payload_ = frame_header().payload_length; + // Note that remaining_total_payload() relies on remaining_padding_ being + // zero for frames that have no padding. + remaining_padding_ = 0; + } + + // Returns the number of bytes of the frame's payload that remain to be + // decoded, including any trailing padding. This method must only be called + // after the variables have been initialized, which in practice means once a + // payload decoder has called InitializeRemainders and/or ReadPadLength. + size_t remaining_total_payload() const { + DCHECK(IsPaddable() || remaining_padding_ == 0) << frame_header(); + return remaining_payload_ + remaining_padding_; + } + + // Returns the number of bytes of the frame's payload that remain to be + // decoded, excluding any trailing padding. This method must only be called + // after the variable has been initialized, which in practice means once a + // payload decoder has called InitializeRemainders; ReadPadLength will deduct + // the total number of padding bytes from remaining_payload_, including the + // size of the Pad Length field itself (1 byte). + size_t remaining_payload() const { return remaining_payload_; } + + // Returns the number of bytes of the frame's payload that remain to be + // decoded, including any trailing padding. This method must only be called if + // the frame type allows padding, and after the variable has been initialized, + // which in practice means once a payload decoder has called + // InitializeRemainders and/or ReadPadLength. + size_t remaining_payload_and_padding() const { + DCHECK(IsPaddable()) << frame_header(); + return remaining_payload_ + remaining_padding_; + } + + // Returns the number of bytes of trailing padding after the payload that + // remain to be decoded. This method must only be called if the frame type + // allows padding, and after the variable has been initialized, which in + // practice means once a payload decoder has called InitializeRemainders, + // and isn't set to a non-zero value until ReadPadLength has been called. + uint32_t remaining_padding() const { + DCHECK(IsPaddable()) << frame_header(); + return remaining_padding_; + } + + // Returns the amount of trailing padding after the payload that remains to be + // decoded. + uint32_t remaining_padding_for_test() const { return remaining_padding_; } + + // How many bytes of the remaining payload are in db? + size_t AvailablePayload(QuicHttpDecodeBuffer* db) const { + return db->MinLengthRemaining(remaining_payload_); + } + + // How many bytes of the remaining payload and padding are in db? + // Call only for frames whose type is paddable. + size_t AvailablePayloadAndPadding(QuicHttpDecodeBuffer* db) const { + DCHECK(IsPaddable()) << frame_header(); + return db->MinLengthRemaining(remaining_payload_ + remaining_padding_); + } + + // How many bytes of the padding that have not yet been skipped are in db? + // Call only after remaining_padding_ has been set (for padded frames), or + // been cleared (for unpadded frames); and after all of the non-padding + // payload has been decoded. + size_t AvailablePadding(QuicHttpDecodeBuffer* db) const { + DCHECK(IsPaddable()) << frame_header(); + DCHECK_EQ(remaining_payload_, 0u); + return db->MinLengthRemaining(remaining_padding_); + } + + // Reduces remaining_payload_ by amount. To be called by a payload decoder + // after it has passed a variable length portion of the payload to the + // listener; remaining_payload_ will be automatically reduced when fixed + // size structures and padding, including the Pad Length field, are decoded. + void ConsumePayload(size_t amount) { + DCHECK_LE(amount, remaining_payload_); + remaining_payload_ -= amount; + } + + // Reads the Pad Length field into remaining_padding_, and appropriately sets + // remaining_payload_. When present, the Pad Length field is always the first + // field in the payload, which this method relies on so that the caller need + // not set remaining_payload_ before calling this method. + // If report_pad_length is true, calls the listener's OnPadLength method when + // it decodes the Pad Length field. + // Returns kDecodeDone if the decode buffer was not empty (i.e. because the + // field is only a single byte long, it can always be decoded if the buffer is + // not empty). + // Returns kDecodeError if the buffer is empty because the frame has no + // payload (i.e. payload_length() == 0). + // Returns kDecodeInProgress if the buffer is empty but the frame has a + // payload. + QuicHttpDecodeStatus ReadPadLength(QuicHttpDecodeBuffer* db, + bool report_pad_length); + + // Skip the trailing padding bytes; only call once remaining_payload_==0. + // Returns true when the padding has been skipped. + // Does NOT check that the padding is all zeroes. + bool SkipPadding(QuicHttpDecodeBuffer* db); + + // Calls the listener's OnFrameSizeError method and returns kDecodeError. + QuicHttpDecodeStatus ReportFrameSizeError(); + + private: + friend class QuicHttpFrameDecoder; + friend class test::QuicHttpFrameDecoderStatePeer; + + // Starts the decoding of a common frame header. Returns true if completed the + // decoding, false if the decode buffer didn't have enough data in it, in + // which case the decode buffer will have been drained and the caller should + // call ResumeDecodingFrameHeader when more data is available. This is called + // from QuicHttpFrameDecoder, a friend class. + bool StartDecodingFrameHeader(QuicHttpDecodeBuffer* db) { + return structure_decoder_.Start(&frame_header_, db); + } + + // Resumes decoding the common frame header after the preceding call to + // StartDecodingFrameHeader returned false, as did any subsequent calls to + // ResumeDecodingFrameHeader. This is called from QuicHttpFrameDecoder, + // a friend class. + bool ResumeDecodingFrameHeader(QuicHttpDecodeBuffer* db) { + return structure_decoder_.Resume(&frame_header_, db); + } + + // Clear any of the flags in the frame header that aren't set in valid_flags. + void RetainFlags(uint8_t valid_flags) { + frame_header_.RetainFlags(valid_flags); + } + + // Clear all of the flags in the frame header; for use with frame types that + // don't define any flags, such as WINDOW_UPDATE. + void ClearFlags() { frame_header_.flags = QuicHttpFrameFlag(); } + + // Returns true if the type of frame being decoded can have padding. + bool IsPaddable() const { + return frame_header().type == QuicHttpFrameType::DATA || + frame_header().type == QuicHttpFrameType::HEADERS || + frame_header().type == QuicHttpFrameType::PUSH_PROMISE; + } + + QuicHttpFrameDecoderListener* listener_ = nullptr; + QuicHttpFrameHeader frame_header_; + + // Number of bytes remaining to be decoded, if set; does not include the + // trailing padding once the length of padding has been determined. + // See ReadPadLength. + uint32_t remaining_payload_; + + // The amount of trailing padding after the payload that remains to be + // decoded. See ReadPadLength. + uint32_t remaining_padding_; + + // Generic decoder of structures, which takes care of buffering the needed + // bytes if the encoded structure is split across decode buffers. + QuicHttpStructureDecoder structure_decoder_; +}; + +} // namespace net + +#endif // NET_QUIC_HTTP_DECODER_QUIC_HTTP_FRAME_DECODER_STATE_H_
diff --git a/net/quic/http/decoder/quic_http_frame_decoder_state_test_util.cc b/net/quic/http/decoder/quic_http_frame_decoder_state_test_util.cc new file mode 100644 index 0000000..0c96d98b --- /dev/null +++ b/net/quic/http/decoder/quic_http_frame_decoder_state_test_util.cc
@@ -0,0 +1,35 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/quic_http_frame_decoder_state_test_util.h" + +#include "base/logging.h" +#include "net/quic/http/decoder/quic_http_structure_decoder_test_util.h" +#include "net/quic/http/quic_http_structures.h" +#include "net/quic/http/quic_http_structures_test_util.h" +#include "net/quic/http/tools/quic_http_random_decoder_test.h" + +namespace net { +namespace test { + +// static +void QuicHttpFrameDecoderStatePeer::Randomize(QuicHttpFrameDecoderState* p, + QuicTestRandomBase* rng) { + VLOG(1) << "QuicHttpFrameDecoderStatePeer::Randomize"; + ::net::test::Randomize(&p->frame_header_, rng); + p->remaining_payload_ = rng->Rand32(); + p->remaining_padding_ = rng->Rand32(); + QuicHttpStructureDecoderPeer::Randomize(&p->structure_decoder_, rng); +} + +// static +void QuicHttpFrameDecoderStatePeer::set_frame_header( + const QuicHttpFrameHeader& header, + QuicHttpFrameDecoderState* p) { + VLOG(1) << "QuicHttpFrameDecoderStatePeer::set_frame_header " << header; + p->frame_header_ = header; +} + +} // namespace test +} // namespace net
diff --git a/net/quic/http/decoder/quic_http_frame_decoder_state_test_util.h b/net/quic/http/decoder/quic_http_frame_decoder_state_test_util.h new file mode 100644 index 0000000..58d3296 --- /dev/null +++ b/net/quic/http/decoder/quic_http_frame_decoder_state_test_util.h
@@ -0,0 +1,36 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_HTTP_DECODER_QUIC_HTTP_FRAME_DECODER_STATE_TEST_UTIL_H_ +#define NET_QUIC_HTTP_DECODER_QUIC_HTTP_FRAME_DECODER_STATE_TEST_UTIL_H_ + +#include "net/quic/http/decoder/quic_http_frame_decoder_state.h" +#include "net/quic/http/quic_http_structures.h" +#include "net/quic/http/tools/quic_http_random_decoder_test.h" + +namespace net { +namespace test { + +class QuicHttpFrameDecoderStatePeer { + public: + // Randomizes (i.e. corrupts) the fields of the QuicHttpFrameDecoderState. + // QuicHttpPayloadDecoderBaseTest::StartDecoding calls this before passing the + // first decode buffer to the payload decoder, which increases the likelihood + // of detecting any use of prior states of the decoder on the decoding of + // future payloads. + static void Randomize(QuicHttpFrameDecoderState* p, QuicTestRandomBase* rng); + + // Inject a frame header into the QuicHttpFrameDecoderState. + // QuicHttpPayloadDecoderBaseTest::StartDecoding calls this just after calling + // Randomize (above), to simulate a full frame decoder having just finished + // decoding the common frame header and then calling the appropriate payload + // decoder based on the frame type in that frame header. + static void set_frame_header(const QuicHttpFrameHeader& header, + QuicHttpFrameDecoderState* p); +}; + +} // namespace test +} // namespace net + +#endif // NET_QUIC_HTTP_DECODER_QUIC_HTTP_FRAME_DECODER_STATE_TEST_UTIL_H_
diff --git a/net/quic/http/decoder/quic_http_frame_decoder_test.cc b/net/quic/http/decoder/quic_http_frame_decoder_test.cc new file mode 100644 index 0000000..6bb0733 --- /dev/null +++ b/net/quic/http/decoder/quic_http_frame_decoder_test.cc
@@ -0,0 +1,939 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/quic_http_frame_decoder.h" + +// Tests of QuicHttpFrameDecoder. + +#include <vector> + +#include "base/logging.h" +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/test_tools/quic_http_frame_parts.h" +#include "net/quic/http/test_tools/quic_http_frame_parts_collector_listener.h" +#include "net/quic/http/tools/quic_http_random_decoder_test.h" +#include "net/quic/platform/api/quic_reconstruct_object.h" +#include "net/quic/platform/api/quic_string.h" +#include "net/quic/platform/api/quic_string_piece.h" +#include "testing/gtest/include/gtest/gtest.h" + +using ::testing::AssertionResult; +using ::testing::AssertionSuccess; + +namespace net { +namespace test { +class QuicHttpFrameDecoderPeer { + public: + static size_t remaining_total_payload(QuicHttpFrameDecoder* decoder) { + return decoder->frame_decoder_state_.remaining_total_payload(); + } +}; + +namespace { + +class QuicHttpFrameDecoderTest : public QuicHttpRandomDecoderTest { + protected: + void SetUp() override { + // On any one run of this suite, we'll always choose the same value for + // use_default_reconstruct_ because the random seed is the same for each + // test case, but across runs the random seed changes. + use_default_reconstruct_ = Random().OneIn(2); + } + + QuicHttpDecodeStatus StartDecoding(QuicHttpDecodeBuffer* db) override { + DVLOG(2) << "StartDecoding, db->Remaining=" << db->Remaining(); + collector_.Reset(); + PrepareDecoder(); + + QuicHttpDecodeStatus status = decoder_.DecodeFrame(db); + if (status != QuicHttpDecodeStatus::kDecodeInProgress) { + // Keep track of this so that a concrete test can verify that both fast + // and slow decoding paths have been tested. + ++fast_decode_count_; + if (status == QuicHttpDecodeStatus::kDecodeError) { + ConfirmDiscardsRemainingPayload(); + } + } + return status; + } + + QuicHttpDecodeStatus ResumeDecoding(QuicHttpDecodeBuffer* db) override { + DVLOG(2) << "ResumeDecoding, db->Remaining=" << db->Remaining(); + QuicHttpDecodeStatus status = decoder_.DecodeFrame(db); + if (status != QuicHttpDecodeStatus::kDecodeInProgress) { + // Keep track of this so that a concrete test can verify that both fast + // and slow decoding paths have been tested. + ++slow_decode_count_; + if (status == QuicHttpDecodeStatus::kDecodeError) { + ConfirmDiscardsRemainingPayload(); + } + } + return status; + } + + // When an error is returned, the decoder is in state kDiscardPayload, and + // stays there until the remaining bytes of the frame's payload have been + // skipped over. There are no callbacks for this situation. + void ConfirmDiscardsRemainingPayload() { + ASSERT_TRUE(decoder_.IsDiscardingPayload()); + size_t remaining = + QuicHttpFrameDecoderPeer::remaining_total_payload(&decoder_); + // The decoder will discard the remaining bytes, but not go beyond that, + // which these conditions verify. + size_t extra = 10; + QuicString junk(remaining + extra, '0'); + QuicHttpDecodeBuffer tmp(junk); + EXPECT_EQ(QuicHttpDecodeStatus::kDecodeDone, decoder_.DecodeFrame(&tmp)); + EXPECT_EQ(remaining, tmp.Offset()); + EXPECT_EQ(extra, tmp.Remaining()); + EXPECT_FALSE(decoder_.IsDiscardingPayload()); + } + + void PrepareDecoder() { + // Save and restore the maximum_payload_size when reconstructing + // the decoder. + size_t maximum_payload_size = decoder_.maximum_payload_size(); + + // Alternate which constructor is used. + if (use_default_reconstruct_) { + QuicDefaultReconstructObject(&decoder_, RandomPtr()); + decoder_.set_listener(&collector_); + } else { + QuicReconstructObject(&decoder_, RandomPtr(), &collector_); + } + decoder_.set_maximum_payload_size(maximum_payload_size); + + use_default_reconstruct_ = !use_default_reconstruct_; + } + + void ResetDecodeSpeedCounters() { + fast_decode_count_ = 0; + slow_decode_count_ = 0; + } + + AssertionResult VerifyCollected(const QuicHttpFrameParts& expected) { + VERIFY_FALSE(collector_.IsInProgress()); + VERIFY_EQ(1u, collector_.size()); + VERIFY_AND_RETURN_SUCCESS(expected.VerifyEquals(*collector_.frame(0))); + } + + AssertionResult DecodePayloadAndValidateSeveralWays( + QuicStringPiece payload, + const Validator& validator) { + QuicHttpDecodeBuffer db(payload); + bool start_decoding_requires_non_empty = false; + return DecodeAndValidateSeveralWays(&db, start_decoding_requires_non_empty, + validator); + } + + // Decode one frame's payload and confirm that the listener recorded the + // expected QuicHttpFrameParts instance, and only one QuicHttpFrameParts + // instance. The payload will be decoded several times with different + // partitionings of the payload, and after each the validator will be called. + AssertionResult DecodePayloadAndValidateSeveralWays( + QuicStringPiece payload, + const QuicHttpFrameParts& expected) { + auto validator = [&expected, this]( + const QuicHttpDecodeBuffer& input, + QuicHttpDecodeStatus status) -> AssertionResult { + VERIFY_EQ(status, QuicHttpDecodeStatus::kDecodeDone); + VERIFY_AND_RETURN_SUCCESS(VerifyCollected(expected)); + }; + ResetDecodeSpeedCounters(); + VERIFY_SUCCESS(DecodePayloadAndValidateSeveralWays( + payload, ValidateDoneAndEmpty(validator))); + VERIFY_GT(fast_decode_count_, 0u); + VERIFY_GT(slow_decode_count_, 0u); + + // Repeat with more input; it should stop without reading that input. + QuicString next_frame = Random().RandString(10); + QuicString input(payload); + input += next_frame; + + ResetDecodeSpeedCounters(); + VERIFY_SUCCESS(DecodePayloadAndValidateSeveralWays( + payload, ValidateDoneAndOffset(payload.size(), validator))); + VERIFY_GT(fast_decode_count_, 0u); + VERIFY_GT(slow_decode_count_, 0u); + + return AssertionSuccess(); + } + + template <size_t N> + AssertionResult DecodePayloadAndValidateSeveralWays( + const char (&buf)[N], + const QuicHttpFrameParts& expected) { + return DecodePayloadAndValidateSeveralWays(QuicStringPiece(buf, N), + expected); + } + + template <size_t N> + AssertionResult DecodePayloadAndValidateSeveralWays( + const char (&buf)[N], + const QuicHttpFrameHeader& header) { + return DecodePayloadAndValidateSeveralWays(QuicStringPiece(buf, N), + QuicHttpFrameParts(header)); + } + + template <size_t N> + AssertionResult DecodePayloadExpectingError( + const char (&buf)[N], + const QuicHttpFrameParts& expected) { + auto validator = [&expected, this]( + const QuicHttpDecodeBuffer& input, + QuicHttpDecodeStatus status) -> AssertionResult { + VERIFY_EQ(status, QuicHttpDecodeStatus::kDecodeError); + VERIFY_AND_RETURN_SUCCESS(VerifyCollected(expected)); + }; + ResetDecodeSpeedCounters(); + EXPECT_TRUE( + DecodePayloadAndValidateSeveralWays(ToStringPiece(buf), validator)); + EXPECT_GT(fast_decode_count_, 0u); + EXPECT_GT(slow_decode_count_, 0u); + return AssertionSuccess(); + } + + template <size_t N> + AssertionResult DecodePayloadExpectingFrameSizeError( + const char (&buf)[N], + QuicHttpFrameParts expected) { + expected.has_frame_size_error = true; + VERIFY_AND_RETURN_SUCCESS(DecodePayloadExpectingError(buf, expected)); + } + + template <size_t N> + AssertionResult DecodePayloadExpectingFrameSizeError( + const char (&buf)[N], + const QuicHttpFrameHeader& header) { + return DecodePayloadExpectingFrameSizeError(buf, + QuicHttpFrameParts(header)); + } + + // Count of payloads that are fully decoded by StartDecodingPayload or for + // which an error was detected by StartDecodingPayload. + size_t fast_decode_count_ = 0; + + // Count of payloads that required calling ResumeDecodingPayload in order to + // decode completely, or for which an error was detected by + // ResumeDecodingPayload. + size_t slow_decode_count_ = 0; + + QuicHttpFramePartsCollectorListener collector_; + QuicHttpFrameDecoder decoder_; + bool use_default_reconstruct_; +}; + +//////////////////////////////////////////////////////////////////////////////// +// Tests that pass the minimum allowed size for the frame type, which is often +// empty. The tests are in order by frame type value (i.e. 0 for DATA frames). + +TEST_F(QuicHttpFrameDecoderTest, DataEmpty) { + const char kFrameData[] = { + 0x00, 0x00, 0x00, // Payload length: 0 + 0x00, // DATA + 0x00, // Flags: none + 0x00, 0x00, 0x00, 0x00, // Stream ID: 0 (invalid but unchecked here) + }; + QuicHttpFrameHeader header(0, QuicHttpFrameType::DATA, 0, 0); + QuicHttpFrameParts expected(header, ""); + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); +} + +TEST_F(QuicHttpFrameDecoderTest, HeadersEmpty) { + const char kFrameData[] = { + 0x00, 0x00, 0x00, // Payload length: 0 + 0x01, // HEADERS + 0x00, // Flags: none + 0x00, 0x00, 0x00, 0x01, // Stream ID: 0 (REQUIRES ID) + }; + QuicHttpFrameHeader header(0, QuicHttpFrameType::HEADERS, 0, 1); + QuicHttpFrameParts expected(header, ""); + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); +} + +TEST_F(QuicHttpFrameDecoderTest, Priority) { + const char kFrameData[] = { + 0x00, 0x00, 0x05, // Length: 5 + 0x02, // Type: QUIC_HTTP_PRIORITY + 0x00, // Flags: none + 0x00, 0x00, 0x00, 0x02, // Stream: 2 + 0x80u, 0x00, 0x00, 0x01, // Parent: 1 (Exclusive) + 0x10, // Weight: 17 + }; + QuicHttpFrameHeader header(5, QuicHttpFrameType::QUIC_HTTP_PRIORITY, 0, 2); + QuicHttpFrameParts expected(header); + expected.opt_priority = QuicHttpPriorityFields(1, 17, true); + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); +} + +TEST_F(QuicHttpFrameDecoderTest, RstStream) { + const char kFrameData[] = { + 0x00, 0x00, 0x04, // Length: 4 + 0x03, // Type: RST_STREAM + 0x00, // Flags: none + 0x00, 0x00, 0x00, 0x01, // Stream: 1 + 0x00, 0x00, 0x00, 0x01, // Error: PROTOCOL_ERROR + }; + QuicHttpFrameHeader header(4, QuicHttpFrameType::RST_STREAM, 0, 1); + QuicHttpFrameParts expected(header); + expected.opt_rst_stream_error_code = QuicHttpErrorCode::PROTOCOL_ERROR; + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); +} + +TEST_F(QuicHttpFrameDecoderTest, SettingsEmpty) { + const char kFrameData[] = { + 0x00, 0x00, 0x00, // Length: 0 + 0x04, // Type: SETTINGS + 0x00, // Flags: none + 0x00, 0x00, 0x00, 0x01, // Stream: 1 (invalid but unchecked here) + }; + QuicHttpFrameHeader header(0, QuicHttpFrameType::SETTINGS, 0, 1); + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, header)); +} + +TEST_F(QuicHttpFrameDecoderTest, SettingsAck) { + const char kFrameData[] = { + 0x00, 0x00, 0x00, // Length: 6 + 0x04, // Type: SETTINGS + 0x01, // Flags: QUIC_HTTP_ACK + 0x00, 0x00, 0x00, 0x00, // Stream: 0 + }; + QuicHttpFrameHeader header(0, QuicHttpFrameType::SETTINGS, + QuicHttpFrameFlag::QUIC_HTTP_ACK, 0); + QuicHttpFrameParts expected(header); + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); +} + +TEST_F(QuicHttpFrameDecoderTest, PushPromiseMinimal) { + const char kFrameData[] = { + 0x00, 0x00, 0x04, // Payload length: 4 + 0x05, // PUSH_PROMISE + 0x04, // Flags: QUIC_HTTP_END_HEADERS + 0x00, 0x00, 0x00, 0x02, // Stream: 2 (invalid but unchecked here) + 0x00, 0x00, 0x00, 0x01, // Promised: 1 (invalid but unchecked here) + }; + QuicHttpFrameHeader header(4, QuicHttpFrameType::PUSH_PROMISE, + QuicHttpFrameFlag::QUIC_HTTP_END_HEADERS, 2); + QuicHttpFrameParts expected(header, ""); + expected.opt_push_promise = QuicHttpPushPromiseFields{1}; + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); +} + +TEST_F(QuicHttpFrameDecoderTest, Ping) { + const char kFrameData[] = { + 0x00, 0x00, 0x08, // Length: 8 + 0x06, // Type: PING + 0xfeu, // Flags: no valid flags + 0x00, 0x00, 0x00, 0x00, // Stream: 0 + 's', 'o', 'm', 'e', // "some" + 'd', 'a', 't', 'a', // "data" + }; + QuicHttpFrameHeader header(8, QuicHttpFrameType::PING, 0, 0); + QuicHttpFrameParts expected(header); + expected.opt_ping = + QuicHttpPingFields{{'s', 'o', 'm', 'e', 'd', 'a', 't', 'a'}}; + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); +} + +TEST_F(QuicHttpFrameDecoderTest, PingAck) { + const char kFrameData[] = { + 0x00, 0x00, 0x08, // Length: 8 + 0x06, // Type: PING + 0xffu, // Flags: QUIC_HTTP_ACK (plus all invalid flags) + 0x00, 0x00, 0x00, 0x00, // Stream: 0 + 's', 'o', 'm', 'e', // "some" + 'd', 'a', 't', 'a', // "data" + }; + QuicHttpFrameHeader header(8, QuicHttpFrameType::PING, + QuicHttpFrameFlag::QUIC_HTTP_ACK, 0); + QuicHttpFrameParts expected(header); + expected.opt_ping = + QuicHttpPingFields{{'s', 'o', 'm', 'e', 'd', 'a', 't', 'a'}}; + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); +} + +TEST_F(QuicHttpFrameDecoderTest, GoAwayMinimal) { + const char kFrameData[] = { + 0x00, 0x00, 0x08, // Length: 8 (no opaque data) + 0x07, // Type: GOAWAY + 0xffu, // Flags: 0xff (no valid flags) + 0x00, 0x00, 0x00, 0x01, // Stream: 1 (invalid but unchecked here) + 0x80u, 0x00, 0x00, 0xffu, // Last: 255 (plus R bit) + 0x00, 0x00, 0x00, 0x09, // Error: COMPRESSION_ERROR + }; + QuicHttpFrameHeader header(8, QuicHttpFrameType::GOAWAY, 0, 1); + QuicHttpFrameParts expected(header); + expected.opt_goaway = + QuicHttpGoAwayFields(255, QuicHttpErrorCode::COMPRESSION_ERROR); + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); +} + +TEST_F(QuicHttpFrameDecoderTest, WindowUpdate) { + const char kFrameData[] = { + 0x00, 0x00, 0x04, // Length: 4 + 0x08, // Type: WINDOW_UPDATE + 0x0f, // Flags: 0xff (no valid flags) + 0x00, 0x00, 0x00, 0x01, // Stream: 1 + 0x80u, 0x00, 0x04, 0x00, // Incr: 1024 (plus R bit) + }; + QuicHttpFrameHeader header(4, QuicHttpFrameType::WINDOW_UPDATE, 0, 1); + QuicHttpFrameParts expected(header); + expected.opt_window_update_increment = 1024; + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); +} + +TEST_F(QuicHttpFrameDecoderTest, ContinuationEmpty) { + const char kFrameData[] = { + 0x00, 0x00, 0x00, // Payload length: 0 + 0x09, // CONTINUATION + 0x00, // Flags: none + 0x00, 0x00, 0x00, 0x00, // Stream ID: 0 (invalid but unchecked here) + }; + QuicHttpFrameHeader header(0, QuicHttpFrameType::CONTINUATION, 0, 0); + QuicHttpFrameParts expected(header); + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); +} + +TEST_F(QuicHttpFrameDecoderTest, AltSvcMinimal) { + const char kFrameData[] = { + 0x00, 0x00, 0x02, // Payload length: 2 + 0x0a, // ALTSVC + 0xffu, // Flags: none (plus 0xff) + 0x00, 0x00, 0x00, 0x00, // Stream ID: 0 (invalid but unchecked here) + 0x00, 0x00, // Origin Length: 0 + }; + QuicHttpFrameHeader header(2, QuicHttpFrameType::ALTSVC, 0, 0); + QuicHttpFrameParts expected(header); + expected.opt_altsvc_origin_length = 0; + expected.opt_altsvc_value_length = 0; + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); +} + +TEST_F(QuicHttpFrameDecoderTest, UnknownEmpty) { + const char kFrameData[] = { + 0x00, 0x00, 0x00, // Payload length: 0 + 0x20, // 32 (unknown) + 0xffu, // Flags: all + 0x00, 0x00, 0x00, 0x00, // Stream ID: 0 + }; + QuicHttpFrameHeader header(0, static_cast<QuicHttpFrameType>(32), 0xff, 0); + QuicHttpFrameParts expected(header); + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); +} + +//////////////////////////////////////////////////////////////////////////////// +// Tests of longer payloads, for those frame types that allow longer payloads. + +TEST_F(QuicHttpFrameDecoderTest, DataPayload) { + const char kFrameData[] = { + 0x00, 0x00, 0x03, // Payload length: 7 + 0x00, // DATA + 0x80u, // Flags: 0x80 + 0x00, 0x00, 0x02, 0x02, // Stream ID: 514 + 'a', 'b', 'c', // Data + }; + QuicHttpFrameHeader header(3, QuicHttpFrameType::DATA, 0, 514); + QuicHttpFrameParts expected(header, "abc"); + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); +} + +TEST_F(QuicHttpFrameDecoderTest, HeadersPayload) { + const char kFrameData[] = { + 0x00, 0x00, 0x03, // Payload length: 3 + 0x01, // HEADERS + 0x05, // Flags: QUIC_HTTP_END_STREAM | QUIC_HTTP_END_HEADERS + 0x00, 0x00, 0x00, 0x02, // Stream ID: 0 (REQUIRES ID) + 'a', 'b', 'c', // HPQUIC_HTTP_ACK fragment (doesn't have to be valid) + }; + QuicHttpFrameHeader header(3, QuicHttpFrameType::HEADERS, + QuicHttpFrameFlag::QUIC_HTTP_END_STREAM | + QuicHttpFrameFlag::QUIC_HTTP_END_HEADERS, + 2); + QuicHttpFrameParts expected(header, "abc"); + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); +} + +TEST_F(QuicHttpFrameDecoderTest, HeadersPriority) { + const char kFrameData[] = { + 0x00, 0x00, 0x05, // Payload length: 5 + 0x01, // HEADERS + 0x20, // Flags: QUIC_HTTP_PRIORITY + 0x00, 0x00, 0x00, 0x02, // Stream ID: 0 (REQUIRES ID) + 0x00, 0x00, 0x00, 0x01, // Parent: 1 (Not Exclusive) + 0xffu, // Weight: 256 + }; + QuicHttpFrameHeader header(5, QuicHttpFrameType::HEADERS, + QuicHttpFrameFlag::QUIC_HTTP_PRIORITY, 2); + QuicHttpFrameParts expected(header); + expected.opt_priority = QuicHttpPriorityFields(1, 256, false); + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); +} + +TEST_F(QuicHttpFrameDecoderTest, Settings) { + const char kFrameData[] = { + 0x00, 0x00, 0x0c, // Length: 12 + 0x04, // Type: SETTINGS + 0x00, // Flags: none + 0x00, 0x00, 0x00, 0x00, // Stream: 0 + 0x00, 0x04, // Param: INITIAL_WINDOW_SIZE + 0x0a, 0x0b, 0x0c, 0x0d, // Value: 168496141 + 0x00, 0x02, // Param: ENABLE_PUSH + 0x00, 0x00, 0x00, 0x03, // Value: 3 (invalid but unchecked here) + }; + QuicHttpFrameHeader header(12, QuicHttpFrameType::SETTINGS, 0, 0); + QuicHttpFrameParts expected(header); + expected.settings.push_back(QuicHttpSettingFields( + QuicHttpSettingsParameter::INITIAL_WINDOW_SIZE, 168496141)); + expected.settings.push_back( + QuicHttpSettingFields(QuicHttpSettingsParameter::ENABLE_PUSH, 3)); + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); +} + +TEST_F(QuicHttpFrameDecoderTest, PushPromisePayload) { + const char kFrameData[] = { + 0x00, 0x00, 7, // Payload length: 7 + 0x05, // PUSH_PROMISE + 0x04, // Flags: QUIC_HTTP_END_HEADERS + 0x00, 0x00, 0x00, 0xffu, // Stream ID: 255 + 0x00, 0x00, 0x01, 0x00, // Promised: 256 + 'a', 'b', 'c', // HPQUIC_HTTP_ACK fragment (doesn't have to be valid) + }; + QuicHttpFrameHeader header(7, QuicHttpFrameType::PUSH_PROMISE, + QuicHttpFrameFlag::QUIC_HTTP_END_HEADERS, 255); + QuicHttpFrameParts expected(header, "abc"); + expected.opt_push_promise = QuicHttpPushPromiseFields{256}; + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); +} + +TEST_F(QuicHttpFrameDecoderTest, GoAwayOpaqueData) { + const char kFrameData[] = { + 0x00, 0x00, 0x0e, // Length: 14 + 0x07, // Type: GOAWAY + 0xffu, // Flags: 0xff (no valid flags) + 0x80u, 0x00, 0x00, 0x00, // Stream: 0 (plus R bit) + 0x00, 0x00, 0x01, 0x00, // Last: 256 + 0x00, 0x00, 0x00, 0x03, // Error: FLOW_CONTROL_ERROR + 'o', 'p', 'a', 'q', 'u', 'e', + }; + QuicHttpFrameHeader header(14, QuicHttpFrameType::GOAWAY, 0, 0); + QuicHttpFrameParts expected(header, "opaque"); + expected.opt_goaway = + QuicHttpGoAwayFields(256, QuicHttpErrorCode::FLOW_CONTROL_ERROR); + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); +} + +TEST_F(QuicHttpFrameDecoderTest, ContinuationPayload) { + const char kFrameData[] = { + 0x00, 0x00, 0x03, // Payload length: 3 + 0x09, // CONTINUATION + 0xffu, // Flags: QUIC_HTTP_END_HEADERS | 0xfb + 0x00, 0x00, 0x00, 0x02, // Stream ID: 2 + 'a', 'b', 'c', // Data + }; + QuicHttpFrameHeader header(3, QuicHttpFrameType::CONTINUATION, + QuicHttpFrameFlag::QUIC_HTTP_END_HEADERS, 2); + QuicHttpFrameParts expected(header, "abc"); + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); +} + +TEST_F(QuicHttpFrameDecoderTest, AltSvcPayload) { + const char kFrameData[] = { + 0x00, 0x00, 0x08, // Payload length: 3 + 0x0a, // ALTSVC + 0x00, // Flags: none + 0x00, 0x00, 0x00, 0x02, // Stream ID: 2 + 0x00, 0x03, // Origin Length: 0 + 'a', 'b', 'c', // Origin + 'd', 'e', 'f', // Value + }; + QuicHttpFrameHeader header(8, QuicHttpFrameType::ALTSVC, 0, 2); + QuicHttpFrameParts expected(header); + expected.SetAltSvcExpected("abc", "def"); + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); +} + +TEST_F(QuicHttpFrameDecoderTest, UnknownPayload) { + const char kFrameData[] = { + 0x00, 0x00, 0x03, // Payload length: 3 + 0x30, // 48 (unknown) + 0x00, // Flags: none + 0x00, 0x00, 0x00, 0x02, // Stream ID: 2 + 'a', 'b', 'c', // Payload + }; + QuicHttpFrameHeader header(3, static_cast<QuicHttpFrameType>(48), 0, 2); + QuicHttpFrameParts expected(header, "abc"); + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); +} + +//////////////////////////////////////////////////////////////////////////////// +// Tests of padded payloads, for those frame types that allow padding. + +TEST_F(QuicHttpFrameDecoderTest, DataPayloadAndPadding) { + const char kFrameData[] = { + 0x00, 0x00, 0x07, // Payload length: 7 + 0x00, // DATA + 0x09, // Flags: QUIC_HTTP_END_STREAM | QUIC_HTTP_PADDED + 0x00, 0x00, 0x00, 0x02, // Stream ID: 0 (REQUIRES ID) + 0x03, // Pad Len + 'a', 'b', 'c', // Data + 0x00, 0x00, 0x00, // Padding + }; + QuicHttpFrameHeader header(7, QuicHttpFrameType::DATA, + QuicHttpFrameFlag::QUIC_HTTP_END_STREAM | + QuicHttpFrameFlag::QUIC_HTTP_PADDED, + 2); + size_t total_pad_length = 4; // Including the Pad Length field. + QuicHttpFrameParts expected(header, "abc", total_pad_length); + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); +} + +TEST_F(QuicHttpFrameDecoderTest, HeadersPayloadAndPadding) { + const char kFrameData[] = { + 0x00, 0x00, 0x07, // Payload length: 7 + 0x01, // HEADERS + 0x08, // Flags: QUIC_HTTP_PADDED + 0x00, 0x00, 0x00, 0x02, // Stream ID: 0 (REQUIRES ID) + 0x03, // Pad Len + 'a', 'b', 'c', // HPQUIC_HTTP_ACK fragment (doesn't have to be valid) + 0x00, 0x00, 0x00, // Padding + }; + QuicHttpFrameHeader header(7, QuicHttpFrameType::HEADERS, + QuicHttpFrameFlag::QUIC_HTTP_PADDED, 2); + size_t total_pad_length = 4; // Including the Pad Length field. + QuicHttpFrameParts expected(header, "abc", total_pad_length); + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); +} + +TEST_F(QuicHttpFrameDecoderTest, HeadersPayloadPriorityAndPadding) { + const char kFrameData[] = { + 0x00, 0x00, 0x0c, // Payload length: 12 + 0x01, // HEADERS + 0xffu, // Flags: all, including undefined + 0x00, 0x00, 0x00, 0x02, // Stream ID: 0 (REQUIRES ID) + 0x03, // Pad Len + 0x80u, 0x00, 0x00, 0x01, // Parent: 1 (Exclusive) + 0x10, // Weight: 17 + 'a', 'b', 'c', // HPQUIC_HTTP_ACK fragment (doesn't have to be valid) + 0x00, 0x00, 0x00, // Padding + }; + QuicHttpFrameHeader header(12, QuicHttpFrameType::HEADERS, + QuicHttpFrameFlag::QUIC_HTTP_END_STREAM | + QuicHttpFrameFlag::QUIC_HTTP_END_HEADERS | + QuicHttpFrameFlag::QUIC_HTTP_PADDED | + QuicHttpFrameFlag::QUIC_HTTP_PRIORITY, + 2); + size_t total_pad_length = 4; // Including the Pad Length field. + QuicHttpFrameParts expected(header, "abc", total_pad_length); + expected.opt_priority = QuicHttpPriorityFields(1, 17, true); + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); +} + +TEST_F(QuicHttpFrameDecoderTest, PushPromisePayloadAndPadding) { + const char kFrameData[] = { + 0x00, 0x00, 11, // Payload length: 11 + 0x05, // PUSH_PROMISE + 0xffu, // Flags: QUIC_HTTP_END_HEADERS | QUIC_HTTP_PADDED | 0xf3 + 0x00, 0x00, 0x00, 0x01, // Stream ID: 1 + 0x03, // Pad Len + 0x00, 0x00, 0x00, 0x02, // Promised: 2 + 'a', 'b', 'c', // HPQUIC_HTTP_ACK fragment (doesn't have to be valid) + 0x00, 0x00, 0x00, // Padding + }; + QuicHttpFrameHeader header(11, QuicHttpFrameType::PUSH_PROMISE, + QuicHttpFrameFlag::QUIC_HTTP_END_HEADERS | + QuicHttpFrameFlag::QUIC_HTTP_PADDED, + 1); + size_t total_pad_length = 4; // Including the Pad Length field. + QuicHttpFrameParts expected(header, "abc", total_pad_length); + expected.opt_push_promise = QuicHttpPushPromiseFields{2}; + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected)); +} + +//////////////////////////////////////////////////////////////////////////////// +// Payload too short errors. + +TEST_F(QuicHttpFrameDecoderTest, DataMissingPadLengthField) { + const char kFrameData[] = { + 0x00, 0x00, 0x00, // Payload length: 0 + 0x00, // DATA + 0x08, // Flags: QUIC_HTTP_PADDED + 0x00, 0x00, 0x00, 0x01, // Stream ID: 1 + }; + QuicHttpFrameHeader header(0, QuicHttpFrameType::DATA, + QuicHttpFrameFlag::QUIC_HTTP_PADDED, 1); + QuicHttpFrameParts expected(header); + expected.opt_missing_length = 1; + EXPECT_TRUE(DecodePayloadExpectingError(kFrameData, expected)); +} + +TEST_F(QuicHttpFrameDecoderTest, HeaderPaddingTooLong) { + const char kFrameData[] = { + 0x00, 0x00, 0x02, // Payload length: 0 + 0x01, // HEADERS + 0x08, // Flags: QUIC_HTTP_PADDED + 0x00, 0x01, 0x00, 0x00, // Stream ID: 65536 + 0xffu, // Pad Len: 255 + 0x00, // Only one byte of padding + }; + QuicHttpFrameHeader header(2, QuicHttpFrameType::HEADERS, + QuicHttpFrameFlag::QUIC_HTTP_PADDED, 65536); + QuicHttpFrameParts expected(header); + expected.opt_missing_length = 254; + EXPECT_TRUE(DecodePayloadExpectingError(kFrameData, expected)); +} + +TEST_F(QuicHttpFrameDecoderTest, HeaderMissingPriority) { + const char kFrameData[] = { + 0x00, 0x00, 0x04, // Payload length: 0 + 0x01, // HEADERS + 0x20, // Flags: QUIC_HTTP_PRIORITY + 0x00, 0x01, 0x00, 0x00, // Stream ID: 65536 + 0x00, 0x00, 0x00, 0x00, // Priority (truncated) + }; + QuicHttpFrameHeader header(4, QuicHttpFrameType::HEADERS, + QuicHttpFrameFlag::QUIC_HTTP_PRIORITY, 65536); + EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header)); +} + +TEST_F(QuicHttpFrameDecoderTest, PriorityTooShort) { + const char kFrameData[] = { + 0x00, 0x00, 0x04, // Length: 5 + 0x02, // Type: QUIC_HTTP_PRIORITY + 0x00, // Flags: none + 0x00, 0x00, 0x00, 0x02, // Stream: 2 + 0x80u, 0x00, 0x00, 0x01, // Parent: 1 (Exclusive) + }; + QuicHttpFrameHeader header(4, QuicHttpFrameType::QUIC_HTTP_PRIORITY, 0, 2); + EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header)); +} + +TEST_F(QuicHttpFrameDecoderTest, RstStreamTooShort) { + const char kFrameData[] = { + 0x00, 0x00, 0x03, // Length: 4 + 0x03, // Type: RST_STREAM + 0x00, // Flags: none + 0x00, 0x00, 0x00, 0x01, // Stream: 1 + 0x00, 0x00, 0x00, // Truncated + }; + QuicHttpFrameHeader header(3, QuicHttpFrameType::RST_STREAM, 0, 1); + EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header)); +} + +// SETTINGS frames must a multiple of 6 bytes long, so an 9 byte payload is +// invalid. +TEST_F(QuicHttpFrameDecoderTest, SettingsWrongSize) { + const char kFrameData[] = { + 0x00, 0x00, 0x09, // Length: 2 + 0x04, // Type: SETTINGS + 0x00, // Flags: none + 0x00, 0x00, 0x00, 0x00, // Stream: 0 + 0x00, 0x02, // Param: ENABLE_PUSH + 0x00, 0x00, 0x00, 0x03, // Value: 1 + 0x00, 0x04, // Param: INITIAL_WINDOW_SIZE + 0x00, // Value: Truncated + }; + QuicHttpFrameHeader header(9, QuicHttpFrameType::SETTINGS, 0, 0); + QuicHttpFrameParts expected(header); + expected.settings.push_back( + QuicHttpSettingFields(QuicHttpSettingsParameter::ENABLE_PUSH, 3)); + EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, expected)); +} + +TEST_F(QuicHttpFrameDecoderTest, PushPromiseTooShort) { + const char kFrameData[] = { + 0x00, 0x00, 3, // Payload length: 3 + 0x05, // PUSH_PROMISE + 0x00, // Flags: none + 0x00, 0x00, 0x00, 0x01, // Stream ID: 1 + 0x00, 0x00, 0x00, // Truncated promise id + }; + QuicHttpFrameHeader header(3, QuicHttpFrameType::PUSH_PROMISE, 0, 1); + EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header)); +} + +TEST_F(QuicHttpFrameDecoderTest, PushPromisePaddedTruncatedPromise) { + const char kFrameData[] = { + 0x00, 0x00, 4, // Payload length: 4 + 0x05, // PUSH_PROMISE + 0x08, // Flags: QUIC_HTTP_PADDED + 0x00, 0x00, 0x00, 0x01, // Stream ID: 1 + 0x00, // Pad Len + 0x00, 0x00, 0x00, // Truncated promise id + }; + QuicHttpFrameHeader header(4, QuicHttpFrameType::PUSH_PROMISE, + QuicHttpFrameFlag::QUIC_HTTP_PADDED, 1); + EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header)); +} + +TEST_F(QuicHttpFrameDecoderTest, PingTooShort) { + const char kFrameData[] = { + 0x00, 0x00, 0x07, // Length: 8 + 0x06, // Type: PING + 0xfeu, // Flags: no valid flags + 0x00, 0x00, 0x00, 0x00, // Stream: 0 + 's', 'o', 'm', 'e', // "some" + 'd', 'a', 't', // Too little + }; + QuicHttpFrameHeader header(7, QuicHttpFrameType::PING, 0, 0); + EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header)); +} + +TEST_F(QuicHttpFrameDecoderTest, GoAwayTooShort) { + const char kFrameData[] = { + 0x00, 0x00, 0x00, // Length: 0 + 0x07, // Type: GOAWAY + 0xffu, // Flags: 0xff (no valid flags) + 0x00, 0x00, 0x00, 0x00, // Stream: 0 + }; + QuicHttpFrameHeader header(0, QuicHttpFrameType::GOAWAY, 0, 0); + EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header)); +} + +TEST_F(QuicHttpFrameDecoderTest, WindowUpdateTooShort) { + const char kFrameData[] = { + 0x00, 0x00, 0x03, // Length: 3 + 0x08, // Type: WINDOW_UPDATE + 0x0f, // Flags: 0xff (no valid flags) + 0x00, 0x00, 0x00, 0x01, // Stream: 1 + 0x80u, 0x00, 0x04, // Truncated + }; + QuicHttpFrameHeader header(3, QuicHttpFrameType::WINDOW_UPDATE, 0, 1); + EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header)); +} + +TEST_F(QuicHttpFrameDecoderTest, AltSvcTruncatedOriginLength) { + const char kFrameData[] = { + 0x00, 0x00, 0x01, // Payload length: 3 + 0x0a, // ALTSVC + 0x00, // Flags: none + 0x00, 0x00, 0x00, 0x02, // Stream ID: 2 + 0x00, // Origin Length: truncated + }; + QuicHttpFrameHeader header(1, QuicHttpFrameType::ALTSVC, 0, 2); + EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header)); +} + +TEST_F(QuicHttpFrameDecoderTest, AltSvcTruncatedOrigin) { + const char kFrameData[] = { + 0x00, 0x00, 0x05, // Payload length: 3 + 0x0a, // ALTSVC + 0x00, // Flags: none + 0x00, 0x00, 0x00, 0x02, // Stream ID: 2 + 0x00, 0x04, // Origin Length: 4 (too long) + 'a', 'b', 'c', // Origin + }; + QuicHttpFrameHeader header(5, QuicHttpFrameType::ALTSVC, 0, 2); + EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header)); +} + +//////////////////////////////////////////////////////////////////////////////// +// Payload too long errors. + +// The decoder calls the listener's OnFrameSizeError method if the frame's +// payload is longer than the currently configured maximum payload size. +TEST_F(QuicHttpFrameDecoderTest, BeyondMaximum) { + decoder_.set_maximum_payload_size(2); + const char kFrameData[] = { + 0x00, 0x00, 0x07, // Payload length: 7 + 0x00, // DATA + 0x09, // Flags: QUIC_HTTP_END_STREAM | QUIC_HTTP_PADDED + 0x00, 0x00, 0x00, 0x02, // Stream ID: 0 (REQUIRES ID) + 0x03, // Pad Len + 'a', 'b', 'c', // Data + 0x00, 0x00, 0x00, // Padding + }; + QuicHttpFrameHeader header(7, QuicHttpFrameType::DATA, + QuicHttpFrameFlag::QUIC_HTTP_END_STREAM | + QuicHttpFrameFlag::QUIC_HTTP_PADDED, + 2); + QuicHttpFrameParts expected(header); + expected.has_frame_size_error = true; + auto validator = [&expected, this]( + const QuicHttpDecodeBuffer& input, + QuicHttpDecodeStatus status) -> AssertionResult { + VERIFY_EQ(status, QuicHttpDecodeStatus::kDecodeError); + // The decoder detects this error after decoding the header, and without + // trying to decode the payload. + VERIFY_EQ(input.Offset(), QuicHttpFrameHeader::EncodedSize()); + VERIFY_AND_RETURN_SUCCESS(VerifyCollected(expected)); + }; + ResetDecodeSpeedCounters(); + EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(ToStringPiece(kFrameData), + validator)); + EXPECT_GT(fast_decode_count_, 0u); + EXPECT_GT(slow_decode_count_, 0u); +} + +TEST_F(QuicHttpFrameDecoderTest, PriorityTooLong) { + const char kFrameData[] = { + 0x00, 0x00, 0x06, // Length: 5 + 0x02, // Type: QUIC_HTTP_PRIORITY + 0x00, // Flags: none + 0x00, 0x00, 0x00, 0x02, // Stream: 2 + 0x80u, 0x00, 0x00, 0x01, // Parent: 1 (Exclusive) + 0x10, // Weight: 17 + 0x00, // Too much + }; + QuicHttpFrameHeader header(6, QuicHttpFrameType::QUIC_HTTP_PRIORITY, 0, 2); + EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header)); +} + +TEST_F(QuicHttpFrameDecoderTest, RstStreamTooLong) { + const char kFrameData[] = { + 0x00, 0x00, 0x05, // Length: 4 + 0x03, // Type: RST_STREAM + 0x00, // Flags: none + 0x00, 0x00, 0x00, 0x01, // Stream: 1 + 0x00, 0x00, 0x00, 0x01, // Error: PROTOCOL_ERROR + 0x00, // Too much + }; + QuicHttpFrameHeader header(5, QuicHttpFrameType::RST_STREAM, 0, 1); + EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header)); +} + +TEST_F(QuicHttpFrameDecoderTest, SettingsAckTooLong) { + const char kFrameData[] = { + 0x00, 0x00, 0x06, // Length: 6 + 0x04, // Type: SETTINGS + 0x01, // Flags: QUIC_HTTP_ACK + 0x00, 0x00, 0x00, 0x00, // Stream: 0 + 0x00, 0x00, // Extra + 0x00, 0x00, 0x00, 0x00, // Extra + }; + QuicHttpFrameHeader header(6, QuicHttpFrameType::SETTINGS, + QuicHttpFrameFlag::QUIC_HTTP_ACK, 0); + EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header)); +} + +TEST_F(QuicHttpFrameDecoderTest, PingAckTooLong) { + const char kFrameData[] = { + 0x00, 0x00, 0x09, // Length: 8 + 0x06, // Type: PING + 0xffu, // Flags: QUIC_HTTP_ACK | 0xfe + 0x00, 0x00, 0x00, 0x00, // Stream: 0 + 's', 'o', 'm', 'e', // "some" + 'd', 'a', 't', 'a', // "data" + 0x00, // Too much + }; + QuicHttpFrameHeader header(9, QuicHttpFrameType::PING, + QuicHttpFrameFlag::QUIC_HTTP_ACK, 0); + EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header)); +} + +TEST_F(QuicHttpFrameDecoderTest, WindowUpdateTooLong) { + const char kFrameData[] = { + 0x00, 0x00, 0x05, // Length: 5 + 0x08, // Type: WINDOW_UPDATE + 0x0f, // Flags: 0xff (no valid flags) + 0x00, 0x00, 0x00, 0x01, // Stream: 1 + 0x80u, 0x00, 0x04, 0x00, // Incr: 1024 (plus R bit) + 0x00, // Too much + }; + QuicHttpFrameHeader header(5, QuicHttpFrameType::WINDOW_UPDATE, 0, 1); + EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header)); +} + +} // namespace +} // namespace test +} // namespace net
diff --git a/net/quic/http/decoder/quic_http_structure_decoder.cc b/net/quic/http/decoder/quic_http_structure_decoder.cc new file mode 100644 index 0000000..0f2759b --- /dev/null +++ b/net/quic/http/decoder/quic_http_structure_decoder.cc
@@ -0,0 +1,91 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/quic_http_structure_decoder.h" + +#include <algorithm> + +#include "net/quic/platform/api/quic_bug_tracker.h" + +namespace net { + +// Below we have some defensive coding: if we somehow run off the end, don't +// overwrite lots of memory. Note that most of this decoder is not defensive +// against bugs in the decoder, only against malicious encoders, but since +// we're copying memory into a buffer here, let's make sure we don't allow a +// small mistake to grow larger. The decoder will get stuck if we hit the +// QUIC_BUG conditions, but shouldn't corrupt memory. + +uint32_t QuicHttpStructureDecoder::IncompleteStart(QuicHttpDecodeBuffer* db, + uint32_t target_size) { + if (target_size > sizeof buffer_) { + QUIC_BUG << "target_size too large for buffer: " << target_size; + return 0; + } + const uint32_t num_to_copy = db->MinLengthRemaining(target_size); + memcpy(buffer_, db->cursor(), num_to_copy); + offset_ = num_to_copy; + db->AdvanceCursor(num_to_copy); + return num_to_copy; +} + +QuicHttpDecodeStatus QuicHttpStructureDecoder::IncompleteStart( + QuicHttpDecodeBuffer* db, + uint32_t* remaining_payload, + uint32_t target_size) { + DVLOG(1) << "IncompleteStart@" << this + << ": *remaining_payload=" << *remaining_payload + << "; target_size=" << target_size + << "; db->Remaining=" << db->Remaining(); + *remaining_payload -= + IncompleteStart(db, std::min(target_size, *remaining_payload)); + if (*remaining_payload > 0 && db->Empty()) { + return QuicHttpDecodeStatus::kDecodeInProgress; + } + DVLOG(1) << "IncompleteStart: kDecodeError"; + return QuicHttpDecodeStatus::kDecodeError; +} + +bool QuicHttpStructureDecoder::ResumeFillingBuffer(QuicHttpDecodeBuffer* db, + uint32_t target_size) { + DVLOG(2) << "ResumeFillingBuffer@" << this << ": target_size=" << target_size + << "; offset_=" << offset_ << "; db->Remaining=" << db->Remaining(); + if (target_size < offset_) { + QUIC_BUG << "Already filled buffer_! target_size=" << target_size + << " offset_=" << offset_; + return false; + } + const uint32_t needed = target_size - offset_; + const uint32_t num_to_copy = db->MinLengthRemaining(needed); + DVLOG(2) << "ResumeFillingBuffer num_to_copy=" << num_to_copy; + memcpy(&buffer_[offset_], db->cursor(), num_to_copy); + db->AdvanceCursor(num_to_copy); + offset_ += num_to_copy; + return needed == num_to_copy; +} + +bool QuicHttpStructureDecoder::ResumeFillingBuffer(QuicHttpDecodeBuffer* db, + uint32_t* remaining_payload, + uint32_t target_size) { + DVLOG(2) << "ResumeFillingBuffer@" << this << ": target_size=" << target_size + << "; offset_=" << offset_ + << "; *remaining_payload=" << *remaining_payload + << "; db->Remaining=" << db->Remaining(); + if (target_size < offset_) { + QUIC_BUG << "Already filled buffer_! target_size=" << target_size + << " offset_=" << offset_; + return false; + } + const uint32_t needed = target_size - offset_; + const uint32_t num_to_copy = + db->MinLengthRemaining(std::min(needed, *remaining_payload)); + DVLOG(2) << "ResumeFillingBuffer num_to_copy=" << num_to_copy; + memcpy(&buffer_[offset_], db->cursor(), num_to_copy); + db->AdvanceCursor(num_to_copy); + offset_ += num_to_copy; + *remaining_payload -= num_to_copy; + return needed == num_to_copy; +} + +} // namespace net
diff --git a/net/quic/http/decoder/quic_http_structure_decoder.h b/net/quic/http/decoder/quic_http_structure_decoder.h new file mode 100644 index 0000000..77d61048 --- /dev/null +++ b/net/quic/http/decoder/quic_http_structure_decoder.h
@@ -0,0 +1,133 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_HTTP_DECODER_QUIC_HTTP_STRUCTURE_DECODER_H_ +#define NET_QUIC_HTTP_DECODER_QUIC_HTTP_STRUCTURE_DECODER_H_ + +// QuicHttpStructureDecoder is a class for decoding the fixed size structures in +// the HTTP/2 spec, defined in gfe/quic/http/quic_http_structures.h. This class +// is in aid of deciding whether to keep the SlowDecode methods which I +// (jamessynge) now think may not be worth their complexity. In particular, +// if most transport buffers are large, so it is rare that a structure is +// split across buffer boundaries, than the cost of buffering upon +// those rare occurrences is small, which then simplifies the callers. + +#include <cstdint> + +#include "base/logging.h" +#include "net/quic/http/decoder/quic_http_decode_buffer.h" +#include "net/quic/http/decoder/quic_http_decode_status.h" +#include "net/quic/http/decoder/quic_http_decode_structures.h" +#include "net/quic/http/quic_http_structures.h" +#include "net/quic/platform/api/quic_export.h" + +namespace net { +namespace test { +class QuicHttpStructureDecoderPeer; +} // namespace test + +class QUIC_EXPORT_PRIVATE QuicHttpStructureDecoder { + public: + // The caller needs to keep track of whether to call Start or Resume. + // + // Start has an optimization for the case where the QuicHttpDecodeBuffer holds + // the entire encoded structure; in that case it decodes into *out and returns + // true, and does NOT touch the data members of the QuicHttpStructureDecoder + // instance because the caller won't be calling Resume later. + // + // However, if the QuicHttpDecodeBuffer is too small to hold the entire + // encoded structure, Start copies the available bytes into the + // QuicHttpStructureDecoder instance, and returns false to indicate that it + // has not been able to complete the decoding. + // + template <class S> + bool Start(S* out, QuicHttpDecodeBuffer* db) { + static_assert(S::EncodedSize() <= sizeof buffer_, "buffer_ is too small"); + DVLOG(2) << __func__ << "@" << this << ": db->Remaining=" << db->Remaining() + << "; EncodedSize=" << S::EncodedSize(); + if (db->Remaining() >= S::EncodedSize()) { + DoDecode(out, db); + return true; + } + IncompleteStart(db, S::EncodedSize()); + return false; + } + + template <class S> + bool Resume(S* out, QuicHttpDecodeBuffer* db) { + DVLOG(2) << __func__ << "@" << this << ": offset_=" << offset_ + << "; db->Remaining=" << db->Remaining(); + if (ResumeFillingBuffer(db, S::EncodedSize())) { + // We have the whole thing now. + DVLOG(2) << __func__ << "@" << this << " offset_=" << offset_ + << " Ready to decode from buffer_."; + QuicHttpDecodeBuffer buffer_db(buffer_, S::EncodedSize()); + DoDecode(out, &buffer_db); + return true; + } + DCHECK_LT(offset_, S::EncodedSize()); + return false; + } + + // A second pair of Start and Resume, where the caller has a variable, + // |remaining_payload| that is both tested for sufficiency and updated + // during decoding. Note that the decode buffer may extend beyond the + // remaining payload because the buffer may include padding. + template <class S> + QuicHttpDecodeStatus Start(S* out, + QuicHttpDecodeBuffer* db, + uint32_t* remaining_payload) { + static_assert(S::EncodedSize() <= sizeof buffer_, "buffer_ is too small"); + DVLOG(2) << __func__ << "@" << this + << ": *remaining_payload=" << *remaining_payload + << "; db->Remaining=" << db->Remaining() + << "; EncodedSize=" << S::EncodedSize(); + if (db->MinLengthRemaining(*remaining_payload) >= S::EncodedSize()) { + DoDecode(out, db); + *remaining_payload -= S::EncodedSize(); + return QuicHttpDecodeStatus::kDecodeDone; + } + return IncompleteStart(db, remaining_payload, S::EncodedSize()); + } + + template <class S> + bool Resume(S* out, QuicHttpDecodeBuffer* db, uint32_t* remaining_payload) { + DVLOG(3) << __func__ << "@" << this << ": offset_=" << offset_ + << "; *remaining_payload=" << *remaining_payload + << "; db->Remaining=" << db->Remaining() + << "; EncodedSize=" << S::EncodedSize(); + if (ResumeFillingBuffer(db, remaining_payload, S::EncodedSize())) { + // We have the whole thing now. + DVLOG(2) << __func__ << "@" << this << ": offset_=" << offset_ + << "; Ready to decode from buffer_."; + QuicHttpDecodeBuffer buffer_db(buffer_, S::EncodedSize()); + DoDecode(out, &buffer_db); + return true; + } + DCHECK_LT(offset_, S::EncodedSize()); + return false; + } + + uint32_t offset() const { return offset_; } + + private: + friend class test::QuicHttpStructureDecoderPeer; + + uint32_t IncompleteStart(QuicHttpDecodeBuffer* db, uint32_t target_size); + QuicHttpDecodeStatus IncompleteStart(QuicHttpDecodeBuffer* db, + uint32_t* remaining_payload, + uint32_t target_size); + + bool ResumeFillingBuffer(QuicHttpDecodeBuffer* db, uint32_t target_size); + bool ResumeFillingBuffer(QuicHttpDecodeBuffer* db, + uint32_t* remaining_payload, + uint32_t target_size); + + uint32_t offset_; + char buffer_[QuicHttpFrameHeader::EncodedSize()]; +}; + +} // namespace net + +#endif // NET_QUIC_HTTP_DECODER_QUIC_HTTP_STRUCTURE_DECODER_H_
diff --git a/net/quic/http/decoder/quic_http_structure_decoder_test.cc b/net/quic/http/decoder/quic_http_structure_decoder_test.cc new file mode 100644 index 0000000..3f7f1ee5 --- /dev/null +++ b/net/quic/http/decoder/quic_http_structure_decoder_test.cc
@@ -0,0 +1,545 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/quic_http_structure_decoder.h" + +// Tests decoding all of the fixed size HTTP/2 structures (i.e. those defined in +// gfe/quic/http/quic_http_structures.h) using QuicHttpStructureDecoder, which +// handles buffering of structures split across input buffer boundaries, and in +// turn uses DoDecode when it has all of a structure in a contiguous buffer. + +// NOTE: This tests the first pair of Start and Resume, which don't take +// a remaining_payload parameter. The other pair are well tested via the +// payload decoder tests, though... +// TODO(jamessynge): Create type parameterized tests for +// QuicHttpStructureDecoder where the type is the type of structure, and with +// testing of both pairs of Start and Resume methods; note that it appears that +// the first pair will be used only for QuicHttpFrameHeader, and the other pair +// only for structures in the frame payload. + +#include <stddef.h> + +#include <cstdint> + +#include "base/logging.h" +#include "net/quic/http/decoder/quic_http_decode_buffer.h" +#include "net/quic/http/decoder/quic_http_decode_status.h" +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/quic_http_structures_test_util.h" +#include "net/quic/http/tools/quic_http_random_decoder_test.h" +#include "net/quic/platform/api/quic_reconstruct_object.h" +#include "net/quic/platform/api/quic_string.h" +#include "net/quic/platform/api/quic_string_piece.h" +#include "testing/gtest/include/gtest/gtest.h" + +using ::testing::AssertionFailure; +using ::testing::AssertionResult; +using ::testing::AssertionSuccess; + +namespace net { +namespace test { +namespace { +const bool kMayReturnZeroOnFirst = false; + +template <class S> +class QuicHttpStructureDecoderTest : public QuicHttpRandomDecoderTest { + protected: + typedef S Structure; + + QuicHttpStructureDecoderTest() { + // IF the test adds more data after the encoded structure, stop as + // soon as the structure is decoded. + stop_decode_on_done_ = true; + } + + QuicHttpDecodeStatus StartDecoding(QuicHttpDecodeBuffer* b) override { + // Overwrite the current contents of |structure_|, in to which we'll + // decode the buffer, so that we can be confident that we really decoded + // the structure every time. + QuicDefaultReconstructObject(&structure_, RandomPtr()); + uint32_t old_remaining = b->Remaining(); + if (structure_decoder_.Start(&structure_, b)) { + EXPECT_EQ(old_remaining - S::EncodedSize(), b->Remaining()); + ++fast_decode_count_; + return QuicHttpDecodeStatus::kDecodeDone; + } else { + EXPECT_LT(structure_decoder_.offset(), S::EncodedSize()); + EXPECT_EQ(0u, b->Remaining()); + EXPECT_EQ(old_remaining - structure_decoder_.offset(), b->Remaining()); + ++incomplete_start_count_; + return QuicHttpDecodeStatus::kDecodeInProgress; + } + } + + QuicHttpDecodeStatus ResumeDecoding(QuicHttpDecodeBuffer* b) override { + uint32_t old_offset = structure_decoder_.offset(); + EXPECT_LT(old_offset, S::EncodedSize()); + uint32_t avail = b->Remaining(); + if (structure_decoder_.Resume(&structure_, b)) { + EXPECT_LE(S::EncodedSize(), old_offset + avail); + EXPECT_EQ(b->Remaining(), avail - (S::EncodedSize() - old_offset)); + ++slow_decode_count_; + return QuicHttpDecodeStatus::kDecodeDone; + } else { + EXPECT_LT(structure_decoder_.offset(), S::EncodedSize()); + EXPECT_EQ(0u, b->Remaining()); + EXPECT_GT(S::EncodedSize(), old_offset + avail); + ++incomplete_resume_count_; + return QuicHttpDecodeStatus::kDecodeInProgress; + } + } + + // Fully decodes the Structure at the start of data, and confirms it matches + // *expected (if provided). + AssertionResult DecodeLeadingStructure(const S* expected, + QuicStringPiece data) { + VERIFY_LE(S::EncodedSize(), data.size()); + QuicHttpDecodeBuffer original(data); + + // The validator is called after each of the several times that the input + // QuicHttpDecodeBuffer is decoded, each with a different segmentation of + // the input. Validate that structure_ matches the expected value, if + // provided. + Validator validator; + if (expected != nullptr) { + validator = [expected, this]( + const QuicHttpDecodeBuffer& db, + QuicHttpDecodeStatus status) -> AssertionResult { + VERIFY_EQ(*expected, structure_); + return AssertionSuccess(); + }; + } + + // Before that, validate that decoding is done and that we've advanced + // the cursor the expected amount. + validator = ValidateDoneAndOffset(S::EncodedSize(), validator); + + // Decode several times, with several segmentations of the input buffer. + fast_decode_count_ = 0; + slow_decode_count_ = 0; + incomplete_start_count_ = 0; + incomplete_resume_count_ = 0; + VERIFY_SUCCESS(DecodeAndValidateSeveralWays( + &original, kMayReturnZeroOnFirst, validator)); + VERIFY_FALSE(HasFailure()); + VERIFY_EQ(S::EncodedSize(), structure_decoder_.offset()); + VERIFY_EQ(S::EncodedSize(), original.Offset()); + VERIFY_LT(0u, fast_decode_count_); + VERIFY_LT(0u, slow_decode_count_); + VERIFY_LT(0u, incomplete_start_count_); + + // If the structure is large enough so that SelectZeroOrOne will have + // caused Resume to return false, check that occurred. + if (S::EncodedSize() >= 2) { + VERIFY_LE(0u, incomplete_resume_count_); + } else { + VERIFY_EQ(0u, incomplete_resume_count_); + } + if (expected != nullptr) { + DVLOG(1) << "DecodeLeadingStructure expected: " << *expected; + DVLOG(1) << "DecodeLeadingStructure actual: " << structure_; + VERIFY_EQ(*expected, structure_); + } + return AssertionSuccess(); + } + + template <size_t N> + AssertionResult DecodeLeadingStructure(const char (&data)[N]) { + VERIFY_AND_RETURN_SUCCESS( + DecodeLeadingStructure(nullptr, QuicStringPiece(data, N))); + } + + template <size_t N> + AssertionResult DecodeLeadingStructure(const unsigned char (&data)[N]) { + VERIFY_AND_RETURN_SUCCESS( + DecodeLeadingStructure(nullptr, ToStringPiece(data))); + } + + // Encode the structure |in_s| into bytes, then decode the bytes + // and validate that the decoder produced the same field values. + AssertionResult EncodeThenDecode(const S& in_s) { + QuicString bytes = SerializeStructure(in_s); + VERIFY_EQ(S::EncodedSize(), bytes.size()); + VERIFY_AND_RETURN_SUCCESS(DecodeLeadingStructure(&in_s, bytes)); + } + + // Repeatedly fill a structure with random but valid contents, encode it, then + // decode it, and finally validate that the decoded structure matches the + // random input. Lather-rinse-and-repeat. + AssertionResult TestDecodingRandomizedStructures(size_t count) { + for (size_t i = 0; i < count; ++i) { + Structure input; + Randomize(&input, RandomPtr()); + VERIFY_SUCCESS(EncodeThenDecode(input)); + } + return AssertionSuccess(); + } + + AssertionResult TestDecodingRandomizedStructures() { + VERIFY_SUCCESS(TestDecodingRandomizedStructures(100)); + return AssertionSuccess(); + } + + uint32_t decode_offset_ = 0; + S structure_; + QuicHttpStructureDecoder structure_decoder_; + size_t fast_decode_count_ = 0; + size_t slow_decode_count_ = 0; + size_t incomplete_start_count_ = 0; + size_t incomplete_resume_count_ = 0; +}; + +class QuicHttpFrameHeaderDecoderTest + : public QuicHttpStructureDecoderTest<QuicHttpFrameHeader> {}; + +TEST_F(QuicHttpFrameHeaderDecoderTest, DecodesLiteral) { + { + // Realistic input. + // clang-format off + const char kData[] = { + 0x00, 0x00, 0x05, // Payload length: 5 + 0x01, // Frame type: HEADERS + 0x08, // Flags: QUIC_HTTP_PADDED + 0x00, 0x00, 0x00, 0x01, // Stream ID: 1 + 0x04, // Padding length: 4 + 0x00, 0x00, 0x00, 0x00, // Padding bytes + }; + // clang-format on + ASSERT_TRUE(DecodeLeadingStructure(kData)); + EXPECT_EQ(5u, structure_.payload_length); + EXPECT_EQ(QuicHttpFrameType::HEADERS, structure_.type); + EXPECT_EQ(QuicHttpFrameFlag::QUIC_HTTP_PADDED, structure_.flags); + EXPECT_EQ(1u, structure_.stream_id); + } + { + // Unlikely input. + // clang-format off + const unsigned char kData[] = { + 0xff, 0xff, 0xff, // Payload length: uint24 max + 0xff, // Frame type: Unknown + 0xff, // Flags: Unknown/All + 0xff, 0xff, 0xff, 0xff, // Stream ID: uint31 max, plus R-bit + }; + // clang-format on + ASSERT_TRUE(DecodeLeadingStructure(kData)); + EXPECT_EQ((1 << 24) - 1u, structure_.payload_length); + EXPECT_EQ(static_cast<QuicHttpFrameType>(255), structure_.type); + EXPECT_EQ(255, structure_.flags); + EXPECT_EQ(0x7fffffffu, structure_.stream_id); + } +} + +TEST_F(QuicHttpFrameHeaderDecoderTest, DecodesRandomized) { + TestDecodingRandomizedStructures(); +} + +//------------------------------------------------------------------------------ + +class QuicHttpPriorityFieldsDecoderTest + : public QuicHttpStructureDecoderTest<QuicHttpPriorityFields> {}; + +TEST_F(QuicHttpPriorityFieldsDecoderTest, DecodesLiteral) { + { + // clang-format off + const unsigned char kData[] = { + 0x80, 0x00, 0x00, 0x05, // Exclusive (yes) and Dependency (5) + 0xff, // Weight: 256 (after adding 1) + }; + // clang-format on + ASSERT_TRUE(DecodeLeadingStructure(kData)); + EXPECT_EQ(5u, structure_.stream_dependency); + EXPECT_EQ(256u, structure_.weight); + EXPECT_EQ(true, structure_.is_exclusive); + } + { + // clang-format off + const unsigned char kData[] = { + 0x7f, 0xff, 0xff, 0xff, // Excl. (no) and Dependency (uint31 max) + 0x00, // Weight: 1 (after adding 1) + }; + // clang-format on + ASSERT_TRUE(DecodeLeadingStructure(kData)); + EXPECT_EQ(QuicHttpStreamIdMask(), structure_.stream_dependency); + EXPECT_EQ(1u, structure_.weight); + EXPECT_EQ(false, structure_.is_exclusive); + } +} + +TEST_F(QuicHttpPriorityFieldsDecoderTest, DecodesRandomized) { + TestDecodingRandomizedStructures(); +} + +//------------------------------------------------------------------------------ + +class QuicHttpRstStreamFieldsDecoderTest + : public QuicHttpStructureDecoderTest<QuicHttpRstStreamFields> {}; + +TEST_F(QuicHttpRstStreamFieldsDecoderTest, DecodesLiteral) { + { + // clang-format off + const char kData[] = { + 0x00, 0x00, 0x00, 0x01, // Error: PROTOCOL_ERROR + }; + // clang-format on + ASSERT_TRUE(DecodeLeadingStructure(kData)); + EXPECT_TRUE(structure_.IsSupportedErrorCode()); + EXPECT_EQ(QuicHttpErrorCode::PROTOCOL_ERROR, structure_.error_code); + } + { + // clang-format off + const unsigned char kData[] = { + 0xff, 0xff, 0xff, 0xff, // Error: max uint32 (Unknown error code) + }; + // clang-format on + ASSERT_TRUE(DecodeLeadingStructure(kData)); + EXPECT_FALSE(structure_.IsSupportedErrorCode()); + EXPECT_EQ(static_cast<QuicHttpErrorCode>(0xffffffff), + structure_.error_code); + } +} + +TEST_F(QuicHttpRstStreamFieldsDecoderTest, DecodesRandomized) { + TestDecodingRandomizedStructures(); +} + +//------------------------------------------------------------------------------ + +class QuicHttpSettingFieldsDecoderTest + : public QuicHttpStructureDecoderTest<QuicHttpSettingFields> {}; + +TEST_F(QuicHttpSettingFieldsDecoderTest, DecodesLiteral) { + { + // clang-format off + const char kData[] = { + 0x00, 0x01, // Setting: HEADER_TABLE_SIZE + 0x00, 0x00, 0x40, 0x00, // Value: 16K + }; + // clang-format on + ASSERT_TRUE(DecodeLeadingStructure(kData)); + EXPECT_TRUE(structure_.IsSupportedParameter()); + EXPECT_EQ(QuicHttpSettingsParameter::HEADER_TABLE_SIZE, + structure_.parameter); + EXPECT_EQ(1u << 14, structure_.value); + } + { + // clang-format off + const unsigned char kData[] = { + 0x00, 0x00, // Setting: Unknown (0) + 0xff, 0xff, 0xff, 0xff, // Value: max uint32 + }; + // clang-format on + ASSERT_TRUE(DecodeLeadingStructure(kData)); + EXPECT_FALSE(structure_.IsSupportedParameter()); + EXPECT_EQ(static_cast<QuicHttpSettingsParameter>(0), structure_.parameter); + } +} + +TEST_F(QuicHttpSettingFieldsDecoderTest, DecodesRandomized) { + TestDecodingRandomizedStructures(); +} + +//------------------------------------------------------------------------------ + +class QuicHttpPushPromiseFieldsDecoderTest + : public QuicHttpStructureDecoderTest<QuicHttpPushPromiseFields> {}; + +TEST_F(QuicHttpPushPromiseFieldsDecoderTest, DecodesLiteral) { + { + // clang-format off + const unsigned char kData[] = { + 0x00, 0x01, 0x8a, 0x92, // Promised Stream ID: 101010 + }; + // clang-format on + ASSERT_TRUE(DecodeLeadingStructure(kData)); + EXPECT_EQ(101010u, structure_.promised_stream_id); + } + { + // Promised stream id has R-bit (reserved for future use) set, which + // should be cleared by the decoder. + // clang-format off + const unsigned char kData[] = { + // Promised Stream ID: max uint31 and R-bit + 0xff, 0xff, 0xff, 0xff, + }; + // clang-format on + ASSERT_TRUE(DecodeLeadingStructure(kData)); + EXPECT_EQ(QuicHttpStreamIdMask(), structure_.promised_stream_id); + } +} + +TEST_F(QuicHttpPushPromiseFieldsDecoderTest, DecodesRandomized) { + TestDecodingRandomizedStructures(); +} + +//------------------------------------------------------------------------------ + +class QuicHttpPingFieldsDecoderTest + : public QuicHttpStructureDecoderTest<QuicHttpPingFields> {}; + +TEST_F(QuicHttpPingFieldsDecoderTest, DecodesLiteral) { + { + // Each byte is different, so can detect if order changed. + const char kData[] = { + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + }; + ASSERT_TRUE(DecodeLeadingStructure(kData)); + EXPECT_EQ(ToStringPiece(kData), ToStringPiece(structure_.opaque_bytes)); + } + { + // All zeros, detect problems handling NULs. + const char kData[] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + }; + ASSERT_TRUE(DecodeLeadingStructure(kData)); + EXPECT_EQ(ToStringPiece(kData), ToStringPiece(structure_.opaque_bytes)); + } + { + const unsigned char kData[] = { + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + }; + ASSERT_TRUE(DecodeLeadingStructure(kData)); + EXPECT_EQ(ToStringPiece(kData), ToStringPiece(structure_.opaque_bytes)); + } +} + +TEST_F(QuicHttpPingFieldsDecoderTest, DecodesRandomized) { + TestDecodingRandomizedStructures(); +} + +//------------------------------------------------------------------------------ + +class QuicHttpGoAwayFieldsDecoderTest + : public QuicHttpStructureDecoderTest<QuicHttpGoAwayFields> {}; + +TEST_F(QuicHttpGoAwayFieldsDecoderTest, DecodesLiteral) { + { + // clang-format off + const char kData[] = { + 0x00, 0x00, 0x00, 0x00, // Last Stream ID: 0 + 0x00, 0x00, 0x00, 0x00, // Error: NO_ERROR (0) + }; + // clang-format on + ASSERT_TRUE(DecodeLeadingStructure(kData)); + EXPECT_EQ(0u, structure_.last_stream_id); + EXPECT_TRUE(structure_.IsSupportedErrorCode()); + EXPECT_EQ(QuicHttpErrorCode::HTTP2_NO_ERROR, structure_.error_code); + } + { + // clang-format off + const char kData[] = { + 0x00, 0x00, 0x00, 0x01, // Last Stream ID: 1 + 0x00, 0x00, 0x00, 0x0d, // Error: HTTP_1_1_REQUIRED + }; + // clang-format on + ASSERT_TRUE(DecodeLeadingStructure(kData)); + EXPECT_EQ(1u, structure_.last_stream_id); + EXPECT_TRUE(structure_.IsSupportedErrorCode()); + EXPECT_EQ(QuicHttpErrorCode::HTTP_1_1_REQUIRED, structure_.error_code); + } + { + // clang-format off + const unsigned char kData[] = { + 0xff, 0xff, 0xff, 0xff, // Last Stream ID: max uint31 and R-bit + 0xff, 0xff, 0xff, 0xff, // Error: max uint32 (Unknown error code) + }; + // clang-format on + ASSERT_TRUE(DecodeLeadingStructure(kData)); + EXPECT_EQ(QuicHttpStreamIdMask(), + structure_.last_stream_id); // No high-bit. + EXPECT_FALSE(structure_.IsSupportedErrorCode()); + EXPECT_EQ(static_cast<QuicHttpErrorCode>(0xffffffff), + structure_.error_code); + } +} + +TEST_F(QuicHttpGoAwayFieldsDecoderTest, DecodesRandomized) { + TestDecodingRandomizedStructures(); +} + +//------------------------------------------------------------------------------ + +class QuicHttpWindowUpdateFieldsDecoderTest + : public QuicHttpStructureDecoderTest<QuicHttpWindowUpdateFields> {}; + +TEST_F(QuicHttpWindowUpdateFieldsDecoderTest, DecodesLiteral) { + { + // clang-format off + const char kData[] = { + 0x00, 0x01, 0x00, 0x00, // Window Size Increment: 2 ^ 16 + }; + // clang-format on + ASSERT_TRUE(DecodeLeadingStructure(kData)); + EXPECT_EQ(1u << 16, structure_.window_size_increment); + } + { + // Increment must be non-zero, but we need to be able to decode the invalid + // zero to detect it. + // clang-format off + const char kData[] = { + 0x00, 0x00, 0x00, 0x00, // Window Size Increment: 0 + }; + // clang-format on + ASSERT_TRUE(DecodeLeadingStructure(kData)); + EXPECT_EQ(0u, structure_.window_size_increment); + } + { + // Increment has R-bit (reserved for future use) set, which + // should be cleared by the decoder. + // clang-format off + const unsigned char kData[] = { + // Window Size Increment: max uint31 and R-bit + 0xff, 0xff, 0xff, 0xff, + }; + // clang-format on + ASSERT_TRUE(DecodeLeadingStructure(kData)); + EXPECT_EQ(QuicHttpStreamIdMask(), structure_.window_size_increment); + } +} + +TEST_F(QuicHttpWindowUpdateFieldsDecoderTest, DecodesRandomized) { + TestDecodingRandomizedStructures(); +} + +//------------------------------------------------------------------------------ + +class QuicHttpAltSvcFieldsDecoderTest + : public QuicHttpStructureDecoderTest<QuicHttpAltSvcFields> {}; + +TEST_F(QuicHttpAltSvcFieldsDecoderTest, DecodesLiteral) { + { + // clang-format off + const char kData[] = { + 0x00, 0x00, // Origin Length: 0 + }; + // clang-format on + ASSERT_TRUE(DecodeLeadingStructure(kData)); + EXPECT_EQ(0u, structure_.origin_length); + } + { + // clang-format off + const char kData[] = { + 0x00, 0x14, // Origin Length: 20 + }; + // clang-format on + ASSERT_TRUE(DecodeLeadingStructure(kData)); + EXPECT_EQ(20u, structure_.origin_length); + } + { + // clang-format off + const unsigned char kData[] = { + 0xff, 0xff, // Origin Length: uint16 max + }; + // clang-format on + ASSERT_TRUE(DecodeLeadingStructure(kData)); + EXPECT_EQ(65535u, structure_.origin_length); + } +} + +TEST_F(QuicHttpAltSvcFieldsDecoderTest, DecodesRandomized) { + TestDecodingRandomizedStructures(); +} + +} // namespace +} // namespace test +} // namespace net
diff --git a/net/quic/http/decoder/quic_http_structure_decoder_test_util.cc b/net/quic/http/decoder/quic_http_structure_decoder_test_util.cc new file mode 100644 index 0000000..7a9b7ae5 --- /dev/null +++ b/net/quic/http/decoder/quic_http_structure_decoder_test_util.cc
@@ -0,0 +1,19 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/decoder/quic_http_structure_decoder_test_util.h" + +namespace net { +namespace test { + +void QuicHttpStructureDecoderPeer::Randomize(QuicHttpStructureDecoder* p, + QuicTestRandomBase* rng) { + p->offset_ = rng->Rand32(); + for (size_t i = 0; i < sizeof p->buffer_; ++i) { + p->buffer_[i] = rng->Rand8(); + } +} + +} // namespace test +} // namespace net
diff --git a/net/quic/http/decoder/quic_http_structure_decoder_test_util.h b/net/quic/http/decoder/quic_http_structure_decoder_test_util.h new file mode 100644 index 0000000..c37de6a1 --- /dev/null +++ b/net/quic/http/decoder/quic_http_structure_decoder_test_util.h
@@ -0,0 +1,23 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_HTTP_DECODER_QUIC_HTTP_STRUCTURE_DECODER_TEST_UTIL_H_ +#define NET_QUIC_HTTP_DECODER_QUIC_HTTP_STRUCTURE_DECODER_TEST_UTIL_H_ + +#include "net/quic/http/decoder/quic_http_structure_decoder.h" +#include "net/quic/platform/api/quic_test_random.h" + +namespace net { +namespace test { + +class QuicHttpStructureDecoderPeer { + public: + // Overwrite the QuicHttpStructureDecoder instance with random values. + static void Randomize(QuicHttpStructureDecoder* p, QuicTestRandomBase* rng); +}; + +} // namespace test +} // namespace net + +#endif // NET_QUIC_HTTP_DECODER_QUIC_HTTP_STRUCTURE_DECODER_TEST_UTIL_H_
diff --git a/net/quic/http/quic_http_constants.cc b/net/quic/http/quic_http_constants.cc new file mode 100644 index 0000000..1083040 --- /dev/null +++ b/net/quic/http/quic_http_constants.cc
@@ -0,0 +1,156 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/quic_http_constants.h" + +#include "base/logging.h" +#include "net/quic/platform/api/quic_str_cat.h" +#include "net/quic/platform/api/quic_string_piece.h" +#include "net/quic/platform/api/quic_string_utils.h" +#include "net/quic/platform/api/quic_text_utils.h" + +namespace net { + +QuicString QuicHttpFrameTypeToString(QuicHttpFrameType v) { + switch (v) { + case QuicHttpFrameType::DATA: + return "DATA"; + case QuicHttpFrameType::HEADERS: + return "HEADERS"; + case QuicHttpFrameType::QUIC_HTTP_PRIORITY: + return "QUIC_HTTP_PRIORITY"; + case QuicHttpFrameType::RST_STREAM: + return "RST_STREAM"; + case QuicHttpFrameType::SETTINGS: + return "SETTINGS"; + case QuicHttpFrameType::PUSH_PROMISE: + return "PUSH_PROMISE"; + case QuicHttpFrameType::PING: + return "PING"; + case QuicHttpFrameType::GOAWAY: + return "GOAWAY"; + case QuicHttpFrameType::WINDOW_UPDATE: + return "WINDOW_UPDATE"; + case QuicHttpFrameType::CONTINUATION: + return "CONTINUATION"; + case QuicHttpFrameType::ALTSVC: + return "ALTSVC"; + } + return QuicStrCat("UnknownFrameType(", static_cast<int>(v), ")"); +} + +QuicString QuicHttpFrameTypeToString(uint8_t v) { + return QuicHttpFrameTypeToString(static_cast<QuicHttpFrameType>(v)); +} + +QuicString QuicHttpFrameFlagsToString(QuicHttpFrameType type, uint8_t flags) { + QuicString s; + // Closure to append flag name |v| to the QuicString |s|, + // and to clear |bit| from |flags|. + auto append_and_clear = [&s, &flags](QuicStringPiece v, uint8_t bit) { + if (!s.empty()) { + s.push_back('|'); + } + QuicStrAppend(&s, v); + flags ^= bit; + }; + if (flags & 0x01) { + if (type == QuicHttpFrameType::DATA || type == QuicHttpFrameType::HEADERS) { + append_and_clear("QUIC_HTTP_END_STREAM", + QuicHttpFrameFlag::QUIC_HTTP_END_STREAM); + } else if (type == QuicHttpFrameType::SETTINGS || + type == QuicHttpFrameType::PING) { + append_and_clear("QUIC_HTTP_ACK", QuicHttpFrameFlag::QUIC_HTTP_ACK); + } + } + if (flags & 0x04) { + if (type == QuicHttpFrameType::HEADERS || + type == QuicHttpFrameType::PUSH_PROMISE || + type == QuicHttpFrameType::CONTINUATION) { + append_and_clear("QUIC_HTTP_END_HEADERS", + QuicHttpFrameFlag::QUIC_HTTP_END_HEADERS); + } + } + if (flags & 0x08) { + if (type == QuicHttpFrameType::DATA || type == QuicHttpFrameType::HEADERS || + type == QuicHttpFrameType::PUSH_PROMISE) { + append_and_clear("QUIC_HTTP_PADDED", QuicHttpFrameFlag::QUIC_HTTP_PADDED); + } + } + if (flags & 0x20) { + if (type == QuicHttpFrameType::HEADERS) { + append_and_clear("QUIC_HTTP_PRIORITY", + QuicHttpFrameFlag::QUIC_HTTP_PRIORITY); + } + } + if (flags != 0) { + append_and_clear(QuicStringPrintf("0x%02x", flags), flags); + } + DCHECK_EQ(0, flags); + return s; +} +QuicString QuicHttpFrameFlagsToString(uint8_t type, uint8_t flags) { + return QuicHttpFrameFlagsToString(static_cast<QuicHttpFrameType>(type), + flags); +} + +QuicString QuicHttpErrorCodeToString(uint32_t v) { + switch (v) { + case 0x0: + return "NO_ERROR"; + case 0x1: + return "PROTOCOL_ERROR"; + case 0x2: + return "INTERNAL_ERROR"; + case 0x3: + return "FLOW_CONTROL_ERROR"; + case 0x4: + return "SETTINGS_TIMEOUT"; + case 0x5: + return "STREAM_CLOSED"; + case 0x6: + return "FRAME_SIZE_ERROR"; + case 0x7: + return "REFUSED_STREAM"; + case 0x8: + return "CANCEL"; + case 0x9: + return "COMPRESSION_ERROR"; + case 0xa: + return "CONNECT_ERROR"; + case 0xb: + return "ENHANCE_YOUR_CALM"; + case 0xc: + return "INADEQUATE_SECURITY"; + case 0xd: + return "HTTP_1_1_REQUIRED"; + } + return QuicStrCat("UnknownErrorCode(0x", QuicTextUtils::Hex(v), ")"); +} +QuicString QuicHttpErrorCodeToString(QuicHttpErrorCode v) { + return QuicHttpErrorCodeToString(static_cast<uint32_t>(v)); +} + +QuicString QuicHttpSettingsParameterToString(uint32_t v) { + switch (v) { + case 0x1: + return "HEADER_TABLE_SIZE"; + case 0x2: + return "ENABLE_PUSH"; + case 0x3: + return "MAX_CONCURRENT_STREAMS"; + case 0x4: + return "INITIAL_WINDOW_SIZE"; + case 0x5: + return "MAX_FRAME_SIZE"; + case 0x6: + return "MAX_HEADER_LIST_SIZE"; + } + return QuicStrCat("UnknownSettingsParameter(0x", QuicTextUtils::Hex(v), ")"); +} +QuicString QuicHttpSettingsParameterToString(QuicHttpSettingsParameter v) { + return QuicHttpSettingsParameterToString(static_cast<uint32_t>(v)); +} + +} // namespace net
diff --git a/net/quic/http/quic_http_constants.h b/net/quic/http/quic_http_constants.h new file mode 100644 index 0000000..1338dc2 --- /dev/null +++ b/net/quic/http/quic_http_constants.h
@@ -0,0 +1,262 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_HTTP_QUIC_HTTP_CONSTANTS_H_ +#define NET_QUIC_HTTP_QUIC_HTTP_CONSTANTS_H_ + +// Constants from the HTTP/2 spec, RFC 7540, and associated helper functions. + +#include <cstdint> +#include <iosfwd> + +#include "net/quic/platform/api/quic_export.h" +#include "net/quic/platform/api/quic_string.h" + +namespace net { + +// TODO(jamessynge): create http2_simple_types for types similar to +// SpdyStreamId, but not for structures like QuicHttpFrameHeader. Then will be +// able to move these stream id functions there. +constexpr uint32_t QuicHttpUint31Mask() { + return 0x7fffffff; +} +constexpr uint32_t QuicHttpStreamIdMask() { + return QuicHttpUint31Mask(); +} + +// The value used to identify types of frames. Upper case to match the RFC. +// The comments indicate which flags are valid for that frame type. +// ALTSVC is defined in http://httpwg.org/http-extensions/alt-svc.html +// (not yet final standard as of March 2016, but close). +enum class QuicHttpFrameType : uint8_t { + DATA = 0, // QUIC_HTTP_END_STREAM | QUIC_HTTP_PADDED + HEADERS = 1, // QUIC_HTTP_END_STREAM | QUIC_HTTP_END_HEADERS | + // QUIC_HTTP_PADDED | QUIC_HTTP_PRIORITY + QUIC_HTTP_PRIORITY = 2, // + RST_STREAM = 3, // + SETTINGS = 4, // QUIC_HTTP_ACK + PUSH_PROMISE = 5, // QUIC_HTTP_END_HEADERS | QUIC_HTTP_PADDED + PING = 6, // QUIC_HTTP_ACK + GOAWAY = 7, // + WINDOW_UPDATE = 8, // + CONTINUATION = 9, // QUIC_HTTP_END_HEADERS + ALTSVC = 10, // +}; + +// Is the frame type known/supported? +inline bool IsSupportedQuicHttpFrameType(uint32_t v) { + return v <= static_cast<uint32_t>(QuicHttpFrameType::ALTSVC); +} +inline bool IsSupportedQuicHttpFrameType(QuicHttpFrameType v) { + return IsSupportedQuicHttpFrameType(static_cast<uint32_t>(v)); +} + +// The return type is 'std::string' so that they can generate a unique +// std::string for each unsupported value. Since these are just used for +// debugging/error messages, that isn't a cost to we need to worry about. The +// same applies to the functions later in this file. +QUIC_EXPORT_PRIVATE QuicString QuicHttpFrameTypeToString(QuicHttpFrameType v); +QUIC_EXPORT_PRIVATE QuicString QuicHttpFrameTypeToString(uint8_t v); +QUIC_EXPORT_PRIVATE inline std::ostream& operator<<(std::ostream& out, + QuicHttpFrameType v) { + return out << QuicHttpFrameTypeToString(v); +} + +// Flags that appear in supported frame types. These are treated as bit masks. +// The comments indicate for which frame types the flag is valid. +enum QuicHttpFrameFlag { + QUIC_HTTP_END_STREAM = 0x01, // DATA, HEADERS + QUIC_HTTP_ACK = 0x01, // SETTINGS, PING + QUIC_HTTP_END_HEADERS = 0x04, // HEADERS, PUSH_PROMISE, CONTINUATION + QUIC_HTTP_PADDED = 0x08, // DATA, HEADERS, PUSH_PROMISE + QUIC_HTTP_PRIORITY = 0x20, // HEADERS +}; + +// Formats zero or more flags for the specified type of frame. Returns an +// empty std::string if flags==0. +QUIC_EXPORT_PRIVATE QuicString +QuicHttpFrameFlagsToString(QuicHttpFrameType type, uint8_t flags); +QUIC_EXPORT_PRIVATE QuicString QuicHttpFrameFlagsToString(uint8_t type, + uint8_t flags); + +// Error codes for GOAWAY and RST_STREAM frames. +enum class QuicHttpErrorCode : uint32_t { + // The associated condition is not a result of an error. For example, a GOAWAY + // might include this code to indicate graceful shutdown of a connection. + HTTP2_NO_ERROR = 0x0, + + // The endpoint detected an unspecific protocol error. This error is for use + // when a more specific error code is not available. + PROTOCOL_ERROR = 0x1, + + // The endpoint encountered an unexpected internal error. + INTERNAL_ERROR = 0x2, + + // The endpoint detected that its peer violated the flow-control protocol. + FLOW_CONTROL_ERROR = 0x3, + + // The endpoint sent a SETTINGS frame but did not receive a response in a + // timely manner. See Section 6.5.3 ("Settings Synchronization"). + SETTINGS_TIMEOUT = 0x4, + + // The endpoint received a frame after a stream was half-closed. + STREAM_CLOSED = 0x5, + + // The endpoint received a frame with an invalid size. + FRAME_SIZE_ERROR = 0x6, + + // The endpoint refused the stream prior to performing any application + // processing (see Section 8.1.4 for details). + REFUSED_STREAM = 0x7, + + // Used by the endpoint to indicate that the stream is no longer needed. + CANCEL = 0x8, + + // The endpoint is unable to maintain the header compression context + // for the connection. + COMPRESSION_ERROR = 0x9, + + // The connection established in response to a CONNECT request (Section 8.3) + // was reset or abnormally closed. + CONNECT_ERROR = 0xa, + + // The endpoint detected that its peer is exhibiting a behavior that might + // be generating excessive load. + ENHANCE_YOUR_CALM = 0xb, + + // The underlying transport has properties that do not meet minimum + // security requirements (see Section 9.2). + INADEQUATE_SECURITY = 0xc, + + // The endpoint requires that HTTP/1.1 be used instead of HTTP/2. + HTTP_1_1_REQUIRED = 0xd, +}; + +// Is the error code supported? (So far that means it is in RFC 7540.) +inline bool IsSupportedQuicHttpErrorCode(uint32_t v) { + return v <= static_cast<uint32_t>(QuicHttpErrorCode::HTTP_1_1_REQUIRED); +} +inline bool IsSupportedQuicHttpErrorCode(QuicHttpErrorCode v) { + return IsSupportedQuicHttpErrorCode(static_cast<uint32_t>(v)); +} + +// Format the specified error code. +QUIC_EXPORT_PRIVATE QuicString QuicHttpErrorCodeToString(uint32_t v); +QUIC_EXPORT_PRIVATE QuicString QuicHttpErrorCodeToString(QuicHttpErrorCode v); +QUIC_EXPORT_PRIVATE inline std::ostream& operator<<(std::ostream& out, + QuicHttpErrorCode v) { + return out << QuicHttpErrorCodeToString(v); +} + +// Supported parameters in SETTINGS frames; so far just those in RFC 7540. +enum class QuicHttpSettingsParameter : uint16_t { + // Allows the sender to inform the remote endpoint of the maximum size of the + // header compression table used to decode header blocks, in octets. The + // encoder can select any size equal to or less than this value by using + // signaling specific to the header compression format inside a header block + // (see [COMPRESSION]). The initial value is 4,096 octets. + HEADER_TABLE_SIZE = 0x1, + + // This setting can be used to disable server push (Section 8.2). An endpoint + // MUST NOT send a PUSH_PROMISE frame if it receives this parameter set to a + // value of 0. An endpoint that has both set this parameter to 0 and had it + // acknowledged MUST treat the receipt of a PUSH_PROMISE frame as a connection + // error (Section 5.4.1) of type PROTOCOL_ERROR. + // + // The initial value is 1, which indicates that server push is permitted. Any + // value other than 0 or 1 MUST be treated as a connection error (Section + // 5.4.1) of type PROTOCOL_ERROR. + ENABLE_PUSH = 0x2, + + // Indicates the maximum number of concurrent streams that the sender will + // allow. This limit is directional: it applies to the number of streams that + // the sender permits the receiver to create. Initially, there is no limit to + // this value. It is recommended that this value be no smaller than 100, so as + // to not unnecessarily limit parallelism. + // + // A value of 0 for MAX_CONCURRENT_STREAMS SHOULD NOT be treated as + // special by endpoints. A zero value does prevent the creation of new + // streams; however, this can also happen for any limit that is exhausted with + // active streams. Servers SHOULD only set a zero value for short durations; + // if a server does not wish to accept requests, closing the connection is + // more appropriate. + MAX_CONCURRENT_STREAMS = 0x3, + + // Indicates the sender's initial window size (in octets) for stream-level + // flow control. The initial value is 2^16-1 (65,535) octets. + // + // This setting affects the window size of all streams (see Section 6.9.2). + // + // Values above the maximum flow-control window size of 2^31-1 MUST be treated + // as a connection error (Section 5.4.1) of type FLOW_CONTROL_ERROR. + INITIAL_WINDOW_SIZE = 0x4, + + // Indicates the size of the largest frame payload that the sender is willing + // to receive, in octets. + // + // The initial value is 2^14 (16,384) octets. The value advertised by an + // endpoint MUST be between this initial value and the maximum allowed frame + // size (2^24-1 or 16,777,215 octets), inclusive. Values outside this range + // MUST be treated as a connection error (Section 5.4.1) of type + // PROTOCOL_ERROR. + MAX_FRAME_SIZE = 0x5, + + // This advisory setting informs a peer of the maximum size of header list + // that the sender is prepared to accept, in octets. The value is based on the + // uncompressed size of header fields, including the length of the name and + // value in octets plus an overhead of 32 octets for each header field. + // + // For any given request, a lower limit than what is advertised MAY be + // enforced. The initial value of this setting is unlimited. + MAX_HEADER_LIST_SIZE = 0x6, +}; + +// Is the settings parameter supported (so far that means it is in RFC 7540)? +inline bool IsSupportedQuicHttpSettingsParameter(uint32_t v) { + return 0 < v && v <= static_cast<uint32_t>( + QuicHttpSettingsParameter::MAX_HEADER_LIST_SIZE); +} +inline bool IsSupportedQuicHttpSettingsParameter(QuicHttpSettingsParameter v) { + return IsSupportedQuicHttpSettingsParameter(static_cast<uint32_t>(v)); +} + +// Format the specified settings parameter. +QUIC_EXPORT_PRIVATE QuicString QuicHttpSettingsParameterToString(uint32_t v); +QUIC_EXPORT_PRIVATE QuicString +QuicHttpSettingsParameterToString(QuicHttpSettingsParameter v); +inline std::ostream& operator<<(std::ostream& out, + QuicHttpSettingsParameter v) { + return out << QuicHttpSettingsParameterToString(v); +} + +// Information about the initial, minimum and maximum value of settings (not +// applicable to all settings parameters). +class QuicHttpSettingsInfo { + public: + // Default value for HEADER_TABLE_SIZE. + static constexpr uint32_t DefaultHeaderTableSize() { return 4096; } + + // Default value for ENABLE_PUSH. + static constexpr bool DefaultEnablePush() { return true; } + + // Default value for INITIAL_WINDOW_SIZE. + static constexpr uint32_t DefaultInitialWindowSize() { return 65535; } + + // Maximum value for INITIAL_WINDOW_SIZE, and for the connection flow control + // window, and for each stream flow control window. + static constexpr uint32_t MaximumWindowSize() { return QuicHttpUint31Mask(); } + + // Default value for MAX_FRAME_SIZE. + static constexpr uint32_t DefaultMaxFrameSize() { return 16384; } + + // Minimum value for MAX_FRAME_SIZE. + static constexpr uint32_t MinimumMaxFrameSize() { return 16384; } + + // Maximum value for MAX_FRAME_SIZE. + static constexpr uint32_t MaximumMaxFrameSize() { return (1 << 24) - 1; } +}; + +} // namespace net + +#endif // NET_QUIC_HTTP_QUIC_HTTP_CONSTANTS_H_
diff --git a/net/quic/http/quic_http_constants_test.cc b/net/quic/http/quic_http_constants_test.cc new file mode 100644 index 0000000..23f7f46 --- /dev/null +++ b/net/quic/http/quic_http_constants_test.cc
@@ -0,0 +1,304 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/quic_http_constants.h" + +#include "testing/gtest/include/gtest/gtest.h" + +namespace net { +namespace test { +namespace { + +TEST(QuicHttpConstantsTest, QuicHttpFrameType) { + EXPECT_EQ(QuicHttpFrameType::DATA, static_cast<QuicHttpFrameType>(0)); + EXPECT_EQ(QuicHttpFrameType::HEADERS, static_cast<QuicHttpFrameType>(1)); + EXPECT_EQ(QuicHttpFrameType::QUIC_HTTP_PRIORITY, + static_cast<QuicHttpFrameType>(2)); + EXPECT_EQ(QuicHttpFrameType::RST_STREAM, static_cast<QuicHttpFrameType>(3)); + EXPECT_EQ(QuicHttpFrameType::SETTINGS, static_cast<QuicHttpFrameType>(4)); + EXPECT_EQ(QuicHttpFrameType::PUSH_PROMISE, static_cast<QuicHttpFrameType>(5)); + EXPECT_EQ(QuicHttpFrameType::PING, static_cast<QuicHttpFrameType>(6)); + EXPECT_EQ(QuicHttpFrameType::GOAWAY, static_cast<QuicHttpFrameType>(7)); + EXPECT_EQ(QuicHttpFrameType::WINDOW_UPDATE, + static_cast<QuicHttpFrameType>(8)); + EXPECT_EQ(QuicHttpFrameType::CONTINUATION, static_cast<QuicHttpFrameType>(9)); + EXPECT_EQ(QuicHttpFrameType::ALTSVC, static_cast<QuicHttpFrameType>(10)); +} + +TEST(QuicHttpConstantsTest, QuicHttpFrameTypeToString) { + EXPECT_EQ("DATA", QuicHttpFrameTypeToString(QuicHttpFrameType::DATA)); + EXPECT_EQ("HEADERS", QuicHttpFrameTypeToString(QuicHttpFrameType::HEADERS)); + EXPECT_EQ("QUIC_HTTP_PRIORITY", + QuicHttpFrameTypeToString(QuicHttpFrameType::QUIC_HTTP_PRIORITY)); + EXPECT_EQ("RST_STREAM", + QuicHttpFrameTypeToString(QuicHttpFrameType::RST_STREAM)); + EXPECT_EQ("SETTINGS", QuicHttpFrameTypeToString(QuicHttpFrameType::SETTINGS)); + EXPECT_EQ("PUSH_PROMISE", + QuicHttpFrameTypeToString(QuicHttpFrameType::PUSH_PROMISE)); + EXPECT_EQ("PING", QuicHttpFrameTypeToString(QuicHttpFrameType::PING)); + EXPECT_EQ("GOAWAY", QuicHttpFrameTypeToString(QuicHttpFrameType::GOAWAY)); + EXPECT_EQ("WINDOW_UPDATE", + QuicHttpFrameTypeToString(QuicHttpFrameType::WINDOW_UPDATE)); + EXPECT_EQ("CONTINUATION", + QuicHttpFrameTypeToString(QuicHttpFrameType::CONTINUATION)); + EXPECT_EQ("ALTSVC", QuicHttpFrameTypeToString(QuicHttpFrameType::ALTSVC)); + + EXPECT_EQ("DATA", QuicHttpFrameTypeToString(0)); + EXPECT_EQ("HEADERS", QuicHttpFrameTypeToString(1)); + EXPECT_EQ("QUIC_HTTP_PRIORITY", QuicHttpFrameTypeToString(2)); + EXPECT_EQ("RST_STREAM", QuicHttpFrameTypeToString(3)); + EXPECT_EQ("SETTINGS", QuicHttpFrameTypeToString(4)); + EXPECT_EQ("PUSH_PROMISE", QuicHttpFrameTypeToString(5)); + EXPECT_EQ("PING", QuicHttpFrameTypeToString(6)); + EXPECT_EQ("GOAWAY", QuicHttpFrameTypeToString(7)); + EXPECT_EQ("WINDOW_UPDATE", QuicHttpFrameTypeToString(8)); + EXPECT_EQ("CONTINUATION", QuicHttpFrameTypeToString(9)); + EXPECT_EQ("ALTSVC", QuicHttpFrameTypeToString(10)); + + EXPECT_EQ("UnknownFrameType(99)", QuicHttpFrameTypeToString(99)); +} + +TEST(QuicHttpConstantsTest, QuicHttpFrameFlag) { + EXPECT_EQ(QuicHttpFrameFlag::QUIC_HTTP_END_STREAM, + static_cast<QuicHttpFrameFlag>(0x01)); + EXPECT_EQ(QuicHttpFrameFlag::QUIC_HTTP_ACK, + static_cast<QuicHttpFrameFlag>(0x01)); + EXPECT_EQ(QuicHttpFrameFlag::QUIC_HTTP_END_HEADERS, + static_cast<QuicHttpFrameFlag>(0x04)); + EXPECT_EQ(QuicHttpFrameFlag::QUIC_HTTP_PADDED, + static_cast<QuicHttpFrameFlag>(0x08)); + EXPECT_EQ(QuicHttpFrameFlag::QUIC_HTTP_PRIORITY, + static_cast<QuicHttpFrameFlag>(0x20)); + + EXPECT_EQ(QuicHttpFrameFlag::QUIC_HTTP_END_STREAM, 0x01); + EXPECT_EQ(QuicHttpFrameFlag::QUIC_HTTP_ACK, 0x01); + EXPECT_EQ(QuicHttpFrameFlag::QUIC_HTTP_END_HEADERS, 0x04); + EXPECT_EQ(QuicHttpFrameFlag::QUIC_HTTP_PADDED, 0x08); + EXPECT_EQ(QuicHttpFrameFlag::QUIC_HTTP_PRIORITY, 0x20); +} + +TEST(QuicHttpConstantsTest, QuicHttpFrameFlagsToString) { + // Single flags... + + // 0b00000001 + EXPECT_EQ( + "QUIC_HTTP_END_STREAM", + QuicHttpFrameFlagsToString(QuicHttpFrameType::DATA, + QuicHttpFrameFlag::QUIC_HTTP_END_STREAM)); + EXPECT_EQ("QUIC_HTTP_END_STREAM", + QuicHttpFrameFlagsToString(QuicHttpFrameType::HEADERS, 0x01)); + EXPECT_EQ("QUIC_HTTP_ACK", + QuicHttpFrameFlagsToString(QuicHttpFrameType::SETTINGS, + QuicHttpFrameFlag::QUIC_HTTP_ACK)); + EXPECT_EQ("QUIC_HTTP_ACK", + QuicHttpFrameFlagsToString(QuicHttpFrameType::PING, 0x01)); + + // 0b00000010 + EXPECT_EQ("0x02", QuicHttpFrameFlagsToString(0xff, 0x02)); + + // 0b00000100 + EXPECT_EQ( + "QUIC_HTTP_END_HEADERS", + QuicHttpFrameFlagsToString(QuicHttpFrameType::HEADERS, + QuicHttpFrameFlag::QUIC_HTTP_END_HEADERS)); + EXPECT_EQ("QUIC_HTTP_END_HEADERS", + QuicHttpFrameFlagsToString(QuicHttpFrameType::PUSH_PROMISE, 0x04)); + EXPECT_EQ("QUIC_HTTP_END_HEADERS", QuicHttpFrameFlagsToString(0x09, 0x04)); + EXPECT_EQ("0x04", QuicHttpFrameFlagsToString(0xff, 0x04)); + + // 0b00001000 + EXPECT_EQ("QUIC_HTTP_PADDED", + QuicHttpFrameFlagsToString(QuicHttpFrameType::DATA, + QuicHttpFrameFlag::QUIC_HTTP_PADDED)); + EXPECT_EQ("QUIC_HTTP_PADDED", + QuicHttpFrameFlagsToString(QuicHttpFrameType::HEADERS, 0x08)); + EXPECT_EQ("QUIC_HTTP_PADDED", QuicHttpFrameFlagsToString(0x05, 0x08)); + EXPECT_EQ("0x08", QuicHttpFrameFlagsToString( + 0xff, QuicHttpFrameFlag::QUIC_HTTP_PADDED)); + + // 0b00010000 + EXPECT_EQ("0x10", + QuicHttpFrameFlagsToString(QuicHttpFrameType::SETTINGS, 0x10)); + + // 0b00100000 + EXPECT_EQ("QUIC_HTTP_PRIORITY", + QuicHttpFrameFlagsToString(QuicHttpFrameType::HEADERS, 0x20)); + EXPECT_EQ("0x20", + QuicHttpFrameFlagsToString(QuicHttpFrameType::PUSH_PROMISE, 0x20)); + + // 0b01000000 + EXPECT_EQ("0x40", QuicHttpFrameFlagsToString(0xff, 0x40)); + + // 0b10000000 + EXPECT_EQ("0x80", QuicHttpFrameFlagsToString(0xff, 0x80)); + + // Combined flags... + + EXPECT_EQ("QUIC_HTTP_END_STREAM|QUIC_HTTP_PADDED|0xf6", + QuicHttpFrameFlagsToString(QuicHttpFrameType::DATA, 0xff)); + EXPECT_EQ( + "QUIC_HTTP_END_STREAM|QUIC_HTTP_END_HEADERS|QUIC_HTTP_PADDED|QUIC_HTTP_" + "PRIORITY|0xd2", + QuicHttpFrameFlagsToString(QuicHttpFrameType::HEADERS, 0xff)); + EXPECT_EQ("0xff", QuicHttpFrameFlagsToString( + QuicHttpFrameType::QUIC_HTTP_PRIORITY, 0xff)); + EXPECT_EQ("0xff", + QuicHttpFrameFlagsToString(QuicHttpFrameType::RST_STREAM, 0xff)); + EXPECT_EQ("QUIC_HTTP_ACK|0xfe", + QuicHttpFrameFlagsToString(QuicHttpFrameType::SETTINGS, 0xff)); + EXPECT_EQ("QUIC_HTTP_END_HEADERS|QUIC_HTTP_PADDED|0xf3", + QuicHttpFrameFlagsToString(QuicHttpFrameType::PUSH_PROMISE, 0xff)); + EXPECT_EQ("QUIC_HTTP_ACK|0xfe", + QuicHttpFrameFlagsToString(QuicHttpFrameType::PING, 0xff)); + EXPECT_EQ("0xff", + QuicHttpFrameFlagsToString(QuicHttpFrameType::GOAWAY, 0xff)); + EXPECT_EQ("0xff", + QuicHttpFrameFlagsToString(QuicHttpFrameType::WINDOW_UPDATE, 0xff)); + EXPECT_EQ("QUIC_HTTP_END_HEADERS|0xfb", + QuicHttpFrameFlagsToString(QuicHttpFrameType::CONTINUATION, 0xff)); + EXPECT_EQ("0xff", + QuicHttpFrameFlagsToString(QuicHttpFrameType::ALTSVC, 0xff)); + EXPECT_EQ("0xff", QuicHttpFrameFlagsToString(0xff, 0xff)); +} + +TEST(QuicHttpConstantsTest, QuicHttpErrorCode) { + EXPECT_EQ(QuicHttpErrorCode::HTTP2_NO_ERROR, + static_cast<QuicHttpErrorCode>(0x0)); + EXPECT_EQ(QuicHttpErrorCode::PROTOCOL_ERROR, + static_cast<QuicHttpErrorCode>(0x1)); + EXPECT_EQ(QuicHttpErrorCode::INTERNAL_ERROR, + static_cast<QuicHttpErrorCode>(0x2)); + EXPECT_EQ(QuicHttpErrorCode::FLOW_CONTROL_ERROR, + static_cast<QuicHttpErrorCode>(0x3)); + EXPECT_EQ(QuicHttpErrorCode::SETTINGS_TIMEOUT, + static_cast<QuicHttpErrorCode>(0x4)); + EXPECT_EQ(QuicHttpErrorCode::STREAM_CLOSED, + static_cast<QuicHttpErrorCode>(0x5)); + EXPECT_EQ(QuicHttpErrorCode::FRAME_SIZE_ERROR, + static_cast<QuicHttpErrorCode>(0x6)); + EXPECT_EQ(QuicHttpErrorCode::REFUSED_STREAM, + static_cast<QuicHttpErrorCode>(0x7)); + EXPECT_EQ(QuicHttpErrorCode::CANCEL, static_cast<QuicHttpErrorCode>(0x8)); + EXPECT_EQ(QuicHttpErrorCode::COMPRESSION_ERROR, + static_cast<QuicHttpErrorCode>(0x9)); + EXPECT_EQ(QuicHttpErrorCode::CONNECT_ERROR, + static_cast<QuicHttpErrorCode>(0xa)); + EXPECT_EQ(QuicHttpErrorCode::ENHANCE_YOUR_CALM, + static_cast<QuicHttpErrorCode>(0xb)); + EXPECT_EQ(QuicHttpErrorCode::INADEQUATE_SECURITY, + static_cast<QuicHttpErrorCode>(0xc)); + EXPECT_EQ(QuicHttpErrorCode::HTTP_1_1_REQUIRED, + static_cast<QuicHttpErrorCode>(0xd)); +} + +TEST(QuicHttpConstantsTest, QuicHttpErrorCodeToString) { + EXPECT_EQ("NO_ERROR", + QuicHttpErrorCodeToString(QuicHttpErrorCode::HTTP2_NO_ERROR)); + EXPECT_EQ("NO_ERROR", QuicHttpErrorCodeToString(0x0)); + EXPECT_EQ("PROTOCOL_ERROR", + QuicHttpErrorCodeToString(QuicHttpErrorCode::PROTOCOL_ERROR)); + EXPECT_EQ("PROTOCOL_ERROR", QuicHttpErrorCodeToString(0x1)); + EXPECT_EQ("INTERNAL_ERROR", + QuicHttpErrorCodeToString(QuicHttpErrorCode::INTERNAL_ERROR)); + EXPECT_EQ("INTERNAL_ERROR", QuicHttpErrorCodeToString(0x2)); + EXPECT_EQ("FLOW_CONTROL_ERROR", + QuicHttpErrorCodeToString(QuicHttpErrorCode::FLOW_CONTROL_ERROR)); + EXPECT_EQ("FLOW_CONTROL_ERROR", QuicHttpErrorCodeToString(0x3)); + EXPECT_EQ("SETTINGS_TIMEOUT", + QuicHttpErrorCodeToString(QuicHttpErrorCode::SETTINGS_TIMEOUT)); + EXPECT_EQ("SETTINGS_TIMEOUT", QuicHttpErrorCodeToString(0x4)); + EXPECT_EQ("STREAM_CLOSED", + QuicHttpErrorCodeToString(QuicHttpErrorCode::STREAM_CLOSED)); + EXPECT_EQ("STREAM_CLOSED", QuicHttpErrorCodeToString(0x5)); + EXPECT_EQ("FRAME_SIZE_ERROR", + QuicHttpErrorCodeToString(QuicHttpErrorCode::FRAME_SIZE_ERROR)); + EXPECT_EQ("FRAME_SIZE_ERROR", QuicHttpErrorCodeToString(0x6)); + EXPECT_EQ("REFUSED_STREAM", + QuicHttpErrorCodeToString(QuicHttpErrorCode::REFUSED_STREAM)); + EXPECT_EQ("REFUSED_STREAM", QuicHttpErrorCodeToString(0x7)); + EXPECT_EQ("CANCEL", QuicHttpErrorCodeToString(QuicHttpErrorCode::CANCEL)); + EXPECT_EQ("CANCEL", QuicHttpErrorCodeToString(0x8)); + EXPECT_EQ("COMPRESSION_ERROR", + QuicHttpErrorCodeToString(QuicHttpErrorCode::COMPRESSION_ERROR)); + EXPECT_EQ("COMPRESSION_ERROR", QuicHttpErrorCodeToString(0x9)); + EXPECT_EQ("CONNECT_ERROR", + QuicHttpErrorCodeToString(QuicHttpErrorCode::CONNECT_ERROR)); + EXPECT_EQ("CONNECT_ERROR", QuicHttpErrorCodeToString(0xa)); + EXPECT_EQ("ENHANCE_YOUR_CALM", + QuicHttpErrorCodeToString(QuicHttpErrorCode::ENHANCE_YOUR_CALM)); + EXPECT_EQ("ENHANCE_YOUR_CALM", QuicHttpErrorCodeToString(0xb)); + EXPECT_EQ("INADEQUATE_SECURITY", + QuicHttpErrorCodeToString(QuicHttpErrorCode::INADEQUATE_SECURITY)); + EXPECT_EQ("INADEQUATE_SECURITY", QuicHttpErrorCodeToString(0xc)); + EXPECT_EQ("HTTP_1_1_REQUIRED", + QuicHttpErrorCodeToString(QuicHttpErrorCode::HTTP_1_1_REQUIRED)); + EXPECT_EQ("HTTP_1_1_REQUIRED", QuicHttpErrorCodeToString(0xd)); + + EXPECT_EQ("UnknownErrorCode(0x123)", QuicHttpErrorCodeToString(0x123)); +} + +TEST(QuicHttpConstantsTest, QuicHttpSettingsParameter) { + EXPECT_EQ(QuicHttpSettingsParameter::HEADER_TABLE_SIZE, + static_cast<QuicHttpSettingsParameter>(0x1)); + EXPECT_EQ(QuicHttpSettingsParameter::ENABLE_PUSH, + static_cast<QuicHttpSettingsParameter>(0x2)); + EXPECT_EQ(QuicHttpSettingsParameter::MAX_CONCURRENT_STREAMS, + static_cast<QuicHttpSettingsParameter>(0x3)); + EXPECT_EQ(QuicHttpSettingsParameter::INITIAL_WINDOW_SIZE, + static_cast<QuicHttpSettingsParameter>(0x4)); + EXPECT_EQ(QuicHttpSettingsParameter::MAX_FRAME_SIZE, + static_cast<QuicHttpSettingsParameter>(0x5)); + EXPECT_EQ(QuicHttpSettingsParameter::MAX_HEADER_LIST_SIZE, + static_cast<QuicHttpSettingsParameter>(0x6)); + + EXPECT_TRUE(IsSupportedQuicHttpSettingsParameter( + QuicHttpSettingsParameter::HEADER_TABLE_SIZE)); + EXPECT_TRUE(IsSupportedQuicHttpSettingsParameter( + QuicHttpSettingsParameter::ENABLE_PUSH)); + EXPECT_TRUE(IsSupportedQuicHttpSettingsParameter( + QuicHttpSettingsParameter::MAX_CONCURRENT_STREAMS)); + EXPECT_TRUE(IsSupportedQuicHttpSettingsParameter( + QuicHttpSettingsParameter::INITIAL_WINDOW_SIZE)); + EXPECT_TRUE(IsSupportedQuicHttpSettingsParameter( + QuicHttpSettingsParameter::MAX_FRAME_SIZE)); + EXPECT_TRUE(IsSupportedQuicHttpSettingsParameter( + QuicHttpSettingsParameter::MAX_HEADER_LIST_SIZE)); + + EXPECT_FALSE(IsSupportedQuicHttpSettingsParameter( + static_cast<QuicHttpSettingsParameter>(0))); + EXPECT_FALSE(IsSupportedQuicHttpSettingsParameter( + static_cast<QuicHttpSettingsParameter>(7))); +} + +TEST(QuicHttpConstantsTest, QuicHttpSettingsParameterToString) { + EXPECT_EQ("HEADER_TABLE_SIZE", + QuicHttpSettingsParameterToString( + QuicHttpSettingsParameter::HEADER_TABLE_SIZE)); + EXPECT_EQ("HEADER_TABLE_SIZE", QuicHttpSettingsParameterToString(0x1)); + EXPECT_EQ("ENABLE_PUSH", QuicHttpSettingsParameterToString( + QuicHttpSettingsParameter::ENABLE_PUSH)); + EXPECT_EQ("ENABLE_PUSH", QuicHttpSettingsParameterToString(0x2)); + EXPECT_EQ("MAX_CONCURRENT_STREAMS", + QuicHttpSettingsParameterToString( + QuicHttpSettingsParameter::MAX_CONCURRENT_STREAMS)); + EXPECT_EQ("MAX_CONCURRENT_STREAMS", QuicHttpSettingsParameterToString(0x3)); + EXPECT_EQ("INITIAL_WINDOW_SIZE", + QuicHttpSettingsParameterToString( + QuicHttpSettingsParameter::INITIAL_WINDOW_SIZE)); + EXPECT_EQ("INITIAL_WINDOW_SIZE", QuicHttpSettingsParameterToString(0x4)); + EXPECT_EQ("MAX_FRAME_SIZE", QuicHttpSettingsParameterToString( + QuicHttpSettingsParameter::MAX_FRAME_SIZE)); + EXPECT_EQ("MAX_FRAME_SIZE", QuicHttpSettingsParameterToString(0x5)); + EXPECT_EQ("MAX_HEADER_LIST_SIZE", + QuicHttpSettingsParameterToString( + QuicHttpSettingsParameter::MAX_HEADER_LIST_SIZE)); + EXPECT_EQ("MAX_HEADER_LIST_SIZE", QuicHttpSettingsParameterToString(0x6)); + + EXPECT_EQ("UnknownSettingsParameter(0x123)", + QuicHttpSettingsParameterToString(0x123)); +} + +} // namespace +} // namespace test +} // namespace net
diff --git a/net/quic/http/quic_http_constants_test_util.cc b/net/quic/http/quic_http_constants_test_util.cc new file mode 100644 index 0000000..ddfc030 --- /dev/null +++ b/net/quic/http/quic_http_constants_test_util.cc
@@ -0,0 +1,145 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/quic_http_constants_test_util.h" + +namespace net { +namespace test { + +std::vector<QuicHttpFrameType> AllQuicHttpFrameTypes() { + // clang-format off + return { + QuicHttpFrameType::DATA, + QuicHttpFrameType::HEADERS, + QuicHttpFrameType::QUIC_HTTP_PRIORITY, + QuicHttpFrameType::RST_STREAM, + QuicHttpFrameType::SETTINGS, + QuicHttpFrameType::PUSH_PROMISE, + QuicHttpFrameType::PING, + QuicHttpFrameType::GOAWAY, + QuicHttpFrameType::WINDOW_UPDATE, + QuicHttpFrameType::CONTINUATION, + QuicHttpFrameType::ALTSVC, + }; + // clang-format on +} + +std::vector<QuicHttpFrameFlag> AllQuicHttpFrameFlagsForFrameType( + QuicHttpFrameType type) { + // clang-format off + switch (type) { + case QuicHttpFrameType::DATA: + return { + QuicHttpFrameFlag::QUIC_HTTP_END_STREAM, + QuicHttpFrameFlag::QUIC_HTTP_PADDED, + }; + case QuicHttpFrameType::HEADERS: + return { + QuicHttpFrameFlag::QUIC_HTTP_END_STREAM, + QuicHttpFrameFlag::QUIC_HTTP_END_HEADERS, + QuicHttpFrameFlag::QUIC_HTTP_PADDED, + QuicHttpFrameFlag::QUIC_HTTP_PRIORITY, + }; + case QuicHttpFrameType::SETTINGS: + return { + QuicHttpFrameFlag::QUIC_HTTP_ACK, + }; + case QuicHttpFrameType::PUSH_PROMISE: + return { + QuicHttpFrameFlag::QUIC_HTTP_END_HEADERS, + QuicHttpFrameFlag::QUIC_HTTP_PADDED, + }; + case QuicHttpFrameType::PING: + return { + QuicHttpFrameFlag::QUIC_HTTP_ACK, + }; + case QuicHttpFrameType::CONTINUATION: + return { + QuicHttpFrameFlag::QUIC_HTTP_END_HEADERS, + }; + default: + return {}; + } + // clang-format on +} + +std::vector<QuicHttpErrorCode> AllQuicHttpErrorCodes() { + // clang-format off + return { + QuicHttpErrorCode::HTTP2_NO_ERROR, + QuicHttpErrorCode::PROTOCOL_ERROR, + QuicHttpErrorCode::INTERNAL_ERROR, + QuicHttpErrorCode::FLOW_CONTROL_ERROR, + QuicHttpErrorCode::SETTINGS_TIMEOUT, + QuicHttpErrorCode::STREAM_CLOSED, + QuicHttpErrorCode::FRAME_SIZE_ERROR, + QuicHttpErrorCode::REFUSED_STREAM, + QuicHttpErrorCode::CANCEL, + QuicHttpErrorCode::COMPRESSION_ERROR, + QuicHttpErrorCode::CONNECT_ERROR, + QuicHttpErrorCode::ENHANCE_YOUR_CALM, + QuicHttpErrorCode::INADEQUATE_SECURITY, + QuicHttpErrorCode::HTTP_1_1_REQUIRED, + }; + // clang-format on +} + +std::vector<QuicHttpSettingsParameter> AllQuicHttpSettingsParameters() { + // clang-format off + return { + QuicHttpSettingsParameter::HEADER_TABLE_SIZE, + QuicHttpSettingsParameter::ENABLE_PUSH, + QuicHttpSettingsParameter::MAX_CONCURRENT_STREAMS, + QuicHttpSettingsParameter::INITIAL_WINDOW_SIZE, + QuicHttpSettingsParameter::MAX_FRAME_SIZE, + QuicHttpSettingsParameter::MAX_HEADER_LIST_SIZE, + }; + // clang-format on +} + +// Returns a mask of flags supported for the specified frame type. Returns +// zero for unknown frame types. +uint8_t KnownFlagsMaskForFrameType(QuicHttpFrameType type) { + switch (type) { + case QuicHttpFrameType::DATA: + return QuicHttpFrameFlag::QUIC_HTTP_END_STREAM | + QuicHttpFrameFlag::QUIC_HTTP_PADDED; + case QuicHttpFrameType::HEADERS: + return QuicHttpFrameFlag::QUIC_HTTP_END_STREAM | + QuicHttpFrameFlag::QUIC_HTTP_END_HEADERS | + QuicHttpFrameFlag::QUIC_HTTP_PADDED | + QuicHttpFrameFlag::QUIC_HTTP_PRIORITY; + case QuicHttpFrameType::QUIC_HTTP_PRIORITY: + return 0x00; + case QuicHttpFrameType::RST_STREAM: + return 0x00; + case QuicHttpFrameType::SETTINGS: + return QuicHttpFrameFlag::QUIC_HTTP_ACK; + case QuicHttpFrameType::PUSH_PROMISE: + return QuicHttpFrameFlag::QUIC_HTTP_END_HEADERS | + QuicHttpFrameFlag::QUIC_HTTP_PADDED; + case QuicHttpFrameType::PING: + return QuicHttpFrameFlag::QUIC_HTTP_ACK; + case QuicHttpFrameType::GOAWAY: + return 0x00; + case QuicHttpFrameType::WINDOW_UPDATE: + return 0x00; + case QuicHttpFrameType::CONTINUATION: + return QuicHttpFrameFlag::QUIC_HTTP_END_HEADERS; + case QuicHttpFrameType::ALTSVC: + return 0x00; + default: + return 0x00; + } +} + +uint8_t InvalidFlagMaskForFrameType(QuicHttpFrameType type) { + if (IsSupportedQuicHttpFrameType(type)) { + return ~KnownFlagsMaskForFrameType(type); + } + return 0x00; +} + +} // namespace test +} // namespace net
diff --git a/net/quic/http/quic_http_constants_test_util.h b/net/quic/http/quic_http_constants_test_util.h new file mode 100644 index 0000000..951de336 --- /dev/null +++ b/net/quic/http/quic_http_constants_test_util.h
@@ -0,0 +1,42 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_HTTP_QUIC_HTTP_CONSTANTS_TEST_UTIL_H_ +#define NET_QUIC_HTTP_QUIC_HTTP_CONSTANTS_TEST_UTIL_H_ + +#include <cstdint> +#include <vector> + +#include "net/quic/http/quic_http_constants.h" + +namespace net { +namespace test { + +// Returns a vector of all supported frame types. +std::vector<QuicHttpFrameType> AllQuicHttpFrameTypes(); + +// Returns a vector of all supported frame flags for the specified +// frame type. Empty if the type is unknown. +std::vector<QuicHttpFrameFlag> AllQuicHttpFrameFlagsForFrameType( + QuicHttpFrameType type); + +// Returns a vector of all supported RST_STREAM and GOAWAY error codes. +std::vector<QuicHttpErrorCode> AllQuicHttpErrorCodes(); + +// Returns a vector of all supported parameters in SETTINGS frames. +std::vector<QuicHttpSettingsParameter> AllQuicHttpSettingsParameters(); + +// Returns a mask of flags supported for the specified frame type. Returns +// zero for unknown frame types. +uint8_t KnownFlagsMaskForFrameType(QuicHttpFrameType type); + +// Returns a mask of flag bits known to be invalid for the frame type. +// For unknown frame types, the mask is zero; i.e., we don't know that any +// are invalid. +uint8_t InvalidFlagMaskForFrameType(QuicHttpFrameType type); + +} // namespace test +} // namespace net + +#endif // NET_QUIC_HTTP_QUIC_HTTP_CONSTANTS_TEST_UTIL_H_
diff --git a/net/quic/http/quic_http_structures.cc b/net/quic/http/quic_http_structures.cc new file mode 100644 index 0000000..a215cda --- /dev/null +++ b/net/quic/http/quic_http_structures.cc
@@ -0,0 +1,142 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/quic_http_structures.h" + +#include <cstring> // For std::memcmp + +#include "net/quic/platform/api/quic_str_cat.h" +#include "net/quic/platform/api/quic_string_utils.h" +#include "net/quic/platform/api/quic_text_utils.h" + +namespace net { + +// QuicHttpFrameHeader: + +bool QuicHttpFrameHeader::IsProbableHttpResponse() const { + return (payload_length == 0x485454 && // "HTT" + static_cast<char>(type) == 'P' && // "P" + flags == '/'); // "/" +} + +QuicString QuicHttpFrameHeader::ToString() const { + return QuicStrCat("length=", payload_length, + ", type=", QuicHttpFrameTypeToString(type), + ", flags=", FlagsToString(), ", stream=", stream_id); +} + +QuicString QuicHttpFrameHeader::FlagsToString() const { + return QuicHttpFrameFlagsToString(type, flags); +} + +bool operator==(const QuicHttpFrameHeader& a, const QuicHttpFrameHeader& b) { + return a.payload_length == b.payload_length && a.stream_id == b.stream_id && + a.type == b.type && a.flags == b.flags; +} + +std::ostream& operator<<(std::ostream& out, const QuicHttpFrameHeader& v) { + return out << v.ToString(); +} + +// QuicHttpPriorityFields: + +bool operator==(const QuicHttpPriorityFields& a, + const QuicHttpPriorityFields& b) { + return a.stream_dependency == b.stream_dependency && a.weight == b.weight; +} + +QuicString QuicHttpPriorityFields::ToString() const { + std::stringstream ss; + ss << "E=" << (is_exclusive ? "true" : "false") + << ", stream=" << stream_dependency + << ", weight=" << static_cast<uint32_t>(weight); + return ss.str(); +} + +std::ostream& operator<<(std::ostream& out, const QuicHttpPriorityFields& v) { + return out << "E=" << (v.is_exclusive ? "true" : "false") + << ", stream=" << v.stream_dependency + << ", weight=" << static_cast<uint32_t>(v.weight); +} + +// QuicHttpRstStreamFields: + +bool operator==(const QuicHttpRstStreamFields& a, + const QuicHttpRstStreamFields& b) { + return a.error_code == b.error_code; +} + +std::ostream& operator<<(std::ostream& out, const QuicHttpRstStreamFields& v) { + return out << "error_code=" << v.error_code; +} + +// QuicHttpSettingFields: + +bool operator==(const QuicHttpSettingFields& a, + const QuicHttpSettingFields& b) { + return a.parameter == b.parameter && a.value == b.value; +} +std::ostream& operator<<(std::ostream& out, const QuicHttpSettingFields& v) { + return out << "parameter=" << v.parameter << ", value=" << v.value; +} + +// QuicHttpPushPromiseFields: + +bool operator==(const QuicHttpPushPromiseFields& a, + const QuicHttpPushPromiseFields& b) { + return a.promised_stream_id == b.promised_stream_id; +} + +std::ostream& operator<<(std::ostream& out, + const QuicHttpPushPromiseFields& v) { + return out << "promised_stream_id=" << v.promised_stream_id; +} + +// QuicHttpPingFields: + +bool operator==(const QuicHttpPingFields& a, const QuicHttpPingFields& b) { + static_assert((sizeof a.opaque_bytes) == QuicHttpPingFields::EncodedSize(), + "Why not the same size?"); + return 0 == + std::memcmp(a.opaque_bytes, b.opaque_bytes, sizeof a.opaque_bytes); +} + +std::ostream& operator<<(std::ostream& out, const QuicHttpPingFields& v) { + return out << "opaque_bytes=0x" + << QuicTextUtils::HexEncode( + reinterpret_cast<const char*>(v.opaque_bytes), + sizeof v.opaque_bytes); +} + +// QuicHttpGoAwayFields: + +bool operator==(const QuicHttpGoAwayFields& a, const QuicHttpGoAwayFields& b) { + return a.last_stream_id == b.last_stream_id && a.error_code == b.error_code; +} +std::ostream& operator<<(std::ostream& out, const QuicHttpGoAwayFields& v) { + return out << "last_stream_id=" << v.last_stream_id + << ", error_code=" << v.error_code; +} + +// QuicHttpWindowUpdateFields: + +bool operator==(const QuicHttpWindowUpdateFields& a, + const QuicHttpWindowUpdateFields& b) { + return a.window_size_increment == b.window_size_increment; +} +std::ostream& operator<<(std::ostream& out, + const QuicHttpWindowUpdateFields& v) { + return out << "window_size_increment=" << v.window_size_increment; +} + +// QuicHttpAltSvcFields: + +bool operator==(const QuicHttpAltSvcFields& a, const QuicHttpAltSvcFields& b) { + return a.origin_length == b.origin_length; +} +std::ostream& operator<<(std::ostream& out, const QuicHttpAltSvcFields& v) { + return out << "origin_length=" << v.origin_length; +} + +} // namespace net
diff --git a/net/quic/http/quic_http_structures.h b/net/quic/http/quic_http_structures.h new file mode 100644 index 0000000..10c7d9e --- /dev/null +++ b/net/quic/http/quic_http_structures.h
@@ -0,0 +1,330 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_HTTP_QUIC_HTTP_STRUCTURES_H_ +#define NET_QUIC_HTTP_QUIC_HTTP_STRUCTURES_H_ + +// Defines structs for various fixed sized structures in HTTP/2. +// +// Those structs with multiple fields have constructors that take arguments in +// the same order as their encoding (which may be different from their order +// in the struct). For single field structs, use aggregate initialization if +// desired, e.g.: +// +// QuicHttpRstStreamFields var{QuicHttpErrorCode::ENHANCE_YOUR_CALM}; +// or: +// SomeFunc(QuicHttpRstStreamFields{QuicHttpErrorCode::ENHANCE_YOUR_CALM}); +// +// Each struct includes a static method EncodedSize which returns the number +// of bytes of the encoding. +// +// With the exception of QuicHttpFrameHeader, all the types are named +// QuicHttp<X>Fields, where X is the title-case form of the frame which always +// includes the fields; the "always" is to cover the case of the +// QUIC_HTTP_PRIORITY frame; its fields optionally appear in the HEADERS frame, +// but the struct is called QuicHttpPriorityFields. + +#include <stddef.h> + +#include <cstdint> + +#include "base/logging.h" +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/platform/api/quic_export.h" +#include "net/quic/platform/api/quic_string.h" + +namespace net { + +struct QUIC_EXPORT_PRIVATE QuicHttpFrameHeader { + QuicHttpFrameHeader() {} + QuicHttpFrameHeader(uint32_t payload_length, + QuicHttpFrameType type, + uint8_t flags, + uint32_t stream_id) + : payload_length(payload_length), + stream_id(stream_id), + type(type), + flags(static_cast<QuicHttpFrameFlag>(flags)) { + DCHECK_LT(payload_length, 1u << 24) + << "Payload Length is only a 24 bit field\n" + << ToString(); + } + + static constexpr size_t EncodedSize() { return 9; } + + // Keep the current value of those flags that are in + // valid_flags, and clear all the others. + void RetainFlags(uint8_t valid_flags) { + flags = static_cast<QuicHttpFrameFlag>(flags & valid_flags); + } + + // Returns true if any of the flags in flag_mask are set, + // otherwise false. + bool HasAnyFlags(uint8_t flag_mask) const { return 0 != (flags & flag_mask); } + + // Is the QUIC_HTTP_END_STREAM flag set? + bool IsEndStream() const { + DCHECK(type == QuicHttpFrameType::DATA || + type == QuicHttpFrameType::HEADERS) + << ToString(); + return (flags & QuicHttpFrameFlag::QUIC_HTTP_END_STREAM) != 0; + } + + // Is the QUIC_HTTP_ACK flag set? + bool IsAck() const { + DCHECK(type == QuicHttpFrameType::SETTINGS || + type == QuicHttpFrameType::PING) + << ToString(); + return (flags & QuicHttpFrameFlag::QUIC_HTTP_ACK) != 0; + } + + // Is the QUIC_HTTP_END_HEADERS flag set? + bool IsEndHeaders() const { + DCHECK(type == QuicHttpFrameType::HEADERS || + type == QuicHttpFrameType::PUSH_PROMISE || + type == QuicHttpFrameType::CONTINUATION) + << ToString(); + return (flags & QuicHttpFrameFlag::QUIC_HTTP_END_HEADERS) != 0; + } + + // Is the QUIC_HTTP_PADDED flag set? + bool IsPadded() const { + DCHECK(type == QuicHttpFrameType::DATA || + type == QuicHttpFrameType::HEADERS || + type == QuicHttpFrameType::PUSH_PROMISE) + << ToString(); + return (flags & QuicHttpFrameFlag::QUIC_HTTP_PADDED) != 0; + } + + // Is the QUIC_HTTP_PRIORITY flag set? + bool HasPriority() const { + DCHECK_EQ(type, QuicHttpFrameType::HEADERS) << ToString(); + return (flags & QuicHttpFrameFlag::QUIC_HTTP_PRIORITY) != 0; + } + + // Does the encoding of this header start with "HTTP/", indicating that it + // might be from a non-HTTP/2 server. + bool IsProbableHttpResponse() const; + + // Produce std::strings useful for debugging/logging messages. + QuicString ToString() const; + QuicString FlagsToString() const; + + // 24 bit length of the payload after the header, including any padding. + // First field in encoding. + uint32_t payload_length; // 24 bits + + // 31 bit stream id, with high bit (32nd bit) reserved (must be zero), + // and is cleared during decoding. + // Fourth field in encoding. + uint32_t stream_id; + + // Type of the frame. + // Second field in encoding. + QuicHttpFrameType type; + + // Flag bits, with interpretations that depend upon the frame type. + // Flag bits not used by the frame type are cleared. + // Third field in encoding. + QuicHttpFrameFlag flags; +}; + +QUIC_EXPORT_PRIVATE bool operator==(const QuicHttpFrameHeader& a, + const QuicHttpFrameHeader& b); +QUIC_EXPORT_PRIVATE inline bool operator!=(const QuicHttpFrameHeader& a, + const QuicHttpFrameHeader& b) { + return !(a == b); +} +QUIC_EXPORT_PRIVATE std::ostream& operator<<(std::ostream& out, + const QuicHttpFrameHeader& v); + +// QuicHttpPriorityFields: + +struct QUIC_EXPORT_PRIVATE QuicHttpPriorityFields { + QuicHttpPriorityFields() {} + QuicHttpPriorityFields(uint32_t stream_dependency, + uint32_t weight, + bool is_exclusive) + : stream_dependency(stream_dependency), + weight(weight), + is_exclusive(is_exclusive) { + // Can't have the high-bit set in the stream id because we need to use + // that for the EXCLUSIVE flag bit. + DCHECK_EQ(stream_dependency, stream_dependency & QuicHttpStreamIdMask()) + << "Stream Dependency is only a 31-bit field.\n" + << ToString(); + DCHECK_LE(1u, weight) << "Weight is too small."; + DCHECK_LE(weight, 256u) << "Weight is too large."; + } + static constexpr size_t EncodedSize() { return 5; } + + QuicString ToString() const; + + // A 31-bit stream identifier for the stream that this stream depends on. + uint32_t stream_dependency; + + // Weight (1 to 256) is encoded as a byte in the range 0 to 255, so we + // add one when decoding, and store it in a field larger than a byte. + uint32_t weight; + + // A single-bit flag indicating that the stream dependency is exclusive; + // extracted from high bit of stream dependency field during decoding. + bool is_exclusive; +}; + +QUIC_EXPORT_PRIVATE bool operator==(const QuicHttpPriorityFields& a, + const QuicHttpPriorityFields& b); +QUIC_EXPORT_PRIVATE inline bool operator!=(const QuicHttpPriorityFields& a, + const QuicHttpPriorityFields& b) { + return !(a == b); +} +QUIC_EXPORT_PRIVATE std::ostream& operator<<(std::ostream& out, + const QuicHttpPriorityFields& v); + +// QuicHttpRstStreamFields: + +struct QuicHttpRstStreamFields { + static constexpr size_t EncodedSize() { return 4; } + bool IsSupportedErrorCode() const { + return IsSupportedQuicHttpErrorCode(error_code); + } + + QuicHttpErrorCode error_code; +}; + +QUIC_EXPORT_PRIVATE bool operator==(const QuicHttpRstStreamFields& a, + const QuicHttpRstStreamFields& b); +QUIC_EXPORT_PRIVATE inline bool operator!=(const QuicHttpRstStreamFields& a, + const QuicHttpRstStreamFields& b) { + return !(a == b); +} +QUIC_EXPORT_PRIVATE std::ostream& operator<<(std::ostream& out, + const QuicHttpRstStreamFields& v); + +// QuicHttpSettingFields: + +struct QuicHttpSettingFields { + QuicHttpSettingFields() {} + QuicHttpSettingFields(QuicHttpSettingsParameter parameter, uint32_t value) + : parameter(parameter), value(value) {} + static constexpr size_t EncodedSize() { return 6; } + bool IsSupportedParameter() const { + return IsSupportedQuicHttpSettingsParameter(parameter); + } + + QuicHttpSettingsParameter parameter; + uint32_t value; +}; + +QUIC_EXPORT_PRIVATE bool operator==(const QuicHttpSettingFields& a, + const QuicHttpSettingFields& b); +QUIC_EXPORT_PRIVATE inline bool operator!=(const QuicHttpSettingFields& a, + const QuicHttpSettingFields& b) { + return !(a == b); +} +QUIC_EXPORT_PRIVATE std::ostream& operator<<(std::ostream& out, + const QuicHttpSettingFields& v); + +// QuicHttpPushPromiseFields: + +struct QuicHttpPushPromiseFields { + static constexpr size_t EncodedSize() { return 4; } + + uint32_t promised_stream_id; +}; + +QUIC_EXPORT_PRIVATE bool operator==(const QuicHttpPushPromiseFields& a, + const QuicHttpPushPromiseFields& b); +QUIC_EXPORT_PRIVATE inline bool operator!=(const QuicHttpPushPromiseFields& a, + const QuicHttpPushPromiseFields& b) { + return !(a == b); +} +QUIC_EXPORT_PRIVATE std::ostream& operator<<( + std::ostream& out, + const QuicHttpPushPromiseFields& v); + +// QuicHttpPingFields: + +struct QuicHttpPingFields { + static constexpr size_t EncodedSize() { return 8; } + + // TODO(jamessynge): Rename opaque_bytes to opaque_bytes. + uint8_t opaque_bytes[8]; +}; + +QUIC_EXPORT_PRIVATE bool operator==(const QuicHttpPingFields& a, + const QuicHttpPingFields& b); +QUIC_EXPORT_PRIVATE inline bool operator!=(const QuicHttpPingFields& a, + const QuicHttpPingFields& b) { + return !(a == b); +} +QUIC_EXPORT_PRIVATE std::ostream& operator<<(std::ostream& out, + const QuicHttpPingFields& v); + +// QuicHttpGoAwayFields: + +struct QuicHttpGoAwayFields { + QuicHttpGoAwayFields() {} + QuicHttpGoAwayFields(uint32_t last_stream_id, QuicHttpErrorCode error_code) + : last_stream_id(last_stream_id), error_code(error_code) {} + static constexpr size_t EncodedSize() { return 8; } + bool IsSupportedErrorCode() const { + return IsSupportedQuicHttpErrorCode(error_code); + } + + uint32_t last_stream_id; + QuicHttpErrorCode error_code; +}; + +QUIC_EXPORT_PRIVATE bool operator==(const QuicHttpGoAwayFields& a, + const QuicHttpGoAwayFields& b); +QUIC_EXPORT_PRIVATE inline bool operator!=(const QuicHttpGoAwayFields& a, + const QuicHttpGoAwayFields& b) { + return !(a == b); +} +QUIC_EXPORT_PRIVATE std::ostream& operator<<(std::ostream& out, + const QuicHttpGoAwayFields& v); + +// QuicHttpWindowUpdateFields: + +struct QuicHttpWindowUpdateFields { + static constexpr size_t EncodedSize() { return 4; } + + // 31-bit, unsigned increase in the window size (only positive values are + // allowed). The high-bit is reserved for the future. + uint32_t window_size_increment; +}; + +QUIC_EXPORT_PRIVATE bool operator==(const QuicHttpWindowUpdateFields& a, + const QuicHttpWindowUpdateFields& b); +QUIC_EXPORT_PRIVATE inline bool operator!=( + const QuicHttpWindowUpdateFields& a, + const QuicHttpWindowUpdateFields& b) { + return !(a == b); +} +QUIC_EXPORT_PRIVATE std::ostream& operator<<( + std::ostream& out, + const QuicHttpWindowUpdateFields& v); + +// QuicHttpAltSvcFields: + +struct QuicHttpAltSvcFields { + static constexpr size_t EncodedSize() { return 2; } + + // This is the one fixed size portion of the ALTSVC payload. + uint16_t origin_length; +}; + +QUIC_EXPORT_PRIVATE bool operator==(const QuicHttpAltSvcFields& a, + const QuicHttpAltSvcFields& b); +QUIC_EXPORT_PRIVATE inline bool operator!=(const QuicHttpAltSvcFields& a, + const QuicHttpAltSvcFields& b) { + return !(a == b); +} +QUIC_EXPORT_PRIVATE std::ostream& operator<<(std::ostream& out, + const QuicHttpAltSvcFields& v); + +} // namespace net + +#endif // NET_QUIC_HTTP_QUIC_HTTP_STRUCTURES_H_
diff --git a/net/quic/http/quic_http_structures_test.cc b/net/quic/http/quic_http_structures_test.cc new file mode 100644 index 0000000..a1d00dfa --- /dev/null +++ b/net/quic/http/quic_http_structures_test.cc
@@ -0,0 +1,501 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. +#include "net/quic/http/quic_http_structures.h" + +// Tests are focused on QuicHttpFrameHeader because it has by far the most +// methods of any of the structures. +// Note that EXPECT.*DEATH tests are slow (a fork is probably involved). + +// And in case you're wondering, yes, these are ridiculously thorough tests, +// but believe it or not, I've found stupid bugs this way. + +#include <memory> +#include <ostream> // IWYU pragma: keep // for stringstream +#include <type_traits> +#include <vector> + +#include "net/quic/http/quic_http_structures_test_util.h" +#include "net/quic/platform/api/quic_str_cat.h" +#include "net/quic/platform/api/quic_string_utils.h" +#include "net/quic/platform/api/quic_test_random.h" +#include "net/quic/platform/api/quic_text_utils.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +using ::testing::AssertionResult; +using ::testing::AssertionSuccess; +using ::testing::Combine; +using ::testing::Contains; +using ::testing::HasSubstr; +using ::testing::Not; +using ::testing::Values; +using ::testing::ValuesIn; + +namespace net { +namespace test { +namespace { + +template <typename E> +E IncrementEnum(E e) { + typedef typename std::underlying_type<E>::type I; + return static_cast<E>(1 + static_cast<I>(e)); +} + +#if GTEST_HAS_DEATH_TEST && !defined(NDEBUG) +std::vector<QuicHttpFrameType> ValidFrameTypes() { + std::vector<QuicHttpFrameType> valid_types{QuicHttpFrameType::DATA}; + while (valid_types.back() != QuicHttpFrameType::ALTSVC) { + valid_types.push_back(IncrementEnum(valid_types.back())); + } + return valid_types; +} +#endif // GTEST_HAS_DEATH_TEST && !defined(NDEBUG) + +TEST(QuicHttpFrameHeaderTest, Constructor) { + QuicTestRandom random; + uint8_t frame_type = 0; + do { + // Only the payload length is DCHECK'd in the constructor, so we need to + // make sure it is a "uint24". + uint32_t payload_length = random.Rand32() & 0xffffff; + QuicHttpFrameType type = static_cast<QuicHttpFrameType>(frame_type); + uint8_t flags = random.Rand8(); + uint32_t stream_id = random.Rand32(); + + QuicHttpFrameHeader v(payload_length, type, flags, stream_id); + + EXPECT_EQ(payload_length, v.payload_length); + EXPECT_EQ(type, v.type); + EXPECT_EQ(flags, v.flags); + EXPECT_EQ(stream_id, v.stream_id); + } while (frame_type++ == 255); + +#if GTEST_HAS_DEATH_TEST && !defined(NDEBUG) + EXPECT_DEBUG_DEATH( + QuicHttpFrameHeader(0x01000000, QuicHttpFrameType::DATA, 0, 1), + "payload_length"); +#endif // GTEST_HAS_DEATH_TEST && !defined(NDEBUG) +} + +TEST(QuicHttpFrameHeaderTest, Eq) { + QuicTestRandom random; + uint32_t payload_length = random.Rand32() & 0xffffff; + QuicHttpFrameType type = static_cast<QuicHttpFrameType>(random.Rand8()); + + uint8_t flags = random.Rand8(); + uint32_t stream_id = random.Rand32(); + + QuicHttpFrameHeader v(payload_length, type, flags, stream_id); + + EXPECT_EQ(payload_length, v.payload_length); + EXPECT_EQ(type, v.type); + EXPECT_EQ(flags, v.flags); + EXPECT_EQ(stream_id, v.stream_id); + + QuicHttpFrameHeader u(0, type, ~flags, stream_id); + + EXPECT_NE(u, v); + EXPECT_NE(v, u); + EXPECT_FALSE(u == v); + EXPECT_FALSE(v == u); + EXPECT_TRUE(u != v); + EXPECT_TRUE(v != u); + + u = v; + + EXPECT_EQ(u, v); + EXPECT_EQ(v, u); + EXPECT_TRUE(u == v); + EXPECT_TRUE(v == u); + EXPECT_FALSE(u != v); + EXPECT_FALSE(v != u); +} + +#if GTEST_HAS_DEATH_TEST && !defined(NDEBUG) +// The tests of the valid frame types include EXPECT_DEBUG_DEATH, which is +// quite slow, so using value parameterized tests in order to allow sharding. +class QuicHttpFrameHeaderTypeAndFlagTest + : public ::testing::TestWithParam< + std::tuple<QuicHttpFrameType, QuicHttpFrameFlag>> { + protected: + QuicHttpFrameHeaderTypeAndFlagTest() + : type_(std::get<0>(GetParam())), flags_(std::get<1>(GetParam())) { + LOG(INFO) << "Frame type: " << type_; + LOG(INFO) << "Frame flags: " << QuicHttpFrameFlagsToString(type_, flags_); + } + + const QuicHttpFrameType type_; + const QuicHttpFrameFlag flags_; +}; + +class QuicHttpIsEndStreamTest : public QuicHttpFrameHeaderTypeAndFlagTest {}; +INSTANTIATE_TEST_CASE_P(IsEndStream, + QuicHttpIsEndStreamTest, + Combine(ValuesIn(ValidFrameTypes()), + Values(~QuicHttpFrameFlag::QUIC_HTTP_END_STREAM, + 0xff))); +TEST_P(QuicHttpIsEndStreamTest, IsEndStream) { + const bool is_set = (flags_ & QuicHttpFrameFlag::QUIC_HTTP_END_STREAM) == + QuicHttpFrameFlag::QUIC_HTTP_END_STREAM; + QuicString flags_string; + QuicHttpFrameHeader v(0, type_, flags_, 0); + switch (type_) { + case QuicHttpFrameType::DATA: + case QuicHttpFrameType::HEADERS: + EXPECT_EQ(is_set, v.IsEndStream()) << v; + flags_string = v.FlagsToString(); + if (is_set) { + EXPECT_THAT(QuicTextUtils::Split(flags_string, '|'), + Contains("QUIC_HTTP_END_STREAM")); + } else { + EXPECT_THAT(flags_string, Not(HasSubstr("QUIC_HTTP_END_STREAM"))); + } + v.RetainFlags(QuicHttpFrameFlag::QUIC_HTTP_END_STREAM); + EXPECT_EQ(is_set, v.IsEndStream()) << v; + { + std::stringstream s; + s << v; + EXPECT_EQ(v.ToString(), s.str()); + if (is_set) { + EXPECT_THAT(s.str(), HasSubstr("flags=QUIC_HTTP_END_STREAM,")); + } else { + EXPECT_THAT(s.str(), HasSubstr("flags=,")); + } + } + break; + default: + EXPECT_DEBUG_DEATH(v.IsEndStream(), "DATA.*HEADERS") << v; + } +} + +class IsQUIC_HTTP_ACKTest : public QuicHttpFrameHeaderTypeAndFlagTest {}; +INSTANTIATE_TEST_CASE_P(IsAck, + IsQUIC_HTTP_ACKTest, + Combine(ValuesIn(ValidFrameTypes()), + Values(~QuicHttpFrameFlag::QUIC_HTTP_ACK, + 0xff))); +TEST_P(IsQUIC_HTTP_ACKTest, IsAck) { + const bool is_set = (flags_ & QuicHttpFrameFlag::QUIC_HTTP_ACK) == + QuicHttpFrameFlag::QUIC_HTTP_ACK; + QuicString flags_string; + QuicHttpFrameHeader v(0, type_, flags_, 0); + switch (type_) { + case QuicHttpFrameType::SETTINGS: + case QuicHttpFrameType::PING: + EXPECT_EQ(is_set, v.IsAck()) << v; + flags_string = v.FlagsToString(); + if (is_set) { + EXPECT_THAT(QuicTextUtils::Split(flags_string, '|'), + Contains("QUIC_HTTP_ACK")); + } else { + EXPECT_THAT(flags_string, Not(HasSubstr("QUIC_HTTP_ACK"))); + } + v.RetainFlags(QuicHttpFrameFlag::QUIC_HTTP_ACK); + EXPECT_EQ(is_set, v.IsAck()) << v; + { + std::stringstream s; + s << v; + EXPECT_EQ(v.ToString(), s.str()); + if (is_set) { + EXPECT_THAT(s.str(), HasSubstr("flags=QUIC_HTTP_ACK,")); + } else { + EXPECT_THAT(s.str(), HasSubstr("flags=,")); + } + } + break; + default: + EXPECT_DEBUG_DEATH(v.IsAck(), "SETTINGS.*PING") << v; + } +} + +class QuicHttpIsEndHeadersTest : public QuicHttpFrameHeaderTypeAndFlagTest {}; +INSTANTIATE_TEST_CASE_P( + IsEndHeaders, + QuicHttpIsEndHeadersTest, + Combine(ValuesIn(ValidFrameTypes()), + Values(~QuicHttpFrameFlag::QUIC_HTTP_END_HEADERS, 0xff))); +TEST_P(QuicHttpIsEndHeadersTest, IsEndHeaders) { + const bool is_set = (flags_ & QuicHttpFrameFlag::QUIC_HTTP_END_HEADERS) == + QuicHttpFrameFlag::QUIC_HTTP_END_HEADERS; + QuicString flags_string; + QuicHttpFrameHeader v(0, type_, flags_, 0); + switch (type_) { + case QuicHttpFrameType::HEADERS: + case QuicHttpFrameType::PUSH_PROMISE: + case QuicHttpFrameType::CONTINUATION: + EXPECT_EQ(is_set, v.IsEndHeaders()) << v; + flags_string = v.FlagsToString(); + if (is_set) { + EXPECT_THAT(QuicTextUtils::Split(flags_string, '|'), + Contains("QUIC_HTTP_END_HEADERS")); + } else { + EXPECT_THAT(flags_string, Not(HasSubstr("QUIC_HTTP_END_HEADERS"))); + } + v.RetainFlags(QuicHttpFrameFlag::QUIC_HTTP_END_HEADERS); + EXPECT_EQ(is_set, v.IsEndHeaders()) << v; + { + std::stringstream s; + s << v; + EXPECT_EQ(v.ToString(), s.str()); + if (is_set) { + EXPECT_THAT(s.str(), HasSubstr("flags=QUIC_HTTP_END_HEADERS,")); + } else { + EXPECT_THAT(s.str(), HasSubstr("flags=,")); + } + } + break; + default: + EXPECT_DEBUG_DEATH(v.IsEndHeaders(), + "HEADERS.*PUSH_PROMISE.*CONTINUATION") + << v; + } +} + +class QuicHttpIsPaddedTest : public QuicHttpFrameHeaderTypeAndFlagTest {}; +INSTANTIATE_TEST_CASE_P(IsPadded, + QuicHttpIsPaddedTest, + Combine(ValuesIn(ValidFrameTypes()), + Values(~QuicHttpFrameFlag::QUIC_HTTP_PADDED, + 0xff))); +TEST_P(QuicHttpIsPaddedTest, IsPadded) { + const bool is_set = (flags_ & QuicHttpFrameFlag::QUIC_HTTP_PADDED) == + QuicHttpFrameFlag::QUIC_HTTP_PADDED; + QuicString flags_string; + QuicHttpFrameHeader v(0, type_, flags_, 0); + switch (type_) { + case QuicHttpFrameType::DATA: + case QuicHttpFrameType::HEADERS: + case QuicHttpFrameType::PUSH_PROMISE: + EXPECT_EQ(is_set, v.IsPadded()) << v; + flags_string = v.FlagsToString(); + if (is_set) { + EXPECT_THAT(QuicTextUtils::Split(flags_string, '|'), + Contains("QUIC_HTTP_PADDED")); + } else { + EXPECT_THAT(flags_string, Not(HasSubstr("QUIC_HTTP_PADDED"))); + } + v.RetainFlags(QuicHttpFrameFlag::QUIC_HTTP_PADDED); + EXPECT_EQ(is_set, v.IsPadded()) << v; + { + std::stringstream s; + s << v; + EXPECT_EQ(v.ToString(), s.str()); + if (is_set) { + EXPECT_THAT(s.str(), HasSubstr("flags=QUIC_HTTP_PADDED,")); + } else { + EXPECT_THAT(s.str(), HasSubstr("flags=,")); + } + } + break; + default: + EXPECT_DEBUG_DEATH(v.IsPadded(), "DATA.*HEADERS.*PUSH_PROMISE") << v; + } +} + +class QuicHttpHasPriorityTest : public QuicHttpFrameHeaderTypeAndFlagTest {}; +INSTANTIATE_TEST_CASE_P(HasPriority, + QuicHttpHasPriorityTest, + Combine(ValuesIn(ValidFrameTypes()), + Values(~QuicHttpFrameFlag::QUIC_HTTP_PRIORITY, + 0xff))); +TEST_P(QuicHttpHasPriorityTest, HasPriority) { + const bool is_set = (flags_ & QuicHttpFrameFlag::QUIC_HTTP_PRIORITY) == + QuicHttpFrameFlag::QUIC_HTTP_PRIORITY; + QuicString flags_string; + QuicHttpFrameHeader v(0, type_, flags_, 0); + switch (type_) { + case QuicHttpFrameType::HEADERS: + EXPECT_EQ(is_set, v.HasPriority()) << v; + flags_string = v.FlagsToString(); + if (is_set) { + EXPECT_THAT(QuicTextUtils::Split(flags_string, '|'), + Contains("QUIC_HTTP_PRIORITY")); + } else { + EXPECT_THAT(flags_string, Not(HasSubstr("QUIC_HTTP_PRIORITY"))); + } + v.RetainFlags(QuicHttpFrameFlag::QUIC_HTTP_PRIORITY); + EXPECT_EQ(is_set, v.HasPriority()) << v; + { + std::stringstream s; + s << v; + EXPECT_EQ(v.ToString(), s.str()); + if (is_set) { + EXPECT_THAT(s.str(), HasSubstr("flags=QUIC_HTTP_PRIORITY,")); + } else { + EXPECT_THAT(s.str(), HasSubstr("flags=,")); + } + } + break; + default: + EXPECT_DEBUG_DEATH(v.HasPriority(), "HEADERS") << v; + } +} + +TEST(QuicHttpPriorityFieldsTest, Constructor) { + QuicTestRandom random; + uint32_t stream_dependency = random.Rand32() & QuicHttpStreamIdMask(); + uint32_t weight = 1 + random.Rand8(); + bool is_exclusive = random.OneIn(2); + + QuicHttpPriorityFields v(stream_dependency, weight, is_exclusive); + + EXPECT_EQ(stream_dependency, v.stream_dependency); + EXPECT_EQ(weight, v.weight); + EXPECT_EQ(is_exclusive, v.is_exclusive); + + // The high-bit must not be set on the stream id. + EXPECT_DEBUG_DEATH(QuicHttpPriorityFields(stream_dependency | 0x80000000, + weight, is_exclusive), + "31-bit"); + + // The weight must be in the range 1-256. + EXPECT_DEBUG_DEATH(QuicHttpPriorityFields(stream_dependency, 0, is_exclusive), + "too small"); + EXPECT_DEBUG_DEATH( + QuicHttpPriorityFields(stream_dependency, weight + 256, is_exclusive), + "too large"); +} +#endif // GTEST_HAS_DEATH_TEST && !defined(NDEBUG) + +TEST(QuicHttpRstStreamFieldsTest, IsSupported) { + QuicHttpRstStreamFields v{QuicHttpErrorCode::HTTP2_NO_ERROR}; + EXPECT_TRUE(v.IsSupportedErrorCode()) << v; + + QuicHttpRstStreamFields u{static_cast<QuicHttpErrorCode>(~0)}; + EXPECT_FALSE(u.IsSupportedErrorCode()) << v; +} + +TEST(QuicHttpSettingFieldsTest, Misc) { + QuicTestRandom random; + QuicHttpSettingsParameter parameter = + static_cast<QuicHttpSettingsParameter>(random.Rand16()); + uint32_t value = random.Rand32(); + + QuicHttpSettingFields v(parameter, value); + + EXPECT_EQ(v, v); + EXPECT_EQ(parameter, v.parameter); + EXPECT_EQ(value, v.value); + + if (static_cast<int>(parameter) < 7) { + EXPECT_TRUE(v.IsSupportedParameter()) << v; + } else { + EXPECT_FALSE(v.IsSupportedParameter()) << v; + } + + QuicHttpSettingFields u(parameter, ~value); + EXPECT_NE(v, u); + EXPECT_EQ(v.parameter, u.parameter); + EXPECT_NE(v.value, u.value); + + QuicHttpSettingFields w(IncrementEnum(parameter), value); + EXPECT_NE(v, w); + EXPECT_NE(v.parameter, w.parameter); + EXPECT_EQ(v.value, w.value); + + QuicHttpSettingFields x(QuicHttpSettingsParameter::MAX_FRAME_SIZE, 123); + std::stringstream s; + s << x; + EXPECT_EQ("parameter=MAX_FRAME_SIZE, value=123", s.str()); +} + +TEST(QuicHttpPushPromiseTest, Misc) { + QuicTestRandom random; + uint32_t promised_stream_id = random.Rand32() & QuicHttpStreamIdMask(); + + QuicHttpPushPromiseFields v{promised_stream_id}; + EXPECT_EQ(promised_stream_id, v.promised_stream_id); + EXPECT_EQ(v, v); + + std::stringstream s; + s << v; + EXPECT_EQ(QuicStrCat("promised_stream_id=", promised_stream_id), s.str()); + + // High-bit is reserved, but not used, so we can set it. + promised_stream_id |= 0x80000000; + QuicHttpPushPromiseFields w{promised_stream_id}; + EXPECT_EQ(w, w); + EXPECT_NE(v, w); + + v.promised_stream_id = promised_stream_id; + EXPECT_EQ(v, w); +} + +TEST(QuicHttpPingFieldsTest, Misc) { + QuicHttpPingFields v{{'8', ' ', 'b', 'y', 't', 'e', 's', '\0'}}; + std::stringstream s; + s << v; + EXPECT_EQ("opaque_bytes=0x3820627974657300", s.str()); +} + +// Started becoming very flaky on all platforms after around crrev.com/519987. +TEST(QuicHttpGoAwayFieldsTest, DISABLED_Misc) { + QuicTestRandom random; + uint32_t last_stream_id = random.Rand32() & QuicHttpStreamIdMask(); + QuicHttpErrorCode error_code = + static_cast<QuicHttpErrorCode>(random.Rand32()); + + QuicHttpGoAwayFields v(last_stream_id, error_code); + EXPECT_EQ(v, v); + EXPECT_EQ(last_stream_id, v.last_stream_id); + EXPECT_EQ(error_code, v.error_code); + + if (static_cast<int>(error_code) < 14) { + EXPECT_TRUE(v.IsSupportedErrorCode()) << v; + } else { + EXPECT_FALSE(v.IsSupportedErrorCode()) << v; + } + + QuicHttpGoAwayFields u(~last_stream_id, error_code); + EXPECT_NE(v, u); + EXPECT_NE(v.last_stream_id, u.last_stream_id); + EXPECT_EQ(v.error_code, u.error_code); +} + +TEST(QuicHttpWindowUpdateTest, Misc) { + QuicTestRandom random; + uint32_t window_size_increment = random.Rand32() & QuicHttpUint31Mask(); + + QuicHttpWindowUpdateFields v{window_size_increment}; + EXPECT_EQ(window_size_increment, v.window_size_increment); + EXPECT_EQ(v, v); + + std::stringstream s; + s << v; + EXPECT_EQ(QuicStrCat("window_size_increment=", window_size_increment), + s.str()); + + // High-bit is reserved, but not used, so we can set it. + window_size_increment |= 0x80000000; + QuicHttpWindowUpdateFields w{window_size_increment}; + EXPECT_EQ(w, w); + EXPECT_NE(v, w); + + v.window_size_increment = window_size_increment; + EXPECT_EQ(v, w); +} + +TEST(QuicHttpAltSvcTest, Misc) { + QuicTestRandom random; + uint16_t origin_length = random.Rand16(); + + QuicHttpAltSvcFields v{origin_length}; + EXPECT_EQ(origin_length, v.origin_length); + EXPECT_EQ(v, v); + + std::stringstream s; + s << v; + EXPECT_EQ(QuicStrCat("origin_length=", origin_length), s.str()); + + QuicHttpAltSvcFields w{++origin_length}; + EXPECT_EQ(w, w); + EXPECT_NE(v, w); + + v.origin_length = w.origin_length; + EXPECT_EQ(v, w); +} + +} // namespace +} // namespace test +} // namespace net
diff --git a/net/quic/http/quic_http_structures_test_util.cc b/net/quic/http/quic_http_structures_test_util.cc new file mode 100644 index 0000000..e0518980 --- /dev/null +++ b/net/quic/http/quic_http_structures_test_util.cc
@@ -0,0 +1,109 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/quic_http_structures_test_util.h" + +#include <cstdint> + +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/quic_http_constants_test_util.h" +#include "net/quic/http/quic_http_structures.h" +#include "net/quic/platform/api/quic_test_random.h" + +namespace net { +namespace test { + +void Randomize(QuicHttpFrameHeader* p, QuicTestRandomBase* rng) { + p->payload_length = rng->Rand32() & 0xffffff; + p->type = static_cast<QuicHttpFrameType>(rng->Rand8()); + p->flags = static_cast<QuicHttpFrameFlag>(rng->Rand8()); + p->stream_id = rng->Rand32() & QuicHttpStreamIdMask(); +} +void Randomize(QuicHttpPriorityFields* p, QuicTestRandomBase* rng) { + p->stream_dependency = rng->Rand32() & QuicHttpStreamIdMask(); + p->weight = rng->Rand8() + 1; + p->is_exclusive = rng->OneIn(2); +} +void Randomize(QuicHttpRstStreamFields* p, QuicTestRandomBase* rng) { + p->error_code = static_cast<QuicHttpErrorCode>(rng->Rand32()); +} +void Randomize(QuicHttpSettingFields* p, QuicTestRandomBase* rng) { + p->parameter = static_cast<QuicHttpSettingsParameter>(rng->Rand16()); + p->value = rng->Rand32(); +} +void Randomize(QuicHttpPushPromiseFields* p, QuicTestRandomBase* rng) { + p->promised_stream_id = rng->Rand32() & QuicHttpStreamIdMask(); +} +void Randomize(QuicHttpPingFields* p, QuicTestRandomBase* rng) { + for (int ndx = 0; ndx < 8; ++ndx) { + p->opaque_bytes[ndx] = rng->Rand8(); + } +} +void Randomize(QuicHttpGoAwayFields* p, QuicTestRandomBase* rng) { + p->last_stream_id = rng->Rand32() & QuicHttpStreamIdMask(); + p->error_code = static_cast<QuicHttpErrorCode>(rng->Rand32()); +} +void Randomize(QuicHttpWindowUpdateFields* p, QuicTestRandomBase* rng) { + p->window_size_increment = rng->Rand32() & 0x7fffffff; +} +void Randomize(QuicHttpAltSvcFields* p, QuicTestRandomBase* rng) { + p->origin_length = rng->Rand16(); +} + +void ScrubFlagsOfHeader(QuicHttpFrameHeader* header) { + uint8_t invalid_mask = InvalidFlagMaskForFrameType(header->type); + uint8_t keep_mask = ~invalid_mask; + header->RetainFlags(keep_mask); +} + +bool FrameIsPadded(const QuicHttpFrameHeader& header) { + switch (header.type) { + case QuicHttpFrameType::DATA: + case QuicHttpFrameType::HEADERS: + case QuicHttpFrameType::PUSH_PROMISE: + return header.IsPadded(); + default: + return false; + } +} + +bool FrameHasPriority(const QuicHttpFrameHeader& header) { + switch (header.type) { + case QuicHttpFrameType::HEADERS: + return header.HasPriority(); + case QuicHttpFrameType::QUIC_HTTP_PRIORITY: + return true; + default: + return false; + } +} + +bool FrameCanHavePayload(const QuicHttpFrameHeader& header) { + switch (header.type) { + case QuicHttpFrameType::DATA: + case QuicHttpFrameType::HEADERS: + case QuicHttpFrameType::PUSH_PROMISE: + case QuicHttpFrameType::CONTINUATION: + case QuicHttpFrameType::PING: + case QuicHttpFrameType::GOAWAY: + case QuicHttpFrameType::ALTSVC: + return true; + default: + return false; + } +} + +bool FrameCanHaveHpackPayload(const QuicHttpFrameHeader& header) { + switch (header.type) { + case QuicHttpFrameType::HEADERS: + case QuicHttpFrameType::PUSH_PROMISE: + case QuicHttpFrameType::CONTINUATION: + return true; + default: + return false; + } +} + +} // namespace test +} // namespace net
diff --git a/net/quic/http/quic_http_structures_test_util.h b/net/quic/http/quic_http_structures_test_util.h new file mode 100644 index 0000000..5a92808 --- /dev/null +++ b/net/quic/http/quic_http_structures_test_util.h
@@ -0,0 +1,60 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_HTTP_QUIC_HTTP_STRUCTURES_TEST_UTIL_H_ +#define NET_QUIC_HTTP_QUIC_HTTP_STRUCTURES_TEST_UTIL_H_ + +#include "net/quic/http/quic_http_structures.h" +#include "net/quic/http/tools/quic_http_frame_builder.h" +#include "net/quic/platform/api/quic_string.h" +#include "net/quic/platform/api/quic_test_random.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace net { +namespace test { + +template <class S> +QuicString SerializeStructure(const S& s) { + QuicHttpFrameBuilder fb; + fb.Append(s); + EXPECT_EQ(S::EncodedSize(), fb.size()); + return fb.buffer(); +} + +// Randomize the members of out, in a manner that yields encodeable contents +// (e.g. a "uint24" field has only the low 24 bits set). +void Randomize(QuicHttpFrameHeader* p, QuicTestRandomBase* rng); +void Randomize(QuicHttpPriorityFields* p, QuicTestRandomBase* rng); +void Randomize(QuicHttpRstStreamFields* p, QuicTestRandomBase* rng); +void Randomize(QuicHttpSettingFields* p, QuicTestRandomBase* rng); +void Randomize(QuicHttpPushPromiseFields* p, QuicTestRandomBase* rng); +void Randomize(QuicHttpPingFields* p, QuicTestRandomBase* rng); +void Randomize(QuicHttpGoAwayFields* p, QuicTestRandomBase* rng); +void Randomize(QuicHttpWindowUpdateFields* p, QuicTestRandomBase* rng); +void Randomize(QuicHttpAltSvcFields* p, QuicTestRandomBase* rng); + +// Clear bits of header->flags that are known to be invalid for the +// type. For unknown frame types, no change is made. +void ScrubFlagsOfHeader(QuicHttpFrameHeader* header); + +// Is the frame with this header padded? Only true for known/supported frame +// types. +bool FrameIsPadded(const QuicHttpFrameHeader& header); + +// Does the frame with this header have QuicHttpPriorityFields? +bool FrameHasPriority(const QuicHttpFrameHeader& header); + +// Does the frame with this header have a variable length payload (including +// empty) payload (e.g. DATA or HEADERS)? Really a test of the frame type. +bool FrameCanHavePayload(const QuicHttpFrameHeader& header); + +// Does the frame with this header have a variable length HPQUIC_HTTP_ACK +// payload (including empty) payload (e.g. HEADERS)? Really a test of the frame +// type. +bool FrameCanHaveHpackPayload(const QuicHttpFrameHeader& header); + +} // namespace test +} // namespace net + +#endif // NET_QUIC_HTTP_QUIC_HTTP_STRUCTURES_TEST_UTIL_H_
diff --git a/net/quic/http/test_tools/quic_http_frame_parts.cc b/net/quic/http/test_tools/quic_http_frame_parts.cc new file mode 100644 index 0000000..b039712 --- /dev/null +++ b/net/quic/http/test_tools/quic_http_frame_parts.cc
@@ -0,0 +1,542 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/test_tools/quic_http_frame_parts.h" + +#include <type_traits> + +#include "net/base/escape.h" +#include "net/http2/tools/failure.h" +#include "net/quic/http/quic_http_structures_test_util.h" +#include "testing/gtest/include/gtest/gtest.h" + +using ::testing::AssertionFailure; +using ::testing::AssertionResult; +using ::testing::AssertionSuccess; +using ::testing::ContainerEq; + +namespace net { +namespace test { +namespace { + +static_assert( + std::is_base_of<QuicHttpFrameDecoderListener, QuicHttpFrameParts>::value && + !std::is_abstract<QuicHttpFrameParts>::value, + "QuicHttpFrameParts needs to implement all of the methods of " + "QuicHttpFrameDecoderListener"); + +// Compare two optional variables of the same type. +// TODO(jamessynge): Maybe create a ::testing::Matcher for this. +template <class T> +AssertionResult VerifyOptionalEq(const T& opt_a, const T& opt_b) { + if (opt_a) { + if (opt_b) { + VERIFY_EQ(opt_a.value(), opt_b.value()); + } else { + return AssertionFailure() + << "opt_b is not set; opt_a.value()=" << opt_a.value(); + } + } else if (opt_b) { + return AssertionFailure() + << "opt_a is not set; opt_b.value()=" << opt_b.value(); + } + return AssertionSuccess(); +} + +} // namespace + +QuicHttpFrameParts::QuicHttpFrameParts(const QuicHttpFrameHeader& header) + : frame_header(header) { + VLOG(1) << "QuicHttpFrameParts, header: " << frame_header; +} + +QuicHttpFrameParts::QuicHttpFrameParts(const QuicHttpFrameHeader& header, + QuicStringPiece payload) + : QuicHttpFrameParts(header) { + VLOG(1) << "QuicHttpFrameParts with payload.size() = " << payload.size(); + this->payload.append(payload.data(), payload.size()); + opt_payload_length = payload.size(); +} +QuicHttpFrameParts::QuicHttpFrameParts(const QuicHttpFrameHeader& header, + QuicStringPiece payload, + size_t total_pad_length) + : QuicHttpFrameParts(header, payload) { + VLOG(1) << "QuicHttpFrameParts with total_pad_length=" << total_pad_length; + SetTotalPadLength(total_pad_length); +} + +QuicHttpFrameParts::QuicHttpFrameParts(const QuicHttpFrameParts& header) = + default; + +QuicHttpFrameParts::~QuicHttpFrameParts() {} + +AssertionResult QuicHttpFrameParts::VerifyEquals( + const QuicHttpFrameParts& that) const { +#define COMMON_MESSAGE "\n this: " << *this << "\n that: " << that + + VERIFY_EQ(frame_header, that.frame_header) << COMMON_MESSAGE; + VERIFY_EQ(payload, that.payload) << COMMON_MESSAGE; + VERIFY_EQ(padding, that.padding) << COMMON_MESSAGE; + VERIFY_EQ(altsvc_origin, that.altsvc_origin) << COMMON_MESSAGE; + VERIFY_EQ(altsvc_value, that.altsvc_value) << COMMON_MESSAGE; + VERIFY_THAT(settings, ContainerEq(that.settings)) << COMMON_MESSAGE; + +#define VERIFY_OPTIONAL_FIELD(field_name) \ + VERIFY_SUCCESS(VerifyOptionalEq(field_name, that.field_name)) + + VERIFY_OPTIONAL_FIELD(opt_altsvc_origin_length) << COMMON_MESSAGE; + VERIFY_OPTIONAL_FIELD(opt_altsvc_value_length) << COMMON_MESSAGE; + VERIFY_OPTIONAL_FIELD(opt_goaway) << COMMON_MESSAGE; + VERIFY_OPTIONAL_FIELD(opt_missing_length) << COMMON_MESSAGE; + VERIFY_OPTIONAL_FIELD(opt_pad_length) << COMMON_MESSAGE; + VERIFY_OPTIONAL_FIELD(opt_ping) << COMMON_MESSAGE; + VERIFY_OPTIONAL_FIELD(opt_priority) << COMMON_MESSAGE; + VERIFY_OPTIONAL_FIELD(opt_push_promise) << COMMON_MESSAGE; + VERIFY_OPTIONAL_FIELD(opt_rst_stream_error_code) << COMMON_MESSAGE; + VERIFY_OPTIONAL_FIELD(opt_window_update_increment) << COMMON_MESSAGE; + +#undef VERIFY_OPTIONAL_FIELD + + return AssertionSuccess(); +} + +void QuicHttpFrameParts::SetTotalPadLength(size_t total_pad_length) { + opt_pad_length.reset(); + padding.clear(); + if (total_pad_length > 0) { + ASSERT_LE(total_pad_length, 256u); + ASSERT_TRUE(frame_header.IsPadded()); + opt_pad_length = total_pad_length - 1; + char zero = 0; + padding.append(opt_pad_length.value(), zero); + } + + if (opt_pad_length) { + VLOG(1) << "SetTotalPadLength: pad_length=" << opt_pad_length.value(); + } else { + VLOG(1) << "SetTotalPadLength: has no pad length"; + } +} + +void QuicHttpFrameParts::SetAltSvcExpected(QuicStringPiece origin, + QuicStringPiece value) { + altsvc_origin.append(origin.data(), origin.size()); + altsvc_value.append(value.data(), value.size()); + opt_altsvc_origin_length = origin.size(); + opt_altsvc_value_length = value.size(); +} + +bool QuicHttpFrameParts::OnFrameHeader(const QuicHttpFrameHeader& header) { + ADD_FAILURE() << "OnFrameHeader: " << *this; + return true; +} + +void QuicHttpFrameParts::OnDataStart(const QuicHttpFrameHeader& header) { + VLOG(1) << "OnDataStart: " << header; + ASSERT_TRUE(StartFrameOfType(header, QuicHttpFrameType::DATA)) << *this; + opt_payload_length = header.payload_length; +} + +void QuicHttpFrameParts::OnDataPayload(const char* data, size_t len) { + VLOG(1) << "OnDataPayload: len=" << len << "; frame_header: " << frame_header; + ASSERT_TRUE(InFrameOfType(QuicHttpFrameType::DATA)) << *this; + ASSERT_TRUE( + AppendString(QuicStringPiece(data, len), &payload, &opt_payload_length)); +} + +void QuicHttpFrameParts::OnDataEnd() { + VLOG(1) << "OnDataEnd; frame_header: " << frame_header; + ASSERT_TRUE(EndFrameOfType(QuicHttpFrameType::DATA)) << *this; +} + +void QuicHttpFrameParts::OnHeadersStart(const QuicHttpFrameHeader& header) { + VLOG(1) << "OnHeadersStart: " << header; + ASSERT_TRUE(StartFrameOfType(header, QuicHttpFrameType::HEADERS)) << *this; + opt_payload_length = header.payload_length; +} + +void QuicHttpFrameParts::OnHeadersPriority( + const QuicHttpPriorityFields& priority) { + VLOG(1) << "OnHeadersPriority: priority: " << priority + << "; frame_header: " << frame_header; + ASSERT_TRUE(InFrameOfType(QuicHttpFrameType::HEADERS)) << *this; + ASSERT_FALSE(opt_priority); + opt_priority = priority; + ASSERT_TRUE(opt_payload_length); + opt_payload_length = + opt_payload_length.value() - QuicHttpPriorityFields::EncodedSize(); +} + +void QuicHttpFrameParts::OnHpackFragment(const char* data, size_t len) { + VLOG(1) << "OnHpackFragment: len=" << len + << "; frame_header: " << frame_header; + ASSERT_TRUE(got_start_callback); + ASSERT_FALSE(got_end_callback); + ASSERT_TRUE(FrameCanHaveHpackPayload(frame_header)) << *this; + ASSERT_TRUE( + AppendString(QuicStringPiece(data, len), &payload, &opt_payload_length)); +} + +void QuicHttpFrameParts::OnHeadersEnd() { + VLOG(1) << "OnHeadersEnd; frame_header: " << frame_header; + ASSERT_TRUE(EndFrameOfType(QuicHttpFrameType::HEADERS)) << *this; +} + +void QuicHttpFrameParts::OnPriorityFrame( + const QuicHttpFrameHeader& header, + const QuicHttpPriorityFields& priority) { + VLOG(1) << "OnPriorityFrame: " << header << "; priority: " << priority; + ASSERT_TRUE(StartFrameOfType(header, QuicHttpFrameType::QUIC_HTTP_PRIORITY)) + << *this; + ASSERT_FALSE(opt_priority); + opt_priority = priority; + ASSERT_TRUE(EndFrameOfType(QuicHttpFrameType::QUIC_HTTP_PRIORITY)) << *this; +} + +void QuicHttpFrameParts::OnContinuationStart( + const QuicHttpFrameHeader& header) { + VLOG(1) << "OnContinuationStart: " << header; + ASSERT_TRUE(StartFrameOfType(header, QuicHttpFrameType::CONTINUATION)) + << *this; + opt_payload_length = header.payload_length; +} + +void QuicHttpFrameParts::OnContinuationEnd() { + VLOG(1) << "OnContinuationEnd; frame_header: " << frame_header; + ASSERT_TRUE(EndFrameOfType(QuicHttpFrameType::CONTINUATION)) << *this; +} + +void QuicHttpFrameParts::OnPadLength(size_t trailing_length) { + VLOG(1) << "OnPadLength: trailing_length=" << trailing_length; + ASSERT_TRUE(InPaddedFrame()) << *this; + ASSERT_FALSE(opt_pad_length); + ASSERT_TRUE(opt_payload_length); + size_t total_padding_length = trailing_length + 1; + ASSERT_GE(opt_payload_length.value(), total_padding_length); + opt_payload_length = opt_payload_length.value() - total_padding_length; + opt_pad_length = trailing_length; +} + +void QuicHttpFrameParts::OnPadding(const char* pad, size_t skipped_length) { + VLOG(1) << "OnPadding: skipped_length=" << skipped_length; + ASSERT_TRUE(InPaddedFrame()) << *this; + ASSERT_TRUE(opt_pad_length); + ASSERT_TRUE(AppendString(QuicStringPiece(pad, skipped_length), &padding, + &opt_pad_length)); +} + +void QuicHttpFrameParts::OnRstStream(const QuicHttpFrameHeader& header, + QuicHttpErrorCode error_code) { + VLOG(1) << "OnRstStream: " << header << "; code=" << error_code; + ASSERT_TRUE(StartFrameOfType(header, QuicHttpFrameType::RST_STREAM)) << *this; + ASSERT_FALSE(opt_rst_stream_error_code); + opt_rst_stream_error_code = error_code; + ASSERT_TRUE(EndFrameOfType(QuicHttpFrameType::RST_STREAM)) << *this; +} + +void QuicHttpFrameParts::OnSettingsStart(const QuicHttpFrameHeader& header) { + VLOG(1) << "OnSettingsStart: " << header; + ASSERT_TRUE(StartFrameOfType(header, QuicHttpFrameType::SETTINGS)) << *this; + ASSERT_EQ(0u, settings.size()); + ASSERT_FALSE(header.IsAck()) << header; +} + +void QuicHttpFrameParts::OnSetting( + const QuicHttpSettingFields& setting_fields) { + VLOG(1) << "OnSetting: " << setting_fields; + ASSERT_TRUE(InFrameOfType(QuicHttpFrameType::SETTINGS)) << *this; + settings.push_back(setting_fields); +} + +void QuicHttpFrameParts::OnSettingsEnd() { + VLOG(1) << "OnSettingsEnd; frame_header: " << frame_header; + ASSERT_TRUE(EndFrameOfType(QuicHttpFrameType::SETTINGS)) << *this; +} + +void QuicHttpFrameParts::OnSettingsAck(const QuicHttpFrameHeader& header) { + VLOG(1) << "OnSettingsAck: " << header; + ASSERT_TRUE(StartFrameOfType(header, QuicHttpFrameType::SETTINGS)) << *this; + ASSERT_EQ(0u, settings.size()); + ASSERT_TRUE(header.IsAck()); + ASSERT_TRUE(EndFrameOfType(QuicHttpFrameType::SETTINGS)) << *this; +} + +void QuicHttpFrameParts::OnPushPromiseStart( + const QuicHttpFrameHeader& header, + const QuicHttpPushPromiseFields& promise, + size_t total_padding_length) { + VLOG(1) << "OnPushPromiseStart header: " << header << "; promise: " << promise + << "; total_padding_length: " << total_padding_length; + ASSERT_TRUE(StartFrameOfType(header, QuicHttpFrameType::PUSH_PROMISE)) + << *this; + ASSERT_GE(header.payload_length, QuicHttpPushPromiseFields::EncodedSize()); + opt_payload_length = + header.payload_length - QuicHttpPushPromiseFields::EncodedSize(); + ASSERT_FALSE(opt_push_promise); + opt_push_promise = promise; + if (total_padding_length > 0) { + ASSERT_GE(opt_payload_length.value(), total_padding_length); + OnPadLength(total_padding_length - 1); + } else { + ASSERT_FALSE(header.IsPadded()); + } +} + +void QuicHttpFrameParts::OnPushPromiseEnd() { + VLOG(1) << "OnPushPromiseEnd; frame_header: " << frame_header; + ASSERT_TRUE(EndFrameOfType(QuicHttpFrameType::PUSH_PROMISE)) << *this; +} + +void QuicHttpFrameParts::OnPing(const QuicHttpFrameHeader& header, + const QuicHttpPingFields& ping) { + VLOG(1) << "OnPing header: " << header << " ping: " << ping; + ASSERT_TRUE(StartFrameOfType(header, QuicHttpFrameType::PING)) << *this; + ASSERT_FALSE(header.IsAck()); + ASSERT_FALSE(opt_ping); + opt_ping = ping; + ASSERT_TRUE(EndFrameOfType(QuicHttpFrameType::PING)) << *this; +} + +void QuicHttpFrameParts::OnPingAck(const QuicHttpFrameHeader& header, + const QuicHttpPingFields& ping) { + VLOG(1) << "OnPingAck header: " << header << " ping: " << ping; + ASSERT_TRUE(StartFrameOfType(header, QuicHttpFrameType::PING)) << *this; + ASSERT_TRUE(header.IsAck()); + ASSERT_FALSE(opt_ping); + opt_ping = ping; + ASSERT_TRUE(EndFrameOfType(QuicHttpFrameType::PING)) << *this; +} + +void QuicHttpFrameParts::OnGoAwayStart(const QuicHttpFrameHeader& header, + const QuicHttpGoAwayFields& goaway) { + VLOG(1) << "OnGoAwayStart: " << goaway; + ASSERT_TRUE(StartFrameOfType(header, QuicHttpFrameType::GOAWAY)) << *this; + ASSERT_FALSE(opt_goaway); + opt_goaway = goaway; + opt_payload_length = + header.payload_length - QuicHttpGoAwayFields::EncodedSize(); +} + +void QuicHttpFrameParts::OnGoAwayOpaqueData(const char* data, size_t len) { + VLOG(1) << "OnGoAwayOpaqueData: len=" << len; + ASSERT_TRUE(InFrameOfType(QuicHttpFrameType::GOAWAY)) << *this; + ASSERT_TRUE( + AppendString(QuicStringPiece(data, len), &payload, &opt_payload_length)); +} + +void QuicHttpFrameParts::OnGoAwayEnd() { + VLOG(1) << "OnGoAwayEnd; frame_header: " << frame_header; + ASSERT_TRUE(EndFrameOfType(QuicHttpFrameType::GOAWAY)) << *this; +} + +void QuicHttpFrameParts::OnWindowUpdate(const QuicHttpFrameHeader& header, + uint32_t increment) { + VLOG(1) << "OnWindowUpdate header: " << header + << " increment=" << increment; + ASSERT_TRUE(StartFrameOfType(header, QuicHttpFrameType::WINDOW_UPDATE)) + << *this; + ASSERT_FALSE(opt_window_update_increment); + opt_window_update_increment = increment; + ASSERT_TRUE(EndFrameOfType(QuicHttpFrameType::WINDOW_UPDATE)) << *this; +} + +void QuicHttpFrameParts::OnAltSvcStart(const QuicHttpFrameHeader& header, + size_t origin_length, + size_t value_length) { + VLOG(1) << "OnAltSvcStart: " << header + << " origin_length: " << origin_length + << " value_length: " << value_length; + ASSERT_TRUE(StartFrameOfType(header, QuicHttpFrameType::ALTSVC)) << *this; + ASSERT_FALSE(opt_altsvc_origin_length); + opt_altsvc_origin_length = origin_length; + ASSERT_FALSE(opt_altsvc_value_length); + opt_altsvc_value_length = value_length; +} + +void QuicHttpFrameParts::OnAltSvcOriginData(const char* data, size_t len) { + VLOG(1) << "OnAltSvcOriginData: len=" << len; + ASSERT_TRUE(InFrameOfType(QuicHttpFrameType::ALTSVC)) << *this; + ASSERT_TRUE(AppendString(QuicStringPiece(data, len), &altsvc_origin, + &opt_altsvc_origin_length)); +} + +void QuicHttpFrameParts::OnAltSvcValueData(const char* data, size_t len) { + VLOG(1) << "OnAltSvcValueData: len=" << len; + ASSERT_TRUE(InFrameOfType(QuicHttpFrameType::ALTSVC)) << *this; + ASSERT_TRUE(AppendString(QuicStringPiece(data, len), &altsvc_value, + &opt_altsvc_value_length)); +} + +void QuicHttpFrameParts::OnAltSvcEnd() { + VLOG(1) << "OnAltSvcEnd; frame_header: " << frame_header; + ASSERT_TRUE(EndFrameOfType(QuicHttpFrameType::ALTSVC)) << *this; +} + +void QuicHttpFrameParts::OnUnknownStart(const QuicHttpFrameHeader& header) { + VLOG(1) << "OnUnknownStart: " << header; + ASSERT_FALSE(IsSupportedQuicHttpFrameType(header.type)) << header; + ASSERT_FALSE(got_start_callback); + ASSERT_EQ(frame_header, header); + got_start_callback = true; + opt_payload_length = header.payload_length; +} + +void QuicHttpFrameParts::OnUnknownPayload(const char* data, size_t len) { + VLOG(1) << "OnUnknownPayload: len=" << len; + ASSERT_FALSE(IsSupportedQuicHttpFrameType(frame_header.type)) << *this; + ASSERT_TRUE(got_start_callback); + ASSERT_FALSE(got_end_callback); + ASSERT_TRUE( + AppendString(QuicStringPiece(data, len), &payload, &opt_payload_length)); +} + +void QuicHttpFrameParts::OnUnknownEnd() { + VLOG(1) << "OnUnknownEnd; frame_header: " << frame_header; + ASSERT_FALSE(IsSupportedQuicHttpFrameType(frame_header.type)) << *this; + ASSERT_TRUE(got_start_callback); + ASSERT_FALSE(got_end_callback); + got_end_callback = true; +} + +void QuicHttpFrameParts::OnPaddingTooLong(const QuicHttpFrameHeader& header, + size_t missing_length) { + VLOG(1) << "OnPaddingTooLong: " << header + << "; missing_length: " << missing_length; + ASSERT_EQ(frame_header, header); + ASSERT_FALSE(got_end_callback); + ASSERT_TRUE(FrameIsPadded(header)); + ASSERT_FALSE(opt_pad_length); + ASSERT_FALSE(opt_missing_length); + opt_missing_length = missing_length; + got_start_callback = true; + got_end_callback = true; +} + +void QuicHttpFrameParts::OnFrameSizeError(const QuicHttpFrameHeader& header) { + VLOG(1) << "OnFrameSizeError: " << header; + ASSERT_EQ(frame_header, header); + ASSERT_FALSE(got_end_callback); + ASSERT_FALSE(has_frame_size_error); + has_frame_size_error = true; + got_end_callback = true; +} + +void QuicHttpFrameParts::OutputTo(std::ostream& out) const { + out << "QuicHttpFrameParts{\n frame_header: " << frame_header << "\n"; + if (!payload.empty()) { + out << " payload=\"" << EscapeQueryParamValue(payload, false) << "\"\n"; + } + if (!padding.empty()) { + out << " padding=\"" << EscapeQueryParamValue(padding, false) << "\"\n"; + } + if (!altsvc_origin.empty()) { + out << " altsvc_origin=\"" << EscapeQueryParamValue(altsvc_origin, false) + << "\"\n"; + } + if (!altsvc_value.empty()) { + out << " altsvc_value=\"" << EscapeQueryParamValue(altsvc_value, false) + << "\"\n"; + } + if (opt_priority) { + out << " priority=" << opt_priority.value() << "\n"; + } + if (opt_rst_stream_error_code) { + out << " rst_stream=" << opt_rst_stream_error_code.value() << "\n"; + } + if (opt_push_promise) { + out << " push_promise=" << opt_push_promise.value() << "\n"; + } + if (opt_ping) { + out << " ping=" << opt_ping.value() << "\n"; + } + if (opt_goaway) { + out << " goaway=" << opt_goaway.value() << "\n"; + } + if (opt_window_update_increment) { + out << " window_update=" << opt_window_update_increment.value() << "\n"; + } + if (opt_payload_length) { + out << " payload_length=" << opt_payload_length.value() << "\n"; + } + if (opt_pad_length) { + out << " pad_length=" << opt_pad_length.value() << "\n"; + } + if (opt_missing_length) { + out << " missing_length=" << opt_missing_length.value() << "\n"; + } + if (opt_altsvc_origin_length) { + out << " origin_length=" << opt_altsvc_origin_length.value() << "\n"; + } + if (opt_altsvc_value_length) { + out << " value_length=" << opt_altsvc_value_length.value() << "\n"; + } + if (has_frame_size_error) { + out << " has_frame_size_error\n"; + } + if (got_start_callback) { + out << " got_start_callback\n"; + } + if (got_end_callback) { + out << " got_end_callback\n"; + } + for (size_t ndx = 0; ndx < settings.size(); ++ndx) { + out << " setting[" << ndx << "]=" << settings[ndx]; + } + out << "}"; +} + +AssertionResult QuicHttpFrameParts::StartFrameOfType( + const QuicHttpFrameHeader& header, + QuicHttpFrameType expected_frame_type) { + VERIFY_EQ(header.type, expected_frame_type); + VERIFY_FALSE(got_start_callback); + VERIFY_FALSE(got_end_callback); + VERIFY_EQ(frame_header, header); + got_start_callback = true; + return AssertionSuccess(); +} + +AssertionResult QuicHttpFrameParts::InFrameOfType( + QuicHttpFrameType expected_frame_type) { + VERIFY_TRUE(got_start_callback); + VERIFY_FALSE(got_end_callback); + VERIFY_EQ(frame_header.type, expected_frame_type); + return AssertionSuccess(); +} + +AssertionResult QuicHttpFrameParts::EndFrameOfType( + QuicHttpFrameType expected_frame_type) { + VERIFY_SUCCESS(InFrameOfType(expected_frame_type)); + got_end_callback = true; + return AssertionSuccess(); +} + +AssertionResult QuicHttpFrameParts::InPaddedFrame() { + VERIFY_TRUE(got_start_callback); + VERIFY_FALSE(got_end_callback); + VERIFY_TRUE(FrameIsPadded(frame_header)); + return AssertionSuccess(); +} + +AssertionResult QuicHttpFrameParts::AppendString( + QuicStringPiece source, + QuicString* target, + QuicOptional<size_t>* opt_length) { + target->append(source.data(), source.size()); + if (opt_length != nullptr) { + VERIFY_TRUE(*opt_length) << "Length is not set yet\n" << *this; + VERIFY_LE(target->size(), opt_length->value()) + << "String too large; source.size() = " << source.size() << "\n" + << *this; + } + return ::testing::AssertionSuccess(); +} + +std::ostream& operator<<(std::ostream& out, const QuicHttpFrameParts& v) { + v.OutputTo(out); + return out; +} + +} // namespace test +} // namespace net
diff --git a/net/quic/http/test_tools/quic_http_frame_parts.h b/net/quic/http/test_tools/quic_http_frame_parts.h new file mode 100644 index 0000000..c0afe8b --- /dev/null +++ b/net/quic/http/test_tools/quic_http_frame_parts.h
@@ -0,0 +1,183 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_HTTP_TEST_TOOLS_QUIC_HTTP_FRAME_PARTS_H_ +#define NET_QUIC_HTTP_TEST_TOOLS_QUIC_HTTP_FRAME_PARTS_H_ + +// QuicHttpFrameParts implements QuicHttpFrameDecoderListener, recording the +// callbacks during the decoding of a single frame. It is also used for +// comparing the info that a test expects to be recorded during the decoding of +// a frame with the actual recorded value (i.e. by providing a comparator). + +// TODO(jamessynge): Convert QuicHttpFrameParts to a class, hide the members, +// add getters/setters. + +#include <stddef.h> + +#include <cstdint> +#include <vector> + +#include "base/logging.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_listener.h" +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/quic_http_structures.h" +#include "net/quic/platform/api/quic_optional.h" +#include "net/quic/platform/api/quic_string.h" +#include "net/quic/platform/api/quic_string_piece.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace net { +namespace test { + +// Forward declarations. +struct QuicHttpFrameParts; +std::ostream& operator<<(std::ostream& out, const QuicHttpFrameParts& v); + +struct QuicHttpFrameParts : public QuicHttpFrameDecoderListener { + // The first callback for every type of frame includes the frame header; this + // is the only constructor used during decoding of a frame. + explicit QuicHttpFrameParts(const QuicHttpFrameHeader& header); + + // For use in tests where the expected frame has a variable size payload. + QuicHttpFrameParts(const QuicHttpFrameHeader& header, + QuicStringPiece payload); + + // For use in tests where the expected frame has a variable size payload + // and may be padded. + QuicHttpFrameParts(const QuicHttpFrameHeader& header, + QuicStringPiece payload, + size_t total_pad_length); + + // Copy constructor. + QuicHttpFrameParts(const QuicHttpFrameParts& header); + + ~QuicHttpFrameParts() override; + + // Returns AssertionSuccess() if they're equal, else AssertionFailure() + // with info about the difference. + ::testing::AssertionResult VerifyEquals(const QuicHttpFrameParts& that) const; + + // Format this QuicHttpFrameParts object. + void OutputTo(std::ostream& out) const; + + // Set the total padding length (0 to 256). + void SetTotalPadLength(size_t total_pad_length); + + // Set the origin and value expected in an ALTSVC frame. + void SetAltSvcExpected(QuicStringPiece origin, QuicStringPiece value); + + // QuicHttpFrameDecoderListener methods: + bool OnFrameHeader(const QuicHttpFrameHeader& header) override; + void OnDataStart(const QuicHttpFrameHeader& header) override; + void OnDataPayload(const char* data, size_t len) override; + void OnDataEnd() override; + void OnHeadersStart(const QuicHttpFrameHeader& header) override; + void OnHeadersPriority(const QuicHttpPriorityFields& priority) override; + void OnHpackFragment(const char* data, size_t len) override; + void OnHeadersEnd() override; + void OnPriorityFrame(const QuicHttpFrameHeader& header, + const QuicHttpPriorityFields& priority) override; + void OnContinuationStart(const QuicHttpFrameHeader& header) override; + void OnContinuationEnd() override; + void OnPadLength(size_t trailing_length) override; + void OnPadding(const char* pad, size_t skipped_length) override; + void OnRstStream(const QuicHttpFrameHeader& header, + QuicHttpErrorCode error_code) override; + void OnSettingsStart(const QuicHttpFrameHeader& header) override; + void OnSetting(const QuicHttpSettingFields& setting_fields) override; + void OnSettingsEnd() override; + void OnSettingsAck(const QuicHttpFrameHeader& header) override; + void OnPushPromiseStart(const QuicHttpFrameHeader& header, + const QuicHttpPushPromiseFields& promise, + size_t total_padding_length) override; + void OnPushPromiseEnd() override; + void OnPing(const QuicHttpFrameHeader& header, + const QuicHttpPingFields& ping) override; + void OnPingAck(const QuicHttpFrameHeader& header, + const QuicHttpPingFields& ping) override; + void OnGoAwayStart(const QuicHttpFrameHeader& header, + const QuicHttpGoAwayFields& goaway) override; + void OnGoAwayOpaqueData(const char* data, size_t len) override; + void OnGoAwayEnd() override; + void OnWindowUpdate(const QuicHttpFrameHeader& header, + uint32_t increment) override; + void OnAltSvcStart(const QuicHttpFrameHeader& header, + size_t origin_length, + size_t value_length) override; + void OnAltSvcOriginData(const char* data, size_t len) override; + void OnAltSvcValueData(const char* data, size_t len) override; + void OnAltSvcEnd() override; + void OnUnknownStart(const QuicHttpFrameHeader& header) override; + void OnUnknownPayload(const char* data, size_t len) override; + void OnUnknownEnd() override; + void OnPaddingTooLong(const QuicHttpFrameHeader& header, + size_t missing_length) override; + void OnFrameSizeError(const QuicHttpFrameHeader& header) override; + + // The fields are public for access by tests. + + const QuicHttpFrameHeader frame_header; + + QuicString payload; + QuicString padding; + QuicString altsvc_origin; + QuicString altsvc_value; + + QuicOptional<QuicHttpPriorityFields> opt_priority; + QuicOptional<QuicHttpErrorCode> opt_rst_stream_error_code; + QuicOptional<QuicHttpPushPromiseFields> opt_push_promise; + QuicOptional<QuicHttpPingFields> opt_ping; + QuicOptional<QuicHttpGoAwayFields> opt_goaway; + + QuicOptional<size_t> opt_pad_length; + QuicOptional<size_t> opt_payload_length; + QuicOptional<size_t> opt_missing_length; + QuicOptional<size_t> opt_altsvc_origin_length; + QuicOptional<size_t> opt_altsvc_value_length; + + QuicOptional<size_t> opt_window_update_increment; + + bool has_frame_size_error = false; + + std::vector<QuicHttpSettingFields> settings; + + // These booleans are not checked by CompareCollectedFrames. + bool got_start_callback = false; + bool got_end_callback = false; + + private: + // ASSERT during an On* method that we're handling a frame of type + // expected_frame_type, and have not already received other On* methods + // (i.e. got_start_callback is false). + ::testing::AssertionResult StartFrameOfType( + const QuicHttpFrameHeader& header, + QuicHttpFrameType expected_frame_type); + + // ASSERT that StartFrameOfType has already been called with + // expected_frame_type (i.e. got_start_callback has been called), and that + // EndFrameOfType has not yet been called (i.e. got_end_callback is false). + ::testing::AssertionResult InFrameOfType( + QuicHttpFrameType expected_frame_type); + + // ASSERT that we're InFrameOfType, and then sets got_end_callback=true. + ::testing::AssertionResult EndFrameOfType( + QuicHttpFrameType expected_frame_type); + + // ASSERT that we're in the middle of processing a frame that is padded. + ::testing::AssertionResult InPaddedFrame(); + + // Append source to target. If opt_length is not nullptr, then verifies that + // the optional has a value (i.e. that the necessary On*Start method has been + // called), and that target is not longer than opt_length->value(). + ::testing::AssertionResult AppendString(QuicStringPiece source, + QuicString* target, + QuicOptional<size_t>* opt_length); +}; + +std::ostream& operator<<(std::ostream& out, const QuicHttpFrameParts& v); + +} // namespace test +} // namespace net + +#endif // NET_QUIC_HTTP_TEST_TOOLS_QUIC_HTTP_FRAME_PARTS_H_
diff --git a/net/quic/http/test_tools/quic_http_frame_parts_collector.cc b/net/quic/http/test_tools/quic_http_frame_parts_collector.cc new file mode 100644 index 0000000..4c02829 --- /dev/null +++ b/net/quic/http/test_tools/quic_http_frame_parts_collector.cc
@@ -0,0 +1,115 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/test_tools/quic_http_frame_parts_collector.h" + +#include <utility> + +#include "base/logging.h" +#include "net/quic/http/quic_http_structures_test_util.h" +#include "net/quic/platform/api/quic_ptr_util.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace net { +namespace test { + +QuicHttpFramePartsCollector::QuicHttpFramePartsCollector() {} +QuicHttpFramePartsCollector::~QuicHttpFramePartsCollector() {} + +void QuicHttpFramePartsCollector::Reset() { + current_frame_.reset(); + collected_frames_.clear(); + expected_header_set_ = false; +} + +const QuicHttpFrameParts* QuicHttpFramePartsCollector::frame(size_t n) const { + if (n < size()) { + return collected_frames_.at(n).get(); + } + CHECK(n == size()); + return current_frame(); +} + +void QuicHttpFramePartsCollector::ExpectFrameHeader( + const QuicHttpFrameHeader& header) { + EXPECT_FALSE(IsInProgress()); + EXPECT_FALSE(expected_header_set_) + << "expected_header_: " << expected_header_; + expected_header_ = header; + expected_header_set_ = true; + // OnFrameHeader is called before the flags are scrubbed, but the other + // methods are called after, so scrub the invalid flags from expected_header_. + ScrubFlagsOfHeader(&expected_header_); +} + +void QuicHttpFramePartsCollector::TestExpectedHeader( + const QuicHttpFrameHeader& header) { + if (expected_header_set_) { + EXPECT_EQ(header, expected_header_); + expected_header_set_ = false; + } +} + +QuicHttpFrameDecoderListener* QuicHttpFramePartsCollector::StartFrame( + const QuicHttpFrameHeader& header) { + TestExpectedHeader(header); + EXPECT_FALSE(IsInProgress()); + if (current_frame_ == nullptr) { + current_frame_ = QuicMakeUnique<QuicHttpFrameParts>(header); + } + return current_frame(); +} + +QuicHttpFrameDecoderListener* QuicHttpFramePartsCollector::StartAndEndFrame( + const QuicHttpFrameHeader& header) { + TestExpectedHeader(header); + EXPECT_FALSE(IsInProgress()); + if (current_frame_ == nullptr) { + current_frame_ = QuicMakeUnique<QuicHttpFrameParts>(header); + } + QuicHttpFrameDecoderListener* result = current_frame(); + collected_frames_.push_back(std::move(current_frame_)); + return result; +} + +QuicHttpFrameDecoderListener* QuicHttpFramePartsCollector::CurrentFrame() { + EXPECT_TRUE(IsInProgress()); + if (current_frame_ == nullptr) { + return &failing_listener_; + } + return current_frame(); +} + +QuicHttpFrameDecoderListener* QuicHttpFramePartsCollector::EndFrame() { + EXPECT_TRUE(IsInProgress()); + if (current_frame_ == nullptr) { + return &failing_listener_; + } + QuicHttpFrameDecoderListener* result = current_frame(); + collected_frames_.push_back(std::move(current_frame_)); + return result; +} + +QuicHttpFrameDecoderListener* QuicHttpFramePartsCollector::FrameError( + const QuicHttpFrameHeader& header) { + TestExpectedHeader(header); + if (current_frame_ == nullptr) { + // The decoder may detect an error before making any calls to the listener + // regarding the frame, in which case current_frame_==nullptr and we need + // to create a QuicHttpFrameParts instance. + current_frame_ = QuicMakeUnique<QuicHttpFrameParts>(header); + } else { + // Similarly, the decoder may have made calls to the listener regarding the + // frame before detecting the error; for example, the DATA payload decoder + // calls OnDataStart before it can detect padding errors, hence before it + // can call OnPaddingTooLong. + EXPECT_EQ(header, current_frame_->frame_header); + } + QuicHttpFrameDecoderListener* result = current_frame(); + collected_frames_.push_back(std::move(current_frame_)); + return result; +} + +} // namespace test +} // namespace net
diff --git a/net/quic/http/test_tools/quic_http_frame_parts_collector.h b/net/quic/http/test_tools/quic_http_frame_parts_collector.h new file mode 100644 index 0000000..3917451 --- /dev/null +++ b/net/quic/http/test_tools/quic_http_frame_parts_collector.h
@@ -0,0 +1,114 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_HTTP_TEST_TOOLS_QUIC_HTTP_FRAME_PARTS_COLLECTOR_H_ +#define NET_QUIC_HTTP_TEST_TOOLS_QUIC_HTTP_FRAME_PARTS_COLLECTOR_H_ + +// QuicHttpFramePartsCollector is a base class for QuicHttpFrameDecoderListener +// implementations that create one QuicHttpFrameParts instance for each decoded +// frame. + +#include <stddef.h> +#include <memory> +#include <vector> + +#include "net/quic/http/decoder/quic_http_frame_decoder_listener.h" +#include "net/quic/http/decoder/quic_http_frame_decoder_listener_test_util.h" +#include "net/quic/http/quic_http_structures.h" +#include "net/quic/http/test_tools/quic_http_frame_parts.h" + +namespace net { +namespace test { + +class QuicHttpFramePartsCollector : public FailingQuicHttpFrameDecoderListener { + public: + QuicHttpFramePartsCollector(); + ~QuicHttpFramePartsCollector() override; + + // Toss out the collected data. + void Reset(); + + // Returns true if has started recording the info for a frame and has not yet + // finished doing so. + bool IsInProgress() const { return current_frame_ != nullptr; } + + // Returns the QuicHttpFrameParts instance into which we're currently + // recording callback info if IsInProgress, else nullptr. + const QuicHttpFrameParts* current_frame() const { + return current_frame_.get(); + } + + // Returns the number of completely collected QuicHttpFrameParts instances. + size_t size() const { return collected_frames_.size(); } + + // Returns the n'th frame, where 0 is the oldest of the collected frames, + // and n==size() is the frame currently being collected, if there is one. + // Returns nullptr if the requested index is not valid. + const QuicHttpFrameParts* frame(size_t n) const; + + protected: + // In support of OnFrameHeader, set the header that we expect to be used in + // the next call. + // TODO(jamessynge): Remove ExpectFrameHeader et al. once done with supporting + // SpdyFramer's exact states. + void ExpectFrameHeader(const QuicHttpFrameHeader& header); + + // For use in implementing On*Start methods of QuicHttpFrameDecoderListener, + // returns a QuicHttpFrameParts instance, which will be newly created if + // IsInProgress==false (which the caller should ensure), else will be the + // current_frame(); never returns nullptr. + // If called when IsInProgress==true, a test failure will be recorded. + QuicHttpFrameDecoderListener* StartFrame(const QuicHttpFrameHeader& header); + + // For use in implementing On* callbacks, such as OnPingAck, that are the only + // call expected for the frame being decoded; not for On*Start methods. + // Returns a QuicHttpFrameParts instance, which will be newly created if + // IsInProgress==false (which the caller should ensure), else will be the + // current_frame(); never returns nullptr. + // If called when IsInProgress==true, a test failure will be recorded. + QuicHttpFrameDecoderListener* StartAndEndFrame( + const QuicHttpFrameHeader& header); + + // If IsInProgress==true, returns the QuicHttpFrameParts into which the + // current frame is being recorded; else records a test failure and returns + // failing_listener_, which will record a test failure when any of its + // On* methods is called. + QuicHttpFrameDecoderListener* CurrentFrame(); + + // For use in implementing On*End methods, pushes the current frame onto + // the vector of completed frames, and returns a pointer to it for recording + // the info in the final call. If IsInProgress==false, records a test failure + // and returns failing_listener_, which will record a test failure when any + // of its On* methods is called. + QuicHttpFrameDecoderListener* EndFrame(); + + // For use in implementing OnPaddingTooLong and OnFrameSizeError, is + // equivalent to EndFrame() if IsInProgress==true, else equivalent to + // StartAndEndFrame(). + QuicHttpFrameDecoderListener* FrameError(const QuicHttpFrameHeader& header); + + private: + // Returns the mutable QuicHttpFrameParts instance into which we're currently + // recording callback info if IsInProgress, else nullptr. + QuicHttpFrameParts* current_frame() { return current_frame_.get(); } + + // If expected header is set, verify that it matches the header param. + // TODO(jamessynge): Remove TestExpectedHeader et al. once done + // with supporting SpdyFramer's exact states. + void TestExpectedHeader(const QuicHttpFrameHeader& header); + + std::unique_ptr<QuicHttpFrameParts> current_frame_; + std::vector<std::unique_ptr<QuicHttpFrameParts>> collected_frames_; + FailingQuicHttpFrameDecoderListener failing_listener_; + + // TODO(jamessynge): Remove expected_header_ et al. once done with supporting + // SpdyFramer's exact states. + QuicHttpFrameHeader expected_header_; + bool expected_header_set_ = false; +}; + +} // namespace test +} // namespace net + +#endif // NET_QUIC_HTTP_TEST_TOOLS_QUIC_HTTP_FRAME_PARTS_COLLECTOR_H_
diff --git a/net/quic/http/test_tools/quic_http_frame_parts_collector_listener.cc b/net/quic/http/test_tools/quic_http_frame_parts_collector_listener.cc new file mode 100644 index 0000000..7e54dd3 --- /dev/null +++ b/net/quic/http/test_tools/quic_http_frame_parts_collector_listener.cc
@@ -0,0 +1,236 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/test_tools/quic_http_frame_parts_collector_listener.h" + +#include "base/logging.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace net { +namespace test { + +bool QuicHttpFramePartsCollectorListener::OnFrameHeader( + const QuicHttpFrameHeader& header) { + VLOG(1) << "OnFrameHeader: " << header; + ExpectFrameHeader(header); + return true; +} + +void QuicHttpFramePartsCollectorListener::OnDataStart( + const QuicHttpFrameHeader& header) { + VLOG(1) << "OnDataStart: " << header; + StartFrame(header)->OnDataStart(header); +} + +void QuicHttpFramePartsCollectorListener::OnDataPayload(const char* data, + size_t len) { + VLOG(1) << "OnDataPayload: len=" << len; + CurrentFrame()->OnDataPayload(data, len); +} + +void QuicHttpFramePartsCollectorListener::OnDataEnd() { + VLOG(1) << "OnDataEnd"; + EndFrame()->OnDataEnd(); +} + +void QuicHttpFramePartsCollectorListener::OnHeadersStart( + const QuicHttpFrameHeader& header) { + VLOG(1) << "OnHeadersStart: " << header; + StartFrame(header)->OnHeadersStart(header); +} + +void QuicHttpFramePartsCollectorListener::OnHeadersPriority( + const QuicHttpPriorityFields& priority) { + VLOG(1) << "OnHeadersPriority: " << priority; + CurrentFrame()->OnHeadersPriority(priority); +} + +void QuicHttpFramePartsCollectorListener::OnHpackFragment(const char* data, + size_t len) { + VLOG(1) << "OnHpackFragment: len=" << len; + CurrentFrame()->OnHpackFragment(data, len); +} + +void QuicHttpFramePartsCollectorListener::OnHeadersEnd() { + VLOG(1) << "OnHeadersEnd"; + EndFrame()->OnHeadersEnd(); +} + +void QuicHttpFramePartsCollectorListener::OnPriorityFrame( + const QuicHttpFrameHeader& header, + const QuicHttpPriorityFields& priority_fields) { + VLOG(1) << "OnPriority: " << header << "; " << priority_fields; + StartAndEndFrame(header)->OnPriorityFrame(header, priority_fields); +} + +void QuicHttpFramePartsCollectorListener::OnContinuationStart( + const QuicHttpFrameHeader& header) { + VLOG(1) << "OnContinuationStart: " << header; + StartFrame(header)->OnContinuationStart(header); +} + +void QuicHttpFramePartsCollectorListener::OnContinuationEnd() { + VLOG(1) << "OnContinuationEnd"; + EndFrame()->OnContinuationEnd(); +} + +void QuicHttpFramePartsCollectorListener::OnPadLength(size_t pad_length) { + VLOG(1) << "OnPadLength: " << pad_length; + CurrentFrame()->OnPadLength(pad_length); +} + +void QuicHttpFramePartsCollectorListener::OnPadding(const char* padding, + size_t skipped_length) { + VLOG(1) << "OnPadding: " << skipped_length; + CurrentFrame()->OnPadding(padding, skipped_length); +} + +void QuicHttpFramePartsCollectorListener::OnRstStream( + const QuicHttpFrameHeader& header, + QuicHttpErrorCode error_code) { + VLOG(1) << "OnRstStream: " << header << "; error_code=" << error_code; + StartAndEndFrame(header)->OnRstStream(header, error_code); +} + +void QuicHttpFramePartsCollectorListener::OnSettingsStart( + const QuicHttpFrameHeader& header) { + VLOG(1) << "OnSettingsStart: " << header; + EXPECT_EQ(QuicHttpFrameType::SETTINGS, header.type) << header; + EXPECT_EQ(QuicHttpFrameFlag(), header.flags) << header; + StartFrame(header)->OnSettingsStart(header); +} + +void QuicHttpFramePartsCollectorListener::OnSetting( + const QuicHttpSettingFields& setting_fields) { + VLOG(1) << "QuicHttpSettingFields: setting_fields=" << setting_fields; + CurrentFrame()->OnSetting(setting_fields); +} + +void QuicHttpFramePartsCollectorListener::OnSettingsEnd() { + VLOG(1) << "OnSettingsEnd"; + EndFrame()->OnSettingsEnd(); +} + +void QuicHttpFramePartsCollectorListener::OnSettingsAck( + const QuicHttpFrameHeader& header) { + VLOG(1) << "OnSettingsAck: " << header; + StartAndEndFrame(header)->OnSettingsAck(header); +} + +void QuicHttpFramePartsCollectorListener::OnPushPromiseStart( + const QuicHttpFrameHeader& header, + const QuicHttpPushPromiseFields& promise, + size_t total_padding_length) { + VLOG(1) << "OnPushPromiseStart header: " << header << " promise: " << promise + << " total_padding_length: " << total_padding_length; + EXPECT_EQ(QuicHttpFrameType::PUSH_PROMISE, header.type); + StartFrame(header)->OnPushPromiseStart(header, promise, total_padding_length); +} + +void QuicHttpFramePartsCollectorListener::OnPushPromiseEnd() { + VLOG(1) << "OnPushPromiseEnd"; + EndFrame()->OnPushPromiseEnd(); +} + +void QuicHttpFramePartsCollectorListener::OnPing( + const QuicHttpFrameHeader& header, + const QuicHttpPingFields& ping) { + VLOG(1) << "OnPing: " << header << "; " << ping; + StartAndEndFrame(header)->OnPing(header, ping); +} + +void QuicHttpFramePartsCollectorListener::OnPingAck( + const QuicHttpFrameHeader& header, + const QuicHttpPingFields& ping) { + VLOG(1) << "OnPingAck: " << header << "; " << ping; + StartAndEndFrame(header)->OnPingAck(header, ping); +} + +void QuicHttpFramePartsCollectorListener::OnGoAwayStart( + const QuicHttpFrameHeader& header, + const QuicHttpGoAwayFields& goaway) { + VLOG(1) << "OnGoAwayStart header: " << header << "; goaway: " << goaway; + StartFrame(header)->OnGoAwayStart(header, goaway); +} + +void QuicHttpFramePartsCollectorListener::OnGoAwayOpaqueData(const char* data, + size_t len) { + VLOG(1) << "OnGoAwayOpaqueData: len=" << len; + CurrentFrame()->OnGoAwayOpaqueData(data, len); +} + +void QuicHttpFramePartsCollectorListener::OnGoAwayEnd() { + VLOG(1) << "OnGoAwayEnd"; + EndFrame()->OnGoAwayEnd(); +} + +void QuicHttpFramePartsCollectorListener::OnWindowUpdate( + const QuicHttpFrameHeader& header, + uint32_t window_size_increment) { + VLOG(1) << "OnWindowUpdate: " << header + << "; window_size_increment=" << window_size_increment; + EXPECT_EQ(QuicHttpFrameType::WINDOW_UPDATE, header.type); + StartAndEndFrame(header)->OnWindowUpdate(header, window_size_increment); +} + +void QuicHttpFramePartsCollectorListener::OnAltSvcStart( + const QuicHttpFrameHeader& header, + size_t origin_length, + size_t value_length) { + VLOG(1) << "OnAltSvcStart header: " << header + << "; origin_length=" << origin_length + << "; value_length=" << value_length; + StartFrame(header)->OnAltSvcStart(header, origin_length, value_length); +} + +void QuicHttpFramePartsCollectorListener::OnAltSvcOriginData(const char* data, + size_t len) { + VLOG(1) << "OnAltSvcOriginData: len=" << len; + CurrentFrame()->OnAltSvcOriginData(data, len); +} + +void QuicHttpFramePartsCollectorListener::OnAltSvcValueData(const char* data, + size_t len) { + VLOG(1) << "OnAltSvcValueData: len=" << len; + CurrentFrame()->OnAltSvcValueData(data, len); +} + +void QuicHttpFramePartsCollectorListener::OnAltSvcEnd() { + VLOG(1) << "OnAltSvcEnd"; + EndFrame()->OnAltSvcEnd(); +} + +void QuicHttpFramePartsCollectorListener::OnUnknownStart( + const QuicHttpFrameHeader& header) { + VLOG(1) << "OnUnknownStart: " << header; + StartFrame(header)->OnUnknownStart(header); +} + +void QuicHttpFramePartsCollectorListener::OnUnknownPayload(const char* data, + size_t len) { + VLOG(1) << "OnUnknownPayload: len=" << len; + CurrentFrame()->OnUnknownPayload(data, len); +} + +void QuicHttpFramePartsCollectorListener::OnUnknownEnd() { + VLOG(1) << "OnUnknownEnd"; + EndFrame()->OnUnknownEnd(); +} + +void QuicHttpFramePartsCollectorListener::OnPaddingTooLong( + const QuicHttpFrameHeader& header, + size_t missing_length) { + VLOG(1) << "OnPaddingTooLong: " << header + << " missing_length: " << missing_length; + EndFrame()->OnPaddingTooLong(header, missing_length); +} + +void QuicHttpFramePartsCollectorListener::OnFrameSizeError( + const QuicHttpFrameHeader& header) { + VLOG(1) << "OnFrameSizeError: " << header; + FrameError(header)->OnFrameSizeError(header); +} + +} // namespace test +} // namespace net
diff --git a/net/quic/http/test_tools/quic_http_frame_parts_collector_listener.h b/net/quic/http/test_tools/quic_http_frame_parts_collector_listener.h new file mode 100644 index 0000000..54f1229 --- /dev/null +++ b/net/quic/http/test_tools/quic_http_frame_parts_collector_listener.h
@@ -0,0 +1,84 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_HTTP_TEST_TOOLS_QUIC_HTTP_FRAME_PARTS_COLLECTOR_LISTENER_H_ +#define NET_QUIC_HTTP_TEST_TOOLS_QUIC_HTTP_FRAME_PARTS_COLLECTOR_LISTENER_H_ + +// QuicHttpFramePartsCollectorListener extends QuicHttpFramePartsCollector with +// an implementation of every method of QuicHttpFrameDecoderListener; it is +// essentially the union of all the Listener classes in the tests of the +// payload decoders (i.e. in ./payload_decoders/*_test.cc files), with the +// addition of the OnFrameHeader method. +// QuicHttpFramePartsCollectorListener supports tests of QuicHttpFrameDecoder. + +#include <stddef.h> + +#include <cstdint> + +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/quic_http_structures.h" +#include "net/quic/http/test_tools/quic_http_frame_parts_collector.h" + +namespace net { +namespace test { + +class QuicHttpFramePartsCollectorListener : public QuicHttpFramePartsCollector { + public: + QuicHttpFramePartsCollectorListener() {} + ~QuicHttpFramePartsCollectorListener() override {} + + // TODO(jamessynge): Remove OnFrameHeader once done with supporting + // SpdyFramer's exact states. + bool OnFrameHeader(const QuicHttpFrameHeader& header) override; + void OnDataStart(const QuicHttpFrameHeader& header) override; + void OnDataPayload(const char* data, size_t len) override; + void OnDataEnd() override; + void OnHeadersStart(const QuicHttpFrameHeader& header) override; + void OnHeadersPriority(const QuicHttpPriorityFields& priority) override; + void OnHpackFragment(const char* data, size_t len) override; + void OnHeadersEnd() override; + void OnPriorityFrame(const QuicHttpFrameHeader& header, + const QuicHttpPriorityFields& priority_fields) override; + void OnContinuationStart(const QuicHttpFrameHeader& header) override; + void OnContinuationEnd() override; + void OnPadLength(size_t pad_length) override; + void OnPadding(const char* padding, size_t skipped_length) override; + void OnRstStream(const QuicHttpFrameHeader& header, + QuicHttpErrorCode error_code) override; + void OnSettingsStart(const QuicHttpFrameHeader& header) override; + void OnSetting(const QuicHttpSettingFields& setting_fields) override; + void OnSettingsEnd() override; + void OnSettingsAck(const QuicHttpFrameHeader& header) override; + void OnPushPromiseStart(const QuicHttpFrameHeader& header, + const QuicHttpPushPromiseFields& promise, + size_t total_padding_length) override; + void OnPushPromiseEnd() override; + void OnPing(const QuicHttpFrameHeader& header, + const QuicHttpPingFields& ping) override; + void OnPingAck(const QuicHttpFrameHeader& header, + const QuicHttpPingFields& ping) override; + void OnGoAwayStart(const QuicHttpFrameHeader& header, + const QuicHttpGoAwayFields& goaway) override; + void OnGoAwayOpaqueData(const char* data, size_t len) override; + void OnGoAwayEnd() override; + void OnWindowUpdate(const QuicHttpFrameHeader& header, + uint32_t window_size_increment) override; + void OnAltSvcStart(const QuicHttpFrameHeader& header, + size_t origin_length, + size_t value_length) override; + void OnAltSvcOriginData(const char* data, size_t len) override; + void OnAltSvcValueData(const char* data, size_t len) override; + void OnAltSvcEnd() override; + void OnUnknownStart(const QuicHttpFrameHeader& header) override; + void OnUnknownPayload(const char* data, size_t len) override; + void OnUnknownEnd() override; + void OnPaddingTooLong(const QuicHttpFrameHeader& header, + size_t missing_length) override; + void OnFrameSizeError(const QuicHttpFrameHeader& header) override; +}; + +} // namespace test +} // namespace net + +#endif // NET_QUIC_HTTP_TEST_TOOLS_QUIC_HTTP_FRAME_PARTS_COLLECTOR_LISTENER_H_
diff --git a/net/quic/http/tools/quic_http_frame_builder.cc b/net/quic/http/tools/quic_http_frame_builder.cc new file mode 100644 index 0000000..1c01a56 --- /dev/null +++ b/net/quic/http/tools/quic_http_frame_builder.cc
@@ -0,0 +1,181 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/tools/quic_http_frame_builder.h" + +#ifdef WIN32 +#include <winsock2.h> // for htonl() functions +#else +#include <arpa/inet.h> // IWYU pragma: keep // because of Chrome +#include <netinet/in.h> // for htonl, htons +#endif + +#include "net/quic/platform/api/quic_string_utils.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace net { +namespace test { + +QuicHttpFrameBuilder::QuicHttpFrameBuilder(QuicHttpFrameType type, + uint8_t flags, + uint32_t stream_id) { + AppendUInt24(0); // Frame payload length, unknown so far. + Append(type); + AppendUInt8(flags); + AppendUInt31(stream_id); +} + +QuicHttpFrameBuilder::QuicHttpFrameBuilder(const QuicHttpFrameHeader& v) { + Append(v); +} + +void QuicHttpFrameBuilder::Append(QuicStringPiece s) { + QuicStrAppend(&buffer_, s); +} + +void QuicHttpFrameBuilder::AppendBytes(const void* data, uint32_t num_bytes) { + Append(QuicStringPiece(static_cast<const char*>(data), num_bytes)); +} + +void QuicHttpFrameBuilder::AppendZeroes(size_t num_zero_bytes) { + char zero = 0; + buffer_.append(num_zero_bytes, zero); +} + +void QuicHttpFrameBuilder::AppendUInt8(uint8_t value) { + AppendBytes(&value, 1); +} + +void QuicHttpFrameBuilder::AppendUInt16(uint16_t value) { + value = htons(value); + AppendBytes(&value, 2); +} + +void QuicHttpFrameBuilder::AppendUInt24(uint32_t value) { + // Doesn't make sense to try to append a larger value, as that doesn't + // simulate something an encoder could do (i.e. the other 8 bits simply aren't + // there to be occupied). + EXPECT_EQ(value, value & 0xffffff); + value = htonl(value); + AppendBytes(reinterpret_cast<char*>(&value) + 1, 3); +} + +void QuicHttpFrameBuilder::AppendUInt31(uint32_t value) { + // If you want to test the high-bit being set, call AppendUInt32 instead. + uint32_t tmp = value & QuicHttpStreamIdMask(); + EXPECT_EQ(value, value & QuicHttpStreamIdMask()) + << "High-bit of uint32_t should be clear."; + value = htonl(tmp); + AppendBytes(&value, 4); +} + +void QuicHttpFrameBuilder::AppendUInt32(uint32_t value) { + value = htonl(value); + AppendBytes(&value, sizeof(value)); +} + +void QuicHttpFrameBuilder::Append(QuicHttpErrorCode error_code) { + AppendUInt32(static_cast<uint32_t>(error_code)); +} + +void QuicHttpFrameBuilder::Append(QuicHttpFrameType type) { + AppendUInt8(static_cast<uint8_t>(type)); +} + +void QuicHttpFrameBuilder::Append(QuicHttpSettingsParameter parameter) { + AppendUInt16(static_cast<uint16_t>(parameter)); +} + +void QuicHttpFrameBuilder::Append(const QuicHttpFrameHeader& v) { + AppendUInt24(v.payload_length); + Append(v.type); + AppendUInt8(v.flags); + AppendUInt31(v.stream_id); +} + +void QuicHttpFrameBuilder::Append(const QuicHttpPriorityFields& v) { + // The EXCLUSIVE flag is the high-bit of the 32-bit stream dependency field. + uint32_t tmp = v.stream_dependency & QuicHttpStreamIdMask(); + EXPECT_EQ(tmp, v.stream_dependency); + if (v.is_exclusive) { + tmp |= 0x80000000; + } + AppendUInt32(tmp); + + // The QUIC_HTTP_PRIORITY frame's weight field is logically in the range [1, + // 256], but is encoded as a byte in the range [0, 255]. + ASSERT_LE(1u, v.weight); + ASSERT_LE(v.weight, 256u); + AppendUInt8(v.weight - 1); +} + +void QuicHttpFrameBuilder::Append(const QuicHttpRstStreamFields& v) { + Append(v.error_code); +} + +void QuicHttpFrameBuilder::Append(const QuicHttpSettingFields& v) { + Append(v.parameter); + AppendUInt32(v.value); +} + +void QuicHttpFrameBuilder::Append(const QuicHttpPushPromiseFields& v) { + AppendUInt31(v.promised_stream_id); +} + +void QuicHttpFrameBuilder::Append(const QuicHttpPingFields& v) { + AppendBytes(v.opaque_bytes, sizeof QuicHttpPingFields::opaque_bytes); +} + +void QuicHttpFrameBuilder::Append(const QuicHttpGoAwayFields& v) { + AppendUInt31(v.last_stream_id); + Append(v.error_code); +} + +void QuicHttpFrameBuilder::Append(const QuicHttpWindowUpdateFields& v) { + EXPECT_NE(0u, v.window_size_increment) << "Increment must be non-zero."; + AppendUInt31(v.window_size_increment); +} + +void QuicHttpFrameBuilder::Append(const QuicHttpAltSvcFields& v) { + AppendUInt16(v.origin_length); +} + +// Methods for changing existing buffer contents. + +void QuicHttpFrameBuilder::WriteAt(QuicStringPiece s, size_t offset) { + ASSERT_LE(offset, buffer_.size()); + size_t len = offset + s.size(); + if (len > buffer_.size()) { + buffer_.resize(len); + } + for (size_t ndx = 0; ndx < s.size(); ++ndx) { + buffer_[offset + ndx] = s[ndx]; + } +} + +void QuicHttpFrameBuilder::WriteBytesAt(const void* data, + uint32_t num_bytes, + size_t offset) { + WriteAt(QuicStringPiece(static_cast<const char*>(data), num_bytes), offset); +} + +void QuicHttpFrameBuilder::WriteUInt24At(uint32_t value, size_t offset) { + ASSERT_LT(value, 1u << 24); + value = htonl(value); + WriteBytesAt(reinterpret_cast<char*>(&value) + 1, sizeof(value) - 1, offset); +} + +void QuicHttpFrameBuilder::SetPayloadLength(uint32_t payload_length) { + WriteUInt24At(payload_length, 0); +} + +size_t QuicHttpFrameBuilder::SetPayloadLength() { + EXPECT_GE(size(), QuicHttpFrameHeader::EncodedSize()); + uint32_t payload_length = size() - QuicHttpFrameHeader::EncodedSize(); + SetPayloadLength(payload_length); + return payload_length; +} + +} // namespace test +} // namespace net
diff --git a/net/quic/http/tools/quic_http_frame_builder.h b/net/quic/http/tools/quic_http_frame_builder.h new file mode 100644 index 0000000..7dcf3db --- /dev/null +++ b/net/quic/http/tools/quic_http_frame_builder.h
@@ -0,0 +1,103 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_HTTP_TOOLS_QUIC_HTTP_FRAME_BUILDER_H_ +#define NET_QUIC_HTTP_TOOLS_QUIC_HTTP_FRAME_BUILDER_H_ + +// QuicHttpFrameBuilder builds wire-format HTTP/2 frames (or fragments thereof) +// from components. +// +// For now, this is only intended for use in tests, and thus has EXPECT* in the +// code. If desired to use it in an encoder, it will need optimization work, +// especially w.r.t memory mgmt, and the EXPECT* will need to be removed or +// replaced with DCHECKs. + +#include <stddef.h> // for size_t + +#include <cstdint> + +#include "net/quic/http/quic_http_constants.h" +#include "net/quic/http/quic_http_structures.h" +#include "net/quic/platform/api/quic_string.h" +#include "net/quic/platform/api/quic_string_piece.h" + +namespace net { +namespace test { + +class QuicHttpFrameBuilder { + public: + QuicHttpFrameBuilder(QuicHttpFrameType type, + uint8_t flags, + uint32_t stream_id); + explicit QuicHttpFrameBuilder(const QuicHttpFrameHeader& v); + QuicHttpFrameBuilder() {} + ~QuicHttpFrameBuilder() {} + + size_t size() const { return buffer_.size(); } + const QuicString& buffer() const { return buffer_; } + + //---------------------------------------------------------------------------- + // Methods for appending to the end of the buffer. + + // Append a sequence of bytes from various sources. + void Append(QuicStringPiece s); + void AppendBytes(const void* data, uint32_t num_bytes); + + // Append an array of type T[N] to the std::string. Intended for tests with + // arrays initialized from literals, such as: + // const char kData[] = {0x12, 0x23, ...}; + // builder.AppendBytes(kData); + template <typename T, size_t N> + void AppendBytes(T (&buf)[N]) { + AppendBytes(buf, N * sizeof(buf[0])); + } + + // Support for appending padding. Does not read or write the Pad Length field. + void AppendZeroes(size_t num_zero_bytes); + + // Append various sizes of unsigned integers. + void AppendUInt8(uint8_t value); + void AppendUInt16(uint16_t value); + void AppendUInt24(uint32_t value); + void AppendUInt31(uint32_t value); + void AppendUInt32(uint32_t value); + + // Append various enums. + void Append(QuicHttpErrorCode error_code); + void Append(QuicHttpFrameType type); + void Append(QuicHttpSettingsParameter parameter); + + // Append various structures. + void Append(const QuicHttpFrameHeader& v); + void Append(const QuicHttpPriorityFields& v); + void Append(const QuicHttpRstStreamFields& v); + void Append(const QuicHttpSettingFields& v); + void Append(const QuicHttpPushPromiseFields& v); + void Append(const QuicHttpPingFields& v); + void Append(const QuicHttpGoAwayFields& v); + void Append(const QuicHttpWindowUpdateFields& v); + void Append(const QuicHttpAltSvcFields& v); + + // Methods for changing existing buffer contents (mostly focused on updating + // the payload length). + + void WriteAt(QuicStringPiece s, size_t offset); + void WriteBytesAt(const void* data, uint32_t num_bytes, size_t offset); + void WriteUInt24At(uint32_t value, size_t offset); + + // Set the payload length to the specified size. + void SetPayloadLength(uint32_t payload_length); + + // Sets the payload length to the size of the buffer minus the size of + // the frame header. + size_t SetPayloadLength(); + + private: + QuicString buffer_; +}; + +} // namespace test +} // namespace net + +#endif // NET_QUIC_HTTP_TOOLS_QUIC_HTTP_FRAME_BUILDER_H_
diff --git a/net/quic/http/tools/quic_http_random_decoder_test.cc b/net/quic/http/tools/quic_http_random_decoder_test.cc new file mode 100644 index 0000000..76cf9c2 --- /dev/null +++ b/net/quic/http/tools/quic_http_random_decoder_test.cc
@@ -0,0 +1,172 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/tools/quic_http_random_decoder_test.h" + +#include <stddef.h> +#include <algorithm> +#include <memory> + +#include "base/logging.h" +#include "base/strings/string_number_conversions.h" +#include "net/http2/tools/failure.h" +#include "net/quic/http/decoder/quic_http_decode_buffer.h" +#include "net/quic/http/decoder/quic_http_decode_status.h" +#include "net/quic/http/quic_http_constants.h" +#include "testing/gtest/include/gtest/gtest.h" + +// It's rather time consuming to decode large buffers one at a time, +// especially with the log level cranked up. So, by default we don't do +// that unless explicitly requested. + +using ::testing::AssertionFailure; +using ::testing::AssertionResult; +using ::testing::AssertionSuccess; + +namespace net { +namespace test { + +QuicHttpRandomDecoderTest::QuicHttpRandomDecoderTest() {} + +bool QuicHttpRandomDecoderTest::StopDecodeOnDone() { + return stop_decode_on_done_; +} + +QuicHttpDecodeStatus QuicHttpRandomDecoderTest::DecodeSegments( + QuicHttpDecodeBuffer* original, + const SelectSize& select_size) { + QuicHttpDecodeStatus status = QuicHttpDecodeStatus::kDecodeInProgress; + bool first = true; + VLOG(2) << "DecodeSegments: input size=" << original->Remaining(); + while (first || original->HasData()) { + size_t remaining = original->Remaining(); + size_t size = + std::min(remaining, select_size(first, original->Offset(), remaining)); + QuicHttpDecodeBuffer db(original->cursor(), size); + VLOG(2) << "Decoding " << size << " bytes of " << remaining << " remaining"; + if (first) { + first = false; + status = StartDecoding(&db); + } else { + status = ResumeDecoding(&db); + } + // A decoder MUST consume some input (if any is available), else we could + // get stuck in infinite loops. + if (db.Offset() == 0 && db.HasData() && + status != QuicHttpDecodeStatus::kDecodeError) { + ADD_FAILURE() << "Decoder didn't make any progress; db.FullSize=" + << db.FullSize() + << " original.Offset=" << original->Offset(); + return QuicHttpDecodeStatus::kDecodeError; + } + original->AdvanceCursor(db.Offset()); + switch (status) { + case QuicHttpDecodeStatus::kDecodeDone: + if (original->Empty() || StopDecodeOnDone()) { + return QuicHttpDecodeStatus::kDecodeDone; + } + continue; + case QuicHttpDecodeStatus::kDecodeInProgress: + continue; + case QuicHttpDecodeStatus::kDecodeError: + return QuicHttpDecodeStatus::kDecodeError; + } + } + return status; +} + +// Decode |original| multiple times, with different segmentations, validating +// after each decode, returning on the first failure. +AssertionResult QuicHttpRandomDecoderTest::DecodeAndValidateSeveralWays( + QuicHttpDecodeBuffer* original, + bool return_non_zero_on_first, + const Validator& validator) { + const uint32_t original_remaining = original->Remaining(); + VLOG(1) << "DecodeAndValidateSeveralWays - Start, remaining = " + << original_remaining; + uint32_t first_consumed; + { + // Fast decode (no stopping unless decoder does so). + QuicHttpDecodeBuffer input(original->cursor(), original_remaining); + VLOG(2) << "DecodeSegmentsAndValidate with SelectRemaining"; + VERIFY_SUCCESS( + DecodeSegmentsAndValidate(&input, SelectRemaining(), validator)) + << "\nFailed with SelectRemaining; input.Offset=" << input.Offset() + << "; input.Remaining=" << input.Remaining(); + first_consumed = input.Offset(); + } + if (original_remaining <= 30) { + // Decode again, one byte at a time. + QuicHttpDecodeBuffer input(original->cursor(), original_remaining); + VLOG(2) << "DecodeSegmentsAndValidate with SelectOne"; + VERIFY_SUCCESS(DecodeSegmentsAndValidate(&input, SelectOne(), validator)) + << "\nFailed with SelectOne; input.Offset=" << input.Offset() + << "; input.Remaining=" << input.Remaining(); + VERIFY_EQ(first_consumed, input.Offset()) << "\nFailed with SelectOne"; + } + if (original_remaining <= 20) { + // Decode again, one or zero bytes at a time. + QuicHttpDecodeBuffer input(original->cursor(), original_remaining); + VLOG(2) << "DecodeSegmentsAndValidate with SelectZeroAndOne"; + VERIFY_SUCCESS(DecodeSegmentsAndValidate( + &input, SelectZeroAndOne(return_non_zero_on_first), validator)) + << "\nFailed with SelectZeroAndOne"; + VERIFY_EQ(first_consumed, input.Offset()) + << "\nFailed with SelectZeroAndOne; input.Offset=" << input.Offset() + << "; input.Remaining=" << input.Remaining(); + } + { + // Decode again, with randomly selected segment sizes. + QuicHttpDecodeBuffer input(original->cursor(), original_remaining); + VLOG(2) << "DecodeSegmentsAndValidate with SelectRandom"; + VERIFY_SUCCESS(DecodeSegmentsAndValidate( + &input, SelectRandom(return_non_zero_on_first), validator)) + << "\nFailed with SelectRandom; input.Offset=" << input.Offset() + << "; input.Remaining=" << input.Remaining(); + VERIFY_EQ(first_consumed, input.Offset()) << "\nFailed with SelectRandom"; + } + VERIFY_EQ(original_remaining, original->Remaining()); + original->AdvanceCursor(first_consumed); + VLOG(1) << "DecodeAndValidateSeveralWays - SUCCESS"; + return ::testing::AssertionSuccess(); +} + +// static +QuicHttpRandomDecoderTest::SelectSize +QuicHttpRandomDecoderTest::SelectZeroAndOne(bool return_non_zero_on_first) { + std::shared_ptr<bool> zero_next(new bool); + *zero_next = !return_non_zero_on_first; + return [zero_next](bool first, size_t offset, size_t remaining) -> size_t { + if (*zero_next) { + *zero_next = false; + return 0; + } else { + *zero_next = true; + return 1; + } + }; +} + +QuicHttpRandomDecoderTest::SelectSize QuicHttpRandomDecoderTest::SelectRandom( + bool return_non_zero_on_first) { + return [this, return_non_zero_on_first](bool first, size_t offset, + size_t remaining) -> size_t { + uint32_t r = random_.Rand32(); + if (first && return_non_zero_on_first) { + CHECK_LT(0U, remaining); + if (remaining == 1) { + return 1; + } + return 1 + (r % remaining); // size in range [1, remaining). + } + return r % (remaining + 1); // size in range [0, remaining]. + }; +} + +uint32_t QuicHttpRandomDecoderTest::RandStreamId() { + return random_.Rand32() & QuicHttpStreamIdMask(); +} + +} // namespace test +} // namespace net
diff --git a/net/quic/http/tools/quic_http_random_decoder_test.h b/net/quic/http/tools/quic_http_random_decoder_test.h new file mode 100644 index 0000000..a039211 --- /dev/null +++ b/net/quic/http/tools/quic_http_random_decoder_test.h
@@ -0,0 +1,279 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_HTTP_TOOLS_QUIC_HTTP_RANDOM_DECODER_TEST_H_ +#define NET_QUIC_HTTP_TOOLS_QUIC_HTTP_RANDOM_DECODER_TEST_H_ + +// QuicHttpRandomDecoderTest is a base class for tests of decoding various kinds +// of HTTP/2 and HPQUIC_HTTP_ACK encodings. +// Exports QuicTestRandomBase's include file so that all the sub-classes don't +// have to do so (i.e. promising that method Random() will continue to return +// QuicTestRandomBase well into the future). + +// TODO(jamessynge): Move more methods into .cc file. + +#include <stddef.h> + +#include <cstdint> +#include <functional> +#include <type_traits> + +#include "base/logging.h" +#include "net/http2/tools/failure.h" +#include "net/quic/http/decoder/quic_http_decode_buffer.h" +#include "net/quic/http/decoder/quic_http_decode_status.h" +#include "net/quic/platform/api/quic_string.h" +#include "net/quic/platform/api/quic_string_piece.h" +#include "net/quic/platform/api/quic_test.h" +#include "net/quic/platform/api/quic_test_random.h" // IWYU pragma: export +#include "testing/gtest/include/gtest/gtest.h" + +namespace net { +namespace test { + +// Some helpers. + +template <typename T, size_t N> +QuicStringPiece ToStringPiece(T (&data)[N]) { + return QuicStringPiece(reinterpret_cast<const char*>(data), N * sizeof(T)); +} + +// Overwrite the enum with some random value, probably not a valid value for +// the enum type, but which fits into its storage. +template <typename T, + typename E = typename std::enable_if<std::is_enum<T>::value>::type> +void CorruptEnum(T* out, QuicTestRandomBase* rng) { + // Per cppreference.com, if the destination type of a static_cast is + // smaller than the source type (i.e. type of r and uint32 below), the + // resulting value is the smallest unsigned value equal to the source value + // modulo 2^n, where n is the number of bits used to represent the + // destination type unsigned U. + typedef typename std::underlying_type<T>::type underlying_type_T; + typedef typename std::make_unsigned<underlying_type_T>::type + unsigned_underlying_type_T; + auto r = static_cast<unsigned_underlying_type_T>(rng->Rand32()); + *out = static_cast<T>(r); +} + +// Base class for tests of the ability to decode a sequence of bytes with +// various boundaries between the QuicHttpDecodeBuffers provided to the decoder. +class QuicHttpRandomDecoderTest : public QuicTest { + public: + // SelectSize returns the size of the next QuicHttpDecodeBuffer to be passed + // to the decoder. Note that QuicHttpRandomDecoderTest allows that size to be + // zero, though some decoders can't deal with that on the first byte, hence + // the |first| parameter. + typedef std::function<size_t(bool first, size_t offset, size_t remaining)> + SelectSize; + + // Validator returns an AssertionResult so test can do: + // EXPECT_THAT(DecodeAndValidate(..., validator)); + typedef ::testing::AssertionResult AssertionResult; + typedef std::function<AssertionResult(const QuicHttpDecodeBuffer& input, + QuicHttpDecodeStatus status)> + Validator; + typedef std::function<AssertionResult()> NoArgValidator; + + QuicHttpRandomDecoderTest(); + + protected: + // Enables sub-class using BoostLoggingIfDefault to restore the verbosity + // without waiting for gUnit to restore flags at the end of a test case. + class RestoreVerbosity { + public: + explicit RestoreVerbosity(int old_verbosity); + ~RestoreVerbosity(); + + private: + const int old_verbosity_; + }; + + // In support of better coverage of VLOG and DVLOG lines, increase the log + // level if not overridden already. Because there are so many D?VLOG(2) + // statements triggered by the randomized decoding, it is recommended to only + // call this method when decoding a small payload. + // Returns the previous value of FLAGS_v. + int BoostLoggingIfDefault(int target_level); + + // TODO(jamessynge): Modify StartDecoding, etc. to (somehow) return + // AssertionResult so that the VERIFY_* methods exported from + // gunit_helpers.h can be widely used. + + // Start decoding; call allows sub-class to Reset the decoder, or deal with + // the first byte if that is done in a unique fashion. Might be called with + // a zero byte buffer. + virtual QuicHttpDecodeStatus StartDecoding(QuicHttpDecodeBuffer* db) = 0; + + // Resume decoding of the input after a prior call to StartDecoding, and + // possibly many calls to ResumeDecoding. + virtual QuicHttpDecodeStatus ResumeDecoding(QuicHttpDecodeBuffer* db) = 0; + + // Return true if a decode status of kDecodeDone indicates that + // decoding should stop. + virtual bool StopDecodeOnDone(); + + // Decode buffer |original| until we run out of input, or kDecodeDone is + // returned by the decoder AND StopDecodeOnDone() returns true. Segments + // (i.e. cuts up) the original QuicHttpDecodeBuffer into (potentially) smaller + // buffers by calling |select_size| to decide how large each buffer should be. + // We do this to test the ability to deal with arbitrary boundaries, as might + // happen in transport. + // Returns the final QuicHttpDecodeStatus. + QuicHttpDecodeStatus DecodeSegments(QuicHttpDecodeBuffer* original, + const SelectSize& select_size); + + // Decode buffer |original| until we run out of input, or kDecodeDone is + // returned by the decoder AND StopDecodeOnDone() returns true. Segments + // (i.e. cuts up) the original QuicHttpDecodeBuffer into (potentially) smaller + // buffers by calling |select_size| to decide how large each buffer should be. + // We do this to test the ability to deal with arbitrary boundaries, as might + // happen in transport. + // Invokes |validator| with the final decode status and the original decode + // buffer, with the cursor advanced as far as has been consumed by the decoder + // and returns validator's result. + ::testing::AssertionResult DecodeSegmentsAndValidate( + QuicHttpDecodeBuffer* original, + const SelectSize& select_size, + const Validator& validator) { + QuicHttpDecodeStatus status = DecodeSegments(original, select_size); + VERIFY_AND_RETURN_SUCCESS(validator(*original, status)); + } + + // Returns a SelectSize function for fast decoding, i.e. passing all that + // is available to the decoder. + static SelectSize SelectRemaining() { + return [](bool first, size_t offset, size_t remaining) -> size_t { + return remaining; + }; + } + + // Returns a SelectSize function for decoding a single byte at a time. + static SelectSize SelectOne() { + return + [](bool first, size_t offset, size_t remaining) -> size_t { return 1; }; + } + + // Returns a SelectSize function for decoding a single byte at a time, where + // zero byte buffers are also allowed. Alternates between zero and one, + // starting with zero if allowed, else with one. + static SelectSize SelectZeroAndOne(bool return_non_zero_on_first); + + // Returns a SelectSize function for decoding random sized segments. + SelectSize SelectRandom(bool return_non_zero_on_first); + + // Decode |original| multiple times, with different segmentations of the + // decode buffer, validating after each decode, and confirming that they + // each decode the same amount. Returns on the first failure, else returns + // success. + AssertionResult DecodeAndValidateSeveralWays(QuicHttpDecodeBuffer* original, + bool return_non_zero_on_first, + const Validator& validator); + + static Validator ToValidator(std::nullptr_t) { + return [](const QuicHttpDecodeBuffer& input, QuicHttpDecodeStatus status) { + return ::testing::AssertionSuccess(); + }; + } + + static Validator ToValidator(const Validator& validator) { + if (validator == nullptr) { + return ToValidator(nullptr); + } + return validator; + } + + static Validator ToValidator(const NoArgValidator& validator) { + if (validator == nullptr) { + return ToValidator(nullptr); + } + return [validator](const QuicHttpDecodeBuffer& input, + QuicHttpDecodeStatus status) { return validator(); }; + } + + // Wraps a validator (which may be empty) with another validator + // that first checks that the QuicHttpDecodeStatus is kDecodeDone and + // that the QuicHttpDecodeBuffer is empty. + // TODO(jamessynge): Replace this overload with the next, as using this method + // usually means that the wrapped function doesn't need to be passed the + // QuicHttpDecodeBuffer nor the QuicHttpDecodeStatus. + static Validator ValidateDoneAndEmpty(const Validator& wrapped) { + return [wrapped](const QuicHttpDecodeBuffer& input, + QuicHttpDecodeStatus status) -> AssertionResult { + VERIFY_EQ(status, QuicHttpDecodeStatus::kDecodeDone); + VERIFY_EQ(0u, input.Remaining()) << "\nOffset=" << input.Offset(); + if (wrapped) { + return wrapped(input, status); + } + return ::testing::AssertionSuccess(); + }; + } + static Validator ValidateDoneAndEmpty(const NoArgValidator& wrapped) { + return [wrapped](const QuicHttpDecodeBuffer& input, + QuicHttpDecodeStatus status) -> AssertionResult { + VERIFY_EQ(status, QuicHttpDecodeStatus::kDecodeDone); + VERIFY_EQ(0u, input.Remaining()) << "\nOffset=" << input.Offset(); + if (wrapped) { + return wrapped(); + } + return ::testing::AssertionSuccess(); + }; + } + static Validator ValidateDoneAndEmpty() { + NoArgValidator validator; + return ValidateDoneAndEmpty(validator); + } + + // Wraps a validator (which may be empty) with another validator + // that first checks that the QuicHttpDecodeStatus is kDecodeDone and + // that the QuicHttpDecodeBuffer has the expected offset. + // TODO(jamessynge): Replace this overload with the next, as using this method + // usually means that the wrapped function doesn't need to be passed the + // QuicHttpDecodeBuffer nor the QuicHttpDecodeStatus. + static Validator ValidateDoneAndOffset(uint32_t offset, + const Validator& wrapped) { + return [wrapped, offset](const QuicHttpDecodeBuffer& input, + QuicHttpDecodeStatus status) -> AssertionResult { + VERIFY_EQ(status, QuicHttpDecodeStatus::kDecodeDone); + VERIFY_EQ(offset, input.Offset()) << "\nRemaining=" << input.Remaining(); + if (wrapped) { + return wrapped(input, status); + } + return ::testing::AssertionSuccess(); + }; + } + static Validator ValidateDoneAndOffset(uint32_t offset, + const NoArgValidator& wrapped) { + return [wrapped, offset](const QuicHttpDecodeBuffer& input, + QuicHttpDecodeStatus status) -> AssertionResult { + VERIFY_EQ(status, QuicHttpDecodeStatus::kDecodeDone); + VERIFY_EQ(offset, input.Offset()) << "\nRemaining=" << input.Remaining(); + if (wrapped) { + return wrapped(); + } + return ::testing::AssertionSuccess(); + }; + } + static Validator ValidateDoneAndOffset(uint32_t offset) { + NoArgValidator validator; + return ValidateDoneAndOffset(offset, validator); + } + + // Expose random_ as QuicTestRandomBase so callers don't have to care about + // which sub-class of QuicTestRandomBase is used, nor can they rely on the + // specific sub-class that QuicHttpRandomDecoderTest uses. + QuicTestRandomBase& Random() { return random_; } + QuicTestRandomBase* RandomPtr() { return &random_; } + + uint32_t RandStreamId(); + + bool stop_decode_on_done_ = true; + + private: + QuicTestRandom random_; +}; + +} // namespace test +} // namespace net + +#endif // NET_QUIC_HTTP_TOOLS_QUIC_HTTP_RANDOM_DECODER_TEST_H_
diff --git a/net/quic/http/tools/quic_http_random_util.cc b/net/quic/http/tools/quic_http_random_util.cc new file mode 100644 index 0000000..7e7b259 --- /dev/null +++ b/net/quic/http/tools/quic_http_random_util.cc
@@ -0,0 +1,98 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/http/tools/quic_http_random_util.h" + +#include <cmath> + +#include "base/rand_util.h" +#include "net/quic/platform/api/quic_string_piece.h" +#include "net/quic/platform/api/quic_test_random.h" + +namespace net { +namespace test { +namespace { + +const char kWebsafe64[] = + "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_"; + +// Generate two independent standard normal random variables using the polar +// method. +void GenerateRandomSizeSkewedLowHelper(size_t max, size_t* x, size_t* y) { + double a, b, s; + do { + // Draw uniformly on [-1, 1). + a = 2 * base::RandDouble() - 1.0; + b = 2 * base::RandDouble() - 1.0; + s = a * a + b * b; + } while (s >= 1.0); + double t = std::sqrt(-2.0 * std::log(s) / s); + *x = static_cast<size_t>(a * t * max); + *y = static_cast<size_t>(b * t * max); +} + +} // anonymous namespace + +QuicString RandomString(QuicTestRandomBase* rng, + int len, + QuicStringPiece alphabet) { + QuicString random_string; + random_string.reserve(len); + for (int i = 0; i < len; ++i) + random_string.push_back(alphabet[rng->Uniform(alphabet.size())]); + return random_string; +} + +size_t GenerateUniformInRange(size_t lo, size_t hi, QuicTestRandomBase* rng) { + if (lo + 1 >= hi) { + return lo; + } + return lo + rng->Rand64() % (hi - lo); +} + +// Here "word" means something that starts with a lower-case letter, and has +// zero or more additional characters that are numbers or lower-case letters. +QuicString GenerateQuicHttpHeaderName(size_t len, QuicTestRandomBase* rng) { + QuicStringPiece alpha_lc = "abcdefghijklmnopqrstuvwxyz"; + // If the name is short, just make it one word. + if (len < 8) { + return RandomString(rng, len, alpha_lc); + } + // If the name is longer, ensure it starts with a word, and after that may + // have any character in alphanumdash_lc. 4 is arbitrary, could be as low + // as 1. + QuicStringPiece alphanumdash_lc = "abcdefghijklmnopqrstuvwxyz0123456789-"; + return RandomString(rng, 4, alpha_lc) + + RandomString(rng, len - 4, alphanumdash_lc); +} + +QuicString GenerateWebSafeString(size_t len, QuicTestRandomBase* rng) { + return RandomString(rng, len, kWebsafe64); +} + +QuicString GenerateWebSafeString(size_t lo, + size_t hi, + QuicTestRandomBase* rng) { + return GenerateWebSafeString(GenerateUniformInRange(lo, hi, rng), rng); +} + +size_t GenerateRandomSizeSkewedLow(size_t max, QuicTestRandomBase* rng) { + if (max == 0) { + return 0; + } + // Generate a random number with a Gaussian distribution, centered on zero; + // take the absolute, and then keep in range 0 to max. + for (int i = 0; i < 5; i++) { + size_t x, y; + GenerateRandomSizeSkewedLowHelper(max, &x, &y); + if (x <= max) + return x; + if (y <= max) + return y; + } + return rng->Uniform(max + 1); +} + +} // namespace test +} // namespace net
diff --git a/net/quic/http/tools/quic_http_random_util.h b/net/quic/http/tools/quic_http_random_util.h new file mode 100644 index 0000000..da0245a --- /dev/null +++ b/net/quic/http/tools/quic_http_random_util.h
@@ -0,0 +1,38 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_HTTP_TOOLS_QUIC_HTTP_RANDOM_UTIL_H_ +#define NET_QUIC_HTTP_TOOLS_QUIC_HTTP_RANDOM_UTIL_H_ + +#include <stddef.h> + +#include "net/quic/platform/api/quic_string.h" +#include "net/quic/platform/api/quic_test_random.h" + +namespace net { +namespace test { + +// Returns a random integer in the range [lo, hi). +size_t GenerateUniformInRange(size_t lo, size_t hi, QuicTestRandomBase* rng); + +// Generate a std::string with the allowed character set for HTTP/2 / +// HPQUIC_HTTP_ACK header names. +QuicString GenerateQuicHttpHeaderName(size_t len, QuicTestRandomBase* rng); + +// Generate a std::string with the web-safe std::string character set of +// specified len. +QuicString GenerateWebSafeString(size_t len, QuicTestRandomBase* rng); + +// Generate a std::string with the web-safe std::string character set of length +// [lo, hi). +QuicString GenerateWebSafeString(size_t lo, size_t hi, QuicTestRandomBase* rng); + +// Returns a random integer in the range [0, max], with a bias towards producing +// lower numbers. +size_t GenerateRandomSizeSkewedLow(size_t max, QuicTestRandomBase* rng); + +} // namespace test +} // namespace net + +#endif // NET_QUIC_HTTP_TOOLS_QUIC_HTTP_RANDOM_UTIL_H_
diff --git a/net/quic/platform/api/quic_optional.h b/net/quic/platform/api/quic_optional.h new file mode 100644 index 0000000..dce897a --- /dev/null +++ b/net/quic/platform/api/quic_optional.h
@@ -0,0 +1,17 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_PLATFORM_API_QUIC_OPTIONAL_H_ +#define NET_QUIC_PLATFORM_API_QUIC_OPTIONAL_H_ + +#include "net/quic/platform/impl/quic_optional_impl.h" + +namespace net { + +template <typename T> +using QuicOptional = QuicOptionalImpl<T>; + +} // namespace net + +#endif // NET_QUIC_PLATFORM_API_QUIC_OPTIONAL_H_
diff --git a/net/quic/platform/api/quic_reconstruct_object.h b/net/quic/platform/api/quic_reconstruct_object.h new file mode 100644 index 0000000..3922195f --- /dev/null +++ b/net/quic/platform/api/quic_reconstruct_object.h
@@ -0,0 +1,32 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_PLATFORM_API_QUIC_RECONSTRUCT_OBJECT_H_ +#define NET_QUIC_PLATFORM_API_QUIC_RECONSTRUCT_OBJECT_H_ + +#include <utility> + +#include "net/quic/platform/impl/quic_reconstruct_object_impl.h" + +namespace net { +namespace test { + +// Reconstruct an object so that it is initialized as when it was first +// constructed. Runs the destructor to handle objects that might own resources, +// and runs the constructor with the provided arguments, if any. +template <class T, class... Args> +void QuicReconstructObject(T* ptr, QuicTestRandomBase* rng, Args&&... args) { + QuicReconstructObjectImpl(ptr, rng, std::forward<Args>(args)...); +} + +// This version applies default-initialization to the object. +template <class T> +void QuicDefaultReconstructObject(T* ptr, QuicTestRandomBase* rng) { + QuicDefaultReconstructObjectImpl(ptr, rng); +} + +} // namespace test +} // namespace net + +#endif // NET_QUIC_PLATFORM_API_QUIC_RECONSTRUCT_OBJECT_H_
diff --git a/net/quic/platform/api/quic_string.h b/net/quic/platform/api/quic_string.h new file mode 100644 index 0000000..509b9e1 --- /dev/null +++ b/net/quic/platform/api/quic_string.h
@@ -0,0 +1,16 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_PLATFORM_API_QUIC_STRING_H_ +#define NET_QUIC_PLATFORM_API_QUIC_STRING_H_ + +#include "net/quic/platform/impl/quic_string_impl.h" + +namespace net { + +using QuicString = QuicStringImpl; + +} // namespace net + +#endif // NET_QUIC_PLATFORM_API_QUIC_STRING_H_
diff --git a/net/quic/platform/api/quic_string_utils.h b/net/quic/platform/api/quic_string_utils.h new file mode 100644 index 0000000..5a7c6a90 --- /dev/null +++ b/net/quic/platform/api/quic_string_utils.h
@@ -0,0 +1,23 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_PLATFORM_API_QUIC_STRING_UTILS_H_ +#define NET_QUIC_PLATFORM_API_QUIC_STRING_UTILS_H_ + +#include <utility> + +#include "net/quic/platform/api/quic_string.h" +#include "net/quic/platform/api/quic_string_piece.h" +#include "net/quic/platform/impl/quic_string_utils_impl.h" + +namespace net { + +template <typename... Args> +inline void QuicStrAppend(QuicString* output, const Args&... args) { + QuicStrAppendImpl(output, std::forward<const Args&>(args)...); +} + +} // namespace net + +#endif // NET_QUIC_PLATFORM_API_QUIC_STRING_UTILS_H_
diff --git a/net/quic/platform/api/quic_string_utils_test.cc b/net/quic/platform/api/quic_string_utils_test.cc new file mode 100644 index 0000000..eb128f9 --- /dev/null +++ b/net/quic/platform/api/quic_string_utils_test.cc
@@ -0,0 +1,178 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/platform/api/quic_string_utils.h" + +#include <cstdint> + +#include "net/quic/platform/api/quic_str_cat.h" +#include "net/quic/platform/api/quic_string_piece.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace net { +namespace test { +namespace { + +TEST(QuicStringUtilsTest, QuicStrCat) { + // No arguments. + EXPECT_EQ("", QuicStrCat()); + + // Single string-like argument. + const char kFoo[] = "foo"; + const QuicString string_foo(kFoo); + const QuicStringPiece stringpiece_foo(string_foo); + EXPECT_EQ("foo", QuicStrCat(kFoo)); + EXPECT_EQ("foo", QuicStrCat(string_foo)); + EXPECT_EQ("foo", QuicStrCat(stringpiece_foo)); + + // Two string-like arguments. + const char kBar[] = "bar"; + const QuicStringPiece stringpiece_bar(kBar); + const QuicString string_bar(kBar); + EXPECT_EQ("foobar", QuicStrCat(kFoo, kBar)); + EXPECT_EQ("foobar", QuicStrCat(kFoo, string_bar)); + EXPECT_EQ("foobar", QuicStrCat(kFoo, stringpiece_bar)); + EXPECT_EQ("foobar", QuicStrCat(string_foo, kBar)); + EXPECT_EQ("foobar", QuicStrCat(string_foo, string_bar)); + EXPECT_EQ("foobar", QuicStrCat(string_foo, stringpiece_bar)); + EXPECT_EQ("foobar", QuicStrCat(stringpiece_foo, kBar)); + EXPECT_EQ("foobar", QuicStrCat(stringpiece_foo, string_bar)); + EXPECT_EQ("foobar", QuicStrCat(stringpiece_foo, stringpiece_bar)); + + // Many-many arguments. + EXPECT_EQ( + "foobarbazquxquuxquuzcorgegraultgarplywaldofredplughxyzzythud", + QuicStrCat("foo", "bar", "baz", "qux", "quux", "quuz", "corge", "grault", + "garply", "waldo", "fred", "plugh", "xyzzy", "thud")); + + // Numerical arguments. + const int16_t i = 1; + const uint64_t u = 8; + const double d = 3.1415; + + EXPECT_EQ("1 8", QuicStrCat(i, " ", u)); + EXPECT_EQ("3.14151181", QuicStrCat(d, i, i, u, i)); + EXPECT_EQ("i: 1, u: 8, d: 3.1415", + QuicStrCat("i: ", i, ", u: ", u, ", d: ", d)); + + // Boolean arguments. + const bool t = true; + const bool f = false; + + EXPECT_EQ("1", QuicStrCat(t)); + EXPECT_EQ("0", QuicStrCat(f)); + EXPECT_EQ("0110", QuicStrCat(f, t, t, f)); + + // Mixed string-like, numerical, and Boolean arguments. + EXPECT_EQ("foo1foo081bar3.14151", + QuicStrCat(kFoo, i, string_foo, f, u, t, stringpiece_bar, d, t)); + EXPECT_EQ("3.141511bar18bar13.14150", + QuicStrCat(d, t, t, string_bar, i, u, kBar, t, d, f)); +} + +TEST(QuicStringUtilsTest, QuicStrAppend) { + // No arguments on empty string. + QuicString output; + QuicStrAppend(&output); + EXPECT_TRUE(output.empty()); + + // Single string-like argument. + const char kFoo[] = "foo"; + const QuicString string_foo(kFoo); + const QuicStringPiece stringpiece_foo(string_foo); + QuicStrAppend(&output, kFoo); + EXPECT_EQ("foo", output); + QuicStrAppend(&output, string_foo); + EXPECT_EQ("foofoo", output); + QuicStrAppend(&output, stringpiece_foo); + EXPECT_EQ("foofoofoo", output); + + // No arguments on non-empty string. + QuicStrAppend(&output); + EXPECT_EQ("foofoofoo", output); + + output.clear(); + + // Two string-like arguments. + const char kBar[] = "bar"; + const QuicStringPiece stringpiece_bar(kBar); + const QuicString string_bar(kBar); + QuicStrAppend(&output, kFoo, kBar); + EXPECT_EQ("foobar", output); + QuicStrAppend(&output, kFoo, string_bar); + EXPECT_EQ("foobarfoobar", output); + QuicStrAppend(&output, kFoo, stringpiece_bar); + EXPECT_EQ("foobarfoobarfoobar", output); + QuicStrAppend(&output, string_foo, kBar); + EXPECT_EQ("foobarfoobarfoobarfoobar", output); + + output.clear(); + + QuicStrAppend(&output, string_foo, string_bar); + EXPECT_EQ("foobar", output); + QuicStrAppend(&output, string_foo, stringpiece_bar); + EXPECT_EQ("foobarfoobar", output); + QuicStrAppend(&output, stringpiece_foo, kBar); + EXPECT_EQ("foobarfoobarfoobar", output); + QuicStrAppend(&output, stringpiece_foo, string_bar); + EXPECT_EQ("foobarfoobarfoobarfoobar", output); + + output.clear(); + + QuicStrAppend(&output, stringpiece_foo, stringpiece_bar); + EXPECT_EQ("foobar", output); + + // Many-many arguments. + QuicStrAppend(&output, "foo", "bar", "baz", "qux", "quux", "quuz", "corge", + "grault", "garply", "waldo", "fred", "plugh", "xyzzy", "thud"); + EXPECT_EQ( + "foobarfoobarbazquxquuxquuzcorgegraultgarplywaldofredplughxyzzythud", + output); + + output.clear(); + + // Numerical arguments. + const int16_t i = 1; + const uint64_t u = 8; + const double d = 3.1415; + + QuicStrAppend(&output, i, " ", u); + EXPECT_EQ("1 8", output); + QuicStrAppend(&output, d, i, i, u, i); + EXPECT_EQ("1 83.14151181", output); + QuicStrAppend(&output, "i: ", i, ", u: ", u, ", d: ", d); + EXPECT_EQ("1 83.14151181i: 1, u: 8, d: 3.1415", output); + + output.clear(); + + // Boolean arguments. + const bool t = true; + const bool f = false; + + QuicStrAppend(&output, t); + EXPECT_EQ("1", output); + QuicStrAppend(&output, f); + EXPECT_EQ("10", output); + QuicStrAppend(&output, f, t, t, f); + EXPECT_EQ("100110", output); + + output.clear(); + + // Mixed string-like, numerical, and Boolean arguments. + QuicStrAppend(&output, kFoo, i, string_foo, f, u, t, stringpiece_bar, d, t); + EXPECT_EQ("foo1foo081bar3.14151", output); + QuicStrAppend(&output, d, t, t, string_bar, i, u, kBar, t, d, f); + EXPECT_EQ("foo1foo081bar3.141513.141511bar18bar13.14150", output); +} + +TEST(QuicStringUtilsTest, QuicStringPrintf) { + EXPECT_EQ("", QuicStringPrintf("%s", "")); + EXPECT_EQ("foobar", QuicStringPrintf("%sbar", "foo")); + EXPECT_EQ("foobar", QuicStringPrintf("%s%s", "foo", "bar")); + EXPECT_EQ("foo: 1, bar: 2.0", QuicStringPrintf("foo: %d, bar: %.1f", 1, 2.0)); +} + +} // namespace +} // namespace test +} // namespace net
diff --git a/net/quic/platform/api/quic_test_random.h b/net/quic/platform/api/quic_test_random.h new file mode 100644 index 0000000..e3912db7 --- /dev/null +++ b/net/quic/platform/api/quic_test_random.h
@@ -0,0 +1,25 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_PLATFORM_API_QUIC_TEST_RANDOM_H_ +#define NET_QUIC_PLATFORM_API_QUIC_TEST_RANDOM_H_ + +#include <stdint.h> +#include <limits> + +#include "net/quic/platform/api/quic_string.h" +#include "net/quic/platform/impl/quic_test_random_impl.h" + +namespace net { +namespace test { + +using QuicTestRandomBase = QuicTestRandomBaseImpl; + +// QuicTestRandomImpl must inherit from QuicTestRandomBaseImpl; +using QuicTestRandom = QuicTestRandomImpl; + +} // namespace test +} // namespace net + +#endif // NET_QUIC_PLATFORM_API_QUIC_TEST_RANDOM_H_
diff --git a/net/quic/platform/api/quic_text_utils.h b/net/quic/platform/api/quic_text_utils.h index e80df74d..41152bc 100644 --- a/net/quic/platform/api/quic_text_utils.h +++ b/net/quic/platform/api/quic_text_utils.h
@@ -76,6 +76,10 @@ return QuicTextUtilsImpl::HexEncode(data); } + // This converts a uint32 into an 8-character hexidecimal + // representation. Return value: 8 characters of ASCII string. + static std::string Hex(uint32_t v) { return QuicTextUtilsImpl::Hex(v); } + // Converts |data| from a hexadecimal ASCII string to a binary string // that is |data.length()/2| bytes long. static std::string HexDecode(QuicStringPiece data) {
diff --git a/net/quic/platform/impl/quic_optional_impl.h b/net/quic/platform/impl/quic_optional_impl.h new file mode 100644 index 0000000..f15e319 --- /dev/null +++ b/net/quic/platform/impl/quic_optional_impl.h
@@ -0,0 +1,17 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_PLATFORM_IMPL_QUIC_OPTIONAL_IMPL_H_ +#define NET_QUIC_PLATFORM_IMPL_QUIC_OPTIONAL_IMPL_H_ + +#include "base/optional.h" + +namespace net { + +template <typename T> +using QuicOptionalImpl = base::Optional<T>; + +} // namespace net + +#endif // NET_QUIC_PLATFORM_IMPL_QUIC_OPTIONAL_IMPL_H_
diff --git a/net/quic/platform/impl/quic_reconstruct_object_impl.h b/net/quic/platform/impl/quic_reconstruct_object_impl.h new file mode 100644 index 0000000..b269167 --- /dev/null +++ b/net/quic/platform/impl/quic_reconstruct_object_impl.h
@@ -0,0 +1,49 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_PLATFORM_IMPL_QUIC_RECONSTRUCT_OBJECT_IMPL_H_ +#define NET_QUIC_PLATFORM_IMPL_QUIC_RECONSTRUCT_OBJECT_IMPL_H_ + +// Support for marking memory as uninitialized, or otherwise corrupting it. Used +// in testing in an attempt to ensure that there isn't "leakage" of state from +// one sub-test to another. For example, in tests based on RandomDecoderTest, +// the same objects (decoder or decoder destination), will be used multiple +// times as a single encoded input is repeatedly decoded with multiple +// segmentations of the input. +// +// If compiled with Memory Sanitizer, the memory is marked as uninitialized; +// else the memory is overwritten with random bytes. + +#include <stddef.h> + +#include <algorithm> +#include <new> +#include <utility> + +namespace net { +namespace test { + +// Reconstruct an object so that it is initialized as when it was first +// constructed. Runs the destructor to handle objects that might own resources, +// marks the object's memory as as uninitialized, and finally runs the +// constructor with the provided arguments, if any. +template <class T, class... Args> +void QuicReconstructObjectImpl(T* ptr, + QuicTestRandomBase* rng, + Args&&... args) { + ptr->~T(); + ::new (ptr) T(std::forward<Args>(args)...); +} +// This version applies default-initialization to the object. +template <class T> +void QuicDefaultReconstructObjectImpl(T* ptr, QuicTestRandomBase* rng) { + ptr->~T(); + ::new (ptr) T; +} + +} // namespace test + +} // namespace net + +#endif // NET_QUIC_PLATFORM_IMPL_QUIC_RECONSTRUCT_OBJECT_IMPL_H_
diff --git a/net/quic/platform/impl/quic_str_cat_impl.h b/net/quic/platform/impl/quic_str_cat_impl.h index fae149d..0249c94 100644 --- a/net/quic/platform/impl/quic_str_cat_impl.h +++ b/net/quic/platform/impl/quic_str_cat_impl.h
@@ -7,6 +7,7 @@ #include <sstream> #include <string> +#include <utility> #include "base/strings/stringprintf.h"
diff --git a/net/quic/platform/impl/quic_string_impl.h b/net/quic/platform/impl/quic_string_impl.h new file mode 100644 index 0000000..3c84ee3 --- /dev/null +++ b/net/quic/platform/impl/quic_string_impl.h
@@ -0,0 +1,16 @@ +// Copyright (c) 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_PLATFORM_IMPL_QUIC_STRING_IMPL_H_ +#define NET_QUIC_PLATFORM_IMPL_QUIC_STRING_IMPL_H_ + +#include <string> + +namespace net { + +using QuicStringImpl = std::string; + +} // namespace net + +#endif // NET_QUIC_PLATFORM_IMPL_QUIC_STRING_IMPL_H_
diff --git a/net/quic/platform/impl/quic_string_utils_impl.h b/net/quic/platform/impl/quic_string_utils_impl.h new file mode 100644 index 0000000..8b6ea49 --- /dev/null +++ b/net/quic/platform/impl/quic_string_utils_impl.h
@@ -0,0 +1,27 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_QUIC_PLATFORM_IMPL_QUIC_STRING_UTILS_IMPL_H_ +#define NET_QUIC_PLATFORM_IMPL_QUIC_STRING_UTILS_IMPL_H_ + +#include <utility> + +#include "base/strings/string_number_conversions.h" +#include "base/strings/string_util.h" +#include "base/strings/stringprintf.h" +#include "net/base/hex_utils.h" +#include "net/quic/platform/api/quic_str_cat.h" +#include "net/quic/platform/api/quic_string.h" +#include "net/quic/platform/api/quic_string_piece.h" + +namespace net { + +template <typename... Args> +inline void QuicStrAppendImpl(QuicString* output, const Args&... args) { + output->append(QuicStrCatImpl(args...)); +} + +} // namespace net + +#endif // NET_QUIC_PLATFORM_IMPL_QUIC_STRING_UTILS_IMPL_H_
diff --git a/net/quic/platform/impl/quic_test_random_impl.cc b/net/quic/platform/impl/quic_test_random_impl.cc new file mode 100644 index 0000000..eb515f9 --- /dev/null +++ b/net/quic/platform/impl/quic_test_random_impl.cc
@@ -0,0 +1,58 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/quic/platform/api/quic_test_random.h" + +#include <memory> + +#include "base/rand_util.h" + +namespace net { +namespace test { + +bool QuicTestRandom::OneIn(int n) { + return base::RandGenerator(n) == 0; +} + +int32_t QuicTestRandom::Uniform(int32_t n) { + return base::RandGenerator(n); +} + +uint8_t QuicTestRandom::Rand8() { + return base::RandGenerator( + static_cast<uint64_t>(std::numeric_limits<uint8_t>::max()) + 1); +} + +uint16_t QuicTestRandom::Rand16() { + return base::RandGenerator( + static_cast<uint64_t>(std::numeric_limits<uint16_t>::max()) + 1); +} + +uint32_t QuicTestRandom::Rand32() { + return base::RandGenerator( + static_cast<uint64_t>(std::numeric_limits<uint32_t>::max()) + 1); +} + +uint64_t QuicTestRandom::Rand64() { + return base::RandUint64(); +} + +int32_t QuicTestRandom::Next() { + return Rand32(); +} + +int32_t QuicTestRandom::Skewed(int max_log) { + const uint32_t base = Rand32() % (max_log + 1); + const uint32_t mask = ((base < 32) ? (1u << base) : 0u) - 1u; + return Rand32() & mask; +} + +QuicString QuicTestRandom::RandString(int length) { + std::unique_ptr<char[]> buffer(new char[length]); + base::RandBytes(buffer.get(), length); + return QuicString(buffer.get(), length); +} + +} // namespace test +} // namespace net
diff --git a/net/quic/platform/impl/quic_test_random_impl.h b/net/quic/platform/impl/quic_test_random_impl.h new file mode 100644 index 0000000..1a3ed8f --- /dev/null +++ b/net/quic/platform/impl/quic_test_random_impl.h
@@ -0,0 +1,52 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef GFE_QUIC_PLATFORM_API_QUIC_TEST_RANDOM_IMPL_H_ +#define GFE_QUIC_PLATFORM_API_QUIC_TEST_RANDOM_IMPL_H_ + +namespace net { +namespace test { + +class QuicTestRandomBaseImpl { + public: + virtual ~QuicTestRandomBaseImpl() {} + virtual bool OneIn(int n) = 0; + virtual int32_t Uniform(int32_t n) = 0; + virtual uint8_t Rand8() = 0; + virtual uint16_t Rand16() = 0; + virtual uint32_t Rand32() = 0; + virtual uint64_t Rand64() = 0; + virtual int32_t Next() = 0; + virtual int32_t Skewed(int max_log) = 0; + virtual QuicString RandString(int length) = 0; + + // STL UniformRandomNumberGenerator implementation. + typedef uint32_t result_type; + static constexpr result_type min() { return 0; } + static constexpr result_type max() { + return std::numeric_limits<uint32_t>::max(); + } + result_type operator()() { return Rand32(); } +}; + +// QuicTestRandom holds no state: instances use the same base::RandGenerator +// with a global state. +class QuicTestRandomImpl : public QuicTestRandomBaseImpl { + public: + ~QuicTestRandomImpl() override {} + bool OneIn(int n) override; + int32_t Uniform(int32_t n) override; + uint8_t Rand8() override; + uint16_t Rand16() override; + uint32_t Rand32() override; + uint64_t Rand64() override; + int32_t Next() override; + int32_t Skewed(int max_log) override; + QuicString RandString(int length) override; +}; + +} // namespace test +} // namespace net + +#endif // GFE_QUIC_PLATFORM_API_QUIC_TEST_RANDOM_IMPL_H_
diff --git a/net/quic/platform/impl/quic_text_utils_impl.h b/net/quic/platform/impl/quic_text_utils_impl.h index cb14d8c..40871774 100644 --- a/net/quic/platform/impl/quic_text_utils_impl.h +++ b/net/quic/platform/impl/quic_text_utils_impl.h
@@ -80,6 +80,12 @@ return base::ToLowerASCII(::base::HexEncode(data.data(), data.size())); } + static std::string Hex(uint32_t v) { + std::stringstream ss; + ss << std::hex << v; + return ss.str(); + } + // Converts |data| from a hexadecimal ASCII string to a binary string // that is |data.length()/2| bytes long. static std::string HexDecode(QuicStringPiece data) {
diff --git a/net/quic/test_tools/quic_stream_sequencer_buffer_peer.cc b/net/quic/test_tools/quic_stream_sequencer_buffer_peer.cc index 83602be..da5754a6 100644 --- a/net/quic/test_tools/quic_stream_sequencer_buffer_peer.cc +++ b/net/quic/test_tools/quic_stream_sequencer_buffer_peer.cc
@@ -139,5 +139,8 @@ return buffer_->blocks_ != nullptr; } +size_t QuicStreamSequencerBufferPeer::block_count() { + return buffer_->blocks_count_; +} } // namespace test } // namespace net
diff --git a/net/quic/test_tools/quic_stream_sequencer_buffer_peer.h b/net/quic/test_tools/quic_stream_sequencer_buffer_peer.h index 0989843..1255d3a7 100644 --- a/net/quic/test_tools/quic_stream_sequencer_buffer_peer.h +++ b/net/quic/test_tools/quic_stream_sequencer_buffer_peer.h
@@ -51,6 +51,8 @@ bool IsBufferAllocated(); + size_t block_count(); + private: QuicStreamSequencerBuffer* buffer_; DISALLOW_COPY_AND_ASSIGN(QuicStreamSequencerBufferPeer);
diff --git a/net/socket/ssl_client_socket_impl.cc b/net/socket/ssl_client_socket_impl.cc index 7faad87..ecdf6f8 100644 --- a/net/socket/ssl_client_socket_impl.cc +++ b/net/socket/ssl_client_socket_impl.cc
@@ -1502,18 +1502,14 @@ server_cert_verify_result_.verified_cert.get(), ocsp_response, sct_list, &ct_verify_result_.scts, net_log_); - ct_verify_result_.ct_policies_applied = true; - SCTList verified_scts = ct::SCTsMatchingStatus(ct_verify_result_.scts, ct::SCT_STATUS_OK); - ct_verify_result_.cert_policy_compliance = - policy_enforcer_->DoesConformToCertPolicy( - server_cert_verify_result_.verified_cert.get(), verified_scts, - net_log_); + ct_verify_result_.policy_compliance = policy_enforcer_->CheckCompliance( + server_cert_verify_result_.verified_cert.get(), verified_scts, net_log_); if (server_cert_verify_result_.cert_status & CERT_STATUS_IS_EV) { - if (ct_verify_result_.cert_policy_compliance != - ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS) { + if (ct_verify_result_.policy_compliance != + ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS) { server_cert_verify_result_.cert_status |= CERT_STATUS_CT_COMPLIANCE_FAILED; server_cert_verify_result_.cert_status &= ~CERT_STATUS_IS_EV; @@ -1523,16 +1519,16 @@ // distinguish how often EV status is being dropped due to failing CT // compliance. UMA_HISTOGRAM_ENUMERATION("Net.CertificateTransparency.EVCompliance.SSL", - ct_verify_result_.cert_policy_compliance, - ct::CertPolicyCompliance::CERT_POLICY_MAX); + ct_verify_result_.policy_compliance, + ct::CTPolicyCompliance::CT_POLICY_MAX); } // Record the CT compliance of every connection to get an overall picture of // how many connections are CT-compliant. UMA_HISTOGRAM_ENUMERATION( "Net.CertificateTransparency.ConnectionComplianceStatus.SSL", - ct_verify_result_.cert_policy_compliance, - ct::CertPolicyCompliance::CERT_POLICY_MAX); + ct_verify_result_.policy_compliance, + ct::CTPolicyCompliance::CT_POLICY_MAX); TransportSecurityState::CTRequirementsStatus ct_requirement_status = transport_security_state_->CheckCTRequirements( @@ -1541,7 +1537,7 @@ server_cert_verify_result_.verified_cert.get(), server_cert_.get(), ct_verify_result_.scts, TransportSecurityState::ENABLE_EXPECT_CT_REPORTS, - ct_verify_result_.cert_policy_compliance); + ct_verify_result_.policy_compliance); if (ct_requirement_status != TransportSecurityState::CT_NOT_REQUIRED) { ct_verify_result_.policy_compliance_required = true; // Record the CT compliance of connections for which compliance is required; @@ -1549,8 +1545,8 @@ // be serving valid CT information, how many fail to do so?" UMA_HISTOGRAM_ENUMERATION( "Net.CertificateTransparency.CTRequiredConnectionComplianceStatus.SSL", - ct_verify_result_.cert_policy_compliance, - ct::CertPolicyCompliance::CERT_POLICY_MAX); + ct_verify_result_.policy_compliance, + ct::CTPolicyCompliance::CT_POLICY_MAX); } else { ct_verify_result_.policy_compliance_required = false; }
diff --git a/net/socket/ssl_client_socket_unittest.cc b/net/socket/ssl_client_socket_unittest.cc index a7d662c..93f14a4 100644 --- a/net/socket/ssl_client_socket_unittest.cc +++ b/net/socket/ssl_client_socket_unittest.cc
@@ -867,10 +867,10 @@ // A mock CTPolicyEnforcer that returns a custom verification result. class MockCTPolicyEnforcer : public CTPolicyEnforcer { public: - MOCK_METHOD3(DoesConformToCertPolicy, - ct::CertPolicyCompliance(X509Certificate* cert, - const ct::SCTList&, - const NetLogWithSource&)); + MOCK_METHOD3(CheckCompliance, + ct::CTPolicyCompliance(X509Certificate* cert, + const ct::SCTList&, + const NetLogWithSource&)); }; class MockRequireCTDelegate : public TransportSecurityState::RequireCTDelegate { @@ -895,9 +895,9 @@ // Set a dummy session cache shard to enable session caching. context_.ssl_session_cache_shard = "shard"; - EXPECT_CALL(*ct_policy_enforcer_, DoesConformToCertPolicy(_, _, _)) + EXPECT_CALL(*ct_policy_enforcer_, CheckCompliance(_, _, _)) .WillRepeatedly( - Return(ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS)); + Return(ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS)); } protected: @@ -2549,9 +2549,9 @@ // Emulate compliance of the certificate to the policy. MockCTPolicyEnforcer policy_enforcer; SetCTPolicyEnforcer(&policy_enforcer); - EXPECT_CALL(policy_enforcer, DoesConformToCertPolicy(_, _, _)) + EXPECT_CALL(policy_enforcer, CheckCompliance(_, _, _)) .WillRepeatedly( - Return(ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS)); + Return(ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS)); int rv; ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv)); @@ -2576,9 +2576,9 @@ // Emulate non-compliance of the certificate to the policy. MockCTPolicyEnforcer policy_enforcer; SetCTPolicyEnforcer(&policy_enforcer); - EXPECT_CALL(policy_enforcer, DoesConformToCertPolicy(_, _, _)) + EXPECT_CALL(policy_enforcer, CheckCompliance(_, _, _)) .WillRepeatedly( - Return(ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS)); + Return(ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS)); int rv; ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv)); @@ -2605,9 +2605,9 @@ // Emulate non-compliance of the certificate to the policy. MockCTPolicyEnforcer policy_enforcer; SetCTPolicyEnforcer(&policy_enforcer); - EXPECT_CALL(policy_enforcer, DoesConformToCertPolicy(_, _, _)) + EXPECT_CALL(policy_enforcer, CheckCompliance(_, _, _)) .WillRepeatedly( - Return(ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS)); + Return(ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS)); int rv; ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv)); @@ -2620,8 +2620,7 @@ // The histogram should have been recorded with the CT compliance status. histograms.ExpectUniqueSample( kHistogramName, - static_cast<int>(ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS), - 1); + static_cast<int>(ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS), 1); } // Test that when an EV certificate does conform to the CT policy and its EV @@ -2638,9 +2637,9 @@ // Emulate non-compliance of the certificate to the policy. MockCTPolicyEnforcer policy_enforcer; SetCTPolicyEnforcer(&policy_enforcer); - EXPECT_CALL(policy_enforcer, DoesConformToCertPolicy(_, _, _)) + EXPECT_CALL(policy_enforcer, CheckCompliance(_, _, _)) .WillRepeatedly( - Return(ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS)); + Return(ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS)); int rv; ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv)); @@ -2653,8 +2652,7 @@ // The histogram should have been recorded with the CT compliance status. histograms.ExpectUniqueSample( kHistogramName, - static_cast<int>(ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS), - 1); + static_cast<int>(ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS), 1); } // Test that enabling Signed Certificate Timestamps enables OCSP stapling. @@ -3500,10 +3498,9 @@ IsCTRequiredForHost(spawned_test_server()->host_port_pair().host())) .WillRepeatedly(Return(TransportSecurityState::RequireCTDelegate:: CTRequirementLevel::REQUIRED)); - EXPECT_CALL(*ct_policy_enforcer_, - DoesConformToCertPolicy(server_cert.get(), _, _)) + EXPECT_CALL(*ct_policy_enforcer_, CheckCompliance(server_cert.get(), _, _)) .WillRepeatedly( - Return(ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS)); + Return(ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS)); SSLConfig ssl_config; int rv; @@ -3535,10 +3532,9 @@ cert_verifier_->AddResultForCert(server_cert.get(), verify_result, OK); // Set up CT. - EXPECT_CALL(*ct_policy_enforcer_, - DoesConformToCertPolicy(server_cert.get(), _, _)) + EXPECT_CALL(*ct_policy_enforcer_, CheckCompliance(server_cert.get(), _, _)) .WillRepeatedly( - Return(ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS)); + Return(ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS)); SSLConfig ssl_config; int rv; @@ -3549,8 +3545,7 @@ // The histogram should have been recorded with the CT compliance status. histograms.ExpectUniqueSample( kHistogramName, - static_cast<int>(ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS), - 1); + static_cast<int>(ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS), 1); } // Test that when CT is required (in this case, by an Expect-CT opt-in) and the @@ -3586,10 +3581,9 @@ MockExpectCTReporter reporter; transport_security_state_->SetExpectCTReporter(&reporter); - EXPECT_CALL(*ct_policy_enforcer_, - DoesConformToCertPolicy(server_cert.get(), _, _)) + EXPECT_CALL(*ct_policy_enforcer_, CheckCompliance(server_cert.get(), _, _)) .WillRepeatedly( - Return(ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS)); + Return(ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS)); SSLConfig ssl_config; int rv; @@ -3600,8 +3594,7 @@ // The histogram should have been recorded with the CT compliance status. histograms.ExpectUniqueSample( kHistogramName, - static_cast<int>(ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS), - 1); + static_cast<int>(ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS), 1); } // Test that when CT is not required and the connection is compliant, the @@ -3623,10 +3616,9 @@ verify_result.public_key_hashes = MakeHashValueVector(0); cert_verifier_->AddResultForCert(server_cert.get(), verify_result, OK); - EXPECT_CALL(*ct_policy_enforcer_, - DoesConformToCertPolicy(server_cert.get(), _, _)) + EXPECT_CALL(*ct_policy_enforcer_, CheckCompliance(server_cert.get(), _, _)) .WillRepeatedly( - Return(ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS)); + Return(ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS)); SSLConfig ssl_config; int rv; @@ -3672,10 +3664,9 @@ MockExpectCTReporter reporter; transport_security_state_->SetExpectCTReporter(&reporter); - EXPECT_CALL(*ct_policy_enforcer_, - DoesConformToCertPolicy(server_cert.get(), _, _)) + EXPECT_CALL(*ct_policy_enforcer_, CheckCompliance(server_cert.get(), _, _)) .WillRepeatedly( - Return(ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS)); + Return(ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS)); SSLConfig ssl_config; int rv; @@ -3688,8 +3679,7 @@ // The histogram should have been recorded with the CT compliance status. histograms.ExpectUniqueSample( kHistogramName, - static_cast<int>(ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS), - 1); + static_cast<int>(ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS), 1); } // Test that when CT is required (in this case, by an Expect-CT opt-in) but the @@ -3714,10 +3704,9 @@ spawned_test_server()->host_port_pair().host(), expiry, true /* enforce */, GURL()); - EXPECT_CALL(*ct_policy_enforcer_, - DoesConformToCertPolicy(server_cert.get(), _, _)) + EXPECT_CALL(*ct_policy_enforcer_, CheckCompliance(server_cert.get(), _, _)) .WillRepeatedly( - Return(ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS)); + Return(ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS)); SSLConfig ssl_config; int rv; @@ -3749,10 +3738,9 @@ spawned_test_server()->host_port_pair().host(), expiry, true /* enforce */, GURL()); - EXPECT_CALL(*ct_policy_enforcer_, - DoesConformToCertPolicy(server_cert.get(), _, _)) + EXPECT_CALL(*ct_policy_enforcer_, CheckCompliance(server_cert.get(), _, _)) .WillRepeatedly( - Return(ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS)); + Return(ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS)); SSLConfig ssl_config; int rv; @@ -3790,10 +3778,9 @@ MockExpectCTReporter reporter; transport_security_state_->SetExpectCTReporter(&reporter); - EXPECT_CALL(*ct_policy_enforcer_, - DoesConformToCertPolicy(server_cert.get(), _, _)) + EXPECT_CALL(*ct_policy_enforcer_, CheckCompliance(server_cert.get(), _, _)) .WillRepeatedly( - Return(ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS)); + Return(ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS)); SSLConfig ssl_config; int rv; @@ -3814,10 +3801,9 @@ EXPECT_EQ(0u, reporter.signed_certificate_timestamps().size()); transport_security_state_->ClearReportCachesForTesting(); - EXPECT_CALL(*ct_policy_enforcer_, - DoesConformToCertPolicy(server_cert.get(), _, _)) + EXPECT_CALL(*ct_policy_enforcer_, CheckCompliance(server_cert.get(), _, _)) .WillRepeatedly( - Return(ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS)); + Return(ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS)); ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv)); ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info)); @@ -3835,10 +3821,9 @@ // If the connection is CT compliant, then there should be no socket error nor // a report. - EXPECT_CALL(*ct_policy_enforcer_, - DoesConformToCertPolicy(server_cert.get(), _, _)) + EXPECT_CALL(*ct_policy_enforcer_, CheckCompliance(server_cert.get(), _, _)) .WillRepeatedly( - Return(ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS)); + Return(ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS)); ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv)); ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info)); @@ -3848,10 +3833,9 @@ EXPECT_TRUE(sock_->IsConnected()); EXPECT_EQ(2u, reporter.num_failures()); - EXPECT_CALL(*ct_policy_enforcer_, - DoesConformToCertPolicy(server_cert.get(), _, _)) + EXPECT_CALL(*ct_policy_enforcer_, CheckCompliance(server_cert.get(), _, _)) .WillRepeatedly( - Return(ct::CertPolicyCompliance::CERT_POLICY_BUILD_NOT_TIMELY)); + Return(ct::CTPolicyCompliance::CT_POLICY_BUILD_NOT_TIMELY)); ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv)); ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info)); @@ -3896,10 +3880,9 @@ IsCTRequiredForHost(spawned_test_server()->host_port_pair().host())) .WillRepeatedly(Return(TransportSecurityState::RequireCTDelegate:: CTRequirementLevel::REQUIRED)); - EXPECT_CALL(*ct_policy_enforcer_, - DoesConformToCertPolicy(server_cert.get(), _, _)) + EXPECT_CALL(*ct_policy_enforcer_, CheckCompliance(server_cert.get(), _, _)) .WillRepeatedly( - Return(ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS)); + Return(ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS)); SSLConfig ssl_config; int rv;
diff --git a/net/socket/ssl_server_socket_unittest.cc b/net/socket/ssl_server_socket_unittest.cc index e6e6bbc..102e8033b 100644 --- a/net/socket/ssl_server_socket_unittest.cc +++ b/net/socket/ssl_server_socket_unittest.cc
@@ -88,11 +88,11 @@ public: MockCTPolicyEnforcer() = default; ~MockCTPolicyEnforcer() override = default; - ct::CertPolicyCompliance DoesConformToCertPolicy( + ct::CTPolicyCompliance CheckCompliance( X509Certificate* cert, const SCTList& verified_scts, const NetLogWithSource& net_log) override { - return ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS; + return ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS; } };
diff --git a/net/spdy/chromium/header_coalescer.cc b/net/spdy/chromium/header_coalescer.cc index 30cefb3..287ae85 100644 --- a/net/spdy/chromium/header_coalescer.cc +++ b/net/spdy/chromium/header_coalescer.cc
@@ -18,6 +18,7 @@ namespace net { namespace { + std::unique_ptr<base::Value> ElideNetLogHeaderCallback( SpdyStringPiece header_name, SpdyStringPiece header_value, @@ -105,13 +106,24 @@ return false; } - // End of line delimiter is forbidden according to RFC 7230 Section 3.2. - // Line folding, RFC 7230 Section 3.2.4., is a special case of this. - if (value.find("\r\n") != SpdyStringPiece::npos) { - net_log_.AddEvent(NetLogEventType::HTTP2_SESSION_RECV_INVALID_HEADER, - base::Bind(&ElideNetLogHeaderCallback, key, value, - "Header value must not contain CR+LF.")); - return false; + // RFC 7540 Section 10.3: "Any request or response that contains a character + // not permitted in a header field value MUST be treated as malformed (Section + // 8.1.2.6). Valid characters are defined by the field-content ABNF rule in + // Section 3.2 of [RFC7230]." RFC 7230 Section 3.2 says: + // field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + // field-vchar = VCHAR / obs-text + // RFC 5234 Appendix B.1 defines |VCHAR|: + // VCHAR = %x21-7E + // RFC 7230 Section 3.2.6 defines |obs-text|: + // obs-text = %x80-FF + // Therefore allowed characters are '\t' (HTAB), x20 (SP), x21-7E, and x80-FF. + for (const unsigned char c : value) { + if (c < '\t' || ('\t' < c && c < 0x20) || c == 0x7f) { + net_log_.AddEvent(NetLogEventType::HTTP2_SESSION_RECV_INVALID_HEADER, + base::Bind(&ElideNetLogHeaderCallback, key, value, + "Invalid character in header value.")); + return false; + } } auto iter = headers_.find(key);
diff --git a/net/spdy/chromium/header_coalescer_test.cc b/net/spdy/chromium/header_coalescer_test.cc index d4eae58..e5f9455 100644 --- a/net/spdy/chromium/header_coalescer_test.cc +++ b/net/spdy/chromium/header_coalescer_test.cc
@@ -71,10 +71,10 @@ EXPECT_FALSE(header_coalescer_.error_seen()); // Another 3 + 4 + 32 bytes: too large. - SpdyStringPiece header_value("\x1\x7F\x80\xFF"); + SpdyStringPiece header_value("abcd"); header_coalescer_.OnHeader("bar", header_value); EXPECT_TRUE(header_coalescer_.error_seen()); - ExpectEntry("bar", "%01%7F%80%FF", "Header list too large."); + ExpectEntry("bar", "abcd", "Header list too large."); } TEST_F(HeaderCoalescerTest, PseudoHeadersMustNotFollowRegularHeaders) { @@ -98,12 +98,6 @@ Pair("cookie", "baz; qux"))); } -TEST_F(HeaderCoalescerTest, CRLFInHeaderValue) { - header_coalescer_.OnHeader("foo", "bar\r\nbaz"); - EXPECT_TRUE(header_coalescer_.error_seen()); - ExpectEntry("foo", "bar%0D%0Abaz", "Header value must not contain CR+LF."); -} - TEST_F(HeaderCoalescerTest, HeaderNameNotValid) { SpdyStringPiece header_name("\x1\x7F\x80\xFF"); header_coalescer_.OnHeader(header_name, "foo"); @@ -136,41 +130,29 @@ EXPECT_THAT(header_block, ElementsAre(Pair(header_name, "foo"))); } -// RFC 7230 Section 3.2. Valid header value is defined as: -// field-value = *( field-content / obs-fold ) -// field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] -// field-vchar = VCHAR / obs-text -// -// obs-fold = CRLF 1*( SP / HTAB ) -// ; obsolete line folding -// ; see Section 3.2.4 +// According to RFC 7540 Section 10.3 and RFC 7230 Section 3.2, allowed +// characters in header values are '\t', ' ', 0x21 to 0x7E, and 0x80 to 0xFF. TEST_F(HeaderCoalescerTest, HeaderValueValid) { - // Add two headers, one with an HTAB and one with a SP. - std::vector<char> header_values[2]; - char prefixes[] = {'\t', ' '}; - for (int i = 0; i < 2; ++i) { - header_values[i] = std::vector<char>(); - header_values[i].push_back(prefixes[i]); - // obs-text. From 0x80 to 0xff. - for (int j = 0x80; j <= 0xff; ++j) { - header_values[i].push_back(j); - } - // vchar - for (int j = 0x21; j <= 0x7E; ++j) { - header_values[i].push_back(j); - } - header_coalescer_.OnHeader( - SpdyStringPrintf("%s_%d", "foo", i), - SpdyStringPiece(header_values[i].data(), header_values[i].size())); - EXPECT_FALSE(header_coalescer_.error_seen()); - } - SpdyHeaderBlock header_block = header_coalescer_.release_headers(); - EXPECT_THAT( - header_block, - ElementsAre(Pair("foo_0", SpdyStringPiece(header_values[0].data(), - header_values[0].size())), - Pair("foo_1", SpdyStringPiece(header_values[1].data(), - header_values[1].size())))); + header_coalescer_.OnHeader("foo", " bar \x21 \x7e baz\tqux\x80\xff "); + EXPECT_FALSE(header_coalescer_.error_seen()); +} + +TEST_F(HeaderCoalescerTest, HeaderValueContainsLF) { + header_coalescer_.OnHeader("foo", "bar\nbaz"); + EXPECT_TRUE(header_coalescer_.error_seen()); + ExpectEntry("foo", "bar%0Abaz", "Invalid character in header value."); +} + +TEST_F(HeaderCoalescerTest, HeaderValueContainsCR) { + header_coalescer_.OnHeader("foo", "bar\rbaz"); + EXPECT_TRUE(header_coalescer_.error_seen()); + ExpectEntry("foo", "bar%0Dbaz", "Invalid character in header value."); +} + +TEST_F(HeaderCoalescerTest, HeaderValueContains0x7f) { + header_coalescer_.OnHeader("foo", "bar\x7f baz"); + EXPECT_TRUE(header_coalescer_.error_seen()); + ExpectEntry("foo", "bar%7F%20baz", "Invalid character in header value."); } } // namespace test
diff --git a/net/spdy/chromium/spdy_session.cc b/net/spdy/chromium/spdy_session.cc index c990efd..6393542 100644 --- a/net/spdy/chromium/spdy_session.cc +++ b/net/spdy/chromium/spdy_session.cc
@@ -66,8 +66,9 @@ const int kDefaultConnectionAtRiskOfLossSeconds = 10; const int kHungIntervalSeconds = 10; -// Minimum seconds that unclaimed pushed streams will be kept in memory. -const int kMinPushedStreamLifetimeSeconds = 300; +// Lifetime of unclaimed pushed stream, in seconds: after this period, a pushed +// stream is cancelled if still not claimed. +const int kPushedStreamLifetimeSeconds = 300; // Default initial value for HTTP/2 SETTINGS. const uint32_t kDefaultInitialHeaderTableSize = 4096; @@ -711,7 +712,7 @@ ssl_info.public_key_hashes, ssl_info.cert.get(), ssl_info.unverified_cert.get(), ssl_info.signed_certificate_timestamps, TransportSecurityState::DISABLE_EXPECT_CT_REPORTS, - ssl_info.ct_cert_policy_compliance)) { + ssl_info.ct_policy_compliance)) { case TransportSecurityState::CT_REQUIREMENTS_NOT_MET: return false; case TransportSecurityState::CT_REQUIREMENTS_MET: @@ -794,9 +795,6 @@ net_log_.BeginEvent( NetLogEventType::HTTP2_SESSION, base::Bind(&NetLogSpdySessionCallback, &host_port_proxy_pair())); - next_unclaimed_push_stream_sweep_time_ = - time_func_() + - base::TimeDelta::FromSeconds(kMinPushedStreamLifetimeSeconds); DCHECK(base::ContainsKey(initial_settings_, SETTINGS_HEADER_TABLE_SIZE)); DCHECK(base::ContainsKey(initial_settings_, SETTINGS_MAX_CONCURRENT_STREAMS)); @@ -864,8 +862,7 @@ if (unclaimed_it == unclaimed_pushed_streams_.end()) return; - SpdyStreamId stream_id = unclaimed_it->second.stream_id; - + const SpdyStreamId stream_id = unclaimed_it->second; DCHECK(active_streams_.find(stream_id) != active_streams_.end()); ResetStream(stream_id, ERROR_CODE_CANCEL, "Cancelled push stream."); } @@ -1385,13 +1382,13 @@ SpdySession::UnclaimedPushedStreamContainer::~UnclaimedPushedStreamContainer() { } -size_t SpdySession::UnclaimedPushedStreamContainer::erase(const GURL& url) { +bool SpdySession::UnclaimedPushedStreamContainer::erase(const GURL& url) { const_iterator it = find(url); - if (it != end()) { - erase(it); - return 1; - } - return 0; + if (it == end()) + return false; + + erase(it); + return true; } SpdySession::UnclaimedPushedStreamContainer::iterator @@ -1408,12 +1405,9 @@ bool SpdySession::UnclaimedPushedStreamContainer::insert( const GURL& url, - SpdyStreamId stream_id, - const base::TimeTicks& creation_time) { + SpdyStreamId stream_id) { DCHECK(spdy_session_->pool_); - auto result = streams_.insert(std::make_pair( - url, SpdySession::UnclaimedPushedStreamContainer::PushedStreamInfo( - stream_id, creation_time))); + auto result = streams_.insert(std::make_pair(url, stream_id)); if (!result.second) { // Only one pushed stream is allowed for each URL. return false; @@ -1678,13 +1672,19 @@ } // Insertion fails if there already is a pushed stream with the same path. - if (!unclaimed_pushed_streams_.insert(gurl, stream_id, time_func_())) { + if (!unclaimed_pushed_streams_.insert(gurl, stream_id)) { EnqueueResetStreamFrame(stream_id, request_priority, ERROR_CODE_REFUSED_STREAM, "Duplicate pushed stream with url: " + gurl.spec()); return; } + base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( + FROM_HERE, + base::Bind(&SpdySession::CancelPushedStreamIfUnclaimed, GetWeakPtr(), + stream_id), + base::TimeDelta::FromSeconds(kPushedStreamLifetimeSeconds)); + auto stream = std::make_unique<SpdyStream>( SPDY_PUSH_STREAM, GetWeakPtr(), gurl, request_priority, stream_initial_send_window_size_, stream_max_recv_window_size_, net_log_); @@ -1704,8 +1704,6 @@ associated_it->second->AddRawReceivedBytes(last_compressed_frame_len_); last_compressed_frame_len_ = 0; - DeleteExpiredPushedStreams(); - InsertActivatedStream(std::move(stream)); ActiveStreamMap::iterator active_it = active_streams_.find(stream_id); @@ -1744,7 +1742,9 @@ // push is hardly used. Write tests for this and fix this. (See // http://crbug.com/261712 .) if (owned_stream->type() == SPDY_PUSH_STREAM) { - unclaimed_pushed_streams_.erase(owned_stream->url()); + if (unclaimed_pushed_streams_.erase(owned_stream->url())) { + bytes_pushed_and_unclaimed_count_ += owned_stream->recv_bytes(); + } bytes_pushed_count_ += owned_stream->recv_bytes(); num_pushed_streams_--; if (!owned_stream->IsReservedRemote()) @@ -2425,7 +2425,7 @@ if (unclaimed_it == unclaimed_pushed_streams_.end()) return nullptr; - SpdyStreamId stream_id = unclaimed_it->second.stream_id; + const SpdyStreamId stream_id = unclaimed_it->second; unclaimed_pushed_streams_.erase(unclaimed_it); ActiveStreamMap::iterator active_it = active_streams_.find(stream_id); @@ -2435,9 +2435,9 @@ } SpdyStream* stream = active_it->second; - net_log_.AddEvent(NetLogEventType::HTTP2_STREAM_ADOPTED_PUSH_STREAM, - base::Bind(&NetLogSpdyAdoptedPushStreamCallback, - stream->stream_id(), &url)); + net_log_.AddEvent( + NetLogEventType::HTTP2_STREAM_ADOPTED_PUSH_STREAM, + base::Bind(&NetLogSpdyAdoptedPushStreamCallback, stream_id, &url)); return stream; } @@ -2583,44 +2583,28 @@ } } -void SpdySession::DeleteExpiredPushedStreams() { - if (unclaimed_pushed_streams_.empty()) +void SpdySession::CancelPushedStreamIfUnclaimed(SpdyStreamId stream_id) { + ActiveStreamMap::iterator active_it = active_streams_.find(stream_id); + if (active_it == active_streams_.end()) return; - // Check that adequate time has elapsed since the last sweep. - if (time_func_() < next_unclaimed_push_stream_sweep_time_) + // Grab URL for faster lookup in unclaimed_pushed_streams_. + const GURL& url = active_it->second->url(); + UnclaimedPushedStreamContainer::const_iterator unclaimed_it = + unclaimed_pushed_streams_.find(url); + // Make sure to cancel the correct stream. It is possible that the pushed + // stream |stream_id| is already claimed, and another stream has been pushed + // for the same URL. + if (unclaimed_it == unclaimed_pushed_streams_.end() || + unclaimed_it->second != stream_id) { return; - - // Gather old streams to delete. - base::TimeTicks minimum_freshness = - time_func_() - - base::TimeDelta::FromSeconds(kMinPushedStreamLifetimeSeconds); - std::vector<SpdyStreamId> streams_to_close; - for (UnclaimedPushedStreamContainer::const_iterator it = - unclaimed_pushed_streams_.begin(); - it != unclaimed_pushed_streams_.end(); ++it) { - if (minimum_freshness > it->second.creation_time) - streams_to_close.push_back(it->second.stream_id); } - for (std::vector<SpdyStreamId>::const_iterator to_close_it = - streams_to_close.begin(); - to_close_it != streams_to_close.end(); ++to_close_it) { - ActiveStreamMap::iterator active_it = active_streams_.find(*to_close_it); - if (active_it == active_streams_.end()) - continue; - bytes_pushed_and_unclaimed_count_ += active_it->second->recv_bytes(); - - LogAbandonedActiveStream(active_it, ERR_TIMED_OUT); - // CloseActiveStreamIterator() will remove the stream from - // |unclaimed_pushed_streams_|. - ResetStreamIterator(active_it, ERROR_CODE_REFUSED_STREAM, - "Stream not claimed."); - } - - next_unclaimed_push_stream_sweep_time_ = - time_func_() + - base::TimeDelta::FromSeconds(kMinPushedStreamLifetimeSeconds); + LogAbandonedActiveStream(active_it, ERR_TIMED_OUT); + // CloseActiveStreamIterator() will remove the stream from + // |unclaimed_pushed_streams_|. + ResetStreamIterator(active_it, ERROR_CODE_REFUSED_STREAM, + "Stream not claimed."); } void SpdySession::OnError(
diff --git a/net/spdy/chromium/spdy_session.h b/net/spdy/chromium/spdy_session.h index 416aeef..3d527f8e 100644 --- a/net/spdy/chromium/spdy_session.h +++ b/net/spdy/chromium/spdy_session.h
@@ -18,6 +18,7 @@ #include "base/gtest_prod_util.h" #include "base/macros.h" #include "base/memory/ref_counted.h" +#include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" #include "base/time/time.h" #include "net/base/host_port_pair.h" @@ -521,11 +522,10 @@ // Allow tests to access our innards for testing purposes. FRIEND_TEST_ALL_PREFIXES(SpdySessionTest, ClientPing); FRIEND_TEST_ALL_PREFIXES(SpdySessionTest, FailedPing); - FRIEND_TEST_ALL_PREFIXES(SpdySessionTest, DeleteExpiredPushStreams); - FRIEND_TEST_ALL_PREFIXES(SpdySessionTest, MetricsCollectionOnPushStreams); FRIEND_TEST_ALL_PREFIXES(SpdySessionTest, CancelPushBeforeClaimed); FRIEND_TEST_ALL_PREFIXES(SpdySessionTest, CancelPushAfterSessionGoesAway); FRIEND_TEST_ALL_PREFIXES(SpdySessionTest, CancelPushAfterExpired); + FRIEND_TEST_ALL_PREFIXES(SpdySessionTest, ClaimPushedStreamBeforeExpires); FRIEND_TEST_ALL_PREFIXES(SpdySessionTest, ProtocolNegotiation); FRIEND_TEST_ALL_PREFIXES(SpdySessionTest, AdjustRecvWindowSize); FRIEND_TEST_ALL_PREFIXES(SpdySessionTest, AdjustSendWindowSize); @@ -591,17 +591,7 @@ // an unclaimed pushed stream is claimed. class UnclaimedPushedStreamContainer { public: - struct PushedStreamInfo { - PushedStreamInfo() : stream_id(0) {} - PushedStreamInfo(SpdyStreamId stream_id, base::TimeTicks creation_time) - : stream_id(stream_id), creation_time(creation_time) {} - ~PushedStreamInfo() {} - size_t EstimateMemoryUsage() const { return 0; } - - SpdyStreamId stream_id; - base::TimeTicks creation_time; - }; - using PushedStreamMap = std::map<GURL, PushedStreamInfo>; + using PushedStreamMap = std::map<GURL, SpdyStreamId>; using iterator = PushedStreamMap::iterator; using const_iterator = PushedStreamMap::const_iterator; @@ -619,14 +609,15 @@ return streams_.lower_bound(url); } - size_t erase(const GURL& url); + // Return true if there was an element with |url|, which was then erased. + bool erase(const GURL& url); + + // Return the iterator following |it|. iterator erase(const_iterator it); // Return true if there was not already an entry with |url|, // in which case the insertion was successful. - bool insert(const GURL& url, - SpdyStreamId stream_id, - const base::TimeTicks& creation_time) WARN_UNUSED_RESULT; + bool insert(const GURL& url, SpdyStreamId stream_id) WARN_UNUSED_RESULT; size_t EstimateMemoryUsage() const; @@ -841,8 +832,11 @@ void CompleteStreamRequest( const base::WeakPtr<SpdyStreamRequest>& pending_request); - // Remove old unclaimed pushed streams. - void DeleteExpiredPushedStreams(); + // Cancel pushed stream with |stream_id|, if still unclaimed. Identifying a + // pushed stream by GURL instead of stream ID could result in incorrect + // behavior if a pushed stream was claimed but later another stream was pushed + // for the same GURL. + void CancelPushedStreamIfUnclaimed(SpdyStreamId stream_id); // BufferedSpdyFramerVisitorInterface: void OnError(Http2DecoderAdapter::SpdyFramerError spdy_framer_error) override; @@ -1113,10 +1107,6 @@ // This is the length of the last compressed frame. size_t last_compressed_frame_len_; - // This is the next time that unclaimed push streams should be checked for - // expirations. - base::TimeTicks next_unclaimed_push_stream_sweep_time_; - // Indicate if we have already scheduled a delayed task to check the ping // status. bool check_ping_status_pending_;
diff --git a/net/spdy/chromium/spdy_session_unittest.cc b/net/spdy/chromium/spdy_session_unittest.cc index b0df61f..e8634991 100644 --- a/net/spdy/chromium/spdy_session_unittest.cc +++ b/net/spdy/chromium/spdy_session_unittest.cc
@@ -13,6 +13,7 @@ #include "base/run_loop.h" #include "base/test/histogram_tester.h" #include "base/test/scoped_feature_list.h" +#include "base/test/test_mock_time_task_runner.h" #include "net/base/host_port_pair.h" #include "net/base/io_buffer.h" #include "net/base/ip_endpoint.h" @@ -1282,34 +1283,19 @@ TEST_F(SpdySessionTest, CancelPushAfterSessionGoesAway) { base::HistogramTester histogram_tester; - session_deps_.host_resolver->set_synchronous_mode(true); - session_deps_.time_func = TheNearFuture; SpdySerializedFrame req( spdy_util_.ConstructSpdyGet(nullptr, 0, 1, MEDIUM, true)); - SpdySerializedFrame priority_a( + SpdySerializedFrame priority( spdy_util_.ConstructSpdyPriority(2, 1, IDLE, true)); - SpdySerializedFrame priority_b( - spdy_util_.ConstructSpdyPriority(4, 2, IDLE, true)); - SpdySerializedFrame rst_a( - spdy_util_.ConstructSpdyRstStream(2, ERROR_CODE_REFUSED_STREAM)); - MockWrite writes[] = { - CreateMockWrite(req, 0), CreateMockWrite(priority_a, 2), - CreateMockWrite(priority_b, 6), CreateMockWrite(rst_a, 7), - }; + MockWrite writes[] = {CreateMockWrite(req, 0), CreateMockWrite(priority, 2)}; - SpdySerializedFrame push_a(spdy_util_.ConstructSpdyPush( + SpdySerializedFrame push(spdy_util_.ConstructSpdyPush( nullptr, 0, 2, 1, "https://www.example.org/a.dat")); - SpdySerializedFrame push_a_body(spdy_util_.ConstructSpdyDataFrame(2, false)); - // In ascii "0" < "a". We use it to verify that we properly handle std::map - // iterators inside. See http://crbug.com/443490 - SpdySerializedFrame push_b(spdy_util_.ConstructSpdyPush( - nullptr, 0, 4, 1, "https://www.example.org/0.dat")); - MockRead reads[] = { - CreateMockRead(push_a, 1), CreateMockRead(push_a_body, 3), - MockRead(ASYNC, ERR_IO_PENDING, 4), CreateMockRead(push_b, 5), - MockRead(ASYNC, ERR_IO_PENDING, 8), MockRead(ASYNC, 0, 9) // EOF - }; + SpdySerializedFrame push_body(spdy_util_.ConstructSpdyDataFrame(2, false)); + MockRead reads[] = {CreateMockRead(push, 1), CreateMockRead(push_body, 3), + MockRead(ASYNC, ERR_IO_PENDING, 4), + MockRead(ASYNC, 0, 5)}; SequencedSocketData data(reads, arraysize(reads), writes, arraysize(writes)); session_deps_.socket_factory->AddSocketDataProvider(&data); @@ -1319,7 +1305,6 @@ CreateNetworkSession(); CreateSpdySession(); - // Process the principal request, and the first push stream request & body. base::WeakPtr<SpdyStream> spdy_stream = CreateStreamSynchronously(SPDY_REQUEST_RESPONSE_STREAM, session_, test_url_, MEDIUM, NetLogWithSource()); @@ -1336,72 +1321,49 @@ EXPECT_EQ(1u, session_->count_unclaimed_pushed_streams_for_url( GURL("https://www.example.org/a.dat"))); - // Unclaimed push body consumed bytes from the session window. + // Unclaimed push body consumes bytes from the session window. EXPECT_EQ(kDefaultInitialWindowSize - kUploadDataSize, session_->session_recv_window_size_); EXPECT_EQ(0, session_->session_unacked_recv_window_bytes_); - // Shift time to expire the push stream. Read the second HEADERS, - // and verify a RST_STREAM was written. - g_time_delta = base::TimeDelta::FromSeconds(301); - data.Resume(); - base::RunLoop().RunUntilIdle(); - - // Verify that the second pushed stream evicted the first pushed stream. - EXPECT_EQ(1u, session_->num_unclaimed_pushed_streams()); - EXPECT_EQ(1u, session_->count_unclaimed_pushed_streams_for_url( - GURL("https://www.example.org/0.dat"))); - - // Verify that the session window reclaimed the evicted stream body. - EXPECT_EQ(kDefaultInitialWindowSize, session_->session_recv_window_size_); - EXPECT_EQ(kUploadDataSize, session_->session_unacked_recv_window_bytes_); - EXPECT_TRUE(session_); - // Read and process EOF. data.Resume(); base::RunLoop().RunUntilIdle(); - // Cancel the first push after session goes away. Verify the test doesn't - // crash. + // Cancel the push after session goes away. The test must not crash. EXPECT_FALSE(session_); EXPECT_TRUE( test_push_delegate_->CancelPush(GURL("https://www.example.org/a.dat"))); + histogram_tester.ExpectBucketCount("Net.SpdyStreamsPushedPerSession", 1, 1); histogram_tester.ExpectBucketCount("Net.SpdySession.PushedBytes", 6, 1); histogram_tester.ExpectBucketCount("Net.SpdySession.PushedAndUnclaimedBytes", 6, 1); } TEST_F(SpdySessionTest, CancelPushAfterExpired) { + auto task_runner = base::MakeRefCounted<base::TestMockTimeTaskRunner>(); + base::TestMockTimeTaskRunner::ScopedContext scoped_context(task_runner.get()); + base::HistogramTester histogram_tester; - session_deps_.host_resolver->set_synchronous_mode(true); - session_deps_.time_func = TheNearFuture; SpdySerializedFrame req( spdy_util_.ConstructSpdyGet(nullptr, 0, 1, MEDIUM, true)); - SpdySerializedFrame priority_a( + SpdySerializedFrame priority( spdy_util_.ConstructSpdyPriority(2, 1, IDLE, true)); - SpdySerializedFrame priority_b( - spdy_util_.ConstructSpdyPriority(4, 2, IDLE, true)); - SpdySerializedFrame rst_a( + SpdySerializedFrame rst( spdy_util_.ConstructSpdyRstStream(2, ERROR_CODE_REFUSED_STREAM)); MockWrite writes[] = { - CreateMockWrite(req, 0), CreateMockWrite(priority_a, 2), - CreateMockWrite(priority_b, 6), CreateMockWrite(rst_a, 7), + CreateMockWrite(req, 0), CreateMockWrite(priority, 3), + CreateMockWrite(rst, 5), }; - SpdySerializedFrame push_a(spdy_util_.ConstructSpdyPush( + SpdySerializedFrame push(spdy_util_.ConstructSpdyPush( nullptr, 0, 2, 1, "https://www.example.org/a.dat")); - SpdySerializedFrame push_a_body(spdy_util_.ConstructSpdyDataFrame(2, false)); - // In ascii "0" < "a". We use it to verify that we properly handle std::map - // iterators inside. See http://crbug.com/443490 - SpdySerializedFrame push_b(spdy_util_.ConstructSpdyPush( - nullptr, 0, 4, 1, "https://www.example.org/0.dat")); - MockRead reads[] = { - CreateMockRead(push_a, 1), CreateMockRead(push_a_body, 3), - MockRead(ASYNC, ERR_IO_PENDING, 4), CreateMockRead(push_b, 5), - MockRead(ASYNC, ERR_IO_PENDING, 8), MockRead(ASYNC, 0, 9) // EOF - }; + SpdySerializedFrame push_body(spdy_util_.ConstructSpdyDataFrame(2, false)); + MockRead reads[] = {CreateMockRead(push, 1), CreateMockRead(push_body, 2), + MockRead(ASYNC, ERR_IO_PENDING, 4), + MockRead(ASYNC, 0, 6)}; SequencedSocketData data(reads, arraysize(reads), writes, arraysize(writes)); session_deps_.socket_factory->AddSocketDataProvider(&data); @@ -1409,9 +1371,40 @@ AddSSLSocketData(); CreateNetworkSession(); - CreateSpdySession(); - // Process the principal request, and the first push stream request & body. + // TODO(bnc): Use CreateSpdySession() instead of the boilerplate below once + // ScopedTaskEnvironment supports mocked time and can be used instead of + // TestMockTimeTaskRunner. + auto transport_params = base::MakeRefCounted<TransportSocketParams>( + key_.host_port_pair(), false, OnHostResolutionCallback(), + TransportSocketParams::COMBINE_CONNECT_AND_WRITE_DEFAULT); + + auto connection = std::make_unique<ClientSocketHandle>(); + TestCompletionCallback callback; + + auto ssl_params = base::MakeRefCounted<SSLSocketParams>( + transport_params, nullptr, nullptr, key_.host_port_pair(), SSLConfig(), + key_.privacy_mode(), 0, false); + int rv = connection->Init( + key_.host_port_pair().ToString(), ssl_params, MEDIUM, + ClientSocketPool::RespectLimits::ENABLED, callback.callback(), + http_session_->GetSSLSocketPool(HttpNetworkSession::NORMAL_SOCKET_POOL), + log_.bound()); + EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); + + task_runner->RunUntilIdle(); + // At this point, |callback| already has the result, so the following will not + // call RunLoop(). + rv = callback.WaitForResult(); + + EXPECT_THAT(rv, IsOk()); + + session_ = + http_session_->spdy_session_pool()->CreateAvailableSessionFromSocket( + key_, std::move(connection), log_.bound()); + EXPECT_TRUE(session_); + EXPECT_TRUE(HasSpdySession(http_session_->spdy_session_pool(), key_)); + base::WeakPtr<SpdyStream> spdy_stream = CreateStreamSynchronously(SPDY_REQUEST_RESPONSE_STREAM, session_, test_url_, MEDIUM, NetLogWithSource()); @@ -1421,83 +1414,173 @@ SpdyHeaderBlock headers(spdy_util_.ConstructGetHeaderBlock(kDefaultUrl)); spdy_stream->SendRequestHeaders(std::move(headers), NO_MORE_DATA_TO_SEND); - base::RunLoop().RunUntilIdle(); + task_runner->RunUntilIdle(); // Verify that there is one unclaimed push stream. + const GURL pushed_url("https://www.example.org/a.dat"); EXPECT_EQ(1u, session_->num_unclaimed_pushed_streams()); - EXPECT_EQ(1u, session_->count_unclaimed_pushed_streams_for_url( - GURL("https://www.example.org/a.dat"))); + EXPECT_EQ(1u, session_->count_unclaimed_pushed_streams_for_url(pushed_url)); - // Unclaimed push body consumed bytes from the session window. + // Unclaimed push body consumes bytes from the session window. EXPECT_EQ(kDefaultInitialWindowSize - kUploadDataSize, session_->session_recv_window_size_); EXPECT_EQ(0, session_->session_unacked_recv_window_bytes_); - // Shift time to expire the push stream. Read the second HEADERS, - // and verify a RST_STREAM was written. - g_time_delta = base::TimeDelta::FromSeconds(301); - data.Resume(); - base::RunLoop().RunUntilIdle(); + // Fast forward to CancelPushedStreamIfUnclaimed() that was posted with a + // delay. + task_runner->FastForwardUntilNoTasksRemain(); + task_runner->RunUntilIdle(); - // Verify that the second pushed stream evicted the first pushed stream. - EXPECT_EQ(1u, session_->num_unclaimed_pushed_streams()); - EXPECT_EQ(1u, session_->count_unclaimed_pushed_streams_for_url( - GURL("https://www.example.org/0.dat"))); - - // Cancel the first push after its expiration. - EXPECT_TRUE( - test_push_delegate_->CancelPush(GURL("https://www.example.org/a.dat"))); - EXPECT_EQ(1u, session_->num_unclaimed_pushed_streams()); - EXPECT_TRUE(session_); + // Verify that pushed stream is cancelled. + EXPECT_EQ(0u, session_->num_unclaimed_pushed_streams()); // Verify that the session window reclaimed the evicted stream body. EXPECT_EQ(kDefaultInitialWindowSize, session_->session_recv_window_size_); EXPECT_EQ(kUploadDataSize, session_->session_unacked_recv_window_bytes_); + + // Try to cancel the expired push after its expiration: must not crash. + EXPECT_TRUE(session_); + EXPECT_TRUE(test_push_delegate_->CancelPush(pushed_url)); + EXPECT_EQ(0u, session_->num_unclaimed_pushed_streams()); + + // Read and process EOF. + data.Resume(); + task_runner->RunUntilIdle(); + EXPECT_FALSE(session_); + + histogram_tester.ExpectBucketCount("Net.SpdyStreamsPushedPerSession", 1, 1); + histogram_tester.ExpectBucketCount("Net.SpdySession.PushedBytes", 6, 1); + histogram_tester.ExpectBucketCount("Net.SpdySession.PushedAndUnclaimedBytes", + 6, 1); +} + +TEST_F(SpdySessionTest, ClaimPushedStreamBeforeExpires) { + auto task_runner = base::MakeRefCounted<base::TestMockTimeTaskRunner>(); + base::TestMockTimeTaskRunner::ScopedContext scoped_context(task_runner.get()); + + base::HistogramTester histogram_tester; + + SpdySerializedFrame req( + spdy_util_.ConstructSpdyGet(nullptr, 0, 1, MEDIUM, true)); + SpdySerializedFrame priority( + spdy_util_.ConstructSpdyPriority(2, 1, IDLE, true)); + MockWrite writes[] = {CreateMockWrite(req, 0), CreateMockWrite(priority, 3)}; + + SpdySerializedFrame push(spdy_util_.ConstructSpdyPush( + nullptr, 0, 2, 1, "https://www.example.org/a.dat")); + SpdySerializedFrame push_body(spdy_util_.ConstructSpdyDataFrame(2, false)); + MockRead reads[] = {CreateMockRead(push, 1), CreateMockRead(push_body, 2), + MockRead(ASYNC, ERR_IO_PENDING, 4), + MockRead(ASYNC, 0, 5)}; + + SequencedSocketData data(reads, arraysize(reads), writes, arraysize(writes)); + session_deps_.socket_factory->AddSocketDataProvider(&data); + + AddSSLSocketData(); + + CreateNetworkSession(); + + // TODO(bnc): Use CreateSpdySession() instead of the boilerplate below once + // ScopedTaskEnvironment supports mocked time and can be used instead of + // TestMockTimeTaskRunner. + auto transport_params = base::MakeRefCounted<TransportSocketParams>( + key_.host_port_pair(), false, OnHostResolutionCallback(), + TransportSocketParams::COMBINE_CONNECT_AND_WRITE_DEFAULT); + + auto connection = std::make_unique<ClientSocketHandle>(); + TestCompletionCallback callback; + + auto ssl_params = base::MakeRefCounted<SSLSocketParams>( + transport_params, nullptr, nullptr, key_.host_port_pair(), SSLConfig(), + key_.privacy_mode(), 0, false); + int rv = connection->Init( + key_.host_port_pair().ToString(), ssl_params, MEDIUM, + ClientSocketPool::RespectLimits::ENABLED, callback.callback(), + http_session_->GetSSLSocketPool(HttpNetworkSession::NORMAL_SOCKET_POOL), + log_.bound()); + EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); + + task_runner->RunUntilIdle(); + // At this point, |callback| already has the result, so the following will not + // call RunLoop(). + rv = callback.WaitForResult(); + + EXPECT_THAT(rv, IsOk()); + + session_ = + http_session_->spdy_session_pool()->CreateAvailableSessionFromSocket( + key_, std::move(connection), log_.bound()); + EXPECT_TRUE(session_); + EXPECT_TRUE(HasSpdySession(http_session_->spdy_session_pool(), key_)); + + base::WeakPtr<SpdyStream> spdy_stream1 = + CreateStreamSynchronously(SPDY_REQUEST_RESPONSE_STREAM, session_, + test_url_, MEDIUM, NetLogWithSource()); + test::StreamDelegateDoNothing delegate1(spdy_stream1); + spdy_stream1->SetDelegate(&delegate1); + + SpdyHeaderBlock headers1(spdy_util_.ConstructGetHeaderBlock(kDefaultUrl)); + spdy_stream1->SendRequestHeaders(std::move(headers1), NO_MORE_DATA_TO_SEND); + + task_runner->RunUntilIdle(); + + // Verify that there is one unclaimed push stream. + const GURL pushed_url("https://www.example.org/a.dat"); + EXPECT_EQ(1u, session_->num_unclaimed_pushed_streams()); + EXPECT_EQ(1u, session_->count_unclaimed_pushed_streams_for_url(pushed_url)); + + // Unclaimed push body consumes bytes from the session window. + EXPECT_EQ(kDefaultInitialWindowSize - kUploadDataSize, + session_->session_recv_window_size_); + EXPECT_EQ(0, session_->session_unacked_recv_window_bytes_); + + SpdyStream* spdy_stream2; + rv = session_->GetPushStream(pushed_url, MEDIUM, &spdy_stream2, + NetLogWithSource()); + ASSERT_THAT(rv, IsOk()); + ASSERT_TRUE(spdy_stream2); + + test::StreamDelegateDoNothing delegate2(spdy_stream2->GetWeakPtr()); + spdy_stream2->SetDelegate(&delegate2); + + // Verify that pushed stream is claimed. + EXPECT_EQ(0u, session_->num_unclaimed_pushed_streams()); + + // Fast forward to CancelPushedStreamIfUnclaimed() that was posted with a + // delay. CancelPushedStreamIfUnclaimed() must be a no-op. + task_runner->FastForwardUntilNoTasksRemain(); + task_runner->RunUntilIdle(); EXPECT_TRUE(session_); // Read and process EOF. data.Resume(); - base::RunLoop().RunUntilIdle(); + task_runner->RunUntilIdle(); EXPECT_FALSE(session_); + histogram_tester.ExpectBucketCount("Net.SpdyStreamsPushedPerSession", 1, 1); histogram_tester.ExpectBucketCount("Net.SpdySession.PushedBytes", 6, 1); histogram_tester.ExpectBucketCount("Net.SpdySession.PushedAndUnclaimedBytes", - 6, 1); + 0, 1); } TEST_F(SpdySessionTest, CancelPushBeforeClaimed) { base::HistogramTester histogram_tester; - session_deps_.host_resolver->set_synchronous_mode(true); - session_deps_.time_func = TheNearFuture; SpdySerializedFrame req( spdy_util_.ConstructSpdyGet(nullptr, 0, 1, MEDIUM, true)); - SpdySerializedFrame priority_a( + SpdySerializedFrame priority( spdy_util_.ConstructSpdyPriority(2, 1, IDLE, true)); - SpdySerializedFrame priority_b( - spdy_util_.ConstructSpdyPriority(4, 2, IDLE, true)); - SpdySerializedFrame rst_a( - spdy_util_.ConstructSpdyRstStream(2, ERROR_CODE_REFUSED_STREAM)); - SpdySerializedFrame rst_b( - spdy_util_.ConstructSpdyRstStream(4, ERROR_CODE_CANCEL)); - MockWrite writes[] = { - CreateMockWrite(req, 0), CreateMockWrite(priority_a, 2), - CreateMockWrite(priority_b, 6), CreateMockWrite(rst_a, 7), - CreateMockWrite(rst_b, 9), - }; + SpdySerializedFrame rst( + spdy_util_.ConstructSpdyRstStream(2, ERROR_CODE_CANCEL)); + MockWrite writes[] = {CreateMockWrite(req, 0), CreateMockWrite(priority, 3), + CreateMockWrite(rst, 5)}; - SpdySerializedFrame push_a(spdy_util_.ConstructSpdyPush( + SpdySerializedFrame push(spdy_util_.ConstructSpdyPush( nullptr, 0, 2, 1, "https://www.example.org/a.dat")); - SpdySerializedFrame push_a_body(spdy_util_.ConstructSpdyDataFrame(2, false)); - // In ascii "0" < "a". We use it to verify that we properly handle std::map - // iterators inside. See http://crbug.com/443490 - SpdySerializedFrame push_b(spdy_util_.ConstructSpdyPush( - nullptr, 0, 4, 1, "https://www.example.org/0.dat")); - MockRead reads[] = { - CreateMockRead(push_a, 1), CreateMockRead(push_a_body, 3), - MockRead(ASYNC, ERR_IO_PENDING, 4), CreateMockRead(push_b, 5), - MockRead(ASYNC, ERR_IO_PENDING, 8), MockRead(ASYNC, 0, 10) // EOF - }; + SpdySerializedFrame push_body(spdy_util_.ConstructSpdyDataFrame(2, false)); + MockRead reads[] = {CreateMockRead(push, 1), CreateMockRead(push_body, 2), + MockRead(ASYNC, ERR_IO_PENDING, 4), + MockRead(ASYNC, 0, 6)}; SequencedSocketData data(reads, arraysize(reads), writes, arraysize(writes)); session_deps_.socket_factory->AddSocketDataProvider(&data); @@ -1507,7 +1590,6 @@ CreateNetworkSession(); CreateSpdySession(); - // Process the principal request, and the first push stream request & body. base::WeakPtr<SpdyStream> spdy_stream = CreateStreamSynchronously(SPDY_REQUEST_RESPONSE_STREAM, session_, test_url_, MEDIUM, NetLogWithSource()); @@ -1520,238 +1602,37 @@ base::RunLoop().RunUntilIdle(); // Verify that there is one unclaimed push stream. + const GURL pushed_url("https://www.example.org/a.dat"); EXPECT_EQ(1u, session_->num_unclaimed_pushed_streams()); - EXPECT_EQ(1u, session_->count_unclaimed_pushed_streams_for_url( - GURL("https://www.example.org/a.dat"))); + EXPECT_EQ(1u, session_->count_unclaimed_pushed_streams_for_url(pushed_url)); - // Unclaimed push body consumed bytes from the session window. + // Unclaimed push body consumes bytes from the session window. EXPECT_EQ(kDefaultInitialWindowSize - kUploadDataSize, session_->session_recv_window_size_); EXPECT_EQ(0, session_->session_unacked_recv_window_bytes_); - // Shift time to expire the push stream. Read the second HEADERS, - // and verify a RST_STREAM was written. - g_time_delta = base::TimeDelta::FromSeconds(301); - data.Resume(); - base::RunLoop().RunUntilIdle(); - - // Verify that the second pushed stream evicted the first pushed stream. - GURL pushed_url("https://www.example.org/0.dat"); - EXPECT_EQ(1u, session_->num_unclaimed_pushed_streams()); - EXPECT_EQ(1u, session_->count_unclaimed_pushed_streams_for_url(pushed_url)); - - // Verify that the session window reclaimed the evicted stream body. - EXPECT_EQ(kDefaultInitialWindowSize, session_->session_recv_window_size_); - EXPECT_EQ(kUploadDataSize, session_->session_unacked_recv_window_bytes_); - - EXPECT_TRUE(session_); - // Cancel the push before it's claimed. + // Cancel the push before it is claimed. EXPECT_TRUE(test_push_delegate_->CancelPush(pushed_url)); EXPECT_EQ(0u, session_->num_unclaimed_pushed_streams()); EXPECT_EQ(0u, session_->count_unclaimed_pushed_streams_for_url(pushed_url)); - // Read and process EOF. - data.Resume(); - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(session_); - histogram_tester.ExpectBucketCount("Net.SpdySession.PushedBytes", 6, 1); - histogram_tester.ExpectBucketCount("Net.SpdySession.PushedAndUnclaimedBytes", - 6, 1); -} - -TEST_F(SpdySessionTest, DeleteExpiredPushStreams) { - base::HistogramTester histogram_tester; - session_deps_.host_resolver->set_synchronous_mode(true); - session_deps_.time_func = TheNearFuture; - - SpdySerializedFrame req( - spdy_util_.ConstructSpdyGet(nullptr, 0, 1, MEDIUM, true)); - SpdySerializedFrame priority_a( - spdy_util_.ConstructSpdyPriority(2, 1, IDLE, true)); - SpdySerializedFrame priority_b( - spdy_util_.ConstructSpdyPriority(4, 2, IDLE, true)); - SpdySerializedFrame rst_a( - spdy_util_.ConstructSpdyRstStream(2, ERROR_CODE_REFUSED_STREAM)); - MockWrite writes[] = { - CreateMockWrite(req, 0), CreateMockWrite(priority_a, 2), - CreateMockWrite(priority_b, 6), CreateMockWrite(rst_a, 7), - }; - - SpdySerializedFrame push_a(spdy_util_.ConstructSpdyPush( - nullptr, 0, 2, 1, "https://www.example.org/a.dat")); - SpdySerializedFrame push_a_body(spdy_util_.ConstructSpdyDataFrame(2, false)); - // In ascii "0" < "a". We use it to verify that we properly handle std::map - // iterators inside. See http://crbug.com/443490 - SpdySerializedFrame push_b(spdy_util_.ConstructSpdyPush( - nullptr, 0, 4, 1, "https://www.example.org/0.dat")); - MockRead reads[] = { - CreateMockRead(push_a, 1), CreateMockRead(push_a_body, 3), - MockRead(ASYNC, ERR_IO_PENDING, 4), CreateMockRead(push_b, 5), - MockRead(ASYNC, ERR_IO_PENDING, 8), MockRead(ASYNC, 0, 9) // EOF - }; - - SequencedSocketData data(reads, arraysize(reads), writes, arraysize(writes)); - session_deps_.socket_factory->AddSocketDataProvider(&data); - - AddSSLSocketData(); - - CreateNetworkSession(); - CreateSpdySession(); - - // Process the principal request, and the first push stream request & body. - base::WeakPtr<SpdyStream> spdy_stream = - CreateStreamSynchronously(SPDY_REQUEST_RESPONSE_STREAM, session_, - test_url_, MEDIUM, NetLogWithSource()); - test::StreamDelegateDoNothing delegate(spdy_stream); - spdy_stream->SetDelegate(&delegate); - - SpdyHeaderBlock headers(spdy_util_.ConstructGetHeaderBlock(kDefaultUrl)); - spdy_stream->SendRequestHeaders(std::move(headers), NO_MORE_DATA_TO_SEND); - - base::RunLoop().RunUntilIdle(); - - // Verify that there is one unclaimed push stream. - EXPECT_EQ(1u, session_->num_unclaimed_pushed_streams()); - EXPECT_EQ(1u, session_->count_unclaimed_pushed_streams_for_url( - GURL("https://www.example.org/a.dat"))); - - // Unclaimed push body consumed bytes from the session window. - EXPECT_EQ(kDefaultInitialWindowSize - kUploadDataSize, - session_->session_recv_window_size_); - EXPECT_EQ(0, session_->session_unacked_recv_window_bytes_); - - // Shift time to expire the push stream. Read the second HEADERS, - // and verify a RST_STREAM was written. - g_time_delta = base::TimeDelta::FromSeconds(301); - data.Resume(); - base::RunLoop().RunUntilIdle(); - - // Verify that the second pushed stream evicted the first pushed stream. - EXPECT_EQ(1u, session_->num_unclaimed_pushed_streams()); - EXPECT_EQ(1u, session_->count_unclaimed_pushed_streams_for_url( - GURL("https://www.example.org/0.dat"))); - // Verify that the session window reclaimed the evicted stream body. EXPECT_EQ(kDefaultInitialWindowSize, session_->session_recv_window_size_); EXPECT_EQ(kUploadDataSize, session_->session_unacked_recv_window_bytes_); - // Read and process EOF. EXPECT_TRUE(session_); + + // Read and process EOF. data.Resume(); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(session_); + + histogram_tester.ExpectBucketCount("Net.SpdyStreamsPushedPerSession", 1, 1); histogram_tester.ExpectBucketCount("Net.SpdySession.PushedBytes", 6, 1); histogram_tester.ExpectBucketCount("Net.SpdySession.PushedAndUnclaimedBytes", 6, 1); } -TEST_F(SpdySessionTest, MetricsCollectionOnPushStreams) { - base::HistogramTester histogram_tester; - session_deps_.host_resolver->set_synchronous_mode(true); - session_deps_.time_func = TheNearFuture; - - SpdySerializedFrame req( - spdy_util_.ConstructSpdyGet(nullptr, 0, 1, MEDIUM, true)); - SpdySerializedFrame priority_a( - spdy_util_.ConstructSpdyPriority(2, 1, IDLE, true)); - SpdySerializedFrame priority_b( - spdy_util_.ConstructSpdyPriority(4, 2, IDLE, true)); - SpdySerializedFrame priority_c( - spdy_util_.ConstructSpdyPriority(6, 4, IDLE, true)); - SpdySerializedFrame rst_a( - spdy_util_.ConstructSpdyRstStream(2, ERROR_CODE_REFUSED_STREAM)); - MockWrite writes[] = { - CreateMockWrite(req, 0), CreateMockWrite(priority_a, 2), - CreateMockWrite(priority_b, 6), CreateMockWrite(rst_a, 7), - CreateMockWrite(priority_c, 10), - }; - - SpdySerializedFrame push_a(spdy_util_.ConstructSpdyPush( - nullptr, 0, 2, 1, "https://www.example.org/a.dat")); - SpdySerializedFrame push_a_body(spdy_util_.ConstructSpdyDataFrame(2, false)); - // In ascii "0" < "a". We use it to verify that we properly handle std::map - // iterators inside. See http://crbug.com/443490 - SpdySerializedFrame push_b(spdy_util_.ConstructSpdyPush( - nullptr, 0, 4, 1, "https://www.example.org/0.dat")); - SpdySerializedFrame push_c(spdy_util_.ConstructSpdyPush( - nullptr, 0, 6, 1, "https://www.example.org/1.dat")); - SpdySerializedFrame push_c_body(spdy_util_.ConstructSpdyDataFrame(6, false)); - - MockRead reads[] = { - CreateMockRead(push_a, 1), - CreateMockRead(push_a_body, 3), - MockRead(ASYNC, ERR_IO_PENDING, 4), - CreateMockRead(push_b, 5), - MockRead(ASYNC, ERR_IO_PENDING, 8), - CreateMockRead(push_c, 9), - CreateMockRead(push_c_body, 11), - MockRead(ASYNC, ERR_IO_PENDING, 12), - MockRead(ASYNC, 0, 13) // EOF - }; - - SequencedSocketData data(reads, arraysize(reads), writes, arraysize(writes)); - session_deps_.socket_factory->AddSocketDataProvider(&data); - - AddSSLSocketData(); - - CreateNetworkSession(); - CreateSpdySession(); - - // Process the principal request, and the first push stream request & body. - base::WeakPtr<SpdyStream> spdy_stream = - CreateStreamSynchronously(SPDY_REQUEST_RESPONSE_STREAM, session_, - test_url_, MEDIUM, NetLogWithSource()); - test::StreamDelegateDoNothing delegate(spdy_stream); - spdy_stream->SetDelegate(&delegate); - - SpdyHeaderBlock headers(spdy_util_.ConstructGetHeaderBlock(kDefaultUrl)); - spdy_stream->SendRequestHeaders(std::move(headers), NO_MORE_DATA_TO_SEND); - - base::RunLoop().RunUntilIdle(); - - // Verify that there is one unclaimed push stream. - EXPECT_EQ(1u, session_->num_unclaimed_pushed_streams()); - EXPECT_EQ(1u, session_->count_unclaimed_pushed_streams_for_url( - GURL("https://www.example.org/a.dat"))); - - // Unclaimed push body consumed bytes from the session window. - EXPECT_EQ(kDefaultInitialWindowSize - kUploadDataSize, - session_->session_recv_window_size_); - EXPECT_EQ(0, session_->session_unacked_recv_window_bytes_); - - // Shift time to expire the push stream. Read the second HEADERS, - // and verify a RST_STREAM was written. - g_time_delta = base::TimeDelta::FromSeconds(300); - data.Resume(); - base::RunLoop().RunUntilIdle(); - - // Verify that the second pushed stream evicted the first pushed stream. - EXPECT_EQ(1u, session_->num_unclaimed_pushed_streams()); - EXPECT_EQ(1u, session_->count_unclaimed_pushed_streams_for_url( - GURL("https://www.example.org/0.dat"))); - - // Verify that the session window reclaimed the evicted stream body. - EXPECT_EQ(kDefaultInitialWindowSize, session_->session_recv_window_size_); - EXPECT_EQ(kUploadDataSize, session_->session_unacked_recv_window_bytes_); - - // Read the third PUSH, this will not be expired when the test tear down. - data.Resume(); - base::RunLoop().RunUntilIdle(); - - EXPECT_EQ(2u, session_->num_unclaimed_pushed_streams()); - EXPECT_EQ(1u, session_->count_unclaimed_pushed_streams_for_url( - GURL("https://www.example.org/1.dat"))); - - // Read and process EOF. - EXPECT_TRUE(session_); - data.Resume(); - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(session_); - histogram_tester.ExpectBucketCount("Net.SpdySession.PushedBytes", 12, 1); - histogram_tester.ExpectBucketCount("Net.SpdySession.PushedAndUnclaimedBytes", - 6, 1); -} - TEST_F(SpdySessionTest, FailedPing) { session_deps_.host_resolver->set_synchronous_mode(true); @@ -6076,8 +5957,8 @@ ssl_info.cert = ImportCertFromFile(GetTestCertsDirectory(), "spdy_pooling.pem"); ssl_info.unverified_cert = ssl_info.cert; - ssl_info.ct_cert_policy_compliance = - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS; + ssl_info.ct_policy_compliance = + ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS; ssl_info.is_issued_by_known_root = true; EXPECT_TRUE(SpdySession::CanPool(&tss, ssl_info, "www.example.org", @@ -6085,8 +5966,8 @@ const base::Time current_time(base::Time::Now()); const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000); - ssl_info.ct_cert_policy_compliance = - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS; + ssl_info.ct_policy_compliance = + ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS; // A different Expect-CT enabled host should not be allowed to pool. tss.AddExpectCT("mail.example.org", expiry, true, GURL()); @@ -6182,8 +6063,8 @@ ImportCertFromFile(GetTestCertsDirectory(), "spdy_pooling.pem"); ssl_info.is_issued_by_known_root = true; ssl_info.public_key_hashes.push_back(test::GetTestHashValue(1)); - ssl_info.ct_cert_policy_compliance = - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS; + ssl_info.ct_policy_compliance = + ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS; MockRequireCTDelegate require_ct_delegate; EXPECT_CALL(require_ct_delegate, IsCTRequiredForHost("www.example.org")) @@ -6208,8 +6089,8 @@ ImportCertFromFile(GetTestCertsDirectory(), "spdy_pooling.pem"); ssl_info.is_issued_by_known_root = true; ssl_info.public_key_hashes.push_back(test::GetTestHashValue(1)); - ssl_info.ct_cert_policy_compliance = - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS; + ssl_info.ct_policy_compliance = + ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS; MockRequireCTDelegate require_ct_delegate; EXPECT_CALL(require_ct_delegate, IsCTRequiredForHost("www.example.org")) @@ -6234,8 +6115,8 @@ ImportCertFromFile(GetTestCertsDirectory(), "spdy_pooling.pem"); ssl_info.is_issued_by_known_root = true; ssl_info.public_key_hashes.push_back(test::GetTestHashValue(1)); - ssl_info.ct_cert_policy_compliance = - ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS; + ssl_info.ct_policy_compliance = + ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS; MockRequireCTDelegate require_ct_delegate; EXPECT_CALL(require_ct_delegate, IsCTRequiredForHost("www.example.org"))
diff --git a/net/spdy/chromium/spdy_test_util_common.cc b/net/spdy/chromium/spdy_test_util_common.cc index 54883d1..3a0dc7a 100644 --- a/net/spdy/chromium/spdy_test_util_common.cc +++ b/net/spdy/chromium/spdy_test_util_common.cc
@@ -408,11 +408,11 @@ AllowAnyCertCTPolicyEnforcer() {} ~AllowAnyCertCTPolicyEnforcer() override = default; - ct::CertPolicyCompliance DoesConformToCertPolicy( + ct::CTPolicyCompliance CheckCompliance( X509Certificate* cert, const SCTList& verified_scts, const NetLogWithSource& net_log) override { - return ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS; + return ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS; } };
diff --git a/net/ssl/ssl_info.cc b/net/ssl/ssl_info.cc index e2f869e70..9d9c2f4 100644 --- a/net/ssl/ssl_info.cc +++ b/net/ssl/ssl_info.cc
@@ -43,8 +43,7 @@ public_key_hashes = info.public_key_hashes; pinning_failure_log = info.pinning_failure_log; signed_certificate_timestamps = info.signed_certificate_timestamps; - ct_compliance_details_available = info.ct_compliance_details_available; - ct_cert_policy_compliance = info.ct_cert_policy_compliance; + ct_policy_compliance = info.ct_policy_compliance; ct_policy_compliance_required = info.ct_policy_compliance_required; ocsp_result = info.ocsp_result; return *this; @@ -67,9 +66,8 @@ base::STLClearObject(&public_key_hashes); base::STLClearObject(&pinning_failure_log); base::STLClearObject(&signed_certificate_timestamps); - ct_compliance_details_available = false; - ct_cert_policy_compliance = - ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS; + ct_policy_compliance = + ct::CTPolicyCompliance::CT_POLICY_COMPLIANCE_DETAILS_NOT_AVAILABLE; ct_policy_compliance_required = false; ocsp_result = OCSPVerifyResult(); } @@ -84,8 +82,7 @@ ct_verify_result.scts.begin(), ct_verify_result.scts.end()); - ct_compliance_details_available = ct_verify_result.ct_policies_applied; - ct_cert_policy_compliance = ct_verify_result.cert_policy_compliance; + ct_policy_compliance = ct_verify_result.policy_compliance; ct_policy_compliance_required = ct_verify_result.policy_compliance_required; }
diff --git a/net/ssl/ssl_info.h b/net/ssl/ssl_info.h index 23c0e12..fd39bbc 100644 --- a/net/ssl/ssl_info.h +++ b/net/ssl/ssl_info.h
@@ -23,7 +23,7 @@ namespace ct { -enum class CertPolicyCompliance; +enum class CTPolicyCompliance; } // namespace ct @@ -128,20 +128,13 @@ // status. SignedCertificateTimestampAndStatusList signed_certificate_timestamps; - // True if Certificate Transparency policies were applied on this - // connection and results are available. If true, the field below - // (|ct_cert_policy_compliance|) will contain information about whether - // the connection complied with the policy and why the connection - // was considered non-compliant, if applicable. - bool ct_compliance_details_available; - // Whether the connection complied with the CT cert policy, and if - // not, why not. Only meaningful if |ct_compliance_details_available| - // is true. - ct::CertPolicyCompliance ct_cert_policy_compliance; + // not, why not. + ct::CTPolicyCompliance ct_policy_compliance; // True if the connection was required to comply with the CT cert policy. Only - // meaningful if |ct_compliance_details_available| is true. + // meaningful if |ct_policy_compliance| is not + // COMPLIANCE_DETAILS_NOT_AVAILABLE. bool ct_policy_compliance_required; // OCSP stapling details.
diff --git a/net/url_request/url_request_http_job.cc b/net/url_request/url_request_http_job.cc index 60eba4f..1b1afc07 100644 --- a/net/url_request/url_request_http_job.cc +++ b/net/url_request/url_request_http_job.cc
@@ -100,8 +100,10 @@ // Records per-request histograms relating to Certificate Transparency // compliance. void RecordCTHistograms(const net::SSLInfo& ssl_info) { - if (!ssl_info.ct_compliance_details_available) + if (ssl_info.ct_policy_compliance == + net::ct::CTPolicyCompliance::CT_POLICY_COMPLIANCE_DETAILS_NOT_AVAILABLE) { return; + } if (!ssl_info.is_issued_by_known_root) return; @@ -120,16 +122,16 @@ // percentage of overall requests that are CT-compliant. UMA_HISTOGRAM_ENUMERATION( "Net.CertificateTransparency.RequestComplianceStatus", - ssl_info.ct_cert_policy_compliance, - net::ct::CertPolicyCompliance::CERT_POLICY_MAX); + ssl_info.ct_policy_compliance, + net::ct::CTPolicyCompliance::CT_POLICY_MAX); // Record the CT compliance of each request which was required to be CT // compliant. This gives a picture of the sites that are supposed to be // compliant and how well they do at actually being compliant. if (ssl_info.ct_policy_compliance_required) { UMA_HISTOGRAM_ENUMERATION( "Net.CertificateTransparency.CTRequiredRequestComplianceStatus", - ssl_info.ct_cert_policy_compliance, - net::ct::CertPolicyCompliance::CERT_POLICY_MAX); + ssl_info.ct_policy_compliance, + net::ct::CTPolicyCompliance::CT_POLICY_MAX); } }
diff --git a/net/url_request/url_request_http_job_unittest.cc b/net/url_request/url_request_http_job_unittest.cc index 7360ea6..e0820ee 100644 --- a/net/url_request/url_request_http_job_unittest.cc +++ b/net/url_request/url_request_http_job_unittest.cc
@@ -1080,10 +1080,9 @@ ssl_socket_data.ssl_info.cert = ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"); ssl_socket_data.ssl_info.is_issued_by_known_root = true; - ssl_socket_data.ssl_info.ct_compliance_details_available = true; ssl_socket_data.ssl_info.ct_policy_compliance_required = false; - ssl_socket_data.ssl_info.ct_cert_policy_compliance = - ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS; + ssl_socket_data.ssl_info.ct_policy_compliance = + ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS; socket_factory_.AddSSLSocketDataProvider(&ssl_socket_data); @@ -1107,8 +1106,7 @@ histograms.ExpectUniqueSample( kCTComplianceHistogramName, - static_cast<int32_t>( - ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS), + static_cast<int32_t>(ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS), 1); // CTRequiredRequestComplianceStatus should *not* have been recorded because // it is only recorded for requests which are required to be compliant. @@ -1123,10 +1121,9 @@ ssl_socket_data.ssl_info.cert = ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"); ssl_socket_data.ssl_info.is_issued_by_known_root = false; - ssl_socket_data.ssl_info.ct_compliance_details_available = true; ssl_socket_data.ssl_info.ct_policy_compliance_required = false; - ssl_socket_data.ssl_info.ct_cert_policy_compliance = - ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS; + ssl_socket_data.ssl_info.ct_policy_compliance = + ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS; socket_factory_.AddSSLSocketDataProvider(&ssl_socket_data); @@ -1160,10 +1157,9 @@ ssl_socket_data.ssl_info.cert = ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"); ssl_socket_data.ssl_info.is_issued_by_known_root = true; - ssl_socket_data.ssl_info.ct_compliance_details_available = true; ssl_socket_data.ssl_info.ct_policy_compliance_required = true; - ssl_socket_data.ssl_info.ct_cert_policy_compliance = - ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS; + ssl_socket_data.ssl_info.ct_policy_compliance = + ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS; socket_factory_.AddSSLSocketDataProvider(&ssl_socket_data); @@ -1187,13 +1183,11 @@ histograms.ExpectUniqueSample( kCTComplianceHistogramName, - static_cast<int32_t>( - ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS), + static_cast<int32_t>(ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS), 1); histograms.ExpectUniqueSample( kCTRequiredHistogramName, - static_cast<int32_t>( - ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS), + static_cast<int32_t>(ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS), 1); } @@ -1205,10 +1199,9 @@ ssl_socket_data.ssl_info.cert = ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"); ssl_socket_data.ssl_info.is_issued_by_known_root = true; - ssl_socket_data.ssl_info.ct_compliance_details_available = true; ssl_socket_data.ssl_info.ct_policy_compliance_required = true; - ssl_socket_data.ssl_info.ct_cert_policy_compliance = - ct::CertPolicyCompliance::CERT_POLICY_NOT_DIVERSE_SCTS; + ssl_socket_data.ssl_info.ct_policy_compliance = + ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS; ssl_socket_data.ssl_info.cert_status = net::CERT_STATUS_DATE_INVALID; socket_factory_.AddSSLSocketDataProvider(&ssl_socket_data);
diff --git a/net/url_request/url_request_unittest.cc b/net/url_request/url_request_unittest.cc index f7c592d..00a2ebd 100644 --- a/net/url_request/url_request_unittest.cc +++ b/net/url_request/url_request_unittest.cc
@@ -6801,28 +6801,27 @@ uint32_t num_failures_; }; -// A CTPolicyEnforcer that returns a default CertPolicyCompliance value +// A CTPolicyEnforcer that returns a default CTPolicyCompliance value // for every certificate. class MockCTPolicyEnforcer : public CTPolicyEnforcer { public: MockCTPolicyEnforcer() - : default_result_( - ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS) {} + : default_result_(ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS) {} ~MockCTPolicyEnforcer() override {} - ct::CertPolicyCompliance DoesConformToCertPolicy( + ct::CTPolicyCompliance CheckCompliance( X509Certificate* cert, const SCTList& verified_scts, const NetLogWithSource& net_log) override { return default_result_; } - void set_default_result(ct::CertPolicyCompliance default_result) { + void set_default_result(ct::CTPolicyCompliance default_result) { default_result_ = default_result; } private: - ct::CertPolicyCompliance default_result_; + ct::CTPolicyCompliance default_result_; }; // Tests that Expect CT headers for the preload list are processed correctly. @@ -6855,7 +6854,7 @@ DoNothingCTVerifier ct_verifier; MockCTPolicyEnforcer ct_policy_enforcer; ct_policy_enforcer.set_default_result( - ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS); + ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS); TestNetworkDelegate network_delegate; // Use a MockHostResolver (which by default maps all hosts to @@ -6916,7 +6915,7 @@ DoNothingCTVerifier ct_verifier; MockCTPolicyEnforcer ct_policy_enforcer; ct_policy_enforcer.set_default_result( - ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS); + ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS); TestNetworkDelegate network_delegate; // Use a MockHostResolver (which by default maps all hosts to @@ -6978,7 +6977,7 @@ DoNothingCTVerifier ct_verifier; MockCTPolicyEnforcer ct_policy_enforcer; ct_policy_enforcer.set_default_result( - ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS); + ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS); TestNetworkDelegate network_delegate; // Use a MockHostResolver (which by default maps all hosts to @@ -10413,11 +10412,11 @@ AllowAnyCertCTPolicyEnforcer() = default; ~AllowAnyCertCTPolicyEnforcer() override = default; - ct::CertPolicyCompliance DoesConformToCertPolicy( + ct::CTPolicyCompliance CheckCompliance( X509Certificate* cert, const SCTList& verified_scts, const NetLogWithSource& net_log) override { - return ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS; + return ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS; } }; // SetupContext configures the URLRequestContext that will be used for making
diff --git a/printing/backend/print_backend_win.cc b/printing/backend/print_backend_win.cc index abdf03d..a3b7826 100644 --- a/printing/backend/print_backend_win.cc +++ b/printing/backend/print_backend_win.cc
@@ -30,7 +30,7 @@ HRESULT StreamOnHGlobalToString(IStream* stream, std::string* out) { DCHECK(stream); DCHECK(out); - HGLOBAL hdata = NULL; + HGLOBAL hdata = nullptr; HRESULT hr = GetHGlobalFromStream(stream, &hdata); if (SUCCEEDED(hr)) { DCHECK(hdata); @@ -45,16 +45,18 @@ const wchar_t* port, WORD id, std::vector<T>* result) { - int count = DeviceCapabilities(printer, port, id, NULL, NULL); + int count = DeviceCapabilities(printer, port, id, nullptr, nullptr); if (count <= 0) return; + std::vector<T> tmp; tmp.resize(count * 2); count = DeviceCapabilities(printer, port, id, - reinterpret_cast<LPTSTR>(tmp.data()), NULL); + reinterpret_cast<LPTSTR>(tmp.data()), nullptr); if (count <= 0) return; - CHECK_LE(count, base::checked_cast<int>(tmp.size())); + + CHECK_LE(static_cast<size_t>(count), tmp.size()); tmp.resize(count); result->swap(tmp); } @@ -105,31 +107,32 @@ caps->papers.push_back(paper); } - if (devmode) { - // Copy paper with the same ID as default paper. - if (devmode->dmFields & DM_PAPERSIZE) { - for (size_t i = 0; i < ids.size(); ++i) { - if (ids[i] == devmode->dmPaperSize) { - DCHECK_EQ(ids.size(), caps->papers.size()); - caps->default_paper = caps->papers[i]; - break; - } + if (!devmode) + return; + + // Copy paper with the same ID as default paper. + if (devmode->dmFields & DM_PAPERSIZE) { + for (size_t i = 0; i < ids.size(); ++i) { + if (ids[i] == devmode->dmPaperSize) { + DCHECK_EQ(ids.size(), caps->papers.size()); + caps->default_paper = caps->papers[i]; + break; } } + } - gfx::Size default_size; - if (devmode->dmFields & DM_PAPERWIDTH) - default_size.set_width(devmode->dmPaperWidth * kToUm); - if (devmode->dmFields & DM_PAPERLENGTH) - default_size.set_height(devmode->dmPaperLength * kToUm); + gfx::Size default_size; + if (devmode->dmFields & DM_PAPERWIDTH) + default_size.set_width(devmode->dmPaperWidth * kToUm); + if (devmode->dmFields & DM_PAPERLENGTH) + default_size.set_height(devmode->dmPaperLength * kToUm); - if (!default_size.IsEmpty()) { - // Reset default paper if |dmPaperWidth| or |dmPaperLength| does not - // match default paper set by. - if (default_size != caps->default_paper.size_um) - caps->default_paper = PrinterSemanticCapsAndDefaults::Paper(); - caps->default_paper.size_um = default_size; - } + if (!default_size.IsEmpty()) { + // Reset default paper if |dmPaperWidth| or |dmPaperLength| does not + // match default paper set by. + if (default_size != caps->default_paper.size_um) + caps->default_paper = PrinterSemanticCapsAndDefaults::Paper(); + caps->default_paper.size_um = default_size; } } @@ -140,16 +143,16 @@ std::vector<POINT> dpis; GetDeviceCapabilityArray(printer, port, DC_ENUMRESOLUTIONS, &dpis); - for (size_t i = 0; i < dpis.size() ; ++i) + for (size_t i = 0; i < dpis.size(); ++i) caps->dpis.push_back(gfx::Size(dpis[i].x, dpis[i].y)); - if (devmode) { - if ((devmode->dmFields & DM_PRINTQUALITY) && devmode->dmPrintQuality > 0) { - caps->default_dpi.SetSize(devmode->dmPrintQuality, - devmode->dmPrintQuality); - if (devmode->dmFields & DM_YRESOLUTION) { - caps->default_dpi.set_height(devmode->dmYResolution); - } + if (!devmode) + return; + + if ((devmode->dmFields & DM_PRINTQUALITY) && devmode->dmPrintQuality > 0) { + caps->default_dpi.SetSize(devmode->dmPrintQuality, devmode->dmPrintQuality); + if (devmode->dmFields & DM_YRESOLUTION) { + caps->default_dpi.set_height(devmode->dmYResolution); } } } @@ -254,7 +257,7 @@ PrinterSemanticCapsAndDefaults caps; std::unique_ptr<DEVMODE, base::FreeDeleter> user_settings = - CreateDevMode(printer_handle.Get(), NULL); + CreateDevMode(printer_handle.Get(), nullptr); if (user_settings) { if (user_settings->dmFields & DM_COLOR) caps.color_default = (user_settings->dmColor == DMCOLOR_COLOR); @@ -286,18 +289,18 @@ // Get printer capabilities. For more info see here: // http://msdn.microsoft.com/en-us/library/windows/desktop/dd183552(v=vs.85).aspx caps.color_changeable = - (DeviceCapabilities(name, port, DC_COLORDEVICE, NULL, NULL) == 1); + (DeviceCapabilities(name, port, DC_COLORDEVICE, nullptr, nullptr) == 1); caps.color_model = printing::COLOR; caps.bw_model = printing::GRAY; caps.duplex_capable = - (DeviceCapabilities(name, port, DC_DUPLEX, NULL, NULL) == 1); + (DeviceCapabilities(name, port, DC_DUPLEX, nullptr, nullptr) == 1); caps.collate_capable = - (DeviceCapabilities(name, port, DC_COLLATE, NULL, NULL) == 1); + (DeviceCapabilities(name, port, DC_COLLATE, nullptr, nullptr) == 1); caps.copies_capable = - (DeviceCapabilities(name, port, DC_COPIES, NULL, NULL) > 1); + (DeviceCapabilities(name, port, DC_COPIES, nullptr, nullptr) > 1); LoadPaper(name, port, user_settings.get(), &caps); LoadDpi(name, port, user_settings.get(), &caps); @@ -374,9 +377,8 @@ std::string PrintBackendWin::GetPrinterDriverInfo( const std::string& printer_name) { ScopedPrinterHandle printer; - if (!printer.OpenPrinter(base::UTF8ToWide(printer_name).c_str())) { + if (!printer.OpenPrinter(base::UTF8ToWide(printer_name).c_str())) return std::string(); - } return GetDriverInfo(printer.Get()); } @@ -388,7 +390,7 @@ // static scoped_refptr<PrintBackend> PrintBackend::CreateInstanceImpl( const base::DictionaryValue* print_backend_settings) { - return new PrintBackendWin; + return base::MakeRefCounted<PrintBackendWin>(); } } // namespace printing
diff --git a/printing/backend/win_helper.cc b/printing/backend/win_helper.cc index 0c7632d..7b15a9f2 100644 --- a/printing/backend/win_helper.cc +++ b/printing/backend/win_helper.cc
@@ -75,19 +75,22 @@ IXpsPrintJobStream** document_stream, IXpsPrintJobStream** print_ticket_stream); -PTOpenProviderProc g_open_provider_proc = NULL; -PTGetPrintCapabilitiesProc g_get_print_capabilities_proc = NULL; -PTConvertDevModeToPrintTicketProc g_convert_devmode_to_print_ticket_proc = NULL; -PTConvertPrintTicketToDevModeProc g_convert_print_ticket_to_devmode_proc = NULL; -PTMergeAndValidatePrintTicketProc g_merge_and_validate_print_ticket_proc = NULL; -PTReleaseMemoryProc g_release_memory_proc = NULL; -PTCloseProviderProc g_close_provider_proc = NULL; -StartXpsPrintJobProc g_start_xps_print_job_proc = NULL; +PTOpenProviderProc g_open_provider_proc = nullptr; +PTGetPrintCapabilitiesProc g_get_print_capabilities_proc = nullptr; +PTConvertDevModeToPrintTicketProc g_convert_devmode_to_print_ticket_proc = + nullptr; +PTConvertPrintTicketToDevModeProc g_convert_print_ticket_to_devmode_proc = + nullptr; +PTMergeAndValidatePrintTicketProc g_merge_and_validate_print_ticket_proc = + nullptr; +PTReleaseMemoryProc g_release_memory_proc = nullptr; +PTCloseProviderProc g_close_provider_proc = nullptr; +StartXpsPrintJobProc g_start_xps_print_job_proc = nullptr; HRESULT StreamFromPrintTicket(const std::string& print_ticket, IStream** stream) { DCHECK(stream); - HRESULT hr = CreateStreamOnHGlobal(NULL, TRUE, stream); + HRESULT hr = CreateStreamOnHGlobal(nullptr, TRUE, stream); if (FAILED(hr)) { return hr; } @@ -132,7 +135,7 @@ bool XPSModule::InitImpl() { HMODULE prntvpt_module = LoadLibrary(L"prntvpt.dll"); - if (prntvpt_module == NULL) + if (!prntvpt_module) return false; g_open_provider_proc = reinterpret_cast<PTOpenProviderProc>( GetProcAddress(prntvpt_module, "PTOpenProvider")); @@ -265,14 +268,14 @@ // crash. To protect ourselves from such drivers we make sure we always have // an extra CoInitialize (calls to CoInitialize/CoUninitialize are // refcounted). - HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED); + HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED); // If this succeeded we are done because the PTOpenProvider call will provide // the extra refcount on the apartment. If it failed because someone already // called CoInitializeEx with COINIT_APARTMENTTHREADED, we try the other model // to provide the additional refcount (since we don't know which model buggy // printer drivers will use). if (!SUCCEEDED(hr)) - hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); + hr = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); DCHECK(SUCCEEDED(hr)); initialized_ = true; } @@ -290,7 +293,7 @@ bool XPSPrintModule::InitImpl() { HMODULE xpsprint_module = LoadLibrary(L"xpsprint.dll"); - if (xpsprint_module == NULL) + if (!xpsprint_module) return false; g_start_xps_print_job_proc = reinterpret_cast<StartXpsPrintJobProc>( GetProcAddress(xpsprint_module, "StartXpsPrintJob")); @@ -394,13 +397,13 @@ const base::string16& printer_name, const std::string& print_ticket) { std::unique_ptr<DEVMODE, base::FreeDeleter> dev_mode; - printing::ScopedXPSInitializer xps_initializer; + ScopedXPSInitializer xps_initializer; if (!xps_initializer.initialized()) { // TODO(sanjeevr): Handle legacy proxy case (with no prntvpt.dll) return dev_mode; } - printing::ScopedPrinterHandle printer; + ScopedPrinterHandle printer; if (!printer.OpenPrinter(printer_name.c_str())) return dev_mode; @@ -409,22 +412,22 @@ if (FAILED(hr)) return dev_mode; - HPTPROVIDER provider = NULL; - hr = printing::XPSModule::OpenProvider(printer_name, 1, &provider); + HPTPROVIDER provider = nullptr; + hr = XPSModule::OpenProvider(printer_name, 1, &provider); if (SUCCEEDED(hr)) { ULONG size = 0; - DEVMODE* dm = NULL; + DEVMODE* dm = nullptr; // Use kPTJobScope, because kPTDocumentScope breaks duplex. - hr = printing::XPSModule::ConvertPrintTicketToDevMode( + hr = XPSModule::ConvertPrintTicketToDevMode( provider, pt_stream.Get(), kUserDefaultDevmode, kPTJobScope, &size, &dm, - NULL); + nullptr); if (SUCCEEDED(hr)) { // Correct DEVMODE using DocumentProperties. See documentation for // PTConvertPrintTicketToDevMode. dev_mode = CreateDevMode(printer.Get(), dm); - printing::XPSModule::ReleaseMemory(dm); + XPSModule::ReleaseMemory(dm); } - printing::XPSModule::CloseProvider(provider); + XPSModule::CloseProvider(provider); } return dev_mode; } @@ -434,7 +437,7 @@ const base::string16& printer_name, bool color) { std::unique_ptr<DEVMODE, base::FreeDeleter> default_ticket = - CreateDevMode(printer, NULL); + CreateDevMode(printer, nullptr); if (!default_ticket) return default_ticket; @@ -457,14 +460,14 @@ return default_ticket; // Need XPS for this workaround. - printing::ScopedXPSInitializer xps_initializer; + ScopedXPSInitializer xps_initializer; if (!xps_initializer.initialized()) return default_ticket; const char* xps_color = color ? kXpsTicketColor : kXpsTicketMonochrome; std::string xps_ticket = base::StringPrintf(kXpsTicketTemplate, xps_color); std::unique_ptr<DEVMODE, base::FreeDeleter> ticket = - printing::XpsTicketToDevMode(printer_name, xps_ticket); + XpsTicketToDevMode(printer_name, xps_ticket); if (!ticket) return default_ticket; @@ -477,8 +480,9 @@ std::unique_ptr<DEVMODE, base::FreeDeleter> CreateDevMode(HANDLE printer, DEVMODE* in) { - LONG buffer_size = DocumentProperties( - NULL, printer, const_cast<wchar_t*>(L""), NULL, NULL, 0); + wchar_t* device_name_ptr = const_cast<wchar_t*>(L""); + LONG buffer_size = DocumentProperties(nullptr, printer, device_name_ptr, + nullptr, nullptr, 0); if (buffer_size < static_cast<int>(sizeof(DEVMODE))) return nullptr; @@ -493,21 +497,21 @@ PrinterInfo5 info_5; if (!info_5.Init(printer)) return nullptr; - const wchar_t* name = info_5.get()->pPrinterName; - const wchar_t* port = info_5.get()->pPortName; // Check that valid paper sizes exist; some old drivers return no paper sizes // and crash in DocumentProperties if used with Win10. See crbug.com/679160, // crbug.com/724595 + const wchar_t* name = info_5.get()->pPrinterName; + const wchar_t* port = info_5.get()->pPortName; if (!PrinterHasValidPaperSize(name, port)) { return nullptr; } - if (DocumentProperties( - NULL, printer, const_cast<wchar_t*>(L""), out.get(), in, flags) != - IDOK) { + if (DocumentProperties(nullptr, printer, device_name_ptr, out.get(), in, + flags) != IDOK) { return nullptr; } + int size = out->dmSize; int extra_size = out->dmDriverExtra; CHECK_GE(buffer_size, size + extra_size); @@ -520,13 +524,9 @@ DEVMODE* in, HWND window, bool* canceled) { - LONG buffer_size = - DocumentProperties(window, - printer, - const_cast<wchar_t*>(printer_name.c_str()), - NULL, - NULL, - 0); + wchar_t* printer_name_ptr = const_cast<wchar_t*>(printer_name.c_str()); + LONG buffer_size = DocumentProperties(window, printer, printer_name_ptr, + nullptr, nullptr, 0); if (buffer_size < static_cast<int>(sizeof(DEVMODE))) return std::unique_ptr<DEVMODE, base::FreeDeleter>(); @@ -537,16 +537,13 @@ std::unique_ptr<DEVMODE, base::FreeDeleter> out( reinterpret_cast<DEVMODE*>(calloc(buffer_size, 1))); DWORD flags = (in ? (DM_IN_BUFFER) : 0) | DM_OUT_BUFFER | DM_IN_PROMPT; - LONG result = DocumentProperties(window, - printer, - const_cast<wchar_t*>(printer_name.c_str()), - out.get(), - in, - flags); + LONG result = DocumentProperties(window, printer, printer_name_ptr, out.get(), + in, flags); if (canceled) *canceled = (result == IDCANCEL); if (result != IDOK) return std::unique_ptr<DEVMODE, base::FreeDeleter>(); + int size = out->dmSize; int extra_size = out->dmDriverExtra; CHECK_GE(buffer_size, size + extra_size);
diff --git a/remoting/ios/app/app_delegate.h b/remoting/ios/app/app_delegate.h index ad33119..9bba76cc 100644 --- a/remoting/ios/app/app_delegate.h +++ b/remoting/ios/app/app_delegate.h
@@ -16,9 +16,6 @@ @property(strong, nonatomic) UIWindow* window; @property(class, strong, nonatomic, readonly) AppDelegate* instance; -// This will push the FAQ view controller onto the provided nav controller. -- (void)navigateToFAQs:(UINavigationController*)navigationController; - // This will push the Help Center view controller onto the provided nav // controller. - (void)navigateToHelpCenter:(UINavigationController*)navigationController;
diff --git a/remoting/ios/app/app_delegate.mm b/remoting/ios/app/app_delegate.mm index b93a270..2581fb5 100644 --- a/remoting/ios/app/app_delegate.mm +++ b/remoting/ios/app/app_delegate.mm
@@ -8,8 +8,6 @@ #import "remoting/ios/app/app_delegate.h" -#import "ios/third_party/material_components_ios/src/components/Dialogs/src/ColorThemer/MDCAlertColorThemer.h" -#import "ios/third_party/material_components_ios/src/components/Themes/src/MDCColorScheme.h" #import "remoting/ios/app/app_view_controller.h" #import "remoting/ios/app/first_launch_view_presenter.h" #import "remoting/ios/app/help_and_feedback.h" @@ -32,10 +30,6 @@ } @end -// TODO(nicholss): There is no FAQ page at the moment. -static NSString* const kFAQsUrl = - @"https://support.google.com/chrome/answer/1649523?co=GENIE.Platform%3DiOS"; - @implementation AppDelegate @synthesize window = _window; @@ -51,17 +45,13 @@ - (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions { [self launchRootViewController]; - - // TODO(yuweih): Follow up on this to see if it can be removed. There is a bug - // where the MDC alert is defaulting to white text on white background. - MDCBasicColorScheme* colorScheme = [[MDCBasicColorScheme alloc] - initWithPrimaryColor:RemotingTheme.flatButtonTextColor]; - [MDCAlertColorThemer applyColorScheme:colorScheme]; + [RemotingTheme applyColorSchemes]; return YES; } #ifndef NDEBUG +// Used by Chromium debug build to authenticate. - (BOOL)application:(UIApplication*)application handleOpenURL:(NSURL*)url { DCHECK([RemotingService.instance.authentication isKindOfClass:[RemotingOAuthAuthentication class]]); @@ -126,13 +116,6 @@ #pragma mark - AppDelegate -- (void)navigateToFAQs:(UINavigationController*)navigationController { - WebViewController* viewController = - [[WebViewController alloc] initWithUrl:kFAQsUrl - title:l10n_util::GetNSString(IDS_FAQS)]; - [navigationController pushViewController:viewController animated:YES]; -} - - (void)navigateToHelpCenter:(UINavigationController*)navigationController { [navigationController pushViewController:[[HelpViewController alloc] init] animated:YES];
diff --git a/remoting/ios/app/client_connection_view_controller.mm b/remoting/ios/app/client_connection_view_controller.mm index 19f2185..e8effdf 100644 --- a/remoting/ios/app/client_connection_view_controller.mm +++ b/remoting/ios/app/client_connection_view_controller.mm
@@ -559,16 +559,13 @@ } - (void)didProvidePin:(NSString*)pin createPairing:(BOOL)createPairing { - // TODO(nicholss): There is an open question if createPairing is supported on - // iOS. Need to fingure this out. [[NSNotificationCenter defaultCenter] postNotificationName:kHostSessionPinProvided object:self userInfo:@{ kHostSessionHostName : _remoteHostName, kHostSessionPin : pin, - kHostSessionCreatePairing : - [NSNumber numberWithBool:createPairing] + kHostSessionCreatePairing : @(createPairing) }]; }
diff --git a/remoting/ios/app/help_and_feedback.mm b/remoting/ios/app/help_and_feedback.mm index 856cdf3..5285b3c 100644 --- a/remoting/ios/app/help_and_feedback.mm +++ b/remoting/ios/app/help_and_feedback.mm
@@ -17,7 +17,7 @@ #pragma mark - Public - (void)presentFeedbackFlowWithContext:(NSString*)context { - NOTREACHED() << "This should be implemented by a subclass."; + NOTIMPLEMENTED() << "This should be implemented by a subclass."; } #pragma mark - Static Properties
diff --git a/remoting/ios/app/host_view_controller.mm b/remoting/ios/app/host_view_controller.mm index eba4817..9ad365c5 100644 --- a/remoting/ios/app/host_view_controller.mm +++ b/remoting/ios/app/host_view_controller.mm
@@ -319,8 +319,6 @@ #pragma mark - RemotingSettingsViewControllerDelegate - (void)setResizeToFit:(BOOL)resizeToFit { - // TODO(yuweih): Maybe we add a native screen size mimimum before enabling - // this option? This doesn't work well for smaller screens. Ask Jon. _settings.shouldResizeHostToFit = resizeToFit; [self resizeHostToFitIfNeeded]; }
diff --git a/remoting/ios/app/remoting_menu_view_controller.mm b/remoting/ios/app/remoting_menu_view_controller.mm index d7c59fb..ff5bb4d5f 100644 --- a/remoting/ios/app/remoting_menu_view_controller.mm +++ b/remoting/ios/app/remoting_menu_view_controller.mm
@@ -11,10 +11,12 @@ #import "ios/third_party/material_components_ios/src/components/AppBar/src/MaterialAppBar.h" #import "ios/third_party/material_components_ios/src/components/Buttons/src/MaterialButtons.h" #import "remoting/ios/app/remoting_theme.h" +#import "remoting/ios/app/side_menu_items.h" #import "remoting/ios/facade/remoting_authentication.h" #import "remoting/ios/facade/remoting_service.h" #include "base/strings/stringprintf.h" +#include "base/strings/sys_string_conversions.h" #include "google_apis/google_api_keys.h" #include "net/base/escape.h" #include "remoting/base/string_resources.h" @@ -28,6 +30,7 @@ [UIColor colorWithRed:0.f green:0.67f blue:0.55f alpha:1.f]; namespace { + const char kChromotingAuthScopeValues[] = "https://www.googleapis.com/auth/chromoting " "https://www.googleapis.com/auth/googletalk " @@ -56,23 +59,18 @@ @interface RemotingMenuViewController () { MDCAppBar* _appBar; - NSMutableArray* _content; + NSArray<NSArray<SideMenuItem*>*>* _content; } @end // This is the chromium version of the menu view controller. This will // launch a web view to login and collect an oauth token to be able to login to -// the app without the standard google login flow. +// the app without the standard google login flow. It also loads and shows all +// other menu items from SideMenuItemsProvider. // -// This class is majority boiler plate code to get a collection view. -// It will be replaced with a sidebar-like view in the future, but in -// chromium this is how we get an oauth token to login to the app. +// The official app's implementation is in //ios_internal. // // Note: this class is not localized, it will not be shipped to production. -// -// TODO(nicholss): This class needs to be split into a shareable view -// for chromium and prod to share. -// @implementation RemotingMenuViewController - (id)init { @@ -117,23 +115,38 @@ self.styler.cellStyle = MDCCollectionViewCellStyleCard; - _content = [NSMutableArray array]; - [_content addObject:@[ - l10n_util::GetNSString(IDS_SIGN_IN_BUTTON), - l10n_util::GetNSString(IDS_SIGN_OUT_BUTTON) - ]]; + // Add the account management section to the beginning of the content. + __weak __typeof(self) weakSelf = self; + NSArray<SideMenuItem*>* accountManagementSection = @[ + [[SideMenuItem alloc] + initWithTitle:l10n_util::GetNSString(IDS_SIGN_IN_BUTTON) + icon:nil + action:^{ + [weakSelf didTapGetAccessCode]; + }], + [[SideMenuItem alloc] + initWithTitle:l10n_util::GetNSString(IDS_SIGN_OUT_BUTTON) + icon:nil + action:^{ + [weakSelf didTapLogout]; + }] + ]; + NSMutableArray<NSArray<SideMenuItem*>*>* mutableContent = + [NSMutableArray arrayWithArray:SideMenuItemsProvider.sideMenuItems]; + [mutableContent insertObject:accountManagementSection atIndex:0]; + _content = mutableContent; } #pragma mark - UICollectionViewDataSource - (NSInteger)numberOfSectionsInCollectionView: (UICollectionView*)collectionView { - return (NSInteger)[_content count]; + return _content.count; } - (NSInteger)collectionView:(UICollectionView*)collectionView numberOfItemsInSection:(NSInteger)section { - return (NSInteger)[_content[(NSUInteger)section] count]; + return _content[section].count; } - (UICollectionViewCell*)collectionView:(UICollectionView*)collectionView @@ -141,30 +154,9 @@ MDCCollectionViewTextCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:kReusableIdentifierItem forIndexPath:indexPath]; - cell.textLabel.text = - _content[(NSUInteger)indexPath.section][(NSUInteger)indexPath.item]; - - if (indexPath.section == 0 && indexPath.item == 0) { - MDCRaisedButton* accessCodeButton = [[MDCRaisedButton alloc] init]; - [accessCodeButton setTitle:@"Get Access Code" - forState:UIControlStateNormal]; - [accessCodeButton sizeToFit]; - [accessCodeButton addTarget:self - action:@selector(didTapGetAccessCode:) - forControlEvents:UIControlEventTouchUpInside]; - accessCodeButton.translatesAutoresizingMaskIntoConstraints = NO; - cell.accessoryView = accessCodeButton; - } else if (indexPath.section == 0 && indexPath.item == 1) { - MDCRaisedButton* logoutButton = [[MDCRaisedButton alloc] init]; - [logoutButton setTitle:l10n_util::GetNSString(IDS_SIGN_OUT_BUTTON) - forState:UIControlStateNormal]; - [logoutButton sizeToFit]; - [logoutButton addTarget:self - action:@selector(didTapLogout:) - forControlEvents:UIControlEventTouchUpInside]; - logoutButton.translatesAutoresizingMaskIntoConstraints = NO; - cell.accessoryView = logoutButton; - } + SideMenuItem* item = _content[indexPath.section][indexPath.item]; + cell.textLabel.text = item.title; + cell.imageView.image = item.icon; return cell; } @@ -185,12 +177,24 @@ return supplementaryView; } +#pragma mark - UICollectionViewDelegate + +- (void)collectionView:(UICollectionView*)collectionView + didSelectItemAtIndexPath:(NSIndexPath*)indexPath { + [super collectionView:collectionView didSelectItemAtIndexPath:indexPath]; + _content[indexPath.section][indexPath.item].action(); +} + #pragma mark - <UICollectionViewDelegateFlowLayout> - (CGSize)collectionView:(UICollectionView*)collectionView layout: (UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section { + // Only show the title if it's the account manangement section. + if (section != 0) { + return CGSizeZero; + } return CGSizeMake(collectionView.bounds.size.width, MDCCellDefaultOneLineHeight); } @@ -201,10 +205,8 @@ [self dismissViewControllerAnimated:YES completion:nil]; } -- (void)didTapGetAccessCode:(id)sender { - NSString* authUri = - [NSString stringWithCString:GetAuthorizationCodeUri().c_str() - encoding:[NSString defaultCStringEncoding]]; +- (void)didTapGetAccessCode { + NSString* authUri = base::SysUTF8ToNSString(GetAuthorizationCodeUri()); if (@available(iOS 10, *)) { [[UIApplication sharedApplication] openURL:[NSURL URLWithString:authUri] options:@{} @@ -217,7 +219,7 @@ #endif } -- (void)didTapLogout:(id)sender { +- (void)didTapLogout { [RemotingService.instance.authentication logout]; }
diff --git a/remoting/ios/app/remoting_theme.h b/remoting/ios/app/remoting_theme.h index 8cd274e5..f21abd63 100644 --- a/remoting/ios/app/remoting_theme.h +++ b/remoting/ios/app/remoting_theme.h
@@ -10,6 +10,9 @@ // Styles to be used when rendering the iOS client's UI. @interface RemotingTheme : NSObject +// Applys default color schemes on elements like buttons and alerts. ++ (void)applyColorSchemes; + // Colors @property(class, nonatomic, readonly) UIColor* buttonBackgroundColor;
diff --git a/remoting/ios/app/remoting_theme.mm b/remoting/ios/app/remoting_theme.mm index d16613e..78a343e3 100644 --- a/remoting/ios/app/remoting_theme.mm +++ b/remoting/ios/app/remoting_theme.mm
@@ -8,11 +8,20 @@ #import "remoting/ios/app/remoting_theme.h" +#import "ios/third_party/material_components_ios/src/components/Dialogs/src/ColorThemer/MDCAlertColorThemer.h" +#import "ios/third_party/material_components_ios/src/components/Themes/src/MDCColorScheme.h" + #include "remoting/base/string_resources.h" #include "ui/base/l10n/l10n_util.h" @implementation RemotingTheme ++ (void)applyColorSchemes { + MDCBasicColorScheme* colorScheme = [[MDCBasicColorScheme alloc] + initWithPrimaryColor:RemotingTheme.flatButtonTextColor]; + [MDCAlertColorThemer applyColorScheme:colorScheme]; +} + #pragma mark - Colors + (UIColor*)firstLaunchViewBackgroundColor {
diff --git a/remoting/ios/app/resources/BUILD.gn b/remoting/ios/app/resources/BUILD.gn index da227d7..b1e7137 100644 --- a/remoting/ios/app/resources/BUILD.gn +++ b/remoting/ios/app/resources/BUILD.gn
@@ -43,13 +43,6 @@ ] } -# TODO(yuweih): This target is used to exclude material design imagesets from -# the internal app's source set, that are already pulled-in by other deps of the -# internal app. We will need to redesign these once crbug.com/734054 is -# resolved. -group("system_icons") { -} - group("launchscreen_assets") { public_deps = [ ":launchscreen_app_logo",
diff --git a/remoting/ios/app/settings/remoting_settings_view_controller.mm b/remoting/ios/app/settings/remoting_settings_view_controller.mm index c2bd6cf..f2627ea 100644 --- a/remoting/ios/app/settings/remoting_settings_view_controller.mm +++ b/remoting/ios/app/settings/remoting_settings_view_controller.mm
@@ -72,7 +72,6 @@ forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:UICollectionElementKindSectionHeader]; - // TODO(nicholss): All of these strings need to be setup for l18n. _sections = @[ l10n_util::GetNSString(IDS_DISPLAY_OPTIONS), l10n_util::GetNSString(IDS_MOUSE_OPTIONS), @@ -234,22 +233,6 @@ __weak RemotingSettingsViewController* weakSelf = self; -// We are not going to support the shrink option for now. -#if 0 - SettingOption* shrinkOption = [[SettingOption alloc] init]; - shrinkOption.title = l10n_util::GetNSString(IDS_SHRINK_TO_FIT); - // TODO(nicholss): I think this text changes based on value. Confirm. - shrinkOption.subtext = l10n_util::GetNSString(IDS_SHRINK_TO_FIT_SUBTITLE); - shrinkOption.style = OptionCheckbox; - shrinkOption.checked = NO; - __weak SettingOption* weakShrinkOption = shrinkOption; - shrinkOption.action = ^{ - if ([weakSelf.delegate respondsToSelector:@selector(setShrinkToFit:)]) { - [weakSelf.delegate setShrinkToFit:weakShrinkOption.checked]; - } - }; -#endif - SettingOption* resizeOption = [[SettingOption alloc] init]; resizeOption.title = l10n_util::GetNSString(IDS_RESIZE_TO_CLIENT); // TODO(nicholss): I think this text changes based on value. Confirm.
diff --git a/remoting/ios/app/side_menu_items.h b/remoting/ios/app/side_menu_items.h index fcd67c7..093c623 100644 --- a/remoting/ios/app/side_menu_items.h +++ b/remoting/ios/app/side_menu_items.h
@@ -12,6 +12,10 @@ // Represents an item on the side menu. @interface SideMenuItem : NSObject +- (instancetype)initWithTitle:(NSString*)title + icon:(UIImage*)icon + action:(SideMenuItemAction)action; + @property(nonatomic, readonly) NSString* title; @property(nonatomic, readonly) UIImage* icon; @property(nonatomic, readonly) SideMenuItemAction action;
diff --git a/remoting/ios/app/side_menu_items.mm b/remoting/ios/app/side_menu_items.mm index aba7479..3da806d 100644 --- a/remoting/ios/app/side_menu_items.mm +++ b/remoting/ios/app/side_menu_items.mm
@@ -20,14 +20,6 @@ #pragma mark - SideMenuItem -@interface SideMenuItem () - -- (instancetype)initWithTitle:(NSString*)title - icon:(UIImage*)icon - action:(SideMenuItemAction)action; - -@end - @implementation SideMenuItem @synthesize title = _title;
diff --git a/remoting/ios/domain/user_info.h b/remoting/ios/domain/user_info.h index 9b381f1..650730b 100644 --- a/remoting/ios/domain/user_info.h +++ b/remoting/ios/domain/user_info.h
@@ -8,7 +8,6 @@ #import <Foundation/Foundation.h> // A detail record for a Remoting User. -// TODO(nicholss): This is not the final object yet. @interface UserInfo : NSObject @property(nonatomic, copy) NSString* userId;
diff --git a/remoting/ios/facade/remoting_oauth_authentication.mm b/remoting/ios/facade/remoting_oauth_authentication.mm index 39cbc52..5b32998 100644 --- a/remoting/ios/facade/remoting_oauth_authentication.mm +++ b/remoting/ios/facade/remoting_oauth_authentication.mm
@@ -123,7 +123,6 @@ std::string(base::SysNSStringToUTF8(authorizationCode)), base::BindBlockArc( ^(const std::string& user_email, const std::string& refresh_token) { - // TODO(nicholss): Do something with these new creds. VLOG(1) << "New Creds: " << user_email << " " << refresh_token; UserInfo* user = [[UserInfo alloc] init]; user.userEmail = base::SysUTF8ToNSString(user_email); @@ -161,8 +160,8 @@ } - (void)callbackWithAccessToken:(AccessTokenCallback)onAccessToken { - // TODO(nicholss): Be careful here since a failure to reset onAccessToken - // will end up with retain cycle and memory leakage. + // Be careful here since a failure to reset onAccessToken will end up with + // retain cycle and memory leakage. if (_tokenGetter) { _tokenGetter->CallWithToken(base::BindBlockArc( ^(remoting::OAuthTokenGetter::Status status,
diff --git a/remoting/ios/facade/remoting_service.mm b/remoting/ios/facade/remoting_service.mm index 45a422e..33fdfa1 100644 --- a/remoting/ios/facade/remoting_service.mm +++ b/remoting/ios/facade/remoting_service.mm
@@ -73,7 +73,6 @@ // TODO(yuweih): Maybe better to just cancel the previous request. _hostListState = HostListStateNotFetched; _lastFetchFailureReason = HostListFetchFailureReasonNoFailure; - // TODO(nicholss): This might need a pointer back to the service. _clientRuntimeDelegate = new remoting::IosClientRuntimeDelegate(); [self runtime]->SetDelegate(_clientRuntimeDelegate);
diff --git a/remoting/ios/keychain_wrapper.h b/remoting/ios/keychain_wrapper.h index 51a57d0..60f909d 100644 --- a/remoting/ios/keychain_wrapper.h +++ b/remoting/ios/keychain_wrapper.h
@@ -16,8 +16,6 @@ NSString* secret); // Class to abstract the details from how iOS wants to write to the keychain. -// TODO(nicholss): This will have to be futher refactored when we integrate -// with the private Google auth. @interface KeychainWrapper : NSObject // Save a refresh token to the keychain.
diff --git a/remoting/ios/session/remoting_client.mm b/remoting/ios/session/remoting_client.mm index a32c1a2..cbf0854 100644 --- a/remoting/ios/session/remoting_client.mm +++ b/remoting/ios/session/remoting_client.mm
@@ -113,8 +113,7 @@ info.pairing_secret = ""; } - // TODO(nicholss): I am not sure about the following fields yet. - // info.capabilities = + info.capabilities = ""; if ([RemotingPreferences.instance boolForFlag:RemotingFlagUseWebRTC]) { info.flags = "useWebrtc"; [MDCSnackbarManager
diff --git a/remoting/protocol/ssl_hmac_channel_authenticator.cc b/remoting/protocol/ssl_hmac_channel_authenticator.cc index a093cc3..226c9283 100644 --- a/remoting/protocol/ssl_hmac_channel_authenticator.cc +++ b/remoting/protocol/ssl_hmac_channel_authenticator.cc
@@ -73,11 +73,11 @@ IgnoresCTPolicyEnforcer() = default; ~IgnoresCTPolicyEnforcer() override = default; - net::ct::CertPolicyCompliance DoesConformToCertPolicy( + net::ct::CTPolicyCompliance CheckCompliance( net::X509Certificate* cert, const net::SCTList& verified_scts, const net::NetLogWithSource& net_log) override { - return net::ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS; + return net::ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS; } };
diff --git a/sandbox/linux/BUILD.gn b/sandbox/linux/BUILD.gn index 4b321e2..8c9cf2c 100644 --- a/sandbox/linux/BUILD.gn +++ b/sandbox/linux/BUILD.gn
@@ -112,6 +112,7 @@ ":sandbox", ":sandbox_linux_test_utils", "//base", + "//base/third_party/dynamic_annotations", "//testing/gtest", ] @@ -250,6 +251,7 @@ deps = [ ":sandbox_services", "//base", + "//base/third_party/dynamic_annotations", ] if (is_nacl_nonsfi) { @@ -374,6 +376,7 @@ ] deps = [ "//base", + "//base/third_party/dynamic_annotations", ] if (compile_credentials || is_nacl_nonsfi) { @@ -457,6 +460,7 @@ deps = [ ":sandbox_services", "//base", + "//base/third_party/dynamic_annotations", ] if (is_nacl_nonsfi) {
diff --git a/sandbox/linux/seccomp-bpf/sandbox_bpf.cc b/sandbox/linux/seccomp-bpf/sandbox_bpf.cc index c61e8e7..9ff79d7 100644 --- a/sandbox/linux/seccomp-bpf/sandbox_bpf.cc +++ b/sandbox/linux/seccomp-bpf/sandbox_bpf.cc
@@ -15,6 +15,7 @@ #include "base/logging.h" #include "base/macros.h" #include "base/posix/eintr_wrapper.h" +#include "base/third_party/dynamic_annotations/dynamic_annotations.h" #include "base/third_party/valgrind/valgrind.h" #include "sandbox/linux/bpf_dsl/bpf_dsl.h" #include "sandbox/linux/bpf_dsl/codegen.h" @@ -36,8 +37,6 @@ namespace { -bool IsRunningOnValgrind() { return RUNNING_ON_VALGRIND; } - // Check if the kernel supports seccomp-filter (a.k.a. seccomp mode 2) via // prctl(). bool KernelSupportsSeccompBPF() { @@ -125,7 +124,7 @@ bool SandboxBPF::SupportsSeccompSandbox(SeccompLevel level) { // Never pretend to support seccomp with Valgrind, as it // throws the tool off. - if (IsRunningOnValgrind()) { + if (RunningOnValgrind()) { return false; }
diff --git a/sandbox/linux/seccomp-bpf/sandbox_bpf_test_runner.cc b/sandbox/linux/seccomp-bpf/sandbox_bpf_test_runner.cc index 1317609..5f59cbb 100644 --- a/sandbox/linux/seccomp-bpf/sandbox_bpf_test_runner.cc +++ b/sandbox/linux/seccomp-bpf/sandbox_bpf_test_runner.cc
@@ -9,6 +9,7 @@ #include <memory> #include "base/logging.h" +#include "base/third_party/dynamic_annotations/dynamic_annotations.h" #include "sandbox/linux/bpf_dsl/policy.h" #include "sandbox/linux/seccomp-bpf/die.h" #include "sandbox/linux/seccomp-bpf/sandbox_bpf.h" @@ -45,7 +46,7 @@ printf("This BPF test is not fully running in this configuration!\n"); // Android and Valgrind are the only configurations where we accept not // having kernel BPF support. - if (!IsAndroid() && !IsRunningOnValgrind()) { + if (!IsAndroid() && !RunningOnValgrind()) { const bool seccomp_bpf_is_supported = false; SANDBOX_ASSERT(seccomp_bpf_is_supported); }
diff --git a/sandbox/linux/services/credentials.cc b/sandbox/linux/services/credentials.cc index 0a0b6eb2..d97f094 100644 --- a/sandbox/linux/services/credentials.cc +++ b/sandbox/linux/services/credentials.cc
@@ -23,6 +23,7 @@ #include "base/macros.h" #include "base/posix/eintr_wrapper.h" #include "base/process/launch.h" +#include "base/third_party/dynamic_annotations/dynamic_annotations.h" #include "base/third_party/valgrind/valgrind.h" #include "build/build_config.h" #include "sandbox/linux/services/namespace_utils.h" @@ -36,8 +37,6 @@ namespace { -bool IsRunningOnValgrind() { return RUNNING_ON_VALGRIND; } - const int kExitSuccess = 0; #if defined(__clang__) @@ -259,7 +258,7 @@ bool Credentials::CanCreateProcessInNewUserNS() { // Valgrind will let clone(2) pass-through, but doesn't support unshare(), // so always consider UserNS unsupported there. - if (IsRunningOnValgrind()) { + if (RunningOnValgrind()) { return false; }
diff --git a/sandbox/linux/services/namespace_utils.cc b/sandbox/linux/services/namespace_utils.cc index 97add26..83749ad 100644 --- a/sandbox/linux/services/namespace_utils.cc +++ b/sandbox/linux/services/namespace_utils.cc
@@ -20,15 +20,12 @@ #include "base/posix/eintr_wrapper.h" #include "base/process/launch.h" #include "base/strings/safe_sprintf.h" +#include "base/third_party/dynamic_annotations/dynamic_annotations.h" #include "base/third_party/valgrind/valgrind.h" namespace sandbox { namespace { -bool IsRunningOnValgrind() { - return RUNNING_ON_VALGRIND; -} - const char kProcSelfSetgroups[] = "/proc/self/setgroups"; } // namespace @@ -57,7 +54,7 @@ bool NamespaceUtils::KernelSupportsUnprivilegedNamespace(int type) { // Valgrind will let clone(2) pass-through, but doesn't support unshare(), // so always consider namespaces unsupported there. - if (IsRunningOnValgrind()) { + if (RunningOnValgrind()) { return false; }
diff --git a/sandbox/linux/services/thread_helpers_unittests.cc b/sandbox/linux/services/thread_helpers_unittests.cc index fe1080b..78e6d83 100644 --- a/sandbox/linux/services/thread_helpers_unittests.cc +++ b/sandbox/linux/services/thread_helpers_unittests.cc
@@ -14,6 +14,7 @@ #include "base/macros.h" #include "base/posix/eintr_wrapper.h" #include "base/process/process_metrics.h" +#include "base/third_party/dynamic_annotations/dynamic_annotations.h" #include "base/threading/platform_thread.h" #include "base/threading/thread.h" #include "build/build_config.h" @@ -30,7 +31,7 @@ #if !defined(THREAD_SANITIZER) int GetRaceTestIterations() { - if (IsRunningOnValgrind()) { + if (RunningOnValgrind()) { return 2; } else { return 1000;
diff --git a/sandbox/linux/syscall_broker/broker_file_permission.cc b/sandbox/linux/syscall_broker/broker_file_permission.cc index 3907344..3947145 100644 --- a/sandbox/linux/syscall_broker/broker_file_permission.cc +++ b/sandbox/linux/syscall_broker/broker_file_permission.cc
@@ -14,7 +14,6 @@ #include "sandbox/linux/syscall_broker/broker_common.h" namespace sandbox { - namespace syscall_broker { // Async signal safe @@ -52,25 +51,21 @@ // methods are async signal safe in common standard libs. // TODO(leecam): remove dependency on std::string bool BrokerFilePermission::MatchPath(const char* requested_filename) const { - const char* path = path_.c_str(); - if ((recursive_ && strncmp(requested_filename, path, strlen(path)) == 0)) { - // Note: This prefix match will allow any path under the whitelisted - // path, for any number of directory levels. E.g. if the whitelisted - // path is /good/ then the following will be permitted by the policy. - // /good/file1 - // /good/folder/file2 - // /good/folder/folder2/file3 - // If an attacker could make 'folder' a symlink to ../../ they would have - // access to the entire filesystem. - // Whitelisting with multiple depths is useful, e.g /proc/ but - // the system needs to ensure symlinks can not be created! - // That said if an attacker can convert any of the absolute paths - // to a symlink they can control any file on the system also. - return true; - } else if (strcmp(requested_filename, path) == 0) { - return true; - } - return false; + // Note: This recursive match will allow any path under the whitelisted + // path, for any number of directory levels. E.g. if the whitelisted + // path is /good/ then the following will be permitted by the policy. + // /good/file1 + // /good/folder/file2 + // /good/folder/folder2/file3 + // If an attacker could make 'folder' a symlink to ../../ they would have + // access to the entire filesystem. + // Whitelisting with multiple depths is useful, e.g /proc/ but + // the system needs to ensure symlinks can not be created! + // That said if an attacker can convert any of the absolute paths + // to a symlink they can control any file on the system also. + return recursive_ + ? strncmp(requested_filename, path_.c_str(), path_.length()) == 0 + : strcmp(requested_filename, path_.c_str()) == 0; } // Async signal safe. @@ -82,45 +77,39 @@ const char** file_to_access) const { // First, check if |mode| is existence, ability to read or ability // to write. We do not support X_OK. - if (mode != F_OK && mode & ~(R_OK | W_OK)) { + if (mode != F_OK && mode & ~(R_OK | W_OK)) return false; - } if (!ValidatePath(requested_filename)) return false; - if (!MatchPath(requested_filename)) { + if (!MatchPath(requested_filename)) return false; - } + bool allowed = false; switch (mode) { case F_OK: - if (allow_read_ || allow_write_) - allowed = true; + allowed = allow_read_ || allow_write_; break; case R_OK: - if (allow_read_) - allowed = true; + allowed = allow_read_; break; case W_OK: - if (allow_write_) - allowed = true; + allowed = allow_write_; break; case R_OK | W_OK: - if (allow_read_ && allow_write_) - allowed = true; + allowed = allow_read_ && allow_write_; break; default: - return false; + break; } + if (!allowed) + return false; - if (allowed && file_to_access) { - if (!recursive_) - *file_to_access = path_.c_str(); - else - *file_to_access = requested_filename; - } - return allowed; + if (file_to_access) + *file_to_access = recursive_ ? requested_filename : path_.c_str(); + + return true; } // Async signal safe. @@ -134,9 +123,8 @@ if (!ValidatePath(requested_filename)) return false; - if (!MatchPath(requested_filename)) { + if (!MatchPath(requested_filename)) return false; - } // First, check the access mode is valid. const int access_mode = flags & O_ACCMODE; @@ -165,8 +153,8 @@ return false; } - // If this file is to be unlinked, ensure it's created. - if (unlink_ && !(flags & O_CREAT)) { + // If this file is to be temporary, ensure it's created. + if (temporary_only_ && !(flags & O_CREAT)) { return false; } @@ -178,7 +166,6 @@ // Now check that all the flags are known to us. const int creation_and_status_flags = flags & ~O_ACCMODE; - const int known_flags = O_APPEND | O_ASYNC | O_CLOEXEC | O_CREAT | O_DIRECT | O_DIRECTORY | O_EXCL | O_LARGEFILE | O_NOATIME | O_NOCTTY | O_NOFOLLOW | O_NONBLOCK | O_NDELAY | @@ -190,55 +177,49 @@ if (has_unknown_flags) return false; - if (file_to_open) { - if (!recursive_) - *file_to_open = path_.c_str(); - else - *file_to_open = requested_filename; - } + if (file_to_open) + *file_to_open = recursive_ ? requested_filename : path_.c_str(); + if (unlink_after_open) - *unlink_after_open = unlink_; + *unlink_after_open = temporary_only_; return true; } const char* BrokerFilePermission::GetErrorMessageForTests() { - static char kInvalidBrokerFileString[] = "Invalid BrokerFilePermission"; - return kInvalidBrokerFileString; + return "Invalid BrokerFilePermission"; } BrokerFilePermission::BrokerFilePermission(const std::string& path, bool recursive, - bool unlink, + bool temporary_only, bool allow_read, bool allow_write, bool allow_create) : path_(path), recursive_(recursive), - unlink_(unlink), + temporary_only_(temporary_only), allow_read_(allow_read), allow_write_(allow_write), allow_create_(allow_create) { - // Validate this permission and die if invalid! - // Must have enough length for a '/' CHECK(path_.length() > 0) << GetErrorMessageForTests(); + // Whitelisted paths must be absolute. CHECK(path_[0] == '/') << GetErrorMessageForTests(); - // Don't allow unlinking on creation without create permission - if (unlink_) { + // Don't allow temporary creation without create permission + if (temporary_only_) CHECK(allow_create) << GetErrorMessageForTests(); - } + + // Recursive paths must have a trailing slash, absolutes must not. const char last_char = *(path_.rbegin()); - // Recursive paths must have a trailing slash - if (recursive_) { + if (recursive_) CHECK(last_char == '/') << GetErrorMessageForTests(); - } else { + else CHECK(last_char != '/') << GetErrorMessageForTests(); - } } } // namespace syscall_broker -} // namespace sandbox \ No newline at end of file +} // namespace sandbox
diff --git a/sandbox/linux/syscall_broker/broker_file_permission.h b/sandbox/linux/syscall_broker/broker_file_permission.h index 2431145..b39ac6c 100644 --- a/sandbox/linux/syscall_broker/broker_file_permission.h +++ b/sandbox/linux/syscall_broker/broker_file_permission.h
@@ -11,7 +11,6 @@ #include "sandbox/sandbox_export.h" namespace sandbox { - namespace syscall_broker { // BrokerFilePermission defines a path for whitelisting. @@ -50,11 +49,7 @@ return BrokerFilePermission(path, true, false, true, true, true); } - static BrokerFilePermission ReadWriteCreateUnlink(const std::string& path) { - return BrokerFilePermission(path, false, true, true, true, true); - } - - static BrokerFilePermission ReadWriteCreateUnlinkRecursive( + static BrokerFilePermission ReadWriteCreateTemporaryRecursive( const std::string& path) { return BrokerFilePermission(path, true, true, true, true, true); } @@ -65,16 +60,17 @@ // the |requested_filename| in the case of a recursive match, // or a pointer the matched path in the whitelist if an absolute // match. - // If not NULL |unlink_after_open| is set to point to true if the - // caller should unlink the path after opening. + // If not NULL, |unlink_after_open| is set to point to true if the + // caller is required to unlink the path after opening. // Async signal safe if |file_to_open| is NULL. bool CheckOpen(const char* requested_filename, int flags, const char** file_to_open, bool* unlink_after_open) const; + // Returns true if |requested_filename| is allowed to be accessed // by this permission as per access(2). - // If |file_to_open| is not NULL it is set to point to either + // If |file_to_open| is not NULL, it is set to point to either // the |requested_filename| in the case of a recursive match, // or a pointer to the matched path in the whitelist if an absolute // match. @@ -86,9 +82,11 @@ private: friend class BrokerFilePermissionTester; + + // NOTE: Validates the permission and dies if invalid! BrokerFilePermission(const std::string& path, bool recursive, - bool unlink, + bool temporary_only, bool allow_read, bool allow_write, bool allow_create); @@ -107,18 +105,17 @@ static const char* GetErrorMessageForTests(); // These are not const as std::vector requires copy-assignment and this class - // is stored in vectors. All methods are marked const so - // the compiler will still enforce no changes outside of the constructor. + // is stored in vectors. All methods are marked const so the compiler will + // still enforce no changes outside of the constructor. std::string path_; - bool recursive_; // Allow everything under this path. |path| must be a dir. - bool unlink_; // unlink after opening. + bool recursive_; // Allow everything under |path| (must be a dir). + bool temporary_only_; // File must be unlink'd after opening. bool allow_read_; bool allow_write_; bool allow_create_; }; } // namespace syscall_broker - } // namespace sandbox #endif // SANDBOX_LINUX_SYSCALL_BROKER_BROKER_FILE_PERMISSION_H_
diff --git a/sandbox/linux/syscall_broker/broker_file_permission_unittest.cc b/sandbox/linux/syscall_broker/broker_file_permission_unittest.cc index 83840779..dc56b4c 100644 --- a/sandbox/linux/syscall_broker/broker_file_permission_unittest.cc +++ b/sandbox/linux/syscall_broker/broker_file_permission_unittest.cc
@@ -231,20 +231,11 @@ ASSERT_TRUE(unlink); } -TEST(BrokerFilePermission, ReadWriteCreateUnlink) { - const char kPath[] = "/tmp/good"; - BrokerFilePermission perm = - BrokerFilePermission::ReadWriteCreateUnlink(kPath); - CheckUnlink(perm, kPath, O_RDWR); - // Don't do anything here, so that ASSERT works in the subfunction as - // expected. -} - -TEST(BrokerFilePermission, ReadWriteCreateUnlinkRecursive) { +TEST(BrokerFilePermission, ReadWriteCreateTemporaryRecursive) { const char kPath[] = "/tmp/good/"; const char kPathFile[] = "/tmp/good/file"; BrokerFilePermission perm = - BrokerFilePermission::ReadWriteCreateUnlinkRecursive(kPath); + BrokerFilePermission::ReadWriteCreateTemporaryRecursive(kPath); CheckUnlink(perm, kPathFile, O_RDWR); // Don't do anything here, so that ASSERT works in the subfunction as // expected.
diff --git a/sandbox/linux/syscall_broker/broker_host.cc b/sandbox/linux/syscall_broker/broker_host.cc index 6c216cf..13b8ea3 100644 --- a/sandbox/linux/syscall_broker/broker_host.cc +++ b/sandbox/linux/syscall_broker/broker_host.cc
@@ -22,6 +22,7 @@ #include "base/pickle.h" #include "base/posix/eintr_wrapper.h" #include "base/posix/unix_domain_socket.h" +#include "base/third_party/dynamic_annotations/dynamic_annotations.h" #include "base/third_party/valgrind/valgrind.h" #include "sandbox/linux/syscall_broker/broker_common.h" #include "sandbox/linux/syscall_broker/broker_policy.h" @@ -33,10 +34,6 @@ namespace { -bool IsRunningOnValgrind() { - return RUNNING_ON_VALGRIND; -} - // A little open(2) wrapper to handle some oddities for us. In the general case // make a direct system call since we want to keep in control of the broker // process' system calls profile to be able to loosely sandbox it. @@ -48,7 +45,7 @@ } else { mode = 0; } - if (IsRunningOnValgrind()) { + if (RunningOnValgrind()) { // Valgrind does not support AT_FDCWD, just use libc's open() in this case. return open(pathname, flags, mode); } else {
diff --git a/sandbox/linux/tests/unit_tests.cc b/sandbox/linux/tests/unit_tests.cc index efe2896..6df7730 100644 --- a/sandbox/linux/tests/unit_tests.cc +++ b/sandbox/linux/tests/unit_tests.cc
@@ -17,6 +17,7 @@ #include "base/debug/leak_annotations.h" #include "base/files/file_util.h" #include "base/posix/eintr_wrapper.h" +#include "base/third_party/dynamic_annotations/dynamic_annotations.h" #include "base/third_party/valgrind/valgrind.h" #include "build/build_config.h" #include "sandbox/linux/tests/unit_tests.h" @@ -75,10 +76,6 @@ #endif } -// TODO(jln): figure out why base/.../dynamic_annotations.h's -// RunningOnValgrind() cannot link. -bool IsRunningOnValgrind() { return RUNNING_ON_VALGRIND; } - static const int kExpectedValue = 42; static const int kIgnoreThisTest = 43; static const int kExitWithAssertionFailure = 1; @@ -184,7 +181,7 @@ // Don't set a timeout if running on Valgrind, since it's generally much // slower. - if (!IsRunningOnValgrind()) { + if (!RunningOnValgrind()) { #if !defined(OS_NACL_NONSFI) SetProcessTimeout(GetSubProcessTimeoutTimeInSeconds()); #endif
diff --git a/sandbox/linux/tests/unit_tests.h b/sandbox/linux/tests/unit_tests.h index 20f3505a..cd2d511 100644 --- a/sandbox/linux/tests/unit_tests.h +++ b/sandbox/linux/tests/unit_tests.h
@@ -27,9 +27,6 @@ bool IsArchitectureArm(); -// Is Valgrind currently being used? -bool IsRunningOnValgrind(); - #if defined(ADDRESS_SANITIZER) #define DISABLE_ON_ASAN(test_name) DISABLED_##test_name #else
diff --git a/services/data_decoder/BUILD.gn b/services/data_decoder/BUILD.gn index e10cd16..3d9da8c 100644 --- a/services/data_decoder/BUILD.gn +++ b/services/data_decoder/BUILD.gn
@@ -4,6 +4,7 @@ import("//services/service_manager/public/cpp/service.gni") import("//services/service_manager/public/service_manifest.gni") +import("//testing/libfuzzer/fuzzer_test.gni") source_set("lib") { sources = [ @@ -13,6 +14,8 @@ "image_decoder_impl.h", "json_parser_impl.cc", "json_parser_impl.h", + "xml_parser.cc", + "xml_parser.h", ] deps = [ @@ -20,6 +23,7 @@ "//mojo/public/cpp/bindings", "//skia", "//third_party/WebKit/public:blink", + "//third_party/libxml", "//ui/gfx", "//ui/gfx/geometry", ] @@ -36,7 +40,9 @@ sources = [ "image_decoder_impl_unittest.cc", "public/cpp/json_sanitizer_unittest.cc", + "public/cpp/safe_xml_parser_unittest.cc", "public/cpp/testing_json_parser_unittest.cc", + "xml_parser_unittest.cc", ] deps = [ @@ -59,3 +65,15 @@ name = "data_decoder" source = "manifest.json" } + +fuzzer_test("xml_parser_fuzzer") { + sources = [ + "xml_parser_fuzzer.cc", + ] + deps = [ + ":lib", + "//base", + ] + dict = "//testing/libfuzzer/fuzzers/dicts/xml.dict" + seed_corpus = "xml_parser_fuzzer_corpus" +}
diff --git a/services/data_decoder/DEPS b/services/data_decoder/DEPS index e1f42c99..c70e822 100644 --- a/services/data_decoder/DEPS +++ b/services/data_decoder/DEPS
@@ -2,6 +2,7 @@ "+gin", "+jni", "+skia", + "+third_party/libxml/chromium", "+third_party/WebKit/public", "+third_party/skia", "+ui/gfx",
diff --git a/services/data_decoder/data_decoder_service.cc b/services/data_decoder/data_decoder_service.cc index 0392df9a..0fdd5023 100644 --- a/services/data_decoder/data_decoder_service.cc +++ b/services/data_decoder/data_decoder_service.cc
@@ -12,6 +12,7 @@ #include "services/data_decoder/image_decoder_impl.h" #include "services/data_decoder/json_parser_impl.h" #include "services/data_decoder/public/interfaces/image_decoder.mojom.h" +#include "services/data_decoder/xml_parser.h" #include "services/service_manager/public/cpp/service_context.h" namespace data_decoder { @@ -33,6 +34,12 @@ std::move(request)); } +void OnXmlParserRequest(service_manager::ServiceContextRefFactory* ref_factory, + mojom::XmlParserRequest request) { + mojo::MakeStrongBinding(base::MakeUnique<XmlParser>(ref_factory->CreateRef()), + std::move(request)); +} + } // namespace DataDecoderService::DataDecoderService() : weak_factory_(this) {} @@ -50,6 +57,7 @@ registry_.AddInterface( base::Bind(&OnImageDecoderRequest, ref_factory_.get())); registry_.AddInterface(base::Bind(&OnJsonParserRequest, ref_factory_.get())); + registry_.AddInterface(base::Bind(&OnXmlParserRequest, ref_factory_.get())); } void DataDecoderService::OnBindInterface(
diff --git a/services/data_decoder/manifest.json b/services/data_decoder/manifest.json index 954d104..5917062b 100644 --- a/services/data_decoder/manifest.json +++ b/services/data_decoder/manifest.json
@@ -5,7 +5,8 @@ "service_manager:connector": { "provides": { "image_decoder": [ "data_decoder::mojom::ImageDecoder" ], - "json_parser": [ "data_decoder::mojom::JsonParser" ] + "json_parser": [ "data_decoder::mojom::JsonParser" ], + "xml_parser": [ "data_decoder::mojom::XmlParser" ] }, "requires": { "service_manager": [ "service_manager:all_users" ]
diff --git a/services/data_decoder/public/cpp/BUILD.gn b/services/data_decoder/public/cpp/BUILD.gn index 142508a..7a85003 100644 --- a/services/data_decoder/public/cpp/BUILD.gn +++ b/services/data_decoder/public/cpp/BUILD.gn
@@ -15,6 +15,8 @@ "safe_json_parser_impl.cc", "safe_json_parser_impl.h", "safe_json_parser_impl.h", + "safe_xml_parser.cc", + "safe_xml_parser.h", ] public_deps = [
diff --git a/services/data_decoder/public/cpp/safe_xml_parser.cc b/services/data_decoder/public/cpp/safe_xml_parser.cc new file mode 100644 index 0000000..05ec471e --- /dev/null +++ b/services/data_decoder/public/cpp/safe_xml_parser.cc
@@ -0,0 +1,221 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "services/data_decoder/public/cpp/safe_xml_parser.h" + +#include "base/callback.h" +#include "base/macros.h" +#include "base/threading/thread_checker.h" +#include "base/unguessable_token.h" +#include "base/values.h" +#include "services/data_decoder/public/interfaces/constants.mojom.h" +#include "services/data_decoder/public/interfaces/xml_parser.mojom.h" +#include "services/service_manager/public/cpp/connector.h" +#include "services/service_manager/public/interfaces/constants.mojom.h" + +namespace data_decoder { + +namespace { + +// Class that does the actual parsing. Deletes itself when parsing is done. +class SafeXmlParser { + public: + SafeXmlParser(service_manager::Connector* connector, + const std::string& unsafe_xml, + XmlParserCallback callback, + const std::string& batch_id); + ~SafeXmlParser(); + + private: + void ReportResults(std::unique_ptr<base::Value> parsed_json, + const base::Optional<std::string>& error); + + XmlParserCallback callback_; + mojom::XmlParserPtr xml_parser_ptr_; + SEQUENCE_CHECKER(sequence_checker_); + + DISALLOW_COPY_AND_ASSIGN(SafeXmlParser); +}; + +SafeXmlParser::SafeXmlParser(service_manager::Connector* connector, + const std::string& unsafe_xml, + XmlParserCallback callback, + const std::string& batch_id) + : callback_(std::move(callback)) { + DCHECK(callback_); // Parsing without a callback is useless. + + // If no batch ID has been provided, use a random instance ID to guarantee the + // connection is to a new service running in its own process. + service_manager::Identity identity( + mojom::kServiceName, service_manager::mojom::kInheritUserID, + batch_id.empty() ? base::UnguessableToken::Create().ToString() + : batch_id); + connector->BindInterface(identity, &xml_parser_ptr_); + + // Unretained(this) is safe as the xml_parser_ptr_ is owned by this class. + xml_parser_ptr_.set_connection_error_handler(base::BindOnce( + &SafeXmlParser::ReportResults, base::Unretained(this), + /*parsed_xml=*/nullptr, + base::make_optional( + std::string("Connection error with the XML parser process.")))); + xml_parser_ptr_->Parse( + unsafe_xml, + base::BindOnce(&SafeXmlParser::ReportResults, base::Unretained(this))); +} + +SafeXmlParser::~SafeXmlParser() = default; + +void SafeXmlParser::ReportResults(std::unique_ptr<base::Value> parsed_xml, + const base::Optional<std::string>& error) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + std::move(callback_).Run(std::move(parsed_xml), error); + + // This should be the last interaction with this instance, safely delete. + delete this; +} + +const base::Value* GetChildren(const base::Value& element) { + if (!element.is_dict()) + return nullptr; + return element.FindKeyOfType(mojom::XmlParser::kChildrenKey, + base::Value::Type::LIST); +} + +} // namespace + +void ParseXml(service_manager::Connector* connector, + const std::string& unsafe_xml, + XmlParserCallback callback, + const std::string& batch_id) { + new SafeXmlParser(connector, unsafe_xml, std::move(callback), batch_id); +} + +bool IsXmlElementNamed(const base::Value& element, const std::string& name) { + if (!element.is_dict()) + return false; + const base::Value* tag_text = element.FindKeyOfType( + mojom::XmlParser::kTagKey, base::Value::Type::STRING); + return tag_text ? tag_text->GetString() == name : false; +} + +bool IsXmlElementOfType(const base::Value& element, const std::string& type) { + if (!element.is_dict()) + return false; + const base::Value* type_text = element.FindKeyOfType( + mojom::XmlParser::kTypeKey, base::Value::Type::STRING); + return type_text ? type_text->GetString() == type : false; +} + +bool GetXmlElementTagName(const base::Value& element, std::string* tag_name) { + DCHECK(tag_name); + if (!element.is_dict()) + return false; + const base::Value* tag_text = element.FindKeyOfType( + mojom::XmlParser::kTagKey, base::Value::Type::STRING); + if (!tag_text) + return false; + *tag_name = tag_text->GetString(); + return true; +} + +bool GetXmlElementText(const base::Value& element, std::string* text) { + DCHECK(text); + const base::Value* children = GetChildren(element); + if (!children) + return false; + + const base::Value* text_node = nullptr; + for (const base::Value& value : children->GetList()) { + if (IsXmlElementOfType(value, mojom::XmlParser::kTextNodeType) || + IsXmlElementOfType(value, mojom::XmlParser::kCDataNodeType)) { + text_node = &value; + break; + } + } + if (!text_node) + return false; + + const base::Value* text_value = text_node->FindKeyOfType( + mojom::XmlParser::kTextKey, base::Value::Type::STRING); + ; + *text = text_value ? text_value->GetString() : ""; + return true; +} + +int GetXmlElementChildrenCount(const base::Value& element, + const std::string& name) { + const base::Value* children = GetChildren(element); + if (!children) + return 0; + int child_count = 0; + for (const base::Value& value : children->GetList()) { + DCHECK(value.is_dict()); + std::string tag_name; + bool success = GetXmlElementTagName(value, &tag_name); + if (success && tag_name == name) + child_count++; + } + return child_count; +} + +const base::Value* GetXmlElementChildWithType(const base::Value& element, + const std::string& type) { + const base::Value* children = GetChildren(element); + if (!children) + return nullptr; + for (const base::Value& value : children->GetList()) { + DCHECK(value.is_dict()); + if (IsXmlElementOfType(value, type)) { + return &value; + } + } + return nullptr; +} + +const base::Value* GetXmlElementChildWithTag(const base::Value& element, + const std::string& tag) { + const base::Value* children = GetChildren(element); + if (!children) + return nullptr; + for (const base::Value& value : children->GetList()) { + DCHECK(value.is_dict()); + if (IsXmlElementNamed(value, tag)) + return &value; + } + return nullptr; +} + +const base::Value* FindXmlElementPath( + const base::Value& element, + std::initializer_list<base::StringPiece> path, + bool* unique_path) { + const base::Value* cur = nullptr; + if (unique_path) + *unique_path = true; + + for (const base::StringPiece component_piece : path) { + std::string component(component_piece); + if (!cur) { + // First element has to match the current node. + if (!IsXmlElementNamed(element, component)) + return nullptr; + cur = &element; + continue; + } + + const base::Value* new_cur = GetXmlElementChildWithTag(*cur, component); + if (!new_cur) + return nullptr; + + if (unique_path && *unique_path && + GetXmlElementChildrenCount(*cur, component) > 1) + *unique_path = false; + + cur = new_cur; + } + return cur; +} + +} // namespace data_decoder
diff --git a/services/data_decoder/public/cpp/safe_xml_parser.h b/services/data_decoder/public/cpp/safe_xml_parser.h new file mode 100644 index 0000000..ac0dd71 --- /dev/null +++ b/services/data_decoder/public/cpp/safe_xml_parser.h
@@ -0,0 +1,101 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef SERVICES_DATA_DECODER_PUBLIC_CPP_SAFE_XML_PARSER_H_ +#define SERVICES_DATA_DECODER_PUBLIC_CPP_SAFE_XML_PARSER_H_ + +#include <initializer_list> +#include <memory> +#include <string> + +#include "base/callback.h" +#include "base/optional.h" + +namespace base { +class Value; +} + +namespace service_manager { +class Connector; +} + +namespace data_decoder { + +// Callback invoked when parsing with ParseXml has finished. +// |value| contains the base::Value dictionary structure representing the parsed +// XML. See xml_parser.mojom for an example. +// If the parsing failed, |error| contains an error message and |value| is null. +using XmlParserCallback = + base::OnceCallback<void(std::unique_ptr<base::Value> value, + const base::Optional<std::string>& error)>; + +// Parses |unsafe_xml| using the data_decoder service which, whenever feasible, +// will be run in an isolated sandboxed process. Invokes |callback| when +// done. The XML document is transformed into a base::Value dictionary +// structure, with special keys holding the tag name and child nodes. +// See xml_parser.mojom for details on the format. +// |connector| is the Connector to use when connecting to the data_decoder +// service. This should be retrieved from whichever service is requesting the +// decode operation. +// If |batch_id| is non-empty, the system may batch this parse request with +// other parse requests using the same |batch_id| in an effort to amortize the +// overhead of a single request. The trade-off is that batch requests may not be +// well-isolated from each other, so this should be used with appropriate +// caution. +void ParseXml(service_manager::Connector* connector, + const std::string& unsafe_xml, + XmlParserCallback callback, + const std::string& batch_id = ""); + +// Below are convenience methods for handling the elements returned by +// ParseXml(). + +// Returns true if |element| is an XML element with a tag name |name|, false +// otherwise. +bool IsXmlElementNamed(const base::Value& element, const std::string& name); + +// Returns true if |element| is an XML element with a type |type|, false +// otherwise. Valid types are data_decoder::mojom::XmlParser::kElementType, +// kTextNodeType or kCDataNodeType. +bool IsXmlElementOfType(const base::Value& element, const std::string& type); + +// Sets |name| with the tag name of |element| and returns true. +// Returns false if |element| does not represent a node with a tag or is not a +// valid XML element. +bool GetXmlElementTagName(const base::Value& element, std::string* name); + +// Sets |text| with the text of |element| and returns true. +// Returns false if |element| does not contain any text (if it's not a text or +// CData node). +bool GetXmlElementText(const base::Value& element, std::string* text); + +// Returns the number of children of |element| named |name|. +int GetXmlElementChildrenCount(const base::Value& element, + const std::string& name); + +// Returns the first child of |element| with the type |type|, or null if there +// are no children with that type. +// |type| are data_decoder::mojom::XmlParser::kElementType, kTextNodeType or +// kCDataNodeType. +const base::Value* GetXmlElementChildWithType(const base::Value& element, + const std::string& type); + +// Returns the first child of |element| with the tag |tag|, or null if there +// are no children with that tag. +const base::Value* GetXmlElementChildWithTag(const base::Value& element, + const std::string& tag); + +// Returns the value of the element path |path| starting at |element|, or null +// if any element in |path| is missing. Note that if there are more than one +// element matching any part of the path, the first one is used and +// |unique_path| is set to false. It is set to true otherwise and can be null if +// not needed. +const base::Value* FindXmlElementPath( + const base::Value& element, + std::initializer_list<base::StringPiece> path, + bool* unique_path); + +} // namespace data_decoder + +#endif // SERVICES_DATA_DECODER_PUBLIC_CPP_SAFE_XML_PARSER_H_
diff --git a/services/data_decoder/public/cpp/safe_xml_parser_unittest.cc b/services/data_decoder/public/cpp/safe_xml_parser_unittest.cc new file mode 100644 index 0000000..8a2ba4b --- /dev/null +++ b/services/data_decoder/public/cpp/safe_xml_parser_unittest.cc
@@ -0,0 +1,189 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "services/data_decoder/public/cpp/safe_xml_parser.h" + +#include <memory> + +#include "base/bind.h" +#include "base/values.h" +#include "build/build_config.h" +#include "services/data_decoder/xml_parser.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace data_decoder { + +namespace { + +std::unique_ptr<base::Value> ParseXml(const std::string& xml) { + XmlParser parser_impl(/*service_ref=*/nullptr); + mojom::XmlParser& parser = parser_impl; + std::unique_ptr<base::Value> root_node; + parser.Parse(xml, base::Bind( + [](std::unique_ptr<base::Value>* node, + std::unique_ptr<base::Value> parsed_root_node, + const base::Optional<std::string>& error) { + *node = std::move(parsed_root_node); + }, + &root_node)); + return root_node; +} + +void ExpectElementTextEq(const base::Value& element, + const std::string& expected_text) { + std::string text; + if (expected_text.empty()) { + EXPECT_FALSE(GetXmlElementText(element, &text)); + } else { + EXPECT_TRUE(GetXmlElementText(element, &text)); + EXPECT_EQ(expected_text, text); + } +} + +using SafeXmlParserTest = testing::Test; + +} // namespace + +TEST_F(SafeXmlParserTest, NameAccessors) { + // Test that the API does not choke on non XML element values. + base::Value not_an_xml_value; + EXPECT_FALSE(IsXmlElementNamed(not_an_xml_value, "hello")); + not_an_xml_value = base::Value("hello"); + EXPECT_FALSE(IsXmlElementNamed(not_an_xml_value, "hello")); + + // Test IsXmlElementNamed. + std::unique_ptr<base::Value> xml_element = ParseXml("<hello></hello>"); + ASSERT_TRUE(xml_element); + EXPECT_TRUE(IsXmlElementNamed(*xml_element, "hello")); + EXPECT_FALSE(IsXmlElementNamed(*xml_element, "bonjour")); + + // Test GetXmlElementTagName. + std::string tag_name; + EXPECT_TRUE(GetXmlElementTagName(*xml_element, &tag_name)); + EXPECT_EQ("hello", tag_name); +} + +TEST_F(SafeXmlParserTest, TextAccessor) { + // Test that the API does not choke on non XML element values. + ExpectElementTextEq(base::Value(), ""); + ExpectElementTextEq(base::Value("hello"), ""); + + // Test retrieving text from elements with no text. + std::unique_ptr<base::Value> no_text_element = ParseXml("<hello/>"); + ExpectElementTextEq(*no_text_element, ""); + + // Test retrieving text from elements with actual text. + std::unique_ptr<base::Value> text_element = + ParseXml("<hello>bonjour bonjour</hello>"); + ASSERT_TRUE(text_element); + ExpectElementTextEq(*text_element, "bonjour bonjour"); + + // Retrieving text from elements with multiple text children returns the first + // one only. + std::unique_ptr<base::Value> multiple_text_elements = + ParseXml("<hello>bonjour<space/>bonjour</hello>"); + ASSERT_TRUE(multiple_text_elements); + ExpectElementTextEq(*multiple_text_elements, "bonjour"); + + std::unique_ptr<base::Value> cdata_element = + ParseXml("<hello><![CDATA[This is <b>CData</b>.]]></hello>"); + ASSERT_TRUE(cdata_element); + ExpectElementTextEq(*cdata_element, "This is <b>CData</b>."); + + std::unique_ptr<base::Value> text_and_cdata_element = + ParseXml("<hello>This is text.<![CDATA[This is <b>CData</b>.]]></hello>"); + ASSERT_TRUE(text_and_cdata_element); + ExpectElementTextEq(*text_and_cdata_element, "This is text."); + + std::unique_ptr<base::Value> cdata_and_text_element = + ParseXml("<hello><![CDATA[This is <b>CData</b>.]]>This is text.</hello>"); + ASSERT_TRUE(cdata_and_text_element); + ExpectElementTextEq(*cdata_and_text_element, "This is <b>CData</b>."); +} + +TEST_F(SafeXmlParserTest, ChildAccessor) { + // Test that the API does not choke on non XML element values. + base::Value not_an_xml_value; + EXPECT_FALSE(GetXmlElementChildrenCount(not_an_xml_value, "hello")); + EXPECT_FALSE(GetXmlElementChildWithTag(not_an_xml_value, "hello")); + + // Childless element case. + std::unique_ptr<base::Value> childless_element = ParseXml("<hello/>"); + ASSERT_TRUE(childless_element); + EXPECT_EQ(0, GetXmlElementChildrenCount(*childless_element, "fr")); + EXPECT_FALSE(GetXmlElementChildWithTag(*childless_element, "fr")); + childless_element = ParseXml("<hello>bonjour</hello>"); + EXPECT_EQ(0, GetXmlElementChildrenCount(*childless_element, "fr")); + EXPECT_FALSE(GetXmlElementChildWithTag(*childless_element, "fr")); + + // Element with children case. + std::unique_ptr<base::Value> element = + ParseXml("<hello><fr>bonjour</fr><fr>salut</fr><es>hola</es></hello>"); + ASSERT_TRUE(element); + EXPECT_EQ(2, GetXmlElementChildrenCount(*element, "fr")); + EXPECT_EQ(1, GetXmlElementChildrenCount(*element, "es")); + EXPECT_EQ(0, GetXmlElementChildrenCount(*element, "jp")); + const base::Value* value = GetXmlElementChildWithTag(*element, "fr"); + ASSERT_TRUE(value); + // The first matching element is returned. + ExpectElementTextEq(*value, "bonjour"); + + value = GetXmlElementChildWithTag(*element, "es"); + ExpectElementTextEq(*value, "hola"); + + EXPECT_FALSE(GetXmlElementChildWithTag(*element, "jp")); +} + +TEST_F(SafeXmlParserTest, FindByPath) { + // Test that the API does not choke on non XML element values. + EXPECT_FALSE( + FindXmlElementPath(base::Value(), {"hello"}, /*unique_path=*/nullptr)); + + std::unique_ptr<base::Value> element = ParseXml( + "<hello>" + " <fr>" + " <formal>bonjour</formal>" + " <casual>salut</casual>" + " <casual>ca gaze</casual>" + " </fr>" + " <es>" + " <formal>buenos dias</formal>" + " <casual>hola</casual>" + " </es>" + "</hello>"); + + // Unexiting paths. + EXPECT_FALSE(FindXmlElementPath(*element, {"bad"}, /*unique_path=*/nullptr)); + EXPECT_FALSE( + FindXmlElementPath(*element, {"hello", "bad"}, /*unique_path=*/nullptr)); + + // Partial paths. + const base::Value* fr_element = + FindXmlElementPath(*element, {"hello", "fr"}, /*unique_path=*/nullptr); + ASSERT_TRUE(fr_element); + EXPECT_TRUE(IsXmlElementNamed(*fr_element, "fr")); + EXPECT_EQ(1, GetXmlElementChildrenCount(*fr_element, "formal")); + EXPECT_EQ(2, GetXmlElementChildrenCount(*fr_element, "casual")); + + // Path to a leaf element. + const base::Value* es_element = FindXmlElementPath( + *element, {"hello", "es", "casual"}, /*unique_path=*/nullptr); + ASSERT_TRUE(es_element); + ExpectElementTextEq(*es_element, "hola"); + + // Test unique path. + bool unique_path = true; + fr_element = + FindXmlElementPath(*element, {"hello", "fr", "casual"}, &unique_path); + ASSERT_TRUE(fr_element); + EXPECT_FALSE(unique_path); + + unique_path = false; + fr_element = + FindXmlElementPath(*element, {"hello", "es", "casual"}, &unique_path); + ASSERT_TRUE(fr_element); + EXPECT_TRUE(unique_path); +} + +} // namespace data_decoder
diff --git a/services/data_decoder/public/interfaces/BUILD.gn b/services/data_decoder/public/interfaces/BUILD.gn index 7af99699..7dac2c1b 100644 --- a/services/data_decoder/public/interfaces/BUILD.gn +++ b/services/data_decoder/public/interfaces/BUILD.gn
@@ -8,6 +8,7 @@ sources = [ "image_decoder.mojom", "json_parser.mojom", + "xml_parser.mojom", ] public_deps = [
diff --git a/services/data_decoder/public/interfaces/xml_parser.mojom b/services/data_decoder/public/interfaces/xml_parser.mojom new file mode 100644 index 0000000..df91241 --- /dev/null +++ b/services/data_decoder/public/interfaces/xml_parser.mojom
@@ -0,0 +1,89 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Interface used to parse simple XML files. +// +// Ignores namespaces, node attributes, comments and white-spaces. +// Note also that the text content of elements is returned as base::Value of +// type STRING (UTF-8 encoded): no effort is made by the parser to parse numeric +// values. + +module data_decoder.mojom; + +import "mojo/common/values.mojom"; + +interface XmlParser { + const string kTypeKey = "type"; + const string kTagKey = "tag"; + const string kTextKey = "text"; + const string kChildrenKey = "children"; + + const string kElementType = "element"; + const string kTextNodeType = "text"; + const string kCDataNodeType = "cdata"; + + // Parses the input XML and returns a Value with its content. If parsing + // failed that value is empty and an error is set: + // + // For example the following XML: + // + // <library> + // <book id="k123"> + // <author>Isaac Newton</author> + // <title><![CDATA[Philosophiae Naturalis Principia Mathematica]]</title> + // <price>40.95</price> + // </book> + // <book id="k456"> + // <author>Dr. Seuss</author> + // <title>Green Eggs and Ham</title> + // <genre>Kid</genre> + // <kids/> + // <price>4.95</price> + // </book> + // </library> + // + // becomes (base::Value dictionary represented as JSON): + // + // {"type": "element", + // "tag": "library", + // "children": [ + // {"type": "element", + // "tag": "book", + // "children": [ + // {"type": "element", + // "tag": "author", + // "children": [{"type": "text", "text": "Isaac Newton"}]}, + // {"type": "element", + // "tag": "title", + // "children": [ + // {"type": "cdata", + // "text": "Philosophiae Naturalis Principia Mathematica"}]}, + // {"type": "element", + // "tag": "price", + // "children": [{"type": "text", "text": "40.95"}]} + // ]}, + // {"type": "element", + // "tag": "book", + // "children": [ + // {"type": "element", + // "tag": "author", + // "children": [{"type": "text", "text": "Dr. Seuss"}]}, + // {"type": "element", + // "tag": "title", + // "children": [{"type": "text", "text": "Green Eggs and Ham"}]}, + // {"type": "element", "tag": "kids"}, + // {"type": "element", + // "tag": "price", + // "children": [{"type": "text", "text": "4.95"}], + // } + // } + // ] + // } + // ]} + // + // Note that the client library provides convenience methods for accessing + // data from the returned base::Value dictionary structure (see + // safe_parser_xml.h). + Parse(string xml) => (mojo.common.mojom.Value? result, string? error); +};
diff --git a/services/data_decoder/xml_parser.cc b/services/data_decoder/xml_parser.cc new file mode 100644 index 0000000..a82051a --- /dev/null +++ b/services/data_decoder/xml_parser.cc
@@ -0,0 +1,131 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "services/data_decoder/xml_parser.h" + +#include <utility> + +#include "base/values.h" +#include "third_party/libxml/chromium/libxml_utils.h" + +namespace data_decoder { + +namespace { + +void ReportError(XmlParser::ParseCallback callback, const std::string& error) { + std::move(callback).Run(/*result=*/nullptr, base::make_optional(error)); +} + +enum class TextNodeType { kText, kCData }; + +base::Value CreateTextNode(const std::string& text, TextNodeType node_type) { + base::Value element(base::Value::Type::DICTIONARY); + element.SetKey(mojom::XmlParser::kTypeKey, + base::Value(node_type == TextNodeType::kText + ? mojom::XmlParser::kTextNodeType + : mojom::XmlParser::kCDataNodeType)); + element.SetKey(mojom::XmlParser::kTextKey, base::Value(text)); + return element; +} + +// Creates and returns new element node with the tag name |name|. +base::Value CreateNewElement(const std::string& name) { + base::Value element(base::Value::Type::DICTIONARY); + element.SetKey(mojom::XmlParser::kTypeKey, + base::Value(mojom::XmlParser::kElementType)); + element.SetKey(mojom::XmlParser::kTagKey, base::Value(name)); + return element; +} + +// Adds |child| as a child of |element|, creating the children list if +// necessary. Returns a ponter to |child|. +base::Value* AddChildToElement(base::Value* element, base::Value child) { + DCHECK(element->is_dict()); + base::Value* children = element->FindKey(mojom::XmlParser::kChildrenKey); + DCHECK(!children || children->is_list()); + if (!children) + children = element->SetKey(mojom::XmlParser::kChildrenKey, + base::Value(base::Value::Type::LIST)); + children->GetList().push_back(std::move(child)); + return &children->GetList().back(); +} + +} // namespace + +XmlParser::XmlParser( + std::unique_ptr<service_manager::ServiceContextRef> service_ref) + : service_ref_(std::move(service_ref)) {} + +XmlParser::~XmlParser() = default; + +void XmlParser::Parse(const std::string& xml, ParseCallback callback) { + XmlReader xml_reader; + if (!xml_reader.Load(xml)) { + ReportError(std::move(callback), "Invalid XML: failed to load"); + return; + } + + base::Value root_element; + std::vector<base::Value*> element_stack; + while (xml_reader.Read()) { + if (xml_reader.IsWhiteSpace() || xml_reader.IsComment()) + continue; + + if (xml_reader.IsClosingElement()) { + if (element_stack.empty()) { + ReportError(std::move(callback), "Invalid XML: unbalanced elements"); + return; + } + element_stack.pop_back(); + continue; + } + + std::string cdata; + std::string text; + base::Value* current_element = + element_stack.empty() ? nullptr : element_stack.back(); + bool push_new_node_to_stack = false; + base::Value new_element; + if (xml_reader.GetTextIfTextElement(&text)) { + new_element = CreateTextNode(text, TextNodeType::kText); + } else if (xml_reader.GetTextIfCDataElement(&text)) { + new_element = CreateTextNode(text, TextNodeType::kCData); + } else { + // Element node. + new_element = CreateNewElement(xml_reader.NodeName()); + // Self-closing (empty) element have no close tag (or children); don't + // push them on the element stack. + push_new_node_to_stack = !xml_reader.IsEmptyElement(); + } + + base::Value* new_element_ptr; + if (current_element) { + new_element_ptr = + AddChildToElement(current_element, std::move(new_element)); + } else { + // First element we are parsing, it becomes the root element. + DCHECK(root_element.is_none()); + root_element = std::move(new_element); + new_element_ptr = &root_element; + } + if (push_new_node_to_stack) + element_stack.push_back(new_element_ptr); + } + + if (!element_stack.empty()) { + ReportError(std::move(callback), "Invalid XML: unbalanced elements"); + return; + } + base::DictionaryValue* dictionary = nullptr; + root_element.GetAsDictionary(&dictionary); + if (!dictionary || dictionary->empty()) { + ReportError(std::move(callback), "Invalid XML: bad content"); + return; + } + std::move(callback).Run( + base::Value::ToUniquePtrValue(std::move(root_element)), + base::Optional<std::string>()); +} + +} // namespace data_decoder
diff --git a/services/data_decoder/xml_parser.h b/services/data_decoder/xml_parser.h new file mode 100644 index 0000000..44a51ed --- /dev/null +++ b/services/data_decoder/xml_parser.h
@@ -0,0 +1,34 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef SERVICES_DATA_DECODER_XML_PARSER_H_ +#define SERVICES_DATA_DECODER_XML_PARSER_H_ + +#include <memory> +#include <string> + +#include "base/macros.h" +#include "services/data_decoder/public/interfaces/xml_parser.mojom.h" +#include "services/service_manager/public/cpp/service_context_ref.h" + +namespace data_decoder { + +class XmlParser : public mojom::XmlParser { + public: + explicit XmlParser( + std::unique_ptr<service_manager::ServiceContextRef> service_ref); + ~XmlParser() override; + + private: + const std::unique_ptr<service_manager::ServiceContextRef> service_ref_; + + // mojom::XmlParser implementation. + void Parse(const std::string& xml, ParseCallback callback) override; + + DISALLOW_COPY_AND_ASSIGN(XmlParser); +}; + +} // namespace data_decoder + +#endif // SERVICES_DATA_DECODER_XML_PARSER_H_
diff --git a/services/data_decoder/xml_parser_fuzzer.cc b/services/data_decoder/xml_parser_fuzzer.cc new file mode 100644 index 0000000..afc9d821 --- /dev/null +++ b/services/data_decoder/xml_parser_fuzzer.cc
@@ -0,0 +1,39 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include <stddef.h> +#include <stdint.h> + +#include <string> + +#include "base/bind.h" +#include "base/message_loop/message_loop.h" +#include "base/run_loop.h" +#include "services/data_decoder/xml_parser.h" + +namespace { + +void OnParseXml(base::Closure quit_loop, + std::unique_ptr<base::Value> value, + const base::Optional<std::string>& error) { + std::move(quit_loop).Run(); +} + +} // namespace + +// Entry point for LibFuzzer. +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + const char* data_ptr = reinterpret_cast<const char*>(data); + + data_decoder::XmlParser xml_parser_impl(/*service_ref=*/nullptr); + data_decoder::mojom::XmlParser& xml_parser = xml_parser_impl; + + base::MessageLoop message_loop; + base::RunLoop run_loop; + xml_parser.Parse(std::string(data_ptr, size), + base::Bind(&OnParseXml, run_loop.QuitClosure())); + run_loop.Run(); + + return 0; +}
diff --git a/services/data_decoder/xml_parser_fuzzer_corpus/input0 b/services/data_decoder/xml_parser_fuzzer_corpus/input0 new file mode 100644 index 0000000..f10ac7c4 --- /dev/null +++ b/services/data_decoder/xml_parser_fuzzer_corpus/input0
@@ -0,0 +1 @@ +<hello>bonjour</hello> \ No newline at end of file
diff --git a/services/data_decoder/xml_parser_fuzzer_corpus/input1 b/services/data_decoder/xml_parser_fuzzer_corpus/input1 new file mode 100644 index 0000000..3e105ba --- /dev/null +++ b/services/data_decoder/xml_parser_fuzzer_corpus/input1
@@ -0,0 +1,53 @@ +<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> +Alphabet +</z> +</y> +</x> +</w> +</v> +</u> +</t> +</s> +</r> +</q> +</p> +</o> +</n> +</m> +</l> +</k> +</j> +</i> +</h> +</g> +</f> +</e> +</d> +</c> +</b> +</a> \ No newline at end of file
diff --git a/services/data_decoder/xml_parser_fuzzer_corpus/input2 b/services/data_decoder/xml_parser_fuzzer_corpus/input2 new file mode 100644 index 0000000..487657d --- /dev/null +++ b/services/data_decoder/xml_parser_fuzzer_corpus/input2
@@ -0,0 +1,19 @@ +<?xml version='1.0' encoding='UTF-8'?> +<!-- This is an XML sample --> +<library xmlns='http://library' xmlns:foo='http://foo.com'> + <book foo:id="k123"> + <author>Isaac Newton</author> + <title>Philosophiae Naturalis Principia Mathematica</title> + <genre>Science</genre> + <price>40.95</price> + <publish_date>1947-9-03</publish_date> + </book> + <book foo:id="k456"> + <author>Dr. Seuss</author> + <title>Green Eggs and Ham</title> + <genre>Kid</genre> + <foo:kids/> + <price>4.95</price> + <publish_date>1960-8-12</publish_date> + </book> +</library> \ No newline at end of file
diff --git a/services/data_decoder/xml_parser_fuzzer_corpus/input3 b/services/data_decoder/xml_parser_fuzzer_corpus/input3 new file mode 100644 index 0000000..82c1adaf --- /dev/null +++ b/services/data_decoder/xml_parser_fuzzer_corpus/input3
@@ -0,0 +1 @@ +<test>{"tag": "woop", "boing": 123, 12: ""foodyums"}</test> \ No newline at end of file
diff --git a/services/data_decoder/xml_parser_fuzzer_corpus/input4 b/services/data_decoder/xml_parser_fuzzer_corpus/input4 new file mode 100644 index 0000000..d7d3dbc3 --- /dev/null +++ b/services/data_decoder/xml_parser_fuzzer_corpus/input4
@@ -0,0 +1 @@ +<number>18446744073709551616</number>
diff --git a/services/data_decoder/xml_parser_fuzzer_corpus/input5 b/services/data_decoder/xml_parser_fuzzer_corpus/input5 new file mode 100644 index 0000000..3941055 --- /dev/null +++ b/services/data_decoder/xml_parser_fuzzer_corpus/input5
@@ -0,0 +1 @@ +<a><b>b1</b><c>c1</c><b>b2</b><c>c2</c><b>b3</b><c>c3</c></a> \ No newline at end of file
diff --git a/services/data_decoder/xml_parser_fuzzer_corpus/input6 b/services/data_decoder/xml_parser_fuzzer_corpus/input6 new file mode 100644 index 0000000..6b18aed --- /dev/null +++ b/services/data_decoder/xml_parser_fuzzer_corpus/input6
@@ -0,0 +1,5 @@ +<hello> +<fr>coucou</fr> +<fr><proper>bonjour</proper><slang>salut</slang></fr> + <fr>ca va</fr> +</hello>
diff --git a/services/data_decoder/xml_parser_fuzzer_corpus/input7 b/services/data_decoder/xml_parser_fuzzer_corpus/input7 new file mode 100644 index 0000000..f69e7e7 --- /dev/null +++ b/services/data_decoder/xml_parser_fuzzer_corpus/input7
@@ -0,0 +1 @@ +<a><b></b><b></b></a> \ No newline at end of file
diff --git a/services/data_decoder/xml_parser_unittest.cc b/services/data_decoder/xml_parser_unittest.cc new file mode 100644 index 0000000..f464ab8 --- /dev/null +++ b/services/data_decoder/xml_parser_unittest.cc
@@ -0,0 +1,354 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include <memory> + +#include "base/bind.h" +#include "base/json/json_reader.h" +#include "base/message_loop/message_loop.h" +#include "services/data_decoder/xml_parser.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace data_decoder { + +namespace { + +void TestParseXmlCallback(std::unique_ptr<base::Value>* value_out, + base::Optional<std::string>* error_out, + std::unique_ptr<base::Value> value, + const base::Optional<std::string>& error) { + *value_out = std::move(value); + *error_out = error; +} + +// Parses the passed in |xml| and compares the result to |json|. +// If |json| is empty, the parsing is expected to fail. +void TestParseXml(const std::string& xml, const std::string& json) { + XmlParser parser_impl(/*service_ref=*/nullptr); + // Use a reference to mojom::XmlParser as XmlParser implements the interface + // privately. + mojom::XmlParser& parser = parser_impl; + + std::unique_ptr<base::Value> actual_value; + base::Optional<std::string> error; + parser.Parse(xml, base::Bind(&TestParseXmlCallback, &actual_value, &error)); + if (json.empty()) { + EXPECT_TRUE(error); + EXPECT_FALSE(actual_value); + return; + } + + EXPECT_FALSE(error) << "Unexpected error: " << *error; + EXPECT_TRUE(actual_value); + + std::unique_ptr<base::Value> expected_value = base::JSONReader::Read(json); + DCHECK(expected_value) << "Bad test, incorrect JSON: " << json; + + EXPECT_EQ(*expected_value, *actual_value); +} + +} // namespace + +using XmlParserTest = testing::Test; + +TEST_F(XmlParserTest, ParseBadXml) { + std::string invalid_xml_strings[] = {"", + " ", + "Awesome possum", + "[\"json\", \"or\", \"xml?\"]", + "<unbalanced>", + "<hello>bad tag</goodbye>"}; + for (auto& xml : invalid_xml_strings) + TestParseXml(xml, ""); +} + +TEST_F(XmlParserTest, ParseSelfClosingTag) { + TestParseXml("<a/>", R"( {"type": "element", "tag": "a"} )"); + TestParseXml("<a><b/></a>", + R"( {"type": "element", + "tag": "a", + "children": [{"type": "element", "tag": "b"}]} )"); + TestParseXml("<a><b/><b/><b/></a>", + R"( {"type": "element", + "tag": "a", + "children":[ + {"type": "element", "tag": "b"}, + {"type": "element", "tag": "b"}, + {"type": "element", "tag": "b"} + ]} + )"); +} + +TEST_F(XmlParserTest, ParseEmptyTag) { + TestParseXml("<a></a>", R"( {"type": "element", "tag": "a"} )"); + TestParseXml("<a><b></b></a>", + R"( {"type": "element", + "tag": "a", + "children": [{"type": "element", "tag": "b"}]} )"); + TestParseXml("<a><b></b><b></b></a>", + R"( {"type": "element", + "tag": "a", + "children":[{"type": "element", "tag": "b"}, + {"type": "element", "tag": "b"}]} )"); +} + +TEST_F(XmlParserTest, ParseTextElement) { + TestParseXml("<hello>bonjour</hello>", + R"( {"type": "element", + "tag": "hello", + "children": [{"type": "text", "text": "bonjour"}]} )"); +} + +TEST_F(XmlParserTest, ParseCDataElement) { + TestParseXml(R"(<hello><![CDATA[This is CData. + With weird chars [ ] { } <> ; : ' " and + some <b>formatting</b> <br>]]> + </hello> )", + R"( {"type": "element", + "tag": "hello", + "children": [{"type": "cdata", + "text": "This is CData.\n With weird chars [ ] { } <> ; : ' \" and\n some <b>formatting</b> <br>" + }]} )"); +} + +TEST_F(XmlParserTest, ParseBadCDataElement) { + // Missing first bracket. + TestParseXml("<hello><!CDATA[This is CData.]]></hello>", ""); + // Space before last bracket. + TestParseXml("<hello><![CDATA[This is CData.] ]></hello>", ""); + // Space before closing >. + TestParseXml("<hello><![CDATA[This is CData.]] ></hello>", ""); +} + +TEST_F(XmlParserTest, ParseTextWithEntities) { + TestParseXml("<hello>"bonjour& ' <hello></hello>", + R"( {"type": "element", + "tag": "hello", + "children": [{"type": "text", + "text": "\"bonjour& ' <hello>"}]} )"); + // Entities in CDATA are not evaluated. + TestParseXml("<hello><![CDATA["bonjour& ']]></hello>", + R"( {"type": "element", + "tag": "hello", + "children": [{"type": "cdata", + "text": ""bonjour& '"}]} )"); +} + +TEST_F(XmlParserTest, ParseMultipleSimilarTextElement) { + TestParseXml("<hello><fr>bonjour</fr><fr>salut</fr><fr>coucou</fr></hello>", + R"( {"type": "element", + "tag": "hello", + "children": [ + {"type": "element", + "tag": "fr", + "children": [{"type": "text", "text": "bonjour"}]}, + {"type": "element", + "tag": "fr", + "children": [{"type": "text", "text": "salut"}]}, + {"type": "element", + "tag": "fr", + "children": [{"type": "text", "text": "coucou"}]} + ]} )"); +} + +TEST_F(XmlParserTest, ParseMixMatchTextNonTextElement) { + TestParseXml( + R"( + <hello> + <fr>coucou</fr> + <fr><proper>bonjour</proper><slang>salut</slang></fr> + <fr>ca va</fr> + </hello> )", + R"( + {"type": "element", + "tag": "hello", + "children": [ + {"type": "element", + "tag": "fr", + "children": [{"type": "text", "text": "coucou"}]}, + {"type": "element", + "tag": "fr", + "children": [ + {"type": "element", + "tag": "proper", + "children": [{"type": "text", "text": "bonjour" }]}, + {"type": "element", + "tag": "slang", + "children": [{"type": "text", "text": "salut" }]} + ]}, + {"type": "element", + "tag": "fr", + "children": [{"type": "text", "text": "ca va"}]} + ]} )"); +} + +TEST_F(XmlParserTest, ParseElementsInText) { + TestParseXml( + "<p>This is <b>some</b> text.<![CDATA[ this <i>formatting</i> is ignored" + " ]]></p>", + R"( + {"type": "element", "tag": "p", "children": [ + {"type": "text", "text": "This is "}, + {"type": "element", "tag": "b", "children": [ + {"type": "text", "text": "some"} + ]}, + {"type": "text", "text": " text."}, + {"type": "cdata", "text": " this <i>formatting</i> is ignored "} + ]} )"); +} + +TEST_F(XmlParserTest, ParseNestedXml) { + TestParseXml( + R"( <M><a><t><r><y><o><s><h><k><a>Zdravstvuy</a> + </k></h></s></o></y></r></t></a></M> )", + R"( {"type": "element", "tag": "M", "children": [ + {"type": "element", "tag": "a", "children": [ + {"type": "element", "tag": "t", "children": [ + {"type": "element", "tag": "r", "children": [ + {"type": "element", "tag": "y", "children": [ + {"type": "element", "tag": "o", "children": [ + {"type": "element", "tag": "s", "children": [ + {"type": "element", "tag": "h", "children": [ + {"type": "element", "tag": "k", "children": [ + {"type": "element", "tag": "a", "children": [ + {"type": "text", "text": "Zdravstvuy"} + ]} + ]} + ]} + ]} + ]} + ]} + ]} + ]} + ]} + ]} )"); +} + +TEST_F(XmlParserTest, ParseMultipleSimilarElements) { + TestParseXml("<a><b>b1</b><c>c1</c><b>b2</b><c>c2</c><b>b3</b><c>c3</c></a>", + R"( {"type": "element", "tag": "a", "children": [ + {"type": "element", "tag": "b", "children":[ + {"type": "text", "text": "b1"}]}, + {"type": "element", "tag": "c", "children":[ + {"type": "text", "text": "c1"}]}, + {"type": "element", "tag": "b", "children":[ + {"type": "text", "text": "b2"}]}, + {"type": "element", "tag": "c", "children":[ + {"type": "text", "text": "c2"}]}, + {"type": "element", "tag": "b", "children":[ + {"type": "text", "text": "b3"}]}, + {"type": "element", "tag": "c", "children":[ + {"type": "text", "text": "c3"}]} + ]} )"); +} + +TEST_F(XmlParserTest, LargeNumber) { + TestParseXml("<number>18446744073709551616</number>", + R"( {"type": "element", + "tag": "number", + "children": [ + { "type": "text", "text": "18446744073709551616"} + ]} )"); +} + +TEST_F(XmlParserTest, JsonInjection) { + TestParseXml( + R"( <test>{"tag": "woop", "boing": 123, 12: ""foodyums"}</test> )", + R"( {"type": "element", + "tag": "test", + "children": [ + {"type": "text", + "text": "{\"tag\": \"woop\", \"boing\": 123, 12: \"\"foodyums\"}"} + ]} + )"); +} + +TEST_F(XmlParserTest, ParseTypicalXml) { + constexpr char kXml[] = R"(<?xml version='1.0' encoding='UTF-8'?> + <!-- This is an XML sample --> + <library xmlns='http://library' xmlns:foo='http://foo.com'> + <book foo:id="k123"> + <author>Isaac Newton</author> + <title>Philosophiae Naturalis Principia Mathematica</title> + <genre>Science</genre> + <price>40.95</price> + <publish_date>1947-9-03</publish_date> + </book> + <book foo:id="k456"> + <author>Dr. Seuss</author> + <title>Green Eggs and Ham</title> + <genre>Kid</genre> + <foo:kids/> + <price>4.95</price> + <publish_date>1960-8-12</publish_date> + </book> + </library> + )"; + + constexpr char kJson[] = R"( + {"type": "element", + "tag": "library", + "children": [ + {"type": "element", + "tag": "book", + "children": [ + {"type": "element", + "tag": "author", + "children": [{"type": "text", "text": "Isaac Newton"}] + }, + {"type": "element", + "tag": "title", + "children": [ + {"type": "text", + "text": "Philosophiae Naturalis Principia Mathematica"} + ] + }, + {"type": "element", + "tag": "genre", + "children": [{"type": "text", "text": "Science"}] + }, + {"type": "element", + "tag": "price", + "children": [{"type": "text", "text": "40.95"}] + }, + {"type": "element", + "tag": "publish_date", + "children": [{"type": "text", "text": "1947-9-03"}] + } + ] + }, + {"type": "element", + "tag": "book", + "children": [ + {"type": "element", + "tag": "author", + "children": [{"type": "text", "text": "Dr. Seuss"}] + }, + {"type": "element", + "tag": "title", + "children": [{"type": "text", "text": "Green Eggs and Ham"}] + }, + {"type": "element", + "tag": "genre", + "children": [{"type": "text", "text": "Kid"}] + }, + {"type": "element", + "tag": "kids" + }, + {"type": "element", + "tag": "price", + "children": [{"type": "text", "text": "4.95"}] + }, + {"type": "element", + "tag": "publish_date", + "children": [{"type": "text", "text": "1960-8-12"}] + } + ]} + ] + } + )"; + TestParseXml(kXml, kJson); +} + +} // namespace data_decoder
diff --git a/services/network/public/interfaces/BUILD.gn b/services/network/public/interfaces/BUILD.gn index 2bdc3d0..120027f7 100644 --- a/services/network/public/interfaces/BUILD.gn +++ b/services/network/public/interfaces/BUILD.gn
@@ -8,6 +8,7 @@ sources = [ "cookie_manager.mojom", "cors.mojom", + "data_pipe_getter.mojom", "fetch_api.mojom", "http_request_headers.mojom", "mutable_network_traffic_annotation_tag.mojom",
diff --git a/services/network/public/interfaces/data_pipe_getter.mojom b/services/network/public/interfaces/data_pipe_getter.mojom new file mode 100644 index 0000000..cfadd97 --- /dev/null +++ b/services/network/public/interfaces/data_pipe_getter.mojom
@@ -0,0 +1,15 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +module network.mojom; + +// An interface that can vend a data pipe multiple times. You can think of it +// as backed by content like a Blob that can be read multiple times. +interface DataPipeGetter { + // Reads all the content, writing into |pipe|. Calls the callback with |size| + // once the size of the content is known. If an error occurred before the + // size was known, the callback is instead called with the net::Error + // |status|. + Read(handle<data_pipe_producer> pipe) => (int32 status, uint64 size); +};
diff --git a/services/resource_coordinator/public/cpp/memory_instrumentation/client_process_impl.h b/services/resource_coordinator/public/cpp/memory_instrumentation/client_process_impl.h index c24a59a..345533c 100644 --- a/services/resource_coordinator/public/cpp/memory_instrumentation/client_process_impl.h +++ b/services/resource_coordinator/public/cpp/memory_instrumentation/client_process_impl.h
@@ -82,14 +82,15 @@ const std::vector<base::ProcessId>& ids, const RequestOSMemoryDumpCallback& callback) override; + // Map containing pending chrome memory callbacks indexed by dump guid. + // This must be destroyed after |binding_|. + std::map<uint64_t, RequestChromeMemoryDumpCallback> pending_chrome_callbacks_; + mojom::CoordinatorPtr coordinator_; mojo::Binding<mojom::ClientProcess> binding_; const mojom::ProcessType process_type_; scoped_refptr<base::SingleThreadTaskRunner> task_runner_; - // Map containing pending chrome memory callbacks indexed by dump guid. - std::map<uint64_t, RequestChromeMemoryDumpCallback> pending_chrome_callbacks_; - // TODO(ssid): This should be moved to coordinator instead of clients once we // have the whole chrome dumps sent via mojo, crbug.com/728199. std::unique_ptr<TracingObserver> tracing_observer_;
diff --git a/services/service_manager/sandbox/linux/sandbox_linux.cc b/services/service_manager/sandbox/linux/sandbox_linux.cc index db37946..04dde3d 100644 --- a/services/service_manager/sandbox/linux/sandbox_linux.cc +++ b/services/service_manager/sandbox/linux/sandbox_linux.cc
@@ -58,14 +58,6 @@ namespace { -struct FDCloser { - inline void operator()(int* fd) const { - DCHECK(fd); - PCHECK(0 == IGNORE_EINTR(close(*fd))); - *fd = -1; - } -}; - void LogSandboxStarted(const std::string& sandbox_name) { const std::string process_type = base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
diff --git a/services/service_manager/sandbox/mac/renderer_v2.sb b/services/service_manager/sandbox/mac/renderer_v2.sb index 655e9f4..c7527be 100644 --- a/services/service_manager/sandbox/mac/renderer_v2.sb +++ b/services/service_manager/sandbox/mac/renderer_v2.sb
@@ -41,7 +41,7 @@ (allow signal (target self)) ; Consumes a subpath and appends it to the user's homedir path. -(define (user-homedir-path subpath) +(define (user-homedir-path subpath) (string-append (param homedir-as-literal) subpath)) ; Allow logging for all processes. @@ -75,7 +75,8 @@ (path (user-homedir-path "/.CFUserTextEncoding")) (path (user-homedir-path "/Library/Preferences/com.apple.universalaccess.plist")) (path (user-homedir-path "/Library/Preferences/.GlobalPreferences.plist")) - (regex (user-homedir-path #"/Library/Preferences/ByHost/.GlobalPreferences.*"))) + (regex (user-homedir-path #"/Library/Preferences/ByHost/.GlobalPreferences.*")) + (subpath (user-homedir-path "/Library/Fonts"))) ; Reads of /dev devices. (allow file-read-data @@ -133,13 +134,13 @@ (iokit-registry-entry-class "RootDomainUserClient")) ; POSIX IPC -(allow ipc-posix-shm-read-data +(allow ipc-posix-shm-read-data (ipc-posix-name "apple.cfprefs.317580v1") (ipc-posix-name "apple.cfprefs.daemonv1") (ipc-posix-name "apple.shm.notification_center")) ; mach IPC -(allow mach-lookup +(allow mach-lookup (global-name "com.apple.distributed_notifications@Uv3") (global-name "com.apple.fonts") ; crbug.com/756145, crbug.com/786615 @@ -156,6 +157,11 @@ (if (< os-version 1012) (allow mach-lookup (global-name "com.apple.FontServer"))) +; To allow accessing downloaded and other hidden fonts in +; /System/Library/Asssets/com_apple_MobileAsset_Font*. +; (https://crbug.com/662686) +(allow file-read* (extension "com.apple.app-sandbox.read")) + ; sysctl (if (= os-version 1009) (allow sysctl-read)
diff --git a/services/ui/demo/mus_demo_unittests.cc b/services/ui/demo/mus_demo_unittests.cc index e89c167f..febdb6d 100644 --- a/services/ui/demo/mus_demo_unittests.cc +++ b/services/ui/demo/mus_demo_unittests.cc
@@ -10,6 +10,7 @@ #include "services/ui/public/interfaces/constants.mojom.h" #include "services/ui/public/interfaces/window_server_test.mojom.h" #include "testing/gtest/include/gtest/gtest.h" +#include "ui/base/ui_base_switches.h" namespace ui { namespace demo { @@ -30,6 +31,8 @@ void SetUp() override { base::CommandLine::ForCurrentProcess()->AppendSwitch("use-test-config"); + base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( + switches::kMus, switches::kMusHostVizValue); ServiceTest::SetUp(); }
diff --git a/services/ui/ws/gpu_host.cc b/services/ui/ws/gpu_host.cc index 928aa43..938c2bdc 100644 --- a/services/ui/ws/gpu_host.cc +++ b/services/ui/ws/gpu_host.cc
@@ -152,6 +152,8 @@ void DefaultGpuHost::DidFailInitialize() {} +void DefaultGpuHost::DidCreateContextSuccessfully() {} + void DefaultGpuHost::DidCreateOffscreenContext(const GURL& url) {} void DefaultGpuHost::DidDestroyOffscreenContext(const GURL& url) {}
diff --git a/services/ui/ws/gpu_host.h b/services/ui/ws/gpu_host.h index 361a2632..bb51cab 100644 --- a/services/ui/ws/gpu_host.h +++ b/services/ui/ws/gpu_host.h
@@ -93,6 +93,7 @@ void DidInitialize(const gpu::GPUInfo& gpu_info, const gpu::GpuFeatureInfo& gpu_feature_info) override; void DidFailInitialize() override; + void DidCreateContextSuccessfully() override; void DidCreateOffscreenContext(const GURL& url) override; void DidDestroyOffscreenContext(const GURL& url) override; void DidDestroyChannel(int32_t client_id) override;
diff --git a/services/ui/ws/window_manager_client_unittest.cc b/services/ui/ws/window_manager_client_unittest.cc index a752aae8..df3ba09 100644 --- a/services/ui/ws/window_manager_client_unittest.cc +++ b/services/ui/ws/window_manager_client_unittest.cc
@@ -20,6 +20,7 @@ #include "ui/aura/mus/window_tree_client_delegate.h" #include "ui/aura/mus/window_tree_host_mus.h" #include "ui/aura/mus/window_tree_host_mus_init_params.h" +#include "ui/aura/test/mus/test_window_manager_delegate.h" #include "ui/aura/test/mus/window_tree_client_private.h" #include "ui/aura/window.h" #include "ui/aura/window_observer.h" @@ -40,69 +41,6 @@ return aura::WindowTreeClientPrivate(client).GetWindowByServerId(id); } -class TestWindowManagerDelegate : public aura::WindowManagerDelegate { - public: - TestWindowManagerDelegate() {} - ~TestWindowManagerDelegate() override {} - - // WindowManagerDelegate: - void SetWindowManagerClient(aura::WindowManagerClient* client) override {} - void OnWmAcceleratedWidgetAvailableForDisplay( - int64_t display_id, - gfx::AcceleratedWidget widget) override {} - void OnWmConnected() override {} - void OnWmSetBounds(aura::Window* window, const gfx::Rect& bounds) override {} - bool OnWmSetProperty( - aura::Window* window, - const std::string& name, - std::unique_ptr<std::vector<uint8_t>>* new_data) override { - return false; - } - void OnWmSetModalType(aura::Window* window, ui::ModalType type) override {} - void OnWmSetCanFocus(aura::Window* window, bool can_focus) override {} - aura::Window* OnWmCreateTopLevelWindow( - ui::mojom::WindowType window_type, - std::map<std::string, std::vector<uint8_t>>* properties) override { - return nullptr; - } - void OnWmClientJankinessChanged(const std::set<aura::Window*>& client_windows, - bool not_responding) override {} - void OnWmBuildDragImage(const gfx::Point& screen_location, - const SkBitmap& drag_image, - const gfx::Vector2d& drag_image_offset, - ui::mojom::PointerKind source) override {} - void OnWmMoveDragImage(const gfx::Point& screen_location) override {} - void OnWmDestroyDragImage() override {} - void OnWmWillCreateDisplay(const display::Display& display) override {} - void OnWmNewDisplay(std::unique_ptr<aura::WindowTreeHostMus> window_tree_host, - const display::Display& display) override {} - void OnWmDisplayRemoved(aura::WindowTreeHostMus* window_tree_host) override {} - void OnWmDisplayModified(const display::Display& display) override {} - mojom::EventResult OnAccelerator( - uint32_t accelerator_id, - const ui::Event& event, - std::unordered_map<std::string, std::vector<uint8_t>>* properties) - override { - return ui::mojom::EventResult::UNHANDLED; - } - void OnCursorTouchVisibleChanged(bool enabled) override {} - void OnWmPerformMoveLoop(aura::Window* window, - mojom::MoveLoopSource source, - const gfx::Point& cursor_location, - const base::Callback<void(bool)>& on_done) override { - } - void OnWmCancelMoveLoop(aura::Window* window) override {} - void OnWmSetClientArea( - aura::Window* window, - const gfx::Insets& insets, - const std::vector<gfx::Rect>& additional_client_areas) override {} - bool IsWindowActive(aura::Window* window) override { return true; } - void OnWmDeactivateWindow(aura::Window* window) override {} - - private: - DISALLOW_COPY_AND_ASSIGN(TestWindowManagerDelegate); -}; - class BoundsChangeObserver : public aura::WindowObserver { public: explicit BoundsChangeObserver(aura::Window* window) : window_(window) { @@ -444,7 +382,7 @@ // Verifies that bounds changes applied to a window owned by a different // client can be refused. TEST_F(WindowServerTest, SetBoundsSecurity) { - TestWindowManagerDelegate wm_delegate; + aura::TestWindowManagerDelegate wm_delegate; set_window_manager_delegate(&wm_delegate); aura::Window* window = NewVisibleWindow(GetFirstWMRoot(), window_manager(), @@ -703,7 +641,8 @@ EXPECT_EQ(insets, client_area_change->insets); } -class EstablishConnectionViaFactoryDelegate : public TestWindowManagerDelegate { +class EstablishConnectionViaFactoryDelegate + : public aura::TestWindowManagerDelegate { public: explicit EstablishConnectionViaFactoryDelegate(aura::WindowTreeClient* client) : client_(client), run_loop_(nullptr), created_window_(nullptr) {}
diff --git a/services/ui/ws/window_server.cc b/services/ui/ws/window_server.cc index 3409c31f..b0ab2c9 100644 --- a/services/ui/ws/window_server.cc +++ b/services/ui/ws/window_server.cc
@@ -152,6 +152,8 @@ std::make_unique<VizHostProxyImpl>(host_frame_sink_manager_.get())), video_detector_(host_frame_sink_manager_.get()), display_creation_config_(DisplayCreationConfig::UNKNOWN) { + if (host_frame_sink_manager_) + host_frame_sink_manager_->WillAssignTemporaryReferencesExternally(); user_id_tracker_.AddObserver(this); OnUserIdAdded(user_id_tracker_.active_id()); }
diff --git a/services/ui/ws/window_server_test_base.cc b/services/ui/ws/window_server_test_base.cc index ef10984..b1bd277 100644 --- a/services/ui/ws/window_server_test_base.cc +++ b/services/ui/ws/window_server_test_base.cc
@@ -5,6 +5,7 @@ #include "services/ui/ws/window_server_test_base.h" #include "base/bind.h" +#include "base/command_line.h" #include "base/location.h" #include "base/memory/ptr_util.h" #include "base/run_loop.h" @@ -15,6 +16,7 @@ #include "ui/aura/env.h" #include "ui/aura/mus/window_tree_client.h" #include "ui/aura/mus/window_tree_host_mus.h" +#include "ui/base/ui_base_switches.h" #include "ui/display/display.h" #include "ui/display/display_list.h" #include "ui/wm/core/capture_controller.h" @@ -91,6 +93,8 @@ } void WindowServerTestBase::SetUp() { + base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( + switches::kMus, switches::kMusHostVizValue); WindowServerServiceTestBase::SetUp(); env_ = aura::Env::CreateInstance(aura::Env::Mode::MUS);
diff --git a/services/viz/privileged/interfaces/gl/gpu_host.mojom b/services/viz/privileged/interfaces/gl/gpu_host.mojom index a23f8ef..c23f7110 100644 --- a/services/viz/privileged/interfaces/gl/gpu_host.mojom +++ b/services/viz/privileged/interfaces/gl/gpu_host.mojom
@@ -17,6 +17,7 @@ gpu.mojom.GpuFeatureInfo gpu_feature_info); DidFailInitialize(); + DidCreateContextSuccessfully(); DidCreateOffscreenContext(url.mojom.Url url); DidDestroyOffscreenContext(url.mojom.Url url);
diff --git a/skia/config/SkUserConfig.h b/skia/config/SkUserConfig.h index 88bb2586..91306257 100644 --- a/skia/config/SkUserConfig.h +++ b/skia/config/SkUserConfig.h
@@ -204,10 +204,6 @@ #define SK_USE_LEGACY_DISTANCE_FIELDS #endif -#ifndef SK_SUPPORT_LEGACY_BLUR_IMAGE -#define SK_SUPPORT_LEGACY_BLUR_IMAGE -#endif - // Skia is enabling this feature soon. Chrome probably does // not want it for M64 #ifndef SK_DISABLE_EXPLICIT_GPU_RESOURCE_ALLOCATION
diff --git a/skia/ext/SkDiscardableMemory_chrome.cc b/skia/ext/SkDiscardableMemory_chrome.cc index 76923b9..90adda1e 100644 --- a/skia/ext/SkDiscardableMemory_chrome.cc +++ b/skia/ext/SkDiscardableMemory_chrome.cc
@@ -11,7 +11,7 @@ #include "base/memory/discardable_memory.h" #include "base/memory/discardable_memory_allocator.h" -SkDiscardableMemoryChrome::~SkDiscardableMemoryChrome() {} +SkDiscardableMemoryChrome::~SkDiscardableMemoryChrome() = default; bool SkDiscardableMemoryChrome::lock() { return discardable_->Lock();
diff --git a/skia/ext/analysis_canvas.cc b/skia/ext/analysis_canvas.cc index f047ae48..cd98ee7 100644 --- a/skia/ext/analysis_canvas.cc +++ b/skia/ext/analysis_canvas.cc
@@ -340,7 +340,7 @@ draw_op_count_(0), rejected_op_count_(0) {} -AnalysisCanvas::~AnalysisCanvas() {} +AnalysisCanvas::~AnalysisCanvas() = default; bool AnalysisCanvas::GetColorIfSolid(SkColor* color) const { if (is_transparent_) {
diff --git a/skia/ext/benchmarking_canvas.cc b/skia/ext/benchmarking_canvas.cc index 1f46938..053839e 100644 --- a/skia/ext/benchmarking_canvas.cc +++ b/skia/ext/benchmarking_canvas.cc
@@ -429,8 +429,7 @@ addCanvas(canvas); } -BenchmarkingCanvas::~BenchmarkingCanvas() { -} +BenchmarkingCanvas::~BenchmarkingCanvas() = default; size_t BenchmarkingCanvas::CommandCount() const { return op_records_.GetSize();
diff --git a/skia/ext/convolver.cc b/skia/ext/convolver.cc index 092fefaa..de03146 100644 --- a/skia/ext/convolver.cc +++ b/skia/ext/convolver.cc
@@ -261,8 +261,7 @@ : max_filter_(0) { } -ConvolutionFilter1D::~ConvolutionFilter1D() { -} +ConvolutionFilter1D::~ConvolutionFilter1D() = default; void ConvolutionFilter1D::AddFilter(int filter_offset, const float* filter_values,
diff --git a/skia/ext/skia_memory_dump_provider.cc b/skia/ext/skia_memory_dump_provider.cc index 5c61225..2afdd86 100644 --- a/skia/ext/skia_memory_dump_provider.cc +++ b/skia/ext/skia_memory_dump_provider.cc
@@ -19,9 +19,9 @@ base::LeakySingletonTraits<SkiaMemoryDumpProvider>>::get(); } -SkiaMemoryDumpProvider::SkiaMemoryDumpProvider() {} +SkiaMemoryDumpProvider::SkiaMemoryDumpProvider() = default; -SkiaMemoryDumpProvider::~SkiaMemoryDumpProvider() {} +SkiaMemoryDumpProvider::~SkiaMemoryDumpProvider() = default; bool SkiaMemoryDumpProvider::OnMemoryDump( const base::trace_event::MemoryDumpArgs& args,
diff --git a/skia/ext/skia_trace_memory_dump_impl.cc b/skia/ext/skia_trace_memory_dump_impl.cc index 920fa222..ebdec805 100644 --- a/skia/ext/skia_trace_memory_dump_impl.cc +++ b/skia/ext/skia_trace_memory_dump_impl.cc
@@ -31,7 +31,7 @@ ? SkTraceMemoryDump::kLight_LevelOfDetail : SkTraceMemoryDump::kObjectsBreakdowns_LevelOfDetail) {} -SkiaTraceMemoryDumpImpl::~SkiaTraceMemoryDumpImpl() {} +SkiaTraceMemoryDumpImpl::~SkiaTraceMemoryDumpImpl() = default; void SkiaTraceMemoryDumpImpl::dumpNumericValue(const char* dumpName, const char* valueName,
diff --git a/skia/public/interfaces/image_filter_struct_traits.cc b/skia/public/interfaces/image_filter_struct_traits.cc index b21d6d4..7fbbc925 100644 --- a/skia/public/interfaces/image_filter_struct_traits.cc +++ b/skia/public/interfaces/image_filter_struct_traits.cc
@@ -6,7 +6,7 @@ namespace mojo { -ImageFilterBuffer::ImageFilterBuffer() {} +ImageFilterBuffer::ImageFilterBuffer() = default; ImageFilterBuffer::ImageFilterBuffer(const ImageFilterBuffer& other) = default;
diff --git a/skia/public/interfaces/test/struct_traits_unittest.cc b/skia/public/interfaces/test/struct_traits_unittest.cc index 9005b72c..624197b 100644 --- a/skia/public/interfaces/test/struct_traits_unittest.cc +++ b/skia/public/interfaces/test/struct_traits_unittest.cc
@@ -20,7 +20,7 @@ class StructTraitsTest : public testing::Test, public mojom::TraitsTestService { public: - StructTraitsTest() {} + StructTraitsTest() = default; protected: mojom::TraitsTestServicePtr GetTraitsTestProxy() {
diff --git a/storage/DEPS b/storage/DEPS index 1743043..53c7b52 100644 --- a/storage/DEPS +++ b/storage/DEPS
@@ -2,6 +2,7 @@ "+mojo", "+net", "+services/network/public/cpp", + "+services/network/public/interfaces", "+sql", "+third_party/leveldatabase", "+third_party/sqlite",
diff --git a/storage/common/BUILD.gn b/storage/common/BUILD.gn index 60e2f7d..b3454ba 100644 --- a/storage/common/BUILD.gn +++ b/storage/common/BUILD.gn
@@ -2,6 +2,8 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +import("//mojo/public/tools/bindings/mojom.gni") + component("common") { output_name = "storage_common" sources = [ @@ -44,6 +46,7 @@ defines = [ "STORAGE_COMMON_IMPLEMENTATION" ] public_deps = [ + "//services/network/public/interfaces", "//third_party/WebKit/public:blink_headers", ] @@ -55,6 +58,16 @@ ] } +mojom("mojo_bindings") { + sources = [ + "quota/quota_types.mojom", + ] + + public_deps = [ + "//url/mojo:url_mojom_gurl", + ] +} + source_set("unittests") { testonly = true
diff --git a/storage/common/data_element.cc b/storage/common/data_element.cc index bc0577462..56ed739 100644 --- a/storage/common/data_element.cc +++ b/storage/common/data_element.cc
@@ -76,22 +76,18 @@ length_ = length; } -void DataElement::SetToDataPipe(mojo::ScopedDataPipeConsumerHandle handle, - blink::mojom::SizeGetterPtr size_getter) { +void DataElement::SetToDataPipe( + network::mojom::DataPipeGetterPtr data_pipe_getter) { type_ = TYPE_DATA_PIPE; - data_pipe_ = std::move(handle); - data_pipe_size_getter_ = std::move(size_getter); + data_pipe_getter_ = std::move(data_pipe_getter); } base::File DataElement::ReleaseFile() { return std::move(file_); } -mojo::ScopedDataPipeConsumerHandle DataElement::ReleaseDataPipe( - blink::mojom::SizeGetterPtr* size_getter) { - if (size_getter) - *size_getter = std::move(data_pipe_size_getter_); - return std::move(data_pipe_); +network::mojom::DataPipeGetterPtr DataElement::ReleaseDataPipeGetter() { + return std::move(data_pipe_getter_); } void PrintTo(const DataElement& x, std::ostream* os) {
diff --git a/storage/common/data_element.h b/storage/common/data_element.h index 20bb5db6..2e79b67 100644 --- a/storage/common/data_element.h +++ b/storage/common/data_element.h
@@ -20,8 +20,8 @@ #include "base/logging.h" #include "base/time/time.h" #include "mojo/public/cpp/system/data_pipe.h" +#include "services/network/public/interfaces/data_pipe_getter.mojom.h" #include "storage/common/storage_common_export.h" -#include "third_party/WebKit/common/blob/size_getter.mojom.h" #include "url/gurl.h" namespace storage { @@ -67,8 +67,8 @@ const base::File& file() const { return file_; } const GURL& filesystem_url() const { return filesystem_url_; } const std::string& blob_uuid() const { return blob_uuid_; } - const mojo::DataPipeConsumerHandle& data_pipe() const { - return data_pipe_.get(); + const network::mojom::DataPipeGetterPtr& data_pipe() const { + return data_pipe_getter_; } uint64_t offset() const { return offset_; } uint64_t length() const { return length_; } @@ -174,15 +174,14 @@ void SetToDiskCacheEntryRange(uint64_t offset, uint64_t length); // Sets TYPE_DATA_PIPE data. - void SetToDataPipe(mojo::ScopedDataPipeConsumerHandle handle, - blink::mojom::SizeGetterPtr size_getter); + void SetToDataPipe(network::mojom::DataPipeGetterPtr data_pipe_getter); // Takes ownership of the File, if this is of TYPE_RAW_FILE. The file is open // for reading (asynchronous reading on Windows). base::File ReleaseFile(); - mojo::ScopedDataPipeConsumerHandle ReleaseDataPipe( - blink::mojom::SizeGetterPtr* size_getter); + // Takes ownership of the DataPipeGetter, if this is of TYPE_DATA_PIPE. + network::mojom::DataPipeGetterPtr ReleaseDataPipeGetter(); private: FRIEND_TEST_ALL_PREFIXES(BlobAsyncTransportStrategyTest, TestInvalidParams); @@ -194,9 +193,8 @@ base::FilePath path_; // For TYPE_FILE and TYPE_RAW_FILE. base::File file_; // For TYPE_RAW_FILE. GURL filesystem_url_; // For TYPE_FILE_FILESYSTEM. - std::string blob_uuid_; - mojo::ScopedDataPipeConsumerHandle data_pipe_; - blink::mojom::SizeGetterPtr data_pipe_size_getter_; + std::string blob_uuid_; // For TYPE_BLOB. + network::mojom::DataPipeGetterPtr data_pipe_getter_; // For TYPE_DATA_PIPE. uint64_t offset_; uint64_t length_; base::Time expected_modification_time_;
diff --git a/storage/common/quota/OWNERS b/storage/common/quota/OWNERS index 8c196cc..c5fd619 100644 --- a/storage/common/quota/OWNERS +++ b/storage/common/quota/OWNERS
@@ -1,2 +1,9 @@ # TEAM: storage-dev@chromium.org # COMPONENT: Blink>Storage>Quota + +per-file *.mojom=file://ipc/SECURITY_OWNERS +per-file *.mojom=set noparent +per-file *.typemap=file://ipc/SECURITY_OWNERS +per-file *.typemap=set noparent +per-file *_struct_traits*.*=file://ipc/SECURITY_OWNERS +per-file *_struct_traits*.*=set noparent
diff --git a/storage/common/quota/quota_types.mojom b/storage/common/quota/quota_types.mojom new file mode 100644 index 0000000..915a673 --- /dev/null +++ b/storage/common/quota/quota_types.mojom
@@ -0,0 +1,24 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +module storage.mojom; + +// TODO(sashab): Remove duplicate definition storage::StorageType. +enum StorageType { + kTemporary, + kPersistent, + kSyncable, + kQuotaNotManaged, + kUnknown, +}; + +// TODO(sashab): Remove duplicate definition storage::QuotaStatusCode. +enum QuotaStatusCode { + kOk = 0, + kErrorNotSupported, + kErrorInvalidModification, + kErrorInvalidAccess, + kErrorAbort, + kUnknown, +};
diff --git a/storage/common/quota/quota_types.typemap b/storage/common/quota/quota_types.typemap new file mode 100644 index 0000000..d55ef180 --- /dev/null +++ b/storage/common/quota/quota_types.typemap
@@ -0,0 +1,17 @@ +# Copyright 2017 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +mojom = "//storage/common/quota/quota_types.mojom" +public_headers = [ + "//storage/common/quota/quota_status_code.h", + "//storage/common/quota/quota_types.h", +] +traits_headers = [ "//storage/common/quota/quota_types_struct_traits.h" ] +deps = [ + "//storage/common", +] +type_mappings = [ + "storage.mojom.QuotaStatusCode=storage::QuotaStatusCode", + "storage.mojom.StorageType=storage::StorageType", +]
diff --git a/storage/common/quota/quota_types_struct_traits.h b/storage/common/quota/quota_types_struct_traits.h new file mode 100644 index 0000000..73cfb742 --- /dev/null +++ b/storage/common/quota/quota_types_struct_traits.h
@@ -0,0 +1,111 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_COMMON_QUOTA_MESSAGES_STRUCT_TRAITS_H_ +#define CONTENT_COMMON_QUOTA_MESSAGES_STRUCT_TRAITS_H_ + +#include "mojo/public/cpp/bindings/enum_traits.h" +#include "storage/common/quota/quota_status_code.h" +#include "storage/common/quota/quota_types.h" +#include "storage/common/quota/quota_types.mojom.h" + +namespace mojo { + +template <> +struct EnumTraits<storage::mojom::StorageType, storage::StorageType> { + static storage::mojom::StorageType ToMojom( + storage::StorageType storage_type) { + switch (storage_type) { + case storage::kStorageTypeTemporary: + return storage::mojom::StorageType::kTemporary; + case storage::kStorageTypePersistent: + return storage::mojom::StorageType::kPersistent; + case storage::kStorageTypeSyncable: + return storage::mojom::StorageType::kSyncable; + case storage::kStorageTypeQuotaNotManaged: + return storage::mojom::StorageType::kQuotaNotManaged; + case storage::kStorageTypeUnknown: + return storage::mojom::StorageType::kUnknown; + } + NOTREACHED(); + return storage::mojom::StorageType::kUnknown; + } + + static bool FromMojom(storage::mojom::StorageType storage_type, + storage::StorageType* out) { + switch (storage_type) { + case storage::mojom::StorageType::kTemporary: + *out = storage::kStorageTypeTemporary; + return true; + case storage::mojom::StorageType::kPersistent: + *out = storage::kStorageTypePersistent; + return true; + case storage::mojom::StorageType::kSyncable: + *out = storage::kStorageTypeSyncable; + return true; + case storage::mojom::StorageType::kQuotaNotManaged: + *out = storage::kStorageTypeQuotaNotManaged; + return true; + case storage::mojom::StorageType::kUnknown: + *out = storage::kStorageTypeUnknown; + return true; + } + NOTREACHED(); + *out = storage::kStorageTypeUnknown; + return false; + } +}; + +template <> +struct EnumTraits<storage::mojom::QuotaStatusCode, storage::QuotaStatusCode> { + static storage::mojom::QuotaStatusCode ToMojom( + storage::QuotaStatusCode status_code) { + switch (status_code) { + case storage::kQuotaStatusOk: + return storage::mojom::QuotaStatusCode::kOk; + case storage::kQuotaErrorNotSupported: + return storage::mojom::QuotaStatusCode::kErrorNotSupported; + case storage::kQuotaErrorInvalidModification: + return storage::mojom::QuotaStatusCode::kErrorInvalidModification; + case storage::kQuotaErrorInvalidAccess: + return storage::mojom::QuotaStatusCode::kErrorInvalidAccess; + case storage::kQuotaErrorAbort: + return storage::mojom::QuotaStatusCode::kErrorAbort; + case storage::kQuotaStatusUnknown: + return storage::mojom::QuotaStatusCode::kUnknown; + } + NOTREACHED(); + return storage::mojom::QuotaStatusCode::kUnknown; + } + + static bool FromMojom(storage::mojom::QuotaStatusCode status_code, + storage::QuotaStatusCode* out) { + switch (status_code) { + case storage::mojom::QuotaStatusCode::kOk: + *out = storage::kQuotaStatusOk; + return true; + case storage::mojom::QuotaStatusCode::kErrorNotSupported: + *out = storage::kQuotaErrorNotSupported; + return true; + case storage::mojom::QuotaStatusCode::kErrorInvalidModification: + *out = storage::kQuotaErrorInvalidModification; + return true; + case storage::mojom::QuotaStatusCode::kErrorInvalidAccess: + *out = storage::kQuotaErrorInvalidAccess; + return true; + case storage::mojom::QuotaStatusCode::kErrorAbort: + *out = storage::kQuotaErrorAbort; + return true; + case storage::mojom::QuotaStatusCode::kUnknown: + *out = storage::kQuotaStatusUnknown; + return true; + } + NOTREACHED(); + return false; + } +}; + +} // namespace mojo + +#endif // CONTENT_COMMON_QUOTA_MESSAGES_STRUCT_TRAITS_H_
diff --git a/storage/common/typemaps.gni b/storage/common/typemaps.gni new file mode 100644 index 0000000..e802553 --- /dev/null +++ b/storage/common/typemaps.gni
@@ -0,0 +1,5 @@ +# Copyright 2017 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +typemaps = [ "//storage/common/quota/quota_types.typemap" ]
diff --git a/testing/buildbot/chromium.android.json b/testing/buildbot/chromium.android.json index 38f6a40f..c8d1fe0 100644 --- a/testing/buildbot/chromium.android.json +++ b/testing/buildbot/chromium.android.json
@@ -601,1617 +601,6 @@ } ] }, - "Android N5X Swarm Builder": { - "additional_compile_targets": [ - "monochrome_static_initializers" - ], - "gtest_tests": [ - { - "args": [ - "--gs-results-bucket=chromium-result-details" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "android_webview_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "android_webview_unittests" - }, - { - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "base_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "hard_timeout": 960, - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "base_unittests" - }, - { - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "blink_heap_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "hard_timeout": 960, - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "blink_heap_unittests" - }, - { - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "breakpad_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "breakpad_unittests" - }, - { - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "capture_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "capture_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "hard_timeout": 960, - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "cc_unittests" - }, - { - "args": [ - "--shared-prefs-file=//chrome/android/shared_preference_files/test/vr_cardboard_skipdon_setupcomplete.json", - "--additional-apk=//third_party/gvr-android-sdk/test-apks/vr_services/vr_services_current.apk" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "chrome_public_test_vr_apk" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "hard_timeout": 1200, - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "chrome_public_test_vr_apk" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "chrome_sync_shell_test_apk" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "hard_timeout": 960, - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "chrome_sync_shell_test_apk" - }, - { - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "components_browsertests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "hard_timeout": 960, - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "components_browsertests" - }, - { - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "components_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "hard_timeout": 960, - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "shards": 2 - }, - "test": "components_unittests" - }, - { - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "content_browsertests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "hard_timeout": 1200, - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "shards": 6 - }, - "test": "content_browsertests" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "content_shell_test_apk" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "hard_timeout": 960, - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "shards": 3 - }, - "test": "content_shell_test_apk" - }, - { - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "content_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "hard_timeout": 960, - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "content_unittests" - }, - { - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "device_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "hard_timeout": 960, - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "device_unittests" - }, - { - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "events_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "events_unittests" - }, - { - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "gfx_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "hard_timeout": 960, - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "gfx_unittests" - }, - { - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "gl_tests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "gl_tests" - }, - { - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "gl_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "hard_timeout": 120, - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "gl_unittests" - }, - { - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "gpu_ipc_service_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "gpu_ipc_service_unittests" - }, - { - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "gpu_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "hard_timeout": 960, - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "gpu_unittests" - }, - { - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "ipc_tests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "ipc_tests" - }, - { - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "latency_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "latency_unittests" - }, - { - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "media_blink_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "media_blink_unittests" - }, - { - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "media_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "hard_timeout": 960, - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "media_unittests" - }, - { - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "mojo_common_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "hard_timeout": 120, - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "mojo_common_unittests" - }, - { - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "mojo_public_bindings_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "hard_timeout": 120, - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "mojo_public_bindings_unittests" - }, - { - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "mojo_public_system_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "hard_timeout": 120, - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "mojo_public_system_unittests" - }, - { - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "mojo_system_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "hard_timeout": 300, - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "mojo_system_unittests" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "mojo_test_apk" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "hard_timeout": 300, - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "mojo_test_apk" - }, - { - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "net_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "hard_timeout": 960, - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "shards": 3 - }, - "test": "net_unittests" - }, - { - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "sandbox_linux_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "sandbox_linux_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "hard_timeout": 300, - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "services_unittests" - }, - { - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "sql_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "sql_unittests" - }, - { - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "storage_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "storage_unittests" - }, - { - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "ui_android_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "ui_android_unittests" - }, - { - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "ui_base_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "ui_base_unittests" - }, - { - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "ui_touch_selection_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "ui_touch_selection_unittests" - }, - { - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "unit_tests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "hard_timeout": 960, - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "shards": 2 - }, - "test": "unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "hard_timeout": 960, - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "viz_unittests" - }, - { - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "vr_common_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "hard_timeout": 960, - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ] - }, - "test": "vr_common_unittests" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "webview_instrumentation_test_apk" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead" - } - ], - "hard_timeout": 1200, - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "shards": 8 - }, - "test": "webview_instrumentation_test_apk" - } - ], - "isolated_scripts": [ - { - "args": [ - "--browser=android-chromium", - "--device=android" - ], - "isolate_name": "telemetry_perf_unittests", - "name": "telemetry_perf_unittests", - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "device_os": "MMB29Q", - "device_type": "bullhead", - "temp_band": "<30" - } - ], - "hard_timeout": 1500, - "shards": 15 - } - } - ] - }, "Android WebView L (dbg)": { "cts_tests": [ { @@ -6221,7 +4610,7 @@ } ], "expiration": 10800, - "hard_timeout": 1500, + "hard_timeout": 1800, "output_links": [ { "link": [ @@ -7429,7 +5818,7 @@ } ], "expiration": 10800, - "hard_timeout": 960, + "hard_timeout": 1800, "output_links": [ { "link": [ @@ -8948,7 +7337,7 @@ } ], "expiration": 10800, - "hard_timeout": 1200, + "hard_timeout": 1800, "output_links": [ { "link": [ @@ -13474,7 +11863,7 @@ } ], "expiration": 10800, - "hard_timeout": 1200, + "hard_timeout": 1800, "output_links": [ { "link": [
diff --git a/testing/buildbot/chromium.clang.json b/testing/buildbot/chromium.clang.json index 0d24b571..77164e3b 100644 --- a/testing/buildbot/chromium.clang.json +++ b/testing/buildbot/chromium.clang.json
@@ -1055,272 +1055,6 @@ } ] }, - "CrWinAsan tester": { - "gtest_tests": [ - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "angle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 10 - }, - "test": "browser_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cacheinvalidation_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "capture_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_app_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_elf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "components_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_browsertests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "courgette_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crypto_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "device_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "extensions_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gcm_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "google_apis_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_ipc_service_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "installer_util_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ipc_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "jingle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_blink_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "midi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "native_theme_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "net_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "pdf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ppapi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "printing_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "remoting_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "sbox_integration_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_validation_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "setup_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "skia_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sql_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ui_base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "url_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "views_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "zucchini_unittests" - } - ] - }, "CrWinAsan(dll)": { "gtest_tests": [ { @@ -1587,272 +1321,6 @@ } ] }, - "CrWinAsan(dll) tester": { - "gtest_tests": [ - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "angle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 10 - }, - "test": "browser_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cacheinvalidation_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "capture_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_app_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_elf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "components_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_browsertests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "courgette_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crypto_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "device_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "extensions_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gcm_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "google_apis_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_ipc_service_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "installer_util_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ipc_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "jingle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_blink_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "midi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "native_theme_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "net_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "pdf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ppapi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "printing_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "remoting_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "sbox_integration_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_validation_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "setup_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "skia_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sql_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ui_base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "url_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "views_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "zucchini_unittests" - } - ] - }, "CrWinAsanCov": { "gtest_tests": [ { @@ -2100,253 +1568,6 @@ } ] }, - "CrWinAsanCov tester": { - "gtest_tests": [ - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "angle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cacheinvalidation_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "capture_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_app_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_elf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "components_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_browsertests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "courgette_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crypto_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "device_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "extensions_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gcm_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "google_apis_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_ipc_service_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "installer_util_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ipc_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "jingle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_blink_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "midi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "native_theme_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "pdf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ppapi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "printing_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "remoting_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "sbox_integration_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_validation_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "setup_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "skia_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sql_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ui_base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "url_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "views_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "zucchini_unittests" - } - ] - }, "CrWinClang": { "gtest_tests": [ { @@ -2649,308 +1870,6 @@ } ] }, - "CrWinClang tester": { - "gtest_tests": [ - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "angle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_heap_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_platform_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 10 - }, - "test": "browser_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cacheinvalidation_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "capture_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_app_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_elf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "components_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_browsertests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "courgette_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crashpad_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crypto_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "device_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "extensions_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gcm_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "google_apis_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_ipc_service_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "installer_util_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ipc_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "jingle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_blink_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "midi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "native_theme_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "net_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "pdf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ppapi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "printing_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "remoting_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "sbox_integration_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_validation_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "services_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "setup_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "skia_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sql_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ui_base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "url_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "views_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "webkit_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "wtf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "zucchini_unittests" - } - ] - }, "CrWinClang(dbg)": { "gtest_tests": [ { @@ -3253,308 +2172,6 @@ } ] }, - "CrWinClang(dbg) tester": { - "gtest_tests": [ - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "angle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_heap_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_platform_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 20 - }, - "test": "browser_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cacheinvalidation_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "capture_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_app_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_elf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "components_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_browsertests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "courgette_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crashpad_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crypto_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "device_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "extensions_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gcm_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "google_apis_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_ipc_service_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "installer_util_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ipc_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "jingle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_blink_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "midi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "native_theme_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "net_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "pdf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ppapi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "printing_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "remoting_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "sbox_integration_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_validation_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "services_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "setup_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "skia_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sql_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ui_base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "url_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "views_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "webkit_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "wtf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "zucchini_unittests" - } - ] - }, "CrWinClang(shared)": { "gtest_tests": [ { @@ -3857,308 +2474,6 @@ } ] }, - "CrWinClang(shared) tester": { - "gtest_tests": [ - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "angle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_heap_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_platform_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 10 - }, - "test": "browser_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cacheinvalidation_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "capture_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_app_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_elf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "components_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_browsertests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "courgette_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crashpad_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crypto_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "device_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "extensions_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gcm_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "google_apis_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_ipc_service_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "installer_util_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ipc_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "jingle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_blink_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "midi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "native_theme_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "net_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "pdf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ppapi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "printing_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "remoting_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "sbox_integration_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_validation_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "services_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "setup_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "skia_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sql_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ui_base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "url_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "views_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "webkit_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "wtf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "zucchini_unittests" - } - ] - }, "CrWinClang64": { "gtest_tests": [ { @@ -4461,308 +2776,6 @@ } ] }, - "CrWinClang64 tester": { - "gtest_tests": [ - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "angle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_heap_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_platform_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 10 - }, - "test": "browser_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cacheinvalidation_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "capture_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_app_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_elf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "components_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_browsertests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "courgette_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crashpad_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crypto_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "device_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "extensions_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gcm_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "google_apis_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_ipc_service_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "installer_util_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ipc_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "jingle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_blink_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "midi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "native_theme_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "net_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "pdf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ppapi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "printing_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "remoting_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "sbox_integration_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_validation_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "services_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "setup_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "skia_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sql_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ui_base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "url_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "views_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "webkit_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "wtf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "zucchini_unittests" - } - ] - }, "CrWinClang64(dbg)": { "gtest_tests": [ { @@ -5065,308 +3078,6 @@ } ] }, - "CrWinClang64(dbg) tester": { - "gtest_tests": [ - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "angle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_heap_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_platform_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 20 - }, - "test": "browser_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cacheinvalidation_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "capture_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_app_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_elf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "components_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_browsertests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "courgette_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crashpad_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crypto_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "device_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "extensions_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gcm_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "google_apis_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_ipc_service_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "installer_util_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ipc_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "jingle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_blink_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "midi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "native_theme_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "net_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "pdf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ppapi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "printing_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "remoting_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "sbox_integration_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_validation_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "services_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "setup_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "skia_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sql_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ui_base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "url_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "views_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "webkit_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "wtf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "zucchini_unittests" - } - ] - }, "CrWinClang64(dll)": { "gtest_tests": [ { @@ -5669,308 +3380,6 @@ } ] }, - "CrWinClang64(dll) tester": { - "gtest_tests": [ - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "angle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_heap_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_platform_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 10 - }, - "test": "browser_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cacheinvalidation_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "capture_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_app_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_elf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "components_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_browsertests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "courgette_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crashpad_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crypto_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "device_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "extensions_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gcm_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "google_apis_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_ipc_service_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "installer_util_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ipc_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "jingle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_blink_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "midi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "native_theme_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "net_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "pdf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ppapi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "printing_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "remoting_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "sbox_integration_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_validation_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "services_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "setup_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "skia_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sql_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ui_base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "url_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "views_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "webkit_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "wtf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "zucchini_unittests" - } - ] - }, "CrWinClangLLD": { "gtest_tests": [ { @@ -6273,308 +3682,6 @@ } ] }, - "CrWinClangLLD tester": { - "gtest_tests": [ - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "angle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_heap_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_platform_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 10 - }, - "test": "browser_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cacheinvalidation_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "capture_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_app_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_elf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "components_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_browsertests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "courgette_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crashpad_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crypto_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "device_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "extensions_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gcm_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "google_apis_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_ipc_service_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "installer_util_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ipc_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "jingle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_blink_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "midi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "native_theme_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "net_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "pdf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ppapi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "printing_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "remoting_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "sbox_integration_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_validation_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "services_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "setup_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "skia_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sql_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ui_base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "url_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "views_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "webkit_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "wtf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "zucchini_unittests" - } - ] - }, "CrWinClangLLD64": { "gtest_tests": [ { @@ -6877,308 +3984,6 @@ } ] }, - "CrWinClangLLD64 tester": { - "gtest_tests": [ - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "angle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_heap_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_platform_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 10 - }, - "test": "browser_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cacheinvalidation_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "capture_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_app_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_elf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "components_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_browsertests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "courgette_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crashpad_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crypto_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "device_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "extensions_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gcm_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "google_apis_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_ipc_service_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "installer_util_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ipc_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "jingle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_blink_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "midi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "native_theme_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "net_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "pdf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ppapi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "printing_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "remoting_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "sbox_integration_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_validation_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "services_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "setup_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "skia_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sql_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ui_base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "url_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "views_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "webkit_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "wtf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "zucchini_unittests" - } - ] - }, "CrWinClngLLD64dbg": { "gtest_tests": [ { @@ -7475,302 +4280,6 @@ } ] }, - "CrWinClngLLD64dbg tester": { - "gtest_tests": [ - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "angle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_heap_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_platform_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 10 - }, - "test": "browser_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cacheinvalidation_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "capture_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_app_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_elf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "components_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_browsertests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "courgette_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crashpad_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crypto_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "device_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "extensions_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gcm_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "google_apis_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "installer_util_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ipc_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "jingle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_blink_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "midi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "native_theme_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "net_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "pdf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ppapi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "printing_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "remoting_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "sbox_integration_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_validation_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "services_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "setup_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "skia_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sql_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ui_base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "url_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "views_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "webkit_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "wtf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "zucchini_unittests" - } - ] - }, "CrWinClngLLDdbg": { "gtest_tests": [ { @@ -8073,308 +4582,6 @@ } ] }, - "CrWinClngLLDdbg tester": { - "gtest_tests": [ - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "angle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_heap_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_platform_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 10 - }, - "test": "browser_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cacheinvalidation_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "capture_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_app_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_elf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "components_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_browsertests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "courgette_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crashpad_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crypto_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "device_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "extensions_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gcm_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "google_apis_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_ipc_service_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "installer_util_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ipc_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "jingle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_blink_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "midi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "native_theme_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "net_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "pdf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ppapi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "printing_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "remoting_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "sbox_integration_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_validation_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "services_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "setup_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "skia_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sql_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ui_base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "url_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "views_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "webkit_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "wtf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "zucchini_unittests" - } - ] - }, "ToTAndroid": { "additional_compile_targets": [ "all" @@ -9822,365 +6029,6 @@ "all" ] }, - "ToTLinux tester": { - "gtest_tests": [ - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "accessibility_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "angle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "app_shell_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "aura_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_heap_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_platform_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 5 - }, - "test": "browser_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cacheinvalidation_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "capture_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cast_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cc_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chromedriver_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "components_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "compositor_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_browsertests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crypto_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "dbus_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "device_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "display_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "events_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "extensions_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gcm_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gfx_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "google_apis_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_ipc_service_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "interactive_ui_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ipc_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "jingle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_blink_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "midi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "mojo_common_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "mojo_public_bindings_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "mojo_public_system_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "mojo_system_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "nacl_helper_nonsfi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "nacl_loader_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "native_theme_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "net_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "pdf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ppapi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "printing_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "remoting_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sandbox_linux_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "services_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "skia_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sql_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "storage_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ui_base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ui_touch_selection_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "url_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "views_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "webkit_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "wm_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "wtf_unittests" - } - ] - }, "ToTLinuxASan": { "additional_compile_targets": [ "all" @@ -10449,271 +6297,6 @@ } ] }, - "ToTLinuxASan tester": { - "gtest_tests": [ - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "accessibility_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "angle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_heap_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_platform_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 5 - }, - "test": "browser_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cacheinvalidation_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "capture_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cast_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cc_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "components_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_browsertests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crypto_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "device_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "display_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "extensions_browsertests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "extensions_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gcm_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gfx_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "google_apis_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_ipc_service_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "interactive_ui_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ipc_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "jingle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_blink_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "midi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 4 - }, - "test": "net_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "pdf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ppapi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "printing_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "remoting_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sandbox_linux_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "services_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "skia_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sql_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ui_base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 2 - }, - "test": "unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "url_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "webkit_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "wtf_unittests" - } - ] - }, "ToTLinuxLLD": { "additional_compile_targets": [ "all" @@ -11064,353 +6647,6 @@ } ] }, - "ToTLinuxLLD tester": { - "gtest_tests": [ - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "accessibility_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "angle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "app_shell_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "aura_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_heap_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_platform_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 5 - }, - "test": "browser_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cacheinvalidation_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "capture_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cast_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cc_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chromedriver_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "components_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "compositor_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_browsertests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crypto_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "dbus_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "device_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "display_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "events_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "extensions_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gcm_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gfx_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "google_apis_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "interactive_ui_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ipc_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "jingle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_blink_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "midi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "mojo_common_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "mojo_public_bindings_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "mojo_public_system_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "mojo_system_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "nacl_helper_nonsfi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "nacl_loader_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "native_theme_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "net_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "pdf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ppapi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "printing_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "remoting_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sandbox_linux_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "services_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "skia_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sql_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ui_base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ui_touch_selection_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "url_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "views_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "webkit_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "wm_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "wtf_unittests" - } - ] - }, "ToTLinuxMSan": { "gtest_tests": [ { @@ -12350,251 +7586,6 @@ } ] }, - "ToTLinuxUBSanVptr tester": { - "gtest_tests": [ - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "accessibility_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "angle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_heap_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_platform_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cacheinvalidation_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cast_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cc_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 5 - }, - "test": "content_browsertests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crypto_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "device_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "display_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "extensions_browsertests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "extensions_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gcm_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gfx_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "google_apis_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_ipc_service_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ipc_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "jingle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_blink_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "midi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "native_theme_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "net_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "pdf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ppapi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "printing_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "remoting_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sandbox_linux_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "services_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "skia_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sql_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ui_base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "url_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "views_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "webkit_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "wtf_unittests" - } - ] - }, "ToTMac": { "gtest_tests": [ { @@ -12927,338 +7918,6 @@ } ] }, - "ToTMac tester": { - "gtest_tests": [ - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "accessibility_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "angle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 5 - }, - "test": "base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_heap_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_platform_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 10 - }, - "test": "browser_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cacheinvalidation_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "capture_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cast_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cc_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chromedriver_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "components_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_browsertests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crashpad_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crypto_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "display_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "extensions_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gcm_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gfx_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "google_apis_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_ipc_service_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "interactive_ui_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ipc_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "jingle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_blink_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "midi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "mojo_common_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "mojo_public_bindings_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "mojo_public_system_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "mojo_system_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "native_theme_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "net_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "pdf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ppapi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "printing_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "remoting_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sandbox_mac_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "services_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "skia_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sql_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sync_integration_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ui_base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "url_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "views_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "webkit_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "wtf_unittests" - } - ], - "isolated_scripts": [ - { - "isolate_name": "telemetry_gpu_unittests", - "name": "telemetry_gpu_unittests", - "swarming": { - "can_use_on_swarming_builders": true - } - }, - { - "isolate_name": "telemetry_perf_unittests", - "name": "telemetry_perf_unittests", - "swarming": { - "can_use_on_swarming_builders": true, - "hard_timeout": 960, - "shards": 12 - } - }, - { - "isolate_name": "telemetry_unittests", - "name": "telemetry_unittests", - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 2 - } - } - ] - }, "ToTMacASan": { "gtest_tests": [ { @@ -13546,293 +8205,6 @@ } ] }, - "ToTMacASan tester": { - "gtest_tests": [ - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "accessibility_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "angle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_heap_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_platform_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 10 - }, - "test": "browser_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cacheinvalidation_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "capture_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cast_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cc_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chromedriver_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "components_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_browsertests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crypto_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "display_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "extensions_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gcm_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gfx_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "google_apis_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_ipc_service_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "interactive_ui_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ipc_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "jingle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_blink_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "midi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "mojo_common_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "mojo_public_bindings_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "mojo_public_system_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "mojo_system_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "net_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "pdf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ppapi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "printing_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "remoting_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sandbox_mac_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "services_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "skia_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sql_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sync_integration_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ui_base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "url_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "webkit_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "wtf_unittests" - } - ] - }, "ToTWin": { "gtest_tests": [ { @@ -14147,320 +8519,6 @@ } ] }, - "ToTWin tester": { - "gtest_tests": [ - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "angle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_heap_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_platform_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 10 - }, - "test": "browser_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cacheinvalidation_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "capture_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_app_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_elf_import_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_elf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "components_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_browsertests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "courgette_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crashpad_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crypto_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "device_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "extensions_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gcm_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "google_apis_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_ipc_service_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "install_static_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "installer_util_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ipc_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "jingle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_blink_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "midi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "native_theme_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "net_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "pdf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ppapi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "printing_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "remoting_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "sbox_integration_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_validation_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "services_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "setup_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "skia_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sql_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ui_base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "url_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "views_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "webkit_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "wtf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "zucchini_unittests" - } - ] - }, "ToTWin(dbg)": { "gtest_tests": [ { @@ -14769,314 +8827,6 @@ } ] }, - "ToTWin(dbg) tester": { - "gtest_tests": [ - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "angle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_heap_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_platform_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 20 - }, - "test": "browser_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cacheinvalidation_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "capture_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_app_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_elf_import_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_elf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "components_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_browsertests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "courgette_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crashpad_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crypto_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "device_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "extensions_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gcm_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "google_apis_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_ipc_service_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "installer_util_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ipc_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "jingle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_blink_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "midi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "native_theme_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "net_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "pdf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ppapi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "printing_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "remoting_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "sbox_integration_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_validation_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "services_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "setup_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "skia_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sql_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ui_base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "url_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "views_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "webkit_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "wtf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "zucchini_unittests" - } - ] - }, "ToTWin(dll)": { "gtest_tests": [ { @@ -15379,308 +9129,6 @@ } ] }, - "ToTWin(dll) tester": { - "gtest_tests": [ - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "angle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_heap_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_platform_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 10 - }, - "test": "browser_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cacheinvalidation_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "capture_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_app_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_elf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "components_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_browsertests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "courgette_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crashpad_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crypto_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "device_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "extensions_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gcm_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "google_apis_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_ipc_service_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "installer_util_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ipc_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "jingle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_blink_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "midi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "native_theme_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "net_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "pdf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ppapi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "printing_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "remoting_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "sbox_integration_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_validation_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "services_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "setup_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "skia_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sql_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ui_base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "url_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "views_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "webkit_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "wtf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "zucchini_unittests" - } - ] - }, "ToTWin64": { "gtest_tests": [ { @@ -15983,308 +9431,6 @@ } ] }, - "ToTWin64 tester": { - "gtest_tests": [ - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "angle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_heap_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_platform_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 10 - }, - "test": "browser_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cacheinvalidation_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "capture_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_app_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_elf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "components_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_browsertests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "courgette_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crashpad_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crypto_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "device_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "extensions_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gcm_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "google_apis_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_ipc_service_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "installer_util_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ipc_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "jingle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_blink_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "midi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "native_theme_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "net_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "pdf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ppapi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "printing_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "remoting_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "sbox_integration_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_validation_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "services_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "setup_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "skia_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sql_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ui_base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "url_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "views_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "webkit_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "wtf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "zucchini_unittests" - } - ] - }, "ToTWin64(dbg)": { "gtest_tests": [ { @@ -16587,308 +9733,6 @@ } ] }, - "ToTWin64(dbg) tester": { - "gtest_tests": [ - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "angle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_heap_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_platform_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 20 - }, - "test": "browser_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cacheinvalidation_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "capture_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_app_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_elf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "components_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_browsertests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "courgette_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crashpad_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crypto_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "device_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "extensions_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gcm_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "google_apis_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_ipc_service_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "installer_util_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ipc_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "jingle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_blink_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "midi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "native_theme_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "net_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "pdf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ppapi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "printing_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "remoting_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "sbox_integration_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_validation_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "services_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "setup_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "skia_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sql_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ui_base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "url_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "views_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "webkit_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "wtf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "zucchini_unittests" - } - ] - }, "ToTWin64(dll)": { "gtest_tests": [ { @@ -17191,308 +10035,6 @@ } ] }, - "ToTWin64(dll) tester": { - "gtest_tests": [ - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "angle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_heap_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "blink_platform_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 10 - }, - "test": "browser_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "cacheinvalidation_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "capture_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_app_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "chrome_elf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "components_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_browsertests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "content_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "courgette_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crashpad_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "crypto_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "device_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "extensions_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gcm_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "google_apis_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_ipc_service_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "gpu_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "installer_util_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ipc_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "jingle_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_blink_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "media_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "midi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "native_theme_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "net_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "pdf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ppapi_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "printing_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "remoting_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "sbox_integration_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sbox_validation_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "services_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true, - "dimension_sets": [ - { - "integrity": "high" - } - ] - }, - "test": "setup_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "skia_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "sql_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "ui_base_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "url_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "views_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "webkit_unit_tests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "wtf_unittests" - }, - { - "swarming": { - "can_use_on_swarming_builders": true - }, - "test": "zucchini_unittests" - } - ] - }, "ToTWinCFI": { "gtest_tests": [ {
diff --git a/testing/buildbot/chromium.fyi.json b/testing/buildbot/chromium.fyi.json index 9ab24ad..a4aa513c 100644 --- a/testing/buildbot/chromium.fyi.json +++ b/testing/buildbot/chromium.fyi.json
@@ -14,6 +14,13 @@ "name": "chrome_public_test_vr_apk-nonddready-cardboard-current-kitkat", "swarming": { "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], "dimension_sets": [ { "device_os": "KTU84P", @@ -32,6 +39,13 @@ "name": "chrome_public_test_vr_apk-nonddready-cardboard-current-lollipop", "swarming": { "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], "dimension_sets": [ { "device_os": "LMY48I", @@ -50,6 +64,13 @@ "name": "chrome_public_test_vr_apk-nonddready-cardboard-current-marshmallow", "swarming": { "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], "dimension_sets": [ { "device_os": "MMB29Q", @@ -68,6 +89,13 @@ "name": "chrome_public_test_vr_apk-marlin-cardboard-nougat", "swarming": { "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], "dimension_sets": [ { "device_os": "NMF26U", @@ -86,6 +114,13 @@ "name": "chrome_public_test_vr_apk-marlin-ddview-nougat", "swarming": { "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], "dimension_sets": [ { "device_os": "NMF26U", @@ -106,6 +141,13 @@ "name": "chrome_public_test_vr_apk-marlin-ddview-nougat-donenabled", "swarming": { "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], "dimension_sets": [ { "device_os": "NMF26U", @@ -137,6 +179,13 @@ "name": "webview_instrumentation_test_apk-marlin-ddview-nougat", "swarming": { "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], "dimension_sets": [ { "device_os": "NMF26U", @@ -2322,7 +2371,7 @@ } ] }, - "Chromium Mac 10.9 Goma Canary LocalOutputCache": { + "Chromium Mac Goma Canary LocalOutputCache": { "additional_compile_targets": [ "all" ],
diff --git a/testing/buildbot/chromium.linux.json b/testing/buildbot/chromium.linux.json index 8248ac5..4779202 100644 --- a/testing/buildbot/chromium.linux.json +++ b/testing/buildbot/chromium.linux.json
@@ -3689,18 +3689,6 @@ "test": "compositor_unittests" }, { - "args": [ - "--enable-viz", - "--test-launcher-filter-file=../../testing/buildbot/filters/viz.content_browsertests.filter" - ], - "name": "viz_content_browsertests", - "swarming": { - "can_use_on_swarming_builders": true, - "shards": 2 - }, - "test": "content_browsertests" - }, - { "swarming": { "can_use_on_swarming_builders": true }, @@ -3728,6 +3716,18 @@ "test": "content_browsertests" }, { + "args": [ + "--enable-viz", + "--test-launcher-filter-file=../../testing/buildbot/filters/viz.content_browsertests.filter" + ], + "name": "viz_content_browsertests", + "swarming": { + "can_use_on_swarming_builders": true, + "shards": 2 + }, + "test": "content_browsertests" + }, + { "swarming": { "can_use_on_swarming_builders": true }, @@ -4193,12 +4193,12 @@ "script": "checkdeps.py" }, { - "name": "webkit_lint", - "script": "webkit_lint.py" - }, - { "name": "checkperms", "script": "checkperms.py" + }, + { + "name": "webkit_lint", + "script": "webkit_lint.py" } ] }, @@ -4672,7 +4672,7 @@ }, { "args": [ - "--site_per_process" + "--site-per-process" ], "name": "site_per_process_unit_tests", "swarming": {
diff --git a/testing/buildbot/filters/mojo.fyi.network_browser_tests.filter b/testing/buildbot/filters/mojo.fyi.network_browser_tests.filter index 7efcd0dc..a22c902c 100644 --- a/testing/buildbot/filters/mojo.fyi.network_browser_tests.filter +++ b/testing/buildbot/filters/mojo.fyi.network_browser_tests.filter
@@ -901,9 +901,4 @@ -NoStatePrefetchBrowserTest/NoStatePrefetchBrowserTest.Prefetch301LoadFlags/0 -NoStatePrefetchBrowserTest/NoStatePrefetchBrowserTest.Prefetch301LoadFlags/1 -NoStatePrefetchBrowserTest/NoStatePrefetchBrowserTest.PrefetchLoadFlag/0 --NoStatePrefetchBrowserTest/NoStatePrefetchBrowserTest.PrefetchLoadFlag/1 - -# Started failing after r519463 --SBNavigationObserverBrowserTest.DownloadViaHTML5FileApiWithoutUserGesture --SBNavigationObserverBrowserTest.DownloadViaHTML5FileApiWithUserGesture --DownloadTest.CloseNewTab4 +-NoStatePrefetchBrowserTest/NoStatePrefetchBrowserTest.PrefetchLoadFlag/1 \ No newline at end of file
diff --git a/testing/libfuzzer/efficient_fuzzer.md b/testing/libfuzzer/efficient_fuzzer.md index 308f62cc..ce0a8365 100644 --- a/testing/libfuzzer/efficient_fuzzer.md +++ b/testing/libfuzzer/efficient_fuzzer.md
@@ -1,54 +1,60 @@ # Efficient Fuzzer -This document describes ways to determine your fuzzer efficiency and ways +This document describes ways to determine your fuzzer efficiency and ways to improve it. ## Overview Being a coverage-driven fuzzer, libFuzzer considers a certain input *interesting* -if it results in new coverage. The set of all interesting inputs is called -*corpus*. -Items in corpus are constantly mutated in search of new interesting input. -Corpus is usually maintained between multiple fuzzer runs. +if it results in new code coverage. The set of all interesting inputs is called +*corpus*. -Following things can be so effective for a fuzzer, that we *strongly recommend* -for any fuzzer: +Items in corpus are constantly mutated in search of new interesting inputs. +Corpus can be shared across fuzzer runs and grows over time as new code is +reached. -* [seed corpus](#Seed-Corpus) gives your fuzzer examples of input. -* [fuzzer dictionary](#Fuzzer-Dictionary) improves fuzzer mutations by using - supplied dictionary. +The following things are extremely effective for improving fuzzer efficiency, so we +*strongly recommend* them for any fuzzer: + +* [Seed Corpus](#Seed-Corpus) +* [Fuzzer Fictionary](#Fuzzer-Dictionary) There are several metrics you should look at to determine your fuzzer effectiveness: -* [fuzzer speed](#Fuzzer-Speed) (exec/s) -* [corpus size](#Corpus-Size) -* [coverage](#Coverage) +* [Fuzzer Speed](#Fuzzer-Speed) +* [Corpus Size](#Corpus-Size) +* [Coverage](#Coverage) You can collect these metrics manually or take them from [ClusterFuzz status] -pages. +pages after a fuzzer is checked in Chromium repository. ## Seed Corpus -You can pass a corpus directory to a fuzzer that you run manually: +Seed corpus is a set of *valid* and *interesting* inputs that serve as starting points +for a fuzzer. If one is not provided, a fuzzer would have to guess these inputs +from scratch, which can take an indefinite amount of time depending of the size +of inputs. + +Seed corpus works especially well for strictly defined file formats and data +transmission protocols. + +* For file format parsers, add valid files from your test suite. +* For protocol parsers, add valid raw streams from test suite into separate files. + +Other examples include a graphics library seed corpus, which would be a variety of +small PNG/JPG/GIF files. + +If you are running the fuzzer locally, you can pass a corpus directory as an argument: ``` ./out/libfuzzer/my_fuzzer ~/tmp/my_fuzzer_corpus ``` -The directory can initially be empty. The fuzzer would store all the interesting -items it finds in the directory. You can help the fuzzer by "seeding" the corpus: -simply copy interesting inputs for your function to the corpus directory before -running. This works especially well for strictly defined file formats or data -transmission protocols. +While libFuzzer can start with an empty corpus, most fuzzers require a seed corpus +to be useful. The fuzzer would store all the interesting items it finds in that directory. -* For file-parsing functionality just use some valid files from your test suite. - -* For protocol processing targets put raw streams from test suite into separate -files. - - -ClusterFuzz uses seed corpus stored in Chromium repository. You need to add -`seed_corpus` attribute to fuzzer target: +ClusterFuzz uses seed corpus defined in Chromium source repository. You need to +add a `seed_corpus` attribute to your fuzzer definition in BUILD.gn file: ``` fuzzer_test("my_protocol_fuzzer") { @@ -68,33 +74,90 @@ } ``` -All files found in the directories and their subdirectories will be archived -into `%YOUR_FUZZER_NAME%_seed_corpus.zip` output archive. +All files found in these directories and their subdirectories will be archived +into a `<my_fuzzer_name>_seed_corpus.zip` output archive. -If you don't want to store seed corpus in Chromium repository, you can upload -corpus to Google Cloud Storage bucket used by ClusterFuzz: +If you can't store seed corpus in Chromium repository (e.g. it is too large, has +licensing issues, etc), you can upload the corpus to Google Cloud Storage bucket +used by ClusterFuzz: +1) Go to [Corpus GCS Bucket]. +2) Open directory named `<my_fuzzer_name>_static`. If the directory does not +exist, please create it. +3) Upload corpus files into the directory. -1) go to [Corpus GCS Bucket] - -2) open directory named `%YOUR_FUZZER_NAME%_static` - -3) upload corpus files into the directory - - -Alternative way is to use `gsutil` tool: +Alternative and faster way is to use [gsutil] command line tool: ```bash -gsutil -m rsync <corpus_dir_on_disk> gs://clusterfuzz-corpus/libfuzzer/%YOUR_FUZZER_NAME%_static +gsutil -m rsync <path_to_corpus> gs://clusterfuzz-corpus/libfuzzer/<my_fuzzer_name>_static ``` +## Fuzzer Dictionary + +It is very useful to provide fuzzer a set of *common words or values* that you +expect to find in the input. Adding a dictionary highly improves the efficiency of +finding new units and works especially well in certain usecases (e.g. fuzzing file +format decoders). + +To add a dictionary, first create a dictionary file. Dictionary file is a flat text file +where tokens are listed one per line in the format of name="value". The +alphanumeric name is ignored and can be omitted, although it is a convenient +way to document the meaning of a particular token. The value must appear in +quotes, with hex escaping (\xNN) applied to all non-printable, high-bit, or +otherwise problematic characters (\\ and \" shorthands are recognized too). +This syntax is similar to the one used by [AFL] fuzzing engine (-x option). + +An examples dictionary looks like: + +``` +# Lines starting with '#' and empty lines are ignored. + +# Adds "blah" word (w/o quotes) to the dictionary. +kw1="blah" +# Use \\ for backslash and \" for quotes. +kw2="\"ac\\dc\"" +# Use \xAB for hex values. +kw3="\xF7\xF8" +# Key name before '=' can be omitted: +"foo\x0Abar" +``` + +Make sure to test your dictionary by running your fuzzer locally: + +```bash +./out/libfuzzer/my_protocol_fuzzer -dict=<path_to_dict> <path_to_corpus> +``` + +If the dictionary is effective, you should see new units discovered in fuzzer output. + +To submit a dictionary to Chromium repository: + +1) Add the dictionary file in the same directory as your fuzz target, with name +`<my_fuzzer>.dict`. +2) Add `dict` attribute to fuzzer definition in BUILD.gn file: + +``` +fuzzer_test("my_protocol_fuzzer") { + ... + dict = "my_protocol_fuzzer.dict" +} +``` + +The dictionary will be used automatically by ClusterFuzz once it picks up a new +revision build. + ### Corpus Minimization -It's important to minimize seed corpus before uploading. The minimization can -be done with `-merge=1` option of libFuzzer: +It's important to minimize seed corpus to a *small set of interesting inputs* before +uploading. The reason being that seed corpus is synced to all fuzzing bots for every +iteration, so it is important to keep it small both for fuzzing efficiency and to prevent +our bots from running out of disk space (should not exceed 1 Gb). + +The minimization can be done using `-merge=1` option of libFuzzer: ```bash # Create an empty directory. mkdir seed_corpus_minimized + # Run the fuzzer with -merge=1 flag. ./my_fuzzer -merge=1 ./seed_corpus_minimized ./seed_corpus ``` @@ -103,102 +166,70 @@ a minimized corpus that gives the same code coverage as the initial `seed_corpus` directory. - -## Fuzzer Dictionary - -It is very useful to provide fuzzer a set of common words/values that you expect -to find in the input. This greatly improves efficiency of finding new units and -works especially well while fuzzing file format decoders. - -To add a dictionary, first create a dictionary file. -Dictionary syntax is similar to that used by [AFL] for its -x option: - -``` -# Lines starting with '#' and empty lines are ignored. - -# Adds "blah" (w/o quotes) to the dictionary. -kw1="blah" -# Use \\ for backslash and \" for quotes. -kw2="\"ac\\dc\"" -# Use \xAB for hex values -kw3="\xF7\xF8" -# the name of the keyword followed by '=' may be omitted: -"foo\x0Abar" -``` - -Test your dictionary by running your fuzzer locally: - -```bash -./out/libfuzzer/my_protocol_fuzzer -dict=<path_to_dict> <path_to_corpus> -``` - -You should see lots of new units discovered. - -Add `dict` attribute to fuzzer target: - -``` -fuzzer_test("my_protocol_fuzzer") { - ... - dict = "protocol.dict" -} -``` - -Make sure to submit dictionary file to git. The dictionary will be used -automatically by ClusterFuzz once it picks up new fuzzer version (once a day). - ## Fuzzer Speed -Fuzzer speed is printed while fuzzer runs: +Fuzzer speed is calculated in executions per second. It is printed while the fuzzer +is running: ``` #19346 NEW cov: 2815 bits: 1082 indir: 43 units: 150 exec/s: 19346 L: 62 ``` -Because libFuzzer performs randomized search, it is critical to have it as fast -as possible. You should try to get to at least 1,000 exec/s. Profile the fuzzer +Because libFuzzer performs randomized mutations, it is critical to have it run as +fast as possible to navigate the large search space efficiently and find interesting +code paths. You should try to get to at least 1,000 exec/s from your fuzzer runs +locally before submitting the fuzzer to Chromium repository. Profile the fuzzer using any standard tool to see where it spends its time. ### Initialization/Cleanup -Try to keep your fuzzing function as simple as possible. Prefer to use static -initialization and shared resources rather than bringing environment up and down -every single run. +Try to keep `LLVMFuzzerTestOneInput` function as simple as possible. If your fuzzing +function is too complex, it can bring down fuzzer execution speed OR it might target +very specific usecases and fail to account for unexpected scenarios. -Fuzzers don't have to shutdown gracefully (we either kill them or they crash -because sanitizer has found a problem). You can skip freeing static resource. +Prefer to use static initialization and shared resources rather than bringing the +environment up and down on every single run. Otherwise, it will slow down +fuzzer speed on every run and its ability to find new interesting inputs. +Checkout example on [startup initialization] in libFuzzer documentation. -Of course all resources allocated within `LLVMFuzzerTestOneInput` function -should be deallocated since this function is called millions of times during -one fuzzing session. +Fuzzers don't have to shutdown gracefully. We either kill them or they crash +because memory sanitizer tool found a problem. You can skip freeing static +resources. + +All resources allocated within `LLVMFuzzerTestOneInput` function should be +de-allocated since this function is called millions of times during a fuzzing session. +Otherwise, we will hit OOMs frequently and reduce overall fuzzing efficiency. ### Memory Usage -Avoid allocation of dynamic memory wherever possible. Instrumentation works -faster for stack-based and static objects than for heap allocated ones. +Avoid allocation of dynamic memory wherever possible. Memory instrumentation +works faster for stack-based and static objects, than for heap allocated ones. -It is always a good idea to play with different versions of a fuzzer to find the -fastest implementation. +It is always a good idea to try different variants for your fuzzer locally, and then +submit the fastest implementation. ### Maximum Testcase Length -Experiment with different values of `-max_len` parameter. This parameter often -significantly affects execution speed, but not always. +You can control the maximum length of a test input using `-max_len` parameter +(see [custom options](#Custom-Options)). This parameter can often significantly +improve execution speed. Beware that you might miss coverage and unexpected +scenarios happening from longer size inputs. 1) Define which `-max_len` value is reasonable for your target. For example, it may be useless to fuzz an image decoder with too small value of testcase length. 2) Increase the value defined on previous step. Check its influence on execution speed of fuzzer. If speed doesn't drop significantly for long inputs, it is fine -to have some bigger value for `-max_len`. +to have some bigger value for `-max_len` or even skip it completely. -In general, bigger `-max_len` value gives better coverage. Coverage is main +In general, bigger `-max_len` value gives better coverage which is the main priority for fuzzing. However, low execution speed may result in waste of -resources used for fuzzing. If large inputs make fuzzer too slow you have to -adjust value of `-max_len` and find a trade-off between coverage and execution -speed. +fuzzing resources and being unable to find interesting inputs in reasonable time. +If large inputs make the fuzzer too slow, you should adjust the value of `-max_len` +and find a trade-off between coverage and execution speed. *Note:* ClusterFuzz runs two different fuzzing engines (**LibFuzzer** and **AFL**) using the same target functions. AFL doesn't support `-max_len` @@ -216,44 +247,44 @@ ## Code Coverage -[ClusterFuzz status] page provides fuzzer source-level coverage report from the -recent run. Looking at the report might provide an insight to improve fuzzer +[ClusterFuzz status] page provides fuzzer source-level coverage report from +recent runs. Looking at the report might provide an insight to improve fuzzer coverage. -You can also generate source-level coverage report locally via running +You can also generate source-level coverage report locally by running the [coverage script] stored in Chromium repository. The script provides detailed -instructions as well as usage example. +instructions as well as an usage example. We encourage you to try out the script, as it usually generates a better code coverage visualization compared to the coverage report hosted on ClusterFuzz. - *NOTE: This is an experimental feature and an active area of work. We are working on improving this process.* ## Corpus Size -After running for a while the fuzzer would reach a plateau and won't discover -new interesting input. Corpus for a reasonably complex functionality -should contain hundreds (if not thousands) of items. +After running for a while, the fuzzer would reach a plateau and won't discover +new interesting inputs. Corpus for a reasonably complex functionality should +contain hundreds (if not thousands) of items. -Too small corpus size indicates some code barrier that -libFuzzer is having problems penetrating. Common cases include: checksums, -magic numbers etc. The easiest way to diagnose this problem is to generate a -[coverage report](#Coverage). To fix the issue you can: +Too small of a corpus size indicates fuzzer is hitting a code barrier and is unable +to get past it. Common cases of such issues include: checksums, magic numbers, +etc. The easiest way to diagnose this problem is to generate and analyze a +[coverage report](#Coverage). To fix the issue, you can: -* change the code (e.g. disable crc checks while fuzzing) -* prepare [corpus seed](#Corpus-Seed) -* prepare [fuzzer dictionary](#Fuzzer-Dictionary) -* specify [custom options](#Custom-Options) +* Change the code (e.g. disable crc checks while fuzzing). +* Prepare or improve [seed corpus](#Seed-Corpus). +* Prepare or improve [fuzzer dictionary](#Fuzzer-Dictionary). +* Add [custom options](#Custom-Options). ### Custom Options -It is possible to specify [libFuzzer parameters](http://llvm.org/docs/LibFuzzer.html#usage) -for any fuzzer being run at ClusterFuzz. Custom options will overwrite default -values provided by ClusterFuzz. +Custom options help to fine tune libFuzzer execution parameters and will also +override the default values used by ClusterFuzz. Please read [libFuzzer options] +page for detailed documentation on how these work. -Just list all parameters in `libfuzzer_options` variable of build target: +Add the options needed in `libfuzzer_options` attribute to your fuzzer definition in +BUILD.gn file: ``` fuzzer_test("my_protocol_fuzzer") { @@ -266,11 +297,13 @@ ``` Please note that `dict` parameter should be provided [separately](#Fuzzer-Dictionary). -Other options may be passed through `libfuzzer_options` property. - +All other options can be passed using `libfuzzer_options` property. [AFL]: http://lcamtuf.coredump.cx/afl/ [ClusterFuzz status]: clusterfuzz.md#Status-Links [Corpus GCS Bucket]: https://goto.google.com/libfuzzer-clusterfuzz-corpus [issue 638836]: https://bugs.chromium.org/p/chromium/issues/detail?id=638836 [coverage script]: https://cs.chromium.org/chromium/src/testing/libfuzzer/coverage.py +[gsutil]: https://cloud.google.com/storage/docs/gsutil +[libFuzzer options]: https://llvm.org/docs/LibFuzzer.html#options +[startup initialization]: https://llvm.org/docs/LibFuzzer.html#startup-initialization
diff --git a/testing/libfuzzer/getting_started.md b/testing/libfuzzer/getting_started.md index d9f16dc8..b22ae98 100644 --- a/testing/libfuzzer/getting_started.md +++ b/testing/libfuzzer/getting_started.md
@@ -1,7 +1,7 @@ # Getting Started with libFuzzer in Chrome -*** note -**Prerequisites:** libFuzzer in Chrome is supported with GN on Linux only. +*** +**Prerequisites:** libFuzzer in Chrome is supported with GN on Linux and Mac only. *** This document will walk you through: @@ -15,9 +15,9 @@ Use `use_libfuzzer` GN argument together with sanitizer to generate build files: *Notice*: current implementation also supports `use_afl` argument, but it is -recommended to use libFuzzer for development. Running libFuzzer locally doesn't -require any special configuration and quickly gives meaningful output for speed, -coverage and other parameters. +recommended to use libFuzzer for local development. Running libFuzzer locally +doesn't require any special configuration and gives meaningful output quickly for +speed, coverage and other parameters. ```bash # With address sanitizer @@ -42,7 +42,7 @@ ## Write Fuzzer Function -Create a new .cc file and define a `LLVMFuzzerTestOneInput` function: +Create a new `<my_fuzzer>.cc` file and define a `LLVMFuzzerTestOneInput` function: ```cpp #include <stddef.h> @@ -54,11 +54,16 @@ } ``` -[url_parse_fuzzer.cc] is a simple example of real-world fuzzer. +*Note*: You should create the fuzzer file `<my_fuzzer>.cc next to the code that is being +tested and in the same directory as your other unit tests. Please do not use +`testing/libfuzzer/fuzzers` directory, this was a directory used for initial sample fuzzers and +is no longer recommended for any new fuzzers. + +[quic_stream_factory_fuzzer.cc] is a good example of real-world fuzz target. ## Define GN Target -Define `fuzzer_test` GN target: +Define `fuzzer_test` GN target in BUILD.gn: ```python import("//testing/libfuzzer/fuzzer_test.gni") @@ -88,7 +93,7 @@ #2 NEW cov: 2710 bits: 359 indir: 36 units: 2 exec/s: 0 L: 64 MS: 0 ``` -The `... NEW ...` line appears when libFuzzer finds new and interesting input. +The `... NEW ...` line appears when libFuzzer finds new and interesting inputs. The efficient fuzzer should be able to finds lots of them rather quickly. The `... pulse ...` line will appear periodically to show the current status. @@ -99,15 +104,15 @@ binary added in `$PATH`. The symbolizer binary is included in Chromium's Clang package located at `third_party/llvm-build/Release+Asserts/bin/` directory. -Alternatively, you can set `external_symbolizer_path` option via `ASAN_OPTIONS` -env variable: +Alternatively, you can set `external_symbolizer_path` option via +`ASAN_OPTIONS` env variable: ```bash $ ASAN_OPTIONS=external_symbolizer_path=/my/local/llvm/build/llvm-symbolizer \ ./fuzzer ./crash-input ``` -The same approach works with other sanitizers (e.g. `MSAN_OPTIONS` and others). +The same approach works with other sanitizers (e.g. `MSAN_OPTIONS`, `UBSAN_OPTIONS`, etc). ## Improving Your Fuzzer @@ -120,18 +125,19 @@ *Make sure corpus files are appropriately licensed.* * Create mutation dictionary. With a `dict = "protocol.dict"` attribute and `key=value` dicitionary file format, mutations can be more effective. -See [Fuzzer Dictionary]. +See [Fuzzer Dictionary] section of efficient fuzzer guide. * Specify maximum testcase length. By default libFuzzer uses `-max_len=64` (or takes the longest testcase in a corpus). ClusterFuzz takes random value in range from `1` to `10000` for each fuzzing session and passes that value to libFuzzers. If corpus contains testcases of size greater than -`max_len`, libFuzzer will use only first `max_len` bytes of such testcases. -See [Maximum Testcase Length]. +`max_len`, libFuzzer will use only first `max_len` bytes of such testcases. +See [Maximum Testcase Length] section of the efficient fuzzer guide. ## Disable noisy error message logging -If the code that you are a fuzzing generates error messages when encountering -incorrect or invalid data then you need to silence those errors in the fuzzer. +If the code that you are a fuzzing generates lot of error messages when +encountering incorrect or invalid data, then you need to silence those errors +in the fuzzer. Otherwise, fuzzer will be slow and inefficient. If the target uses the Chromium logging APIs, the best way to do that is to override the environment used for logging in your fuzzer: @@ -148,12 +154,16 @@ ## Submitting Fuzzer to ClusterFuzz -ClusterFuzz builds and executes all `fuzzer_test` targets in the source tree. -The only thing you should do is to submit a fuzzer into Chrome. +ClusterFuzz builds and executes all `fuzzer_test` targets in the Chromium +repository. It is extremely important to submit a fuzzer into Chromium +repository so that ClusterFuzz can run it at scale. Do not rely on just +running fuzzing locally in your own environment, as it will catch far less +issues. It's crucial to run fuzzers continuously forever for catching +regressions and improving code coverage over time. ## Next Steps -* After your fuzzer is submitted, you should check its [ClusterFuzz status] in +* After your fuzzer is submitted, you should check [ClusterFuzz status] page in a day or two. * Check the [Efficient Fuzzer Guide] to better understand your fuzzer performance and for optimization hints. @@ -168,5 +178,5 @@ [Seed Corpus]: efficient_fuzzer.md#Seed-Corpus [Undefined Behavior Sanitizer]: http://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html [crbug/598448]: https://bugs.chromium.org/p/chromium/issues/detail?id=598448 -[url_parse_fuzzer.cc]: https://code.google.com/p/chromium/codesearch#chromium/src/testing/libfuzzer/fuzzers/url_parse_fuzzer.cc +[quic_stream_factory_fuzzer.cc]: https://cs.chromium.org/chromium/src/net/quic/chromium/quic_stream_factory_fuzzer.cc [Build Config]: reference.md#Builder-configurations
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index 66114f4..c16e3da 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -399,10 +399,15 @@ ] } ], - "AutofillCreditCardDropdownVariations": [ + "AutofillCreditCardBankNameDisplay": [ { "platforms": [ - "android" + "android", + "chromeos", + "ios", + "linux", + "mac", + "win" ], "experiments": [ { @@ -779,6 +784,24 @@ ] } ], + "ChromeHomeBottomNavLabels": [ + { + "platforms": [ + "android" + ], + "experiments": [ + { + "name": "Enabled", + "enable_features": [ + "ChromeHomeBottomNavLabels" + ] + }, + { + "name": "Default" + } + ] + } + ], "ChromeHomeInactivitySheetExpansion": [ { "platforms": [ @@ -904,8 +927,7 @@ { "name": "Expected", "params": { - "contextual-search-ranker-model-url": "https://www.gstatic.com/chrome/intelligence/assist/ranker/models/contextual_search/test_ranker_model_20171109_short_words.pb.bin", - "enable_ranker_integration": "true" + "contextual-search-ranker-model-url": "https://www.gstatic.com/chrome/intelligence/assist/ranker/models/contextual_search/test_ranker_model_20171109_short_words.pb.bin" }, "enable_features": [ "ContextualSearchMlTapSuppression", @@ -2050,22 +2072,6 @@ ] } ], - "NTPMostLikelyFaviconsFromServer": [ - { - "platforms": [ - "android", - "ios" - ], - "experiments": [ - { - "name": "Enabled", - "enable_features": [ - "NTPMostLikelyFaviconsFromServer" - ] - } - ] - } - ], "NTPPopularSites": [ { "platforms": [ @@ -3229,21 +3235,6 @@ ] } ], - "SafeBrowsingUseLocalBlacklist": [ - { - "platforms": [ - "android" - ], - "experiments": [ - { - "name": "Use3PAPI", - "params": { - "check_local_blacklist": "false" - } - } - ] - } - ], "SearchEnginePromo": [ { "platforms": [
diff --git a/third_party/WebKit/LayoutTests/FlagExpectations/enable-blink-features=LayoutNG b/third_party/WebKit/LayoutTests/FlagExpectations/enable-blink-features=LayoutNG index 40b3859..ff996a3a 100644 --- a/third_party/WebKit/LayoutTests/FlagExpectations/enable-blink-features=LayoutNG +++ b/third_party/WebKit/LayoutTests/FlagExpectations/enable-blink-features=LayoutNG
@@ -121,6 +121,7 @@ crbug.com/591099 accessibility/textarea-caret-position.html [ Failure Timeout ] crbug.com/591099 accessibility/textarea-selection.html [ Failure ] crbug.com/591099 accessibility/whitespace-in-name-calc.html [ Failure ] +crbug.com/591099 animations/animation-ready-reject-script-forbidden.html [ Pass ] crbug.com/591099 animations/cross-fade-list-style-image.html [ Failure ] crbug.com/591099 animations/interpolation/backdrop-filter-interpolation.html [ Timeout ] crbug.com/591099 animations/interpolation/line-height-interpolation.html [ Pass Timeout ] @@ -1248,7 +1249,7 @@ crbug.com/591099 css3/selectors3/html/css3-modsel-17.html [ Failure ] crbug.com/591099 css3/selectors3/html/css3-modsel-170.html [ Failure ] crbug.com/591099 css3/selectors3/html/css3-modsel-170a.html [ Failure ] -crbug.com/591099 css3/selectors3/html/css3-modsel-170b.html [ Failure ] +crbug.com/591099 css3/selectors3/html/css3-modsel-170b.html [ Crash Failure ] crbug.com/591099 css3/selectors3/html/css3-modsel-170c.html [ Failure ] crbug.com/591099 css3/selectors3/html/css3-modsel-170d.html [ Failure ] crbug.com/591099 css3/selectors3/html/css3-modsel-175a.html [ Failure ] @@ -1972,7 +1973,7 @@ crbug.com/591099 editing/caret/caret-color-004.html [ Crash Failure ] crbug.com/591099 editing/caret/caret-color-005.html [ Failure ] crbug.com/591099 editing/caret/caret-color-007.html [ Crash Failure ] -crbug.com/591099 editing/caret/caret-color-010.html [ Failure ] +crbug.com/591099 editing/caret/caret-color-010.html [ Crash Failure Timeout ] crbug.com/591099 editing/caret/caret-color-011.html [ Failure ] crbug.com/591099 editing/caret/caret-color-012.html [ Crash Failure ] crbug.com/591099 editing/caret/caret-color-014.html [ Crash Failure ] @@ -2231,7 +2232,6 @@ crbug.com/591099 editing/selection/move-backwords-by-word-001.html [ Failure ] crbug.com/591099 editing/selection/move-between-lines-of-different-editabilities.html [ Failure ] crbug.com/591099 editing/selection/move-by-line-002.html [ Failure ] -crbug.com/591099 editing/selection/move-by-line-006.html [ Failure Pass ] crbug.com/591099 editing/selection/move-by-sentence-001.html [ Failure ] crbug.com/591099 editing/selection/move-by-word-001.html [ Failure ] crbug.com/591099 editing/selection/move-left-right.html [ Failure Timeout ] @@ -2478,7 +2478,7 @@ crbug.com/591099 external/wpt/css/css-shapes/spec-examples/shape-outside-004.html [ Crash Failure ] crbug.com/591099 external/wpt/css/css-shapes/spec-examples/shape-outside-005.html [ Failure ] crbug.com/591099 external/wpt/css/css-shapes/spec-examples/shape-outside-006.html [ Failure ] -crbug.com/591099 external/wpt/css/css-shapes/spec-examples/shape-outside-007.html [ Failure ] +crbug.com/591099 external/wpt/css/css-shapes/spec-examples/shape-outside-007.html [ Crash Failure ] crbug.com/591099 external/wpt/css/css-shapes/spec-examples/shape-outside-008.html [ Failure ] crbug.com/591099 external/wpt/css/css-shapes/spec-examples/shape-outside-010.html [ Failure ] crbug.com/591099 external/wpt/css/css-shapes/spec-examples/shape-outside-011.html [ Failure ] @@ -3427,7 +3427,7 @@ crbug.com/591099 fast/css/focus-ring-outline-color.html [ Failure ] crbug.com/591099 fast/css/focus-ring-outline-offset.html [ Failure ] crbug.com/591099 fast/css/focus-ring-outline-width.html [ Failure ] -crbug.com/591099 fast/css/font-face-opentype.html [ Failure ] +crbug.com/591099 fast/css/font-face-opentype.html [ Crash Failure ] crbug.com/591099 fast/css/font-face-synthetic-bold-italic-for-locally-installed.html [ Failure ] crbug.com/591099 fast/css/font-face-synthetic-bold-italic.html [ Failure ] crbug.com/591099 fast/css/font-face-weight-matching.html [ Failure ] @@ -5257,7 +5257,7 @@ crbug.com/591099 fast/multicol/flowthread-with-floats-destroyed-crash.html [ Crash ] crbug.com/591099 fast/multicol/infinite-height-causing-fractional-row-height-crash.html [ Crash ] # This one is really just very slow: -crbug.com/591099 animations/animation-ready-reject-script-forbidden.html [ Pass ] +crbug.com/591099 fast/multicol/infinitely-tall-content-in-outer-crash.html [ Pass Timeout ] crbug.com/591099 external/wpt/css/css-fonts/matching/fixed-stretch-style-over-weight.html [ Pass ] crbug.com/591099 external/wpt/css/css-multicol/multicol-basic-001.html [ Failure ] crbug.com/591099 external/wpt/css/css-multicol/multicol-basic-002.html [ Failure ] @@ -5407,7 +5407,6 @@ crbug.com/591099 fast/multicol/span/spanner-after-negative-margin-bottom-crash-2.html [ Crash ] crbug.com/591099 fast/multicol/span/spanner-after-negative-margin-bottom-crash.html [ Crash ] crbug.com/591099 fast/multicol/triply-nested-with-padding-crash.html [ Crash ] -crbug.com/591099 fast/overflow/line-clamp-hides-trailing-anchor.html [ Failure Pass ] crbug.com/591099 fast/overflow/overflow-visible-should-ignore-scroll.html [ Failure ] crbug.com/591099 fast/pagination/div-x-vertical-lr-ltr.html [ Failure ] crbug.com/591099 fast/pagination/div-x-vertical-lr-rtl.html [ Failure ] @@ -5531,7 +5530,7 @@ crbug.com/591099 fast/ruby/rubyDOM-remove-text1.html [ Failure ] crbug.com/591099 fast/ruby/rubyDOM-remove-text2.html [ Failure ] crbug.com/591099 fast/ruby/select-ruby.html [ Failure ] -crbug.com/591099 fast/scroll-behavior/subframe-interrupted-scroll.html [ Failure ] +crbug.com/591099 fast/scroll-behavior/subframe-interrupted-scroll.html [ Failure Pass ] crbug.com/591099 fast/scrolling/content-box-smaller-than-scrollbar.html [ Failure ] crbug.com/591099 fast/scrolling/fractional-scroll-offset-fixed-position-non-composited.html [ Crash ] crbug.com/591099 fast/scrolling/horizontal-overflow-quirks.html [ Failure ] @@ -5951,7 +5950,7 @@ crbug.com/591099 fast/tokenizer/script-after-frameset.html [ Failure ] crbug.com/591099 fast/tokenizer/script_extra_close.html [ Failure ] crbug.com/591099 fast/tokenizer/write-partial-entity.html [ Crash ] -crbug.com/591099 fast/url/degenerate-file-base.html [ Crash ] +crbug.com/591099 fast/url/degenerate-file-base.html [ Crash Pass ] crbug.com/591099 fast/workers/shared-worker-location.html [ Failure ] crbug.com/591099 fast/workers/worker-location.html [ Failure ] crbug.com/591099 fast/writing-mode/Kusa-Makura-background-canvas.html [ Failure ] @@ -6256,7 +6255,6 @@ crbug.com/591099 http/tests/csspaint/invalidation-content-image.html [ Timeout ] crbug.com/591099 http/tests/devtools/audits2/audits2-limited-run.js [ Crash ] crbug.com/591099 http/tests/devtools/audits2/audits2-successful-run.js [ Crash ] -crbug.com/591099 http/tests/devtools/console/command-line-api.js [ Pass Timeout ] crbug.com/591099 http/tests/devtools/console/console-format.js [ Failure ] crbug.com/591099 http/tests/devtools/console/console-functions.js [ Failure ] crbug.com/591099 http/tests/devtools/console/console-uncaught-promise.js [ Failure Pass ] @@ -6535,7 +6533,6 @@ crbug.com/591099 ietestcenter/css3/text/textshadow-002.htm [ Failure ] crbug.com/591099 ietestcenter/css3/text/textshadow-009.htm [ Failure ] crbug.com/591099 ietestcenter/css3/text/textshadow-010.htm [ Failure ] -crbug.com/591099 imagecapture/MediaStreamTrack-applyConstraints.html [ Failure Pass ] crbug.com/591099 imagecapture/MediaStreamTrack-getCapabilities.html [ Failure Pass ] crbug.com/591099 images/12-55.html [ Failure ] crbug.com/591099 images/182.html [ Failure ] @@ -7613,7 +7610,7 @@ crbug.com/591099 svg/custom/bug45331.svg [ Failure ] crbug.com/591099 svg/custom/click-overflowing-element.html [ Failure ] crbug.com/591099 svg/custom/clone-element-with-animated-svg-properties.html [ Failure ] -crbug.com/591099 svg/custom/createImageElement2.xhtml [ Failure ] +crbug.com/591099 svg/custom/createImageElement2.xhtml [ Crash Failure ] crbug.com/591099 svg/custom/dominant-baseline-hanging.svg [ Failure ] crbug.com/591099 svg/custom/elementTimeControl-nan-crash.html [ Failure ] crbug.com/591099 svg/custom/embedding-external-svgs.xhtml [ Failure ] @@ -8071,7 +8068,7 @@ crbug.com/591099 virtual/gpu/fast/canvas/canvas-transforms-during-path.html [ Failure ] crbug.com/591099 virtual/gpu/fast/canvas/fill-stroke-clip-reset-path.html [ Failure ] crbug.com/591099 virtual/gpu/fast/canvas/fillrect_gradient.html [ Failure ] -crbug.com/591099 virtual/gpu/fast/canvas/patternfill-repeat.html [ Failure ] +crbug.com/591099 virtual/gpu/fast/canvas/patternfill-repeat.html [ Failure Timeout ] crbug.com/591099 virtual/high-contrast-mode/paint/high-contrast-mode/image-filter-all/text-on-backgrounds.html [ Failure ] crbug.com/591099 virtual/incremental-shadow-dom/fast/dom/shadow/focus-navigation-with-distributed-nodes.html [ Crash ] crbug.com/591099 virtual/incremental-shadow-dom/fast/dom/shadow/form-in-shadow.html [ Crash ] @@ -8420,6 +8417,7 @@ crbug.com/591099 virtual/spv175/compositing/overflow/overflow-compositing-descendant.html [ Failure ] crbug.com/591099 virtual/spv175/compositing/overflow/overflow-positioning.html [ Failure ] crbug.com/591099 virtual/spv175/compositing/overflow/overflow-scroll-with-local-image-background.html [ Failure ] +crbug.com/591099 virtual/spv175/compositing/overflow/overflow-scroll.html [ Failure ] crbug.com/591099 virtual/spv175/compositing/overflow/overflow-scrollbar-layers.html [ Failure ] crbug.com/591099 virtual/spv175/compositing/overflow/overflow-with-negative-z-index-child.html [ Failure ] crbug.com/591099 virtual/spv175/compositing/overflow/parent-overflow.html [ Failure ] @@ -8432,6 +8430,7 @@ crbug.com/591099 virtual/spv175/compositing/overflow/scroll-parent-absolute.html [ Failure ] crbug.com/591099 virtual/spv175/compositing/overflow/scroll-parent-with-non-stacking-context-composited-ancestor.html [ Failure ] crbug.com/591099 virtual/spv175/compositing/overflow/scrollbar-layer-placement.html [ Failure ] +crbug.com/591099 virtual/spv175/compositing/overflow/scrollbar-painting.html [ Failure ] crbug.com/591099 virtual/spv175/compositing/overflow/scrolling-content-clip-to-viewport.html [ Failure ] crbug.com/591099 virtual/spv175/compositing/overflow/textarea-scroll-touch.html [ Failure ] crbug.com/591099 virtual/spv175/compositing/overflow/theme-affects-visual-overflow.html [ Failure ] @@ -8452,6 +8451,7 @@ crbug.com/591099 virtual/spv175/compositing/reflections/load-video-in-reflection.html [ Failure ] crbug.com/591099 virtual/spv175/compositing/reflections/masked-reflection-on-composited.html [ Failure ] crbug.com/591099 virtual/spv175/compositing/reflections/nested-reflection-mask-change.html [ Failure ] +crbug.com/591099 virtual/spv175/compositing/reflections/nested-reflection-on-overflow.html [ Failure ] crbug.com/591099 virtual/spv175/compositing/reflections/nested-reflection-opacity.html [ Failure ] crbug.com/591099 virtual/spv175/compositing/reflections/nested-reflection-size-change.html [ Failure ] crbug.com/591099 virtual/spv175/compositing/reflections/nested-reflection-transformed.html [ Failure ] @@ -8942,6 +8942,7 @@ crbug.com/591099 virtual/spv175/paint/invalidation/resize-iframe-text.html [ Failure ] crbug.com/591099 virtual/spv175/paint/invalidation/ruby-flipped-blocks.html [ Failure ] crbug.com/591099 virtual/spv175/paint/invalidation/scroll/caret-with-composited-scroll.html [ Failure ] +crbug.com/591099 virtual/spv175/paint/invalidation/scroll/composited-add-resizer.html [ Failure ] crbug.com/591099 virtual/spv175/paint/invalidation/scroll/composited-iframe-scroll-repaint.html [ Failure ] crbug.com/591099 virtual/spv175/paint/invalidation/scroll/destroy-composited-scrollbar.html [ Failure ] crbug.com/591099 virtual/spv175/paint/invalidation/scroll/destroy-overlay-scrollbar.html [ Failure ] @@ -9050,6 +9051,7 @@ crbug.com/591099 virtual/spv175/paint/invalidation/svg/svg-image-change-content-size.xhtml [ Failure ] crbug.com/591099 virtual/spv175/paint/invalidation/svg/svg-layout-root-style-attr-update.html [ Failure ] crbug.com/591099 virtual/spv175/paint/invalidation/svg/text-rescale.html [ Failure ] +crbug.com/591099 virtual/spv175/paint/invalidation/svg/transform-focus-ring-repaint.html [ Failure ] crbug.com/591099 virtual/spv175/paint/invalidation/svg/transform-foreign-object.html [ Failure ] crbug.com/591099 virtual/spv175/paint/invalidation/svg/use-instanceRoot-event-bubbling.xhtml [ Timeout ] crbug.com/591099 virtual/spv175/paint/invalidation/svg/use-setAttribute-crash.svg [ Failure ]
diff --git a/third_party/WebKit/LayoutTests/FlagExpectations/enable-features=NetworkService b/third_party/WebKit/LayoutTests/FlagExpectations/enable-features=NetworkService index 5dda84b..0cbbe34 100644 --- a/third_party/WebKit/LayoutTests/FlagExpectations/enable-features=NetworkService +++ b/third_party/WebKit/LayoutTests/FlagExpectations/enable-features=NetworkService
@@ -135,7 +135,6 @@ Bug(none) http/tests/loading/307-after-303-after-post.html [ Failure ] Bug(none) http/tests/doc-write-intervention/doc-write-sync-third-party-script-reload.html [ Crash ] Bug(none) http/tests/loading/bad-scheme-subframe.html [ Failure ] -Bug(none) http/tests/local/fileapi/send-sliced-dragged-file.html [ Failure Timeout ] Bug(none) http/tests/local/serviceworker/fetch-request-body-file.html [ Crash Timeout ] Bug(none) http/tests/media/video-buffered.html [ Timeout ] Bug(none) http/tests/misc/embed-image-load-outlives-gc-without-crashing.html [ Failure Pass ] @@ -233,8 +232,5 @@ crbug.com/721408 http/tests/inspector-protocol/network/navigation-xfer-size.js [ Failure ] -crbug.com/789081 fast/dom/HTMLAnchorElement/anchor-download.html [ Timeout ] -crbug.com/789081 fast/dom/HTMLAnchorElement/anchor-nodownload-set.html [ Timeout ] - # Started flaking after test was rewritten in r517585. Bug(none) http/tests/devtools/service-workers/service-worker-agents.js [ Crash Pass ]
diff --git a/third_party/WebKit/LayoutTests/FlagExpectations/root-layer-scrolls b/third_party/WebKit/LayoutTests/FlagExpectations/root-layer-scrolls index febea15d..137d02f 100644 --- a/third_party/WebKit/LayoutTests/FlagExpectations/root-layer-scrolls +++ b/third_party/WebKit/LayoutTests/FlagExpectations/root-layer-scrolls
@@ -1,21 +1,20 @@ crbug.com/417782 compositing/iframes/become-composited-nested-iframes.html [ Failure ] crbug.com/417782 compositing/layer-creation/iframe-background-attachment-fixed.html [ Failure ] +crbug.com/417782 compositing/squashing/dont-squash-into-videos.html [ Failure ] crbug.com/417782 compositing/squashing/squash-above-fixed-1.html [ Failure ] crbug.com/417782 compositing/squashing/squash-above-fixed-3.html [ Failure ] crbug.com/417782 compositing/visibility/visibility-image-layers-dynamic.html [ Failure ] crbug.com/417782 external/wpt/css/css-position/position-sticky-root-scroller.html [ Failure ] crbug.com/417782 fast/css/sticky/replaced-sticky.html [ Failure ] crbug.com/417782 fast/css/sticky/sticky-style-change.html [ Failure ] -crbug.com/417782 fast/css/zoom-body-scroll.html [ Failure ] crbug.com/417782 fast/dom/Window/window-xy-properties.html [ Failure ] -crbug.com/417782 fast/dom/horizontal-scrollbar-when-dir-change.html [ Failure ] +crbug.com/417782 [ Linux Mac ] fast/dom/horizontal-scrollbar-when-dir-change.html [ Failure ] crbug.com/417782 fast/dom/rtl-scroll-to-leftmost-and-resize.html [ Failure ] crbug.com/417782 fast/dom/scroll-reveal-left-overflow.html [ Failure ] crbug.com/417782 fast/dom/scroll-reveal-top-overflow.html [ Failure ] crbug.com/417782 fast/events/autoscroll.html [ Failure ] crbug.com/417782 fast/events/clientXY-in-zoom-and-scroll.html [ Failure ] crbug.com/417782 fast/events/drag-and-drop-autoscroll-frameset.html [ Timeout ] -crbug.com/417782 fast/events/drag-and-drop-autoscroll-inner-frame.html [ Timeout ] crbug.com/417782 fast/events/drag-and-drop-autoscroll-mainframe.html [ Timeout ] crbug.com/417782 fast/events/pointerevents/pointer-event-mouse-coords-in-zoom-and-scroll.html [ Failure ] crbug.com/417782 fast/events/scale-and-scroll-iframe-window.html [ Failure ] @@ -40,14 +39,10 @@ crbug.com/417782 html/dialog/form-method-dialog.html [ Crash ] crbug.com/417782 http/tests/devtools/device-mode/default-background-color.html [ Failure ] crbug.com/417782 http/tests/devtools/layers/layer-compositing-reasons.js [ Failure ] -crbug.com/417782 http/tests/devtools/layers/layer-scroll-rects-get.js [ Failure ] crbug.com/417782 http/tests/devtools/layers/layer-tree-model.js [ Failure ] -crbug.com/417782 http/tests/devtools/layers/layers-3d-view-hit-testing.js [ Failure ] -crbug.com/417782 [ Linux ] http/tests/devtools/sources/autocomplete-hide-on-smart-brace.js [ Timeout ] +crbug.com/417782 http/tests/devtools/layers/layers-panel-mouse-events.js [ Crash ] crbug.com/417782 http/tests/devtools/tracing/scroll-invalidations.html [ Failure ] crbug.com/417782 http/tests/devtools/tracing/timeline-paint/layer-tree.js [ Failure ] -crbug.com/417782 http/tests/devtools/tracing/timeline-paint/paint-profiler-update.js [ Timeout ] -crbug.com/417782 http/tests/devtools/tracing/timeline-paint/timeline-paint-and-multiple-style-invalidations.js [ Failure ] crbug.com/417782 http/tests/devtools/tracing/timeline-paint/timeline-paint-with-layout-invalidations-on-deleted-node.js [ Failure ] crbug.com/417782 http/tests/devtools/tracing/timeline-paint/timeline-paint-with-layout-invalidations.js [ Failure ] crbug.com/417782 http/tests/devtools/tracing/timeline-paint/timeline-paint-with-style-recalc-invalidations.js [ Failure ] @@ -56,13 +51,15 @@ crbug.com/417782 inspector-protocol/dom-snapshot/dom-snapshot-getSnapshot.js [ Failure ] crbug.com/417782 inspector-protocol/layers/paint-profiler.js [ Crash ] crbug.com/417782 inspector-protocol/page/get-layout-metrics.js [ Failure ] +crbug.com/417782 paint/invalidation/resize-iframe-text.html [ Failure ] crbug.com/417782 paint/invalidation/scroll/iframe-scroll-repaint.html [ Failure ] crbug.com/417782 paint/invalidation/scroll/overflow-scroll-body-appear.html [ Failure ] -crbug.com/417782 paint/invalidation/resize-iframe-text.html [ Failure ] crbug.com/417782 paint/invalidation/svg/absolute-sized-document-no-scrollbars.svg [ Failure ] crbug.com/417782 paint/invalidation/svg/deep-nested-embedded-svg-size-changes-no-layout-triggers-1.html [ Failure ] crbug.com/417782 paint/invalidation/svg/deep-nested-embedded-svg-size-changes-no-layout-triggers-2.html [ Failure ] +crbug.com/417782 paint/invalidation/svg/window.svg [ Failure ] crbug.com/417782 paint/invalidation/window-resize/window-resize-vertical-writing-mode.html [ Crash ] +crbug.com/417782 [ Mac Win ] paint/overflow/fixed-background-scroll-window.html [ Failure ] crbug.com/417782 plugins/webview-plugin-nested-iframe-scroll.html [ Failure ] crbug.com/417782 plugins/webview-plugin-scroll.html [ Failure ] crbug.com/417782 transforms/selection-bounds-in-transformed-view.html [ Failure ] @@ -72,19 +69,26 @@ crbug.com/417782 [ Linux ] virtual/android/fullscreen/full-screen-iframe-allowed-video.html [ Failure ] crbug.com/417782 [ Linux ] virtual/android/fullscreen/video-controls-timeline.html [ Failure ] crbug.com/417782 [ Linux ] virtual/android/fullscreen/video-scrolled-iframe.html [ Failure ] +crbug.com/417782 [ Linux ] virtual/gpu/fast/canvas/OffscreenCanvas-2d-imageSmoothing.html [ Timeout ] crbug.com/417782 virtual/mojo-loading/http/tests/devtools/device-mode/default-background-color.html [ Failure ] crbug.com/417782 virtual/mojo-loading/http/tests/devtools/layers/layer-compositing-reasons.js [ Failure ] -crbug.com/417782 virtual/mojo-loading/http/tests/devtools/layers/layer-scroll-rects-get.js [ Failure ] crbug.com/417782 virtual/mojo-loading/http/tests/devtools/layers/layer-tree-model.js [ Failure ] -crbug.com/417782 virtual/mojo-loading/http/tests/devtools/layers/layers-3d-view-hit-testing.js [ Failure ] +crbug.com/417782 virtual/mojo-loading/http/tests/devtools/layers/layers-3d-view-hit-testing.js [ Crash ] crbug.com/417782 virtual/mojo-loading/http/tests/devtools/tracing/timeline-paint/layer-tree.js [ Failure ] -crbug.com/417782 virtual/mojo-loading/http/tests/devtools/tracing/timeline-paint/paint-profiler-update.js [ Timeout ] -crbug.com/417782 virtual/mojo-loading/http/tests/devtools/tracing/timeline-paint/timeline-paint-and-multiple-style-invalidations.js [ Failure ] crbug.com/417782 virtual/mojo-loading/http/tests/devtools/tracing/timeline-paint/timeline-paint-with-layout-invalidations-on-deleted-node.js [ Failure ] crbug.com/417782 virtual/mojo-loading/http/tests/devtools/tracing/timeline-paint/timeline-paint-with-layout-invalidations.js [ Failure ] crbug.com/417782 virtual/mojo-loading/http/tests/devtools/tracing/timeline-paint/timeline-paint-with-style-recalc-invalidations.js [ Failure ] crbug.com/417782 virtual/mojo-loading/http/tests/devtools/tracing/timeline-paint/timeline-paint.js [ Failure ] crbug.com/417782 virtual/mojo-loading/http/tests/misc/acid3.html [ Failure ] +crbug.com/417782 virtual/mouseevent_fractional/fast/events/autoscroll.html [ Failure ] +crbug.com/417782 virtual/mouseevent_fractional/fast/events/pointerevents/pointer-event-mouse-coords-in-zoom-and-scroll.html [ Failure ] +crbug.com/417782 virtual/mouseevent_fractional/fast/events/pointerevents/pointer-event-pen-coords-in-zoom-and-scroll.html [ Failure ] +crbug.com/417782 virtual/mouseevent_fractional/fast/events/scale-and-scroll-iframe-window.html [ Failure ] +crbug.com/417782 virtual/mouseevent_fractional/fast/events/touch/gesture/gesture-tap-frame-scrolled.html [ Failure ] +crbug.com/417782 virtual/mouseevent_fractional/fast/events/touch/gesture/gesture-tap-scrolled.html [ Failure ] +crbug.com/417782 virtual/mouseevent_fractional/fast/events/touch/touch-coords-in-zoom-and-scroll.html [ Failure ] +crbug.com/417782 virtual/mouseevent_fractional/fast/events/touch/touch-fractional-coordinates.html [ Failure ] +crbug.com/417782 virtual/mouseevent_fractional/fast/events/touch/touch-inside-iframe-scrolled.html [ Failure ] crbug.com/417782 virtual/scroll_customization/fast/events/touch/compositor-touch-hit-rects-iframes.html [ Failure ] crbug.com/417782 virtual/scroll_customization/fast/events/touch/gesture/gesture-tap-frame-scrolled.html [ Failure ] crbug.com/417782 virtual/scroll_customization/fast/events/touch/gesture/gesture-tap-scrolled.html [ Failure ] @@ -94,41 +98,33 @@ crbug.com/417782 virtual/threaded/compositing/visibility/visibility-image-layers-dynamic.html [ Failure ] crbug.com/417782 [ Linux Win ] virtual/threaded/fast/scroll-behavior/smooth-scroll/main-thread-scrolling-reason-correctness.html [ Failure ] crbug.com/417782 virtual/threaded/http/tests/devtools/tracing/scroll-invalidations.html [ Failure ] -crbug.com/417782 virtual/threaded/http/tests/devtools/tracing/timeline-paint/paint-profiler-update.js [ Timeout ] -crbug.com/417782 virtual/threaded/http/tests/devtools/tracing/timeline-paint/timeline-paint-and-multiple-style-invalidations.js [ Failure ] crbug.com/417782 virtual/threaded/http/tests/devtools/tracing/timeline-paint/timeline-paint-with-layout-invalidations-on-deleted-node.js [ Failure ] crbug.com/417782 virtual/threaded/http/tests/devtools/tracing/timeline-paint/timeline-paint-with-layout-invalidations.js [ Failure ] crbug.com/417782 virtual/threaded/http/tests/devtools/tracing/timeline-paint/timeline-paint-with-style-recalc-invalidations.js [ Failure ] crbug.com/417782 virtual/threaded/http/tests/devtools/tracing/timeline-paint/timeline-paint.js [ Failure ] -crbug.com/417782 [ Win ] virtual/threaded/http/tests/devtools/tracing/timeline-paint/update-layer-tree.js [ Crash ] -crbug.com/417782 virtual/threaded/printing/fixed-positioned-scrolled.html [ Failure ] -crbug.com/417782 virtual/threaded/printing/quirks-percentage-height-body.html [ Failure ] -crbug.com/417782 virtual/threaded/printing/quirks-percentage-height.html [ Failure ] -crbug.com/417782 virtual/threaded/printing/standards-percentage-heights.html [ Failure ] -crbug.com/417782 virtual/threaded/printing/subframes-percentage-height.html [ Failure ] -crbug.com/417782 virtual/threaded/printing/thead-repeats-at-top-of-each-page.html [ Failure ] -crbug.com/417782 compositing/iframes/iframe-composited-scrolling.html [ Failure ] -crbug.com/417782 compositing/squashing/dont-squash-into-videos.html [ Failure ] -crbug.com/417782 virtual/mouseevent_fractional/fast/events/autoscroll.html [ Failure ] -crbug.com/417782 virtual/mouseevent_fractional/fast/events/mouse-coords-in-zoom-and-scroll.html [ Failure ] -crbug.com/417782 virtual/mouseevent_fractional/fast/events/mouse-right-coords-in-zoom-and-scroll-right.html [ Failure ] -crbug.com/417782 virtual/mouseevent_fractional/fast/events/scale-and-scroll-iframe-window.html [ Failure ] -crbug.com/417782 virtual/mouseevent_fractional/fast/events/pointerevents/pointer-event-mouse-coords-in-zoom-and-scroll.html [ Failure ] -crbug.com/417782 virtual/mouseevent_fractional/fast/events/pointerevents/pointer-event-pen-coords-in-zoom-and-scroll.html [ Failure ] -crbug.com/417782 virtual/mouseevent_fractional/fast/events/touch/touch-coords-in-zoom-and-scroll.html [ Failure ] -crbug.com/417782 virtual/mouseevent_fractional/fast/events/touch/touch-fractional-coordinates.html [ Failure ] -crbug.com/417782 virtual/mouseevent_fractional/fast/events/touch/touch-inside-iframe-scrolled.html [ Failure ] -crbug.com/417782 virtual/mouseevent_fractional/fast/events/touch/gesture/gesture-tap-frame-scrolled.html [ Failure ] -crbug.com/417782 virtual/mouseevent_fractional/fast/events/touch/gesture/gesture-tap-scrolled.html [ Failure ] # Tests known to be flaky crbug.com/417782 virtual/mouseevent_fractional/fast/events/drag-and-drop-autoscroll-frameset.html [ Timeout Failure ] crbug.com/417782 virtual/mouseevent_fractional/fast/events/drag-and-drop-autoscroll-inner-frame.html [ Timeout Failure ] crbug.com/417782 virtual/mouseevent_fractional/fast/events/drag-and-drop-autoscroll-mainframe.html [ Timeout Failure ] +crbug.com/417782 virtual/mouseevent_fractional/fast/events/mouse-coords-in-zoom-and-scroll.html [ Failure Timeout ] +crbug.com/417782 virtual/mouseevent_fractional/fast/events/mouse-right-coords-in-zoom-and-scroll-right.html [ Failure Timeout ] crbug.com/417782 fast/events/pointerevents/pointer-event-pen-coords-in-zoom-and-scroll.html [ Failure Timeout ] crbug.com/417782 http/tests/devtools/agents-enable-disable.js [ Timeout Crash ] +crbug.com/417782 http/tests/devtools/layers/layer-canvas-log.js [ Crash Timeout ] +crbug.com/417782 http/tests/devtools/layers/layer-replay-scale.js [ Crash Timeout ] +crbug.com/417782 http/tests/devtools/layers/layer-scroll-rects-get.js [ Crash Timeout ] +crbug.com/417782 http/tests/devtools/layers/layer-sticky-position-constraint-get.js [ Crash Timeout ] +crbug.com/417782 http/tests/devtools/layers/layers-3d-view-hit-testing.js [ Crash Timeout ] +crbug.com/417782 http/tests/devtools/layers/no-overlay-layers.js [ Crash Timeout ] crbug.com/417782 virtual/mojo-loading/http/tests/devtools/agents-enable-disable.js [ Timeout Crash ] crbug.com/786117 [ Linux ] plugins/mouse-events-fixedpos.html [ Pass Crash ] +crbug.com/417782 virtual/mojo-loading/http/tests/devtools/layers/layer-canvas-log.js [ Crash Timeout ] +crbug.com/417782 virtual/mojo-loading/http/tests/devtools/layers/layer-replay-scale.js [ Crash Timeout ] +crbug.com/417782 virtual/mojo-loading/http/tests/devtools/layers/layer-scroll-rects-get.js [ Crash Timeout ] +crbug.com/417782 virtual/mojo-loading/http/tests/devtools/layers/layer-sticky-position-constraint-get.js [ Crash Timeout ] +crbug.com/417782 virtual/mojo-loading/http/tests/devtools/layers/layers-panel-mouse-events.js [ Crash Timeout ] +crbug.com/417782 virtual/mojo-loading/http/tests/devtools/layers/no-overlay-layers.js [ Crash Timeout ] crbug.com/417782 virtual/mojo-loading/http/tests/devtools/tracing/scroll-invalidations.html [ Crash Failure ] # Virtual test suites to skip.
diff --git a/third_party/WebKit/LayoutTests/SlowTests b/third_party/WebKit/LayoutTests/SlowTests index 4ed5cee..7f07460 100644 --- a/third_party/WebKit/LayoutTests/SlowTests +++ b/third_party/WebKit/LayoutTests/SlowTests
@@ -155,8 +155,8 @@ crbug.com/451577 [ Win10 ] http/tests/devtools/extensions/extensions-sidebar.html [ Slow ] crbug.com/451577 [ Mac ] http/tests/devtools/layers/layer-canvas-log.js [ Slow ] crbug.com/667560 [ Mac ] virtual/mojo-loading/http/tests/devtools/layers/layer-canvas-log.js [ Slow ] -crbug.com/451577 [ Mac ] http/tests/devtools/network/network-domain-filter.html [ Slow ] -crbug.com/667560 [ Mac ] virtual/mojo-loading/http/tests/devtools/network/network-domain-filter.html [ Slow ] +crbug.com/451577 [ Mac ] http/tests/devtools/network/network-domain-filter.js [ Slow ] +crbug.com/667560 [ Mac ] virtual/mojo-loading/http/tests/devtools/network/network-domain-filter.js [ Slow ] # Random slow tests crbug.com/763197 [ Linux Mac ] virtual/gpu-rasterization/images/color-profile-border-radius.html [ Slow ]
diff --git a/third_party/WebKit/LayoutTests/TestExpectations b/third_party/WebKit/LayoutTests/TestExpectations index e70a6d5..03a021f6 100644 --- a/third_party/WebKit/LayoutTests/TestExpectations +++ b/third_party/WebKit/LayoutTests/TestExpectations
@@ -84,7 +84,6 @@ crbug.com/771643 virtual/spv175/compositing/composited-translated-child-with-border-radius-parent-clip.html [ Failure ] crbug.com/771643 virtual/spv175/compositing/opacity-with-mask.html [ Failure ] crbug.com/771643 virtual/spv175/compositing/fixed-body-background-positioned.html [ Failure Pass ] -crbug.com/771643 virtual/spv175/compositing/geometry/composited-in-columns.html [ Failure ] crbug.com/771643 virtual/spv175/compositing/geometry/repaint-foreground-layer.html [ Crash ] crbug.com/771643 virtual/spv175/compositing/images/direct-image-dynamic-border-radius.html [ Failure ] crbug.com/771643 virtual/spv175/compositing/masks/direct-image-mask.html [ Failure ] @@ -127,16 +126,7 @@ # Seems to pass with DCHECK. crbug.com/771643 virtual/spv175/paint/invalidation/filters/filter-on-html-element-with-fixed-position-child.html [ Failure Pass ] crbug.com/771643 virtual/spv175/paint/invalidation/forms/select-option-background-color.html [ Failure ] -crbug.com/771643 virtual/spv175/paint/invalidation/multicol/column-rule-change.html [ Failure ] -crbug.com/771643 virtual/spv175/paint/invalidation/multicol/column-rules-fixed-height.html [ Failure ] -crbug.com/771643 virtual/spv175/paint/invalidation/multicol/multicol-as-paint-container.html [ Failure ] -crbug.com/771643 virtual/spv175/paint/invalidation/multicol/multicol-nested.html [ Failure ] -crbug.com/771643 virtual/spv175/paint/invalidation/multicol/multicol-repaint.html [ Failure ] -crbug.com/771643 virtual/spv175/paint/invalidation/multicol/multicol-rule-actual-columns-change.html [ Failure ] -crbug.com/771643 virtual/spv175/paint/invalidation/multicol/multicol-with-block.html [ Failure ] -crbug.com/771643 virtual/spv175/paint/invalidation/multicol/multicol-with-inline.html [ Failure ] crbug.com/771643 virtual/spv175/paint/invalidation/multicol/multicol-with-overflowing-block-rl.html [ Failure ] -crbug.com/771643 virtual/spv175/paint/invalidation/multicol/multicol-with-text.html [ Failure ] crbug.com/771643 virtual/spv175/paint/invalidation/overflow/composited-overflow-with-negative-offset-outline.html [ Failure ] crbug.com/771643 virtual/spv175/paint/invalidation/overflow/opacity-change-on-overflow-float.html [ Failure ] crbug.com/771643 virtual/spv175/paint/invalidation/overflow/paged-with-overflowing-block-rl.html [ Failure ] @@ -774,6 +764,9 @@ # ====== DevTools test migration failures until here ====== +crbug.com/789225 http/tests/devtools/console/console-focus.js [ Pass Failure ] +crbug.com/789225 virtual/mojo-loading/http/tests/devtools/console/console-focus.js [ Pass Failure ] + crbug.com/667560 [ Win ] http/tests/devtools/console-cross-origin-iframe-logging.js [ Pass Timeout ] crbug.com/667560 [ Win ] virtual/mojo-loading/http/tests/devtools/console-cross-origin-iframe-logging.js [ Pass Timeout ] @@ -2982,7 +2975,7 @@ # ====== Begin of display: contents tests ====== crbug.com/657748 external/wpt/css/css-display/display-contents-dynamic-flex-002-inline.html [ Failure ] -crbug.com/657748 external/wpt/css/css-display/display-contents-dynamic-table-001-inline.html [ Failure ] +crbug.com/181374 external/wpt/css/css-display/display-contents-dynamic-table-001-inline.html [ Failure ] # ====== End of display: contents tests ====== @@ -3555,7 +3548,6 @@ crbug.com/755405 [ Android ] external/wpt/web-animations/animation-model/combining-effects/effect-composition.html [ Failure ] crbug.com/755405 [ Android ] external/wpt/web-animations/animation-model/keyframe-effects/effect-value-context.html [ Failure ] crbug.com/755405 [ Android ] external/wpt/web-animations/interfaces/Animatable/getAnimations.html [ Failure ] -crbug.com/755405 [ Android ] external/wpt/web-animations/interfaces/Animation/playState.html [ Failure ] crbug.com/755405 [ Android ] external/wpt/web-animations/interfaces/Animation/ready.html [ Failure ] crbug.com/755405 [ Android ] external/wpt/web-animations/interfaces/AnimationEffectTiming/delay.html [ Failure ] crbug.com/755405 [ Android ] external/wpt/web-animations/interfaces/Document/getAnimations.html [ Failure ] @@ -4070,3 +4062,8 @@ crbug.com/789111 http/tests/devtools/service-workers/service-worker-v8-cache.js [ Pass Failure ] crbug.com/789139 [ Linux ] http/tests/devtools/sources/debugger/live-edit-no-reveal.js [ Pass Failure ] crbug.com/789139 [ Linux ] virtual/mojo-loading/http/tests/devtools/sources/debugger/live-edit-no-reveal.js [ Pass Failure ] +crbug.com/785179 [ Mac10.11 ] http/tests/devtools/console/console-viewport-stick-to-bottom.js [ Pass Failure ] +# Sheriff failures 2017-11-29 +crbug.com/789478 [ Mac ] virtual/prefer_compositing_to_lcd_text/scrollbars/custom-scrollbar-adjust-on-inactive-pseudo.html [ Pass Failure ] +crbug.com/789485 [ Linux ] virtual/mouseevent_fractional/fast/events/touch/gesture/gesture-tap-mouse-events-between-frames.html [ Pass Failure ] +crbug.com/789533 virtual/gpu/fast/canvas/OffscreenCanvas-2d-imageSmoothing.html [ Pass Failure ]
diff --git a/third_party/WebKit/LayoutTests/bluetooth/requestDevice/acceptAllDevices/optional-services-present.html b/third_party/WebKit/LayoutTests/bluetooth/requestDevice/acceptAllDevices/optional-services-present.html index 3c57feb..655c18776 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/requestDevice/acceptAllDevices/optional-services-present.html +++ b/third_party/WebKit/LayoutTests/bluetooth/requestDevice/acceptAllDevices/optional-services-present.html
@@ -6,20 +6,22 @@ <script src="../../../resources/bluetooth/bluetooth-helpers.js"></script> <script> 'use strict'; -bluetooth_test(() => { - return setBluetoothFakeAdapter('TwoHeartRateServicesAdapter') - .then(() => requestDeviceWithTrustedClick({ - acceptAllDevices: true, - optionalServices: ['heart_rate'] - })) - .then(device => device.gatt.connect()) - .then(gattServer => gattServer.getPrimaryServices()) - .then(services => { - assert_equals(services.length, 2); - services.forEach(service => { - assert_equals(service.uuid, BluetoothUUID.getService('heart_rate')); - }); - }) -}, 'requestDevice called with acceptAllDevices: true and with ' + - 'optionalServices. Should get access to services.'); +const test_desc = 'requestDevice called with acceptAllDevices: true and with ' + + 'optionalServices. Should get access to services.'; + +bluetooth_test(() => + getTwoHealthThermometerServicesDevice() + .then(() => requestDeviceWithTrustedClick({ + acceptAllDevices: true, + optionalServices: ['health_thermometer'] + })) + .then(device => device.gatt.connect()) + .then(gattServer => gattServer.getPrimaryServices()) + .then(services => { + assert_equals(services.length, 2); + services.forEach(service => { + assert_equals(service.uuid, + BluetoothUUID.getService('health_thermometer')); + }); +}), test_desc); </script>
diff --git a/third_party/WebKit/LayoutTests/bluetooth/requestDevice/request-from-iframe.html b/third_party/WebKit/LayoutTests/bluetooth/requestDevice/request-from-iframe.html index 0bc8749..748f010d 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/requestDevice/request-from-iframe.html +++ b/third_party/WebKit/LayoutTests/bluetooth/requestDevice/request-from-iframe.html
@@ -28,11 +28,7 @@ .then(() => new Promise(async (resolve) => { let numMessages = 0; window.onmessage = messageEvent => { - if (messageEvent.data !== 'Success') { - assert_unreached('Bad message, expected "Success": ' + - messageEvent.data); - } - + assert_equals(messageEvent.data, 'Success'); if (++numMessages === iframes.length) { resolve(); }
diff --git a/third_party/WebKit/LayoutTests/bluetooth/requestDevice/request-from-sandboxed-iframe.html b/third_party/WebKit/LayoutTests/bluetooth/requestDevice/request-from-sandboxed-iframe.html index 0832590..af2e57b 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/requestDevice/request-from-sandboxed-iframe.html +++ b/third_party/WebKit/LayoutTests/bluetooth/requestDevice/request-from-sandboxed-iframe.html
@@ -22,15 +22,15 @@ })) // 2. Request the device from the iframe. .then(() => new Promise(resolve => { + callWithTrustedClick(() => { + iframe.contentWindow.postMessage('Go', '*'); + }); + window.onmessage = messageEvent => { assert_equals(messageEvent.data, 'SecurityError: requestDevice() ' + 'called from cross-origin iframe.'); resolve(); } - - callWithTrustedClick(() => { - iframe.contentWindow.postMessage('Go', '*'); - }); })), test_desc); </script> </body>
diff --git a/third_party/WebKit/LayoutTests/bluetooth/server/disconnect/connect-disconnect-twice.html b/third_party/WebKit/LayoutTests/bluetooth/server/disconnect/connect-disconnect-twice.html index 55f49b2..94ce8c15 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/server/disconnect/connect-disconnect-twice.html +++ b/third_party/WebKit/LayoutTests/bluetooth/server/disconnect/connect-disconnect-twice.html
@@ -6,20 +6,24 @@ <script src="../../../resources/bluetooth/bluetooth-helpers.js"></script> <script> 'use strict'; -bluetooth_test(() => { - return setBluetoothFakeAdapter('HeartRateAdapter') - .then(() => requestDeviceWithTrustedClick({ - filters: [{services: ['heart_rate']}]})) - .then(device => { - return device.gatt.connect() - .then(gattServer => { - gattServer.disconnect(); - assert_false(gattServer.connected); - }) - .then(() => device.gatt.connect()).then(gattServer => { - gattServer.disconnect(); - assert_false(gattServer.connected); - }); - }); -}, 'Connect + Disconnect twice still results in \'connected\' being false.'); +const test_desc = 'Connect + Disconnect twice still results in ' + + '\'connected\' being false.'; +let device, fake_peripheral; + +// TODO(569716): Test that the disconnect signal was sent to the device. +bluetooth_test(() => getDiscoveredHealthThermometerDevice() + .then(_ => ({device, fake_peripheral} = _)) + .then(() => fake_peripheral.setNextGATTConnectionResponse({ + code: HCI_SUCCESS, + })) + .then(() => device.gatt.connect() + .then(gattServer => { + gattServer.disconnect(); + assert_false(gattServer.connected); + }) + .then(() => device.gatt.connect()) + .then(gattServer => { + gattServer.disconnect(); + assert_false(gattServer.connected); + })), test_desc); </script>
diff --git a/third_party/WebKit/LayoutTests/bluetooth/server/disconnect/disconnect-twice-in-a-row.html b/third_party/WebKit/LayoutTests/bluetooth/server/disconnect/disconnect-twice-in-a-row.html index 6f51a99e..be40770 100644 --- a/third_party/WebKit/LayoutTests/bluetooth/server/disconnect/disconnect-twice-in-a-row.html +++ b/third_party/WebKit/LayoutTests/bluetooth/server/disconnect/disconnect-twice-in-a-row.html
@@ -6,17 +6,21 @@ <script src="../../../resources/bluetooth/bluetooth-helpers.js"></script> <script> 'use strict'; -bluetooth_test(() => { - return setBluetoothFakeAdapter('HeartRateAdapter') - .then(() => requestDeviceWithTrustedClick({ - filters: [{services: ['heart_rate']}]})) - .then(device => device.gatt.connect()) - .then(gattServer => { - gattServer.disconnect(); - assert_false(gattServer.connected); - gattServer.disconnect(); - assert_false(gattServer.connected); - }); -}, 'Calling disconnect twice in a row still results in \'connected\' ' + - 'being false.'); +const test_desc = 'Calling disconnect twice in a row still results in ' + + '\'connected\' being false.'; +let device, fake_peripheral; + +// TODO(569716): Test that the disconnect signal was sent to the device. +bluetooth_test(() => getDiscoveredHealthThermometerDevice() + .then(_ => ({device, fake_peripheral} = _)) + .then(() => fake_peripheral.setNextGATTConnectionResponse({ + code: HCI_SUCCESS, + })) + .then(() => device.gatt.connect()) + .then(gattServer => { + gattServer.disconnect(); + assert_false(gattServer.connected); + gattServer.disconnect(); + assert_false(gattServer.connected); +}), test_desc); </script>
diff --git a/third_party/WebKit/LayoutTests/compositing/overflow/mask-with-filter-expected.png b/third_party/WebKit/LayoutTests/compositing/overflow/mask-with-filter-expected.png deleted file mode 100644 index fff540df..0000000 --- a/third_party/WebKit/LayoutTests/compositing/overflow/mask-with-filter-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/css3/filters/blur-filter-page-scroll-self-expected.png b/third_party/WebKit/LayoutTests/css3/filters/blur-filter-page-scroll-self-expected.png new file mode 100644 index 0000000..dffda23 --- /dev/null +++ b/third_party/WebKit/LayoutTests/css3/filters/blur-filter-page-scroll-self-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/css3/filters/crash-filter-change-expected.png b/third_party/WebKit/LayoutTests/css3/filters/crash-filter-change-expected.png index 45fcc5a..217268f1 100644 --- a/third_party/WebKit/LayoutTests/css3/filters/crash-filter-change-expected.png +++ b/third_party/WebKit/LayoutTests/css3/filters/crash-filter-change-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/css3/filters/effect-blur-expected.png b/third_party/WebKit/LayoutTests/css3/filters/effect-blur-expected.png index 4f8998f..c5744cc 100644 --- a/third_party/WebKit/LayoutTests/css3/filters/effect-blur-expected.png +++ b/third_party/WebKit/LayoutTests/css3/filters/effect-blur-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/css3/filters/filter-change-repaint-expected.png b/third_party/WebKit/LayoutTests/css3/filters/filter-change-repaint-expected.png deleted file mode 100644 index 8495c55..0000000 --- a/third_party/WebKit/LayoutTests/css3/filters/filter-change-repaint-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/css3/filters/filter-repaint-blur-expected.png b/third_party/WebKit/LayoutTests/css3/filters/filter-repaint-blur-expected.png new file mode 100644 index 0000000..644479e1 --- /dev/null +++ b/third_party/WebKit/LayoutTests/css3/filters/filter-repaint-blur-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/css3/filters/filter-repaint-child-layers-expected.png b/third_party/WebKit/LayoutTests/css3/filters/filter-repaint-child-layers-expected.png index c79bc09..8222ae09 100644 --- a/third_party/WebKit/LayoutTests/css3/filters/filter-repaint-child-layers-expected.png +++ b/third_party/WebKit/LayoutTests/css3/filters/filter-repaint-child-layers-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/css3/filters/filter-repaint-expected.png b/third_party/WebKit/LayoutTests/css3/filters/filter-repaint-expected.png new file mode 100644 index 0000000..0232e0f --- /dev/null +++ b/third_party/WebKit/LayoutTests/css3/filters/filter-repaint-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/css3/filters/filter-repaint-shadow-expected.png b/third_party/WebKit/LayoutTests/css3/filters/filter-repaint-shadow-expected.png new file mode 100644 index 0000000..fb4ab60 --- /dev/null +++ b/third_party/WebKit/LayoutTests/css3/filters/filter-repaint-shadow-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/css3/filters/filtered-inline-expected.png b/third_party/WebKit/LayoutTests/css3/filters/filtered-inline-expected.png new file mode 100644 index 0000000..9919eba --- /dev/null +++ b/third_party/WebKit/LayoutTests/css3/filters/filtered-inline-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/css3/filters/regions-expanding-expected.png b/third_party/WebKit/LayoutTests/css3/filters/regions-expanding-expected.png index 83d26a9..3356944 100644 --- a/third_party/WebKit/LayoutTests/css3/filters/regions-expanding-expected.png +++ b/third_party/WebKit/LayoutTests/css3/filters/regions-expanding-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/external/WPT_BASE_MANIFEST.json b/third_party/WebKit/LayoutTests/external/WPT_BASE_MANIFEST.json index d5a41f5..1deea7f 100644 --- a/third_party/WebKit/LayoutTests/external/WPT_BASE_MANIFEST.json +++ b/third_party/WebKit/LayoutTests/external/WPT_BASE_MANIFEST.json
@@ -76125,6 +76125,18 @@ {} ] ], + "css/cssom/medialist-dynamic-001.html": [ + [ + "/css/cssom/medialist-dynamic-001.html", + [ + [ + "/css/cssom/medialist-dynamic-001-ref.html", + "==" + ] + ], + {} + ] + ], "css/cssom/selectorText-modification-restyle-001.html": [ [ "/css/cssom/selectorText-modification-restyle-001.html", @@ -98401,6 +98413,11 @@ {} ] ], + "css/css-color/OWNERS": [ + [ + {} + ] + ], "css/css-color/blacktext-ref.html": [ [ {} @@ -118866,6 +118883,11 @@ {} ] ], + "css/cssom/medialist-dynamic-001-ref.html": [ + [ + {} + ] + ], "css/cssom/medialist-interfaces-001-expected.txt": [ [ {} @@ -135661,11 +135683,6 @@ {} ] ], - "html/semantics/forms/the-progress-element/progress-expected.txt": [ - [ - {} - ] - ], "html/semantics/forms/the-select-element/.gitkeep": [ [ {} @@ -144141,31 +144158,6 @@ {} ] ], - "service-workers/service-worker/link-element-register-mime-types.https-expected.txt": [ - [ - {} - ] - ], - "service-workers/service-worker/link-element-register-scope.https-expected.txt": [ - [ - {} - ] - ], - "service-workers/service-worker/link-element-register-script-url.https-expected.txt": [ - [ - {} - ] - ], - "service-workers/service-worker/link-element-register-script.https-expected.txt": [ - [ - {} - ] - ], - "service-workers/service-worker/link-element-register-security-error.https-expected.txt": [ - [ - {} - ] - ], "service-workers/service-worker/multi-globals/current/current.https.html": [ [ {} @@ -144841,11 +144833,6 @@ {} ] ], - "service-workers/service-worker/resources/iframe-register-link-element.html": [ - [ - {} - ] - ], "service-workers/service-worker/resources/immutable-prototype-serviceworker.js": [ [ {} @@ -144946,11 +144933,6 @@ {} ] ], - "service-workers/service-worker/resources/link-header.py": [ - [ - {} - ] - ], "service-workers/service-worker/resources/load_worker.js": [ [ {} @@ -147061,6 +147043,16 @@ {} ] ], + "web-animations/interfaces/Animation/pause-expected.txt": [ + [ + {} + ] + ], + "web-animations/interfaces/Animation/pending-expected.txt": [ + [ + {} + ] + ], "web-animations/interfaces/AnimationEffectTiming/getComputedTiming-expected.txt": [ [ {} @@ -147176,6 +147168,16 @@ {} ] ], + "web-animations/timing-model/animations/pausing-an-animation-expected.txt": [ + [ + {} + ] + ], + "web-animations/timing-model/animations/play-states-expected.txt": [ + [ + {} + ] + ], "web-animations/timing-model/animations/reversing-an-animation-expected.txt": [ [ {} @@ -167848,6 +167850,12 @@ {} ] ], + "css/cssom-view/scroll-behavior-smooth.html": [ + [ + "/css/cssom-view/scroll-behavior-smooth.html", + {} + ] + ], "css/cssom-view/scrollIntoView-shadow.html": [ [ "/css/cssom-view/scrollIntoView-shadow.html", @@ -169096,6 +169104,12 @@ {} ] ], + "custom-elements/reactions/with-exceptions.html": [ + [ + "/custom-elements/reactions/with-exceptions.html", + {} + ] + ], "custom-elements/upgrading.html": [ [ "/custom-elements/upgrading.html", @@ -197250,6 +197264,12 @@ {} ] ], + "paint-timing/sibling-painting-first-image.html": [ + [ + "/paint-timing/sibling-painting-first-image.html", + {} + ] + ], "payment-handler/interfaces.https.any.js": [ [ "/payment-handler/interfaces.https.any.html", @@ -207188,12 +207208,6 @@ {} ] ], - "service-workers/service-worker/iframe-sandbox-register-link-element.https.html": [ - [ - "/service-workers/service-worker/iframe-sandbox-register-link-element.https.html", - {} - ] - ], "service-workers/service-worker/immutable-prototype-serviceworker.https.html": [ [ "/service-workers/service-worker/immutable-prototype-serviceworker.https.html", @@ -207266,42 +207280,6 @@ {} ] ], - "service-workers/service-worker/link-element-register-basic.https.html": [ - [ - "/service-workers/service-worker/link-element-register-basic.https.html", - {} - ] - ], - "service-workers/service-worker/link-element-register-mime-types.https.html": [ - [ - "/service-workers/service-worker/link-element-register-mime-types.https.html", - {} - ] - ], - "service-workers/service-worker/link-element-register-scope.https.html": [ - [ - "/service-workers/service-worker/link-element-register-scope.https.html", - {} - ] - ], - "service-workers/service-worker/link-element-register-script-url.https.html": [ - [ - "/service-workers/service-worker/link-element-register-script-url.https.html", - {} - ] - ], - "service-workers/service-worker/link-element-register-script.https.html": [ - [ - "/service-workers/service-worker/link-element-register-script.https.html", - {} - ] - ], - "service-workers/service-worker/link-element-register-security-error.https.html": [ - [ - "/service-workers/service-worker/link-element-register-security-error.https.html", - {} - ] - ], "service-workers/service-worker/mime-sniffing.https.html": [ [ "/service-workers/service-worker/mime-sniffing.https.html", @@ -207484,12 +207462,6 @@ {} ] ], - "service-workers/service-worker/register-link-header.https.html": [ - [ - "/service-workers/service-worker/register-link-header.https.html", - {} - ] - ], "service-workers/service-worker/register-same-scope-different-script-url.https.html": [ [ "/service-workers/service-worker/register-same-scope-different-script-url.https.html", @@ -210698,15 +210670,15 @@ {} ] ], - "web-animations/interfaces/Animation/play.html": [ + "web-animations/interfaces/Animation/pending.html": [ [ - "/web-animations/interfaces/Animation/play.html", + "/web-animations/interfaces/Animation/pending.html", {} ] ], - "web-animations/interfaces/Animation/playState.html": [ + "web-animations/interfaces/Animation/play.html": [ [ - "/web-animations/interfaces/Animation/playState.html", + "/web-animations/interfaces/Animation/play.html", {} ] ], @@ -210932,6 +210904,12 @@ {} ] ], + "web-animations/timing-model/animations/play-states.html": [ + [ + "/web-animations/timing-model/animations/play-states.html", + {} + ] + ], "web-animations/timing-model/animations/playing-an-animation.html": [ [ "/web-animations/timing-model/animations/playing-an-animation.html", @@ -221514,7 +221492,7 @@ "support" ], "./lint.whitelist": [ - "3e99e9b1067fa53972fabfb34b1e880ae056558f", + "d92bc2e8adfdf40cd2023883e69e42fe59b5f069", "support" ], "./update-built-tests.sh": [ @@ -222394,7 +222372,7 @@ "testharness" ], "2dcontext/drawing-images-to-the-canvas/2d.drawImage.zerosource.image-expected.txt": [ - "05fc596d6534b2a9ab87f3a02bfab28d9b3c243b", + "9a724594c0003fad4f1d8ee50f1db97fa4800c07", "support" ], "2dcontext/drawing-images-to-the-canvas/2d.drawImage.zerosource.image.html": [ @@ -229458,7 +229436,7 @@ "testharness" ], "XMLHttpRequest/send-content-type-charset-expected.txt": [ - "bf6d058086886b6b0881a42b7f8daa0e9945e444", + "04326d5b654c4855fbcd30f741f2bc8be3168674", "support" ], "XMLHttpRequest/send-content-type-charset.htm": [ @@ -250241,6 +250219,10 @@ "471498a01f4a40e6905bed7af941ffe638fa747e", "support" ], + "css/css-color/OWNERS": [ + "495f99b874611fd8f82f2e33bc4b7d930cc60fde", + "support" + ], "css/css-color/blacktext-ref.html": [ "5541159a1753a7e249c36d31f65e47d02e98f848", "support" @@ -285874,7 +285856,7 @@ "testharness" ], "css/cssom-view/overscrollBehavior-manual.html": [ - "ca369af991f1e1c34116f2effe0d53a806ed9df5", + "65cb71ca6b606dc8b0b527c58902566539e771b2", "manual" ], "css/cssom-view/resources/elementsFromPoint.js": [ @@ -285889,6 +285871,10 @@ "0a8784c474ccdd4a3e76cb936855a8ef59566217", "support" ], + "css/cssom-view/scroll-behavior-smooth.html": [ + "966ebff69f91c0ea92f4bc2f943df9ef9dc3bcf9", + "testharness" + ], "css/cssom-view/scrollIntoView-shadow.html": [ "3c4a18992105fd7bf19cbf29f0b6d80cb12ca98c", "testharness" @@ -286313,6 +286299,14 @@ "c1dfd96239986c9c57d7b07caebbd1fc9654e0b9", "testharness" ], + "css/cssom/medialist-dynamic-001-ref.html": [ + "bdf98c994adcebff3a3434260dfe71e99c8441e1", + "support" + ], + "css/cssom/medialist-dynamic-001.html": [ + "8c62d1e6b5791b68240551c0c9cd115f4d16a892", + "reftest" + ], "css/cssom/medialist-interfaces-001-expected.txt": [ "0a6f54e6927a8ce27b16585062dc85b7df8ac18b", "support" @@ -291585,6 +291579,10 @@ "e966b6c608ee9b4183e040b8be7adb2b73722c7b", "support" ], + "custom-elements/reactions/with-exceptions.html": [ + "b72ee82a3d98c61683e62c4834f54269898e12d5", + "testharness" + ], "custom-elements/resources/custom-elements-helpers.js": [ "875838d63f7d44c7a958a03c494ba709c53816c9", "support" @@ -302314,7 +302312,7 @@ "support" ], "html/dom/interfaces-expected.txt": [ - "f77edca9285e6a18aa48d4881038d77da43e003b", + "7d8e224ad8944e40d251576b26468881b1852a55", "support" ], "html/dom/interfaces.html": [ @@ -311353,12 +311351,8 @@ "39e1303dd97060348893e6a32e23a2723ce86170", "testharness" ], - "html/semantics/forms/the-progress-element/progress-expected.txt": [ - "cb64a3fe3f0c68d7eafbf303a28200fab8c30066", - "support" - ], "html/semantics/forms/the-progress-element/progress.html": [ - "ae4f3f8d86b720ba8f6c1fe7443cc425519de5da", + "786e7998c0a1e10ba76b26a87d45ea9c3c9893b4", "testharness" ], "html/semantics/forms/the-progress-element/progress.window.js": [ @@ -316442,7 +316436,7 @@ "support" ], "interfaces/html.idl": [ - "4a50b985b8db843991c9b2ebf00be9b408e8077e", + "b2bdcbda51884672a5efe3f62e93d622709e7f82", "support" ], "interfaces/magnetometer.idl": [ @@ -325582,7 +325576,7 @@ "testharness" ], "paint-timing/child-painting-first-image.html": [ - "53429c63e77999dbcc633ff45469b869d2005d5e", + "a2b3a8fd7cf8a700f7dd6b7f044eb6d6deb9ceee", "testharness" ], "paint-timing/first-contentful-bg-image.html": [ @@ -325637,6 +325631,10 @@ "14013a37d0f6496ab3d793c4c51eb8d22c1aec57", "support" ], + "paint-timing/sibling-painting-first-image.html": [ + "e820a430d03a1ceb40f96f91982eea9ed1d6ac75", + "testharness" + ], "payment-handler/OWNERS": [ "75c6f2aca2a7226545ea81a5f6ea93cb9742ace4", "support" @@ -325810,7 +325808,7 @@ "testharness" ], "payment-request/payment-request-constructor.https.html": [ - "1cda9bee85f3afe53e492a7f0e98b12cbfcd9b98", + "511c4d25939d344f187fe4a8daa4a8ff926b613d", "testharness" ], "payment-request/payment-request-ctor-currency-code-checks.https.html": [ @@ -335633,10 +335631,6 @@ "95aee5b0d561467fb5da27f62210be9808539706", "testharness" ], - "service-workers/service-worker/iframe-sandbox-register-link-element.https.html": [ - "6cafc3245c88f7d96f6a4672b327d3b58ee4a0ee", - "testharness" - ], "service-workers/service-worker/immutable-prototype-serviceworker.https.html": [ "5c17042fa54cd1fdba6f7aae513412d4a223b432", "testharness" @@ -335697,50 +335691,6 @@ "3c75caa66d3906602d10b07ff22e7d0f210cfee9", "testharness" ], - "service-workers/service-worker/link-element-register-basic.https.html": [ - "c38709eafae1c43fb6de9c90ad41634bfb749d14", - "testharness" - ], - "service-workers/service-worker/link-element-register-mime-types.https-expected.txt": [ - "ac763c885ae2978c8e4da5484ae69ecbf2bd1ca1", - "support" - ], - "service-workers/service-worker/link-element-register-mime-types.https.html": [ - "7f09c63104e39c76638e9193ac07e383ac0435ad", - "testharness" - ], - "service-workers/service-worker/link-element-register-scope.https-expected.txt": [ - "3a59df28b22f7b6321dd15ec525fdebc217f4816", - "support" - ], - "service-workers/service-worker/link-element-register-scope.https.html": [ - "c29407cfdce522c6a576d866ece6fffe831c85ac", - "testharness" - ], - "service-workers/service-worker/link-element-register-script-url.https-expected.txt": [ - "44db94bf1009cf70d3044862401fed207549dfc8", - "support" - ], - "service-workers/service-worker/link-element-register-script-url.https.html": [ - "f3920a47686a1e4792f097f52cf51531dccd58a8", - "testharness" - ], - "service-workers/service-worker/link-element-register-script.https-expected.txt": [ - "de8bf975e6ac0ad0c06f5a2c2f4e91ed421663cb", - "support" - ], - "service-workers/service-worker/link-element-register-script.https.html": [ - "9751dfe02dff339124352311115e61b19e7edf66", - "testharness" - ], - "service-workers/service-worker/link-element-register-security-error.https-expected.txt": [ - "4d32a8b5a3a95d0a26c9ba315bfa37572cadeebc", - "support" - ], - "service-workers/service-worker/link-element-register-security-error.https.html": [ - "026a444eb0ff60e7885f70c7a4c3fa03a2510de3", - "testharness" - ], "service-workers/service-worker/mime-sniffing.https.html": [ "d61a859a111dea758efb91480817fa1a029c152b", "testharness" @@ -335961,10 +335911,6 @@ "864f5435fc40124dbe2c1ffb0e1942fee58228d2", "testharness" ], - "service-workers/service-worker/register-link-header.https.html": [ - "fa97635d3a16a0f2a0a0bae8e4b81c8b5100d9cd", - "testharness" - ], "service-workers/service-worker/register-same-scope-different-script-url.https.html": [ "2d337b2252fc4235830de53fcb3dc280d3aca82c", "testharness" @@ -336022,11 +335968,11 @@ "testharness" ], "service-workers/service-worker/registration-updateviacache.https-expected.txt": [ - "16a53b3b83466274f5ae17bb58a5abcf95f54487", + "a2bfe6d6414cf0816391aa6830efcf09863053e1", "support" ], "service-workers/service-worker/registration-updateviacache.https.html": [ - "90c97975a11fc639e775d26e9d0354d514ae7a9b", + "c1caf6840bc36eed4f4ece8e42702151e08b3754", "testharness" ], "service-workers/service-worker/rejections.https.html": [ @@ -336469,10 +336415,6 @@ "b1a69bedbfbcb8f5b38d35f637f75f167d80118a", "support" ], - "service-workers/service-worker/resources/iframe-register-link-element.html": [ - "9ea5eb8893ae3d75c18566f5862c66df6bc831c0", - "support" - ], "service-workers/service-worker/resources/immutable-prototype-serviceworker.js": [ "0a428649e0ceaaacdea5d156e829c63668bc3f72", "support" @@ -336553,10 +336495,6 @@ "3af11938ec23e1989785be2da453922686e5ace1", "support" ], - "service-workers/service-worker/resources/link-header.py": [ - "5717930bd579b9a63f1b3619195d65b46aa044cf", - "support" - ], "service-workers/service-worker/resources/load_worker.js": [ "08525451705224fd78993adaed33a345d514c9a1", "support" @@ -340614,7 +340552,7 @@ "testharness" ], "web-animations/interfaces/Animatable/animate-expected.txt": [ - "be0d48b5b82c87caa9f965d204937b7d2f9e20d3", + "44f12cffe79ea1057136d9f6587e1434464fc0b9", "support" ], "web-animations/interfaces/Animatable/animate-no-browsing-context-expected.txt": [ @@ -340622,11 +340560,11 @@ "support" ], "web-animations/interfaces/Animatable/animate-no-browsing-context.html": [ - "284d173b6875923ddd894d2ac7498cd07311c001", + "1d9479b404662702c2592099bde95a472f65d403", "testharness" ], "web-animations/interfaces/Animatable/animate.html": [ - "b4e51f3b2fe045dfa87b0e67437b625721804bca", + "2860fe7264ba57cff3f73725cf95b7d7640a10f1", "testharness" ], "web-animations/interfaces/Animatable/getAnimations.html": [ @@ -340666,11 +340604,11 @@ "testharness" ], "web-animations/interfaces/Animation/idlharness-expected.txt": [ - "cf789f0ccea1e1ebe9de6718f8a10d13ec6c314a", + "b271a90539fa3706a914a7199a7ad0b3c2a47102", "support" ], "web-animations/interfaces/Animation/idlharness.html": [ - "b9784215a32d3d00d9a2c17c115ec9048d67c779", + "b369d57caf6557abee257ecbae0c7b4fd49965d7", "testharness" ], "web-animations/interfaces/Animation/oncancel.html": [ @@ -340681,18 +340619,26 @@ "597362b0108c367511c26b9561158b6f32c63f54", "testharness" ], + "web-animations/interfaces/Animation/pause-expected.txt": [ + "6446f4d113410f1fcb644069e6bb896d27afca72", + "support" + ], "web-animations/interfaces/Animation/pause.html": [ - "bdbd4d3e88a0b41f3685ba14fa049d507d7dbd59", + "5be086cfc44f3d6d464016c2fe9b17220a6a4dc6", + "testharness" + ], + "web-animations/interfaces/Animation/pending-expected.txt": [ + "83baa5622e52753854a14cb66c84f673dd71ed72", + "support" + ], + "web-animations/interfaces/Animation/pending.html": [ + "38042fa2c8c1c4d0dae660e0d33393ba404a7c4d", "testharness" ], "web-animations/interfaces/Animation/play.html": [ "b375f449a4c75b02d0d746e44e2ca6ff9646819b", "testharness" ], - "web-animations/interfaces/Animation/playState.html": [ - "69da0c5be9b5734fc45ccf0d5c855dbae8b71a8a", - "testharness" - ], "web-animations/interfaces/Animation/playbackRate.html": [ "a5463d070f7273e54099bc94d8a7b31b5366665d", "testharness" @@ -340929,8 +340875,20 @@ "f662027f020312c17ec9385542583ba675c38e82", "testharness" ], + "web-animations/timing-model/animations/pausing-an-animation-expected.txt": [ + "99b5fcf7a330f5c8fe1e8308395423cee80e5d4a", + "support" + ], "web-animations/timing-model/animations/pausing-an-animation.html": [ - "9106dcffe7b9816cd9bda222714520f640b0afdc", + "689b3dbdb202210d908e61ed780a7c43f2a7f04c", + "testharness" + ], + "web-animations/timing-model/animations/play-states-expected.txt": [ + "5f923216eba021a2b3c8ec8b8cf417a394e0b161", + "support" + ], + "web-animations/timing-model/animations/play-states.html": [ + "6d460def8ee43c4c044bc80f9c41954891b7cb06", "testharness" ], "web-animations/timing-model/animations/playing-an-animation.html": [ @@ -340938,31 +340896,31 @@ "testharness" ], "web-animations/timing-model/animations/reversing-an-animation-expected.txt": [ - "a5dbf9c9ab43c46a8aa2f15da03b4647e901d540", + "7213d1ca191c82bb4faba325e213a1c9911a21bd", "support" ], "web-animations/timing-model/animations/reversing-an-animation.html": [ - "01975f70399d3934db8247f3a8ddfb09afd26b78", + "2f23c434ffded1caea40dd2511ed91e7d2ca1d8a", "testharness" ], "web-animations/timing-model/animations/set-the-animation-start-time.html": [ - "9ead33eebc9f697b71c7a7d5b22cf6302d29837b", + "ee034df474b45ec0f186dd2de44c453ffad212ef", "testharness" ], "web-animations/timing-model/animations/set-the-target-effect-of-an-animation-expected.txt": [ - "a04535dc40d2b987a46d248f9b4580acecd02fc6", + "615dad4a26af923ab4ecd2a86c0679c9ce4a8e5b", "support" ], "web-animations/timing-model/animations/set-the-target-effect-of-an-animation.html": [ - "dec02f25748e0abdad129469469cbf0e5539941a", + "fa6bfd26bd1df7a12959cbbbd8eda8a92ac265d6", "testharness" ], "web-animations/timing-model/animations/set-the-timeline-of-an-animation-expected.txt": [ - "2b9c1d6d8b662302c74dbe0e9eac9ac2f2cfc371", + "52775ff2bf8d19a4f69bc3797197ce10bb6bc6bb", "support" ], "web-animations/timing-model/animations/set-the-timeline-of-an-animation.html": [ - "fd0c7192901ae0030268457c2dfa7554783608b3", + "c167894c1968cf15b85ebe329bd50e7e00782195", "testharness" ], "web-animations/timing-model/animations/updating-the-finished-state.html": [
diff --git a/third_party/WebKit/LayoutTests/external/wpt/XMLHttpRequest/send-authentication-competing-names-passwords-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/XMLHttpRequest/send-authentication-competing-names-passwords-expected.txt index 185fe39..3635bb3 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/XMLHttpRequest/send-authentication-competing-names-passwords-expected.txt +++ b/third_party/WebKit/LayoutTests/external/wpt/XMLHttpRequest/send-authentication-competing-names-passwords-expected.txt
@@ -2,7 +2,7 @@ PASS XMLHttpRequest: send() - "Basic" authenticated requests with competing user name/password options user/pass in open() call PASS XMLHttpRequest: send() - "Basic" authenticated requests with competing user name/password options another user/pass in open() call - must override cached credentials from previous test PASS XMLHttpRequest: send() - "Basic" authenticated requests with competing user name/password options user/pass both in URL userinfo AND open() call - expexted that open() wins -PASS XMLHttpRequest: send() - "Basic" authenticated requests with competing user name/password options user/pass *only* in URL userinfo +FAIL XMLHttpRequest: send() - "Basic" authenticated requests with competing user name/password options user/pass *only* in URL userinfo assert_true: responseText should contain the right user and password expected true got false FAIL XMLHttpRequest: send() - "Basic" authenticated requests with competing user name/password options user name in URL userinfo, password in open() call: user name wins and password is thrown away assert_true: responseText should contain the right user and password expected true got false FAIL XMLHttpRequest: send() - "Basic" authenticated requests with competing user name/password options user name and password in URL userinfo, only user name in open() call: user name in open() wins assert_true: responseText should contain the right user and password expected true got false Harness: the test ran to completion.
diff --git a/third_party/WebKit/LayoutTests/external/wpt/XMLHttpRequest/send-redirect-post-upload.htm b/third_party/WebKit/LayoutTests/external/wpt/XMLHttpRequest/send-redirect-post-upload.htm index 37a90d4..5c1c638 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/XMLHttpRequest/send-redirect-post-upload.htm +++ b/third_party/WebKit/LayoutTests/external/wpt/XMLHttpRequest/send-redirect-post-upload.htm
@@ -15,8 +15,8 @@ <div id="log"></div> <script type="text/javascript"> - function testRedirectPost(code, shouldResendPost) { - var test = async_test(document.title + " (" + code + ")"); + function testRedirectPost(params) { + var test = async_test(document.title + " (" + params.name + ")"); var actual = []; // We check upload.onprogress with a boolean because it *might* fire more than once var progressFiredReadyState1 = false; @@ -24,13 +24,13 @@ var expectedHeaders, expectedEvents; // 307 redirects should resend the POST data, and events and headers will be a little different.. - if(shouldResendPost) { + if(params.expectResendPost) { expectedHeaders = { - "X-Request-Content-Length": "11988", + "X-Request-Content-Length": "12000", "X-Request-Content-Type": "text/plain;charset=UTF-8", "X-Request-Method": "POST", "X-Request-Query": "NO", - "Content-Length": "11988" + "Content-Length": "12000" } expectedEvents = [ "xhr onreadystatechange 1", @@ -63,6 +63,10 @@ "xhr loadend 4" ]; } + // Override expectations if provided. + if(params.expectedContentType) + expectedHeaders["X-Request-Content-Type"] = params.expectedContentType; + test.step(function() { var xhr = new XMLHttpRequest(); @@ -105,20 +109,24 @@ } assert_array_equals(actual, expectedEvents, "events firing in expected order and states"); + if (params.expectedBody) + assert_equals(xhr.response, params.expectedBody, 'request body was resent'); test.done(); }); - xhr.open("POST", "./resources/redirect.py?location=content.py&code=" + code, true); - xhr.send((new Array(1000)).join("Test Message")); + xhr.open("POST", "./resources/redirect.py?location=content.py&code=" + params.code, true); + xhr.send(params.body); }); } + const stringBody = "Test Message".repeat(1000); + const blobBody = new Blob(new Array(1000).fill("Test Message")); - testRedirectPost(301, false); - testRedirectPost(302, false); - testRedirectPost(303, false); - testRedirectPost(307, true); - + testRedirectPost({name: "301", code: 301, expectResendPost: false, body: stringBody}); + testRedirectPost({name: "302", code: 302, expectResendPost: false, body: stringBody}); + testRedirectPost({name: "303", code: 303, expectResendPost: false, body: stringBody}); + testRedirectPost({name: "307 (string)", code: 307, expectResendPost: true, body: stringBody, expectedBody: stringBody }); + testRedirectPost({name: "307 (blob)", code: 307, expectResendPost: true, body: blobBody, expectedBody: stringBody, expectedContentType: "NO" }); </script> </body> </html>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/XMLHttpRequest/setrequestheader-bogus-name-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/XMLHttpRequest/setrequestheader-bogus-name-expected.txt deleted file mode 100644 index ce71c46..0000000 --- a/third_party/WebKit/LayoutTests/external/wpt/XMLHttpRequest/setrequestheader-bogus-name-expected.txt +++ /dev/null
@@ -1,75 +0,0 @@ -This is a testharness.js-based test. -Found 71 tests; 69 PASS, 2 FAIL, 0 TIMEOUT, 0 NOTRUN. -PASS setRequestHeader should throw with header name "(". -PASS setRequestHeader should throw with header name ")". -PASS setRequestHeader should throw with header name "<". -PASS setRequestHeader should throw with header name ">". -PASS setRequestHeader should throw with header name "@". -PASS setRequestHeader should throw with header name ",". -PASS setRequestHeader should throw with header name ";". -PASS setRequestHeader should throw with header name ":". -PASS setRequestHeader should throw with header name "\\". -PASS setRequestHeader should throw with header name "\"". -PASS setRequestHeader should throw with header name "/". -PASS setRequestHeader should throw with header name "[". -PASS setRequestHeader should throw with header name "]". -PASS setRequestHeader should throw with header name "?". -PASS setRequestHeader should throw with header name "=". -PASS setRequestHeader should throw with header name "{". -PASS setRequestHeader should throw with header name "}". -PASS setRequestHeader should throw with header name " ". -PASS setRequestHeader should throw with header name "". -PASS setRequestHeader should throw with header name "". -PASS setRequestHeader should throw with header name "t\rt". -PASS setRequestHeader should throw with header name "t\nt". -PASS setRequestHeader should throw with header name "t: t". -PASS setRequestHeader should throw with header name "t:t". -PASS setRequestHeader should throw with header name "t<t". -PASS setRequestHeader should throw with header name "t t". -PASS setRequestHeader should throw with header name " tt". -PASS setRequestHeader should throw with header name ":tt". -PASS setRequestHeader should throw with header name "\ttt". -PASS setRequestHeader should throw with header name "\vtt". -PASS setRequestHeader should throw with header name "t\0t". -PASS setRequestHeader should throw with header name "t\"t". -PASS setRequestHeader should throw with header name "t,t". -PASS setRequestHeader should throw with header name "t;t". -PASS setRequestHeader should throw with header name "()[]{}". -PASS setRequestHeader should throw with header name "a?B". -PASS setRequestHeader should throw with header name "a=B". -PASS setRequestHeader should throw with header name "\0". -PASS setRequestHeader should throw with header name "\x01". -PASS setRequestHeader should throw with header name "\x02". -PASS setRequestHeader should throw with header name "\x03". -PASS setRequestHeader should throw with header name "\x04". -PASS setRequestHeader should throw with header name "\x05". -PASS setRequestHeader should throw with header name "\x06". -PASS setRequestHeader should throw with header name "\x07". -PASS setRequestHeader should throw with header name "\b". -PASS setRequestHeader should throw with header name "\t". -PASS setRequestHeader should throw with header name "\n". -PASS setRequestHeader should throw with header name "\v". -PASS setRequestHeader should throw with header name "\f". -PASS setRequestHeader should throw with header name "\r". -PASS setRequestHeader should throw with header name "\x0e". -PASS setRequestHeader should throw with header name "\x0f". -PASS setRequestHeader should throw with header name "\x10". -PASS setRequestHeader should throw with header name "\x11". -PASS setRequestHeader should throw with header name "\x12". -PASS setRequestHeader should throw with header name "\x13". -PASS setRequestHeader should throw with header name "\x14". -PASS setRequestHeader should throw with header name "\x15". -PASS setRequestHeader should throw with header name "\x16". -PASS setRequestHeader should throw with header name "\x17". -PASS setRequestHeader should throw with header name "\x18". -PASS setRequestHeader should throw with header name "\x19". -PASS setRequestHeader should throw with header name "\x1a". -PASS setRequestHeader should throw with header name "\x1b". -PASS setRequestHeader should throw with header name "\x1c". -PASS setRequestHeader should throw with header name "\x1d". -PASS setRequestHeader should throw with header name "\x1e". -PASS setRequestHeader should throw with header name "\x1f". -FAIL setRequestHeader should throw with header name "テスト". assert_throws: function "function () { client.setRequestHeader(name, 'x-value') }" threw object "SyntaxError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': 'テスト' is not a valid HTTP header field name." ("SyntaxError") expected object "TypeError" ("TypeError") -FAIL setRequestHeader should throw with header name "X-テスト". assert_throws: function "function () { client.setRequestHeader(name, 'x-value') }" threw object "SyntaxError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': 'X-テスト' is not a valid HTTP header field name." ("SyntaxError") expected object "TypeError" ("TypeError") -Harness: the test ran to completion. -
diff --git a/third_party/WebKit/LayoutTests/external/wpt/XMLHttpRequest/setrequestheader-bogus-value-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/XMLHttpRequest/setrequestheader-bogus-value-expected.txt deleted file mode 100644 index f935868..0000000 --- a/third_party/WebKit/LayoutTests/external/wpt/XMLHttpRequest/setrequestheader-bogus-value-expected.txt +++ /dev/null
@@ -1,8 +0,0 @@ -This is a testharness.js-based test. -PASS XMLHttpRequest: setRequestHeader() value argument checks -PASS XMLHttpRequest: setRequestHeader() value argument checks 1 -PASS XMLHttpRequest: setRequestHeader() value argument checks 2 -FAIL XMLHttpRequest: setRequestHeader() value argument checks 3 assert_throws: given value テスト, function "function () { client.setRequestHeader("x-test", "テスト") }" threw object "SyntaxError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': 'テスト' is not a valid HTTP header field value." ("SyntaxError") expected object "TypeError" ("TypeError") -PASS Omitted value argument -Harness: the test ran to completion. -
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-transforms/transform-box/fill-box.html b/third_party/WebKit/LayoutTests/external/wpt/css/css-transforms/transform-box/fill-box.html new file mode 100644 index 0000000..eaea02a --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-transforms/transform-box/fill-box.html
@@ -0,0 +1,33 @@ +<!DOCTYPE html> +<title>transform-box: fill-box</title> +<link rel="match" href="support/greensquare200x200.html"> +<link rel="help" href="https://drafts.csswg.org/css-transforms/#transform-box"> +<style> +svg { + background-color: red; +} +rect { + transform-box: fill-box; +} +#target1 { + transform: rotate(90deg); +} +#target2 { + transform: translate(50%, -50%); +} +#target3 { + transform-origin: 25% 25%; + transform: rotate(180deg) translate(-25%, -25%); +} +#target4 { + transform-origin: 75px 75px; + transform: rotate(-180deg) translate(-25%, -25%); +} +</style> +<p>There should be a green 200x200 rectangle below, and no red.</p> +<svg width="200" height="200"> + <rect id="target1" x="100" y="100" width="100" height="100" fill="green"/> + <rect id="target2" x="50" y="50" width="100" height="100" fill="green"/> + <rect id="target3" x="25" y="25" width="100" height="100" fill="green"/> + <rect id="target4" x="25" y="25" width="100" height="100" fill="green"/> +</svg>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-transforms/transform-box/support/greensquare200x200.html b/third_party/WebKit/LayoutTests/external/wpt/css/css-transforms/transform-box/support/greensquare200x200.html new file mode 100644 index 0000000..bee8bc70 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-transforms/transform-box/support/greensquare200x200.html
@@ -0,0 +1,3 @@ +<!DOCTYPE html> +<p>There should be a green 200x200 rectangle below, and no red.</p> +<div style="width: 200px; height: 200px; background-color: green"></div>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-transforms/transform-box/view-box-nested.html b/third_party/WebKit/LayoutTests/external/wpt/css/css-transforms/transform-box/view-box-nested.html new file mode 100644 index 0000000..7f59777 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-transforms/transform-box/view-box-nested.html
@@ -0,0 +1,17 @@ +<!DOCTYPE html> +<title>transform-box: view-box, relative to nested viewport</title> +<link rel="match" href="support/greensquare200x200.html"> +<link rel="help" href="https://drafts.csswg.org/css-transforms/#transform-box"> +<style> +#target { + transform-box: view-box; + transform: translate(-50%, -50%); +} +</style> +<p>There should be a green 200x200 rectangle below, and no red.</p> +<svg width="400" height="200"> + <rect width="200" height="200" fill="red"/> + <svg width="200" height="200"> + <rect id="target" x="100" y="100" width="200" height="200" fill="green"/> + </svg> +</svg>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-transforms/transform-box/view-box-viewbox-nested.html b/third_party/WebKit/LayoutTests/external/wpt/css/css-transforms/transform-box/view-box-viewbox-nested.html new file mode 100644 index 0000000..4f667e2 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-transforms/transform-box/view-box-viewbox-nested.html
@@ -0,0 +1,17 @@ +<!DOCTYPE html> +<title>transform-box: view-box, relative to viewport defined by nested viewBox</title> +<link rel="match" href="support/greensquare200x200.html"> +<link rel="help" href="https://drafts.csswg.org/css-transforms/#transform-box"> +<style> +#target { + transform-box: view-box; + transform: translate(-50%, -50%); +} +</style> +<p>There should be a green 200x200 rectangle below, and no red.</p> +<svg width="400" height="200"> + <rect width="200" height="200" fill="red"/> + <svg viewBox="0 0 200 200" preserveAspectRatio="xMinYMin"> + <rect id="target" x="100" y="100" width="200" height="200" fill="green"/> + </svg> +</svg>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-transforms/transform-box/view-box-viewbox.html b/third_party/WebKit/LayoutTests/external/wpt/css/css-transforms/transform-box/view-box-viewbox.html new file mode 100644 index 0000000..cd040c1 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-transforms/transform-box/view-box-viewbox.html
@@ -0,0 +1,15 @@ +<!DOCTYPE html> +<title>transform-box: view-box, relative to viewport defined by viewBox</title> +<link rel="match" href="support/greensquare200x200.html"> +<link rel="help" href="https://drafts.csswg.org/css-transforms/#transform-box"> +<style> +#target { + transform-box: view-box; + transform: translate(-50%, -50%); +} +</style> +<p>There should be a green 200x200 rectangle below, and no red.</p> +<svg width="400" height="200" viewBox="0 0 200 200" preserveAspectRatio="xMinYMin"> + <rect width="200" height="200" fill="red"/> + <rect id="target" x="100" y="100" width="200" height="200" fill="green"/> +</svg>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-transforms/transform-box/view-box.html b/third_party/WebKit/LayoutTests/external/wpt/css/css-transforms/transform-box/view-box.html new file mode 100644 index 0000000..3345467 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-transforms/transform-box/view-box.html
@@ -0,0 +1,33 @@ +<!DOCTYPE html> +<title>transform-box: view-box</title> +<link rel="match" href="support/greensquare200x200.html"> +<link rel="help" href="https://drafts.csswg.org/css-transforms/#transform-box"> +<style> +svg { + background-color: red; +} +rect { + transform-box: view-box; +} +#target1 { + transform-origin: 25% 25%; + transform: scale(2); +} +#target2 { + transform: translate(50%, 0); +} +#target3 { + transform: translate(0, 50%); +} +#target4 { + transform-origin: 50% 50%; + transform: rotate(180deg); +} +</style> +<p>There should be a green 200x200 rectangle below, and no red.</p> +<svg width="200" height="200"> + <rect id="target1" x="25" y="25" width="50" height="50" fill="green"/> + <rect id="target2" width="100" height="100" fill="green"/> + <rect id="target3" width="100" height="100" fill="green"/> + <rect id="target4" width="100" height="100" fill="green"/> +</svg>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/cssom-view/overscrollBehavior-manual.html b/third_party/WebKit/LayoutTests/external/wpt/css/cssom-view/overscrollBehavior-manual.html index b37c4dc..78a5d7e 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/css/cssom-view/overscrollBehavior-manual.html +++ b/third_party/WebKit/LayoutTests/external/wpt/css/cssom-view/overscrollBehavior-manual.html
@@ -52,6 +52,7 @@ <script> +setup({explicit_timeout: true}); const container = document.getElementById('container'); const non_scrollable = document.getElementById('non_scrollable'); const root = document.getElementById('root');
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/cssom-view/scroll-behavior-smooth.html b/third_party/WebKit/LayoutTests/external/wpt/css/cssom-view/scroll-behavior-smooth.html new file mode 100644 index 0000000..f144a5f --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/css/cssom-view/scroll-behavior-smooth.html
@@ -0,0 +1,60 @@ +<!DOCTYPE html> +<title>cssom-view - scroll-behavior: smooth</title> +<link rel="author" title="Rune Lillesveen" href="mailto:futhark@chromium.org"> +<link rel="help" href="https://drafts.csswg.org/cssom-view/#smooth-scrolling"> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<style> + .filler { height: 10000px } + + .smooth { + scroll-behavior: smooth; + } + + #scrollable { + overflow: scroll; + width: 100px; + height: 100px; + } +</style> +<div id="testContainer"> + <div id="scrollable"> + <div class="filler"></div> + </div> + <div class="filler"></div> +</div> +<script> + test(() => { + scrollable.scrollTo(0, 5000); + assert_equals(scrollable.scrollTop, 5000, "Initially scrolls instantly"); + scrollable.scrollTo(0, 0); + scrollable.className = "smooth"; + scrollable.scrollTo(0, 5000); + assert_less_than(scrollable.scrollTop, 5000, "scroll-behavior:smooth should not scroll instantly"); + scrollable.className = ""; + scrollable.scrollTo(0, 0); + }, "scroll-behavior: smooth on DIV element"); + + test(() => { + window.scrollTo(0, 5000); + assert_equals(window.scrollY, 5000, "Initially scrolls instantly"); + window.scrollTo(0, 0); + document.documentElement.className = "smooth"; + assert_less_than(window.scrollY, 5000, "scroll-behavior:smooth should not scroll instantly"); + document.documentElement.className = ""; + window.scrollTo(0, 0); + }, "HTML element scroll-behavior should propagate to viewport"); + + test(() => { + window.scrollTo(0, 5000); + assert_equals(window.scrollY, 5000, "Initially scrolls instantly"); + window.scrollTo(0, 0); + document.body.className = "smooth"; + window.scrollTo(0, 5000); + assert_equals(window.scrollY, 5000, "scroll-behavior:smooth on BODY should scroll viewport instantly"); + document.body.className = ""; + window.scrollTo(0, 0); + }, "BODY element scroll-behavior should not propagate to viewport"); + + testContainer.style.display = "none"; +</script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/cssom/medialist-dynamic-001-ref.html b/third_party/WebKit/LayoutTests/external/wpt/css/cssom/medialist-dynamic-001-ref.html new file mode 100644 index 0000000..9715b5a --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/css/cssom/medialist-dynamic-001-ref.html
@@ -0,0 +1,5 @@ +<!doctype html> +<meta charset="utf-8"> +<title>CSS Test Reference</title> +<link rel="author" title="Emilio Cobos Álvarez" href="mailto:emilio@crisal.io"> +Should not be red.
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/cssom/medialist-dynamic-001.html b/third_party/WebKit/LayoutTests/external/wpt/css/cssom/medialist-dynamic-001.html new file mode 100644 index 0000000..ab9c134 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/css/cssom/medialist-dynamic-001.html
@@ -0,0 +1,12 @@ +<!doctype html> +<meta charset="utf-8"> +<title>CSS Test: Dynamic changes to the stylesheet media attributes via CSSOM get reflected</title> +<link rel="author" title="Emilio Cobos Álvarez" href="mailto:emilio@crisal.io"> +<link rel="match" href="medialist-dynamic-001-ref.html"> +<link rel="help" href="https://drafts.csswg.org/cssom/#dom-medialist-mediatext"> +<style media="all">* { color: red }</style> +Should not be red. +<script> + document.body.offsetTop; + document.styleSheets[0].media.mediaText = "not all"; +</script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/cssom/stylesheet-same-origin.sub-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/css/cssom/stylesheet-same-origin.sub-expected.txt index 81cc135..6f8127d 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/css/cssom/stylesheet-same-origin.sub-expected.txt +++ b/third_party/WebKit/LayoutTests/external/wpt/css/cssom/stylesheet-same-origin.sub-expected.txt
@@ -1,8 +1,6 @@ This is a testharness.js-based test. -FAIL Origin-clean check in cross-origin CSSOM Stylesheets assert_throws: Cross origin stylesheet.cssRules should throw SecurityError. function "function () { - crossorigin.cssRules; - }" did not throw +PASS Origin-clean check in cross-origin CSSOM Stylesheets PASS Origin-clean check in same-origin CSSOM Stylesheets -FAIL Origin-clean check in data:css CSSOM Stylesheets Cannot read property 'length' of null +FAIL Origin-clean check in data:css CSSOM Stylesheets Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules Harness: the test ran to completion.
diff --git a/third_party/WebKit/LayoutTests/external/wpt/custom-elements/reactions/with-exceptions.html b/third_party/WebKit/LayoutTests/external/wpt/custom-elements/reactions/with-exceptions.html new file mode 100644 index 0000000..82e0f59c --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/custom-elements/reactions/with-exceptions.html
@@ -0,0 +1,31 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>Custom Elements: CEReactions interaction with exceptions</title> +<link rel="author" title="Domenic Denicola" href="mailto:d@domenic.me"> +<meta name="help" content="https://html.spec.whatwg.org/multipage/#cereactions"> +<meta name="help" content="https://github.com/whatwg/html/pull/3235"> + +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="../resources/custom-elements-helpers.js"></script> + +<div id="log"></div> + +<script> +"use strict"; +// Basically from https://github.com/whatwg/html/issues/3217#issuecomment-343633273 +test_with_window((contentWindow, contentDocument) => { + let reactionRan = false; + contentWindow.customElements.define("custom-element", class extends contentWindow.HTMLElement { + disconnectedCallback() { + reactionRan = true; + } + }); + const text = contentDocument.createTextNode(""); + contentDocument.documentElement.appendChild(text); + const element = contentDocument.createElement("custom-element"); + contentDocument.documentElement.appendChild(element); + assert_throws("HierarchyRequestError", () => text.before("", contentDocument.documentElement)); + assert_true(reactionRan); +}, "Reaction must run even after the exception is thrown"); +</script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/fetch/api/redirect/redirect-method.js b/third_party/WebKit/LayoutTests/external/wpt/fetch/api/redirect/redirect-method.js index 13433a1..0a7f2df 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/fetch/api/redirect/redirect-method.js +++ b/third_party/WebKit/LayoutTests/external/wpt/fetch/api/redirect/redirect-method.js
@@ -3,14 +3,22 @@ importScripts("../resources/utils.js"); } -function redirectMethod(desc, redirectUrl, redirectLocation, redirectStatus, method, expectedMethod) { +// Creates a promise_test that fetches a URL that returns a redirect response. +// +// |opts| has additional options: +// |opts.body|: the request body as a string or blob (default is empty body) +// |opts.expectedBodyAsString|: the expected response body as a string. The +// server is expected to echo the request body. The default is the empty string +// if the request after redirection isn't POST; otherwise it's |opts.body|. +function redirectMethod(desc, redirectUrl, redirectLocation, redirectStatus, method, expectedMethod, opts) { var url = redirectUrl; var urlParameters = "?redirect_status=" + redirectStatus; urlParameters += "&location=" + encodeURIComponent(redirectLocation); var requestInit = {"method": method, "redirect": "follow"}; - if (method != "GET" && method != "HEAD") - requestInit.body = "this is my body"; + opts = opts || {}; + if (opts.body) + requestInit.body = opts.body; promise_test(function(test) { return fetch(url + urlParameters, requestInit).then(function(resp) { @@ -19,7 +27,10 @@ assert_equals(resp.headers.get("x-request-method"), expectedMethod, "Request method after redirection is " + expectedMethod); assert_true(resp.redirected); return resp.text().then(function(text) { - assert_equals(text, expectedMethod == "POST" ? requestInit.body : ""); + let expectedBody = ""; + if (expectedMethod == "POST") + expectedBody = opts.expectedBodyAsString || requestInit.body; + assert_equals(text, expectedBody, "request body"); }); }); }, desc); @@ -36,20 +47,25 @@ var redirUrl = RESOURCES_DIR + "redirect.py"; var locationUrl = "method.py"; +const stringBody = "this is my body"; +const blobBody = new Blob(["it's me the blob!", " ", "and more blob!"]); +const blobBodyAsString = "it's me the blob! and more blob!"; + redirectMethod("Redirect 301 with GET", redirUrl, locationUrl, 301, "GET", "GET"); -redirectMethod("Redirect 301 with POST", redirUrl, locationUrl, 301, "POST", "GET"); +redirectMethod("Redirect 301 with POST", redirUrl, locationUrl, 301, "POST", "GET", { body: stringBody }); redirectMethod("Redirect 301 with HEAD", redirUrl, locationUrl, 301, "HEAD", "HEAD"); redirectMethod("Redirect 302 with GET", redirUrl, locationUrl, 302, "GET", "GET"); -redirectMethod("Redirect 302 with POST", redirUrl, locationUrl, 302, "POST", "GET"); +redirectMethod("Redirect 302 with POST", redirUrl, locationUrl, 302, "POST", "GET", { body: stringBody }); redirectMethod("Redirect 302 with HEAD", redirUrl, locationUrl, 302, "HEAD", "HEAD"); redirectMethod("Redirect 303 with GET", redirUrl, locationUrl, 303, "GET", "GET"); -redirectMethod("Redirect 303 with POST", redirUrl, locationUrl, 303, "POST", "GET"); +redirectMethod("Redirect 303 with POST", redirUrl, locationUrl, 303, "POST", "GET", { body: stringBody }); redirectMethod("Redirect 303 with HEAD", redirUrl, locationUrl, 303, "HEAD", "HEAD"); redirectMethod("Redirect 307 with GET", redirUrl, locationUrl, 307, "GET", "GET"); -redirectMethod("Redirect 307 with POST", redirUrl, locationUrl, 307, "POST", "POST"); +redirectMethod("Redirect 307 with POST (string body)", redirUrl, locationUrl, 307, "POST", "POST", { body: stringBody }); +redirectMethod("Redirect 307 with POST (blob body)", redirUrl, locationUrl, 307, "POST", "POST", { body: blobBody, expectedBodyAsString: blobBodyAsString }); redirectMethod("Redirect 307 with HEAD", redirUrl, locationUrl, 307, "HEAD", "HEAD"); done();
diff --git a/third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-progress-element/progress-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-progress-element/progress-expected.txt deleted file mode 100644 index f5c5684..0000000 --- a/third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-progress-element/progress-expected.txt +++ /dev/null
@@ -1,14 +0,0 @@ -This is a testharness.js-based test. -PASS Indeterminate progress bar should have position -1 -PASS Revoming the value attribute makes an intermediate progress bar, which should have position -1 -PASS Determinate progress bar should have fractional position -PASS Indeterminate progress bar should have value 0 -FAIL Value must equal max if the parsed value is larger than max assert_array_equals: value is 1, expected array -PASS Max must be 1 by default -FAIL Max must be 1 by default, even if value is specified assert_array_equals: value is 1, expected array -PASS Max must be 1 if max value is invalid -PASS Max must be 1 if the parsed max value is less than or equal to zero -PASS Value must be 0 if value is invalid -PASS Value must be 0 if the parsed value is less than or equal to zero -Harness: the test ran to completion. -
diff --git a/third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-progress-element/progress.html b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-progress-element/progress.html index 0c176d8..00d63c37 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-progress-element/progress.html +++ b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-progress-element/progress.html
@@ -42,7 +42,7 @@ }, "Indeterminate progress bar should have value 0"); test(function() { - assert_array_equals(largerthanmax.value, 1); + assert_equals(largerthanmax.value, 1); }, "Value must equal max if the parsed value is larger than max"); test(function() { @@ -50,7 +50,7 @@ }, "Max must be 1 by default"); test(function() { - assert_array_equals(largerthanmax.max, 1); + assert_equals(largerthanmax.max, 1); }, "Max must be 1 by default, even if value is specified"); test(function() {
diff --git a/third_party/WebKit/LayoutTests/external/wpt/lint.whitelist b/third_party/WebKit/LayoutTests/external/wpt/lint.whitelist index dcbc2a5..be63695 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/lint.whitelist +++ b/third_party/WebKit/LayoutTests/external/wpt/lint.whitelist
@@ -18,7 +18,6 @@ INDENT TABS: shadow-dom/* INDENT TABS: svg/import/* INDENT TABS: tools/* -INDENT TABS: touch-events/* INDENT TABS: web-animations/* INDENT TABS: webaudio/* INDENT TABS: webvtt/* @@ -70,17 +69,17 @@ ## Documentation ## -W3C-TEST.ORG:README.md -W3C-TEST.ORG:*/README.md -W3C-TEST.ORG:docs/* +W3C-TEST.ORG: README.md +W3C-TEST.ORG: */README.md +W3C-TEST.ORG: docs/* SET TIMEOUT: docs/* ## Helper scripts ## -W3C-TEST.ORG:tools/* -PRINT STATEMENT:tools/* -W3C-TEST.ORG:*/tools/* -PRINT STATEMENT:*/tools/* +W3C-TEST.ORG: tools/* +PRINT STATEMENT: tools/* +W3C-TEST.ORG: */tools/* +PRINT STATEMENT: */tools/* ## Deliberate copies of Ahem ## # The allowed copy @@ -92,42 +91,45 @@ # https://github.com/w3c/web-platform-tests/issues/7437 AHEM COPY: css/vendor-imports/mozilla/mozilla-central-reftests/*/Ahem.ttf -### Test exclusions ## +## Test exclusions ## -CR AT EOL:WebIDL/valid/idl/documentation-dos.widl -CR AT EOL:cors/resources/cors-headers.asis -CR AT EOL:html/semantics/embedded-content/the-canvas-element/size.attributes.parse.whitespace.html -INDENT TABS:html/semantics/embedded-content/the-canvas-element/size.attributes.parse.whitespace.html -CR AT EOL:webvtt/parsing/file-parsing/tests/support/newlines.vtt -PARSE-FAILED:dom/nodes/Document-createElement-namespace-tests/empty.svg -PARSE-FAILED:dom/nodes/Document-createElement-namespace-tests/empty.xhtml -PARSE-FAILED:dom/nodes/Document-createElement-namespace-tests/minimal_html.svg -PARSE-FAILED:dom/nodes/Document-createElement-namespace-tests/minimal_html.xhtml +# Intentional use of CRLF +CR AT EOL: WebIDL/valid/idl/documentation-dos.widl +CR AT EOL: cors/resources/cors-headers.asis +CR AT EOL: html/semantics/embedded-content/the-canvas-element/size.attributes.parse.whitespace.html +CR AT EOL: webvtt/parsing/file-parsing/tests/support/newlines.vtt + +# Intentional use of tabs +INDENT TABS: html/semantics/embedded-content/the-canvas-element/size.attributes.parse.whitespace.html # Test generation files containing print statements -PRINT STATEMENT:dom/nodes/Document-createElement-namespace-tests/generate.py -PRINT STATEMENT:encrypted-media/polyfill/make-polyfill-tests.py +PRINT STATEMENT: dom/nodes/Document-createElement-namespace-tests/generate.py +PRINT STATEMENT: encrypted-media/polyfill/make-polyfill-tests.py # semi-legitimate use of console.* -CONSOLE:console/* -CONSOLE:streams/resources/test-utils.js -CONSOLE:service-workers/service-worker/resources/navigation-redirect-other-origin.html -CONSOLE:service-workers/service-worker/navigation-redirect.https.html -CONSOLE:service-workers/service-worker/resources/clients-get-other-origin.html +CONSOLE: console/* +CONSOLE: streams/resources/test-utils.js +CONSOLE: service-workers/service-worker/resources/navigation-redirect-other-origin.html +CONSOLE: service-workers/service-worker/navigation-redirect.https.html +CONSOLE: service-workers/service-worker/resources/clients-get-other-origin.html # use of console in a public library - annotation-model ensures # it is not actually used -CONSOLE:annotation-model/scripts/ajv.min.js -CONSOLE:annotation-model/scripts/showdown.min.js +CONSOLE: annotation-model/scripts/ajv.min.js +CONSOLE: annotation-model/scripts/showdown.min.js CR AT EOL: annotation-model/scripts/showdown.min.js # Lint doesn't know about sub.svg I guess -PARSE-FAILED:content-security-policy/svg/including.sub.svg +PARSE-FAILED: content-security-policy/svg/including.sub.svg -#Helper files that aren't valid XML -PARSE-FAILED:dom/nodes/Document-createElement-namespace-tests/empty.xml -PARSE-FAILED:dom/nodes/Document-createElement-namespace-tests/minimal_html.xml -PARSE-FAILED:acid/acid3/empty.xml +# Helper files that aren't valid XML +PARSE-FAILED: acid/acid3/empty.xml +PARSE-FAILED: dom/nodes/Document-createElement-namespace-tests/empty.svg +PARSE-FAILED: dom/nodes/Document-createElement-namespace-tests/empty.xhtml +PARSE-FAILED: dom/nodes/Document-createElement-namespace-tests/empty.xml +PARSE-FAILED: dom/nodes/Document-createElement-namespace-tests/minimal_html.svg +PARSE-FAILED: dom/nodes/Document-createElement-namespace-tests/minimal_html.xhtml +PARSE-FAILED: dom/nodes/Document-createElement-namespace-tests/minimal_html.xml # setTimeout usage (should probably mostly be fixed) SET TIMEOUT: *-manual.* @@ -303,16 +305,16 @@ SET TIMEOUT: acid/acid3/test.html # Travis -W3C-TEST.ORG:.travis.yml +W3C-TEST.ORG: .travis.yml # Git submodules are not currently scanned -*:tools/* -*:resources/* -*:css/tools/apiclient/* -*:css/tools/w3ctestlib/* +*: tools/* +*: resources/* +*: css/tools/apiclient/* +*: css/tools/w3ctestlib/* # Build system virtualenv -*:css/tools/_virtualenv/* +*: css/tools/_virtualenv/* ## Third party data files @@ -923,10 +925,10 @@ # TODO https://github.com/w3c/web-platform-tests/issues/5770 MISSING-LINK: css/geometry/*.worker.js -WEBIDL2.JS:.gitmodules +WEBIDL2.JS: .gitmodules # Manual test that uses console.logs for feedback -CONSOLE:payment-request/payment-request-response-id.html +CONSOLE: payment-request/payment-request-response-id.html # Tests that use WebKit/Blink testing APIs LAYOUTTESTS APIS: css/css-regions/interactivity/*
diff --git a/third_party/WebKit/LayoutTests/external/wpt/paint-timing/child-painting-first-image.html b/third_party/WebKit/LayoutTests/external/wpt/paint-timing/child-painting-first-image.html index 99f761f..4671604 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/paint-timing/child-painting-first-image.html +++ b/third_party/WebKit/LayoutTests/external/wpt/paint-timing/child-painting-first-image.html
@@ -7,9 +7,9 @@ async_test(function (t) { window.addEventListener('message', t.step_func(e => { assert_equals(e.data, '2 paint first-paint paint first-contentful-paint'); - const bufferedEntries = performance.getEntriesByType('paint'); // When only child frame paints, expect only first-paint. t.step_timeout( function() { + const bufferedEntries = performance.getEntriesByType('paint'); assert_equals(bufferedEntries.length, 1); assert_equals(bufferedEntries[0].entryType, 'paint'); assert_equals(bufferedEntries[0].name, 'first-paint');
diff --git a/third_party/WebKit/LayoutTests/external/wpt/paint-timing/sibling-painting-first-image.html b/third_party/WebKit/LayoutTests/external/wpt/paint-timing/sibling-painting-first-image.html new file mode 100644 index 0000000..d4197e8 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/paint-timing/sibling-painting-first-image.html
@@ -0,0 +1,34 @@ +<!DOCTYPE html> +<body> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> + <!-- This iframe will have a sibling that paints, we want to ensure it does not detect that paint. --> +<iframe id="listening-iframe" src="resources/subframe-sending-paint.html"></iframe> +<script> +async_test(function (t) { + let paintingIframeHasDispatchedEntries = false; + window.addEventListener('message', t.step_func(e => { + if (!paintingIframeHasDispatchedEntries) { + // Check paint-timing entries from the painting iframe. + assert_equals(e.data, '2 paint first-paint paint first-contentful-paint'); + paintingIframeHasDispatchedEntries = true; + // Ask the listening iframe to send its paint-timing entries. + document.getElementById('listening-iframe'). + contentWindow.postMessage('', '*'); + return; + } + // Check the paint-timing entries from the listening iframe. + assert_equals(e.data, '0'); + // Check that current frame receives first-paint but not first-contentful-paint. + const bufferedEntries = performance.getEntriesByType('paint'); + assert_equals(bufferedEntries.length, 1); + assert_equals(bufferedEntries[0].entryType, 'paint'); + assert_equals(bufferedEntries[0].name, 'first-paint'); + t.done(); + })); +}, 'Frame ignores paint-timing events fired from sibling frame.'); +</script> +<!-- This iframe is where all of the painting occurs. --> +<iframe id="painting-iframe" src="resources/subframe-painting.html"></iframe> +</body> +</html>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/payment-request/payment-request-constructor.https.html b/third_party/WebKit/LayoutTests/external/wpt/payment-request/payment-request-constructor.https.html index e4e1292f..b5997a0 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/payment-request/payment-request-constructor.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/payment-request/payment-request-constructor.https.html
@@ -15,17 +15,41 @@ currency: "USD", value: "1.0", }); +const defaultNumberAmount = Object.freeze({ + currency: "USD", + value: 1.0, +}); const defaultTotal = Object.freeze({ label: "Default Total", amount: defaultAmount, }); +const defaultNumberTotal = Object.freeze({ + label: "Default Number Total", + amount: defaultNumberAmount, +}); const defaultDetails = Object.freeze({ total: defaultTotal, + displayItems: [ + { + label: "Default Display Item", + amount: defaultAmount, + }, + ], +}); +const defaultNumberDetails = Object.freeze({ + total: defaultNumberTotal, + displayItems: [ + { + label: "Default Display Item", + amount: defaultNumberAmount, + }, + ], }); // Avoid false positives, this should always pass function smokeTest() { new PaymentRequest(defaultMethods, defaultDetails); + new PaymentRequest(defaultMethods, defaultNumberDetails); } test(() => { smokeTest(); @@ -177,6 +201,7 @@ "-1.0", "-1.00", "-1000.000", + -10, ]); test(() => { smokeTest();
diff --git a/third_party/WebKit/LayoutTests/external/wpt/pointerevents/extension/pointerevent_coalesced_events_attributes-manual-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/pointerevents/extension/pointerevent_coalesced_events_attributes-manual-expected.txt index 3f22888..15bf520 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/pointerevents/extension/pointerevent_coalesced_events_attributes-manual-expected.txt +++ b/third_party/WebKit/LayoutTests/external/wpt/pointerevents/extension/pointerevent_coalesced_events_attributes-manual-expected.txt
@@ -5,7 +5,7 @@ PASS touch pointerover should not have any coalesced events PASS touch pointerenter should not have any coalesced events PASS touch pointerdown should not have any coalesced events -FAIL touch pointermove should have >2 coalesced events as main thread is busy.assert_greater_than: pointermove should have at least 2 coalesced events. expected a number greater than 1 but got 0 +FAIL touch pointermove should have >2 coalesced events as main thread is busy.assert_greater_than: pointermove should have at least 2 coalesced events. expected a number greater than 1 but got 1 PASS touch pointermove coalesced events should all be marked as trusted. PASS touch time stamps of coalesced events must be ascending. PASS touch pointermove coalesced events should all bubbles and cancelable as false.
diff --git a/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animatable/animate-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animatable/animate-expected.txt index 36647164..bc2ea5a 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animatable/animate-expected.txt +++ b/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animatable/animate-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -Found 121 tests; 58 PASS, 63 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 121 tests; 57 PASS, 64 FAIL, 0 TIMEOUT, 0 NOTRUN. PASS Element.animate() creates an Animation object PASS Element.animate() creates an Animation object in the relevant realm of the target element PASS Element.animate() creates an Animation object with a KeyframeEffect @@ -124,7 +124,7 @@ PASS Element.animate() correctly sets the id attribute PASS Element.animate() correctly sets the Animation's timeline PASS Element.animate() correctly sets the Animation's timeline when triggered on an element in a different document -PASS Element.animate() calls play on the Animation +FAIL Element.animate() calls play on the Animation assert_equals: expected "running" but got "pending" FAIL CSSPseudoElement.animate() creates an Animation object Cannot read property 'parentElement' of undefined FAIL CSSPseudoElement.animate() creates an Animation object targeting to the correct CSSPseudoElement object Cannot read property 'parentElement' of undefined Harness: the test ran to completion.
diff --git a/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animatable/animate-no-browsing-context.html b/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animatable/animate-no-browsing-context.html index e4fd70a4..c72b5dee 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animatable/animate-no-browsing-context.html +++ b/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animatable/animate-no-browsing-context.html
@@ -76,16 +76,15 @@ const div = xhrdoc.getElementById('test'); anim = div.animate(null); anim.timeline = document.timeline; - assert_equals(anim.playState, 'pending', - 'The animation should be initially pending'); + assert_true(anim.pending, 'The animation should be initially pending'); return waitForAnimationFrames(2); }).then(() => { // Because the element is in a document without a browsing context, it will // not be rendered and hence the user agent will never deem it ready to // animate. - assert_equals(anim.playState, 'pending', - 'The animation should still be pending after replacing' - + ' the document timeline'); + assert_true(anim.pending, + 'The animation should still be pending after replacing' + + ' the document timeline'); }); }, 'Replacing the timeline of an animation targetting an element in a' + ' document without a browsing context leaves it in the pending state');
diff --git a/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animatable/animate.html b/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animatable/animate.html index 5464711..49842ff 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animatable/animate.html +++ b/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animatable/animate.html
@@ -170,7 +170,7 @@ test(t => { const div = createDiv(t); const anim = div.animate({ opacity: [ 0, 1 ] }, 2000); - assert_equals(anim.playState, 'pending'); + assert_equals(anim.playState, 'running'); }, 'Element.animate() calls play on the Animation'); // Tests on CSSPseudoElement
diff --git a/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animation/idlharness-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animation/idlharness-expected.txt index 641cb4d..1213da7 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animation/idlharness-expected.txt +++ b/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animation/idlharness-expected.txt
@@ -11,6 +11,7 @@ PASS Animation interface: attribute currentTime PASS Animation interface: attribute playbackRate PASS Animation interface: attribute playState +FAIL Animation interface: attribute pending assert_true: The prototype object must have a property "pending" expected true got false PASS Animation interface: attribute ready PASS Animation interface: attribute finished PASS Animation interface: attribute onfinish @@ -29,6 +30,7 @@ PASS Animation interface: new Animation() must inherit property "currentTime" with the proper type PASS Animation interface: new Animation() must inherit property "playbackRate" with the proper type PASS Animation interface: new Animation() must inherit property "playState" with the proper type +FAIL Animation interface: new Animation() must inherit property "pending" with the proper type assert_inherits: property "pending" not found in prototype chain PASS Animation interface: new Animation() must inherit property "ready" with the proper type PASS Animation interface: new Animation() must inherit property "finished" with the proper type PASS Animation interface: new Animation() must inherit property "onfinish" with the proper type
diff --git a/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animation/idlharness.html b/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animation/idlharness.html index 74813e1..ef630591 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animation/idlharness.html +++ b/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animation/idlharness.html
@@ -20,6 +20,7 @@ attribute double? currentTime; attribute double playbackRate; readonly attribute AnimationPlayState playState; + readonly attribute boolean pending; readonly attribute Promise<Animation> ready; readonly attribute Promise<Animation> finished; attribute EventHandler onfinish;
diff --git a/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animation/pause-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animation/pause-expected.txt new file mode 100644 index 0000000..7333ed6 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animation/pause-expected.txt
@@ -0,0 +1,8 @@ +This is a testharness.js-based test. +PASS pause() a running animation +FAIL pause() from idle assert_equals: in paused play state expected "paused" but got "pending" +PASS pause() from idle with a negative playbackRate +PASS pause() from idle with a negative playbackRate and endless effect +PASS pause() on a finished animation +Harness: the test ran to completion. +
diff --git a/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animation/pause.html b/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animation/pause.html index 3be8bc3..71e30b0 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animation/pause.html +++ b/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animation/pause.html
@@ -39,12 +39,12 @@ assert_equals(animation.currentTime, 0, 'currentTime is set to 0'); assert_equals(animation.startTime, null, 'startTime is not set'); - assert_equals(animation.playState, 'pending', 'initially pause-pending'); + assert_equals(animation.playState, 'paused', 'in paused play state'); + assert_true(animation.pending, 'initially pause-pending'); // Check it still resolves as expected return animation.ready.then(() => { - assert_equals(animation.playState, 'paused', - 'resolves to paused state asynchronously'); + assert_false(animation.pending, 'no longer pending'); assert_equals(animation.currentTime, 0, 'keeps the initially set currentTime'); });
diff --git a/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animation/pending-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animation/pending-expected.txt new file mode 100644 index 0000000..fad7127 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animation/pending-expected.txt
@@ -0,0 +1,5 @@ +This is a testharness.js-based test. +FAIL reports true -> false when initially played assert_true: expected true got undefined +FAIL reports true -> false when paused assert_true: expected true got undefined +Harness: the test ran to completion. +
diff --git a/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animation/pending.html b/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animation/pending.html new file mode 100644 index 0000000..aa53eef --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animation/pending.html
@@ -0,0 +1,35 @@ +<!DOCTYPE html> +<meta charset=utf-8> +<title>Animation.pending</title> +<link rel="help" href="https://w3c.github.io/web-animations/#dom-animation-pending"> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="../../testcommon.js"></script> +<body> +<div id="log"></div> +<script> +'use strict'; + +promise_test(t => { + const div = createDiv(t); + const animation = div.animate({}, 100 * MS_PER_SEC); + + assert_true(animation.pending); + return animation.ready.then(() => { + assert_false(animation.pending); + }); +}, 'reports true -> false when initially played'); + +promise_test(t => { + const div = createDiv(t); + const animation = div.animate({}, 100 * MS_PER_SEC); + animation.pause(); + + assert_true(animation.pending); + return animation.ready.then(() => { + assert_false(animation.pending); + }); +}, 'reports true -> false when paused'); + +</script> +</body>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animation/playState.html b/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animation/playState.html deleted file mode 100644 index cf6ce66..0000000 --- a/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animation/playState.html +++ /dev/null
@@ -1,53 +0,0 @@ -<!DOCTYPE html> -<meta charset=utf-8> -<title>Animation.playState</title> -<link rel="help" href="https://w3c.github.io/web-animations/#dom-animation-playstate"> -<script src="/resources/testharness.js"></script> -<script src="/resources/testharnessreport.js"></script> -<script src="../../testcommon.js"></script> -<body> -<div id="log"></div> -<script> -'use strict'; - -promise_test(t => { - const div = createDiv(t); - const animation = div.animate({}, 100 * MS_PER_SEC); - - assert_equals(animation.playState, 'pending'); - return animation.ready.then(() => { - assert_equals(animation.playState, 'running'); - }); -}, 'Animation.playState reports \'pending\'->\'running\' when initially ' + - 'played'); - -promise_test(t => { - const div = createDiv(t); - const animation = div.animate({}, 100 * MS_PER_SEC); - animation.pause(); - - assert_equals(animation.playState, 'pending'); - return animation.ready.then(() => { - assert_equals(animation.playState, 'paused'); - }); -}, 'Animation.playState reports \'pending\'->\'paused\' when pausing'); - -test(t => { - const div = createDiv(t); - const animation = div.animate({}, 100 * MS_PER_SEC); - animation.cancel(); - assert_equals(animation.playState, 'idle'); -}, 'Animation.playState is \'idle\' when canceled.'); - -test(t => { - const div = createDiv(t); - const animation = div.animate({}, 100 * MS_PER_SEC); - animation.cancel(); - animation.currentTime = 50 * MS_PER_SEC; - assert_equals(animation.playState, 'paused', - 'After seeking an idle animation, it is effectively paused'); -}, 'Animation.playState is \'paused\' after cancelling an animation, ' + - 'seeking it makes it paused'); - -</script> -</body>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/pausing-an-animation-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/pausing-an-animation-expected.txt new file mode 100644 index 0000000..fbf1ee2 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/pausing-an-animation-expected.txt
@@ -0,0 +1,4 @@ +This is a testharness.js-based test. +FAIL A pending ready promise should be resolved and not replaced when the animation is paused assert_false: No longer pause-pending expected false got undefined +Harness: the test ran to completion. +
diff --git a/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/pausing-an-animation.html b/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/pausing-an-animation.html index bb75dcc..b1614c1 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/pausing-an-animation.html +++ b/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/pausing-an-animation.html
@@ -18,7 +18,7 @@ return promise.then(p => { assert_equals(p, animation); assert_equals(animation.ready, promise); - assert_equals(animation.playState, 'paused'); + assert_false(animation.pending, 'No longer pause-pending'); }); }, 'A pending ready promise should be resolved and not replaced when the' + ' animation is paused');
diff --git a/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/play-states-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/play-states-expected.txt new file mode 100644 index 0000000..cfff459 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/play-states-expected.txt
@@ -0,0 +1,15 @@ +This is a testharness.js-based test. +PASS reports 'idle' for an animation with an unresolved current time and no pending tasks +FAIL reports 'paused' for an animation with a pending pause task assert_equals: expected "paused" but got "pending" +PASS reports 'paused' for an animation with a resolved current time and unresolved start time +PASS reports 'running' for an animation with a resolved start time and current time +PASS reports 'finished' when playback rate > 0 and current time = target effect end +PASS reports 'running' when playback rate = 0 and current time = target effect end +FAIL reports 'running' when playback rate < 0 and current time = target effect end assert_equals: expected "running" but got "pending" +PASS reports 'running' when playback rate > 0 and current time = 0 +PASS reports 'running' when playback rate = 0 and current time = 0 +FAIL reports 'finished' when playback rate < 0 and current time = 0 assert_equals: expected "finished" but got "pending" +FAIL reports 'finished' when playback rate > 0 and current time = target effect end and there is a pending play task assert_equals: expected "finished" but got "pending" +FAIL reports 'running' when playback rate > 0 and current time < target effect end and there is a pending play task assert_equals: expected "running" but got "pending" +Harness: the test ran to completion. +
diff --git a/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/play-states.html b/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/play-states.html new file mode 100644 index 0000000..22d8ff3 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/play-states.html
@@ -0,0 +1,157 @@ +<!DOCTYPE html> +<meta charset=utf-8> +<title>Play states</title> +<link rel="help" href="https://w3c.github.io/web-animations/#play-state"> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="../../testcommon.js"></script> +<body> +<div id="log"></div> +<script> +'use strict'; + +test(t => { + const animation = new Animation( + new KeyframeEffect(null, {}, 100 * MS_PER_SEC) + ); + assert_equals(animation.currentTime, null, + 'Current time should be initially unresolved'); + + assert_equals(animation.playState, 'idle'); +}, 'reports \'idle\' for an animation with an unresolved current time' + + ' and no pending tasks') + +test(t => { + const div = createDiv(t); + const animation = div.animate({}, 100 * MS_PER_SEC); + + animation.pause(); + + assert_equals(animation.playState, 'paused'); +}, 'reports \'paused\' for an animation with a pending pause task'); + +test(t => { + const animation = new Animation( + new KeyframeEffect(null, {}, 100 * MS_PER_SEC) + ); + + animation.currentTime = 0; + assert_equals(animation.startTime, null, + 'Start time should still be unresolved after setting current' + + ' time'); + + assert_equals(animation.playState, 'paused'); +}, 'reports \'paused\' for an animation with a resolved current time and' + + ' unresolved start time') + +test(t => { + const animation = new Animation( + new KeyframeEffect(null, {}, 100 * MS_PER_SEC) + ); + + animation.startTime = document.timeline.currentTime; + assert_not_equals(animation.currentTime, null, + 'Current time should be resolved after setting start time'); + + assert_equals(animation.playState, 'running'); +}, 'reports \'running\' for an animation with a resolved start time and' + + ' current time'); + +test(t => { + const animation = new Animation( + new KeyframeEffect(null, {}, 100 * MS_PER_SEC) + ); + animation.startTime = document.timeline.currentTime; + + animation.currentTime = 100 * MS_PER_SEC; + + assert_equals(animation.playState, 'finished'); +}, 'reports \'finished\' when playback rate > 0 and' + + ' current time = target effect end'); + +test(t => { + const animation = new Animation( + new KeyframeEffect(null, {}, 100 * MS_PER_SEC) + ); + animation.startTime = document.timeline.currentTime; + + animation.playbackRate = 0; + animation.currentTime = 100 * MS_PER_SEC; + + assert_equals(animation.playState, 'running'); +}, 'reports \'running\' when playback rate = 0 and' + + ' current time = target effect end'); + +test(t => { + const animation = new Animation( + new KeyframeEffect(null, {}, 100 * MS_PER_SEC) + ); + animation.startTime = document.timeline.currentTime; + + animation.playbackRate = -1; + animation.currentTime = 100 * MS_PER_SEC; + + assert_equals(animation.playState, 'running'); +}, 'reports \'running\' when playback rate < 0 and' + + ' current time = target effect end'); + +test(t => { + const animation = new Animation( + new KeyframeEffect(null, {}, 100 * MS_PER_SEC) + ); + animation.startTime = document.timeline.currentTime; + + animation.currentTime = 0; + + assert_equals(animation.playState, 'running'); +}, 'reports \'running\' when playback rate > 0 and' + + ' current time = 0'); + +test(t => { + const animation = new Animation( + new KeyframeEffect(null, {}, 100 * MS_PER_SEC) + ); + animation.startTime = document.timeline.currentTime; + + animation.playbackRate = 0; + animation.currentTime = 0; + + assert_equals(animation.playState, 'running'); +}, 'reports \'running\' when playback rate = 0 and' + + ' current time = 0'); + +test(t => { + const animation = new Animation( + new KeyframeEffect(null, {}, 100 * MS_PER_SEC) + ); + animation.startTime = document.timeline.currentTime; + + animation.playbackRate = -1; + animation.currentTime = 0; + + assert_equals(animation.playState, 'finished'); +}, 'reports \'finished\' when playback rate < 0 and' + + ' current time = 0'); + +test(t => { + const div = createDiv(t); + const animation = div.animate({}, 0); + assert_equals(animation.startTime, null, + 'Sanity check: start time should be unresolved'); + + assert_equals(animation.playState, 'finished'); +}, 'reports \'finished\' when playback rate > 0 and' + + ' current time = target effect end and there is a pending play task'); + +test(t => { + const div = createDiv(t); + const animation = div.animate({}, 100 * MS_PER_SEC); + assert_equals(animation.startTime, null, + 'Sanity check: start time should be unresolved'); + + assert_equals(animation.playState, 'running'); +}, 'reports \'running\' when playback rate > 0 and' + + ' current time < target effect end and there is a pending play task'); + +</script> +</body>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/reversing-an-animation-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/reversing-an-animation-expected.txt index 59488bb..35672cb 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/reversing-an-animation-expected.txt +++ b/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/reversing-an-animation-expected.txt
@@ -2,7 +2,7 @@ PASS Reversing an animation inverts the playback rate PASS Reversing an animation plays a pausing animation PASS Reversing an animation maintains the same current time -PASS Reversing an animation does not cause it to leave the pending state +FAIL Reversing an animation does not cause it to leave the pending state assert_true: The animation is pending before we call reverse expected true got undefined PASS Reversing an animation does not cause it to resolve the ready promise PASS Reversing an animation when playbackRate > 0 and currentTime > effect end should make it play from the end PASS Reversing an animation when playbackRate > 0 and currentTime < 0 should make it play from the end
diff --git a/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/reversing-an-animation.html b/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/reversing-an-animation.html index 5c96a6f..bdae2ad 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/reversing-an-animation.html +++ b/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/reversing-an-animation.html
@@ -60,13 +60,13 @@ const div = createDiv(t); const animation = div.animate({}, { duration: 200 * MS_PER_SEC, delay: -100 * MS_PER_SEC }); - assert_equals(animation.playState, 'pending', - 'The playState is pending before we call reverse'); + assert_true(animation.pending, + 'The animation is pending before we call reverse'); animation.reverse(); - assert_equals(animation.playState, 'pending', - 'The playState is still pending after calling reverse'); + assert_true(animation.pending, + 'The animation is still pending after calling reverse'); }, 'Reversing an animation does not cause it to leave the pending state'); promise_test(t => {
diff --git a/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/set-the-animation-start-time.html b/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/set-the-animation-start-time.html index 48071c0..070d5bc 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/set-the-animation-start-time.html +++ b/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/set-the-animation-start-time.html
@@ -123,8 +123,8 @@ animation.play(); // Sanity check - assert_equals(animation.playState, 'pending', - 'Animation is in play-pending state'); + assert_true(animation.pending && animation.playState === 'running', + 'Animation is in play-pending state'); // Setting the start time should resolve the 'ready' promise, i.e. // it should schedule a microtask to run the promise callbacks. @@ -153,8 +153,8 @@ animation.pause(); // Sanity check - assert_equals(animation.playState, 'pending', - 'Animation is in pause-pending state'); + assert_true(animation.pending && animation.playState === 'paused', + 'Animation is in pause-pending state'); // Setting the start time should resolve the 'ready' promise although // the resolution callbacks when be run in a separate microtask.
diff --git a/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/set-the-target-effect-of-an-animation-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/set-the-target-effect-of-an-animation-expected.txt index f8a620f..502e2a2 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/set-the-target-effect-of-an-animation-expected.txt +++ b/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/set-the-target-effect-of-an-animation-expected.txt
@@ -1,8 +1,7 @@ This is a testharness.js-based test. -Harness Error. harness_status.status = 1 , harness_status.message = assert_equals: ready promise is rejected with AbortError expected "AbortError" but got "Error" -FAIL If new effect is null and old effect is not null, we reset the pending tasks and ready promise is rejected assert_equals: expected "paused" but got "pending" -PASS If animation has a pending pause task, reschedule that task to run as soon as animation is ready. -PASS If animation has a pending play task, reschedule that task to run as soon as animation is ready to play new effect. +FAIL If new effect is null and old effect is not null, we reset the pending tasks and ready promise is rejected assert_true: expected true got undefined +FAIL If animation has a pending pause task, reschedule that task to run as soon as animation is ready. assert_true: expected true got undefined +FAIL If animation has a pending play task, reschedule that task to run as soon as animation is ready to play new effect. assert_true: expected true got undefined FAIL When setting the effect of an animation to the effect of an existing animation, the existing animation's target effect should be set to null. assert_equals: expected "finished" but got "idle" PASS After setting the target effect of animation to the target effect of an existing animation, the target effect's timing is updated to reflect the current time of the new animation. Harness: the test ran to completion.
diff --git a/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/set-the-target-effect-of-an-animation.html b/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/set-the-target-effect-of-an-animation.html index 8f835cc..c90dc82 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/set-the-target-effect-of-an-animation.html +++ b/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/set-the-target-effect-of-an-animation.html
@@ -13,7 +13,7 @@ promise_test(t => { const anim = createDiv(t).animate({ marginLeft: [ '0px', '100px' ] }, 100 * MS_PER_SEC); - assert_equals(anim.playState, 'pending'); + assert_true(anim.pending); const retPromise = anim.ready.then(() => { assert_unreached('ready promise is fulfilled'); @@ -23,7 +23,9 @@ }); anim.effect = null; + // This is a bit odd, see: https://github.com/w3c/web-animations/issues/207 assert_equals(anim.playState, 'paused'); + assert_false(anim.pending); return retPromise; }, 'If new effect is null and old effect is not null, we reset the pending ' + @@ -32,14 +34,15 @@ promise_test(t => { const anim = new Animation(); anim.pause(); - assert_equals(anim.playState, 'pending'); + assert_true(anim.pending); anim.effect = new KeyframeEffectReadOnly(createDiv(t), { marginLeft: [ '0px', '100px' ] }, 100 * MS_PER_SEC); - assert_equals(anim.playState, 'pending'); + assert_true(anim.pending); return anim.ready.then(() => { + assert_false(anim.pending); assert_equals(anim.playState, 'paused'); }); }, 'If animation has a pending pause task, reschedule that task to run ' + @@ -48,14 +51,15 @@ promise_test(t => { const anim = new Animation(); anim.play(); - assert_equals(anim.playState, 'pending'); + assert_true(anim.pending); anim.effect = new KeyframeEffectReadOnly(createDiv(t), { marginLeft: [ '0px', '100px' ] }, 100 * MS_PER_SEC); - assert_equals(anim.playState, 'pending'); + assert_true(anim.pending); return anim.ready.then(() => { + assert_false(anim.pending); assert_equals(anim.playState, 'running'); }); }, 'If animation has a pending play task, reschedule that task to run ' +
diff --git a/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/set-the-timeline-of-an-animation-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/set-the-timeline-of-an-animation-expected.txt index 88093d4..25cea30 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/set-the-timeline-of-an-animation-expected.txt +++ b/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/set-the-timeline-of-an-animation-expected.txt
@@ -4,18 +4,16 @@ FAIL After setting timeline on an idle animation without a start time it is still idle Cannot assign to read only property 'timeline' of object '#<Animation>' FAIL After setting timeline on an idle animation with a start time it is running assert_equals: expected "idle" but got "running" FAIL After setting timeline on an idle animation with a sufficiently ancient start time it is finished assert_equals: expected "idle" but got "finished" -FAIL After setting timeline on a play-pending animation it is still pending Cannot assign to read only property 'timeline' of object '#<Animation>' -FAIL After setting timeline on a play-pending animation it begins playing after pending Cannot assign to read only property 'timeline' of object '#<Animation>' -FAIL After setting timeline on a pause-pending animation it is still pending Cannot assign to read only property 'timeline' of object '#<Animation>' +FAIL After setting timeline on a play-pending animation it begins playing after pending assert_true: Animation is initially play-pending expected true got undefined FAIL After setting timeline on a pause-pending animation it becomes paused after pending Cannot assign to read only property 'timeline' of object '#<Animation>' -FAIL After clearing timeline on paused animation it is still paused Cannot assign to read only property 'timeline' of object '#<Animation>' +FAIL After clearing timeline on paused animation it is still paused assert_false: expected false got undefined FAIL After clearing timeline on finished animation it is idle Cannot assign to read only property 'timeline' of object '#<Animation>' FAIL After clearing timeline on running animation it is idle Cannot assign to read only property 'timeline' of object '#<Animation>' FAIL After clearing timeline on idle animation it is still idle Cannot assign to read only property 'timeline' of object '#<Animation>' -FAIL After clearing timeline on play-pending animation it is still pending Cannot assign to read only property 'timeline' of object '#<Animation>' -FAIL After clearing and re-setting timeline on play-pending animation it begins to play Cannot assign to read only property 'timeline' of object '#<Animation>' -FAIL After clearing timeline on a pause-pending animation it is still pending Cannot assign to read only property 'timeline' of object '#<Animation>' -FAIL After clearing and re-setting timeline on a pause-pending animation it becomes paused Cannot assign to read only property 'timeline' of object '#<Animation>' +FAIL After clearing timeline on play-pending animation it is still pending assert_true: expected true got undefined +FAIL After clearing and re-setting timeline on play-pending animation it begins to play assert_true: expected true got undefined +FAIL After clearing timeline on a pause-pending animation it is still pending assert_true: expected true got undefined +FAIL After clearing and re-setting timeline on a pause-pending animation it completes pausing assert_true: expected true got undefined FAIL After clearing and re-setting timeline on an animation in the middle of an aborted pause, it continues playing using the same start time Cannot assign to read only property 'timeline' of object '#<Animation>' Harness: the test ran to completion.
diff --git a/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/set-the-timeline-of-an-animation.html b/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/set-the-timeline-of-an-animation.html index 63662fd..f6a77411 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/set-the-timeline-of-an-animation.html +++ b/third_party/WebKit/LayoutTests/external/wpt/web-animations/timing-model/animations/set-the-timeline-of-an-animation.html
@@ -81,47 +81,26 @@ }, 'After setting timeline on an idle animation with a sufficiently ancient' + ' start time it is finished'); -test(t => { - const animation = - new Animation(new KeyframeEffect(createDiv(t), null, 100 * MS_PER_SEC), - null); - animation.play(); - assert_equals(animation.playState, 'pending'); - - animation.timeline = document.timeline; - - assert_equals(animation.playState, 'pending'); -}, 'After setting timeline on a play-pending animation it is still pending'); - promise_test(t => { const animation = new Animation(new KeyframeEffect(createDiv(t), null, 100 * MS_PER_SEC), null); animation.play(); - assert_equals(animation.playState, 'pending'); + assert_true(animation.pending && animation.playState === 'running', + 'Animation is initially play-pending'); animation.timeline = document.timeline; + assert_true(animation.pending && animation.playState === 'running', + 'Animation is still play-pending after setting timeline'); + return animation.ready.then(() => { - assert_equals(animation.playState, 'running'); + assert_true(!animation.pending && animation.playState === 'running', + 'Animation plays after it finishes pending'); }); }, 'After setting timeline on a play-pending animation it begins playing' + ' after pending'); -test(t => { - const animation = - new Animation(new KeyframeEffect(createDiv(t), null, 100 * MS_PER_SEC), - null); - animation.startTime = document.timeline.currentTime; - animation.pause(); - animation.timeline = null; - assert_equals(animation.playState, 'pending'); - - animation.timeline = document.timeline; - - assert_equals(animation.playState, 'pending'); -}, 'After setting timeline on a pause-pending animation it is still pending'); - promise_test(t => { const animation = new Animation(new KeyframeEffect(createDiv(t), null, 100 * MS_PER_SEC), @@ -129,12 +108,17 @@ animation.startTime = document.timeline.currentTime; animation.pause(); animation.timeline = null; - assert_equals(animation.playState, 'pending'); + assert_true(animation.pending && animation.playState === 'paused', + 'Animation is initially pause-pending'); animation.timeline = document.timeline; + assert_true(animation.pending && animation.playState === 'paused', + 'Animation is still pause-pending after setting timeline'); + return animation.ready.then(() => { - assert_equals(animation.playState, 'paused'); + assert_true(!animation.pending && animation.playState === 'paused', + 'Animation pauses after it finishes pending'); }); }, 'After setting timeline on a pause-pending animation it becomes paused' + ' after pending'); @@ -150,10 +134,12 @@ new Animation(new KeyframeEffect(createDiv(t), null, 100 * MS_PER_SEC), document.timeline); animation.currentTime = 50 * MS_PER_SEC; + assert_false(animation.pending); assert_equals(animation.playState, 'paused'); animation.timeline = null; + assert_false(animation.pending); assert_equals(animation.playState, 'paused'); assert_times_equal(animation.currentTime, 50 * MS_PER_SEC); }, 'After clearing timeline on paused animation it is still paused'); @@ -200,23 +186,23 @@ test(t => { const animation = createDiv(t).animate(null, 100 * MS_PER_SEC); - assert_equals(animation.playState, 'pending'); + assert_true(animation.pending && animation.playState === 'running'); animation.timeline = null; - assert_equals(animation.playState, 'pending'); + assert_true(animation.pending && animation.playState === 'running'); }, 'After clearing timeline on play-pending animation it is still pending'); promise_test(t => { const animation = createDiv(t).animate(null, 100 * MS_PER_SEC); - assert_equals(animation.playState, 'pending'); + assert_true(animation.pending && animation.playState === 'running'); animation.timeline = null; animation.timeline = document.timeline; - assert_equals(animation.playState, 'pending'); + assert_true(animation.pending && animation.playState === 'running'); return animation.ready.then(() => { - assert_equals(animation.playState, 'running'); + assert_true(!animation.pending && animation.playState === 'running'); }); }, 'After clearing and re-setting timeline on play-pending animation it' + ' begins to play'); @@ -227,11 +213,11 @@ document.timeline); animation.startTime = document.timeline.currentTime; animation.pause(); - assert_equals(animation.playState, 'pending'); + assert_true(animation.pending && animation.playState === 'paused'); animation.timeline = null; - assert_equals(animation.playState, 'pending'); + assert_true(animation.pending && animation.playState === 'paused'); }, 'After clearing timeline on a pause-pending animation it is still pending'); promise_test(t => { @@ -240,17 +226,17 @@ document.timeline); animation.startTime = document.timeline.currentTime; animation.pause(); - assert_equals(animation.playState, 'pending'); + assert_true(animation.pending && animation.playState === 'paused'); animation.timeline = null; animation.timeline = document.timeline; - assert_equals(animation.playState, 'pending'); + assert_true(animation.pending && animation.playState === 'paused'); return animation.ready.then(() => { - assert_equals(animation.playState, 'paused'); + assert_true(!animation.pending && animation.playState === 'paused'); }); }, 'After clearing and re-setting timeline on a pause-pending animation it' - + ' becomes paused'); + + ' completes pausing'); promise_test(t => { const animation = @@ -263,10 +249,8 @@ animation.timeline = null; animation.timeline = document.timeline; - assert_equals(animation.playState, 'pending'); return animation.ready.then(() => { - assert_equals(animation.playState, 'running'); assert_times_equal(animation.startTime, initialStartTime); }); }, 'After clearing and re-setting timeline on an animation in the middle of'
diff --git a/third_party/WebKit/LayoutTests/external/wpt/webrtc/RTCPeerConnection-setRemoteDescription-tracks.https-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/webrtc/RTCPeerConnection-setRemoteDescription-tracks.https-expected.txt index 8cf5fa79..3ddc9f22 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/webrtc/RTCPeerConnection-setRemoteDescription-tracks.https-expected.txt +++ b/third_party/WebKit/LayoutTests/external/wpt/webrtc/RTCPeerConnection-setRemoteDescription-tracks.https-expected.txt
@@ -1,13 +1,16 @@ This is a testharness.js-based test. FAIL addTrack() with a track and no stream makes ontrack fire with a track and no stream. assert_equals: Expected remote track not to belong to a stream. expected 0 but got 1 PASS addTrack() with a track and a stream makes ontrack fire with a track and a stream. +PASS ontrack fires before setRemoteDescription resolves. PASS addTrack() with two tracks and one stream makes ontrack fire twice with the tracks and shared stream. PASS addTrack() for an existing stream makes stream.onaddtrack fire. +PASS stream.onaddtrack fires before setRemoteDescription resolves. FAIL addTrack() with a track and two streams makes ontrack fire with a track and two streams. Failed to execute 'addTrack' on 'RTCPeerConnection': Adding a track to multiple streams is not supported. -FAIL ontrack fires before setRemoteDescription resolves. assert_equals: expected "ontrack;setRemoteDescription;" but got "setRemoteDescription;ontrack;" PASS ontrack's receiver matches getReceivers(). FAIL removeTrack() does not remove the receiver. assert_array_equals: Expected the set of receivers to remain the same. lengths differ, expected 1 got 0 -PASS removeTrack() causes onremovetrack and the track to be removed from the stream. -PASS removeTrack() causes onmute and the track to be muted. +PASS removeTrack() makes stream.onremovetrack fire and the track to be removed from the stream. +PASS stream.onremovetrack fires before setRemoteDescription resolves. +PASS removeTrack() makes track.onmute fire and the track to be muted. +PASS track.onmute fires before setRemoteDescription resolves. Harness: the test ran to completion.
diff --git a/third_party/WebKit/LayoutTests/external/wpt/webrtc/RTCPeerConnection-setRemoteDescription-tracks.https.html b/third_party/WebKit/LayoutTests/external/wpt/webrtc/RTCPeerConnection-setRemoteDescription-tracks.https.html index f530e94c..a310d9a 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/webrtc/RTCPeerConnection-setRemoteDescription-tracks.https.html +++ b/third_party/WebKit/LayoutTests/external/wpt/webrtc/RTCPeerConnection-setRemoteDescription-tracks.https.html
@@ -24,11 +24,11 @@ const callee = new RTCPeerConnection(); return getUserMediaTracksAndStreams(1) .then(t.step_func(([tracks, streams]) => { - let localTrack = tracks[0]; + const localTrack = tracks[0]; caller.addTrack(localTrack); - let offerPromise = performOffer(caller, callee); + const offerPromise = performOffer(caller, callee); callee.ontrack = t.step_func(trackEvent => { - let remoteTrack = trackEvent.track; + const remoteTrack = trackEvent.track; assert_equals(remoteTrack.id, localTrack.id, 'Expected local and remote track IDs to match.'); assert_equals(trackEvent.streams.length, 0, @@ -47,15 +47,15 @@ const callee = new RTCPeerConnection(); return getUserMediaTracksAndStreams(1) .then(t.step_func(([tracks, streams]) => { - let localTrack = tracks[0]; - let localStream = streams[0]; + const localTrack = tracks[0]; + const localStream = streams[0]; caller.addTrack(localTrack, localStream); - let offerPromise = performOffer(caller, callee); + const offerPromise = performOffer(caller, callee); callee.ontrack = t.step_func(trackEvent => { assert_equals(trackEvent.streams.length, 1, 'Expected track event to fire with a single stream.'); - let remoteTrack = trackEvent.track; - let remoteStream = trackEvent.streams[0]; + const remoteTrack = trackEvent.track; + const remoteStream = trackEvent.streams[0]; assert_equals(remoteTrack.id, localTrack.id, 'Expected local and remote track IDs to match.'); assert_equals(remoteStream.id, localStream.id, @@ -74,19 +74,47 @@ async_test(t => { const caller = new RTCPeerConnection(); const callee = new RTCPeerConnection(); + let eventSequence = ''; + return getUserMediaTracksAndStreams(1) + .then(t.step_func(([tracks, streams]) => { + const ontrackResolver = new Resolver(); + callee.ontrack = () => { + eventSequence += 'ontrack;'; + ontrackResolver.resolve(); + } + caller.addTrack(tracks[0]); + return Promise.all([ + ontrackResolver.promise, + performOffer(caller, callee).then(() => { + eventSequence += 'setRemoteDescription;'; + }) + ]); + })) + .then(t.step_func(() => { + assert_equals(eventSequence, 'ontrack;setRemoteDescription;'); + t.done(); + })) + .catch(t.step_func(reason => { + assert_unreached(reason); + })); + }, 'ontrack fires before setRemoteDescription resolves.'); + + async_test(t => { + const caller = new RTCPeerConnection(); + const callee = new RTCPeerConnection(); return getUserMediaTracksAndStreams(2) .then(t.step_func(([tracks, streams]) => { - let localTrack1 = tracks[0]; - let localTrack2 = tracks[1]; - let localStream = streams[0]; + const localTrack1 = tracks[0]; + const localTrack2 = tracks[1]; + const localStream = streams[0]; caller.addTrack(localTrack1, localStream); caller.addTrack(localTrack2, localStream); - let offerPromise = performOffer(caller, callee); + const offerPromise = performOffer(caller, callee); callee.ontrack = t.step_func(trackEvent => { assert_equals(trackEvent.streams.length, 1, 'Expected track event to fire with a single stream.'); - let remoteTrack1 = trackEvent.track; - let remoteStream = trackEvent.streams[0]; + const remoteTrack1 = trackEvent.track; + const remoteStream = trackEvent.streams[0]; assert_equals(remoteTrack1.id, localTrack1.id, 'Expected first remote track ID to match first local track ID.'); assert_equals(remoteStream.getTracks().length, 2, @@ -94,7 +122,7 @@ callee.ontrack = t.step_func(trackEvent => { assert_equals(trackEvent.streams.length, 1, 'Expected track event to fire with a single stream.'); - let remoteTrack2 = trackEvent.track; + const remoteTrack2 = trackEvent.track; assert_equals(trackEvent.streams[0], remoteStream, 'Expected both track events to fire with the same remote stream.'); assert_equals(remoteTrack2.id, localTrack2.id, @@ -151,17 +179,53 @@ async_test(t => { const caller = new RTCPeerConnection(); const callee = new RTCPeerConnection(); + let eventSequence = ''; return getUserMediaTracksAndStreams(2) .then(t.step_func(([tracks, streams]) => { - let localTrack = tracks[0]; - let localStreams = streams; + const localTracks = tracks; + const localStream = streams[0]; + caller.addTrack(localTracks[0], localStream); + const offerPromise = performOffer(caller, callee); + callee.ontrack = t.step_func(trackEvent => { + callee.ontrack = null; + const remoteStream = trackEvent.streams[0]; + const onaddtrackResolver = new Resolver(); + remoteStream.onaddtrack = () => { + eventSequence += 'stream.onaddtrack;'; + onaddtrackResolver.resolve(); + } + caller.addTrack(localTracks[1], localStream); + Promise.all([ + onaddtrackResolver.promise, + performOffer(caller, callee).then(() => { + eventSequence += 'setRemoteDescription;'; + }) + ]).then(t.step_func(() => { + assert_equals(eventSequence, 'stream.onaddtrack;setRemoteDescription;'); + t.done(); + })); + }); + return offerPromise; + })) + .catch(t.step_func(reason => { + assert_unreached(reason); + })); + }, 'stream.onaddtrack fires before setRemoteDescription resolves.'); + + async_test(t => { + const caller = new RTCPeerConnection(); + const callee = new RTCPeerConnection(); + return getUserMediaTracksAndStreams(2) + .then(t.step_func(([tracks, streams]) => { + const localTrack = tracks[0]; + const localStreams = streams; caller.addTrack(localTrack, localStreams[0], localStreams[1]); - let performOffer = performOffer(caller, callee); + const performOffer = performOffer(caller, callee); callee.ontrack = t.step_func(trackEvent => { assert_equals(trackEvent.streams.length, 2, 'Expected the track event to fire with two streams.'); - let remoteTrack = trackEvent.track; - let remoteStreams = trackEvent.streams; + const remoteTrack = trackEvent.track; + const remoteStreams = trackEvent.streams; assert_equals(remoteTrack.id, localTrack.id, 'Expected local and remote track IDs to match.'); assert_equals(remoteStreams[0].id, localStreams[0].id, @@ -184,38 +248,10 @@ async_test(t => { const caller = new RTCPeerConnection(); const callee = new RTCPeerConnection(); - let eventSequence = ''; return getUserMediaTracksAndStreams(1) .then(t.step_func(([tracks, streams]) => { caller.addTrack(tracks[0]); - let ontrackResolver = new Resolver(); - callee.ontrack = () => { - eventSequence += 'ontrack;'; - ontrackResolver.resolve(); - } - return Promise.all([ - ontrackResolver.promise, - performOffer(caller, callee).then(() => { - eventSequence += 'setRemoteDescription;'; - }) - ]); - })) - .then(t.step_func(() => { - assert_equals(eventSequence, 'ontrack;setRemoteDescription;'); - t.done(); - })) - .catch(t.step_func(reason => { - assert_unreached(reason); - })); - }, 'ontrack fires before setRemoteDescription resolves.'); - - async_test(t => { - const caller = new RTCPeerConnection(); - const callee = new RTCPeerConnection(); - return getUserMediaTracksAndStreams(1) - .then(t.step_func(([tracks, streams]) => { - caller.addTrack(tracks[0]); - let offerPromise = performOffer(caller, callee); + const offerPromise = performOffer(caller, callee); callee.ontrack = t.step_func(trackEvent => { assert_array_equals(callee.getReceivers(), [trackEvent.receiver]); t.done(); @@ -232,11 +268,11 @@ const callee = new RTCPeerConnection(); return getUserMediaTracksAndStreams(1) .then(t.step_func(([tracks, streams]) => { - let sender = caller.addTrack(tracks[0]); - assert_true(sender != null); - let offerPromise = performOffer(caller, callee); + const sender = caller.addTrack(tracks[0]); + assert_not_equals(sender, null); + const offerPromise = performOffer(caller, callee); callee.ontrack = t.step_func(trackEvent => { - let receivers = callee.getReceivers(); + const receivers = callee.getReceivers(); assert_equals(receivers.length, 1, 'Expected getReceivers() to be the track event\'s receiver.'); caller.removeTrack(sender); @@ -259,9 +295,9 @@ const callee = new RTCPeerConnection(); return getUserMediaTracksAndStreams(1) .then(t.step_func(([tracks, streams]) => { - let sender = caller.addTrack(tracks[0], streams[0]); - assert_true(sender != null); - let offerPromise = performOffer(caller, callee); + const sender = caller.addTrack(tracks[0], streams[0]); + assert_not_equals(sender, null); + const offerPromise = performOffer(caller, callee); callee.ontrack = t.step_func(trackEvent => { assert_not_equals(trackEvent.track, null); assert_equals(trackEvent.streams.length, 1); @@ -279,21 +315,55 @@ .catch(t.step_func(reason => { assert_unreached(reason); })); - }, 'removeTrack() causes onremovetrack and the track to be removed from the stream.'); + }, 'removeTrack() makes stream.onremovetrack fire and the track to be removed from the stream.'); + + async_test(t => { + const caller = new RTCPeerConnection(); + const callee = new RTCPeerConnection(); + let eventSequence = ''; + return getUserMediaTracksAndStreams(1) + .then(t.step_func(([tracks, streams]) => { + const sender = caller.addTrack(tracks[0], streams[0]); + assert_not_equals(sender, null); + const offerPromise = performOffer(caller, callee); + callee.ontrack = t.step_func(trackEvent => { + const remoteStream = trackEvent.streams[0]; + const onremovetrackResolver = new Resolver(); + remoteStream.onremovetrack = t.step_func(removeEvent => { + eventSequence += 'stream.onremovetrack;'; + onremovetrackResolver.resolve(); + }); + caller.removeTrack(sender); + return Promise.all([ + onremovetrackResolver.promise, + performOffer(caller, callee).then(() => { + eventSequence += 'setRemoteDescription;'; + }) + ]).then(t.step_func(() => { + assert_equals(eventSequence, 'stream.onremovetrack;setRemoteDescription;'); + t.done(); + })); + }); + return offerPromise; + })) + .catch(t.step_func(reason => { + assert_unreached(reason); + })); + }, 'stream.onremovetrack fires before setRemoteDescription resolves.'); async_test(t => { const caller = new RTCPeerConnection(); const callee = new RTCPeerConnection(); return getUserMediaTracksAndStreams(1) .then(t.step_func(([tracks, streams]) => { - let sender = caller.addTrack(tracks[0]); - assert_true(sender != null); - let offerPromise = performOffer(caller, callee); + const sender = caller.addTrack(tracks[0]); + assert_not_equals(sender, null); + const offerPromise = performOffer(caller, callee); callee.ontrack = t.step_func(trackEvent => { - assert_not_equals(trackEvent.track, null); + const remoteTrack = trackEvent.track; caller.removeTrack(sender); performOffer(caller, callee); - trackEvent.track.onmute = t.step_func(() => { + remoteTrack.onmute = t.step_func(() => { assert_true(trackEvent.track.muted); t.done(); }); @@ -303,6 +373,40 @@ .catch(t.step_func(reason => { assert_unreached(reason); })); - }, 'removeTrack() causes onmute and the track to be muted.'); + }, 'removeTrack() makes track.onmute fire and the track to be muted.'); + + async_test(t => { + const caller = new RTCPeerConnection(); + const callee = new RTCPeerConnection(); + let eventSequence = ''; + return getUserMediaTracksAndStreams(1) + .then(t.step_func(([tracks, streams]) => { + const sender = caller.addTrack(tracks[0]); + assert_not_equals(sender, null); + const offerPromise = performOffer(caller, callee); + callee.ontrack = t.step_func(trackEvent => { + const remoteTrack = trackEvent.track; + const onmuteResolver = new Resolver(); + remoteTrack.onmute = t.step_func(() => { + eventSequence += 'track.onmute;'; + onmuteResolver.resolve(); + }); + caller.removeTrack(sender); + return Promise.all([ + onmuteResolver.promise, + performOffer(caller, callee).then(() => { + eventSequence += 'setRemoteDescription;'; + }) + ]).then(t.step_func(() => { + assert_equals(eventSequence, 'track.onmute;setRemoteDescription;'); + t.done(); + })); + }); + return offerPromise; + })) + .catch(t.step_func(reason => { + assert_unreached(reason); + })); + }, 'track.onmute fires before setRemoteDescription resolves.'); </script>
diff --git a/third_party/WebKit/LayoutTests/fast/dom/Document/document-open-usvstring.html b/third_party/WebKit/LayoutTests/fast/dom/Document/document-open-usvstring.html new file mode 100644 index 0000000..1c23696 --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/dom/Document/document-open-usvstring.html
@@ -0,0 +1,17 @@ +<!DOCTYPE HTML> +<title>document.open test for USVString url</title> +<script src="../../../resources/testharness.js"></script> +<script src="../../../resources/testharnessreport.js"></script> +<body> +<script> +test(function() { + // USVString is equivalent to DOMString except for not allowing unpaired surrogate codepoints. + // U+D800 to U+DFFF code point values are reserved as high and low surrogates, so no UTF forms, including UTF-16, can encode these code points. + // Unpaired surrogate codepoints present in USVString are converted by the browser to Unicode 'replacement character' U+FFFD. + w = document.open("data:text/html,<span>\ud801 is an unpaired surrogate codepoint</span>", "", ""); + // w should be a window object in case of url as USVString type, otherwise in case of DOMString type + // javascript execution stops after throwing syntax error "Unable to open a window with invalid URL". + assert_equals(typeof(w), 'object', 'w should be a window object'); +}, "unpaired surrogate codepoint should be replaced with U+FFFD"); +</script> +</body>
diff --git a/third_party/WebKit/LayoutTests/fast/peerconnection/RTCPeerConnection-ontrack.html b/third_party/WebKit/LayoutTests/fast/peerconnection/RTCPeerConnection-ontrack.html index dbe1acd..e593dc6 100644 --- a/third_party/WebKit/LayoutTests/fast/peerconnection/RTCPeerConnection-ontrack.html +++ b/third_party/WebKit/LayoutTests/fast/peerconnection/RTCPeerConnection-ontrack.html
@@ -8,9 +8,11 @@ <body> <script> +// TODO(hbos): Consider removing this file, it duplicates wpt tests. + promise_test(function() { let pc = new RTCPeerConnection(); - let pc2 = new RTCPeerConnection(); + let pc2 = new RTCPeerConnection(); let eventSequence = []; return createStreams({audio:true, video:false}, 1) .then(function(streams) { @@ -26,7 +28,7 @@ }); return Promise.all(Resolver.promises(resolvers)); }).then(function() { - let expectedEventSequence = [ 'setRemoteDescription', 'ontrack' ]; + let expectedEventSequence = [ 'ontrack', 'setRemoteDescription' ]; assert_array_equals(expectedEventSequence, eventSequence); }); }, 'ontrack fires before negotiation done.'); @@ -49,14 +51,14 @@ }); return Promise.all(Resolver.promises(resolvers)); }).then(function() { - let expectedEventSequence = [ 'setRemoteDescription', 'onaddstream' ]; + let expectedEventSequence = [ 'onaddstream', 'setRemoteDescription' ]; assert_array_equals(eventSequence, expectedEventSequence); }); }, 'onaddstream fires before negotation done.'); promise_test(function() { let pc = new RTCPeerConnection(); - let pc2 = new RTCPeerConnection(); + let pc2 = new RTCPeerConnection(); let eventSequence = []; return createStreams({audio:true, video:false}, 2) .then(function(streams) { @@ -86,7 +88,7 @@ promise_test(function() { let pc = new RTCPeerConnection(); - let pc2 = new RTCPeerConnection(); + let pc2 = new RTCPeerConnection(); let eventSequence = []; return createStreams({audio:true, video:false}, 1) .then(function(streams) { @@ -116,7 +118,7 @@ promise_test(function() { let pc = new RTCPeerConnection(); - let pc2 = new RTCPeerConnection(); + let pc2 = new RTCPeerConnection(); return createStreams({audio:true, video:false}, 1) .then(function(streams) { pc.addStream(streams[0]); @@ -134,7 +136,7 @@ promise_test(function() { let pc = new RTCPeerConnection(); - let pc2 = new RTCPeerConnection(); + let pc2 = new RTCPeerConnection(); return createStreams({audio:true, video:false}, 1) .then(function(streams) { pc.addStream(streams[0]); @@ -151,7 +153,7 @@ promise_test(function() { let pc = new RTCPeerConnection(); - let pc2 = new RTCPeerConnection(); + let pc2 = new RTCPeerConnection(); return createStreams({audio:true, video:false}, 1) .then(function(streams) { pc.addStream(streams[0]); @@ -167,7 +169,7 @@ promise_test(function() { let pc = new RTCPeerConnection(); - let pc2 = new RTCPeerConnection(); + let pc2 = new RTCPeerConnection(); let firedForAudioTrack = false; let firedForVideoTrack = false; return createStreams({audio:true, video:true}, 1)
diff --git a/third_party/WebKit/LayoutTests/fast/workers/resources/shared-worker-common.js b/third_party/WebKit/LayoutTests/fast/workers/resources/shared-worker-common.js index c975d1c..1c1dac3 100644 --- a/third_party/WebKit/LayoutTests/fast/workers/resources/shared-worker-common.js +++ b/third_party/WebKit/LayoutTests/fast/workers/resources/shared-worker-common.js
@@ -8,13 +8,6 @@ event.ports[0].onmessage = function(evt) { handleMessage(evt, event.ports[0]); }; }; -function gc() -{ - for (var i = 0; i < 10000; i++) { // force garbage collection (FF requires about 9K allocations before a collect) - var s = new String("abc"); - } -} - function handleMessage(event, port) { self.port = port; if (event.data == "ping")
diff --git a/third_party/WebKit/LayoutTests/fast/workers/resources/worker-common.js b/third_party/WebKit/LayoutTests/fast/workers/resources/worker-common.js index e05f7ec5..034d5d6 100644 --- a/third_party/WebKit/LayoutTests/fast/workers/resources/worker-common.js +++ b/third_party/WebKit/LayoutTests/fast/workers/resources/worker-common.js
@@ -1,10 +1,3 @@ -function gc() -{ - for (var i = 0; i < 10000; i++) { // > force garbage collection (FF requires about 9K allocations before a collect) - var s = new String("abc"); - } -} - onmessage = function(evt) { gc();
diff --git a/third_party/WebKit/LayoutTests/fast/workers/resources/worker-event-listener.js b/third_party/WebKit/LayoutTests/fast/workers/resources/worker-event-listener.js index fb8bd86..42f7b42d 100644 --- a/third_party/WebKit/LayoutTests/fast/workers/resources/worker-event-listener.js +++ b/third_party/WebKit/LayoutTests/fast/workers/resources/worker-event-listener.js
@@ -1,10 +1,3 @@ -function gc() -{ - for (var i = 0; i < 10000; i++) { // > force garbage collection (FF requires about 9K allocations before a collect) - var s = new String("abc"); - } -} - function onmessage(evt) { postMessage("SUCCESS");
diff --git a/third_party/WebKit/LayoutTests/http/tests/background_fetch/background-fetch-manager-fetch.https.html b/third_party/WebKit/LayoutTests/http/tests/background_fetch/background-fetch-manager-fetch.https.html index e98ff339..11ece21 100644 --- a/third_party/WebKit/LayoutTests/http/tests/background_fetch/background-fetch-manager-fetch.https.html +++ b/third_party/WebKit/LayoutTests/http/tests/background_fetch/background-fetch-manager-fetch.https.html
@@ -96,7 +96,6 @@ assert_true(backgroundFetchRegistration instanceof BackgroundFetchRegistration); assert_equals(backgroundFetchRegistration.id, id); assert_equals(backgroundFetchRegistration.downloadTotal, options.downloadTotal); - assert_equals(backgroundFetchRegistration.title, options.title); // TODO(crbug.com/769770): Remove support for the deprecated attributes. assert_equals(backgroundFetchRegistration.totalDownloadSize, options.downloadTotal);
diff --git a/third_party/WebKit/LayoutTests/http/tests/background_fetch/background-fetch-manager-get.https.html b/third_party/WebKit/LayoutTests/http/tests/background_fetch/background-fetch-manager-get.https.html index bda333e..0c27f4d3 100644 --- a/third_party/WebKit/LayoutTests/http/tests/background_fetch/background-fetch-manager-get.https.html +++ b/third_party/WebKit/LayoutTests/http/tests/background_fetch/background-fetch-manager-get.https.html
@@ -78,7 +78,6 @@ assert_true(secondBackgroundFetchRegistration instanceof BackgroundFetchRegistration); assert_equals(secondBackgroundFetchRegistration.id, id); assert_equals(secondBackgroundFetchRegistration.downloadTotal, options.downloadTotal); - assert_equals(secondBackgroundFetchRegistration.title, options.title); // TODO(crbug.com/769770): Remove support for the deprecated attributes. assert_equals(secondBackgroundFetchRegistration.totalDownloadSize, options.downloadTotal);
diff --git a/third_party/WebKit/LayoutTests/http/tests/bluetooth/https/requestDevice/cross-origin-iframe.html b/third_party/WebKit/LayoutTests/http/tests/bluetooth/https/requestDevice/cross-origin-iframe.html index 381548745..0060fd2 100644 --- a/third_party/WebKit/LayoutTests/http/tests/bluetooth/https/requestDevice/cross-origin-iframe.html +++ b/third_party/WebKit/LayoutTests/http/tests/bluetooth/https/requestDevice/cross-origin-iframe.html
@@ -22,15 +22,15 @@ })) // 2. Request the device from the iframe. .then(() => { + callWithTrustedClick(() => { + iframe.contentWindow.postMessage('Go', '*'); + }); + window.onmessage = messageEvent => test.step(() => { assert_equals(messageEvent.data, 'SecurityError: requestDevice() ' + 'called from cross-origin iframe.'); test.done(); }); - - callWithTrustedClick(() => { - iframe.contentWindow.postMessage('Go', '*'); - }); }), test_desc); </script> </body>
diff --git a/third_party/WebKit/LayoutTests/http/tests/credentialmanager/credentialscontainer-create-basics.html b/third_party/WebKit/LayoutTests/http/tests/credentialmanager/credentialscontainer-create-basics.html index 582cc054..1dca01c 100644 --- a/third_party/WebKit/LayoutTests/http/tests/credentialmanager/credentialscontainer-create-basics.html +++ b/third_party/WebKit/LayoutTests/http/tests/credentialmanager/credentialscontainer-create-basics.html
@@ -16,7 +16,7 @@ }; var public_key_user = { - id: "1098237235409872", + id: new TextEncoder().encode("1098237235409872"), name: "avery.a.jones@example.com", displayName: "Avery A. Jones", icon: "https://pics.acme.com/00/p/aBjjjpqPb.png" @@ -24,15 +24,15 @@ var public_key_parameters = [{ type: "public-key", - algorithm: -7, + alg: -7, },]; var publicKey = { challenge, rp: public_key_rp, user: public_key_user, - parameters: public_key_parameters, - excludeList: [], + pubKeyCredParams: public_key_parameters, + excludeCredentials: [], }; var raw_id = new TextEncoder("utf-8").encode("rawId"); @@ -117,7 +117,7 @@ // No challenge. rp: public_key_rp, user: public_key_user, - parameters: public_key_parameters, + pubKeyCredParams: public_key_parameters, }; return promise_rejects(t, new TypeError(), @@ -141,7 +141,7 @@ challenge, // No rp. user: public_key_user, - parameters: public_key_parameters, + pubKeyCredParams: public_key_parameters, }; return promise_rejects(t, new TypeError(), @@ -153,7 +153,7 @@ challenge, rp: public_key_rp, // No user. - parameters: public_key_parameters, + pubKeyCredParams: public_key_parameters, }; return promise_rejects(t, new TypeError(), @@ -173,7 +173,7 @@ challenge, rp: { name: "Acme" }, user: public_key_user, - parameters: public_key_parameters, + pubKeyCredParams: public_key_parameters, }; return navigator.credentials.create({publicKey: publicKey}).then(r => { @@ -199,10 +199,10 @@ challenge, rp: { id: "1098237235409872" }, user: public_key_user, - parameters: public_key_parameters, + pubKeyCredParams: public_key_parameters, }; - return promise_rejects(t, "NotSupportedError", + return promise_rejects(t, new TypeError(), navigator.credentials.create({publicKey: custom_public_key})); }, "navigator.credentials.create() with missing rp.name"); @@ -215,10 +215,10 @@ displayName: "Avery A. Jones", icon: "https://pics.acme.com/00/p/aBjjjpqPb.png" }, - parameters: public_key_parameters, + pubKeyCredParams: public_key_parameters, }; - return promise_rejects(t, "NotSupportedError", + return promise_rejects(t, new TypeError(), navigator.credentials.create({publicKey: custom_public_key})); }, "navigator.credentials.create() with missing user.id"); @@ -227,16 +227,16 @@ challenge, rp: public_key_rp, user: { - id: "1098237235409872", + id: new TextEncoder().encode("1098237235409872"), displayName: "Avery A. Jones", icon: "https://pics.acme.com/00/p/aBjjjpqPb.png" }, - parameters: public_key_parameters, + pubKeyCredParams: public_key_parameters, timeout: 60000, // 1 minute - excludeList: [], // No excludeList + excludeCredentials: [], // No already-registered credentials. }; - return promise_rejects(t, "NotSupportedError", + return promise_rejects(t, new TypeError(), navigator.credentials.create({publicKey: custom_public_key})); }, "navigator.credentials.create() with missing user.name"); @@ -245,14 +245,14 @@ challenge, rp: public_key_rp, user: { - id: "1098237235409872", + id: new TextEncoder().encode("1098237235409872"), name: "avery.a.jones@example.com", icon: "https://pics.acme.com/00/p/aBjjjpqPb.png" }, - parameters: public_key_parameters, + pubKeyCredParams: public_key_parameters, }; - return promise_rejects(t, "NotSupportedError", + return promise_rejects(t, new TypeError(), navigator.credentials.create({publicKey: custom_public_key})); }, "navigator.credentials.create() with missing user.displayName"); @@ -269,11 +269,11 @@ challenge, rp: public_key_rp, user: { - id: "1098237235409872", + id: new TextEncoder().encode("1098237235409872"), name: "avery.a.jones@example.com", displayName: "Avery A. Jones", }, - parameters: public_key_parameters, + pubKeyCredParams: public_key_parameters, }; return navigator.credentials.create({publicKey: public_key}).then(r => {
diff --git a/third_party/WebKit/LayoutTests/http/tests/credentialmanager/resources/authenticator-helpers.js b/third_party/WebKit/LayoutTests/http/tests/credentialmanager/resources/authenticator-helpers.js index 2ef0529..78b545b 100644 --- a/third_party/WebKit/LayoutTests/http/tests/credentialmanager/resources/authenticator-helpers.js +++ b/third_party/WebKit/LayoutTests/http/tests/credentialmanager/resources/authenticator-helpers.js
@@ -21,7 +21,8 @@ let response = new webauth.mojom.AuthenticatorResponse( { attestationObject: this.attestationObject_, authenticatorData: this.authenticatorData_, - signature: this.signature_ + signature: this.signature_, + userHandle: this.userHandle_ }); info = new webauth.mojom.PublicKeyCredentialInfo( { id: this.id_, @@ -46,6 +47,7 @@ this.attestationObject_ = new Uint8Array(0); this.authenticatorData_ = new Uint8Array(0); this.signature_ = new Uint8Array(0); + this.userHandle = new Uint8Array(0); } setAuthenticatorStatus(status) { @@ -75,6 +77,10 @@ setSignature(signature) { this.signature_ = signature; } + + setUserHandle(userHandle) { + this.userHandle = userHandle; + } } let mockAuthenticator = new MockAuthenticator();
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/components/file-path-scoring.js b/third_party/WebKit/LayoutTests/http/tests/devtools/components/file-path-scoring.js index 5544e8ab..9037b58 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/components/file-path-scoring.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/components/file-path-scoring.js
@@ -25,7 +25,7 @@ TestRunner.addResult('Expected score must be equal to the actual score'); function step1(filePaths) { - var files = filePaths.value.split(':'); + var files = filePaths.split(':'); TestRunner.addResult('Test set size: ' + files.length); for (var i = 0; i < TestQueries.length; ++i) { runQuery(files, TestQueries[i][0], TestQueries[i][1]);
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/console-cd-completions.js b/third_party/WebKit/LayoutTests/http/tests/devtools/console-cd-completions.js index cfbb53a61..9dfcec7 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/console-cd-completions.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/console-cd-completions.js
@@ -131,7 +131,7 @@ } function dumpCounter(result) { - TestRunner.addResult('window.counter = ' + result.value); + TestRunner.addResult('window.counter = ' + result); requestMyClassWithMixinCompletions(); }
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/console/command-line-api-getEventListeners.js b/third_party/WebKit/LayoutTests/http/tests/devtools/console/command-line-api-getEventListeners.js index 36985e9..59a79e5 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/console/command-line-api-getEventListeners.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/console/command-line-api-getEventListeners.js
@@ -112,7 +112,7 @@ ConsoleTestRunner.evaluateInConsole('runTestsInPage(getEventListeners)', async function() { const output = await TestRunner.evaluateInPageAsync('JSON.stringify(self._output)'); - TestRunner.addResults(JSON.parse(output.value)); + TestRunner.addResults(JSON.parse(output)); TestRunner.completeTest(); }); })();
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/console/console-format-broken-unicode.js b/third_party/WebKit/LayoutTests/http/tests/devtools/console/console-format-broken-unicode.js index 1a70b02..d0b3019 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/console/console-format-broken-unicode.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/console/console-format-broken-unicode.js
@@ -38,7 +38,7 @@ } function step5(result) { - var text = result.description; + var text = result; TestRunner.assertEquals(15, text.length, 'text length'); TestRunner.assertEquals(8, countTextNodes(text), 'nodes count'); TestRunner.assertEquals(1, countTextNodes('"' + text + '"'), 'nodes with quoted text count');
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/console/console-format-es6-2.js b/third_party/WebKit/LayoutTests/http/tests/devtools/console/console-format-es6-2.js index 9236e582..908ff8c 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/console/console-format-es6-2.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/console/console-format-es6-2.js
@@ -46,7 +46,7 @@ function advance() { var next = current + 1; - if (next == total.description) + if (next == total) finish(); else loopOverGlobals(next, total);
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/console/console-format.js b/third_party/WebKit/LayoutTests/http/tests/devtools/console/console-format.js index e054610..31ad390 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/console/console-format.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/console/console-format.js
@@ -127,7 +127,7 @@ function loopOverGlobals(current, total) { function advance() { var next = current + 1; - if (next == total.description) + if (next == total) ConsoleTestRunner.waitForRemoteObjectsConsoleMessages(onRemoteObjectsLoaded); else loopOverGlobals(next, total);
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/console/console-proxy.js b/third_party/WebKit/LayoutTests/http/tests/devtools/console/console-proxy.js index 4dca8741d..2f42714 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/console/console-proxy.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/console/console-proxy.js
@@ -41,7 +41,7 @@ } function dumpAccessedGetAndExpand(result) { - TestRunner.addResult('window.accessedGet = ' + result.value); + TestRunner.addResult('window.accessedGet = ' + result); ConsoleTestRunner.expandConsoleMessages(dumpExpandedConsoleMessages); } @@ -54,7 +54,7 @@ } function dumpAccessedGetAndCompleteTest(result) { - TestRunner.addResult('window.accessedGet = ' + result.value); + TestRunner.addResult('window.accessedGet = ' + result); TestRunner.completeTest(); }
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/console/console-uncaught-promise.js b/third_party/WebKit/LayoutTests/http/tests/devtools/console/console-uncaught-promise.js index 106a3e98..fd50ea7 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/console/console-uncaught-promise.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/console/console-uncaught-promise.js
@@ -106,7 +106,7 @@ TestRunner.evaluateInPage('runNextPromiseTest()', callback); function callback(result) { - if (!result.value) + if (!result) ConsoleTestRunner.expandConsoleMessages(dump); } }
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/editor/text-editor-auto-whitespace-removing.js b/third_party/WebKit/LayoutTests/http/tests/devtools/editor/text-editor-auto-whitespace-removing.js index a909a07f..8267007d 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/editor/text-editor-auto-whitespace-removing.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/editor/text-editor-auto-whitespace-removing.js
@@ -26,7 +26,7 @@ var codeSnippetText; function onCodeSnippet(result) { - codeSnippetText = result.value; + codeSnippetText = result; TestRunner.runTestSuite(testSuite); }
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/editor/text-editor-block-indent.js b/third_party/WebKit/LayoutTests/http/tests/devtools/editor/text-editor-block-indent.js index 5f97daf6..f1ace426 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/editor/text-editor-block-indent.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/editor/text-editor-block-indent.js
@@ -31,7 +31,7 @@ var codeSnippetText; function onCodeSnippet(result) { - codeSnippetText = result.value; + codeSnippetText = result; TestRunner.runTestSuite(testSuite); }
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/editor/text-editor-ctrl-d-1.js b/third_party/WebKit/LayoutTests/http/tests/devtools/editor/text-editor-ctrl-d-1.js index 74f49dd..e290572 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/editor/text-editor-ctrl-d-1.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/editor/text-editor-ctrl-d-1.js
@@ -48,7 +48,7 @@ TestRunner.evaluateInPage('codeSnippet();', onCodeSnippet); function onCodeSnippet(result) { - var codeLines = result.value; + var codeLines = result; textEditor.setText(codeLines); TestRunner.runTestSuite(testSuite); }
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/editor/text-editor-ctrl-d-2.js b/third_party/WebKit/LayoutTests/http/tests/devtools/editor/text-editor-ctrl-d-2.js index 6841f306..43262fd 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/editor/text-editor-ctrl-d-2.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/editor/text-editor-ctrl-d-2.js
@@ -48,7 +48,7 @@ TestRunner.evaluateInPage('codeSnippet();', onCodeSnippet); function onCodeSnippet(result) { - var codeLines = result.value; + var codeLines = result; textEditor.setText(codeLines); TestRunner.runTestSuite(testSuite); }
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/editor/text-editor-formatter.js b/third_party/WebKit/LayoutTests/http/tests/devtools/editor/text-editor-formatter.js index 112f403..de4029bf 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/editor/text-editor-formatter.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/editor/text-editor-formatter.js
@@ -40,7 +40,7 @@ textEditor.element.focus(); function step2(result) { - var codeLines = result.value; + var codeLines = result; SourcesTestRunner.typeIn(textEditor, codeLines, step3); }
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/editor/text-editor-goto-matching-bracket.js b/third_party/WebKit/LayoutTests/http/tests/devtools/editor/text-editor-goto-matching-bracket.js index 41aee31..516267e 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/editor/text-editor-goto-matching-bracket.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/editor/text-editor-goto-matching-bracket.js
@@ -29,7 +29,7 @@ var codeSnippetText; function onCodeSnippet(result) { - codeSnippetText = result.value; + codeSnippetText = result; TestRunner.runTestSuite(testSuite); }
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/editor/text-editor-indent-autodetection.js b/third_party/WebKit/LayoutTests/http/tests/devtools/editor/text-editor-indent-autodetection.js index ce8ec22..d6e1d5e1 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/editor/text-editor-indent-autodetection.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/editor/text-editor-indent-autodetection.js
@@ -127,7 +127,7 @@ var command = 'codeSnippet(\'' + snippetName + '\');'; TestRunner.evaluateInPage(command, step2); function step2(result) { - textEditor.setText(result.value); + textEditor.setText(result); var indent = textEditor.indent(); var description = indent === TextUtils.TextUtils.Indent.TabCharacter ? 'Tab' : indent.length + ' spaces'; TestRunner.addResult('Autodetected indentation for ' + snippetName + ': ' + description); @@ -137,8 +137,8 @@ function onTestNumberReceived(result) { var testSuite = []; - TestRunner.addResult('Tests number: ' + result.value); - for (var i = 1; i <= result.value; ++i) + TestRunner.addResult('Tests number: ' + result); + for (var i = 1; i <= result; ++i) testSuite.push(genericTest.bind(this, 'test' + i)); TestRunner.runTestSuite(testSuite);
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/elements/elements-css-path.js b/third_party/WebKit/LayoutTests/http/tests/devtools/elements/elements-css-path.js index 21e02c9..4b3b177 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/elements/elements-css-path.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/elements/elements-css-path.js
@@ -111,7 +111,7 @@ TestRunner.evaluateInPage('matchingElements(\'' + escapedPath + '\')', callback); function callback(result) { - TestRunner.assertEquals(1, result.value); + TestRunner.assertEquals(1, result); dumpNodeData(); } }
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/elements/hide-shortcut.js b/third_party/WebKit/LayoutTests/http/tests/devtools/elements/hide-shortcut.js index 1985eca..d15dd13 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/elements/hide-shortcut.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/elements/hide-shortcut.js
@@ -140,7 +140,7 @@ TestRunner.evaluateInPagePromise('pseudoIframeVisibility()').then(function(result) { TestRunner.addResult('=== Added hide shortcut in frame ==='); TestRunner.addResult('=== Frame node is hidden ==='); - TestRunner.addResult('visibility: ' + result.value + ';'); + TestRunner.addResult('visibility: ' + result + ';'); next(); }); } @@ -156,7 +156,7 @@ function callback() { var pseudoNodeTypeArg = pseudoNode.pseudoType() ? ('"' + pseudoNode.pseudoType() + '"') : 'undefined'; TestRunner.evaluateInPagePromise('pseudoVisibility(' + pseudoNodeTypeArg + ')').then(function(result) { - TestRunner.addResult('::' + pseudoNode.pseudoType() + ' node visibility: \'' + result.value + '\''); + TestRunner.addResult('::' + pseudoNode.pseudoType() + ' node visibility: \'' + result + '\''); next(); }); }
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/elements/resolve-node-blocked.js b/third_party/WebKit/LayoutTests/http/tests/devtools/elements/resolve-node-blocked.js index d038f93..737caab1 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/elements/resolve-node-blocked.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/elements/resolve-node-blocked.js
@@ -15,11 +15,9 @@ </p> `); - TestRunner.evaluateInPage('document', didReceiveDocumentObject); - async function didReceiveDocumentObject(remoteObject) { - TestRunner.addResult('didReceiveDocumentObject'); - var nodeId = await TestRunner.DOMAgent.requestNode(remoteObject.objectId); - TestRunner.addResult('didRequestNode error = ' + (nodeId ? 'null' : 'error')); - TestRunner.completeTest(); - } + var remoteObject = await TestRunner.evaluateInPageRemoteObject('document'); + TestRunner.addResult('didReceiveDocumentObject'); + var nodeId = await TestRunner.DOMAgent.requestNode(remoteObject.objectId); + TestRunner.addResult('didRequestNode error = ' + (nodeId ? 'null' : 'error')); + TestRunner.completeTest(); })();
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/elements/reveal-whitespace-text-node.js b/third_party/WebKit/LayoutTests/http/tests/devtools/elements/reveal-whitespace-text-node.js index 6e85ec7b..f991432 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/elements/reveal-whitespace-text-node.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/elements/reveal-whitespace-text-node.js
@@ -20,13 +20,11 @@ } `); - TestRunner.evaluateInPage('whitespaceChild()', childCallback); + var childObject = await TestRunner.evaluateInPageRemoteObject('whitespaceChild()'); - function childCallback(childObject) { - ElementsTestRunner.firstElementsTreeOutline().addEventListener( - Elements.ElementsTreeOutline.Events.SelectedNodeChanged, selectedNodeChanged); - Common.Revealer.reveal(childObject); - } + ElementsTestRunner.firstElementsTreeOutline().addEventListener( + Elements.ElementsTreeOutline.Events.SelectedNodeChanged, selectedNodeChanged); + Common.Revealer.reveal(childObject); function selectedNodeChanged(event) { var node = event.data.node;
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/elements/styles-1/css-outline.html b/third_party/WebKit/LayoutTests/http/tests/devtools/elements/styles-1/css-outline.html index 7b316b2c..cd350a8 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/elements/styles-1/css-outline.html +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/elements/styles-1/css-outline.html
@@ -71,7 +71,7 @@ } function onStyleFetched(result) { - Formatter.formatterWorkerPool().parseCSS(result.value, onRulesParsed); + Formatter.formatterWorkerPool().parseCSS(result, onRulesParsed); } TestRunner.evaluateInPage('getCSS()', onStyleFetched);
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/evaluate-in-page.js b/third_party/WebKit/LayoutTests/http/tests/devtools/evaluate-in-page.js index aea0ed8d3..6c2d5b6c 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/evaluate-in-page.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/evaluate-in-page.js
@@ -12,7 +12,7 @@ `); function callback(result) { - TestRunner.addResult('2 + 2 = ' + result.description); + TestRunner.addResult('2 + 2 = ' + result); TestRunner.completeTest(); } TestRunner.evaluateInPage('sum(2, 2)', callback);
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/import-open-inspector.js b/third_party/WebKit/LayoutTests/http/tests/devtools/import-open-inspector.js index 95ea5bb..5622f4f9 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/import-open-inspector.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/import-open-inspector.js
@@ -27,7 +27,7 @@ function checkGreetingSet(next) { TestRunner.evaluateInPage('getGreeting()', callback); function callback(result) { - TestRunner.addResult('Received: ' + result.value); + TestRunner.addResult('Received: ' + result); next(); } },
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/inspected-objects-not-overriden.js b/third_party/WebKit/LayoutTests/http/tests/devtools/inspected-objects-not-overriden.js index 8b4f9c4b..e78ab6d 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/inspected-objects-not-overriden.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/inspected-objects-not-overriden.js
@@ -48,7 +48,7 @@ async function callback() { const output = await TestRunner.evaluateInPageAsync('originalJSONStringify(self._output)'); - TestRunner.addResults(JSON.parse(output.value)); + TestRunner.addResults(JSON.parse(output)); TestRunner.completeTest(); }
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/layers/layer-oopif-expected.txt b/third_party/WebKit/LayoutTests/http/tests/devtools/layers/layer-oopif-expected.txt new file mode 100644 index 0000000..a8d7cb5a --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/layers/layer-oopif-expected.txt
@@ -0,0 +1,2 @@ +Tests renderer does not crash with an out-of-process iframe +
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/layers/layer-oopif.js b/third_party/WebKit/LayoutTests/http/tests/devtools/layers/layer-oopif.js new file mode 100644 index 0000000..a323923 --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/layers/layer-oopif.js
@@ -0,0 +1,19 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +(async function() { + TestRunner.addResult(`Tests renderer does not crash with an out-of-process iframe`); + await TestRunner.loadModule('layers_test_runner'); + await TestRunner.loadHTML(` + <style> + #frame { + width: 200px; + height: 200px; + } + </style> + `); + await TestRunner.addIframe('http://localhost:8000/devtools/layers/resources/composited-iframe.html', {id: 'frame'}); + await LayersTestRunner.requestLayers(); + TestRunner.completeTest(); +})();
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-disable-cache-xhrs-expected.txt b/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-disable-cache-xhrs-expected.txt index 36ce85a..b9f9adf 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-disable-cache-xhrs-expected.txt +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-disable-cache-xhrs-expected.txt
@@ -1,6 +1,3 @@ -CONSOLE MESSAGE: line 5: XHR loaded: 1 -CONSOLE MESSAGE: line 5: XHR loaded: 2 -CONSOLE MESSAGE: line 5: XHR loaded: 3 Tests disabling cache from inspector. http://127.0.0.1:8000/devtools/network/resources/resource.php?random=1&cached=1
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-disable-cache-xhrs.html b/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-disable-cache-xhrs.html deleted file mode 100644 index e5b97d2..0000000 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-disable-cache-xhrs.html +++ /dev/null
@@ -1,52 +0,0 @@ -<html> -<head> -<script src="../../inspector/inspector-test.js"></script> -<script src="../../inspector/network-test.js"></script> -<script> -function test() { - NetworkTestRunner.recordNetwork(); - NetworkTestRunner.makeSimpleXHR('GET', 'resources/resource.php?random=1&cached=1', true, firstXHRLoaded); - - function firstXHRLoaded() { - NetworkTestRunner.makeSimpleXHR('GET', 'resources/resource.php?random=1&cached=1', true, step2); - } - - function step2() { - TestRunner.NetworkAgent.setCacheDisabled(true).then(step3); - } - - function step3() { - NetworkTestRunner.makeSimpleXHR('GET', 'resources/resource.php?random=1&cached=1', true, step4); - } - - async function step4(msg) { - // inspector-test.js appears in network panel occasionally in Safari on - // Mac, so checking two last resources. - var requests = NetworkTestRunner.networkRequests(); - var request1 = requests[requests.length - 3]; - var request2 = requests[requests.length - 2]; - var request3 = requests[requests.length - 1]; - - var request1Content = await request1.requestContent(); - var request2Content = await request2.requestContent(); - var request3Content = await request3.requestContent(); - - TestRunner.addResult(request1.url()); - TestRunner.addResult(request2.url()); - TestRunner.addResult(request3.url()); - TestRunner.assertTrue(request1Content === request2Content, 'First and second resources are equal'); - TestRunner.assertTrue(request2Content !== request3Content, 'Second and third resources differ'); - TestRunner.NetworkAgent.setCacheDisabled(false).then(step5); - } - - function step5() { - TestRunner.completeTest(); - } -} -</script> -</head> -<body onload="runTest()"> - <p>Tests disabling cache from inspector.</p> -</body> -</html> -
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-disable-cache-xhrs.js b/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-disable-cache-xhrs.js new file mode 100644 index 0000000..615adec --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-disable-cache-xhrs.js
@@ -0,0 +1,48 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +(async function() { + TestRunner.addResult(`Tests disabling cache from inspector.\n`); + await TestRunner.loadModule('network_test_runner'); + await TestRunner.showPanel('network'); + + NetworkTestRunner.recordNetwork(); + NetworkTestRunner.makeSimpleXHR('GET', 'resources/resource.php?random=1&cached=1', true, firstXHRLoaded); + + function firstXHRLoaded() { + NetworkTestRunner.makeSimpleXHR('GET', 'resources/resource.php?random=1&cached=1', true, step2); + } + + function step2() { + TestRunner.NetworkAgent.setCacheDisabled(true).then(step3); + } + + function step3() { + NetworkTestRunner.makeSimpleXHR('GET', 'resources/resource.php?random=1&cached=1', true, step4); + } + + async function step4(msg) { + // inspector-test.js appears in network panel occasionally in Safari on + // Mac, so checking two last resources. + var requests = NetworkTestRunner.networkRequests(); + var request1 = requests[requests.length - 3]; + var request2 = requests[requests.length - 2]; + var request3 = requests[requests.length - 1]; + + var request1Content = await request1.requestContent(); + var request2Content = await request2.requestContent(); + var request3Content = await request3.requestContent(); + + TestRunner.addResult(request1.url()); + TestRunner.addResult(request2.url()); + TestRunner.addResult(request3.url()); + TestRunner.assertTrue(request1Content === request2Content, 'First and second resources are equal'); + TestRunner.assertTrue(request2Content !== request3Content, 'Second and third resources differ'); + TestRunner.NetworkAgent.setCacheDisabled(false).then(step5); + } + + function step5() { + TestRunner.completeTest(); + } +})();
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-disabling-check-no-memory-leak-expected.txt b/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-disabling-check-no-memory-leak-expected.txt index 7917a2e5..cd57b42 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-disabling-check-no-memory-leak-expected.txt +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-disabling-check-no-memory-leak-expected.txt
@@ -1,5 +1,3 @@ -CONSOLE MESSAGE: line 5: XHR loaded: 1 -Tests that after disabling network domain, content saved on backend is removed. Bug 67995 - +Tests that after disabling network domain, content saved on backend is removed. https://bugs.webkit.org/show_bug.cgi?id=67995 resource.content after disabling network domain: null
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-disabling-check-no-memory-leak.html b/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-disabling-check-no-memory-leak.html deleted file mode 100644 index 14d6c17..0000000 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-disabling-check-no-memory-leak.html +++ /dev/null
@@ -1,33 +0,0 @@ -<html> -<head> -<script src="../../inspector/inspector-test.js"></script> -<script src="../../inspector/network-test.js"></script> -<script> -function test() { - NetworkTestRunner.recordNetwork(); - NetworkTestRunner.makeSimpleXHR('GET', 'resources/resource.php', true, step2); - - async function step2() { - await TestRunner.NetworkAgent.disable(); - var request1 = NetworkTestRunner.networkRequests().pop(); - request1.requestContent().then(step4); - } - - function step4(content) { - TestRunner.addResult('resource.content after disabling network domain: ' + content); - TestRunner.NetworkAgent.enable().then(step5); - } - - function step5() { - TestRunner.completeTest(); - } -} -</script> -</head> -<body onload="runTest()"> - <p> - Tests that after disabling network domain, content saved on backend is removed. -<a href="https://bugs.webkit.org/show_bug.cgi?id=67995">Bug 67995</a> -</p> -</body> -</html>
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-disabling-check-no-memory-leak.js b/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-disabling-check-no-memory-leak.js new file mode 100644 index 0000000..b4a30dc --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-disabling-check-no-memory-leak.js
@@ -0,0 +1,34 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +(async function() { + TestRunner.addResult( + `Tests that after disabling network domain, content saved on backend is removed. https://bugs.webkit.org/show_bug.cgi?id=67995`); + await TestRunner.loadModule('network_test_runner'); + await TestRunner.showPanel('network'); + await TestRunner.loadHTML(` + <p> + Tests that after disabling network domain, content saved on backend is removed. + <a href="https://bugs.webkit.org/show_bug.cgi?id=67995">Bug 67995</a> + </p> + `); + + NetworkTestRunner.recordNetwork(); + NetworkTestRunner.makeSimpleXHR('GET', 'resources/resource.php', true, step2); + + async function step2() { + await TestRunner.NetworkAgent.disable(); + var request1 = NetworkTestRunner.networkRequests().pop(); + request1.requestContent().then(step4); + } + + function step4(content) { + TestRunner.addResult('resource.content after disabling network domain: ' + content); + TestRunner.NetworkAgent.enable().then(step5); + } + + function step5() { + TestRunner.completeTest(); + } +})();
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-document-initiator-expected.txt b/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-document-initiator-expected.txt index dd776e5..f9be31d 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-document-initiator-expected.txt +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-document-initiator-expected.txt
@@ -1,6 +1,6 @@ Tests that page navigation initiated by JS is correctly reported. Page reloaded. -http://127.0.0.1:8000/devtools/network/network-document-initiator.html?foo: script - navigateFromScript http://127.0.0.1:8000/devtools/network/network-document-initiator.html 8 +http://127.0.0.1:8000/devtools/network/resources/initiator.html?foo: script + navigateFromScript http://127.0.0.1:8000/devtools/network/resources/initiator.html 7
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-document-initiator.html b/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-document-initiator.html deleted file mode 100644 index 8d80cb5..0000000 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-document-initiator.html +++ /dev/null
@@ -1,46 +0,0 @@ -<html> -<head> -<link href="resources/initiator.css" rel="stylesheet" type="text/css"> -<script src="../../inspector/inspector-test.js"></script> -<script src="../../inspector/network-test.js"></script> -<script> -function navigateFromScript() -{ - window.location.href = "?foo"; -} - -var test = function() { - TestRunner.evaluateInPage('navigateFromScript()'); - TestRunner.runWhenPageLoads(step1); - - function dumpInitiator(request) { - var initiator = request.initiator(); - TestRunner.addResult(request.url() + ': ' + initiator.type); - if (initiator.url) - TestRunner.addResult(' ' + initiator.url + ' ' + initiator.lineNumber); - var stackTrace = initiator.stack; - if (!stackTrace) - return; - for (var i = 0; i < stackTrace.callFrames.length; ++i) { - var frame = stackTrace.callFrames[i]; - if (frame.lineNumber) { - TestRunner.addResult(' ' + frame.functionName + ' ' + frame.url + ' ' + frame.lineNumber); - return; - } - } - } - - function step1() { - var results = NetworkTestRunner.findRequestsByURLPattern(/\?foo/); - TestRunner.assertTrue(results.length !== 0); - dumpInitiator(results[0]); - TestRunner.completeTest(); - } -}; - -</script> -</head> -<body onload="runTest()"> -<p>Tests that page navigation initiated by JS is correctly reported.</p> -</body> -</html>
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-document-initiator.js b/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-document-initiator.js new file mode 100644 index 0000000..cf954cef --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-document-initiator.js
@@ -0,0 +1,37 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +(async function() { + TestRunner.addResult(`Tests that page navigation initiated by JS is correctly reported.\n`); + await TestRunner.loadModule('network_test_runner'); + await TestRunner.showPanel('network'); + await TestRunner.navigatePromise('resources/initiator.html'); + TestRunner.runWhenPageLoads(step1); + TestRunner.resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.Load, TestRunner.pageLoaded); + await TestRunner.evaluateInPage('navigateFromScript()'); + + function dumpInitiator(request) { + var initiator = request.initiator(); + TestRunner.addResult(request.url() + ': ' + initiator.type); + if (initiator.url) + TestRunner.addResult(' ' + initiator.url + ' ' + initiator.lineNumber); + var stackTrace = initiator.stack; + if (!stackTrace) + return; + for (var i = 0; i < stackTrace.callFrames.length; ++i) { + var frame = stackTrace.callFrames[i]; + if (frame.lineNumber) { + TestRunner.addResult(' ' + frame.functionName + ' ' + frame.url + ' ' + frame.lineNumber); + return; + } + } + } + + function step1() { + var results = NetworkTestRunner.findRequestsByURLPattern(/\?foo/); + TestRunner.assertEquals(1, results.length); + dumpInitiator(results[0]); + TestRunner.completeTest(); + } +})();
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-domain-filter.html b/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-domain-filter.html deleted file mode 100644 index 4115086..0000000 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-domain-filter.html +++ /dev/null
@@ -1,36 +0,0 @@ -<html> -<head> -<script src="../../inspector/inspector-test.js"></script> -<script src="../../inspector/network-test.js"></script> -<script> -function test() { - function checkSubdomains(domain) { - TestRunner.addResult(''); - TestRunner.addResult('Domain: ' + domain); - TestRunner.addResult('Subdomains: ' + JSON.stringify(Network.NetworkLogView._subdomains(domain))); - } - - function checkFilter(value, domains) { - var filter = Network.NetworkLogView._createRequestDomainFilter(value); - TestRunner.addResult(''); - TestRunner.addResult('Filter: ' + value); - for (var i = 0; i < domains.length; ++i) - TestRunner.addResult('Domain \'' + domains[i] + '\' matches: ' + filter({domain: domains[i]})); - } - - checkSubdomains('foo.bar.com'); - checkSubdomains('thumbnails'); - - checkFilter('bar.com', ['foo.bar.com', 'bar.com', 'com']); - checkFilter('*.bar.com', ['foo.bar.com', 'bar.com']); - checkFilter('*.bar.*', ['foo.bar.com', 'baz.bar.org', 'bar.foo.net']); - - TestRunner.completeTest(); -} - -</script> -</head> -<body onload="runTest()"> -<p>Tests doamin filter.</p> -</body> -</html>
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-domain-filter.js b/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-domain-filter.js new file mode 100644 index 0000000..d8bec1c --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-domain-filter.js
@@ -0,0 +1,32 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +(async function() { + TestRunner.addResult(`Tests doamin filter.\n`); + await TestRunner.loadModule('network_test_runner'); + await TestRunner.showPanel('network'); + + function checkSubdomains(domain) { + TestRunner.addResult(''); + TestRunner.addResult('Domain: ' + domain); + TestRunner.addResult('Subdomains: ' + JSON.stringify(Network.NetworkLogView._subdomains(domain))); + } + + function checkFilter(value, domains) { + var filter = Network.NetworkLogView._createRequestDomainFilter(value); + TestRunner.addResult(''); + TestRunner.addResult('Filter: ' + value); + for (var i = 0; i < domains.length; ++i) + TestRunner.addResult('Domain \'' + domains[i] + '\' matches: ' + filter({domain: domains[i]})); + } + + checkSubdomains('foo.bar.com'); + checkSubdomains('thumbnails'); + + checkFilter('bar.com', ['foo.bar.com', 'bar.com', 'com']); + checkFilter('*.bar.com', ['foo.bar.com', 'bar.com']); + checkFilter('*.bar.*', ['foo.bar.com', 'baz.bar.org', 'bar.foo.net']); + + TestRunner.completeTest(); +})();
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-empty-xhr-expected.txt b/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-empty-xhr-expected.txt index a8941c50..2ec3830 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-empty-xhr-expected.txt +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-empty-xhr-expected.txt
@@ -1,9 +1,4 @@ -CONSOLE WARNING: line 31: Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/. -CONSOLE MESSAGE: line 5: XHR loaded: 1 -CONSOLE MESSAGE: line 5: XHR loaded: 2 -Tests empty xhr content is correctly loaded in inspector. - -Bug 79026 +Tests empty xhr content is correctly loaded in inspector. https://bugs.webkit.org/show_bug.cgi?id=79026 http://127.0.0.1:8000/devtools/network/resources/empty.html?sync resource.content: http://127.0.0.1:8000/devtools/network/resources/empty.html?async
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-empty-xhr.html b/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-empty-xhr.html deleted file mode 100644 index e6bdfbf..0000000 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-empty-xhr.html +++ /dev/null
@@ -1,50 +0,0 @@ -<html> -<head> -<script src="../../inspector/inspector-test.js"></script> -<script src="../../inspector/network-test.js"></script> -<script> -function test() { - function dumpRequest(request, callback) { - if (!request) - return callback(); - TestRunner.addResult(request.url()); - - function contentLoaded(content) { - TestRunner.addResult('resource.content: ' + content); - callback(); - } - - request.requestContent().then(contentLoaded); - } - - NetworkTestRunner.recordNetwork(); - NetworkTestRunner.makeSimpleXHR('GET', 'resources/empty.html?sync', false, firstXHRLoaded); - - function firstXHRLoaded() { - NetworkTestRunner.makeSimpleXHR('GET', 'resources/empty.html?async', true, step2); - } - - function step2() { - var requests = NetworkTestRunner.networkRequests(); - var request = requests[requests.length - 2]; - dumpRequest(request, step3); - } - - function step3() { - var requests = NetworkTestRunner.networkRequests(); - var request = requests[requests.length - 1]; - dumpRequest(request, step4); - } - - function step4() { - TestRunner.completeTest(); - } -} -</script> -</head> -<body onload="runTest()"> -<p> Tests empty xhr content is correctly loaded in inspector.</p> -<a href="https://bugs.webkit.org/show_bug.cgi?id=79026">Bug 79026</a> -</body> -</html> -
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-empty-xhr.js b/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-empty-xhr.js new file mode 100644 index 0000000..da12a38e --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-empty-xhr.js
@@ -0,0 +1,50 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +(async function() { + TestRunner.addResult( + `Tests empty xhr content is correctly loaded in inspector. https://bugs.webkit.org/show_bug.cgi?id=79026`); + await TestRunner.loadModule('network_test_runner'); + await TestRunner.showPanel('network'); + await TestRunner.loadHTML(` + <p> Tests empty xhr content is correctly loaded in inspector.</p> + <a href="https://bugs.webkit.org/show_bug.cgi?id=79026">Bug 79026</a> + `); + + function dumpRequest(request, callback) { + if (!request) + return callback(); + TestRunner.addResult(request.url()); + + function contentLoaded(content) { + TestRunner.addResult('resource.content: ' + content); + callback(); + } + + request.requestContent().then(contentLoaded); + } + + NetworkTestRunner.recordNetwork(); + NetworkTestRunner.makeSimpleXHR('GET', 'resources/empty.html?sync', false, firstXHRLoaded); + + function firstXHRLoaded() { + NetworkTestRunner.makeSimpleXHR('GET', 'resources/empty.html?async', true, step2); + } + + function step2() { + var requests = NetworkTestRunner.networkRequests(); + var request = requests[requests.length - 2]; + dumpRequest(request, step3); + } + + function step3() { + var requests = NetworkTestRunner.networkRequests(); + var request = requests[requests.length - 1]; + dumpRequest(request, step4); + } + + function step4() { + TestRunner.completeTest(); + } +})();
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-eventsource.js b/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-eventsource.js index 22a9b86..1d58596 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-eventsource.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-eventsource.js
@@ -41,7 +41,7 @@ async function step2() { const output = await TestRunner.evaluateInPageAsync('JSON.stringify(self._output)'); - TestRunner.addResults(JSON.parse(output.value)); + TestRunner.addResults(JSON.parse(output)); var request1 = NetworkTestRunner.networkRequests().pop(); TestRunner.addResult(request1.url()); TestRunner.addResult('resource.type: ' + request1.resourceType());
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-worker-fetch-blocked.js b/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-worker-fetch-blocked.js index fdc69b6..132d3f7 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-worker-fetch-blocked.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-worker-fetch-blocked.js
@@ -14,7 +14,7 @@ NetworkTestRunner.makeFetchInWorker('resource.php', {}, fetchCallback); function fetchCallback(result) { - TestRunner.addResult('Fetch in worker result: ' + result.value); + TestRunner.addResult('Fetch in worker result: ' + result); var requests = NetworkTestRunner.networkRequests(); requests.forEach((request) => {
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-worker-fetch-parallel.js b/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-worker-fetch-parallel.js index 3e11108e..d17d11a 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-worker-fetch-parallel.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-worker-fetch-parallel.js
@@ -23,7 +23,7 @@ TestRunner.callFunctionInPageAsync('makeFetchesInWorker', [['./resource.php?1', './resource.php?2']]) .then((result) => { - TestRunner.addResult('Parallel fetch in worker result: ' + result.value); + TestRunner.addResult('Parallel fetch in worker result: ' + result); var requests = NetworkTestRunner.networkRequests(); requests.forEach((request) => { TestRunner.addResult(request.url());
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-worker-fetch.js b/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-worker-fetch.js index 7758d02..09b4a7c 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-worker-fetch.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/network/network-worker-fetch.js
@@ -12,7 +12,7 @@ NetworkTestRunner.makeFetchInWorker('resource.php', {}, fetchCallback); function fetchCallback(result) { - TestRunner.addResult('Fetch in worker result: ' + result.value); + TestRunner.addResult('Fetch in worker result: ' + result); var requests = NetworkTestRunner.networkRequests(); requests.forEach((request) => {
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/network/resources/initiator.html b/third_party/WebKit/LayoutTests/http/tests/devtools/network/resources/initiator.html new file mode 100644 index 0000000..275ed502e --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/network/resources/initiator.html
@@ -0,0 +1,15 @@ +<!DOCTYPE html> +<html> +<head> +<link rel="stylesheet" type="text/css" href="initiator.css"> +<script type="text/javascript"> +function navigateFromScript() +{ + window.location.href = '?foo'; +} +</script> +</head> +<body> + +</body> +</html>
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/remote-object.js b/third_party/WebKit/LayoutTests/http/tests/devtools/remote-object.js index 340222d..49545de 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/remote-object.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/remote-object.js
@@ -5,10 +5,7 @@ (async function() { TestRunner.addResult(`Tests formatting of different types of remote objects.\n`); - - function callback(result) { - TestRunner.addResult('date = ' + result.description.substring(0, 25)); - TestRunner.completeTest(); - } - TestRunner.evaluateInPage('new Date(2011, 11, 7, 12, 01)', callback); + var result = await TestRunner.evaluateInPageRemoteObject('new Date(2011, 11, 7, 12, 01)'); + TestRunner.addResult('date = ' + result.description.substring(0, 25)); + TestRunner.completeTest(); })();
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/runtime/runtime-callFunctionOn.js b/third_party/WebKit/LayoutTests/http/tests/devtools/runtime/runtime-callFunctionOn.js index 2c73524e..28101d3 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/runtime/runtime-callFunctionOn.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/runtime/runtime-callFunctionOn.js
@@ -17,7 +17,7 @@ } var result = await TestRunner.RuntimeAgent.callFunctionOn(sum.toString(), obj1.objectId); - TestRunner.addResult(result.value); + TestRunner.addResult(result); next(); }, @@ -31,7 +31,7 @@ var result = await TestRunner.RuntimeAgent.callFunctionOn(format.toString(), obj1.objectId, [obj1, obj2, {value: 4}, {}]); - TestRunner.addResult(result.value); + TestRunner.addResult(result); next(); } ]);
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/screen-orientation-override.js b/third_party/WebKit/LayoutTests/http/tests/devtools/screen-orientation-override.js index a98eb03..d9eda58 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/screen-orientation-override.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/screen-orientation-override.js
@@ -13,7 +13,7 @@ TestRunner.evaluateInPage('dump()', dumpCallback); function dumpCallback(result) { - TestRunner.addResult(result.value); + TestRunner.addResult(result); next(); } } @@ -49,7 +49,7 @@ TestRunner.evaluateInPage('dump()', dumpCallback); function dumpCallback(result) { - original = result.value; + original = result; next(); } }, @@ -94,7 +94,7 @@ } function dumpCallback(result) { - TestRunner.addResult('Equals to initial: ' + (original === result.value ? 'true' : 'false')); + TestRunner.addResult('Equals to initial: ' + (original === result ? 'true' : 'false')); next(); } }
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/service-workers/service-worker-network-fetch-blocked.js b/third_party/WebKit/LayoutTests/http/tests/devtools/service-workers/service-worker-network-fetch-blocked.js index 2f161a67..92e65de 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/service-workers/service-worker-network-fetch-blocked.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/service-workers/service-worker-network-fetch-blocked.js
@@ -19,7 +19,7 @@ ApplicationTestRunner.makeFetchInServiceWorker(scope, '../../network/resources/resource.php', {}, fetchCallback); function fetchCallback(result) { - TestRunner.addResult('Fetch in worker result: ' + result.value); + TestRunner.addResult('Fetch in worker result: ' + result); var requests = NetworkTestRunner.networkRequests(); requests.forEach((request) => {
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/service-workers/service-worker-network-fetch.js b/third_party/WebKit/LayoutTests/http/tests/devtools/service-workers/service-worker-network-fetch.js index c323370..06afa0e 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/service-workers/service-worker-network-fetch.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/service-workers/service-worker-network-fetch.js
@@ -17,7 +17,7 @@ ApplicationTestRunner.makeFetchInServiceWorker(scope, '../../network/resources/resource.php', {}, fetchCallback); function fetchCallback(result) { - TestRunner.addResult('Fetch in worker result: ' + result.value); + TestRunner.addResult('Fetch in worker result: ' + result); var requests = NetworkTestRunner.networkRequests(); requests.forEach((request) => {
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/service-workers/service-workers-bypass-for-network-cors.js b/third_party/WebKit/LayoutTests/http/tests/devtools/service-workers/service-workers-bypass-for-network-cors.js index e55dd28..fa26fb6 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/service-workers/service-workers-bypass-for-network-cors.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/service-workers/service-workers-bypass-for-network-cors.js
@@ -41,7 +41,7 @@ function dumpInterceptedRequests() { return TestRunner.callFunctionInPageAsync('takeInterceptedRequests', [scope]).then((data) => { TestRunner.addResult('Intercepted requests:'); - JSON.parse(data.value).forEach((request) => { + JSON.parse(data).forEach((request) => { TestRunner.addResult(' url: ' + request.url); TestRunner.addResult(' mode: ' + request.mode); }); @@ -52,15 +52,15 @@ TestRunner.addResult('CORS fetch(): ' + index); return TestRunner.callFunctionInPageAsync('fetchInIframe', [target + '?type=txt&fetch' + index, frameId]) .then((data) => { - if (data.value !== 'hello') { - TestRunner.addResult('fetch response miss match: ' + data.value); + if (data !== 'hello') { + TestRunner.addResult('fetch response miss match: ' + data); } TestRunner.addResult('CORS XHR: ' + index); return TestRunner.callFunctionInPageAsync('xhrInIframe', [target + '?type=txt&xhr' + index, frameId]); }) .then((data) => { - if (data.value !== 'hello') { - TestRunner.addResult('XHR response miss match: ' + data.value); + if (data !== 'hello') { + TestRunner.addResult('XHR response miss match: ' + data); } TestRunner.addResult('CORS image: ' + index); return TestRunner.callFunctionInPageAsync('corsImageInIframe', [target + '?type=img&img' + index, frameId]);
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/service-workers/service-workers-bypass-for-network-navigation.js b/third_party/WebKit/LayoutTests/http/tests/devtools/service-workers/service-workers-bypass-for-network-navigation.js index fc6456b..9092596 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/service-workers/service-workers-bypass-for-network-navigation.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/service-workers/service-workers-bypass-for-network-navigation.js
@@ -28,7 +28,7 @@ return TestRunner.callFunctionInPageAsync('getIframeBodyText', [frame_id]); }) .then((data) => { - TestRunner.addResult(' body: ' + data.value); + TestRunner.addResult(' body: ' + data); }); }
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/service-workers/service-workers-redundant.html b/third_party/WebKit/LayoutTests/http/tests/devtools/service-workers/service-workers-redundant.html index a0291b32..fac86f1a 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/service-workers/service-workers-redundant.html +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/service-workers/service-workers-redundant.html
@@ -6,7 +6,7 @@ <script src="../../inspector/console-test.js"></script> <script> -function test() { +async function test() { const scriptURL = 'http://127.0.0.1:8000/devtools/service-workers/resources/changing-worker.php'; const scope = 'http://127.0.0.1:8000/devtools/service-workers/resources/service-worker-redundant-scope/'; const frameId = 'frame_id'; @@ -15,58 +15,57 @@ let secondVersionId = -1; Resources.ServiceWorkersView._noThrottle = true; - TestRunner.evaluateInPage('frontendReopeningCount', function(result) { - if (result._description == '0') { - TestRunner.addSniffer(Resources.ServiceWorkersView.prototype, '_updateRegistration', updateRegistration, true); - function updateRegistration(registration) { - if (registration.scopeURL != scope) - return; - for (let version of registration.versions.values()) { - if (step == 0 && version.isRunning() && version.isActivated()) { - ++step; - firstVersionId = version.id; - TestRunner.addResult('The first ServiceWorker is activated.'); - TestRunner.addResult('==== ServiceWorkersView ===='); - TestRunner.addResult(ApplicationTestRunner.dumpServiceWorkersView([scope])); - TestRunner.addResult('============================'); - TestRunner.addIframe(scope, {id: frameId}); - } else if (step == 1 && version.isRunning() && version.isInstalled()) { - ++step; - secondVersionId = version.id; - TestRunner.addResult('The second Serviceworker is installed.'); - TestRunner.addResult('==== ServiceWorkersView ===='); - TestRunner.addResult(ApplicationTestRunner.dumpServiceWorkersView([scope])); - TestRunner.addResult('============================'); - TestRunner.evaluateInPagePromise(`document.getElementById('${frameId}').remove();`); - } - } - if (step != 2) - return; - const firstVersion = registration.versions.get(firstVersionId); - const secondVersion = registration.versions.get(secondVersionId); - if ((!firstVersion || (firstVersion.isStopped() && firstVersion.isRedundant())) && - secondVersion.isActivated() && secondVersion.isRunning()) { + var result = await TestRunner.evaluateInPageRemoteObject('frontendReopeningCount'); + if (result._description == '0') { + TestRunner.addSniffer(Resources.ServiceWorkersView.prototype, '_updateRegistration', updateRegistration, true); + function updateRegistration(registration) { + if (registration.scopeURL != scope) + return; + for (let version of registration.versions.values()) { + if (step == 0 && version.isRunning() && version.isActivated()) { ++step; - TestRunner.addResult('The first ServiceWorker worker became redundant and stopped.'); + firstVersionId = version.id; + TestRunner.addResult('The first ServiceWorker is activated.'); TestRunner.addResult('==== ServiceWorkersView ===='); TestRunner.addResult(ApplicationTestRunner.dumpServiceWorkersView([scope])); TestRunner.addResult('============================'); - TestRunner.flushResults(); - TestRunner.evaluateInPage('reopenFrontend()'); + TestRunner.addIframe(scope, {id: frameId}); + } else if (step == 1 && version.isRunning() && version.isInstalled()) { + ++step; + secondVersionId = version.id; + TestRunner.addResult('The second Serviceworker is installed.'); + TestRunner.addResult('==== ServiceWorkersView ===='); + TestRunner.addResult(ApplicationTestRunner.dumpServiceWorkersView([scope])); + TestRunner.addResult('============================'); + TestRunner.evaluateInPagePromise(`document.getElementById('${frameId}').remove();`); } } - UI.panels.resources._sidebar.serviceWorkersTreeElement.select(); - ApplicationTestRunner.registerServiceWorker(scriptURL, scope); - } else { - TestRunner.addResult('DevTools frontend is reopened.'); - UI.panels.resources._sidebar.serviceWorkersTreeElement.select(); - TestRunner.addResult('==== ServiceWorkersView ===='); - TestRunner.addResult(ApplicationTestRunner.dumpServiceWorkersView([scope])); - TestRunner.addResult('============================'); - ApplicationTestRunner.deleteServiceWorkerRegistration(scope); - TestRunner.completeTest(); + if (step != 2) + return; + const firstVersion = registration.versions.get(firstVersionId); + const secondVersion = registration.versions.get(secondVersionId); + if ((!firstVersion || (firstVersion.isStopped() && firstVersion.isRedundant())) && + secondVersion.isActivated() && secondVersion.isRunning()) { + ++step; + TestRunner.addResult('The first ServiceWorker worker became redundant and stopped.'); + TestRunner.addResult('==== ServiceWorkersView ===='); + TestRunner.addResult(ApplicationTestRunner.dumpServiceWorkersView([scope])); + TestRunner.addResult('============================'); + TestRunner.flushResults(); + TestRunner.evaluateInPage('reopenFrontend()'); + } } - }); + UI.panels.resources._sidebar.serviceWorkersTreeElement.select(); + ApplicationTestRunner.registerServiceWorker(scriptURL, scope); + } else { + TestRunner.addResult('DevTools frontend is reopened.'); + UI.panels.resources._sidebar.serviceWorkersTreeElement.select(); + TestRunner.addResult('==== ServiceWorkersView ===='); + TestRunner.addResult(ApplicationTestRunner.dumpServiceWorkersView([scope])); + TestRunner.addResult('============================'); + ApplicationTestRunner.deleteServiceWorkerRegistration(scope); + TestRunner.completeTest(); + } } </script>
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/sources/debugger-frameworks/frameworks-jquery.js b/third_party/WebKit/LayoutTests/http/tests/devtools/sources/debugger-frameworks/frameworks-jquery.js index a663cb2..eb8c235c 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/sources/debugger-frameworks/frameworks-jquery.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/sources/debugger-frameworks/frameworks-jquery.js
@@ -79,7 +79,7 @@ async function step4() { const output = await TestRunner.evaluateInPageAsync('JSON.stringify(self._output)'); - TestRunner.addResults(JSON.parse(output.value)); + TestRunner.addResults(JSON.parse(output)); TestRunner.completeTest(); } })();
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/sources/debugger-step/debugger-step-into-custom-element-callbacks.js b/third_party/WebKit/LayoutTests/http/tests/devtools/sources/debugger-step/debugger-step-into-custom-element-callbacks.js index 169c9adc..db830003f 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/sources/debugger-step/debugger-step-into-custom-element-callbacks.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/sources/debugger-step/debugger-step-into-custom-element-callbacks.js
@@ -110,7 +110,7 @@ async function step10() { const output = await TestRunner.evaluateInPageAsync('JSON.stringify(self._output)'); - TestRunner.addResults(JSON.parse(output.value)); + TestRunner.addResults(JSON.parse(output)); TestRunner.completeTest(); } })();
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/sources/debugger-step/debugger-step-out-custom-element-callbacks.js b/third_party/WebKit/LayoutTests/http/tests/devtools/sources/debugger-step/debugger-step-out-custom-element-callbacks.js index fbb0d1b..84d95aa 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/sources/debugger-step/debugger-step-out-custom-element-callbacks.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/sources/debugger-step/debugger-step-out-custom-element-callbacks.js
@@ -72,7 +72,7 @@ async function step4() { const output = await TestRunner.evaluateInPageAsync('JSON.stringify(self._output)'); - TestRunner.addResults(JSON.parse(output.value)); + TestRunner.addResults(JSON.parse(output)); TestRunner.completeTest(); } })();
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/sources/debugger-ui/custom-element-lifecycle-events.js b/third_party/WebKit/LayoutTests/http/tests/devtools/sources/debugger-ui/custom-element-lifecycle-events.js index 7a5dd431..2cf145e2 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/sources/debugger-ui/custom-element-lifecycle-events.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/sources/debugger-ui/custom-element-lifecycle-events.js
@@ -59,7 +59,7 @@ async function step6() { const output = await TestRunner.evaluateInPageAsync('JSON.stringify(self._output)'); - TestRunner.addResults(JSON.parse(output.value)); + TestRunner.addResults(JSON.parse(output)); TestRunner.completeTest(); } })();
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/sources/debugger-ui/function-details.js b/third_party/WebKit/LayoutTests/http/tests/devtools/sources/debugger-ui/function-details.js index 78f8b93..d7e5727f 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/sources/debugger-ui/function-details.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/sources/debugger-ui/function-details.js
@@ -117,28 +117,26 @@ end(); } - function performStandardTestCase(pageExpression, next) { - TestRunner.evaluateInPage(pageExpression, didEvaluate); + async function performStandardTestCase(pageExpression, next) { + var remote = await TestRunner.evaluateInPageRemoteObject(pageExpression); - async function didEvaluate(remote) { - TestRunner.addResult(pageExpression + ' type = ' + remote.type); - var response = - await TestRunner.RuntimeAgent.invoke_getProperties({objectId: remote.objectId, isOwnProperty: false}); + TestRunner.addResult(pageExpression + ' type = ' + remote.type); + var response = + await TestRunner.RuntimeAgent.invoke_getProperties({objectId: remote.objectId, isOwnProperty: false}); - var propertiesMap = new Map(); - for (var prop of response.internalProperties) - propertiesMap.set(prop.name, prop); - for (var prop of response.result) { - if (prop.name === 'name' && prop.value && prop.value.type === 'string') - propertiesMap.set('name', prop); - if (prop.name === 'displayName' && prop.value && prop.value.type === 'string') { - propertiesMap.set('name', prop); - break; - } + var propertiesMap = new Map(); + for (var prop of response.internalProperties) + propertiesMap.set(prop.name, prop); + for (var prop of response.result) { + if (prop.name === 'name' && prop.value && prop.value.type === 'string') + propertiesMap.set('name', prop); + if (prop.name === 'displayName' && prop.value && prop.value.type === 'string') { + propertiesMap.set('name', prop); + break; } - dumpFunctionDetails(propertiesMap); - loadAndDumpScopeObjects(propertiesMap.get('[[Scopes]]'), next); } + dumpFunctionDetails(propertiesMap); + loadAndDumpScopeObjects(propertiesMap.get('[[Scopes]]'), next); } SourcesTestRunner.runDebuggerTestSuite([
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/sources/debugger-ui/show-generator-location.js b/third_party/WebKit/LayoutTests/http/tests/devtools/sources/debugger-ui/show-generator-location.js index edba53c2..3add889 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/sources/debugger-ui/show-generator-location.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/sources/debugger-ui/show-generator-location.js
@@ -35,13 +35,11 @@ var panel = UI.panels.sources; - function performStandardTestCase(pageExpression, next) { + async function performStandardTestCase(pageExpression, next) { TestRunner.addSniffer(panel, 'showUISourceCode', showUISourceCodeHook); - TestRunner.evaluateInPage(pageExpression, didEvaluate); + var remote = await TestRunner.evaluateInPageRemoteObject(pageExpression); - function didEvaluate(remote) { - remote.getOwnPropertiesPromise().then(revealLocation.bind(null, remote)); - } + remote.getOwnPropertiesPromise().then(revealLocation.bind(null, remote)); function revealLocation(remote, properties) { var loc;
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/sources/debugger/debug-inlined-scripts-fragment-id.js b/third_party/WebKit/LayoutTests/http/tests/devtools/sources/debugger/debug-inlined-scripts-fragment-id.js index 4532a3e..26db448 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/sources/debugger/debug-inlined-scripts-fragment-id.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/sources/debugger/debug-inlined-scripts-fragment-id.js
@@ -17,7 +17,7 @@ } function step1(loc) { - TestRunner.addResult('window.location: ' + loc.description); + TestRunner.addResult('window.location: ' + loc); SourcesTestRunner.showScriptSource('inline-scripts.html', step2); }
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/sources/debugger/live-edit.js b/third_party/WebKit/LayoutTests/http/tests/devtools/sources/debugger/live-edit.js index aa48537..716a56c 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/sources/debugger/live-edit.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/sources/debugger/live-edit.js
@@ -22,11 +22,8 @@ didEditScriptSource); } - function didEditScriptSource() { - TestRunner.evaluateInPage('f()', didEvaluateInPage); - } - - function didEvaluateInPage(result) { + async function didEditScriptSource() { + var result = await TestRunner.evaluateInPageRemoteObject('f()'); TestRunner.assertEquals( 'live-edited string', result.description, 'edited function returns wrong result'); @@ -52,9 +49,12 @@ SourcesTestRunner.showScriptSource( 'edit-me-when-paused.js', didShowScriptSource); - function didShowScriptSource(sourceFrame) { + async function didShowScriptSource(sourceFrame) { SourcesTestRunner.waitUntilPaused(paused); - TestRunner.evaluateInPage('f1()', didEvaluateInPage); + var result = await TestRunner.evaluateInPageRemoteObject('f1()'); + TestRunner.assertEquals( + '3', result.description, 'edited function returns wrong result'); + next(); } function paused(callFrames) { @@ -66,12 +66,6 @@ function didEditScriptSource() { SourcesTestRunner.resumeExecution(); } - - function didEvaluateInPage(result) { - TestRunner.assertEquals( - '3', result.description, 'edited function returns wrong result'); - next(); - } }, function testNoCrashWhenOnlyOneFunctionOnStack(next) {
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/startup/console/console-format-startup.html b/third_party/WebKit/LayoutTests/http/tests/devtools/startup/console/console-format-startup.html index 608a815c..6a00daf 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/startup/console/console-format-startup.html +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/startup/console/console-format-startup.html
@@ -300,10 +300,10 @@ } </script> <script> -function test() { +async function test() { TestRunner.hideInspectorView(); - TestRunner.evaluateInPage('globals.length', loopOverGlobals.bind(this, 0)); - + var total = await TestRunner.evaluateInPageRemoteObject('globals.length'); + loopOverGlobals(0, total); function loopOverGlobals(current, total) { function advance() { var next = current + 1;
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/startup/injected-script-discard.html b/third_party/WebKit/LayoutTests/http/tests/devtools/startup/injected-script-discard.html index ff5ed52..bf365e0 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/startup/injected-script-discard.html +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/startup/injected-script-discard.html
@@ -27,23 +27,23 @@ var result = await TestRunner.RuntimeAgent.evaluate('window.objectId'); if (result.type !== 'string') { - TestRunner.evaluateInPage('console.log(\'Opening front-end for the first time\')'); + TestRunner.evaluateInPageAnonymously('console.log(\'Opening front-end for the first time\')'); result = await TestRunner.RuntimeAgent.evaluate(`({ handle : "handle" })`); checkHandleInInjectedScript(result.objectId, reopenInspector); } else { - TestRunner.evaluateInPage('console.log(\'Opening front-end second time\')'); + TestRunner.evaluateInPageAnonymously('console.log(\'Opening front-end second time\')'); checkHandleInInjectedScript(result.value, TestRunner.completeTest); } function reopenInspector() { - TestRunner.evaluateInPage('reopenWebInspector(\'' + escape(result.objectId) + '\')'); + TestRunner.evaluateInPageAnonymously('reopenWebInspector(\'' + escape(result.objectId) + '\')'); } async function checkHandleInInjectedScript(objectId, callback) { var properties = await TestRunner.RuntimeAgent.getProperties(objectId, false); - TestRunner.evaluateInPage( - !properties ? 'console.log(\'Error resolving object\')' : 'console.log(\'Resolved object successfully\')', - callback); + var result = await TestRunner.evaluateInPageRemoteObject( + !properties ? 'console.log(\'Error resolving object\')' : 'console.log(\'Resolved object successfully\')'); + callback(result); } }
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/text-autosizing-override.js b/third_party/WebKit/LayoutTests/http/tests/devtools/text-autosizing-override.js index b4864c7..123ca29 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/text-autosizing-override.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/text-autosizing-override.js
@@ -23,7 +23,7 @@ function assertAutosizingResult(expected, callback) { function resultCallback(jsonResult) { - var result = JSON.parse(jsonResult.value); + var result = JSON.parse(jsonResult); var actual = result.textHeight > 200; TestRunner.addResult( 'Text ' + (actual ? 'was' : 'was not') + ' autosized. ' + (expected == actual ? 'PASS' : 'FAIL'));
diff --git a/third_party/WebKit/LayoutTests/http/tests/devtools/user-agent-setting.js b/third_party/WebKit/LayoutTests/http/tests/devtools/user-agent-setting.js index df46b10..9fce0c6 100644 --- a/third_party/WebKit/LayoutTests/http/tests/devtools/user-agent-setting.js +++ b/third_party/WebKit/LayoutTests/http/tests/devtools/user-agent-setting.js
@@ -23,7 +23,7 @@ TestRunner.evaluateInPage('navigator.userAgent', step2); function step2(result) { - TestRunner.addResult(result.value); + TestRunner.addResult(result); TestRunner.completeTest(); } })();
diff --git a/third_party/WebKit/LayoutTests/http/tests/inspector/inspector-test.js b/third_party/WebKit/LayoutTests/http/tests/inspector/inspector-test.js index ad26ba1..322aea3f 100644 --- a/third_party/WebKit/LayoutTests/http/tests/inspector/inspector-test.js +++ b/third_party/WebKit/LayoutTests/http/tests/inspector/inspector-test.js
@@ -50,7 +50,20 @@ objectGroup: "console" }); if (!response[Protocol.Error]) - InspectorTest.safeWrap(callback)(InspectorTest.runtimeModel.createRemoteObject(response.result), response.exceptionDetails); + InspectorTest.safeWrap(callback)(response.result.value, response.exceptionDetails); +} + +/** + * TestRunner.evaluateInPageRemoteObject inserts sourceURL by inspecting the call stack. + */ +InspectorTest.evaluateInPageRemoteObject = async function(code, callback) +{ + var response = await InspectorTest.RuntimeAgent.invoke_evaluate({ + expression: code, + objectGroup: "console" + }); + if (!response[Protocol.Error]) + return InspectorTest.runtimeModel.createRemoteObject(response.result); } InspectorTest.addResult = function(text)
diff --git a/third_party/WebKit/LayoutTests/http/tests/notifications/request-permission-detached-context.html b/third_party/WebKit/LayoutTests/http/tests/notifications/request-permission-detached-context.html index 7857c21..49c2e7e 100644 --- a/third_party/WebKit/LayoutTests/http/tests/notifications/request-permission-detached-context.html +++ b/third_party/WebKit/LayoutTests/http/tests/notifications/request-permission-detached-context.html
@@ -26,7 +26,7 @@ win.close(); } else if (event.data == 'closed') { - assert_equals(notificationObj.permission, 'granted'); + assert_equals(notificationObj.permission, 'denied'); notificationObj.requestPermission(function () {}); test.done();
diff --git a/third_party/WebKit/LayoutTests/http/tests/security/cannot-read-cssrules-expected.txt b/third_party/WebKit/LayoutTests/http/tests/security/cannot-read-cssrules-expected.txt deleted file mode 100644 index 7a78bab..0000000 --- a/third_party/WebKit/LayoutTests/http/tests/security/cannot-read-cssrules-expected.txt +++ /dev/null
@@ -1,10 +0,0 @@ -This test whether a script can read the rules from a cross-origin style sheet. For more information on why we block this, please see https://bugs.webkit.org/show_bug.cgi?id=20527. - -Test begins. -== Cross-Origin == -cssRules: null -rules: null -== Same-Origin == -cssRules: [object CSSRuleList] -rules: [object CSSRuleList] -Test ends.
diff --git a/third_party/WebKit/LayoutTests/http/tests/security/cannot-read-cssrules-redirect-expected.txt b/third_party/WebKit/LayoutTests/http/tests/security/cannot-read-cssrules-redirect-expected.txt deleted file mode 100644 index 062646f..0000000 --- a/third_party/WebKit/LayoutTests/http/tests/security/cannot-read-cssrules-redirect-expected.txt +++ /dev/null
@@ -1,10 +0,0 @@ -This test whether a script can read the rules from a cross-origin style sheet in the presence of redirects. For more information on why we block this, please see https://bugs.webkit.org/show_bug.cgi?id=20527. - -Test begins. -== Same-Origin to Cross-Origin == -cssRules: null -rules: null -== Cross-Origin to Same-Origin == -cssRules: [object CSSRuleList] -rules: [object CSSRuleList] -Test ends.
diff --git a/third_party/WebKit/LayoutTests/http/tests/security/cannot-read-cssrules-redirect.html b/third_party/WebKit/LayoutTests/http/tests/security/cannot-read-cssrules-redirect.html index 1cdc3d01..0bc45ca 100644 --- a/third_party/WebKit/LayoutTests/http/tests/security/cannot-read-cssrules-redirect.html +++ b/third_party/WebKit/LayoutTests/http/tests/security/cannot-read-cssrules-redirect.html
@@ -1,32 +1,30 @@ <!DOCTYPE html> <html> <head> +<script src="../../../resources/testharness.js"></script> +<script src="../../../resources/testharnessreport.js"></script> <link rel="stylesheet" href="resources/redir.php?url=http://localhost:8000/security/resources/cssStyle.css"> <link rel="stylesheet" href="http://localhost:8000/security/resources/redir.php?url=http://127.0.0.1:8000/security/resources/cssStyle.css"> <script> -if (window.testRunner) - testRunner.dumpAsText(); -function log(msg) { - var div = document.createElement("div"); - div.textContent = msg; - document.getElementById("console").appendChild(div); -} +test(() => { + var sheet1 = document.styleSheets[0]; + assert_throws("SecurityError", () => { + sheet1.cssRules; + }); + assert_throws("SecurityError", () => { + sheet1.rules; + }); +}, "Can't access Cross-Origin sheets that were redirected to from Same-Origin"); -window.onload = function() { - log("Test begins."); - log("== Same-Origin to Cross-Origin =="); - var sheet1 = document.styleSheets[0]; - log("cssRules: " + sheet1.cssRules); - log("rules: " + sheet1.rules); - log("== Cross-Origin to Same-Origin =="); - var sheet2 = document.styleSheets[1]; - log("cssRules: " + sheet2.cssRules); - log("rules: " + sheet2.rules); - log("Test ends."); -} +test(() => { + var sheet2 = document.styleSheets[1]; + assert_not_equals(sheet2.cssRules, null); + assert_not_equals(sheet2.rules, null); +}, "Can access Same-Origin sheets that were redirected to from Cross-Origin"); + </script> </head> <body> @@ -35,6 +33,5 @@ this, please see <a href="https://bugs.webkit.org/show_bug.cgi?id=20527">https://bugs.webkit.org/show_bug.cgi?id=20527</a>. </p> -<div id="console"></div> </body> </html>
diff --git a/third_party/WebKit/LayoutTests/http/tests/security/cannot-read-cssrules.html b/third_party/WebKit/LayoutTests/http/tests/security/cannot-read-cssrules.html index 626092bd..45d8170 100644 --- a/third_party/WebKit/LayoutTests/http/tests/security/cannot-read-cssrules.html +++ b/third_party/WebKit/LayoutTests/http/tests/security/cannot-read-cssrules.html
@@ -1,31 +1,29 @@ <!DOCTYPE html> <html> <head> +<script src="../../../resources/testharness.js"></script> +<script src="../../../resources/testharnessreport.js"></script> <link rel="stylesheet" href="http://localhost:8000/security/resources/cssStyle.css"> <link rel="stylesheet" href="resources/cssStyle.css"> <script> -if (window.testRunner) - testRunner.dumpAsText(); -function log(msg) { - var div = document.createElement("div"); - div.textContent = msg; - document.getElementById("console").appendChild(div); -} +test(() => { + var sheet1 = document.styleSheets[0]; + assert_throws("SecurityError", () => { + sheet1.cssRules; + }); + assert_throws("SecurityError", () => { + sheet1.rules; + }); +}, "Can't access Cross-Origin sheets"); -window.onload = function() { - log("Test begins."); - log("== Cross-Origin =="); - var sheet1 = document.styleSheets[0]; - log("cssRules: " + sheet1.cssRules); - log("rules: " + sheet1.rules); - log("== Same-Origin =="); - var sheet2 = document.styleSheets[1]; - log("cssRules: " + sheet2.cssRules); - log("rules: " + sheet2.rules); - log("Test ends."); -} +test(() => { + var sheet2 = document.styleSheets[1]; + assert_not_equals(sheet2.cssRules, null); + assert_not_equals(sheet2.rules, null); +}, "Can access Same-Origin sheets"); + </script> </head> <body> @@ -33,6 +31,5 @@ sheet. For more information on why we block this, please see <a href="https://bugs.webkit.org/show_bug.cgi?id=20527">https://bugs.webkit.org/show_bug.cgi?id=20527</a>. </p> -<div id="console"></div> </body> </html>
diff --git a/third_party/WebKit/LayoutTests/http/tests/security/suborigins/suborigin-cssRules.php b/third_party/WebKit/LayoutTests/http/tests/security/suborigins/suborigin-cssRules.php index 9f0d002..8c86ba9 100644 --- a/third_party/WebKit/LayoutTests/http/tests/security/suborigins/suborigin-cssRules.php +++ b/third_party/WebKit/LayoutTests/http/tests/security/suborigins/suborigin-cssRules.php
@@ -11,11 +11,13 @@ <link rel="stylesheet" href="/security/resources/cssStyle.css"></link> </head> <script> -window.onload = function() { + +test(() => { var sheet = document.styleSheets[0]; - assert_equals(sheet.cssRules, null, - 'stylesheet rules should not be readable from a suborigin'); - done(); -}; + assert_throws("SecurityError", () => { + sheet.cssRules; + }); +}, "stylesheet rules should not be readable from a suborigin"); + </script> </html>
diff --git a/third_party/WebKit/LayoutTests/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt b/third_party/WebKit/LayoutTests/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt index d39a255..fb14276 100644 --- a/third_party/WebKit/LayoutTests/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt +++ b/third_party/WebKit/LayoutTests/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt
@@ -31,7 +31,6 @@ getter downloaded getter id getter onprogress - getter title getter totalDownloadSize getter uploadTotal getter uploaded
diff --git a/third_party/WebKit/LayoutTests/images/color-profile-mask-image-svg-expected.png b/third_party/WebKit/LayoutTests/images/color-profile-mask-image-svg-expected.png index 5757dc6a..5a804fa 100644 --- a/third_party/WebKit/LayoutTests/images/color-profile-mask-image-svg-expected.png +++ b/third_party/WebKit/LayoutTests/images/color-profile-mask-image-svg-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/images/resources/crbug779261.gif b/third_party/WebKit/LayoutTests/images/resources/crbug779261.gif new file mode 100644 index 0000000..4a7abd3 --- /dev/null +++ b/third_party/WebKit/LayoutTests/images/resources/crbug779261.gif Binary files differ
diff --git a/third_party/WebKit/LayoutTests/installedapp/idl.html b/third_party/WebKit/LayoutTests/installedapp/idl.html index 4111fe73..0a9b819 100644 --- a/third_party/WebKit/LayoutTests/installedapp/idl.html +++ b/third_party/WebKit/LayoutTests/installedapp/idl.html
@@ -2,7 +2,7 @@ <link rel="help" href="https://github.com/WICG/get-installed-related-apps/blob/master/EXPLAINER.md"> <script src=../resources/testharness.js></script> <script src=../resources/testharnessreport.js></script> -<script src=../resources/WebIDLParser.js></script> +<script src=../resources/webidl2.js></script> <script src=../resources/idlharness.js></script> <script type="text/plain" id="untested"> interface Navigator {
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/media/white.mp4 b/third_party/WebKit/LayoutTests/media/content/white.mp4 similarity index 100% rename from third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/media/white.mp4 rename to third_party/WebKit/LayoutTests/media/content/white.mp4 Binary files differ
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/media/white.webm b/third_party/WebKit/LayoutTests/media/content/white.webm similarity index 100% rename from third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/media/white.webm rename to third_party/WebKit/LayoutTests/media/content/white.webm Binary files differ
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/adhoc/support/12345_timestamps.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/adhoc/support/12345_timestamps.vtt deleted file mode 100644 index 4abdb04..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/adhoc/support/12345_timestamps.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:10.000 -<b>1</b><00:01.000> <b>2</b><00:02.000> <b>3</b><00:03.000> <b>4</b><00:04.000> <b>5</b><00:05.000> <b>6</b><00:06.000> <b>7</b><00:07.000> <b>8</b><00:08.000> <b>9</b><00:09.000> <b>10</b><00:10.000>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/adhoc/support/class.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/adhoc/support/class.vtt deleted file mode 100644 index 10948e6..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/adhoc/support/class.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 -<c>This cue should not change font size</c>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/adhoc/support/voice_with_evil_timestamp.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/adhoc/support/voice_with_evil_timestamp.vtt deleted file mode 100644 index 99f4937..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/adhoc/support/voice_with_evil_timestamp.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:10.000 -<00:00.000><v>This is a test subtitle</v><00:00.001>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/2_cues_overlapping_completely_move_up-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/2_cues_overlapping_completely_move_up-ref.html deleted file mode 100644 index cdffd4e4..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/2_cues_overlapping_completely_move_up-ref.html +++ /dev/null
@@ -1,36 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, repositioning (up) when 2 cues overlap completely</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -#cue1 { - position: absolute; - top: 50%; - left: 0; - right: 0; - margin-top: -18px; - text-align: center -} -#cue2 { - position: absolute; - top: 50%; - left: 0; - right: 0; - margin-top: -54px; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px; -} -</style> -<div class="video"><span class="cue" id="cue1"><span>This is a test subtitle</span></span><span class="cue" id="cue2"><span>This is another test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/2_cues_overlapping_completely_move_up.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/2_cues_overlapping_completely_move_up.html deleted file mode 100644 index c6c3615..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/2_cues_overlapping_completely_move_up.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, repositioning (up) when 2 cues overlap completely</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); this.currentTime = 2;" onseeked="this.onseeked = null; takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src="support/2_cues_overlapping_completely_move_up.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/2_cues_overlapping_partially_move_down-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/2_cues_overlapping_partially_move_down-ref.html deleted file mode 100644 index 1860fed..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/2_cues_overlapping_partially_move_down-ref.html +++ /dev/null
@@ -1,36 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, repositioning (down) when 2 cues overlap partially</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -#cue1 { - position: absolute; - top: 50%; - left: 0; - right: 0; - margin-top: -18px; - text-align: center -} -#cue2 { - position: absolute; - top: 50%; - left: 0; - right: 0; - margin-top: 18px; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px; -} -</style> -<div class="video"><span class="cue" id="cue1"><span>This is a test subtitle</span></span><span class="cue" id="cue2"><span>This is another test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/2_cues_overlapping_partially_move_down.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/2_cues_overlapping_partially_move_down.html deleted file mode 100644 index a1fb0fd..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/2_cues_overlapping_partially_move_down.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, repositioning (down) when 2 cues overlap partially</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); this.currentTime = 2;" onseeked="this.onseeked = null; takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src="support/2_cues_overlapping_partially_move_down.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/2_cues_overlapping_partially_move_up-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/2_cues_overlapping_partially_move_up-ref.html deleted file mode 100644 index bcae5ac2..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/2_cues_overlapping_partially_move_up-ref.html +++ /dev/null
@@ -1,36 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, repositioning (down) when 2 cues overlap partially</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -#cue1 { - position: absolute; - top: 50%; - left: 0; - right: 0; - margin-top: -18px; - text-align: center -} -#cue2 { - position: absolute; - top: 50%; - left: 0; - right: 0; - margin-top: -54px; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px; -} -</style> -<div class="video"><span class="cue" id="cue1"><span>This is a test subtitle</span></span><span class="cue" id="cue2"><span>This is another test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/2_cues_overlapping_partially_move_up.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/2_cues_overlapping_partially_move_up.html deleted file mode 100644 index 59fc43e9..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/2_cues_overlapping_partially_move_up.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, repositioning (down) when 2 cues overlap partially</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); this.currentTime = 2;" onseeked="this.onseeked = null; takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src="support/2_cues_overlapping_partially_move_up.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/2_tracks-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/2_tracks-ref.html deleted file mode 100644 index f0f4504..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/2_tracks-ref.html +++ /dev/null
@@ -1,26 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, 2 tracks enabled at the same time</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - font-size: 36px; -} -</style> -<div class="video"><span class="cue"><span>This is a <u>test subtitle</u><br>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/2_tracks.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/2_tracks.html deleted file mode 100644 index 853503d1..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/2_tracks.html +++ /dev/null
@@ -1,19 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, 2 tracks enabled at the same time</title> -<style> -html { overflow:hidden } -body { margin:0 } -</style> -<script src="support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src="support/test.vtt"> - <track src="support/test_underline.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -document.getElementsByTagName('track')[1].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/3_tracks-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/3_tracks-ref.html deleted file mode 100644 index 9fdd7b1..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/3_tracks-ref.html +++ /dev/null
@@ -1,26 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, 3 tracks enabled at the same time</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - font-size: 36px; -} -</style> -<div class="video"><span class="cue"><span>This is a <b>test subtitle</b><br>This is a <u>test subtitle</u><br>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/3_tracks.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/3_tracks.html deleted file mode 100644 index 6e1fa78b..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/3_tracks.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, 3 tracks enabled at the same time</title> -<style> -html { overflow:hidden } -body { margin:0 } -</style> -<script src="support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src="support/test.vtt"> - <track src="support/test_underline.vtt"> - <track src="support/test_bold.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -document.getElementsByTagName('track')[1].track.mode = 'showing'; -document.getElementsByTagName('track')[2].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_end-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_end-ref.html deleted file mode 100644 index 143291d..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_end-ref.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, align:end</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - width: 50%; - text-align: right; -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px -} -</style> -<div class=video><span class=cue><span>This is a test</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_end.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_end.html deleted file mode 100644 index a6eb11b..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_end.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, align:end</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src="support/align_end.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_end_wrapped-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_end_wrapped-ref.html deleted file mode 100644 index a7636dc..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_end_wrapped-ref.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, align:end with long cues</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - width: 50%; - text-align: right -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px -} -</style> -<div class=video><span class=cue><span>This is a test <br>subtitle that <br>most likely <br>will span over <br>several rows <br>since it is a <br>pretty long <br>cue with a <br>lot of text.</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_end_wrapped.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_end_wrapped.html deleted file mode 100644 index ee9ae58..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_end_wrapped.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, align:end with long cues</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src="support/align_end_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle-ref.html deleted file mode 100644 index ce19e1f..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, align:middle</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center; -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px -} -</style> -<div class=video><span class=cue><span>This is a test</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle.html deleted file mode 100644 index a52fd906..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, align:middle</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src="support/align_middle.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle_position_50-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle_position_50-ref.html deleted file mode 100644 index 5ad4a4ae..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle_position_50-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, align:middle, position:50%</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center; -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px -} -</style> -<div class=video><span class=cue><span>This is a test</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle_position_50.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle_position_50.html deleted file mode 100644 index 8813b0ba..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle_position_50.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, align:middle, position:50%</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src="support/align_middle_position_50.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle_position_gt_50-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle_position_gt_50-ref.html deleted file mode 100644 index 9f382ae..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle_position_gt_50-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, align:middle, position greater than 50%</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - right: 92px; - width: 256px; - text-align: center; -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px -} -</style> -<div class=video><span class=cue><span>Aweso<br>me!!!</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle_position_gt_50.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle_position_gt_50.html deleted file mode 100644 index a33ac51..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle_position_gt_50.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, align:middle, position greater than 50%</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src="support/align_middle_position_gt_50.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle_position_lt_50-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle_position_lt_50-ref.html deleted file mode 100644 index 66383b3..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle_position_lt_50-ref.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, align:middle, position less than 50%</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 92px; - right: 0; - width: 256px; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px -} -</style> -<div class=video><span class=cue><span>Awesome<br>!!!</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle_position_lt_50.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle_position_lt_50.html deleted file mode 100644 index e12b93e..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle_position_lt_50.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, align:middle, position less than 50%</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src="support/align_middle_position_lt_50.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle_position_lt_50_size_gt_maximum_size-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle_position_lt_50_size_gt_maximum_size-ref.html deleted file mode 100644 index 06d6bff..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle_position_lt_50_size_gt_maximum_size-ref.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, align:middle, position less than 50%, size greater than maximum size</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 92px; - right: 0; - width: 256px; - text-align: center; -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px -} -</style> -<div class=video><span class=cue><span>Aweso<br>me!!!</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle_position_lt_50_size_gt_maximum_size.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle_position_lt_50_size_gt_maximum_size.html deleted file mode 100644 index afed5c4b..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle_position_lt_50_size_gt_maximum_size.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, align:middle, position less than 50%, size greater than maximum size</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src="support/align_middle_position_lt_50_size_gt_maximum_size.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle_wrapped-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle_wrapped-ref.html deleted file mode 100644 index c306537..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle_wrapped-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, align:middle with long cues</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center; -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px -} -</style> -<div class=video><span class=cue><span>This is a test subtitle that <br>most likely will span over <br>several rows since it is a pretty <br>long cue with a lot of text.</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle_wrapped.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle_wrapped.html deleted file mode 100644 index 56864c4..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_middle_wrapped.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, align:middle with long cues</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src="support/align_middle_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_start-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_start-ref.html deleted file mode 100644 index 8ca2388..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_start-ref.html +++ /dev/null
@@ -1,26 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, align:start</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 50%; - right: 0; -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px -} -</style> -<div class=video><span class=cue><span>This is a test</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_start.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_start.html deleted file mode 100644 index f6e697c..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_start.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, align:start</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src="support/align_start.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_start_wrapped-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_start_wrapped-ref.html deleted file mode 100644 index 2e81135d..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_start_wrapped-ref.html +++ /dev/null
@@ -1,26 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, align:start with long cues</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 50%; - right: 0; -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px -} -</style> -<div class=video><span class=cue><span>This is a test <br>subtitle that <br>most likely <br>will span over <br>several rows <br>since it is a <br>pretty long <br>cue with a <br>lot of text.</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_start_wrapped.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_start_wrapped.html deleted file mode 100644 index 00c2dc5a..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/align_start_wrapped.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, align:start with long cues</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src="support/align_start_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/audio_has_no_subtitles-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/audio_has_no_subtitles-ref.html deleted file mode 100644 index b647a24..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/audio_has_no_subtitles-ref.html +++ /dev/null
@@ -1,15 +0,0 @@ -<!DOCTYPE html> -<html> -<title>Reference for WebVTT rendering, <audio> should not have subtitles</title> -<style> -audio { - width: 1280px; - height: 720px; - outline: solid -} -</style> -<script src="support/refTestWait.js"></script> -<audio autoplay controls onplaying="this.onplaying = null; this.pause(); this.currentTime = 0; takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> -</audio>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/audio_has_no_subtitles.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/audio_has_no_subtitles.html deleted file mode 100644 index a7abad66..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/audio_has_no_subtitles.html +++ /dev/null
@@ -1,25 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, <audio> should not have subtitles</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -audio { - width: 1280px; - height: 720px; - outline: solid -} -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="support/refTestWait.js"></script> -<audio autoplay controls onplaying="this.onplaying = null; this.pause(); this.currentTime = 0; takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src="support/test.vtt"> -</audio> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/basic-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/basic-ref.html deleted file mode 100644 index 28bfe1ab..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/basic-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, basic</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/basic.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/basic.html deleted file mode 100644 index 8420c29..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/basic.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, basic</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src="support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/bidi_ruby-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/bidi_ruby-ref.html deleted file mode 100644 index cda42be..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/bidi_ruby-ref.html +++ /dev/null
@@ -1,26 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, bidi ruby</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - font-size: 36px; -} -</style> -<div class="video"><span class="cue"><span><ruby>.<rt><bdo dir="ltr">אא</bdo></rt>ab)<rt>x</rt></ruby></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/bidi_ruby.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/bidi_ruby.html deleted file mode 100644 index 3c197bc..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/bidi_ruby.html +++ /dev/null
@@ -1,17 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, bidi ruby</title> -<style> -html { overflow:hidden } -body { margin:0 } -</style> -<script src="../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../media/white.webm" type="video/webm"> - <source src="../media/white.mp4" type="video/mp4"> - <track src="../support/bidi_ruby.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u002E_LF_u05D0-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u002E_LF_u05D0-ref.html deleted file mode 100644 index 1d22556..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u002E_LF_u05D0-ref.html +++ /dev/null
@@ -1,26 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, bidi U+002E LF U+05D0</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - font-size: 36px; -} -</style> -<div class="video"><span class="cue"><span>.<br><bdo dir=ltr>אab)</bdo></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u002E_LF_u05D0.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u002E_LF_u05D0.html deleted file mode 100644 index c54d7e46..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u002E_LF_u05D0.html +++ /dev/null
@@ -1,17 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, bidi U+002E LF U+05D0</title> -<style> -html { overflow:hidden } -body { margin:0 } -</style> -<script src="../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../media/white.webm" type="video/webm"> - <source src="../media/white.mp4" type="video/mp4"> - <track src="../support/u002E_LF_u05D0.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u002E_u2028_u05D0-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u002E_u2028_u05D0-ref.html deleted file mode 100644 index a1d748ed..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u002E_u2028_u05D0-ref.html +++ /dev/null
@@ -1,26 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, bidi U+002E U+2028 U+05D0</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - font-size: 36px; -} -</style> -<div class="video"><span class="cue"><span>.<br><bdo dir=ltr>(abא</bdo></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u002E_u2028_u05D0.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u002E_u2028_u05D0.html deleted file mode 100644 index a991edd..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u002E_u2028_u05D0.html +++ /dev/null
@@ -1,17 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, bidi U+002E U+2028 U+05D0</title> -<style> -html { overflow:hidden } -body { margin:0 } -</style> -<script src="../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../media/white.webm" type="video/webm"> - <source src="../media/white.mp4" type="video/mp4"> - <track src="../support/u002E_u2028_u05D0.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u002E_u2029_u05D0-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u002E_u2029_u05D0-ref.html deleted file mode 100644 index 09be0be..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u002E_u2029_u05D0-ref.html +++ /dev/null
@@ -1,26 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, bidi U+002E U+2029 U+05D0</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - font-size: 36px; -} -</style> -<div class="video"><span class="cue"><span>.<br><bdo dir=ltr>אab)</bdo></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u002E_u2029_u05D0.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u002E_u2029_u05D0.html deleted file mode 100644 index 7a4de0f..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u002E_u2029_u05D0.html +++ /dev/null
@@ -1,17 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, bidi U+002E U+2029 U+05D0</title> -<style> -html { overflow:hidden } -body { margin:0 } -</style> -<script src="../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../media/white.webm" type="video/webm"> - <source src="../media/white.mp4" type="video/mp4"> - <track src="../support/u002E_u2029_u05D0.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u0041_first-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u0041_first-ref.html deleted file mode 100644 index 208d20a..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u0041_first-ref.html +++ /dev/null
@@ -1,26 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, bidi U+0041 first</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - font-size: 36px; -} -</style> -<div class="video"><span class="cue"><span><bdo dir=ltr>Aab)</bdo></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u0041_first.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u0041_first.html deleted file mode 100644 index 6107afc..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u0041_first.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, bidi U+0041 first</title> -<!-- -0041..005A ; L # L& [26] LATIN CAPITAL LETTER A..LATIN CAPITAL LETTER Z -http://www.unicode.org/Public/UNIDATA/extracted/DerivedBidiClass.txt ---> -<style> -html { overflow:hidden } -body { margin:0 } -</style> -<script src="../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../media/white.webm" type="video/webm"> - <source src="../media/white.mp4" type="video/mp4"> - <track src="../support/u0041_first.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u05D0_first-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u05D0_first-ref.html deleted file mode 100644 index 211f864..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u05D0_first-ref.html +++ /dev/null
@@ -1,26 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, bidi U+05D0 first</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - font-size: 36px; -} -</style> -<div class="video"><span class="cue"><span><bdo dir=ltr>(abא</bdo></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u05D0_first.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u05D0_first.html deleted file mode 100644 index dd26cbe..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u05D0_first.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, bidi U+05D0 first</title> -<!-- -05D0..05EA ; R # Lo [27] HEBREW LETTER ALEF..HEBREW LETTER TAV -http://www.unicode.org/Public/UNIDATA/extracted/DerivedBidiClass.txt ---> -<style> -html { overflow:hidden } -body { margin:0 } -</style> -<script src="../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../media/white.webm" type="video/webm"> - <source src="../media/white.mp4" type="video/mp4"> - <track src="../support/u05D0_first.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u0628_first-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u0628_first-ref.html deleted file mode 100644 index 4fb97c4..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u0628_first-ref.html +++ /dev/null
@@ -1,26 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, bidi U+0628 first</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - font-size: 36px; -} -</style> -<div class="video"><span class="cue"><span><bdo dir=ltr>(abب</bdo></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u0628_first.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u0628_first.html deleted file mode 100644 index 61990a3..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u0628_first.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, bidi U+0628 first</title> -<!-- -0620..063F ; AL # Lo [32] ARABIC LETTER KASHMIRI YEH..ARABIC LETTER FARSI YEH WITH THREE DOTS ABOVE -http://www.unicode.org/Public/UNIDATA/extracted/DerivedBidiClass.txt ---> -<style> -html { overflow:hidden } -body { margin:0 } -</style> -<script src="../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../media/white.webm" type="video/webm"> - <source src="../media/white.mp4" type="video/mp4"> - <track src="../support/u0628_first.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u06E9_no_strong_dir-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u06E9_no_strong_dir-ref.html deleted file mode 100644 index cbd9ee0..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u06E9_no_strong_dir-ref.html +++ /dev/null
@@ -1,26 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, bidi U+06E9 no strong direction</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - font-size: 36px; -} -</style> -<div class="video"><span class="cue"><span><bdo dir=ltr>۩)</bdo></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u06E9_no_strong_dir.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u06E9_no_strong_dir.html deleted file mode 100644 index 4dcc0425..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/bidi/u06E9_no_strong_dir.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, bidi U+06E9 no strong direction</title> -<!-- -06E9 ; ON # So ARABIC PLACE OF SAJDAH -http://www.unicode.org/Public/UNIDATA/extracted/DerivedBidiClass.txt ---> -<style> -html { overflow:hidden } -body { margin:0 } -</style> -<script src="../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../media/white.webm" type="video/webm"> - <source src="../media/white.mp4" type="video/mp4"> - <track src="../support/u06E9_no_strong_dir.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/build-manifest.py b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/build-manifest.py deleted file mode 100755 index 9338ebc..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/build-manifest.py +++ /dev/null
@@ -1,30 +0,0 @@ -#!/usr/bin/python - -import os -import re - -manifest = open('reftest.list', 'w') -paths = [ - './', - 'evil/', - 'selectors/cue/', - 'selectors/cue_function/', - 'selectors/cue_function/bold_object/', - 'selectors/cue_function/italic_object/', - 'selectors/cue_function/underline_object/', - 'selectors/cue_function/class_object/', - 'selectors/cue_function/voice_object/', - 'selectors/default_styles/', - 'bidi/' -] - -for path in paths: - listing = os.listdir(path) - for infile in listing: - if re.search(r'-ref\.html$', infile): - continue - if not re.search(r'\.html$', infile): - continue - manifest.write('== '+path+infile+' '+path+infile[:-5] + '-ref.html\n') - -manifest.close()
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/cue_too_long-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/cue_too_long-ref.html deleted file mode 100644 index bb73e9c..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/cue_too_long-ref.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, size:50%, cue too long - should be cut</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 25%; - right: 0; - width: 50%; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle that should wrap several times and become so long that the cue must be cut when displayed, because it does not fit on the screen. This is a test subtitle that should wrap several times and become so long that the cue must be cut when displayed, because it does not fit on the</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/cue_too_long.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/cue_too_long.html deleted file mode 100644 index ee38f5d3..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/cue_too_long.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, size:50%, cue too long - should be cut</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src="support/very_long_cue.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/decode_escaped_entities-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/decode_escaped_entities-ref.html deleted file mode 100644 index 30cd00a6..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/decode_escaped_entities-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, decoding of escaped entities</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px; -} -</style> -<div class="video"><span class="cue"><span>Here are the escaped <br>entities: & < > ‎ ‏ </span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/decode_escaped_entities.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/decode_escaped_entities.html deleted file mode 100644 index 4221c87..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/decode_escaped_entities.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>Reference for WebVTT rendering, decoding of escaped entities</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src="support/decode_escaped_entities.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/disable_controls_reposition-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/disable_controls_reposition-ref.html deleted file mode 100644 index 5df384c..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/disable_controls_reposition-ref.html +++ /dev/null
@@ -1,26 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, cue reposition after enabling controls</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -.video { - display: inline-block; - outline: solid; - width: 320px; - height: 240px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 50px; -} -</style> -<div class="video"><span class="cue"><span>Foo</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/disable_controls_reposition.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/disable_controls_reposition.html deleted file mode 100644 index 868ae908..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/disable_controls_reposition.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!doctype html> -<title>WebVTT rendering, cue reposition after disabling controls</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -video { - outline: solid; - width: 320px; - height: 240px; -} -::cue { - font-family: Ahem, sans-serif; - font-size: 50px; - color: green; -} -</style> -<script src="support/refTestWait.js"></script> -<video autoplay controls onplaying="this.onplaying = null; - this.pause(); - this.currentTime = 0; - setTimeout(function(video){ - video.controls = false; - }, 100, this); - setTimeout(takeScreenshot, 200);"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src=support/foo.vtt> -</video>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_cue_align_position_line_size-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_cue_align_position_line_size-ref.html deleted file mode 100644 index dae20a1..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_cue_align_position_line_size-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, a cue's align, position, line and size properties is possible to override using the DOM APIs</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - top: 0; - right: 204.8px; - width: 256px; - text-align: left -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px; -} -</style> -<div class="video"><span class="cue"><span>There is nothing to see here people, move on</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_cue_align_position_line_size.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_cue_align_position_line_size.html deleted file mode 100644 index 8bf9f33..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_cue_align_position_line_size.html +++ /dev/null
@@ -1,43 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, a cue's align, position, line and size properties is possible to override using the DOM APIs</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="support/refTestWait.js"></script> -<script> - function updateCue() { - var t = document.getElementById('track'); - var c = t.track.cues[0]; - c.align = 'start'; - c.position = 80; - c.line = 0; - c.size = 20; - c.text = 'There is nothing to see here people, move on'; - updateRendering(); - } - function updateRendering() { - var v = document.getElementById('video'); - v.onplaying = function() { - this.onplaying = null; - this.pause(); - takeScreenshot(); - }; - v.play(); - } -</script> -<video id="video" width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); updateCue();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track id="track" src="support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_cue_align_position_line_size_while_paused-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_cue_align_position_line_size_while_paused-ref.html deleted file mode 100644 index 1acc7c0d..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_cue_align_position_line_size_while_paused-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, a cue's align, position, line and size properties should be rerendered when overriding them using the DOM APIs while paused</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - top: 0; - right: 204.8px; - width: 256px; - text-align: left -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px; -} -</style> -<div class="video"><span class="cue"><span>This test tests</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_cue_align_position_line_size_while_paused.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_cue_align_position_line_size_while_paused.html deleted file mode 100644 index 0fcbcddb..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_cue_align_position_line_size_while_paused.html +++ /dev/null
@@ -1,34 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, a cue's align, position, line and size properties should be rerendered when overriding them using the DOM APIs while paused</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="support/refTestWait.js"></script> -<script> - function updateCue() { - var t = document.getElementById('track'); - var c = t.track.cues[0]; - c.align = 'start'; - c.position = 80; - c.line = 0; - c.size = 20; - c.text = 'This test tests'; - takeScreenshot(); - } -</script> -<video id="video" width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); updateCue();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track id="track" src="support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_cue_line-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_cue_line-ref.html deleted file mode 100644 index 508b117..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_cue_line-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, it is possible to override cue line with the DOM APIs</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - top: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_cue_line.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_cue_line.html deleted file mode 100644 index 87d2f081a..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_cue_line.html +++ /dev/null
@@ -1,39 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, it is possible to override cue line with the DOM APIs</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="support/refTestWait.js"></script> -<script> - function updateCue() { - var t = document.getElementById('track'); - var c = t.track.cues[0]; - c.line = 0; - updateRendering(); - } - function updateRendering() { - var v = document.getElementById('video'); - v.onplaying = function() { - this.onplaying = null; - this.pause(); - takeScreenshot(); - }; - v.play(); - } -</script> -<video id="video" width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); updateCue();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track id="track" src="support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_cue_text-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_cue_text-ref.html deleted file mode 100644 index 1009f4b..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_cue_text-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, it is possible to override cue text with the DOM APIs</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px; -} -</style> -<div class="video"><span class="cue"><span>f o o</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_cue_text.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_cue_text.html deleted file mode 100644 index 07f4f79..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_cue_text.html +++ /dev/null
@@ -1,39 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, it is possible to override cue text with the DOM APIs</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="support/refTestWait.js"></script> -<script> - function updateCue() { - var t = document.getElementById('track'); - var c = t.track.cues[0]; - c.text = 'f o o'; - updateRendering(); - } - function updateRendering() { - var v = document.getElementById('video'); - v.onplaying = function() { - this.onplaying = null; - this.pause(); - takeScreenshot(); - }; - v.play(); - } -</script> -<video id="video" width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); updateCue();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track id="track" src="support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_cue_text_while_paused-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_cue_text_while_paused-ref.html deleted file mode 100644 index a3da62a..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_cue_text_while_paused-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, cue text should be rerendered when overriding them using the DOM APIs while paused</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px; -} -</style> -<div class="video"><span class="cue"><span>f o o</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_cue_text_while_paused.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_cue_text_while_paused.html deleted file mode 100644 index 5c376075..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_cue_text_while_paused.html +++ /dev/null
@@ -1,30 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, cue text should be rerendered when overriding them using the DOM APIs while paused</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="support/refTestWait.js"></script> -<script> - function updateCue() { - var t = document.getElementById('track'); - var c = t.track.cues[0]; - c.text = 'f o o'; - takeScreenshot(); - } -</script> -<video id="video" width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); updateCue();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track id="track" src="support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_remove_cue_while_paused-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_remove_cue_while_paused-ref.html deleted file mode 100644 index 4525a7c..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_remove_cue_while_paused-ref.html +++ /dev/null
@@ -1,13 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, cue text should be removed when removing them using the DOM APIs while paused</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -</style> -<div class="video"></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_remove_cue_while_paused.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_remove_cue_while_paused.html deleted file mode 100644 index 97f81e7..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/dom_override_remove_cue_while_paused.html +++ /dev/null
@@ -1,30 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, cue text should be removed when removing them using the DOM APIs while paused</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="support/refTestWait.js"></script> -<script> - function updateCue() { - var t = document.getElementById('track'); - var c = t.track.cues[0]; - t.track.removeCue(c); - takeScreenshot(); - } -</script> -<video id="video" width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); updateCue();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track id="track" src="support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/enable_controls_reposition-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/enable_controls_reposition-ref.html deleted file mode 100644 index 8a62ce8..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/enable_controls_reposition-ref.html +++ /dev/null
@@ -1,35 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, cue reposition after enabling controls</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -.video { - display: inline-block; - outline: solid; - width: 320px; - height: 240px; - position: relative -} -video { - position: absolute; - width:320px; - height:240px; -} -.cue { - position: absolute; - bottom: 50px; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 50px; -} -</style> -<video controls> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> -</video> -<div class="video"><span class="cue"><span>Foo</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/enable_controls_reposition.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/enable_controls_reposition.html deleted file mode 100644 index 660f6845..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/enable_controls_reposition.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!doctype html> -<title>WebVTT rendering, cue reposition after enabling controls</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -video { - outline: solid; - width: 320px; - height: 240px; -} -::cue { - font-family: Ahem, sans-serif; - font-size: 50px; - color: green; -} -</style> -<script src="support/refTestWait.js"></script> -<video autoplay onplaying="this.onplaying = null; - this.pause(); - this.currentTime = 0; - setTimeout(function(video){ - video.controls = true; - }, 100, this); - setTimeout(takeScreenshot, 200);"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src=support/foo.vtt> -</video>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/9_cues_overlapping_completely-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/9_cues_overlapping_completely-ref.html deleted file mode 100644 index 6fb78c88..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/9_cues_overlapping_completely-ref.html +++ /dev/null
@@ -1,113 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, repositioning of 9 cues that overlap completely</title> -<script src="../../../../../../../../resources/ahem.js"></script> -<style> -.video { - display: inline-block; - width: 720px; - height: 720px; - outline: solid; - position: relative -} -#cue1 { - position: absolute; - top: 50%; - left: 50%; - right: 0; - margin-top: -18px; - margin-left: -18px; - color: #000 -} -#cue2 { - position: absolute; - top: 50%; - left: 50%; - right: 0; - margin-top: -54px; - margin-left: -18px; - color: #222 -} -#cue3 { - position: absolute; - top: 50%; - left: 50%; - right: 0; - margin-top: -18px; - margin-left: -54px; - color: #444 -} -#cue4 { - position: absolute; - top: 50%; - left: 50%; - right: 0; - margin-top: -18px; - margin-left: 18px; - color: #666 -} -#cue5 { - position: absolute; - top: 50%; - left: 50%; - right: 0; - margin-top: 18px; - margin-left: -18px; - color: #888 -} -#cue6 { - position: absolute; - top: 50%; - left: 50%; - right: 0; - margin-top: -54px; - margin-left: -54px; - color: #aaa -} -#cue7 { - position: absolute; - top: 50%; - left: 50%; - right: 0; - margin-top: -54px; - margin-left: 18px; - color: #ccc -} -#cue8 { - position: absolute; - top: 50%; - left: 50%; - right: 0; - margin-top: 18px; - margin-left: -54px; - color: #eee -} -#cue9 { - position: absolute; - top: 50%; - left: 50%; - right: 0; - margin-top: 18px; - margin-left: 18px; - color: green -} -.cue { - width: 36px; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; -} -</style> -<div class="video"> - <span class="cue" id="cue1"><span>1</span></span> - <span class="cue" id="cue2"><span>2</span></span> - <span class="cue" id="cue3"><span>3</span></span> - <span class="cue" id="cue4"><span>4</span></span> - <span class="cue" id="cue5"><span>5</span></span> - <span class="cue" id="cue6"><span>6</span></span> - <span class="cue" id="cue7"><span>7</span></span> - <span class="cue" id="cue8"><span>8</span></span> - <span class="cue" id="cue9"><span>9</span></span> -</div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/9_cues_overlapping_completely.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/9_cues_overlapping_completely.html deleted file mode 100644 index 7018af0..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/9_cues_overlapping_completely.html +++ /dev/null
@@ -1,48 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, repositioning of 9 cues that overlap completely</title> -<script src="../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; -} -::cue(#cue1) { - color: #000 -} -::cue(#cue2) { - color: #222 -} -::cue(#cue3) { - color: #444 -} -::cue(#cue4) { - color: #666 -} -::cue(#cue5) { - color: #888 -} -::cue(#cue6) { - color: #aaa -} -::cue(#cue7) { - color: #ccc -} -::cue(#cue8) { - color: #eee -} -::cue(#cue9) { - color: green -} -</style> -<script src="../support/refTestWait.js"></script> -<video width="720" height="720" autoplay ontimeupdate="if (this.currentTime >= 1) { this.ontimeupdate = null; this.pause(); takeScreenshot(); }"> - <source src="../media/white.webm" type="video/webm"> - <source src="../media/white.mp4" type="video/mp4"> - <track src="support/9_cues_overlapping_completely.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/9_cues_overlapping_completely_all_cues_have_same_timestamp-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/9_cues_overlapping_completely_all_cues_have_same_timestamp-ref.html deleted file mode 100644 index 759bbcd..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/9_cues_overlapping_completely_all_cues_have_same_timestamp-ref.html +++ /dev/null
@@ -1,113 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, repositioning of 9 cues that overlap completely and all cues have the same timestamp</title> -<script src="../../../../../../../../resources/ahem.js"></script> -<style> -.video { - display: inline-block; - width: 720px; - height: 720px; - outline: solid; - position: relative -} -#cue1 { - position: absolute; - top: 50%; - left: 50%; - right: 0; - margin-top: -18px; - margin-left: -18px; - color: #000 -} -#cue2 { - position: absolute; - top: 50%; - left: 50%; - right: 0; - margin-top: -54px; - margin-left: -18px; - color: #222 -} -#cue3 { - position: absolute; - top: 50%; - left: 50%; - right: 0; - margin-top: -18px; - margin-left: -54px; - color: #444 -} -#cue4 { - position: absolute; - top: 50%; - left: 50%; - right: 0; - margin-top: -18px; - margin-left: 18px; - color: #666 -} -#cue5 { - position: absolute; - top: 50%; - left: 50%; - right: 0; - margin-top: 18px; - margin-left: -18px; - color: #888 -} -#cue6 { - position: absolute; - top: 50%; - left: 50%; - right: 0; - margin-top: -54px; - margin-left: -54px; - color: #aaa -} -#cue7 { - position: absolute; - top: 50%; - left: 50%; - right: 0; - margin-top: -54px; - margin-left: 18px; - color: #ccc -} -#cue8 { - position: absolute; - top: 50%; - left: 50%; - right: 0; - margin-top: 18px; - margin-left: -54px; - color: #eee -} -#cue9 { - position: absolute; - top: 50%; - left: 50%; - right: 0; - margin-top: 18px; - margin-left: 18px; - color: green -} -.cue { - width: 36px; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; -} -</style> -<div class="video"> - <span class="cue" id="cue1"><span>1</span></span> - <span class="cue" id="cue2"><span>2</span></span> - <span class="cue" id="cue3"><span>3</span></span> - <span class="cue" id="cue4"><span>4</span></span> - <span class="cue" id="cue5"><span>5</span></span> - <span class="cue" id="cue6"><span>6</span></span> - <span class="cue" id="cue7"><span>7</span></span> - <span class="cue" id="cue8"><span>8</span></span> - <span class="cue" id="cue9"><span>9</span></span> -</div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/9_cues_overlapping_completely_all_cues_have_same_timestamp.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/9_cues_overlapping_completely_all_cues_have_same_timestamp.html deleted file mode 100644 index 8f7047c3..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/9_cues_overlapping_completely_all_cues_have_same_timestamp.html +++ /dev/null
@@ -1,48 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, repositioning of 9 cues that overlap completely and all cues have the same timestamp</title> -<script src="../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; -} -::cue(#cue1) { - color: #000 -} -::cue(#cue2) { - color: #222 -} -::cue(#cue3) { - color: #444 -} -::cue(#cue4) { - color: #666 -} -::cue(#cue5) { - color: #888 -} -::cue(#cue6) { - color: #aaa -} -::cue(#cue7) { - color: #ccc -} -::cue(#cue8) { - color: #eee -} -::cue(#cue9) { - color: green -} -</style> -<script src="../support/refTestWait.js"></script> -<video width="720" height="720" autoplay ontimeupdate="if (this.currentTime >= 1) { this.ontimeupdate = null; this.pause(); takeScreenshot(); }"> - <source src="../media/white.webm" type="video/webm"> - <source src="../media/white.mp4" type="video/mp4"> - <track src="support/9_cues_overlapping_completely_all_cues_have_same_timestamp.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/media_404_omit_subtitles-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/media_404_omit_subtitles-ref.html deleted file mode 100644 index a3b4803..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/media_404_omit_subtitles-ref.html +++ /dev/null
@@ -1,13 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, when media cannot be played (404 error), subtitles are not displayed</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -</style> -<div class="video"></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/media_404_omit_subtitles.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/media_404_omit_subtitles.html deleted file mode 100644 index 4744397e..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/media_404_omit_subtitles.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, when media cannot be played (404 error), subtitles are not displayed</title> -<script src="../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="videonotfound.webm" type="video/webm"> - <source src="videonotfound.mp4" type="video/mp4"> - <track src="support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/media_height_19-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/media_height_19-ref.html deleted file mode 100644 index 607edaf..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/media_height_19-ref.html +++ /dev/null
@@ -1,26 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, when media height is 19 or less, font size should be smaller than when it is 20 and above</title> -<script src="../../../../../../../../resources/ahem.js"></script> -<style> -.video { - display: inline-block; - width: 1280px; - height: 19px; - outline: solid; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 0.95px -} -</style> -<div class=video><span class=cue><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/media_height_19.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/media_height_19.html deleted file mode 100644 index 4f031939..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/media_height_19.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, when media height is 19 or less, font size should be smaller than when it is 20 and above</title> -<script src="../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family:Ahem, sans-serif; - color:green -} -</style> -<script src="../support/refTestWait.js"></script> -<video width="1280" height="19" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../media/white.webm" type="video/webm"> - <source src="../media/white.mp4" type="video/mp4"> - <track src="support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/single_quote-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/single_quote-ref.html deleted file mode 100644 index 2f1c1505..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/single_quote-ref.html +++ /dev/null
@@ -1,26 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, single quote should not be levitated</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px; -} -</style> -<div class="video"><span class="cue"><span>'</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/single_quote.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/single_quote.html deleted file mode 100644 index 526b9ba..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/single_quote.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, single quote should not be levitated</title> -<script src="../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../media/white.webm" type="video/webm"> - <source src="../media/white.mp4" type="video/mp4"> - <track src="support/single_quote.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/size_90-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/size_90-ref.html deleted file mode 100644 index b5e34c3..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/size_90-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, size:90% == size:100% when text does not need to wrap</title> -<script src="../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px -} -</style> -<div class=video><span class=cue><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/size_90.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/size_90.html deleted file mode 100644 index 13cb138f..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/size_90.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, size:99% == size:100% when text does not need to wrap</title> -<script src="../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../media/white.webm" type="video/webm"> - <source src="../media/white.mp4" type="video/mp4"> - <track src="support/size_90.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/size_99-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/size_99-ref.html deleted file mode 100644 index 69139fe..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/size_99-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, size:99% == size:100% when text does not need to wrap</title> -<script src="../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px -} -</style> -<div class=video><span class=cue><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/size_99.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/size_99.html deleted file mode 100644 index 76a7009..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/size_99.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, size:99% == size:100% when text does not need to wrap</title> -<script src="../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../media/white.webm" type="video/webm"> - <source src="../media/white.mp4" type="video/mp4"> - <track src="support/size_99.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/support/9_cues_overlapping_completely.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/support/9_cues_overlapping_completely.vtt deleted file mode 100644 index 3f4250d..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/support/9_cues_overlapping_completely.vtt +++ /dev/null
@@ -1,37 +0,0 @@ -WEBVTT - -cue1 -00:00:00.001 --> 00:00:05.000 position:50% size:5% line:50% -1 - -cue2 -00:00:00.002 --> 00:00:05.000 position:50% size:5% line:50% -2 - -cue3 -00:00:00.003 --> 00:00:05.000 position:50% size:5% line:50% -3 - -cue4 -00:00:00.004 --> 00:00:05.000 position:50% size:5% line:50% -4 - -cue5 -00:00:00.005 --> 00:00:05.000 position:50% size:5% line:50% -5 - -cue6 -00:00:00.006 --> 00:00:05.000 position:50% size:5% line:50% -6 - -cue7 -00:00:00.007 --> 00:00:05.000 position:50% size:5% line:50% -7 - -cue8 -00:00:00.008 --> 00:00:05.000 position:50% size:5% line:50% -8 - -cue9 -00:00:00.009 --> 00:00:05.000 position:50% size:5% line:50% -9
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/support/9_cues_overlapping_completely_all_cues_have_same_timestamp.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/support/9_cues_overlapping_completely_all_cues_have_same_timestamp.vtt deleted file mode 100644 index d5019e0..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/support/9_cues_overlapping_completely_all_cues_have_same_timestamp.vtt +++ /dev/null
@@ -1,37 +0,0 @@ -WEBVTT - -cue1 -00:00:00.000 --> 00:00:05.000 position:50% size:5% line:50% -1 - -cue2 -00:00:00.000 --> 00:00:05.000 position:50% size:5% line:50% -2 - -cue3 -00:00:00.000 --> 00:00:05.000 position:50% size:5% line:50% -3 - -cue4 -00:00:00.000 --> 00:00:05.000 position:50% size:5% line:50% -4 - -cue5 -00:00:00.000 --> 00:00:05.000 position:50% size:5% line:50% -5 - -cue6 -00:00:00.000 --> 00:00:05.000 position:50% size:5% line:50% -6 - -cue7 -00:00:00.000 --> 00:00:05.000 position:50% size:5% line:50% -7 - -cue8 -00:00:00.000 --> 00:00:05.000 position:50% size:5% line:50% -8 - -cue9 -00:00:00.000 --> 00:00:05.000 position:50% size:5% line:50% -9
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/support/single_quote.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/support/single_quote.vtt deleted file mode 100644 index 5e7eefd..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/support/single_quote.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 -'
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/support/size_90.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/support/size_90.vtt deleted file mode 100644 index 2ab4fa1..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/support/size_90.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 size:90% -This is a test subtitle
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/support/size_99.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/support/size_99.vtt deleted file mode 100644 index cd14574f0..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/support/size_99.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 size:99% -This is a test subtitle
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/support/test.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/support/test.vtt deleted file mode 100644 index ab71ec5..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/evil/support/test.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 -This is a test subtitle
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_-2_wrapped_cue_grow_upwards-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_-2_wrapped_cue_grow_upwards-ref.html deleted file mode 100644 index 162cde2..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_-2_wrapped_cue_grow_upwards-ref.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, line:-2, size:50%, wrapped cue should grow upwards</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 36px; - left: 320px; - right: 0; - width: 640px; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle that will line break</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_-2_wrapped_cue_grow_upwards.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_-2_wrapped_cue_grow_upwards.html deleted file mode 100644 index 80b54c6..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_-2_wrapped_cue_grow_upwards.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, line:-2, size:50%, wrapped cue should grow upwards</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src="support/line_-2_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_0_is_top-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_0_is_top-ref.html deleted file mode 100644 index f9fd55a..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_0_is_top-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, line:0 should be top line</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - top: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_0_is_top.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_0_is_top.html deleted file mode 100644 index 2ca2afc..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_0_is_top.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, line:0 should be top line</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src="support/line_0.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_1_wrapped_cue_grow_downwards-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_1_wrapped_cue_grow_downwards-ref.html deleted file mode 100644 index dfb72e68f..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_1_wrapped_cue_grow_downwards-ref.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, line:1, size:50%, wrapped cue should grow downwards</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - top: 36px; - left: 320px; - right: 0; - width: 640px; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle that will line break</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_1_wrapped_cue_grow_downwards.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_1_wrapped_cue_grow_downwards.html deleted file mode 100644 index 98e12aa..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_1_wrapped_cue_grow_downwards.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, line:1, size:50%, wrapped cue should grow downwards</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src="support/line_1_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_50_percent-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_50_percent-ref.html deleted file mode 100644 index f1067702e..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_50_percent-ref.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, line:50% should be vertically centered</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - top: 50%; - left: 0; - right: 0; - margin-top: -18px; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_50_percent.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_50_percent.html deleted file mode 100644 index 91c0d9e..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_50_percent.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, line:50% should be vertically centered</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src="support/line_50_percent.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_integer_and_percent_mixed_overlap-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_integer_and_percent_mixed_overlap-ref.html deleted file mode 100644 index 1d84b371..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_integer_and_percent_mixed_overlap-ref.html +++ /dev/null
@@ -1,34 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, line integer and percent mixed with overlap</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -#cue1 { - position: absolute; - top: 324px; - left: 0; - right: 0; - text-align: center -} -#cue2 { - position: absolute; - top: 360px; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px; -} -</style> -<div class="video"><span id="cue1" class="cue"><span>This is a test subtitle</span></span><span id="cue2" class="cue"><span>This is another test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_integer_and_percent_mixed_overlap.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_integer_and_percent_mixed_overlap.html deleted file mode 100644 index 4c37600..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_integer_and_percent_mixed_overlap.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, line integer and percent mixed with overlap</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green; -} -</style> -<script src="support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src="support/line_integer_and_percent_overlap.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_integer_and_percent_mixed_overlap_move_up-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_integer_and_percent_mixed_overlap_move_up-ref.html deleted file mode 100644 index 1f85ef28..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_integer_and_percent_mixed_overlap_move_up-ref.html +++ /dev/null
@@ -1,34 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, line integer and percent mixed with overlap move up</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -#cue1 { - position: absolute; - top: 360px; - left: 0; - right: 0; - text-align: center -} -#cue2 { - position: absolute; - top: 324px; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px; -} -</style> -<div class="video"><span id="cue1" class="cue"><span>This is a test subtitle</span></span><span id="cue2" class="cue"><span>This is another test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_integer_and_percent_mixed_overlap_move_up.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_integer_and_percent_mixed_overlap_move_up.html deleted file mode 100644 index aa03a7b..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_integer_and_percent_mixed_overlap_move_up.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, line integer and percent mixed with overlap move up</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green; -} -</style> -<script src="support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src="support/line_integer_and_percent_overlap_move_up.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_percent_and_integer_mixed_overlap-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_percent_and_integer_mixed_overlap-ref.html deleted file mode 100644 index 01ba472..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_percent_and_integer_mixed_overlap-ref.html +++ /dev/null
@@ -1,34 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, line percent and integer mixed with overlap</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -#cue1 { - position: absolute; - top: 307.8px; - left: 0; - right: 0; - text-align: center -} -#cue2 { - position: absolute; - top: 360px; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px; -} -</style> -<div class="video"><span id="cue1" class="cue"><span>This is a test subtitle</span></span><span id="cue2" class="cue"><span>This is another test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_percent_and_integer_mixed_overlap.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_percent_and_integer_mixed_overlap.html deleted file mode 100644 index 49bc1106..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_percent_and_integer_mixed_overlap.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, line percent and integer mixed with overlap</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green; -} -</style> -<script src="support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src="support/line_percent_and_integer_overlap.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_percent_and_integer_mixed_overlap_move_up-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_percent_and_integer_mixed_overlap_move_up-ref.html deleted file mode 100644 index 85cd2f0..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_percent_and_integer_mixed_overlap_move_up-ref.html +++ /dev/null
@@ -1,34 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, line percent and integer mixed with overlap move up</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -#cue1 { - position: absolute; - top: 376.2px; - left: 0; - right: 0; - text-align: center -} -#cue2 { - position: absolute; - top: 324px; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px; -} -</style> -<div class="video"><span id="cue1" class="cue"><span>This is a test subtitle</span></span><span id="cue2" class="cue"><span>This is another test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_percent_and_integer_mixed_overlap_move_up.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_percent_and_integer_mixed_overlap_move_up.html deleted file mode 100644 index 59acb04..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/line_percent_and_integer_mixed_overlap_move_up.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, line percent and integer mixed with overlap move up</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green; -} -</style> -<script src="support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src="support/line_percent_and_integer_overlap_move_up.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/media/background.gif b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/media/background.gif deleted file mode 100644 index b3185c4..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/media/background.gif +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/media_height400_with_controls-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/media_height400_with_controls-ref.html deleted file mode 100644 index 015d30b..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/media_height400_with_controls-ref.html +++ /dev/null
@@ -1,34 +0,0 @@ -<!DOCTYPE html> -<html> -<title>Reference for WebVTT rendering, the subtitles is not covered by or covering the controls</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -.video { - display: inline-block; - position: absolute; - width: 1280px; - height: 400px; - outline: solid -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center; - padding-bottom: 40px -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 20px -} -</style> -<script src="support/refTestWait.js"></script> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div> -<video width="1280" height="400" autoplay controls onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track> -</video>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/media_height400_with_controls.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/media_height400_with_controls.html deleted file mode 100644 index 7636ae09..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/media_height400_with_controls.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, the subtitles is not covered by or covering the controls</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="support/refTestWait.js"></script> -<video width="1280" height="400" autoplay controls onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src="support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/media_with_controls-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/media_with_controls-ref.html deleted file mode 100644 index cb8e3dce..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/media_with_controls-ref.html +++ /dev/null
@@ -1,34 +0,0 @@ -<!DOCTYPE html> -<html> -<title>Reference for WebVTT rendering, the subtitles are moved up to correct position when controls are visible</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -.video { - display: inline-block; - position: absolute; - width: 1280px; - height: 720px; - outline: solid -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center; - padding-bottom: 36px -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px -} -</style> -<script src="support/refTestWait.js"></script> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div> -<video width="1280" height="720" autoplay controls onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track> -</video>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/media_with_controls.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/media_with_controls.html deleted file mode 100644 index 4a7fe4d8..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/media_with_controls.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, the subtitles are moved up to correct position when controls are visible</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="support/refTestWait.js"></script> -<video width="1280" height="720" autoplay controls onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src="support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/navigate_cue_position-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/navigate_cue_position-ref.html deleted file mode 100644 index fca6455..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/navigate_cue_position-ref.html +++ /dev/null
@@ -1,35 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, cue position after navigation</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -.video { - display: inline-block; - outline: solid; - width: 320px; - height: 240px; - position: relative -} -video { - position: absolute; - width:320px; - height:240px; -} -.cue { - position: absolute; - bottom: 50px; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 50px; -} -</style> -<video controls> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> -</video> -<div class="video"><span class="cue"><span>Foo</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/navigate_cue_position.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/navigate_cue_position.html deleted file mode 100644 index 8214abc1..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/navigate_cue_position.html +++ /dev/null
@@ -1,41 +0,0 @@ -<!doctype html> -<title>WebVTT rendering, cue position after navigation</title> -<script src="../../../../../../../resources/ahem.js"></script> -<script src="support/refTestWait.js"></script> -<script> -onload = function() { - if (sessionStorage.navigate_cue_position_navigated) { - document.body.appendChild(document.createTextNode('FAIL (page reloaded after navigation)')); - delete sessionStorage.navigate_cue_position_navigated; - setTimeout(takeScreenshot, 100); - return; - } - setTimeout(function() { - location.assign('data:text/html,<body onload="setTimeout(function(){history.back()}, 100); sessionStorage.navigate_cue_position_navigated = \'true\';">x'); - setTimeout(function() { - delete sessionStorage.navigate_cue_position_navigated; - takeScreenshot(); - }, 500); - }, 100); -} -</script> -<style> -video { - outline: solid; - width: 320px; - height: 240px; -} -::cue { - font-family: Ahem, sans-serif; - font-size: 50px; - color: green; -} -</style> -<video autoplay controls onplaying="this.onplaying = null; - this.pause(); - this.currentTime = 0; - "> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src=support/foo.vtt> -</video>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/one_line_cue_plus_wrapped_cue-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/one_line_cue_plus_wrapped_cue-ref.html deleted file mode 100644 index 3dc525a..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/one_line_cue_plus_wrapped_cue-ref.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, one line cue and cue that wraps - both should be fully visible</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 15%; - right: 0; - width: 70%; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle<br>This test subtitle wraps and should be visible</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/one_line_cue_plus_wrapped_cue.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/one_line_cue_plus_wrapped_cue.html deleted file mode 100644 index e944be7..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/one_line_cue_plus_wrapped_cue.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, one line cue and cue that wraps - both should be fully visible</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src="support/one_line_cue_plus_wrapped_cue.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/reftest.list b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/reftest.list deleted file mode 100644 index c2f111c1..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/reftest.list +++ /dev/null
@@ -1,221 +0,0 @@ -== ./2_cues_overlapping_completely_move_up.html ./2_cues_overlapping_completely_move_up-ref.html -== ./2_cues_overlapping_partially_move_down.html ./2_cues_overlapping_partially_move_down-ref.html -== ./2_cues_overlapping_partially_move_up.html ./2_cues_overlapping_partially_move_up-ref.html -== ./2_tracks.html ./2_tracks-ref.html -== ./3_tracks.html ./3_tracks-ref.html -== ./align_end.html ./align_end-ref.html -== ./align_end_wrapped.html ./align_end_wrapped-ref.html -== ./align_middle.html ./align_middle-ref.html -== ./align_middle_position_50.html ./align_middle_position_50-ref.html -== ./align_middle_position_gt_50.html ./align_middle_position_gt_50-ref.html -== ./align_middle_position_lt_50.html ./align_middle_position_lt_50-ref.html -== ./align_middle_position_lt_50_size_gt_maximum_size.html ./align_middle_position_lt_50_size_gt_maximum_size-ref.html -== ./align_middle_wrapped.html ./align_middle_wrapped-ref.html -== ./align_start.html ./align_start-ref.html -== ./align_start_wrapped.html ./align_start_wrapped-ref.html -== ./audio_has_no_subtitles.html ./audio_has_no_subtitles-ref.html -== ./basic.html ./basic-ref.html -== ./cue_too_long.html ./cue_too_long-ref.html -== ./decode_escaped_entities.html ./decode_escaped_entities-ref.html -== ./disable_controls_reposition.html ./disable_controls_reposition-ref.html -== ./dom_override_cue_align_position_line_size.html ./dom_override_cue_align_position_line_size-ref.html -== ./dom_override_cue_align_position_line_size_while_paused.html ./dom_override_cue_align_position_line_size_while_paused-ref.html -== ./dom_override_cue_line.html ./dom_override_cue_line-ref.html -== ./dom_override_cue_text.html ./dom_override_cue_text-ref.html -== ./dom_override_cue_text_while_paused.html ./dom_override_cue_text_while_paused-ref.html -== ./dom_override_remove_cue_while_paused.html ./dom_override_remove_cue_while_paused-ref.html -== ./enable_controls_reposition.html ./enable_controls_reposition-ref.html -== ./line_-2_wrapped_cue_grow_upwards.html ./line_-2_wrapped_cue_grow_upwards-ref.html -== ./line_0_is_top.html ./line_0_is_top-ref.html -== ./line_1_wrapped_cue_grow_downwards.html ./line_1_wrapped_cue_grow_downwards-ref.html -== ./line_50_percent.html ./line_50_percent-ref.html -== ./line_integer_and_percent_mixed_overlap.html ./line_integer_and_percent_mixed_overlap-ref.html -== ./line_integer_and_percent_mixed_overlap_move_up.html ./line_integer_and_percent_mixed_overlap_move_up-ref.html -== ./line_percent_and_integer_mixed_overlap.html ./line_percent_and_integer_mixed_overlap-ref.html -== ./line_percent_and_integer_mixed_overlap_move_up.html ./line_percent_and_integer_mixed_overlap_move_up-ref.html -== ./media_height400_with_controls.html ./media_height400_with_controls-ref.html -== ./media_with_controls.html ./media_with_controls-ref.html -== ./navigate_cue_position.html ./navigate_cue_position-ref.html -== ./one_line_cue_plus_wrapped_cue.html ./one_line_cue_plus_wrapped_cue-ref.html -== ./repaint.html ./repaint-ref.html -== ./size_50.html ./size_50-ref.html -== ./too_many_cues.html ./too_many_cues-ref.html -== ./too_many_cues_wrapped.html ./too_many_cues_wrapped-ref.html -== evil/9_cues_overlapping_completely.html evil/9_cues_overlapping_completely-ref.html -== evil/9_cues_overlapping_completely_all_cues_have_same_timestamp.html evil/9_cues_overlapping_completely_all_cues_have_same_timestamp-ref.html -== evil/media_404_omit_subtitles.html evil/media_404_omit_subtitles-ref.html -== evil/media_height_19.html evil/media_height_19-ref.html -== evil/single_quote.html evil/single_quote-ref.html -== evil/size_90.html evil/size_90-ref.html -== evil/size_99.html evil/size_99-ref.html -== selectors/cue/background_properties.html selectors/cue/background_properties-ref.html -== selectors/cue/background_shorthand.html selectors/cue/background_shorthand-ref.html -== selectors/cue/background_shorthand_css_relative_url.html selectors/cue/background_shorthand_css_relative_url-ref.html -== selectors/cue/color_hex.html selectors/cue/color_hex-ref.html -== selectors/cue/color_hsla.html selectors/cue/color_hsla-ref.html -== selectors/cue/color_rgba.html selectors/cue/color_rgba-ref.html -== selectors/cue/cue_selector_single_colon.html selectors/cue/cue_selector_single_colon-ref.html -== selectors/cue/font_properties.html selectors/cue/font_properties-ref.html -== selectors/cue/font_shorthand.html selectors/cue/font_shorthand-ref.html -== selectors/cue/inherit_values_from_media_element.html selectors/cue/inherit_values_from_media_element-ref.html -== selectors/cue/outline_properties.html selectors/cue/outline_properties-ref.html -== selectors/cue/outline_shorthand.html selectors/cue/outline_shorthand-ref.html -== selectors/cue/text-decoration_line-through.html selectors/cue/text-decoration_line-through-ref.html -== selectors/cue/text-decoration_overline.html selectors/cue/text-decoration_overline-ref.html -== selectors/cue/text-decoration_overline_underline_line-through.html selectors/cue/text-decoration_overline_underline_line-through-ref.html -== selectors/cue/text-decoration_underline.html selectors/cue/text-decoration_underline-ref.html -== selectors/cue/text-shadow.html selectors/cue/text-shadow-ref.html -== selectors/cue/white-space_normal_wrapped.html selectors/cue/white-space_normal_wrapped-ref.html -== selectors/cue/white-space_nowrap_wrapped.html selectors/cue/white-space_nowrap_wrapped-ref.html -== selectors/cue/white-space_pre-line_wrapped.html selectors/cue/white-space_pre-line_wrapped-ref.html -== selectors/cue/white-space_pre-wrap_wrapped.html selectors/cue/white-space_pre-wrap_wrapped-ref.html -== selectors/cue/white-space_pre.html selectors/cue/white-space_pre-ref.html -== selectors/cue/white-space_pre_wrapped.html selectors/cue/white-space_pre_wrapped-ref.html -== selectors/cue_function/background_box.html selectors/cue_function/background_box-ref.html -== selectors/cue_function/background_properties.html selectors/cue_function/background_properties-ref.html -== selectors/cue_function/background_shorthand.html selectors/cue_function/background_shorthand-ref.html -== selectors/cue_function/background_shorthand_css_relative_url.html selectors/cue_function/background_shorthand_css_relative_url-ref.html -== selectors/cue_function/color_hex.html selectors/cue_function/color_hex-ref.html -== selectors/cue_function/color_hsla.html selectors/cue_function/color_hsla-ref.html -== selectors/cue_function/color_rgba.html selectors/cue_function/color_rgba-ref.html -== selectors/cue_function/cue_func_selector_single_colon.html selectors/cue_function/cue_func_selector_single_colon-ref.html -== selectors/cue_function/font_properties.html selectors/cue_function/font_properties-ref.html -== selectors/cue_function/font_shorthand.html selectors/cue_function/font_shorthand-ref.html -== selectors/cue_function/id_color.html selectors/cue_function/id_color-ref.html -== selectors/cue_function/inherit_values_from_media_element.html selectors/cue_function/inherit_values_from_media_element-ref.html -== selectors/cue_function/not_allowed_properties.html selectors/cue_function/not_allowed_properties-ref.html -== selectors/cue_function/not_root_selector.html selectors/cue_function/not_root_selector-ref.html -== selectors/cue_function/outline_properties.html selectors/cue_function/outline_properties-ref.html -== selectors/cue_function/outline_shorthand.html selectors/cue_function/outline_shorthand-ref.html -== selectors/cue_function/root_namespace.html selectors/cue_function/root_namespace-ref.html -== selectors/cue_function/root_selector.html selectors/cue_function/root_selector-ref.html -== selectors/cue_function/text-decoration_line-through.html selectors/cue_function/text-decoration_line-through-ref.html -== selectors/cue_function/text-decoration_overline.html selectors/cue_function/text-decoration_overline-ref.html -== selectors/cue_function/text-decoration_overline_underline_line-through.html selectors/cue_function/text-decoration_overline_underline_line-through-ref.html -== selectors/cue_function/text-decoration_underline.html selectors/cue_function/text-decoration_underline-ref.html -== selectors/cue_function/text-shadow.html selectors/cue_function/text-shadow-ref.html -== selectors/cue_function/type_selector_root.html selectors/cue_function/type_selector_root-ref.html -== selectors/cue_function/white-space_normal_wrapped.html selectors/cue_function/white-space_normal_wrapped-ref.html -== selectors/cue_function/white-space_nowrap_wrapped.html selectors/cue_function/white-space_nowrap_wrapped-ref.html -== selectors/cue_function/white-space_pre-line_wrapped.html selectors/cue_function/white-space_pre-line_wrapped-ref.html -== selectors/cue_function/white-space_pre-wrap_wrapped.html selectors/cue_function/white-space_pre-wrap_wrapped-ref.html -== selectors/cue_function/white-space_pre.html selectors/cue_function/white-space_pre-ref.html -== selectors/cue_function/white-space_pre_wrapped.html selectors/cue_function/white-space_pre_wrapped-ref.html -== selectors/cue_function/bold_object/bold_animation_with_timestamp.html selectors/cue_function/bold_object/bold_animation_with_timestamp-ref.html -== selectors/cue_function/bold_object/bold_background_properties.html selectors/cue_function/bold_object/bold_background_properties-ref.html -== selectors/cue_function/bold_object/bold_background_shorthand.html selectors/cue_function/bold_object/bold_background_shorthand-ref.html -== selectors/cue_function/bold_object/bold_color.html selectors/cue_function/bold_object/bold_color-ref.html -== selectors/cue_function/bold_object/bold_font_properties.html selectors/cue_function/bold_object/bold_font_properties-ref.html -== selectors/cue_function/bold_object/bold_font_shorthand.html selectors/cue_function/bold_object/bold_font_shorthand-ref.html -== selectors/cue_function/bold_object/bold_namespace.html selectors/cue_function/bold_object/bold_namespace-ref.html -== selectors/cue_function/bold_object/bold_outline_properties.html selectors/cue_function/bold_object/bold_outline_properties-ref.html -== selectors/cue_function/bold_object/bold_outline_shorthand.html selectors/cue_function/bold_object/bold_outline_shorthand-ref.html -== selectors/cue_function/bold_object/bold_text-decoration_line-through.html selectors/cue_function/bold_object/bold_text-decoration_line-through-ref.html -== selectors/cue_function/bold_object/bold_text-shadow.html selectors/cue_function/bold_object/bold_text-shadow-ref.html -== selectors/cue_function/bold_object/bold_timestamp_future.html selectors/cue_function/bold_object/bold_timestamp_future-ref.html -== selectors/cue_function/bold_object/bold_timestamp_past.html selectors/cue_function/bold_object/bold_timestamp_past-ref.html -== selectors/cue_function/bold_object/bold_transition_with_timestamp.html selectors/cue_function/bold_object/bold_transition_with_timestamp-ref.html -== selectors/cue_function/bold_object/bold_white-space_normal_wrapped.html selectors/cue_function/bold_object/bold_white-space_normal_wrapped-ref.html -== selectors/cue_function/bold_object/bold_white-space_nowrap.html selectors/cue_function/bold_object/bold_white-space_nowrap-ref.html -== selectors/cue_function/bold_object/bold_white-space_pre-line_wrapped.html selectors/cue_function/bold_object/bold_white-space_pre-line_wrapped-ref.html -== selectors/cue_function/bold_object/bold_white-space_pre-wrap_wrapped.html selectors/cue_function/bold_object/bold_white-space_pre-wrap_wrapped-ref.html -== selectors/cue_function/bold_object/bold_white-space_pre_wrapped.html selectors/cue_function/bold_object/bold_white-space_pre_wrapped-ref.html -== selectors/cue_function/bold_object/bold_with_class.html selectors/cue_function/bold_object/bold_with_class-ref.html -== selectors/cue_function/bold_object/bold_with_class_object_specific_selector.html selectors/cue_function/bold_object/bold_with_class_object_specific_selector-ref.html -== selectors/cue_function/italic_object/italic_animation_with_timestamp.html selectors/cue_function/italic_object/italic_animation_with_timestamp-ref.html -== selectors/cue_function/italic_object/italic_background_properties.html selectors/cue_function/italic_object/italic_background_properties-ref.html -== selectors/cue_function/italic_object/italic_background_shorthand.html selectors/cue_function/italic_object/italic_background_shorthand-ref.html -== selectors/cue_function/italic_object/italic_color.html selectors/cue_function/italic_object/italic_color-ref.html -== selectors/cue_function/italic_object/italic_font_properties.html selectors/cue_function/italic_object/italic_font_properties-ref.html -== selectors/cue_function/italic_object/italic_font_shorthand.html selectors/cue_function/italic_object/italic_font_shorthand-ref.html -== selectors/cue_function/italic_object/italic_namespace.html selectors/cue_function/italic_object/italic_namespace-ref.html -== selectors/cue_function/italic_object/italic_outline_properties.html selectors/cue_function/italic_object/italic_outline_properties-ref.html -== selectors/cue_function/italic_object/italic_outline_shorthand.html selectors/cue_function/italic_object/italic_outline_shorthand-ref.html -== selectors/cue_function/italic_object/italic_text-decoration_line-through.html selectors/cue_function/italic_object/italic_text-decoration_line-through-ref.html -== selectors/cue_function/italic_object/italic_text-shadow.html selectors/cue_function/italic_object/italic_text-shadow-ref.html -== selectors/cue_function/italic_object/italic_timestamp_future.html selectors/cue_function/italic_object/italic_timestamp_future-ref.html -== selectors/cue_function/italic_object/italic_timestamp_past.html selectors/cue_function/italic_object/italic_timestamp_past-ref.html -== selectors/cue_function/italic_object/italic_transition_with_timestamp.html selectors/cue_function/italic_object/italic_transition_with_timestamp-ref.html -== selectors/cue_function/italic_object/italic_white-space_normal_wrapped.html selectors/cue_function/italic_object/italic_white-space_normal_wrapped-ref.html -== selectors/cue_function/italic_object/italic_white-space_nowrap.html selectors/cue_function/italic_object/italic_white-space_nowrap-ref.html -== selectors/cue_function/italic_object/italic_white-space_pre-line_wrapped.html selectors/cue_function/italic_object/italic_white-space_pre-line_wrapped-ref.html -== selectors/cue_function/italic_object/italic_white-space_pre-wrap_wrapped.html selectors/cue_function/italic_object/italic_white-space_pre-wrap_wrapped-ref.html -== selectors/cue_function/italic_object/italic_white-space_pre_wrapped.html selectors/cue_function/italic_object/italic_white-space_pre_wrapped-ref.html -== selectors/cue_function/italic_object/italic_with_class.html selectors/cue_function/italic_object/italic_with_class-ref.html -== selectors/cue_function/italic_object/italic_with_class_object_specific_selector.html selectors/cue_function/italic_object/italic_with_class_object_specific_selector-ref.html -== selectors/cue_function/underline_object/underline_animation_with_timestamp.html selectors/cue_function/underline_object/underline_animation_with_timestamp-ref.html -== selectors/cue_function/underline_object/underline_background_properties.html selectors/cue_function/underline_object/underline_background_properties-ref.html -== selectors/cue_function/underline_object/underline_background_shorthand.html selectors/cue_function/underline_object/underline_background_shorthand-ref.html -== selectors/cue_function/underline_object/underline_color.html selectors/cue_function/underline_object/underline_color-ref.html -== selectors/cue_function/underline_object/underline_font_properties.html selectors/cue_function/underline_object/underline_font_properties-ref.html -== selectors/cue_function/underline_object/underline_font_shorthand.html selectors/cue_function/underline_object/underline_font_shorthand-ref.html -== selectors/cue_function/underline_object/underline_namespace.html selectors/cue_function/underline_object/underline_namespace-ref.html -== selectors/cue_function/underline_object/underline_outline_properties.html selectors/cue_function/underline_object/underline_outline_properties-ref.html -== selectors/cue_function/underline_object/underline_outline_shorthand.html selectors/cue_function/underline_object/underline_outline_shorthand-ref.html -== selectors/cue_function/underline_object/underline_text-decoration_line-through.html selectors/cue_function/underline_object/underline_text-decoration_line-through-ref.html -== selectors/cue_function/underline_object/underline_text-shadow.html selectors/cue_function/underline_object/underline_text-shadow-ref.html -== selectors/cue_function/underline_object/underline_timestamp_future.html selectors/cue_function/underline_object/underline_timestamp_future-ref.html -== selectors/cue_function/underline_object/underline_timestamp_past.html selectors/cue_function/underline_object/underline_timestamp_past-ref.html -== selectors/cue_function/underline_object/underline_transition_with_timestamp.html selectors/cue_function/underline_object/underline_transition_with_timestamp-ref.html -== selectors/cue_function/underline_object/underline_white-space_normal_wrapped.html selectors/cue_function/underline_object/underline_white-space_normal_wrapped-ref.html -== selectors/cue_function/underline_object/underline_white-space_nowrap.html selectors/cue_function/underline_object/underline_white-space_nowrap-ref.html -== selectors/cue_function/underline_object/underline_white-space_pre-line_wrapped.html selectors/cue_function/underline_object/underline_white-space_pre-line_wrapped-ref.html -== selectors/cue_function/underline_object/underline_white-space_pre-wrap_wrapped.html selectors/cue_function/underline_object/underline_white-space_pre-wrap_wrapped-ref.html -== selectors/cue_function/underline_object/underline_white-space_pre_wrapped.html selectors/cue_function/underline_object/underline_white-space_pre_wrapped-ref.html -== selectors/cue_function/underline_object/underline_with_class.html selectors/cue_function/underline_object/underline_with_class-ref.html -== selectors/cue_function/underline_object/underline_with_class_object_specific_selector.html selectors/cue_function/underline_object/underline_with_class_object_specific_selector-ref.html -== selectors/cue_function/class_object/class_animation_with_timestamp.html selectors/cue_function/class_object/class_animation_with_timestamp-ref.html -== selectors/cue_function/class_object/class_background_properties.html selectors/cue_function/class_object/class_background_properties-ref.html -== selectors/cue_function/class_object/class_background_shorthand.html selectors/cue_function/class_object/class_background_shorthand-ref.html -== selectors/cue_function/class_object/class_color.html selectors/cue_function/class_object/class_color-ref.html -== selectors/cue_function/class_object/class_font_properties.html selectors/cue_function/class_object/class_font_properties-ref.html -== selectors/cue_function/class_object/class_font_shorthand.html selectors/cue_function/class_object/class_font_shorthand-ref.html -== selectors/cue_function/class_object/class_namespace.html selectors/cue_function/class_object/class_namespace-ref.html -== selectors/cue_function/class_object/class_outline_properties.html selectors/cue_function/class_object/class_outline_properties-ref.html -== selectors/cue_function/class_object/class_outline_shorthand.html selectors/cue_function/class_object/class_outline_shorthand-ref.html -== selectors/cue_function/class_object/class_text-decoration_line-through.html selectors/cue_function/class_object/class_text-decoration_line-through-ref.html -== selectors/cue_function/class_object/class_text-shadow.html selectors/cue_function/class_object/class_text-shadow-ref.html -== selectors/cue_function/class_object/class_timestamp_future.html selectors/cue_function/class_object/class_timestamp_future-ref.html -== selectors/cue_function/class_object/class_timestamp_past.html selectors/cue_function/class_object/class_timestamp_past-ref.html -== selectors/cue_function/class_object/class_transition_with_timestamp.html selectors/cue_function/class_object/class_transition_with_timestamp-ref.html -== selectors/cue_function/class_object/class_white-space_normal_wrapped.html selectors/cue_function/class_object/class_white-space_normal_wrapped-ref.html -== selectors/cue_function/class_object/class_white-space_nowrap.html selectors/cue_function/class_object/class_white-space_nowrap-ref.html -== selectors/cue_function/class_object/class_white-space_pre-line_wrapped.html selectors/cue_function/class_object/class_white-space_pre-line_wrapped-ref.html -== selectors/cue_function/class_object/class_white-space_pre-wrap_wrapped.html selectors/cue_function/class_object/class_white-space_pre-wrap_wrapped-ref.html -== selectors/cue_function/class_object/class_white-space_pre_wrapped.html selectors/cue_function/class_object/class_white-space_pre_wrapped-ref.html -== selectors/cue_function/class_object/class_with_class.html selectors/cue_function/class_object/class_with_class-ref.html -== selectors/cue_function/class_object/class_with_class_object_specific_selector.html selectors/cue_function/class_object/class_with_class_object_specific_selector-ref.html -== selectors/cue_function/voice_object/voice_animation_with_timestamp.html selectors/cue_function/voice_object/voice_animation_with_timestamp-ref.html -== selectors/cue_function/voice_object/voice_background_properties.html selectors/cue_function/voice_object/voice_background_properties-ref.html -== selectors/cue_function/voice_object/voice_background_shorthand.html selectors/cue_function/voice_object/voice_background_shorthand-ref.html -== selectors/cue_function/voice_object/voice_color.html selectors/cue_function/voice_object/voice_color-ref.html -== selectors/cue_function/voice_object/voice_font_properties.html selectors/cue_function/voice_object/voice_font_properties-ref.html -== selectors/cue_function/voice_object/voice_font_shorthand.html selectors/cue_function/voice_object/voice_font_shorthand-ref.html -== selectors/cue_function/voice_object/voice_namespace.html selectors/cue_function/voice_object/voice_namespace-ref.html -== selectors/cue_function/voice_object/voice_outline_properties.html selectors/cue_function/voice_object/voice_outline_properties-ref.html -== selectors/cue_function/voice_object/voice_outline_shorthand.html selectors/cue_function/voice_object/voice_outline_shorthand-ref.html -== selectors/cue_function/voice_object/voice_text-decoration_line-through.html selectors/cue_function/voice_object/voice_text-decoration_line-through-ref.html -== selectors/cue_function/voice_object/voice_text-shadow.html selectors/cue_function/voice_object/voice_text-shadow-ref.html -== selectors/cue_function/voice_object/voice_timestamp_future.html selectors/cue_function/voice_object/voice_timestamp_future-ref.html -== selectors/cue_function/voice_object/voice_timestamp_past.html selectors/cue_function/voice_object/voice_timestamp_past-ref.html -== selectors/cue_function/voice_object/voice_transition_with_timestamp.html selectors/cue_function/voice_object/voice_transition_with_timestamp-ref.html -== selectors/cue_function/voice_object/voice_voice_attribute.html selectors/cue_function/voice_object/voice_voice_attribute-ref.html -== selectors/cue_function/voice_object/voice_white-space_normal_wrapped.html selectors/cue_function/voice_object/voice_white-space_normal_wrapped-ref.html -== selectors/cue_function/voice_object/voice_white-space_nowrap.html selectors/cue_function/voice_object/voice_white-space_nowrap-ref.html -== selectors/cue_function/voice_object/voice_white-space_pre-line_wrapped.html selectors/cue_function/voice_object/voice_white-space_pre-line_wrapped-ref.html -== selectors/cue_function/voice_object/voice_white-space_pre-wrap_wrapped.html selectors/cue_function/voice_object/voice_white-space_pre-wrap_wrapped-ref.html -== selectors/cue_function/voice_object/voice_white-space_pre_wrapped.html selectors/cue_function/voice_object/voice_white-space_pre_wrapped-ref.html -== selectors/cue_function/voice_object/voice_with_class.html selectors/cue_function/voice_object/voice_with_class-ref.html -== selectors/cue_function/voice_object/voice_with_class_object_specific_selector.html selectors/cue_function/voice_object/voice_with_class_object_specific_selector-ref.html -== selectors/default_styles/bold_object_default_font-style.html selectors/default_styles/bold_object_default_font-style-ref.html -== selectors/default_styles/inherit_as_default_value_inherits_values_from_media_element.html selectors/default_styles/inherit_as_default_value_inherits_values_from_media_element-ref.html -== selectors/default_styles/italic_object_default_font-style.html selectors/default_styles/italic_object_default_font-style-ref.html -== selectors/default_styles/underline_object_default_font-style.html selectors/default_styles/underline_object_default_font-style-ref.html -== bidi/bidi_ruby.html bidi/bidi_ruby-ref.html -== bidi/u002E_LF_u05D0.html bidi/u002E_LF_u05D0-ref.html -== bidi/u002E_u2028_u05D0.html bidi/u002E_u2028_u05D0-ref.html -== bidi/u002E_u2029_u05D0.html bidi/u002E_u2029_u05D0-ref.html -== bidi/u0041_first.html bidi/u0041_first-ref.html -== bidi/u05D0_first.html bidi/u05D0_first-ref.html -== bidi/u0620_first.html bidi/u0620_first-ref.html -== bidi/u06E9_no_strong_dir.html bidi/u06E9_no_strong_dir-ref.html
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/repaint-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/repaint-ref.html deleted file mode 100644 index d0943070..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/repaint-ref.html +++ /dev/null
@@ -1,25 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, cue should repaint after hiding a covering abspos box</title> -<style> -.video { - display: inline-block; - width: 320px; - height: 240px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 50px; -} -</style> -<p>You should see the word 'PASS' below.</p> -<div class="video"><span class="cue"><span>PASS</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/repaint.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/repaint.html deleted file mode 100644 index 916c57d..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/repaint.html +++ /dev/null
@@ -1,49 +0,0 @@ -<!doctype html> -<title>WebVTT rendering, cue should repaint after hiding a covering abspos box</title> -<style> -#wrapper { - position: relative; -} -#cover { - position: absolute; - left: 0px; - top: 180px; - width: 320px; - height: 60px; - background-color: gray; -} -video { - width: 320px; - height: 240px; -} -::cue { - font-size: 50px; - color: green; -} -</style> -<p>You should see the word 'PASS' below.</p> -<script src="support/refTestWait.js"></script> -<div id=wrapper> - <video> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - </video> - <div id=cover></div> -</div> -<script> -var v = document.querySelector('video'); -var c = document.getElementById('cover'); -var t = v.addTextTrack('subtitles'); -t.mode = "showing"; -t.addCue(new VTTCue(0, 100, 'PASS')); -v.onplaying = function() { - setTimeout(function() { - v.pause(); - setTimeout(function() { - c.style.visibility = 'hidden'; - setTimeout(takeScreenshot, 100); - }, 100); - }, 100); -}; -v.play(); -</script>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/background_properties-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/background_properties-ref.html deleted file mode 100644 index 0ed10a9..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/background_properties-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue, background properties</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: #0f0 url('../../media/background.gif') repeat-x top left; - font-size: 36px; - color: green; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/background_properties.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/background_properties.html deleted file mode 100644 index e6f0d9b..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/background_properties.html +++ /dev/null
@@ -1,26 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue, background properties</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - background-color: #0f0; - background-image: url('../../media/background.gif'); - background-repeat: repeat-x; - background-position: top left; - color: green; -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/background_shorthand-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/background_shorthand-ref.html deleted file mode 100644 index 7fa034c..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/background_shorthand-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue, background shorthand</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: #0f0 url('../../media/background.gif') repeat-x top left; - font-size: 36px; - color: green; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/background_shorthand.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/background_shorthand.html deleted file mode 100644 index 13d8ce5..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/background_shorthand.html +++ /dev/null
@@ -1,23 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue, background shorthand</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - background: #0f0 url('../../media/background.gif') repeat-x top left; - color: green; -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/background_shorthand_css_relative_url-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/background_shorthand_css_relative_url-ref.html deleted file mode 100644 index 6c0f376..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/background_shorthand_css_relative_url-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue, background shorthand, background image URL with relative path from CSS file</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: #0f0 url('../../media/background.gif') repeat-x top left; - font-size: 36px; - color: green; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/background_shorthand_css_relative_url.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/background_shorthand_css_relative_url.html deleted file mode 100644 index c5452ad..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/background_shorthand_css_relative_url.html +++ /dev/null
@@ -1,23 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue, background shorthand, background image URL with relative path from CSS file</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - background: #0f0 url('../../media/background.gif') repeat-x top left; - color: green; -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/color_hex-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/color_hex-ref.html deleted file mode 100644 index a4341be..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/color_hex-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue, color: #60ff60</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: #60ff60; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/color_hex.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/color_hex.html deleted file mode 100644 index 6f86137..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/color_hex.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue, color: #60ff60</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: #60ff60; -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/color_hsla-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/color_hsla-ref.html deleted file mode 100644 index a8edcbd..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/color_hsla-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue, color: hsla()</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: hsla(100,100%,50%,0.5); -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/color_hsla.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/color_hsla.html deleted file mode 100644 index b3438ffa..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/color_hsla.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue, color: hsla()</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: hsla(100,100%,50%,0.5); -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/color_rgba-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/color_rgba-ref.html deleted file mode 100644 index 9efe85412..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/color_rgba-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue, color: rgba()</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: rgba(128,255,128,0.5); -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/color_rgba.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/color_rgba.html deleted file mode 100644 index 88a5660..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/color_rgba.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue, color: rgba()</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: rgba(128,255,128,0.5); -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/cue_selector_single_colon-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/cue_selector_single_colon-ref.html deleted file mode 100644 index 709f517..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/cue_selector_single_colon-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, :cue (single colon) should not be supported</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 25%; - right: 0; - width: 50%; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - font-size: 36px; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/cue_selector_single_colon.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/cue_selector_single_colon.html deleted file mode 100644 index 1b03657..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/cue_selector_single_colon.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, :cue (single colon) should not be supported</title> -<style> -html { overflow:hidden } -body { margin:0 } -:cue { - background: red; - color: yellow -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/font_properties-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/font_properties-ref.html deleted file mode 100644 index d7071fcc..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/font_properties-ref.html +++ /dev/null
@@ -1,25 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue, font properties</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - font: italic small-caps bold 36px/72px sans-serif; - text-align: center -} -.cue > span { - background: rgba(0,0,0,0.8); - color: white; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle that most likely will span over several rows since it's a pretty long cue with a lot of text.</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/font_properties.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/font_properties.html deleted file mode 100644 index e078c5df..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/font_properties.html +++ /dev/null
@@ -1,25 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue, font properties</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-style: italic; - font-variant: small-caps; - font-weight: bold; - font-size: 36px; - line-height: 72px; - font-family: sans-serif; -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/font_shorthand-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/font_shorthand-ref.html deleted file mode 100644 index b3a5d47..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/font_shorthand-ref.html +++ /dev/null
@@ -1,25 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue, font shorthand</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - font: italic small-caps bold 36px/72px sans-serif; - text-align: center -} -.cue > span { - background: rgba(0,0,0,0.8); - color: white; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle that most likely will span over several rows since it's a pretty long cue with a lot of text.</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/font_shorthand.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/font_shorthand.html deleted file mode 100644 index b1db8b0..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/font_shorthand.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue, font shorthand</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font: italic small-caps bold 36px/72px sans-serif; -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/inherit_values_from_media_element-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/inherit_values_from_media_element-ref.html deleted file mode 100644 index e8ef51b..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/inherit_values_from_media_element-ref.html +++ /dev/null
@@ -1,46 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue, css properties with value inherit should inherit from media element</title> -<style> -.video { - position: absolute; - display: inline-block; - width: 1280px; - height: 720px; - position: relative; - color: #f0f; - white-space: pre-wrap; - font: italic small-caps bold 36px/72px sans-serif; - text-decoration: overline underline line-through; - text-shadow: 0px 0px 5px #0f0; - background: #0f0 url('../../media/background.gif') repeat-x top left; - outline: solid #00f 2px; -} -.videoWhite { - position: absolute; - top: 0; - left: 160px; - width: 960px; - height: 720px;; - background: #fff; - z-index: 1; -} -.cue { - position: absolute; - bottom: 0; - left: 30%; - right: 0; - width: 40%; - text-align: center; - outline: inherit; - text-shadow: inherit; - text-decoration: inherit; - outline-bottom: none; - z-index: 2 -} -.cue > span { - background: #0f0 url('../../media/background.gif') repeat-x top left; - text-decoration: inherit; - white-space: pre-wrap -} -</style> -<div class="video"><div class="videoWhite"></div><span class="cue"><span>A A A A A A A A A A A</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/inherit_values_from_media_element.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/inherit_values_from_media_element.html deleted file mode 100644 index 143faf6..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/inherit_values_from_media_element.html +++ /dev/null
@@ -1,33 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue, css properties with value inherit should inherit from media element</title> -<style> -video { - color: #f0f; - white-space: pre-wrap; - font: italic small-caps bold 36px/72px sans-serif; - text-decoration: overline underline line-through; - text-shadow: 0px 0px 5px #0f0; - background: #0f0 url('../../media/background.gif') repeat-x top left; - outline: solid #00f 2px; -} -::cue { - white-space: inherit; - font: inherit; - color: inherit; - text-decoration: inherit; - text-shadow: inherit; - background: inherit; - outline: inherit; -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/white-spaces_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/outline_properties-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/outline_properties-ref.html deleted file mode 100644 index 65470f9..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/outline_properties-ref.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue, outline properties</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - outline: solid #00f 2px; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: green; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/outline_properties.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/outline_properties.html deleted file mode 100644 index 75adc47..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/outline_properties.html +++ /dev/null
@@ -1,25 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue, outline properties</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - outline-style: solid; - outline-color: #00f; - outline-width: 2px; - color: green; -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/outline_shorthand-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/outline_shorthand-ref.html deleted file mode 100644 index 6616037..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/outline_shorthand-ref.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue, outline shorthand</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - outline: solid #00f 2px; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: green; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/outline_shorthand.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/outline_shorthand.html deleted file mode 100644 index f7526db4..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/outline_shorthand.html +++ /dev/null
@@ -1,23 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue, outline shorthand</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - outline: solid #00f 2px; - color: green; -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/text-decoration_line-through-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/text-decoration_line-through-ref.html deleted file mode 100644 index 70e314aa..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/text-decoration_line-through-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue, text-decoration: line-through</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; - text-decoration: line-through; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/text-decoration_line-through.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/text-decoration_line-through.html deleted file mode 100644 index b5d27663..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/text-decoration_line-through.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue, text-decoration: line-through</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: sans-serif; - text-decoration: line-through; -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/text-decoration_overline-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/text-decoration_overline-ref.html deleted file mode 100644 index e3a3473..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/text-decoration_overline-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue, text-decoration: overline</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; - text-decoration: overline; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/text-decoration_overline.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/text-decoration_overline.html deleted file mode 100644 index 1eb408e..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/text-decoration_overline.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue, text-decoration: overline</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: sans-serif; - text-decoration: overline; -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/text-decoration_overline_underline_line-through-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/text-decoration_overline_underline_line-through-ref.html deleted file mode 100644 index 7fb7d24c..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/text-decoration_overline_underline_line-through-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue, text-decoration: overline underline line-through</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; - text-decoration: overline underline line-through; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/text-decoration_overline_underline_line-through.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/text-decoration_overline_underline_line-through.html deleted file mode 100644 index c300936..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/text-decoration_overline_underline_line-through.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue, text-decoration: overline underline line-through</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: sans-serif; - text-decoration: overline underline line-through; -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/text-decoration_underline-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/text-decoration_underline-ref.html deleted file mode 100644 index acc0fb3e..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/text-decoration_underline-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue, text-decoration: underline</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; - text-decoration: underline; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/text-decoration_underline.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/text-decoration_underline.html deleted file mode 100644 index 73d9b8c..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/text-decoration_underline.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue, text-decoration: underline</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: sans-serif; - text-decoration: underline; -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/text-shadow-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/text-shadow-ref.html deleted file mode 100644 index d12360f..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/text-shadow-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue, text-shadow</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; - text-shadow: 0px 0px 5px #0f0; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/text-shadow.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/text-shadow.html deleted file mode 100644 index 433d058..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/text-shadow.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue, text-shadow</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: sans-serif; - text-shadow: 0px 0px 5px #0f0; -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_normal_wrapped-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_normal_wrapped-ref.html deleted file mode 100644 index 56a79a18..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_normal_wrapped-ref.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue, white-space: normal (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 40%; - right: 0; - width: 20%; - text-align: center; -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - white-space: normal -} -</style> -<div class="video"><span class="cue"><span>foo bar baz</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_normal_wrapped.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_normal_wrapped.html deleted file mode 100644 index a44a351..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_normal_wrapped.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue, white-space: normal (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - white-space: normal -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/foo_space_space_bar_LF_baz.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_nowrap_wrapped-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_nowrap_wrapped-ref.html deleted file mode 100644 index ab23711..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_nowrap_wrapped-ref.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue, white-space: nowrap (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 40%; - right: 0; - width: 20%; - text-align: center; -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - white-space: nowrap -} -</style> -<div class="video"><span class="cue"><span>A A A A A A A A A A A</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_nowrap_wrapped.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_nowrap_wrapped.html deleted file mode 100644 index 6e631fc..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_nowrap_wrapped.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue, white-space: nowrap (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - white-space: nowrap -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/white-spaces_long_size_20.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_pre-line_wrapped-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_pre-line_wrapped-ref.html deleted file mode 100644 index 3d7607a11..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_pre-line_wrapped-ref.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue, white-space: pre-line (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 40%; - right: 0; - width: 20%; - text-align: center; -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - white-space: normal -} -</style> -<div class="video"><span class="cue"><span>A A A A A A<br> A A A A A</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_pre-line_wrapped.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_pre-line_wrapped.html deleted file mode 100644 index c2c90cc..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_pre-line_wrapped.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue, white-space: pre-line (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - white-space: pre-line -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/white-spaces_long_size_20.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_pre-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_pre-ref.html deleted file mode 100644 index ad03b21..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_pre-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue, white-space: pre</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - font-family: sans-serif; - text-align: center -} -.cue > span { - background: rgba(0,0,0,0.8); - color: white; - white-space: pre -} -</style> -<div class="video"><span class="cue"><span>A A A A A A</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_pre-wrap_wrapped-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_pre-wrap_wrapped-ref.html deleted file mode 100644 index c92c303..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_pre-wrap_wrapped-ref.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue, white-space: pre-wrap (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 30%; - right: 0; - width: 40%; - font-family: sans-serif; - text-align: center; -} -.cue > span { - background: rgba(0,0,0,0.8); - color: white; - white-space: pre -} -</style> -<div class="video"><span class="cue"><span>A A A A A <br> A <br>A A A A A</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_pre-wrap_wrapped.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_pre-wrap_wrapped.html deleted file mode 100644 index 910ed60..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_pre-wrap_wrapped.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue, white-space: pre-wrap (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - white-space: pre-wrap -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/white-spaces_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_pre.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_pre.html deleted file mode 100644 index 7d91af8..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_pre.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue, white-space: pre</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - white-space: pre -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/white-spaces.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_pre_wrapped-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_pre_wrapped-ref.html deleted file mode 100644 index 65adcd3..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_pre_wrapped-ref.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue, white-space: pre (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 30%; - right: 0; - width: 40%; - font-family: sans-serif; - text-align: center; -} -.cue > span { - background: rgba(0,0,0,0.8); - color: white; - white-space: pre -} -</style> -<div class="video"><span class="cue"><span>A A A A A <br> A <br>A A A A A</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_pre_wrapped.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_pre_wrapped.html deleted file mode 100644 index a757f2e7..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue/white-space_pre_wrapped.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue, white-space: pre (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - white-space: pre -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/white-spaces_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/background_box-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/background_box-ref.html deleted file mode 100644 index 05948c5..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/background_box-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(* *) should match nothing (since the background box is anonymous)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 25%; - right: 0; - width: 50%; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - font-size: 36px; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/background_box.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/background_box.html deleted file mode 100644 index 53fab931..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/background_box.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(* *) should match nothing (since the background box is anonymous)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(* *) { - background:red; - color:yellow -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/background_properties-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/background_properties-ref.html deleted file mode 100644 index af320bde..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/background_properties-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(), background properties</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: #0f0 url('../../media/background.gif') repeat-x top left; - font-size: 36px; - color: green; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/background_properties.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/background_properties.html deleted file mode 100644 index 0bf1b50..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/background_properties.html +++ /dev/null
@@ -1,26 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(), background properties</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(*) { - font-family: Ahem, sans-serif; - background-color: #0f0; - background-image: url('../../media/background.gif'); - background-repeat: repeat-x; - background-position: top left; - color: green; -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/background_shorthand-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/background_shorthand-ref.html deleted file mode 100644 index 567ff07..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/background_shorthand-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(), background shorthand</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: #0f0 url('../../media/background.gif') repeat-x top left; - font-size: 36px; - color: green; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/background_shorthand.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/background_shorthand.html deleted file mode 100644 index 30c3556..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/background_shorthand.html +++ /dev/null
@@ -1,23 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(), background shorthand</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(*) { - font-family: Ahem, sans-serif; - background: #0f0 url('../../media/background.gif') repeat-x top left; - color: green; -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/background_shorthand_css_relative_url-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/background_shorthand_css_relative_url-ref.html deleted file mode 100644 index 4e037deb..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/background_shorthand_css_relative_url-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(), background shorthand, background image URL with relative path from CSS file</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: #0f0 url('../../media/background.gif') repeat-x top left; - font-size: 36px; - color: green; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/background_shorthand_css_relative_url.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/background_shorthand_css_relative_url.html deleted file mode 100644 index 45b594d..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/background_shorthand_css_relative_url.html +++ /dev/null
@@ -1,23 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(), background shorthand, background image URL with relative path from CSS file</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(*) { - font-family: Ahem, sans-serif; - background: #0f0 url('../../media/background.gif') repeat-x top left; - color: green; -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_animation_with_timestamp-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_animation_with_timestamp-ref.html deleted file mode 100644 index 747b525e..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_animation_with_timestamp-ref.html +++ /dev/null
@@ -1,30 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, bold object animation with timestamp, ::cue(b:past) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.green { - color: #80ff80; - font-weight: bold; -} -</style> -<div class="video"><span class="cue"><span><span class="green">This is a test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_animation_with_timestamp.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_animation_with_timestamp.html deleted file mode 100644 index fad1c379..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_animation_with_timestamp.html +++ /dev/null
@@ -1,37 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, bold object animation with timestamp, ::cue(b:past) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(b:past) { - -o-animation: test 9s steps(2, start); - animation: test 9s steps(2, start); -} -@-o-keyframes test { - 0% { - color: #ffffff; - } - 100% { - color: #00ff00; - } -} -@keyframes test { - 0% { - color: #ffffff; - } - 100% { - color: #00ff00; - } -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; takeScreenshotDelayed(200);"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/bold_with_timestamp.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_background_properties-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_background_properties-ref.html deleted file mode 100644 index 40e10546..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_background_properties-ref.html +++ /dev/null
@@ -1,30 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(b), background properties</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - font-size: 36px; - background: rgba(0,0,0,0.8); - color: white; -} -.cue > span > b { - background: #0f0 url('../../../media/background.gif') repeat-x top left; - color: #000; -} -</style> -<div class="video"><span class="cue"><span>This is a <b>test subtitle</b></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_background_properties.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_background_properties.html deleted file mode 100644 index aab70191..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_background_properties.html +++ /dev/null
@@ -1,25 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(b), background properties</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(b) { - font-family: sans-serif; - background-color: #0f0; - background-image: url('../../../media/background.gif'); - background-repeat: repeat-x; - background-position: top left; - color: black; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_bold.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_background_shorthand-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_background_shorthand-ref.html deleted file mode 100644 index 68571ebf5..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_background_shorthand-ref.html +++ /dev/null
@@ -1,30 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(b), background shorthand</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - font-size: 36px; - background: rgba(0,0,0,0.8); - color: white; -} -.cue > span > b { - background: #0f0 url('../../../media/background.gif') repeat-x top left; - color: #000; -} -</style> -<div class="video"><span class="cue"><span>This is a <b>test subtitle</b></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_background_shorthand.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_background_shorthand.html deleted file mode 100644 index fa41bb92..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_background_shorthand.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(b), background shorthand</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(b) { - font-family: sans-serif; - background: #0f0 url('../../../media/background.gif') repeat-x top left; - color: #000; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_bold.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_color-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_color-ref.html deleted file mode 100644 index 1d703ed4..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_color-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(b), color: #0000ff</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.cue > span > b { - color: #0000ff; -} -</style> -<div class="video"><span class="cue"><span>This is a <b>test subtitle</b></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_color.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_color.html deleted file mode 100644 index 7e2c15f..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_color.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(b), color: #0000ff</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(b) { - font-family: sans-serif; - color: #0000ff; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_bold.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_font_properties-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_font_properties-ref.html deleted file mode 100644 index 68c7e5b4..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_font_properties-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(b), font properties</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - font-family: sans-serif; - font-size: 36px; - text-align: center -} -.cue > span { - background: rgba(0,0,0,0.8); - color: white; -} -.cue > span > b { - font: italic small-caps normal 36px/72px sans-serif; -} -</style> -<div class="video"><span class="cue"><span>This is a <b>test subtitle</b></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_font_properties.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_font_properties.html deleted file mode 100644 index 359f8e7..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_font_properties.html +++ /dev/null
@@ -1,25 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(b), font properties</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(b) { - font-style: italic; - font-variant: small-caps; - font-weight: normal; - font-size: 36px; - line-height: 72px; - font-family: sans-serif; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_bold.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_font_shorthand-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_font_shorthand-ref.html deleted file mode 100644 index 6cbd672..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_font_shorthand-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(b), font shorthand</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - font-family: sans-serif; - font-size: 36px; - text-align: center -} -.cue > span { - background: rgba(0,0,0,0.8); - color: white; -} -.cue > span > b { - font: normal small-caps normal 36px/72px sans-serif; -} -</style> -<div class="video"><span class="cue"><span>This is a <b>test subtitle</b></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_font_shorthand.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_font_shorthand.html deleted file mode 100644 index 9489fae..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_font_shorthand.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(b), font shorthand</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(b) { - font: normal small-caps normal 36px/72px sans-serif; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_bold.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_namespace-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_namespace-ref.html deleted file mode 100644 index a0c20ef..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_namespace-ref.html +++ /dev/null
@@ -1,30 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(|b) should match</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px -} -.green { - font-weight: bold; - color: green; -} -</style> -<div class="video"><span class="cue"><span>This is a <span class="green">test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_namespace.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_namespace.html deleted file mode 100644 index cd3c14a..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_namespace.html +++ /dev/null
@@ -1,26 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(|b) should match</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - color: green; -} -::cue(*|b) { - color: red -} -::cue(|b) { - color: green -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_bold.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_outline_properties-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_outline_properties-ref.html deleted file mode 100644 index a771152..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_outline_properties-ref.html +++ /dev/null
@@ -1,33 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(b), outline properties</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.cue > span > b { - display: inline-block; - margin-left: -2px; - margin-right: -2px; - border: solid #00f 2px; - border-bottom: none; -} -</style> -<div class="video"><span class="cue"><span>This is a <b>test subtitle</b></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_outline_properties.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_outline_properties.html deleted file mode 100644 index 9532de91..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_outline_properties.html +++ /dev/null
@@ -1,23 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(b), outline properties</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(b) { - font-family: sans-serif; - outline-style: solid; - outline-color: #00f; - outline-width: 2px; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_bold.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_outline_shorthand-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_outline_shorthand-ref.html deleted file mode 100644 index 46f19dd..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_outline_shorthand-ref.html +++ /dev/null
@@ -1,33 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(b), outline shorthand</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.cue > span > b { - display: inline-block; - margin-left: -2px; - margin-right: -2px; - border: solid #00f 2px; - border-bottom: none; -} -</style> -<div class="video"><span class="cue"><span>This is a <b>test subtitle</b></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_outline_shorthand.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_outline_shorthand.html deleted file mode 100644 index ecb52c90e..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_outline_shorthand.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(b), outline shorthand</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(b) { - font-family: sans-serif; - outline: solid #00f 2px; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_bold.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_text-decoration_line-through-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_text-decoration_line-through-ref.html deleted file mode 100644 index aa984fc..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_text-decoration_line-through-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(b), text-decoration: line-through</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.cue > span > b { - text-decoration: line-through; -} -</style> -<div class="video"><span class="cue"><span>This is a <b>test subtitle</b></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_text-decoration_line-through.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_text-decoration_line-through.html deleted file mode 100644 index 5c3c2379..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_text-decoration_line-through.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(b), text-decoration: line-through</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(b) { - font-family: sans-serif; - text-decoration: line-through; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_bold.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_text-shadow-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_text-shadow-ref.html deleted file mode 100644 index c1d64400..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_text-shadow-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(b), text-shadow</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.cue > span > b { - text-shadow: 0px 0px 5px #0f0; -} -</style> -<div class="video"><span class="cue"><span>This is a <b>test subtitle</b></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_text-shadow.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_text-shadow.html deleted file mode 100644 index 0d83813..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_text-shadow.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(b), text-shadow</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(b) { - font-family: sans-serif; - text-shadow: 0px 0px 5px #0f0; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_bold.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_timestamp_future-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_timestamp_future-ref.html deleted file mode 100644 index bdc4c16d..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_timestamp_future-ref.html +++ /dev/null
@@ -1,30 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, bold object transition with timestamp, ::cue(b:future) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - font-weight: bold; - color: white; -} -.green { - color: #00ff00; -} -</style> -<div class="video"><span class="cue"><span>This is a <span class="green">test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_timestamp_future.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_timestamp_future.html deleted file mode 100644 index b7f7cab..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_timestamp_future.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, bold object transition with timestamp, ::cue(b:future) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(b:future) { - color: #00ff00; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; takeScreenshotDelayed(200);"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/bold_with_2_timestamps.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_timestamp_past-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_timestamp_past-ref.html deleted file mode 100644 index f0fd1ae..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_timestamp_past-ref.html +++ /dev/null
@@ -1,30 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, bold object transition with timestamp, ::cue(b:past) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - font-weight: bold; - color: white; -} -.green { - color: #00ff00; -} -</style> -<div class="video"><span class="cue"><span><span class="green">This is a test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_timestamp_past.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_timestamp_past.html deleted file mode 100644 index 3d388754..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_timestamp_past.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, bold object transition with timestamp, ::cue(b:past) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(b:past) { - color: #00ff00; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; takeScreenshotDelayed(200);"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/bold_with_timestamp.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_transition_with_timestamp-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_transition_with_timestamp-ref.html deleted file mode 100644 index 602480a..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_transition_with_timestamp-ref.html +++ /dev/null
@@ -1,30 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, bold object transition with timestamp, ::cue(b:past) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.green { - color: #80ff80; - font-weight: bold; -} -</style> -<div class="video"><span class="cue"><span><span class="green">This is a test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_transition_with_timestamp.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_transition_with_timestamp.html deleted file mode 100644 index 10ce4eb..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_transition_with_timestamp.html +++ /dev/null
@@ -1,24 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, bold object transition with timestamp, ::cue(b:past) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(b) { - -o-transition: color 9s steps(2, start); - transition: color 9s steps(2, start); -} -::cue(b:past) { - color: #00ff00; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; takeScreenshotDelayed(200);"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/bold_with_timestamp.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_white-space_normal_wrapped-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_white-space_normal_wrapped-ref.html deleted file mode 100644 index 3ba3d4b4..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_white-space_normal_wrapped-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, bold object, ::cue(b), white-space: normal (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 25%; - right: 0; - width: 50%; - text-align: center; -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - font-weight: bold; - white-space: normal -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle that most likely will span over several rows since it's a pretty long cue with a lot of text.</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_white-space_normal_wrapped.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_white-space_normal_wrapped.html deleted file mode 100644 index 614282ee..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_white-space_normal_wrapped.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, bold object, ::cue(b), white-space: normal (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(b) { - white-space: normal -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/bold_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_white-space_nowrap-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_white-space_nowrap-ref.html deleted file mode 100644 index 4aca609..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_white-space_nowrap-ref.html +++ /dev/null
@@ -1,30 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, bold object, ::cue(b), white-space: nowrap (cue does not wrap)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative; - overflow: hidden; -} -.cue { - position: absolute; - bottom: 0; - left: 25%; - right: 0; - width: 50%; - text-align: center; -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - font-weight: bold; - white-space: nowrap -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle that most likely will span over several rows since it's a pretty long cue with a lot of text.</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_white-space_nowrap.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_white-space_nowrap.html deleted file mode 100644 index 65eede6..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_white-space_nowrap.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, bold object, ::cue(b), white-space: nowrap (cue does not wrap)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(b) { - white-space: nowrap -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/bold_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_white-space_pre-line_wrapped-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_white-space_pre-line_wrapped-ref.html deleted file mode 100644 index 19da7439..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_white-space_pre-line_wrapped-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, bold object, ::cue(b), white-space: pre-line (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 25%; - right: 0; - width: 50%; - text-align: center; -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - font-weight: bold; - white-space: pre-line -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle that most likely will span over several rows since it's a pretty long cue with a lot of text.</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_white-space_pre-line_wrapped.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_white-space_pre-line_wrapped.html deleted file mode 100644 index f87af4f..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_white-space_pre-line_wrapped.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, bold object, ::cue(b), white-space: pre-line (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(b) { - white-space: pre-line -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/bold_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_white-space_pre-wrap_wrapped-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_white-space_pre-wrap_wrapped-ref.html deleted file mode 100644 index 4d4eecf..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_white-space_pre-wrap_wrapped-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, bold object, ::cue(b), white-space: pre-wrap (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 25%; - right: 0; - width: 50%; - text-align: center; -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - font-weight: bold; - white-space: pre-wrap -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle that most likely will span over several rows since it's a pretty long cue with a lot of text.</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_white-space_pre-wrap_wrapped.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_white-space_pre-wrap_wrapped.html deleted file mode 100644 index 0156d87..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_white-space_pre-wrap_wrapped.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, bold object, ::cue(b), white-space: pre-wrap (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(b) { - white-space: pre-wrap -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/bold_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_white-space_pre_wrapped-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_white-space_pre_wrapped-ref.html deleted file mode 100644 index 398c090..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_white-space_pre_wrapped-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, bold object, ::cue(b), white-space: pre (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 25%; - right: 0; - width: 50%; - text-align: center; -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - font-weight: bold; - white-space: pre -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle that most <br>likely will span over several <br>rows since it's a pretty long cue <br>with a lot of text.</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_white-space_pre_wrapped.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_white-space_pre_wrapped.html deleted file mode 100644 index f3d34ae..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_white-space_pre_wrapped.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, bold object, ::cue(b), white-space: pre (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(b) { - white-space: pre -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/bold_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_with_class-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_with_class-ref.html deleted file mode 100644 index 7e0b4af..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_with_class-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, bold object with class, ::cue(.foo) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.green { - color: #00ff00; -} -</style> -<div class="video"><span class="cue"><span>This is a <b>test subtitle</b>, <b class="green">test subtitle</b></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_with_class.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_with_class.html deleted file mode 100644 index c5a71b6..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_with_class.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, bold object with class, ::cue(.foo) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(.foo) { - font-family: sans-serif; - color: #00ff00; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_bold_with_class.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_with_class_object_specific_selector-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_with_class_object_specific_selector-ref.html deleted file mode 100644 index 7097530b..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_with_class_object_specific_selector-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, bold object with class, ::cue(b.foo) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.green { - color: #00ff00; -} -</style> -<div class="video"><span class="cue"><span>This is a <b>test subtitle</b>, <b class="green">test subtitle</b></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_with_class_object_specific_selector.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_with_class_object_specific_selector.html deleted file mode 100644 index 93709589..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/bold_object/bold_with_class_object_specific_selector.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, bold object with class, ::cue(b.foo) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(b.foo) { - font-family: sans-serif; - color: #00ff00; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_bold_with_class.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_animation_with_timestamp-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_animation_with_timestamp-ref.html deleted file mode 100644 index 81c6ca5..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_animation_with_timestamp-ref.html +++ /dev/null
@@ -1,30 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, class object animation with timestamp, ::cue(c:past) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.green { - color: #80ff80; - font-weight: bold; -} -</style> -<div class="video"><span class="cue"><span><span class="green">This is a test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_animation_with_timestamp.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_animation_with_timestamp.html deleted file mode 100644 index c1636c6..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_animation_with_timestamp.html +++ /dev/null
@@ -1,37 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, class object animation with timestamp, ::cue(c:past) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(c:past) { - -o-animation: test 9s steps(2, start); - animation: test 9s steps(2, start); -} -@-o-keyframes test { - 0% { - color: #ffffff; - } - 100% { - color: #00ff00; - } -} -@keyframes test { - 0% { - color: #ffffff; - } - 100% { - color: #00ff00; - } -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; takeScreenshotDelayed(200);"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/class_with_timestamp.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_background_properties-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_background_properties-ref.html deleted file mode 100644 index 703daabd..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_background_properties-ref.html +++ /dev/null
@@ -1,30 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(c), background properties</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - font-size: 36px; - background: rgba(0,0,0,0.8); - color: white; -} -.cue > span > span { - background: #0f0 url('../../../media/background.gif') repeat-x top left; - color: #000; -} -</style> -<div class="video"><span class="cue"><span>This is a <span>test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_background_properties.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_background_properties.html deleted file mode 100644 index 5dfb390..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_background_properties.html +++ /dev/null
@@ -1,25 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(c), background properties</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(c) { - font-family: sans-serif; - background-color: #0f0; - background-image: url('../../../media/background.gif'); - background-repeat: repeat-x; - background-position: top left; - color: black; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_class.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_background_shorthand-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_background_shorthand-ref.html deleted file mode 100644 index b66ec76..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_background_shorthand-ref.html +++ /dev/null
@@ -1,30 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(c), background shorthand</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - font-size: 36px; - background: rgba(0,0,0,0.8); - color: white; -} -.cue > span > span { - background: #0f0 url('../../../media/background.gif') repeat-x top left; - color: #000; -} -</style> -<div class="video"><span class="cue"><span>This is a <span>test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_background_shorthand.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_background_shorthand.html deleted file mode 100644 index 1986af9..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_background_shorthand.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(c), background shorthand</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(c) { - font-family: sans-serif; - background: #0f0 url('../../../media/background.gif') repeat-x top left; - color: #000; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_class.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_color-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_color-ref.html deleted file mode 100644 index e665021..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_color-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(c), color: #0000ff</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.cue > span > span { - color: #0000ff; -} -</style> -<div class="video"><span class="cue"><span>This is a <span>test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_color.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_color.html deleted file mode 100644 index e93181b..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_color.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(c), color: #0000ff</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(c) { - font-family: sans-serif; - color: #0000ff; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_class.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_font_properties-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_font_properties-ref.html deleted file mode 100644 index 2c6fec8..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_font_properties-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(c), font properties</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - font-family: sans-serif; - font-size: 36px; - text-align: center -} -.cue > span { - background: rgba(0,0,0,0.8); - color: white; -} -.cue > span > span { - font: italic small-caps bold 36px/72px sans-serif; -} -</style> -<div class="video"><span class="cue"><span>This is a <span>test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_font_properties.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_font_properties.html deleted file mode 100644 index 865f779..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_font_properties.html +++ /dev/null
@@ -1,25 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(c), font properties</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(c) { - font-style: italic; - font-variant: small-caps; - font-weight: bold; - font-size: 36px; - line-height: 72px; - font-family: sans-serif; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_class.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_font_shorthand-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_font_shorthand-ref.html deleted file mode 100644 index 1ea755a3..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_font_shorthand-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(c), font shorthand</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - font-family: sans-serif; - font-size: 36px; - text-align: center -} -.cue > span { - background: rgba(0,0,0,0.8); - color: white; -} -.cue > span > span { - font: normal small-caps bold 36px/72px sans-serif; -} -</style> -<div class="video"><span class="cue"><span>This is a <span>test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_font_shorthand.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_font_shorthand.html deleted file mode 100644 index 5ef4f79b..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_font_shorthand.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(c), font shorthand</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(c) { - font: normal small-caps bold 36px/72px sans-serif; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_class.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_namespace-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_namespace-ref.html deleted file mode 100644 index 4fb9f7c..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_namespace-ref.html +++ /dev/null
@@ -1,30 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(|c) should match</title> -<script src="../../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px -} -.green { - color: green; -} -</style> -<div class="video"><span class="cue"><span>This is a <span class="green">test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_namespace.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_namespace.html deleted file mode 100644 index ee9c840..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_namespace.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(|c) should match</title> -<script src="../../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - color: green; - font-family: Ahem, sans-serif -} -::cue(*|c) { - color: red -} -::cue(|c) { - color: green -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_class.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_outline_properties-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_outline_properties-ref.html deleted file mode 100644 index 0384141..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_outline_properties-ref.html +++ /dev/null
@@ -1,33 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(c), outline properties</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.cue > span > span { - display: inline-block; - margin-left: -2px; - margin-right: -2px; - border: solid #00f 2px; - border-bottom: none; -} -</style> -<div class="video"><span class="cue"><span>This is a <span>test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_outline_properties.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_outline_properties.html deleted file mode 100644 index 3c19cb2a..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_outline_properties.html +++ /dev/null
@@ -1,23 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(c), outline properties</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(c) { - font-family: sans-serif; - outline-style: solid; - outline-color: #00f; - outline-width: 2px; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_class.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_outline_shorthand-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_outline_shorthand-ref.html deleted file mode 100644 index fa6bdb6..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_outline_shorthand-ref.html +++ /dev/null
@@ -1,33 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(c), outline shorthand</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.cue > span > span { - display: inline-block; - margin-left: -2px; - margin-right: -2px; - border: solid #00f 2px; - border-bottom: none; -} -</style> -<div class="video"><span class="cue"><span>This is a <span>test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_outline_shorthand.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_outline_shorthand.html deleted file mode 100644 index a198d73..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_outline_shorthand.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(c), outline shorthand</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(c) { - font-family: sans-serif; - outline: solid #00f 2px; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_class.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_text-decoration_line-through-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_text-decoration_line-through-ref.html deleted file mode 100644 index ceec8b8..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_text-decoration_line-through-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(c), text-decoration: line-through</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.cue > span > span { - text-decoration: line-through; -} -</style> -<div class="video"><span class="cue"><span>This is a <span>test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_text-decoration_line-through.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_text-decoration_line-through.html deleted file mode 100644 index c457cff..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_text-decoration_line-through.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(c), text-decoration: line-through</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(c) { - font-family: sans-serif; - text-decoration: line-through; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_class.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_text-shadow-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_text-shadow-ref.html deleted file mode 100644 index cfd46836..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_text-shadow-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(c), text-shadow</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.cue > span > span { - text-shadow: 0px 0px 5px #0f0; -} -</style> -<div class="video"><span class="cue"><span>This is a <span>test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_text-shadow.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_text-shadow.html deleted file mode 100644 index 6b44d0b..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_text-shadow.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(c), text-shadow</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(c) { - font-family: sans-serif; - text-shadow: 0px 0px 5px #0f0; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_class.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_timestamp_future-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_timestamp_future-ref.html deleted file mode 100644 index 5333596f..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_timestamp_future-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, class object transition with timestamp, ::cue(c:future) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.green { - color: #00ff00; -} -</style> -<div class="video"><span class="cue"><span>This is a <span class="green">test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_timestamp_future.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_timestamp_future.html deleted file mode 100644 index 73353d7..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_timestamp_future.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, class object transition with timestamp, ::cue(c:future) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(c:future) { - color: #00ff00; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; takeScreenshotDelayed(200);"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/class_with_2_timestamps.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_timestamp_past-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_timestamp_past-ref.html deleted file mode 100644 index 5f45ee7..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_timestamp_past-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, class object transition with timestamp, ::cue(c:past) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.green { - color: #00ff00; -} -</style> -<div class="video"><span class="cue"><span><span class="green">This is a test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_timestamp_past.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_timestamp_past.html deleted file mode 100644 index 492ee1e..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_timestamp_past.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, class object transition with timestamp, ::cue(c:past) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(c:past) { - color: #00ff00; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; takeScreenshotDelayed(200);"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/class_with_timestamp.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_transition_with_timestamp-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_transition_with_timestamp-ref.html deleted file mode 100644 index 4a53043a1..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_transition_with_timestamp-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, class object transition with timestamp, ::cue(c:past) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.green { - color: #80ff80; -} -</style> -<div class="video"><span class="cue"><span><span class="green">This is a test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_transition_with_timestamp.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_transition_with_timestamp.html deleted file mode 100644 index 69ed447..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_transition_with_timestamp.html +++ /dev/null
@@ -1,24 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, class object transition with timestamp, ::cue(c:past) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(c) { - -o-transition: color 9s steps(2, start); - transition: color 9s steps(2, start); -} -::cue(c:past) { - color: #00ff00; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; takeScreenshotDelayed(200);"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/class_with_timestamp.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_white-space_normal_wrapped-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_white-space_normal_wrapped-ref.html deleted file mode 100644 index 7cd630d7..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_white-space_normal_wrapped-ref.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, class object, ::cue(c), white-space: normal (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 25%; - right: 0; - width: 50%; - text-align: center; -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - white-space: normal -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle that most likely will span over several rows since it's a pretty long cue with a lot of text.</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_white-space_normal_wrapped.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_white-space_normal_wrapped.html deleted file mode 100644 index e2fd82b..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_white-space_normal_wrapped.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, class object, ::cue(c), white-space: normal (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(c) { - white-space: normal -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/class_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_white-space_nowrap-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_white-space_nowrap-ref.html deleted file mode 100644 index 640a889..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_white-space_nowrap-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, class object, ::cue(c), white-space: nowrap (cue does not wrap)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative; - overflow: hidden; -} -.cue { - position: absolute; - bottom: 0; - left: 25%; - right: 0; - width: 50%; - text-align: center; -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - white-space: nowrap -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle that most likely will span over several rows since it's a pretty long cue with a lot of text.</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_white-space_nowrap.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_white-space_nowrap.html deleted file mode 100644 index bb2fc6a..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_white-space_nowrap.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, class object, ::cue(c), white-space: nowrap (cue does not wrap)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(c) { - white-space: nowrap -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/class_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_white-space_pre-line_wrapped-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_white-space_pre-line_wrapped-ref.html deleted file mode 100644 index 2c9a49d..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_white-space_pre-line_wrapped-ref.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, class object, ::cue(c), white-space: pre-line (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 25%; - right: 0; - width: 50%; - text-align: center; -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - white-space: pre-line -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle that most likely will span over several rows since it's a pretty long cue with a lot of text.</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_white-space_pre-line_wrapped.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_white-space_pre-line_wrapped.html deleted file mode 100644 index 25a3e16a..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_white-space_pre-line_wrapped.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, class object, ::cue(c), white-space: pre-line (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(c) { - white-space: pre-line -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/class_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_white-space_pre-wrap_wrapped-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_white-space_pre-wrap_wrapped-ref.html deleted file mode 100644 index da4db85..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_white-space_pre-wrap_wrapped-ref.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, class object, ::cue(c), white-space: pre-wrap (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 25%; - right: 0; - width: 50%; - text-align: center; -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - white-space: pre-wrap -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle that most likely will span over several rows since it's a pretty long cue with a lot of text.</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_white-space_pre-wrap_wrapped.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_white-space_pre-wrap_wrapped.html deleted file mode 100644 index 7a2fa35..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_white-space_pre-wrap_wrapped.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, class object, ::cue(c), white-space: pre-wrap (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(c) { - white-space: pre-wrap -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/class_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_white-space_pre_wrapped-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_white-space_pre_wrapped-ref.html deleted file mode 100644 index 03852d9..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_white-space_pre_wrapped-ref.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, class object, ::cue(c), white-space: pre (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 25%; - right: 0; - width: 50%; - text-align: center; -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - white-space: pre -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle that most <br>likely will span over several <br>rows since it's a pretty long cue <br>with a lot of text.</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_white-space_pre_wrapped.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_white-space_pre_wrapped.html deleted file mode 100644 index 0926b13..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_white-space_pre_wrapped.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, class object, ::cue(c), white-space: pre (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(c) { - white-space: pre -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/class_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_with_class-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_with_class-ref.html deleted file mode 100644 index 343fccc9..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_with_class-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, class object with class, ::cue(.foo) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.green { - color: #00ff00; -} -</style> -<div class="video"><span class="cue"><span>This is a <span>test subtitle</span>, <span class="green">test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_with_class.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_with_class.html deleted file mode 100644 index c58cec4..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_with_class.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, class object with class, ::cue(.foo) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(.foo) { - font-family: sans-serif; - color: #00ff00; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_class_with_class.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_with_class_object_specific_selector-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_with_class_object_specific_selector-ref.html deleted file mode 100644 index 01081e98..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_with_class_object_specific_selector-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, class object with class, ::cue(c.foo) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.green { - color: #00ff00; -} -</style> -<div class="video"><span class="cue"><span>This is a <span>test subtitle</span>, <span class="green">test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_with_class_object_specific_selector.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_with_class_object_specific_selector.html deleted file mode 100644 index 4fbcd81b..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/class_object/class_with_class_object_specific_selector.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, class object with class, ::cue(c.foo) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(c.foo) { - font-family: sans-serif; - color: #00ff00; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_class_with_class.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/color_hex-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/color_hex-ref.html deleted file mode 100644 index e59a4e4..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/color_hex-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(), color: #60ff60</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: #60ff60; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/color_hex.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/color_hex.html deleted file mode 100644 index 92133f39..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/color_hex.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(), color: #60ff60</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(*) { - font-family: Ahem, sans-serif; - color: #60ff60; -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/color_hsla-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/color_hsla-ref.html deleted file mode 100644 index 9511b8f..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/color_hsla-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(), color: hsla()</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: hsla(100,100%,50%,0.5); -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/color_hsla.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/color_hsla.html deleted file mode 100644 index 9fe59e5..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/color_hsla.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(), color: hsla()</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(*) { - font-family: Ahem, sans-serif; - color: hsla(100,100%,50%,0.5); -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/color_rgba-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/color_rgba-ref.html deleted file mode 100644 index e4507804..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/color_rgba-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(), color: rgba()</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: rgba(128,255,128,0.5); -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/color_rgba.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/color_rgba.html deleted file mode 100644 index 9dd23f9..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/color_rgba.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(), color: rgba()</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(*) { - font-family: Ahem, sans-serif; - color: rgba(128,255,128,0.5); -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/cue_func_selector_single_colon-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/cue_func_selector_single_colon-ref.html deleted file mode 100644 index bc541fb..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/cue_func_selector_single_colon-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, :cue()</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 25%; - right: 0; - width: 50%; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - font-size: 36px; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/cue_func_selector_single_colon.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/cue_func_selector_single_colon.html deleted file mode 100644 index 77528628c..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/cue_func_selector_single_colon.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, :cue()</title> -<style> -html { overflow:hidden } -body { margin:0 } -:cue(*) { - background: red; - color: yellow -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/font_properties-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/font_properties-ref.html deleted file mode 100644 index 41be87a..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/font_properties-ref.html +++ /dev/null
@@ -1,25 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(), font properties</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - font: italic small-caps bold 36px/72px sans-serif; - text-align: center -} -.cue > span { - background: rgba(0,0,0,0.8); - color: white; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle that most likely will span over several rows since it's a pretty long cue with a lot of text.</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/font_properties.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/font_properties.html deleted file mode 100644 index 8f379a9e0..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/font_properties.html +++ /dev/null
@@ -1,25 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(), font properties</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(*) { - font-style: italic; - font-variant: small-caps; - font-weight: bold; - font-size: 36px; - line-height: 72px; - font-family: sans-serif; -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/font_shorthand-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/font_shorthand-ref.html deleted file mode 100644 index 341079b1..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/font_shorthand-ref.html +++ /dev/null
@@ -1,25 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(), font shorthand</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - font: italic small-caps bold 36px/72px sans-serif; - text-align: center -} -.cue > span { - background: rgba(0,0,0,0.8); - color: white; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle that most likely will span over several rows since it's a pretty long cue with a lot of text.</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/font_shorthand.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/font_shorthand.html deleted file mode 100644 index 0706e36..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/font_shorthand.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(), font shorthand</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(*) { - font: italic small-caps bold 36px/72px sans-serif; -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/id_color-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/id_color-ref.html deleted file mode 100644 index b185c0ad..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/id_color-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, cue with ID, ::cue(#foo) selector</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: #00ff00; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/id_color.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/id_color.html deleted file mode 100644 index 748206e..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/id_color.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, cue with ID, ::cue(#foo) selector</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(#foo) { - font-family: Ahem, sans-serif; - color: #00ff00; -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/cue_with_id.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/inherit_values_from_media_element-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/inherit_values_from_media_element-ref.html deleted file mode 100644 index ba554e2..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/inherit_values_from_media_element-ref.html +++ /dev/null
@@ -1,46 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(*), css properties with value inherit should inherit from media element</title> -<style> -.video { - position: absolute; - display: inline-block; - width: 1280px; - height: 720px; - position: relative; - color: #f0f; - white-space: pre-wrap; - font: italic small-caps bold 36px/72px sans-serif; - text-decoration: overline underline line-through; - text-shadow: 0px 0px 5px #0f0; - background: #0f0 url('../../media/background.gif') repeat-x top left; - outline: solid #00f 2px; -} -.videoWhite { - position: absolute; - top: 0; - left: 160px; - width: 960px; - height: 720px;; - background: #fff; - z-index: 1; -} -.cue { - position: absolute; - bottom: 0; - left: 30%; - right: 0; - width: 40%; - text-align: center; - outline: inherit; - text-shadow: inherit; - text-decoration: inherit; - outline-bottom: none; - z-index: 2 -} -.cue > span { - background: #0f0 url('../../media/background.gif') repeat-x top left; - text-decoration: inherit; - white-space: pre-wrap -} -</style> -<div class="video"><div class="videoWhite"></div><span class="cue"><span>A A A A A A A A A A A</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/inherit_values_from_media_element.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/inherit_values_from_media_element.html deleted file mode 100644 index 3870f473..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/inherit_values_from_media_element.html +++ /dev/null
@@ -1,33 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(*), css properties with value inherit should inherit from media element</title> -<style> -video { - color: #f0f; - white-space: pre-wrap; - font: italic small-caps bold 36px/72px sans-serif; - text-decoration: overline underline line-through; - text-shadow: 0px 0px 5px #0f0; - background: #0f0 url('../../media/background.gif') repeat-x top left; - outline: solid #00f 2px; -} -::cue(*) { - white-space: inherit; - font: inherit; - color: inherit; - text-decoration: inherit; - text-shadow: inherit; - background: inherit; - outline: inherit; -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/white-spaces_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_animation_with_timestamp-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_animation_with_timestamp-ref.html deleted file mode 100644 index 8567adb..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_animation_with_timestamp-ref.html +++ /dev/null
@@ -1,30 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, italic object animation with timestamp, ::cue(i:past) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.green { - color: #80ff80; - font-weight: bold; -} -</style> -<div class="video"><span class="cue"><span><span class="green">This is a test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_animation_with_timestamp.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_animation_with_timestamp.html deleted file mode 100644 index afe99ab..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_animation_with_timestamp.html +++ /dev/null
@@ -1,37 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, italic object animation with timestamp, ::cue(i:past) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(i:past) { - -o-animation: test 9s steps(2, start); - animation: test 9s steps(2, start); -} -@-o-keyframes test { - 0% { - color: #ffffff; - } - 100% { - color: #00ff00; - } -} -@keyframes test { - 0% { - color: #ffffff; - } - 100% { - color: #00ff00; - } -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; takeScreenshotDelayed(200);"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/italic_with_timestamp.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_background_properties-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_background_properties-ref.html deleted file mode 100644 index 6cd53d42..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_background_properties-ref.html +++ /dev/null
@@ -1,30 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(i), background properties</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - font-size: 36px; - background: rgba(0,0,0,0.8); - color: white; -} -.cue > span > i { - background: #0f0 url('../../../media/background.gif') repeat-x top left; - color: #000; -} -</style> -<div class="video"><span class="cue"><span>This is a <i>test subtitle</i></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_background_properties.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_background_properties.html deleted file mode 100644 index 41250b81..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_background_properties.html +++ /dev/null
@@ -1,25 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(i), background properties</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(i) { - font-family: sans-serif; - background-color: #0f0; - background-image: url('../../../media/background.gif'); - background-repeat: repeat-x; - background-position: top left; - color: black; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_italic.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_background_shorthand-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_background_shorthand-ref.html deleted file mode 100644 index d4d94a6e..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_background_shorthand-ref.html +++ /dev/null
@@ -1,30 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(i), background shorthand</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - font-size: 36px; - background: rgba(0,0,0,0.8); - color: white; -} -.cue > span > i { - background: #0f0 url('../../../media/background.gif') repeat-x top left; - color: #000; -} -</style> -<div class="video"><span class="cue"><span>This is a <i>test subtitle</i></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_background_shorthand.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_background_shorthand.html deleted file mode 100644 index feaa737..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_background_shorthand.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(i), background shorthand</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(i) { - font-family: sans-serif; - background: #0f0 url('../../../media/background.gif') repeat-x top left; - color: #000; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_italic.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_color-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_color-ref.html deleted file mode 100644 index f7b60d7..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_color-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(i), color: #0000ff</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.cue > span > i { - color: #0000ff; -} -</style> -<div class="video"><span class="cue"><span>This is a <i>test subtitle</i></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_color.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_color.html deleted file mode 100644 index 66e6d7ae..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_color.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(i), color: #0000ff</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(i) { - font-family: sans-serif; - color: #0000ff; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_italic.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_font_properties-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_font_properties-ref.html deleted file mode 100644 index c02042f..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_font_properties-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(i), font properties</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - font-family: sans-serif; - font-size: 36px; - text-align: center -} -.cue > span { - background: rgba(0,0,0,0.8); - color: white; -} -.cue > span > i { - font: italic small-caps bold 36px/72px sans-serif; -} -</style> -<div class="video"><span class="cue"><span>This is a <i>test subtitle</i></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_font_properties.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_font_properties.html deleted file mode 100644 index 2a9f35f..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_font_properties.html +++ /dev/null
@@ -1,25 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(i), font properties</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(i) { - font-style: italic; - font-variant: small-caps; - font-weight: bold; - font-size: 36px; - line-height: 72px; - font-family: sans-serif; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_italic.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_font_shorthand-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_font_shorthand-ref.html deleted file mode 100644 index f00ee60..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_font_shorthand-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(i), font shorthand</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - font-family: sans-serif; - font-size: 36px; - text-align: center -} -.cue > span { - background: rgba(0,0,0,0.8); - color: white; -} -.cue > span > i { - font: normal small-caps bold 36px/72px sans-serif; -} -</style> -<div class="video"><span class="cue"><span>This is a <i>test subtitle</i></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_font_shorthand.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_font_shorthand.html deleted file mode 100644 index cc44e58b..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_font_shorthand.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(i), font shorthand</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(i) { - font: normal small-caps bold 36px/72px sans-serif; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_italic.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_namespace-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_namespace-ref.html deleted file mode 100644 index 6bad23b..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_namespace-ref.html +++ /dev/null
@@ -1,30 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(|i) should match</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px -} -.green { - font-style: italic; - color: green; -} -</style> -<div class="video"><span class="cue"><span>This is a <span class="green">test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_namespace.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_namespace.html deleted file mode 100644 index b6ae9d9..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_namespace.html +++ /dev/null
@@ -1,26 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(|i) should match</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - color: green; -} -::cue(*|i) { - color: red -} -::cue(|i) { - color: green -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_italic.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_outline_properties-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_outline_properties-ref.html deleted file mode 100644 index 849d6e7..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_outline_properties-ref.html +++ /dev/null
@@ -1,33 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(i), outline properties</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.cue > span > i { - display: inline-block; - margin-left: -2px; - margin-right: -2px; - border: solid #00f 2px; - border-bottom: none; -} -</style> -<div class="video"><span class="cue"><span>This is a <i>test subtitle</i></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_outline_properties.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_outline_properties.html deleted file mode 100644 index 121da400..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_outline_properties.html +++ /dev/null
@@ -1,23 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(i), outline properties</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(i) { - font-family: sans-serif; - outline-style: solid; - outline-color: #00f; - outline-width: 2px; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_italic.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_outline_shorthand-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_outline_shorthand-ref.html deleted file mode 100644 index 218eb00..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_outline_shorthand-ref.html +++ /dev/null
@@ -1,33 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(i), outline shorthand</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.cue > span > i { - display: inline-block; - margin-left: -2px; - margin-right: -2px; - border: solid #00f 2px; - border-bottom: none; -} -</style> -<div class="video"><span class="cue"><span>This is a <i>test subtitle</i></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_outline_shorthand.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_outline_shorthand.html deleted file mode 100644 index d2dd446..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_outline_shorthand.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(i), outline shorthand</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(i) { - font-family: sans-serif; - outline: solid #00f 2px; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_italic.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_text-decoration_line-through-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_text-decoration_line-through-ref.html deleted file mode 100644 index c1de8d04a..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_text-decoration_line-through-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(i), text-decoration: line-through</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.cue > span > i { - text-decoration: line-through; -} -</style> -<div class="video"><span class="cue"><span>This is a <i>test subtitle</i></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_text-decoration_line-through.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_text-decoration_line-through.html deleted file mode 100644 index 12d8b69..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_text-decoration_line-through.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(i), text-decoration: line-through</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(i) { - font-family: sans-serif; - text-decoration: line-through; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_italic.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_text-shadow-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_text-shadow-ref.html deleted file mode 100644 index a20a8eb..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_text-shadow-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(i), text-shadow</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.cue > span > i { - text-shadow: 0px 0px 5px #0f0; -} -</style> -<div class="video"><span class="cue"><span>This is a <i>test subtitle</i></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_text-shadow.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_text-shadow.html deleted file mode 100644 index 4659c1d..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_text-shadow.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(i), text-shadow</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(i) { - font-family: sans-serif; - text-shadow: 0px 0px 5px #0f0; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_italic.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_timestamp_future-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_timestamp_future-ref.html deleted file mode 100644 index 17f7709..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_timestamp_future-ref.html +++ /dev/null
@@ -1,30 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, italic object transition with timestamp, ::cue(i:future) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - font-style: italic; - color: white; -} -.green { - color: #00ff00; -} -</style> -<div class="video"><span class="cue"><span>This is a <span class="green">test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_timestamp_future.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_timestamp_future.html deleted file mode 100644 index 26ce197..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_timestamp_future.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, italic object transition with timestamp, ::cue(i:future) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(i:future) { - color: #00ff00; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; takeScreenshotDelayed(200);"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/italic_with_2_timestamps.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_timestamp_past-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_timestamp_past-ref.html deleted file mode 100644 index 6b02c72..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_timestamp_past-ref.html +++ /dev/null
@@ -1,30 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, italic object transition with timestamp, ::cue(i:past) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - font-style: italic; - color: white; -} -.green { - color: #00ff00; -} -</style> -<div class="video"><span class="cue"><span><span class="green">This is a test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_timestamp_past.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_timestamp_past.html deleted file mode 100644 index 6f7facc6..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_timestamp_past.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, italic object transition with timestamp, ::cue(i:past) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(i:past) { - color: #00ff00; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; takeScreenshotDelayed(200);"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/italic_with_timestamp.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_transition_with_timestamp-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_transition_with_timestamp-ref.html deleted file mode 100644 index 9bca411..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_transition_with_timestamp-ref.html +++ /dev/null
@@ -1,30 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, italic object transition with timestamp, ::cue(i:past) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.green { - color: #80ff80; - font-style: italic; -} -</style> -<div class="video"><span class="cue"><span><span class="green">This is a test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_transition_with_timestamp.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_transition_with_timestamp.html deleted file mode 100644 index 58b8c34341..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_transition_with_timestamp.html +++ /dev/null
@@ -1,24 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, italic object transition with timestamp, ::cue(i:past) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(i) { - -o-transition: color 9s steps(2, start); - transition: color 9s steps(2, start); -} -::cue(i:past) { - color: #00ff00; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; takeScreenshotDelayed(200);"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/italic_with_timestamp.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_white-space_normal_wrapped-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_white-space_normal_wrapped-ref.html deleted file mode 100644 index a765d9f..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_white-space_normal_wrapped-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, italic object, ::cue(i), white-space: normal (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 25%; - right: 0; - width: 50%; - text-align: center; -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - font-style: italic; - white-space: normal -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle that most likely will span over several rows since it's a pretty long cue with a lot of text.</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_white-space_normal_wrapped.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_white-space_normal_wrapped.html deleted file mode 100644 index 48dd4f72..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_white-space_normal_wrapped.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, italic object, ::cue(i), white-space: normal (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(i) { - white-space: normal -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/italic_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_white-space_nowrap-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_white-space_nowrap-ref.html deleted file mode 100644 index ee0bd02..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_white-space_nowrap-ref.html +++ /dev/null
@@ -1,30 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, italic object, ::cue(i), white-space: nowrap (cue does not wrap)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative; - overflow: hidden; -} -.cue { - position: absolute; - bottom: 0; - left: 25%; - right: 0; - width: 50%; - text-align: center; -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - font-style: italic; - white-space: nowrap -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle that most likely will span over several rows since it's a pretty long cue with a lot of text.</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_white-space_nowrap.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_white-space_nowrap.html deleted file mode 100644 index ac5f47a..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_white-space_nowrap.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, italic object, ::cue(i), white-space: nowrap (cue does not wrap)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(i) { - white-space: nowrap -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/italic_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_white-space_pre-line_wrapped-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_white-space_pre-line_wrapped-ref.html deleted file mode 100644 index d0177e3..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_white-space_pre-line_wrapped-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, italic object, ::cue(i), white-space: pre-line (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 25%; - right: 0; - width: 50%; - text-align: center; -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - font-style: italic; - white-space: pre-line -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle that most likely will span over several rows since it's a pretty long cue with a lot of text.</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_white-space_pre-line_wrapped.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_white-space_pre-line_wrapped.html deleted file mode 100644 index 203d2506..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_white-space_pre-line_wrapped.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, italic object, ::cue(i), white-space: pre-line (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(i) { - white-space: pre-line -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/italic_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_white-space_pre-wrap_wrapped-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_white-space_pre-wrap_wrapped-ref.html deleted file mode 100644 index 1dfdb7b..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_white-space_pre-wrap_wrapped-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, italic object, ::cue(i), white-space: pre-wrap (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 25%; - right: 0; - width: 50%; - text-align: center; -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - font-style: italic; - white-space: pre-wrap -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle that most likely will span over several rows since it's a pretty long cue with a lot of text.</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_white-space_pre-wrap_wrapped.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_white-space_pre-wrap_wrapped.html deleted file mode 100644 index f9e24bc..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_white-space_pre-wrap_wrapped.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, italic object, ::cue(i), white-space: pre-wrap (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(i) { - white-space: pre-wrap -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/italic_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_white-space_pre_wrapped-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_white-space_pre_wrapped-ref.html deleted file mode 100644 index 2734b32..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_white-space_pre_wrapped-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, italic object, ::cue(i), white-space: pre (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 25%; - right: 0; - width: 50%; - text-align: center; -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - font-style: italic; - white-space: pre -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle that most <br>likely will span over several <br>rows since it's a pretty long cue <br>with a lot of text.</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_white-space_pre_wrapped.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_white-space_pre_wrapped.html deleted file mode 100644 index ab70bec6..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_white-space_pre_wrapped.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, italic object, ::cue(i), white-space: pre (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(i) { - white-space: pre -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/italic_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_with_class-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_with_class-ref.html deleted file mode 100644 index 658c20083..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_with_class-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, italic object with class, ::cue(.foo) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.green { - color: #00ff00; -} -</style> -<div class="video"><span class="cue"><span>This is a <i>test subtitle</i>, <i class="green">test subtitle</i></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_with_class.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_with_class.html deleted file mode 100644 index 2594430..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_with_class.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, italic object with class, ::cue(.foo) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(.foo) { - font-family: sans-serif; - color: #00ff00; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_italic_with_class.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_with_class_object_specific_selector-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_with_class_object_specific_selector-ref.html deleted file mode 100644 index ed73e77..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_with_class_object_specific_selector-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, italic object with class, ::cue(i.foo) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.green { - color: #00ff00; -} -</style> -<div class="video"><span class="cue"><span>This is a <i>test subtitle</i>, <i class="green">test subtitle</i></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_with_class_object_specific_selector.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_with_class_object_specific_selector.html deleted file mode 100644 index acb9e75..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/italic_object/italic_with_class_object_specific_selector.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, italic object with class, ::cue(i.foo) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(i.foo) { - font-family: sans-serif; - color: #00ff00; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_italic_with_class.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/not_allowed_properties-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/not_allowed_properties-ref.html deleted file mode 100644 index c3fcae2c..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/not_allowed_properties-ref.html +++ /dev/null
@@ -1,26 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(), properties that should not affect the cue</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/not_allowed_properties.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/not_allowed_properties.html deleted file mode 100644 index 1a0072a..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/not_allowed_properties.html +++ /dev/null
@@ -1,46 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(), properties that should not affect the cue</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(*) { - border: 2px solid red; - border-radius: 5px; - bottom: 300px; - box-shadow: 5px 5px 5px 5px #123456; - box-sizing: border-box; - clip: rect(0px, 5px, 0px, 5px); - columns: 100px 2; - content: 'hello!'; - display: inline-block; - float: left; - font-family: sans-serif; - height: 90px; - left: -150px; - letter-spacing: 20px; - margin: 20px; - min-height: 100px; - min-width: 100px; - opacity: 0.2; - overflow: scroll; - padding: 20px; - position: absolute; - right: 200px; - text-align: left; - text-indent: 50px; - top: -50px; - width: 140px; - word-spacing: 50px; -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/not_root_selector-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/not_root_selector-ref.html deleted file mode 100644 index fd7ce73..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/not_root_selector-ref.html +++ /dev/null
@@ -1,30 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(:not(:root)) should not match the root</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 25%; - right: 0; - width: 50%; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - font-size: 36px; -} -.cue > span > span { - color: lime -} -</style> -<div class="video"><span class="cue"><span>Foo<span>bar</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/not_root_selector.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/not_root_selector.html deleted file mode 100644 index 5f856ec..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/not_root_selector.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(:not(:root)) should not match the root</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(:not(:root)) { - color:lime -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/foo_c_bar.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/outline_properties-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/outline_properties-ref.html deleted file mode 100644 index c1b2d0a..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/outline_properties-ref.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(), outline properties</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - outline: solid #00f 2px; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: green; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/outline_properties.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/outline_properties.html deleted file mode 100644 index f2a376e..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/outline_properties.html +++ /dev/null
@@ -1,25 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(), outline properties</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(*) { - font-family: Ahem, sans-serif; - outline-style: solid; - outline-color: #00f; - outline-width: 2px; - color: green; -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/outline_shorthand-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/outline_shorthand-ref.html deleted file mode 100644 index d9d0cce..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/outline_shorthand-ref.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(), outline shorthand</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - outline: solid #00f 2px; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: green; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/outline_shorthand.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/outline_shorthand.html deleted file mode 100644 index 93358651..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/outline_shorthand.html +++ /dev/null
@@ -1,23 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(), outline shorthand</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(*) { - font-family: Ahem, sans-serif; - outline: solid #00f 2px; - color: green; -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/root_namespace-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/root_namespace-ref.html deleted file mode 100644 index afb4112..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/root_namespace-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(|*) should match the root</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/root_namespace.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/root_namespace.html deleted file mode 100644 index c5d7675c..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/root_namespace.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(|*) should match the root</title> -<script src="../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif -} -::cue(*|*) { - color: red -} -::cue(|*) { - color: green -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/root_selector-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/root_selector-ref.html deleted file mode 100644 index 7216054c..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/root_selector-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(:root) should match the root</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 25%; - right: 0; - width: 50%; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: lime; - font-size: 36px; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/root_selector.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/root_selector.html deleted file mode 100644 index 64ec9a3..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/root_selector.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(:root) should match the root</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(:root) { - color:lime -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/text-decoration_line-through-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/text-decoration_line-through-ref.html deleted file mode 100644 index 8bf1dd4..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/text-decoration_line-through-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(), text-decoration: line-through</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; - text-decoration: line-through; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/text-decoration_line-through.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/text-decoration_line-through.html deleted file mode 100644 index e29d3f0..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/text-decoration_line-through.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(), text-decoration: line-through</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(*) { - font-family: sans-serif; - text-decoration: line-through; -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/text-decoration_overline-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/text-decoration_overline-ref.html deleted file mode 100644 index 351353b..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/text-decoration_overline-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(), text-decoration: overline</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; - text-decoration: overline; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/text-decoration_overline.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/text-decoration_overline.html deleted file mode 100644 index 5b99326..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/text-decoration_overline.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(), text-decoration: overline</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(*) { - font-family: sans-serif; - text-decoration: overline; -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/text-decoration_overline_underline_line-through-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/text-decoration_overline_underline_line-through-ref.html deleted file mode 100644 index 9a6017a7..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/text-decoration_overline_underline_line-through-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(), text-decoration: overline underline line-through</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; - text-decoration: overline underline line-through; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/text-decoration_overline_underline_line-through.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/text-decoration_overline_underline_line-through.html deleted file mode 100644 index 33f906c..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/text-decoration_overline_underline_line-through.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(), text-decoration: overline underline line-through</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(*) { - font-family: sans-serif; - text-decoration: overline underline line-through; -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/text-decoration_underline-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/text-decoration_underline-ref.html deleted file mode 100644 index 864a930..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/text-decoration_underline-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(), text-decoration: underline</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; - text-decoration: underline; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/text-decoration_underline.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/text-decoration_underline.html deleted file mode 100644 index 74b5955..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/text-decoration_underline.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(), text-decoration: underline</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(*) { - font-family: sans-serif; - text-decoration: underline; -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/text-shadow-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/text-shadow-ref.html deleted file mode 100644 index e3a59193..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/text-shadow-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(), text-shadow</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; - text-shadow: 0px 0px 5px #0f0; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/text-shadow.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/text-shadow.html deleted file mode 100644 index 86b1faf..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/text-shadow.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(), text-shadow</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(*) { - font-family: sans-serif; - text-shadow: 0px 0px 5px #0f0; -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/type_selector_root-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/type_selector_root-ref.html deleted file mode 100644 index 016b3c4..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/type_selector_root-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(root) should match nothing; the root element should have no name</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 25%; - right: 0; - width: 50%; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - font-size: 36px; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/type_selector_root.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/type_selector_root.html deleted file mode 100644 index a53ee2f..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/type_selector_root.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(root) should match nothing; the root element should have no name</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(root) { - color:yellow; - background:red -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_animation_with_timestamp-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_animation_with_timestamp-ref.html deleted file mode 100644 index 7822dd6..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_animation_with_timestamp-ref.html +++ /dev/null
@@ -1,30 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, underline object animation with timestamp, ::cue(u:past) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.green { - color: #80ff80; - font-weight: bold; -} -</style> -<div class="video"><span class="cue"><span><span class="green">This is a test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_animation_with_timestamp.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_animation_with_timestamp.html deleted file mode 100644 index bf86208c..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_animation_with_timestamp.html +++ /dev/null
@@ -1,37 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, underline object animation with timestamp, ::cue(u:past) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(u:past) { - -o-animation: test 9s steps(2, start); - animation: test 9s steps(2, start); -} -@-o-keyframes test { - 0% { - color: #ffffff; - } - 100% { - color: #00ff00; - } -} -@keyframes test { - 0% { - color: #ffffff; - } - 100% { - color: #00ff00; - } -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; takeScreenshotDelayed(200);"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/underline_with_timestamp.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_background_properties-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_background_properties-ref.html deleted file mode 100644 index f065a514..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_background_properties-ref.html +++ /dev/null
@@ -1,30 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(u), background properties</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - font-size: 36px; - background: rgba(0,0,0,0.8); - color: white; -} -.cue > span > u { - background: #0f0 url('../../../media/background.gif') repeat-x top left; - color: #000; -} -</style> -<div class="video"><span class="cue"><span>This is a <u>test subtitle</u></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_background_properties.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_background_properties.html deleted file mode 100644 index ccd637d5..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_background_properties.html +++ /dev/null
@@ -1,25 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(u), background properties</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(u) { - font-family: sans-serif; - background-color: #0f0; - background-image: url('../../../media/background.gif'); - background-repeat: repeat-x; - background-position: top left; - color: black; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_underline.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_background_shorthand-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_background_shorthand-ref.html deleted file mode 100644 index d435823..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_background_shorthand-ref.html +++ /dev/null
@@ -1,30 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(u), background shorthand</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - font-size: 36px; - background: rgba(0,0,0,0.8); - color: white; -} -.cue > span > u { - background: #0f0 url('../../../media/background.gif') repeat-x top left; - color: #000; -} -</style> -<div class="video"><span class="cue"><span>This is a <u>test subtitle</u></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_background_shorthand.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_background_shorthand.html deleted file mode 100644 index 71f4c1aa..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_background_shorthand.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(u), background shorthand</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(u) { - font-family: sans-serif; - background: #0f0 url('../../../media/background.gif') repeat-x top left; - color: #000; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_underline.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_color-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_color-ref.html deleted file mode 100644 index 64367cf..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_color-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(u), color: #0000ff</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.cue > span > u { - color: #0000ff; -} -</style> -<div class="video"><span class="cue"><span>This is a <u>test subtitle</u></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_color.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_color.html deleted file mode 100644 index 0e090bb..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_color.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(u), color: #0000ff</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(u) { - font-family: sans-serif; - color: #0000ff; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_underline.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_font_properties-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_font_properties-ref.html deleted file mode 100644 index edc2f02..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_font_properties-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(u), font properties</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - font-family: sans-serif; - font-size: 36px; - text-align: center -} -.cue > span { - background: rgba(0,0,0,0.8); - color: white; -} -.cue > span > u { - font: italic small-caps normal 36px/72px sans-serif; -} -</style> -<div class="video"><span class="cue"><span>This is a <u>test subtitle</u></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_font_properties.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_font_properties.html deleted file mode 100644 index f7d7d655..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_font_properties.html +++ /dev/null
@@ -1,25 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(u), font properties</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(u) { - font-style: italic; - font-variant: small-caps; - font-weight: normal; - font-size: 36px; - line-height: 72px; - font-family: sans-serif; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_underline.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_font_shorthand-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_font_shorthand-ref.html deleted file mode 100644 index 355f5d7f..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_font_shorthand-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(u), font shorthand</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - font-family: sans-serif; - font-size: 36px; - text-align: center -} -.cue > span { - background: rgba(0,0,0,0.8); - color: white; -} -.cue > span > u { - font: normal small-caps normal 36px/72px sans-serif; -} -</style> -<div class="video"><span class="cue"><span>This is a <u>test subtitle</u></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_font_shorthand.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_font_shorthand.html deleted file mode 100644 index 973c9cf..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_font_shorthand.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(u), font shorthand</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(u) { - font: normal small-caps normal 36px/72px sans-serif; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_underline.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_namespace-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_namespace-ref.html deleted file mode 100644 index 31b61e1..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_namespace-ref.html +++ /dev/null
@@ -1,30 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(|u) should match</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px -} -.green { - text-decoration: underline; - color: green; -} -</style> -<div class="video"><span class="cue"><span>This is a <span class="green">test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_namespace.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_namespace.html deleted file mode 100644 index 12681cb..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_namespace.html +++ /dev/null
@@ -1,26 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(|u) should match</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - color: green; -} -::cue(*|u) { - color: red -} -::cue(|u) { - color: green -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_underline.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_outline_properties-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_outline_properties-ref.html deleted file mode 100644 index 8554b59..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_outline_properties-ref.html +++ /dev/null
@@ -1,33 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(u), outline properties</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.cue > span > u { - display: inline-block; - margin-left: -2px; - margin-right: -2px; - border: solid #00f 2px; - border-bottom: none; -} -</style> -<div class="video"><span class="cue"><span>This is a <u>test subtitle</u></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_outline_properties.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_outline_properties.html deleted file mode 100644 index dfe396a..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_outline_properties.html +++ /dev/null
@@ -1,23 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(u), outline properties</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(u) { - font-family: sans-serif; - outline-style: solid; - outline-color: #00f; - outline-width: 2px; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_underline.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_outline_shorthand-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_outline_shorthand-ref.html deleted file mode 100644 index 6537b87..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_outline_shorthand-ref.html +++ /dev/null
@@ -1,33 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(u), outline shorthand</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.cue > span > u { - display: inline-block; - margin-left: -2px; - margin-right: -2px; - border: solid #00f 2px; - border-bottom: none; -} -</style> -<div class="video"><span class="cue"><span>This is a <u>test subtitle</u></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_outline_shorthand.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_outline_shorthand.html deleted file mode 100644 index 5979539..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_outline_shorthand.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(u), outline shorthand</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(u) { - font-family: sans-serif; - outline: solid #00f 2px; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_underline.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_text-decoration_line-through-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_text-decoration_line-through-ref.html deleted file mode 100644 index cd30f46..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_text-decoration_line-through-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(u), text-decoration: line-through</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.cue > span > u { - text-decoration: line-through; -} -</style> -<div class="video"><span class="cue"><span>This is a <u>test subtitle</u></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_text-decoration_line-through.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_text-decoration_line-through.html deleted file mode 100644 index 34a5fdd..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_text-decoration_line-through.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(u), text-decoration: line-through</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(u) { - font-family: sans-serif; - text-decoration: line-through; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_underline.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_text-shadow-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_text-shadow-ref.html deleted file mode 100644 index 7bbc39f2..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_text-shadow-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(u), text-shadow</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.cue > span > u { - text-shadow: 0px 0px 5px #0f0; -} -</style> -<div class="video"><span class="cue"><span>This is a <u>test subtitle</u></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_text-shadow.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_text-shadow.html deleted file mode 100644 index 6d2e36f..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_text-shadow.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(u), text-shadow</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(u) { - font-family: sans-serif; - text-shadow: 0px 0px 5px #0f0; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_underline.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_timestamp_future-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_timestamp_future-ref.html deleted file mode 100644 index 1fa3755..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_timestamp_future-ref.html +++ /dev/null
@@ -1,31 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, underline object transition with timestamp, ::cue(u:future) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - text-decoration: underline; - color: white; -} -.green { - text-decoration: underline; - color: #00ff00; -} -</style> -<div class="video"><span class="cue"><span>This is a <span class="green">test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_timestamp_future.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_timestamp_future.html deleted file mode 100644 index add41fccd..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_timestamp_future.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, underline object transition with timestamp, ::cue(u:future) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(u:future) { - color: #00ff00; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; takeScreenshotDelayed(200);"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/underline_with_2_timestamps.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_timestamp_past-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_timestamp_past-ref.html deleted file mode 100644 index e32ff05c..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_timestamp_past-ref.html +++ /dev/null
@@ -1,30 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, underline object transition with timestamp, ::cue(u:past) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.green { - text-decoration: underline; - color: #00ff00; -} -</style> -<div class="video"><span class="cue"><span><span class="green">This is a test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_timestamp_past.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_timestamp_past.html deleted file mode 100644 index cfcbf6ca..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_timestamp_past.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, underline object transition with timestamp, ::cue(u:past) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(u:past) { - color: #00ff00; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; takeScreenshotDelayed(200);"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/underline_with_timestamp.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_transition_with_timestamp-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_transition_with_timestamp-ref.html deleted file mode 100644 index 6d5d3fa..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_transition_with_timestamp-ref.html +++ /dev/null
@@ -1,30 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, underline object transition with timestamp, ::cue(u:past) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.green { - color: #80ff80; - text-decoration: underline; -} -</style> -<div class="video"><span class="cue"><span><span class="green">This is a test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_transition_with_timestamp.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_transition_with_timestamp.html deleted file mode 100644 index bf09595f..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_transition_with_timestamp.html +++ /dev/null
@@ -1,24 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, underline object transition with timestamp, ::cue(u:past) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(u) { - -o-transition: color 9s steps(2, start); - transition: color 9s steps(2, start); -} -::cue(u:past) { - color: #00ff00; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; takeScreenshotDelayed(200);"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/underline_with_timestamp.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_white-space_normal_wrapped-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_white-space_normal_wrapped-ref.html deleted file mode 100644 index fe576afa..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_white-space_normal_wrapped-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, underline object, ::cue(u), white-space: normal (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 25%; - right: 0; - width: 50%; - text-align: center; -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - text-decoration: underline; - white-space: normal -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle that most likely will span over several rows since it's a pretty long cue with a lot of text.</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_white-space_normal_wrapped.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_white-space_normal_wrapped.html deleted file mode 100644 index 605adbe4..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_white-space_normal_wrapped.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, voice object, ::cue(u), white-space: normal (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(u) { - white-space: normal -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/underline_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_white-space_nowrap-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_white-space_nowrap-ref.html deleted file mode 100644 index 1dc7af8..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_white-space_nowrap-ref.html +++ /dev/null
@@ -1,30 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, underline object, ::cue(u), white-space: nowrap (cue does not wrap)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative; - overflow: hidden; -} -.cue { - position: absolute; - bottom: 0; - left: 25%; - right: 0; - width: 50%; - text-align: center; -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - text-decoration: underline; - white-space: nowrap -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle that most likely will span over several rows since it's a pretty long cue with a lot of text.</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_white-space_nowrap.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_white-space_nowrap.html deleted file mode 100644 index 98245af..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_white-space_nowrap.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, underline object, ::cue(u), white-space: nowrap (cue does not wrap)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(u) { - white-space: nowrap -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/underline_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_white-space_pre-line_wrapped-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_white-space_pre-line_wrapped-ref.html deleted file mode 100644 index 288d89c..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_white-space_pre-line_wrapped-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, underline object, ::cue(u), white-space: pre-line (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 25%; - right: 0; - width: 50%; - text-align: center; -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - text-decoration: underline; - white-space: pre-line -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle that most likely will span over several rows since it's a pretty long cue with a lot of text.</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_white-space_pre-line_wrapped.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_white-space_pre-line_wrapped.html deleted file mode 100644 index e2084e5..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_white-space_pre-line_wrapped.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, underline object, ::cue(u), white-space: pre-line (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(u) { - white-space: pre-line -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/underline_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_white-space_pre-wrap_wrapped-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_white-space_pre-wrap_wrapped-ref.html deleted file mode 100644 index 8819e44..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_white-space_pre-wrap_wrapped-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, underline object, ::cue(u), white-space: pre-wrap (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 25%; - right: 0; - width: 50%; - text-align: center; -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - text-decoration: underline; - white-space: pre-wrap -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle that most likely will span over several rows since it's a pretty long cue with a lot of text.</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_white-space_pre-wrap_wrapped.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_white-space_pre-wrap_wrapped.html deleted file mode 100644 index 8913b82..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_white-space_pre-wrap_wrapped.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, underline object, ::cue(u), white-space: pre-wrap (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(u) { - white-space: pre-wrap -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/underline_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_white-space_pre_wrapped-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_white-space_pre_wrapped-ref.html deleted file mode 100644 index 2c3b204..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_white-space_pre_wrapped-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, underline object, ::cue(u), white-space: pre (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 25%; - right: 0; - width: 50%; - text-align: center; -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - text-decoration: underline; - white-space: pre -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle that most <br>likely will span over several <br>rows since it's a pretty long cue <br>with a lot of text.</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_white-space_pre_wrapped.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_white-space_pre_wrapped.html deleted file mode 100644 index 597aee115..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_white-space_pre_wrapped.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, underline object, ::cue(u), white-space: pre (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(u) { - white-space: pre -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/underline_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_with_class-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_with_class-ref.html deleted file mode 100644 index b948cc8..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_with_class-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, underline object with class, ::cue(.foo) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.green { - color: #00ff00; -} -</style> -<div class="video"><span class="cue"><span>This is a <u>test subtitle</u>, <u class="green">test subtitle</u></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_with_class.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_with_class.html deleted file mode 100644 index 6e06911a..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_with_class.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, underline object with class, ::cue(.foo) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(.foo) { - font-family: sans-serif; - color: #00ff00; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_underline_with_class.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_with_class_object_specific_selector-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_with_class_object_specific_selector-ref.html deleted file mode 100644 index 9ce9e3b6..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_with_class_object_specific_selector-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, underline object with class, ::cue(u.foo) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.green { - color: #00ff00; -} -</style> -<div class="video"><span class="cue"><span>This is a <u>test subtitle</u>, <u class="green">test subtitle</u></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_with_class_object_specific_selector.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_with_class_object_specific_selector.html deleted file mode 100644 index c6424a40..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/underline_object/underline_with_class_object_specific_selector.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, underline object with class, ::cue(u.foo) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(u.foo) { - font-family: sans-serif; - color: #00ff00; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_underline_with_class.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_animation_with_timestamp-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_animation_with_timestamp-ref.html deleted file mode 100644 index fb57a8f..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_animation_with_timestamp-ref.html +++ /dev/null
@@ -1,30 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, voice object animation with timestamp, ::cue(v:past) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.green { - color: #80ff80; - font-weight: bold; -} -</style> -<div class="video"><span class="cue"><span><span class="green">This is a test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_animation_with_timestamp.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_animation_with_timestamp.html deleted file mode 100644 index 0cc042c..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_animation_with_timestamp.html +++ /dev/null
@@ -1,37 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, voice object animation with timestamp, ::cue(v:past) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(v:past) { - -o-animation: test 9s steps(2, start); - animation: test 9s steps(2, start); -} -@-o-keyframes test { - 0% { - color: #ffffff; - } - 100% { - color: #00ff00; - } -} -@keyframes test { - 0% { - color: #ffffff; - } - 100% { - color: #00ff00; - } -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; takeScreenshotDelayed(200);"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/voice_with_timestamp.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_background_properties-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_background_properties-ref.html deleted file mode 100644 index 7ead3aeb..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_background_properties-ref.html +++ /dev/null
@@ -1,30 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(v), background properties</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - font-size: 36px; - background: rgba(0,0,0,0.8); - color: white; -} -.cue > span > span { - background: #0f0 url('../../../media/background.gif') repeat-x top left; - color: #000; -} -</style> -<div class="video"><span class="cue"><span>This is a <span>test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_background_properties.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_background_properties.html deleted file mode 100644 index 3cb6111..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_background_properties.html +++ /dev/null
@@ -1,25 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(v), background properties</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(v) { - font-family: sans-serif; - background-color: #0f0; - background-image: url('../../../media/background.gif'); - background-repeat: repeat-x; - background-position: top left; - color: black; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_voice.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_background_shorthand-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_background_shorthand-ref.html deleted file mode 100644 index 30ca288..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_background_shorthand-ref.html +++ /dev/null
@@ -1,30 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(v), background shorthand</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - font-size: 36px; - background: rgba(0,0,0,0.8); - color: white; -} -.cue > span > span { - background: #0f0 url('../../../media/background.gif') repeat-x top left; - color: #000; -} -</style> -<div class="video"><span class="cue"><span>This is a <span>test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_background_shorthand.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_background_shorthand.html deleted file mode 100644 index e961fa0..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_background_shorthand.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(v), background shorthand</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(v) { - font-family: sans-serif; - background: #0f0 url('../../../media/background.gif') repeat-x top left; - color: #000; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_voice.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_color-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_color-ref.html deleted file mode 100644 index 8375977..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_color-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(v), color: #0000ff</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.cue > span > span { - color: #0000ff; -} -</style> -<div class="video"><span class="cue"><span>This is a <span>test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_color.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_color.html deleted file mode 100644 index 15a9898..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_color.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(v), color: #0000ff</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(v) { - font-family: sans-serif; - color: #0000ff; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_voice.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_font_properties-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_font_properties-ref.html deleted file mode 100644 index 6675e8c..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_font_properties-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(v), font properties</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - font-family: sans-serif; - font-size: 36px; - text-align: center -} -.cue > span { - background: rgba(0,0,0,0.8); - color: white; -} -.cue > span > span { - font: italic small-caps bold 36px/72px sans-serif; -} -</style> -<div class="video"><span class="cue"><span>This is a <span>test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_font_properties.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_font_properties.html deleted file mode 100644 index 392f1088..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_font_properties.html +++ /dev/null
@@ -1,25 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(v), font properties</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(v) { - font-style: italic; - font-variant: small-caps; - font-weight: bold; - font-size: 36px; - line-height: 72px; - font-family: sans-serif; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_voice.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_font_shorthand-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_font_shorthand-ref.html deleted file mode 100644 index b656ea9..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_font_shorthand-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(v), font shorthand</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - font-family: sans-serif; - font-size: 36px; - text-align: center -} -.cue > span { - background: rgba(0,0,0,0.8); - color: white; -} -.cue > span > span { - font: normal small-caps bold 36px/72px sans-serif; -} -</style> -<div class="video"><span class="cue"><span>This is a <span>test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_font_shorthand.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_font_shorthand.html deleted file mode 100644 index 49cf65a..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_font_shorthand.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(v), font shorthand</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(v) { - font: normal small-caps bold 36px/72px sans-serif; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_voice.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_namespace-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_namespace-ref.html deleted file mode 100644 index cb1dc5b..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_namespace-ref.html +++ /dev/null
@@ -1,30 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(|v) should match</title> -<script src="../../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px -} -.green { - color: green; -} -</style> -<div class="video"><span class="cue"><span>This is a <span class="green">test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_namespace.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_namespace.html deleted file mode 100644 index 630822f..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_namespace.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(|v) should match</title> -<script src="../../../../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - color: green; - font-family: Ahem, sans-serif -} -::cue(*|v) { - color: red -} -::cue(|v) { - color: green -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_voice.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_outline_properties-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_outline_properties-ref.html deleted file mode 100644 index 2d2fd34b..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_outline_properties-ref.html +++ /dev/null
@@ -1,33 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(v), outline properties</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.cue > span > span { - display: inline-block; - margin-left: -2px; - margin-right: -2px; - border: solid #00f 2px; - border-bottom: none; -} -</style> -<div class="video"><span class="cue"><span>This is a <span>test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_outline_properties.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_outline_properties.html deleted file mode 100644 index 6fb3a6a5..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_outline_properties.html +++ /dev/null
@@ -1,23 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(v), outline properties</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(v) { - font-family: sans-serif; - outline-style: solid; - outline-color: #00f; - outline-width: 2px; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_voice.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_outline_shorthand-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_outline_shorthand-ref.html deleted file mode 100644 index 01731bd1..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_outline_shorthand-ref.html +++ /dev/null
@@ -1,33 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(v), outline shorthand</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.cue > span > span { - display: inline-block; - margin-left: -2px; - margin-right: -2px; - border: solid #00f 2px; - border-bottom: none; -} -</style> -<div class="video"><span class="cue"><span>This is a <span>test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_outline_shorthand.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_outline_shorthand.html deleted file mode 100644 index 7342066..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_outline_shorthand.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(v), outline shorthand</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(v) { - font-family: sans-serif; - outline: solid #00f 2px; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_voice.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_text-decoration_line-through-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_text-decoration_line-through-ref.html deleted file mode 100644 index b6bc91f..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_text-decoration_line-through-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(v), text-decoration: line-through</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.cue > span > span { - text-decoration: line-through; -} -</style> -<div class="video"><span class="cue"><span>This is a <span>test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_text-decoration_line-through.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_text-decoration_line-through.html deleted file mode 100644 index 0507036..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_text-decoration_line-through.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(v), text-decoration: line-through</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(v) { - font-family: sans-serif; - text-decoration: line-through; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_voice.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_text-shadow-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_text-shadow-ref.html deleted file mode 100644 index b67b96c..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_text-shadow-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(v), text-shadow</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.cue > span > span { - text-shadow: 0px 0px 5px #0f0; -} -</style> -<div class="video"><span class="cue"><span>This is a <span>test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_text-shadow.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_text-shadow.html deleted file mode 100644 index f69a487..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_text-shadow.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(v), text-shadow</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(v) { - font-family: sans-serif; - text-shadow: 0px 0px 5px #0f0; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_voice.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_timestamp_future-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_timestamp_future-ref.html deleted file mode 100644 index 9face62..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_timestamp_future-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, voice object transition with timestamp, ::cue(v:future) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.green { - color: #00ff00; -} -</style> -<div class="video"><span class="cue"><span>This is a <span class="green">test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_timestamp_future.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_timestamp_future.html deleted file mode 100644 index 98ba0a4..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_timestamp_future.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, voice object transition with timestamp, ::cue(v:future) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(v:future) { - color: #00ff00; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; takeScreenshotDelayed(200);"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/voice_with_2_timestamps.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_timestamp_past-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_timestamp_past-ref.html deleted file mode 100644 index e7bb2ec..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_timestamp_past-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, voice object transition with timestamp, ::cue(v:past) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.green { - color: #00ff00; -} -</style> -<div class="video"><span class="cue"><span><span class="green">This is a test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_timestamp_past.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_timestamp_past.html deleted file mode 100644 index 2106e32..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_timestamp_past.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, voice object transition with timestamp, ::cue(v:past) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(v:past) { - color: #00ff00; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; takeScreenshotDelayed(200);"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/voice_with_timestamp.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_transition_with_timestamp-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_transition_with_timestamp-ref.html deleted file mode 100644 index b672da2..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_transition_with_timestamp-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, voice object transition with timestamp, ::cue(v:past) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.green { - color: #80ff80; -} -</style> -<div class="video"><span class="cue"><span><span class="green">This is a test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_transition_with_timestamp.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_transition_with_timestamp.html deleted file mode 100644 index 00953bc..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_transition_with_timestamp.html +++ /dev/null
@@ -1,24 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, voice object transition with timestamp, ::cue(v:past) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(v) { - -o-transition: color 9s steps(2, start); - transition: color 9s steps(2, start); -} -::cue(v:past) { - color: #00ff00; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; takeScreenshotDelayed(200);"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/voice_with_timestamp.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_voice_attribute-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_voice_attribute-ref.html deleted file mode 100644 index cac9a86..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_voice_attribute-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(v[voice="bar"])</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.green { - color: #00ff00; -} -</style> -<div class="video"><span class="cue"><span>This is a <span>test subtitle</span>, <span class="green">test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_voice_attribute.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_voice_attribute.html deleted file mode 100644 index 6f574bc..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_voice_attribute.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(v[voice="bar"])</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(v[voice="bar"]) { - font-family: sans-serif; - color: #00ff00; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_two_voices.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_white-space_normal_wrapped-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_white-space_normal_wrapped-ref.html deleted file mode 100644 index 046d1a2..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_white-space_normal_wrapped-ref.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, voice object, ::cue(v), white-space: normal (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 25%; - right: 0; - width: 50%; - text-align: center; -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - white-space: normal -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle that most likely will span over several rows since it's a pretty long cue with a lot of text.</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_white-space_normal_wrapped.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_white-space_normal_wrapped.html deleted file mode 100644 index 5917eff..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_white-space_normal_wrapped.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, voice object, ::cue(v), white-space: normal (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(v) { - white-space: normal -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/voice_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_white-space_nowrap-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_white-space_nowrap-ref.html deleted file mode 100644 index 014a2c8..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_white-space_nowrap-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, voice object, ::cue(v), white-space: nowrap (cue does not wrap)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative; - overflow: hidden; -} -.cue { - position: absolute; - bottom: 0; - left: 25%; - right: 0; - width: 50%; - text-align: center; -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - white-space: nowrap -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle that most likely will span over several rows since it's a pretty long cue with a lot of text.</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_white-space_nowrap.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_white-space_nowrap.html deleted file mode 100644 index 602979b..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_white-space_nowrap.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, voice object, ::cue(v), white-space: nowrap (cue does not wrap)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(v) { - white-space: nowrap -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/voice_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_white-space_pre-line_wrapped-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_white-space_pre-line_wrapped-ref.html deleted file mode 100644 index 59d9d35..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_white-space_pre-line_wrapped-ref.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, voice object, ::cue(v), white-space: pre-line (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 25%; - right: 0; - width: 50%; - text-align: center; -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - white-space: pre-line -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle that most likely will span over several rows since it's a pretty long cue with a lot of text.</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_white-space_pre-line_wrapped.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_white-space_pre-line_wrapped.html deleted file mode 100644 index 1d9069f..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_white-space_pre-line_wrapped.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, voice object, ::cue(v), white-space: pre-line (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(v) { - white-space: pre-line -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/voice_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_white-space_pre-wrap_wrapped-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_white-space_pre-wrap_wrapped-ref.html deleted file mode 100644 index c15e59e..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_white-space_pre-wrap_wrapped-ref.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, voice object, ::cue(v), white-space: pre-wrap (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 25%; - right: 0; - width: 50%; - text-align: center; -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - white-space: pre-wrap -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle that most likely will span over several rows since it's a pretty long cue with a lot of text.</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_white-space_pre-wrap_wrapped.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_white-space_pre-wrap_wrapped.html deleted file mode 100644 index 757ea84..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_white-space_pre-wrap_wrapped.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, voice object, ::cue(v), white-space: pre-wrap (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(v) { - white-space: pre-wrap -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/voice_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_white-space_pre_wrapped-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_white-space_pre_wrapped-ref.html deleted file mode 100644 index 9ae0bf8d7..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_white-space_pre_wrapped-ref.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, voice object, ::cue(v), white-space: pre (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 25%; - right: 0; - width: 50%; - text-align: center; -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - white-space: pre -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle that most <br>likely will span over several <br>rows since it's a pretty long cue <br>with a lot of text.</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_white-space_pre_wrapped.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_white-space_pre_wrapped.html deleted file mode 100644 index 1d96f34..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_white-space_pre_wrapped.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, voice object, ::cue(v), white-space: pre (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(v) { - white-space: pre -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/voice_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_with_class-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_with_class-ref.html deleted file mode 100644 index af1988c..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_with_class-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, voice object with class, ::cue(.foo) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.green { - color: #00ff00; -} -</style> -<div class="video"><span class="cue"><span>This is a <span>test subtitle</span>, <span class="green">test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_with_class.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_with_class.html deleted file mode 100644 index a44cbc7..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_with_class.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, voice object with class, ::cue(.foo) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(.foo) { - font-family: sans-serif; - color: #00ff00; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_voice_with_class.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_with_class_object_specific_selector-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_with_class_object_specific_selector-ref.html deleted file mode 100644 index 8e5fc06..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_with_class_object_specific_selector-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, voice object with class, ::cue(v.foo) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - text-align: center -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - font-size: 36px; - color: white; -} -.green { - color: #00ff00; -} -</style> -<div class="video"><span class="cue"><span>This is a <span>test subtitle</span>, <span class="green">test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_with_class_object_specific_selector.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_with_class_object_specific_selector.html deleted file mode 100644 index 83842f45..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/voice_object/voice_with_class_object_specific_selector.html +++ /dev/null
@@ -1,21 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, voice object with class, ::cue(v.foo) selector</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(v.foo) { - font-family: sans-serif; - color: #00ff00; -} -</style> -<script src="../../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../../media/white.webm" type="video/webm"> - <source src="../../../media/white.mp4" type="video/mp4"> - <track src="../../../support/test_voice_with_class.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_normal_wrapped-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_normal_wrapped-ref.html deleted file mode 100644 index bb5f6d5..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_normal_wrapped-ref.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(), white-space: normal (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 40%; - right: 0; - width: 20%; - text-align: center; -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - white-space: normal -} -</style> -<div class="video"><span class="cue"><span>foo bar baz</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_normal_wrapped.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_normal_wrapped.html deleted file mode 100644 index 160ed59..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_normal_wrapped.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(), white-space: normal (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(*) { - white-space: normal -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/foo_space_space_bar_LF_baz.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_nowrap_wrapped-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_nowrap_wrapped-ref.html deleted file mode 100644 index c1519e7..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_nowrap_wrapped-ref.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(), white-space: nowrap (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 40%; - right: 0; - width: 20%; - text-align: center; -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - white-space: nowrap -} -</style> -<div class="video"><span class="cue"><span>A A A A A A A A A A A</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_nowrap_wrapped.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_nowrap_wrapped.html deleted file mode 100644 index 144e2e2..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_nowrap_wrapped.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(), white-space: nowrap (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(*) { - white-space: nowrap -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/white-spaces_long_size_20.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_pre-line_wrapped-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_pre-line_wrapped-ref.html deleted file mode 100644 index bc8214d2..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_pre-line_wrapped-ref.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(), white-space: pre-line (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 40%; - right: 0; - width: 20%; - text-align: center; -} -.cue > span { - font-family: sans-serif; - background: rgba(0,0,0,0.8); - color: white; - white-space: normal -} -</style> -<div class="video"><span class="cue"><span>A A A A A A<br> A A A A A</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_pre-line_wrapped.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_pre-line_wrapped.html deleted file mode 100644 index f14419f..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_pre-line_wrapped.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(), white-space: pre-line (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(*) { - white-space: pre-line -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/white-spaces_long_size_20.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_pre-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_pre-ref.html deleted file mode 100644 index 8b7ccda..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_pre-ref.html +++ /dev/null
@@ -1,27 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(), white-space: pre</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - font-family: sans-serif; - text-align: center -} -.cue > span { - background: rgba(0,0,0,0.8); - color: white; - white-space: pre -} -</style> -<div class="video"><span class="cue"><span>A A A A A A</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_pre-wrap_wrapped-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_pre-wrap_wrapped-ref.html deleted file mode 100644 index 6979f1d8..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_pre-wrap_wrapped-ref.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(), white-space: pre-wrap (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 30%; - right: 0; - width: 40%; - font-family: sans-serif; - text-align: center; -} -.cue > span { - background: rgba(0,0,0,0.8); - color: white; - white-space: pre -} -</style> -<div class="video"><span class="cue"><span>A A A A A <br> A <br>A A A A A</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_pre-wrap_wrapped.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_pre-wrap_wrapped.html deleted file mode 100644 index 3a47c8a..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_pre-wrap_wrapped.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(), white-space: pre-wrap (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(*) { - white-space: pre-wrap -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/white-spaces_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_pre.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_pre.html deleted file mode 100644 index 6f86d5e9..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_pre.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(), white-space: pre</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(*) { - white-space: pre -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/white-spaces.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_pre_wrapped-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_pre_wrapped-ref.html deleted file mode 100644 index 1ad6d44..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_pre_wrapped-ref.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, ::cue(), white-space: pre (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - font-size: 36px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 30%; - right: 0; - width: 40%; - font-family: sans-serif; - text-align: center; -} -.cue > span { - background: rgba(0,0,0,0.8); - color: white; - white-space: pre -} -</style> -<div class="video"><span class="cue"><span>A A A A A <br> A <br>A A A A A</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_pre_wrapped.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_pre_wrapped.html deleted file mode 100644 index c672192..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/cue_function/white-space_pre_wrapped.html +++ /dev/null
@@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, ::cue(), white-space: pre (cue that wraps)</title> -<style> -html { overflow:hidden } -body { margin:0 } -::cue(*) { - white-space: pre -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/white-spaces_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/default_styles/bold_object_default_font-style-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/default_styles/bold_object_default_font-style-ref.html deleted file mode 100644 index 4097c4b..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/default_styles/bold_object_default_font-style-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, default style, bold objects</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - font-family: sans-serif; - font-size: 36px; - text-align: center -} -.cue > span { - background: rgba(0,0,0,0.8); - color: white; -} -.cue > span > span { - font-weight: bold; -} -</style> -<div class="video"><span class="cue"><span>This is a <span>test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/default_styles/bold_object_default_font-style.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/default_styles/bold_object_default_font-style.html deleted file mode 100644 index 1d3c263f0..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/default_styles/bold_object_default_font-style.html +++ /dev/null
@@ -1,17 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, default style, bold objects</title> -<style> -html { overflow:hidden } -body { margin:0 } -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test_bold.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/default_styles/inherit_as_default_value_inherits_values_from_media_element-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/default_styles/inherit_as_default_value_inherits_values_from_media_element-ref.html deleted file mode 100644 index f8d433a..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/default_styles/inherit_as_default_value_inherits_values_from_media_element-ref.html +++ /dev/null
@@ -1,40 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, only css properties with default value inherit should inherit from media element</title> -<style> -.video { - position: absolute; - display: inline-block; - width: 1280px; - height: 720px; - position: relative; - color: #f0f; - white-space: pre-line; - font: italic small-caps bold 36px/72px sans-serif; - text-shadow: 0px 0px 5px #0f0; - background: #0f0 url('../../media/background.gif') repeat-x top left; - outline: solid #00f 2px; -} -.videoWhite { - position: absolute; - top: 0; - left: 160px; - width: 960px; - height: 720px;; - background: #fff; - z-index: 1; -} -.cue { - position: absolute; - bottom: 0; - left: 30%; - right: 0; - width: 40%; - text-align: center; - z-index: 2 -} -.cue > span { - background-color: rgba(0,0,0,0.8); - color: #fff; -} -</style> -<div class="video"><div class="videoWhite"></div><span class="cue"><span>A A A A A A A A A A A</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/default_styles/inherit_as_default_value_inherits_values_from_media_element.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/default_styles/inherit_as_default_value_inherits_values_from_media_element.html deleted file mode 100644 index 89a4872..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/default_styles/inherit_as_default_value_inherits_values_from_media_element.html +++ /dev/null
@@ -1,24 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, only css properties with default value inherit should inherit from media element</title> -<style> -video { - color: #f0f; - white-space: pre-wrap; - font: italic small-caps bold 36px/72px sans-serif; - text-decoration: overline underline line-through; - text-shadow: 0px 0px 5px #0f0; - background: #0f0 url('../../media/background.gif') repeat-x top left; - outline: solid #00f 2px; -} -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/white-spaces_long.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/default_styles/italic_object_default_font-style-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/default_styles/italic_object_default_font-style-ref.html deleted file mode 100644 index b24a259..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/default_styles/italic_object_default_font-style-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, default style, italic objects</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - font-family: sans-serif; - font-size: 36px; - text-align: center -} -.cue > span { - background: rgba(0,0,0,0.8); - color: white; -} -.cue > span > span { - font-style: italic; -} -</style> -<div class="video"><span class="cue"><span>This is a <span>test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/default_styles/italic_object_default_font-style.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/default_styles/italic_object_default_font-style.html deleted file mode 100644 index e4ed9978..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/default_styles/italic_object_default_font-style.html +++ /dev/null
@@ -1,17 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, default style, italic objects</title> -<style> -html { overflow:hidden } -body { margin:0 } -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test_italic.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/default_styles/underline_object_default_font-style-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/default_styles/underline_object_default_font-style-ref.html deleted file mode 100644 index 1b3744ab..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/default_styles/underline_object_default_font-style-ref.html +++ /dev/null
@@ -1,29 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, default style, underline objects</title> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 0; - right: 0; - font-family: sans-serif; - font-size: 36px; - text-align: center -} -.cue > span { - background: rgba(0,0,0,0.8); - color: white; -} -.cue > span > span { - text-decoration: underline; -} -</style> -<div class="video"><span class="cue"><span>This is a <span>test subtitle</span></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/default_styles/underline_object_default_font-style.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/default_styles/underline_object_default_font-style.html deleted file mode 100644 index ff73df8..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/selectors/default_styles/underline_object_default_font-style.html +++ /dev/null
@@ -1,17 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, default style, underline objects</title> -<style> -html { overflow:hidden } -body { margin:0 } -</style> -<script src="../../support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="../../media/white.webm" type="video/webm"> - <source src="../../media/white.mp4" type="video/mp4"> - <track src="../../support/test_underline.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/size_50-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/size_50-ref.html deleted file mode 100644 index 41a0887..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/size_50-ref.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, size:50%</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 25%; - right: 0; - width: 50%; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle that should wrap</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/size_50.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/size_50.html deleted file mode 100644 index d3810ba..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/size_50.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, size:50%</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src="support/size_50.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/2_cues_overlapping_completely_move_up.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/2_cues_overlapping_completely_move_up.vtt deleted file mode 100644 index d4a96792..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/2_cues_overlapping_completely_move_up.vtt +++ /dev/null
@@ -1,7 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 line:50% -This is a test subtitle - -00:00:01.000 --> 00:00:05.000 line:50% -This is another test subtitle
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/2_cues_overlapping_partially_move_down.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/2_cues_overlapping_partially_move_down.vtt deleted file mode 100644 index 227e7db6..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/2_cues_overlapping_partially_move_down.vtt +++ /dev/null
@@ -1,7 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 line:50% -This is a test subtitle - -00:00:01.000 --> 00:00:05.000 line:52% -This is another test subtitle
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/2_cues_overlapping_partially_move_up.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/2_cues_overlapping_partially_move_up.vtt deleted file mode 100644 index 6c99ce3..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/2_cues_overlapping_partially_move_up.vtt +++ /dev/null
@@ -1,7 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 line:50% -This is a test subtitle - -00:00:01.000 --> 00:00:05.000 line:49% -This is another test subtitle
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/align_end.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/align_end.vtt deleted file mode 100644 index 83f691e..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/align_end.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 align:end -This is a test
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/align_end_long.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/align_end_long.vtt deleted file mode 100644 index 09ace0d..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/align_end_long.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 align:end -This is a test subtitle that most likely will span over several rows since it is a pretty long cue with a lot of text.
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/align_middle.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/align_middle.vtt deleted file mode 100644 index cdee051..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/align_middle.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 align:middle -This is a test
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/align_middle_long.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/align_middle_long.vtt deleted file mode 100644 index 8c89441a..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/align_middle_long.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 align:middle -This is a test subtitle that most likely will span over several rows since it is a pretty long cue with a lot of text.
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/align_middle_position_50.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/align_middle_position_50.vtt deleted file mode 100644 index c4437739..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/align_middle_position_50.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 align:middle position:50% -This is a test
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/align_middle_position_gt_50.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/align_middle_position_gt_50.vtt deleted file mode 100644 index 186ae1e..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/align_middle_position_gt_50.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 align:middle position:90% -Awesome!!!
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/align_middle_position_lt_50.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/align_middle_position_lt_50.vtt deleted file mode 100644 index 6928c5dc..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/align_middle_position_lt_50.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 align:middle position:10% -Awesome!!!
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/align_middle_position_lt_50_size_gt_maximum_size.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/align_middle_position_lt_50_size_gt_maximum_size.vtt deleted file mode 100644 index 32bc4ed3..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/align_middle_position_lt_50_size_gt_maximum_size.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 align:middle position:10% size:75% -Awesome!!!
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/align_start.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/align_start.vtt deleted file mode 100644 index 161c457..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/align_start.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 align:start -This is a test
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/align_start_long.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/align_start_long.vtt deleted file mode 100644 index c70ac13..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/align_start_long.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 align:start -This is a test subtitle that most likely will span over several rows since it is a pretty long cue with a lot of text.
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/bidi_ruby.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/bidi_ruby.vtt deleted file mode 100644 index 19e6745..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/bidi_ruby.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 -<ruby>.<rt>א<c>א</c></rt>ab)<rt>x</rt></ruby>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/bold_long.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/bold_long.vtt deleted file mode 100644 index c452682..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/bold_long.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 size:50% -<b>This is a test subtitle that most likely will span over several rows since it's a pretty long cue with a lot of text.</b>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/bold_with_2_timestamps.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/bold_with_2_timestamps.vtt deleted file mode 100644 index 53508f9..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/bold_with_2_timestamps.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:10.000 -<00:00.000><b>This is a </b><00:05.000><b>test subtitle</b>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/bold_with_timestamp.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/bold_with_timestamp.vtt deleted file mode 100644 index 85474b1..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/bold_with_timestamp.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:10.000 -<00:00.000><b>This is a test subtitle</b><00:00.001>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/class_long.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/class_long.vtt deleted file mode 100644 index a551d677..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/class_long.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 size:50% -<c>This is a test subtitle that most likely will span over several rows since it's a pretty long cue with a lot of text.</c>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/class_with_2_timestamps.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/class_with_2_timestamps.vtt deleted file mode 100644 index d95f760..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/class_with_2_timestamps.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:10.000 -<00:00.000><c>This is a </c><00:05.000><c>test subtitle</c>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/class_with_timestamp.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/class_with_timestamp.vtt deleted file mode 100644 index 2e328ab..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/class_with_timestamp.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:10.000 -<00:00.000><c>This is a test subtitle</c><00:00.001>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/cue_with_id.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/cue_with_id.vtt deleted file mode 100644 index 3a8a88c..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/cue_with_id.vtt +++ /dev/null
@@ -1,5 +0,0 @@ -WEBVTT - -foo -00:00:00.000 --> 00:00:05.000 -This is a test subtitle
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/decode_escaped_entities.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/decode_escaped_entities.vtt deleted file mode 100644 index 36373d2..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/decode_escaped_entities.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 -Here are the escaped entities: & < > ‎ ‏
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/foo.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/foo.vtt deleted file mode 100644 index b533895c..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/foo.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 -Foo
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/foo_c_bar.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/foo_c_bar.vtt deleted file mode 100644 index 325df1e5..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/foo_c_bar.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 -Foo<c>bar</c>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/foo_space_space_bar_LF_baz.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/foo_space_space_bar_LF_baz.vtt deleted file mode 100644 index 047d80e..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/foo_space_space_bar_LF_baz.vtt +++ /dev/null
@@ -1,5 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 -foo bar -baz
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/italic_long.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/italic_long.vtt deleted file mode 100644 index 75cbd1e6..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/italic_long.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 size:50% -<i>This is a test subtitle that most likely will span over several rows since it's a pretty long cue with a lot of text.</i>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/italic_with_2_timestamps.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/italic_with_2_timestamps.vtt deleted file mode 100644 index d239c4e..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/italic_with_2_timestamps.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:10.000 -<00:00.000><i>This is a </i><00:05.000><i>test subtitle</i>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/italic_with_timestamp.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/italic_with_timestamp.vtt deleted file mode 100644 index 94b03a20..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/italic_with_timestamp.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:10.000 -<00:00.000><i>This is a test subtitle</i><00:00.001>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/line_-2_long.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/line_-2_long.vtt deleted file mode 100644 index 0f366c1..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/line_-2_long.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 line:-2 size:50% -This is a test subtitle that will line break
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/line_0.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/line_0.vtt deleted file mode 100644 index 18d2bd4..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/line_0.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 line:0 -This is a test subtitle
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/line_1_long.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/line_1_long.vtt deleted file mode 100644 index 414c9de3..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/line_1_long.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 line:1 size:50% -This is a test subtitle that will line break
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/line_50_percent.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/line_50_percent.vtt deleted file mode 100644 index acf612c4..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/line_50_percent.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 line:50% -This is a test subtitle
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/line_integer_and_percent_overlap.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/line_integer_and_percent_overlap.vtt deleted file mode 100644 index 6a1326e9..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/line_integer_and_percent_overlap.vtt +++ /dev/null
@@ -1,7 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:10.000 line:9 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 line:50% -This is another test subtitle
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/line_integer_and_percent_overlap_move_up.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/line_integer_and_percent_overlap_move_up.vtt deleted file mode 100644 index 819f8e2..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/line_integer_and_percent_overlap_move_up.vtt +++ /dev/null
@@ -1,7 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:10.000 line:10 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 line:48% -This is another test subtitle
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/line_percent_and_integer_overlap.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/line_percent_and_integer_overlap.vtt deleted file mode 100644 index 47819a0..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/line_percent_and_integer_overlap.vtt +++ /dev/null
@@ -1,7 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:10.000 line:45% -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 line:9 -This is another test subtitle
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/line_percent_and_integer_overlap_move_up.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/line_percent_and_integer_overlap_move_up.vtt deleted file mode 100644 index 1a7bd7f..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/line_percent_and_integer_overlap_move_up.vtt +++ /dev/null
@@ -1,7 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:10.000 line:55% -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 line:10 -This is another test subtitle
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/one_line_cue_plus_wrapped_cue.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/one_line_cue_plus_wrapped_cue.vtt deleted file mode 100644 index b9b3fecf..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/one_line_cue_plus_wrapped_cue.vtt +++ /dev/null
@@ -1,7 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:10.000 size:70% -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 size:70% -This test subtitle wraps and should be visible
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/refTestWait.js b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/refTestWait.js deleted file mode 100644 index 90e0d1fd..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/refTestWait.js +++ /dev/null
@@ -1,11 +0,0 @@ -var refTestTimer = setTimeout(function() {}, 30000); - -function takeScreenshot() { - clearTimeout(refTestTimer); -} - -function takeScreenshoDelayed(timeout) { - setTimeout(function() { - clearTimeout(refTestTimer); - }, timeout); -}
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/size_50.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/size_50.vtt deleted file mode 100644 index b165af1..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/size_50.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 size:50% -This is a test subtitle that should wrap
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test.vtt deleted file mode 100644 index ab71ec5..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 -This is a test subtitle
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_bold.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_bold.vtt deleted file mode 100644 index 5709f4dd..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_bold.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 -This is a <b>test subtitle</b>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_bold_with_class.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_bold_with_class.vtt deleted file mode 100644 index 1eebeea..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_bold_with_class.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 -This is a <b>test subtitle</b>, <b.foo>test subtitle</b>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_class.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_class.vtt deleted file mode 100644 index 8ee08aad..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_class.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 -This is a <c>test subtitle</c>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_class_with_class.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_class_with_class.vtt deleted file mode 100644 index c17abc9..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_class_with_class.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 -This is a <c>test subtitle</c>, <c.foo>test subtitle</c>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_italic.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_italic.vtt deleted file mode 100644 index 11c2c81..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_italic.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 -This is a <i>test subtitle</i>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_italic_with_class.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_italic_with_class.vtt deleted file mode 100644 index a2255d00..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_italic_with_class.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 -This is a <i>test subtitle</i>, <i.foo>test subtitle</i>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_long.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_long.vtt deleted file mode 100644 index 826ec1d..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_long.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 -This is a test subtitle that most likely will span over several rows since it's a pretty long cue with a lot of text.
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_two_voices.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_two_voices.vtt deleted file mode 100644 index c41fe2e..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_two_voices.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 -This is a <v foo>test subtitle</v>, <v bar>test subtitle</v>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_underline.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_underline.vtt deleted file mode 100644 index 8b1f021..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_underline.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 -This is a <u>test subtitle</u>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_underline_with_class.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_underline_with_class.vtt deleted file mode 100644 index 7894c87e..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_underline_with_class.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 -This is a <u>test subtitle</u>, <u.foo>test subtitle</u>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_voice.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_voice.vtt deleted file mode 100644 index 3e25cff..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_voice.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 -This is a <v foo>test subtitle</v>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_voice_with_class.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_voice_with_class.vtt deleted file mode 100644 index 8f1f375..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/test_voice_with_class.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 -This is a <v foo>test subtitle</v>, <v.foo>test subtitle</v>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/too_many_cues.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/too_many_cues.vtt deleted file mode 100644 index 6deac930..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/too_many_cues.vtt +++ /dev/null
@@ -1,64 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -abcdefghijklmnopqrstuvw
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/too_many_cues_wrapped.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/too_many_cues_wrapped.vtt deleted file mode 100644 index 1363acb..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/too_many_cues_wrapped.vtt +++ /dev/null
@@ -1,61 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 -This is a test subtitle - -00:00:00.000 --> 00:00:10.000 size:70% -This is a test subtitle that wraps and the part after the first subtitle should be cut out
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/u002E_LF_u05D0.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/u002E_LF_u05D0.vtt deleted file mode 100644 index 24cd29b..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/u002E_LF_u05D0.vtt +++ /dev/null
@@ -1,5 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 -. -אab)
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/u002E_u2028_u05D0.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/u002E_u2028_u05D0.vtt deleted file mode 100644 index 9367a09..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/u002E_u2028_u05D0.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 -. אab)
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/u002E_u2029_u05D0.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/u002E_u2029_u05D0.vtt deleted file mode 100644 index 81d21a45..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/u002E_u2029_u05D0.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 -. אab)
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/u0041_first.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/u0041_first.vtt deleted file mode 100644 index 19dc55c..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/u0041_first.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 -Aab)
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/u05D0_first.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/u05D0_first.vtt deleted file mode 100644 index fdc74bf..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/u05D0_first.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 -אab)
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/u0628_first.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/u0628_first.vtt deleted file mode 100644 index a0b953d..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/u0628_first.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 -بab)
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/u06E9_no_strong_dir.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/u06E9_no_strong_dir.vtt deleted file mode 100644 index f097151..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/u06E9_no_strong_dir.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 -۩)
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/underline_long.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/underline_long.vtt deleted file mode 100644 index 7f4ee28..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/underline_long.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 size:50% -<u>This is a test subtitle that most likely will span over several rows since it's a pretty long cue with a lot of text.</u>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/underline_with_2_timestamps.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/underline_with_2_timestamps.vtt deleted file mode 100644 index 54905bf..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/underline_with_2_timestamps.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:10.000 -<00:00.000><u>This is a </u><00:05.000><u>test subtitle</u>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/underline_with_timestamp.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/underline_with_timestamp.vtt deleted file mode 100644 index e6d942b..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/underline_with_timestamp.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:10.000 -<00:00.000><u>This is a test subtitle</u><00:00.001>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/very_long_cue.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/very_long_cue.vtt deleted file mode 100644 index fc62842..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/very_long_cue.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:10.000 size:50% -This is a test subtitle that should wrap several times and become so long that the cue must be cut when displayed, because it does not fit on the screen. This is a test subtitle that should wrap several times and become so long that the cue must be cut when displayed, because it does not fit on the screen.
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/voice_long.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/voice_long.vtt deleted file mode 100644 index 1a443df..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/voice_long.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 size:50% -<v foo>This is a test subtitle that most likely will span over several rows since it's a pretty long cue with a lot of text.</v>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/voice_with_2_timestamps.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/voice_with_2_timestamps.vtt deleted file mode 100644 index b5d2089..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/voice_with_2_timestamps.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:10.000 -<00:00.000><v>This is a </v><00:05.000><v>test subtitle</v>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/voice_with_timestamp.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/voice_with_timestamp.vtt deleted file mode 100644 index 99f4937..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/voice_with_timestamp.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:10.000 -<00:00.000><v>This is a test subtitle</v><00:00.001>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/white-spaces.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/white-spaces.vtt deleted file mode 100644 index 99b772ff..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/white-spaces.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 -A A A A A A
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/white-spaces_long.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/white-spaces_long.vtt deleted file mode 100644 index 53522123..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/white-spaces_long.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 size:40% -A A A A A A A A A A A
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/white-spaces_long_size_20.vtt b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/white-spaces_long_size_20.vtt deleted file mode 100644 index 7807ca32..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/support/white-spaces_long_size_20.vtt +++ /dev/null
@@ -1,4 +0,0 @@ -WEBVTT - -00:00:00.000 --> 00:00:05.000 size:20% -A A A A A A A A A A A
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/too_many_cues-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/too_many_cues-ref.html deleted file mode 100644 index dbf7f5c4..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/too_many_cues-ref.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, too many cues - cues that cannot fit should not be shown</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 15%; - right: 0; - width: 70%; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br></span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/too_many_cues.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/too_many_cues.html deleted file mode 100644 index 0dc3fb2d7..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/too_many_cues.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, too many cues - cues that cannot fit should not be shown</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src="support/too_many_cues.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/too_many_cues_wrapped-ref.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/too_many_cues_wrapped-ref.html deleted file mode 100644 index 87f56c9..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/too_many_cues_wrapped-ref.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> -<title>Reference for WebVTT rendering, too many cues (wrapped) - cues that cannot fit should not be shown</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -.video { - display: inline-block; - width: 1280px; - height: 720px; - position: relative -} -.cue { - position: absolute; - bottom: 0; - left: 15%; - right: 0; - width: 70%; - text-align: center -} -.cue > span { - font-family: Ahem, sans-serif; - background: rgba(0,0,0,0.8); - color: green; - font-size: 36px; -} -</style> -<div class="video"><span class="cue"><span>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle<br>This is a test subtitle</span></span></div>
diff --git a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/too_many_cues_wrapped.html b/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/too_many_cues_wrapped.html deleted file mode 100644 index 052f21e..0000000 --- a/third_party/WebKit/LayoutTests/media/track/opera/track/webvtt/rendering/reftest/too_many_cues_wrapped.html +++ /dev/null
@@ -1,22 +0,0 @@ -<!DOCTYPE html> -<html> -<title>WebVTT rendering, too many cues (wrapped) - cues that cannot fit should not be shown</title> -<script src="../../../../../../../resources/ahem.js"></script> -<style> -html { overflow:hidden } -body { margin:0 } -::cue { - font-family: Ahem, sans-serif; - color: green -} -</style> -<script src="support/refTestWait.js"></script> -<video width="1280" height="720" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();"> - <source src="media/white.webm" type="video/webm"> - <source src="media/white.mp4" type="video/mp4"> - <track src="support/too_many_cues_wrapped.vtt"> -</video> -<script> -document.getElementsByTagName('track')[0].track.mode = 'showing'; -</script> -</html>
diff --git a/third_party/WebKit/LayoutTests/media/track/track-cue-rendering-after-controls-added-expected.html b/third_party/WebKit/LayoutTests/media/track/track-cue-rendering-after-controls-added-expected.html index 14bdb31..f521d72 100644 --- a/third_party/WebKit/LayoutTests/media/track/track-cue-rendering-after-controls-added-expected.html +++ b/third_party/WebKit/LayoutTests/media/track/track-cue-rendering-after-controls-added-expected.html
@@ -7,8 +7,8 @@ </style> <!-- Width should be large enough to display all of the media controls. --> <video controls style="border:1px solid gray; width: 500px;"> - <source src="opera/track/webvtt/rendering/reftest/media/white.webm" type="video/webm"> - <source src="opera/track/webvtt/rendering/reftest/media/white.mp4" type="video/mp4"> + <source src="../content/white.webm" type="video/webm"> + <source src="../content/white.mp4" type="video/mp4"> </video> <script> // Add a single cue at line -2, where it would be if there were controls visible
diff --git a/third_party/WebKit/LayoutTests/media/track/track-cue-rendering-after-controls-added.html b/third_party/WebKit/LayoutTests/media/track/track-cue-rendering-after-controls-added.html index 22bbdae..e622a149 100644 --- a/third_party/WebKit/LayoutTests/media/track/track-cue-rendering-after-controls-added.html +++ b/third_party/WebKit/LayoutTests/media/track/track-cue-rendering-after-controls-added.html
@@ -7,8 +7,8 @@ </style> <!-- Width should be large enough to display all of the media controls. --> <video style="border:1px solid gray; width: 500px;"> - <source src="opera/track/webvtt/rendering/reftest/media/white.webm" type="video/webm"> - <source src="opera/track/webvtt/rendering/reftest/media/white.mp4" type="video/mp4"> + <source src="../content/white.webm" type="video/webm"> + <source src="../content/white.mp4" type="video/mp4"> </video> <script> // Without testRunner.layoutAndPaintAsyncThen there is no guarantee for when the first
diff --git a/third_party/WebKit/LayoutTests/media/track/track-cue-rendering-after-controls-removed-expected.html b/third_party/WebKit/LayoutTests/media/track/track-cue-rendering-after-controls-removed-expected.html index 953c458..5979937 100644 --- a/third_party/WebKit/LayoutTests/media/track/track-cue-rendering-after-controls-removed-expected.html +++ b/third_party/WebKit/LayoutTests/media/track/track-cue-rendering-after-controls-removed-expected.html
@@ -6,8 +6,8 @@ } </style> <video style="border:1px solid gray"> - <source src="opera/track/webvtt/rendering/reftest/media/white.webm" type="video/webm"> - <source src="opera/track/webvtt/rendering/reftest/media/white.mp4" type="video/mp4"> + <source src="../content/white.webm" type="video/webm"> + <source src="../content/white.mp4" type="video/mp4"> </video> <script> // Add a single cue at line -2, where it would be if there were controls visible
diff --git a/third_party/WebKit/LayoutTests/media/track/track-cue-rendering-after-controls-removed.html b/third_party/WebKit/LayoutTests/media/track/track-cue-rendering-after-controls-removed.html index 3a04ef3..1bcfcfa 100644 --- a/third_party/WebKit/LayoutTests/media/track/track-cue-rendering-after-controls-removed.html +++ b/third_party/WebKit/LayoutTests/media/track/track-cue-rendering-after-controls-removed.html
@@ -6,8 +6,8 @@ } </style> <video controls style="border:1px solid gray"> - <source src="opera/track/webvtt/rendering/reftest/media/white.webm" type="video/webm"> - <source src="opera/track/webvtt/rendering/reftest/media/white.mp4" type="video/mp4"> + <source src="../content/white.webm" type="video/webm"> + <source src="../content/white.mp4" type="video/mp4"> </video> <script> // Without testRunner.layoutAndPaintAsyncThen there is no guarantee for when the first
diff --git a/third_party/WebKit/LayoutTests/media/track/track-webvtt-two-cue-layout-after-first-end-expected.html b/third_party/WebKit/LayoutTests/media/track/track-webvtt-two-cue-layout-after-first-end-expected.html index 2f00935..fa89860 100644 --- a/third_party/WebKit/LayoutTests/media/track/track-webvtt-two-cue-layout-after-first-end-expected.html +++ b/third_party/WebKit/LayoutTests/media/track/track-webvtt-two-cue-layout-after-first-end-expected.html
@@ -1,8 +1,8 @@ <!DOCTYPE html> <title>WebVTT two-cue layout after the first cue has ended (reference)</title> <video style="border:1px solid gray"> - <source src="opera/track/webvtt/rendering/reftest/media/white.webm" type="video/webm"> - <source src="opera/track/webvtt/rendering/reftest/media/white.mp4" type="video/mp4"> + <source src="../content/white.webm" type="video/webm"> + <source src="../content/white.mp4" type="video/mp4"> </video> <script> // Add a single cue at line -2, where it would be if there was a first
diff --git a/third_party/WebKit/LayoutTests/media/track/track-webvtt-two-cue-layout-after-first-end.html b/third_party/WebKit/LayoutTests/media/track/track-webvtt-two-cue-layout-after-first-end.html index 7f61d44..dd0ef417 100644 --- a/third_party/WebKit/LayoutTests/media/track/track-webvtt-two-cue-layout-after-first-end.html +++ b/third_party/WebKit/LayoutTests/media/track/track-webvtt-two-cue-layout-after-first-end.html
@@ -1,8 +1,8 @@ <!DOCTYPE html> <title>WebVTT two-cue layout after the first cue has ended</title> <video style="border:1px solid gray"> - <source src="opera/track/webvtt/rendering/reftest/media/white.webm" type="video/webm"> - <source src="opera/track/webvtt/rendering/reftest/media/white.mp4" type="video/mp4"> + <source src="../content/white.webm" type="video/webm"> + <source src="../content/white.mp4" type="video/mp4"> </video> <script> // Without testRunner.layoutAndPaintAsyncThen there is no guarantee for when the first
diff --git a/third_party/WebKit/LayoutTests/media/video-canvas.html b/third_party/WebKit/LayoutTests/media/video-canvas.html index d26150d..3a0c2981 100644 --- a/third_party/WebKit/LayoutTests/media/video-canvas.html +++ b/third_party/WebKit/LayoutTests/media/video-canvas.html
@@ -13,12 +13,14 @@ var results = { current: 0, values: [ - { time: 0, r: 255, g: 255, b: 0 }, - { time: 2, r: 0, g: 9, b: 237 }, - { time: 4, r: 0, g: 32, b: 209 }, - { time: 6, r: 0, g: 54, b: 182 }, - { time: 8, r: 0, g: 77, b: 154 }, - { time: 10, r: 0, g: 97, b: 126 } + // Different platforms may take different RGB conversion paths or + // have slight rounding differences, so allow multiple values here. + { time: 0, r: [255], g: [255], b: [0] }, + { time: 2, r: [0], g: [3], b: [240, 243] }, + { time: 4, r: [0], g: [31], b: [213, 216] }, + { time: 6, r: [0], g: [48], b: [182, 185] }, + { time: 8, r: [0], g: [75, 76], b: [153, 155] }, + { time: 10, r: [0], g: [96, 97], b: [126, 128] } ] }; @@ -46,9 +48,9 @@ var g = frame.data[4 * 2 * width + 16 + 1]; var b = frame.data[4 * 2 * width + 16 + 2]; - assert_equals(r, expected.r); - assert_equals(g, expected.g); - assert_equals(b, expected.b); + assert_true(expected.r.includes(r)); + assert_true(expected.g.includes(g)); + assert_true(expected.b.includes(b)); if (++results.current == results.values.length) t.done();
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/svg/filter-child-repaint-expected.png b/third_party/WebKit/LayoutTests/paint/invalidation/svg/filter-child-repaint-expected.png new file mode 100644 index 0000000..0a0e61e --- /dev/null +++ b/third_party/WebKit/LayoutTests/paint/invalidation/svg/filter-child-repaint-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/svg/invalidate-on-child-layout-expected.png b/third_party/WebKit/LayoutTests/paint/invalidation/svg/invalidate-on-child-layout-expected.png index a355b9c..73983cb 100644 --- a/third_party/WebKit/LayoutTests/paint/invalidation/svg/invalidate-on-child-layout-expected.png +++ b/third_party/WebKit/LayoutTests/paint/invalidation/svg/invalidate-on-child-layout-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/svg/resource-invalidate-on-target-update-expected.png b/third_party/WebKit/LayoutTests/paint/invalidation/svg/resource-invalidate-on-target-update-expected.png index 731c48b8..0f2f5aa 100644 --- a/third_party/WebKit/LayoutTests/paint/invalidation/svg/resource-invalidate-on-target-update-expected.png +++ b/third_party/WebKit/LayoutTests/paint/invalidation/svg/resource-invalidate-on-target-update-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/compositing/masks/mask-with-added-filters-expected.png b/third_party/WebKit/LayoutTests/platform/linux/compositing/masks/mask-with-added-filters-expected.png index 5119710..8bbc8e7 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/compositing/masks/mask-with-added-filters-expected.png +++ b/third_party/WebKit/LayoutTests/platform/linux/compositing/masks/mask-with-added-filters-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/fast/canvas/canvas-composite-video-shadow-expected.png b/third_party/WebKit/LayoutTests/platform/linux/fast/canvas/canvas-composite-video-shadow-expected.png index ee72053..bd46744 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/fast/canvas/canvas-composite-video-shadow-expected.png +++ b/third_party/WebKit/LayoutTests/platform/linux/fast/canvas/canvas-composite-video-shadow-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/fast/canvas/canvas-incremental-repaint-expected.png b/third_party/WebKit/LayoutTests/platform/linux/fast/canvas/canvas-incremental-repaint-expected.png index fc457708..7090a8f34f 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/fast/canvas/canvas-incremental-repaint-expected.png +++ b/third_party/WebKit/LayoutTests/platform/linux/fast/canvas/canvas-incremental-repaint-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/fast/canvas/canvas-shadow-source-in-expected.png b/third_party/WebKit/LayoutTests/platform/linux/fast/canvas/canvas-shadow-source-in-expected.png index 3188b16c..ea3ef0b 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/fast/canvas/canvas-shadow-source-in-expected.png +++ b/third_party/WebKit/LayoutTests/platform/linux/fast/canvas/canvas-shadow-source-in-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/images/color-profile-image-filter-all-expected.png b/third_party/WebKit/LayoutTests/platform/linux/images/color-profile-image-filter-all-expected.png index d167ca5..3a00f5a8 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/images/color-profile-image-filter-all-expected.png +++ b/third_party/WebKit/LayoutTests/platform/linux/images/color-profile-image-filter-all-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/media/video-canvas-expected.txt b/third_party/WebKit/LayoutTests/platform/linux/media/video-canvas-expected.txt deleted file mode 100644 index 1540aa9..0000000 --- a/third_party/WebKit/LayoutTests/platform/linux/media/video-canvas-expected.txt +++ /dev/null
@@ -1,4 +0,0 @@ -This is a testharness.js-based test. -FAIL Test "video" as a source for "canvas". assert_equals: expected 9 but got 8 -Harness: the test ran to completion. -
diff --git a/third_party/WebKit/LayoutTests/platform/linux/paint/filters/clip-filter-overflow-clip-expected.png b/third_party/WebKit/LayoutTests/platform/linux/paint/filters/clip-filter-overflow-clip-expected.png index 1c241ed..8f15a06 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/paint/filters/clip-filter-overflow-clip-expected.png +++ b/third_party/WebKit/LayoutTests/platform/linux/paint/filters/clip-filter-overflow-clip-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/paint/invalidation/svg/filter-width-update-expected.png b/third_party/WebKit/LayoutTests/platform/linux/paint/invalidation/svg/filter-width-update-expected.png index f7c0e8d5..52b8ab1 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/paint/invalidation/svg/filter-width-update-expected.png +++ b/third_party/WebKit/LayoutTests/platform/linux/paint/invalidation/svg/filter-width-update-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/paint/invalidation/svg/window-expected.txt b/third_party/WebKit/LayoutTests/platform/linux/paint/invalidation/svg/window-expected.txt index f02767c..97b804e 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/paint/invalidation/svg/window-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/linux/paint/invalidation/svg/window-expected.txt
@@ -508,7 +508,7 @@ }, { "object": "LayoutSVGContainer g id='windowTitlebarGroupnavWindow'", - "rect": [755, 93, 39, 13], + "rect": [756, 94, 37, 11], "reason": "appeared" }, { @@ -527,91 +527,6 @@ "reason": "appeared" }, { - "object": "LayoutSVGPath line", - "rect": [614, 82, 14, 14], - "reason": "geometry" - }, - { - "object": "LayoutSVGPath line", - "rect": [614, 82, 14, 14], - "reason": "geometry" - }, - { - "object": "LayoutSVGPath line", - "rect": [453, 378, 14, 14], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [453, 378, 14, 14], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [234, 196, 14, 14], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [234, 196, 14, 14], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [781, 93, 14, 13], - "reason": "geometry" - }, - { - "object": "LayoutSVGPath line", - "rect": [781, 93, 14, 13], - "reason": "geometry" - }, - { - "object": "LayoutSVGPath line", - "rect": [781, 93, 14, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [781, 93, 14, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [570, 144, 14, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [570, 144, 14, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [754, 101, 14, 5], - "reason": "geometry" - }, - { - "object": "LayoutSVGPath line", - "rect": [754, 101, 14, 5], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [614, 122, 14, 5], - "reason": "geometry" - }, - { - "object": "LayoutSVGPath line", - "rect": [426, 387, 14, 5], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [348, 191, 14, 5], - "reason": "appeared" - }, - { "object": "LayoutSVGInlineText #text", "rect": [615, 153, 13, 81], "reason": "appeared" @@ -622,169 +537,34 @@ "reason": "appeared" }, { - "object": "LayoutSVGContainer use id='closeButtonsmallWindow'", - "rect": [453, 378, 13, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='closeButton'", - "rect": [453, 378, 13, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='closeButtonnestedWindow'", - "rect": [375, 183, 13, 13], - "reason": "appeared" - }, - { "object": "LayoutSVGPath line", - "rect": [375, 183, 13, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [375, 183, 13, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='closeButton'", - "rect": [375, 183, 13, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='minimizeButtonstatusWindow'", - "rect": [362, 346, 13, 12], - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='minimizeButton'", - "rect": [362, 346, 13, 12], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='minimizeButtonnavWindow'", - "rect": [755, 95, 13, 11], - "reason": "full" - }, - { - "object": "LayoutSVGContainer use id='minimizeButtonnavWindow'", - "rect": [755, 95, 13, 11], - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='minimizeButton'", - "rect": [755, 95, 13, 11], - "reason": "full" - }, - { - "object": "LayoutSVGViewportContainer svg id='minimizeButton'", - "rect": [755, 95, 13, 11], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='minimizeButtonbigWindow'", - "rect": [544, 146, 13, 11], - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='minimizeButton'", - "rect": [544, 146, 13, 11], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='minimizeButtonsmallWindow'", - "rect": [427, 380, 13, 11], - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='minimizeButton'", - "rect": [427, 380, 13, 11], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='minimizeButtoncolourPickerWindow'", - "rect": [208, 198, 13, 11], - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='minimizeButton'", - "rect": [208, 198, 13, 11], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [208, 204, 13, 6], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [544, 152, 13, 5], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [362, 353, 13, 5], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='closeButtonnavWindow'", - "rect": [782, 93, 12, 13], - "reason": "full" - }, - { - "object": "LayoutSVGContainer use id='closeButtonnavWindow'", - "rect": [782, 93, 12, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='closeButton'", - "rect": [782, 93, 12, 13], - "reason": "full" - }, - { - "object": "LayoutSVGViewportContainer svg id='closeButton'", - "rect": [782, 93, 12, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='closeButtonbigWindow'", - "rect": [571, 144, 12, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='closeButton'", - "rect": [571, 144, 12, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='closeButtoncolourPickerWindow'", - "rect": [235, 196, 12, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='closeButton'", - "rect": [235, 196, 12, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='closeButtonnavWindow'", "rect": [615, 83, 12, 12], - "reason": "full" + "reason": "geometry" }, { - "object": "LayoutSVGViewportContainer svg id='closeButton'", + "object": "LayoutSVGPath line", "rect": [615, 83, 12, 12], - "reason": "full" + "reason": "geometry" }, { - "object": "LayoutSVGContainer use id='minimizeButtonnavWindow'", - "rect": [615, 116, 12, 11], - "reason": "full" + "object": "LayoutSVGPath line", + "rect": [782, 94, 12, 11], + "reason": "geometry" }, { - "object": "LayoutSVGViewportContainer svg id='minimizeButton'", - "rect": [615, 116, 12, 11], - "reason": "full" + "object": "LayoutSVGPath line", + "rect": [782, 94, 12, 11], + "reason": "geometry" + }, + { + "object": "LayoutSVGPath line", + "rect": [782, 94, 12, 11], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [782, 94, 12, 11], + "reason": "appeared" }, { "object": "LayoutSVGRect rect", @@ -792,13 +572,33 @@ "reason": "geometry" }, { - "object": "LayoutSVGContainer use id='minimizeButtonnestedWindow'", - "rect": [349, 185, 12, 11], + "object": "LayoutSVGPath line", + "rect": [571, 145, 12, 11], "reason": "appeared" }, { - "object": "LayoutSVGViewportContainer svg id='minimizeButton'", - "rect": [349, 185, 12, 11], + "object": "LayoutSVGPath line", + "rect": [571, 145, 12, 11], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [235, 197, 12, 11], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [235, 197, 12, 11], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [615, 123, 12, 3], + "reason": "geometry" + }, + { + "object": "LayoutSVGPath line", + "rect": [349, 192, 12, 3], "reason": "appeared" }, { @@ -852,11 +652,41 @@ "reason": "appeared" }, { + "object": "LayoutSVGPath line", + "rect": [454, 379, 11, 11], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [454, 379, 11, 11], + "reason": "appeared" + }, + { "object": "LayoutSVGRect rect", "rect": [441, 379, 11, 11], "reason": "appeared" }, { + "object": "LayoutSVGContainer use id='closeButtonnestedWindow'", + "rect": [376, 184, 11, 11], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [376, 184, 11, 11], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [376, 184, 11, 11], + "reason": "appeared" + }, + { + "object": "LayoutSVGViewportContainer svg id='closeButton'", + "rect": [376, 184, 11, 11], + "reason": "appeared" + }, + { "object": "LayoutSVGContainer use id='maximizeButtonnestedWindow'", "rect": [363, 184, 11, 11], "reason": "appeared" @@ -877,6 +707,36 @@ "reason": "appeared" }, { + "object": "LayoutSVGContainer use id='minimizeButtonnavWindow'", + "rect": [756, 95, 11, 10], + "reason": "full" + }, + { + "object": "LayoutSVGContainer use id='minimizeButtonnavWindow'", + "rect": [756, 95, 11, 10], + "reason": "appeared" + }, + { + "object": "LayoutSVGViewportContainer svg id='minimizeButton'", + "rect": [756, 95, 11, 10], + "reason": "full" + }, + { + "object": "LayoutSVGViewportContainer svg id='minimizeButton'", + "rect": [756, 95, 11, 10], + "reason": "appeared" + }, + { + "object": "LayoutSVGContainer use id='minimizeButtonbigWindow'", + "rect": [545, 146, 11, 10], + "reason": "appeared" + }, + { + "object": "LayoutSVGViewportContainer svg id='minimizeButton'", + "rect": [545, 146, 11, 10], + "reason": "appeared" + }, + { "object": "LayoutSVGContainer use id='maximizeButtonsmallWindow'", "rect": [441, 380, 11, 10], "reason": "appeared" @@ -897,6 +757,86 @@ "reason": "appeared" }, { + "object": "LayoutSVGContainer use id='minimizeButtonstatusWindow'", + "rect": [363, 346, 11, 10], + "reason": "appeared" + }, + { + "object": "LayoutSVGViewportContainer svg id='minimizeButton'", + "rect": [363, 346, 11, 10], + "reason": "appeared" + }, + { + "object": "LayoutSVGContainer use id='minimizeButtoncolourPickerWindow'", + "rect": [209, 198, 11, 10], + "reason": "appeared" + }, + { + "object": "LayoutSVGViewportContainer svg id='minimizeButton'", + "rect": [209, 198, 11, 10], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [545, 153, 11, 3], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [363, 354, 11, 3], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [756, 103, 11, 2], + "reason": "geometry" + }, + { + "object": "LayoutSVGPath line", + "rect": [756, 103, 11, 2], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [428, 388, 11, 2], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [209, 206, 11, 2], + "reason": "appeared" + }, + { + "object": "LayoutSVGContainer use id='closeButtonnavWindow'", + "rect": [783, 94, 10, 11], + "reason": "full" + }, + { + "object": "LayoutSVGContainer use id='closeButtonnavWindow'", + "rect": [783, 94, 10, 11], + "reason": "appeared" + }, + { + "object": "LayoutSVGViewportContainer svg id='closeButton'", + "rect": [783, 94, 10, 11], + "reason": "full" + }, + { + "object": "LayoutSVGViewportContainer svg id='closeButton'", + "rect": [783, 94, 10, 11], + "reason": "appeared" + }, + { + "object": "LayoutSVGContainer use id='closeButtonbigWindow'", + "rect": [572, 145, 10, 11], + "reason": "appeared" + }, + { + "object": "LayoutSVGViewportContainer svg id='closeButton'", + "rect": [572, 145, 10, 11], + "reason": "appeared" + }, + { "object": "LayoutSVGContainer use id='maximizeButtonnavWindow'", "rect": [616, 100, 10, 10], "reason": "full" @@ -907,26 +847,76 @@ "reason": "full" }, { + "object": "LayoutSVGContainer use id='closeButtonnavWindow'", + "rect": [616, 84, 10, 10], + "reason": "full" + }, + { "object": "LayoutSVGRect rect", "rect": [616, 84, 10, 10], "reason": "geometry" }, { + "object": "LayoutSVGViewportContainer svg id='closeButton'", + "rect": [616, 84, 10, 10], + "reason": "full" + }, + { + "object": "LayoutSVGContainer use id='closeButtonsmallWindow'", + "rect": [455, 380, 10, 10], + "reason": "appeared" + }, + { "object": "LayoutSVGRect rect", "rect": [455, 380, 10, 10], "reason": "appeared" }, { + "object": "LayoutSVGViewportContainer svg id='closeButton'", + "rect": [455, 380, 10, 10], + "reason": "appeared" + }, + { + "object": "LayoutSVGContainer use id='minimizeButtonsmallWindow'", + "rect": [428, 380, 10, 10], + "reason": "appeared" + }, + { "object": "LayoutSVGRect rect", "rect": [428, 380, 10, 10], "reason": "appeared" }, { + "object": "LayoutSVGViewportContainer svg id='minimizeButton'", + "rect": [428, 380, 10, 10], + "reason": "appeared" + }, + { + "object": "LayoutSVGContainer use id='minimizeButtonnestedWindow'", + "rect": [350, 185, 10, 10], + "reason": "appeared" + }, + { + "object": "LayoutSVGViewportContainer svg id='minimizeButton'", + "rect": [350, 185, 10, 10], + "reason": "appeared" + }, + { + "object": "LayoutSVGContainer use id='closeButtoncolourPickerWindow'", + "rect": [236, 198, 10, 10], + "reason": "appeared" + }, + { "object": "LayoutSVGRect rect", "rect": [236, 198, 10, 10], "reason": "appeared" }, { + "object": "LayoutSVGViewportContainer svg id='closeButton'", + "rect": [236, 198, 10, 10], + "reason": "appeared" + }, + { "object": "LayoutSVGContainer use id='maximizeButtoncolourPickerWindow'", "rect": [223, 198, 10, 10], "reason": "appeared" @@ -947,11 +937,21 @@ "reason": "appeared" }, { + "object": "LayoutSVGContainer use id='minimizeButtonnavWindow'", + "rect": [616, 116, 10, 9], + "reason": "full" + }, + { "object": "LayoutSVGRect rect", "rect": [616, 116, 10, 9], "reason": "geometry" }, { + "object": "LayoutSVGViewportContainer svg id='minimizeButton'", + "rect": [616, 116, 10, 9], + "reason": "full" + }, + { "object": "LayoutSVGRect rect", "rect": [572, 146, 10, 9], "reason": "appeared"
diff --git a/third_party/WebKit/LayoutTests/platform/linux/svg/W3C-SVG-1.1/filters-example-01-b-expected.png b/third_party/WebKit/LayoutTests/platform/linux/svg/W3C-SVG-1.1/filters-example-01-b-expected.png index 05ef45b..27266cfc 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/svg/W3C-SVG-1.1/filters-example-01-b-expected.png +++ b/third_party/WebKit/LayoutTests/platform/linux/svg/W3C-SVG-1.1/filters-example-01-b-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/svg/W3C-SVG-1.1/filters-gauss-01-b-expected.png b/third_party/WebKit/LayoutTests/platform/linux/svg/W3C-SVG-1.1/filters-gauss-01-b-expected.png index e1a533b..de44214a 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/svg/W3C-SVG-1.1/filters-gauss-01-b-expected.png +++ b/third_party/WebKit/LayoutTests/platform/linux/svg/W3C-SVG-1.1/filters-gauss-01-b-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/svg/batik/text/smallFonts-expected.png b/third_party/WebKit/LayoutTests/platform/linux/svg/batik/text/smallFonts-expected.png index 90620142..8e381a7 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/svg/batik/text/smallFonts-expected.png +++ b/third_party/WebKit/LayoutTests/platform/linux/svg/batik/text/smallFonts-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/svg/batik/text/textEffect-expected.png b/third_party/WebKit/LayoutTests/platform/linux/svg/batik/text/textEffect-expected.png index c7313fe..ead2f17 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/svg/batik/text/textEffect-expected.png +++ b/third_party/WebKit/LayoutTests/platform/linux/svg/batik/text/textEffect-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/svg/batik/text/textEffect3-expected.png b/third_party/WebKit/LayoutTests/platform/linux/svg/batik/text/textEffect3-expected.png index 75114e8..432ad79 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/svg/batik/text/textEffect3-expected.png +++ b/third_party/WebKit/LayoutTests/platform/linux/svg/batik/text/textEffect3-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/svg/batik/text/textFeatures-expected.png b/third_party/WebKit/LayoutTests/platform/linux/svg/batik/text/textFeatures-expected.png index 452b18c..5192b9e 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/svg/batik/text/textFeatures-expected.png +++ b/third_party/WebKit/LayoutTests/platform/linux/svg/batik/text/textFeatures-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/svg/batik/text/textProperties-expected.png b/third_party/WebKit/LayoutTests/platform/linux/svg/batik/text/textProperties-expected.png index d4ad910..4c3da9f5 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/svg/batik/text/textProperties-expected.png +++ b/third_party/WebKit/LayoutTests/platform/linux/svg/batik/text/textProperties-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/svg/custom/image-with-transform-clip-filter-expected.png b/third_party/WebKit/LayoutTests/platform/linux/svg/custom/image-with-transform-clip-filter-expected.png index 4af5ac58..e49d4dc3 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/svg/custom/image-with-transform-clip-filter-expected.png +++ b/third_party/WebKit/LayoutTests/platform/linux/svg/custom/image-with-transform-clip-filter-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/svg/custom/recursive-filter-expected.png b/third_party/WebKit/LayoutTests/platform/linux/svg/custom/recursive-filter-expected.png index 212ef69..fb68d046 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/svg/custom/recursive-filter-expected.png +++ b/third_party/WebKit/LayoutTests/platform/linux/svg/custom/recursive-filter-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/svg/custom/text-filter-expected.png b/third_party/WebKit/LayoutTests/platform/linux/svg/custom/text-filter-expected.png index 7608a326..bc0943fd 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/svg/custom/text-filter-expected.png +++ b/third_party/WebKit/LayoutTests/platform/linux/svg/custom/text-filter-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/svg/filters/filter-on-filter-for-text-expected.png b/third_party/WebKit/LayoutTests/platform/linux/svg/filters/filter-on-filter-for-text-expected.png index 2281808..2a7d18c6 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/svg/filters/filter-on-filter-for-text-expected.png +++ b/third_party/WebKit/LayoutTests/platform/linux/svg/filters/filter-on-filter-for-text-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/virtual/display_list_2d_canvas/fast/canvas/canvas-composite-video-shadow-expected.png b/third_party/WebKit/LayoutTests/platform/linux/virtual/display_list_2d_canvas/fast/canvas/canvas-composite-video-shadow-expected.png index ee72053..bd46744 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/virtual/display_list_2d_canvas/fast/canvas/canvas-composite-video-shadow-expected.png +++ b/third_party/WebKit/LayoutTests/platform/linux/virtual/display_list_2d_canvas/fast/canvas/canvas-composite-video-shadow-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/virtual/display_list_2d_canvas/fast/canvas/canvas-incremental-repaint-expected.png b/third_party/WebKit/LayoutTests/platform/linux/virtual/display_list_2d_canvas/fast/canvas/canvas-incremental-repaint-expected.png index fc457708..7090a8f34f 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/virtual/display_list_2d_canvas/fast/canvas/canvas-incremental-repaint-expected.png +++ b/third_party/WebKit/LayoutTests/platform/linux/virtual/display_list_2d_canvas/fast/canvas/canvas-incremental-repaint-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/virtual/display_list_2d_canvas/fast/canvas/canvas-shadow-source-in-expected.png b/third_party/WebKit/LayoutTests/platform/linux/virtual/display_list_2d_canvas/fast/canvas/canvas-shadow-source-in-expected.png index 3188b16c..ea3ef0b 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/virtual/display_list_2d_canvas/fast/canvas/canvas-shadow-source-in-expected.png +++ b/third_party/WebKit/LayoutTests/platform/linux/virtual/display_list_2d_canvas/fast/canvas/canvas-shadow-source-in-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/virtual/exotic-color-space/images/color-profile-image-filter-all-expected.png b/third_party/WebKit/LayoutTests/platform/linux/virtual/exotic-color-space/images/color-profile-image-filter-all-expected.png index cbebdf2..27cee2f756 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/virtual/exotic-color-space/images/color-profile-image-filter-all-expected.png +++ b/third_party/WebKit/LayoutTests/platform/linux/virtual/exotic-color-space/images/color-profile-image-filter-all-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/virtual/spv175/compositing/overflow/mask-with-filter-expected.png b/third_party/WebKit/LayoutTests/platform/linux/virtual/spv175/compositing/overflow/mask-with-filter-expected.png new file mode 100644 index 0000000..38d98ac --- /dev/null +++ b/third_party/WebKit/LayoutTests/platform/linux/virtual/spv175/compositing/overflow/mask-with-filter-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/virtual/spv175/paint/filters/clip-filter-overflow-clip-expected.png b/third_party/WebKit/LayoutTests/platform/linux/virtual/spv175/paint/filters/clip-filter-overflow-clip-expected.png new file mode 100644 index 0000000..8f15a06 --- /dev/null +++ b/third_party/WebKit/LayoutTests/platform/linux/virtual/spv175/paint/filters/clip-filter-overflow-clip-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/virtual/spv175/paint/invalidation/svg/filter-width-update-expected.png b/third_party/WebKit/LayoutTests/platform/linux/virtual/spv175/paint/invalidation/svg/filter-width-update-expected.png new file mode 100644 index 0000000..52b8ab1 --- /dev/null +++ b/third_party/WebKit/LayoutTests/platform/linux/virtual/spv175/paint/invalidation/svg/filter-width-update-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/virtual/spv175/paint/invalidation/svg/window-expected.txt b/third_party/WebKit/LayoutTests/platform/linux/virtual/spv175/paint/invalidation/svg/window-expected.txt deleted file mode 100644 index ac8d95e..0000000 --- a/third_party/WebKit/LayoutTests/platform/linux/virtual/spv175/paint/invalidation/svg/window-expected.txt +++ /dev/null
@@ -1,1170 +0,0 @@ -{ - "layers": [ - { - "name": "LayoutView #document", - "bounds": [800, 600], - "contentsOpaque": true, - "backgroundColor": "#FFFFFF", - "paintInvalidations": [ - { - "object": "LayoutSVGContainer g id='bigWindow'", - "rect": [37, 142, 551, 394], - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect id='titleBarbigWindow'", - "rect": [37, 142, 551, 17], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g id='nestedWindow'", - "rect": [76, 181, 316, 238], - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect id='titleBarnestedWindow'", - "rect": [76, 181, 316, 17], - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect id='decoGroupMinimizednavWindow'", - "rect": [612, 80, 187, 18], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g id='navWindow'", - "rect": [623, 91, 176, 160], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g id='colourPickerWindow'", - "rect": [76, 194, 176, 144], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g id='smallWindow'", - "rect": [311, 376, 160, 145], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g id='statusWindow'", - "rect": [248, 343, 144, 66], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g id='minimalWindow'", - "rect": [38, 475, 121, 50], - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect", - "rect": [612, 80, 18, 160], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='closeButtonnestedWindow'", - "rect": [374, 182, 15, 15], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='minimizeButtonnavWindow'", - "rect": [754, 94, 15, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='minimizeButtonnavWindow'", - "rect": [754, 94, 15, 13], - "reason": "paint property change" - }, - { - "object": "LayoutSVGContainer use id='minimizeButtonbigWindow'", - "rect": [543, 145, 15, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='minimizeButtonstatusWindow'", - "rect": [361, 345, 15, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='minimizeButtoncolourPickerWindow'", - "rect": [207, 197, 15, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGText text", - "rect": [615, 153, 14, 81], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='closeButtonnavWindow'", - "rect": [781, 92, 14, 15], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='closeButtonnavWindow'", - "rect": [781, 92, 14, 15], - "reason": "paint property change" - }, - { - "object": "LayoutSVGContainer use id='closeButtonbigWindow'", - "rect": [570, 143, 14, 15], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='closeButtoncolourPickerWindow'", - "rect": [234, 195, 14, 15], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='closeButtonnavWindow'", - "rect": [614, 82, 14, 14], - "reason": "paint property change" - }, - { - "object": "LayoutSVGContainer use id='closeButtonsmallWindow'", - "rect": [453, 378, 14, 14], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='minimizeButtonnavWindow'", - "rect": [614, 115, 14, 13], - "reason": "paint property change" - }, - { - "object": "LayoutSVGContainer use id='minimizeButtonsmallWindow'", - "rect": [426, 379, 14, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='minimizeButtonnestedWindow'", - "rect": [348, 184, 14, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='maximizeButtonnavWindow'", - "rect": [615, 99, 12, 11], - "reason": "paint property change" - }, - { - "object": "LayoutSVGContainer use id='maximizeButtonstatusWindow'", - "rect": [376, 345, 11, 12], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='maximizeButtonnavWindow'", - "rect": [769, 94, 11, 11], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='maximizeButtonnavWindow'", - "rect": [769, 94, 11, 11], - "reason": "paint property change" - }, - { - "object": "LayoutSVGContainer use id='maximizeButtonbigWindow'", - "rect": [558, 145, 11, 11], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='maximizeButtonsmallWindow'", - "rect": [441, 379, 11, 11], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='maximizeButtonnestedWindow'", - "rect": [363, 184, 11, 11], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='maximizeButtoncolourPickerWindow'", - "rect": [222, 197, 11, 11], - "reason": "appeared" - } - ] - } - ], - "objectPaintInvalidations": [ - { - "object": "LayoutSVGContainer g id='Windows'", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g id='navWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g id='windowMainGroupnavWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g", - "reason": "appeared" - }, - { - "object": "LayoutSVGText text id='textNavWindow'", - "reason": "appeared" - }, - { - "object": "RootInlineBox", - "reason": "appeared" - }, - { - "object": "LayoutSVGInlineText #text", - "reason": "appeared" - }, - { - "object": "InlineTextBox 'This window should'", - "reason": "appeared" - }, - { - "object": "LayoutSVGTSpan tspan", - "reason": "appeared" - }, - { - "object": "InlineFlowBox", - "reason": "appeared" - }, - { - "object": "LayoutSVGInlineText #text", - "reason": "appeared" - }, - { - "object": "InlineTextBox 'contain navigation tools'", - "reason": "appeared" - }, - { - "object": "LayoutSVGTSpan tspan", - "reason": "appeared" - }, - { - "object": "InlineFlowBox", - "reason": "appeared" - }, - { - "object": "LayoutSVGInlineText #text", - "reason": "appeared" - }, - { - "object": "InlineTextBox 'Click on button'", - "reason": "appeared" - }, - { - "object": "LayoutSVGTSpan tspan", - "reason": "appeared" - }, - { - "object": "InlineFlowBox", - "reason": "appeared" - }, - { - "object": "LayoutSVGInlineText #text", - "reason": "appeared" - }, - { - "object": "InlineTextBox ''Resize Navigation Window' for a'", - "reason": "appeared" - }, - { - "object": "LayoutSVGTSpan tspan", - "reason": "appeared" - }, - { - "object": "InlineFlowBox", - "reason": "appeared" - }, - { - "object": "LayoutSVGInlineText #text", - "reason": "appeared" - }, - { - "object": "InlineTextBox 'random resize of this Window'", - "reason": "appeared" - }, - { - "object": "LayoutSVGTSpan tspan", - "reason": "appeared" - }, - { - "object": "InlineFlowBox", - "reason": "appeared" - }, - { - "object": "LayoutSVGInlineText #text", - "reason": "appeared" - }, - { - "object": "InlineTextBox 'Note that this window also'", - "reason": "appeared" - }, - { - "object": "LayoutSVGTSpan tspan", - "reason": "appeared" - }, - { - "object": "InlineFlowBox", - "reason": "appeared" - }, - { - "object": "LayoutSVGInlineText #text", - "reason": "appeared" - }, - { - "object": "InlineTextBox 'features a window decoration'", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect", - "reason": "appeared" - }, - { - "object": "LayoutSVGText text", - "reason": "appeared" - }, - { - "object": "RootInlineBox", - "reason": "appeared" - }, - { - "object": "LayoutSVGInlineText #text", - "reason": "appeared" - }, - { - "object": "InlineTextBox 'Statusbar'", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g id='windowTitlebarGroupnavWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='closeButtonnavWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='closeButton'", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect", - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='maximizeButtonnavWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='maximizeButton'", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='minimizeButtonnavWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='minimizeButton'", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect", - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g id='bigWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g id='windowMainGroupbigWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect", - "reason": "appeared" - }, - { - "object": "LayoutSVGText text", - "reason": "appeared" - }, - { - "object": "RootInlineBox", - "reason": "appeared" - }, - { - "object": "LayoutSVGInlineText #text", - "reason": "appeared" - }, - { - "object": "InlineTextBox 'This is a big movable window'", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g id='nestedWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g id='windowMainGroupnestedWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect", - "reason": "appeared" - }, - { - "object": "LayoutSVGText text", - "reason": "appeared" - }, - { - "object": "RootInlineBox", - "reason": "appeared" - }, - { - "object": "LayoutSVGInlineText #text", - "reason": "appeared" - }, - { - "object": "InlineTextBox 'This window contains other windows'", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g id='colourPickerWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g id='windowMainGroupcolourPickerWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect", - "reason": "appeared" - }, - { - "object": "LayoutSVGText text", - "reason": "appeared" - }, - { - "object": "RootInlineBox", - "reason": "appeared" - }, - { - "object": "LayoutSVGInlineText #text", - "reason": "appeared" - }, - { - "object": "InlineTextBox 'Changing a colour changes background'", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g id='windowTitlebarGroupcolourPickerWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect id='titleBarcolourPickerWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGText text", - "reason": "appeared" - }, - { - "object": "RootInlineBox", - "reason": "appeared" - }, - { - "object": "LayoutSVGInlineText #text", - "reason": "appeared" - }, - { - "object": "InlineTextBox 'Colour Picker'", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='closeButtoncolourPickerWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='closeButton'", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect", - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='maximizeButtoncolourPickerWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='maximizeButton'", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='minimizeButtoncolourPickerWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='minimizeButton'", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect", - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g id='statusWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g id='windowMainGroupstatusWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g", - "reason": "appeared" - }, - { - "object": "LayoutSVGText text id='textStatusWindow'", - "reason": "appeared" - }, - { - "object": "RootInlineBox", - "reason": "appeared" - }, - { - "object": "LayoutSVGInlineText #text", - "reason": "appeared" - }, - { - "object": "InlineTextBox 'This is a none-moveable'", - "reason": "appeared" - }, - { - "object": "LayoutSVGTSpan tspan", - "reason": "appeared" - }, - { - "object": "InlineFlowBox", - "reason": "appeared" - }, - { - "object": "LayoutSVGInlineText #text", - "reason": "appeared" - }, - { - "object": "InlineTextBox 'none-closeable status'", - "reason": "appeared" - }, - { - "object": "LayoutSVGTSpan tspan", - "reason": "appeared" - }, - { - "object": "InlineFlowBox", - "reason": "appeared" - }, - { - "object": "LayoutSVGInlineText #text", - "reason": "appeared" - }, - { - "object": "InlineTextBox 'window'", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g id='windowTitlebarGroupstatusWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect id='titleBarstatusWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGText text", - "reason": "appeared" - }, - { - "object": "RootInlineBox", - "reason": "appeared" - }, - { - "object": "LayoutSVGInlineText #text", - "reason": "appeared" - }, - { - "object": "InlineTextBox 'Status Window'", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='maximizeButtonstatusWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='maximizeButton'", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='minimizeButtonstatusWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='minimizeButton'", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect", - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g id='windowTitlebarGroupnestedWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect id='titleBarnestedWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGText text", - "reason": "appeared" - }, - { - "object": "RootInlineBox", - "reason": "appeared" - }, - { - "object": "LayoutSVGInlineText #text", - "reason": "appeared" - }, - { - "object": "InlineTextBox 'Nested middlesize Window'", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='closeButtonnestedWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='closeButton'", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect", - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='maximizeButtonnestedWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='maximizeButton'", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='minimizeButtonnestedWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='minimizeButton'", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect", - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g id='smallWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g id='windowMainGroupsmallWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g", - "reason": "appeared" - }, - { - "object": "LayoutSVGText text id='textSmallWindow'", - "reason": "appeared" - }, - { - "object": "RootInlineBox", - "reason": "appeared" - }, - { - "object": "LayoutSVGInlineText #text", - "reason": "appeared" - }, - { - "object": "InlineTextBox 'This window has a callback'", - "reason": "appeared" - }, - { - "object": "LayoutSVGTSpan tspan", - "reason": "appeared" - }, - { - "object": "InlineFlowBox", - "reason": "appeared" - }, - { - "object": "LayoutSVGInlineText #text", - "reason": "appeared" - }, - { - "object": "InlineTextBox 'function indicating mouse'", - "reason": "appeared" - }, - { - "object": "LayoutSVGTSpan tspan", - "reason": "appeared" - }, - { - "object": "InlineFlowBox", - "reason": "appeared" - }, - { - "object": "LayoutSVGInlineText #text", - "reason": "appeared" - }, - { - "object": "InlineTextBox 'movements in the statusbar'", - "reason": "appeared" - }, - { - "object": "LayoutSVGTSpan tspan", - "reason": "appeared" - }, - { - "object": "InlineFlowBox", - "reason": "appeared" - }, - { - "object": "LayoutSVGInlineText #text", - "reason": "appeared" - }, - { - "object": "InlineTextBox 'and alerting window'", - "reason": "appeared" - }, - { - "object": "LayoutSVGTSpan tspan", - "reason": "appeared" - }, - { - "object": "InlineFlowBox", - "reason": "appeared" - }, - { - "object": "LayoutSVGInlineText #text", - "reason": "appeared" - }, - { - "object": "InlineTextBox 'events'", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect", - "reason": "appeared" - }, - { - "object": "LayoutSVGText text", - "reason": "appeared" - }, - { - "object": "RootInlineBox", - "reason": "appeared" - }, - { - "object": "LayoutSVGInlineText #text", - "reason": "appeared" - }, - { - "object": "InlineTextBox 'Callback function is active'", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g id='windowTitlebarGroupsmallWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect id='titleBarsmallWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGText text", - "reason": "appeared" - }, - { - "object": "RootInlineBox", - "reason": "appeared" - }, - { - "object": "LayoutSVGInlineText #text", - "reason": "appeared" - }, - { - "object": "InlineTextBox 'Small Window'", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='closeButtonsmallWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='closeButton'", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect", - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='maximizeButtonsmallWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='maximizeButton'", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='minimizeButtonsmallWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='minimizeButton'", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect", - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g id='minimalWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g id='windowMainGroupminimalWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g", - "reason": "appeared" - }, - { - "object": "LayoutSVGText text id='textMinimalWindow'", - "reason": "appeared" - }, - { - "object": "RootInlineBox", - "reason": "appeared" - }, - { - "object": "LayoutSVGInlineText #text", - "reason": "appeared" - }, - { - "object": "InlineTextBox 'This is a minimal window'", - "reason": "appeared" - }, - { - "object": "LayoutSVGTSpan tspan", - "reason": "appeared" - }, - { - "object": "InlineFlowBox", - "reason": "appeared" - }, - { - "object": "LayoutSVGInlineText #text", - "reason": "appeared" - }, - { - "object": "InlineTextBox 'without title and status bar.'", - "reason": "appeared" - }, - { - "object": "LayoutSVGTSpan tspan", - "reason": "appeared" - }, - { - "object": "InlineFlowBox", - "reason": "appeared" - }, - { - "object": "LayoutSVGInlineText #text", - "reason": "appeared" - }, - { - "object": "InlineTextBox 'it is also not moveable'", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g id='windowTitlebarGroupminimalWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g id='windowTitlebarGroupbigWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect id='titleBarbigWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGText text", - "reason": "appeared" - }, - { - "object": "RootInlineBox", - "reason": "appeared" - }, - { - "object": "LayoutSVGInlineText #text", - "reason": "appeared" - }, - { - "object": "InlineTextBox 'Big Window'", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='closeButtonbigWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='closeButton'", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect", - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='maximizeButtonbigWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='maximizeButton'", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='minimizeButtonbigWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='minimizeButton'", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect", - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g id='Windows'", - "reason": "geometry" - }, - { - "object": "LayoutSVGContainer g id='navWindow'", - "reason": "geometry" - }, - { - "object": "LayoutSVGContainer g id='windowTitlebarGroupnavWindow'", - "reason": "geometry" - }, - { - "object": "LayoutSVGContainer g id='decoGroupnavWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect", - "reason": "appeared" - }, - { - "object": "LayoutSVGRect rect id='decoGroupMinimizednavWindow'", - "reason": "appeared" - }, - { - "object": "LayoutSVGText text", - "reason": "appeared" - }, - { - "object": "RootInlineBox", - "reason": "appeared" - }, - { - "object": "LayoutSVGInlineText #text", - "reason": "appeared" - }, - { - "object": "InlineTextBox 'Navigation Window'", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='closeButtonnavWindow'", - "reason": "full" - }, - { - "object": "LayoutSVGViewportContainer svg id='closeButton'", - "reason": "full" - }, - { - "object": "LayoutSVGContainer use id='maximizeButtonnavWindow'", - "reason": "full" - }, - { - "object": "LayoutSVGViewportContainer svg id='maximizeButton'", - "reason": "full" - }, - { - "object": "LayoutSVGContainer use id='minimizeButtonnavWindow'", - "reason": "full" - }, - { - "object": "LayoutSVGViewportContainer svg id='minimizeButton'", - "reason": "full" - }, - { - "object": "LayoutSVGContainer g", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g", - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer g id='windowTitlebarGroupminimalWindow'", - "reason": "appeared" - } - ] -} -
diff --git a/third_party/WebKit/LayoutTests/platform/mac/compositing/masks/mask-with-added-filters-expected.png b/third_party/WebKit/LayoutTests/platform/mac/compositing/masks/mask-with-added-filters-expected.png index 8f0e44c..248b341 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/compositing/masks/mask-with-added-filters-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/compositing/masks/mask-with-added-filters-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/compositing/overflow/mask-with-filter-expected.png b/third_party/WebKit/LayoutTests/platform/mac/compositing/overflow/mask-with-filter-expected.png new file mode 100644 index 0000000..4537715 --- /dev/null +++ b/third_party/WebKit/LayoutTests/platform/mac/compositing/overflow/mask-with-filter-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/css3/filters/blur-filter-page-scroll-self-expected.png b/third_party/WebKit/LayoutTests/platform/mac/css3/filters/blur-filter-page-scroll-self-expected.png deleted file mode 100644 index 236feee..0000000 --- a/third_party/WebKit/LayoutTests/platform/mac/css3/filters/blur-filter-page-scroll-self-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/css3/filters/effect-brightness-clamping-expected.png b/third_party/WebKit/LayoutTests/platform/mac/css3/filters/effect-brightness-clamping-expected.png index 9e5b05f..576c31e 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/css3/filters/effect-brightness-clamping-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/css3/filters/effect-brightness-clamping-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/css3/filters/effect-combined-expected.png b/third_party/WebKit/LayoutTests/platform/mac/css3/filters/effect-combined-expected.png index bb5cedf7..eab2f82 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/css3/filters/effect-combined-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/css3/filters/effect-combined-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/css3/filters/effect-drop-shadow-expected.png b/third_party/WebKit/LayoutTests/platform/mac/css3/filters/effect-drop-shadow-expected.png index e70ffa6b..e893177 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/css3/filters/effect-drop-shadow-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/css3/filters/effect-drop-shadow-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/css3/filters/filter-change-repaint-expected.png b/third_party/WebKit/LayoutTests/platform/mac/css3/filters/filter-change-repaint-expected.png new file mode 100644 index 0000000..84e258a --- /dev/null +++ b/third_party/WebKit/LayoutTests/platform/mac/css3/filters/filter-change-repaint-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/css3/filters/filter-repaint-blur-expected.png b/third_party/WebKit/LayoutTests/platform/mac/css3/filters/filter-repaint-blur-expected.png deleted file mode 100644 index d9a28e6..0000000 --- a/third_party/WebKit/LayoutTests/platform/mac/css3/filters/filter-repaint-blur-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/css3/filters/filter-repaint-expected.png b/third_party/WebKit/LayoutTests/platform/mac/css3/filters/filter-repaint-expected.png deleted file mode 100644 index dbd0807..0000000 --- a/third_party/WebKit/LayoutTests/platform/mac/css3/filters/filter-repaint-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/css3/filters/filter-repaint-shadow-expected.png b/third_party/WebKit/LayoutTests/platform/mac/css3/filters/filter-repaint-shadow-expected.png deleted file mode 100644 index d570cd7..0000000 --- a/third_party/WebKit/LayoutTests/platform/mac/css3/filters/filter-repaint-shadow-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/css3/filters/filtered-inline-expected.png b/third_party/WebKit/LayoutTests/platform/mac/css3/filters/filtered-inline-expected.png deleted file mode 100644 index 86a3b04..0000000 --- a/third_party/WebKit/LayoutTests/platform/mac/css3/filters/filtered-inline-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/fast/canvas/canvas-composite-video-shadow-expected.png b/third_party/WebKit/LayoutTests/platform/mac/fast/canvas/canvas-composite-video-shadow-expected.png index 90973311..80e70c8 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/fast/canvas/canvas-composite-video-shadow-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/fast/canvas/canvas-composite-video-shadow-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/fast/canvas/canvas-incremental-repaint-expected.png b/third_party/WebKit/LayoutTests/platform/mac/fast/canvas/canvas-incremental-repaint-expected.png index d1a5b0f1..5d1cfde 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/fast/canvas/canvas-incremental-repaint-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/fast/canvas/canvas-incremental-repaint-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/fast/canvas/canvas-shadow-source-in-expected.png b/third_party/WebKit/LayoutTests/platform/mac/fast/canvas/canvas-shadow-source-in-expected.png index 6dcdb8e1..7ed103a 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/fast/canvas/canvas-shadow-source-in-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/fast/canvas/canvas-shadow-source-in-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/images/color-profile-filter-expected.png b/third_party/WebKit/LayoutTests/platform/mac/images/color-profile-filter-expected.png index 1c035e2..f35a381 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/images/color-profile-filter-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/images/color-profile-filter-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/images/color-profile-image-filter-all-expected.png b/third_party/WebKit/LayoutTests/platform/mac/images/color-profile-image-filter-all-expected.png index 8b20244..1dcba1c 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/images/color-profile-image-filter-all-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/images/color-profile-image-filter-all-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/paint/filters/clip-filter-overflow-clip-expected.png b/third_party/WebKit/LayoutTests/platform/mac/paint/filters/clip-filter-overflow-clip-expected.png index 70852c6..9a38f848 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/paint/filters/clip-filter-overflow-clip-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/paint/filters/clip-filter-overflow-clip-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/paint/invalidation/svg/filter-child-repaint-expected.png b/third_party/WebKit/LayoutTests/platform/mac/paint/invalidation/svg/filter-child-repaint-expected.png deleted file mode 100644 index 222236d..0000000 --- a/third_party/WebKit/LayoutTests/platform/mac/paint/invalidation/svg/filter-child-repaint-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/paint/invalidation/svg/filter-width-update-expected.png b/third_party/WebKit/LayoutTests/platform/mac/paint/invalidation/svg/filter-width-update-expected.png index 79076502a..b15362d 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/paint/invalidation/svg/filter-width-update-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/paint/invalidation/svg/filter-width-update-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/paint/invalidation/svg/window-expected.txt b/third_party/WebKit/LayoutTests/platform/mac/paint/invalidation/svg/window-expected.txt index 5037d40d..fe111b6 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/paint/invalidation/svg/window-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/mac/paint/invalidation/svg/window-expected.txt
@@ -508,7 +508,7 @@ }, { "object": "LayoutSVGContainer g id='windowTitlebarGroupnavWindow'", - "rect": [755, 93, 39, 13], + "rect": [756, 94, 37, 11], "reason": "appeared" }, { @@ -528,253 +528,33 @@ }, { "object": "LayoutSVGPath line", - "rect": [614, 82, 14, 14], - "reason": "geometry" - }, - { - "object": "LayoutSVGPath line", - "rect": [614, 82, 14, 14], - "reason": "geometry" - }, - { - "object": "LayoutSVGPath line", - "rect": [453, 378, 14, 14], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [453, 378, 14, 14], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [234, 196, 14, 14], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [234, 196, 14, 14], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [781, 93, 14, 13], - "reason": "geometry" - }, - { - "object": "LayoutSVGPath line", - "rect": [781, 93, 14, 13], - "reason": "geometry" - }, - { - "object": "LayoutSVGPath line", - "rect": [781, 93, 14, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [781, 93, 14, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [570, 144, 14, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [570, 144, 14, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [754, 101, 14, 5], - "reason": "geometry" - }, - { - "object": "LayoutSVGPath line", - "rect": [754, 101, 14, 5], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [614, 122, 14, 5], - "reason": "geometry" - }, - { - "object": "LayoutSVGPath line", - "rect": [426, 387, 14, 5], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [348, 191, 14, 5], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='closeButtonsmallWindow'", - "rect": [453, 378, 13, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='closeButton'", - "rect": [453, 378, 13, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='closeButtonnestedWindow'", - "rect": [375, 183, 13, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [375, 183, 13, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [375, 183, 13, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='closeButton'", - "rect": [375, 183, 13, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='minimizeButtonstatusWindow'", - "rect": [362, 346, 13, 12], - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='minimizeButton'", - "rect": [362, 346, 13, 12], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='minimizeButtonnavWindow'", - "rect": [755, 95, 13, 11], - "reason": "full" - }, - { - "object": "LayoutSVGContainer use id='minimizeButtonnavWindow'", - "rect": [755, 95, 13, 11], - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='minimizeButton'", - "rect": [755, 95, 13, 11], - "reason": "full" - }, - { - "object": "LayoutSVGViewportContainer svg id='minimizeButton'", - "rect": [755, 95, 13, 11], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='minimizeButtonbigWindow'", - "rect": [544, 146, 13, 11], - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='minimizeButton'", - "rect": [544, 146, 13, 11], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='minimizeButtonsmallWindow'", - "rect": [427, 380, 13, 11], - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='minimizeButton'", - "rect": [427, 380, 13, 11], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='minimizeButtoncolourPickerWindow'", - "rect": [208, 198, 13, 11], - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='minimizeButton'", - "rect": [208, 198, 13, 11], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [208, 204, 13, 6], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [544, 152, 13, 5], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [362, 353, 13, 5], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='closeButtonnavWindow'", - "rect": [782, 93, 12, 13], - "reason": "full" - }, - { - "object": "LayoutSVGContainer use id='closeButtonnavWindow'", - "rect": [782, 93, 12, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='closeButton'", - "rect": [782, 93, 12, 13], - "reason": "full" - }, - { - "object": "LayoutSVGViewportContainer svg id='closeButton'", - "rect": [782, 93, 12, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='closeButtonbigWindow'", - "rect": [571, 144, 12, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='closeButton'", - "rect": [571, 144, 12, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='closeButtoncolourPickerWindow'", - "rect": [235, 196, 12, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='closeButton'", - "rect": [235, 196, 12, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='closeButtonnavWindow'", "rect": [615, 83, 12, 12], - "reason": "full" + "reason": "geometry" }, { - "object": "LayoutSVGViewportContainer svg id='closeButton'", + "object": "LayoutSVGPath line", "rect": [615, 83, 12, 12], - "reason": "full" + "reason": "geometry" }, { - "object": "LayoutSVGContainer use id='minimizeButtonnavWindow'", - "rect": [615, 116, 12, 11], - "reason": "full" + "object": "LayoutSVGPath line", + "rect": [782, 94, 12, 11], + "reason": "geometry" }, { - "object": "LayoutSVGViewportContainer svg id='minimizeButton'", - "rect": [615, 116, 12, 11], - "reason": "full" + "object": "LayoutSVGPath line", + "rect": [782, 94, 12, 11], + "reason": "geometry" + }, + { + "object": "LayoutSVGPath line", + "rect": [782, 94, 12, 11], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [782, 94, 12, 11], + "reason": "appeared" }, { "object": "LayoutSVGRect rect", @@ -782,13 +562,33 @@ "reason": "geometry" }, { - "object": "LayoutSVGContainer use id='minimizeButtonnestedWindow'", - "rect": [349, 185, 12, 11], + "object": "LayoutSVGPath line", + "rect": [571, 145, 12, 11], "reason": "appeared" }, { - "object": "LayoutSVGViewportContainer svg id='minimizeButton'", - "rect": [349, 185, 12, 11], + "object": "LayoutSVGPath line", + "rect": [571, 145, 12, 11], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [235, 197, 12, 11], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [235, 197, 12, 11], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [615, 123, 12, 3], + "reason": "geometry" + }, + { + "object": "LayoutSVGPath line", + "rect": [349, 192, 12, 3], "reason": "appeared" }, { @@ -852,11 +652,41 @@ "reason": "appeared" }, { + "object": "LayoutSVGPath line", + "rect": [454, 379, 11, 11], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [454, 379, 11, 11], + "reason": "appeared" + }, + { "object": "LayoutSVGRect rect", "rect": [441, 379, 11, 11], "reason": "appeared" }, { + "object": "LayoutSVGContainer use id='closeButtonnestedWindow'", + "rect": [376, 184, 11, 11], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [376, 184, 11, 11], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [376, 184, 11, 11], + "reason": "appeared" + }, + { + "object": "LayoutSVGViewportContainer svg id='closeButton'", + "rect": [376, 184, 11, 11], + "reason": "appeared" + }, + { "object": "LayoutSVGContainer use id='maximizeButtonnestedWindow'", "rect": [363, 184, 11, 11], "reason": "appeared" @@ -877,6 +707,36 @@ "reason": "appeared" }, { + "object": "LayoutSVGContainer use id='minimizeButtonnavWindow'", + "rect": [756, 95, 11, 10], + "reason": "full" + }, + { + "object": "LayoutSVGContainer use id='minimizeButtonnavWindow'", + "rect": [756, 95, 11, 10], + "reason": "appeared" + }, + { + "object": "LayoutSVGViewportContainer svg id='minimizeButton'", + "rect": [756, 95, 11, 10], + "reason": "full" + }, + { + "object": "LayoutSVGViewportContainer svg id='minimizeButton'", + "rect": [756, 95, 11, 10], + "reason": "appeared" + }, + { + "object": "LayoutSVGContainer use id='minimizeButtonbigWindow'", + "rect": [545, 146, 11, 10], + "reason": "appeared" + }, + { + "object": "LayoutSVGViewportContainer svg id='minimizeButton'", + "rect": [545, 146, 11, 10], + "reason": "appeared" + }, + { "object": "LayoutSVGContainer use id='maximizeButtonsmallWindow'", "rect": [441, 380, 11, 10], "reason": "appeared" @@ -897,6 +757,86 @@ "reason": "appeared" }, { + "object": "LayoutSVGContainer use id='minimizeButtonstatusWindow'", + "rect": [363, 346, 11, 10], + "reason": "appeared" + }, + { + "object": "LayoutSVGViewportContainer svg id='minimizeButton'", + "rect": [363, 346, 11, 10], + "reason": "appeared" + }, + { + "object": "LayoutSVGContainer use id='minimizeButtoncolourPickerWindow'", + "rect": [209, 198, 11, 10], + "reason": "appeared" + }, + { + "object": "LayoutSVGViewportContainer svg id='minimizeButton'", + "rect": [209, 198, 11, 10], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [545, 153, 11, 3], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [363, 354, 11, 3], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [756, 103, 11, 2], + "reason": "geometry" + }, + { + "object": "LayoutSVGPath line", + "rect": [756, 103, 11, 2], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [428, 388, 11, 2], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [209, 206, 11, 2], + "reason": "appeared" + }, + { + "object": "LayoutSVGContainer use id='closeButtonnavWindow'", + "rect": [783, 94, 10, 11], + "reason": "full" + }, + { + "object": "LayoutSVGContainer use id='closeButtonnavWindow'", + "rect": [783, 94, 10, 11], + "reason": "appeared" + }, + { + "object": "LayoutSVGViewportContainer svg id='closeButton'", + "rect": [783, 94, 10, 11], + "reason": "full" + }, + { + "object": "LayoutSVGViewportContainer svg id='closeButton'", + "rect": [783, 94, 10, 11], + "reason": "appeared" + }, + { + "object": "LayoutSVGContainer use id='closeButtonbigWindow'", + "rect": [572, 145, 10, 11], + "reason": "appeared" + }, + { + "object": "LayoutSVGViewportContainer svg id='closeButton'", + "rect": [572, 145, 10, 11], + "reason": "appeared" + }, + { "object": "LayoutSVGContainer use id='maximizeButtonnavWindow'", "rect": [616, 100, 10, 10], "reason": "full" @@ -907,26 +847,76 @@ "reason": "full" }, { + "object": "LayoutSVGContainer use id='closeButtonnavWindow'", + "rect": [616, 84, 10, 10], + "reason": "full" + }, + { "object": "LayoutSVGRect rect", "rect": [616, 84, 10, 10], "reason": "geometry" }, { + "object": "LayoutSVGViewportContainer svg id='closeButton'", + "rect": [616, 84, 10, 10], + "reason": "full" + }, + { + "object": "LayoutSVGContainer use id='closeButtonsmallWindow'", + "rect": [455, 380, 10, 10], + "reason": "appeared" + }, + { "object": "LayoutSVGRect rect", "rect": [455, 380, 10, 10], "reason": "appeared" }, { + "object": "LayoutSVGViewportContainer svg id='closeButton'", + "rect": [455, 380, 10, 10], + "reason": "appeared" + }, + { + "object": "LayoutSVGContainer use id='minimizeButtonsmallWindow'", + "rect": [428, 380, 10, 10], + "reason": "appeared" + }, + { "object": "LayoutSVGRect rect", "rect": [428, 380, 10, 10], "reason": "appeared" }, { + "object": "LayoutSVGViewportContainer svg id='minimizeButton'", + "rect": [428, 380, 10, 10], + "reason": "appeared" + }, + { + "object": "LayoutSVGContainer use id='minimizeButtonnestedWindow'", + "rect": [350, 185, 10, 10], + "reason": "appeared" + }, + { + "object": "LayoutSVGViewportContainer svg id='minimizeButton'", + "rect": [350, 185, 10, 10], + "reason": "appeared" + }, + { + "object": "LayoutSVGContainer use id='closeButtoncolourPickerWindow'", + "rect": [236, 198, 10, 10], + "reason": "appeared" + }, + { "object": "LayoutSVGRect rect", "rect": [236, 198, 10, 10], "reason": "appeared" }, { + "object": "LayoutSVGViewportContainer svg id='closeButton'", + "rect": [236, 198, 10, 10], + "reason": "appeared" + }, + { "object": "LayoutSVGContainer use id='maximizeButtoncolourPickerWindow'", "rect": [223, 198, 10, 10], "reason": "appeared" @@ -947,11 +937,21 @@ "reason": "appeared" }, { + "object": "LayoutSVGContainer use id='minimizeButtonnavWindow'", + "rect": [616, 116, 10, 9], + "reason": "full" + }, + { "object": "LayoutSVGRect rect", "rect": [616, 116, 10, 9], "reason": "geometry" }, { + "object": "LayoutSVGViewportContainer svg id='minimizeButton'", + "rect": [616, 116, 10, 9], + "reason": "full" + }, + { "object": "LayoutSVGRect rect", "rect": [572, 146, 10, 9], "reason": "appeared"
diff --git a/third_party/WebKit/LayoutTests/platform/mac/svg/W3C-SVG-1.1/filters-example-01-b-expected.png b/third_party/WebKit/LayoutTests/platform/mac/svg/W3C-SVG-1.1/filters-example-01-b-expected.png index a15c34b..f2635d4 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/svg/W3C-SVG-1.1/filters-example-01-b-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/svg/W3C-SVG-1.1/filters-example-01-b-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/svg/W3C-SVG-1.1/filters-gauss-01-b-expected.png b/third_party/WebKit/LayoutTests/platform/mac/svg/W3C-SVG-1.1/filters-gauss-01-b-expected.png index a49b863..e7ff33b 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/svg/W3C-SVG-1.1/filters-gauss-01-b-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/svg/W3C-SVG-1.1/filters-gauss-01-b-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/svg/batik/text/smallFonts-expected.png b/third_party/WebKit/LayoutTests/platform/mac/svg/batik/text/smallFonts-expected.png index 2e864da..0ba7f15 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/svg/batik/text/smallFonts-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/svg/batik/text/smallFonts-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/svg/batik/text/textEffect-expected.png b/third_party/WebKit/LayoutTests/platform/mac/svg/batik/text/textEffect-expected.png index 21c36cdf..acdc566 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/svg/batik/text/textEffect-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/svg/batik/text/textEffect-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/svg/batik/text/textEffect3-expected.png b/third_party/WebKit/LayoutTests/platform/mac/svg/batik/text/textEffect3-expected.png index 75917d8..0ef7380 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/svg/batik/text/textEffect3-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/svg/batik/text/textEffect3-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/svg/batik/text/textFeatures-expected.png b/third_party/WebKit/LayoutTests/platform/mac/svg/batik/text/textFeatures-expected.png index 83765b08..6d9395a 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/svg/batik/text/textFeatures-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/svg/batik/text/textFeatures-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/svg/batik/text/textProperties-expected.png b/third_party/WebKit/LayoutTests/platform/mac/svg/batik/text/textProperties-expected.png index 43f6f936..f5fa06e 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/svg/batik/text/textProperties-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/svg/batik/text/textProperties-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/svg/custom/image-with-transform-clip-filter-expected.png b/third_party/WebKit/LayoutTests/platform/mac/svg/custom/image-with-transform-clip-filter-expected.png index 5541ca8e..c66e2a4 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/svg/custom/image-with-transform-clip-filter-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/svg/custom/image-with-transform-clip-filter-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/svg/custom/recursive-filter-expected.png b/third_party/WebKit/LayoutTests/platform/mac/svg/custom/recursive-filter-expected.png index 8898e298..03d5b28b 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/svg/custom/recursive-filter-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/svg/custom/recursive-filter-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/svg/custom/text-filter-expected.png b/third_party/WebKit/LayoutTests/platform/mac/svg/custom/text-filter-expected.png index 06f1157..ee50c3d 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/svg/custom/text-filter-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/svg/custom/text-filter-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/svg/filters/filter-on-filter-for-text-expected.png b/third_party/WebKit/LayoutTests/platform/mac/svg/filters/filter-on-filter-for-text-expected.png index 7cb9ae8..0f83fc0 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/svg/filters/filter-on-filter-for-text-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/svg/filters/filter-on-filter-for-text-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/virtual/display_list_2d_canvas/fast/canvas/canvas-composite-video-shadow-expected.png b/third_party/WebKit/LayoutTests/platform/mac/virtual/display_list_2d_canvas/fast/canvas/canvas-composite-video-shadow-expected.png deleted file mode 100644 index 90973311..0000000 --- a/third_party/WebKit/LayoutTests/platform/mac/virtual/display_list_2d_canvas/fast/canvas/canvas-composite-video-shadow-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/virtual/display_list_2d_canvas/fast/canvas/canvas-incremental-repaint-expected.png b/third_party/WebKit/LayoutTests/platform/mac/virtual/display_list_2d_canvas/fast/canvas/canvas-incremental-repaint-expected.png deleted file mode 100644 index d1a5b0f1..0000000 --- a/third_party/WebKit/LayoutTests/platform/mac/virtual/display_list_2d_canvas/fast/canvas/canvas-incremental-repaint-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/virtual/display_list_2d_canvas/fast/canvas/canvas-shadow-source-in-expected.png b/third_party/WebKit/LayoutTests/platform/mac/virtual/display_list_2d_canvas/fast/canvas/canvas-shadow-source-in-expected.png deleted file mode 100644 index 6dcdb8e1..0000000 --- a/third_party/WebKit/LayoutTests/platform/mac/virtual/display_list_2d_canvas/fast/canvas/canvas-shadow-source-in-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/virtual/exotic-color-space/images/color-profile-filter-expected.png b/third_party/WebKit/LayoutTests/platform/mac/virtual/exotic-color-space/images/color-profile-filter-expected.png index ef26dbb..676cc3b 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/virtual/exotic-color-space/images/color-profile-filter-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/virtual/exotic-color-space/images/color-profile-filter-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/virtual/exotic-color-space/images/color-profile-image-filter-all-expected.png b/third_party/WebKit/LayoutTests/platform/mac/virtual/exotic-color-space/images/color-profile-image-filter-all-expected.png index 5fef371..4c3436c 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/virtual/exotic-color-space/images/color-profile-image-filter-all-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/virtual/exotic-color-space/images/color-profile-image-filter-all-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/virtual/exotic-color-space/images/color-profile-mask-image-svg-expected.png b/third_party/WebKit/LayoutTests/platform/mac/virtual/exotic-color-space/images/color-profile-mask-image-svg-expected.png new file mode 100644 index 0000000..b6545e91 --- /dev/null +++ b/third_party/WebKit/LayoutTests/platform/mac/virtual/exotic-color-space/images/color-profile-mask-image-svg-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/compositing/masks/mask-with-added-filters-expected.png b/third_party/WebKit/LayoutTests/platform/win/compositing/masks/mask-with-added-filters-expected.png index 03928de..1efe5f9 100644 --- a/third_party/WebKit/LayoutTests/platform/win/compositing/masks/mask-with-added-filters-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/compositing/masks/mask-with-added-filters-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/compositing/overflow/mask-with-filter-expected.png b/third_party/WebKit/LayoutTests/platform/win/compositing/overflow/mask-with-filter-expected.png index 169096bd..be37544 100644 --- a/third_party/WebKit/LayoutTests/platform/win/compositing/overflow/mask-with-filter-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/compositing/overflow/mask-with-filter-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/css3/filters/blur-filter-page-scroll-self-expected.png b/third_party/WebKit/LayoutTests/platform/win/css3/filters/blur-filter-page-scroll-self-expected.png deleted file mode 100644 index f0665b3..0000000 --- a/third_party/WebKit/LayoutTests/platform/win/css3/filters/blur-filter-page-scroll-self-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/css3/filters/effect-brightness-clamping-expected.png b/third_party/WebKit/LayoutTests/platform/win/css3/filters/effect-brightness-clamping-expected.png index ae7ad9fa..7ff4f1fb 100644 --- a/third_party/WebKit/LayoutTests/platform/win/css3/filters/effect-brightness-clamping-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/css3/filters/effect-brightness-clamping-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/css3/filters/effect-combined-expected.png b/third_party/WebKit/LayoutTests/platform/win/css3/filters/effect-combined-expected.png index 7770c75..cea4cd00 100644 --- a/third_party/WebKit/LayoutTests/platform/win/css3/filters/effect-combined-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/css3/filters/effect-combined-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/css3/filters/effect-drop-shadow-expected.png b/third_party/WebKit/LayoutTests/platform/win/css3/filters/effect-drop-shadow-expected.png index 4f273f55..ffd9d85 100644 --- a/third_party/WebKit/LayoutTests/platform/win/css3/filters/effect-drop-shadow-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/css3/filters/effect-drop-shadow-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/css3/filters/filter-change-repaint-expected.png b/third_party/WebKit/LayoutTests/platform/win/css3/filters/filter-change-repaint-expected.png index 63ee4e0..c1910585 100644 --- a/third_party/WebKit/LayoutTests/platform/win/css3/filters/filter-change-repaint-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/css3/filters/filter-change-repaint-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/css3/filters/filter-repaint-blur-expected.png b/third_party/WebKit/LayoutTests/platform/win/css3/filters/filter-repaint-blur-expected.png deleted file mode 100644 index 942a577..0000000 --- a/third_party/WebKit/LayoutTests/platform/win/css3/filters/filter-repaint-blur-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/css3/filters/filter-repaint-expected.png b/third_party/WebKit/LayoutTests/platform/win/css3/filters/filter-repaint-expected.png deleted file mode 100644 index 83bcdc3..0000000 --- a/third_party/WebKit/LayoutTests/platform/win/css3/filters/filter-repaint-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/css3/filters/filter-repaint-shadow-expected.png b/third_party/WebKit/LayoutTests/platform/win/css3/filters/filter-repaint-shadow-expected.png deleted file mode 100644 index 735667a..0000000 --- a/third_party/WebKit/LayoutTests/platform/win/css3/filters/filter-repaint-shadow-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/css3/filters/filtered-inline-expected.png b/third_party/WebKit/LayoutTests/platform/win/css3/filters/filtered-inline-expected.png deleted file mode 100644 index 1a04f87..0000000 --- a/third_party/WebKit/LayoutTests/platform/win/css3/filters/filtered-inline-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/external/wpt/pointerevents/extension/pointerevent_coalesced_events_attributes-manual-expected.txt b/third_party/WebKit/LayoutTests/platform/win/external/wpt/pointerevents/extension/pointerevent_coalesced_events_attributes-manual-expected.txt index fe718a8..e84ebdb 100644 --- a/third_party/WebKit/LayoutTests/platform/win/external/wpt/pointerevents/extension/pointerevent_coalesced_events_attributes-manual-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/win/external/wpt/pointerevents/extension/pointerevent_coalesced_events_attributes-manual-expected.txt
@@ -5,7 +5,7 @@ PASS touch pointerover should not have any coalesced events PASS touch pointerenter should not have any coalesced events PASS touch pointerdown should not have any coalesced events -FAIL touch pointermove should have >2 coalesced events as main thread is busy. assert_greater_than: pointermove should have at least 2 coalesced events. expected a number greater than 1 but got 0 +FAIL touch pointermove should have >2 coalesced events as main thread is busy. assert_greater_than: pointermove should have at least 2 coalesced events. expected a number greater than 1 but got 1 PASS touch pointermove coalesced events should all be marked as trusted. PASS touch time stamps of coalesced events must be ascending. PASS touch pointermove coalesced events should all bubbles and cancelable as false.
diff --git a/third_party/WebKit/LayoutTests/platform/win/fast/canvas/canvas-composite-video-shadow-expected.png b/third_party/WebKit/LayoutTests/platform/win/fast/canvas/canvas-composite-video-shadow-expected.png index 05a993d..e88967a 100644 --- a/third_party/WebKit/LayoutTests/platform/win/fast/canvas/canvas-composite-video-shadow-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/fast/canvas/canvas-composite-video-shadow-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/fast/canvas/canvas-incremental-repaint-expected.png b/third_party/WebKit/LayoutTests/platform/win/fast/canvas/canvas-incremental-repaint-expected.png index aa94bdad..f7a73fe 100644 --- a/third_party/WebKit/LayoutTests/platform/win/fast/canvas/canvas-incremental-repaint-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/fast/canvas/canvas-incremental-repaint-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/fast/canvas/canvas-shadow-source-in-expected.png b/third_party/WebKit/LayoutTests/platform/win/fast/canvas/canvas-shadow-source-in-expected.png index fdcda21..e5ed879 100644 --- a/third_party/WebKit/LayoutTests/platform/win/fast/canvas/canvas-shadow-source-in-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/fast/canvas/canvas-shadow-source-in-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/images/color-profile-filter-expected.png b/third_party/WebKit/LayoutTests/platform/win/images/color-profile-filter-expected.png index 1dca3d54..1006e4e8 100644 --- a/third_party/WebKit/LayoutTests/platform/win/images/color-profile-filter-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/images/color-profile-filter-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/images/color-profile-image-filter-all-expected.png b/third_party/WebKit/LayoutTests/platform/win/images/color-profile-image-filter-all-expected.png index 49e5ce1..955ddb9 100644 --- a/third_party/WebKit/LayoutTests/platform/win/images/color-profile-image-filter-all-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/images/color-profile-image-filter-all-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/paint/filters/clip-filter-overflow-clip-expected.png b/third_party/WebKit/LayoutTests/platform/win/paint/filters/clip-filter-overflow-clip-expected.png index d42bfd3..5334e4b 100644 --- a/third_party/WebKit/LayoutTests/platform/win/paint/filters/clip-filter-overflow-clip-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/paint/filters/clip-filter-overflow-clip-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/paint/invalidation/svg/filter-child-repaint-expected.png b/third_party/WebKit/LayoutTests/platform/win/paint/invalidation/svg/filter-child-repaint-expected.png deleted file mode 100644 index 5a2de70..0000000 --- a/third_party/WebKit/LayoutTests/platform/win/paint/invalidation/svg/filter-child-repaint-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/paint/invalidation/svg/filter-width-update-expected.png b/third_party/WebKit/LayoutTests/platform/win/paint/invalidation/svg/filter-width-update-expected.png index 7548748..095a7fb 100644 --- a/third_party/WebKit/LayoutTests/platform/win/paint/invalidation/svg/filter-width-update-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/paint/invalidation/svg/filter-width-update-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/paint/invalidation/svg/window-expected.txt b/third_party/WebKit/LayoutTests/platform/win/paint/invalidation/svg/window-expected.txt index c7c8b54..afe1402e 100644 --- a/third_party/WebKit/LayoutTests/platform/win/paint/invalidation/svg/window-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/win/paint/invalidation/svg/window-expected.txt
@@ -508,7 +508,7 @@ }, { "object": "LayoutSVGContainer g id='windowTitlebarGroupnavWindow'", - "rect": [755, 93, 39, 13], + "rect": [756, 94, 37, 11], "reason": "appeared" }, { @@ -527,91 +527,6 @@ "reason": "appeared" }, { - "object": "LayoutSVGPath line", - "rect": [614, 82, 14, 14], - "reason": "geometry" - }, - { - "object": "LayoutSVGPath line", - "rect": [614, 82, 14, 14], - "reason": "geometry" - }, - { - "object": "LayoutSVGPath line", - "rect": [453, 378, 14, 14], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [453, 378, 14, 14], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [234, 196, 14, 14], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [234, 196, 14, 14], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [781, 93, 14, 13], - "reason": "geometry" - }, - { - "object": "LayoutSVGPath line", - "rect": [781, 93, 14, 13], - "reason": "geometry" - }, - { - "object": "LayoutSVGPath line", - "rect": [781, 93, 14, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [781, 93, 14, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [570, 144, 14, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [570, 144, 14, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [754, 101, 14, 5], - "reason": "geometry" - }, - { - "object": "LayoutSVGPath line", - "rect": [754, 101, 14, 5], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [614, 122, 14, 5], - "reason": "geometry" - }, - { - "object": "LayoutSVGPath line", - "rect": [426, 387, 14, 5], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [348, 191, 14, 5], - "reason": "appeared" - }, - { "object": "LayoutSVGInlineText #text", "rect": [615, 153, 13, 81], "reason": "appeared" @@ -622,169 +537,34 @@ "reason": "appeared" }, { - "object": "LayoutSVGContainer use id='closeButtonsmallWindow'", - "rect": [453, 378, 13, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='closeButton'", - "rect": [453, 378, 13, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='closeButtonnestedWindow'", - "rect": [375, 183, 13, 13], - "reason": "appeared" - }, - { "object": "LayoutSVGPath line", - "rect": [375, 183, 13, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [375, 183, 13, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='closeButton'", - "rect": [375, 183, 13, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='minimizeButtonstatusWindow'", - "rect": [362, 346, 13, 12], - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='minimizeButton'", - "rect": [362, 346, 13, 12], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='minimizeButtonnavWindow'", - "rect": [755, 95, 13, 11], - "reason": "full" - }, - { - "object": "LayoutSVGContainer use id='minimizeButtonnavWindow'", - "rect": [755, 95, 13, 11], - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='minimizeButton'", - "rect": [755, 95, 13, 11], - "reason": "full" - }, - { - "object": "LayoutSVGViewportContainer svg id='minimizeButton'", - "rect": [755, 95, 13, 11], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='minimizeButtonbigWindow'", - "rect": [544, 146, 13, 11], - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='minimizeButton'", - "rect": [544, 146, 13, 11], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='minimizeButtonsmallWindow'", - "rect": [427, 380, 13, 11], - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='minimizeButton'", - "rect": [427, 380, 13, 11], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='minimizeButtoncolourPickerWindow'", - "rect": [208, 198, 13, 11], - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='minimizeButton'", - "rect": [208, 198, 13, 11], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [208, 204, 13, 6], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [544, 152, 13, 5], - "reason": "appeared" - }, - { - "object": "LayoutSVGPath line", - "rect": [362, 353, 13, 5], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='closeButtonnavWindow'", - "rect": [782, 93, 12, 13], - "reason": "full" - }, - { - "object": "LayoutSVGContainer use id='closeButtonnavWindow'", - "rect": [782, 93, 12, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='closeButton'", - "rect": [782, 93, 12, 13], - "reason": "full" - }, - { - "object": "LayoutSVGViewportContainer svg id='closeButton'", - "rect": [782, 93, 12, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='closeButtonbigWindow'", - "rect": [571, 144, 12, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='closeButton'", - "rect": [571, 144, 12, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='closeButtoncolourPickerWindow'", - "rect": [235, 196, 12, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGViewportContainer svg id='closeButton'", - "rect": [235, 196, 12, 13], - "reason": "appeared" - }, - { - "object": "LayoutSVGContainer use id='closeButtonnavWindow'", "rect": [615, 83, 12, 12], - "reason": "full" + "reason": "geometry" }, { - "object": "LayoutSVGViewportContainer svg id='closeButton'", + "object": "LayoutSVGPath line", "rect": [615, 83, 12, 12], - "reason": "full" + "reason": "geometry" }, { - "object": "LayoutSVGContainer use id='minimizeButtonnavWindow'", - "rect": [615, 116, 12, 11], - "reason": "full" + "object": "LayoutSVGPath line", + "rect": [782, 94, 12, 11], + "reason": "geometry" }, { - "object": "LayoutSVGViewportContainer svg id='minimizeButton'", - "rect": [615, 116, 12, 11], - "reason": "full" + "object": "LayoutSVGPath line", + "rect": [782, 94, 12, 11], + "reason": "geometry" + }, + { + "object": "LayoutSVGPath line", + "rect": [782, 94, 12, 11], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [782, 94, 12, 11], + "reason": "appeared" }, { "object": "LayoutSVGRect rect", @@ -792,13 +572,33 @@ "reason": "geometry" }, { - "object": "LayoutSVGContainer use id='minimizeButtonnestedWindow'", - "rect": [349, 185, 12, 11], + "object": "LayoutSVGPath line", + "rect": [571, 145, 12, 11], "reason": "appeared" }, { - "object": "LayoutSVGViewportContainer svg id='minimizeButton'", - "rect": [349, 185, 12, 11], + "object": "LayoutSVGPath line", + "rect": [571, 145, 12, 11], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [235, 197, 12, 11], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [235, 197, 12, 11], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [615, 123, 12, 3], + "reason": "geometry" + }, + { + "object": "LayoutSVGPath line", + "rect": [349, 192, 12, 3], "reason": "appeared" }, { @@ -852,11 +652,41 @@ "reason": "appeared" }, { + "object": "LayoutSVGPath line", + "rect": [454, 379, 11, 11], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [454, 379, 11, 11], + "reason": "appeared" + }, + { "object": "LayoutSVGRect rect", "rect": [441, 379, 11, 11], "reason": "appeared" }, { + "object": "LayoutSVGContainer use id='closeButtonnestedWindow'", + "rect": [376, 184, 11, 11], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [376, 184, 11, 11], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [376, 184, 11, 11], + "reason": "appeared" + }, + { + "object": "LayoutSVGViewportContainer svg id='closeButton'", + "rect": [376, 184, 11, 11], + "reason": "appeared" + }, + { "object": "LayoutSVGContainer use id='maximizeButtonnestedWindow'", "rect": [363, 184, 11, 11], "reason": "appeared" @@ -877,6 +707,36 @@ "reason": "appeared" }, { + "object": "LayoutSVGContainer use id='minimizeButtonnavWindow'", + "rect": [756, 95, 11, 10], + "reason": "full" + }, + { + "object": "LayoutSVGContainer use id='minimizeButtonnavWindow'", + "rect": [756, 95, 11, 10], + "reason": "appeared" + }, + { + "object": "LayoutSVGViewportContainer svg id='minimizeButton'", + "rect": [756, 95, 11, 10], + "reason": "full" + }, + { + "object": "LayoutSVGViewportContainer svg id='minimizeButton'", + "rect": [756, 95, 11, 10], + "reason": "appeared" + }, + { + "object": "LayoutSVGContainer use id='minimizeButtonbigWindow'", + "rect": [545, 146, 11, 10], + "reason": "appeared" + }, + { + "object": "LayoutSVGViewportContainer svg id='minimizeButton'", + "rect": [545, 146, 11, 10], + "reason": "appeared" + }, + { "object": "LayoutSVGContainer use id='maximizeButtonsmallWindow'", "rect": [441, 380, 11, 10], "reason": "appeared" @@ -897,6 +757,86 @@ "reason": "appeared" }, { + "object": "LayoutSVGContainer use id='minimizeButtonstatusWindow'", + "rect": [363, 346, 11, 10], + "reason": "appeared" + }, + { + "object": "LayoutSVGViewportContainer svg id='minimizeButton'", + "rect": [363, 346, 11, 10], + "reason": "appeared" + }, + { + "object": "LayoutSVGContainer use id='minimizeButtoncolourPickerWindow'", + "rect": [209, 198, 11, 10], + "reason": "appeared" + }, + { + "object": "LayoutSVGViewportContainer svg id='minimizeButton'", + "rect": [209, 198, 11, 10], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [545, 153, 11, 3], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [363, 354, 11, 3], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [756, 103, 11, 2], + "reason": "geometry" + }, + { + "object": "LayoutSVGPath line", + "rect": [756, 103, 11, 2], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [428, 388, 11, 2], + "reason": "appeared" + }, + { + "object": "LayoutSVGPath line", + "rect": [209, 206, 11, 2], + "reason": "appeared" + }, + { + "object": "LayoutSVGContainer use id='closeButtonnavWindow'", + "rect": [783, 94, 10, 11], + "reason": "full" + }, + { + "object": "LayoutSVGContainer use id='closeButtonnavWindow'", + "rect": [783, 94, 10, 11], + "reason": "appeared" + }, + { + "object": "LayoutSVGViewportContainer svg id='closeButton'", + "rect": [783, 94, 10, 11], + "reason": "full" + }, + { + "object": "LayoutSVGViewportContainer svg id='closeButton'", + "rect": [783, 94, 10, 11], + "reason": "appeared" + }, + { + "object": "LayoutSVGContainer use id='closeButtonbigWindow'", + "rect": [572, 145, 10, 11], + "reason": "appeared" + }, + { + "object": "LayoutSVGViewportContainer svg id='closeButton'", + "rect": [572, 145, 10, 11], + "reason": "appeared" + }, + { "object": "LayoutSVGContainer use id='maximizeButtonnavWindow'", "rect": [616, 100, 10, 10], "reason": "full" @@ -907,26 +847,76 @@ "reason": "full" }, { + "object": "LayoutSVGContainer use id='closeButtonnavWindow'", + "rect": [616, 84, 10, 10], + "reason": "full" + }, + { "object": "LayoutSVGRect rect", "rect": [616, 84, 10, 10], "reason": "geometry" }, { + "object": "LayoutSVGViewportContainer svg id='closeButton'", + "rect": [616, 84, 10, 10], + "reason": "full" + }, + { + "object": "LayoutSVGContainer use id='closeButtonsmallWindow'", + "rect": [455, 380, 10, 10], + "reason": "appeared" + }, + { "object": "LayoutSVGRect rect", "rect": [455, 380, 10, 10], "reason": "appeared" }, { + "object": "LayoutSVGViewportContainer svg id='closeButton'", + "rect": [455, 380, 10, 10], + "reason": "appeared" + }, + { + "object": "LayoutSVGContainer use id='minimizeButtonsmallWindow'", + "rect": [428, 380, 10, 10], + "reason": "appeared" + }, + { "object": "LayoutSVGRect rect", "rect": [428, 380, 10, 10], "reason": "appeared" }, { + "object": "LayoutSVGViewportContainer svg id='minimizeButton'", + "rect": [428, 380, 10, 10], + "reason": "appeared" + }, + { + "object": "LayoutSVGContainer use id='minimizeButtonnestedWindow'", + "rect": [350, 185, 10, 10], + "reason": "appeared" + }, + { + "object": "LayoutSVGViewportContainer svg id='minimizeButton'", + "rect": [350, 185, 10, 10], + "reason": "appeared" + }, + { + "object": "LayoutSVGContainer use id='closeButtoncolourPickerWindow'", + "rect": [236, 198, 10, 10], + "reason": "appeared" + }, + { "object": "LayoutSVGRect rect", "rect": [236, 198, 10, 10], "reason": "appeared" }, { + "object": "LayoutSVGViewportContainer svg id='closeButton'", + "rect": [236, 198, 10, 10], + "reason": "appeared" + }, + { "object": "LayoutSVGContainer use id='maximizeButtoncolourPickerWindow'", "rect": [223, 198, 10, 10], "reason": "appeared" @@ -947,11 +937,21 @@ "reason": "appeared" }, { + "object": "LayoutSVGContainer use id='minimizeButtonnavWindow'", + "rect": [616, 116, 10, 9], + "reason": "full" + }, + { "object": "LayoutSVGRect rect", "rect": [616, 116, 10, 9], "reason": "geometry" }, { + "object": "LayoutSVGViewportContainer svg id='minimizeButton'", + "rect": [616, 116, 10, 9], + "reason": "full" + }, + { "object": "LayoutSVGRect rect", "rect": [572, 146, 10, 9], "reason": "appeared"
diff --git a/third_party/WebKit/LayoutTests/platform/win/svg/W3C-SVG-1.1/filters-example-01-b-expected.png b/third_party/WebKit/LayoutTests/platform/win/svg/W3C-SVG-1.1/filters-example-01-b-expected.png index e764867f..a0c0b06 100644 --- a/third_party/WebKit/LayoutTests/platform/win/svg/W3C-SVG-1.1/filters-example-01-b-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/svg/W3C-SVG-1.1/filters-example-01-b-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/svg/W3C-SVG-1.1/filters-gauss-01-b-expected.png b/third_party/WebKit/LayoutTests/platform/win/svg/W3C-SVG-1.1/filters-gauss-01-b-expected.png index bedb653..32c8993 100644 --- a/third_party/WebKit/LayoutTests/platform/win/svg/W3C-SVG-1.1/filters-gauss-01-b-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/svg/W3C-SVG-1.1/filters-gauss-01-b-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/svg/batik/text/smallFonts-expected.png b/third_party/WebKit/LayoutTests/platform/win/svg/batik/text/smallFonts-expected.png index c7b51fd..b978d4c 100644 --- a/third_party/WebKit/LayoutTests/platform/win/svg/batik/text/smallFonts-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/svg/batik/text/smallFonts-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/svg/batik/text/textEffect-expected.png b/third_party/WebKit/LayoutTests/platform/win/svg/batik/text/textEffect-expected.png index dae3e38..04ebb91 100644 --- a/third_party/WebKit/LayoutTests/platform/win/svg/batik/text/textEffect-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/svg/batik/text/textEffect-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/svg/batik/text/textEffect3-expected.png b/third_party/WebKit/LayoutTests/platform/win/svg/batik/text/textEffect3-expected.png index ef66c20..5e9396d 100644 --- a/third_party/WebKit/LayoutTests/platform/win/svg/batik/text/textEffect3-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/svg/batik/text/textEffect3-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/svg/batik/text/textFeatures-expected.png b/third_party/WebKit/LayoutTests/platform/win/svg/batik/text/textFeatures-expected.png index a1a56c3..948a1b3 100644 --- a/third_party/WebKit/LayoutTests/platform/win/svg/batik/text/textFeatures-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/svg/batik/text/textFeatures-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/svg/batik/text/textProperties-expected.png b/third_party/WebKit/LayoutTests/platform/win/svg/batik/text/textProperties-expected.png index 538556d..1d3612a 100644 --- a/third_party/WebKit/LayoutTests/platform/win/svg/batik/text/textProperties-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/svg/batik/text/textProperties-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/svg/custom/image-with-transform-clip-filter-expected.png b/third_party/WebKit/LayoutTests/platform/win/svg/custom/image-with-transform-clip-filter-expected.png index 92becb28..db74913 100644 --- a/third_party/WebKit/LayoutTests/platform/win/svg/custom/image-with-transform-clip-filter-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/svg/custom/image-with-transform-clip-filter-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/svg/custom/recursive-filter-expected.png b/third_party/WebKit/LayoutTests/platform/win/svg/custom/recursive-filter-expected.png index 4d6f642..f3c7f6c 100644 --- a/third_party/WebKit/LayoutTests/platform/win/svg/custom/recursive-filter-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/svg/custom/recursive-filter-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/svg/custom/text-filter-expected.png b/third_party/WebKit/LayoutTests/platform/win/svg/custom/text-filter-expected.png index 4cea4bf..0ed7d05 100644 --- a/third_party/WebKit/LayoutTests/platform/win/svg/custom/text-filter-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/svg/custom/text-filter-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/svg/filters/filter-on-filter-for-text-expected.png b/third_party/WebKit/LayoutTests/platform/win/svg/filters/filter-on-filter-for-text-expected.png index a040145..773551e 100644 --- a/third_party/WebKit/LayoutTests/platform/win/svg/filters/filter-on-filter-for-text-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/svg/filters/filter-on-filter-for-text-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/virtual/display_list_2d_canvas/fast/canvas/canvas-composite-video-shadow-expected.png b/third_party/WebKit/LayoutTests/platform/win/virtual/display_list_2d_canvas/fast/canvas/canvas-composite-video-shadow-expected.png deleted file mode 100644 index 05a993d..0000000 --- a/third_party/WebKit/LayoutTests/platform/win/virtual/display_list_2d_canvas/fast/canvas/canvas-composite-video-shadow-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/virtual/display_list_2d_canvas/fast/canvas/canvas-incremental-repaint-expected.png b/third_party/WebKit/LayoutTests/platform/win/virtual/display_list_2d_canvas/fast/canvas/canvas-incremental-repaint-expected.png deleted file mode 100644 index aa94bdad..0000000 --- a/third_party/WebKit/LayoutTests/platform/win/virtual/display_list_2d_canvas/fast/canvas/canvas-incremental-repaint-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/virtual/display_list_2d_canvas/fast/canvas/canvas-shadow-source-in-expected.png b/third_party/WebKit/LayoutTests/platform/win/virtual/display_list_2d_canvas/fast/canvas/canvas-shadow-source-in-expected.png deleted file mode 100644 index fdcda21..0000000 --- a/third_party/WebKit/LayoutTests/platform/win/virtual/display_list_2d_canvas/fast/canvas/canvas-shadow-source-in-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/virtual/exotic-color-space/images/color-profile-filter-expected.png b/third_party/WebKit/LayoutTests/platform/win/virtual/exotic-color-space/images/color-profile-filter-expected.png index b917ae4..64dc9bd 100644 --- a/third_party/WebKit/LayoutTests/platform/win/virtual/exotic-color-space/images/color-profile-filter-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/virtual/exotic-color-space/images/color-profile-filter-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/virtual/exotic-color-space/images/color-profile-image-filter-all-expected.png b/third_party/WebKit/LayoutTests/platform/win/virtual/exotic-color-space/images/color-profile-image-filter-all-expected.png index d50a529..aa26b47c 100644 --- a/third_party/WebKit/LayoutTests/platform/win/virtual/exotic-color-space/images/color-profile-image-filter-all-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/virtual/exotic-color-space/images/color-profile-image-filter-all-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/virtual/exotic-color-space/images/color-profile-mask-image-svg-expected.png b/third_party/WebKit/LayoutTests/platform/win/virtual/exotic-color-space/images/color-profile-mask-image-svg-expected.png index 756ad838..bf76203 100644 --- a/third_party/WebKit/LayoutTests/platform/win/virtual/exotic-color-space/images/color-profile-mask-image-svg-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/virtual/exotic-color-space/images/color-profile-mask-image-svg-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/resources/README.txt b/third_party/WebKit/LayoutTests/resources/README.txt index d3bf5047..ec4f135b 100644 --- a/third_party/WebKit/LayoutTests/resources/README.txt +++ b/third_party/WebKit/LayoutTests/resources/README.txt
@@ -1,25 +1,22 @@ -The following files are used to run W3C testharness.js-style tests, -either authored for Blink or imported from W3C's web-platform-tests. -These files should not be modified locally, as they are imported. +The following files are used to run W3C testharness.js-based tests. +These files should not be modified locally, as they are manually +synced from LayoutTests/external/wpt/resources (https://crbug.com/685854), +which is automatically synced with W3C web-platform-tests. -* testharness.js from testharness.js -* testharness.css from testharness.js -* idlharness.js from testharness.js -* WebIDLParser.js from webidl2.js - -NOTE: The 'WebIDLParser.js' file is developed as 'webidl2.js' but -web-platform-tests's wpt-tools server is configured to serve the -resource under a different name, which is matched here. +* testdriver.js +* testharness.js +* testharness.css +* idlharness.js +* webidl2.js The following files are native to Blink and can be modified: +* testdriver-vendor.js automation via Blink internal APIs * testharnessreport.js integration with Blink's test runner See also: -* https://www.chromium.org/blink/importing-the-w3c-tests -* LayoutTests/imported/README +https://chromium.googlesource.com/chromium/src/+/master/docs/testing/web_platform_tests.md References: * web-platform-tests https://github.com/w3c/web-platform-tests -* testharness.js https://github.com/w3c/testharness.js -* webidl2.js https://github.com/darobin/webidl2.js +* webidl2.js https://github.com/w3c/webidl2.js
diff --git a/third_party/WebKit/LayoutTests/resources/WebIDLParser.js b/third_party/WebKit/LayoutTests/resources/webidl2.js similarity index 100% rename from third_party/WebKit/LayoutTests/resources/WebIDLParser.js rename to third_party/WebKit/LayoutTests/resources/webidl2.js
diff --git a/third_party/WebKit/LayoutTests/svg/css/path-gradient-stroke-shadow-expected.png b/third_party/WebKit/LayoutTests/svg/css/path-gradient-stroke-shadow-expected.png index deecee4f..98ccd3d 100644 --- a/third_party/WebKit/LayoutTests/svg/css/path-gradient-stroke-shadow-expected.png +++ b/third_party/WebKit/LayoutTests/svg/css/path-gradient-stroke-shadow-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/css/rect-gradient-stroke-shadow-expected.png b/third_party/WebKit/LayoutTests/svg/css/rect-gradient-stroke-shadow-expected.png index 05e1c41..0c81e0d 100644 --- a/third_party/WebKit/LayoutTests/svg/css/rect-gradient-stroke-shadow-expected.png +++ b/third_party/WebKit/LayoutTests/svg/css/rect-gradient-stroke-shadow-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-dom-diffuseConstant-attr-expected.png b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-dom-diffuseConstant-attr-expected.png index e1ef031..32fa64d 100644 --- a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-dom-diffuseConstant-attr-expected.png +++ b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-dom-diffuseConstant-attr-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-dom-in-attr-expected.png b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-dom-in-attr-expected.png index e1ef031..32fa64d 100644 --- a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-dom-in-attr-expected.png +++ b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-dom-in-attr-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-dom-lighting-color-attr-expected.png b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-dom-lighting-color-attr-expected.png index e1ef031..32fa64d 100644 --- a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-dom-lighting-color-attr-expected.png +++ b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-dom-lighting-color-attr-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-dom-surfaceScale-attr-expected.png b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-dom-surfaceScale-attr-expected.png index e1ef031..32fa64d 100644 --- a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-dom-surfaceScale-attr-expected.png +++ b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-dom-surfaceScale-attr-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-inherit-lighting-color-css-prop-expected.png b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-inherit-lighting-color-css-prop-expected.png index e1ef031..32fa64d 100644 --- a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-inherit-lighting-color-css-prop-expected.png +++ b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-inherit-lighting-color-css-prop-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-lighting-color-css-prop-expected.png b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-lighting-color-css-prop-expected.png index e1ef031..32fa64d 100644 --- a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-lighting-color-css-prop-expected.png +++ b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-lighting-color-css-prop-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-svgdom-diffuseConstant-prop-expected.png b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-svgdom-diffuseConstant-prop-expected.png index e1ef031..32fa64d 100644 --- a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-svgdom-diffuseConstant-prop-expected.png +++ b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-svgdom-diffuseConstant-prop-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-svgdom-in-prop-expected.png b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-svgdom-in-prop-expected.png index e1ef031..32fa64d 100644 --- a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-svgdom-in-prop-expected.png +++ b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-svgdom-in-prop-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-svgdom-surfaceScale-prop-expected.png b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-svgdom-surfaceScale-prop-expected.png index e1ef031..32fa64d 100644 --- a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-svgdom-surfaceScale-prop-expected.png +++ b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDiffuseLightingElement-svgdom-surfaceScale-prop-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDistantLightElement-dom-azimuth-attr-expected.png b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDistantLightElement-dom-azimuth-attr-expected.png index f4d4eb6c..f566fbb 100644 --- a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDistantLightElement-dom-azimuth-attr-expected.png +++ b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDistantLightElement-dom-azimuth-attr-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDistantLightElement-dom-elevation-attr-expected.png b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDistantLightElement-dom-elevation-attr-expected.png index f4d4eb6c..f566fbb 100644 --- a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDistantLightElement-dom-elevation-attr-expected.png +++ b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDistantLightElement-dom-elevation-attr-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDistantLightElement-svgdom-azimuth-prop-expected.png b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDistantLightElement-svgdom-azimuth-prop-expected.png index f4d4eb6c..f566fbb 100644 --- a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDistantLightElement-svgdom-azimuth-prop-expected.png +++ b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDistantLightElement-svgdom-azimuth-prop-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDistantLightElement-svgdom-elevation-prop-expected.png b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDistantLightElement-svgdom-elevation-prop-expected.png index f4d4eb6c..f566fbb 100644 --- a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDistantLightElement-svgdom-elevation-prop-expected.png +++ b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDistantLightElement-svgdom-elevation-prop-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDropShadowElement-dom-dx-attr-expected.png b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDropShadowElement-dom-dx-attr-expected.png index 7d8b733a..34ca3870 100644 --- a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDropShadowElement-dom-dx-attr-expected.png +++ b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDropShadowElement-dom-dx-attr-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDropShadowElement-dom-dy-attr-expected.png b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDropShadowElement-dom-dy-attr-expected.png index 7d8b733a..34ca3870 100644 --- a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDropShadowElement-dom-dy-attr-expected.png +++ b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDropShadowElement-dom-dy-attr-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDropShadowElement-dom-in-attr-expected.png b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDropShadowElement-dom-in-attr-expected.png index 7d8b733a..34ca3870 100644 --- a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDropShadowElement-dom-in-attr-expected.png +++ b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDropShadowElement-dom-in-attr-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDropShadowElement-dom-stdDeviation-attr-expected.png b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDropShadowElement-dom-stdDeviation-attr-expected.png index 7dddcae9a..746bcaf 100644 --- a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDropShadowElement-dom-stdDeviation-attr-expected.png +++ b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDropShadowElement-dom-stdDeviation-attr-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDropShadowElement-svgdom-dx-prop-expected.png b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDropShadowElement-svgdom-dx-prop-expected.png index 7d8b733a..34ca3870 100644 --- a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDropShadowElement-svgdom-dx-prop-expected.png +++ b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDropShadowElement-svgdom-dx-prop-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDropShadowElement-svgdom-dy-prop-expected.png b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDropShadowElement-svgdom-dy-prop-expected.png index 7d8b733a..34ca3870 100644 --- a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDropShadowElement-svgdom-dy-prop-expected.png +++ b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDropShadowElement-svgdom-dy-prop-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDropShadowElement-svgdom-in-prop-expected.png b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDropShadowElement-svgdom-in-prop-expected.png index 7d8b733a..34ca3870 100644 --- a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDropShadowElement-svgdom-in-prop-expected.png +++ b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDropShadowElement-svgdom-in-prop-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDropShadowElement-svgdom-stdDeviation-prop-expected.png b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDropShadowElement-svgdom-stdDeviation-prop-expected.png index 7dddcae9a..746bcaf 100644 --- a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDropShadowElement-svgdom-stdDeviation-prop-expected.png +++ b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEDropShadowElement-svgdom-stdDeviation-prop-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEGaussianBlurElement-dom-in-attr-expected.png b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEGaussianBlurElement-dom-in-attr-expected.png index 57ea65b..b66398bfa 100644 --- a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEGaussianBlurElement-dom-in-attr-expected.png +++ b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEGaussianBlurElement-dom-in-attr-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEGaussianBlurElement-dom-stdDeviation-attr-expected.png b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEGaussianBlurElement-dom-stdDeviation-attr-expected.png index 57ea65b..b66398bfa 100644 --- a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEGaussianBlurElement-dom-stdDeviation-attr-expected.png +++ b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEGaussianBlurElement-dom-stdDeviation-attr-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEGaussianBlurElement-dom-stdDeviation-call-expected.png b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEGaussianBlurElement-dom-stdDeviation-call-expected.png index 57ea65b..b66398bfa 100644 --- a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEGaussianBlurElement-dom-stdDeviation-call-expected.png +++ b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEGaussianBlurElement-dom-stdDeviation-call-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEGaussianBlurElement-svgdom-in-prop-expected.png b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEGaussianBlurElement-svgdom-in-prop-expected.png index 57ea65b..b66398bfa 100644 --- a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEGaussianBlurElement-svgdom-in-prop-expected.png +++ b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEGaussianBlurElement-svgdom-in-prop-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEPointLightElement-dom-x-attr-expected.png b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEPointLightElement-dom-x-attr-expected.png index e1ef031..32fa64d 100644 --- a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEPointLightElement-dom-x-attr-expected.png +++ b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEPointLightElement-dom-x-attr-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEPointLightElement-dom-y-attr-expected.png b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEPointLightElement-dom-y-attr-expected.png index e1ef031..32fa64d 100644 --- a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEPointLightElement-dom-y-attr-expected.png +++ b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEPointLightElement-dom-y-attr-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEPointLightElement-dom-z-attr-expected.png b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEPointLightElement-dom-z-attr-expected.png index e1ef031..32fa64d 100644 --- a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEPointLightElement-dom-z-attr-expected.png +++ b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEPointLightElement-dom-z-attr-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEPointLightElement-svgdom-x-prop-expected.png b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEPointLightElement-svgdom-x-prop-expected.png index e1ef031..32fa64d 100644 --- a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEPointLightElement-svgdom-x-prop-expected.png +++ b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEPointLightElement-svgdom-x-prop-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEPointLightElement-svgdom-y-prop-expected.png b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEPointLightElement-svgdom-y-prop-expected.png index e1ef031..32fa64d 100644 --- a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEPointLightElement-svgdom-y-prop-expected.png +++ b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEPointLightElement-svgdom-y-prop-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEPointLightElement-svgdom-z-prop-expected.png b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEPointLightElement-svgdom-z-prop-expected.png index e1ef031..32fa64d 100644 --- a/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEPointLightElement-svgdom-z-prop-expected.png +++ b/third_party/WebKit/LayoutTests/svg/dynamic-updates/SVGFEPointLightElement-svgdom-z-prop-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/filters/feDropShadow-expected.png b/third_party/WebKit/LayoutTests/svg/filters/feDropShadow-expected.png index cc3cec1..b967d88 100644 --- a/third_party/WebKit/LayoutTests/svg/filters/feDropShadow-expected.png +++ b/third_party/WebKit/LayoutTests/svg/filters/feDropShadow-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/filters/feGaussianBlur-expected.png b/third_party/WebKit/LayoutTests/svg/filters/feGaussianBlur-expected.png index 85d216a..49ac1fc9 100644 --- a/third_party/WebKit/LayoutTests/svg/filters/feGaussianBlur-expected.png +++ b/third_party/WebKit/LayoutTests/svg/filters/feGaussianBlur-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/filters/feGaussianBlur-zero-deviation-expected.png b/third_party/WebKit/LayoutTests/svg/filters/feGaussianBlur-zero-deviation-expected.png index 68dd751..c735347 100644 --- a/third_party/WebKit/LayoutTests/svg/filters/feGaussianBlur-zero-deviation-expected.png +++ b/third_party/WebKit/LayoutTests/svg/filters/feGaussianBlur-zero-deviation-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/filters/filter-clip-expected.png b/third_party/WebKit/LayoutTests/svg/filters/filter-clip-expected.png index 76482fb..69808d8 100644 --- a/third_party/WebKit/LayoutTests/svg/filters/filter-clip-expected.png +++ b/third_party/WebKit/LayoutTests/svg/filters/filter-clip-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/filters/innershadow-expected.png b/third_party/WebKit/LayoutTests/svg/filters/innershadow-expected.png index 428b6cd..8f6a45b5b 100644 --- a/third_party/WebKit/LayoutTests/svg/filters/innershadow-expected.png +++ b/third_party/WebKit/LayoutTests/svg/filters/innershadow-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/typedcssom/stylevalue-subclasses/cssPositionValue-expected.txt b/third_party/WebKit/LayoutTests/typedcssom/stylevalue-subclasses/cssPositionValue-expected.txt deleted file mode 100644 index 69dee27..0000000 --- a/third_party/WebKit/LayoutTests/typedcssom/stylevalue-subclasses/cssPositionValue-expected.txt +++ /dev/null
@@ -1,48 +0,0 @@ -This is a testharness.js-based test. -PASS Constructing a CSSPositionValue with a keyword throws a TypeError -PASS Constructing a CSSPositionValue with a double throws a TypeError -PASS Constructing a CSSPositionValue with a unitless zero throws a TypeError -PASS Constructing a CSSPositionValue with a string length throws a TypeError -PASS Constructing a CSSPositionValue with a number CSSUnitValue throws a TypeError -PASS Constructing a CSSPositionValue with a time dimension CSSUnitValue throws a TypeError -PASS Constructing a CSSPositionValue with a CSSMathValue of angle type throws a TypeError -PASS Updating CSSKeywordValue.x with a keyword throws a TypeError -PASS Updating CSSKeywordValue.x with a double throws a TypeError -PASS Updating CSSKeywordValue.x with a unitless zero throws a TypeError -PASS Updating CSSKeywordValue.x with a string length throws a TypeError -PASS Updating CSSKeywordValue.x with a number CSSUnitValue throws a TypeError -PASS Updating CSSKeywordValue.x with a time dimension CSSUnitValue throws a TypeError -PASS Updating CSSKeywordValue.x with a CSSMathValue of angle type throws a TypeError -PASS Updating CSSKeywordValue.y with a keyword throws a TypeError -PASS Updating CSSKeywordValue.y with a double throws a TypeError -PASS Updating CSSKeywordValue.y with a unitless zero throws a TypeError -PASS Updating CSSKeywordValue.y with a string length throws a TypeError -PASS Updating CSSKeywordValue.y with a number CSSUnitValue throws a TypeError -PASS Updating CSSKeywordValue.y with a time dimension CSSUnitValue throws a TypeError -PASS Updating CSSKeywordValue.y with a CSSMathValue of angle type throws a TypeError -PASS CSSPositionValue can be constructed from a length CSSUnitValue and a length CSSUnitValue -PASS CSSPositionValue can be constructed from a length CSSUnitValue and a percent CSSUnitValue -FAIL CSSPositionValue can be constructed from a length CSSUnitValue and a CSSMathValue of length type Failed to construct 'CSSPositionValue': Must pass length or percentage to y in CSSPositionValue -FAIL CSSPositionValue can be constructed from a length CSSUnitValue and a CSSMathValue of percent type Failed to construct 'CSSPositionValue': Must pass length or percentage to y in CSSPositionValue -PASS CSSPositionValue can be constructed from a percent CSSUnitValue and a length CSSUnitValue -PASS CSSPositionValue can be constructed from a percent CSSUnitValue and a percent CSSUnitValue -FAIL CSSPositionValue can be constructed from a percent CSSUnitValue and a CSSMathValue of length type Failed to construct 'CSSPositionValue': Must pass length or percentage to y in CSSPositionValue -FAIL CSSPositionValue can be constructed from a percent CSSUnitValue and a CSSMathValue of percent type Failed to construct 'CSSPositionValue': Must pass length or percentage to y in CSSPositionValue -FAIL CSSPositionValue can be constructed from a CSSMathValue of length type and a length CSSUnitValue Failed to construct 'CSSPositionValue': Must pass length or percentage to x in CSSPositionValue -FAIL CSSPositionValue can be constructed from a CSSMathValue of length type and a percent CSSUnitValue Failed to construct 'CSSPositionValue': Must pass length or percentage to x in CSSPositionValue -FAIL CSSPositionValue can be constructed from a CSSMathValue of length type and a CSSMathValue of length type Failed to construct 'CSSPositionValue': Must pass length or percentage to x in CSSPositionValue -FAIL CSSPositionValue can be constructed from a CSSMathValue of length type and a CSSMathValue of percent type Failed to construct 'CSSPositionValue': Must pass length or percentage to x in CSSPositionValue -FAIL CSSPositionValue can be constructed from a CSSMathValue of percent type and a length CSSUnitValue Failed to construct 'CSSPositionValue': Must pass length or percentage to x in CSSPositionValue -FAIL CSSPositionValue can be constructed from a CSSMathValue of percent type and a percent CSSUnitValue Failed to construct 'CSSPositionValue': Must pass length or percentage to x in CSSPositionValue -FAIL CSSPositionValue can be constructed from a CSSMathValue of percent type and a CSSMathValue of length type Failed to construct 'CSSPositionValue': Must pass length or percentage to x in CSSPositionValue -FAIL CSSPositionValue can be constructed from a CSSMathValue of percent type and a CSSMathValue of percent type Failed to construct 'CSSPositionValue': Must pass length or percentage to x in CSSPositionValue -PASS CSSKeywordValue.x can be updated to a length CSSUnitValue -PASS CSSKeywordValue.x can be updated to a percent CSSUnitValue -FAIL CSSKeywordValue.x can be updated to a CSSMathValue of length type Failed to set the 'x' property on 'CSSPositionValue': Must pass length or percentage to x in CSSPositionValue -FAIL CSSKeywordValue.x can be updated to a CSSMathValue of percent type Failed to set the 'x' property on 'CSSPositionValue': Must pass length or percentage to x in CSSPositionValue -PASS CSSKeywordValue.y can be updated to a length CSSUnitValue -PASS CSSKeywordValue.y can be updated to a percent CSSUnitValue -FAIL CSSKeywordValue.y can be updated to a CSSMathValue of length type Failed to set the 'y' property on 'CSSPositionValue': Must pass length or percentage to y in CSSPositionValue -FAIL CSSKeywordValue.y can be updated to a CSSMathValue of percent type Failed to set the 'y' property on 'CSSPositionValue': Must pass length or percentage to y in CSSPositionValue -Harness: the test ran to completion. -
diff --git a/third_party/WebKit/LayoutTests/typedcssom/stylevalue-subclasses/cssPositionValue.html b/third_party/WebKit/LayoutTests/typedcssom/stylevalue-subclasses/cssPositionValue.html index 6f9e22c..32c7a72 100644 --- a/third_party/WebKit/LayoutTests/typedcssom/stylevalue-subclasses/cssPositionValue.html +++ b/third_party/WebKit/LayoutTests/typedcssom/stylevalue-subclasses/cssPositionValue.html
@@ -31,7 +31,7 @@ const position = new CSSPositionValue(CSS.px(0), CSS.px(0)); assert_throws(new TypeError(), () => position[attr] = value); assert_style_value_equals(position[attr], CSS.px(0)); - }, 'Updating CSSKeywordValue.' + attr + ' with ' + desc + ' throws a TypeError'); + }, 'Updating CSSPositionValue.' + attr + ' with ' + desc + ' throws a TypeError'); } } @@ -58,7 +58,7 @@ const position = new CSSPositionValue(CSS.px(0), CSS.px(0)); position[attr] = value; assert_style_value_equals(position[attr], value); - }, 'CSSKeywordValue.' + attr + ' can be updated to ' + desc); + }, 'CSSPositionValue.' + attr + ' can be updated to ' + desc); } }
diff --git a/third_party/WebKit/LayoutTests/virtual/exotic-color-space/images/color-profile-mask-image-svg-expected.png b/third_party/WebKit/LayoutTests/virtual/exotic-color-space/images/color-profile-mask-image-svg-expected.png deleted file mode 100644 index a03e7cd..0000000 --- a/third_party/WebKit/LayoutTests/virtual/exotic-color-space/images/color-profile-mask-image-svg-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/multicol/column-rules-fixed-height-expected.txt b/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/multicol/column-rules-fixed-height-expected.txt new file mode 100644 index 0000000..722b25b --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/multicol/column-rules-fixed-height-expected.txt
@@ -0,0 +1,63 @@ +{ + "layers": [ + { + "name": "LayoutView #document", + "bounds": [800, 600], + "contentsOpaque": true, + "backgroundColor": "#FFFFFF", + "paintInvalidations": [ + { + "object": "LayoutMultiColumnSet (anonymous)", + "rect": [8, 52, 525, 315], + "reason": "style change" + }, + { + "object": "InlineTextBox 'There should be a blue square below. There should also be five vertical red lines.'", + "rect": [8, 16, 509, 19], + "reason": "appeared" + }, + { + "object": "LayoutMultiColumnFlowThread (anonymous)", + "rect": [110, 52, 106, 315], + "reason": "chunk uncacheable" + }, + { + "object": "LayoutMultiColumnFlowThread (anonymous)", + "rect": [110, 52, 106, 315], + "reason": "chunk uncacheable" + }, + { + "object": "LayoutMultiColumnFlowThread (anonymous)", + "rect": [8, 0, 103, 367], + "reason": "chunk uncacheable" + }, + { + "object": "LayoutMultiColumnFlowThread (anonymous)", + "rect": [8, 0, 103, 367], + "reason": "chunk uncacheable" + }, + { + "object": "LayoutMultiColumnFlowThread (anonymous)", + "rect": [215, 52, 103, 315], + "reason": "chunk uncacheable" + }, + { + "object": "LayoutMultiColumnFlowThread (anonymous)", + "rect": [215, 52, 103, 315], + "reason": "chunk uncacheable" + } + ] + } + ], + "objectPaintInvalidations": [ + { + "object": "LayoutBlockFlow DIV id='target'", + "reason": "style change" + }, + { + "object": "LayoutMultiColumnSet (anonymous)", + "reason": "style change" + } + ] +} +
diff --git a/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/multicol/multicol-as-paint-container-expected.txt b/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/multicol/multicol-as-paint-container-expected.txt new file mode 100644 index 0000000..7ce9c45 --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/multicol/multicol-as-paint-container-expected.txt
@@ -0,0 +1,189 @@ +{ + "layers": [ + { + "name": "LayoutView #document", + "bounds": [800, 600], + "contentsOpaque": true, + "backgroundColor": "#FFFFFF" + }, + { + "name": "LayoutBlockFlow DIV id='target'", + "position": [8, 8], + "bounds": [630, 180], + "backfaceVisibility": "hidden", + "paintInvalidations": [ + { + "object": "InlineTextBox 'Lorem ipsum'", + "rect": [0, 0, 315, 180], + "reason": "chunk uncacheable" + }, + { + "object": "InlineTextBox 'Lorem ipsum'", + "rect": [0, 0, 315, 180], + "reason": "chunk uncacheable" + }, + { + "object": "LayoutMultiColumnFlowThread (anonymous)", + "rect": [315, 0, 310, 180], + "reason": "chunk uncacheable" + }, + { + "object": "LayoutMultiColumnFlowThread (anonymous)", + "rect": [315, 0, 310, 180], + "reason": "chunk uncacheable" + } + ] + } + ], + "objectPaintInvalidations": [ + { + "object": "LayoutText #text", + "reason": "style change" + }, + { + "object": "InlineTextBox 'Lorem ipsum'", + "reason": "style change" + }, + { + "object": "InlineTextBox 'dolor sit amet,'", + "reason": "style change" + }, + { + "object": "InlineTextBox 'consectetur'", + "reason": "style change" + }, + { + "object": "InlineTextBox 'adipiscing'", + "reason": "style change" + }, + { + "object": "InlineTextBox 'elit. Fusce'", + "reason": "style change" + }, + { + "object": "InlineTextBox 'varius, metus'", + "reason": "style change" + }, + { + "object": "InlineTextBox 'eu fringilla'", + "reason": "style change" + }, + { + "object": "InlineTextBox 'pulvinar, ipsum'", + "reason": "style change" + }, + { + "object": "InlineTextBox 'sapien'", + "reason": "style change" + }, + { + "object": "InlineTextBox 'ultricies arcu,'", + "reason": "style change" + }, + { + "object": "InlineTextBox 'non condimentum'", + "reason": "style change" + }, + { + "object": "InlineTextBox 'quam est eu'", + "reason": "style change" + }, + { + "object": "InlineTextBox 'purus. Ut nisl'", + "reason": "style change" + }, + { + "object": "InlineTextBox 'libero,'", + "reason": "style change" + }, + { + "object": "InlineTextBox 'suscipit ut leo'", + "reason": "style change" + }, + { + "object": "InlineTextBox 'eget, dapibus'", + "reason": "style change" + }, + { + "object": "InlineTextBox 'ultrices dolor.'", + "reason": "style change" + }, + { + "object": "LayoutText #text", + "reason": "style change" + }, + { + "object": "InlineTextBox 'Lorem ipsum'", + "reason": "style change" + }, + { + "object": "InlineTextBox 'dolor sit amet,'", + "reason": "style change" + }, + { + "object": "InlineTextBox 'consectetur'", + "reason": "style change" + }, + { + "object": "InlineTextBox 'adipiscing'", + "reason": "style change" + }, + { + "object": "InlineTextBox 'elit. Fusce'", + "reason": "style change" + }, + { + "object": "InlineTextBox 'varius, metus'", + "reason": "style change" + }, + { + "object": "InlineTextBox 'eu fringilla'", + "reason": "style change" + }, + { + "object": "InlineTextBox 'pulvinar, ipsum'", + "reason": "style change" + }, + { + "object": "InlineTextBox 'sapien'", + "reason": "style change" + }, + { + "object": "InlineTextBox 'ultricies arcu,'", + "reason": "style change" + }, + { + "object": "InlineTextBox 'non condimentum'", + "reason": "style change" + }, + { + "object": "InlineTextBox 'quam est eu'", + "reason": "style change" + }, + { + "object": "InlineTextBox 'purus. Ut nisl'", + "reason": "style change" + }, + { + "object": "InlineTextBox 'libero,'", + "reason": "style change" + }, + { + "object": "InlineTextBox 'suscipit ut leo'", + "reason": "style change" + }, + { + "object": "InlineTextBox 'eget, dapibus'", + "reason": "style change" + }, + { + "object": "InlineTextBox 'ultrices dolor.'", + "reason": "style change" + }, + { + "object": "LayoutMultiColumnSet (anonymous)", + "reason": "style change" + } + ] +} +
diff --git a/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/multicol/multicol-repaint-expected.txt b/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/multicol/multicol-repaint-expected.txt new file mode 100644 index 0000000..362d4a7 --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/multicol/multicol-repaint-expected.txt
@@ -0,0 +1,120 @@ +{ + "layers": [ + { + "name": "LayoutView #document", + "bounds": [800, 600], + "contentsOpaque": true, + "backgroundColor": "#FFFFFF", + "paintInvalidations": [ + { + "object": "LayoutBlockFlow DIV class='container'", + "rect": [8, 8, 402, 102], + "reason": "appeared" + }, + { + "object": "LayoutMultiColumnFlowThread (anonymous)", + "rect": [209, 15, 325, 150], + "reason": "chunk uncacheable" + }, + { + "object": "InlineTextBox '\u00A0'", + "rect": [9, 0, 200, 67], + "reason": "chunk uncacheable" + }, + { + "object": "InlineTextBox '\u00A0'", + "rect": [9, 0, 200, 67], + "reason": "chunk uncacheable" + }, + { + "object": "LayoutMultiColumnFlowThread (anonymous)", + "rect": [209, 15, 75, 150], + "reason": "chunk uncacheable" + } + ] + } + ], + "objectPaintInvalidations": [ + { + "object": "LayoutMultiColumnFlowThread (anonymous)", + "reason": "geometry" + }, + { + "object": "RootInlineBox", + "reason": "geometry" + }, + { + "object": "LayoutMultiColumnFlowThread (anonymous)", + "reason": "geometry" + }, + { + "object": "RootInlineBox", + "reason": "geometry" + }, + { + "object": "LayoutText #text", + "reason": "geometry" + }, + { + "object": "InlineTextBox '\u00A0'", + "reason": "geometry" + }, + { + "object": "LayoutText #text", + "reason": "geometry" + }, + { + "object": "InlineTextBox '\u00A0'", + "reason": "geometry" + }, + { + "object": "LayoutBR BR", + "reason": "geometry" + }, + { + "object": "InlineTextBox '\n'", + "reason": "geometry" + }, + { + "object": "LayoutBR BR", + "reason": "geometry" + }, + { + "object": "InlineTextBox '\n'", + "reason": "geometry" + }, + { + "object": "LayoutInline SPAN id='a'", + "reason": "geometry" + }, + { + "object": "InlineFlowBox", + "reason": "geometry" + }, + { + "object": "LayoutInline SPAN id='a'", + "reason": "geometry" + }, + { + "object": "InlineFlowBox", + "reason": "geometry" + }, + { + "object": "LayoutText #text", + "reason": "appeared" + }, + { + "object": "InlineTextBox 'XXXXXX'", + "reason": "appeared" + }, + { + "object": "LayoutText #text", + "reason": "appeared" + }, + { + "object": "InlineTextBox 'XXXXXX'", + "reason": "appeared" + } + ] +} +
diff --git a/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/multicol/multicol-with-block-expected.txt b/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/multicol/multicol-with-block-expected.txt new file mode 100644 index 0000000..4925573 --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/multicol/multicol-with-block-expected.txt
@@ -0,0 +1,41 @@ +{ + "layers": [ + { + "name": "LayoutView #document", + "bounds": [800, 600], + "contentsOpaque": true, + "backgroundColor": "#FFFFFF", + "paintInvalidations": [ + { + "object": "InlineTextBox 'A green rectangle should be seen above (if tested manually, you need to click first).'", + "rect": [8, 44, 523, 19], + "reason": "appeared" + }, + { + "object": "LayoutMultiColumnFlowThread (anonymous)", + "rect": [488, 8, 80, 20], + "reason": "chunk uncacheable" + } + ] + } + ], + "objectPaintInvalidations": [ + { + "object": "LayoutBlockFlow DIV id='target'", + "reason": "style change" + }, + { + "object": "RootInlineBox", + "reason": "style change" + }, + { + "object": "LayoutText #text", + "reason": "style change" + }, + { + "object": "InlineTextBox 'PASS'", + "reason": "style change" + } + ] +} +
diff --git a/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/multicol/multicol-with-inline-expected.txt b/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/multicol/multicol-with-inline-expected.txt new file mode 100644 index 0000000..d10854f --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/multicol/multicol-with-inline-expected.txt
@@ -0,0 +1,73 @@ +{ + "layers": [ + { + "name": "LayoutView #document", + "bounds": [800, 600], + "contentsOpaque": true, + "backgroundColor": "#FFFFFF", + "paintInvalidations": [ + { + "object": "InlineTextBox 'A green rectangle should be seen above (if tested manually, you need to click first).'", + "rect": [8, 44, 523, 19], + "reason": "appeared" + }, + { + "object": "LayoutMultiColumnFlowThread (anonymous)", + "rect": [483, 8, 85, 80], + "reason": "chunk uncacheable" + } + ] + } + ], + "objectPaintInvalidations": [ + { + "object": "LayoutInline SPAN id='target'", + "reason": "style change" + }, + { + "object": "LayoutInline SPAN id='target'", + "reason": "style change" + }, + { + "object": "LayoutInline SPAN id='target'", + "reason": "style change" + }, + { + "object": "LayoutInline SPAN id='target'", + "reason": "style change" + }, + { + "object": "LayoutText #text", + "reason": "style change" + }, + { + "object": "InlineTextBox 'PASS'", + "reason": "style change" + }, + { + "object": "LayoutText #text", + "reason": "style change" + }, + { + "object": "InlineTextBox 'PASS'", + "reason": "style change" + }, + { + "object": "LayoutText #text", + "reason": "style change" + }, + { + "object": "InlineTextBox 'PASS'", + "reason": "style change" + }, + { + "object": "LayoutText #text", + "reason": "style change" + }, + { + "object": "InlineTextBox 'PASS'", + "reason": "style change" + } + ] +} +
diff --git a/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/multicol/multicol-with-text-expected.txt b/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/multicol/multicol-with-text-expected.txt new file mode 100644 index 0000000..b44d92d --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/spv175/paint/invalidation/multicol/multicol-with-text-expected.txt
@@ -0,0 +1,189 @@ +{ + "layers": [ + { + "name": "LayoutView #document", + "bounds": [800, 600], + "contentsOpaque": true, + "backgroundColor": "#FFFFFF", + "paintInvalidations": [ + { + "object": "InlineTextBox 'A green rectangle should be seen above (if tested manually, you need to click first).'", + "rect": [8, 44, 523, 19], + "reason": "appeared" + }, + { + "object": "LayoutMultiColumnFlowThread (anonymous)", + "rect": [483, 8, 85, 80], + "reason": "chunk uncacheable" + } + ] + } + ], + "objectPaintInvalidations": [ + { + "object": "LayoutMultiColumnFlowThread (anonymous)", + "reason": "geometry" + }, + { + "object": "RootInlineBox", + "reason": "geometry" + }, + { + "object": "LayoutMultiColumnFlowThread (anonymous)", + "reason": "geometry" + }, + { + "object": "RootInlineBox", + "reason": "geometry" + }, + { + "object": "LayoutMultiColumnFlowThread (anonymous)", + "reason": "geometry" + }, + { + "object": "RootInlineBox", + "reason": "geometry" + }, + { + "object": "LayoutMultiColumnFlowThread (anonymous)", + "reason": "geometry" + }, + { + "object": "RootInlineBox", + "reason": "geometry" + }, + { + "object": "LayoutBR BR", + "reason": "geometry" + }, + { + "object": "InlineTextBox '\n'", + "reason": "geometry" + }, + { + "object": "LayoutBR BR", + "reason": "geometry" + }, + { + "object": "InlineTextBox '\n'", + "reason": "geometry" + }, + { + "object": "LayoutBR BR", + "reason": "geometry" + }, + { + "object": "InlineTextBox '\n'", + "reason": "geometry" + }, + { + "object": "LayoutBR BR", + "reason": "geometry" + }, + { + "object": "InlineTextBox '\n'", + "reason": "geometry" + }, + { + "object": "LayoutBR BR", + "reason": "geometry" + }, + { + "object": "InlineTextBox '\n'", + "reason": "geometry" + }, + { + "object": "LayoutBR BR", + "reason": "geometry" + }, + { + "object": "InlineTextBox '\n'", + "reason": "geometry" + }, + { + "object": "LayoutBR BR", + "reason": "geometry" + }, + { + "object": "InlineTextBox '\n'", + "reason": "geometry" + }, + { + "object": "LayoutBR BR", + "reason": "geometry" + }, + { + "object": "InlineTextBox '\n'", + "reason": "geometry" + }, + { + "object": "LayoutBR BR", + "reason": "geometry" + }, + { + "object": "InlineTextBox '\n'", + "reason": "geometry" + }, + { + "object": "LayoutBR BR", + "reason": "geometry" + }, + { + "object": "InlineTextBox '\n'", + "reason": "geometry" + }, + { + "object": "LayoutBR BR", + "reason": "geometry" + }, + { + "object": "InlineTextBox '\n'", + "reason": "geometry" + }, + { + "object": "LayoutBR BR", + "reason": "geometry" + }, + { + "object": "InlineTextBox '\n'", + "reason": "geometry" + }, + { + "object": "LayoutText #text", + "reason": "appeared" + }, + { + "object": "InlineTextBox 'PASS'", + "reason": "appeared" + }, + { + "object": "LayoutText #text", + "reason": "appeared" + }, + { + "object": "InlineTextBox 'PASS'", + "reason": "appeared" + }, + { + "object": "LayoutText #text", + "reason": "appeared" + }, + { + "object": "InlineTextBox 'PASS'", + "reason": "appeared" + }, + { + "object": "LayoutText #text", + "reason": "appeared" + }, + { + "object": "InlineTextBox 'PASS'", + "reason": "appeared" + }, + { + "object": "LayoutMultiColumnSet (anonymous)", + "reason": "geometry" + } + ] +} +
diff --git a/third_party/WebKit/LayoutTests/webaudio/AudioParam/event-insertion.html b/third_party/WebKit/LayoutTests/webaudio/AudioParam/event-insertion.html new file mode 100644 index 0000000..790d7975 --- /dev/null +++ b/third_party/WebKit/LayoutTests/webaudio/AudioParam/event-insertion.html
@@ -0,0 +1,314 @@ +<!doctype html> +<html> + <head> + <title> + Test Handling of Event Insertion + </title> + <script src="../../resources/testharness.js"></script> + <script src="../../resources/testharnessreport.js"></script> + <script src="../resources/audit-util.js"></script> + <script src="../resources/audit.js"></script> + <script src="../resources/audio-param.js"></script> + </head> + <body> + <script id="layout-test-code"> + let audit = Audit.createTaskRunner(); + + // Use a power of two for the sample rate so there's no round-off in + // computing time from frame. + let sampleRate = 16384; + + audit.define( + {label: 'Insert same event at same time'}, (task, should) => { + // Context for testing. + let context = new OfflineAudioContext( + {length: 16384, sampleRate: sampleRate}); + + // The source node to use. Automations will be scheduled here. + let src = new ConstantSourceNode(context, {offset: 0}); + src.connect(context.destination); + + // An array of tests to be done. Each entry specifies the event + // type and the event time. The events are inserted in the order + // given (in |values|), and the second event should replace the + // first, as required by the spec. + let testCases = [ + { + event: 'setValueAtTime', + frame: RENDER_QUANTUM_FRAMES, + values: [99, 1], + outputTestFrame: RENDER_QUANTUM_FRAMES, + expectedOutputValue: 1 + }, + { + event: 'linearRampToValueAtTime', + frame: 2 * RENDER_QUANTUM_FRAMES, + values: [99, 2], + outputTestFrame: 2 * RENDER_QUANTUM_FRAMES, + expectedOutputValue: 2 + }, + { + event: 'exponentialRampToValueAtTime', + frame: 3 * RENDER_QUANTUM_FRAMES, + values: [99, 3], + outputTestFrame: 3 * RENDER_QUANTUM_FRAMES, + expectedOutputValue: 3 + }, + { + event: 'setValueCurveAtTime', + frame: 3 * RENDER_QUANTUM_FRAMES, + values: [[98, 99], [3, 4]], + extraArgs: RENDER_QUANTUM_FRAMES / context.sampleRate, + outputTestFrame: 4 * RENDER_QUANTUM_FRAMES, + expectedOutputValue: 4 + } + ]; + + testCases.forEach(entry => { + entry.values.forEach(value => { + let eventTime = entry.frame / context.sampleRate; + let message = eventToString( + entry.event, value, eventTime, entry.extraArgs); + // This is mostly to print out the event that is getting + // inserted. It should never ever throw. + should(() => { + src.offset[entry.event](value, eventTime, entry.extraArgs); + }, message).notThrow(); + }); + }); + + src.start(); + + context.startRendering() + .then(audioBuffer => { + let audio = audioBuffer.getChannelData(0); + + // Look through the test cases to figure out what the correct + // output values should be. + testCases.forEach(entry => { + let expected = entry.expectedOutputValue; + let frame = entry.outputTestFrame; + let time = frame / context.sampleRate; + should( + audio[frame], `Output at frame ${frame} (time ${time})`) + .beEqualTo(expected); + }); + }) + .then(() => task.done()); + }); + + audit.define( + { + label: 'Linear + Expo', + description: 'Different events at same time' + }, + (task, should) => { + // Should be a linear ramp up to the event time, and after a + // constant value because the exponential ramp has ended. + let testCase = [ + {event: 'linearRampToValueAtTime', value: 2, relError: 0}, + {event: 'setValueAtTime', value: 99}, + {event: 'exponentialRampToValueAtTime', value: 3}, + ]; + let eventFrame = 2 * RENDER_QUANTUM_FRAMES; + let prefix = 'Linear+Expo: '; + + testEventInsertion(prefix, should, eventFrame, testCase) + .then(expectConstant(prefix, should, eventFrame, testCase)) + .then(() => task.done()); + }); + + audit.define( + { + label: 'Expo + Linear', + description: 'Different events at same time', + }, + (task, should) => { + // Should be an exponential ramp up to the event time, and after a + // constant value because the linear ramp has ended. + let testCase = [ + { + event: 'exponentialRampToValueAtTime', + value: 3, + relError: 4.2533e-6 + }, + {event: 'setValueAtTime', value: 99}, + {event: 'linearRampToValueAtTime', value: 2}, + ]; + let eventFrame = 2 * RENDER_QUANTUM_FRAMES; + let prefix = 'Expo+Linear: '; + + testEventInsertion(prefix, should, eventFrame, testCase) + .then(expectConstant(prefix, should, eventFrame, testCase)) + .then(() => task.done()); + }); + + audit.define( + { + label: 'Linear + SetTarget', + description: 'Different events at same time', + }, + (task, should) => { + // Should be a linear ramp up to the event time, and then a + // decaying value. + let testCase = [ + {event: 'linearRampToValueAtTime', value: 3, relError: 0}, + {event: 'setValueAtTime', value: 100}, + {event: 'setTargetAtTime', value: 0, extraArgs: 0.1}, + ]; + let eventFrame = 2 * RENDER_QUANTUM_FRAMES; + let prefix = 'Linear+SetTarget: '; + + testEventInsertion(prefix, should, eventFrame, testCase) + .then(audioBuffer => { + let audio = audioBuffer.getChannelData(0); + let prefix = 'Linear+SetTarget: '; + let eventTime = eventFrame / sampleRate; + let expectedValue = methodMap[testCase[0].event]( + (eventFrame - 1) / sampleRate, 1, 0, testCase[0].value, + eventTime); + should( + audio[eventFrame - 1], + prefix + + `At time ${ + (eventFrame - 1) / sampleRate + } (frame ${eventFrame - 1}) output`) + .beCloseTo( + expectedValue, + {threshold: testCase[0].relError || 0}); + + // The setValue should have taken effect + should( + audio[eventFrame], + prefix + + `At time ${eventTime} (frame ${eventFrame}) output`) + .beEqualTo(testCase[1].value); + + // The final event is setTarget. Compute the expected output. + let actual = audio.slice(eventFrame); + let expected = new Float32Array(actual.length); + for (let k = 0; k < expected.length; ++k) { + let t = (eventFrame + k) / sampleRate; + expected[k] = audioParamSetTarget( + t, testCase[1].value, eventTime, testCase[2].value, + testCase[2].extraArgs); + } + should( + actual, + prefix + + `At time ${eventTime} (frame ${ + eventFrame + }) and later`) + .beCloseToArray(expected, {relativeThreshold: 1.7807e-7}); + }) + .then(() => task.done()); + }); + + + audit.run(); + + // Takes a list of |testCases| consisting of automation methods and + // schedules them to occur at |eventFrame|. |prefix| is a prefix for + // messages produced by |should|. + // + // Each item in |testCases| is a dictionary with members: + // event - the name of automation method to be inserted, + // value - the value for the event, + // extraArgs - extra arguments if the event needs more than the value + // and time (such as setTargetAtTime). + function testEventInsertion(prefix, should, eventFrame, testCases) { + let context = new OfflineAudioContext( + {length: 4 * RENDER_QUANTUM_FRAMES, sampleRate: sampleRate}); + + // The source node to use. Automations will be scheduled here. + let src = new ConstantSourceNode(context, {offset: 0}); + src.connect(context.destination); + + // Initialize value to 1 at the beginning. + src.offset.setValueAtTime(1, 0); + + // Test automations have this event time. + let eventTime = eventFrame / context.sampleRate; + + // Sanity check that context is long enough for the test + should( + eventFrame < context.length, + prefix + 'Context length is long enough for the test') + .beTrue(); + + // Automations to be tested. The first event should be the actual + // output up to the event time. The last event should be the final + // output from the event time and onwards. + testCases.forEach(entry => { + should( + () => { + src.offset[entry.event]( + entry.value, eventTime, entry.extraArgs); + }, + prefix + + eventToString( + entry.event, entry.value, eventTime, entry.extraArgs)) + .notThrow(); + }); + + src.start(); + + return context.startRendering(); + } + + // Verify output of test where the final value of the automation is + // expected to be constant. + function expectConstant(prefix, should, eventFrame, testCases) { + return audioBuffer => { + let audio = audioBuffer.getChannelData(0); + + let eventTime = eventFrame / sampleRate; + + // Compute the expected value of the first automation one frame before + // the event time. This is a quick check that the correct automation + // was done. + let expectedValue = methodMap[testCases[0].event]( + (eventFrame - 1) / sampleRate, 1, 0, testCases[0].value, + eventTime); + should( + audio[eventFrame - 1], + prefix + + `At time ${ + (eventFrame - 1) / sampleRate + } (frame ${eventFrame - 1}) output`) + .beCloseTo(expectedValue, {threshold: testCases[0].relError}); + + // The last event scheduled is expected to set the value for all + // future times. Verify that the output has the expected value. + should( + audio.slice(eventFrame), + prefix + + `At time ${eventTime} (frame ${ + eventFrame + }) and later, output`) + .beConstantValueOf(testCases[testCases.length - 1].value); + }; + } + + // Convert an automation method to a string for printing. + function eventToString(method, value, time, extras) { + let string = method + '('; + string += (value instanceof Array) ? `[${value}]` : value; + string += ', ' + time; + if (extras) { + string += ', ' + extras; + } + string += ')'; + return string; + } + + // Map between the automation method name and a function that computes the + // output value of the automation method. + const methodMap = { + linearRampToValueAtTime: audioParamLinearRamp, + exponentialRampToValueAtTime: audioParamExponentialRamp, + setValueAtTime: (t, v) => v + }; + </script> + </body> +</html>
diff --git a/third_party/WebKit/LayoutTests/webaudio/WaveShaper/waveshaper-copy-curve.html b/third_party/WebKit/LayoutTests/webaudio/WaveShaper/waveshaper-copy-curve.html index a635473..ce0649b 100644 --- a/third_party/WebKit/LayoutTests/webaudio/WaveShaper/waveshaper-copy-curve.html +++ b/third_party/WebKit/LayoutTests/webaudio/WaveShaper/waveshaper-copy-curve.html
@@ -18,70 +18,81 @@ let audit = Audit.createTaskRunner(); - audit.define('test copying', (task, should) => { - // Two-channel context; channel 0 contains the test data and channel 1 - // contains the expected result. Channel 1 has the normal WaveShaper - // output and channel 0 has the WaveShaper output with a modified curve. - let context = new OfflineAudioContext(2, renderFrames, sampleRate); + audit.define( + { + label: 'test copying', + description: 'Modifying curve should not modify WaveShaper' + }, + (task, should) => { + // Two-channel context; channel 0 contains the test data and channel + // 1 contains the expected result. Channel 1 has the normal + // WaveShaper output and channel 0 has the WaveShaper output with a + // modified curve. + let context = new OfflineAudioContext(2, renderFrames, sampleRate); - // Just use a default oscillator as the source. Doesn't really matter - // what we use. - let src = context.createOscillator(); - src.type = 'sawtooth'; + // Just use a default oscillator as the source. Doesn't really + // matter what we use. + let src = context.createOscillator(); + src.type = 'sawtooth'; - // Create the wave shapers: ws0 is the test shaper, and ws1 is the - // reference wave shaper. - let ws0 = context.createWaveShaper(); - let ws1 = context.createWaveShaper(); + // Create the wave shapers: ws0 is the test shaper, and ws1 is the + // reference wave shaper. + let ws0 = context.createWaveShaper(); + let ws1 = context.createWaveShaper(); - // Wave shaper curves. Doesn't really matter what we use as long as it - // modifies the input in some way. Thus, keep it simple and just invert - // the input. - let desiredCurve = [1, 0, -1]; - let curve0 = Float32Array.from(desiredCurve); - let curve1 = Float32Array.from(desiredCurve); + // Wave shaper curves. Doesn't really matter what we use as long as + // it modifies the input in some way. Thus, keep it simple and just + // invert the input. + let desiredCurve = [1, 0, -1]; + let curve0 = Float32Array.from(desiredCurve); + let curve1 = Float32Array.from(desiredCurve); - ws0.curve = curve0; - ws1.curve = curve1; + ws0.curve = curve0; + ws1.curve = curve1; - let merger = context.createChannelMerger(2); + let merger = context.createChannelMerger(2); - // Connect the graph - src.connect(ws0); - src.connect(ws1); + // Connect the graph + src.connect(ws0); + src.connect(ws1); - ws0.connect(merger, 0, 0); - ws1.connect(merger, 0, 1); + ws0.connect(merger, 0, 0); + ws1.connect(merger, 0, 1); - merger.connect(context.destination); + merger.connect(context.destination); - // Let the context run for a bit and then modify the curve for ws0. - // Doesn't really matter what we modify the curve to as long as it's - // different. - context.suspend(256 / context.sampleRate) - .then(function() { - curve0[0] = -0.5; - curve0[1] = 0.125; - curve0[2] = 0.75; - }) - .then(context.resume.bind(context)); + // Let the context run for a bit and then modify the curve for ws0. + // Doesn't really matter what we modify the curve to as long as it's + // different. + context.suspend(256 / context.sampleRate) + .then(() => { + should( + () => { + curve0[0] = -0.5; + curve0[1] = 0.125; + curve0[2] = 0.75; + }, + `Modifying curve array at time ${context.currentTime}`) + .notThrow(); + }) + .then(context.resume.bind(context)); - src.start(); + src.start(); - context.startRendering() - .then(function(renderedBuffer) { - let actual = renderedBuffer.getChannelData(0); - let expected = renderedBuffer.getChannelData(1); + context.startRendering() + .then(function(renderedBuffer) { + let actual = renderedBuffer.getChannelData(0); + let expected = renderedBuffer.getChannelData(1); - // Modifying the wave shaper curve should not modify the output so - // the outputs from the two wave shaper nodes should be exactly - // identical. - should(actual, 'WaveShaper with modified curve') - .beEqualToArray(expected); + // Modifying the wave shaper curve should not modify the + // output so the outputs from the two wave shaper nodes should + // be exactly identical. + should(actual, 'Output of WaveShaper with modified curve') + .beEqualToArray(expected); - }) - .then(() => task.done()); - }); + }) + .then(() => task.done()); + }); audit.run(); </script>
diff --git a/third_party/WebKit/LayoutTests/webaudio/WaveShaper/waveshaper-simple.html b/third_party/WebKit/LayoutTests/webaudio/WaveShaper/waveshaper-simple.html index 4e6acd46..73133a07 100644 --- a/third_party/WebKit/LayoutTests/webaudio/WaveShaper/waveshaper-simple.html +++ b/third_party/WebKit/LayoutTests/webaudio/WaveShaper/waveshaper-simple.html
@@ -18,30 +18,38 @@ let shaper = context.createWaveShaper(); // Verify default values are correct. - should(shaper.curve, 'WaveShaper.curve').beEqualTo(null); - should(shaper.oversample, 'WaveShaper.oversample').beEqualTo('none'); + should(shaper.curve, 'Initial WaveShaper.curve').beEqualTo(null); + should(shaper.oversample, 'Initial WaveShaper.oversample') + .beEqualTo('none'); // Set oversample and verify that it is set correctly. - shaper.oversample = '2x'; + should(() => shaper.oversample = '2x', 'Setting oversample to "2x"') + .notThrow(); should(shaper.oversample, 'Waveshaper.oversample = "2x"') .beEqualTo('2x'); - shaper.oversample = '4x'; + should(() => shaper.oversample = '4x', 'Setting oversample to "4x"') + .notThrow(); should(shaper.oversample, 'Waveshaper.oversample = "4x"') .beEqualTo('4x'); - shaper.oversample = 'invalid'; + should( + () => shaper.oversample = 'invalid', + 'Setting oversample to "invalid"') + .notThrow(); should(shaper.oversample, 'Waveshaper.oversample = "invalid"') .beEqualTo('4x'); // Set the curve and verify that the returned curve is the same as what // it was set to. let curve = Float32Array.from([-1, 0.25, .75]); - shaper.curve = curve; + should(() => shaper.curve = curve, 'Setting curve to [' + curve + ']') + .notThrow(); should(shaper.curve, 'WaveShaper.curve').beEqualToArray(curve); // Verify setting the curve to null works. - shaper.curve = null; + should(() => shaper.curve = null, 'Setting curve back to null') + .notThrow(); should(shaper.curve, 'Waveshaper.curve = null').beEqualTo(null); task.done();
diff --git a/third_party/WebKit/LayoutTests/webaudio/audio-worklet/audio-worklet-node-idl.html b/third_party/WebKit/LayoutTests/webaudio/audio-worklet/audio-worklet-node-idl.html index ecb895b..89812d60 100644 --- a/third_party/WebKit/LayoutTests/webaudio/audio-worklet/audio-worklet-node-idl.html +++ b/third_party/WebKit/LayoutTests/webaudio/audio-worklet/audio-worklet-node-idl.html
@@ -6,7 +6,7 @@ </title> <script src="../../resources/testharness.js"></script> <script src="../../resources/testharnessreport.js"></script> - <script src="../../resources/WebIDLParser.js"></script> + <script src="../../resources/webidl2.js"></script> <script src="../../resources/idlharness.js"></script> </head> <body>
diff --git a/third_party/WebKit/LayoutTests/webauth/idl-expected.txt b/third_party/WebKit/LayoutTests/webauth/idl-expected.txt index 86ed362..7e97a6d 100644 --- a/third_party/WebKit/LayoutTests/webauth/idl-expected.txt +++ b/third_party/WebKit/LayoutTests/webauth/idl-expected.txt
@@ -25,5 +25,6 @@ PASS AuthenticatorAssertionResponse interface: existence and properties of interface prototype object's "constructor" property PASS AuthenticatorAssertionResponse interface: attribute authenticatorData PASS AuthenticatorAssertionResponse interface: attribute signature +PASS AuthenticatorAssertionResponse interface: attribute userHandle Harness: the test ran to completion.
diff --git a/third_party/WebKit/LayoutTests/webauth/idl.html b/third_party/WebKit/LayoutTests/webauth/idl.html index 769724a..668a2176 100644 --- a/third_party/WebKit/LayoutTests/webauth/idl.html +++ b/third_party/WebKit/LayoutTests/webauth/idl.html
@@ -1,74 +1,78 @@ <!DOCTYPE html> <script src=../resources/testharness.js></script> <script src=../resources/testharnessreport.js></script> -<script src=../resources/WebIDLParser.js></script> +<script src=../resources/webidl2.js></script> <script src=../resources/idlharness.js></script> <script type="text/plain" id="tested"> -[SecureContext] +[SecureContext, Exposed=Window] interface PublicKeyCredential : Credential { - readonly attribute ArrayBuffer rawId; - readonly attribute AuthenticatorResponse response; + [SameObject] readonly attribute ArrayBuffer rawId; + [SameObject] readonly attribute AuthenticatorResponse response; }; partial dictionary CredentialCreationOptions { - MakeCredentialOptions? publicKey; + MakePublicKeyCredentialOptions? publicKey; }; partial dictionary CredentialRequestOptions { PublicKeyCredentialRequestOptions? publicKey; }; -[SecureContext] +[SecureContext, Exposed=Window] interface AuthenticatorResponse { - readonly attribute ArrayBuffer clientDataJSON; + [SameObject] readonly attribute ArrayBuffer clientDataJSON; }; -[SecureContext] +[SecureContext, Exposed=Window] interface AuthenticatorAttestationResponse : AuthenticatorResponse { - readonly attribute ArrayBuffer attestationObject; + [SameObject] readonly attribute ArrayBuffer attestationObject; }; -[SecureContext] +[SecureContext, Exposed=Window] interface AuthenticatorAssertionResponse : AuthenticatorResponse { - readonly attribute ArrayBuffer authenticatorData; - readonly attribute ArrayBuffer signature; + [SameObject] readonly attribute ArrayBuffer authenticatorData; + [SameObject] readonly attribute ArrayBuffer signature; + [SameObject] readonly attribute ArrayBuffer userHandle; }; -typedef long COSEAlgorithmIdentifier; - dictionary PublicKeyCredentialParameters { required PublicKeyCredentialType type; - required COSEAlgorithmIdentifier algorithm; + required COSEAlgorithmIdentifier alg; }; -dictionary MakeCredentialOptions { - required PublicKeyCredentialEntity rp; +dictionary MakePublicKeyCredentialOptions { + required PublicKeyCredentialRpEntity rp; required PublicKeyCredentialUserEntity user; required BufferSource challenge; - required sequence<PublicKeyCredentialParameters> parameters; + required sequence<PublicKeyCredentialParameters> pubKeyCredParams; unsigned long timeout; - sequence<PublicKeyCredentialDescriptor> excludeList = []; + sequence<PublicKeyCredentialDescriptor> excludeCredentials = []; AuthenticatorSelectionCriteria authenticatorSelection; }; dictionary PublicKeyCredentialEntity { - DOMString id; - DOMString name; + required DOMString name; USVString icon; }; +dictionary PublicKeyCredentialRpEntity : PublicKeyCredentialEntity { + DOMString id; +}; + dictionary PublicKeyCredentialUserEntity : PublicKeyCredentialEntity { - DOMString displayName; + required BufferSource id; + required DOMString displayName; }; dictionary AuthenticatorSelectionCriteria { Attachment attachment; boolean requireResidentKey = false; + boolean requireUserVerification = false; }; -enum Attachment { +enum AuthenticatorAttachment { "platform", "cross-platform" }; @@ -77,13 +81,14 @@ required BufferSource challenge; unsigned long timeout; USVString rpId; - sequence<PublicKeyCredentialDescriptor> allowList = []; + sequence<PublicKeyCredentialDescriptor> allowCredentials = []; }; dictionary CollectedClientData { + required DOMString type; required DOMString challenge; required DOMString origin; - required DOMString hashAlg; + required DOMString hashAlgorithm; DOMString tokenBindingId; }; @@ -94,15 +99,17 @@ dictionary PublicKeyCredentialDescriptor { required PublicKeyCredentialType type; required BufferSource id; - sequence<Transport> transports; + sequence<AuthenticatorTransport> transports; }; -enum Transport { +enum AuthenticatorTransport { "usb", "nfc", "ble" }; +typedef long COSEAlgorithmIdentifier; + </script> <script> (function() { @@ -111,4 +118,4 @@ idl_array.add_idls(document.querySelector('#tested').textContent); idl_array.test(); })(); -</script> \ No newline at end of file +</script>
diff --git a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-dedicated-worker-expected.txt b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-dedicated-worker-expected.txt index 6c47d5d..8c083674 100644 --- a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-dedicated-worker-expected.txt +++ b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-dedicated-worker-expected.txt
@@ -21,7 +21,6 @@ [Worker] getter downloaded [Worker] getter id [Worker] getter onprogress -[Worker] getter title [Worker] getter totalDownloadSize [Worker] getter uploadTotal [Worker] getter uploaded
diff --git a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt index a3531846..0cc9fc59 100644 --- a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt +++ b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt
@@ -409,6 +409,7 @@ attribute @@toStringTag getter authenticatorData getter signature + getter userHandle method constructor interface AuthenticatorAttestationResponse : AuthenticatorResponse attribute @@toStringTag @@ -434,7 +435,6 @@ getter downloaded getter id getter onprogress - getter title getter totalDownloadSize getter uploadTotal getter uploaded
diff --git a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-shared-worker-expected.txt b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-shared-worker-expected.txt index 5ffc2303..a30a0e11 100644 --- a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-shared-worker-expected.txt +++ b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-shared-worker-expected.txt
@@ -21,7 +21,6 @@ [Worker] getter downloaded [Worker] getter id [Worker] getter onprogress -[Worker] getter title [Worker] getter totalDownloadSize [Worker] getter uploadTotal [Worker] getter uploaded
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8Initializer.cpp b/third_party/WebKit/Source/bindings/core/v8/V8Initializer.cpp index cfb957e7..cf94fc1 100644 --- a/third_party/WebKit/Source/bindings/core/v8/V8Initializer.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/V8Initializer.cpp
@@ -595,6 +595,7 @@ // NOTE: Some threads (namely utility threads) don't have a scheduler. WebScheduler* scheduler = Platform::Current()->CurrentThread()->Scheduler(); +#if defined(USE_V8_CONTEXT_SNAPSHOT) V8PerIsolateData::V8ContextSnapshotMode v8_context_snapshot_mode = Platform::Current()->IsTakingV8ContextSnapshot() ? V8PerIsolateData::V8ContextSnapshotMode::kTakeSnapshot @@ -605,6 +606,10 @@ v8_context_snapshot_mode = V8PerIsolateData::V8ContextSnapshotMode::kDontUseSnapshot; } +#else + V8PerIsolateData::V8ContextSnapshotMode v8_context_snapshot_mode = + V8PerIsolateData::V8ContextSnapshotMode::kDontUseSnapshot; +#endif // USE_V8_CONTEXT_SNAPSHOT v8::Isolate* isolate = V8PerIsolateData::Initialize( scheduler ? scheduler->V8TaskRunner()
diff --git a/third_party/WebKit/Source/bindings/modules/BUILD.gn b/third_party/WebKit/Source/bindings/modules/BUILD.gn index aa4266b7..2fcd3a68 100644 --- a/third_party/WebKit/Source/bindings/modules/BUILD.gn +++ b/third_party/WebKit/Source/bindings/modules/BUILD.gn
@@ -48,7 +48,6 @@ "//third_party/WebKit/Source/modules/serviceworkers/ExtendableEvent.idl", "//third_party/WebKit/Source/modules/serviceworkers/ExtendableMessageEvent.idl", "//third_party/WebKit/Source/modules/serviceworkers/FetchEvent.idl", - "//third_party/WebKit/Source/modules/serviceworkers/ForeignFetchEvent.idl", "//third_party/WebKit/Source/modules/serviceworkers/InstallEvent.idl", "//third_party/WebKit/Source/modules/speech/SpeechRecognitionError.idl", "//third_party/WebKit/Source/modules/speech/SpeechRecognitionEvent.idl",
diff --git a/third_party/WebKit/Source/core/BUILD.gn b/third_party/WebKit/Source/core/BUILD.gn index d3605d3f..d6b5d94 100644 --- a/third_party/WebKit/Source/core/BUILD.gn +++ b/third_party/WebKit/Source/core/BUILD.gn
@@ -1314,6 +1314,7 @@ configs += [ ":core_include_dirs", + "//tools/v8_context_snapshot:use_v8_context_snapshot", # TODO(jschuh): crbug.com/167187 fix size_t to int truncations. "//build/config/compiler:no_size_t_to_int_warning",
diff --git a/third_party/WebKit/Source/core/CoreInitializer.h b/third_party/WebKit/Source/core/CoreInitializer.h index ffb77cfb..48bf187e 100644 --- a/third_party/WebKit/Source/core/CoreInitializer.h +++ b/third_party/WebKit/Source/core/CoreInitializer.h
@@ -38,13 +38,11 @@ namespace blink { class Document; -class HTMLLinkElement; class HTMLMediaElement; class InspectedFrames; class InspectorDOMAgent; class InspectorSession; class InterfaceRegistry; -class LinkResource; class LocalFrame; class MediaControls; class Page; @@ -98,8 +96,6 @@ InspectorDOMAgent*, InspectedFrames*, Page*) const = 0; - virtual LinkResource* CreateServiceWorkerLinkResource( - HTMLLinkElement*) const = 0; virtual void OnClearWindowObjectInMainWorld(Document&, const Settings&) const = 0;
diff --git a/third_party/WebKit/Source/core/animation/AnimationInputHelpersTest.cpp b/third_party/WebKit/Source/core/animation/AnimationInputHelpersTest.cpp index dbcc025f..e818487f 100644 --- a/third_party/WebKit/Source/core/animation/AnimationInputHelpersTest.cpp +++ b/third_party/WebKit/Source/core/animation/AnimationInputHelpersTest.cpp
@@ -8,13 +8,13 @@ #include "core/animation/PropertyHandle.h" #include "core/dom/Element.h" #include "core/dom/ExceptionCode.h" -#include "core/testing/DummyPageHolder.h" +#include "core/testing/PageTestBase.h" #include "platform/animation/TimingFunction.h" #include "testing/gtest/include/gtest/gtest.h" namespace blink { -class AnimationAnimationInputHelpersTest : public ::testing::Test { +class AnimationAnimationInputHelpersTest : public PageTestBase { public: CSSPropertyID KeyframeAttributeToCSSProperty(const String& property) { return AnimationInputHelpers::KeyframeAttributeToCSSProperty(property, @@ -68,8 +68,8 @@ protected: void SetUp() override { - page_holder = DummyPageHolder::Create(); - document = &page_holder->GetDocument(); + PageTestBase::SetUp(IntSize()); + document = &GetDocument(); } void TearDown() override { @@ -77,7 +77,6 @@ ThreadState::Current()->CollectAllGarbage(); } - std::unique_ptr<DummyPageHolder> page_holder; Persistent<Document> document; };
diff --git a/third_party/WebKit/Source/core/animation/EffectStackTest.cpp b/third_party/WebKit/Source/core/animation/EffectStackTest.cpp index c007526e..261d43a 100644 --- a/third_party/WebKit/Source/core/animation/EffectStackTest.cpp +++ b/third_party/WebKit/Source/core/animation/EffectStackTest.cpp
@@ -14,19 +14,18 @@ #include "core/animation/PendingAnimations.h" #include "core/animation/StringKeyframe.h" #include "core/animation/animatable/AnimatableDouble.h" -#include "core/testing/DummyPageHolder.h" +#include "core/testing/PageTestBase.h" #include "testing/gtest/include/gtest/gtest.h" namespace blink { -class AnimationEffectStackTest : public ::testing::Test { +class AnimationEffectStackTest : public PageTestBase { protected: void SetUp() override { - page_holder = DummyPageHolder::Create(); - document = &page_holder->GetDocument(); - document->GetAnimationClock().ResetTimeForTesting(); - timeline = DocumentTimeline::Create(document.Get()); - element = document->createElement("foo"); + PageTestBase::SetUp(IntSize()); + GetDocument().GetAnimationClock().ResetTimeForTesting(); + timeline = DocumentTimeline::Create(&GetDocument()); + element = GetDocument().createElement("foo"); } Animation* Play(KeyframeEffect* effect, double start_time) { @@ -37,8 +36,8 @@ } void UpdateTimeline(double time) { - document->GetAnimationClock().UpdateTime(document->Timeline().ZeroTime() + - time); + GetDocument().GetAnimationClock().UpdateTime( + GetDocument().Timeline().ZeroTime() + time); timeline->ServiceAnimations(kTimingUpdateForAnimationFrame); } @@ -79,7 +78,7 @@ const ActiveInterpolationsMap& active_interpolations) { const ActiveInterpolations& interpolations = active_interpolations.at(PropertyHandle(GetCSSPropertyFontSize())); - EnsureInterpolatedValueCached(interpolations, *document, element); + EnsureInterpolatedValueCached(interpolations, GetDocument(), element); const TypedInterpolationValue* typed_value = ToInvalidatableInterpolation(*interpolations.at(0)) @@ -94,7 +93,7 @@ double GetZIndexValue(const ActiveInterpolationsMap& active_interpolations) { const ActiveInterpolations& interpolations = active_interpolations.at(PropertyHandle(GetCSSPropertyZIndex())); - EnsureInterpolatedValueCached(interpolations, *document, element); + EnsureInterpolatedValueCached(interpolations, GetDocument(), element); const TypedInterpolationValue* typed_value = ToInvalidatableInterpolation(*interpolations.at(0)) @@ -104,8 +103,6 @@ return ToInterpolableNumber(&typed_value->GetInterpolableValue())->Value(); } - std::unique_ptr<DummyPageHolder> page_holder; - Persistent<Document> document; Persistent<DocumentTimeline> timeline; Persistent<Element> element; }; @@ -172,7 +169,8 @@ Play(MakeKeyframeEffect(MakeEffectModel(CSSPropertyFontSize, "1px")), 2); Play(MakeKeyframeEffect(MakeEffectModel(CSSPropertyFontSize, "2px")), 6); Play(MakeKeyframeEffect(MakeEffectModel(CSSPropertyFontSize, "3px")), 4); - document->GetPendingAnimations().Update(Optional<CompositorElementIdSet>()); + GetDocument().GetPendingAnimations().Update( + Optional<CompositorElementIdSet>()); ActiveInterpolationsMap interpolations; UpdateTimeline(11);
diff --git a/third_party/WebKit/Source/core/css/CSSStyleSheet.cpp b/third_party/WebKit/Source/core/css/CSSStyleSheet.cpp index 562d927..37f83d8 100644 --- a/third_party/WebKit/Source/core/css/CSSStyleSheet.cpp +++ b/third_party/WebKit/Source/core/css/CSSStyleSheet.cpp
@@ -266,13 +266,19 @@ return false; } -CSSRuleList* CSSStyleSheet::rules() { - return cssRules(); +CSSRuleList* CSSStyleSheet::rules(ExceptionState& exception_state) { + return cssRules(exception_state); } unsigned CSSStyleSheet::insertRule(const String& rule_string, unsigned index, ExceptionState& exception_state) { + if (!CanAccessRules()) { + exception_state.ThrowSecurityError( + "Cannot access StyleSheet to insertRule"); + return 0; + } + DCHECK(child_rule_cssom_wrappers_.IsEmpty() || child_rule_cssom_wrappers_.size() == contents_->RuleCount()); @@ -313,6 +319,12 @@ void CSSStyleSheet::deleteRule(unsigned index, ExceptionState& exception_state) { + if (!CanAccessRules()) { + exception_state.ThrowSecurityError( + "Cannot access StyleSheet to deleteRule"); + return; + } + DCHECK(child_rule_cssom_wrappers_.IsEmpty() || child_rule_cssom_wrappers_.size() == contents_->RuleCount()); @@ -362,9 +374,11 @@ return addRule(selector, style, length(), exception_state); } -CSSRuleList* CSSStyleSheet::cssRules() { - if (!CanAccessRules()) +CSSRuleList* CSSStyleSheet::cssRules(ExceptionState& exception_state) { + if (!CanAccessRules()) { + exception_state.ThrowSecurityError("Cannot access rules"); return nullptr; + } if (!rule_list_cssom_wrapper_) rule_list_cssom_wrapper_ = StyleSheetCSSRuleList::Create(this); return rule_list_cssom_wrapper_.Get();
diff --git a/third_party/WebKit/Source/core/css/CSSStyleSheet.h b/third_party/WebKit/Source/core/css/CSSStyleSheet.h index 710f6f0c..72766e6 100644 --- a/third_party/WebKit/Source/core/css/CSSStyleSheet.h +++ b/third_party/WebKit/Source/core/css/CSSStyleSheet.h
@@ -73,12 +73,12 @@ bool disabled() const override { return is_disabled_; } void setDisabled(bool) override; - CSSRuleList* cssRules(); + CSSRuleList* cssRules(ExceptionState&); unsigned insertRule(const String& rule, unsigned index, ExceptionState&); void deleteRule(unsigned index, ExceptionState&); // IE Extensions - CSSRuleList* rules(); + CSSRuleList* rules(ExceptionState&); int addRule(const String& selector, const String& style, int index,
diff --git a/third_party/WebKit/Source/core/css/CSSStyleSheet.idl b/third_party/WebKit/Source/core/css/CSSStyleSheet.idl index 5306bd6..c966596 100644 --- a/third_party/WebKit/Source/core/css/CSSStyleSheet.idl +++ b/third_party/WebKit/Source/core/css/CSSStyleSheet.idl
@@ -22,12 +22,12 @@ interface CSSStyleSheet : StyleSheet { readonly attribute CSSRule? ownerRule; - [SameObject] readonly attribute CSSRuleList cssRules; + [SameObject, RaisesException] readonly attribute CSSRuleList cssRules; [RaisesException] unsigned long insertRule(DOMString rule, optional unsigned long index = 0); [RaisesException] void deleteRule(unsigned long index); // Non-standard APIs - [MeasureAs=CSSStyleSheetRules] readonly attribute CSSRuleList rules; + [MeasureAs=CSSStyleSheetRules, RaisesException] readonly attribute CSSRuleList rules; [MeasureAs=CSSStyleSheetAddRule, RaisesException] long addRule([Default=Undefined] optional DOMString selector, [Default=Undefined] optional DOMString style, optional unsigned long index); [MeasureAs=CSSStyleSheetRemoveRule, RaisesException] void removeRule([Default=Undefined] optional unsigned long index); };
diff --git a/third_party/WebKit/Source/core/css/CSSTestHelper.cpp b/third_party/WebKit/Source/core/css/CSSTestHelper.cpp index 7082a021..3766cfc5 100644 --- a/third_party/WebKit/Source/core/css/CSSTestHelper.cpp +++ b/third_party/WebKit/Source/core/css/CSSTestHelper.cpp
@@ -29,6 +29,7 @@ #include "core/css/CSSTestHelper.h" +#include "bindings/core/v8/ExceptionState.h" #include "core/css/CSSRuleList.h" #include "core/css/CSSStyleSheet.h" #include "core/css/RuleSet.h" @@ -49,7 +50,10 @@ } CSSRuleList* CSSTestHelper::CssRules() { - return style_sheet_->cssRules(); + DummyExceptionStateForTesting exception_state; + CSSRuleList* result = style_sheet_->cssRules(exception_state); + EXPECT_FALSE(exception_state.HadException()); + return result; } RuleSet& CSSTestHelper::GetRuleSet() { @@ -63,7 +67,7 @@ TextPosition position; unsigned sheet_length = style_sheet_->length(); style_sheet_->Contents()->ParseStringAtPosition(css_text, position); - ASSERT_TRUE(style_sheet_->length() > sheet_length); + ASSERT_GT(style_sheet_->length(), sheet_length); } } // namespace blink
diff --git a/third_party/WebKit/Source/core/css/StyleEngineTest.cpp b/third_party/WebKit/Source/core/css/StyleEngineTest.cpp index ba77fbf3..d0a02a3 100644 --- a/third_party/WebKit/Source/core/css/StyleEngineTest.cpp +++ b/third_party/WebKit/Source/core/css/StyleEngineTest.cpp
@@ -790,8 +790,11 @@ CSSStyleSheet* sheet = ToCSSStyleSheet(GetDocument().StyleSheets().item(0)); ASSERT_TRUE(sheet); - ASSERT_TRUE(sheet->cssRules()); - CSSStyleRule* style_rule = ToCSSStyleRule(sheet->cssRules()->item(0)); + DummyExceptionStateForTesting exception_state; + ASSERT_TRUE(sheet->cssRules(exception_state)); + CSSStyleRule* style_rule = + ToCSSStyleRule(sheet->cssRules(exception_state)->item(0)); + ASSERT_FALSE(exception_state.HadException()); ASSERT_TRUE(style_rule); ASSERT_TRUE(style_rule->style());
diff --git a/third_party/WebKit/Source/core/css/cssom/CSSNumericValueType.cpp b/third_party/WebKit/Source/core/css/cssom/CSSNumericValueType.cpp index d73459e..39f98d03 100644 --- a/third_party/WebKit/Source/core/css/cssom/CSSNumericValueType.cpp +++ b/third_party/WebKit/Source/core/css/cssom/CSSNumericValueType.cpp
@@ -123,8 +123,11 @@ else if (type2.HasPercentHint()) type1.ApplyPercentHint(type2.PercentHint()); - for (unsigned i = 0; i < kNumBaseTypes; ++i) - type1.exponents_[i] += type2.exponents_[i]; + for (unsigned i = 0; i < kNumBaseTypes; ++i) { + const auto base_type = static_cast<BaseType>(i); + type1.SetExponent(base_type, + type1.Exponent(base_type) + type2.Exponent(base_type)); + } error = false; return type1;
diff --git a/third_party/WebKit/Source/core/css/cssom/CSSNumericValueType.h b/third_party/WebKit/Source/core/css/cssom/CSSNumericValueType.h index 5d29688..b3959022 100644 --- a/third_party/WebKit/Source/core/css/cssom/CSSNumericValueType.h +++ b/third_party/WebKit/Source/core/css/cssom/CSSNumericValueType.h
@@ -46,19 +46,54 @@ return exponents_[static_cast<unsigned>(type)]; } - void SetExponent(BaseType type, int value) { + void SetExponent(BaseType type, int new_value) { DCHECK_LT(type, BaseType::kNumBaseTypes); - exponents_[static_cast<unsigned>(type)] = value; + int& old_value = exponents_[static_cast<unsigned>(type)]; + if (old_value == 0 && new_value != 0) + num_non_zero_entries_++; + else if (old_value != 0 && new_value == 0) + num_non_zero_entries_--; + old_value = new_value; } bool HasPercentHint() const { return has_percent_hint_; } BaseType PercentHint() const { return percent_hint_; } void ApplyPercentHint(BaseType hint); + bool MatchesBaseType(BaseType base_type) const { + DCHECK_NE(base_type, BaseType::kPercent); + return IsOnlyNonZeroEntry(base_type, 1) && !HasPercentHint(); + } + + bool MatchesPercentage() const { + return IsOnlyNonZeroEntry(BaseType::kPercent, 1); + } + + bool MatchesBaseTypePercentage(BaseType base_type) const { + DCHECK_NE(base_type, BaseType::kPercent); + return IsOnlyNonZeroEntry(base_type, 1) || + IsOnlyNonZeroEntry(BaseType::kPercent, 1); + } + + bool MatchesNumber() const { + return !HasNonZeroEntries() && !HasPercentHint(); + } + + bool MatchesNumberPercentage() const { + return !HasNonZeroEntries() || IsOnlyNonZeroEntry(BaseType::kPercent, 1); + } + private: + bool HasNonZeroEntries() const { return num_non_zero_entries_ > 0; } + bool IsOnlyNonZeroEntry(BaseType base_type, int value) const { + DCHECK_NE(value, 0); + return num_non_zero_entries_ == 1 && Exponent(base_type) == value; + } + std::array<int, kNumBaseTypes> exponents_{}; // zero-initialize BaseType percent_hint_ = BaseType::kPercent; bool has_percent_hint_ = false; + unsigned num_non_zero_entries_ = 0; }; } // namespace blink
diff --git a/third_party/WebKit/Source/core/css/cssom/CSSNumericValueTypeTest.cpp b/third_party/WebKit/Source/core/css/cssom/CSSNumericValueTypeTest.cpp index 44325fd..e1382a3 100644 --- a/third_party/WebKit/Source/core/css/cssom/CSSNumericValueTypeTest.cpp +++ b/third_party/WebKit/Source/core/css/cssom/CSSNumericValueTypeTest.cpp
@@ -202,4 +202,62 @@ EXPECT_EQ(BaseType::kAngle, result.PercentHint()); } +TEST(CSSNumericValueType, MatchesBaseTypePercentage) { + CSSNumericValueType type; + EXPECT_FALSE(type.MatchesBaseType(BaseType::kLength)); + EXPECT_FALSE(type.MatchesBaseTypePercentage(BaseType::kLength)); + + type.SetExponent(BaseType::kLength, 1); + EXPECT_TRUE(type.MatchesBaseType(BaseType::kLength)); + EXPECT_TRUE(type.MatchesBaseTypePercentage(BaseType::kLength)); + + type.SetExponent(BaseType::kLength, 2); + EXPECT_FALSE(type.MatchesBaseType(BaseType::kLength)); + EXPECT_FALSE(type.MatchesBaseTypePercentage(BaseType::kLength)); + + type.SetExponent(BaseType::kLength, 1); + EXPECT_TRUE(type.MatchesBaseType(BaseType::kLength)); + EXPECT_TRUE(type.MatchesBaseTypePercentage(BaseType::kLength)); + + type.ApplyPercentHint(BaseType::kLength); + EXPECT_FALSE(type.MatchesBaseType(BaseType::kLength)); + EXPECT_TRUE(type.MatchesBaseTypePercentage(BaseType::kLength)); +} + +TEST(CSSNumericValueType, MatchesPercentage) { + CSSNumericValueType type; + EXPECT_FALSE(type.MatchesPercentage()); + + type.SetExponent(BaseType::kPercent, 1); + EXPECT_TRUE(type.MatchesPercentage()); + + type.SetExponent(BaseType::kPercent, 2); + EXPECT_FALSE(type.MatchesPercentage()); + + type.ApplyPercentHint(BaseType::kLength); + EXPECT_FALSE(type.MatchesPercentage()); + + type.SetExponent(BaseType::kLength, 0); + type.SetExponent(BaseType::kPercent, 1); + EXPECT_TRUE(type.MatchesPercentage()); +} + +TEST(CSSNumericValueType, MatchesNumberPercentage) { + CSSNumericValueType type; + EXPECT_TRUE(type.MatchesNumber()); + EXPECT_TRUE(type.MatchesNumberPercentage()); + + type.SetExponent(BaseType::kLength, 1); + EXPECT_FALSE(type.MatchesNumber()); + EXPECT_FALSE(type.MatchesNumberPercentage()); + + type.SetExponent(BaseType::kLength, 0); + EXPECT_TRUE(type.MatchesNumber()); + EXPECT_TRUE(type.MatchesNumberPercentage()); + + type.SetExponent(BaseType::kPercent, 1); + EXPECT_FALSE(type.MatchesNumber()); + EXPECT_TRUE(type.MatchesNumberPercentage()); +} + } // namespace blink
diff --git a/third_party/WebKit/Source/core/css/cssom/CSSPositionValue.cpp b/third_party/WebKit/Source/core/css/cssom/CSSPositionValue.cpp index a52429e..6eaf7da 100644 --- a/third_party/WebKit/Source/core/css/cssom/CSSPositionValue.cpp +++ b/third_party/WebKit/Source/core/css/cssom/CSSPositionValue.cpp
@@ -10,17 +10,24 @@ namespace blink { +namespace { + +bool IsValidCoordinate(CSSNumericValue* v) { + return v->Type().MatchesBaseTypePercentage( + CSSNumericValueType::BaseType::kLength); +} + +} // namespace + CSSPositionValue* CSSPositionValue::Create(CSSNumericValue* x, CSSNumericValue* y, ExceptionState& exception_state) { - if (x->GetType() != CSSStyleValue::StyleValueType::kLengthType && - x->GetType() != CSSStyleValue::StyleValueType::kPercentType) { + if (!IsValidCoordinate(x)) { exception_state.ThrowTypeError( "Must pass length or percentage to x in CSSPositionValue"); return nullptr; } - if (y->GetType() != CSSStyleValue::StyleValueType::kLengthType && - y->GetType() != CSSStyleValue::StyleValueType::kPercentType) { + if (!IsValidCoordinate(y)) { exception_state.ThrowTypeError( "Must pass length or percentage to y in CSSPositionValue"); return nullptr; @@ -30,8 +37,7 @@ void CSSPositionValue::setX(CSSNumericValue* x, ExceptionState& exception_state) { - if (x->GetType() != CSSStyleValue::StyleValueType::kLengthType && - x->GetType() != CSSStyleValue::StyleValueType::kPercentType) { + if (!IsValidCoordinate(x)) { exception_state.ThrowTypeError( "Must pass length or percentage to x in CSSPositionValue"); return; @@ -41,8 +47,7 @@ void CSSPositionValue::setY(CSSNumericValue* y, ExceptionState& exception_state) { - if (y->GetType() != CSSStyleValue::StyleValueType::kLengthType && - y->GetType() != CSSStyleValue::StyleValueType::kPercentType) { + if (!IsValidCoordinate(y)) { exception_state.ThrowTypeError( "Must pass length or percentage to y in CSSPositionValue"); return;
diff --git a/third_party/WebKit/Source/core/css/parser/CSSVariableParser.cpp b/third_party/WebKit/Source/core/css/parser/CSSVariableParser.cpp index 345fd03..0eb3cd6 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSVariableParser.cpp +++ b/third_party/WebKit/Source/core/css/parser/CSSVariableParser.cpp
@@ -10,23 +10,11 @@ namespace blink { -bool CSSVariableParser::IsValidVariableName(const CSSParserToken& token) { - if (token.GetType() != kIdentToken) - return false; +namespace { - StringView value = token.Value(); - return value.length() >= 2 && value[0] == '-' && value[1] == '-'; -} +bool IsValidVariableReference(CSSParserTokenRange); -bool CSSVariableParser::IsValidVariableName(const String& string) { - return string.length() >= 2 && string[0] == '-' && string[1] == '-'; -} - -bool IsValidVariableReference(CSSParserTokenRange, bool& has_at_apply_rule); - -bool ClassifyBlock(CSSParserTokenRange range, - bool& has_references, - bool& has_at_apply_rule) { +bool ClassifyBlock(CSSParserTokenRange range, bool& has_references) { size_t block_stack_size = 0; while (!range.AtEnd()) { @@ -35,7 +23,7 @@ if (range.Peek().GetBlockType() == CSSParserToken::kBlockStart && range.Peek().FunctionId() == CSSValueVar) { CSSParserTokenRange block = range.ConsumeBlock(); - if (!IsValidVariableReference(block, has_at_apply_rule)) + if (!IsValidVariableReference(block)) return false; // Bail if any references are invalid has_references = true; continue; @@ -71,8 +59,7 @@ return true; } -bool IsValidVariableReference(CSSParserTokenRange range, - bool& has_at_apply_rule) { +bool IsValidVariableReference(CSSParserTokenRange range) { range.ConsumeWhitespace(); if (!CSSVariableParser::IsValidVariableName( range.ConsumeIncludingWhitespace())) @@ -86,14 +73,12 @@ return false; bool has_references = false; - return ClassifyBlock(range, has_references, has_at_apply_rule); + return ClassifyBlock(range, has_references); } -static CSSValueID ClassifyVariableRange(CSSParserTokenRange range, - bool& has_references, - bool& has_at_apply_rule) { +CSSValueID ClassifyVariableRange(CSSParserTokenRange range, + bool& has_references) { has_references = false; - has_at_apply_rule = false; range.ConsumeWhitespace(); if (range.Peek().GetType() == kIdentToken) { @@ -103,19 +88,30 @@ return id; } - if (ClassifyBlock(range, has_references, has_at_apply_rule)) + if (ClassifyBlock(range, has_references)) return CSSValueInternalVariableValue; return CSSValueInvalid; } +} // namespace + +bool CSSVariableParser::IsValidVariableName(const CSSParserToken& token) { + if (token.GetType() != kIdentToken) + return false; + + StringView value = token.Value(); + return value.length() >= 2 && value[0] == '-' && value[1] == '-'; +} + +bool CSSVariableParser::IsValidVariableName(const String& string) { + return string.length() >= 2 && string[0] == '-' && string[1] == '-'; +} + bool CSSVariableParser::ContainsValidVariableReferences( CSSParserTokenRange range) { bool has_references; - bool has_at_apply_rule; - CSSValueID type = - ClassifyVariableRange(range, has_references, has_at_apply_rule); - return type == CSSValueInternalVariableValue && has_references && - !has_at_apply_rule; + CSSValueID type = ClassifyVariableRange(range, has_references); + return type == CSSValueInternalVariableValue && has_references; } CSSCustomPropertyDeclaration* CSSVariableParser::ParseDeclarationValue( @@ -126,17 +122,14 @@ return nullptr; bool has_references; - bool has_at_apply_rule; - CSSValueID type = - ClassifyVariableRange(range, has_references, has_at_apply_rule); + CSSValueID type = ClassifyVariableRange(range, has_references); if (type == CSSValueInvalid) return nullptr; if (type == CSSValueInternalVariableValue) { return CSSCustomPropertyDeclaration::Create( variable_name, - CSSVariableData::Create(range, is_animation_tainted, - has_references || has_at_apply_rule)); + CSSVariableData::Create(range, is_animation_tainted, has_references)); } return CSSCustomPropertyDeclaration::Create(variable_name, type); } @@ -150,15 +143,12 @@ return nullptr; bool has_references; - bool has_at_apply_rule; - CSSValueID type = - ClassifyVariableRange(range, has_references, has_at_apply_rule); + CSSValueID type = ClassifyVariableRange(range, has_references); if (type != CSSValueInternalVariableValue) return nullptr; // Invalid or a css-wide keyword if (require_var_reference && !has_references) return nullptr; - // TODO(timloh): Should this be hasReferences || hasAtApplyRule? return CSSVariableReferenceValue::Create( CSSVariableData::Create(range, is_animation_tainted, has_references), context);
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyBackgroundUtils.cpp b/third_party/WebKit/Source/core/css/properties/CSSPropertyBackgroundUtils.cpp index a0611e3..d3156b2b 100644 --- a/third_party/WebKit/Source/core/css/properties/CSSPropertyBackgroundUtils.cpp +++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyBackgroundUtils.cpp
@@ -128,7 +128,7 @@ if (CSSValue* value = CSSPropertyParserHelpers::ConsumeIdentRange( range, CSSValueBorder, CSSValuePaddingBox)) return value; - if (allow_text_value == AllowTextValue::kAllowed && + if (allow_text_value == AllowTextValue::kAllow && range.Peek().Id() == CSSValueText) return CSSPropertyParserHelpers::ConsumeIdent(range); return nullptr;
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyBackgroundUtils.h b/third_party/WebKit/Source/core/css/properties/CSSPropertyBackgroundUtils.h index 0dcae91..6ae3788 100644 --- a/third_party/WebKit/Source/core/css/properties/CSSPropertyBackgroundUtils.h +++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyBackgroundUtils.h
@@ -15,7 +15,7 @@ class CSSValue; enum class ParsingStyle { kLegacy, kNotLegacy }; -enum class AllowTextValue { kAllowed, kNotAllowed }; +enum class AllowTextValue { kAllow, kForbid }; class CSSPropertyBackgroundUtils { STATIC_ONLY(CSSPropertyBackgroundUtils);
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyCounterUtils.h b/third_party/WebKit/Source/core/css/properties/CSSPropertyCounterUtils.h index 9add2206..efc0eb2 100644 --- a/third_party/WebKit/Source/core/css/properties/CSSPropertyCounterUtils.h +++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyCounterUtils.h
@@ -16,10 +16,7 @@ STATIC_ONLY(CSSPropertyCounterUtils); public: - static const int kResetDefaultValue = 0; - static const int kIncrementDefaultValue = 1; - - static CSSValue* ConsumeCounter(CSSParserTokenRange&, int); + static CSSValue* ConsumeCounter(CSSParserTokenRange&, int default_value); }; } // namespace blink
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyGridUtils.cpp b/third_party/WebKit/Source/core/css/properties/CSSPropertyGridUtils.cpp index 2fa6359..b54aaff 100644 --- a/third_party/WebKit/Source/core/css/properties/CSSPropertyGridUtils.cpp +++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyGridUtils.cpp
@@ -298,7 +298,8 @@ if (!CSSPropertyParserHelpers::ConsumeSlashIncludingWhitespace(range)) return false; template_columns = CSSPropertyGridUtils::ConsumeGridTrackList( - range, context.Mode(), CSSPropertyGridUtils::kGridTemplateNoRepeat); + range, context.Mode(), + CSSPropertyGridUtils::TrackListType::kGridTemplateNoRepeat); if (!template_columns || !range.AtEnd()) return false; } else { @@ -374,7 +375,7 @@ CSSParserTokenRange& range, CSSParserMode css_parser_mode, TrackListType track_list_type) { - bool allow_grid_line_names = track_list_type != kGridAuto; + bool allow_grid_line_names = track_list_type != TrackListType::kGridAuto; CSSValueList* values = CSSValueList::CreateSpaceSeparated(); CSSGridLineNamesValue* line_names = ConsumeGridLineNames(range); if (line_names) { @@ -383,7 +384,7 @@ values->Append(*line_names); } - bool allow_repeat = track_list_type == kGridTemplate; + bool allow_repeat = track_list_type == TrackListType::kGridTemplate; bool seen_auto_repeat = false; bool all_tracks_are_fixed_sized = true; do { @@ -491,7 +492,8 @@ CSSParserMode css_parser_mode) { if (range.Peek().Id() == CSSValueNone) return CSSPropertyParserHelpers::ConsumeIdent(range); - return ConsumeGridTrackList(range, css_parser_mode, kGridTemplate); + return ConsumeGridTrackList(range, css_parser_mode, + TrackListType::kGridTemplate); } bool CSSPropertyGridUtils::ConsumeGridItemPositionShorthand( @@ -545,8 +547,10 @@ } // 2- <grid-template-rows> / <grid-template-columns> - if (!template_rows) - template_rows = ConsumeGridTrackList(range, context.Mode(), kGridTemplate); + if (!template_rows) { + template_rows = ConsumeGridTrackList(range, context.Mode(), + TrackListType::kGridTemplate); + } if (template_rows) { if (!CSSPropertyParserHelpers::ConsumeSlashIncludingWhitespace(range))
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyGridUtils.h b/third_party/WebKit/Source/core/css/properties/CSSPropertyGridUtils.h index 530a54d..24c7fa5 100644 --- a/third_party/WebKit/Source/core/css/properties/CSSPropertyGridUtils.h +++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyGridUtils.h
@@ -23,7 +23,7 @@ // all grid-related shorthands have their property classes implemented: // - TrackListType // - ConsumeGridLine - enum TrackListType { kGridTemplate, kGridTemplateNoRepeat, kGridAuto }; + enum class TrackListType { kGridTemplate, kGridTemplateNoRepeat, kGridAuto }; static CSSValue* ConsumeGridLine(CSSParserTokenRange&); static CSSValue* ConsumeGridTrackList(CSSParserTokenRange&, CSSParserMode,
diff --git a/third_party/WebKit/Source/core/css/properties/README.md b/third_party/WebKit/Source/core/css/properties/README.md index bbc40af..4df12c6c 100644 --- a/third_party/WebKit/Source/core/css/properties/README.md +++ b/third_party/WebKit/Source/core/css/properties/README.md
@@ -52,11 +52,11 @@ they are the same thing. Fixing this possible source of confusion is an open issue crbug.com/752745. -### Variable & ApplyAtRule +### Variable -Variable and the Apply at-rule are not true CSS properties, but they are treated -as such in places for convience. They do not appear in CSSProperties.json5; thus -their property class headers needed to be hand-written & manually added to the +The Variable rule is not a true CSS property, but is treated +as such in places for convience. It does not appear in CSSProperties.json5; thus +its property class header needed to be hand-written & manually added to the list of property classes by make_css_property_base.py. Those hand-written headers are in this directory.
diff --git a/third_party/WebKit/Source/core/css/properties/longhands/BackgroundBox.cpp b/third_party/WebKit/Source/core/css/properties/longhands/BackgroundBox.cpp index 90175fc4..5948388a 100644 --- a/third_party/WebKit/Source/core/css/properties/longhands/BackgroundBox.cpp +++ b/third_party/WebKit/Source/core/css/properties/longhands/BackgroundBox.cpp
@@ -19,7 +19,7 @@ if (local_context.UseAliasParsing()) { return CSSPropertyParserHelpers::ConsumeCommaSeparatedList( CSSPropertyBackgroundUtils::ConsumePrefixedBackgroundBox, range, - AllowTextValue::kAllowed); + AllowTextValue::kAllow); } return CSSPropertyParserHelpers::ConsumeCommaSeparatedList( CSSPropertyBackgroundUtils::ConsumeBackgroundBox, range);
diff --git a/third_party/WebKit/Source/core/css/properties/longhands/CounterIncrement.cpp b/third_party/WebKit/Source/core/css/properties/longhands/CounterIncrement.cpp index ddf11c1..f5ba1870 100644 --- a/third_party/WebKit/Source/core/css/properties/longhands/CounterIncrement.cpp +++ b/third_party/WebKit/Source/core/css/properties/longhands/CounterIncrement.cpp
@@ -9,12 +9,14 @@ namespace blink { namespace CSSLonghand { +const int kCounterIncrementDefaultValue = 1; + const CSSValue* CounterIncrement::ParseSingleValue( CSSParserTokenRange& range, const CSSParserContext&, const CSSParserLocalContext&) const { - return CSSPropertyCounterUtils::ConsumeCounter( - range, CSSPropertyCounterUtils::kIncrementDefaultValue); + return CSSPropertyCounterUtils::ConsumeCounter(range, + kCounterIncrementDefaultValue); } } // namespace CSSLonghand
diff --git a/third_party/WebKit/Source/core/css/properties/longhands/CounterReset.cpp b/third_party/WebKit/Source/core/css/properties/longhands/CounterReset.cpp index 6c124b1e..6540a46 100644 --- a/third_party/WebKit/Source/core/css/properties/longhands/CounterReset.cpp +++ b/third_party/WebKit/Source/core/css/properties/longhands/CounterReset.cpp
@@ -9,12 +9,14 @@ namespace blink { namespace CSSLonghand { +const int kCounterResetDefaultValue = 0; + const CSSValue* CounterReset::ParseSingleValue( CSSParserTokenRange& range, const CSSParserContext&, const CSSParserLocalContext&) const { - return CSSPropertyCounterUtils::ConsumeCounter( - range, CSSPropertyCounterUtils::kResetDefaultValue); + return CSSPropertyCounterUtils::ConsumeCounter(range, + kCounterResetDefaultValue); } } // namespace CSSLonghand
diff --git a/third_party/WebKit/Source/core/css/properties/longhands/GridAutoLine.cpp b/third_party/WebKit/Source/core/css/properties/longhands/GridAutoLine.cpp index 979237e..cb3e65a2 100644 --- a/third_party/WebKit/Source/core/css/properties/longhands/GridAutoLine.cpp +++ b/third_party/WebKit/Source/core/css/properties/longhands/GridAutoLine.cpp
@@ -15,7 +15,7 @@ const CSSParserContext& context, const CSSParserLocalContext&) const { return CSSPropertyGridUtils::ConsumeGridTrackList( - range, context.Mode(), CSSPropertyGridUtils::kGridAuto); + range, context.Mode(), CSSPropertyGridUtils::TrackListType::kGridAuto); } } // namespace CSSLonghand
diff --git a/third_party/WebKit/Source/core/css/properties/longhands/Variable.h b/third_party/WebKit/Source/core/css/properties/longhands/Variable.h index 13ce35c..8fc6c900 100644 --- a/third_party/WebKit/Source/core/css/properties/longhands/Variable.h +++ b/third_party/WebKit/Source/core/css/properties/longhands/Variable.h
@@ -3,11 +3,9 @@ // found in the LICENSE file. // This header is hand-written, whereas most CSSProperty subclass -// headers are generated by -// core/css/properties/templates/Subclass.h.tmpl. -// CSSPropertyApplyAtRule and CSSPropertyVariable are treated as -// CSS properties in some places for convenience but are not really -// CSS properties. +// headers are generated by core/css/properties/templates/Subclass.h.tmpl. +// CSSPropertyVariable is treated as a CSS properties in some places for +// convenience but is not really a CSS property. #ifndef Variable_h #define Variable_h
diff --git a/third_party/WebKit/Source/core/css/properties/longhands/WebkitMaskClip.cpp b/third_party/WebKit/Source/core/css/properties/longhands/WebkitMaskClip.cpp index aafee54c..901e7bc8 100644 --- a/third_party/WebKit/Source/core/css/properties/longhands/WebkitMaskClip.cpp +++ b/third_party/WebKit/Source/core/css/properties/longhands/WebkitMaskClip.cpp
@@ -17,7 +17,7 @@ const CSSParserLocalContext&) const { return CSSPropertyParserHelpers::ConsumeCommaSeparatedList( CSSPropertyBackgroundUtils::ConsumePrefixedBackgroundBox, range, - AllowTextValue::kAllowed); + AllowTextValue::kAllow); } } // namespace CSSLonghand
diff --git a/third_party/WebKit/Source/core/css/properties/longhands/WebkitMaskOrigin.cpp b/third_party/WebKit/Source/core/css/properties/longhands/WebkitMaskOrigin.cpp index f694424..d45c806 100644 --- a/third_party/WebKit/Source/core/css/properties/longhands/WebkitMaskOrigin.cpp +++ b/third_party/WebKit/Source/core/css/properties/longhands/WebkitMaskOrigin.cpp
@@ -17,7 +17,7 @@ const CSSParserLocalContext&) const { return CSSPropertyParserHelpers::ConsumeCommaSeparatedList( CSSPropertyBackgroundUtils::ConsumePrefixedBackgroundBox, range, - AllowTextValue::kNotAllowed); + AllowTextValue::kForbid); } } // namespace CSSLonghand
diff --git a/third_party/WebKit/Source/core/css/properties/shorthands/Background.cpp b/third_party/WebKit/Source/core/css/properties/shorthands/Background.cpp index 0721184f..59bc6ee 100644 --- a/third_party/WebKit/Source/core/css/properties/shorthands/Background.cpp +++ b/third_party/WebKit/Source/core/css/properties/shorthands/Background.cpp
@@ -47,10 +47,10 @@ return CSSPropertyParserHelpers::ConsumeColor(range, context.Mode()); case CSSPropertyWebkitMaskClip: return CSSPropertyBackgroundUtils::ConsumePrefixedBackgroundBox( - range, AllowTextValue::kAllowed); + range, AllowTextValue::kAllow); case CSSPropertyWebkitMaskOrigin: return CSSPropertyBackgroundUtils::ConsumePrefixedBackgroundBox( - range, AllowTextValue::kNotAllowed); + range, AllowTextValue::kForbid); default: break; };
diff --git a/third_party/WebKit/Source/core/css/properties/shorthands/Grid.cpp b/third_party/WebKit/Source/core/css/properties/shorthands/Grid.cpp index e842cb6..68e9111 100644 --- a/third_party/WebKit/Source/core/css/properties/shorthands/Grid.cpp +++ b/third_party/WebKit/Source/core/css/properties/shorthands/Grid.cpp
@@ -108,7 +108,8 @@ auto_rows_value = CSSInitialValue::Create(); } else { auto_rows_value = CSSPropertyGridUtils::ConsumeGridTrackList( - range, context.Mode(), CSSPropertyGridUtils::kGridAuto); + range, context.Mode(), + CSSPropertyGridUtils::TrackListType::kGridAuto); if (!auto_rows_value) return false; if (!CSSPropertyParserHelpers::ConsumeSlashIncludingWhitespace(range)) @@ -136,7 +137,8 @@ auto_columns_value = CSSInitialValue::Create(); } else { auto_columns_value = CSSPropertyGridUtils::ConsumeGridTrackList( - range, context.Mode(), CSSPropertyGridUtils::kGridAuto); + range, context.Mode(), + CSSPropertyGridUtils::TrackListType::kGridAuto); if (!auto_columns_value) return false; }
diff --git a/third_party/WebKit/Source/core/css/resolver/StyleResolverState.cpp b/third_party/WebKit/Source/core/css/resolver/StyleResolverState.cpp index ee9cdfe..f3a9608 100644 --- a/third_party/WebKit/Source/core/css/resolver/StyleResolverState.cpp +++ b/third_party/WebKit/Source/core/css/resolver/StyleResolverState.cpp
@@ -154,17 +154,6 @@ } } -void StyleResolverState::SetCustomPropertySetForApplyAtRule( - const String& string, - CSSPropertyValueSet* custom_property_set) { - custom_property_sets_for_apply_at_rule_.Set(string, custom_property_set); -} - -CSSPropertyValueSet* StyleResolverState::CustomPropertySetForApplyAtRule( - const String& string) { - return custom_property_sets_for_apply_at_rule_.at(string); -} - HeapHashMap<CSSPropertyID, Member<const CSSValue>>& StyleResolverState::ParsedPropertiesForPendingSubstitutionCache( const CSSPendingSubstitutionValue& value) const {
diff --git a/third_party/WebKit/Source/core/css/resolver/StyleResolverState.h b/third_party/WebKit/Source/core/css/resolver/StyleResolverState.h index ee5a64d1..3855f95 100644 --- a/third_party/WebKit/Source/core/css/resolver/StyleResolverState.h +++ b/third_party/WebKit/Source/core/css/resolver/StyleResolverState.h
@@ -191,9 +191,6 @@ void SetHasDirAutoAttribute(bool value) { has_dir_auto_attribute_ = value; } bool HasDirAutoAttribute() const { return has_dir_auto_attribute_; } - void SetCustomPropertySetForApplyAtRule(const String&, CSSPropertyValueSet*); - CSSPropertyValueSet* CustomPropertySetForApplyAtRule(const String&); - HeapHashMap<CSSPropertyID, Member<const CSSValue>>& ParsedPropertiesForPendingSubstitutionCache( const CSSPendingSubstitutionValue&) const; @@ -230,9 +227,6 @@ ElementStyleResources element_style_resources_; - HeapHashMap<String, Member<CSSPropertyValueSet>> - custom_property_sets_for_apply_at_rule_; - mutable HeapHashMap< Member<const CSSPendingSubstitutionValue>, Member<HeapHashMap<CSSPropertyID, Member<const CSSValue>>>>
diff --git a/third_party/WebKit/Source/core/dom/Document.idl b/third_party/WebKit/Source/core/dom/Document.idl index 8aa0688..6005bd5 100644 --- a/third_party/WebKit/Source/core/dom/Document.idl +++ b/third_party/WebKit/Source/core/dom/Document.idl
@@ -119,7 +119,7 @@ // dynamic markup insertion [CallWith=EnteredWindow, CEReactions, CustomElementCallbacks, RaisesException, MeasureAs=DocumentOpen] Document open(optional DOMString type = "text/html", optional DOMString replace = ""); - [CallWith=(CurrentWindow,EnteredWindow), RaisesException, MeasureAs=DocumentOpen] Window open(DOMString url, DOMString name, DOMString features); + [CallWith=(CurrentWindow,EnteredWindow), RaisesException, MeasureAs=DocumentOpen] Window open(USVString url, DOMString name, DOMString features); [CEReactions, RaisesException] void close(); [CallWith=EnteredWindow, CEReactions, CustomElementCallbacks, RaisesException] void write(DOMString... text); [CallWith=EnteredWindow, CEReactions, CustomElementCallbacks, RaisesException] void writeln(DOMString... text);
diff --git a/third_party/WebKit/Source/core/dom/ElementVisibilityObserverTest.cpp b/third_party/WebKit/Source/core/dom/ElementVisibilityObserverTest.cpp index 8fe93a6..09ae8bad 100644 --- a/third_party/WebKit/Source/core/dom/ElementVisibilityObserverTest.cpp +++ b/third_party/WebKit/Source/core/dom/ElementVisibilityObserverTest.cpp
@@ -10,7 +10,7 @@ #include "core/html/HTMLDivElement.h" #include "core/html/HTMLDocument.h" #include "core/loader/EmptyClients.h" -#include "core/testing/DummyPageHolder.h" +#include "core/testing/PageTestBase.h" #include "testing/gtest/include/gtest/gtest.h" namespace blink { @@ -37,26 +37,20 @@ WeakMember<Frame> parent_ = nullptr; }; -class ElementVisibilityObserverTest : public ::testing::Test { +class ElementVisibilityObserverTest : public PageTestBase { protected: void SetUp() override { local_frame_client_ = new DOMStubLocalFrameClient(); - dummy_page_holder_ = DummyPageHolder::Create(IntSize(), nullptr, - local_frame_client_, nullptr); + SetupPageWithClients(nullptr, local_frame_client_, nullptr); } - void TearDown() override { - dummy_page_holder_->GetFrame().Detach(FrameDetachType::kRemove); - } + void TearDown() override { GetFrame().Detach(FrameDetachType::kRemove); } - Document& GetDocument() { return dummy_page_holder_->GetDocument(); } - Page& GetPage() { return dummy_page_holder_->GetPage(); } DOMStubLocalFrameClient* LocalFrameClient() const { return local_frame_client_; } private: - std::unique_ptr<DummyPageHolder> dummy_page_holder_; Persistent<DOMStubLocalFrameClient> local_frame_client_; };
diff --git a/third_party/WebKit/Source/core/dom/MessagePort.cpp b/third_party/WebKit/Source/core/dom/MessagePort.cpp index b49aafb74..5cf42dcc 100644 --- a/third_party/WebKit/Source/core/dom/MessagePort.cpp +++ b/third_party/WebKit/Source/core/dom/MessagePort.cpp
@@ -127,7 +127,7 @@ channel_.SetCallback( ConvertToBaseCallback(CrossThreadBind( &MessagePort::MessageAvailable, WrapCrossThreadWeakPersistent(this))), - task_runner_->ToSingleThreadTaskRunner()); + task_runner_); started_ = true; MessageAvailable(); }
diff --git a/third_party/WebKit/Source/core/dom/events/EventPathTest.cpp b/third_party/WebKit/Source/core/dom/events/EventPathTest.cpp index 529fbf6..0ebccf6b 100644 --- a/third_party/WebKit/Source/core/dom/events/EventPathTest.cpp +++ b/third_party/WebKit/Source/core/dom/events/EventPathTest.cpp
@@ -9,24 +9,12 @@ #include "core/dom/PseudoElement.h" #include "core/html_names.h" #include "core/style/ComputedStyleConstants.h" -#include "core/testing/DummyPageHolder.h" +#include "core/testing/PageTestBase.h" #include "testing/gtest/include/gtest/gtest.h" namespace blink { -class EventPathTest : public ::testing::Test { - protected: - Document& GetDocument() const { return dummy_page_holder_->GetDocument(); } - - private: - void SetUp() override; - - std::unique_ptr<DummyPageHolder> dummy_page_holder_; -}; - -void EventPathTest::SetUp() { - dummy_page_holder_ = DummyPageHolder::Create(IntSize(800, 600)); -} +class EventPathTest : public PageTestBase {}; TEST_F(EventPathTest, ShouldBeEmptyForPseudoElementWithoutParentElement) { Element* div =
diff --git a/third_party/WebKit/Source/core/editing/InlineBoxPosition.cpp b/third_party/WebKit/Source/core/editing/InlineBoxPosition.cpp index 192df34..4a6dac5 100644 --- a/third_party/WebKit/Source/core/editing/InlineBoxPosition.cpp +++ b/third_party/WebKit/Source/core/editing/InlineBoxPosition.cpp
@@ -298,8 +298,10 @@ const PositionTemplate<Strategy>& downstream_equivalent = DownstreamIgnoringEditingBoundaries(position); if (downstream_equivalent != position) { - return ComputeInlineBoxPosition(downstream_equivalent, - TextAffinity::kUpstream, primary_direction); + return ComputeInlineBoxPosition( + PositionWithAffinityTemplate<Strategy>(downstream_equivalent, + TextAffinity::kUpstream), + primary_direction); } const PositionTemplate<Strategy>& upstream_equivalent = UpstreamIgnoringEditingBoundaries(position); @@ -307,16 +309,17 @@ DownstreamIgnoringEditingBoundaries(upstream_equivalent) == position) return InlineBoxPosition(); - return ComputeInlineBoxPosition(upstream_equivalent, TextAffinity::kUpstream, - primary_direction); + return ComputeInlineBoxPosition( + PositionWithAffinityTemplate<Strategy>(upstream_equivalent, + TextAffinity::kUpstream), + primary_direction); } template <typename Strategy> InlineBoxPosition ComputeInlineBoxPositionTemplate( - const PositionTemplate<Strategy>& position, - TextAffinity affinity, + const PositionWithAffinityTemplate<Strategy>& position, TextDirection primary_direction) { - int caret_offset = position.ComputeEditingOffset(); + int caret_offset = position.GetPosition().ComputeEditingOffset(); Node* const anchor_node = position.AnchorNode(); LayoutObject* layout_object = anchor_node->IsShadowRoot() @@ -327,7 +330,8 @@ if (layout_object->IsText()) { return ComputeInlineBoxPositionForTextNode( - ToLayoutText(layout_object), caret_offset, affinity, primary_direction); + ToLayoutText(layout_object), caret_offset, position.Affinity(), + primary_direction); } if (layout_object->IsAtomicInlineLevel()) { @@ -339,48 +343,45 @@ !CanHaveChildrenForEditing(anchor_node) || !HasRenderedNonAnonymousDescendantsWithHeight(layout_object)) return InlineBoxPosition(); - return ComputeInlineBoxPositionForBlockFlow(position, primary_direction); + return ComputeInlineBoxPositionForBlockFlow(position.GetPosition(), + primary_direction); } template <typename Strategy> InlineBoxPosition ComputeInlineBoxPositionTemplate( - const PositionTemplate<Strategy>& position, - TextAffinity affinity) { + const PositionWithAffinityTemplate<Strategy>& position) { return ComputeInlineBoxPositionTemplate<Strategy>( - position, affinity, PrimaryDirectionOf(*position.AnchorNode())); + position, PrimaryDirectionOf(*position.AnchorNode())); } } // namespace -InlineBoxPosition ComputeInlineBoxPosition(const Position& position, - TextAffinity affinity) { - return ComputeInlineBoxPositionTemplate<EditingStrategy>(position, affinity); +InlineBoxPosition ComputeInlineBoxPosition( + const PositionWithAffinity& position) { + return ComputeInlineBoxPositionTemplate<EditingStrategy>(position); } -InlineBoxPosition ComputeInlineBoxPosition(const PositionInFlatTree& position, - TextAffinity affinity) { - return ComputeInlineBoxPositionTemplate<EditingInFlatTreeStrategy>(position, - affinity); +InlineBoxPosition ComputeInlineBoxPosition( + const PositionInFlatTreeWithAffinity& position) { + return ComputeInlineBoxPositionTemplate<EditingInFlatTreeStrategy>(position); } InlineBoxPosition ComputeInlineBoxPosition(const VisiblePosition& position) { DCHECK(position.IsValid()) << position; - return ComputeInlineBoxPosition(position.DeepEquivalent(), - position.Affinity()); + return ComputeInlineBoxPosition(position.ToPositionWithAffinity()); } -InlineBoxPosition ComputeInlineBoxPosition(const Position& position, - TextAffinity affinity, +InlineBoxPosition ComputeInlineBoxPosition(const PositionWithAffinity& position, TextDirection primary_direction) { - return ComputeInlineBoxPositionTemplate<EditingStrategy>(position, affinity, + return ComputeInlineBoxPositionTemplate<EditingStrategy>(position, primary_direction); } -InlineBoxPosition ComputeInlineBoxPosition(const PositionInFlatTree& position, - TextAffinity affinity, - TextDirection primary_direction) { +InlineBoxPosition ComputeInlineBoxPosition( + const PositionInFlatTreeWithAffinity& position, + TextDirection primary_direction) { return ComputeInlineBoxPositionTemplate<EditingInFlatTreeStrategy>( - position, affinity, primary_direction); + position, primary_direction); } } // namespace blink
diff --git a/third_party/WebKit/Source/core/editing/InlineBoxPosition.h b/third_party/WebKit/Source/core/editing/InlineBoxPosition.h index 66ef8b5..d0fe919 100644 --- a/third_party/WebKit/Source/core/editing/InlineBoxPosition.h +++ b/third_party/WebKit/Source/core/editing/InlineBoxPosition.h
@@ -61,17 +61,15 @@ } }; -CORE_EXPORT InlineBoxPosition ComputeInlineBoxPosition(const Position&, - TextAffinity); CORE_EXPORT InlineBoxPosition -ComputeInlineBoxPosition(const Position&, - TextAffinity, +ComputeInlineBoxPosition(const PositionWithAffinity&); +CORE_EXPORT InlineBoxPosition +ComputeInlineBoxPosition(const PositionWithAffinity&, TextDirection primary_direction); CORE_EXPORT InlineBoxPosition -ComputeInlineBoxPosition(const PositionInFlatTree&, TextAffinity); +ComputeInlineBoxPosition(const PositionInFlatTreeWithAffinity&); CORE_EXPORT InlineBoxPosition -ComputeInlineBoxPosition(const PositionInFlatTree&, - TextAffinity, +ComputeInlineBoxPosition(const PositionInFlatTreeWithAffinity&, TextDirection primary_direction); CORE_EXPORT InlineBoxPosition ComputeInlineBoxPosition(const VisiblePosition&);
diff --git a/third_party/WebKit/Source/core/editing/InlineBoxPositionTest.cpp b/third_party/WebKit/Source/core/editing/InlineBoxPositionTest.cpp index 0ed619dc..cb1923e 100644 --- a/third_party/WebKit/Source/core/editing/InlineBoxPositionTest.cpp +++ b/third_party/WebKit/Source/core/editing/InlineBoxPositionTest.cpp
@@ -29,8 +29,8 @@ Element* sample = GetDocument().getElementById("sample"); Node* text = sample->firstChild(); - const InlineBoxPosition& actual = - ComputeInlineBoxPosition(Position(text, 0), TextAffinity::kDownstream); + const InlineBoxPosition& actual = ComputeInlineBoxPosition( + PositionWithAffinity(Position(text, 0), TextAffinity::kDownstream)); EXPECT_EQ(ToLayoutText(text->GetLayoutObject())->FirstTextBox(), actual.inline_box); } @@ -41,8 +41,9 @@ "<div contenteditable id=sample>abc<input contenteditable=false></div>"); Element* const sample = GetDocument().getElementById("sample"); - const InlineBoxPosition& actual = ComputeInlineBoxPosition( - Position::LastPositionInNode(*sample), TextAffinity::kDownstream); + const InlineBoxPosition& actual = + ComputeInlineBoxPosition(PositionWithAffinity( + Position::LastPositionInNode(*sample), TextAffinity::kDownstream)); // Should not be in infinite-loop EXPECT_EQ(nullptr, actual.inline_box); EXPECT_EQ(0, actual.offset_in_box);
diff --git a/third_party/WebKit/Source/core/editing/LayoutSelection.cpp b/third_party/WebKit/Source/core/editing/LayoutSelection.cpp index a88d51dc..9aaf07f 100644 --- a/third_party/WebKit/Source/core/editing/LayoutSelection.cpp +++ b/third_party/WebKit/Source/core/editing/LayoutSelection.cpp
@@ -190,6 +190,28 @@ } LOG(INFO) << stream.str(); } + +void PrintSelectionPaintRange(const SelectionPaintRange& paint_range) { + std::stringstream stream; + stream << std::endl << "layout_objects:" << std::endl; + for (LayoutObject* layout_object : paint_range) { + PrintLayoutObjectForSelection(stream, layout_object); + stream << std::endl; + } + LOG(INFO) << stream.str(); +} + +void PrintSelectionStateInLayoutView(const FrameSelection& selection) { + std::stringstream stream; + stream << std::endl << "layout_objects:" << std::endl; + LayoutView* layout_view = selection.GetDocument().GetLayoutView(); + for (LayoutObject* layout_object = layout_view; layout_object; + layout_object = layout_object->NextInPreOrder()) { + PrintLayoutObjectForSelection(stream, layout_object); + stream << std::endl; + } + LOG(INFO) << stream.str(); +} #endif static SelectedLayoutObjects CollectInvalidationSet( @@ -724,10 +746,12 @@ // Create a single bounding box rect that encloses the whole selection. LayoutRect selected_rect; - const SelectedLayoutObjects& current_map = - CollectInvalidationSet(paint_range_); - for (auto layout_object : current_map) + for (LayoutObject* layout_object : paint_range_) { + const SelectionState state = layout_object->GetSelectionState(); + if (state == SelectionState::kContain || state == SelectionState::kNone) + continue; selected_rect.Unite(SelectionRectForLayoutObject(layout_object)); + } return PixelSnappedIntRect(selected_rect); }
diff --git a/third_party/WebKit/Source/core/editing/RenderedPosition.cpp b/third_party/WebKit/Source/core/editing/RenderedPosition.cpp index cf268f2..50e65f0 100644 --- a/third_party/WebKit/Source/core/editing/RenderedPosition.cpp +++ b/third_party/WebKit/Source/core/editing/RenderedPosition.cpp
@@ -76,12 +76,15 @@ RenderedPosition::RenderedPosition(const VisiblePositionInFlatTree& position) : RenderedPosition(position.DeepEquivalent(), position.Affinity()) {} +// TODO(editing-dev): Stop duplicating code in the two constructors + RenderedPosition::RenderedPosition(const Position& position, TextAffinity affinity) : layout_object_(nullptr), inline_box_(nullptr), offset_(0) { if (position.IsNull()) return; - InlineBoxPosition box_position = ComputeInlineBoxPosition(position, affinity); + InlineBoxPosition box_position = + ComputeInlineBoxPosition(PositionWithAffinity(position, affinity)); inline_box_ = box_position.inline_box; offset_ = box_position.offset_in_box; if (inline_box_) @@ -96,7 +99,8 @@ : layout_object_(nullptr), inline_box_(nullptr), offset_(0) { if (position.IsNull()) return; - InlineBoxPosition box_position = ComputeInlineBoxPosition(position, affinity); + InlineBoxPosition box_position = ComputeInlineBoxPosition( + PositionInFlatTreeWithAffinity(position, affinity)); inline_box_ = box_position.inline_box; offset_ = box_position.offset_in_box; if (inline_box_)
diff --git a/third_party/WebKit/Source/core/editing/SelectionModifierCharacter.cpp b/third_party/WebKit/Source/core/editing/SelectionModifierCharacter.cpp index 5f6a337..898ea49 100644 --- a/third_party/WebKit/Source/core/editing/SelectionModifierCharacter.cpp +++ b/third_party/WebKit/Source/core/editing/SelectionModifierCharacter.cpp
@@ -248,8 +248,8 @@ const TextAffinity affinity = visible_position.Affinity(); while (true) { - InlineBoxPosition box_position = - ComputeInlineBoxPosition(p, affinity, primary_direction); + InlineBoxPosition box_position = ComputeInlineBoxPosition( + PositionWithAffinityTemplate<Strategy>(p, affinity), primary_direction); InlineBox* box = box_position.inline_box; int offset = box_position.offset_in_box; if (!box) { @@ -296,7 +296,8 @@ return PositionTemplate<Strategy>(); InlineBox* box_on_left = - ComputeInlineBoxPosition(position_on_left, affinity, + ComputeInlineBoxPosition(PositionWithAffinityTemplate<Strategy>( + position_on_left, affinity), primary_direction) .inline_box; if (box_on_left && box_on_left->Root() == box->Root())
diff --git a/third_party/WebKit/Source/core/editing/SelectionModifierWord.cpp b/third_party/WebKit/Source/core/editing/SelectionModifierWord.cpp index e7caa80f..941b8e1e 100644 --- a/third_party/WebKit/Source/core/editing/SelectionModifierWord.cpp +++ b/third_party/WebKit/Source/core/editing/SelectionModifierWord.cpp
@@ -324,7 +324,8 @@ return VisiblePosition(); InlineBoxPosition box_position = ComputeInlineBoxPosition( - adjacent_character_position.DeepEquivalent(), TextAffinity::kUpstream); + PositionWithAffinity(adjacent_character_position.DeepEquivalent(), + TextAffinity::kUpstream)); InlineBox* box = box_position.inline_box; int offset_in_box = box_position.offset_in_box;
diff --git a/third_party/WebKit/Source/core/editing/VisibleUnits.cpp b/third_party/WebKit/Source/core/editing/VisibleUnits.cpp index fd18869..7f1a486 100644 --- a/third_party/WebKit/Source/core/editing/VisibleUnits.cpp +++ b/third_party/WebKit/Source/core/editing/VisibleUnits.cpp
@@ -695,8 +695,7 @@ if (!layout_object) return LocalCaretRect(); - const InlineBoxPosition& box_position = - ComputeInlineBoxPosition(position.GetPosition(), position.Affinity()); + const InlineBoxPosition& box_position = ComputeInlineBoxPosition(position); if (box_position.inline_box) { return ComputeLocalCaretRect( @@ -722,8 +721,7 @@ if (!node->GetLayoutObject()) return LocalCaretRect(); - const InlineBoxPosition& box_position = - ComputeInlineBoxPosition(position.GetPosition(), position.Affinity()); + const InlineBoxPosition& box_position = ComputeInlineBoxPosition(position); if (!box_position.inline_box) return LocalCaretRect();
diff --git a/third_party/WebKit/Source/core/editing/VisibleUnits.h b/third_party/WebKit/Source/core/editing/VisibleUnits.h index 80f04b4..428555b6 100644 --- a/third_party/WebKit/Source/core/editing/VisibleUnits.h +++ b/third_party/WebKit/Source/core/editing/VisibleUnits.h
@@ -308,7 +308,8 @@ BoundarySearchContextAvailability, bool& need_more_context); -Position NextBoundary(const VisiblePosition&, BoundarySearchFunction); +CORE_EXPORT Position NextBoundary(const VisiblePosition&, + BoundarySearchFunction); PositionInFlatTree NextBoundary(const VisiblePositionInFlatTree&, BoundarySearchFunction); Position PreviousBoundary(const VisiblePosition&, BoundarySearchFunction);
diff --git a/third_party/WebKit/Source/core/editing/VisibleUnitsTest.cpp b/third_party/WebKit/Source/core/editing/VisibleUnitsTest.cpp index c6f0be21..5a365a4 100644 --- a/third_party/WebKit/Source/core/editing/VisibleUnitsTest.cpp +++ b/third_party/WebKit/Source/core/editing/VisibleUnitsTest.cpp
@@ -1815,4 +1815,22 @@ two->lastChild(), visible_position, kContentIsEditable)); } +static unsigned MockBoundarySearch(const UChar*, + unsigned, + unsigned, + BoundarySearchContextAvailability, + bool&) { + return true; +} + +// Regression test for crbug.com/788661 +TEST_F(VisibleUnitsTest, NextBoundaryOfEditableTableWithLeadingSpaceInOutput) { + VisiblePosition pos = CreateVisiblePosition(SetCaretTextToBody( + // The leading whitespace is necessary for bug repro + "<output> <table contenteditable><!--|--></table></output>")); + Position result = NextBoundary(pos, MockBoundarySearch); + EXPECT_EQ("<output> <table contenteditable>|</table></output>", + GetCaretTextFromBody(result)); +} + } // namespace blink
diff --git a/third_party/WebKit/Source/core/exported/LocalFrameClientImpl.cpp b/third_party/WebKit/Source/core/exported/LocalFrameClientImpl.cpp index f9df983..19c0b7f 100644 --- a/third_party/WebKit/Source/core/exported/LocalFrameClientImpl.cpp +++ b/third_party/WebKit/Source/core/exported/LocalFrameClientImpl.cpp
@@ -1117,6 +1117,11 @@ return web_frame_->Client()->GetInterfaceProvider(); } +AssociatedInterfaceProvider* +LocalFrameClientImpl::GetRemoteNavigationAssociatedInterfaces() { + return web_frame_->Client()->GetRemoteNavigationAssociatedInterfaces(); +} + void LocalFrameClientImpl::AnnotatedRegionsChanged() { web_frame_->Client()->DraggableRegionsChanged(); }
diff --git a/third_party/WebKit/Source/core/exported/LocalFrameClientImpl.h b/third_party/WebKit/Source/core/exported/LocalFrameClientImpl.h index ed6bebb0..052c61a 100644 --- a/third_party/WebKit/Source/core/exported/LocalFrameClientImpl.h +++ b/third_party/WebKit/Source/core/exported/LocalFrameClientImpl.h
@@ -243,6 +243,8 @@ std::unique_ptr<WebURLLoaderFactory> CreateURLLoaderFactory() override; service_manager::InterfaceProvider* GetInterfaceProvider() override; + AssociatedInterfaceProvider* GetRemoteNavigationAssociatedInterfaces() + override; void AnnotatedRegionsChanged() override;
diff --git a/third_party/WebKit/Source/core/frame/LocalFrame.cpp b/third_party/WebKit/Source/core/frame/LocalFrame.cpp index b2b105b0..123258b 100644 --- a/third_party/WebKit/Source/core/frame/LocalFrame.cpp +++ b/third_party/WebKit/Source/core/frame/LocalFrame.cpp
@@ -1016,6 +1016,12 @@ return *Client()->GetInterfaceProvider(); } +AssociatedInterfaceProvider* +LocalFrame::GetRemoteNavigationAssociatedInterfaces() { + DCHECK(Client()); + return Client()->GetRemoteNavigationAssociatedInterfaces(); +} + LocalFrameClient* LocalFrame::Client() const { return static_cast<LocalFrameClient*>(Frame::Client()); }
diff --git a/third_party/WebKit/Source/core/frame/LocalFrame.h b/third_party/WebKit/Source/core/frame/LocalFrame.h index b39cb07..9f4fbd8 100644 --- a/third_party/WebKit/Source/core/frame/LocalFrame.h +++ b/third_party/WebKit/Source/core/frame/LocalFrame.h
@@ -48,6 +48,7 @@ namespace blink { +class AssociatedInterfaceProvider; class Color; class ContentSettingsClient; class Document; @@ -230,6 +231,19 @@ service_manager::InterfaceProvider& GetInterfaceProvider(); InterfaceRegistry* GetInterfaceRegistry() { return interface_registry_; } + // Returns an AssociatedInterfaceProvider the frame can use to request + // navigation-associated interfaces from the browser. Messages transmitted + // over such interfaces will be dispatched in FIFO order with respect to each + // other and messages implementing navigation. + // + // Carefully consider whether an interface needs to be navigation-associated + // before introducing new navigation-associated interfaces. + // + // Navigation-associated interfaces are currently implemented as + // channel-associated interfaces. See + // https://chromium.googlesource.com/chromium/src/+/master/ipc#Using-Channel_associated-Interfaces. + AssociatedInterfaceProvider* GetRemoteNavigationAssociatedInterfaces(); + String GetInstrumentationToken() { return instrumentation_token_; } LocalFrameClient* Client() const;
diff --git a/third_party/WebKit/Source/core/frame/LocalFrameClient.h b/third_party/WebKit/Source/core/frame/LocalFrameClient.h index 19d085d06d..4c0595c 100644 --- a/third_party/WebKit/Source/core/frame/LocalFrameClient.h +++ b/third_party/WebKit/Source/core/frame/LocalFrameClient.h
@@ -69,6 +69,7 @@ enum class WebFeature : int32_t; } // namespace mojom +class AssociatedInterfaceProvider; class Document; class DocumentLoader; class HTMLFormElement; @@ -352,6 +353,11 @@ return nullptr; } + virtual AssociatedInterfaceProvider* + GetRemoteNavigationAssociatedInterfaces() { + return nullptr; + } + virtual void SetHasReceivedUserGesture(bool received_previously) {} virtual void AbortClientNavigation() {}
diff --git a/third_party/WebKit/Source/core/frame/WebLocalFrameImpl.cpp b/third_party/WebKit/Source/core/frame/WebLocalFrameImpl.cpp index 9692de0..f485c2d 100644 --- a/third_party/WebKit/Source/core/frame/WebLocalFrameImpl.cpp +++ b/third_party/WebKit/Source/core/frame/WebLocalFrameImpl.cpp
@@ -2478,7 +2478,7 @@ scoped_refptr<base::SingleThreadTaskRunner> WebLocalFrameImpl::GetTaskRunner( TaskType task_type) { - return GetFrame()->GetTaskRunner(task_type)->ToSingleThreadTaskRunner(); + return GetFrame()->GetTaskRunner(task_type); } WebInputMethodController* WebLocalFrameImpl::GetInputMethodController() {
diff --git a/third_party/WebKit/Source/core/html/HTMLLinkElement.cpp b/third_party/WebKit/Source/core/html/HTMLLinkElement.cpp index ea739c1..792187df 100644 --- a/third_party/WebKit/Source/core/html/HTMLLinkElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLLinkElement.cpp
@@ -153,12 +153,6 @@ link_ = LinkImport::Create(this); } else if (rel_attribute_.IsManifest()) { link_ = LinkManifest::Create(this); - } else if (rel_attribute_.IsServiceWorker() && - OriginTrials::linkServiceWorkerEnabled(GetExecutionContext())) { - if (GetDocument().GetFrame()) { - link_ = CoreInitializer::GetInstance().CreateServiceWorkerLinkResource( - this); - } } else { LinkStyle* link = LinkStyle::Create(this); if (FastHasAttribute(disabledAttr)) {
diff --git a/third_party/WebKit/Source/core/html/HTMLLinkElement.idl b/third_party/WebKit/Source/core/html/HTMLLinkElement.idl index 006c4c4..f37b8fd 100644 --- a/third_party/WebKit/Source/core/html/HTMLLinkElement.idl +++ b/third_party/WebKit/Source/core/html/HTMLLinkElement.idl
@@ -53,8 +53,4 @@ // Subresource Integrity // https://w3c.github.io/webappsec-subresource-integrity/#HTMLLinkElement [Reflect] attribute DOMString integrity; - - // Service workers - // https://w3c.github.io/ServiceWorker/#link-type-serviceworker - [Reflect, OriginTrialEnabled=LinkServiceWorker] attribute USVString scope; };
diff --git a/third_party/WebKit/Source/core/html/RelList.cpp b/third_party/WebKit/Source/core/html/RelList.cpp index 5fc831d..7726997 100644 --- a/third_party/WebKit/Source/core/html/RelList.cpp +++ b/third_party/WebKit/Source/core/html/RelList.cpp
@@ -32,10 +32,6 @@ ExceptionState&) const { if (SupportedTokens().Contains(token_value)) return true; - if (OriginTrials::linkServiceWorkerEnabled( - GetElement().GetExecutionContext()) && - token_value == "serviceworker") - return true; if (RuntimeEnabledFeatures::ModulePreloadEnabled() && token_value == "modulepreload") return true;
diff --git a/third_party/WebKit/Source/core/html/custom/CustomElementRegistryTest.cpp b/third_party/WebKit/Source/core/html/custom/CustomElementRegistryTest.cpp index 8851c61..751afa25 100644 --- a/third_party/WebKit/Source/core/html/custom/CustomElementRegistryTest.cpp +++ b/third_party/WebKit/Source/core/html/custom/CustomElementRegistryTest.cpp
@@ -19,7 +19,7 @@ #include "core/html/custom/CustomElementDefinitionBuilder.h" #include "core/html/custom/CustomElementDescriptor.h" #include "core/html/custom/CustomElementTestHelpers.h" -#include "core/testing/DummyPageHolder.h" +#include "core/testing/PageTestBase.h" #include "platform/bindings/ScriptForbiddenScope.h" #include "platform/heap/Handle.h" #include "platform/wtf/text/AtomicString.h" @@ -27,22 +27,16 @@ namespace blink { -class CustomElementRegistryTest : public ::testing::Test { +class CustomElementRegistryTest : public PageTestBase { protected: - void SetUp() { - page_.reset(DummyPageHolder::Create(IntSize(1, 1)).release()); - } - - void TearDown() { page_ = nullptr; } - - Document& GetDocument() { return page_->GetDocument(); } + void SetUp() { PageTestBase::SetUp(IntSize(1, 1)); } CustomElementRegistry& Registry() { - return *page_->GetFrame().DomWindow()->customElements(); + return *GetFrame().DomWindow()->customElements(); } ScriptState* GetScriptState() { - return ToScriptStateForMainWorld(&page_->GetFrame()); + return ToScriptStateForMainWorld(&GetFrame()); } void CollectCandidates(const CustomElementDescriptor& desc, @@ -57,9 +51,6 @@ return element->attachShadow(GetScriptState(), shadow_root_init, no_exceptions); } - - private: - std::unique_ptr<DummyPageHolder> page_; }; TEST_F(CustomElementRegistryTest,
diff --git a/third_party/WebKit/Source/core/html/custom/CustomElementUpgradeSorterTest.cpp b/third_party/WebKit/Source/core/html/custom/CustomElementUpgradeSorterTest.cpp index bf52c05a..2331d5c3 100644 --- a/third_party/WebKit/Source/core/html/custom/CustomElementUpgradeSorterTest.cpp +++ b/third_party/WebKit/Source/core/html/custom/CustomElementUpgradeSorterTest.cpp
@@ -14,31 +14,27 @@ #include "core/dom/ShadowRootInit.h" #include "core/html/HTMLDocument.h" #include "core/html_names.h" -#include "core/testing/DummyPageHolder.h" +#include "core/testing/PageTestBase.h" #include "platform/heap/Handle.h" #include "platform/wtf/text/AtomicString.h" #include "testing/gtest/include/gtest/gtest.h" namespace blink { -class CustomElementUpgradeSorterTest : public ::testing::Test { +class CustomElementUpgradeSorterTest : public PageTestBase { protected: - void SetUp() override { page_ = DummyPageHolder::Create(IntSize(1, 1)); } - - void TearDown() override { page_ = nullptr; } + void SetUp() override { PageTestBase::SetUp(IntSize(1, 1)); } Element* CreateElementWithId(const char* local_name, const char* id) { NonThrowableExceptionState no_exceptions; - Element* element = GetDocument()->createElement( + Element* element = GetDocument().createElement( local_name, StringOrDictionary(), no_exceptions); element->setAttribute(HTMLNames::idAttr, id); return element; } - Document* GetDocument() { return &page_->GetDocument(); } - ScriptState* GetScriptState() { - return ToScriptStateForMainWorld(&page_->GetFrame()); + return ToScriptStateForMainWorld(&GetFrame()); } ShadowRoot* AttachShadowTo(Element* element) { @@ -48,15 +44,12 @@ return element->attachShadow(GetScriptState(), shadow_root_init, no_exceptions); } - - private: - std::unique_ptr<DummyPageHolder> page_; }; TEST_F(CustomElementUpgradeSorterTest, inOtherDocument_notInSet) { NonThrowableExceptionState no_exceptions; Element* element = - GetDocument()->createElement("a-a", StringOrDictionary(), no_exceptions); + GetDocument().createElement("a-a", StringOrDictionary(), no_exceptions); Document* other_document = HTMLDocument::CreateForTest(); other_document->AppendChild(element); @@ -67,7 +60,7 @@ sorter.Add(element); HeapVector<Member<Element>> elements; - sorter.Sorted(&elements, GetDocument()); + sorter.Sorted(&elements, &GetDocument()); EXPECT_EQ(0u, elements.size()) << "the adopted-away candidate should not have been included"; } @@ -75,14 +68,14 @@ TEST_F(CustomElementUpgradeSorterTest, oneCandidate) { NonThrowableExceptionState no_exceptions; Element* element = - GetDocument()->createElement("a-a", StringOrDictionary(), no_exceptions); - GetDocument()->documentElement()->AppendChild(element); + GetDocument().createElement("a-a", StringOrDictionary(), no_exceptions); + GetDocument().documentElement()->AppendChild(element); CustomElementUpgradeSorter sorter; sorter.Add(element); HeapVector<Member<Element>> elements; - sorter.Sorted(&elements, GetDocument()); + sorter.Sorted(&elements, &GetDocument()); EXPECT_EQ(1u, elements.size()) << "exactly one candidate should be in the result set"; EXPECT_TRUE(elements.Contains(element)) @@ -94,9 +87,9 @@ Element* b = CreateElementWithId("a-a", "b"); Element* c = CreateElementWithId("a-a", "c"); - GetDocument()->documentElement()->AppendChild(a); + GetDocument().documentElement()->AppendChild(a); a->AppendChild(b); - GetDocument()->documentElement()->AppendChild(c); + GetDocument().documentElement()->AppendChild(c); CustomElementUpgradeSorter sorter; sorter.Add(b); @@ -104,7 +97,7 @@ sorter.Add(c); HeapVector<Member<Element>> elements; - sorter.Sorted(&elements, GetDocument()); + sorter.Sorted(&elements, &GetDocument()); EXPECT_EQ(3u, elements.size()); EXPECT_EQ(a, elements[0].Get()); EXPECT_EQ(b, elements[1].Get()); @@ -119,7 +112,7 @@ Element* b = CreateElementWithId("a-a", "b"); Element* c = CreateElementWithId("a-a", "c"); - GetDocument()->documentElement()->AppendChild(a); + GetDocument().documentElement()->AppendChild(a); a->AppendChild(b); b->AppendChild(c); @@ -128,7 +121,7 @@ sort.Add(a); HeapVector<Member<Element>> elements; - sort.Sorted(&elements, GetDocument()); + sort.Sorted(&elements, &GetDocument()); EXPECT_EQ(2u, elements.size()); EXPECT_EQ(a, elements[0].Get()); EXPECT_EQ(c, elements[1].Get()); @@ -142,16 +135,16 @@ Element* b = CreateElementWithId("a-a", "b"); Element* c = CreateElementWithId("a-a", "c"); - GetDocument()->documentElement()->AppendChild(a); + GetDocument().documentElement()->AppendChild(a); a->AppendChild(b); - GetDocument()->documentElement()->AppendChild(c); + GetDocument().documentElement()->AppendChild(c); CustomElementUpgradeSorter sort; sort.Add(b); sort.Add(c); HeapVector<Member<Element>> elements; - sort.Sorted(&elements, GetDocument()); + sort.Sorted(&elements, &GetDocument()); EXPECT_EQ(2u, elements.size()); EXPECT_EQ(b, elements[0].Get()); EXPECT_EQ(c, elements[1].Get()); @@ -165,8 +158,8 @@ Element* b = CreateElementWithId("a-a", "b"); Element* c = CreateElementWithId("a-a", "c"); - GetDocument()->documentElement()->AppendChild(a); - GetDocument()->documentElement()->AppendChild(b); + GetDocument().documentElement()->AppendChild(a); + GetDocument().documentElement()->AppendChild(b); b->AppendChild(c); CustomElementUpgradeSorter sort; @@ -174,7 +167,7 @@ sort.Add(c); HeapVector<Member<Element>> elements; - sort.Sorted(&elements, GetDocument()); + sort.Sorted(&elements, &GetDocument()); EXPECT_EQ(2u, elements.size()); EXPECT_EQ(a, elements[0].Get()); EXPECT_EQ(c, elements[1].Get()); @@ -191,7 +184,7 @@ Element* c = CreateElementWithId("a-a", "c"); Element* d = CreateElementWithId("a-a", "d"); - GetDocument()->documentElement()->AppendChild(a); + GetDocument().documentElement()->AppendChild(a); ShadowRoot* s = AttachShadowTo(a); a->AppendChild(d); @@ -204,7 +197,7 @@ sort.Add(d); HeapVector<Member<Element>> elements; - sort.Sorted(&elements, GetDocument()); + sort.Sorted(&elements, &GetDocument()); EXPECT_EQ(3u, elements.size()); EXPECT_EQ(a, elements[0].Get()); EXPECT_EQ(c, elements[1].Get());
diff --git a/third_party/WebKit/Source/core/html/forms/ExternalPopupMenuTest.cpp b/third_party/WebKit/Source/core/html/forms/ExternalPopupMenuTest.cpp index e71a8ab..0b5a1a01 100644 --- a/third_party/WebKit/Source/core/html/forms/ExternalPopupMenuTest.cpp +++ b/third_party/WebKit/Source/core/html/forms/ExternalPopupMenuTest.cpp
@@ -13,7 +13,7 @@ #include "core/html_names.h" #include "core/layout/LayoutMenuList.h" #include "core/page/Page.h" -#include "core/testing/DummyPageHolder.h" +#include "core/testing/PageTestBase.h" #include "platform/testing/URLTestHelpers.h" #include "platform/testing/UnitTestHelpers.h" #include "public/platform/Platform.h" @@ -25,27 +25,23 @@ namespace blink { -class ExternalPopupMenuDisplayNoneItemsTest : public ::testing::Test { +class ExternalPopupMenuDisplayNoneItemsTest : public PageTestBase { public: ExternalPopupMenuDisplayNoneItemsTest() {} protected: void SetUp() override { - dummy_page_holder_ = DummyPageHolder::Create(IntSize(800, 600)); - HTMLSelectElement* element = - HTMLSelectElement::Create(dummy_page_holder_->GetDocument()); + PageTestBase::SetUp(); + HTMLSelectElement* element = HTMLSelectElement::Create(GetDocument()); // Set the 4th an 5th items to have "display: none" property element->SetInnerHTMLFromString( "<option><option><option><option style='display:none;'><option " "style='display:none;'><option><option>"); - dummy_page_holder_->GetDocument().body()->AppendChild(element, - ASSERT_NO_EXCEPTION); + GetDocument().body()->AppendChild(element, ASSERT_NO_EXCEPTION); owner_element_ = element; - dummy_page_holder_->GetDocument() - .UpdateStyleAndLayoutIgnorePendingStylesheets(); + GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheets(); } - std::unique_ptr<DummyPageHolder> dummy_page_holder_; Persistent<HTMLSelectElement> owner_element_; };
diff --git a/third_party/WebKit/Source/core/html/forms/HTMLOutputElement.h b/third_party/WebKit/Source/core/html/forms/HTMLOutputElement.h index f5a5403..3360a3b 100644 --- a/third_party/WebKit/Source/core/html/forms/HTMLOutputElement.h +++ b/third_party/WebKit/Source/core/html/forms/HTMLOutputElement.h
@@ -51,7 +51,9 @@ void setDefaultValue(const String&); DOMTokenList* htmlFor() const; - bool CanContainRangeEndPoint() const override { return false; } + bool CanContainRangeEndPoint() const override { + return is_default_value_mode_; + } void Trace(blink::Visitor*) override;
diff --git a/third_party/WebKit/Source/core/html/forms/TextControlElement.cpp b/third_party/WebKit/Source/core/html/forms/TextControlElement.cpp index 858fcd26..b7997e3 100644 --- a/third_party/WebKit/Source/core/html/forms/TextControlElement.cpp +++ b/third_party/WebKit/Source/core/html/forms/TextControlElement.cpp
@@ -514,22 +514,16 @@ LocalFrame* frame = GetDocument().GetFrame(); if (!frame) return 0; - { - // To avoid regression on speedometer benchmark[1] test, we should not - // update layout tree in this code block. - // [1] http://browserbench.org/Speedometer/ - DocumentLifecycle::DisallowTransitionScope disallow_transition( - GetDocument().Lifecycle()); - const SelectionInDOMTree& selection = - frame->Selection().GetSelectionInDOMTree(); - if (frame->Selection().Granularity() == TextGranularity::kCharacter) { - return IndexForPosition(InnerEditorElement(), - selection.ComputeStartPosition()); - } - } - const VisibleSelection& visible_selection = - frame->Selection().ComputeVisibleSelectionInDOMTreeDeprecated(); - return IndexForPosition(InnerEditorElement(), visible_selection.Start()); + + // To avoid regression on speedometer benchmark[1] test, we should not + // update layout tree in this code block. + // [1] http://browserbench.org/Speedometer/ + DocumentLifecycle::DisallowTransitionScope disallow_transition( + GetDocument().Lifecycle()); + const SelectionInDOMTree& selection = + frame->Selection().GetSelectionInDOMTree(); + return IndexForPosition(InnerEditorElement(), + selection.ComputeStartPosition()); } unsigned TextControlElement::selectionEnd() const { @@ -545,22 +539,15 @@ LocalFrame* frame = GetDocument().GetFrame(); if (!frame) return 0; - { - // To avoid regression on speedometer benchmark[1] test, we should not - // update layout tree in this code block. - // [1] http://browserbench.org/Speedometer/ - DocumentLifecycle::DisallowTransitionScope disallow_transition( - GetDocument().Lifecycle()); - const SelectionInDOMTree& selection = - frame->Selection().GetSelectionInDOMTree(); - if (frame->Selection().Granularity() == TextGranularity::kCharacter) { - return IndexForPosition(InnerEditorElement(), - selection.ComputeEndPosition()); - } - } - const VisibleSelection& visible_selection = - frame->Selection().ComputeVisibleSelectionInDOMTreeDeprecated(); - return IndexForPosition(InnerEditorElement(), visible_selection.End()); + + // To avoid regression on speedometer benchmark[1] test, we should not + // update layout tree in this code block. + // [1] http://browserbench.org/Speedometer/ + DocumentLifecycle::DisallowTransitionScope disallow_transition( + GetDocument().Lifecycle()); + const SelectionInDOMTree& selection = + frame->Selection().GetSelectionInDOMTree(); + return IndexForPosition(InnerEditorElement(), selection.ComputeEndPosition()); } static const AtomicString& DirectionString(
diff --git a/third_party/WebKit/Source/core/imagebitmap/ImageBitmap.cpp b/third_party/WebKit/Source/core/imagebitmap/ImageBitmap.cpp index 3a8401e..018cf7c 100644 --- a/third_party/WebKit/Source/core/imagebitmap/ImageBitmap.cpp +++ b/third_party/WebKit/Source/core/imagebitmap/ImageBitmap.cpp
@@ -171,17 +171,20 @@ } // This function results in a readback due to using SkImage::readPixels(). +// Returns transparent black pixels if the input SkImageInfo.bounds() does +// not intersect with the input image boundaries. scoped_refptr<Uint8Array> CopyImageData( const scoped_refptr<StaticBitmapImage>& input, - const SkImageInfo& info) { + const SkImageInfo& info, + const unsigned x = 0, + const unsigned y = 0) { if (info.isEmpty()) return nullptr; sk_sp<SkImage> sk_image = input->PaintImageForCurrentFrame().GetSkImage(); if (sk_image->bounds().isEmpty()) return nullptr; - unsigned width = static_cast<unsigned>(input->width()); scoped_refptr<ArrayBuffer> dst_buffer = - ArrayBuffer::CreateOrNull(width * input->height(), info.bytesPerPixel()); + ArrayBuffer::CreateOrNull(info.computeMinByteSize(), 1); if (!dst_buffer) return nullptr; unsigned byte_length = dst_buffer->ByteLength(); @@ -189,8 +192,8 @@ Uint8Array::Create(std::move(dst_buffer), 0, byte_length); if (!dst_pixels) return nullptr; - bool read_pixels_successful = sk_image->readPixels( - info, dst_pixels->Data(), width * info.bytesPerPixel(), 0, 0); + bool read_pixels_successful = + sk_image->readPixels(info, dst_pixels->Data(), info.minRowBytes(), x, y); DCHECK(read_pixels_successful); if (!read_pixels_successful) return nullptr; @@ -260,7 +263,9 @@ SkCanvas* canvas = surface->getCanvas(); canvas->scale(1, -1); canvas->translate(0, -input->height()); - canvas->drawImage(image.get(), 0, 0); + SkPaint paint; + paint.setBlendMode(SkBlendMode::kSrc); + canvas->drawImage(image.get(), 0, 0, &paint); return StaticBitmapImage::Create(surface->makeImageSnapshot(), input->ContextProviderWrapper()); } @@ -548,7 +553,9 @@ sk_sp<SkSurface> surface = SkSurface::MakeRaster(GetSkImageInfo(StaticBitmapImage::Create( skia_image, image->ContextProviderWrapper()))); - surface->getCanvas()->drawImage(skia_image.get(), 0, 0); + SkPaint paint; + paint.setBlendMode(SkBlendMode::kSrc); + surface->getCanvas()->drawImage(skia_image.get(), 0, 0, &paint); skia_image = surface->makeImageSnapshot(); } }
diff --git a/third_party/WebKit/Source/core/imagebitmap/ImageBitmapTest.cpp b/third_party/WebKit/Source/core/imagebitmap/ImageBitmapTest.cpp index d8a4590..6d34fe9b 100644 --- a/third_party/WebKit/Source/core/imagebitmap/ImageBitmapTest.cpp +++ b/third_party/WebKit/Source/core/imagebitmap/ImageBitmapTest.cpp
@@ -399,9 +399,8 @@ std::unique_ptr<uint8_t[]> src_pixel( new uint8_t[raster_image_info.bytesPerPixel()]()); - EXPECT_TRUE(image->readPixels( - raster_image_info.makeWH(1, 1), src_pixel.get(), - image->width() * raster_image_info.bytesPerPixel(), 5, 5)); + EXPECT_TRUE(image->readPixels(raster_image_info.makeWH(1, 1), src_pixel.get(), + raster_image_info.minRowBytes(), 5, 5)); ImageResourceContent* source_image_resource = ImageResourceContent::CreateLoaded(
diff --git a/third_party/WebKit/Source/core/inspector/InspectorLayerTreeAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorLayerTreeAgent.cpp index 991b532..3260eb7 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorLayerTreeAgent.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorLayerTreeAgent.cpp
@@ -333,13 +333,16 @@ return; LocalFrameView* child_frame_view = ToLayoutEmbeddedContent(root->GetLayoutObject()).ChildFrameView(); + if (!child_frame_view) + return; LayoutViewItem child_layout_view_item = child_frame_view->GetLayoutViewItem(); - if (!child_layout_view_item.IsNull()) { - if (PaintLayerCompositor* child_compositor = - child_layout_view_item.Compositor()) - BuildLayerIdToNodeIdMap(child_compositor->RootLayer(), - layer_id_to_node_id_map); - } + if (child_layout_view_item.IsNull()) + return; + PaintLayerCompositor* child_compositor = child_layout_view_item.Compositor(); + if (!child_compositor) + return; + BuildLayerIdToNodeIdMap(child_compositor->RootLayer(), + layer_id_to_node_id_map); } void InspectorLayerTreeAgent::GatherGraphicsLayers(
diff --git a/third_party/WebKit/Source/core/layout/ng/ng_block_node.cc b/third_party/WebKit/Source/core/layout/ng/ng_block_node.cc index ca150e4..0b6b90a 100644 --- a/third_party/WebKit/Source/core/layout/ng/ng_block_node.cc +++ b/third_party/WebKit/Source/core/layout/ng/ng_block_node.cc
@@ -279,7 +279,7 @@ return nullptr; } -NGLayoutInputNode NGBlockNode::FirstChild() { +NGLayoutInputNode NGBlockNode::FirstChild() const { auto* block = ToLayoutBlockFlow(box_); auto* child = GetLayoutObjectForFirstChildNode(block); if (!child)
diff --git a/third_party/WebKit/Source/core/layout/ng/ng_block_node.h b/third_party/WebKit/Source/core/layout/ng/ng_block_node.h index 89d1828..3fb01c6 100644 --- a/third_party/WebKit/Source/core/layout/ng/ng_block_node.h +++ b/third_party/WebKit/Source/core/layout/ng/ng_block_node.h
@@ -44,7 +44,7 @@ NGBoxStrut GetScrollbarSizes() const; - NGLayoutInputNode FirstChild(); + NGLayoutInputNode FirstChild() const; // Layout an atomic inline; e.g., inline block. scoped_refptr<NGLayoutResult> LayoutAtomicInline(const NGConstraintSpace&,
diff --git a/third_party/WebKit/Source/core/layout/svg/LayoutSVGShape.cpp b/third_party/WebKit/Source/core/layout/svg/LayoutSVGShape.cpp index 925913d5..6b8642e 100644 --- a/third_party/WebKit/Source/core/layout/svg/LayoutSVGShape.cpp +++ b/third_party/WebKit/Source/core/layout/svg/LayoutSVGShape.cpp
@@ -54,7 +54,9 @@ needs_shape_update_(true), // Default is true, so we grab a AffineTransform object once from // SVGGeometryElement. - needs_transform_update_(true) {} + needs_transform_update_(true), + // <line> elements have no joins and thus needn't care about miters. + affected_by_miter_(!IsSVGLineElement(node)) {} LayoutSVGShape::~LayoutSVGShape() {} @@ -104,7 +106,7 @@ const SVGComputedStyle& svg_style = StyleRef().SvgStyle(); float delta = stroke_width / 2; - if (HasMiterJoinStyle(svg_style)) { + if (affected_by_miter_ && HasMiterJoinStyle(svg_style)) { const float miter = svg_style.StrokeMiterLimit(); if (miter < M_SQRT2 && HasSquareCapStyle(svg_style)) delta *= M_SQRT2;
diff --git a/third_party/WebKit/Source/core/layout/svg/LayoutSVGShape.h b/third_party/WebKit/Source/core/layout/svg/LayoutSVGShape.h index c857ac7..c2107fb 100644 --- a/third_party/WebKit/Source/core/layout/svg/LayoutSVGShape.h +++ b/third_party/WebKit/Source/core/layout/svg/LayoutSVGShape.h
@@ -168,6 +168,7 @@ bool needs_boundaries_update_ : 1; bool needs_shape_update_ : 1; bool needs_transform_update_ : 1; + bool affected_by_miter_ : 1; }; DEFINE_LAYOUT_OBJECT_TYPE_CASTS(LayoutSVGShape, IsSVGShape());
diff --git a/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.cpp b/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.cpp index 2dff1ae..862c501 100644 --- a/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.cpp +++ b/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.cpp
@@ -324,24 +324,22 @@ // following cases: // // - When the request is sync or the protocol is unsupported since we can - // assume that any SW is skipped for such requests by content/ code. - // - When the ServiceWorkerMode is not kAll, the local SW will be skipped. - // The request can still be intercepted by a foreign SW, but we cannot know - // whether such a foreign fetch interception happens or not at this point. - // - If we're not yet controlled by a local SW, then we're sure that this - // request won't be intercepted by a local SW. In case we end up with + // assume that any service worker (SW) is skipped for such requests by + // content/ code. + // - When the ServiceWorkerMode is not kAll, any SW will be skipped. + // - If we're not yet controlled by a SW, then we're sure that this + // request won't be intercepted by a SW. In case we end up with // sending a CORS preflight request, the actual request to be sent later // may be intercepted. This is taken care of in LoadPreflightRequest() by // setting the ServiceWorkerMode to kNone. // // From the above analysis, you can see that the request can never be - // intercepted by a local SW inside this if-block. It's because: + // intercepted by a SW inside this if-block. It's because: // - the ServiceWorkerMode needs to be kAll, and // - we're controlled by a SW at this point - // to allow a local SW to intercept the request. Even when the request gets - // issued asnychronously after performing the CORS preflight, it doesn'g get - // intercepted since LoadPreflightRequest() sets the flag to kNone in - // advance. + // to allow a SW to intercept the request. Even when the request gets issued + // asynchronously after performing the CORS preflight, it doesn't get + // intercepted since LoadPreflightRequest() sets the flag to kNone in advance. if (!async_ || new_request.GetServiceWorkerMode() != WebURLRequest::ServiceWorkerMode::kAll || @@ -354,16 +352,12 @@ if (WebCORS::IsCORSEnabledRequestMode(request.GetFetchRequestMode())) { // Save the request to fallback_request_for_service_worker to use when the - // local SW doesn't handle (call respondWith()) a CORS enabled request. + // service worker doesn't handle (call respondWith()) a CORS enabled + // request. fallback_request_for_service_worker_ = ResourceRequest(request); - - // We still want to give a foreign SW if any a chance to handle the - // request. So, only skip the controlling local SW for the fallback - // request. This is currently safe because of http://crbug.com/604084. The - // WasFallbackRequiredByServiceWorker() flag is never set when a foreign SW - // handled a request. + // Skip the service worker for the fallback request. fallback_request_for_service_worker_.SetServiceWorkerMode( - WebURLRequest::ServiceWorkerMode::kForeign); + WebURLRequest::ServiceWorkerMode::kNone); } LoadRequest(new_request, resource_loader_options_); @@ -950,10 +944,6 @@ } if (response.WasFetchedViaServiceWorker()) { - if (response.WasFetchedViaForeignFetch()) { - loading_context_->GetFetchContext()->CountUsage( - WebFeature::kForeignFetchInterception); - } if (response.WasFallbackRequiredByServiceWorker()) { // At this point we must have m_fallbackRequestForServiceWorker. (For // SharedWorker the request won't be CORS or CORS-with-preflight,
diff --git a/third_party/WebKit/Source/core/loader/FrameFetchContext.cpp b/third_party/WebKit/Source/core/loader/FrameFetchContext.cpp index 714809c..d1f7539 100644 --- a/third_party/WebKit/Source/core/loader/FrameFetchContext.cpp +++ b/third_party/WebKit/Source/core/loader/FrameFetchContext.cpp
@@ -1194,15 +1194,14 @@ DCHECK(!IsDetached()); WrappedResourceRequest webreq(request); if (MasterDocumentLoader()->GetServiceWorkerNetworkProvider()) { - auto loader = - MasterDocumentLoader() - ->GetServiceWorkerNetworkProvider() - ->CreateURLLoader(webreq, task_runner->ToSingleThreadTaskRunner()); + auto loader = MasterDocumentLoader() + ->GetServiceWorkerNetworkProvider() + ->CreateURLLoader(webreq, task_runner); if (loader) return loader; } - return GetFrame()->GetURLLoaderFactory()->CreateURLLoader( - webreq, task_runner->ToSingleThreadTaskRunner()); + return GetFrame()->GetURLLoaderFactory()->CreateURLLoader(webreq, + task_runner); } FetchContext* FrameFetchContext::Detach() {
diff --git a/third_party/WebKit/Source/core/loader/WorkerFetchContext.cpp b/third_party/WebKit/Source/core/loader/WorkerFetchContext.cpp index ce9292f1..6bd9595 100644 --- a/third_party/WebKit/Source/core/loader/WorkerFetchContext.cpp +++ b/third_party/WebKit/Source/core/loader/WorkerFetchContext.cpp
@@ -91,8 +91,7 @@ loading_task_runner_( global_scope_->GetTaskRunner(TaskType::kUnspecedLoading)), save_data_enabled_(GetNetworkStateNotifier().SaveDataEnabled()) { - web_context_->InitializeOnWorkerThread( - loading_task_runner_->ToSingleThreadTaskRunner()); + web_context_->InitializeOnWorkerThread(loading_task_runner_); std::unique_ptr<blink::WebDocumentSubresourceFilter> web_filter = web_context_->TakeSubresourceFilter(); if (web_filter) { @@ -227,8 +226,7 @@ if (!url_loader_factory_) url_loader_factory_ = web_context_->CreateURLLoaderFactory(); WrappedResourceRequest wrapped(request); - return url_loader_factory_->CreateURLLoader( - wrapped, task_runner->ToSingleThreadTaskRunner()); + return url_loader_factory_->CreateURLLoader(wrapped, task_runner); } bool WorkerFetchContext::IsControlledByServiceWorker() const {
diff --git a/third_party/WebKit/Source/core/paint/PaintLayerPainter.cpp b/third_party/WebKit/Source/core/paint/PaintLayerPainter.cpp index c1e68ff9..d59809e 100644 --- a/third_party/WebKit/Source/core/paint/PaintLayerPainter.cpp +++ b/third_party/WebKit/Source/core/paint/PaintLayerPainter.cpp
@@ -982,6 +982,24 @@ ClipState clip_state) { DCHECK(paint_layer_.IsSelfPaintingLayer()); + Optional<ScopedPaintChunkProperties> fragment_paint_chunk_properties; + if (RuntimeEnabledFeatures::SlimmingPaintV175Enabled() && + // We have already created paint chunk properties for the first fragment + // in PaintLayerContents(). + fragment.fragment_data != + &paint_layer_.GetLayoutObject().FirstFragment()) { + auto properties = + *fragment.fragment_data->GetRarePaintData()->LocalBorderBoxProperties(); + // Keep the current effect which might have been set by + // PaintMaskForFragments(). + properties.SetEffect(context.GetPaintController() + .CurrentPaintChunkProperties() + .property_tree_state.Effect()); + fragment_paint_chunk_properties.emplace( + context.GetPaintController(), properties, paint_layer_, + DisplayItem::PaintPhaseToDrawingType(phase)); + } + DisplayItemClient* client = &paint_layer_.GetLayoutObject(); Optional<LayerClipRecorder> clip_recorder; if (clip_state != kHasClipped &&
diff --git a/third_party/WebKit/Source/core/paint/PaintPropertyTreePrinter.cpp b/third_party/WebKit/Source/core/paint/PaintPropertyTreePrinter.cpp index a3453f95..b6c3a4b 100644 --- a/third_party/WebKit/Source/core/paint/PaintPropertyTreePrinter.cpp +++ b/third_party/WebKit/Source/core/paint/PaintPropertyTreePrinter.cpp
@@ -80,10 +80,12 @@ } void CollectPropertyNodes(const LayoutObject& object) { - if (const ObjectPaintProperties* properties = - object.FirstFragment().PaintProperties()) - Traits::AddObjectPaintProperties(object, *properties, *this); - for (LayoutObject* child = object.SlowFirstChild(); child; + for (const auto* fragment = &object.FirstFragment(); fragment; + fragment = fragment->NextFragment()) { + if (const auto* properties = fragment->PaintProperties()) + Traits::AddObjectPaintProperties(object, *properties, *this); + } + for (const auto* child = object.SlowFirstChild(); child; child = child->NextSibling()) CollectPropertyNodes(*child); }
diff --git a/third_party/WebKit/Source/core/testing/Internals.cpp b/third_party/WebKit/Source/core/testing/Internals.cpp index 0490e81..6a52313 100644 --- a/third_party/WebKit/Source/core/testing/Internals.cpp +++ b/third_party/WebKit/Source/core/testing/Internals.cpp
@@ -596,7 +596,7 @@ return; } - image_data->AdvanceTime(delta_time_in_seconds); + image_data->AdvanceTime(TimeDelta::FromSecondsD(delta_time_in_seconds)); } void Internals::advanceImageAnimation(Element* image,
diff --git a/third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp b/third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp index 3b7fc7f..b125b54 100644 --- a/third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp +++ b/third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp
@@ -327,11 +327,12 @@ font_selector_(OffscreenFontSelector::Create(this)) { InstanceCounters::IncrementCounter( InstanceCounters::kWorkerGlobalScopeCounter); - SetSecurityOrigin(SecurityOrigin::Create(url_)); + scoped_refptr<SecurityOrigin> security_origin = SecurityOrigin::Create(url_); if (creation_params->starter_origin) { - GetSecurityOrigin()->TransferPrivilegesFrom( + security_origin->TransferPrivilegesFrom( creation_params->starter_origin->CreatePrivilegeData()); } + SetSecurityOrigin(std::move(security_origin)); ApplyContentSecurityPolicyFromVector( *creation_params->content_security_policy_parsed_headers); SetWorkerSettings(std::move(creation_params->worker_settings));
diff --git a/third_party/WebKit/Source/core/xml/BUILD.gn b/third_party/WebKit/Source/core/xml/BUILD.gn index 9f477558..15bd670 100644 --- a/third_party/WebKit/Source/core/xml/BUILD.gn +++ b/third_party/WebKit/Source/core/xml/BUILD.gn
@@ -45,8 +45,6 @@ "XPathValue.h", "XPathVariableReference.cpp", "XPathVariableReference.h", - "XSLImportRule.cpp", - "XSLImportRule.h", "XSLStyleSheet.h", "XSLStyleSheetLibxslt.cpp", "XSLTExtensions.cpp",
diff --git a/third_party/WebKit/Source/core/xml/XSLImportRule.cpp b/third_party/WebKit/Source/core/xml/XSLImportRule.cpp deleted file mode 100644 index 1d5e398..0000000 --- a/third_party/WebKit/Source/core/xml/XSLImportRule.cpp +++ /dev/null
@@ -1,110 +0,0 @@ -/* - * This file is part of the XSL implementation. - * - * Copyright (C) 2004, 2005, 2006, 2008 Apple Inc. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "core/xml/XSLImportRule.h" - -#include "core/dom/Document.h" -#include "core/loader/resource/XSLStyleSheetResource.h" -#include "platform/SharedBuffer.h" -#include "platform/loader/fetch/FetchParameters.h" -#include "platform/loader/fetch/RawResource.h" -#include "platform/loader/fetch/ResourceFetcher.h" -#include "platform/loader/fetch/ResourceLoaderOptions.h" -#include "platform/loader/fetch/fetch_initiator_type_names.h" -#include "platform/wtf/text/TextEncoding.h" - -namespace blink { - -XSLImportRule::XSLImportRule(XSLStyleSheet* parent, const String& href) - : parent_style_sheet_(parent), str_href_(href), loading_(false) {} - -XSLImportRule::~XSLImportRule() {} - -void XSLImportRule::SetXSLStyleSheet(const String& href, - const KURL& base_url, - const String& sheet) { - if (style_sheet_) - style_sheet_->SetParentStyleSheet(nullptr); - - style_sheet_ = XSLStyleSheet::Create(this, href, base_url); - - XSLStyleSheet* parent = ParentStyleSheet(); - if (parent) - style_sheet_->SetParentStyleSheet(parent); - - style_sheet_->ParseString(sheet); - loading_ = false; - - if (parent) - parent->CheckLoaded(); -} - -bool XSLImportRule::IsLoading() { - return loading_ || (style_sheet_ && style_sheet_->IsLoading()); -} - -void XSLImportRule::LoadSheet() { - Document* owner_document = nullptr; - XSLStyleSheet* root_sheet = ParentStyleSheet(); - - if (root_sheet) { - while (XSLStyleSheet* parent_sheet = root_sheet->parentStyleSheet()) - root_sheet = parent_sheet; - } - - if (root_sheet) - owner_document = root_sheet->OwnerDocument(); - - String abs_href = str_href_; - XSLStyleSheet* parent_sheet = ParentStyleSheet(); - if (!parent_sheet->BaseURL().IsNull()) { - // Use parent styleheet's URL as the base URL - abs_href = KURL(parent_sheet->BaseURL(), str_href_).GetString(); - } - - // Check for a cycle in our import chain. If we encounter a stylesheet in - // our parent chain with the same URL, then just bail. - for (XSLStyleSheet* parent_sheet = ParentStyleSheet(); parent_sheet; - parent_sheet = parent_sheet->parentStyleSheet()) { - if (abs_href == parent_sheet->BaseURL().GetString()) - return; - } - - ResourceLoaderOptions fetch_options; - fetch_options.initiator_info.name = FetchInitiatorTypeNames::xml; - FetchParameters params(ResourceRequest(owner_document->CompleteURL(abs_href)), - fetch_options); - params.SetOriginRestriction(FetchParameters::kRestrictToSameOrigin); - XSLStyleSheetResource* resource = XSLStyleSheetResource::FetchSynchronously( - params, owner_document->Fetcher()); - if (!resource || !resource->Sheet()) - return; - - DCHECK(!style_sheet_); - SetXSLStyleSheet(abs_href, resource->GetResponse().Url(), resource->Sheet()); -} - -void XSLImportRule::Trace(blink::Visitor* visitor) { - visitor->Trace(parent_style_sheet_); - visitor->Trace(style_sheet_); -} - -} // namespace blink
diff --git a/third_party/WebKit/Source/core/xml/XSLImportRule.h b/third_party/WebKit/Source/core/xml/XSLImportRule.h deleted file mode 100644 index 6a6e8dd..0000000 --- a/third_party/WebKit/Source/core/xml/XSLImportRule.h +++ /dev/null
@@ -1,68 +0,0 @@ -/* - * This file is part of the XSL implementation. - * - * Copyright (C) 2004, 2006, 2008 Apple Inc. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - * - */ - -#ifndef XSLImportRule_h -#define XSLImportRule_h - -#include "core/xml/XSLStyleSheet.h" -#include "platform/runtime_enabled_features.h" - -namespace blink { - -class XSLImportRule final : public GarbageCollectedFinalized<XSLImportRule> { - public: - static XSLImportRule* Create(XSLStyleSheet* parent_sheet, - const String& href) { - DCHECK(RuntimeEnabledFeatures::XSLTEnabled()); - return new XSLImportRule(parent_sheet, href); - } - - virtual ~XSLImportRule(); - virtual void Trace(blink::Visitor*); - - const String& Href() const { return str_href_; } - XSLStyleSheet* GetStyleSheet() const { return style_sheet_.Get(); } - - XSLStyleSheet* ParentStyleSheet() const { return parent_style_sheet_; } - void SetParentStyleSheet(XSLStyleSheet* style_sheet) { - parent_style_sheet_ = style_sheet; - } - - bool IsLoading(); - void LoadSheet(); - - private: - XSLImportRule(XSLStyleSheet* parent_sheet, const String& href); - - void SetXSLStyleSheet(const String& href, - const KURL& base_url, - const String& sheet); - - Member<XSLStyleSheet> parent_style_sheet_; - String str_href_; - Member<XSLStyleSheet> style_sheet_; - bool loading_; -}; - -} // namespace blink - -#endif // XSLImportRule_h
diff --git a/third_party/WebKit/Source/core/xml/XSLStyleSheet.h b/third_party/WebKit/Source/core/xml/XSLStyleSheet.h index 5bd05b1..8d495307 100644 --- a/third_party/WebKit/Source/core/xml/XSLStyleSheet.h +++ b/third_party/WebKit/Source/core/xml/XSLStyleSheet.h
@@ -32,16 +32,8 @@ namespace blink { -class XSLImportRule; - class XSLStyleSheet final : public StyleSheet { public: - static XSLStyleSheet* Create(XSLImportRule* parent_import, - const String& original_url, - const KURL& final_url) { - DCHECK(RuntimeEnabledFeatures::XSLTEnabled()); - return new XSLStyleSheet(parent_import, original_url, final_url); - } static XSLStyleSheet* Create(ProcessingInstruction* parent_node, const String& original_url, const KURL& final_url) { @@ -73,16 +65,10 @@ void CheckLoaded(); - const KURL& FinalURL() const { return final_url_; } - - void LoadChildSheets(); - void LoadChildSheet(const String& href); - Document* OwnerDocument(); XSLStyleSheet* parentStyleSheet() const override { return parent_style_sheet_; } - void SetParentStyleSheet(XSLStyleSheet*); xmlDocPtr GetDocument(); xsltStylesheetPtr CompileStyleSheet(); @@ -103,7 +89,7 @@ void ClearOwnerNode() override { owner_node_ = nullptr; } KURL BaseURL() const override { return final_url_; } - bool IsLoading() const override; + bool IsLoading() const override { return false; } virtual void Trace(blink::Visitor*); @@ -117,16 +103,19 @@ const String& original_url, const KURL& final_url, bool embedded); - XSLStyleSheet(XSLImportRule* parent_import, + XSLStyleSheet(XSLStyleSheet* parent_style_sheet, const String& original_url, const KURL& final_url); + void LoadChildSheets(); + void LoadChildSheet(const String& href); + Member<Node> owner_node_; String original_url_; KURL final_url_; bool is_disabled_; - HeapVector<Member<XSLImportRule>> children_; + HeapVector<Member<XSLStyleSheet>> children_; bool embedded_; bool processed_;
diff --git a/third_party/WebKit/Source/core/xml/XSLStyleSheetLibxslt.cpp b/third_party/WebKit/Source/core/xml/XSLStyleSheetLibxslt.cpp index e7578608..a8a4aa7 100644 --- a/third_party/WebKit/Source/core/xml/XSLStyleSheetLibxslt.cpp +++ b/third_party/WebKit/Source/core/xml/XSLStyleSheetLibxslt.cpp
@@ -27,15 +27,17 @@ #include "core/dom/Node.h" #include "core/dom/TransformSource.h" #include "core/frame/LocalFrame.h" -#include "core/xml/XSLImportRule.h" +#include "core/loader/resource/XSLStyleSheetResource.h" #include "core/xml/XSLTProcessor.h" #include "core/xml/parser/XMLDocumentParserScope.h" #include "core/xml/parser/XMLParserInput.h" +#include "platform/loader/fetch/FetchParameters.h" +#include "platform/loader/fetch/fetch_initiator_type_names.h" #include "platform/wtf/text/CString.h" namespace blink { -XSLStyleSheet::XSLStyleSheet(XSLImportRule* parent_rule, +XSLStyleSheet::XSLStyleSheet(XSLStyleSheet* parent_style_sheet, const String& original_url, const KURL& final_url) : owner_node_(nullptr), @@ -49,8 +51,7 @@ stylesheet_doc_(nullptr), stylesheet_doc_taken_(false), compilation_failed_(false), - parent_style_sheet_(parent_rule ? parent_rule->ParentStyleSheet() - : nullptr), + parent_style_sheet_(parent_style_sheet), owner_document_(nullptr) {} XSLStyleSheet::XSLStyleSheet(Node* parent_node, @@ -91,17 +92,7 @@ xmlFreeDoc(stylesheet_doc_); } -bool XSLStyleSheet::IsLoading() const { - for (unsigned i = 0; i < children_.size(); ++i) { - if (children_.at(i)->IsLoading()) - return true; - } - return false; -} - void XSLStyleSheet::CheckLoaded() { - if (IsLoading()) - return; if (XSLStyleSheet* style_sheet = parentStyleSheet()) style_sheet->CheckLoaded(); if (ownerNode()) @@ -116,11 +107,8 @@ void XSLStyleSheet::ClearDocuments() { stylesheet_doc_ = nullptr; - for (unsigned i = 0; i < children_.size(); ++i) { - XSLImportRule* import = children_.at(i).Get(); - if (import->GetStyleSheet()) - import->GetStyleSheet()->ClearDocuments(); - } + for (unsigned i = 0; i < children_.size(); ++i) + children_.at(i)->ClearDocuments(); } bool XSLStyleSheet::ParseString(const String& source) { @@ -155,7 +143,7 @@ stylesheet_doc_ = xmlCtxtReadMemory(ctxt, input.Data(), input.size(), - FinalURL().GetString().Utf8().data(), input.Encoding(), + final_url_.GetString().Utf8().data(), input.Encoding(), XML_PARSE_NOENT | XML_PARSE_DTDATTR | XML_PARSE_NOWARNING | XML_PARSE_NOCDATA); @@ -179,7 +167,7 @@ // We have to locate (by ID) the appropriate embedded stylesheet // element, so that we can walk the import/include list. xmlAttrPtr id_node = xmlGetID( - GetDocument(), (const xmlChar*)(FinalURL().GetString().Utf8().data())); + GetDocument(), (const xmlChar*)(final_url_.GetString().Utf8().data())); if (!id_node) return; stylesheet_root = id_node->parent; @@ -223,9 +211,33 @@ } void XSLStyleSheet::LoadChildSheet(const String& href) { - XSLImportRule* child_rule = XSLImportRule::Create(this, href); - children_.push_back(child_rule); - child_rule->LoadSheet(); + // Use parent styleheet's URL as the base URL + KURL url(BaseURL(), href); + + // Check for a cycle in our import chain. If we encounter a stylesheet in + // our parent chain with the same URL, then just bail. + for (XSLStyleSheet* parent_sheet = parentStyleSheet(); parent_sheet; + parent_sheet = parent_sheet->parentStyleSheet()) { + if (url == parent_sheet->BaseURL()) + return; + } + + const String& url_string = url.GetString(); + ResourceLoaderOptions fetch_options; + fetch_options.initiator_info.name = FetchInitiatorTypeNames::xml; + FetchParameters params( + ResourceRequest(OwnerDocument()->CompleteURL(url_string)), fetch_options); + params.SetOriginRestriction(FetchParameters::kRestrictToSameOrigin); + XSLStyleSheetResource* resource = XSLStyleSheetResource::FetchSynchronously( + params, OwnerDocument()->Fetcher()); + if (!resource || !resource->Sheet()) + return; + + XSLStyleSheet* style_sheet = + new XSLStyleSheet(this, url_string, resource->GetResponse().Url()); + children_.push_back(style_sheet); + style_sheet->ParseString(resource->Sheet()); + CheckLoaded(); } xsltStylesheetPtr XSLStyleSheet::CompileStyleSheet() { @@ -249,10 +261,6 @@ return result; } -void XSLStyleSheet::SetParentStyleSheet(XSLStyleSheet* parent) { - parent_style_sheet_ = parent; -} - Document* XSLStyleSheet::OwnerDocument() { for (XSLStyleSheet* style_sheet = this; style_sheet; style_sheet = style_sheet->parentStyleSheet()) { @@ -269,10 +277,7 @@ const xmlChar* uri) { bool matched_parent = (parent_doc == GetDocument()); for (unsigned i = 0; i < children_.size(); ++i) { - XSLImportRule* import = children_.at(i).Get(); - XSLStyleSheet* child = import->GetStyleSheet(); - if (!child) - continue; + XSLStyleSheet* child = children_.at(i).Get(); if (matched_parent) { if (child->Processed()) continue; // libxslt has been given this sheet already. @@ -281,7 +286,7 @@ // In order to ensure that libxml canonicalized both URLs, we get // the original href string from the import rule and canonicalize it // using libxml before comparing it with the URI argument. - CString import_href = import->Href().Utf8(); + CString import_href = child->href().Utf8(); xmlChar* base = xmlNodeGetBase(parent_doc, (xmlNodePtr)parent_doc); xmlChar* child_uri = xmlBuildURI((const xmlChar*)import_href.data(), base); @@ -294,8 +299,7 @@ } continue; } - xmlDocPtr result = - import->GetStyleSheet()->LocateStylesheetSubResource(parent_doc, uri); + xmlDocPtr result = child->LocateStylesheetSubResource(parent_doc, uri); if (result) return result; }
diff --git a/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequest.idl b/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequest.idl index 5fdbc94a..433a2ba 100644 --- a/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequest.idl +++ b/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequest.idl
@@ -37,8 +37,6 @@ "text", }; -// TODO(foolip, gyuyoung): getResponseHeader, setRequestHeader, and open should -// be replaced with ByteString or USVString. [ ActiveScriptWrappable, Constructor, @@ -58,8 +56,8 @@ // request [RaisesException] void open(ByteString method, USVString url); - [RaisesException] void open(ByteString method, USVString url, boolean async, optional DOMString? username = null, optional DOMString? password = null); - [RaisesException] void setRequestHeader(DOMString name, DOMString value); + [RaisesException] void open(ByteString method, USVString url, boolean async, optional USVString? username = null, optional USVString? password = null); + [RaisesException] void setRequestHeader(ByteString name, ByteString value); [RaisesException=Setter] attribute unsigned long timeout; [RaisesException=Setter] attribute boolean withCredentials; readonly attribute XMLHttpRequestUpload upload; @@ -72,8 +70,8 @@ readonly attribute USVString responseURL; readonly attribute unsigned short status; readonly attribute ByteString statusText; - DOMString? getResponseHeader(DOMString name); - DOMString getAllResponseHeaders(); + ByteString? getResponseHeader(ByteString name); + ByteString getAllResponseHeaders(); [RaisesException] void overrideMimeType(DOMString mime); [RaisesException=Setter] attribute XMLHttpRequestResponseType responseType; [Custom=Getter, RaisesException=Getter] readonly attribute any response;
diff --git a/third_party/WebKit/Source/devtools/front_end/common/ResourceType.js b/third_party/WebKit/Source/devtools/front_end/common/ResourceType.js index bb3eb9a..e658e01 100644 --- a/third_party/WebKit/Source/devtools/front_end/common/ResourceType.js +++ b/third_party/WebKit/Source/devtools/front_end/common/ResourceType.js
@@ -258,7 +258,7 @@ Common.ResourceType._mimeTypeByExtension = new Map([ // Web extensions ['js', 'text/javascript'], ['css', 'text/css'], ['html', 'text/html'], ['htm', 'text/html'], - ['xml', 'application/xml'], ['xsl', 'application/xml'], + ['mjs', 'text/javascript'], ['xml', 'application/xml'], ['xsl', 'application/xml'], // HTML Embedded Scripts, ASP], JSP ['asp', 'application/x-aspx'], ['aspx', 'application/x-aspx'], ['jsp', 'application/x-jsp'],
diff --git a/third_party/WebKit/Source/devtools/front_end/layers/LayerTreeModel.js b/third_party/WebKit/Source/devtools/front_end/layers/LayerTreeModel.js index 54fed9b4..dfc66e95 100644 --- a/third_party/WebKit/Source/devtools/front_end/layers/LayerTreeModel.js +++ b/third_party/WebKit/Source/devtools/front_end/layers/LayerTreeModel.js
@@ -44,6 +44,7 @@ } /** @type {?SDK.LayerTreeBase} */ this._layerTree = null; + this._throttler = new Common.Throttler(20); } disable() { @@ -80,6 +81,13 @@ async _layerTreeChanged(layers) { if (!this._enabled) return; + this._throttler.schedule(this._innerSetLayers.bind(this, layers)); + } + + /** + * @param {?Array.<!Protocol.LayerTree.Layer>} layers + */ + async _innerSetLayers(layers) { var layerTree = /** @type {!Layers.AgentLayerTree} */ (this._layerTree); await layerTree.setLayers(layers);
diff --git a/third_party/WebKit/Source/devtools/front_end/persistence/FileSystemWorkspaceBinding.js b/third_party/WebKit/Source/devtools/front_end/persistence/FileSystemWorkspaceBinding.js index b5401407..578aecd 100644 --- a/third_party/WebKit/Source/devtools/front_end/persistence/FileSystemWorkspaceBinding.js +++ b/third_party/WebKit/Source/devtools/front_end/persistence/FileSystemWorkspaceBinding.js
@@ -195,7 +195,7 @@ Persistence.FileSystemWorkspaceBinding._documentExtensions = new Set(['htm', 'html', 'asp', 'aspx', 'phtml', 'jsp']); Persistence.FileSystemWorkspaceBinding._scriptExtensions = new Set([ 'asp', 'aspx', 'c', 'cc', 'cljs', 'coffee', 'cpp', 'cs', 'dart', 'java', 'js', - 'jsp', 'jsx', 'h', 'm', 'mm', 'py', 'sh', 'ts', 'tsx', 'ls' + 'jsp', 'jsx', 'h', 'm', 'mjs', 'mm', 'py', 'sh', 'ts', 'tsx', 'ls' ]); Persistence.FileSystemWorkspaceBinding._imageExtensions = Persistence.IsolatedFileSystem.ImageExtensions;
diff --git a/third_party/WebKit/Source/devtools/front_end/persistence/editFileSystemView.css b/third_party/WebKit/Source/devtools/front_end/persistence/editFileSystemView.css index a6de783..ae99688 100644 --- a/third_party/WebKit/Source/devtools/front_end/persistence/editFileSystemView.css +++ b/third_party/WebKit/Source/devtools/front_end/persistence/editFileSystemView.css
@@ -13,7 +13,7 @@ } .file-system-header-text { - flex: auto; + flex: 1 0 auto; } .add-button {
diff --git a/third_party/WebKit/Source/devtools/front_end/resources/ServiceWorkersView.js b/third_party/WebKit/Source/devtools/front_end/resources/ServiceWorkersView.js index c08e9aa1..b91d5af 100644 --- a/third_party/WebKit/Source/devtools/front_end/resources/ServiceWorkersView.js +++ b/third_party/WebKit/Source/devtools/front_end/resources/ServiceWorkersView.js
@@ -10,6 +10,7 @@ this.registerRequiredCSS('resources/serviceWorkersView.css'); this._currentWorkersView = new UI.ReportView(Common.UIString('Service Workers')); + this._currentWorkersView.setBodyScrollable(false); this.contentElement.classList.add('service-worker-list'); this._currentWorkersView.show(this.contentElement); this._currentWorkersView.element.classList.add('service-workers-this-origin'); @@ -43,6 +44,7 @@ toolbar.appendToolbarItem(this._filter); this._otherWorkersView = new UI.ReportView(); + this._otherWorkersView.setBodyScrollable(false); this._otherWorkersView.show(this._otherWorkers); this._otherWorkersView.element.classList.add('service-workers-for-other-origins');
diff --git a/third_party/WebKit/Source/devtools/front_end/resources/serviceWorkersView.css b/third_party/WebKit/Source/devtools/front_end/resources/serviceWorkersView.css index 02d9db7ed..f21dc9d 100644 --- a/third_party/WebKit/Source/devtools/front_end/resources/serviceWorkersView.css +++ b/third_party/WebKit/Source/devtools/front_end/resources/serviceWorkersView.css
@@ -114,6 +114,7 @@ .service-worker-list { background-color: #f9f9f9; + overflow: auto; } .service-workers-this-origin { @@ -121,13 +122,6 @@ flex-grow: 0; } -.service-workers-other-origin { - display: flex; - flex-direction: column; - flex-grow: 1; - flex-shrink: 1; -} - .service-worker-has-current .service-workers-other-origin { margin-top: 16px; border-top: 1px solid rgb(230, 230, 230) @@ -137,6 +131,12 @@ display: none; } +.service-workers-this-origin, +.service-worker-filter, +.service-workers-other-origin { + min-width: 400px; +} + .service-worker-filter{ padding: 16px 20px 12px 12px; flex-grow: 0;
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/EmulationModel.js b/third_party/WebKit/Source/devtools/front_end/sdk/EmulationModel.js index 74227a0..94cfed04 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/EmulationModel.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/EmulationModel.js
@@ -175,7 +175,7 @@ var splitPosition = splitError[0].split('@'); if (splitPosition.length === 2) { return new SDK.EmulationModel.Geolocation( - parseFloat(splitPosition[0]), parseFloat(splitPosition[1]), splitError[1]); + parseFloat(splitPosition[0]), parseFloat(splitPosition[1]), !!splitError[1]); } } } @@ -225,9 +225,7 @@ * @return {string} */ toSetting() { - return (typeof this.latitude === 'number' && typeof this.longitude === 'number' && typeof this.error === 'string') ? - this.latitude + '@' + this.longitude + ':' + this.error : - ''; + return this.latitude + '@' + this.longitude + ':' + (this.error || ''); } };
diff --git a/third_party/WebKit/Source/devtools/front_end/settings/frameworkBlackboxSettingsTab.css b/third_party/WebKit/Source/devtools/front_end/settings/frameworkBlackboxSettingsTab.css index c0d004a..cf607ac5 100644 --- a/third_party/WebKit/Source/devtools/front_end/settings/frameworkBlackboxSettingsTab.css +++ b/third_party/WebKit/Source/devtools/front_end/settings/frameworkBlackboxSettingsTab.css
@@ -61,6 +61,7 @@ .blackbox-pattern { flex: auto; + min-width: 100px; } .blackbox-list-item.blackbox-disabled .blackbox-pattern {
diff --git a/third_party/WebKit/Source/devtools/front_end/settings/settingsScreen.css b/third_party/WebKit/Source/devtools/front_end/settings/settingsScreen.css index 8f4bc538..c37cdde 100644 --- a/third_party/WebKit/Source/devtools/front_end/settings/settingsScreen.css +++ b/third_party/WebKit/Source/devtools/front_end/settings/settingsScreen.css
@@ -113,6 +113,7 @@ .settings-tab label { padding-right: 4px; display: inline-flex; + flex-shrink: 0; } #general-tab-content .help-block fieldset legend {
diff --git a/third_party/WebKit/Source/devtools/front_end/test_runner/TestRunner.js b/third_party/WebKit/Source/devtools/front_end/test_runner/TestRunner.js index 07ee3f3..e54bae2 100644 --- a/third_party/WebKit/Source/devtools/front_end/test_runner/TestRunner.js +++ b/third_party/WebKit/Source/devtools/front_end/test_runner/TestRunner.js
@@ -351,14 +351,33 @@ TestRunner.mainTarget = target; }; +/** + * @param {string} code + * @return {!Promise<*>} + */ +TestRunner.evaluateInPageRemoteObject = async function(code) { + var response = await TestRunner._evaluateInPage(code); + return TestRunner.runtimeModel.createRemoteObject(response.result); +}; + +/** + * @param {string} code + * @param {function(*, !Protocol.Runtime.ExceptionDetails=):void} callback + */ +TestRunner.evaluateInPage = async function(code, callback) { + var response = await TestRunner._evaluateInPage(code); + TestRunner.safeWrap(callback)(response.result.value, response.exceptionDetails); +}; + /** @type {number} */ TestRunner._evaluateInPageCounter = 0; /** - * @param {string|!Function} code - * @param {!Function} callback + * @param {string} code + * @return {!Promise<{response: !SDK.RemoteObject, + * exceptionDetails: (!Protocol.Runtime.ExceptionDetails|undefined)}>} */ -TestRunner.evaluateInPage = async function(code, callback) { +TestRunner._evaluateInPage = async function(code) { var lines = new Error().stack.split('at '); // Handles cases where the function is safe wrapped @@ -374,22 +393,25 @@ if (code.indexOf('sourceURL=') === -1) code += `//# sourceURL=${sourceURL}`; var response = await TestRunner.RuntimeAgent.invoke_evaluate({expression: code, objectGroup: 'console'}); - if (!response[Protocol.Error]) { - TestRunner.safeWrap(callback)( - TestRunner.runtimeModel.createRemoteObject(response.result), response.exceptionDetails); + var error = response[Protocol.Error]; + if (error) { + TestRunner.addResult('Error: ' + error); + TestRunner.completeTest(); + return; } + return response; }; /** * Doesn't append sourceURL to snippets evaluated in inspected page * to avoid churning test expectations * @param {string} code - * @return {!Promise<undefined>} + * @return {!Promise<*>} */ TestRunner.evaluateInPageAnonymously = async function(code) { var response = await TestRunner.RuntimeAgent.invoke_evaluate({expression: code, objectGroup: 'console'}); if (!response[Protocol.Error]) - return Promise.resolve(); + return response.result.value; TestRunner.addResult( 'Error: ' + (response.exceptionDetails && response.exceptionDetails.text || 'exception from evaluateInPageAnonymously.')); @@ -397,8 +419,8 @@ }; /** - * @param {string|!Function} code - * @return {!Promise<!SDK.RemoteObject>} + * @param {string} code + * @return {!Promise<*>} */ TestRunner.evaluateInPagePromise = function(code) { return new Promise(success => TestRunner.evaluateInPage(code, success)); @@ -406,7 +428,7 @@ /** * @param {string} code - * @return {!Promise<!SDK.RemoteObject|undefined>} + * @return {!Promise<*>} */ TestRunner.evaluateInPageAsync = async function(code) { var response = await TestRunner.RuntimeAgent.invoke_evaluate( @@ -414,7 +436,7 @@ var error = response[Protocol.Error]; if (!error && !response.exceptionDetails) - return TestRunner.runtimeModel.createRemoteObject(response.result); + return response.result.value; TestRunner.addResult( 'Error: ' + (error || response.exceptionDetails && response.exceptionDetails.text || 'exception while evaluation in page.')); @@ -424,7 +446,7 @@ /** * @param {string} name * @param {!Array<*>} args - * @return {!Promise<!SDK.RemoteObject|undefined>} + * @return {!Promise<*>} */ TestRunner.callFunctionInPageAsync = function(name, args) { args = args || []; @@ -483,7 +505,7 @@ * are relative to the test file and not the inspected page * (i.e. http/tests/devtools/resources/inspected-page.html). * @param {string} html - * @return {!Promise<undefined>} + * @return {!Promise<*>} */ TestRunner.loadHTML = function(html) { if (!html.includes('<base')) { @@ -501,7 +523,7 @@ /** * @param {string} path - * @return {!Promise<!SDK.RemoteObject|undefined>} + * @return {!Promise<*>} */ TestRunner.addScriptTag = function(path) { return TestRunner.evaluateInPageAsync(` @@ -516,7 +538,7 @@ /** * @param {string} path - * @return {!Promise<!SDK.RemoteObject|undefined>} + * @return {!Promise<*>} */ TestRunner.addStylesheetTag = function(path) { return TestRunner.evaluateInPageAsync(` @@ -541,7 +563,7 @@ /** * @param {string} path * @param {!Object|undefined} options - * @return {!Promise<!SDK.RemoteObject|undefined>} + * @return {!Promise<*>} */ TestRunner.addIframe = function(path, options = {}) { options.id = options.id || ''; @@ -1279,8 +1301,8 @@ * @param {string} querySelector */ TestRunner.dumpInspectedPageElementText = async function(querySelector) { - var remoteObject = await TestRunner.evaluateInPageAsync(`document.querySelector('${querySelector}').innerText`); - TestRunner.addResult(remoteObject.value); + var value = await TestRunner.evaluateInPageAsync(`document.querySelector('${querySelector}').innerText`); + TestRunner.addResult(value); }; /** @type {boolean} */
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/ReportView.js b/third_party/WebKit/Source/devtools/front_end/ui/ReportView.js index d66ea3b..22aed1b6 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/ReportView.js +++ b/third_party/WebKit/Source/devtools/front_end/ui/ReportView.js
@@ -12,12 +12,12 @@ super(true); this.registerRequiredCSS('ui/reportView.css'); - var contentBox = this.contentElement.createChild('div', 'report-content-box'); - this._headerElement = contentBox.createChild('div', 'report-header vbox'); + this._contentBox = this.contentElement.createChild('div', 'report-content-box'); + this._headerElement = this._contentBox.createChild('div', 'report-header vbox'); this._titleElement = this._headerElement.createChild('div', 'report-title'); this._titleElement.textContent = title; - this._sectionList = contentBox.createChild('div', 'vbox'); + this._sectionList = this._contentBox.createChild('div', 'vbox'); } /** @@ -92,6 +92,14 @@ setHeaderVisible(visible) { this._headerElement.classList.toggle('hidden', !visible); } + + + /** + * @param {boolean} scrollable + */ + setBodyScrollable(scrollable) { + this._contentBox.classList.toggle('no-scroll', !scrollable); + } }; /**
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/listWidget.css b/third_party/WebKit/Source/devtools/front_end/ui/listWidget.css index c14b144..b1680a3e 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/listWidget.css +++ b/third_party/WebKit/Source/devtools/front_end/ui/listWidget.css
@@ -22,6 +22,7 @@ display: flex; align-items: center; position: relative; + overflow: hidden; } .list-item:hover {
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/reportView.css b/third_party/WebKit/Source/devtools/front_end/ui/reportView.css index cb45d73..50c2f2f 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/reportView.css +++ b/third_party/WebKit/Source/devtools/front_end/ui/reportView.css
@@ -14,6 +14,10 @@ overflow: auto; } +.report-content-box.no-scroll { + overflow: visible; +} + .report-header { border-bottom: 1px solid rgb(230, 230, 230); padding: 12px 24px;
diff --git a/third_party/WebKit/Source/modules/ModulesInitializer.cpp b/third_party/WebKit/Source/modules/ModulesInitializer.cpp index 99e3ca2..80fcbf8 100644 --- a/third_party/WebKit/Source/modules/ModulesInitializer.cpp +++ b/third_party/WebKit/Source/modules/ModulesInitializer.cpp
@@ -68,7 +68,6 @@ #include "modules/remoteplayback/RemotePlayback.h" #include "modules/screen_orientation/ScreenOrientationControllerImpl.h" #include "modules/serviceworkers/NavigatorServiceWorker.h" -#include "modules/serviceworkers/ServiceWorkerLinkResource.h" #include "modules/speech/SpeechRecognitionClientProxy.h" #include "modules/storage/DOMWindowStorageController.h" #include "modules/storage/InspectorDOMStorageAgent.h" @@ -211,11 +210,6 @@ } } -LinkResource* ModulesInitializer::CreateServiceWorkerLinkResource( - HTMLLinkElement* owner) const { - return ServiceWorkerLinkResource::Create(owner); -} - void ModulesInitializer::OnClearWindowObjectInMainWorld( Document& document, const Settings& settings) const {
diff --git a/third_party/WebKit/Source/modules/ModulesInitializer.h b/third_party/WebKit/Source/modules/ModulesInitializer.h index faa34b4..7febcca 100644 --- a/third_party/WebKit/Source/modules/ModulesInitializer.h +++ b/third_party/WebKit/Source/modules/ModulesInitializer.h
@@ -29,8 +29,6 @@ InspectorDOMAgent*, InspectedFrames*, Page*) const override; - LinkResource* CreateServiceWorkerLinkResource( - HTMLLinkElement*) const override; void OnClearWindowObjectInMainWorld(Document&, const Settings&) const override; std::unique_ptr<WebMediaPlayer> CreateWebMediaPlayer(
diff --git a/third_party/WebKit/Source/modules/accessibility/AXImageMapLink.cpp b/third_party/WebKit/Source/modules/accessibility/AXImageMapLink.cpp index 27e7d4e..0f1f11d 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXImageMapLink.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXImageMapLink.cpp
@@ -97,10 +97,10 @@ return AreaElement()->Href(); } -void AXImageMapLink::GetRelativeBounds( - AXObject** out_container, - FloatRect& out_bounds_in_container, - SkMatrix44& out_container_transform) const { +void AXImageMapLink::GetRelativeBounds(AXObject** out_container, + FloatRect& out_bounds_in_container, + SkMatrix44& out_container_transform, + bool* clips_children) const { *out_container = nullptr; out_bounds_in_container = FloatRect(); out_container_transform.setIdentity();
diff --git a/third_party/WebKit/Source/modules/accessibility/AXImageMapLink.h b/third_party/WebKit/Source/modules/accessibility/AXImageMapLink.h index 1313146..ea2ac74 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXImageMapLink.h +++ b/third_party/WebKit/Source/modules/accessibility/AXImageMapLink.h
@@ -63,7 +63,8 @@ AXObject* ComputeParent() const override; void GetRelativeBounds(AXObject** out_container, FloatRect& out_bounds_in_container, - SkMatrix44& out_container_transform) const override; + SkMatrix44& out_container_transform, + bool* clips_children = nullptr) const override; private: bool IsImageMapLink() const override { return true; }
diff --git a/third_party/WebKit/Source/modules/accessibility/AXInlineTextBox.cpp b/third_party/WebKit/Source/modules/accessibility/AXInlineTextBox.cpp index 372cc431..f27da6e3 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXInlineTextBox.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXInlineTextBox.cpp
@@ -56,10 +56,10 @@ inline_text_box_ = nullptr; } -void AXInlineTextBox::GetRelativeBounds( - AXObject** out_container, - FloatRect& out_bounds_in_container, - SkMatrix44& out_container_transform) const { +void AXInlineTextBox::GetRelativeBounds(AXObject** out_container, + FloatRect& out_bounds_in_container, + SkMatrix44& out_container_transform, + bool* clips_children) const { *out_container = nullptr; out_bounds_in_container = FloatRect(); out_container_transform.setIdentity();
diff --git a/third_party/WebKit/Source/modules/accessibility/AXInlineTextBox.h b/third_party/WebKit/Source/modules/accessibility/AXInlineTextBox.h index 435a90e32..b2c81041 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXInlineTextBox.h +++ b/third_party/WebKit/Source/modules/accessibility/AXInlineTextBox.h
@@ -61,7 +61,8 @@ void GetWordBoundaries(Vector<AXRange>&) const override; void GetRelativeBounds(AXObject** out_container, FloatRect& out_bounds_in_container, - SkMatrix44& out_container_transform) const override; + SkMatrix44& out_container_transform, + bool* clips_children = nullptr) const override; AXObject* ComputeParent() const override; AccessibilityTextDirection GetTextDirection() const override; Node* GetNode() const override;
diff --git a/third_party/WebKit/Source/modules/accessibility/AXMenuListOption.cpp b/third_party/WebKit/Source/modules/accessibility/AXMenuListOption.cpp index 3766ff3..ab7199bb 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXMenuListOption.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXMenuListOption.cpp
@@ -132,10 +132,10 @@ return AccessibilityIsIgnoredByDefault(ignored_reasons); } -void AXMenuListOption::GetRelativeBounds( - AXObject** out_container, - FloatRect& out_bounds_in_container, - SkMatrix44& out_container_transform) const { +void AXMenuListOption::GetRelativeBounds(AXObject** out_container, + FloatRect& out_bounds_in_container, + SkMatrix44& out_container_transform, + bool* clips_children) const { *out_container = nullptr; out_bounds_in_container = FloatRect(); out_container_transform.setIdentity(); @@ -150,7 +150,7 @@ return; DCHECK(grandparent->IsMenuList()); grandparent->GetRelativeBounds(out_container, out_bounds_in_container, - out_container_transform); + out_container_transform, clips_children); } String AXMenuListOption::TextAlternative(bool recursive,
diff --git a/third_party/WebKit/Source/modules/accessibility/AXMenuListOption.h b/third_party/WebKit/Source/modules/accessibility/AXMenuListOption.h index 1bf407d..8bbcf7c4 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXMenuListOption.h +++ b/third_party/WebKit/Source/modules/accessibility/AXMenuListOption.h
@@ -65,7 +65,8 @@ void GetRelativeBounds(AXObject** out_container, FloatRect& out_bounds_in_container, - SkMatrix44& out_container_transform) const override; + SkMatrix44& out_container_transform, + bool* clips_children = nullptr) const override; String TextAlternative(bool recursive, bool in_aria_labelled_by_traversal, AXObjectSet& visited,
diff --git a/third_party/WebKit/Source/modules/accessibility/AXNodeObject.cpp b/third_party/WebKit/Source/modules/accessibility/AXNodeObject.cpp index 9e90cd83..49d4a7a 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXNodeObject.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXNodeObject.cpp
@@ -1886,13 +1886,13 @@ return false; } -void AXNodeObject::GetRelativeBounds( - AXObject** out_container, - FloatRect& out_bounds_in_container, - SkMatrix44& out_container_transform) const { +void AXNodeObject::GetRelativeBounds(AXObject** out_container, + FloatRect& out_bounds_in_container, + SkMatrix44& out_container_transform, + bool* clips_children) const { if (LayoutObjectForRelativeBounds()) { AXObject::GetRelativeBounds(out_container, out_bounds_in_container, - out_container_transform); + out_container_transform, clips_children); return; } @@ -1921,7 +1921,8 @@ if (AXObject* obj = AXObjectCache().Get(&child)) { AXObject* container; FloatRect bounds; - obj->GetRelativeBounds(&container, bounds, out_container_transform); + obj->GetRelativeBounds(&container, bounds, out_container_transform, + clips_children); if (container) { *out_container = container; rects.push_back(bounds); @@ -1944,7 +1945,8 @@ position_provider = position_provider->ParentObject()) { if (position_provider->IsAXLayoutObject()) { position_provider->GetRelativeBounds( - out_container, out_bounds_in_container, out_container_transform); + out_container, out_bounds_in_container, out_container_transform, + clips_children); if (*out_container) out_bounds_in_container.SetSize( FloatSize(out_bounds_in_container.Width(),
diff --git a/third_party/WebKit/Source/modules/accessibility/AXNodeObject.h b/third_party/WebKit/Source/modules/accessibility/AXNodeObject.h index 8eb55a3..b12b88c 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXNodeObject.h +++ b/third_party/WebKit/Source/modules/accessibility/AXNodeObject.h
@@ -176,7 +176,8 @@ // Location void GetRelativeBounds(AXObject** out_container, FloatRect& out_bounds_in_container, - SkMatrix44& out_container_transform) const override; + SkMatrix44& out_container_transform, + bool* clips_children = nullptr) const override; // High-level accessibility tree access. AXObject* ComputeParent() const override;
diff --git a/third_party/WebKit/Source/modules/accessibility/AXObject.cpp b/third_party/WebKit/Source/modules/accessibility/AXObject.cpp index de40d34..0a2d78f 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXObject.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXObject.cpp
@@ -1895,7 +1895,8 @@ void AXObject::GetRelativeBounds(AXObject** out_container, FloatRect& out_bounds_in_container, - SkMatrix44& out_container_transform) const { + SkMatrix44& out_container_transform, + bool* clips_children) const { *out_container = nullptr; out_bounds_in_container = FloatRect(); out_container_transform.setIdentity(); @@ -1916,6 +1917,13 @@ if (!layout_object) return; + if (clips_children) { + if (IsWebArea()) + *clips_children = true; + else + *clips_children = layout_object->HasOverflowClip(); + } + if (IsWebArea()) { if (layout_object->GetFrame()->View()) { out_bounds_in_container.SetSize(
diff --git a/third_party/WebKit/Source/modules/accessibility/AXObject.h b/third_party/WebKit/Source/modules/accessibility/AXObject.h index ad8f7f8..12bd3e2 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXObject.h +++ b/third_party/WebKit/Source/modules/accessibility/AXObject.h
@@ -659,9 +659,12 @@ // not null, walk up to its container and offset by the container's offset // from origin, the container's scroll position if any, and apply the // container's transform. Do this until you reach the root of the tree. + // If the object clips its children, for example by having overflow:hidden, + // set |clips_children| to true. virtual void GetRelativeBounds(AXObject** out_container, FloatRect& out_bounds_in_container, - SkMatrix44& out_container_transform) const; + SkMatrix44& out_container_transform, + bool* clips_children = nullptr) const; // Get the bounds in frame-relative coordinates as a LayoutRect. LayoutRect GetBoundsInFrameCoordinates() const;
diff --git a/third_party/WebKit/Source/modules/accessibility/AXSpinButton.cpp b/third_party/WebKit/Source/modules/accessibility/AXSpinButton.cpp index 2e3ad48..9de9314 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXSpinButton.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXSpinButton.cpp
@@ -101,10 +101,10 @@ return new AXSpinButtonPart(ax_object_cache); } -void AXSpinButtonPart::GetRelativeBounds( - AXObject** out_container, - FloatRect& out_bounds_in_container, - SkMatrix44& out_container_transform) const { +void AXSpinButtonPart::GetRelativeBounds(AXObject** out_container, + FloatRect& out_bounds_in_container, + SkMatrix44& out_container_transform, + bool* clips_children) const { *out_container = nullptr; out_bounds_in_container = FloatRect(); out_container_transform.setIdentity(); @@ -114,6 +114,8 @@ // FIXME: This logic should exist in the layout tree or elsewhere, but there // is no relationship that exists that can be queried. + // Not passing |clips_children| here because even if some ancestor of the spin + // button clips its children we shouldn't clip children here. ParentObject()->GetRelativeBounds(out_container, out_bounds_in_container, out_container_transform); out_bounds_in_container = FloatRect(0, 0, out_bounds_in_container.Width(),
diff --git a/third_party/WebKit/Source/modules/accessibility/AXSpinButton.h b/third_party/WebKit/Source/modules/accessibility/AXSpinButton.h index c6fa60e..a40942a6 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXSpinButton.h +++ b/third_party/WebKit/Source/modules/accessibility/AXSpinButton.h
@@ -75,7 +75,8 @@ bool IsSpinButtonPart() const override { return true; } void GetRelativeBounds(AXObject** out_container, FloatRect& out_bounds_in_container, - SkMatrix44& out_container_transform) const override; + SkMatrix44& out_container_transform, + bool* clips_children = nullptr) const override; }; DEFINE_AX_OBJECT_TYPE_CASTS(AXSpinButton, IsNativeSpinButton());
diff --git a/third_party/WebKit/Source/modules/background_fetch/BackgroundFetchRegistration.cpp b/third_party/WebKit/Source/modules/background_fetch/BackgroundFetchRegistration.cpp index 93b993a..0a0aa3d 100644 --- a/third_party/WebKit/Source/modules/background_fetch/BackgroundFetchRegistration.cpp +++ b/third_party/WebKit/Source/modules/background_fetch/BackgroundFetchRegistration.cpp
@@ -20,15 +20,13 @@ unsigned long long upload_total, unsigned long long uploaded, unsigned long long download_total, - unsigned long long downloaded, - const String& title) + unsigned long long downloaded) : developer_id_(developer_id), unique_id_(unique_id), upload_total_(upload_total), uploaded_(uploaded), download_total_(download_total), downloaded_(downloaded), - title_(title), observer_binding_(this) {} BackgroundFetchRegistration::~BackgroundFetchRegistration() = default; @@ -84,10 +82,6 @@ return downloaded_; } -String BackgroundFetchRegistration::title() const { - return title_; -} - const AtomicString& BackgroundFetchRegistration::InterfaceName() const { return EventTargetNames::BackgroundFetchRegistration; }
diff --git a/third_party/WebKit/Source/modules/background_fetch/BackgroundFetchRegistration.h b/third_party/WebKit/Source/modules/background_fetch/BackgroundFetchRegistration.h index 7076740b..e0262f0 100644 --- a/third_party/WebKit/Source/modules/background_fetch/BackgroundFetchRegistration.h +++ b/third_party/WebKit/Source/modules/background_fetch/BackgroundFetchRegistration.h
@@ -34,8 +34,7 @@ unsigned long long upload_total, unsigned long long uploaded, unsigned long long download_total, - unsigned long long downloaded, - const String& title); + unsigned long long downloaded); ~BackgroundFetchRegistration() override; // Initializes the BackgroundFetchRegistration to be associated with the given @@ -62,9 +61,6 @@ ScriptPromise abort(ScriptState*); - // TODO(crbug.com/769770): Remove the following deprecated attributes. - String title() const; - // EventTargetWithInlineData implementation. const AtomicString& InterfaceName() const override; ExecutionContext* GetExecutionContext() const override; @@ -91,7 +87,6 @@ unsigned long long uploaded_; unsigned long long download_total_; unsigned long long downloaded_; - String title_; mojo::Binding<blink::mojom::blink::BackgroundFetchRegistrationObserver> observer_binding_;
diff --git a/third_party/WebKit/Source/modules/background_fetch/BackgroundFetchRegistration.idl b/third_party/WebKit/Source/modules/background_fetch/BackgroundFetchRegistration.idl index 235eb2b..6e50b5a 100644 --- a/third_party/WebKit/Source/modules/background_fetch/BackgroundFetchRegistration.idl +++ b/third_party/WebKit/Source/modules/background_fetch/BackgroundFetchRegistration.idl
@@ -21,5 +21,4 @@ // TODO(crbug.com/769770): Remove the following deprecated attributes. [ImplementedAs=downloadTotal] readonly attribute long totalDownloadSize; - readonly attribute DOMString title; };
diff --git a/third_party/WebKit/Source/modules/background_fetch/BackgroundFetchTypeConverters.cpp b/third_party/WebKit/Source/modules/background_fetch/BackgroundFetchTypeConverters.cpp index de4fe6f0..72e1204 100644 --- a/third_party/WebKit/Source/modules/background_fetch/BackgroundFetchTypeConverters.cpp +++ b/third_party/WebKit/Source/modules/background_fetch/BackgroundFetchTypeConverters.cpp
@@ -21,8 +21,7 @@ return new blink::BackgroundFetchRegistration( mojoRegistration->developer_id, mojoRegistration->unique_id, mojoRegistration->upload_total, mojoRegistration->uploaded, - mojoRegistration->download_total, mojoRegistration->downloaded, - mojoRegistration->title); + mojoRegistration->download_total, mojoRegistration->downloaded); } blink::mojom::blink::BackgroundFetchOptionsPtr TypeConverter<
diff --git a/third_party/WebKit/Source/modules/credentialmanager/AuthenticatorAssertionResponse.cpp b/third_party/WebKit/Source/modules/credentialmanager/AuthenticatorAssertionResponse.cpp index e1ceb22..5efc6b5 100644 --- a/third_party/WebKit/Source/modules/credentialmanager/AuthenticatorAssertionResponse.cpp +++ b/third_party/WebKit/Source/modules/credentialmanager/AuthenticatorAssertionResponse.cpp
@@ -9,24 +9,28 @@ AuthenticatorAssertionResponse* AuthenticatorAssertionResponse::Create( DOMArrayBuffer* client_data_json, DOMArrayBuffer* authenticator_data, - DOMArrayBuffer* signature) { - return new AuthenticatorAssertionResponse(client_data_json, - authenticator_data, signature); + DOMArrayBuffer* signature, + DOMArrayBuffer* user_handle) { + return new AuthenticatorAssertionResponse( + client_data_json, authenticator_data, signature, user_handle); } AuthenticatorAssertionResponse::AuthenticatorAssertionResponse( DOMArrayBuffer* client_data_json, DOMArrayBuffer* authenticator_data, - DOMArrayBuffer* signature) + DOMArrayBuffer* signature, + DOMArrayBuffer* user_handle) : AuthenticatorResponse(client_data_json), authenticator_data_(authenticator_data), - signature_(signature) {} + signature_(signature), + user_handle_(user_handle) {} AuthenticatorAssertionResponse::~AuthenticatorAssertionResponse() {} void AuthenticatorAssertionResponse::Trace(blink::Visitor* visitor) { visitor->Trace(authenticator_data_); visitor->Trace(signature_); + visitor->Trace(user_handle_); AuthenticatorResponse::Trace(visitor); }
diff --git a/third_party/WebKit/Source/modules/credentialmanager/AuthenticatorAssertionResponse.h b/third_party/WebKit/Source/modules/credentialmanager/AuthenticatorAssertionResponse.h index 96fa4df..3fffec5 100644 --- a/third_party/WebKit/Source/modules/credentialmanager/AuthenticatorAssertionResponse.h +++ b/third_party/WebKit/Source/modules/credentialmanager/AuthenticatorAssertionResponse.h
@@ -20,7 +20,8 @@ static AuthenticatorAssertionResponse* Create( DOMArrayBuffer* client_data_json, DOMArrayBuffer* authenticator_data, - DOMArrayBuffer* signature); + DOMArrayBuffer* signature, + DOMArrayBuffer* user_handle); virtual ~AuthenticatorAssertionResponse(); @@ -30,14 +31,18 @@ DOMArrayBuffer* signature() const { return signature_.Get(); } + DOMArrayBuffer* userHandle() const { return user_handle_.Get(); } + virtual void Trace(blink::Visitor*); private: explicit AuthenticatorAssertionResponse(DOMArrayBuffer* client_data_json, DOMArrayBuffer* authenticator_data, - DOMArrayBuffer* signature); + DOMArrayBuffer* signature, + DOMArrayBuffer* user_handle); const Member<DOMArrayBuffer> authenticator_data_; const Member<DOMArrayBuffer> signature_; + const Member<DOMArrayBuffer> user_handle_; }; } // namespace blink
diff --git a/third_party/WebKit/Source/modules/credentialmanager/AuthenticatorAssertionResponse.idl b/third_party/WebKit/Source/modules/credentialmanager/AuthenticatorAssertionResponse.idl index a88a613..ca29887 100644 --- a/third_party/WebKit/Source/modules/credentialmanager/AuthenticatorAssertionResponse.idl +++ b/third_party/WebKit/Source/modules/credentialmanager/AuthenticatorAssertionResponse.idl
@@ -2,12 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// https://www.w3.org/TR/2017/WD-webauthn-20170505/#authenticatorassertionresponse +// https://w3c.github.io/webauthn/#authenticatorassertionresponse [ RuntimeEnabled=WebAuth, - SecureContext + SecureContext, + Exposed=Window ] interface AuthenticatorAssertionResponse : AuthenticatorResponse { - readonly attribute ArrayBuffer authenticatorData; - readonly attribute ArrayBuffer signature; + [SameObject] readonly attribute ArrayBuffer authenticatorData; + [SameObject] readonly attribute ArrayBuffer signature; + [SameObject] readonly attribute ArrayBuffer userHandle; };
diff --git a/third_party/WebKit/Source/modules/credentialmanager/AuthenticatorAttestationResponse.idl b/third_party/WebKit/Source/modules/credentialmanager/AuthenticatorAttestationResponse.idl index f2035826..4205aed 100644 --- a/third_party/WebKit/Source/modules/credentialmanager/AuthenticatorAttestationResponse.idl +++ b/third_party/WebKit/Source/modules/credentialmanager/AuthenticatorAttestationResponse.idl
@@ -2,11 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// https://www.w3.org/TR/2017/WD-webauthn-20170505/#authenticatorattestationresponse +// https://w3c.github.io/webauthn/#authenticatorattestationresponse [ RuntimeEnabled=WebAuth, - SecureContext + SecureContext, + Exposed=Window ] interface AuthenticatorAttestationResponse : AuthenticatorResponse { - readonly attribute ArrayBuffer attestationObject; + [SameObject] readonly attribute ArrayBuffer attestationObject; };
diff --git a/third_party/WebKit/Source/modules/credentialmanager/AuthenticatorResponse.idl b/third_party/WebKit/Source/modules/credentialmanager/AuthenticatorResponse.idl index b10dc2e5..bdfa8a9 100644 --- a/third_party/WebKit/Source/modules/credentialmanager/AuthenticatorResponse.idl +++ b/third_party/WebKit/Source/modules/credentialmanager/AuthenticatorResponse.idl
@@ -2,11 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// https://www.w3.org/TR/2017/WD-webauthn-20170505/#authenticatorresponse +// https://w3c.github.io/webauthn/#authenticatorresponse [ RuntimeEnabled=WebAuth, - SecureContext + SecureContext, + Exposed=Window ] interface AuthenticatorResponse { - readonly attribute ArrayBuffer clientDataJSON; + [SameObject] readonly attribute ArrayBuffer clientDataJSON; };
diff --git a/third_party/WebKit/Source/modules/credentialmanager/AuthenticatorSelectionCriteria.idl b/third_party/WebKit/Source/modules/credentialmanager/AuthenticatorSelectionCriteria.idl index b2a1528..94e593b 100644 --- a/third_party/WebKit/Source/modules/credentialmanager/AuthenticatorSelectionCriteria.idl +++ b/third_party/WebKit/Source/modules/credentialmanager/AuthenticatorSelectionCriteria.idl
@@ -2,16 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// https://www.w3.org/TR/2017/WD-webauthn-20170505/#enumdef-authenticatorattachment +// https://w3c.github.io/webauthn/#enumdef-authenticatorattachment -enum Attachment { +enum AuthenticatorAttachment { "platform", "cross-platform" }; -// https://www.w3.org/TR/2017/WD-webauthn-20170505/#dictdef-authenticatorselectioncriteria +// https://w3c.github.io/webauthn/#dictdef-authenticatorselectioncriteria dictionary AuthenticatorSelectionCriteria { - Attachment attachment; + AuthenticatorAttachment authenticatorAttachment; boolean requireResidentKey = false; + boolean requireUserVerification = false; };
diff --git a/third_party/WebKit/Source/modules/credentialmanager/CollectedClientData.idl b/third_party/WebKit/Source/modules/credentialmanager/CollectedClientData.idl index 01ac885..846432c 100644 --- a/third_party/WebKit/Source/modules/credentialmanager/CollectedClientData.idl +++ b/third_party/WebKit/Source/modules/credentialmanager/CollectedClientData.idl
@@ -2,12 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// https://www.w3.org/TR/2017/WD-webauthn-20170505/#dictdef-collectedclientdata +// https://w3c.github.io/webauthn/#dictdef-collectedclientdata dictionary CollectedClientData { + required DOMString type; required DOMString challenge; required DOMString origin; - required DOMString hashAlg; + required DOMString hashAlgorithm; DOMString tokenBindingId; // TODO(crbug.com/733033): Add extension support };
diff --git a/third_party/WebKit/Source/modules/credentialmanager/CredentialCreationOptions.idl b/third_party/WebKit/Source/modules/credentialmanager/CredentialCreationOptions.idl index 6a3cf462..f824539 100644 --- a/third_party/WebKit/Source/modules/credentialmanager/CredentialCreationOptions.idl +++ b/third_party/WebKit/Source/modules/credentialmanager/CredentialCreationOptions.idl
@@ -11,5 +11,5 @@ dictionary CredentialCreationOptions { PasswordCredentialInit? password; FederatedCredentialInit? federated; - MakeCredentialOptions? publicKey; + MakePublicKeyCredentialOptions? publicKey; };
diff --git a/third_party/WebKit/Source/modules/credentialmanager/CredentialManagerClient.cpp b/third_party/WebKit/Source/modules/credentialmanager/CredentialManagerClient.cpp index d2b2f85..1eacbaa 100644 --- a/third_party/WebKit/Source/modules/credentialmanager/CredentialManagerClient.cpp +++ b/third_party/WebKit/Source/modules/credentialmanager/CredentialManagerClient.cpp
@@ -84,7 +84,7 @@ void CredentialManagerClient::DispatchMakeCredential( LocalFrame& frame, - const MakeCredentialOptions& options, + const MakePublicKeyCredentialOptions& options, std::unique_ptr<WebAuthenticationClient::PublicKeyCallbacks> callbacks) { if (!authentication_client_) authentication_client_ = new WebAuthenticationClient(frame);
diff --git a/third_party/WebKit/Source/modules/credentialmanager/CredentialManagerClient.h b/third_party/WebKit/Source/modules/credentialmanager/CredentialManagerClient.h index d1ca5ade..9e7a0da 100644 --- a/third_party/WebKit/Source/modules/credentialmanager/CredentialManagerClient.h +++ b/third_party/WebKit/Source/modules/credentialmanager/CredentialManagerClient.h
@@ -8,7 +8,7 @@ #include <memory> #include "core/page/Page.h" #include "modules/ModulesExport.h" -#include "modules/credentialmanager/MakeCredentialOptions.h" +#include "modules/credentialmanager/MakePublicKeyCredentialOptions.h" #include "modules/credentialmanager/WebAuthenticationClient.h" #include "platform/Supplementable.h" #include "public/platform/WebCredentialManagerClient.h" @@ -55,7 +55,7 @@ WebCredentialManagerClient::RequestCallbacks*); virtual void DispatchMakeCredential( LocalFrame&, - const MakeCredentialOptions&, + const MakePublicKeyCredentialOptions&, std::unique_ptr<WebAuthenticationClient::PublicKeyCallbacks>); private:
diff --git a/third_party/WebKit/Source/modules/credentialmanager/CredentialManagerTypeConverters.cpp b/third_party/WebKit/Source/modules/credentialmanager/CredentialManagerTypeConverters.cpp index 5a2bfb3..014d823 100644 --- a/third_party/WebKit/Source/modules/credentialmanager/CredentialManagerTypeConverters.cpp +++ b/third_party/WebKit/Source/modules/credentialmanager/CredentialManagerTypeConverters.cpp
@@ -5,10 +5,10 @@ #include "modules/credentialmanager/CredentialManagerTypeConverters.h" #include "bindings/core/v8/array_buffer_or_array_buffer_view.h" -#include "modules/credentialmanager/MakeCredentialOptions.h" +#include "modules/credentialmanager/MakePublicKeyCredentialOptions.h" #include "modules/credentialmanager/PublicKeyCredential.h" -#include "modules/credentialmanager/PublicKeyCredentialEntity.h" #include "modules/credentialmanager/PublicKeyCredentialParameters.h" +#include "modules/credentialmanager/PublicKeyCredentialRpEntity.h" #include "modules/credentialmanager/PublicKeyCredentialUserEntity.h" #include "platform/wtf/Time.h" @@ -21,9 +21,11 @@ namespace mojo { using webauth::mojom::blink::AuthenticatorStatus; -using webauth::mojom::blink::MakeCredentialOptionsPtr; -using webauth::mojom::blink::PublicKeyCredentialEntity; -using webauth::mojom::blink::PublicKeyCredentialEntityPtr; +using webauth::mojom::blink::MakePublicKeyCredentialOptionsPtr; +using webauth::mojom::blink::PublicKeyCredentialRpEntity; +using webauth::mojom::blink::PublicKeyCredentialRpEntityPtr; +using webauth::mojom::blink::PublicKeyCredentialUserEntity; +using webauth::mojom::blink::PublicKeyCredentialUserEntityPtr; using webauth::mojom::blink::PublicKeyCredentialParameters; using webauth::mojom::blink::PublicKeyCredentialParametersPtr; using webauth::mojom::blink::PublicKeyCredentialType; @@ -70,18 +72,12 @@ } // static -PublicKeyCredentialEntityPtr -TypeConverter<PublicKeyCredentialEntityPtr, +PublicKeyCredentialUserEntityPtr +TypeConverter<PublicKeyCredentialUserEntityPtr, blink::PublicKeyCredentialUserEntity>:: Convert(const blink::PublicKeyCredentialUserEntity& user) { - // These manual checks are here because while these aspects are required, - // the IDL itself doesn't mark them as required to allow for future - // types of entities where these params may not be required. - if (!(user.hasId() && user.hasName() && user.hasDisplayName())) { - return nullptr; - } - auto entity = webauth::mojom::blink::PublicKeyCredentialEntity::New(); - entity->id = user.id(); + auto entity = webauth::mojom::blink::PublicKeyCredentialUserEntity::New(); + entity->id = ConvertTo<Vector<uint8_t>>(user.id()); entity->name = user.name(); if (user.hasIcon()) { entity->icon = blink::KURL(blink::KURL(), user.icon()); @@ -91,13 +87,11 @@ } // static -PublicKeyCredentialEntityPtr -TypeConverter<PublicKeyCredentialEntityPtr, blink::PublicKeyCredentialEntity>:: - Convert(const blink::PublicKeyCredentialEntity& rp) { - if (!rp.hasName()) { - return nullptr; - } - auto entity = webauth::mojom::blink::PublicKeyCredentialEntity::New(); +PublicKeyCredentialRpEntityPtr +TypeConverter<PublicKeyCredentialRpEntityPtr, + blink::PublicKeyCredentialRpEntity>:: + Convert(const blink::PublicKeyCredentialRpEntity& rp) { + auto entity = webauth::mojom::blink::PublicKeyCredentialRpEntity::New(); entity->id = rp.id(); entity->name = rp.name(); if (rp.hasIcon()) { @@ -118,17 +112,19 @@ // A COSEAlgorithmIdentifier's value is a number identifying a cryptographic // algorithm. Values are registered in the IANA COSE Algorithms registry. // https://www.iana.org/assignments/cose/cose.xhtml#algorithms - mojo_parameter->algorithm_identifier = parameter.algorithm(); + mojo_parameter->algorithm_identifier = parameter.alg(); return mojo_parameter; } // static -MakeCredentialOptionsPtr -TypeConverter<MakeCredentialOptionsPtr, blink::MakeCredentialOptions>::Convert( - const blink::MakeCredentialOptions& options) { - auto mojo_options = webauth::mojom::blink::MakeCredentialOptions::New(); - mojo_options->relying_party = PublicKeyCredentialEntity::From(options.rp()); - mojo_options->user = PublicKeyCredentialEntity::From(options.user()); +MakePublicKeyCredentialOptionsPtr +TypeConverter<MakePublicKeyCredentialOptionsPtr, + blink::MakePublicKeyCredentialOptions>:: + Convert(const blink::MakePublicKeyCredentialOptions& options) { + auto mojo_options = + webauth::mojom::blink::MakePublicKeyCredentialOptions::New(); + mojo_options->relying_party = PublicKeyCredentialRpEntity::From(options.rp()); + mojo_options->user = PublicKeyCredentialUserEntity::From(options.user()); if (!mojo_options->relying_party | !mojo_options->user) { return nullptr; } @@ -148,7 +144,7 @@ // Steps 8 and 9 of // https://www.w3.org/TR/2017/WD-webauthn-20170505/#createCredential Vector<PublicKeyCredentialParametersPtr> parameters; - for (const auto& parameter : options.parameters()) { + for (const auto& parameter : options.pubKeyCredParams()) { PublicKeyCredentialParametersPtr normalized_parameter = PublicKeyCredentialParameters::From(parameter); if (normalized_parameter) { @@ -156,16 +152,16 @@ } } - if (parameters.IsEmpty() && options.hasParameters()) { + if (parameters.IsEmpty() && options.hasPubKeyCredParams()) { return nullptr; } - mojo_options->crypto_parameters = std::move(parameters); + mojo_options->public_key_parameters = std::move(parameters); - if (options.hasExcludeList()) { - // Adds the excludeList members + if (options.hasExcludeCredentials()) { + // Adds the excludeCredentials members for (const blink::PublicKeyCredentialDescriptor& descriptor : - options.excludeList()) { + options.excludeCredentials()) { auto mojo_descriptor = webauth::mojom::blink::PublicKeyCredentialDescriptor::New(); mojo_descriptor->type =
diff --git a/third_party/WebKit/Source/modules/credentialmanager/CredentialManagerTypeConverters.h b/third_party/WebKit/Source/modules/credentialmanager/CredentialManagerTypeConverters.h index ab25ce0..1ab677c 100644 --- a/third_party/WebKit/Source/modules/credentialmanager/CredentialManagerTypeConverters.h +++ b/third_party/WebKit/Source/modules/credentialmanager/CredentialManagerTypeConverters.h
@@ -11,9 +11,9 @@ namespace blink { class ArrayBufferOrArrayBufferView; -class MakeCredentialOptions; -class PublicKeyCredentialEntity; +class MakePublicKeyCredentialOptions; class PublicKeyCredentialParameters; +class PublicKeyCredentialRpEntity; class PublicKeyCredentialUserEntity; } // namespace blink @@ -39,17 +39,17 @@ }; template <> -struct TypeConverter<webauth::mojom::blink::PublicKeyCredentialEntityPtr, +struct TypeConverter<webauth::mojom::blink::PublicKeyCredentialUserEntityPtr, blink::PublicKeyCredentialUserEntity> { - static webauth::mojom::blink::PublicKeyCredentialEntityPtr Convert( + static webauth::mojom::blink::PublicKeyCredentialUserEntityPtr Convert( const blink::PublicKeyCredentialUserEntity&); }; template <> -struct TypeConverter<webauth::mojom::blink::PublicKeyCredentialEntityPtr, - blink::PublicKeyCredentialEntity> { - static webauth::mojom::blink::PublicKeyCredentialEntityPtr Convert( - const blink::PublicKeyCredentialEntity& rp); +struct TypeConverter<webauth::mojom::blink::PublicKeyCredentialRpEntityPtr, + blink::PublicKeyCredentialRpEntity> { + static webauth::mojom::blink::PublicKeyCredentialRpEntityPtr Convert( + const blink::PublicKeyCredentialRpEntity&); }; template <> @@ -60,10 +60,10 @@ }; template <> -struct TypeConverter<webauth::mojom::blink::MakeCredentialOptionsPtr, - blink::MakeCredentialOptions> { - static webauth::mojom::blink::MakeCredentialOptionsPtr Convert( - const blink::MakeCredentialOptions&); +struct TypeConverter<webauth::mojom::blink::MakePublicKeyCredentialOptionsPtr, + blink::MakePublicKeyCredentialOptions> { + static webauth::mojom::blink::MakePublicKeyCredentialOptionsPtr Convert( + const blink::MakePublicKeyCredentialOptions&); }; } // namespace mojo
diff --git a/third_party/WebKit/Source/modules/credentialmanager/CredentialsContainer.cpp b/third_party/WebKit/Source/modules/credentialmanager/CredentialsContainer.cpp index 799f0a9..15ff29e 100644 --- a/third_party/WebKit/Source/modules/credentialmanager/CredentialsContainer.cpp +++ b/third_party/WebKit/Source/modules/credentialmanager/CredentialsContainer.cpp
@@ -26,7 +26,7 @@ #include "modules/credentialmanager/CredentialRequestOptions.h" #include "modules/credentialmanager/FederatedCredential.h" #include "modules/credentialmanager/FederatedCredentialRequestOptions.h" -#include "modules/credentialmanager/MakeCredentialOptions.h" +#include "modules/credentialmanager/MakePublicKeyCredentialOptions.h" #include "modules/credentialmanager/PasswordCredential.h" #include "modules/credentialmanager/PublicKeyCredential.h" #include "platform/credentialmanager/PlatformFederatedCredential.h" @@ -356,6 +356,13 @@ if (!CheckBoilerplate(resolver)) return promise; + if (!(credential->GetPlatformCredential()->IsFederated() || + credential->GetPlatformCredential()->IsPassword())) { + resolver->Reject(DOMException::Create( + kNotSupportedError, + "Store operation not permitted for PublicKey credentials.")); + } + if (IsIconURLInsecure(credential)) { resolver->Reject(DOMException::Create(kSecurityError, "'iconURL' should be a secure URL"));
diff --git a/third_party/WebKit/Source/modules/credentialmanager/MakeCredentialOptions.idl b/third_party/WebKit/Source/modules/credentialmanager/MakeCredentialOptions.idl deleted file mode 100644 index b318e81a3..0000000 --- a/third_party/WebKit/Source/modules/credentialmanager/MakeCredentialOptions.idl +++ /dev/null
@@ -1,16 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// https://www.w3.org/TR/2017/WD-webauthn-20170505/#dictdef-makecredentialoptions - -dictionary MakeCredentialOptions { - required PublicKeyCredentialEntity rp; - required PublicKeyCredentialUserEntity user; - required BufferSource challenge; - required sequence<PublicKeyCredentialParameters> parameters; - unsigned long timeout; - sequence<PublicKeyCredentialDescriptor> excludeList = []; - AuthenticatorSelectionCriteria authenticatorSelection; - // TODO(crbug.com/733033): Add extension support -};
diff --git a/third_party/WebKit/Source/modules/credentialmanager/MakePublicKeyCredentialOptions.idl b/third_party/WebKit/Source/modules/credentialmanager/MakePublicKeyCredentialOptions.idl new file mode 100644 index 0000000..3efd1f72 --- /dev/null +++ b/third_party/WebKit/Source/modules/credentialmanager/MakePublicKeyCredentialOptions.idl
@@ -0,0 +1,16 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// https://w3c.github.io/webauthn/#dictdef-makepublickeycredentialoptions + +dictionary MakePublicKeyCredentialOptions { + required PublicKeyCredentialRpEntity rp; + required PublicKeyCredentialUserEntity user; + required BufferSource challenge; + required sequence<PublicKeyCredentialParameters> pubKeyCredParams; + unsigned long timeout; + sequence<PublicKeyCredentialDescriptor> excludeCredentials = []; + AuthenticatorSelectionCriteria authenticatorSelection; + // TODO(crbug.com/733033): Add extension support +};
diff --git a/third_party/WebKit/Source/modules/credentialmanager/PublicKeyCredential.idl b/third_party/WebKit/Source/modules/credentialmanager/PublicKeyCredential.idl index c8c8127..c01477f 100644 --- a/third_party/WebKit/Source/modules/credentialmanager/PublicKeyCredential.idl +++ b/third_party/WebKit/Source/modules/credentialmanager/PublicKeyCredential.idl
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// https://www.w3.org/TR/2017/WD-webauthn-20170505/#publickeycredential +// https://w3c.github.io/webauthn/#publickeycredential [ RuntimeEnabled=WebAuth,
diff --git a/third_party/WebKit/Source/modules/credentialmanager/PublicKeyCredentialDescriptor.idl b/third_party/WebKit/Source/modules/credentialmanager/PublicKeyCredentialDescriptor.idl index 0a3e924..fcd20a0 100644 --- a/third_party/WebKit/Source/modules/credentialmanager/PublicKeyCredentialDescriptor.idl +++ b/third_party/WebKit/Source/modules/credentialmanager/PublicKeyCredentialDescriptor.idl
@@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// https://www.w3.org/TR/2017/WD-webauthn-20170505/#enumdef-authenticatortransport +// https://w3c.github.io/webauthn/#enumdef-authenticatortransport -enum Transport { +enum AuthenticatorTransport { "usb", "nfc", "ble" @@ -15,5 +15,5 @@ dictionary PublicKeyCredentialDescriptor { required PublicKeyCredentialType type; required BufferSource id; - sequence<Transport> transports; + sequence<AuthenticatorTransport> transports; };
diff --git a/third_party/WebKit/Source/modules/credentialmanager/PublicKeyCredentialEntity.idl b/third_party/WebKit/Source/modules/credentialmanager/PublicKeyCredentialEntity.idl index 0e15dc9..2dd1b14 100644 --- a/third_party/WebKit/Source/modules/credentialmanager/PublicKeyCredentialEntity.idl +++ b/third_party/WebKit/Source/modules/credentialmanager/PublicKeyCredentialEntity.idl
@@ -2,10 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// https://www.w3.org/TR/2017/WD-webauthn-20170505/#dictdef-publickeycredentialentity +// https://w3c.github.io/webauthn/#dictdef-publickeycredentialentity dictionary PublicKeyCredentialEntity { - DOMString id; - DOMString name; + required DOMString name; USVString icon; };
diff --git a/third_party/WebKit/Source/modules/credentialmanager/PublicKeyCredentialParameters.idl b/third_party/WebKit/Source/modules/credentialmanager/PublicKeyCredentialParameters.idl index 82a3aeb6..2a401c5 100644 --- a/third_party/WebKit/Source/modules/credentialmanager/PublicKeyCredentialParameters.idl +++ b/third_party/WebKit/Source/modules/credentialmanager/PublicKeyCredentialParameters.idl
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// https://www.w3.org/TR/2017/WD-webauthn-20170505/#enumdef-publickeycredentialtype +// https://w3c.github.io/webauthn/#enumdef-publickeycredentialtype enum PublicKeyCredentialType { "public-key" @@ -12,9 +12,9 @@ typedef long COSEAlgorithmIdentifier; -// https://www.w3.org/TR/2017/WD-webauthn-20170505/#dictdef-publickeycredentialparameters +// https://w3c.github.io/webauthn/#dictdef-publickeycredentialparameters dictionary PublicKeyCredentialParameters { required PublicKeyCredentialType type; - required COSEAlgorithmIdentifier algorithm; + required COSEAlgorithmIdentifier alg; };
diff --git a/third_party/WebKit/Source/modules/credentialmanager/PublicKeyCredentialRequestOptions.idl b/third_party/WebKit/Source/modules/credentialmanager/PublicKeyCredentialRequestOptions.idl index 1386f776..3d43d50a 100644 --- a/third_party/WebKit/Source/modules/credentialmanager/PublicKeyCredentialRequestOptions.idl +++ b/third_party/WebKit/Source/modules/credentialmanager/PublicKeyCredentialRequestOptions.idl
@@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// https://www.w3.org/TR/2017/WD-webauthn-20170505/#dictdef-publickeycredentialrequestoptions +// https://w3c.github.io/webauthn/#dictdef-publickeycredentialrequestoptions dictionary PublicKeyCredentialRequestOptions { required BufferSource challenge; unsigned long timeout; USVString rpId; - sequence <PublicKeyCredentialDescriptor> allowList = []; + sequence<PublicKeyCredentialDescriptor> allowCredentials = []; // TODO(crbug.com/733033): Add extension support };
diff --git a/third_party/WebKit/Source/modules/credentialmanager/PublicKeyCredentialRpEntity.idl b/third_party/WebKit/Source/modules/credentialmanager/PublicKeyCredentialRpEntity.idl new file mode 100644 index 0000000..e8e51cf --- /dev/null +++ b/third_party/WebKit/Source/modules/credentialmanager/PublicKeyCredentialRpEntity.idl
@@ -0,0 +1,9 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// https://w3c.github.io/webauthn/#dictdef-publickeycredentialrpentity + +dictionary PublicKeyCredentialRpEntity : PublicKeyCredentialEntity { + DOMString id; +};
diff --git a/third_party/WebKit/Source/modules/credentialmanager/PublicKeyCredentialUserEntity.idl b/third_party/WebKit/Source/modules/credentialmanager/PublicKeyCredentialUserEntity.idl index c792c803..d8b3717 100644 --- a/third_party/WebKit/Source/modules/credentialmanager/PublicKeyCredentialUserEntity.idl +++ b/third_party/WebKit/Source/modules/credentialmanager/PublicKeyCredentialUserEntity.idl
@@ -2,8 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// https://www.w3.org/TR/2017/WD-webauthn-20170505/#dictdef-publickeycredentialuserentity +//https://w3c.github.io/webauthn/#dictdef-publickeycredentialuserentity dictionary PublicKeyCredentialUserEntity : PublicKeyCredentialEntity { - DOMString displayName; + required BufferSource id; + required DOMString displayName; };
diff --git a/third_party/WebKit/Source/modules/credentialmanager/WebAuthenticationClient.cpp b/third_party/WebKit/Source/modules/credentialmanager/WebAuthenticationClient.cpp index a2cae8f..ab98b92 100644 --- a/third_party/WebKit/Source/modules/credentialmanager/WebAuthenticationClient.cpp +++ b/third_party/WebKit/Source/modules/credentialmanager/WebAuthenticationClient.cpp
@@ -12,7 +12,7 @@ #include "core/dom/ExceptionCode.h" #include "core/frame/LocalFrame.h" #include "modules/credentialmanager/CredentialManagerTypeConverters.h" -#include "modules/credentialmanager/MakeCredentialOptions.h" +#include "modules/credentialmanager/MakePublicKeyCredentialOptions.h" #include "public/platform/InterfaceProvider.h" #include "services/service_manager/public/cpp/interface_provider.h" @@ -77,9 +77,10 @@ WebAuthenticationClient::~WebAuthenticationClient() {} void WebAuthenticationClient::DispatchMakeCredential( - const MakeCredentialOptions& publicKey, + const MakePublicKeyCredentialOptions& publicKey, std::unique_ptr<PublicKeyCallbacks> callbacks) { - auto options = webauth::mojom::blink::MakeCredentialOptions::From(publicKey); + auto options = + webauth::mojom::blink::MakePublicKeyCredentialOptions::From(publicKey); if (!options) { callbacks->OnError( WebCredentialManagerError::kWebCredentialManagerNotSupportedError);
diff --git a/third_party/WebKit/Source/modules/credentialmanager/WebAuthenticationClient.h b/third_party/WebKit/Source/modules/credentialmanager/WebAuthenticationClient.h index 465fa66..bda4960c 100644 --- a/third_party/WebKit/Source/modules/credentialmanager/WebAuthenticationClient.h +++ b/third_party/WebKit/Source/modules/credentialmanager/WebAuthenticationClient.h
@@ -14,7 +14,7 @@ namespace blink { class LocalFrame; -class MakeCredentialOptions; +class MakePublicKeyCredentialOptions; class PublicKeyCredentialRequestOptions; class WebAuthenticationClient final @@ -30,7 +30,7 @@ virtual ~WebAuthenticationClient(); // WebAuthentication.idl - void DispatchMakeCredential(const MakeCredentialOptions&, + void DispatchMakeCredential(const MakePublicKeyCredentialOptions&, std::unique_ptr<PublicKeyCallbacks>); void GetAssertion(const PublicKeyCredentialRequestOptions&,
diff --git a/third_party/WebKit/Source/modules/encryptedmedia/NavigatorRequestMediaKeySystemAccess.cpp b/third_party/WebKit/Source/modules/encryptedmedia/NavigatorRequestMediaKeySystemAccess.cpp index b76eeaf2e..ec740bc 100644 --- a/third_party/WebKit/Source/modules/encryptedmedia/NavigatorRequestMediaKeySystemAccess.cpp +++ b/third_party/WebKit/Source/modules/encryptedmedia/NavigatorRequestMediaKeySystemAccess.cpp
@@ -57,8 +57,8 @@ for (size_t i = 0; i < capabilities.size(); ++i) { const WebString& content_type = capabilities[i].contentType(); result[i].content_type = content_type; - ParsedContentType type(content_type, ParsedContentType::Mode::kStrict); - if (type.IsValid()) { + ParsedContentType type(content_type); + if (type.IsValid() && !type.GetParameters().HasDuplicatedNames()) { // From // http://w3c.github.io/encrypted-media/#get-supported-capabilities-for-audio-video-type // "If the user agent does not recognize one or more parameters, @@ -67,7 +67,7 @@ // present. Chromium expects "codecs" to be provided, so this capability // will be skipped if codecs is not the only parameter specified. result[i].mime_type = type.MimeType(); - if (type.ParameterCount() == 1u) + if (type.GetParameters().ParameterCount() == 1u) result[i].codecs = type.ParameterValueForName("codecs"); } result[i].robustness = capabilities[i].robustness();
diff --git a/third_party/WebKit/Source/modules/exported/WebAXObject.cpp b/third_party/WebKit/Source/modules/exported/WebAXObject.cpp index 5720183f5..032ecbe9 100644 --- a/third_party/WebKit/Source/modules/exported/WebAXObject.cpp +++ b/third_party/WebKit/Source/modules/exported/WebAXObject.cpp
@@ -1434,7 +1434,8 @@ void WebAXObject::GetRelativeBounds(WebAXObject& offset_container, WebFloatRect& bounds_in_container, - SkMatrix44& container_transform) const { + SkMatrix44& container_transform, + bool* clips_children) const { if (IsDetached()) return; @@ -1444,7 +1445,8 @@ AXObject* container = nullptr; FloatRect bounds; - private_->GetRelativeBounds(&container, bounds, container_transform); + private_->GetRelativeBounds(&container, bounds, container_transform, + clips_children); offset_container = WebAXObject(container); bounds_in_container = WebFloatRect(bounds); }
diff --git a/third_party/WebKit/Source/modules/fetch/DataConsumerHandleTestUtil.cpp b/third_party/WebKit/Source/modules/fetch/DataConsumerHandleTestUtil.cpp index bacdf64c1..0a845c1 100644 --- a/third_party/WebKit/Source/modules/fetch/DataConsumerHandleTestUtil.cpp +++ b/third_party/WebKit/Source/modules/fetch/DataConsumerHandleTestUtil.cpp
@@ -59,12 +59,8 @@ void DataConsumerHandleTestUtil::Thread::Initialize() { DCHECK(thread_->IsCurrentThread()); if (initialization_policy_ >= kScriptExecution) { - isolate_holder_ = - std::make_unique<gin::IsolateHolder>(Platform::Current() - ->CurrentThread() - ->Scheduler() - ->LoadingTaskRunner() - ->ToSingleThreadTaskRunner()); + isolate_holder_ = std::make_unique<gin::IsolateHolder>( + Platform::Current()->CurrentThread()->Scheduler()->LoadingTaskRunner()); GetIsolate()->Enter(); } thread_->InitializeOnThread();
diff --git a/third_party/WebKit/Source/modules/media_capabilities/MediaCapabilities.cpp b/third_party/WebKit/Source/modules/media_capabilities/MediaCapabilities.cpp index b03d33d..21527039 100644 --- a/third_party/WebKit/Source/modules/media_capabilities/MediaCapabilities.cpp +++ b/third_party/WebKit/Source/modules/media_capabilities/MediaCapabilities.cpp
@@ -59,8 +59,8 @@ } bool IsValidMimeType(const String& content_type, const String& prefix) { - ParsedContentType parsed_content_type(content_type, - ParsedContentType::Mode::kStrict); + ParsedContentType parsed_content_type(content_type); + if (!parsed_content_type.IsValid()) return false; @@ -68,17 +68,15 @@ !parsed_content_type.MimeType().StartsWith(kApplicationMimeTypePrefix)) { return false; } + const auto& parameters = parsed_content_type.GetParameters(); - if (parsed_content_type.ParameterCount() > 1) + if (parameters.ParameterCount() > 1) return false; - if (parsed_content_type.ParameterCount() == 1 && - parsed_content_type.ParameterValueForName(kCodecsMimeTypeParam) - .IsNull()) { - return false; - } + if (parameters.ParameterCount() == 0) + return true; - return true; + return parameters.begin()->name.LowerASCII() == kCodecsMimeTypeParam; } bool IsValidMediaConfiguration(const MediaConfiguration& configuration) { @@ -113,9 +111,9 @@ // |contentType| is mandatory. DCHECK(configuration.hasContentType()); - ParsedContentType parsed_content_type(configuration.contentType(), - ParsedContentType::Mode::kStrict); + ParsedContentType parsed_content_type(configuration.contentType()); DCHECK(parsed_content_type.IsValid()); + DCHECK(!parsed_content_type.GetParameters().HasDuplicatedNames()); DEFINE_STATIC_LOCAL(const String, codecs, ("codecs")); web_configuration.mime_type = parsed_content_type.MimeType().LowerASCII(); @@ -141,9 +139,9 @@ // All the properties are mandatory. DCHECK(configuration.hasContentType()); - ParsedContentType parsed_content_type(configuration.contentType(), - ParsedContentType::Mode::kStrict); + ParsedContentType parsed_content_type(configuration.contentType()); DCHECK(parsed_content_type.IsValid()); + DCHECK(!parsed_content_type.GetParameters().HasDuplicatedNames()); DEFINE_STATIC_LOCAL(const String, codecs, ("codecs")); web_configuration.mime_type = parsed_content_type.MimeType().LowerASCII();
diff --git a/third_party/WebKit/Source/modules/modules_idl_files.gni b/third_party/WebKit/Source/modules/modules_idl_files.gni index 087cc87..0cc1c1f 100644 --- a/third_party/WebKit/Source/modules/modules_idl_files.gni +++ b/third_party/WebKit/Source/modules/modules_idl_files.gni
@@ -268,7 +268,6 @@ "serviceworkers/ExtendableEvent.idl", "serviceworkers/ExtendableMessageEvent.idl", "serviceworkers/FetchEvent.idl", - "serviceworkers/ForeignFetchEvent.idl", "serviceworkers/InstallEvent.idl", "serviceworkers/NavigationPreloadManager.idl", "serviceworkers/ServiceWorker.idl", @@ -462,7 +461,7 @@ "cookie_store/CookieStoreSetOptions.idl", "credentialmanager/AuthenticatorSelectionCriteria.idl", "credentialmanager/CollectedClientData.idl", - "credentialmanager/MakeCredentialOptions.idl", + "credentialmanager/MakePublicKeyCredentialOptions.idl", "credentialmanager/CredentialCreationOptions.idl", "credentialmanager/CredentialData.idl", "credentialmanager/CredentialRequestOptions.idl", @@ -473,6 +472,7 @@ "credentialmanager/PublicKeyCredentialEntity.idl", "credentialmanager/PublicKeyCredentialParameters.idl", "credentialmanager/PublicKeyCredentialRequestOptions.idl", + "credentialmanager/PublicKeyCredentialRpEntity.idl", "credentialmanager/PublicKeyCredentialUserEntity.idl", "csspaint/PaintRenderingContext2DSettings.idl", "device_orientation/DeviceAccelerationInit.idl", @@ -576,9 +576,6 @@ "serviceworkers/ExtendableEventInit.idl", "serviceworkers/ExtendableMessageEventInit.idl", "serviceworkers/FetchEventInit.idl", - "serviceworkers/ForeignFetchEventInit.idl", - "serviceworkers/ForeignFetchOptions.idl", - "serviceworkers/ForeignFetchResponse.idl", "serviceworkers/NavigationPreloadState.idl", "serviceworkers/RegistrationOptions.idl", "shapedetection/FaceDetectorOptions.idl",
diff --git a/third_party/WebKit/Source/modules/notifications/Notification.cpp b/third_party/WebKit/Source/modules/notifications/Notification.cpp index ca614779..012908ad4 100644 --- a/third_party/WebKit/Source/modules/notifications/Notification.cpp +++ b/third_party/WebKit/Source/modules/notifications/Notification.cpp
@@ -172,8 +172,7 @@ return; } - if (NotificationManager::From(GetExecutionContext()) - ->GetPermissionStatus(GetExecutionContext()) != + if (NotificationManager::From(GetExecutionContext())->GetPermissionStatus() != mojom::blink::PermissionStatus::GRANTED) { DispatchErrorEvent(); return; @@ -380,7 +379,7 @@ return PermissionString(mojom::blink::PermissionStatus::DENIED); mojom::blink::PermissionStatus status = - NotificationManager::From(context)->GetPermissionStatus(context); + NotificationManager::From(context)->GetPermissionStatus(); // Permission can only be requested from top-level frames and same-origin // iframes. This should be reflected in calls getting permission status.
diff --git a/third_party/WebKit/Source/modules/notifications/NotificationManager.cpp b/third_party/WebKit/Source/modules/notifications/NotificationManager.cpp index 0e5a0af..3e16e66 100644 --- a/third_party/WebKit/Source/modules/notifications/NotificationManager.cpp +++ b/third_party/WebKit/Source/modules/notifications/NotificationManager.cpp
@@ -17,6 +17,7 @@ #include "public/platform/Platform.h" #include "public/platform/modules/permissions/permission.mojom-blink.h" #include "public/platform/modules/permissions/permission_status.mojom-blink.h" +#include "services/service_manager/public/cpp/interface_provider.h" namespace blink { @@ -29,7 +30,7 @@ NotificationManager* manager = static_cast<NotificationManager*>( Supplement<ExecutionContext>::From(execution_context, SupplementName())); if (!manager) { - manager = new NotificationManager(); + manager = new NotificationManager(*execution_context); Supplement<ExecutionContext>::ProvideTo(*execution_context, SupplementName(), manager); } @@ -42,21 +43,17 @@ return "NotificationManager"; } -NotificationManager::NotificationManager() {} +NotificationManager::NotificationManager(ExecutionContext& execution_context) + : Supplement<ExecutionContext>(execution_context) {} NotificationManager::~NotificationManager() {} -mojom::blink::PermissionStatus NotificationManager::GetPermissionStatus( - ExecutionContext* execution_context) { - if (!notification_service_) { - Platform::Current()->GetInterfaceProvider()->GetInterface( - mojo::MakeRequest(¬ification_service_)); - } +mojom::blink::PermissionStatus NotificationManager::GetPermissionStatus() { + if (GetSupplementable()->IsContextDestroyed()) + return mojom::blink::PermissionStatus::DENIED; mojom::blink::PermissionStatus permission_status; - if (!notification_service_->GetPermissionStatus( - execution_context->GetSecurityOrigin()->ToString(), - &permission_status)) { + if (!GetNotificationService()->GetPermissionStatus(&permission_status)) { NOTREACHED(); return mojom::blink::PermissionStatus::DENIED; } @@ -104,10 +101,29 @@ resolver->Resolve(status_string); } +void NotificationManager::OnNotificationServiceConnectionError() { + notification_service_.reset(); +} + void NotificationManager::OnPermissionServiceConnectionError() { permission_service_.reset(); } +const mojom::blink::NotificationServicePtr& +NotificationManager::GetNotificationService() { + if (!notification_service_) { + if (auto* provider = GetSupplementable()->GetInterfaceProvider()) { + provider->GetInterface(mojo::MakeRequest(¬ification_service_)); + + notification_service_.set_connection_error_handler(ConvertToBaseCallback( + WTF::Bind(&NotificationManager::OnNotificationServiceConnectionError, + WrapWeakPersistent(this)))); + } + } + + return notification_service_; +} + void NotificationManager::Trace(blink::Visitor* visitor) { Supplement<ExecutionContext>::Trace(visitor); }
diff --git a/third_party/WebKit/Source/modules/notifications/NotificationManager.h b/third_party/WebKit/Source/modules/notifications/NotificationManager.h index 6f972a6..c7cb250 100644 --- a/third_party/WebKit/Source/modules/notifications/NotificationManager.h +++ b/third_party/WebKit/Source/modules/notifications/NotificationManager.h
@@ -36,7 +36,7 @@ // Returns the notification permission status of the current origin. This // method is synchronous to support the Notification.permission getter. - mojom::blink::PermissionStatus GetPermissionStatus(ExecutionContext*); + mojom::blink::PermissionStatus GetPermissionStatus(); ScriptPromise RequestPermission( ScriptState*, @@ -45,11 +45,17 @@ virtual void Trace(blink::Visitor*); private: - NotificationManager(); + explicit NotificationManager(ExecutionContext&); + + // Returns an initialized NotificationServicePtr. A connection will be + // established the first time this method is called. + const mojom::blink::NotificationServicePtr& GetNotificationService(); void OnPermissionRequestComplete(ScriptPromiseResolver*, NotificationPermissionCallback*, mojom::blink::PermissionStatus); + + void OnNotificationServiceConnectionError(); void OnPermissionServiceConnectionError(); mojom::blink::NotificationServicePtr notification_service_;
diff --git a/third_party/WebKit/Source/modules/notifications/ServiceWorkerRegistrationNotifications.cpp b/third_party/WebKit/Source/modules/notifications/ServiceWorkerRegistrationNotifications.cpp index c42edb1d..7d9bf17 100644 --- a/third_party/WebKit/Source/modules/notifications/ServiceWorkerRegistrationNotifications.cpp +++ b/third_party/WebKit/Source/modules/notifications/ServiceWorkerRegistrationNotifications.cpp
@@ -79,8 +79,7 @@ // If permission for notification's origin is not "granted", reject the // promise with a TypeError exception, and terminate these substeps. - if (NotificationManager::From(execution_context) - ->GetPermissionStatus(execution_context) != + if (NotificationManager::From(execution_context)->GetPermissionStatus() != mojom::blink::PermissionStatus::GRANTED) return ScriptPromise::Reject( script_state,
diff --git a/third_party/WebKit/Source/modules/payments/PaymentHandlerUtils.cpp b/third_party/WebKit/Source/modules/payments/PaymentHandlerUtils.cpp index 3a1d89da..a556ab4 100644 --- a/third_party/WebKit/Source/modules/payments/PaymentHandlerUtils.cpp +++ b/third_party/WebKit/Source/modules/payments/PaymentHandlerUtils.cpp
@@ -42,9 +42,6 @@ case ServiceWorkerResponseError::kResponseTypeOpaqueForClientRequest: case ServiceWorkerResponseError::kResponseTypeOpaqueRedirect: case ServiceWorkerResponseError::kBodyLocked: - case ServiceWorkerResponseError::kNoForeignFetchResponse: - case ServiceWorkerResponseError::kForeignFetchHeadersWithoutOrigin: - case ServiceWorkerResponseError::kForeignFetchMismatchedOrigin: case ServiceWorkerResponseError::kRedirectedResponseForNotFollowRequest: case ServiceWorkerResponseError::kDataPipeCreationFailed: NOTREACHED();
diff --git a/third_party/WebKit/Source/modules/serviceworkers/BUILD.gn b/third_party/WebKit/Source/modules/serviceworkers/BUILD.gn index d2fb81d..f1797a5 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/BUILD.gn +++ b/third_party/WebKit/Source/modules/serviceworkers/BUILD.gn
@@ -14,10 +14,6 @@ "FetchEvent.h", "FetchRespondWithObserver.cpp", "FetchRespondWithObserver.h", - "ForeignFetchEvent.cpp", - "ForeignFetchEvent.h", - "ForeignFetchRespondWithObserver.cpp", - "ForeignFetchRespondWithObserver.h", "InstallEvent.cpp", "InstallEvent.h", "NavigationPreloadCallbacks.cpp", @@ -50,8 +46,6 @@ "ServiceWorkerGlobalScopeProxy.h", "ServiceWorkerInstalledScriptsManager.cpp", "ServiceWorkerInstalledScriptsManager.h", - "ServiceWorkerLinkResource.cpp", - "ServiceWorkerLinkResource.h", "ServiceWorkerRegistration.cpp", "ServiceWorkerRegistration.h", "ServiceWorkerScriptCachedMetadataHandler.cpp",
diff --git a/third_party/WebKit/Source/modules/serviceworkers/FetchRespondWithObserver.cpp b/third_party/WebKit/Source/modules/serviceworkers/FetchRespondWithObserver.cpp index f16fade5..e440acd 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/FetchRespondWithObserver.cpp +++ b/third_party/WebKit/Source/modules/serviceworkers/FetchRespondWithObserver.cpp
@@ -81,21 +81,6 @@ "a Response whose \"body\" is locked cannot be used to " "respond to a request."; break; - case ServiceWorkerResponseError::kNoForeignFetchResponse: - error_message = - error_message + - "an object that was not a ForeignFetchResponse was passed " - "to respondWith()."; - break; - case ServiceWorkerResponseError::kForeignFetchHeadersWithoutOrigin: - error_message = - error_message + - "headers were specified for a response without an explicit origin."; - break; - case ServiceWorkerResponseError::kForeignFetchMismatchedOrigin: - error_message = error_message + - "origin in response does not match origin of request."; - break; case ServiceWorkerResponseError::kRedirectedResponseForNotFollowRequest: error_message = error_message + "a redirected response was used for a request whose "
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ForeignFetchEvent.cpp b/third_party/WebKit/Source/modules/serviceworkers/ForeignFetchEvent.cpp deleted file mode 100644 index 1adb2e5..0000000 --- a/third_party/WebKit/Source/modules/serviceworkers/ForeignFetchEvent.cpp +++ /dev/null
@@ -1,93 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "modules/serviceworkers/ForeignFetchEvent.h" - -#include "base/memory/scoped_refptr.h" -#include "bindings/core/v8/ToV8ForCore.h" -#include "modules/fetch/Request.h" -#include "modules/serviceworkers/ServiceWorkerGlobalScope.h" -#include "platform/bindings/V8PrivateProperty.h" - -namespace blink { - -ForeignFetchEvent* ForeignFetchEvent::Create( - ScriptState* script_state, - const AtomicString& type, - const ForeignFetchEventInit& initializer) { - return new ForeignFetchEvent(script_state, type, initializer, nullptr, - nullptr); -} - -ForeignFetchEvent* ForeignFetchEvent::Create( - ScriptState* script_state, - const AtomicString& type, - const ForeignFetchEventInit& initializer, - ForeignFetchRespondWithObserver* respond_with_observer, - WaitUntilObserver* wait_until_observer) { - return new ForeignFetchEvent(script_state, type, initializer, - respond_with_observer, wait_until_observer); -} - -Request* ForeignFetchEvent::request() const { - return request_; -} - -String ForeignFetchEvent::origin() const { - return origin_; -} - -void ForeignFetchEvent::respondWith(ScriptState* script_state, - ScriptPromise script_promise, - ExceptionState& exception_state) { - stopImmediatePropagation(); - if (observer_) - observer_->RespondWith(script_state, script_promise, exception_state); -} - -const AtomicString& ForeignFetchEvent::InterfaceName() const { - return EventNames::ForeignFetchEvent; -} - -ForeignFetchEvent::ForeignFetchEvent( - ScriptState* script_state, - const AtomicString& type, - const ForeignFetchEventInit& initializer, - ForeignFetchRespondWithObserver* respond_with_observer, - WaitUntilObserver* wait_until_observer) - : ExtendableEvent(type, initializer, wait_until_observer), - observer_(respond_with_observer) { - if (initializer.hasOrigin()) - origin_ = initializer.origin(); - if (initializer.hasRequest()) { - request_ = initializer.request(); - ScriptState::Scope scope(script_state); - request_ = initializer.request(); - v8::Local<v8::Value> request = ToV8(request_, script_state); - v8::Local<v8::Value> event = ToV8(this, script_state); - if (event.IsEmpty()) { - // |toV8| can return an empty handle when the worker is terminating. - // We don't want the renderer to crash in such cases. - // TODO(yhirano): Replace this branch with an assertion when the - // graceful shutdown mechanism is introduced. - return; - } - DCHECK(event->IsObject()); - // Sets a hidden value in order to teach V8 the dependency from - // the event to the request. - V8PrivateProperty::GetFetchEventRequest(script_state->GetIsolate()) - .Set(event.As<v8::Object>(), request); - // From the same reason as above, setHiddenValue can return false. - // TODO(yhirano): Add an assertion that it returns true once the - // graceful shutdown mechanism is introduced. - } -} - -void ForeignFetchEvent::Trace(blink::Visitor* visitor) { - visitor->Trace(observer_); - visitor->Trace(request_); - ExtendableEvent::Trace(visitor); -} - -} // namespace blink
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ForeignFetchEvent.h b/third_party/WebKit/Source/modules/serviceworkers/ForeignFetchEvent.h deleted file mode 100644 index ba50ce4..0000000 --- a/third_party/WebKit/Source/modules/serviceworkers/ForeignFetchEvent.h +++ /dev/null
@@ -1,63 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef ForeignFetchEvent_h -#define ForeignFetchEvent_h - -#include "bindings/core/v8/ScriptPromise.h" -#include "modules/EventModules.h" -#include "modules/ModulesExport.h" -#include "modules/fetch/Request.h" -#include "modules/serviceworkers/ExtendableEvent.h" -#include "modules/serviceworkers/ForeignFetchEventInit.h" -#include "modules/serviceworkers/ForeignFetchRespondWithObserver.h" -#include "modules/serviceworkers/WaitUntilObserver.h" -#include "platform/heap/Handle.h" - -namespace blink { - -class ExceptionState; -class Request; - -// A foreignfetch event is dispatched by the client to a service worker's script -// context. ForeignFetchRespondWithObserver can be used to notify the client -// about the service worker's response. -class MODULES_EXPORT ForeignFetchEvent final : public ExtendableEvent { - DEFINE_WRAPPERTYPEINFO(); - - public: - static ForeignFetchEvent* Create(ScriptState*, - const AtomicString& type, - const ForeignFetchEventInit&); - static ForeignFetchEvent* Create(ScriptState*, - const AtomicString& type, - const ForeignFetchEventInit&, - ForeignFetchRespondWithObserver*, - WaitUntilObserver*); - - Request* request() const; - String origin() const; - - void respondWith(ScriptState*, ScriptPromise, ExceptionState&); - - const AtomicString& InterfaceName() const override; - - void Trace(blink::Visitor*) override; - - protected: - ForeignFetchEvent(ScriptState*, - const AtomicString& type, - const ForeignFetchEventInit&, - ForeignFetchRespondWithObserver*, - WaitUntilObserver*); - - private: - Member<ForeignFetchRespondWithObserver> observer_; - Member<Request> request_; - String origin_; -}; - -} // namespace blink - -#endif // ForeignFetchEvent_h
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ForeignFetchEvent.idl b/third_party/WebKit/Source/modules/serviceworkers/ForeignFetchEvent.idl deleted file mode 100644 index 815af4b..0000000 --- a/third_party/WebKit/Source/modules/serviceworkers/ForeignFetchEvent.idl +++ /dev/null
@@ -1,16 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// https://w3c.github.io/ServiceWorker/#foreignfetchevent-interface -[ - Constructor(DOMString type, ForeignFetchEventInit eventInitDict), - ConstructorCallWith=ScriptState, - Exposed=ServiceWorker, - OriginTrialEnabled=ForeignFetch -] interface ForeignFetchEvent : ExtendableEvent { - [SameObject] readonly attribute Request request; - readonly attribute USVString origin; - - [CallWith=ScriptState, RaisesException] void respondWith(Promise<ForeignFetchResponse> r); -};
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ForeignFetchEventInit.idl b/third_party/WebKit/Source/modules/serviceworkers/ForeignFetchEventInit.idl deleted file mode 100644 index af8274c..0000000 --- a/third_party/WebKit/Source/modules/serviceworkers/ForeignFetchEventInit.idl +++ /dev/null
@@ -1,10 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// https://w3c.github.io/ServiceWorker/#dictdef-foreignfetcheventinit - -dictionary ForeignFetchEventInit : ExtendableEventInit { - required Request request; - USVString origin = "null"; -};
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ForeignFetchOptions.idl b/third_party/WebKit/Source/modules/serviceworkers/ForeignFetchOptions.idl deleted file mode 100644 index 2a7b72a6..0000000 --- a/third_party/WebKit/Source/modules/serviceworkers/ForeignFetchOptions.idl +++ /dev/null
@@ -1,10 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// https://w3c.github.io/ServiceWorker/#dictdef-foreignfetchoptions - -dictionary ForeignFetchOptions { - required sequence<USVString> scopes; - required sequence<USVString> origins; -};
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ForeignFetchRespondWithObserver.cpp b/third_party/WebKit/Source/modules/serviceworkers/ForeignFetchRespondWithObserver.cpp deleted file mode 100644 index f1f32ddd..0000000 --- a/third_party/WebKit/Source/modules/serviceworkers/ForeignFetchRespondWithObserver.cpp +++ /dev/null
@@ -1,123 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "modules/serviceworkers/ForeignFetchRespondWithObserver.h" - -#include "bindings/modules/v8/V8ForeignFetchResponse.h" -#include "modules/fetch/Response.h" -#include "modules/serviceworkers/ForeignFetchResponse.h" -#include "public/platform/WebCORS.h" -#include "services/network/public/interfaces/fetch_api.mojom-blink.h" - -using blink::mojom::ServiceWorkerResponseError; - -namespace blink { - -ForeignFetchRespondWithObserver* ForeignFetchRespondWithObserver::Create( - ExecutionContext* context, - int event_id, - const KURL& request_url, - network::mojom::FetchRequestMode request_mode, - WebURLRequest::FetchRedirectMode redirect_mode, - WebURLRequest::FrameType frame_type, - WebURLRequest::RequestContext request_context, - scoped_refptr<SecurityOrigin> request_origin, - WaitUntilObserver* observer) { - return new ForeignFetchRespondWithObserver( - context, event_id, request_url, request_mode, redirect_mode, frame_type, - request_context, std::move(request_origin), observer); -} - -void ForeignFetchRespondWithObserver::OnResponseFulfilled( - const ScriptValue& value) { - DCHECK(GetExecutionContext()); - ExceptionState exception_state(value.GetIsolate(), - ExceptionState::kUnknownContext, - "ForeignFetchEvent", "respondWith"); - ForeignFetchResponse foreign_fetch_response = - ScriptValue::To<ForeignFetchResponse>(ToIsolate(GetExecutionContext()), - value, exception_state); - if (exception_state.HadException()) { - exception_state.ClearException(); - OnResponseRejected(ServiceWorkerResponseError::kNoForeignFetchResponse); - return; - } - - Response* response = foreign_fetch_response.response(); - const FetchResponseData* internal_response = response->GetResponse(); - const bool is_opaque = internal_response->GetType() == - network::mojom::FetchResponseType::kOpaque || - internal_response->GetType() == - network::mojom::FetchResponseType::kOpaqueRedirect; - if (internal_response->GetType() != - network::mojom::FetchResponseType::kDefault) - internal_response = internal_response->InternalResponse(); - - if (!foreign_fetch_response.hasOrigin()) { - if (foreign_fetch_response.hasHeaders() && - !foreign_fetch_response.headers().IsEmpty()) { - OnResponseRejected( - ServiceWorkerResponseError::kForeignFetchHeadersWithoutOrigin); - return; - } - - // If response isn't already opaque, make it opaque. - if (!is_opaque) { - FetchResponseData* opaque_data = - internal_response->CreateOpaqueFilteredResponse(); - response = Response::Create(GetExecutionContext(), opaque_data); - } - } else if (request_origin_->ToString() != foreign_fetch_response.origin()) { - OnResponseRejected( - ServiceWorkerResponseError::kForeignFetchMismatchedOrigin); - return; - } else if (!is_opaque) { - WebHTTPHeaderSet headers; - if (foreign_fetch_response.hasHeaders()) { - for (const String& header : foreign_fetch_response.headers()) - headers.emplace(header.Ascii().data(), header.Ascii().length()); - if (response->GetResponse()->GetType() == - network::mojom::FetchResponseType::kCORS) { - const WebHTTPHeaderSet& existing_headers = - response->GetResponse()->CorsExposedHeaderNames(); - for (WebHTTPHeaderSet::iterator it = headers.begin(); - it != headers.end();) { - if (existing_headers.find(*it) == existing_headers.end()) { - it = headers.erase(it); - } else { - ++it; - } - } - } - } - FetchResponseData* response_data = - internal_response->CreateCORSFilteredResponse(headers); - response = Response::Create(GetExecutionContext(), response_data); - } - - FetchRespondWithObserver::OnResponseFulfilled( - ScriptValue::From(value.GetScriptState(), response)); -} - -ForeignFetchRespondWithObserver::ForeignFetchRespondWithObserver( - ExecutionContext* context, - int event_id, - const KURL& request_url, - network::mojom::FetchRequestMode request_mode, - WebURLRequest::FetchRedirectMode redirect_mode, - WebURLRequest::FrameType frame_type, - WebURLRequest::RequestContext request_context, - scoped_refptr<SecurityOrigin> request_origin, - WaitUntilObserver* observer) - : FetchRespondWithObserver(context, - event_id, - request_url, - request_mode, - redirect_mode, - frame_type, - request_context, - observer), - request_origin_(std::move(request_origin)) {} - -} // namespace blink
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ForeignFetchRespondWithObserver.h b/third_party/WebKit/Source/modules/serviceworkers/ForeignFetchRespondWithObserver.h deleted file mode 100644 index f5ab4cb8..0000000 --- a/third_party/WebKit/Source/modules/serviceworkers/ForeignFetchRespondWithObserver.h +++ /dev/null
@@ -1,47 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef ForeignFetchRespondWithObserver_h -#define ForeignFetchRespondWithObserver_h - -#include "modules/serviceworkers/FetchRespondWithObserver.h" -#include "services/network/public/interfaces/fetch_api.mojom-blink.h" - -namespace blink { - -// This class observes the service worker's handling of a ForeignFetchEvent and -// notifies the client. -class MODULES_EXPORT ForeignFetchRespondWithObserver final - : public FetchRespondWithObserver { - public: - static ForeignFetchRespondWithObserver* Create( - ExecutionContext*, - int event_id, - const KURL& request_url, - network::mojom::FetchRequestMode, - WebURLRequest::FetchRedirectMode, - WebURLRequest::FrameType, - WebURLRequest::RequestContext, - scoped_refptr<SecurityOrigin>, - WaitUntilObserver*); - - void OnResponseFulfilled(const ScriptValue&) override; - - private: - ForeignFetchRespondWithObserver(ExecutionContext*, - int event_id, - const KURL& request_url, - network::mojom::FetchRequestMode, - WebURLRequest::FetchRedirectMode, - WebURLRequest::FrameType, - WebURLRequest::RequestContext, - scoped_refptr<SecurityOrigin>, - WaitUntilObserver*); - - scoped_refptr<SecurityOrigin> request_origin_; -}; - -} // namespace blink - -#endif // ForeignFetchRespondWithObserver_h
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ForeignFetchResponse.idl b/third_party/WebKit/Source/modules/serviceworkers/ForeignFetchResponse.idl deleted file mode 100644 index 53ac924f..0000000 --- a/third_party/WebKit/Source/modules/serviceworkers/ForeignFetchResponse.idl +++ /dev/null
@@ -1,11 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// https://w3c.github.io/ServiceWorker/#dictdef-foreignfetchresponse - -dictionary ForeignFetchResponse { - required Response response; - USVString origin; - sequence<ByteString> headers; -};
diff --git a/third_party/WebKit/Source/modules/serviceworkers/InstallEvent.cpp b/third_party/WebKit/Source/modules/serviceworkers/InstallEvent.cpp index b09f7084..30aa548 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/InstallEvent.cpp +++ b/third_party/WebKit/Source/modules/serviceworkers/InstallEvent.cpp
@@ -26,73 +26,6 @@ InstallEvent::~InstallEvent() {} -void InstallEvent::registerForeignFetch(ScriptState* script_state, - const ForeignFetchOptions& options, - ExceptionState& exception_state) { - if (!IsBeingDispatched()) { - exception_state.ThrowDOMException(kInvalidStateError, - "The event handler is already finished."); - return; - } - - if (!options.hasOrigins() || options.origins().IsEmpty()) { - exception_state.ThrowTypeError("At least one origin is required"); - return; - } - const Vector<String>& origin_list = options.origins(); - - // The origins parameter is either just a "*" to indicate all origins, or an - // explicit list of origins as absolute URLs. Internally an empty list of - // origins is used to represent the "*" case though. - Vector<scoped_refptr<SecurityOrigin>> parsed_origins; - if (origin_list.size() != 1 || origin_list[0] != "*") { - parsed_origins.resize(origin_list.size()); - for (size_t i = 0; i < origin_list.size(); ++i) { - parsed_origins[i] = SecurityOrigin::CreateFromString(origin_list[i]); - // Invalid URLs will result in a unique origin. And in general - // unique origins should not be accepted. - if (parsed_origins[i]->IsUnique()) { - exception_state.ThrowTypeError("Invalid origin URL: " + origin_list[i]); - return; - } - } - } - - ExecutionContext* execution_context = ExecutionContext::From(script_state); - ServiceWorkerGlobalScopeClient* client = - ServiceWorkerGlobalScopeClient::From(execution_context); - - String scope_path = static_cast<KURL>(client->Scope()).GetPath(); - scoped_refptr<SecurityOrigin> origin = execution_context->GetSecurityOrigin(); - - if (!options.hasScopes() || options.scopes().IsEmpty()) { - exception_state.ThrowTypeError("At least one scope is required"); - return; - } - const Vector<String>& sub_scopes = options.scopes(); - Vector<KURL> sub_scope_urls(sub_scopes.size()); - for (size_t i = 0; i < sub_scopes.size(); ++i) { - sub_scope_urls[i] = execution_context->CompleteURL(sub_scopes[i]); - if (!sub_scope_urls[i].IsValid()) { - exception_state.ThrowTypeError("Invalid subscope URL: " + sub_scopes[i]); - return; - } - sub_scope_urls[i].RemoveFragmentIdentifier(); - if (!origin->CanRequest(sub_scope_urls[i])) { - exception_state.ThrowTypeError("Subscope URL is not within scope: " + - sub_scopes[i]); - return; - } - String sub_scope_path = sub_scope_urls[i].GetPath(); - if (!sub_scope_path.StartsWith(scope_path)) { - exception_state.ThrowTypeError("Subscope URL is not within scope: " + - sub_scopes[i]); - return; - } - } - client->RegisterForeignFetchScopes(event_id_, sub_scope_urls, parsed_origins); -} - const AtomicString& InstallEvent::InterfaceName() const { return EventNames::InstallEvent; }
diff --git a/third_party/WebKit/Source/modules/serviceworkers/InstallEvent.h b/third_party/WebKit/Source/modules/serviceworkers/InstallEvent.h index 360fdb6..234d42fbb 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/InstallEvent.h +++ b/third_party/WebKit/Source/modules/serviceworkers/InstallEvent.h
@@ -8,7 +8,6 @@ #include "modules/EventModules.h" #include "modules/ModulesExport.h" #include "modules/serviceworkers/ExtendableEvent.h" -#include "modules/serviceworkers/ForeignFetchOptions.h" namespace blink { @@ -25,10 +24,6 @@ ~InstallEvent() override; - void registerForeignFetch(ScriptState*, - const ForeignFetchOptions&, - ExceptionState&); - const AtomicString& InterfaceName() const override; protected:
diff --git a/third_party/WebKit/Source/modules/serviceworkers/InstallEvent.idl b/third_party/WebKit/Source/modules/serviceworkers/InstallEvent.idl index 2113e2f..ce16062 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/InstallEvent.idl +++ b/third_party/WebKit/Source/modules/serviceworkers/InstallEvent.idl
@@ -8,5 +8,4 @@ Constructor(DOMString type, optional ExtendableEventInit eventInitDict), Exposed=ServiceWorker ] interface InstallEvent : ExtendableEvent { - [OriginTrialEnabled=ForeignFetch, CallWith=ScriptState, RaisesException] void registerForeignFetch(ForeignFetchOptions options); };
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScope.h b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScope.h index b7d4efc3..89709cb2 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScope.h +++ b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScope.h
@@ -114,7 +114,6 @@ DEFINE_ATTRIBUTE_EVENT_LISTENER(activate); DEFINE_ATTRIBUTE_EVENT_LISTENER(fetch); DEFINE_ATTRIBUTE_EVENT_LISTENER(message); - DEFINE_ATTRIBUTE_EVENT_LISTENER(foreignfetch); void Trace(blink::Visitor*) override;
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScope.idl b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScope.idl index 4efdf5a..aca0474 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScope.idl +++ b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScope.idl
@@ -46,5 +46,4 @@ attribute EventHandler onfetch; attribute EventHandler oninstall; attribute EventHandler onmessage; - [OriginTrialEnabled=ForeignFetch] attribute EventHandler onforeignfetch; };
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScopeClient.cpp b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScopeClient.cpp index 1ab4dac..94f8444f 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScopeClient.cpp +++ b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScopeClient.cpp
@@ -80,10 +80,6 @@ client_.ClearCachedMetadata(url); } -WebURL ServiceWorkerGlobalScopeClient::Scope() const { - return client_.Scope(); -} - void ServiceWorkerGlobalScopeClient::DidHandleActivateEvent( int event_id, mojom::ServiceWorkerEventStatus status, @@ -274,13 +270,6 @@ client_.Navigate(client_uuid, url, std::move(callback)); } -void ServiceWorkerGlobalScopeClient::RegisterForeignFetchScopes( - int install_event_id, - const WebVector<WebURL>& sub_scopes, - const WebVector<WebSecurityOrigin>& origins) { - client_.RegisterForeignFetchScopes(install_event_id, sub_scopes, origins); -} - const char* ServiceWorkerGlobalScopeClient::SupplementName() { return "ServiceWorkerGlobalScopeClient"; }
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScopeClient.h b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScopeClient.h index 2b195a0..5260f4cd 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScopeClient.h +++ b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScopeClient.h
@@ -77,8 +77,6 @@ void SetCachedMetadata(const WebURL&, const char*, size_t); void ClearCachedMetadata(const WebURL&); - WebURL Scope() const; - void DidHandleActivateEvent(int event_id, mojom::ServiceWorkerEventStatus, double event_dispatch_time); @@ -152,9 +150,6 @@ void Navigate(const WebString& client_uuid, const WebURL&, std::unique_ptr<WebServiceWorkerClientCallbacks>); - void RegisterForeignFetchScopes(int install_event_id, - const WebVector<WebURL>& sub_scopes, - const WebVector<WebSecurityOrigin>&); static const char* SupplementName(); static ServiceWorkerGlobalScopeClient* From(ExecutionContext*);
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScopeProxy.cpp b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScopeProxy.cpp index f6217f4..6b0b641d 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScopeProxy.cpp +++ b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScopeProxy.cpp
@@ -69,7 +69,7 @@ #include "modules/serviceworkers/ExtendableEvent.h" #include "modules/serviceworkers/ExtendableMessageEvent.h" #include "modules/serviceworkers/FetchEvent.h" -#include "modules/serviceworkers/ForeignFetchEvent.h" +#include "modules/serviceworkers/FetchRespondWithObserver.h" #include "modules/serviceworkers/InstallEvent.h" #include "modules/serviceworkers/ServiceWorkerClient.h" #include "modules/serviceworkers/ServiceWorkerGlobalScope.h" @@ -367,52 +367,6 @@ encoded_body_length, decoded_body_length); } -void ServiceWorkerGlobalScopeProxy::DispatchForeignFetchEvent( - int fetch_event_id, - const WebServiceWorkerRequest& web_request) { - DCHECK(WorkerGlobalScope()->IsContextThread()); - if (!OriginTrials::foreignFetchEnabled(WorkerGlobalScope())) { - // If origin trial tokens have expired, or are otherwise no longer valid - // no events should be dispatched. - // TODO(mek): Ideally the browser wouldn't even start the service worker - // if its tokens have expired. - ServiceWorkerGlobalScopeClient::From(WorkerGlobalScope()) - ->RespondToFetchEventWithNoResponse(fetch_event_id, WTF::CurrentTime()); - ServiceWorkerGlobalScopeClient::From(WorkerGlobalScope()) - ->DidHandleFetchEvent(fetch_event_id, - mojom::ServiceWorkerEventStatus::COMPLETED, - WTF::CurrentTime()); - return; - } - - ScriptState::Scope scope( - WorkerGlobalScope()->ScriptController()->GetScriptState()); - scoped_refptr<SecurityOrigin> origin = - SecurityOrigin::Create(web_request.ReferrerUrl()); - WaitUntilObserver* wait_until_observer = WaitUntilObserver::Create( - WorkerGlobalScope(), WaitUntilObserver::kFetch, fetch_event_id); - ForeignFetchRespondWithObserver* respond_with_observer = - ForeignFetchRespondWithObserver::Create( - WorkerGlobalScope(), fetch_event_id, web_request.Url(), - web_request.Mode(), web_request.RedirectMode(), - web_request.GetFrameType(), web_request.GetRequestContext(), origin, - wait_until_observer); - Request* request = Request::Create( - WorkerGlobalScope()->ScriptController()->GetScriptState(), web_request); - request->getHeaders()->SetGuard(Headers::kImmutableGuard); - ForeignFetchEventInit event_init; - event_init.setCancelable(true); - event_init.setRequest(request); - event_init.setOrigin(origin->ToString()); - ForeignFetchEvent* fetch_event = ForeignFetchEvent::Create( - WorkerGlobalScope()->ScriptController()->GetScriptState(), - EventTypeNames::foreignfetch, event_init, respond_with_observer, - wait_until_observer); - - WorkerGlobalScope()->DispatchExtendableEventWithRespondWith( - fetch_event, wait_until_observer, respond_with_observer); -} - void ServiceWorkerGlobalScopeProxy::DispatchInstallEvent(int event_id) { DCHECK(WorkerGlobalScope()->IsContextThread()); WaitUntilObserver* observer = WaitUntilObserver::Create(
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScopeProxy.h b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScopeProxy.h index fcbae60..cb7f232a 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScopeProxy.h +++ b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScopeProxy.h
@@ -109,8 +109,6 @@ void DispatchFetchEvent(int fetch_event_id, const WebServiceWorkerRequest&, bool navigation_preload_sent) override; - void DispatchForeignFetchEvent(int fetch_event_id, - const WebServiceWorkerRequest&) override; void DispatchInstallEvent(int) override; void DispatchNotificationClickEvent(int, const WebString& notification_id,
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerLinkResource.cpp b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerLinkResource.cpp deleted file mode 100644 index 525fe50a..0000000 --- a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerLinkResource.cpp +++ /dev/null
@@ -1,117 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "modules/serviceworkers/ServiceWorkerLinkResource.h" - -#include <memory> - -#include "bindings/core/v8/ExceptionState.h" -#include "bindings/core/v8/V8BindingForCore.h" -#include "core/dom/Document.h" -#include "core/frame/DOMWindow.h" -#include "core/frame/LocalFrame.h" -#include "core/frame/LocalFrameClient.h" -#include "core/html/HTMLLinkElement.h" -#include "core/inspector/ConsoleMessage.h" -#include "modules/serviceworkers/NavigatorServiceWorker.h" -#include "modules/serviceworkers/ServiceWorkerContainer.h" -#include "platform/bindings/ScriptState.h" -#include "platform/scheduler/child/web_scheduler.h" -#include "platform/wtf/PtrUtil.h" -#include "public/platform/Platform.h" -#include "public/platform/TaskType.h" -#include "public/platform/modules/serviceworker/service_worker_error_type.mojom-blink.h" - -namespace blink { - -namespace { - -class RegistrationCallback - : public WebServiceWorkerProvider::WebServiceWorkerRegistrationCallbacks { - public: - explicit RegistrationCallback(HTMLLinkElement* owner) : owner_(owner) {} - ~RegistrationCallback() override {} - - void OnSuccess( - std::unique_ptr<WebServiceWorkerRegistration::Handle> handle) override { - owner_->GetDocument() - .GetTaskRunner(TaskType::kUnthrottled) - ->PostTask(BLINK_FROM_HERE, - WTF::Bind(&LinkLoaderClient::LinkLoaded, owner_)); - } - - void OnError(const WebServiceWorkerError& error) override { - owner_->GetDocument() - .GetTaskRunner(TaskType::kUnthrottled) - ->PostTask(BLINK_FROM_HERE, - WTF::Bind(&LinkLoaderClient::LinkLoadingErrored, owner_)); - } - - private: - WTF_MAKE_NONCOPYABLE(RegistrationCallback); - - Persistent<HTMLLinkElement> owner_; -}; -} // namespace - -ServiceWorkerLinkResource* ServiceWorkerLinkResource::Create( - HTMLLinkElement* owner) { - return new ServiceWorkerLinkResource(owner); -} - -ServiceWorkerLinkResource::~ServiceWorkerLinkResource() {} - -void ServiceWorkerLinkResource::Process() { - if (!owner_ || !owner_->GetDocument().GetFrame()) - return; - - if (!owner_->ShouldLoadLink()) - return; - - Document& document = owner_->GetDocument(); - - KURL script_url = owner_->Href(); - - String scope = owner_->Scope(); - KURL scope_url; - if (scope.IsNull()) - scope_url = KURL(script_url, "./"); - else - scope_url = document.CompleteURL(scope); - scope_url.RemoveFragmentIdentifier(); - - String error_message; - ServiceWorkerContainer* container = NavigatorServiceWorker::serviceWorker( - ToScriptStateForMainWorld(owner_->GetDocument().GetFrame()), - *document.GetFrame()->DomWindow()->navigator(), error_message); - - if (!container) { - document.AddConsoleMessage(ConsoleMessage::Create( - kJSMessageSource, kErrorMessageLevel, - "Cannot register service worker with <link> element. " + - error_message)); - std::make_unique<RegistrationCallback>(owner_)->OnError( - WebServiceWorkerError(mojom::blink::ServiceWorkerErrorType::kSecurity, - error_message)); - return; - } - - container->RegisterServiceWorkerImpl( - &document, script_url, scope_url, - mojom::ServiceWorkerUpdateViaCache::kImports, - std::make_unique<RegistrationCallback>(owner_)); -} - -bool ServiceWorkerLinkResource::HasLoaded() const { - return false; -} - -void ServiceWorkerLinkResource::OwnerRemoved() { - Process(); -} - -ServiceWorkerLinkResource::ServiceWorkerLinkResource(HTMLLinkElement* owner) - : LinkResource(owner) {} - -} // namespace blink
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerLinkResource.h b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerLinkResource.h deleted file mode 100644 index 95cab9db..0000000 --- a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerLinkResource.h +++ /dev/null
@@ -1,35 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef ServiceWorkerLinkResource_h -#define ServiceWorkerLinkResource_h - -#include "base/memory/scoped_refptr.h" -#include "core/html/LinkResource.h" -#include "modules/ModulesExport.h" -#include "platform/wtf/Allocator.h" - -namespace blink { - -class HTMLLinkElement; - -class MODULES_EXPORT ServiceWorkerLinkResource final : public LinkResource { - public: - static ServiceWorkerLinkResource* Create(HTMLLinkElement* owner); - - ~ServiceWorkerLinkResource() override; - - // LinkResource implementation: - void Process() override; - LinkResourceType GetType() const override { return kOther; } - bool HasLoaded() const override; - void OwnerRemoved() override; - - private: - explicit ServiceWorkerLinkResource(HTMLLinkElement* owner); -}; - -} // namespace blink - -#endif // ServiceWorkerLinkResource_h
diff --git a/third_party/WebKit/Source/modules/serviceworkers/WebEmbeddedWorkerImplTest.cpp b/third_party/WebKit/Source/modules/serviceworkers/WebEmbeddedWorkerImplTest.cpp index 8b768f5a3..9133968 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/WebEmbeddedWorkerImplTest.cpp +++ b/third_party/WebKit/Source/modules/serviceworkers/WebEmbeddedWorkerImplTest.cpp
@@ -93,13 +93,6 @@ std::unique_ptr<WebServiceWorkerClientCallbacks>) override { NOTREACHED(); } - void RegisterForeignFetchScopes( - int install_event_id, - const WebVector<WebURL>& sub_scopes, - const WebVector<WebSecurityOrigin>& origins) override { - NOTREACHED(); - } - void WorkerContextDestroyed() override { termination_event_.Signal(); } void WaitUntilScriptEvaluated() { script_evaluated_event_.Wait(); }
diff --git a/third_party/WebKit/Source/modules/vr/VRDisplay.cpp b/third_party/WebKit/Source/modules/vr/VRDisplay.cpp index 5af4af9..6e6f0f0 100644 --- a/third_party/WebKit/Source/modules/vr/VRDisplay.cpp +++ b/third_party/WebKit/Source/modules/vr/VRDisplay.cpp
@@ -706,7 +706,7 @@ if (present_image_needs_copy_) { #if defined(OS_WIN) TRACE_EVENT0("gpu", "VRDisplay::CopyImage"); - if (!frame_copier_) { + if (!frame_copier_ || !last_transfer_succeeded_) { frame_copier_ = std::make_unique<GpuMemoryBufferImageCopy>(context_gl_); } auto gpu_memory_buffer = frame_copier_->CopyImage(image_ref.get()); @@ -784,9 +784,10 @@ rendering_context_->MarkCompositedAndClearBackbufferIfNeeded(); } -void VRDisplay::OnSubmitFrameTransferred() { +void VRDisplay::OnSubmitFrameTransferred(bool success) { DVLOG(3) << __FUNCTION__; pending_submit_frame_ = false; + last_transfer_succeeded_ = success; } void VRDisplay::OnSubmitFrameRendered() {
diff --git a/third_party/WebKit/Source/modules/vr/VRDisplay.h b/third_party/WebKit/Source/modules/vr/VRDisplay.h index b0c23e6..465b300 100644 --- a/third_party/WebKit/Source/modules/vr/VRDisplay.h +++ b/third_party/WebKit/Source/modules/vr/VRDisplay.h
@@ -133,7 +133,7 @@ void OnPresentChange(); // VRSubmitFrameClient - void OnSubmitFrameTransferred() override; + void OnSubmitFrameTransferred(bool success) override; void OnSubmitFrameRendered() override; // VRDisplayClient @@ -215,6 +215,7 @@ bool pending_previous_frame_render_ = false; bool pending_submit_frame_ = false; bool pending_present_request_ = false; + bool last_transfer_succeeded_ = false; device::mojom::blink::VRMagicWindowProviderPtr magic_window_provider_; device::mojom::blink::VRDisplayHostPtr display_;
diff --git a/third_party/WebKit/Source/modules/webaudio/RealtimeAnalyser.cpp b/third_party/WebKit/Source/modules/webaudio/RealtimeAnalyser.cpp index 808fa12a..fd103d90 100644 --- a/third_party/WebKit/Source/modules/webaudio/RealtimeAnalyser.cpp +++ b/third_party/WebKit/Source/modules/webaudio/RealtimeAnalyser.cpp
@@ -86,16 +86,17 @@ if (!is_bus_good) return; + unsigned write_index = GetWriteIndex(); // FIXME : allow to work with non-FFTSize divisible chunking bool is_destination_good = - write_index_ < input_buffer_.size() && - write_index_ + frames_to_process <= input_buffer_.size(); + write_index < input_buffer_.size() && + write_index + frames_to_process <= input_buffer_.size(); DCHECK(is_destination_good); if (!is_destination_good) return; // Perform real-time analysis - float* dest = input_buffer_.Data() + write_index_; + float* dest = input_buffer_.Data() + write_index; // Clear the bus and downmix the input according to the down mixing rules. // Then save the result in the m_inputBuffer at the appropriate place. @@ -104,9 +105,10 @@ memcpy(dest, down_mix_bus_->Channel(0)->Data(), frames_to_process * sizeof(*dest)); - write_index_ += frames_to_process; - if (write_index_ >= kInputBufferSize) - write_index_ = 0; + write_index += frames_to_process; + if (write_index >= kInputBufferSize) + write_index = 0; + SetWriteIndex(write_index); } namespace { @@ -143,7 +145,7 @@ // Take the previous fftSize values from the input buffer and copy into the // temporary buffer. - unsigned write_index = write_index_; + unsigned write_index = GetWriteIndex(); if (write_index < fft_size) { memcpy(temp_p, input_buffer + write_index - fft_size + kInputBufferSize, sizeof(*temp_p) * (fft_size - write_index)); @@ -290,7 +292,7 @@ float* input_buffer = input_buffer_.Data(); float* destination = destination_array->Data(); - unsigned write_index = write_index_; + unsigned write_index = GetWriteIndex(); for (unsigned i = 0; i < len; ++i) { // Buffer access is protected due to modulo operation. @@ -319,7 +321,7 @@ float* input_buffer = input_buffer_.Data(); unsigned char* destination = destination_array->Data(); - unsigned write_index = write_index_; + unsigned write_index = GetWriteIndex(); for (unsigned i = 0; i < len; ++i) { // Buffer access is protected due to modulo operation.
diff --git a/third_party/WebKit/Source/modules/webaudio/RealtimeAnalyser.h b/third_party/WebKit/Source/modules/webaudio/RealtimeAnalyser.h index b3e70e63..419b438 100644 --- a/third_party/WebKit/Source/modules/webaudio/RealtimeAnalyser.h +++ b/third_party/WebKit/Source/modules/webaudio/RealtimeAnalyser.h
@@ -79,6 +79,11 @@ AudioFloatArray input_buffer_; unsigned write_index_; + unsigned GetWriteIndex() const { return AcquireLoad(&write_index_); } + void SetWriteIndex(unsigned new_index) { + ReleaseStore(&write_index_, new_index); + } + // Input audio is downmixed to this bus before copying to m_inputBuffer. scoped_refptr<AudioBus> down_mix_bus_;
diff --git a/third_party/WebKit/Source/modules/websockets/WebSocketHandleImpl.cpp b/third_party/WebKit/Source/modules/websockets/WebSocketHandleImpl.cpp index ecad99f..4549e2a 100644 --- a/third_party/WebKit/Source/modules/websockets/WebSocketHandleImpl.cpp +++ b/third_party/WebKit/Source/modules/websockets/WebSocketHandleImpl.cpp
@@ -62,8 +62,7 @@ client_ = client; mojom::blink::WebSocketClientPtr client_proxy; - client_binding_.Bind(mojo::MakeRequest( - &client_proxy, task_runner->ToSingleThreadTaskRunner())); + client_binding_.Bind(mojo::MakeRequest(&client_proxy, task_runner)); // TODO(crbug.com/786608) remove the following CHECKs once bug is solved. CHECK(url.IsValid());
diff --git a/third_party/WebKit/Source/platform/BUILD.gn b/third_party/WebKit/Source/platform/BUILD.gn index 461ca53..f21cde14 100644 --- a/third_party/WebKit/Source/platform/BUILD.gn +++ b/third_party/WebKit/Source/platform/BUILD.gn
@@ -656,6 +656,7 @@ "fonts/AlternateFontFamily.h", "fonts/BitmapGlyphsBlacklist.cpp", "fonts/BitmapGlyphsBlacklist.h", + "fonts/CanvasRotationInVertical.h", "fonts/CharacterRange.h", "fonts/CustomFontData.h", "fonts/FallbackListCompositeKey.h", @@ -1802,6 +1803,7 @@ "geometry/IntRectTest.cpp", "geometry/LayoutRectOutsetsTest.cpp", "geometry/LayoutRectTest.cpp", + "geometry/LayoutSizeTest.cpp", "geometry/RegionTest.cpp", "graphics/BitmapImageTest.cpp", "graphics/CompositorElementIdTest.cpp",
diff --git a/third_party/WebKit/Source/platform/Timer.cpp b/third_party/WebKit/Source/platform/Timer.cpp index c7084af..f922674 100644 --- a/third_party/WebKit/Source/platform/Timer.cpp +++ b/third_party/WebKit/Source/platform/Timer.cpp
@@ -89,8 +89,7 @@ DCHECK(task_runner->RunsTasksInCurrentSequence()); #endif // If the underlying task runner stays the same, ignore it. - if (web_task_runner_->ToSingleThreadTaskRunner() == - task_runner->ToSingleThreadTaskRunner()) { + if (web_task_runner_ == task_runner) { return; }
diff --git a/third_party/WebKit/Source/platform/WebTaskRunner.h b/third_party/WebKit/Source/platform/WebTaskRunner.h index cabeff97..e2c2d59 100644 --- a/third_party/WebKit/Source/platform/WebTaskRunner.h +++ b/third_party/WebKit/Source/platform/WebTaskRunner.h
@@ -7,6 +7,7 @@ #include <memory> #include "base/callback.h" +#include "base/single_thread_task_runner.h" #include "platform/wtf/Compiler.h" #include "platform/wtf/Functional.h" #include "platform/wtf/RefCounted.h" @@ -56,11 +57,11 @@ // The blink representation of a chromium SingleThreadTaskRunner. class BLINK_PLATFORM_EXPORT WebTaskRunner - : public ThreadSafeRefCounted<WebTaskRunner> { + : public base::SingleThreadTaskRunner { public: - // Returns true if tasks posted to this TaskRunner are sequenced - // with this call. - virtual bool RunsTasksInCurrentSequence() = 0; + virtual bool PostDelayedTask(const base::Location&, + base::OnceClosure, + base::TimeDelta) = 0; // Returns a microsecond resolution platform dependant time source. // This may represent either the real time, or a virtual time depending on @@ -68,10 +69,6 @@ // or a real time domain. virtual double MonotonicallyIncreasingVirtualTimeSeconds() const = 0; - // Returns the underlying task runner object. - virtual scoped_refptr<base::SingleThreadTaskRunner> - ToSingleThreadTaskRunner() = 0; - // Helpers for posting bound functions as tasks. // For cross-thread posting. Can be called from any thread. @@ -98,10 +95,6 @@ WebTaskRunner() = default; virtual ~WebTaskRunner(); - virtual bool PostDelayedTask(const base::Location&, - base::OnceClosure, - base::TimeDelta) = 0; - private: DISALLOW_COPY_AND_ASSIGN(WebTaskRunner); };
diff --git a/third_party/WebKit/Source/platform/WebThread.cpp b/third_party/WebKit/Source/platform/WebThread.cpp index 7cd056b..b8b1eb7 100644 --- a/third_party/WebKit/Source/platform/WebThread.cpp +++ b/third_party/WebKit/Source/platform/WebThread.cpp
@@ -29,7 +29,7 @@ scoped_refptr<base::SingleThreadTaskRunner> WebThread::GetSingleThreadTaskRunner() { - return GetWebTaskRunner()->ToSingleThreadTaskRunner(); + return GetWebTaskRunner(); } } // namespace blink
diff --git a/third_party/WebKit/Source/platform/bindings/V8PerIsolateData.cpp b/third_party/WebKit/Source/platform/bindings/V8PerIsolateData.cpp index 9ebda45..31d64cf 100644 --- a/third_party/WebKit/Source/platform/bindings/V8PerIsolateData.cpp +++ b/third_party/WebKit/Source/platform/bindings/V8PerIsolateData.cpp
@@ -63,7 +63,7 @@ V8ContextSnapshotMode v8_context_snapshot_mode) : v8_context_snapshot_mode_(v8_context_snapshot_mode), isolate_holder_( - task_runner ? task_runner->ToSingleThreadTaskRunner() : nullptr, + task_runner, gin::IsolateHolder::kSingleThread, IsMainThread() ? gin::IsolateHolder::kDisallowAtomicsWait : gin::IsolateHolder::kAllowAtomicsWait,
diff --git a/third_party/WebKit/Source/platform/exported/WebCORS.cpp b/third_party/WebKit/Source/platform/exported/WebCORS.cpp index 0ee9b82..17583920 100644 --- a/third_party/WebKit/Source/platform/exported/WebCORS.cpp +++ b/third_party/WebKit/Source/platform/exported/WebCORS.cpp
@@ -516,9 +516,8 @@ void ExtractCorsExposedHeaderNamesList(const WebURLResponse& response, WebHTTPHeaderSet& header_set) { // If a response was fetched via a service worker, it will always have - // CorsExposedHeaderNames set, either from the Access-Control-Expose-Headers - // header, or explicitly via foreign fetch. For requests that didn't come from - // a service worker, foreign fetch doesn't apply so just parse the CORS + // CorsExposedHeaderNames set from the Access-Control-Expose-Headers header. + // For requests that didn't come from a service worker, just parse the CORS // header. if (response.WasFetchedViaServiceWorker()) { for (const auto& header : response.CorsExposedHeaderNames())
diff --git a/third_party/WebKit/Source/platform/exported/WebURLRequest.cpp b/third_party/WebKit/Source/platform/exported/WebURLRequest.cpp index 3c803548..d20dc63 100644 --- a/third_party/WebKit/Source/platform/exported/WebURLRequest.cpp +++ b/third_party/WebKit/Source/platform/exported/WebURLRequest.cpp
@@ -253,12 +253,12 @@ resource_request_->SetRequestorID(requestor_id); } -int WebURLRequest::RequestorProcessID() const { - return resource_request_->RequestorProcessID(); +int WebURLRequest::GetPluginChildID() const { + return resource_request_->GetPluginChildID(); } -void WebURLRequest::SetRequestorProcessID(int requestor_process_id) { - resource_request_->SetRequestorProcessID(requestor_process_id); +void WebURLRequest::SetPluginChildID(int plugin_child_id) { + resource_request_->SetPluginChildID(plugin_child_id); } int WebURLRequest::AppCacheHostID() const {
diff --git a/third_party/WebKit/Source/platform/exported/WebURLResponse.cpp b/third_party/WebKit/Source/platform/exported/WebURLResponse.cpp index ddd963c..461bcf5 100644 --- a/third_party/WebKit/Source/platform/exported/WebURLResponse.cpp +++ b/third_party/WebKit/Source/platform/exported/WebURLResponse.cpp
@@ -290,10 +290,6 @@ resource_response_->SetWasFetchedViaServiceWorker(value); } -void WebURLResponse::SetWasFetchedViaForeignFetch(bool value) { - resource_response_->SetWasFetchedViaForeignFetch(value); -} - void WebURLResponse::SetWasFallbackRequiredByServiceWorker(bool value) { resource_response_->SetWasFallbackRequiredByServiceWorker(value); }
diff --git a/third_party/WebKit/Source/platform/fonts/CanvasRotationInVertical.h b/third_party/WebKit/Source/platform/fonts/CanvasRotationInVertical.h new file mode 100644 index 0000000..e65562b96 --- /dev/null +++ b/third_party/WebKit/Source/platform/fonts/CanvasRotationInVertical.h
@@ -0,0 +1,13 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CanvasRotationInVertical_h +#define CanvasRotationInVertical_h + +namespace blink { + +enum class CanvasRotationInVertical : char { kRegular, kRotateCanvasUpright }; +} + +#endif
diff --git a/third_party/WebKit/Source/platform/fonts/FontDataCache.cpp b/third_party/WebKit/Source/platform/fonts/FontDataCache.cpp index 77a30ba..c60998af 100644 --- a/third_party/WebKit/Source/platform/fonts/FontDataCache.cpp +++ b/third_party/WebKit/Source/platform/fonts/FontDataCache.cpp
@@ -61,7 +61,7 @@ Cache::iterator result = cache_.find(platform_data); if (result == cache_.end()) { std::pair<scoped_refptr<SimpleFontData>, unsigned> new_value( - SimpleFontData::Create(*platform_data, nullptr, false, + SimpleFontData::Create(*platform_data, nullptr, subpixel_ascent_descent), should_retain == kRetain ? 1 : 0); // The new SimpleFontData takes a copy of the incoming FontPlatformData
diff --git a/third_party/WebKit/Source/platform/fonts/SimpleFontData.cpp b/third_party/WebKit/Source/platform/fonts/SimpleFontData.cpp index 400f8b3e..c67bd976 100644 --- a/third_party/WebKit/Source/platform/fonts/SimpleFontData.cpp +++ b/third_party/WebKit/Source/platform/fonts/SimpleFontData.cpp
@@ -56,13 +56,11 @@ SimpleFontData::SimpleFontData(const FontPlatformData& platform_data, scoped_refptr<CustomFontData> custom_data, - bool is_text_orientation_fallback, bool subpixel_ascent_descent) : max_char_width_(-1), avg_char_width_(-1), platform_data_(platform_data), custom_font_data_(std::move(custom_data)), - is_text_orientation_fallback_(is_text_orientation_fallback), visual_overflow_inflation_for_ascent_(0), visual_overflow_inflation_for_descent_(0) { PlatformInit(subpixel_ascent_descent); @@ -203,20 +201,6 @@ return false; } -scoped_refptr<SimpleFontData> SimpleFontData::VerticalRightOrientationFontData() - const { - if (!derived_font_data_) - derived_font_data_ = DerivedFontData::Create(); - if (!derived_font_data_->vertical_right_orientation) { - FontPlatformData vertical_right_platform_data(platform_data_); - vertical_right_platform_data.SetOrientation(FontOrientation::kHorizontal); - derived_font_data_->vertical_right_orientation = - Create(vertical_right_platform_data, - IsCustomFont() ? CustomFontData::Create() : nullptr, true); - } - return derived_font_data_->vertical_right_orientation; -} - scoped_refptr<SimpleFontData> SimpleFontData::SmallCapsFontData( const FontDescription& font_description) const { if (!derived_font_data_) @@ -239,13 +223,6 @@ return derived_font_data_->emphasis_mark; } -bool SimpleFontData::IsTextOrientationFallbackOf( - const SimpleFontData* font_data) const { - if (!IsTextOrientationFallback() || !font_data->derived_font_data_) - return false; - return font_data->derived_font_data_->vertical_right_orientation == this; -} - std::unique_ptr<SimpleFontData::DerivedFontData> SimpleFontData::DerivedFontData::Create() { return WTF::WrapUnique(new DerivedFontData());
diff --git a/third_party/WebKit/Source/platform/fonts/SimpleFontData.h b/third_party/WebKit/Source/platform/fonts/SimpleFontData.h index 6ac09d7..f9584d4 100644 --- a/third_party/WebKit/Source/platform/fonts/SimpleFontData.h +++ b/third_party/WebKit/Source/platform/fonts/SimpleFontData.h
@@ -30,6 +30,7 @@ #include "build/build_config.h" #include "platform/PlatformExport.h" +#include "platform/fonts/CanvasRotationInVertical.h" #include "platform/fonts/CustomFontData.h" #include "platform/fonts/FontBaseline.h" #include "platform/fonts/FontData.h" @@ -50,10 +51,15 @@ // given // character. struct GlyphData { - GlyphData(Glyph g = 0, const SimpleFontData* f = nullptr) - : glyph(g), font_data(f) {} + STACK_ALLOCATED(); + GlyphData( + Glyph g = 0, + const SimpleFontData* f = nullptr, + CanvasRotationInVertical rotation = CanvasRotationInVertical::kRegular) + : glyph(g), font_data(f), canvas_rotation(rotation) {} Glyph glyph; const SimpleFontData* font_data; + CanvasRotationInVertical canvas_rotation; }; class FontDescription; @@ -64,27 +70,15 @@ static scoped_refptr<SimpleFontData> Create( const FontPlatformData& platform_data, scoped_refptr<CustomFontData> custom_data = nullptr, - bool is_text_orientation_fallback = false, bool subpixel_ascent_descent = false) { return base::AdoptRef(new SimpleFontData( - platform_data, std::move(custom_data), is_text_orientation_fallback, - subpixel_ascent_descent)); + platform_data, std::move(custom_data), subpixel_ascent_descent)); } const FontPlatformData& PlatformData() const { return platform_data_; } - bool UsedVertically() const { - return platform_data_.IsVerticalAnyUpright() && - !is_text_orientation_fallback_; - } scoped_refptr<SimpleFontData> SmallCapsFontData(const FontDescription&) const; scoped_refptr<SimpleFontData> EmphasisMarkFontData(const FontDescription&) const; - scoped_refptr<SimpleFontData> VerticalRightOrientationFontData() const; - - bool IsTextOrientationFallback() const { - return is_text_orientation_fallback_; - } - bool IsTextOrientationFallbackOf(const SimpleFontData*) const; FontMetrics& GetFontMetrics() { return font_metrics_; } const FontMetrics& GetFontMetrics() const { return font_metrics_; } @@ -152,7 +146,6 @@ protected: SimpleFontData(const FontPlatformData&, scoped_refptr<CustomFontData> custom_data, - bool is_text_orientation_fallback = false, bool subpixel_ascent_descent = false); private: @@ -185,7 +178,6 @@ scoped_refptr<SimpleFontData> small_caps; scoped_refptr<SimpleFontData> emphasis_mark; - scoped_refptr<SimpleFontData> vertical_right_orientation; private: DerivedFontData() {} @@ -195,8 +187,6 @@ scoped_refptr<CustomFontData> custom_font_data_; - unsigned is_text_orientation_fallback_ : 1; - // These are set to non-zero when ascent or descent is rounded or shifted // to be smaller than the actual ascent or descent. When calculating visual // overflows, we should add the inflations.
diff --git a/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzShaper.cpp b/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzShaper.cpp index 1eaf9e4..e1976dd 100644 --- a/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzShaper.cpp +++ b/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzShaper.cpp
@@ -159,12 +159,14 @@ FeaturesVector font_features; Deque<ReshapeQueueItem> reshape_queue; - hb_direction_t HarfBuzzDirection(const SimpleFontData* font_data) { + hb_direction_t HarfBuzzDirection(CanvasRotationInVertical canvas_rotation) { FontOrientation orientation = font->GetFontDescription().Orientation(); - hb_direction_t direction = IsVerticalAnyUpright(orientation) && - !font_data->IsTextOrientationFallback() - ? HB_DIRECTION_TTB - : HB_DIRECTION_LTR; + hb_direction_t direction = + IsVerticalAnyUpright(orientation) && + (canvas_rotation == + CanvasRotationInVertical::kRotateCanvasUpright) + ? HB_DIRECTION_TTB + : HB_DIRECTION_LTR; return text_direction == TextDirection::kRtl ? HB_DIRECTION_REVERSE(direction) : direction; @@ -278,19 +280,31 @@ kReshapeQueueRange, slice.start_character_index, slice.num_characters)); } +CanvasRotationInVertical CanvasRotationForRun( + FontOrientation font_orientation, + OrientationIterator::RenderOrientation render_orientation) { + if (font_orientation == FontOrientation::kVerticalUpright || + (font_orientation == FontOrientation::kVerticalMixed && + render_orientation == OrientationIterator::kOrientationKeep)) + return CanvasRotationInVertical::kRotateCanvasUpright; + return CanvasRotationInVertical::kRegular; +} + } // namespace void HarfBuzzShaper::CommitGlyphs(RangeData* range_data, const SimpleFontData* current_font, UScriptCode current_run_script, + CanvasRotationInVertical canvas_rotation, bool is_last_resort, const BufferSlice& slice, ShapeResult* shape_result) const { - hb_direction_t direction = range_data->HarfBuzzDirection(current_font); + hb_direction_t direction = range_data->HarfBuzzDirection(canvas_rotation); // Here we need to specify glyph positions. ShapeResult::RunInfo* run = new ShapeResult::RunInfo( - current_font, direction, ICUScriptToHBScript(current_run_script), - slice.start_character_index, slice.num_glyphs, slice.num_characters); + current_font, direction, canvas_rotation, + ICUScriptToHBScript(current_run_script), slice.start_character_index, + slice.num_glyphs, slice.num_characters); shape_result->InsertRun(WTF::WrapUnique(run), slice.start_glyph_index, slice.num_glyphs, range_data->buffer); if (is_last_resort) @@ -303,6 +317,7 @@ const ReshapeQueueItem& current_queue_item, const SimpleFontData* current_font, UScriptCode current_run_script, + CanvasRotationInVertical canvas_rotation, bool is_last_resort, ShapeResult* shape_result) const { enum ClusterResult { kShaped, kNotDef, kUnknown }; @@ -351,7 +366,7 @@ // the glyphs. We also commit when we've reached the last resort // font. CommitGlyphs(range_data, current_font, current_run_script, - is_last_resort, slice, shape_result); + canvas_rotation, is_last_resort, slice, shape_result); } last_change_glyph_index = previous_cluster_start_glyph_index; } @@ -385,14 +400,14 @@ slice = ComputeSlice(range_data, current_queue_item, glyph_info, num_glyphs, previous_cluster_start_glyph_index, num_glyphs); - CommitGlyphs(range_data, current_font, current_run_script, is_last_resort, - slice, shape_result); + CommitGlyphs(range_data, current_font, current_run_script, + canvas_rotation, is_last_resort, slice, shape_result); } else { BufferSlice slice = ComputeSlice( range_data, current_queue_item, glyph_info, num_glyphs, last_change_glyph_index, previous_cluster_start_glyph_index); - CommitGlyphs(range_data, current_font, current_run_script, is_last_resort, - slice, shape_result); + CommitGlyphs(range_data, current_font, current_run_script, + canvas_rotation, is_last_resort, slice, shape_result); slice = ComputeSlice(range_data, current_queue_item, glyph_info, num_glyphs, previous_cluster_start_glyph_index, num_glyphs); @@ -407,27 +422,12 @@ if (current_cluster_result == kNotDef && !is_last_resort) { QueueCharacters(range_data, current_font, font_cycle_queued, slice); } else { - CommitGlyphs(range_data, current_font, current_run_script, is_last_resort, - slice, shape_result); + CommitGlyphs(range_data, current_font, current_run_script, + canvas_rotation, is_last_resort, slice, shape_result); } } } -static inline const SimpleFontData* FontDataAdjustedForOrientation( - const SimpleFontData* original_font, - FontOrientation run_orientation, - OrientationIterator::RenderOrientation render_orientation) { - if (!IsVerticalBaseline(run_orientation)) - return original_font; - - if (run_orientation == FontOrientation::kVerticalRotated || - (run_orientation == FontOrientation::kVerticalMixed && - render_orientation == OrientationIterator::kOrientationRotateSideways)) - return original_font->VerticalRightOrientationFontData().get(); - - return original_font; -} - bool HarfBuzzShaper::CollectFallbackHintChars( const Deque<ReshapeQueueItem>& reshape_queue, Vector<UChar32>& hint) const { @@ -751,7 +751,6 @@ font_description.VariantCaps() != FontDescription::kCapsNormal; OpenTypeCapsSupport caps_support; - FontOrientation orientation = font->GetFontDescription().Orientation(); scoped_refptr<FontFallbackIterator> fallback_iterator = font->CreateFontFallbackIterator(segment.font_fallback_priority); @@ -806,20 +805,12 @@ } DCHECK(current_queue_item.num_characters_); - const SimpleFontData* smallcaps_adjusted_font = + const SimpleFontData* small_caps_adjusted_font = needs_caps_handling && caps_support.NeedsSyntheticFont(small_caps_behavior) ? font_data->SmallCapsFontData(font_description).get() : font_data; - // Compatibility with SimpleFontData approach of keeping a flag for - // overriding drawing direction. - // TODO: crbug.com/506224 This should go away in favor of storing that - // information elsewhere, for example in ShapeResult. - const SimpleFontData* direction_and_small_caps_adjusted_font = - FontDataAdjustedForOrientation(smallcaps_adjusted_font, orientation, - segment.render_orientation); - CaseMapIntend case_map_intend = CaseMapIntend::kKeepSameCase; if (needs_caps_handling) case_map_intend = caps_support.NeedsCaseChange(small_caps_behavior); @@ -836,25 +827,27 @@ case_map_intend, font_description.LocaleOrDefault(), range_data->buffer, text_, text_length_, shape_start, shape_end - shape_start); + CanvasRotationInVertical canvas_rotation = CanvasRotationForRun( + small_caps_adjusted_font->PlatformData().Orientation(), + segment.render_orientation); + CapsFeatureSettingsScopedOverlay caps_overlay( &range_data->font_features, caps_support.FontFeatureToUse(small_caps_behavior)); - hb_direction_t direction = - range_data->HarfBuzzDirection(direction_and_small_caps_adjusted_font); + hb_direction_t direction = range_data->HarfBuzzDirection(canvas_rotation); if (!ShapeRange(range_data->buffer, range_data->font_features.IsEmpty() ? nullptr : range_data->font_features.data(), - range_data->font_features.size(), - direction_and_small_caps_adjusted_font, + range_data->font_features.size(), small_caps_adjusted_font, current_font_data_for_range_set->Ranges(), segment.script, direction, language)) DLOG(ERROR) << "Shaping range failed."; ExtractShapeResults(range_data, font_cycle_queued, current_queue_item, - direction_and_small_caps_adjusted_font, segment.script, - !fallback_iterator->HasNext(), result); + small_caps_adjusted_font, segment.script, + canvas_rotation, !fallback_iterator->HasNext(), result); hb_buffer_reset(range_data->buffer); }
diff --git a/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzShaper.h b/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzShaper.h index 4c13969..8709e68 100644 --- a/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzShaper.h +++ b/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzShaper.h
@@ -85,6 +85,7 @@ const ReshapeQueueItem&, const SimpleFontData*, UScriptCode, + CanvasRotationInVertical, bool is_last_resort, ShapeResult*) const; @@ -94,6 +95,7 @@ void CommitGlyphs(RangeData*, const SimpleFontData* current_font, UScriptCode current_run_script, + CanvasRotationInVertical, bool is_last_resort, const BufferSlice&, ShapeResult*) const;
diff --git a/third_party/WebKit/Source/platform/fonts/shaping/ShapeResult.cpp b/third_party/WebKit/Source/platform/fonts/shaping/ShapeResult.cpp index b3e74c7..43b6751 100644 --- a/third_party/WebKit/Source/platform/fonts/shaping/ShapeResult.cpp +++ b/third_party/WebKit/Source/platform/fonts/shaping/ShapeResult.cpp
@@ -392,9 +392,7 @@ DCHECK(primary_font_); for (unsigned i = 0; i < runs_.size(); ++i) { if (runs_[i] && runs_[i]->font_data_ && - runs_[i]->font_data_ != primary_font_ && - !runs_[i]->font_data_->IsTextOrientationFallbackOf( - primary_font_.get())) { + runs_[i]->font_data_ != primary_font_) { fallback->insert(runs_[i]->font_data_.get()); } } @@ -683,7 +681,8 @@ Vector<uint16_t> safe_break_offsets) { std::unique_ptr<RunInfo> run = std::make_unique<ShapeResult::RunInfo>( nullptr, IsLtr(direction) ? HB_DIRECTION_LTR : HB_DIRECTION_RTL, - HB_SCRIPT_COMMON, start_index, 0, num_characters); + CanvasRotationInVertical::kRegular, HB_SCRIPT_COMMON, start_index, 0, + num_characters); run->safe_break_offsets_.AppendVector(safe_break_offsets); RunInfo* run_ptr = run.get(); InsertRun(std::move(run)); @@ -833,7 +832,7 @@ // isVerticalAnyUpright(). std::unique_ptr<ShapeResult::RunInfo> run = std::make_unique<RunInfo>( font_data, text_run.Rtl() ? HB_DIRECTION_RTL : HB_DIRECTION_LTR, - HB_SCRIPT_COMMON, 0, count, count); + CanvasRotationInVertical::kRegular, HB_SCRIPT_COMMON, 0, count, count); float position = text_run.XPos() + position_offset; float start_position = position; for (unsigned i = 0; i < count; i++) {
diff --git a/third_party/WebKit/Source/platform/fonts/shaping/ShapeResult.h b/third_party/WebKit/Source/platform/fonts/shaping/ShapeResult.h index d0d82464..867ab98 100644 --- a/third_party/WebKit/Source/platform/fonts/shaping/ShapeResult.h +++ b/third_party/WebKit/Source/platform/fonts/shaping/ShapeResult.h
@@ -34,6 +34,7 @@ #include <memory> #include "platform/LayoutUnit.h" #include "platform/PlatformExport.h" +#include "platform/fonts/CanvasRotationInVertical.h" #include "platform/geometry/FloatRect.h" #include "platform/text/TextDirection.h" #include "platform/wtf/Forward.h"
diff --git a/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultBloberizer.cpp b/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultBloberizer.cpp index 82817cd..47b6660 100644 --- a/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultBloberizer.cpp +++ b/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultBloberizer.cpp
@@ -32,7 +32,7 @@ if (pending_glyphs_.IsEmpty()) return; - const auto pending_rotation = GetBlobRotation(pending_font_data_); + const auto pending_rotation = GetBlobRotation(pending_canvas_rotation_); if (pending_rotation != builder_rotation_) { // The pending run rotation doesn't match the current blob; start a new // blob. @@ -75,14 +75,13 @@ return blobs_; } +// TODO(drott) crbug.com/788725: Try to merge BlobRotation and +// CanvasRotationInVertical. ShapeResultBloberizer::BlobRotation ShapeResultBloberizer::GetBlobRotation( - const SimpleFontData* font_data) { - // For vertical upright text we need to compensate the inherited 90deg CW - // rotation (using a 90deg CCW rotation). - return (font_data->PlatformData().IsVerticalAnyUpright() && - font_data->UsedVertically()) - ? BlobRotation::kCCWRotation - : BlobRotation::kNoRotation; + const CanvasRotationInVertical canvas_rotation) { + return canvas_rotation == CanvasRotationInVertical::kRegular + ? BlobRotation::kNoRotation + : BlobRotation::kCCWRotation; } float ShapeResultBloberizer::FillGlyphs( @@ -189,6 +188,7 @@ inline void AddGlyphToBloberizer(ShapeResultBloberizer& bloberizer, float advance, hb_direction_t direction, + CanvasRotationInVertical canvas_rotation, const SimpleFontData* font_data, const HarfBuzzRunGlyphData& glyph_data, const TextContainerType& text, @@ -197,13 +197,14 @@ ? FloatPoint(advance, 0) : FloatPoint(0, advance); if (!IsSkipInkException(bloberizer, text, character_index)) { - bloberizer.Add(glyph_data.glyph, font_data, + bloberizer.Add(glyph_data.glyph, font_data, canvas_rotation, start_offset + glyph_data.offset); } } inline void AddEmphasisMark(ShapeResultBloberizer& bloberizer, const GlyphData& emphasis_data, + CanvasRotationInVertical canvas_rotation, FloatPoint glyph_center, float mid_glyph_offset) { const SimpleFontData* emphasis_font_data = emphasis_data.font_data; @@ -211,14 +212,17 @@ bool is_vertical = emphasis_font_data->PlatformData().IsVerticalAnyUpright() && - emphasis_font_data->UsedVertically(); + emphasis_data.canvas_rotation == + CanvasRotationInVertical::kRotateCanvasUpright; if (!is_vertical) { bloberizer.Add(emphasis_data.glyph, emphasis_font_data, + CanvasRotationInVertical::kRegular, mid_glyph_offset - glyph_center.X()); } else { bloberizer.Add( emphasis_data.glyph, emphasis_font_data, + CanvasRotationInVertical::kRotateCanvasUpright, FloatPoint(-glyph_center.X(), mid_glyph_offset - glyph_center.Y())); } } @@ -264,8 +268,8 @@ uint16_t character_index) -> bool { AddGlyphToBloberizer(*this, total_advance, run->direction_, - run->font_data_.get(), glyph_data, text, - character_index); + run->canvas_rotation_, run->font_data_.get(), + glyph_data, text, character_index); return true; }); } @@ -324,6 +328,7 @@ float total_advance) -> bool { DCHECK(!glyph_data.offset.Height()); Add(glyph_data.glyph, run->font_data_.get(), + run->CanvasRotation(), total_advance + glyph_data.offset.Width()); return true; }); @@ -387,8 +392,8 @@ if (text.Is8Bit()) { float glyph_advance_x = glyph_data.advance; if (Character::CanReceiveTextEmphasis(text[current_character_index])) { - AddEmphasisMark(*this, emphasis_data, glyph_center, - advance_so_far + glyph_advance_x / 2); + AddEmphasisMark(*this, emphasis_data, run->CanvasRotation(), + glyph_center, advance_so_far + glyph_advance_x / 2); } advance_so_far += glyph_advance_x; } else if (is_cluster_end) { @@ -410,8 +415,8 @@ // Do not put emphasis marks on space, separator, and control // characters. if (Character::CanReceiveTextEmphasis(text[current_character_index])) { - AddEmphasisMark(*this, emphasis_data, glyph_center, - advance_so_far + glyph_advance_x / 2); + AddEmphasisMark(*this, emphasis_data, run->CanvasRotation(), + glyph_center, advance_so_far + glyph_advance_x / 2); } advance_so_far += glyph_advance_x; }
diff --git a/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultBloberizer.h b/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultBloberizer.h index b7ef859..c0666146c 100644 --- a/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultBloberizer.h +++ b/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultBloberizer.h
@@ -48,14 +48,19 @@ const GlyphData& emphasis_data, const ShapeResult*); - void Add(Glyph glyph, const SimpleFontData* font_data, float h_offset) { + void Add(Glyph glyph, + const SimpleFontData* font_data, + CanvasRotationInVertical canvas_rotation, + float h_offset) { // cannot mix x-only/xy offsets DCHECK(!HasPendingVerticalOffsets()); - if (UNLIKELY(font_data != pending_font_data_)) { + if (UNLIKELY(font_data != pending_font_data_) || + UNLIKELY(canvas_rotation != pending_canvas_rotation_)) { CommitPendingRun(); pending_font_data_ = font_data; - DCHECK_EQ(GetBlobRotation(font_data), BlobRotation::kNoRotation); + pending_canvas_rotation_ = canvas_rotation; + DCHECK_EQ(GetBlobRotation(canvas_rotation), BlobRotation::kNoRotation); } pending_glyphs_.push_back(glyph); @@ -64,15 +69,18 @@ void Add(Glyph glyph, const SimpleFontData* font_data, + CanvasRotationInVertical canvas_rotation, const FloatPoint& offset) { // cannot mix x-only/xy offsets DCHECK(pending_glyphs_.IsEmpty() || HasPendingVerticalOffsets()); - if (UNLIKELY(font_data != pending_font_data_)) { + if (UNLIKELY(font_data != pending_font_data_) || + UNLIKELY(canvas_rotation != pending_canvas_rotation_)) { CommitPendingRun(); pending_font_data_ = font_data; + pending_canvas_rotation_ = canvas_rotation; pending_vertical_baseline_x_offset_ = - GetBlobRotation(font_data) == BlobRotation::kNoRotation + GetBlobRotation(canvas_rotation) == BlobRotation::kNoRotation ? 0 : font_data->GetFontMetrics().FloatAscent() - font_data->GetFontMetrics().FloatAscent( @@ -134,7 +142,7 @@ void CommitPendingBlob(); bool HasPendingVerticalOffsets() const; - static BlobRotation GetBlobRotation(const SimpleFontData*); + static BlobRotation GetBlobRotation(const CanvasRotationInVertical); const Font& font_; const float device_scale_factor_; @@ -147,6 +155,8 @@ // Current run state. const SimpleFontData* pending_font_data_ = nullptr; + CanvasRotationInVertical pending_canvas_rotation_ = + CanvasRotationInVertical::kRegular; Vector<Glyph, 1024> pending_glyphs_; Vector<float, 1024> pending_offsets_; float pending_vertical_baseline_x_offset_ = 0;
diff --git a/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultBloberizerTest.cpp b/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultBloberizerTest.cpp index 8d70c8e..d7562904 100644 --- a/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultBloberizerTest.cpp +++ b/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultBloberizerTest.cpp
@@ -85,8 +85,8 @@ scoped_refptr<SimpleFontData> font2 = CreateTestSimpleFontData(); // 2 pending glyphs - bloberizer.Add(42, font1.get(), 10); - bloberizer.Add(43, font1.get(), 15); + bloberizer.Add(42, font1.get(), CanvasRotationInVertical::kRegular, 10); + bloberizer.Add(43, font1.get(), CanvasRotationInVertical::kRegular, 15); EXPECT_EQ(ShapeResultBloberizerTestInfo::PendingRunFontData(bloberizer), font1.get()); @@ -111,7 +111,7 @@ EXPECT_EQ(ShapeResultBloberizerTestInfo::CommittedBlobCount(bloberizer), 0ul); // one more glyph, different font => pending run flush - bloberizer.Add(44, font2.get(), 12); + bloberizer.Add(44, font2.get(), CanvasRotationInVertical::kRegular, 12); EXPECT_EQ(ShapeResultBloberizerTestInfo::PendingRunFontData(bloberizer), font2.get()); @@ -145,8 +145,10 @@ scoped_refptr<SimpleFontData> font2 = CreateTestSimpleFontData(); // 2 pending glyphs - bloberizer.Add(42, font1.get(), FloatPoint(10, 0)); - bloberizer.Add(43, font1.get(), FloatPoint(15, 0)); + bloberizer.Add(42, font1.get(), CanvasRotationInVertical::kRegular, + FloatPoint(10, 0)); + bloberizer.Add(43, font1.get(), CanvasRotationInVertical::kRegular, + FloatPoint(15, 0)); EXPECT_EQ(ShapeResultBloberizerTestInfo::PendingRunFontData(bloberizer), font1.get()); @@ -173,7 +175,8 @@ EXPECT_EQ(ShapeResultBloberizerTestInfo::CommittedBlobCount(bloberizer), 0ul); // one more glyph, different font => pending run flush - bloberizer.Add(44, font2.get(), FloatPoint(12, 2)); + bloberizer.Add(44, font2.get(), CanvasRotationInVertical::kRegular, + FloatPoint(12, 2)); EXPECT_EQ(ShapeResultBloberizerTestInfo::PendingRunFontData(bloberizer), font2.get()); @@ -204,47 +207,41 @@ Font font; ShapeResultBloberizer bloberizer(font, 1); - // Normal (horizontal) font. - scoped_refptr<SimpleFontData> font_normal = CreateTestSimpleFontData(); - ASSERT_FALSE(font_normal->PlatformData().IsVerticalAnyUpright()); - ASSERT_EQ(font_normal->UsedVertically(), false); - - // Rotated (vertical upright) font. - scoped_refptr<SimpleFontData> font_rotated = CreateTestSimpleFontData(true); - ASSERT_TRUE(font_rotated->PlatformData().IsVerticalAnyUpright()); - ASSERT_EQ(font_rotated->UsedVertically(), true); + scoped_refptr<SimpleFontData> test_font = CreateTestSimpleFontData(); struct { - const SimpleFontData* font_data; + CanvasRotationInVertical canvas_rotation; size_t expected_pending_glyphs; size_t expected_pending_runs; size_t expected_committed_blobs; } append_ops[] = { // append 2 horizontal glyphs -> these go into the pending glyph buffer - {font_normal.get(), 1u, 0u, 0u}, - {font_normal.get(), 2u, 0u, 0u}, + {CanvasRotationInVertical::kRegular, 1u, 0u, 0u}, + {CanvasRotationInVertical::kRegular, 2u, 0u, 0u}, // append 3 vertical rotated glyphs -> push the prev pending (horizontal) // glyphs into a new run in the current (horizontal) blob - {font_rotated.get(), 1u, 1u, 0u}, - {font_rotated.get(), 2u, 1u, 0u}, - {font_rotated.get(), 3u, 1u, 0u}, + {CanvasRotationInVertical::kRotateCanvasUpright, 1u, 1u, 0u}, + {CanvasRotationInVertical::kRotateCanvasUpright, 2u, 1u, 0u}, + {CanvasRotationInVertical::kRotateCanvasUpright, 3u, 1u, 0u}, // append 2 more horizontal glyphs -> flush the current (horizontal) blob, // push prev (vertical) pending glyphs into new vertical blob run - {font_normal.get(), 1u, 1u, 1u}, - {font_normal.get(), 2u, 1u, 1u}, + {CanvasRotationInVertical::kRegular, 1u, 1u, 1u}, + {CanvasRotationInVertical::kRegular, 2u, 1u, 1u}, // append 1 more vertical glyph -> flush current (vertical) blob, push // prev (horizontal) pending glyphs into a new horizontal blob run - {font_rotated.get(), 1u, 1u, 2u}, + {CanvasRotationInVertical::kRotateCanvasUpright, 1u, 1u, 2u}, }; for (const auto& op : append_ops) { - bloberizer.Add(42, op.font_data, FloatPoint()); + bloberizer.Add(42, test_font.get(), op.canvas_rotation, FloatPoint()); EXPECT_EQ( op.expected_pending_glyphs, ShapeResultBloberizerTestInfo::PendingRunGlyphs(bloberizer).size()); + EXPECT_EQ(op.canvas_rotation, + ShapeResultBloberizerTestInfo::PendingBlobRotation(bloberizer)); EXPECT_EQ(op.expected_pending_runs, ShapeResultBloberizerTestInfo::PendingBlobRunCount(bloberizer)); EXPECT_EQ(op.expected_committed_blobs,
diff --git a/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultBuffer.cpp b/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultBuffer.cpp index abde58d..3054dfd 100644 --- a/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultBuffer.cpp +++ b/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultBuffer.cpp
@@ -229,7 +229,8 @@ return GlyphData( run->glyph_data_[0].glyph, - run->font_data_->EmphasisMarkFontData(font_description).get()); + run->font_data_->EmphasisMarkFontData(font_description).get(), + run->CanvasRotation()); } }
diff --git a/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultInlineHeaders.h b/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultInlineHeaders.h index d5d586b..a8060e9e 100644 --- a/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultInlineHeaders.h +++ b/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultInlineHeaders.h
@@ -58,12 +58,14 @@ public: RunInfo(const SimpleFontData* font, hb_direction_t dir, + CanvasRotationInVertical canvas_rotation, hb_script_t script, unsigned start_index, unsigned num_glyphs, unsigned num_characters) : font_data_(const_cast<SimpleFontData*>(font)), direction_(dir), + canvas_rotation_(canvas_rotation), script_(script), glyph_data_(num_glyphs), start_index_(start_index), @@ -73,6 +75,7 @@ RunInfo(const RunInfo& other) : font_data_(other.font_data_), direction_(other.direction_), + canvas_rotation_(other.canvas_rotation_), script_(other.script_), glyph_data_(other.glyph_data_), start_index_(other.start_index_), @@ -81,6 +84,7 @@ bool Rtl() const { return HB_DIRECTION_IS_BACKWARD(direction_); } bool IsHorizontal() const { return HB_DIRECTION_IS_HORIZONTAL(direction_); } + CanvasRotationInVertical CanvasRotation() const { return canvas_rotation_; } unsigned NextSafeToBreakOffset(unsigned) const; unsigned PreviousSafeToBreakOffset(unsigned) const; float XPositionForVisualOffset(unsigned, AdjustMidCluster) const; @@ -124,9 +128,9 @@ }); } - auto run = std::make_unique<RunInfo>(font_data_.get(), direction_, script_, - start_index_ + start, number_of_glyphs, - number_of_characters); + auto run = std::make_unique<RunInfo>( + font_data_.get(), direction_, canvas_rotation_, script_, + start_index_ + start, number_of_glyphs, number_of_characters); unsigned sub_glyph_index = 0; float total_advance = 0; @@ -209,6 +213,9 @@ scoped_refptr<SimpleFontData> font_data_; hb_direction_t direction_; + // For upright-in-vertical we need to tell the ShapeResultBloberizer to rotate + // the canvas back 90deg for this RunInfo. + CanvasRotationInVertical canvas_rotation_; hb_script_t script_; Vector<HarfBuzzRunGlyphData> glyph_data_; // List of character indecies before which it's safe to break without
diff --git a/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultTestInfo.h b/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultTestInfo.h index b86dbd3..47e71a2 100644 --- a/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultTestInfo.h +++ b/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultTestInfo.h
@@ -37,6 +37,11 @@ return bloberizer.pending_font_data_; } + static CanvasRotationInVertical PendingBlobRotation( + const ShapeResultBloberizer& bloberizer) { + return bloberizer.pending_canvas_rotation_; + } + static const Vector<Glyph, 1024>& PendingRunGlyphs( const ShapeResultBloberizer& bloberizer) { return bloberizer.pending_glyphs_;
diff --git a/third_party/WebKit/Source/platform/geometry/LayoutSize.h b/third_party/WebKit/Source/platform/geometry/LayoutSize.h index 3ce017ae..9061bc28 100644 --- a/third_party/WebKit/Source/platform/geometry/LayoutSize.h +++ b/third_party/WebKit/Source/platform/geometry/LayoutSize.h
@@ -133,13 +133,17 @@ LayoutSize FitToAspectRatio(const LayoutSize& aspect_ratio, AspectRatioFit fit) const { - float height_scale = Height().ToFloat() / aspect_ratio.Height().ToFloat(); - float width_scale = Width().ToFloat() / aspect_ratio.Width().ToFloat(); - if ((width_scale > height_scale) != (fit == kAspectRatioFitGrow)) - return LayoutSize(Height() * aspect_ratio.Width() / aspect_ratio.Height(), - Height()); - return LayoutSize(Width(), - Width() * aspect_ratio.Height() / aspect_ratio.Width()); + const float height_float = Height().ToFloat(); + const float width_float = Width().ToFloat(); + float height_scale = height_float / aspect_ratio.Height().ToFloat(); + float width_scale = width_float / aspect_ratio.Width().ToFloat(); + if ((width_scale > height_scale) != (fit == kAspectRatioFitGrow)) { + return LayoutSize( + height_float * aspect_ratio.Width() / aspect_ratio.Height(), + Height()); + } + return LayoutSize( + Width(), width_float * aspect_ratio.Height() / aspect_ratio.Width()); } LayoutSize Fraction() const {
diff --git a/third_party/WebKit/Source/platform/geometry/LayoutSizeTest.cpp b/third_party/WebKit/Source/platform/geometry/LayoutSizeTest.cpp new file mode 100644 index 0000000..50b11ba --- /dev/null +++ b/third_party/WebKit/Source/platform/geometry/LayoutSizeTest.cpp
@@ -0,0 +1,28 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "platform/geometry/LayoutSize.h" + +#include "platform/wtf/text/WTFString.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace blink { + +TEST(LayoutSizeTest, FitToAspectRatioDoesntOverflow) { + // FitToAspectRatio() shouldn't overflow due to intermediate calculations, + // for both the "constrained by width" and "constrained by height" cases. + LayoutSize aspect_ratio(50000, 50000); + EXPECT_EQ("1000x1000", + LayoutSize(2000, 1000) + .FitToAspectRatio(aspect_ratio, kAspectRatioFitShrink) + .ToString()); + + LayoutSize size(1000, 2000); + EXPECT_EQ("1000x1000", + LayoutSize(1000, 2000) + .FitToAspectRatio(aspect_ratio, kAspectRatioFitShrink) + .ToString()); +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/platform/graphics/BitmapImage.cpp b/third_party/WebKit/Source/platform/graphics/BitmapImage.cpp index 0eb98bd..fbb8b925 100644 --- a/third_party/WebKit/Source/platform/graphics/BitmapImage.cpp +++ b/third_party/WebKit/Source/platform/graphics/BitmapImage.cpp
@@ -28,6 +28,7 @@ #include "base/memory/scoped_refptr.h" #include "base/metrics/histogram_macros.h" +#include "base/time/default_tick_clock.h" #include "platform/Timer.h" #include "platform/geometry/FloatRect.h" #include "platform/graphics/BitmapImageMetrics.h" @@ -80,8 +81,8 @@ repetition_count_status_(kUnknown), repetition_count_(kAnimationNone), repetitions_complete_(0), - desired_frame_start_time_(0), frame_count_(0), + clock_(base::DefaultTickClock::GetInstance()), task_runner_(Platform::Current() ->CurrentThread() ->Scheduler() @@ -508,8 +509,7 @@ } void BitmapImage::StartAnimation() { - last_num_frames_skipped_ = - StartAnimationInternal(MonotonicallyIncreasingTime()); + last_num_frames_skipped_ = StartAnimationInternal(clock_->NowTicks()); if (!last_num_frames_skipped_.has_value()) return; @@ -517,7 +517,7 @@ last_num_frames_skipped_.value()); } -Optional<size_t> BitmapImage::StartAnimationInternal(const double time) { +Optional<size_t> BitmapImage::StartAnimationInternal(TimeTicks time) { // If the |frame_timer_| is set, it indicates that a task is already pending // to advance the current frame of the animation. We don't need to schedule // a task to advance the animation in that case. @@ -525,7 +525,7 @@ return WTF::nullopt; // If we aren't already animating, set now as the animation start time. - if (!desired_frame_start_time_) + if (desired_frame_start_time_.is_null()) desired_frame_start_time_ = time; // Don't advance the animation to an incomplete frame. @@ -546,16 +546,13 @@ // Determine time for next frame to start. By ignoring paint and timer lag // in this calculation, we make the animation appear to run at its desired // rate regardless of how fast it's being repainted. - // TODO(vmpstr): This function can probably deal in TimeTicks/TimeDelta - // instead. - const double current_duration = - FrameDurationAtIndex(current_frame_index_).InSecondsF(); + TimeDelta current_duration = FrameDurationAtIndex(current_frame_index_); desired_frame_start_time_ += current_duration; // When an animated image is more than five minutes out of date, the // user probably doesn't care about resyncing and we could burn a lot of // time looping through frames below. Just reset the timings. - const double kCAnimationResyncCutoff = 5 * 60; + constexpr TimeDelta kCAnimationResyncCutoff = TimeDelta::FromMinutes(5); if ((time - desired_frame_start_time_) > kCAnimationResyncCutoff) desired_frame_start_time_ = time + current_duration; @@ -577,8 +574,9 @@ // Haven't yet reached time for next frame to start; delay until then frame_timer_ = WTF::WrapUnique(new TaskRunnerTimer<BitmapImage>( task_runner_, this, &BitmapImage::AdvanceAnimation)); - frame_timer_->StartOneShot(std::max(desired_frame_start_time_ - time, 0.), - BLINK_FROM_HERE); + frame_timer_->StartOneShot( + std::max(desired_frame_start_time_ - time, TimeDelta()), + BLINK_FROM_HERE); // No frames needed to be skipped to advance to the next frame. return Optional<size_t>(0u); @@ -616,8 +614,7 @@ DCHECK_EQ(current_frame_index_, next_frame); frames_advanced++; - desired_frame_start_time_ += - FrameDurationAtIndex(current_frame_index_).InSecondsF(); + desired_frame_start_time_ += FrameDurationAtIndex(current_frame_index_); } DCHECK_GT(frames_advanced, 0u); @@ -636,8 +633,7 @@ // the task for the next frame (which may not happen in the call below), it // always updates the |desired_frame_start_time_| based on the current frame // duration. - desired_frame_start_time_ -= - FrameDurationAtIndex(current_frame_index_).InSecondsF(); + desired_frame_start_time_ -= FrameDurationAtIndex(current_frame_index_); // Don't include the |current_frame_index_|, which will be used on the next // paint, in the number of frames skipped. @@ -654,7 +650,7 @@ StopAnimation(); current_frame_index_ = 0; repetitions_complete_ = 0; - desired_frame_start_time_ = 0; + desired_frame_start_time_ = TimeTicks(); animation_finished_ = false; cached_frame_ = PaintImage(); reset_animation_sequence_id_++; @@ -669,12 +665,11 @@ return decoder_ && decoder_->RepetitionCount() != kAnimationNone; } -void BitmapImage::AdvanceTime(double delta_time_in_seconds) { - if (desired_frame_start_time_) - desired_frame_start_time_ -= delta_time_in_seconds; +void BitmapImage::AdvanceTime(TimeDelta delta) { + if (!desired_frame_start_time_.is_null()) + desired_frame_start_time_ -= delta; else - desired_frame_start_time_ = - MonotonicallyIncreasingTime() - delta_time_in_seconds; + desired_frame_start_time_ = clock_->NowTicks() - delta; } void BitmapImage::AdvanceAnimation(TimerBase*) { @@ -709,7 +704,7 @@ repetitions_complete_ > repetition_count_) || animation_policy_ == kImageAnimationPolicyAnimateOnce) { animation_finished_ = true; - desired_frame_start_time_ = 0; + desired_frame_start_time_ = TimeTicks(); // We skipped to the last frame and cannot advance further. The // observer will not receive animationAdvanced notifications while
diff --git a/third_party/WebKit/Source/platform/graphics/BitmapImage.h b/third_party/WebKit/Source/platform/graphics/BitmapImage.h index 3e951c1..22f11ef1 100644 --- a/third_party/WebKit/Source/platform/graphics/BitmapImage.h +++ b/third_party/WebKit/Source/platform/graphics/BitmapImage.h
@@ -43,6 +43,10 @@ #include "platform/wtf/Time.h" #include "third_party/skia/include/core/SkRefCnt.h" +namespace base { +class TickClock; +} + namespace blink { class PLATFORM_EXPORT BitmapImage final : public Image { @@ -81,7 +85,7 @@ void SetAnimationPolicy(ImageAnimationPolicy) override; ImageAnimationPolicy AnimationPolicy() override { return animation_policy_; } - void AdvanceTime(double delta_time_in_seconds) override; + void AdvanceTime(TimeDelta) override; scoped_refptr<Image> ImageForDefaultFrame() override; @@ -108,6 +112,8 @@ return last_num_frames_skipped_; } + void SetTickClockForTesting(base::TickClock* clock) { clock_ = clock; } + protected: bool IsSizeAvailable() override; @@ -167,7 +173,7 @@ // Starts the animation by scheduling a task to advance to the next desired // frame, if possible, and catching up any frames if the time to display them // is in the past. - Optional<size_t> StartAnimationInternal(const double time); + Optional<size_t> StartAnimationInternal(TimeTicks); void StopAnimation(); void AdvanceAnimation(TimerBase*); @@ -216,13 +222,15 @@ // incapable of animation. int repetitions_complete_; // How many repetitions we've finished. - double desired_frame_start_time_; // The system time at which we hope to see - // the next call to startAnimation(). + TimeTicks desired_frame_start_time_; // The system time at which we hope to + // see the next call to + // startAnimation(). size_t frame_count_; PaintImage::AnimationSequenceId reset_animation_sequence_id_ = 0; + base::TickClock* clock_; scoped_refptr<WebTaskRunner> task_runner_; // Value used in UMA tracking for the number of animation frames skipped
diff --git a/third_party/WebKit/Source/platform/graphics/BitmapImageTest.cpp b/third_party/WebKit/Source/platform/graphics/BitmapImageTest.cpp index 700f308..89c576f 100644 --- a/third_party/WebKit/Source/platform/graphics/BitmapImageTest.cpp +++ b/third_party/WebKit/Source/platform/graphics/BitmapImageTest.cpp
@@ -30,6 +30,7 @@ #include "platform/graphics/BitmapImage.h" +#include "base/test/simple_test_tick_clock.h" #include "platform/SharedBuffer.h" #include "platform/graphics/BitmapImageMetrics.h" #include "platform/graphics/DeferredImageDecoder.h" @@ -352,19 +353,15 @@ public MockImageDecoderClient { public: void SetUp() override { - original_time_function_ = SetTimeFunctionsForTesting([] { return now_; }); - BitmapImageTest::SetUp(); + image_->SetTickClockForTesting(&clock_); + auto decoder = MockImageDecoder::Create(this); decoder->SetSize(10, 10); image_->SetDecoderForTesting( DeferredImageDecoder::CreateForTesting(std::move(decoder))); } - void TearDown() override { - SetTimeFunctionsForTesting(original_time_function_); - } - void DecoderBeingDestroyed() override {} void DecodeRequested() override {} ImageFrame::Status GetStatus(size_t index) override { @@ -376,18 +373,19 @@ int RepetitionCount() const override { return repetition_count_; } TimeDelta FrameDuration() const override { return duration_; } + void SetClock(int seconds) { + clock_.SetNowTicks(base::TimeTicks() + TimeDelta::FromSeconds(seconds)); + } + protected: TimeDelta duration_; int repetition_count_; size_t frame_count_; bool last_frame_complete_; - static double now_; - TimeFunction original_time_function_; + base::SimpleTestTickClock clock_; }; -double BitmapImageTestWithMockDecoder::now_ = 0; - TEST_F(BitmapImageTestWithMockDecoder, ImageMetadataTracking) { // For a zero duration, we should make it non-zero when creating a PaintImage. repetition_count_ = kAnimationLoopOnce; @@ -464,7 +462,7 @@ frame_count_ = 3u; last_frame_complete_ = false; duration_ = TimeDelta::FromSeconds(10); - now_ = 10; + SetClock(10); // Last frame of the image is incomplete for a completely loaded image. We // still won't advance it. @@ -481,13 +479,13 @@ EXPECT_EQ(image_->PaintImageForCurrentFrame().frame_index(), 0u); // Run the timer task, image advanced to the second frame. - now_ = 20; + SetClock(20); task_runner->AdvanceTimeAndRun(10); EXPECT_EQ(image_->PaintImageForCurrentFrame().frame_index(), 1u); // Go past the desired time for the next frame, call StartAnimation. The frame // still isn't advanced because its incomplete. - now_ = 45; + SetClock(45); StartAnimation(); EXPECT_EQ(image_->PaintImageForCurrentFrame().frame_index(), 1u); } @@ -499,7 +497,7 @@ frame_count_ = 7u; last_frame_complete_ = false; duration_ = TimeDelta::FromSeconds(10); - now_ = 10; + SetClock(10); // Start with an image that is incomplete, and the last frame is not fully // received. @@ -539,7 +537,7 @@ // advance the frame. // Since the animation started at 10s, and each frame has a duration of 10s, // we should see the fourth frame at 41 seconds. - now_ = 41; + SetClock(41); task_runner->SetTime(41); StartAnimation(); @@ -556,7 +554,7 @@ // At 70s, we would want to display the last frame and would skip 2 frames. // But because its incomplete, we advanced to the sixth frame and only skipped // 1 frame. - now_ = 71; + SetClock(71); task_runner->SetTime(71); StartAnimation(); EXPECT_EQ(image_->PaintImageForCurrentFrame().frame_index(), 5u);
diff --git a/third_party/WebKit/Source/platform/graphics/Image.h b/third_party/WebKit/Source/platform/graphics/Image.h index d615ab3..85bd860 100644 --- a/third_party/WebKit/Source/platform/graphics/Image.h +++ b/third_party/WebKit/Source/platform/graphics/Image.h
@@ -40,6 +40,7 @@ #include "platform/wtf/Forward.h" #include "platform/wtf/Noncopyable.h" #include "platform/wtf/ThreadSafeRefCounted.h" +#include "platform/wtf/Time.h" #include "platform/wtf/WeakPtr.h" #include "third_party/skia/include/core/SkRefCnt.h" @@ -152,7 +153,7 @@ virtual ImageAnimationPolicy AnimationPolicy() { return kImageAnimationPolicyAllowed; } - virtual void AdvanceTime(double delta_time_in_seconds) {} + virtual void AdvanceTime(TimeDelta delta) {} // Advances an animated image. For BitmapImage (e.g., animated gifs) this // will advance to the next frame. For SVGImage, this will trigger an
diff --git a/third_party/WebKit/Source/platform/graphics/ImageBuffer.cpp b/third_party/WebKit/Source/platform/graphics/ImageBuffer.cpp index 6f041c6f..4a8174d 100644 --- a/third_party/WebKit/Source/platform/graphics/ImageBuffer.cpp +++ b/third_party/WebKit/Source/platform/graphics/ImageBuffer.cpp
@@ -274,14 +274,13 @@ bool* is_gpu_readback_invoked) const { uint8_t bytes_per_pixel = surface_->ColorParams().BytesPerPixel(); CheckedNumeric<int> data_size = bytes_per_pixel; - data_size *= rect.Width(); - data_size *= rect.Height(); + data_size *= rect.Size().Area(); if (!data_size.IsValid() || data_size.ValueOrDie() > v8::TypedArray::kMaxLength) return false; if (!IsSurfaceValid()) { - size_t alloc_size_in_bytes = rect.Width() * rect.Height() * bytes_per_pixel; + size_t alloc_size_in_bytes = rect.Size().Area() * bytes_per_pixel; auto data = WTF::ArrayBufferContents::CreateDataHandle( alloc_size_in_bytes, WTF::ArrayBufferContents::kZeroInitialize); if (!data) @@ -304,7 +303,7 @@ || rect.X() < 0 || rect.Y() < 0 || rect.MaxX() > surface_->Size().Width() || rect.MaxY() > surface_->Size().Height(); - size_t alloc_size_in_bytes = rect.Width() * rect.Height() * bytes_per_pixel; + size_t alloc_size_in_bytes = rect.Size().Area() * bytes_per_pixel; WTF::ArrayBufferContents::InitializationPolicy initialization_policy = may_have_stray_area ? WTF::ArrayBufferContents::kZeroInitialize : WTF::ArrayBufferContents::kDontInitialize; @@ -323,7 +322,7 @@ kUnpremul_SkAlphaType); sk_sp<SkImage> sk_image = snapshot->PaintImageForCurrentFrame().GetSkImage(); bool read_pixels_successful = sk_image->readPixels( - info, result.Data(), bytes_per_pixel * rect.Width(), rect.X(), rect.Y()); + info, result.Data(), info.minRowBytes(), rect.X(), rect.Y()); DCHECK(read_pixels_successful || !sk_image->bounds().intersect(SkIRect::MakeXYWH( rect.X(), rect.Y(), info.width(), info.height()))); @@ -410,6 +409,8 @@ image = nullptr; image = StaticBitmapImage::Create(texture_image->makeNonTextureImage()); } + SkPaint paint; + paint.setBlendMode(SkBlendMode::kSrc); surface->Canvas()->drawImage(image->PaintImageForCurrentFrame(), 0, 0); surface->SetImageBuffer(this); surface_ = std::move(surface);
diff --git a/third_party/WebKit/Source/platform/graphics/OffscreenCanvasFrameDispatcherImpl.cpp b/third_party/WebKit/Source/platform/graphics/OffscreenCanvasFrameDispatcherImpl.cpp index ac27a6c..4a95a16 100644 --- a/third_party/WebKit/Source/platform/graphics/OffscreenCanvasFrameDispatcherImpl.cpp +++ b/third_party/WebKit/Source/platform/graphics/OffscreenCanvasFrameDispatcherImpl.cpp
@@ -53,12 +53,8 @@ scoped_refptr<base::SingleThreadTaskRunner> task_runner; auto scheduler = blink::Platform::Current()->CurrentThread()->Scheduler(); - if (scheduler) { - WebTaskRunner* web_task_runner = scheduler->CompositorTaskRunner(); - if (web_task_runner) { - task_runner = web_task_runner->ToSingleThreadTaskRunner(); - } - } + if (scheduler) + task_runner = scheduler->CompositorTaskRunner(); viz::mojom::blink::CompositorFrameSinkClientPtr client; binding_.Bind(mojo::MakeRequest(&client), task_runner); provider->CreateCompositorFrameSink(frame_sink_id_, std::move(client),
diff --git a/third_party/WebKit/Source/platform/graphics/VideoFrameResourceProvider.cpp b/third_party/WebKit/Source/platform/graphics/VideoFrameResourceProvider.cpp index 0a2f25c..0bc3280 100644 --- a/third_party/WebKit/Source/platform/graphics/VideoFrameResourceProvider.cpp +++ b/third_party/WebKit/Source/platform/graphics/VideoFrameResourceProvider.cpp
@@ -11,8 +11,15 @@ #include "cc/resources/video_resource_updater.h" #include "components/viz/common/quads/render_pass.h" #include "components/viz/common/quads/solid_color_draw_quad.h" +#include "components/viz/common/quads/texture_draw_quad.h" +#include "components/viz/common/quads/yuv_video_draw_quad.h" +#include "media/base/video_frame.h" #include "platform/wtf/WeakPtr.h" +namespace cc { +class VideoFrameExternalResources; +} // namespace cc + namespace blink { VideoFrameResourceProvider::VideoFrameResourceProvider( @@ -44,36 +51,41 @@ context_provider_ = media_context_provider; viz::ContextProvider::ScopedContextLock lock(context_provider_); - // TODO(lethalantidote): Get real value for delegated_sync_points_required. resource_provider_ = std::make_unique<cc::LayerTreeResourceProvider>( media_context_provider, shared_bitmap_manager_, - gpu_memory_buffer_manager_, false, settings_.resource_settings); + gpu_memory_buffer_manager_, true, settings_.resource_settings); resource_updater_ = std::make_unique<cc::VideoResourceUpdater>( media_context_provider, resource_provider_.get(), settings_.use_stream_video_draw_quad); } -void VideoFrameResourceProvider::AppendQuads(viz::RenderPass* render_pass) { - gfx::Rect rect(0, 0, 10000, 10000); - gfx::Rect visible_rect(0, 0, 10000, 10000); +void VideoFrameResourceProvider::AppendQuads( + viz::RenderPass* render_pass, + scoped_refptr<media::VideoFrame> frame) { + viz::ContextProvider::ScopedContextLock lock(context_provider_); + resource_updater_->ObtainFrameResources(frame); + // TODO(lethalantidote) : update with true value; + bool contents_opaque = true; + gfx::Rect visible_layer_rect = gfx::Rect(frame->coded_size()); + gfx::Rect clip_rect = gfx::Rect(frame->coded_size()); bool is_clipped = false; - bool are_contents_opaque = true; - viz::SharedQuadState* shared_state = - render_pass->CreateAndAppendSharedQuadState(); - shared_state->SetAll(gfx::Transform(), rect, rect, rect, is_clipped, - are_contents_opaque, 1, SkBlendMode::kSrcOver, 0); - viz::SolidColorDrawQuad* solid_color_quad = - render_pass->CreateAndAppendDrawQuad<viz::SolidColorDrawQuad>(); - // Fluxuate colors for placeholder testing. - static int r = 0; - static int g = 0; - static int b = 0; - r++; - g += 2; - b += 3; - solid_color_quad->SetNew(shared_state, rect, visible_rect, - SkColorSetRGB(r % 255, g % 255, b % 255), false); + float draw_opacity = 1.0f; + int sorting_context_id = 0; + + // Internal to this compositor frame, this video quad is never occluded, + // thus the full quad is visible. + gfx::Rect visible_quad_rect = gfx::Rect(frame->coded_size()); + + resource_updater_->AppendQuads( + render_pass, frame, gfx::Transform(), frame->coded_size(), + visible_layer_rect, clip_rect, is_clipped, contents_opaque, draw_opacity, + sorting_context_id, visible_quad_rect); +} + +void VideoFrameResourceProvider::ReleaseFrameResources() { + viz::ContextProvider::ScopedContextLock lock(context_provider_); + resource_updater_->ReleaseFrameResources(); } void VideoFrameResourceProvider::PrepareSendToParent(
diff --git a/third_party/WebKit/Source/platform/graphics/VideoFrameResourceProvider.h b/third_party/WebKit/Source/platform/graphics/VideoFrameResourceProvider.h index b1f3b96..a0e58b3 100644 --- a/third_party/WebKit/Source/platform/graphics/VideoFrameResourceProvider.h +++ b/third_party/WebKit/Source/platform/graphics/VideoFrameResourceProvider.h
@@ -37,7 +37,8 @@ virtual void ObtainContextProvider(); virtual void Initialize(viz::ContextProvider*); - virtual void AppendQuads(viz::RenderPass*); + virtual void AppendQuads(viz::RenderPass*, scoped_refptr<media::VideoFrame>); + virtual void ReleaseFrameResources(); virtual void PrepareSendToParent( const cc::LayerTreeResourceProvider::ResourceIdArray& resource_ids,
diff --git a/third_party/WebKit/Source/platform/graphics/VideoFrameSubmitter.cpp b/third_party/WebKit/Source/platform/graphics/VideoFrameSubmitter.cpp index f1bb742..c63f1b3e 100644 --- a/third_party/WebKit/Source/platform/graphics/VideoFrameSubmitter.cpp +++ b/third_party/WebKit/Source/platform/graphics/VideoFrameSubmitter.cpp
@@ -116,7 +116,7 @@ render_pass->SetNew(1, gfx::Rect(video_frame->coded_size()), gfx::Rect(video_frame->coded_size()), gfx::Transform()); render_pass->filters = cc::FilterOperations(); - resource_provider_->AppendQuads(render_pass.get()); + resource_provider_->AppendQuads(render_pass.get(), video_frame); compositor_frame.metadata.begin_frame_ack = begin_frame_ack; compositor_frame.metadata.device_scale_factor = 1; compositor_frame.metadata.may_contain_video = true; @@ -129,12 +129,12 @@ } resource_provider_->PrepareSendToParent(resources, &compositor_frame.resource_list); - compositor_frame.render_pass_list.push_back(std::move(render_pass)); // TODO(lethalantidote): Address third/fourth arg in SubmitCompositorFrame. compositor_frame_sink_->SubmitCompositorFrame( current_local_surface_id_, std::move(compositor_frame), nullptr, 0); + resource_provider_->ReleaseFrameResources(); } void VideoFrameSubmitter::OnBeginFrame(const viz::BeginFrameArgs& args) {
diff --git a/third_party/WebKit/Source/platform/graphics/VideoFrameSubmitterTest.cpp b/third_party/WebKit/Source/platform/graphics/VideoFrameSubmitterTest.cpp index 3ededfc..6da889d 100644 --- a/third_party/WebKit/Source/platform/graphics/VideoFrameSubmitterTest.cpp +++ b/third_party/WebKit/Source/platform/graphics/VideoFrameSubmitterTest.cpp
@@ -88,7 +88,9 @@ ~MockVideoFrameResourceProvider() = default; MOCK_METHOD1(Initialize, void(viz::ContextProvider*)); - MOCK_METHOD1(AppendQuads, void(viz::RenderPass*)); + MOCK_METHOD2(AppendQuads, + void(viz::RenderPass*, scoped_refptr<media::VideoFrame>)); + MOCK_METHOD0(ReleaseFrameResources, void()); MOCK_METHOD2(PrepareSendToParent, void(const cc::LayerTreeResourceProvider::ResourceIdArray&, std::vector<viz::TransferableResource>*)); @@ -112,6 +114,11 @@ context_provider_->BindToCurrentThread(); } + void SetUp() override { + MakeSubmitter(); + scoped_task_environment_.RunUntilIdle(); + } + void MakeSubmitter() { resource_provider_ = new StrictMock<MockVideoFrameResourceProvider>(context_provider_.get()); @@ -183,8 +190,9 @@ EXPECT_CALL(*sink_, DoSubmitCompositorFrame(_, _)); EXPECT_CALL(*provider_, PutCurrentFrame()); EXPECT_CALL(*sink_, SetNeedsBeginFrame(false)); - EXPECT_CALL(*resource_provider_, AppendQuads(_)); + EXPECT_CALL(*resource_provider_, AppendQuads(_, _)); EXPECT_CALL(*resource_provider_, PrepareSendToParent(_, _)); + EXPECT_CALL(*resource_provider_, ReleaseFrameResources()); submitter_->StopUsingProvider(); @@ -220,8 +228,9 @@ gfx::Size(8, 8), base::TimeDelta()))); EXPECT_CALL(*sink_, DoSubmitCompositorFrame(_, _)); EXPECT_CALL(*provider_, PutCurrentFrame()); - EXPECT_CALL(*resource_provider_, AppendQuads(_)); + EXPECT_CALL(*resource_provider_, AppendQuads(_, _)); EXPECT_CALL(*resource_provider_, PrepareSendToParent(_, _)); + EXPECT_CALL(*resource_provider_, ReleaseFrameResources()); submitter_->DidReceiveFrame(); scoped_task_environment_.RunUntilIdle(); @@ -243,8 +252,9 @@ gfx::Size(8, 8), base::TimeDelta()))); EXPECT_CALL(*sink_, DoSubmitCompositorFrame(_, _)); EXPECT_CALL(*provider_, PutCurrentFrame()); - EXPECT_CALL(*resource_provider_, AppendQuads(_)); + EXPECT_CALL(*resource_provider_, AppendQuads(_, _)); EXPECT_CALL(*resource_provider_, PrepareSendToParent(_, _)); + EXPECT_CALL(*resource_provider_, ReleaseFrameResources()); viz::BeginFrameArgs args = begin_frame_source_->CreateBeginFrameArgs( BEGINFRAME_FROM_HERE, now_src_.get());
diff --git a/third_party/WebKit/Source/platform/heap/BlinkGC.h b/third_party/WebKit/Source/platform/heap/BlinkGC.h index 2d6c36f..4bac963 100644 --- a/third_party/WebKit/Source/platform/heap/BlinkGC.h +++ b/third_party/WebKit/Source/platform/heap/BlinkGC.h
@@ -12,12 +12,6 @@ #define PRINT_HEAP_STATS 0 // Enable this macro to print heap stats to stderr. -// Enables incremental marking in Oilpan. Note that to fully enable incremental -// marking the runtime flag HeapIncrementalMarking also needs to be true. -#ifndef HEAP_INCREMENTAL_MARKING -#define HEAP_INCREMENTAL_MARKING 0 -#endif // HEAP_INCREMENTAL_MARKING - namespace blink { class Visitor;
diff --git a/third_party/WebKit/Source/platform/heap/IncrementalMarkingTest.cpp b/third_party/WebKit/Source/platform/heap/IncrementalMarkingTest.cpp index 41e48571..59b391f6 100644 --- a/third_party/WebKit/Source/platform/heap/IncrementalMarkingTest.cpp +++ b/third_party/WebKit/Source/platform/heap/IncrementalMarkingTest.cpp
@@ -2,9 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#undef HEAP_INCREMENTAL_MARKING -#define HEAP_INCREMENTAL_MARKING 1 - #include "platform/heap/CallbackStack.h" #include "platform/heap/GarbageCollected.h" #include "platform/heap/Heap.h"
diff --git a/third_party/WebKit/Source/platform/heap/Member.h b/third_party/WebKit/Source/platform/heap/Member.h index 69099e9..7c263a639 100644 --- a/third_party/WebKit/Source/platform/heap/Member.h +++ b/third_party/WebKit/Source/platform/heap/Member.h
@@ -5,6 +5,7 @@ #ifndef Member_h #define Member_h +#include "platform/heap/Heap.h" #include "platform/heap/HeapPage.h" #include "platform/wtf/Allocator.h" #include "platform/wtf/HashFunctions.h" @@ -244,7 +245,6 @@ protected: ALWAYS_INLINE void WriteBarrier(const T* value) const { -#if HEAP_INCREMENTAL_MARKING if (value) { // The following method for retrieving a page works as allocation of // mixins on large object pages is prohibited. @@ -255,7 +255,9 @@ page->IsLargeObjectPage() ? static_cast<LargeObjectPage*>(page)->GetHeapObjectHeader() : static_cast<NormalPage*>(page)->FindHeaderFromAddress( - reinterpret_cast<Address>(const_cast<T*>(value))); + reinterpret_cast<Address>( + const_cast<typename std::remove_const<T>::type*>( + value))); if (header->IsMarked()) return; @@ -266,7 +268,6 @@ ThreadHeap::GcInfo(header->GcInfoIndex())->trace_); } } -#endif // HEAP_INCREMENTAL_MARKING } };
diff --git a/third_party/WebKit/Source/platform/heap/ThreadState.cpp b/third_party/WebKit/Source/platform/heap/ThreadState.cpp index 8ec018f..2a7c0ac3 100644 --- a/third_party/WebKit/Source/platform/heap/ThreadState.cpp +++ b/third_party/WebKit/Source/platform/heap/ThreadState.cpp
@@ -121,6 +121,7 @@ invalidate_dead_objects_in_wrappers_marking_deque_(nullptr), perform_cleanup_(nullptr), wrapper_tracing_in_progress_(false), + incremental_marking_(false), #if defined(ADDRESS_SANITIZER) asan_fake_stack_(__asan_get_current_fake_stack()), #endif @@ -1234,8 +1235,13 @@ void ThreadState::CollectGarbage(BlinkGC::StackState stack_state, BlinkGC::GCType gc_type, BlinkGC::GCReason reason) { - // Nested collectGarbage() invocations aren't supported. + // Nested garbage collection invocations are not supported. CHECK(!IsGCForbidden()); + // Garbage collection during sweeping is not supported. This can happen when + // finalizers trigger garbage collections. + if (SweepForbidden()) + return; + CompleteSweep(); RUNTIME_CALL_TIMER_SCOPE_IF_ISOLATE_EXISTS(
diff --git a/third_party/WebKit/Source/platform/image-decoders/gif/GIFImageDecoderTest.cpp b/third_party/WebKit/Source/platform/image-decoders/gif/GIFImageDecoderTest.cpp index 55bf097..50f6ac9 100644 --- a/third_party/WebKit/Source/platform/image-decoders/gif/GIFImageDecoderTest.cpp +++ b/third_party/WebKit/Source/platform/image-decoders/gif/GIFImageDecoderTest.cpp
@@ -98,6 +98,27 @@ EXPECT_EQ(kAnimationLoopInfinite, decoder->RepetitionCount()); } +TEST(GIFImageDecoderTest, crbug779261) { + std::unique_ptr<ImageDecoder> decoder = CreateDecoder(); + scoped_refptr<SharedBuffer> data = + ReadFile(kLayoutTestResourcesDir, "crbug779261.gif"); + ASSERT_TRUE(data.get()); + decoder->SetData(data.get(), true); + + for (size_t i = 0; i < decoder->FrameCount(); ++i) { + // In crbug.com/779261, an independent, transparent frame following an + // opaque frame failed to decode. This image has an opaque frame 0 with + // DisposalMethod::kDisposeOverwriteBgcolor, making frame 1, which has + // transparency, independent and contain alpha. + const bool has_alpha = 0 == i ? false : true; + ImageFrame* frame = decoder->DecodeFrameBufferAtIndex(i); + EXPECT_EQ(ImageFrame::kFrameComplete, frame->GetStatus()); + EXPECT_EQ(has_alpha, frame->HasAlpha()); + } + + EXPECT_FALSE(decoder->Failed()); +} + TEST(GIFImageDecoderTest, parseAndDecode) { std::unique_ptr<ImageDecoder> decoder = CreateDecoder();
diff --git a/third_party/WebKit/Source/platform/loader/BUILD.gn b/third_party/WebKit/Source/platform/loader/BUILD.gn index d01444f..10ee6f5 100644 --- a/third_party/WebKit/Source/platform/loader/BUILD.gn +++ b/third_party/WebKit/Source/platform/loader/BUILD.gn
@@ -97,10 +97,11 @@ ] public_deps = [ + "//services/network/public/cpp:cpp", "//services/network/public/interfaces", "//third_party/WebKit/Source/platform/blob:blob", "//third_party/WebKit/Source/platform/network:network", - "//third_party/WebKit/public:mojo_bindings_blink", + "//third_party/WebKit/public:blink_headers", ] } @@ -167,8 +168,8 @@ public_deps = [ "//net", "//skia", - "//third_party/WebKit/Source/platform", "//third_party/WebKit/Source/platform/blob:generator", + "//third_party/WebKit/public:blink_headers", "//third_party/icu", ] }
diff --git a/third_party/WebKit/Source/platform/loader/fetch/BufferingDataPipeWriter.cpp b/third_party/WebKit/Source/platform/loader/fetch/BufferingDataPipeWriter.cpp index 3173dfa..a63dd996 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/BufferingDataPipeWriter.cpp +++ b/third_party/WebKit/Source/platform/loader/fetch/BufferingDataPipeWriter.cpp
@@ -20,7 +20,7 @@ : handle_(std::move(handle)), watcher_(BLINK_FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::MANUAL, - runner->ToSingleThreadTaskRunner()) { + runner) { watcher_.Watch( handle_.get(), MOJO_HANDLE_SIGNAL_WRITABLE, MOJO_WATCH_CONDITION_SATISFIED,
diff --git a/third_party/WebKit/Source/platform/loader/fetch/RawResource.cpp b/third_party/WebKit/Source/platform/loader/fetch/RawResource.cpp index 3f69620..4e477b8 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/RawResource.cpp +++ b/third_party/WebKit/Source/platform/loader/fetch/RawResource.cpp
@@ -206,7 +206,8 @@ // not be reused. // Note: This logic is needed here because DocumentThreadableLoader handles // CORS independently from ResourceLoader. Fix it. - GetMemoryCache()->Remove(this); + if (IsMainThread()) + GetMemoryCache()->Remove(this); } bool is_successful_revalidation = @@ -282,7 +283,7 @@ DCHECK_EQ(GetDataBufferingPolicy(), kBufferData); // Preloading for raw resources are not cached. - DCHECK(!GetMemoryCache()->Contains(this)); + DCHECK(!IsMainThread() || !GetMemoryCache()->Contains(this)); constexpr auto kCapacity = 32 * 1024; mojo::ScopedDataPipeProducerHandle producer;
diff --git a/third_party/WebKit/Source/platform/loader/fetch/ResourceLoader.cpp b/third_party/WebKit/Source/platform/loader/fetch/ResourceLoader.cpp index eb5a474a..919b2ed 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/ResourceLoader.cpp +++ b/third_party/WebKit/Source/platform/loader/fetch/ResourceLoader.cpp
@@ -515,20 +515,15 @@ ResourceRequest last_request = resource_->LastResourceRequest(); DCHECK_EQ(last_request.GetServiceWorkerMode(), WebURLRequest::ServiceWorkerMode::kAll); - // This code handles the case when a regular controlling service worker - // doesn't handle a cross origin request. When this happens we still want - // to give foreign fetch a chance to handle the request, so only skip the - // controlling service worker for the fallback request. This is currently - // safe because of http://crbug.com/604084 the - // wasFallbackRequiredByServiceWorker flag is never set when foreign fetch - // handled a request. + // This code handles the case when a controlling service worker doesn't + // handle a cross origin request. if (!Context().ShouldLoadNewResource(resource_type)) { // Cancel the request if we should not trigger a reload now. HandleError(ResourceError::CancelledError(response.Url())); return; } last_request.SetServiceWorkerMode( - WebURLRequest::ServiceWorkerMode::kForeign); + WebURLRequest::ServiceWorkerMode::kNone); Restart(last_request); return; }
diff --git a/third_party/WebKit/Source/platform/loader/fetch/ResourceRequest.cpp b/third_party/WebKit/Source/platform/loader/fetch/ResourceRequest.cpp index b25ba87..e340552 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/ResourceRequest.cpp +++ b/third_party/WebKit/Source/platform/loader/fetch/ResourceRequest.cpp
@@ -62,7 +62,7 @@ priority_(kResourceLoadPriorityLowest), intra_priority_value_(0), requestor_id_(0), - requestor_process_id_(0), + plugin_child_id_(-1), app_cache_host_id_(0), previews_state_(WebURLRequest::kPreviewsUnspecified), request_context_(WebURLRequest::kRequestContextUnspecified), @@ -106,7 +106,7 @@ SetServiceWorkerMode(data->service_worker_mode_); SetShouldResetAppCache(data->should_reset_app_cache_); SetRequestorID(data->requestor_id_); - SetRequestorProcessID(data->requestor_process_id_); + SetPluginChildID(data->plugin_child_id_); SetAppCacheHostID(data->app_cache_host_id_); SetPreviewsState(data->previews_state_); SetRequestContext(data->request_context_); @@ -193,7 +193,7 @@ data->service_worker_mode_ = service_worker_mode_; data->should_reset_app_cache_ = should_reset_app_cache_; data->requestor_id_ = requestor_id_; - data->requestor_process_id_ = requestor_process_id_; + data->plugin_child_id_ = plugin_child_id_; data->app_cache_host_id_ = app_cache_host_id_; data->previews_state_ = previews_state_; data->request_context_ = request_context_;
diff --git a/third_party/WebKit/Source/platform/loader/fetch/ResourceRequest.h b/third_party/WebKit/Source/platform/loader/fetch/ResourceRequest.h index 295e679..a93c720e 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/ResourceRequest.h +++ b/third_party/WebKit/Source/platform/loader/fetch/ResourceRequest.h
@@ -201,13 +201,13 @@ int RequestorID() const { return requestor_id_; } void SetRequestorID(int requestor_id) { requestor_id_ = requestor_id; } - // The process id of the process from which this request originated. In - // the case of out-of-process plugins, this allows to link back the - // request to the plugin process (as it is processed through a render - // view process). - int RequestorProcessID() const { return requestor_process_id_; } - void SetRequestorProcessID(int requestor_process_id) { - requestor_process_id_ = requestor_process_id; + // The unique child id (not PID) of the process from which this request + // originated. In the case of out-of-process plugins, this allows to link back + // the request to the plugin process (as it is processed through a render view + // process). + int GetPluginChildID() const { return plugin_child_id_; } + void SetPluginChildID(int plugin_child_id) { + plugin_child_id_ = plugin_child_id; } // Allows the request to be matched up with its app cache host. @@ -381,7 +381,7 @@ ResourceLoadPriority priority_; int intra_priority_value_; int requestor_id_; - int requestor_process_id_; + int plugin_child_id_; int app_cache_host_id_; WebURLRequest::PreviewsState previews_state_; scoped_refptr<ExtraData> extra_data_; @@ -444,7 +444,7 @@ ResourceLoadPriority priority_; int intra_priority_value_; int requestor_id_; - int requestor_process_id_; + int plugin_child_id_; int app_cache_host_id_; WebURLRequest::RequestContext request_context_; WebURLRequest::FrameType frame_type_;
diff --git a/third_party/WebKit/Source/platform/loader/fetch/ResourceRequestTest.cpp b/third_party/WebKit/Source/platform/loader/fetch/ResourceRequestTest.cpp index 4863bcd..b507cfb3 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/ResourceRequestTest.cpp +++ b/third_party/WebKit/Source/platform/loader/fetch/ResourceRequestTest.cpp
@@ -39,7 +39,7 @@ original.SetFetchCredentialsMode( network::mojom::FetchCredentialsMode::kSameOrigin); original.SetRequestorID(30); - original.SetRequestorProcessID(40); + original.SetPluginChildID(40); original.SetAppCacheHostID(50); original.SetRequestContext(WebURLRequest::kRequestContextAudio); original.SetFrameType(WebURLRequest::kFrameTypeNested); @@ -71,7 +71,7 @@ EXPECT_EQ(network::mojom::FetchCredentialsMode::kSameOrigin, original.GetFetchCredentialsMode()); EXPECT_EQ(30, original.RequestorID()); - EXPECT_EQ(40, original.RequestorProcessID()); + EXPECT_EQ(40, original.GetPluginChildID()); EXPECT_EQ(50, original.AppCacheHostID()); EXPECT_EQ(WebURLRequest::kRequestContextAudio, original.GetRequestContext()); EXPECT_EQ(WebURLRequest::kFrameTypeNested, original.GetFrameType()); @@ -105,7 +105,7 @@ EXPECT_EQ(network::mojom::FetchCredentialsMode::kSameOrigin, copy1.GetFetchCredentialsMode()); EXPECT_EQ(30, copy1.RequestorID()); - EXPECT_EQ(40, copy1.RequestorProcessID()); + EXPECT_EQ(40, copy1.GetPluginChildID()); EXPECT_EQ(50, copy1.AppCacheHostID()); EXPECT_EQ(WebURLRequest::kRequestContextAudio, copy1.GetRequestContext()); EXPECT_EQ(WebURLRequest::kFrameTypeNested, copy1.GetFrameType());
diff --git a/third_party/WebKit/Source/platform/loader/fetch/ResourceResponse.cpp b/third_party/WebKit/Source/platform/loader/fetch/ResourceResponse.cpp index 08b02b5..70a3826 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/ResourceResponse.cpp +++ b/third_party/WebKit/Source/platform/loader/fetch/ResourceResponse.cpp
@@ -92,7 +92,6 @@ was_fetched_via_spdy_(false), was_fetched_via_proxy_(false), was_fetched_via_service_worker_(false), - was_fetched_via_foreign_fetch_(false), was_fallback_required_by_service_worker_(false), did_service_worker_navigation_preload_(false), response_type_via_service_worker_( @@ -133,7 +132,6 @@ was_fetched_via_spdy_(false), was_fetched_via_proxy_(false), was_fetched_via_service_worker_(false), - was_fetched_via_foreign_fetch_(false), was_fallback_required_by_service_worker_(false), did_service_worker_navigation_preload_(false), response_type_via_service_worker_( @@ -169,7 +167,6 @@ was_fetched_via_spdy_ = data->was_fetched_via_spdy_; was_fetched_via_proxy_ = data->was_fetched_via_proxy_; was_fetched_via_service_worker_ = data->was_fetched_via_service_worker_; - was_fetched_via_foreign_fetch_ = data->was_fetched_via_foreign_fetch_; was_fallback_required_by_service_worker_ = data->was_fallback_required_by_service_worker_; did_service_worker_navigation_preload_ = @@ -232,7 +229,6 @@ data->was_fetched_via_spdy_ = was_fetched_via_spdy_; data->was_fetched_via_proxy_ = was_fetched_via_proxy_; data->was_fetched_via_service_worker_ = was_fetched_via_service_worker_; - data->was_fetched_via_foreign_fetch_ = was_fetched_via_foreign_fetch_; data->was_fallback_required_by_service_worker_ = was_fallback_required_by_service_worker_; data->did_service_worker_navigation_preload_ =
diff --git a/third_party/WebKit/Source/platform/loader/fetch/ResourceResponse.h b/third_party/WebKit/Source/platform/loader/fetch/ResourceResponse.h index ce79981..d95b70c 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/ResourceResponse.h +++ b/third_party/WebKit/Source/platform/loader/fetch/ResourceResponse.h
@@ -290,13 +290,6 @@ was_fetched_via_service_worker_ = value; } - bool WasFetchedViaForeignFetch() const { - return was_fetched_via_foreign_fetch_; - } - void SetWasFetchedViaForeignFetch(bool value) { - was_fetched_via_foreign_fetch_ = value; - } - // See ServiceWorkerResponseInfo::was_fallback_required. bool WasFallbackRequiredByServiceWorker() const { return was_fallback_required_by_service_worker_; @@ -460,9 +453,6 @@ // Was the resource fetched over a ServiceWorker. bool was_fetched_via_service_worker_ : 1; - // Was the resource fetched using a foreign fetch service worker. - bool was_fetched_via_foreign_fetch_ : 1; - // Was the fallback request with skip service worker flag required. bool was_fallback_required_by_service_worker_ : 1; @@ -598,7 +588,6 @@ bool was_fetched_via_spdy_; bool was_fetched_via_proxy_; bool was_fetched_via_service_worker_; - bool was_fetched_via_foreign_fetch_; bool was_fallback_required_by_service_worker_; network::mojom::FetchResponseType response_type_via_service_worker_; Vector<KURL> url_list_via_service_worker_;
diff --git a/third_party/WebKit/Source/platform/loader/testing/MockFetchContext.h b/third_party/WebKit/Source/platform/loader/testing/MockFetchContext.h index 24ff2a6d..643c4b6 100644 --- a/third_party/WebKit/Source/platform/loader/testing/MockFetchContext.h +++ b/third_party/WebKit/Source/platform/loader/testing/MockFetchContext.h
@@ -93,8 +93,7 @@ Platform::Current()->CreateDefaultURLLoaderFactory(); } WrappedResourceRequest wrapped(request); - return url_loader_factory_->CreateURLLoader( - wrapped, task_runner->ToSingleThreadTaskRunner()); + return url_loader_factory_->CreateURLLoader(wrapped, task_runner); } WebFrameScheduler* GetFrameScheduler() override {
diff --git a/third_party/WebKit/Source/platform/network/HeaderFieldTokenizer.h b/third_party/WebKit/Source/platform/network/HeaderFieldTokenizer.h index 15d174c..5b4ab11 100644 --- a/third_party/WebKit/Source/platform/network/HeaderFieldTokenizer.h +++ b/third_party/WebKit/Source/platform/network/HeaderFieldTokenizer.h
@@ -5,6 +5,7 @@ #ifndef HeaderFieldTokenizer_h #define HeaderFieldTokenizer_h +#include "platform/PlatformExport.h" #include "platform/network/ParsedContentHeaderFieldParameters.h" #include "platform/wtf/text/WTFString.h" @@ -12,7 +13,7 @@ // Parses header fields into tokens, quoted strings and separators. // Commonly used by ParsedContent* classes. -class HeaderFieldTokenizer final { +class PLATFORM_EXPORT HeaderFieldTokenizer final { STACK_ALLOCATED(); public:
diff --git a/third_party/WebKit/Source/platform/network/ParsedContentDisposition.cpp b/third_party/WebKit/Source/platform/network/ParsedContentDisposition.cpp index 1ce57f7..ca42a8fc 100644 --- a/third_party/WebKit/Source/platform/network/ParsedContentDisposition.cpp +++ b/third_party/WebKit/Source/platform/network/ParsedContentDisposition.cpp
@@ -20,7 +20,8 @@ } type_ = type.ToString(); - parameters_.ParseParameters(std::move(tokenizer), mode); + parameters_ = + ParsedContentHeaderFieldParameters::Parse(std::move(tokenizer), mode); } String ParsedContentDisposition::Filename() const {
diff --git a/third_party/WebKit/Source/platform/network/ParsedContentDisposition.h b/third_party/WebKit/Source/platform/network/ParsedContentDisposition.h index 7cb7686..56e380cf 100644 --- a/third_party/WebKit/Source/platform/network/ParsedContentDisposition.h +++ b/third_party/WebKit/Source/platform/network/ParsedContentDisposition.h
@@ -9,7 +9,8 @@ #include "platform/network/ParsedContentHeaderFieldParameters.h" #include "platform/wtf/Allocator.h" #include "platform/wtf/HashMap.h" -#include "platform/wtf/text/StringHash.h" +#include "platform/wtf/Optional.h" +#include "platform/wtf/text/WTFString.h" namespace blink { @@ -29,15 +30,13 @@ // Note that in the case of multiple values for the same name, the last value // is returned. String ParameterValueForName(const String& name) const { - return parameters_.ParameterValueForName(name); + return IsValid() ? parameters_->ParameterValueForName(name) : String(); } - size_t ParameterCount() const { return parameters_.ParameterCount(); } - - bool IsValid() const { return parameters_.IsValid(); } + bool IsValid() const { return !!parameters_; } private: String type_; - ParsedContentHeaderFieldParameters parameters_; + WTF::Optional<ParsedContentHeaderFieldParameters> parameters_; }; } // namespace blink
diff --git a/third_party/WebKit/Source/platform/network/ParsedContentHeaderFieldParameters.cpp b/third_party/WebKit/Source/platform/network/ParsedContentHeaderFieldParameters.cpp index 3c425e5..6ee09cbf 100644 --- a/third_party/WebKit/Source/platform/network/ParsedContentHeaderFieldParameters.cpp +++ b/third_party/WebKit/Source/platform/network/ParsedContentHeaderFieldParameters.cpp
@@ -5,34 +5,13 @@ #include "platform/network/ParsedContentHeaderFieldParameters.h" #include "platform/network/HeaderFieldTokenizer.h" +#include "platform/wtf/HashSet.h" #include "platform/wtf/text/StringBuilder.h" +#include "platform/wtf/text/StringHash.h" #include "platform/wtf/text/StringView.h" namespace blink { -ParsedContentHeaderFieldParameters::ParsedContentHeaderFieldParameters() - : is_valid_(false) {} - -// static -ParsedContentHeaderFieldParameters -ParsedContentHeaderFieldParameters::CreateForTesting(const String& input, - Mode mode) { - ParsedContentHeaderFieldParameters parameters; - parameters.ParseParameters(HeaderFieldTokenizer(input), mode); - return parameters; -} - -String ParsedContentHeaderFieldParameters::ParameterValueForName( - const String& name) const { - if (!name.ContainsOnlyASCII()) - return String(); - return parameters_.at(name.LowerASCII()); -} - -size_t ParsedContentHeaderFieldParameters::ParameterCount() const { - return parameters_.size(); -} - // parameters := *(";" parameter) // // From http://tools.ietf.org/html/rfc2045#section-5.1: @@ -53,17 +32,14 @@ // "/" / "[" / "]" / "?" / "=" // ; Must be in quoted-string, // ; to use within parameter values -void ParsedContentHeaderFieldParameters::ParseParameters( - HeaderFieldTokenizer tokenizer, - Mode mode) { - DCHECK(!is_valid_); - DCHECK(parameters_.IsEmpty()); - - KeyValuePairs map; +WTF::Optional<ParsedContentHeaderFieldParameters> +ParsedContentHeaderFieldParameters::Parse(HeaderFieldTokenizer tokenizer, + Mode mode) { + NameValuePairs parameters; while (!tokenizer.IsConsumed()) { if (!tokenizer.Consume(';')) { DVLOG(1) << "Failed to find ';'"; - return; + return WTF::nullopt; } StringView key; @@ -71,29 +47,50 @@ if (!tokenizer.ConsumeToken(Mode::kNormal, key)) { DVLOG(1) << "Invalid content parameter name. (at " << tokenizer.Index() << ")"; - return; + return WTF::nullopt; } if (!tokenizer.Consume('=')) { DVLOG(1) << "Failed to find '='"; - return; + return WTF::nullopt; } if (!tokenizer.ConsumeTokenOrQuotedString(mode, value)) { DVLOG(1) << "Invalid content parameter value (at " << tokenizer.Index() << ", for '" << key.ToString() << "')."; - return; + return WTF::nullopt; } - // As |key| is parsed as a token, it consists of ascii characters - // and hence we don't need to care about non-ascii lowercasing. - DCHECK(key.ToString().ContainsOnlyASCII()); - String key_string = key.ToString().LowerASCII(); - if (mode == Mode::kStrict && map.find(key_string) != map.end()) { - DVLOG(1) << "Parameter " << key_string << " is defined multiple times."; - return; - } - map.Set(key_string, value); + parameters.emplace_back(key.ToString(), value); } - parameters_ = std::move(map); - is_valid_ = true; + + return ParsedContentHeaderFieldParameters(std::move(parameters)); +} + +String ParsedContentHeaderFieldParameters::ParameterValueForName( + const String& name) const { + if (!name.ContainsOnlyASCII()) + return String(); + String lower_name = name.LowerASCII(); + + for (auto i = rbegin(); i != rend(); ++i) { + if (i->name.LowerASCII() == lower_name) + return i->value; + } + return String(); +} + +size_t ParsedContentHeaderFieldParameters::ParameterCount() const { + return parameters_.size(); +} + +bool ParsedContentHeaderFieldParameters::HasDuplicatedNames() const { + HashSet<String> names; + for (const auto& parameter : parameters_) { + const String lowered_name = parameter.name.LowerASCII(); + if (names.find(lowered_name) != names.end()) + return true; + + names.insert(lowered_name); + } + return false; } } // namespace blink
diff --git a/third_party/WebKit/Source/platform/network/ParsedContentHeaderFieldParameters.h b/third_party/WebKit/Source/platform/network/ParsedContentHeaderFieldParameters.h index 7158ebc..6271516 100644 --- a/third_party/WebKit/Source/platform/network/ParsedContentHeaderFieldParameters.h +++ b/third_party/WebKit/Source/platform/network/ParsedContentHeaderFieldParameters.h
@@ -7,8 +7,9 @@ #include "platform/PlatformExport.h" #include "platform/wtf/Allocator.h" -#include "platform/wtf/HashMap.h" -#include "platform/wtf/text/StringHash.h" +#include "platform/wtf/Optional.h" +#include "platform/wtf/Vector.h" +#include "platform/wtf/text/WTFString.h" namespace blink { @@ -18,40 +19,52 @@ // them. It is used internally by ParsedContent* classes. // FIXME: add support for comments. class PLATFORM_EXPORT ParsedContentHeaderFieldParameters final { - STACK_ALLOCATED(); + DISALLOW_NEW_EXCEPT_PLACEMENT_NEW(); public: + struct NameValue { + NameValue(String name, String value) : name(name), value(value) {} + + String name; + String value; + }; + + using NameValuePairs = Vector<NameValue>; + using const_iterator = NameValuePairs::const_iterator; + using reverse_const_iterator = NameValuePairs::const_reverse_iterator; + // When |Relaxed| is specified, the parser parses parameter values in a sloppy // manner, i.e., only ';' and '"' are treated as special characters. // See https://chromiumcodereview.appspot.com/23043002. - // When |Strict| is specified, the parser does not allow multiple values - // for the same parameter. Some RFCs based on RFC2045 (e.g. RFC6838) note that - // "It is an error for a specific parameter to be specified more than once." enum class Mode { kNormal, kRelaxed, - kStrict, }; - ParsedContentHeaderFieldParameters(); + // We use base::Optional instead of WTF::Optional which requires its content + // type to be fully defined. They are essentially same, so uses of this class + // can (and should) use WTF::Optional to store the returned value. + static base::Optional<ParsedContentHeaderFieldParameters> Parse( + HeaderFieldTokenizer, + Mode); // Note that in the case of multiple values for the same name, the last value // is returned. String ParameterValueForName(const String&) const; size_t ParameterCount() const; + bool HasDuplicatedNames() const; - bool IsValid() const { return is_valid_; } + const_iterator begin() const { return parameters_.begin(); } + const_iterator end() const { return parameters_.end(); } - void ParseParameters(HeaderFieldTokenizer, Mode); - - static ParsedContentHeaderFieldParameters CreateForTesting( - const String&, - Mode = Mode::kNormal); + reverse_const_iterator rbegin() const { return parameters_.rbegin(); } + reverse_const_iterator rend() const { return parameters_.rend(); } private: - typedef HashMap<String, String> KeyValuePairs; - bool is_valid_; - KeyValuePairs parameters_; + explicit ParsedContentHeaderFieldParameters(NameValuePairs parameters) + : parameters_(std::move(parameters)) {} + + NameValuePairs parameters_; }; } // namespace blink
diff --git a/third_party/WebKit/Source/platform/network/ParsedContentHeaderFieldParametersTest.cpp b/third_party/WebKit/Source/platform/network/ParsedContentHeaderFieldParametersTest.cpp index 9877c05..ce8c49ac 100644 --- a/third_party/WebKit/Source/platform/network/ParsedContentHeaderFieldParametersTest.cpp +++ b/third_party/WebKit/Source/platform/network/ParsedContentHeaderFieldParametersTest.cpp
@@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "platform/network/HeaderFieldTokenizer.h" #include "platform/network/ParsedContentDisposition.h" #include "platform/network/ParsedContentHeaderFieldParameters.h" #include "platform/network/ParsedContentType.h" @@ -17,9 +18,8 @@ void CheckValidity(bool expected, const String& input, Mode mode = Mode::kNormal) { - EXPECT_EQ(expected, - ParsedContentHeaderFieldParameters::CreateForTesting(input, mode) - .IsValid()) + EXPECT_EQ(expected, !!ParsedContentHeaderFieldParameters::Parse( + HeaderFieldTokenizer(input), mode)) << input; const String disposition_input = "attachment" + input; @@ -68,22 +68,24 @@ CheckValidity(true, input); - ParsedContentHeaderFieldParameters t = - ParsedContentHeaderFieldParameters::CreateForTesting(input, - Mode::kNormal); - EXPECT_TRUE(t.IsValid()); - EXPECT_EQ(4u, t.ParameterCount()); - EXPECT_EQ(String(), t.ParameterValueForName("a")); - EXPECT_EQ(String(), t.ParameterValueForName("x")); - EXPECT_EQ("u", t.ParameterValueForName("y")); - EXPECT_EQ("S", t.ParameterValueForName("t")); - EXPECT_EQ("t u\"x", t.ParameterValueForName("k")); - EXPECT_EQ("U", t.ParameterValueForName("Q")); - EXPECT_EQ("S", t.ParameterValueForName("T")); + WTF::Optional<ParsedContentHeaderFieldParameters> t = + ParsedContentHeaderFieldParameters::Parse(HeaderFieldTokenizer(input), + Mode::kNormal); + ASSERT_TRUE(t); + + EXPECT_EQ(6u, t->ParameterCount()); + EXPECT_TRUE(t->HasDuplicatedNames()); + EXPECT_EQ(String(), t->ParameterValueForName("a")); + EXPECT_EQ(String(), t->ParameterValueForName("x")); + EXPECT_EQ("u", t->ParameterValueForName("y")); + EXPECT_EQ("S", t->ParameterValueForName("t")); + EXPECT_EQ("t u\"x", t->ParameterValueForName("k")); + EXPECT_EQ("U", t->ParameterValueForName("Q")); + EXPECT_EQ("S", t->ParameterValueForName("T")); String kelvin = String::FromUTF8("\xe2\x84\xaa"); DCHECK_EQ(kelvin.LowerUnicode(AtomicString()), "k"); - EXPECT_EQ(String(), t.ParameterValueForName(kelvin)); + EXPECT_EQ(String(), t->ParameterValueForName(kelvin)); } TEST(ParsedContentHeaderFieldParametersTest, RelaxedParameterName) { @@ -91,20 +93,72 @@ CheckValidity(true, input, Mode::kRelaxed); - ParsedContentHeaderFieldParameters t = - ParsedContentHeaderFieldParameters::CreateForTesting(input, - Mode::kRelaxed); - EXPECT_TRUE(t.IsValid()); - EXPECT_EQ(2u, t.ParameterCount()); - EXPECT_EQ("q/t:()<>@,:\\/[]?=", t.ParameterValueForName("z")); - EXPECT_EQ("u", t.ParameterValueForName("y")); + WTF::Optional<ParsedContentHeaderFieldParameters> t = + ParsedContentHeaderFieldParameters::Parse(HeaderFieldTokenizer(input), + Mode::kRelaxed); + ASSERT_TRUE(t); + EXPECT_EQ(2u, t->ParameterCount()); + EXPECT_FALSE(t->HasDuplicatedNames()); + EXPECT_EQ("q/t:()<>@,:\\/[]?=", t->ParameterValueForName("z")); + EXPECT_EQ("u", t->ParameterValueForName("y")); } -TEST(ParsedContentHeaderFieldParametersTest, StrictParameterName) { - CheckValidity(true, "", Mode::kStrict); - CheckValidity(true, "; p1=a", Mode::kStrict); - CheckValidity(false, "; p1=a; p1=b", Mode::kStrict); - CheckValidity(true, "; p1=a; p2=b", Mode::kStrict); +TEST(ParsedContentHeaderFieldParametersTest, BeginEnd) { + String input = "; a=b; a=c; b=d"; + + WTF::Optional<ParsedContentHeaderFieldParameters> t = + ParsedContentHeaderFieldParameters::Parse(HeaderFieldTokenizer(input), + Mode::kNormal); + ASSERT_TRUE(t); + EXPECT_TRUE(t->HasDuplicatedNames()); + EXPECT_EQ(3u, t->ParameterCount()); + + auto i = t->begin(); + ASSERT_NE(i, t->end()); + EXPECT_EQ(i->name, "a"); + EXPECT_EQ(i->value, "b"); + + ++i; + ASSERT_NE(i, t->end()); + EXPECT_EQ(i->name, "a"); + EXPECT_EQ(i->value, "c"); + + ++i; + ASSERT_NE(i, t->end()); + EXPECT_EQ(i->name, "b"); + EXPECT_EQ(i->value, "d"); + + ++i; + ASSERT_EQ(i, t->end()); +} + +TEST(ParsedContentHeaderFieldParametersTest, RBeginEnd) { + String input = "; a=B; A=c; b=d"; + + WTF::Optional<ParsedContentHeaderFieldParameters> t = + ParsedContentHeaderFieldParameters::Parse(HeaderFieldTokenizer(input), + Mode::kNormal); + ASSERT_TRUE(t); + EXPECT_TRUE(t->HasDuplicatedNames()); + EXPECT_EQ(3u, t->ParameterCount()); + + auto i = t->rbegin(); + ASSERT_NE(i, t->rend()); + EXPECT_EQ(i->name, "b"); + EXPECT_EQ(i->value, "d"); + + ++i; + ASSERT_NE(i, t->rend()); + EXPECT_EQ(i->name, "A"); + EXPECT_EQ(i->value, "c"); + + ++i; + ASSERT_NE(i, t->rend()); + EXPECT_EQ(i->name, "a"); + EXPECT_EQ(i->value, "B"); + + ++i; + ASSERT_EQ(i, t->rend()); } } // namespace
diff --git a/third_party/WebKit/Source/platform/network/ParsedContentType.cpp b/third_party/WebKit/Source/platform/network/ParsedContentType.cpp index 09123df..7fbd215 100644 --- a/third_party/WebKit/Source/platform/network/ParsedContentType.cpp +++ b/third_party/WebKit/Source/platform/network/ParsedContentType.cpp
@@ -105,7 +105,8 @@ builder.Append(subtype); mime_type_ = builder.ToString(); - parameters_.ParseParameters(std::move(tokenizer), mode); + parameters_ = + ParsedContentHeaderFieldParameters::Parse(std::move(tokenizer), mode); } String ParsedContentType::Charset() const {
diff --git a/third_party/WebKit/Source/platform/network/ParsedContentType.h b/third_party/WebKit/Source/platform/network/ParsedContentType.h index 233f0d7..39d0035a 100644 --- a/third_party/WebKit/Source/platform/network/ParsedContentType.h +++ b/third_party/WebKit/Source/platform/network/ParsedContentType.h
@@ -35,8 +35,8 @@ #include "platform/PlatformExport.h" #include "platform/network/ParsedContentHeaderFieldParameters.h" #include "platform/wtf/Allocator.h" -#include "platform/wtf/HashMap.h" -#include "platform/wtf/text/StringHash.h" +#include "platform/wtf/Optional.h" +#include "platform/wtf/text/WTFString.h" namespace blink { @@ -57,15 +57,18 @@ // Note that in the case of multiple values for the same name, the last value // is returned. String ParameterValueForName(const String& name) const { - return parameters_.ParameterValueForName(name); + return IsValid() ? parameters_->ParameterValueForName(name) : String(); } - size_t ParameterCount() const { return parameters_.ParameterCount(); } + const ParsedContentHeaderFieldParameters& GetParameters() const { + DCHECK(IsValid()); + return *parameters_; + } - bool IsValid() const { return parameters_.IsValid(); } + bool IsValid() const { return !!parameters_; } private: String mime_type_; - ParsedContentHeaderFieldParameters parameters_; + WTF::Optional<ParsedContentHeaderFieldParameters> parameters_; }; } // namespace blink
diff --git a/third_party/WebKit/Source/platform/runtime_enabled_features.json5 b/third_party/WebKit/Source/platform/runtime_enabled_features.json5 index b98b663..bc12f466 100644 --- a/third_party/WebKit/Source/platform/runtime_enabled_features.json5 +++ b/third_party/WebKit/Source/platform/runtime_enabled_features.json5
@@ -425,10 +425,6 @@ name: "ForceTallerSelectPopup", }, { - name: "ForeignFetch", - origin_trial_feature_name: "ForeignFetch", - }, - { name: "FractionalMouseEvent", }, { @@ -541,10 +537,6 @@ status: "experimental", }, { - name: "LinkServiceWorker", - origin_trial_feature_name: "ForeignFetch", - }, - { name: "LoadingWithMojo", }, {
diff --git a/third_party/WebKit/Source/platform/scheduler/child/web_task_runner_impl.cc b/third_party/WebKit/Source/platform/scheduler/child/web_task_runner_impl.cc index 98a27d2db..e8ba336 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/web_task_runner_impl.cc +++ b/third_party/WebKit/Source/platform/scheduler/child/web_task_runner_impl.cc
@@ -19,11 +19,11 @@ scoped_refptr<WebTaskRunnerImpl> WebTaskRunnerImpl::Create( scoped_refptr<TaskQueue> task_queue, base::Optional<TaskType> task_type) { - return base::AdoptRef( + return base::WrapRefCounted( new WebTaskRunnerImpl(std::move(task_queue), task_type)); } -bool WebTaskRunnerImpl::RunsTasksInCurrentSequence() { +bool WebTaskRunnerImpl::RunsTasksInCurrentSequence() const { return task_queue_->RunsTasksInCurrentSequence(); } @@ -47,11 +47,6 @@ return time_domain->Now(); } -scoped_refptr<base::SingleThreadTaskRunner> -WebTaskRunnerImpl::ToSingleThreadTaskRunner() { - return task_queue_.get(); -} - bool WebTaskRunnerImpl::PostDelayedTask(const base::Location& location, base::OnceClosure task, base::TimeDelta delay) { @@ -59,5 +54,14 @@ std::move(task), location, delay, base::Nestable::kNestable, task_type_)); } +bool WebTaskRunnerImpl::PostNonNestableDelayedTask( + const base::Location& location, + base::OnceClosure task, + base::TimeDelta delay) { + return task_queue_->PostTaskWithMetadata( + TaskQueue::PostedTask(std::move(task), location, delay, + base::Nestable::kNonNestable, task_type_)); +} + } // namespace scheduler } // namespace blink
diff --git a/third_party/WebKit/Source/platform/scheduler/child/web_task_runner_impl.h b/third_party/WebKit/Source/platform/scheduler/child/web_task_runner_impl.h index 57b67159..d0bf648 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/web_task_runner_impl.h +++ b/third_party/WebKit/Source/platform/scheduler/child/web_task_runner_impl.h
@@ -26,11 +26,11 @@ scoped_refptr<TaskQueue> task_queue, base::Optional<TaskType> task_type); + // base::SingleThreadTaskRunner implementation: + bool RunsTasksInCurrentSequence() const override; + // WebTaskRunner implementation: - bool RunsTasksInCurrentSequence() override; double MonotonicallyIncreasingVirtualTimeSeconds() const override; - scoped_refptr<base::SingleThreadTaskRunner> ToSingleThreadTaskRunner() - override; TaskQueue* GetTaskQueue() const { return task_queue_.get(); } @@ -38,6 +38,9 @@ bool PostDelayedTask(const base::Location&, base::OnceClosure, base::TimeDelta) override; + bool PostNonNestableDelayedTask(const base::Location&, + base::OnceClosure, + base::TimeDelta) override; private: WebTaskRunnerImpl(scoped_refptr<TaskQueue> task_queue,
diff --git a/third_party/WebKit/Source/platform/scheduler/test/fake_web_task_runner.cc b/third_party/WebKit/Source/platform/scheduler/test/fake_web_task_runner.cc index 4925d248..18e16dc9 100644 --- a/third_party/WebKit/Source/platform/scheduler/test/fake_web_task_runner.cc +++ b/third_party/WebKit/Source/platform/scheduler/test/fake_web_task_runner.cc
@@ -20,7 +20,7 @@ public: Data() {} - void PostTask(base::OnceClosure task, base::TimeDelta delay) { + void PostDelayedTask(base::OnceClosure task, base::TimeDelta delay) { task_queue_.emplace_back(std::move(task), time_ + delay); } @@ -43,38 +43,10 @@ DISALLOW_COPY_AND_ASSIGN(Data); }; -class FakeWebTaskRunner::BaseTaskRunner : public base::SingleThreadTaskRunner { - public: - explicit BaseTaskRunner(scoped_refptr<Data> data) : data_(std::move(data)) {} +FakeWebTaskRunner::FakeWebTaskRunner() : data_(base::AdoptRef(new Data)) {} - bool PostDelayedTask(const base::Location& from_here, - base::OnceClosure task, - base::TimeDelta delay) override { - data_->PostTask(std::move(task), delay); - return true; - } - - bool PostNonNestableDelayedTask(const base::Location& from_here, - base::OnceClosure task, - base::TimeDelta delay) override { - data_->PostTask(std::move(task), delay); - return true; - } - - bool RunsTasksInCurrentSequence() const { return true; } - - private: - scoped_refptr<Data> data_; -}; - -FakeWebTaskRunner::FakeWebTaskRunner() - : data_(base::AdoptRef(new Data)), - base_task_runner_(new BaseTaskRunner(data_)) {} - -FakeWebTaskRunner::FakeWebTaskRunner( - scoped_refptr<Data> data, - scoped_refptr<BaseTaskRunner> base_task_runner) - : data_(std::move(data)), base_task_runner_(std::move(base_task_runner)) {} +FakeWebTaskRunner::FakeWebTaskRunner(scoped_refptr<Data> data) + : data_(std::move(data)) {} FakeWebTaskRunner::~FakeWebTaskRunner() { } @@ -83,7 +55,7 @@ data_->time_ = new_time; } -bool FakeWebTaskRunner::RunsTasksInCurrentSequence() { +bool FakeWebTaskRunner::RunsTasksInCurrentSequence() const { return true; } @@ -91,11 +63,6 @@ return (data_->time_ - base::TimeTicks()).InSecondsF(); } -scoped_refptr<base::SingleThreadTaskRunner> -FakeWebTaskRunner::ToSingleThreadTaskRunner() { - return base_task_runner_; -} - void FakeWebTaskRunner::RunUntilIdle() { while (!data_->task_queue_.empty()) { // Move the task to run into a local variable in case it touches the @@ -124,7 +91,16 @@ bool FakeWebTaskRunner::PostDelayedTask(const base::Location& location, base::OnceClosure task, base::TimeDelta delay) { - return base_task_runner_->PostDelayedTask(location, std::move(task), delay); + data_->PostDelayedTask(std::move(task), delay); + return true; +} + +bool FakeWebTaskRunner::PostNonNestableDelayedTask( + const base::Location& location, + base::OnceClosure task, + base::TimeDelta delay) { + data_->PostDelayedTask(std::move(task), delay); + return true; } } // namespace scheduler
diff --git a/third_party/WebKit/Source/platform/scheduler/test/fake_web_task_runner.h b/third_party/WebKit/Source/platform/scheduler/test/fake_web_task_runner.h index 41c30d3..076d093a 100644 --- a/third_party/WebKit/Source/platform/scheduler/test/fake_web_task_runner.h +++ b/third_party/WebKit/Source/platform/scheduler/test/fake_web_task_runner.h
@@ -26,11 +26,11 @@ SetTime(base::TimeTicks() + base::TimeDelta::FromSecondsD(new_time)); } + // base::SingleThreadTaskRunner implementation: + bool RunsTasksInCurrentSequence() const override; + // WebTaskRunner implementation: - bool RunsTasksInCurrentSequence() override; double MonotonicallyIncreasingVirtualTimeSeconds() const override; - scoped_refptr<base::SingleThreadTaskRunner> ToSingleThreadTaskRunner() - override; void RunUntilIdle(); void AdvanceTimeAndRun(base::TimeDelta delta); @@ -45,6 +45,9 @@ bool PostDelayedTask(const base::Location& location, base::OnceClosure task, base::TimeDelta delay) override; + bool PostNonNestableDelayedTask(const base::Location&, + base::OnceClosure task, + base::TimeDelta delay) override; private: ~FakeWebTaskRunner() override; @@ -52,10 +55,8 @@ class Data; class BaseTaskRunner; scoped_refptr<Data> data_; - scoped_refptr<BaseTaskRunner> base_task_runner_; - FakeWebTaskRunner(scoped_refptr<Data> data, - scoped_refptr<BaseTaskRunner> base_task_runner); + explicit FakeWebTaskRunner(scoped_refptr<Data> data); DISALLOW_COPY_AND_ASSIGN(FakeWebTaskRunner); };
diff --git a/third_party/WebKit/Source/platform/wtf/Time.h b/third_party/WebKit/Source/platform/wtf/Time.h index 929d7e49..74d0cd6 100644 --- a/third_party/WebKit/Source/platform/wtf/Time.h +++ b/third_party/WebKit/Source/platform/wtf/Time.h
@@ -54,24 +54,21 @@ // Allows wtf/Time.h to use the same mock time function WTF_EXPORT TimeFunction GetTimeFunctionForTesting(); -namespace internal { - -template <class WrappedTimeType> -class TimeWrapper { +class TimeTicks { public: - TimeWrapper() {} - explicit TimeWrapper(WrappedTimeType value) : value_(value) {} + TimeTicks() {} + TimeTicks(base::TimeTicks value) : value_(value) {} - static TimeWrapper Now() { + static TimeTicks Now() { if (WTF::GetTimeFunctionForTesting()) { double seconds = (WTF::GetTimeFunctionForTesting())(); - return TimeWrapper() + TimeDelta::FromSecondsD(seconds); + return TimeTicks() + TimeDelta::FromSecondsD(seconds); } - return TimeWrapper(WrappedTimeType::Now()); + return TimeTicks(base::TimeTicks::Now()); } - static TimeWrapper UnixEpoch() { - return TimeWrapper(WrappedTimeType::UnixEpoch()); + static TimeTicks UnixEpoch() { + return TimeTicks(base::TimeTicks::UnixEpoch()); } int64_t ToInternalValueForTesting() const { return value_.ToInternalValue(); } @@ -79,50 +76,50 @@ // Only use this conversion when interfacing with legacy code that represents // time in double. Converting to double can lead to losing information for // large time values. - double InSeconds() const { return (value_ - WrappedTimeType()).InSecondsF(); } + double InSeconds() const { return (value_ - base::TimeTicks()).InSecondsF(); } - static TimeWrapper FromSeconds(double seconds) { - return TimeWrapper() + TimeDelta::FromSecondsD(seconds); + static TimeTicks FromSeconds(double seconds) { + return TimeTicks() + TimeDelta::FromSecondsD(seconds); } - TimeWrapper& operator=(TimeWrapper other) { + bool is_null() const { return value_.is_null(); } + + operator base::TimeTicks() const { return value_; } + + TimeTicks& operator=(TimeTicks other) { value_ = other.value_; return *this; } - TimeDelta operator-(TimeWrapper other) const { return value_ - other.value_; } + TimeDelta operator-(TimeTicks other) const { return value_ - other.value_; } - TimeWrapper operator+(TimeDelta delta) const { - return TimeWrapper(value_ + delta); + TimeTicks operator+(TimeDelta delta) const { + return TimeTicks(value_ + delta); } - TimeWrapper operator-(TimeDelta delta) const { - return TimeWrapper(value_ - delta); + TimeTicks operator-(TimeDelta delta) const { + return TimeTicks(value_ - delta); } - TimeWrapper& operator+=(TimeDelta delta) { + TimeTicks& operator+=(TimeDelta delta) { value_ += delta; return *this; } - TimeWrapper& operator-=(TimeDelta delta) { + TimeTicks& operator-=(TimeDelta delta) { value_ -= delta; return *this; } - bool operator==(TimeWrapper other) const { return value_ == other.value_; } - bool operator!=(TimeWrapper other) const { return value_ != other.value_; } - bool operator<(TimeWrapper other) const { return value_ < other.value_; } - bool operator<=(TimeWrapper other) const { return value_ <= other.value_; } - bool operator>(TimeWrapper other) const { return value_ > other.value_; } - bool operator>=(TimeWrapper other) const { return value_ >= other.value_; } + bool operator==(TimeTicks other) const { return value_ == other.value_; } + bool operator!=(TimeTicks other) const { return value_ != other.value_; } + bool operator<(TimeTicks other) const { return value_ < other.value_; } + bool operator<=(TimeTicks other) const { return value_ <= other.value_; } + bool operator>(TimeTicks other) const { return value_ > other.value_; } + bool operator>=(TimeTicks other) const { return value_ >= other.value_; } private: - WrappedTimeType value_; + base::TimeTicks value_; }; -} // namespace internal - -using TimeTicks = internal::TimeWrapper<base::TimeTicks>; - } // namespace WTF using WTF::CurrentTime;
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/common/net/git_cl.py b/third_party/WebKit/Tools/Scripts/webkitpy/common/net/git_cl.py index 26b7588..2f6ffe3d 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/common/net/git_cl.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/common/net/git_cl.py
@@ -184,7 +184,9 @@ for result in raw_results: if builder_names and result['builder_name'] not in builder_names: continue - is_swarming_task = result['url'] and '/task/' in result['url'] + is_swarming_task = result['url'] and ( + '/task/' in result['url'] or + '//ci.chromium.org' in result['url']) if is_swarming_task and not include_swarming_tasks: continue build_to_status[self._build(result)] = self._try_job_status(result)
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/servers/apache_http.py b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/servers/apache_http.py index dff9484..f9e619e 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/servers/apache_http.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/servers/apache_http.py
@@ -58,7 +58,6 @@ test_dir = self._port_obj.layout_tests_dir() document_root = self._filesystem.join(test_dir, 'http', 'tests') forms_test_resources_dir = self._filesystem.join(test_dir, 'fast', 'forms', 'resources') - imported_resources_dir = self._filesystem.join(test_dir, 'external', 'wpt', 'resources') media_resources_dir = self._filesystem.join(test_dir, 'media') webaudio_resources_dir = self._filesystem.join(test_dir, 'webaudio', 'resources') mime_types_path = self._filesystem.join(self._port_obj.apache_config_directory(), 'mime.types') @@ -80,7 +79,6 @@ '-c', 'Alias /geolocation-api/js-test-resources "%s/geolocation-api/resources"' % test_dir, '-c', 'Alias /resources/testharness.js "%s/resources/testharness.js"' % test_dir, '-c', 'Alias /resources/testharnessreport.js "%s/resources/testharnessreport.js"' % test_dir, - '-c', 'Alias /w3c/resources/WebIDLParser.js "%s/webidl2/lib/webidl2.js"' % imported_resources_dir, '-c', 'Alias /w3c/resources "%s/resources"' % test_dir, '-c', 'Alias /forms-test-resources "%s"' % forms_test_resources_dir, '-c', 'Alias /media-resources "%s"' % media_resources_dir,
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/try_flag.py b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/try_flag.py index 68a8a5c..b607870 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/try_flag.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/try_flag.py
@@ -47,29 +47,41 @@ self._path_finder = PathFinder(self._filesystem) self._git = self._host.git() - def _set_flag(self, flag): + def _force_flag_for_test_runner(self): + flag = self._args.flag path = self._path_finder.path_from_layout_tests(FLAG_FILE) self._filesystem.write_text_file(path, flag + '\n') self._git.add_list([path]) self._git.commit_locally_with_message( 'Flag try job: force %s for run-webkit-tests.' % flag) - def _clear_expectations(self, flag): - path = self._path_finder.path_from_layout_tests( - 'FlagExpectations', flag.lstrip('-')) + def _flag_expectations_path(self): + return self._path_finder.path_from_layout_tests( + 'FlagExpectations', self._args.flag.lstrip('-')) + + def _clear_expectations(self): + path = self._flag_expectations_path() self._filesystem.write_text_file(path, '') self._git.add_list([path]) self._git.commit_locally_with_message( - 'Flag try job: clear expectations for %s.' % flag) + 'Flag try job: clear expectations for %s.' % self._args.flag) + + def _tests_in_flag_expectations(self): + result = set() + path = self._flag_expectations_path() + for line in self._filesystem.read_text_file(path).split('\n'): + expectation_line = TestExpectationLine.tokenize_line(path, line, 0) + test_name = expectation_line.name + if test_name: + result.add(test_name) + return result def trigger(self): - flag = self._args.flag - if flag: - self._set_flag(flag) - if self._args.regenerate: - self._clear_expectations(flag) - self._git_cl.run(['upload', '--bypass-hooks', '-f', - '-m', 'Flag try job for %s.' % flag]) + self._force_flag_for_test_runner() + if self._args.regenerate: + self._clear_expectations() + self._git_cl.run(['upload', '--bypass-hooks', '-f', + '-m', 'Flag try job for %s.' % self._args.flag]) for builder in sorted(BUILDER_MASTERS.keys()): master = BUILDER_MASTERS[builder] self._git_cl.trigger_try_jobs([builder], master) @@ -106,7 +118,7 @@ # TODO: Get jobs from the _tryflag branch. Current branch for now. jobs = self._git_cl.latest_try_jobs(BUILDER_CONFIGS.keys()) buildbot = self._host.buildbot - for build in sorted(jobs.keys()): + for build in sorted(jobs): self._host.print_('-- %s: %s/results.html' % ( BUILDER_CONFIGS[build.builder_name].version, buildbot.results_url(build.builder_name, build.build_number))) @@ -117,11 +129,14 @@ # TODO: Write to flag expectations file. For now, stdout. :) unexpected_failures = [] unexpected_passes = [] + tests_in_flag_expectations = self._tests_in_flag_expectations() for line in self._expectations_model.all_lines(): - if TestExpectations.EXPECTATIONS['pass'] in line.parsed_expectations: - unexpected_passes.append(line) - else: + is_pass = (TestExpectations.EXPECTATIONS['pass'] in + line.parsed_expectations) + if not is_pass: unexpected_failures.append(line) + elif line.name in tests_in_flag_expectations: + unexpected_passes.append(line) self._print_all(unexpected_passes, 'unexpected passes') self._print_all(unexpected_failures, 'unexpected failures') @@ -150,7 +165,7 @@ formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('action', help='"trigger" or "update"') parser.add_argument('--bug', help='crbug number for expectation lines') - parser.add_argument('--flag', + parser.add_argument('--flag', required=True, help='flag to force-enable in run-webkit-tests') parser.add_argument('--regenerate', action='store_true', help='clear the flag expectations before triggering')
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/try_flag_unittest.py b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/try_flag_unittest.py index 0c3dfdda..89a14d23 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/try_flag_unittest.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/try_flag_unittest.py
@@ -19,6 +19,11 @@ self.linux_build = Build('linux_chromium_rel_ng', 100) self.mac_build = Build('mac_chromium_rel_ng', 101) self.win_build = Build('win7_chromium_rel_ng', 102) + self.mock_try_results = { + self.linux_build: TryJobStatus('COMPLETED', 'SUCCESS'), + self.win_build: TryJobStatus('COMPLETED', 'SUCCESS'), + self.mac_build: TryJobStatus('COMPLETED', 'SUCCESS') + } super(TryFlagTest, self).__init__(*args, **kwargs) def _run_trigger_test(self, regenerate): @@ -115,13 +120,18 @@ def test_update(self): host = MockHost() - try_jobs = { - self.linux_build: TryJobStatus('COMPLETED', 'SUCCESS'), - self.win_build: TryJobStatus('COMPLETED', 'SUCCESS'), - self.mac_build: TryJobStatus('COMPLETED', 'SUCCESS') - } + filesystem = host.filesystem + finder = PathFinder(filesystem) + + flag_expectations_file = finder.path_from_layout_tests( + 'FlagExpectations', 'foo') + filesystem.write_text_file( + flag_expectations_file, + 'something/pass-unexpectedly-mac.html [ Fail ]') + self._setup_mock_results(host.buildbot) - TryFlag(['update'], host, MockGitCL(host, try_jobs)).run() + cmd = ['update', '--flag=--foo'] + TryFlag(cmd, host, MockGitCL(host, self.mock_try_results)).run() def results_url(build): return '%s/%s/%s/layout-test-results/results.html' % ( @@ -146,8 +156,24 @@ '' ])) + def test_update_irrelevant_unexpected_pass(self): + host = MockHost() + filesystem = host.filesystem + finder = PathFinder(filesystem) + flag_expectations_file = finder.path_from_layout_tests( + 'FlagExpectations', 'foo') + self._setup_mock_results(host.buildbot) + cmd = ['update', '--flag=--foo'] + + # Unexpected passes that don't have flag-specific failure expectations + # should not be reported. + filesystem.write_text_file(flag_expectations_file, '') + TryFlag(cmd, host, MockGitCL(host, self.mock_try_results)).run() + self.assertTrue('### 0 unexpected passes' in host.stdout.getvalue()) + def test_invalid_action(self): host = MockHost() - TryFlag(['invalid'], host, MockGitCL(host)).run() + cmd = ['invalid', '--flag=--foo'] + TryFlag(cmd, host, MockGitCL(host)).run() self.assertEqual(host.stderr.getvalue(), 'specify "trigger" or "update"\n')
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/local_wpt.py b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/local_wpt.py index 7127cb5fa..bd6907e 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/local_wpt.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/local_wpt.py
@@ -32,7 +32,7 @@ if self.host.filesystem.exists(self.path): _log.info('WPT checkout exists at %s, fetching latest', self.path) self.run(['git', 'fetch', 'origin']) - self.run(['git', 'checkout', 'origin/master']) + self.run(['git', 'reset', '--hard', 'origin/master']) return _log.info('Cloning GitHub w3c/web-platform-tests into %s', self.path)
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/local_wpt_unittest.py b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/local_wpt_unittest.py index ba9fd54..159b6f7f 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/local_wpt_unittest.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/local_wpt_unittest.py
@@ -24,7 +24,7 @@ self.assertEqual(host.executive.calls, [ ['git', 'fetch', 'origin'], - ['git', 'checkout', 'origin/master'], + ['git', 'reset', '--hard', 'origin/master'], ]) def test_fetch_when_wpt_dir_does_not_exist(self):
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/test_importer.py b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/test_importer.py index 25f8022d..173235c 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/test_importer.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/test_importer.py
@@ -45,15 +45,27 @@ def __init__(self, host, wpt_github=None): self.host = host + self.wpt_github = wpt_github + self.executive = host.executive self.fs = host.filesystem self.finder = PathFinder(self.fs) - self.verbose = False - self.git_cl = None - self.wpt_github = wpt_github + self.chromium_git = self.host.git(self.finder.chromium_base()) self.dest_path = self.finder.path_from_layout_tests('external', 'wpt') + # A common.net.git_cl.GitCL instance. + self.git_cl = None + # Another Git instance with local WPT as CWD, which can only be + # instantiated after the working directory is created. + self.wpt_git = None + # The WPT revision we are importing. + self.wpt_revision = None + self.verbose = False + def main(self, argv=None): + # TODO(robertma): Test this method! Split it to make it easier to test + # if necessary. + options = self.parse_args(argv) self.verbose = options.verbose @@ -70,36 +82,36 @@ gh_user = credentials.get('GH_USER') gh_token = credentials.get('GH_TOKEN') self.wpt_github = self.wpt_github or WPTGitHub(self.host, gh_user, gh_token) - local_wpt = LocalWPT(self.host, gh_token=gh_token) self.git_cl = GitCL(self.host, auth_refresh_token_json=options.auth_refresh_token_json) - _log.debug('Noting the current Chromium commit.') - # TODO(qyearsley): Use Git (self.host.git) to run git commands. - _, show_ref_output = self.run(['git', 'show-ref', '--verify', '--head', '--hash', 'HEAD']) - chromium_commit = show_ref_output.strip() + _log.debug('Noting the current Chromium revision.') + chromium_revision = self.chromium_git.latest_git_commit() + # Instantiate Git after local_wpt.fetch() to make sure the path exists. + local_wpt = LocalWPT(self.host, gh_token=gh_token) local_wpt.fetch() + self.wpt_git = self.host.git(local_wpt.path) if options.revision is not None: _log.info('Checking out %s', options.revision) - self.run(['git', 'checkout', options.revision], cwd=local_wpt.path) + self.wpt_git.run(['checkout', options.revision]) _log.debug('Noting the revision we are importing.') - _, show_ref_output = self.run(['git', 'show-ref', 'origin/master'], cwd=local_wpt.path) - import_commit = 'wpt@%s' % show_ref_output.split()[0] + self.wpt_revision = self.wpt_git.latest_git_commit() + import_commit = 'wpt@%s' % self.wpt_revision - _log.info('Importing %s to Chromium %s', import_commit, chromium_commit) + _log.info('Importing %s to Chromium %s', import_commit, chromium_revision) - commit_message = self._commit_message(chromium_commit, import_commit) - - if not options.ignore_exportable_commits: + if options.ignore_exportable_commits: + commit_message = self._commit_message(chromium_revision, import_commit) + else: commits = self.apply_exportable_commits_locally(local_wpt) if commits is None: _log.error('Could not apply some exportable commits cleanly.') _log.error('Aborting import to prevent clobbering commits.') return 1 commit_message = self._commit_message( - chromium_commit, import_commit, locally_applied_commits=commits) + chromium_revision, import_commit, locally_applied_commits=commits) self._clear_out_dest_path() @@ -107,7 +119,8 @@ test_copier = TestCopier(self.host, local_wpt.path) test_copier.do_import() - self.run(['git', 'add', '--all', 'external/wpt']) + # TODO(robertma): Implement `add --all` in Git (it is different from `commit --all`). + self.chromium_git.run(['add', '--all', self.dest_path]) self._generate_manifest() @@ -120,8 +133,7 @@ _log.info('Updating TestExpectations for any removed or renamed tests.') self.update_all_test_expectations_files(self._list_deleted_tests(), self._list_renamed_tests()) - has_changes = self._has_changes() - if not has_changes: + if not self.chromium_git.has_working_directory_changes(): _log.info('Done: no changes to import.') return 0 @@ -177,10 +189,10 @@ if try_results and self.git_cl.some_failed(try_results): self.fetch_new_expectations_and_baselines() - if self.host.git().has_working_directory_changes(): + if self.chromium_git.has_working_directory_changes(): self._generate_manifest() message = 'Update test expectations and baselines.' - self.check_run(['git', 'commit', '-a', '-m', message]) + self._commit_changes(message) self._upload_patchset(message) return True @@ -259,13 +271,11 @@ return parser.parse_args(argv) def checkout_is_okay(self): - git_diff_retcode, _ = self.run( - ['git', 'diff', '--quiet', 'HEAD'], exit_on_failure=False) - if git_diff_retcode: + if self.chromium_git.has_working_directory_changes(): _log.warning('Checkout is dirty; aborting.') return False - _, local_commits = self.run( - ['git', 'log', '--oneline', 'origin/master..HEAD']) + # TODO(robertma): Add a method in Git to query a range of commits. + local_commits = self.chromium_git.run(['log', '--oneline', 'origin/master..HEAD']) if local_commits: _log.warning('Checkout has local commits before import.') return True @@ -304,10 +314,7 @@ _log.error('Commit cannot be applied cleanly:') _log.error(error) return None - self.run( - ['git', 'commit', '--all', '-F', '-'], - stdin='Applying patch %s' % commit.sha, - cwd=local_wpt.path) + self.wpt_git.commit_locally_with_message('Applying patch %s' % commit.sha) return commits def exportable_but_not_exported_commits(self, local_wpt): @@ -336,7 +343,7 @@ manifest_base_path = self.fs.normpath( self.fs.join(self.dest_path, '..', 'WPT_BASE_MANIFEST.json')) self.copyfile(manifest_path, manifest_base_path) - self.run(['git', 'add', manifest_base_path]) + self.chromium_git.add_list([manifest_base_path]) def _clear_out_dest_path(self): """Removes all files that are synced with upstream from Chromium WPT. @@ -353,14 +360,10 @@ def _commit_changes(self, commit_message): _log.info('Committing changes.') - self.run(['git', 'commit', '--all', '-F', '-'], stdin=commit_message) - - def _has_changes(self): - return_code, _ = self.run(['git', 'diff', '--quiet', 'HEAD'], exit_on_failure=False) - return return_code == 1 + self.chromium_git.commit_locally_with_message(commit_message) def _only_wpt_manifest_changed(self): - changed_files = self.host.git().changed_files() + changed_files = self.chromium_git.changed_files() wpt_base_manifest = self.fs.relpath( self.fs.join(self.dest_path, '..', 'WPT_BASE_MANIFEST.json'), self.finder.chromium_base()) @@ -408,30 +411,6 @@ base = '/' + rel_path.replace('-expected.txt', '') return any((base + ext) in wpt_urls for ext in Port.supported_file_extensions) - def run(self, cmd, exit_on_failure=True, cwd=None, stdin=''): - _log.debug('Running command: %s', ' '.join(cmd)) - - cwd = cwd or self.finder.path_from_layout_tests() - proc = self.executive.popen(cmd, stdout=self.executive.PIPE, stderr=self.executive.PIPE, stdin=self.executive.PIPE, cwd=cwd) - out, err = proc.communicate(stdin) - if proc.returncode or self.verbose: - _log.info('# ret> %d', proc.returncode) - if out: - for line in out.splitlines(): - _log.info('# out> %s', line) - if err: - for line in err.splitlines(): - _log.info('# err> %s', line) - if exit_on_failure and proc.returncode: - self.host.exit(proc.returncode) - return proc.returncode, out - - def check_run(self, command): - return_code, out = self.run(command) - if return_code: - raise Exception('%s failed with exit code %d.' % ' '.join(command), return_code) - return out - def copyfile(self, source, destination): _log.debug('cp %s %s', source, destination) self.fs.copyfile(source, destination) @@ -469,7 +448,7 @@ def get_directory_owners(self): """Returns a mapping of email addresses to owners of changed tests.""" _log.info('Gathering directory owners emails to CC.') - changed_files = self.host.git().changed_files() + changed_files = self.chromium_git.changed_files() extractor = DirectoryOwnersExtractor(self.fs) return extractor.list_owners(changed_files) @@ -479,7 +458,8 @@ Args: directory_owners: A dict of tuples of owner names to lists of directories. """ - description = self.check_run(['git', 'log', '-1', '--format=%B']) + # TODO(robertma): Add a method in Git for getting the commit body. + description = self.chromium_git.run(['log', '-1', '--format=%B']) build_link = current_build_link(self.host) if build_link: description += 'Build: %s\n\n' % build_link @@ -586,7 +566,8 @@ def _list_deleted_tests(self): """List of layout tests that have been deleted.""" - out = self.check_run(['git', 'diff', 'origin/master', '-M100%', '--diff-filter=D', '--name-only']) + # TODO(robertma): Improve Git.changed_files so that we can use it here. + out = self.chromium_git.run(['diff', 'origin/master', '-M100%', '--diff-filter=D', '--name-only']) deleted_tests = [] for path in out.splitlines(): test = self._relative_to_layout_test_dir(path) @@ -599,7 +580,7 @@ Returns a dict mapping source name to destination name. """ - out = self.check_run(['git', 'diff', 'origin/master', '-M100%', '--diff-filter=R', '--name-status']) + out = self.chromium_git.run(['diff', 'origin/master', '-M100%', '--diff-filter=R', '--name-status']) renamed_tests = {} for line in out.splitlines(): _, source_path, dest_path = line.split()
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/test_importer_unittest.py b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/test_importer_unittest.py index 140e173f..723f19b 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/test_importer_unittest.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/test_importer_unittest.py
@@ -222,6 +222,7 @@ # TODO(robertma): Consider using MockLocalWPT. host = MockHost() importer = TestImporter(host, wpt_github=MockWPTGitHub(pull_requests=[])) + importer.wpt_git = MockGit(cwd='/tmp/wpt', executive=host.executive) fake_commit = MockChromiumCommit( host, subject='My fake commit', patch=( @@ -233,6 +234,8 @@ importer.exportable_but_not_exported_commits = lambda _: [fake_commit] applied = importer.apply_exportable_commits_locally(LocalWPT(host)) self.assertEqual(applied, [fake_commit]) + # This assertion is implementation details of LocalWPT.apply_patch. + # TODO(robertma): Move this to local_wpt_unittest.py. self.assertEqual(host.executive.full_calls, [ MockCall( ['git', 'apply', '-'], @@ -248,11 +251,10 @@ }), MockCall( ['git', 'add', '.'], - kwargs={'input': None, 'cwd': '/tmp/wpt', 'env': None}), - MockCall( - ['git', 'commit', '--all', '-F', '-'], - kwargs={'cwd': '/tmp/wpt', 'env': None}) + kwargs={'input': None, 'cwd': '/tmp/wpt', 'env': None}) ]) + self.assertEqual(importer.wpt_git.local_commits(), + [['Applying patch 14fd77e88e42147c57935c49d9e3b2412b8491b7']]) def test_apply_exportable_commits_locally_returns_none_on_failure(self): host = MockHost() @@ -290,10 +292,8 @@ host.filesystem.write_text_file('/mock-checkout/third_party/WebKit/LayoutTests/W3CImportExpectations', '') host.filesystem.write_text_file('/mock-checkout/third_party/WebKit/LayoutTests/external/wpt/foo/OWNERS', 'someone@chromium.org\n') - git = MockGit(filesystem=host.filesystem, executive=host.executive, platform=host.platform) - git.changed_files = lambda: ['third_party/WebKit/LayoutTests/external/wpt/foo/x.html'] - host.git = lambda: git importer = TestImporter(host) + importer.chromium_git.changed_files = lambda: ['third_party/WebKit/LayoutTests/external/wpt/foo/x.html'] self.assertEqual(importer.get_directory_owners(), {('someone@chromium.org',): ['external/wpt/foo']}) def test_get_directory_owners_no_changed_files(self): @@ -309,11 +309,8 @@ def test_commit_changes(self): host = MockHost() importer = TestImporter(host) - importer._has_changes = lambda: True importer._commit_changes('dummy message') - self.assertEqual( - host.executive.calls, - [['git', 'commit', '--all', '-F', '-']]) + self.assertEqual(importer.chromium_git.local_commits(), [['dummy message']]) def test_commit_message(self): importer = TestImporter(MockHost()) @@ -472,23 +469,21 @@ '--work', '--tests-root', blink_path + '/LayoutTests/external/wpt', - ], - [ - 'git', - 'add', - blink_path + '/LayoutTests/external/WPT_BASE_MANIFEST.json', ] ]) + self.assertEqual(importer.chromium_git.added_paths, + {blink_path + '/LayoutTests/external/WPT_BASE_MANIFEST.json'}) def test_only_wpt_manifest_changed(self): host = MockHost() - git = host.git() - git.changed_files = lambda: ['third_party/WebKit/LayoutTests/external/WPT_BASE_MANIFEST.json', - 'third_party/WebKit/LayoutTests/external/wpt/foo/x.html'] importer = TestImporter(host) + importer.chromium_git.changed_files = lambda: [ + 'third_party/WebKit/LayoutTests/external/WPT_BASE_MANIFEST.json', + 'third_party/WebKit/LayoutTests/external/wpt/foo/x.html'] self.assertFalse(importer._only_wpt_manifest_changed()) - git.changed_files = lambda: ['third_party/WebKit/LayoutTests/external/WPT_BASE_MANIFEST.json'] + importer.chromium_git.changed_files = lambda: [ + 'third_party/WebKit/LayoutTests/external/WPT_BASE_MANIFEST.json'] self.assertTrue(importer._only_wpt_manifest_changed()) def test_delete_orphaned_baselines_basic(self):
diff --git a/third_party/WebKit/common/BUILD.gn b/third_party/WebKit/common/BUILD.gn index f4a177ba..09ceb82 100644 --- a/third_party/WebKit/common/BUILD.gn +++ b/third_party/WebKit/common/BUILD.gn
@@ -22,6 +22,8 @@ defines = [ "BLINK_COMMON_IMPLEMENTATION=1" ] sources = [ + "associated_interfaces/associated_interface_provider.h", + "associated_interfaces/associated_interface_registry.h", "client_hints/client_hints.cc", "client_hints/client_hints.h", "common_export.h", @@ -100,9 +102,9 @@ sources = [ "blob/blob.mojom", "blob/blob_registry.mojom", - "blob/size_getter.mojom", "page/page_visibility_state.mojom", "service_worker/service_worker_client.mojom", + "service_worker/service_worker_provider_type.mojom", ] public_deps = [
diff --git a/third_party/WebKit/common/associated_interfaces/associated_interface_provider.h b/third_party/WebKit/common/associated_interfaces/associated_interface_provider.h new file mode 100644 index 0000000..8ca9581 --- /dev/null +++ b/third_party/WebKit/common/associated_interfaces/associated_interface_provider.h
@@ -0,0 +1,53 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_WEBKIT_COMMON_ASSOCIATED_INTERFACES_ASSOCIATED_INTERFACE_PROVIDER_H_ +#define THIRD_PARTY_WEBKIT_COMMON_ASSOCIATED_INTERFACES_ASSOCIATED_INTERFACE_PROVIDER_H_ + +#include <string> + +#include "mojo/public/cpp/bindings/associated_interface_ptr.h" +#include "mojo/public/cpp/bindings/associated_interface_request.h" +#include "mojo/public/cpp/bindings/scoped_interface_endpoint_handle.h" + +namespace blink { + +// A helper interface for connecting to remote Channel-associated interfaces. +// +// This is analogous to service_manager::InterfaceProvider in that it provides a +// means of +// binding proxies to remote interfaces, but this is specifically for interfaces +// which must be associated with an IPC::Channel, i.e. retain FIFO message +// ordering with respect to legacy IPC messages. +// +// The Channel with which the remote interfaces are associated depends on +// the configuration of the specific AssociatedInterfaceProvider instance. For +// example, RenderFrameHost exposes an instance of this class for which all +// interfaces are associated with the IPC::ChannelProxy to the render process +// which hosts its corresponding RenderFrame. +class AssociatedInterfaceProvider { + public: + virtual ~AssociatedInterfaceProvider() {} + + // Passes an associated endpoint handle to the remote end to be bound to a + // Channel-associated interface named |name|. + virtual void GetInterface(const std::string& name, + mojo::ScopedInterfaceEndpointHandle handle) = 0; + + // Templated helper for GetInterface(). + template <typename Interface> + void GetInterface(mojo::AssociatedInterfacePtr<Interface>* proxy) { + auto request = mojo::MakeRequest(proxy); + GetInterface(Interface::Name_, request.PassHandle()); + } + + virtual void OverrideBinderForTesting( + const std::string& name, + const base::Callback<void(mojo::ScopedInterfaceEndpointHandle)>& + binder) = 0; +}; + +} // namespace blink + +#endif // THIRD_PARTY_WEBKIT_COMMON_ASSOCIATED_INTERFACES_ASSOCIATED_INTERFACE_PROVIDER_H_
diff --git a/third_party/WebKit/common/associated_interfaces/associated_interface_registry.h b/third_party/WebKit/common/associated_interfaces/associated_interface_registry.h new file mode 100644 index 0000000..7ea930f --- /dev/null +++ b/third_party/WebKit/common/associated_interfaces/associated_interface_registry.h
@@ -0,0 +1,62 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_WEBKIT_COMMON_ASSOCIATED_INTERFACES_ASSOCIATED_INTERFACE_REGISTRY_H_ +#define THIRD_PARTY_WEBKIT_COMMON_ASSOCIATED_INTERFACES_ASSOCIATED_INTERFACE_REGISTRY_H_ + +#include <string> + +#include "base/bind.h" +#include "base/callback.h" +#include "mojo/public/cpp/bindings/associated_interface_request.h" +#include "mojo/public/cpp/bindings/scoped_interface_endpoint_handle.h" + +namespace blink { + +// An AssociatedInterfaceRegistry is a collection of associated interface- +// binding callbacks mapped by interface name. +// +// This is used to register binding callbacks for interfaces which must be +// associated with some IPC::ChannelProxy, meaning that messages on the +// interface retain FIFO with respect to legacy Chrome IPC messages sent or +// dispatched on the channel. +// +// The channel with which a registered interface is associated depends on the +// configuration of the specific AssociatedInterfaceRegistry instance. For +// example, RenderFrame exposes an instance of this class for which all +// interfaces are associated with the IPC::SyncChannel to the browser. +class AssociatedInterfaceRegistry { + public: + using Binder = base::Callback<void(mojo::ScopedInterfaceEndpointHandle)>; + + virtual ~AssociatedInterfaceRegistry() {} + + // Adds an interface binder to the registry. + virtual void AddInterface(const std::string& name, const Binder& binder) = 0; + + // Removes an interface binder from the registry. + virtual void RemoveInterface(const std::string& name) = 0; + + template <typename Interface> + using InterfaceBinder = + base::Callback<void(mojo::AssociatedInterfaceRequest<Interface>)>; + + // Templated helper for AddInterface() above. + template <typename Interface> + void AddInterface(const InterfaceBinder<Interface>& binder) { + AddInterface(Interface::Name_, + base::Bind(&BindInterface<Interface>, binder)); + } + + private: + template <typename Interface> + static void BindInterface(const InterfaceBinder<Interface>& binder, + mojo::ScopedInterfaceEndpointHandle handle) { + binder.Run(mojo::AssociatedInterfaceRequest<Interface>(std::move(handle))); + } +}; + +} // namespace blink + +#endif // THIRD_PARTY_WEBKIT_COMMON_ASSOCIATED_INTERFACES_ASSOCIATED_INTERFACE_REGISTRY_H_
diff --git a/third_party/WebKit/common/blob/size_getter.mojom b/third_party/WebKit/common/blob/size_getter.mojom deleted file mode 100644 index 121c459..0000000 --- a/third_party/WebKit/common/blob/size_getter.mojom +++ /dev/null
@@ -1,12 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -module blink.mojom; - -// An interface for getting the size of another type (could be a data pipe as -// one example). -interface SizeGetter { - // Returns the size of the data. - GetSize() => (uint64 size); -};
diff --git a/third_party/WebKit/common/service_worker/service_worker_provider_type.mojom b/third_party/WebKit/common/service_worker/service_worker_provider_type.mojom new file mode 100644 index 0000000..2ea7c067 --- /dev/null +++ b/third_party/WebKit/common/service_worker/service_worker_provider_type.mojom
@@ -0,0 +1,21 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +module blink.mojom; + +// Identifies the type of a service worker provider. +// +// A service worker provider attaches to a service worker client or a service +// worker itself and "provides" it with functionality related to service +// workers. See the main documentation in content::ServiceWorkerProviderContext. +enum ServiceWorkerProviderType { + kUnknown, + + // For service worker clients. + kForWindow, + kForSharedWorker, + + // For service workers. + kForServiceWorker, +};
diff --git a/third_party/WebKit/public/platform/WebURLRequest.h b/third_party/WebKit/public/platform/WebURLRequest.h index 59cf284..ae8daea 100644 --- a/third_party/WebKit/public/platform/WebURLRequest.h +++ b/third_party/WebKit/public/platform/WebURLRequest.h
@@ -153,16 +153,11 @@ kPreviewsStateLast = kPreviewsOff }; - // Indicates which service workers will receive fetch events for this request. + // Indicates whether service workers will receive fetch events for this + // request. Same as ServiceWorkerMode in + // content/public/common/service_worker_modes.h. enum class ServiceWorkerMode : uint8_t { - // Relevant local and foreign service workers will get a fetch or - // foreignfetch event for this request. kAll, - // Only relevant foreign service workers will get a foreignfetch event for - // this request. - kForeign, - // Neither local nor foreign service workers will get events for this - // request. kNone }; @@ -256,10 +251,12 @@ BLINK_PLATFORM_EXPORT int RequestorID() const; BLINK_PLATFORM_EXPORT void SetRequestorID(int); - // A consumer controlled value intended to be used to identify the - // process of the requestor. - BLINK_PLATFORM_EXPORT int RequestorProcessID() const; - BLINK_PLATFORM_EXPORT void SetRequestorProcessID(int); + // The unique child id (not PID) of the process from which this request + // originated. In the case of out-of-process plugins, this allows to link back + // the request to the plugin process (as it is processed through a render view + // process). + BLINK_PLATFORM_EXPORT int GetPluginChildID() const; + BLINK_PLATFORM_EXPORT void SetPluginChildID(int); // Allows the request to be matched up with its app cache host. BLINK_PLATFORM_EXPORT int AppCacheHostID() const;
diff --git a/third_party/WebKit/public/platform/WebURLResponse.h b/third_party/WebKit/public/platform/WebURLResponse.h index 349b09c..93628af16 100644 --- a/third_party/WebKit/public/platform/WebURLResponse.h +++ b/third_party/WebKit/public/platform/WebURLResponse.h
@@ -219,9 +219,6 @@ BLINK_PLATFORM_EXPORT bool WasFetchedViaServiceWorker() const; BLINK_PLATFORM_EXPORT void SetWasFetchedViaServiceWorker(bool); - // Flag whether this request was loaded using a foreign fetch service worker. - BLINK_PLATFORM_EXPORT void SetWasFetchedViaForeignFetch(bool); - // Flag whether the fallback request with skip service worker flag was // required. See ServiceWorkerResponseInfo::was_fallback_required() for // details.
diff --git a/third_party/WebKit/public/platform/modules/background_fetch/background_fetch.mojom b/third_party/WebKit/public/platform/modules/background_fetch/background_fetch.mojom index 76a65683..dccc100 100644 --- a/third_party/WebKit/public/platform/modules/background_fetch/background_fetch.mojom +++ b/third_party/WebKit/public/platform/modules/background_fetch/background_fetch.mojom
@@ -49,7 +49,6 @@ uint64 uploaded; uint64 download_total; uint64 downloaded; - string title; }; interface BackgroundFetchRegistrationObserver {
diff --git a/third_party/WebKit/public/platform/modules/fetch/fetch_api_request.mojom b/third_party/WebKit/public/platform/modules/fetch/fetch_api_request.mojom index ecd40b7b..400e216 100644 --- a/third_party/WebKit/public/platform/modules/fetch/fetch_api_request.mojom +++ b/third_party/WebKit/public/platform/modules/fetch/fetch_api_request.mojom
@@ -101,10 +101,10 @@ MANUAL, }; -// Whether this is a regular fetch, or a foreign fetch request. +// Whether this is a regular fetch, or a foreign fetch request (now removed). +// TODO(falken): Remove this since it's always FETCH. enum ServiceWorkerFetchType { FETCH, - FOREIGN_FETCH, }; struct FetchAPIRequest {
diff --git a/third_party/WebKit/public/platform/modules/notifications/notification_service.mojom b/third_party/WebKit/public/platform/modules/notifications/notification_service.mojom index b9c5d3e..556d315 100644 --- a/third_party/WebKit/public/platform/modules/notifications/notification_service.mojom +++ b/third_party/WebKit/public/platform/modules/notifications/notification_service.mojom
@@ -9,7 +9,8 @@ // Service through which Blink can request notifications to be shown, closed or // retrieved from the embedder. interface NotificationService { - // Synchronously retrieves the permission status for |origin|. Required to - // be synchronous due to the Notification.permission JavaScript getter. - [Sync] GetPermissionStatus(string origin) => (PermissionStatus status); + // Synchronously retrieves the permission status for the origin associated + // with the interface connection. Required to be synchronous due to the + // Notification.permission JavaScript getter. + [Sync] GetPermissionStatus() => (PermissionStatus status); };
diff --git a/third_party/WebKit/public/platform/modules/serviceworker/service_worker_error_type.mojom b/third_party/WebKit/public/platform/modules/serviceworker/service_worker_error_type.mojom index 4adc777c..aa16afc 100644 --- a/third_party/WebKit/public/platform/modules/serviceworker/service_worker_error_type.mojom +++ b/third_party/WebKit/public/platform/modules/serviceworker/service_worker_error_type.mojom
@@ -42,9 +42,9 @@ kResponseTypeOpaqueForClientRequest = 8, kResponseTypeOpaqueRedirect = 9, kBodyLocked = 10, - kNoForeignFetchResponse = 11, - kForeignFetchHeadersWithoutOrigin = 12, - kForeignFetchMismatchedOrigin = 13, + // kNoForeignFetchResponse = 11, // obsolete + // kForeignFetchHeadersWithoutOrigin = 12, // obsolete + // kForeignFetchMismatchedOrigin = 13, // obsolete kRedirectedResponseForNotFollowRequest = 14, kDataPipeCreationFailed = 15, // Add a new type here, then update kLast and enums.xml.
diff --git a/third_party/WebKit/public/platform/modules/webauth/authenticator.mojom b/third_party/WebKit/public/platform/modules/webauth/authenticator.mojom index e289823..3cc5787 100644 --- a/third_party/WebKit/public/platform/modules/webauth/authenticator.mojom +++ b/third_party/WebKit/public/platform/modules/webauth/authenticator.mojom
@@ -52,27 +52,35 @@ array<uint8> signature; }; -// Information about the relying party and the account held by the user at -// that relying party. This information is used by the authenticator to create -// or retrieve an appropriate public key credential for this account. -// These fields take arbitrary input. -struct PublicKeyCredentialEntity { - // A unique identifier for the entity. An ASCII serialization of an origin - // for a relying party, and an arbitrary string specified by the relying party - // for user accounts. +// Information about the relying party. These fields take arbitrary input. +struct PublicKeyCredentialRpEntity { + // An ASCII serialization of an origin. string? id; - // Friendly name associated with the entity intended for display. - // e.g. "Acme Corporation" for a relying party and "john.p.smith@example.com" - // or "+14255551234" for a user. + // Friendly name associated with the relying party intended for display. + // e.g. "Acme Corporation". string name; - // Image associated with the entity. - // For example, this could be a user’s avatar or a relying party's logo. + // Image associated with the entity. e.g. a relying party's logo. + url.mojom.Url? icon; +}; + +// Informatiom about the account held by the user. These fields take +// arbitrary input. +struct PublicKeyCredentialUserEntity { + // Unique identifier for a user account An opaque byte sequence with a + // maximum size of 64 bytes. + array<uint8> id; + + // Friendly name associated with the entity intended for display. + // e.g."john.p.smith@example.com" or "+14255551234" for a user. + string name; + + // Image associated with the entity. For example, a user’s avatar. url.mojom.Url? icon; // Contains a friendly name for the user account (e.g., "John P. Smith"). - string? display_name; + string display_name; }; // Parameters that are used to generate an appropriate public key credential. @@ -82,18 +90,17 @@ }; // Parameters passed into calls to MakeCredential. -struct MakeCredentialOptions { - // Relying party information. - // Corresponds to |rp| in MakeCredentialOptions.idl. - PublicKeyCredentialEntity relying_party; - - // Information about the user. - PublicKeyCredentialEntity user; +struct MakePublicKeyCredentialOptions { + // Information about the relying party and user entities, respectively. + // Used by the authenticator to create or retrieve an appropriate public key + // credential for the requested account. + PublicKeyCredentialRpEntity relying_party; + PublicKeyCredentialUserEntity user; // A blob passed from the the relying party server. array<uint8> challenge; - array<PublicKeyCredentialParameters> crypto_parameters; + array<PublicKeyCredentialParameters> public_key_parameters; mojo.common.mojom.TimeDelta adjusted_timeout; @@ -128,8 +135,8 @@ // Interface to direct authenticators to create or use a public key credential. interface Authenticator { // Gets the credential info for a new public key credential created by an - // authenticator for the given |MakeCredentialOptions| + // authenticator for the given |MakePublicKeyCredentialOptions| // [PublicKeyCredentialInfo] will only be set if status == SUCCESS. - MakeCredential(MakeCredentialOptions options) + MakeCredential(MakePublicKeyCredentialOptions options) => (AuthenticatorStatus status, PublicKeyCredentialInfo? credential); };
diff --git a/third_party/WebKit/public/platform/web_feature.mojom b/third_party/WebKit/public/platform/web_feature.mojom index aa92c65..95d2ec3 100644 --- a/third_party/WebKit/public/platform/web_feature.mojom +++ b/third_party/WebKit/public/platform/web_feature.mojom
@@ -1089,7 +1089,7 @@ kSVGSMILPausing = 1506, kSVGSMILCurrentTime = 1507, kHTMLBodyElementOnSelectionChangeAttribute = 1508, - kForeignFetchInterception = 1509, + kForeignFetchInterception = 1509, // Obsolete. kUsbGetDevices = 1519, kUsbRequestDevice = 1520, kUsbDeviceOpen = 1521,
diff --git a/third_party/WebKit/public/web/WebAXObject.h b/third_party/WebKit/public/web/WebAXObject.h index d32762f..8fb38e46 100644 --- a/third_party/WebKit/public/web/WebAXObject.h +++ b/third_party/WebKit/public/web/WebAXObject.h
@@ -345,9 +345,12 @@ // not null, walk up to its container and offset by the container's offset // from origin, the container's scroll position if any, and apply the // container's transform. Do this until you reach the root of the tree. + // If the container clips its children, for example with overflow:hidden + // or similar, set |clips_children| to true. BLINK_EXPORT void GetRelativeBounds(WebAXObject& offset_container, WebFloatRect& bounds_in_container, - SkMatrix44& container_transform) const; + SkMatrix44& container_transform, + bool* clips_children = nullptr) const; #if INSIDE_BLINK BLINK_EXPORT WebAXObject(AXObject*);
diff --git a/third_party/WebKit/public/web/WebFrameClient.h b/third_party/WebKit/public/web/WebFrameClient.h index 8e86e43..979921b 100644 --- a/third_party/WebKit/public/web/WebFrameClient.h +++ b/third_party/WebKit/public/web/WebFrameClient.h
@@ -85,6 +85,7 @@ } // namespace mojom enum class WebTreeScopeType; +class AssociatedInterfaceProvider; class WebApplicationCacheHost; class WebApplicationCacheHostClient; class WebColorChooser; @@ -198,6 +199,14 @@ // the browser. This method may not return nullptr. virtual service_manager::InterfaceProvider* GetInterfaceProvider(); + // Returns an AssociatedInterfaceProvider the frame can use to request + // navigation-associated interfaces from the browser. See also + // LocalFrame::GetRemoteNavigationAssociatedInterfaces(). + virtual AssociatedInterfaceProvider* + GetRemoteNavigationAssociatedInterfaces() { + return nullptr; + } + // General notifications ----------------------------------------------- // Indicates if creating a plugin without an associated renderer is supported.
diff --git a/third_party/WebKit/public/web/modules/serviceworker/WebServiceWorkerContextClient.h b/third_party/WebKit/public/web/modules/serviceworker/WebServiceWorkerContextClient.h index 5f5498b..37ceacc 100644 --- a/third_party/WebKit/public/web/modules/serviceworker/WebServiceWorkerContextClient.h +++ b/third_party/WebKit/public/web/modules/serviceworker/WebServiceWorkerContextClient.h
@@ -66,12 +66,6 @@ public: virtual ~WebServiceWorkerContextClient() {} - // Returns the scope of the service worker's registration. Currently - // only used by InstallEvent#registerForeignFetch(). - // TODO(falken): Figure out why registerForeignFetch() can't just use - // self.registration.scope. - virtual WebURL Scope() const { return WebURL(); } - // For Clients#get(id). Requests the embedder to return the specified Client. virtual void GetClient(const WebString& client_id, std::unique_ptr<WebServiceWorkerClientCallbacks>) = 0; @@ -332,13 +326,6 @@ // For Clients#claim(). virtual void Claim( std::unique_ptr<WebServiceWorkerClientsClaimCallbacks>) = 0; - - // Called when the worker wants to register subscopes to handle via foreign - // fetch. Will only be called while an install event is in progress. - virtual void RegisterForeignFetchScopes( - int install_event_id, - const WebVector<WebURL>& sub_scopes, - const WebVector<WebSecurityOrigin>& origins) = 0; }; } // namespace blink
diff --git a/third_party/WebKit/public/web/modules/serviceworker/WebServiceWorkerContextProxy.h b/third_party/WebKit/public/web/modules/serviceworker/WebServiceWorkerContextProxy.h index f608958..26d26b825 100644 --- a/third_party/WebKit/public/web/modules/serviceworker/WebServiceWorkerContextProxy.h +++ b/third_party/WebKit/public/web/modules/serviceworker/WebServiceWorkerContextProxy.h
@@ -95,9 +95,6 @@ virtual void DispatchFetchEvent(int fetch_event_id, const WebServiceWorkerRequest& web_request, bool navigation_preload_sent) = 0; - virtual void DispatchForeignFetchEvent( - int fetch_event_id, - const WebServiceWorkerRequest& web_request) = 0; virtual void DispatchNotificationClickEvent(int event_id, const WebString& notification_id, const WebNotificationData&,
diff --git a/third_party/closure_compiler/externs/networking_private.js b/third_party/closure_compiler/externs/networking_private.js index d4d7b96..2c6609a4 100644 --- a/third_party/closure_compiler/externs/networking_private.js +++ b/third_party/closure_compiler/externs/networking_private.js
@@ -306,6 +306,7 @@ * ServerCAPEMs: (!Array<string>|undefined), * ServerCARefs: (!Array<string>|undefined), * SubjectMatch: (string|undefined), + * TLSVersionMax: (string|undefined), * UseProactiveKeyCaching: (boolean|undefined), * UseSystemCAs: (boolean|undefined) * }} @@ -328,6 +329,7 @@ * ServerCAPEMs: (!chrome.networkingPrivate.ManagedDOMStringList|undefined), * ServerCARefs: (!chrome.networkingPrivate.ManagedDOMStringList|undefined), * SubjectMatch: (!chrome.networkingPrivate.ManagedDOMString|undefined), + * TLSVersionMax: (!chrome.networkingPrivate.ManagedDOMString|undefined), * UseProactiveKeyCaching: (!chrome.networkingPrivate.ManagedBoolean|undefined), * UseSystemCAs: (!chrome.networkingPrivate.ManagedBoolean|undefined) * }}
diff --git a/third_party/crashpad/README.chromium b/third_party/crashpad/README.chromium index 0b822e0..e1f39d0 100644 --- a/third_party/crashpad/README.chromium +++ b/third_party/crashpad/README.chromium
@@ -2,7 +2,7 @@ Short Name: crashpad URL: https://crashpad.chromium.org/ Version: unknown -Revision: e9f40ae176fb15a3a5ed1adb9aa7bd85ad221ce8 +Revision: 2bb56fafe3bd0c7a381ff4a1f54a82f772407a62 License: Apache 2.0 License File: crashpad/LICENSE Security Critical: yes
diff --git a/third_party/crashpad/crashpad/.gitignore b/third_party/crashpad/crashpad/.gitignore index 3311c2e..4180696 100644 --- a/third_party/crashpad/crashpad/.gitignore +++ b/third_party/crashpad/crashpad/.gitignore
@@ -10,6 +10,9 @@ .gdbinit /Makefile /out +/third_party/fuchsia/.cipd +/third_party/fuchsia/clang +/third_party/fuchsia/sdk /third_party/gtest/gtest /third_party/gyp/gyp /third_party/mini_chromium/mini_chromium
diff --git a/third_party/crashpad/crashpad/.gn b/third_party/crashpad/crashpad/.gn new file mode 100644 index 0000000..304422d --- /dev/null +++ b/third_party/crashpad/crashpad/.gn
@@ -0,0 +1,19 @@ +# Copyright 2017 The Crashpad Authors. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +buildconfig = "//build/BUILDCONFIG.gn" + +# This secondary source root is used to put various forwarding/stub files that +# serve to make the core build files compatible with Chromium. +secondary_source = "//build/chromium_compatibility/"
diff --git a/third_party/crashpad/crashpad/BUILD.gn b/third_party/crashpad/crashpad/BUILD.gn index 5c3918ef..88559c4 100644 --- a/third_party/crashpad/crashpad/BUILD.gn +++ b/third_party/crashpad/crashpad/BUILD.gn
@@ -15,7 +15,7 @@ import("//testing/test.gni") config("crashpad_config") { - include_dirs = [ "//third_party/crashpad/crashpad" ] + include_dirs = [ "." ] } test("crashpad_tests") {
diff --git a/third_party/crashpad/crashpad/DEPS b/third_party/crashpad/crashpad/DEPS index 2e40af5e..c37cde7 100644 --- a/third_party/crashpad/crashpad/DEPS +++ b/third_party/crashpad/crashpad/DEPS
@@ -114,6 +114,18 @@ ], }, { + 'name': 'fuchsia_clang', + 'pattern': '.', + 'condition': 'checkout_fuchsia', + 'action': [ + 'cipd', + 'ensure', + '-ensure-file', 'crashpad/third_party/fuchsia/toolchain.ensure', + '-root', 'crashpad/third_party/fuchsia', + '-log-level', 'info', + ], + }, + { 'name': 'gyp', 'pattern': '\.gypi?$', 'action': ['python', 'crashpad/build/gyp_crashpad.py'],
diff --git a/third_party/crashpad/crashpad/build/BUILDCONFIG.gn b/third_party/crashpad/crashpad/build/BUILDCONFIG.gn new file mode 100644 index 0000000..d85494b --- /dev/null +++ b/third_party/crashpad/crashpad/build/BUILDCONFIG.gn
@@ -0,0 +1,66 @@ +# Copyright 2017 The Crashpad Authors. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +if (target_os == "") { + target_os = host_os +} + +if (current_os == "") { + current_os = target_os +} + +declare_args() { + is_debug = false + is_clang = current_os == "mac" || current_os == "fuchsia" + clang_root = "" +} + +is_mac = false +is_win = false +is_linux = false +is_android = false +is_fuchsia = false +is_ios = false # This is necessary for third_party/zlib/zlib/BUILD.gn. + +if (current_os == "mac") { + is_mac = true +} else if (current_os == "win") { + is_win = true +} else if (current_os == "android") { + is_android = true +} else if (current_os == "linux") { + is_linux = true +} else if (current_os == "fuchsia") { + is_fuchsia = true +} + +is_posix = is_mac || is_linux || is_android || is_fuchsia + +if (is_win) { + set_default_toolchain( + "//third_party/mini_chromium/mini_chromium/build:msvc_toolchain") +} else { + set_default_toolchain( + "//third_party/mini_chromium/mini_chromium/build:gcc_like_toolchain") +} + +set_defaults("static_library") { + configs = [ + "//third_party/mini_chromium/mini_chromium/build:default", + + # This (no-op) is added here so that build files that expect to be able to + # remove it can do so without causing an error. + "//build/config/compiler:chromium_code", + ] +}
diff --git a/third_party/crashpad/crashpad/build/chromium_compatibility/README.crashpad b/third_party/crashpad/crashpad/build/chromium_compatibility/README.crashpad new file mode 100644 index 0000000..9a3c1296 --- /dev/null +++ b/third_party/crashpad/crashpad/build/chromium_compatibility/README.crashpad
@@ -0,0 +1,5 @@ +This directory is used as a secondary GN source root for compatibility with +Chromium. Files in this subtree should match file paths that the Crashpad build +files need to refer to when building in Chromium. In the Crashpad tree, they +should either be empty/no-ops, or forward to the real Crashpad implementation +in the real tree. No actual configuration should be done in this secondary tree.
diff --git a/third_party/crashpad/crashpad/build/chromium_compatibility/base/BUILD.gn b/third_party/crashpad/crashpad/build/chromium_compatibility/base/BUILD.gn new file mode 100644 index 0000000..f00a51c2 --- /dev/null +++ b/third_party/crashpad/crashpad/build/chromium_compatibility/base/BUILD.gn
@@ -0,0 +1,26 @@ +# Copyright 2017 The Crashpad Authors. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# This target is a stub so that both Crashpad and Chromium can refer to "//base" +# in their build files. When building in the Chromium tree, "//base" will refer +# the "real" base, but when building standalone in Crashpad, we forward those +# references on to mini_chromium. + +group("base") { + public_configs = + [ "//third_party/mini_chromium/mini_chromium/base:base_public_config" ] + public_deps = [ + "//third_party/mini_chromium/mini_chromium/base", + ] +}
diff --git a/third_party/crashpad/crashpad/build/chromium_compatibility/base/test/BUILD.gn b/third_party/crashpad/crashpad/build/chromium_compatibility/base/test/BUILD.gn new file mode 100644 index 0000000..5bc810a --- /dev/null +++ b/third_party/crashpad/crashpad/build/chromium_compatibility/base/test/BUILD.gn
@@ -0,0 +1,19 @@ +# Copyright 2017 The Crashpad Authors. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# This is a stub to match Chromium. This target is unused and has no effect when +# building standalone in Crashpad. + +group("test_support") { +}
diff --git a/third_party/crashpad/crashpad/build/chromium_compatibility/build/config/compiler/BUILD.gn b/third_party/crashpad/crashpad/build/chromium_compatibility/build/config/compiler/BUILD.gn new file mode 100644 index 0000000..9d4d2e1 --- /dev/null +++ b/third_party/crashpad/crashpad/build/chromium_compatibility/build/config/compiler/BUILD.gn
@@ -0,0 +1,28 @@ +# Copyright 2017 The Crashpad Authors. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# This is a stub to match Chromium. The configs in this file do not have any +# effect on the build when building standalone in Crashpad. + +config("default_symbols") { +} + +config("minimal_symbols") { +} + +config("chromium_code") { +} + +config("no_chromium_code") { +}
diff --git a/third_party/crashpad/crashpad/build/chromium_compatibility/build/config/compiler/compiler.gni b/third_party/crashpad/crashpad/build/chromium_compatibility/build/config/compiler/compiler.gni new file mode 100644 index 0000000..f615259 --- /dev/null +++ b/third_party/crashpad/crashpad/build/chromium_compatibility/build/config/compiler/compiler.gni
@@ -0,0 +1,16 @@ +# Copyright 2017 The Crashpad Authors. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# This is a stub to match Chromium, but is unused when building standalone in +# Crashpad.
diff --git a/third_party/crashpad/crashpad/build/chromium_compatibility/build/win/BUILD.gn b/third_party/crashpad/crashpad/build/chromium_compatibility/build/win/BUILD.gn new file mode 100644 index 0000000..3bf730e --- /dev/null +++ b/third_party/crashpad/crashpad/build/chromium_compatibility/build/win/BUILD.gn
@@ -0,0 +1,25 @@ +# Copyright 2017 The Crashpad Authors. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# This is a stub to match Chromium. The configs in this file do not have any +# effect on the build when building standalone in Crashpad. + +group("default_exe_manifest") { +} + +config("console") { +} + +config("windowed") { +}
diff --git a/third_party/crashpad/crashpad/build/chromium_compatibility/testing/gmock/BUILD.gn b/third_party/crashpad/crashpad/build/chromium_compatibility/testing/gmock/BUILD.gn new file mode 100644 index 0000000..8100104 --- /dev/null +++ b/third_party/crashpad/crashpad/build/chromium_compatibility/testing/gmock/BUILD.gn
@@ -0,0 +1,19 @@ +# Copyright 2017 The Crashpad Authors. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# TODO(GN): This is a placeholder that matches the name of Chromium's location +# for this file. It will need to be filled out to cause a gmock dependency. + +group("gmock") { +}
diff --git a/third_party/crashpad/crashpad/build/chromium_compatibility/testing/gtest/BUILD.gn b/third_party/crashpad/crashpad/build/chromium_compatibility/testing/gtest/BUILD.gn new file mode 100644 index 0000000..03d3046 --- /dev/null +++ b/third_party/crashpad/crashpad/build/chromium_compatibility/testing/gtest/BUILD.gn
@@ -0,0 +1,19 @@ +# Copyright 2017 The Crashpad Authors. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# TODO(GN): This is a placeholder that matches the name of Chromium's location +# for this file. It will need to be filled out to cause a gtest dependency. + +group("gtest") { +}
diff --git a/third_party/crashpad/crashpad/build/chromium_compatibility/testing/test.gni b/third_party/crashpad/crashpad/build/chromium_compatibility/testing/test.gni new file mode 100644 index 0000000..b94470dc --- /dev/null +++ b/third_party/crashpad/crashpad/build/chromium_compatibility/testing/test.gni
@@ -0,0 +1,22 @@ +# Copyright 2017 The Crashpad Authors. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +template("test") { + executable(target_name) { + deps = [] + forward_variables_from(invoker, "*") + + testonly = true + } +}
diff --git a/third_party/crashpad/crashpad/client/BUILD.gn b/third_party/crashpad/crashpad/client/BUILD.gn index 3e24d6d..2fa7110 100644 --- a/third_party/crashpad/crashpad/client/BUILD.gn +++ b/third_party/crashpad/crashpad/client/BUILD.gn
@@ -48,12 +48,12 @@ ] } - public_configs = [ "//third_party/crashpad/crashpad:crashpad_config" ] + public_configs = [ "..:crashpad_config" ] deps = [ + "../compat", + "../util", "//base", - "//third_party/crashpad/crashpad/compat", - "//third_party/crashpad/crashpad/util", ] if (is_win) { @@ -88,20 +88,19 @@ deps = [ ":client", + "../compat", + "../test", + "../util", "//base", "//testing/gmock", "//testing/gtest", - "//third_party/crashpad/crashpad/compat", - "//third_party/crashpad/crashpad/test", - "//third_party/crashpad/crashpad/util", ] data_deps = [ - "//third_party/crashpad/crashpad/handler:crashpad_handler", + "../handler:crashpad_handler", ] if (is_win) { - data_deps += - [ "//third_party/crashpad/crashpad/handler:crashpad_handler_console" ] + data_deps += [ "../handler:crashpad_handler_console" ] } }
diff --git a/third_party/crashpad/crashpad/client/annotation.cc b/third_party/crashpad/crashpad/client/annotation.cc index 22c7395..258f9654 100644 --- a/third_party/crashpad/crashpad/client/annotation.cc +++ b/third_party/crashpad/crashpad/client/annotation.cc
@@ -30,7 +30,9 @@ void Annotation::SetSize(ValueSizeType size) { DCHECK_LT(size, kValueMaxSize); size_ = size; - AnnotationList::Get()->Add(this); + // Use Register() instead of Get() in case the calling module has not + // explicitly initialized the annotation list, to avoid crashing. + AnnotationList::Register()->Add(this); } void Annotation::Clear() {
diff --git a/third_party/crashpad/crashpad/client/crashpad_info.cc b/third_party/crashpad/crashpad/client/crashpad_info.cc index 7ead7445..d2896f4a 100644 --- a/third_party/crashpad/crashpad/client/crashpad_info.cc +++ b/third_party/crashpad/crashpad/client/crashpad_info.cc
@@ -58,11 +58,11 @@ // found without having to consult the symbol table. #if defined(OS_MACOSX) section(SEG_DATA ",crashpad_info"), -#elif defined(OS_LINUX) || defined(OS_ANDROID) +#elif defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_FUCHSIA) section("crashpad_info"), -#else // !defined(OS_MACOSX) && !defined(OS_LINUX) && !defined(OS_ANDROID) +#else #error Port -#endif // !defined(OS_MACOSX) && !defined(OS_LINUX) && !defined(OS_ANDROID) +#endif #if defined(ADDRESS_SANITIZER) // AddressSanitizer would add a trailing red zone of at least 32 bytes,
diff --git a/third_party/crashpad/crashpad/compat/BUILD.gn b/third_party/crashpad/crashpad/compat/BUILD.gn index ddeb53d..0903e79 100644 --- a/third_party/crashpad/crashpad/compat/BUILD.gn +++ b/third_party/crashpad/crashpad/compat/BUILD.gn
@@ -68,7 +68,7 @@ public_configs = [ ":compat_config", - "//third_party/crashpad/crashpad:crashpad_config", + "..:crashpad_config", ] deps = []
diff --git a/third_party/crashpad/crashpad/handler/BUILD.gn b/third_party/crashpad/crashpad/handler/BUILD.gn index 2c17f3d9..05f554b7 100644 --- a/third_party/crashpad/crashpad/handler/BUILD.gn +++ b/third_party/crashpad/crashpad/handler/BUILD.gn
@@ -20,32 +20,42 @@ "crash_report_upload_thread.h", "handler_main.cc", "handler_main.h", - "mac/crash_report_exception_handler.cc", - "mac/crash_report_exception_handler.h", - "mac/exception_handler_server.cc", - "mac/exception_handler_server.h", - "mac/file_limit_annotation.cc", - "mac/file_limit_annotation.h", "minidump_to_upload_parameters.cc", "minidump_to_upload_parameters.h", "prune_crash_reports_thread.cc", "prune_crash_reports_thread.h", "user_stream_data_source.cc", "user_stream_data_source.h", - "win/crash_report_exception_handler.cc", - "win/crash_report_exception_handler.h", ] - public_configs = [ "//third_party/crashpad/crashpad:crashpad_config" ] + if (is_mac) { + sources += [ + "mac/crash_report_exception_handler.cc", + "mac/crash_report_exception_handler.h", + "mac/exception_handler_server.cc", + "mac/exception_handler_server.h", + "mac/file_limit_annotation.cc", + "mac/file_limit_annotation.h", + ] + } + + if (is_win) { + sources += [ + "win/crash_report_exception_handler.cc", + "win/crash_report_exception_handler.h", + ] + } + + public_configs = [ "..:crashpad_config" ] deps = [ + "../client", + "../compat", + "../minidump", + "../snapshot", + "../tools:tool_support", + "../util", "//base", - "//third_party/crashpad/crashpad/client", - "//third_party/crashpad/crashpad/compat", - "//third_party/crashpad/crashpad/minidump", - "//third_party/crashpad/crashpad/snapshot", - "//third_party/crashpad/crashpad/tools:tool_support", - "//third_party/crashpad/crashpad/util", ] if (is_win) { @@ -62,13 +72,13 @@ deps = [ ":handler", + "../client", + "../compat", + "../snapshot", + "../test", + "../util", "//base", "//testing/gtest", - "//third_party/crashpad/crashpad/client", - "//third_party/crashpad/crashpad/compat", - "//third_party/crashpad/crashpad/snapshot", - "//third_party/crashpad/crashpad/test", - "//third_party/crashpad/crashpad/util", ] if (is_win) { @@ -87,9 +97,9 @@ deps = [ ":handler", + "../compat", "//base", "//build/win:default_exe_manifest", - "//third_party/crashpad/crashpad/compat", ] if (is_mac && is_component_build) { @@ -123,11 +133,11 @@ deps = [ ":handler", + "../compat", + "../minidump:test_support", + "../tools:tool_support", "//base", "//build/win:default_exe_manifest", - "//third_party/crashpad/crashpad/compat", - "//third_party/crashpad/crashpad/minidump:test_support", - "//third_party/crashpad/crashpad/tools:tool_support", ] } @@ -144,9 +154,9 @@ deps = [ ":handler", + "../compat", "//base", "//build/win:default_exe_manifest", - "//third_party/crashpad/crashpad/compat", ] }
diff --git a/third_party/crashpad/crashpad/minidump/BUILD.gn b/third_party/crashpad/crashpad/minidump/BUILD.gn index 42f8c3e1..a3c6a2c9 100644 --- a/third_party/crashpad/crashpad/minidump/BUILD.gn +++ b/third_party/crashpad/crashpad/minidump/BUILD.gn
@@ -69,16 +69,16 @@ "minidump_writer_util.h", ] - public_configs = [ "//third_party/crashpad/crashpad:crashpad_config" ] + public_configs = [ "..:crashpad_config" ] public_deps = [ - "//third_party/crashpad/crashpad/compat", + "../compat", ] deps = [ + "../snapshot", + "../util", "//base", - "//third_party/crashpad/crashpad/snapshot", - "//third_party/crashpad/crashpad/util", ] if (is_win) { @@ -111,7 +111,7 @@ "test/minidump_writable_test_util.h", ] - public_configs = [ "//third_party/crashpad/crashpad:crashpad_config" ] + public_configs = [ "..:crashpad_config" ] public_deps = [ ":minidump", @@ -156,11 +156,11 @@ deps = [ ":test_support", + "../snapshot:test_support", + "../test", + "../util", "//base", "//testing/gtest", - "//third_party/crashpad/crashpad/snapshot:test_support", - "//third_party/crashpad/crashpad/test", - "//third_party/crashpad/crashpad/util", ] if (is_win) {
diff --git a/third_party/crashpad/crashpad/minidump/minidump_misc_info_writer.cc b/third_party/crashpad/crashpad/minidump/minidump_misc_info_writer.cc index 3e0dbbc..c1e24892 100644 --- a/third_party/crashpad/crashpad/minidump/minidump_misc_info_writer.cc +++ b/third_party/crashpad/crashpad/minidump/minidump_misc_info_writer.cc
@@ -108,6 +108,8 @@ static constexpr char kOS[] = "linux"; #elif defined(OS_WIN) static constexpr char kOS[] = "win"; +#elif defined(OS_FUCHSIA) + static constexpr char kOS[] = "fuchsia"; #else #error define kOS for this operating system #endif
diff --git a/third_party/crashpad/crashpad/snapshot/BUILD.gn b/third_party/crashpad/crashpad/snapshot/BUILD.gn index 49402fe..2b01fc2 100644 --- a/third_party/crashpad/crashpad/snapshot/BUILD.gn +++ b/third_party/crashpad/crashpad/snapshot/BUILD.gn
@@ -125,13 +125,13 @@ ] } - public_configs = [ "//third_party/crashpad/crashpad:crashpad_config" ] + public_configs = [ "..:crashpad_config" ] deps = [ + "../client", + "../compat", + "../util", "//base", - "//third_party/crashpad/crashpad/client", - "//third_party/crashpad/crashpad/compat", - "//third_party/crashpad/crashpad/util", ] if (is_win) { @@ -147,15 +147,15 @@ "api/module_annotations_win.h", ] - public_configs = [ "//third_party/crashpad/crashpad:crashpad_config" ] + public_configs = [ "..:crashpad_config" ] cflags = [ "/wd4201" ] deps = [ ":snapshot", + "../compat", + "../util", "//base", - "//third_party/crashpad/crashpad/compat", - "//third_party/crashpad/crashpad/util", ] } } else { @@ -185,16 +185,16 @@ "test/test_thread_snapshot.h", ] - public_configs = [ "//third_party/crashpad/crashpad:crashpad_config" ] + public_configs = [ "..:crashpad_config" ] public_deps = [ ":snapshot", ] deps = [ + "../compat", + "../util", "//base", - "//third_party/crashpad/crashpad/compat", - "//third_party/crashpad/crashpad/util", ] if (is_win) { @@ -235,12 +235,12 @@ deps = [ ":snapshot_api", ":test_support", + "../client", + "../compat", + "../test", + "../util", "//base", "//testing/gtest", - "//third_party/crashpad/crashpad/client", - "//third_party/crashpad/crashpad/compat", - "//third_party/crashpad/crashpad/test", - "//third_party/crashpad/crashpad/util", ] data_deps = [ @@ -278,8 +278,8 @@ "crashpad_info_client_options_test_module.cc", ] deps = [ + "../client", "//base", - "//third_party/crashpad/crashpad/client", ] } @@ -328,9 +328,9 @@ "win/crashpad_snapshot_test_annotations.cc", ] deps = [ + "../client", + "../compat", "//base", - "//third_party/crashpad/crashpad/client", - "//third_party/crashpad/crashpad/compat", ] } @@ -340,10 +340,10 @@ "win/crashpad_snapshot_test_crashing_child.cc", ] deps = [ + "../client", + "../compat", + "../util", "//base", - "//third_party/crashpad/crashpad/client", - "//third_party/crashpad/crashpad/compat", - "//third_party/crashpad/crashpad/util", ] } @@ -353,10 +353,10 @@ "win/crashpad_snapshot_test_dump_without_crashing.cc", ] deps = [ + "../client", + "../compat", + "../util", "//base", - "//third_party/crashpad/crashpad/client", - "//third_party/crashpad/crashpad/compat", - "//third_party/crashpad/crashpad/util", ] } @@ -366,9 +366,9 @@ "win/crashpad_snapshot_test_extra_memory_ranges.cc", ] deps = [ + "../client", + "../compat", "//base", - "//third_party/crashpad/crashpad/client", - "//third_party/crashpad/crashpad/compat", ] } @@ -378,10 +378,10 @@ "win/crashpad_snapshot_test_image_reader.cc", ] deps = [ + "../client", + "../compat", + "../util", "//base", - "//third_party/crashpad/crashpad/client", - "//third_party/crashpad/crashpad/compat", - "//third_party/crashpad/crashpad/util", ] if (symbol_level == 0) { # The tests that use this executable rely on at least minimal debug info. @@ -396,8 +396,8 @@ "win/crashpad_snapshot_test_image_reader_module.cc", ] deps = [ + "../client", "//base", - "//third_party/crashpad/crashpad/client", ] if (symbol_level == 0) { # The tests that use this module rely on at least minimal debug info.
diff --git a/third_party/crashpad/crashpad/snapshot/test/BUILD.gn b/third_party/crashpad/crashpad/snapshot/test/BUILD.gn deleted file mode 100644 index 5b9b745..0000000 --- a/third_party/crashpad/crashpad/snapshot/test/BUILD.gn +++ /dev/null
@@ -1,155 +0,0 @@ -# Copyright 2017 The Crashpad Authors. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//testing/test.gni") - -static_library("test") { - testonly = true - - sources = [ - "errors.cc", - "errors.h", - "file.cc", - "file.h", - "filesystem.cc", - "filesystem.h", - "gtest_death_check.h", - "gtest_disabled.cc", - "gtest_disabled.h", - "hex_string.cc", - "hex_string.h", - "mac/dyld.cc", - "mac/dyld.h", - "mac/mach_errors.cc", - "mac/mach_errors.h", - "mac/mach_multiprocess.cc", - "mac/mach_multiprocess.h", - "main_arguments.cc", - "main_arguments.h", - "multiprocess.h", - "multiprocess_exec.h", - "multiprocess_exec_posix.cc", - "multiprocess_exec_win.cc", - "multiprocess_posix.cc", - "scoped_module_handle.cc", - "scoped_module_handle.h", - "scoped_temp_dir.cc", - "scoped_temp_dir.h", - "scoped_temp_dir_posix.cc", - "scoped_temp_dir_win.cc", - "test_paths.cc", - "test_paths.h", - "win/child_launcher.cc", - "win/child_launcher.h", - "win/win_child_process.cc", - "win/win_child_process.h", - "win/win_multiprocess.cc", - "win/win_multiprocess.h", - "win/win_multiprocess_with_temp_dir.cc", - "win/win_multiprocess_with_temp_dir.h", - ] - - public_configs = [ "//third_party/crashpad/crashpad:crashpad_config" ] - - defines = [ "CRASHPAD_IN_CHROMIUM" ] - - data = [ - "test_paths_test_data_root.txt", - ] - - deps = [ - "//base", - "//testing/gtest", - "//third_party/crashpad/crashpad/compat", - "//third_party/crashpad/crashpad/snapshot", - "//third_party/crashpad/crashpad/util", - ] - - if (is_mac) { - libs = [ "bsm" ] - } -} - -source_set("test_test") { - testonly = true - - sources = [ - "hex_string_test.cc", - "mac/mach_multiprocess_test.cc", - "main_arguments_test.cc", - "multiprocess_exec_test.cc", - "scoped_temp_dir_test.cc", - "test_paths_test.cc", - "win/win_child_process_test.cc", - "win/win_multiprocess_test.cc", - ] - - if (!is_win) { - sources += [ "multiprocess_posix_test.cc" ] - } - - deps = [ - ":test", - "//base", - "//testing/gmock", - "//testing/gtest", - "//third_party/crashpad/crashpad/compat", - "//third_party/crashpad/crashpad/util", - ] - - data_deps = [ - ":crashpad_test_test_multiprocess_exec_test_child", - ] -} - -executable("crashpad_test_test_multiprocess_exec_test_child") { - sources = [ - "multiprocess_exec_test_child.cc", - ] -} - -static_library("gmock_main") { - testonly = true - sources = [ - "gtest_main.cc", - ] - defines = [ - "CRASHPAD_IN_CHROMIUM", - "CRASHPAD_TEST_LAUNCHER_GMOCK", - ] - deps = [ - ":test", - "//base", - "//base/test:test_support", - "//testing/gmock", - "//testing/gtest", - ] -} - -static_library("gtest_main") { - testonly = true - sources = [ - "gtest_main.cc", - ] - defines = [ - "CRASHPAD_IN_CHROMIUM", - "CRASHPAD_TEST_LAUNCHER_GTEST", - ] - deps = [ - ":test", - "//base", - "//base/test:test_support", - "//testing/gtest", - ] -}
diff --git a/third_party/crashpad/crashpad/test/BUILD.gn b/third_party/crashpad/crashpad/test/BUILD.gn index c3208ad..50f0c81 100644 --- a/third_party/crashpad/crashpad/test/BUILD.gn +++ b/third_party/crashpad/crashpad/test/BUILD.gn
@@ -62,7 +62,7 @@ "win/win_multiprocess_with_temp_dir.h", ] - public_configs = [ "//third_party/crashpad/crashpad:crashpad_config" ] + public_configs = [ "..:crashpad_config" ] defines = [ "CRASHPAD_IN_CHROMIUM" ] @@ -71,11 +71,11 @@ ] deps = [ + "../compat", + "../snapshot", + "../util", "//base", "//testing/gtest", - "//third_party/crashpad/crashpad/compat", - "//third_party/crashpad/crashpad/snapshot", - "//third_party/crashpad/crashpad/util", ] if (is_mac) { @@ -104,11 +104,11 @@ deps = [ ":test", + "../compat", + "../util", "//base", "//testing/gmock", "//testing/gtest", - "//third_party/crashpad/crashpad/compat", - "//third_party/crashpad/crashpad/util", ] data_deps = [
diff --git a/third_party/crashpad/crashpad/third_party/fuchsia/README.crashpad b/third_party/crashpad/crashpad/third_party/fuchsia/README.crashpad new file mode 100644 index 0000000..fc4a514 --- /dev/null +++ b/third_party/crashpad/crashpad/third_party/fuchsia/README.crashpad
@@ -0,0 +1,4 @@ +This directory is a placeholder for Fuchsia tools that will be downloaded by +CIPD (https://github.com/luci/luci-go/tree/master/cipd). The toolchain.ensure +files specifies which CIPD packages to retrieve, at which versions, and where +they're stored locally. The CIPD update happens as part of gclient runhooks.
diff --git a/third_party/crashpad/crashpad/third_party/fuchsia/toolchain.ensure b/third_party/crashpad/crashpad/third_party/fuchsia/toolchain.ensure new file mode 100644 index 0000000..00f9b78 --- /dev/null +++ b/third_party/crashpad/crashpad/third_party/fuchsia/toolchain.ensure
@@ -0,0 +1,19 @@ +# Copyright 2017 The Crashpad Authors. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +@Subdir clang +fuchsia/clang/${os}-${arch} latest + +@Subdir sdk +fuchsia/sdk/${os=linux}-${arch} latest
diff --git a/third_party/crashpad/crashpad/tools/BUILD.gn b/third_party/crashpad/crashpad/tools/BUILD.gn index e2a82d39f..af02e66 100644 --- a/third_party/crashpad/crashpad/tools/BUILD.gn +++ b/third_party/crashpad/crashpad/tools/BUILD.gn
@@ -18,7 +18,7 @@ "tool_support.h", ] - public_configs = [ "//third_party/crashpad/crashpad:crashpad_config" ] + public_configs = [ "..:crashpad_config" ] deps = [ "//base", @@ -32,11 +32,11 @@ deps = [ ":tool_support", + "../client", + "../compat", + "../util", "//base", "//build/win:default_exe_manifest", - "//third_party/crashpad/crashpad/client", - "//third_party/crashpad/crashpad/compat", - "//third_party/crashpad/crashpad/util", ] } @@ -47,10 +47,10 @@ deps = [ ":tool_support", + "../compat", + "../util", "//base", "//build/win:default_exe_manifest", - "//third_party/crashpad/crashpad/compat", - "//third_party/crashpad/crashpad/util", ] } @@ -61,12 +61,12 @@ deps = [ ":tool_support", + "../compat", + "../minidump", + "../snapshot", + "../util", "//base", "//build/win:default_exe_manifest", - "//third_party/crashpad/crashpad/compat", - "//third_party/crashpad/crashpad/minidump", - "//third_party/crashpad/crashpad/snapshot", - "//third_party/crashpad/crashpad/util", ] if (is_mac) { @@ -96,9 +96,9 @@ deps = [ ":tool_support", + "../compat", + "../util", "//base", - "//third_party/crashpad/crashpad/compat", - "//third_party/crashpad/crashpad/util", ] } @@ -121,9 +121,9 @@ deps = [ ":tool_support", + "../compat", + "../util", "//base", - "//third_party/crashpad/crashpad/compat", - "//third_party/crashpad/crashpad/util", ] } @@ -139,9 +139,9 @@ deps = [ ":tool_support", + "../compat", + "../util", "//base", - "//third_party/crashpad/crashpad/compat", - "//third_party/crashpad/crashpad/util", ] } @@ -152,10 +152,10 @@ deps = [ ":tool_support", + "../client", + "../compat", + "../util", "//base", - "//third_party/crashpad/crashpad/client", - "//third_party/crashpad/crashpad/compat", - "//third_party/crashpad/crashpad/util", ] } }
diff --git a/third_party/crashpad/crashpad/util/BUILD.gn b/third_party/crashpad/crashpad/util/BUILD.gn index 34b3036..7f8e7ecc 100644 --- a/third_party/crashpad/crashpad/util/BUILD.gn +++ b/third_party/crashpad/crashpad/util/BUILD.gn
@@ -12,8 +12,6 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//build/config/sanitizers/sanitizers.gni") -import("//build/toolchain/toolchain.gni") import("//testing/test.gni") if (is_mac) { @@ -61,11 +59,9 @@ "file/delimited_file_reader.h", "file/directory_reader.h", "file/directory_reader_posix.cc", - "file/directory_reader_win.cc", "file/file_io.cc", "file/file_io.h", "file/file_io_posix.cc", - "file/file_io_win.cc", "file/file_reader.cc", "file/file_reader.h", "file/file_seeker.cc", @@ -74,28 +70,16 @@ "file/file_writer.h", "file/filesystem.h", "file/filesystem_posix.cc", - "file/filesystem_win.cc", "file/scoped_remove_file.cc", "file/scoped_remove_file.h", "file/string_file.cc", "file/string_file.h", - "mac/checked_mach_address_range.h", - "mac/launchd.h", - "mac/launchd.mm", - "mac/mac_util.cc", - "mac/mac_util.h", - "mac/service_management.cc", - "mac/service_management.h", - "mac/xattr.cc", - "mac/xattr.h", "misc/address_sanitizer.h", "misc/address_types.h", "misc/arraysize_unsafe.h", "misc/as_underlying_type.h", "misc/clock.h", - "misc/clock_mac.cc", "misc/clock_posix.cc", - "misc/clock_win.cc", "misc/from_pointer_cast.h", "misc/implicit_cast.h", "misc/initialization_state.h", @@ -106,8 +90,6 @@ "misc/metrics.cc", "misc/metrics.h", "misc/paths.h", - "misc/paths_mac.cc", - "misc/paths_win.cc", "misc/pdb_structures.cc", "misc/pdb_structures.h", "misc/random_string.cc", @@ -119,7 +101,6 @@ "misc/symbolic_constants_common.h", "misc/time.cc", "misc/time.h", - "misc/time_win.cc", "misc/tri_state.h", "misc/uuid.cc", "misc/uuid.h", @@ -134,8 +115,6 @@ "net/http_multipart_builder.h", "net/http_transport.cc", "net/http_transport.h", - "net/http_transport_mac.mm", - "net/http_transport_win.cc", "net/url.cc", "net/url.h", "numeric/checked_address_range.cc", @@ -154,7 +133,6 @@ "posix/drop_privileges.cc", "posix/drop_privileges.h", "posix/process_info.h", - "posix/process_info_mac.cc", "posix/scoped_dir.cc", "posix/scoped_dir.h", "posix/scoped_mmap.cc", @@ -177,63 +155,27 @@ "string/split_string.cc", "string/split_string.h", "synchronization/semaphore.h", - "synchronization/semaphore_mac.cc", "synchronization/semaphore_posix.cc", - "synchronization/semaphore_win.cc", "thread/thread.cc", "thread/thread.h", "thread/thread_log_messages.cc", "thread/thread_log_messages.h", "thread/thread_posix.cc", - "thread/thread_win.cc", "thread/worker_thread.cc", "thread/worker_thread.h", - "win/address_types.h", - "win/capture_context.h", - "win/checked_win_address_range.h", - "win/command_line.cc", - "win/command_line.h", - "win/critical_section_with_debug_info.cc", - "win/critical_section_with_debug_info.h", - "win/exception_handler_server.cc", - "win/exception_handler_server.h", - "win/get_function.cc", - "win/get_function.h", - "win/get_module_information.cc", - "win/get_module_information.h", - "win/handle.cc", - "win/handle.h", - "win/initial_client_data.cc", - "win/initial_client_data.h", - "win/module_version.cc", - "win/module_version.h", - "win/nt_internals.cc", - "win/nt_internals.h", - "win/ntstatus_logging.cc", - "win/ntstatus_logging.h", - "win/process_info.cc", - "win/process_info.h", - "win/process_structs.h", - "win/registration_protocol_win.cc", - "win/registration_protocol_win.h", - "win/safe_terminate_process.h", - "win/scoped_handle.cc", - "win/scoped_handle.h", - "win/scoped_local_alloc.cc", - "win/scoped_local_alloc.h", - "win/scoped_process_suspend.cc", - "win/scoped_process_suspend.h", - "win/scoped_set_event.cc", - "win/scoped_set_event.h", - "win/session_end_watcher.cc", - "win/session_end_watcher.h", - "win/termination_codes.h", - "win/xp_compat.h", ] if (is_mac) { - # mach/ are not globally filtered. sources += [ + "mac/checked_mach_address_range.h", + "mac/launchd.h", + "mac/launchd.mm", + "mac/mac_util.cc", + "mac/mac_util.h", + "mac/service_management.cc", + "mac/service_management.h", + "mac/xattr.cc", + "mac/xattr.h", "mach/child_port_handshake.cc", "mach/child_port_handshake.h", "mach/child_port_server.cc", @@ -267,14 +209,69 @@ "mach/task_for_pid.h", "mach/task_memory.cc", "mach/task_memory.h", + "misc/clock_mac.cc", + "misc/paths_mac.cc", + "net/http_transport_mac.mm", + "posix/process_info_mac.cc", + "synchronization/semaphore_mac.cc", ] - } - - if (is_mac) { sources += get_target_outputs(":mig") } if (is_win) { + sources += [ + "file/directory_reader_win.cc", + "file/file_io_win.cc", + "file/filesystem_win.cc", + "misc/clock_win.cc", + "misc/paths_win.cc", + "misc/time_win.cc", + "net/http_transport_win.cc", + "synchronization/semaphore_win.cc", + "thread/thread_win.cc", + "win/address_types.h", + "win/capture_context.h", + "win/checked_win_address_range.h", + "win/command_line.cc", + "win/command_line.h", + "win/critical_section_with_debug_info.cc", + "win/critical_section_with_debug_info.h", + "win/exception_handler_server.cc", + "win/exception_handler_server.h", + "win/get_function.cc", + "win/get_function.h", + "win/get_module_information.cc", + "win/get_module_information.h", + "win/handle.cc", + "win/handle.h", + "win/initial_client_data.cc", + "win/initial_client_data.h", + "win/module_version.cc", + "win/module_version.h", + "win/nt_internals.cc", + "win/nt_internals.h", + "win/ntstatus_logging.cc", + "win/ntstatus_logging.h", + "win/process_info.cc", + "win/process_info.h", + "win/process_structs.h", + "win/registration_protocol_win.cc", + "win/registration_protocol_win.h", + "win/safe_terminate_process.h", + "win/scoped_handle.cc", + "win/scoped_handle.h", + "win/scoped_local_alloc.cc", + "win/scoped_local_alloc.h", + "win/scoped_process_suspend.cc", + "win/scoped_process_suspend.h", + "win/scoped_set_event.cc", + "win/scoped_set_event.h", + "win/session_end_watcher.cc", + "win/session_end_watcher.h", + "win/termination_codes.h", + "win/xp_compat.h", + ] + # There's no ml.exe yet in cross builds, so provide broken-but-not-asm # versions of the functions defined in .asm files. # @@ -298,18 +295,20 @@ } } - public_configs = [ "//third_party/crashpad/crashpad:crashpad_config" ] + public_configs = [ "..:crashpad_config" ] # Include files from here and generated files starting with "util". include_dirs = [ "$root_gen_dir/third_party/crashpad/crashpad" ] public_deps = [ - "//third_party/crashpad/crashpad/compat", + "../compat", ] deps = [ "//base", - "//third_party/crashpad/crashpad/third_party/zlib", + + # TODO(GN): Should this point at Chromium's zlib when in Chromium? + "../third_party/zlib", ] if (is_mac) { @@ -345,10 +344,6 @@ "file/file_reader_test.cc", "file/filesystem_test.cc", "file/string_file_test.cc", - "mac/launchd_test.mm", - "mac/mac_util_test.mm", - "mac/service_management_test.mm", - "mac/xattr_test.cc", "misc/arraysize_unsafe_test.cc", "misc/clock_test.cc", "misc/from_pointer_cast_test.cc", @@ -386,23 +381,14 @@ "thread/thread_log_messages_test.cc", "thread/thread_test.cc", "thread/worker_thread_test.cc", - "win/capture_context_test.cc", - "win/command_line_test.cc", - "win/critical_section_with_debug_info_test.cc", - "win/exception_handler_server_test.cc", - "win/get_function_test.cc", - "win/handle_test.cc", - "win/initial_client_data_test.cc", - "win/process_info_test.cc", - "win/registration_protocol_win_test.cc", - "win/safe_terminate_process_test.cc", - "win/scoped_process_suspend_test.cc", - "win/session_end_watcher_test.cc", ] if (is_mac) { - # mach/ are not globally filtered. sources += [ + "mac/launchd_test.mm", + "mac/mac_util_test.mm", + "mac/service_management_test.mm", + "mac/xattr_test.cc", "mach/child_port_handshake_test.cc", "mach/child_port_server_test.cc", "mach/composite_mach_message_server_test.cc", @@ -421,6 +407,23 @@ ] } + if (is_win) { + sources += [ + "win/capture_context_test.cc", + "win/command_line_test.cc", + "win/critical_section_with_debug_info_test.cc", + "win/exception_handler_server_test.cc", + "win/get_function_test.cc", + "win/handle_test.cc", + "win/initial_client_data_test.cc", + "win/process_info_test.cc", + "win/registration_protocol_win_test.cc", + "win/safe_terminate_process_test.cc", + "win/scoped_process_suspend_test.cc", + "win/session_end_watcher_test.cc", + ] + } + data = [ "net/http_transport_test_server.py", "net/testdata/", @@ -428,13 +431,13 @@ deps = [ ":util", + "../client", + "../compat", + "../test", + "../third_party/zlib", "//base", "//testing/gmock", "//testing/gtest", - "//third_party/crashpad/crashpad/client", - "//third_party/crashpad/crashpad/compat", - "//third_party/crashpad/crashpad/test", - "//third_party/crashpad/crashpad/third_party/zlib", ] if (is_mac) {
diff --git a/third_party/crashpad/crashpad/util/misc/metrics.cc b/third_party/crashpad/crashpad/util/misc/metrics.cc index e2bd9f0..30de6b9 100644 --- a/third_party/crashpad/crashpad/util/misc/metrics.cc +++ b/third_party/crashpad/crashpad/util/misc/metrics.cc
@@ -26,6 +26,8 @@ #define METRICS_OS_NAME "Android" #elif defined(OS_LINUX) #define METRICS_OS_NAME "Linux" +#elif defined(OS_FUCHSIA) +#define METRICS_OS_NAME "Fuchsia" #endif namespace crashpad {
diff --git a/third_party/crashpad/crashpad/util/misc/uuid.cc b/third_party/crashpad/crashpad/util/misc/uuid.cc index 6cf777f5..92fba760 100644 --- a/third_party/crashpad/crashpad/util/misc/uuid.cc +++ b/third_party/crashpad/crashpad/util/misc/uuid.cc
@@ -90,9 +90,11 @@ uuid_generate(uuid); InitializeFromBytes(uuid); return true; -#elif defined(OS_WIN) || defined(OS_LINUX) || defined(OS_ANDROID) - // Linux does not provide a UUID generator in a widely-available system - // library. uuid_generate() from libuuid is not available everywhere. +#elif defined(OS_WIN) || defined(OS_LINUX) || defined(OS_ANDROID) || \ + defined(OS_FUCHSIA) + // Linux, Android, and Fuchsia do not provide a UUID generator in a + // widely-available system library. On Linux and Android, uuid_generate() + // from libuuid is not available everywhere. // On Windows, do not use UuidCreate() to avoid a dependency on rpcrt4, so // that this function is usable early in DllMain(). base::RandBytes(this, sizeof(*this));
diff --git a/third_party/libxml/chromium/libxml_utils.cc b/third_party/libxml/chromium/libxml_utils.cc index 4eed5d6..796afbd 100644 --- a/third_party/libxml/chromium/libxml_utils.cc +++ b/third_party/libxml/chromium/libxml_utils.cc
@@ -48,10 +48,39 @@ return true; } +bool XmlReader::GetTextIfTextElement(std::string* content) { + if (NodeType() != XML_READER_TYPE_TEXT) + return false; + + *content = XmlStringToStdString(xmlTextReaderConstValue(reader_)); + return true; +} + +bool XmlReader::GetTextIfCDataElement(std::string* content) { + if (NodeType() != XML_READER_TYPE_CDATA) + return false; + + *content = XmlStringToStdString(xmlTextReaderConstValue(reader_)); + return true; +} + bool XmlReader::IsClosingElement() { return NodeType() == XML_READER_TYPE_END_ELEMENT; } +bool XmlReader::IsEmptyElement() { + return xmlTextReaderIsEmptyElement(reader_); +} + +bool XmlReader::IsWhiteSpace() { + return NodeType() == XML_READER_TYPE_WHITESPACE || + NodeType() == XML_READER_TYPE_SIGNIFICANT_WHITESPACE; +} + +bool XmlReader::IsComment() { + return NodeType() == XML_READER_TYPE_COMMENT; +} + bool XmlReader::ReadElementContent(std::string* content) { const int start_depth = Depth();
diff --git a/third_party/libxml/chromium/libxml_utils.h b/third_party/libxml/chromium/libxml_utils.h index 9091f49..f58fec7d 100644 --- a/third_party/libxml/chromium/libxml_utils.h +++ b/third_party/libxml/chromium/libxml_utils.h
@@ -73,9 +73,25 @@ // returns true and |value| is set to "a". bool NodeAttribute(const char* name, std::string* value); + // Sets |content| to the content of the current node if it is a #text/#cdata + // node. + // Returns true if the current node is a #text/#cdata node, false otherwise. + bool GetTextIfTextElement(std::string* content); + bool GetTextIfCDataElement(std::string* content); + // Returns true if the node is a closing element (e.g. </foo>). bool IsClosingElement(); + // Returns true if the current node is an empty (self-closing) element (e.g. + // <foo/>). + bool IsEmptyElement(); + + // Returns true if the current node is a white-space node. + bool IsWhiteSpace(); + + // Returns true if the current node is a comment (e.g. <!-- comment -->). + bool IsComment(); + // Helper functions not provided by libxml ---------------------------------- // Return the string content within an element.
diff --git a/third_party/openvr/README.chromium b/third_party/openvr/README.chromium index e28526f..7c3af2d 100644 --- a/third_party/openvr/README.chromium +++ b/third_party/openvr/README.chromium
@@ -14,6 +14,7 @@ Local Modifications: Only contains a subset of the git repo necessary to build Chromium. jsoncpp.cpp has been modified to remove exceptions. +json.h has been modified to remove exceptions (delete "throw()"). openvr.h has been modified to remove dllimport/dllexport when building a non-component build so this can be built as a static library.
diff --git a/third_party/openvr/src/src/json/json.h b/third_party/openvr/src/src/json/json.h index d27f65d..2c4949b3 100644 --- a/third_party/openvr/src/src/json/json.h +++ b/third_party/openvr/src/src/json/json.h
@@ -425,8 +425,8 @@ class JSON_API Exception : public std::exception { public: Exception(std::string const& msg); - ~Exception() throw(); - char const* what() const throw(); + ~Exception(); + char const* what() const; protected: std::string msg_; };
diff --git a/third_party/wayland-protocols/include/protocol/remote-shell-unstable-v1-client-protocol.h b/third_party/wayland-protocols/include/protocol/remote-shell-unstable-v1-client-protocol.h index 05caad9..31e2430e 100644 --- a/third_party/wayland-protocols/include/protocol/remote-shell-unstable-v1-client-protocol.h +++ b/third_party/wayland-protocols/include/protocol/remote-shell-unstable-v1-client-protocol.h
@@ -192,6 +192,10 @@ * moving window state */ ZCR_REMOTE_SHELL_V1_STATE_TYPE_MOVING = 7, + /** + * resizing window state + */ + ZCR_REMOTE_SHELL_V1_STATE_TYPE_RESIZING = 8, }; #endif /* ZCR_REMOTE_SHELL_V1_STATE_TYPE_ENUM */ @@ -556,6 +560,22 @@ int32_t origin_offset_y, struct wl_array *states, uint32_t serial); + /** + * announce window geometry commit + * + * Notify the client of committed window geometry. + * + * The compositor sends this event when it commits window geometry. + * The client may use this information to convert coordinates of + * input events using the latest committed geometry. + * @since 9 + */ + void (*window_geometry_changed)(void *data, + struct zcr_remote_surface_v1 *zcr_remote_surface_v1, + int32_t x, + int32_t y, + int32_t width, + int32_t height); }; /** @@ -595,6 +615,8 @@ #define ZCR_REMOTE_SURFACE_V1_MOVE 23 #define ZCR_REMOTE_SURFACE_V1_SET_ORIENTATION 24 #define ZCR_REMOTE_SURFACE_V1_SET_WINDOW_TYPE 25 +#define ZCR_REMOTE_SURFACE_V1_RESIZE 26 +#define ZCR_REMOTE_SURFACE_V1_SET_RESIZE_OUTSET 27 /** * @ingroup iface_zcr_remote_surface_v1 @@ -608,6 +630,10 @@ * @ingroup iface_zcr_remote_surface_v1 */ #define ZCR_REMOTE_SURFACE_V1_CONFIGURE_SINCE_VERSION 5 +/** + * @ingroup iface_zcr_remote_surface_v1 + */ +#define ZCR_REMOTE_SURFACE_V1_WINDOW_GEOMETRY_CHANGED_SINCE_VERSION 9 /** * @ingroup iface_zcr_remote_surface_v1 @@ -713,6 +739,14 @@ * @ingroup iface_zcr_remote_surface_v1 */ #define ZCR_REMOTE_SURFACE_V1_SET_WINDOW_TYPE_SINCE_VERSION 7 +/** + * @ingroup iface_zcr_remote_surface_v1 + */ +#define ZCR_REMOTE_SURFACE_V1_RESIZE_SINCE_VERSION 9 +/** + * @ingroup iface_zcr_remote_surface_v1 + */ +#define ZCR_REMOTE_SURFACE_V1_SET_RESIZE_OUTSET_SINCE_VERSION 9 /** @ingroup iface_zcr_remote_surface_v1 */ static inline void @@ -827,7 +861,7 @@ /** * @ingroup iface_zcr_remote_surface_v1 * - * Suggests the window's background opacity when the shadow is requested. + * [Deprecated] Suggests the window's background opacity when the shadow is requested. */ static inline void zcr_remote_surface_v1_set_rectangular_shadow_background_opacity(struct zcr_remote_surface_v1 *zcr_remote_surface_v1, wl_fixed_t opacity) @@ -1165,6 +1199,44 @@ ZCR_REMOTE_SURFACE_V1_SET_WINDOW_TYPE, type); } +/** + * @ingroup iface_zcr_remote_surface_v1 + * + * Start an interactive, user-driven resize of the surface. + * + * The compositor responds to this request with a configure event that + * transitions to the "resizing" state. The client must only initiate + * resizing after acknowledging the state change. The compositor can assume + * that subsequent set_window_geometry requests are resizes until the next + * state transition is acknowledged. + * + * The compositor may ignore resize requests depending on the state of the + * surface, e.g. fullscreen or maximized. + */ +static inline void +zcr_remote_surface_v1_resize(struct zcr_remote_surface_v1 *zcr_remote_surface_v1) +{ + wl_proxy_marshal((struct wl_proxy *) zcr_remote_surface_v1, + ZCR_REMOTE_SURFACE_V1_RESIZE); +} + +/** + * @ingroup iface_zcr_remote_surface_v1 + * + * Expand input region of surface with resize outset. + * + * The compositor clips the input region of each surface to its bounds, + * unless the client requests a resize outset. In that case, the input + * region of the root surface is expanded to allow for some leeway around + * visible bounds when starting a user-driven resize. + */ +static inline void +zcr_remote_surface_v1_set_resize_outset(struct zcr_remote_surface_v1 *zcr_remote_surface_v1, int32_t outset) +{ + wl_proxy_marshal((struct wl_proxy *) zcr_remote_surface_v1, + ZCR_REMOTE_SURFACE_V1_SET_RESIZE_OUTSET, outset); +} + #define ZCR_NOTIFICATION_SURFACE_V1_DESTROY 0
diff --git a/third_party/wayland-protocols/include/protocol/remote-shell-unstable-v1-server-protocol.h b/third_party/wayland-protocols/include/protocol/remote-shell-unstable-v1-server-protocol.h index 3972d7a..eddd781 100644 --- a/third_party/wayland-protocols/include/protocol/remote-shell-unstable-v1-server-protocol.h +++ b/third_party/wayland-protocols/include/protocol/remote-shell-unstable-v1-server-protocol.h
@@ -195,6 +195,10 @@ * moving window state */ ZCR_REMOTE_SHELL_V1_STATE_TYPE_MOVING = 7, + /** + * resizing window state + */ + ZCR_REMOTE_SHELL_V1_STATE_TYPE_RESIZING = 8, }; #endif /* ZCR_REMOTE_SHELL_V1_STATE_TYPE_ENUM */ @@ -525,8 +529,8 @@ /** * suggests the window's background opacity * - * Suggests the window's background opacity when the shadow is - * requested. + * [Deprecated] Suggests the window's background opacity when the + * shadow is requested. */ void (*set_rectangular_shadow_background_opacity)(struct wl_client *client, struct wl_resource *resource, @@ -789,11 +793,45 @@ void (*set_window_type)(struct wl_client *client, struct wl_resource *resource, uint32_t type); + /** + * start an interactive resize + * + * Start an interactive, user-driven resize of the surface. + * + * The compositor responds to this request with a configure event + * that transitions to the "resizing" state. The client must only + * initiate resizing after acknowledging the state change. The + * compositor can assume that subsequent set_window_geometry + * requests are resizes until the next state transition is + * acknowledged. + * + * The compositor may ignore resize requests depending on the state + * of the surface, e.g. fullscreen or maximized. + * @since 9 + */ + void (*resize)(struct wl_client *client, + struct wl_resource *resource); + /** + * expand input region for resizing + * + * Expand input region of surface with resize outset. + * + * The compositor clips the input region of each surface to its + * bounds, unless the client requests a resize outset. In that + * case, the input region of the root surface is expanded to allow + * for some leeway around visible bounds when starting a + * user-driven resize. + * @since 9 + */ + void (*set_resize_outset)(struct wl_client *client, + struct wl_resource *resource, + int32_t outset); }; #define ZCR_REMOTE_SURFACE_V1_CLOSE 0 #define ZCR_REMOTE_SURFACE_V1_STATE_TYPE_CHANGED 1 #define ZCR_REMOTE_SURFACE_V1_CONFIGURE 2 +#define ZCR_REMOTE_SURFACE_V1_WINDOW_GEOMETRY_CHANGED 3 /** * @ingroup iface_zcr_remote_surface_v1 @@ -807,6 +845,10 @@ * @ingroup iface_zcr_remote_surface_v1 */ #define ZCR_REMOTE_SURFACE_V1_CONFIGURE_SINCE_VERSION 5 +/** + * @ingroup iface_zcr_remote_surface_v1 + */ +#define ZCR_REMOTE_SURFACE_V1_WINDOW_GEOMETRY_CHANGED_SINCE_VERSION 9 /** * @ingroup iface_zcr_remote_surface_v1 @@ -912,6 +954,14 @@ * @ingroup iface_zcr_remote_surface_v1 */ #define ZCR_REMOTE_SURFACE_V1_SET_WINDOW_TYPE_SINCE_VERSION 7 +/** + * @ingroup iface_zcr_remote_surface_v1 + */ +#define ZCR_REMOTE_SURFACE_V1_RESIZE_SINCE_VERSION 9 +/** + * @ingroup iface_zcr_remote_surface_v1 + */ +#define ZCR_REMOTE_SURFACE_V1_SET_RESIZE_OUTSET_SINCE_VERSION 9 /** * @ingroup iface_zcr_remote_surface_v1 @@ -947,6 +997,17 @@ } /** + * @ingroup iface_zcr_remote_surface_v1 + * Sends an window_geometry_changed event to the client owning the resource. + * @param resource_ The client's resource + */ +static inline void +zcr_remote_surface_v1_send_window_geometry_changed(struct wl_resource *resource_, int32_t x, int32_t y, int32_t width, int32_t height) +{ + wl_resource_post_event(resource_, ZCR_REMOTE_SURFACE_V1_WINDOW_GEOMETRY_CHANGED, x, y, width, height); +} + +/** * @ingroup iface_zcr_notification_surface_v1 * @struct zcr_notification_surface_v1_interface */
diff --git a/third_party/wayland-protocols/protocol/remote-shell-protocol.c b/third_party/wayland-protocols/protocol/remote-shell-protocol.c index 2cefcaff..a18da35 100644 --- a/third_party/wayland-protocols/protocol/remote-shell-protocol.c +++ b/third_party/wayland-protocols/protocol/remote-shell-protocol.c
@@ -70,7 +70,7 @@ }; WL_EXPORT const struct wl_interface zcr_remote_shell_v1_interface = { - "zcr_remote_shell_v1", 8, + "zcr_remote_shell_v1", 9, 3, zcr_remote_shell_v1_requests, 5, zcr_remote_shell_v1_events, }; @@ -102,18 +102,21 @@ { "move", "5", types + 0 }, { "set_orientation", "6i", types + 0 }, { "set_window_type", "7u", types + 0 }, + { "resize", "9", types + 0 }, + { "set_resize_outset", "9i", types + 0 }, }; static const struct wl_message zcr_remote_surface_v1_events[] = { { "close", "", types + 0 }, { "state_type_changed", "u", types + 0 }, { "configure", "5iiau", types + 0 }, + { "window_geometry_changed", "9iiii", types + 0 }, }; WL_EXPORT const struct wl_interface zcr_remote_surface_v1_interface = { - "zcr_remote_surface_v1", 7, - 26, zcr_remote_surface_v1_requests, - 3, zcr_remote_surface_v1_events, + "zcr_remote_surface_v1", 9, + 28, zcr_remote_surface_v1_requests, + 4, zcr_remote_surface_v1_events, }; static const struct wl_message zcr_notification_surface_v1_requests[] = {
diff --git a/third_party/wayland-protocols/unstable/remote-shell/remote-shell-unstable-v1.xml b/third_party/wayland-protocols/unstable/remote-shell/remote-shell-unstable-v1.xml index f3810da4..be657ad2 100644 --- a/third_party/wayland-protocols/unstable/remote-shell/remote-shell-unstable-v1.xml +++ b/third_party/wayland-protocols/unstable/remote-shell/remote-shell-unstable-v1.xml
@@ -38,7 +38,7 @@ reset. </description> - <interface name="zcr_remote_shell_v1" version="8"> + <interface name="zcr_remote_shell_v1" version="9"> <description summary="remote_shell"> The global interface that allows clients to turn a wl_surface into a "real window" which is remotely managed but can be stacked, activated @@ -65,6 +65,7 @@ <entry name="pinned" value="5" summary="pinned window state"/> <entry name="trusted_pinned" value="6" summary="trusted pinned window state"/> <entry name="moving" value="7" summary="moving window state"/> + <entry name="resizing" value="8" summary="resizing window state"/> </enum> <enum name="error"> @@ -180,7 +181,7 @@ </event> </interface> - <interface name="zcr_remote_surface_v1" version="7"> + <interface name="zcr_remote_surface_v1" version="9"> <description summary="A desktop window"> An interface that may be implemented by a wl_surface, for implementations that provide a desktop-style user interface @@ -571,12 +572,55 @@ <request name="set_window_type" since="7"> <description summary="set the type of the window"> - Set the type of window. This is only a hint to the compositor and the - compositor is free to ignore it. + Set the type of window. This is only a hint to the compositor and the + compositor is free to ignore it. </description> <arg name="type" type="uint" summary="type of the window"/> </request> + <!-- Version 9 additions --> + + <request name="resize" since="9"> + <description summary="start an interactive resize"> + Start an interactive, user-driven resize of the surface. + + The compositor responds to this request with a configure event that + transitions to the "resizing" state. The client must only initiate + resizing after acknowledging the state change. The compositor can assume + that subsequent set_window_geometry requests are resizes until the next + state transition is acknowledged. + + The compositor may ignore resize requests depending on the state of the + surface, e.g. fullscreen or maximized. + </description> + </request> + + <request name="set_resize_outset" since="9"> + <description summary="expand input region for resizing"> + Expand input region of surface with resize outset. + + The compositor clips the input region of each surface to its bounds, + unless the client requests a resize outset. In that case, the input + region of the root surface is expanded to allow for some leeway around + visible bounds when starting a user-driven resize. + </description> + <arg name="outset" type="int"/> + </request> + + <event name="window_geometry_changed" since="9"> + <description summary="announce window geometry commit"> + Notify the client of committed window geometry. + + The compositor sends this event when it commits window geometry. The + client may use this information to convert coordinates of input events + using the latest committed geometry. + </description> + <arg name="x" type="int"/> + <arg name="y" type="int"/> + <arg name="width" type="int"/> + <arg name="height" type="int"/> + </event> + </interface> <interface name="zcr_notification_surface_v1" version="1">
diff --git a/tools/android/checkstyle/chromium-style-5.0.xml b/tools/android/checkstyle/chromium-style-5.0.xml index 6363f42..03d7bcf 100644 --- a/tools/android/checkstyle/chromium-style-5.0.xml +++ b/tools/android/checkstyle/chromium-style-5.0.xml
@@ -99,7 +99,7 @@ </module> <module name="ImportOrder"> <property name="severity" value="error"/> - <message key="import.ordering" value="Wrong order for {0} import. Use :JavaImportOrganize (ECLIM), Ctrl+Shift+O (Eclipse), or Ctrl+Alt+O (Android Studio) to sort imports. An importorder file for configuring Eclipse can be found at //tools/android/eclipse/android.importorder. A style configuration file for Android Studio can be found at //tools/android/android_studio/ChromiumStyle.xml."/> + <message key="import.ordering" value="Wrong order for {0} import. Follow the AOSP Java Code Style: https://source.android.com/setup/code-style#order-import-statements. When using Android Studio, use Ctrl+Alt+O to sort imports. A style configuration file can be found at //tools/android/android_studio/ChromiumStyle.xml."/> <property name="groups" value="android, com, dalvik, junit, org, com.google.android.apps.chrome, org.chromium, java, javax"/> <property name="ordered" value="true"/> <property name="option" value="top"/>
diff --git a/tools/binary_size/libsupersize/path_util.py b/tools/binary_size/libsupersize/path_util.py index 1f67b16..ab2ff1c 100644 --- a/tools/binary_size/libsupersize/path_util.py +++ b/tools/binary_size/libsupersize/path_util.py
@@ -108,9 +108,11 @@ if os.path.isfile(ret + _SAMPLE_TOOL_SUFFIX): return ret else: - logging.warn('Invalid default tool-prefix: %s', ret) - # TODO(huangs): For LLD, print more instruction on how to download - # or build the required tools. + err_lines = ['tool-prefix not found: %s' % ret] + if ret.endswith('llvm-'): + err_lines.append('Probably need to run: ' + 'tools/clang/scripts/download_objdump.py') + raise Exception('\n'.join(err_lines)) from_path = distutils.spawn.find_executable(_SAMPLE_TOOL_SUFFIX) if from_path: return from_path[:-7]
diff --git a/tools/cfi/blacklist.txt b/tools/cfi/blacklist.txt index 6cc1c964..bdc885c 100644 --- a/tools/cfi/blacklist.txt +++ b/tools/cfi/blacklist.txt
@@ -175,6 +175,9 @@ # third_party/skia/include/gpu/gl/GrGLFunctions.h fun:*GrGLFunction* +# chrome/browser/ui/libgtkui/gtk_util.cc +fun:*AppendCssNodeToStyleContext* + ######### Function pointers cast to incorrect type signatures # libicu is currently compiled such that in libicu the 'UChar' type is a
diff --git a/tools/cygprofile/delayed_dumper.cc b/tools/cygprofile/delayed_dumper.cc index d22fb92..c2d60b4 100644 --- a/tools/cygprofile/delayed_dumper.cc +++ b/tools/cygprofile/delayed_dumper.cc
@@ -2,12 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include <time.h> #include <unistd.h> #include <thread> #include "base/android/library_loader/anchor_functions.h" #include "base/files/file.h" +#include "base/format_macros.h" #include "base/logging.h" #include "base/strings/stringprintf.h" #include "build/build_config.h" @@ -25,13 +27,20 @@ class DelayedDumper { public: DelayedDumper() { - SanityChecks(); - std::thread([]() { + // Not using base::TimeTicks() to not call too many base:: symbol that would + // pollute the reached symbols dumps. + struct timespec ts; + if (clock_gettime(CLOCK_MONOTONIC, &ts)) + PLOG(FATAL) << "clock_gettime."; + uint64_t start_ns_since_epoch = + static_cast<uint64_t>(ts.tv_sec) * 1000 * 1000 * 1000 + ts.tv_nsec; + + std::thread([start_ns_since_epoch]() { sleep(kDelayInSeconds); auto path = base::StringPrintf( "/data/local/tmp/chrome/cyglog/" - "cygprofile-instrumented-code-hitmap-%d.txt", - getpid()); + "cygprofile-instrumented-code-hitmap-%d-%" PRIu64 ".txt", + getpid(), start_ns_since_epoch); StopAndDumpToFile(base::FilePath(path)); }) .detach();
diff --git a/tools/cygprofile/process_profiles.py b/tools/cygprofile/process_profiles.py index a25b93f..87a0fefd4 100755 --- a/tools/cygprofile/process_profiles.py +++ b/tools/cygprofile/process_profiles.py
@@ -7,6 +7,7 @@ import argparse import logging +import operator import os import sys @@ -17,6 +18,25 @@ import symbol_extractor +def _SortedFilenames(filenames): + """Returns filenames in ascending timestamp order. + + Args: + filenames: ([str]) List of filenames, matching. *-TIMESTAMP.*. + + Returns: + [str] Ordered by ascending timestamp. + """ + filename_timestamp = [] + for filename in filenames: + dash_index = filename.rindex('-') + dot_index = filename.rindex('.') + timestamp = int(filename[dash_index+1:dot_index]) + filename_timestamp.append((filename, timestamp)) + filename_timestamp.sort(key=operator.itemgetter(1)) + return [x[0] for x in filename_timestamp] + + def MergeDumps(filenames): """Merges several dumps. @@ -204,6 +224,7 @@ args = parser.parse_args() logging.info('Merging dumps') dumps = args.dumps.split(',') + sorted_dumps = _SortedFilenames(dumps) instrumented_native_lib = os.path.join(args.instrumented_build_dir, 'lib.unstripped', 'libchrome.so') @@ -211,7 +232,7 @@ 'lib.unstripped', 'libchrome.so') reached_symbols = GetReachedSymbolsFromDumpsAndMaybeWriteOffsets( - dumps, instrumented_native_lib, args.offsets_output) + sorted_dumps, instrumented_native_lib, args.offsets_output) logging.info('Reached Symbols = %d', len(reached_symbols)) total_size = sum(s.size for s in reached_symbols) logging.info('Total reached size = %d', total_size)
diff --git a/tools/cygprofile/process_profiles_unittest.py b/tools/cygprofile/process_profiles_unittest.py index c6c30c25..352643e4 100644 --- a/tools/cygprofile/process_profiles_unittest.py +++ b/tools/cygprofile/process_profiles_unittest.py
@@ -50,6 +50,14 @@ 'AnAlias': symbol_infos[0], 'Another': symbol_infos[2]}, symbol_name_to_primary) + def testSortedFilenames(self): + filenames = ['second-1234-456.txt', 'first-345345-123.txt', + 'third.bar.-789.txt'] + sorted_filenames = process_profiles._SortedFilenames(filenames) + self.assertListEqual( + ['first-345345-123.txt', 'second-1234-456.txt', 'third.bar.-789.txt'], + sorted_filenames) + if __name__ == '__main__': unittest.main()
diff --git a/tools/grit/grit/tool/toolbar_postprocess.py b/tools/grit/grit/tool/toolbar_postprocess.py deleted file mode 100755 index 3d56108..0000000 --- a/tools/grit/grit/tool/toolbar_postprocess.py +++ /dev/null
@@ -1,126 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -''' Toolbar postprocessing class. Modifies the previously processed GRD tree -by creating separate message groups for each of the IDS_COMMAND macros. -Also adds some identifiers nodes to declare specific ids to be included -in the generated grh file. -''' - -import postprocess_interface -from grit import lazy_re -import grit.node.empty -from grit.node import misc - -class ToolbarPostProcessor(postprocess_interface.PostProcessor): - ''' Defines message groups within the grd file for each of the - IDS_COMMAND stuff. - ''' - - _IDS_COMMAND = lazy_re.compile(r'IDS_COMMAND_') - _GRAB_PARAMETERS = lazy_re.compile( - r'(IDS_COMMAND_[a-zA-Z0-9]+)_([a-zA-z0-9]+)') - - def Process(self, rctext, rcpath, grdnode): - ''' Processes the data in rctext and grdnode. - Args: - rctext: string containing the contents of the RC file being processed. - rcpath: the path used to access the file. - grdnode: the root node of the grd xml data generated by - the rc2grd tool. - - Return: - The root node of the processed GRD tree. - ''' - - release = grdnode.children[2] - messages = release.children[2] - - identifiers = grit.node.empty.IdentifiersNode() - identifiers.StartParsing('identifiers', release) - identifiers.EndParsing() - release.AddChild(identifiers) - - - # - # Turn the IDS_COMMAND messages into separate message groups - # with ids that are offsetted to the message group's first id - # - previous_name_attr = '' - previous_prefix = '' - previous_node = '' - new_messages_node = self.ConstructNewMessages(release) - for node in messages.children[:]: - name_attr = node.attrs['name'] - if self._IDS_COMMAND.search(name_attr): - mo = self._GRAB_PARAMETERS.search(name_attr) - mp = self._GRAB_PARAMETERS.search(previous_name_attr) - if mo and mp: - prefix = mo.group(1) - previous_prefix = mp.group(1) - new_message_id = mp.group(2) - if prefix == previous_prefix: - messages.RemoveChild(previous_name_attr) - previous_node.attrs['offset'] = 'PCI_' + new_message_id - del previous_node.attrs['name'] - new_messages_node.AddChild(previous_node) - else: - messages.RemoveChild(previous_name_attr) - previous_node.attrs['offset'] = 'PCI_' + new_message_id - del previous_node.attrs['name'] - new_messages_node.AddChild(previous_node) - new_messages_node.attrs['first_id'] = previous_prefix - new_messages_node = self.ConstructNewMessages(release) - else: - if self._IDS_COMMAND.search(previous_name_attr): - messages.RemoveChild(previous_name_attr) - previous_prefix = mp.group(1) - new_message_id = mp.group(2) - previous_node.attrs['offset'] = 'PCI_' + new_message_id - del previous_node.attrs['name'] - new_messages_node.AddChild(previous_node) - new_messages_node.attrs['first_id'] = previous_prefix - new_messages_node = self.ConstructNewMessages(release) - else: - if self._IDS_COMMAND.search(previous_name_attr): - messages.RemoveChild(previous_name_attr) - mp = self._GRAB_PARAMETERS.search(previous_name_attr) - previous_prefix = mp.group(1) - new_message_id = mp.group(2) - previous_node.attrs['offset'] = 'PCI_' + new_message_id - del previous_node.attrs['name'] - new_messages_node.AddChild(previous_node) - new_messages_node.attrs['first_id'] = previous_prefix - new_messages_node = self.ConstructNewMessages(release) - previous_name_attr = name_attr - previous_node = node - - - self.AddIdentifiers(rctext, identifiers) - return grdnode - - def ConstructNewMessages(self, parent): - new_node = grit.node.empty.MessagesNode() - new_node.StartParsing('messages', parent) - new_node.EndParsing() - parent.AddChild(new_node) - return new_node - - def AddIdentifiers(self, rctext, node): - node.AddChild(misc.IdentifierNode.Construct(node, 'IDS_COMMAND_gcFirst', '12000', '')) - node.AddChild(misc.IdentifierNode.Construct(node, - 'IDS_COMMAND_PCI_SPACE', '16', '')) - node.AddChild(misc.IdentifierNode.Construct(node, 'PCI_BUTTON', '0', '')) - node.AddChild(misc.IdentifierNode.Construct(node, 'PCI_MENU', '1', '')) - node.AddChild(misc.IdentifierNode.Construct(node, 'PCI_TIP', '2', '')) - node.AddChild(misc.IdentifierNode.Construct(node, 'PCI_OPTIONS_TEXT', '3', '')) - node.AddChild(misc.IdentifierNode.Construct(node, 'PCI_TIP_DISABLED', '4', '')) - node.AddChild(misc.IdentifierNode.Construct(node, 'PCI_TIP_MENU', '5', '')) - node.AddChild(misc.IdentifierNode.Construct(node, 'PCI_TIP_MENU_DISABLED', '6', '')) - node.AddChild(misc.IdentifierNode.Construct(node, 'PCI_TIP_OPTIONS', '7', '')) - node.AddChild(misc.IdentifierNode.Construct(node, 'PCI_TIP_OPTIONS_DISABLED', '8', '')) - node.AddChild(misc.IdentifierNode.Construct(node, - 'PCI_TIP_DISABLED_BY_POLICY', '9', '')) -
diff --git a/tools/grit/grit/tool/toolbar_preprocess.py b/tools/grit/grit/tool/toolbar_preprocess.py deleted file mode 100755 index ff26f88..0000000 --- a/tools/grit/grit/tool/toolbar_preprocess.py +++ /dev/null
@@ -1,61 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -''' Toolbar preprocessing code. Turns all IDS_COMMAND macros in the RC file -into simpler constructs that can be understood by GRIT. Also deals with -expansion of $lf; placeholders into the correct linefeed character. -''' - -import preprocess_interface - -from grit import lazy_re - -class ToolbarPreProcessor(preprocess_interface.PreProcessor): - ''' Toolbar PreProcessing class. - ''' - - _IDS_COMMAND_MACRO = lazy_re.compile( - r'(.*IDS_COMMAND)\s*\(([a-zA-Z0-9_]*)\s*,\s*([a-zA-Z0-9_]*)\)(.*)') - _LINE_FEED_PH = lazy_re.compile(r'\$lf;') - _PH_COMMENT = lazy_re.compile(r'PHRWR') - _COMMENT = lazy_re.compile(r'^(\s*)//.*') - - - def Process(self, rctext, rcpath): - ''' Processes the data in rctext. - Args: - rctext: string containing the contents of the RC file being processed - rcpath: the path used to access the file. - - Return: - The processed text. - ''' - - ret = '' - rclines = rctext.splitlines() - for line in rclines: - - if self._LINE_FEED_PH.search(line): - # Replace "$lf;" placeholder comments by an empty line. - # this will not be put into the processed result - if self._PH_COMMENT.search(line): - mm = self._COMMENT.search(line) - if mm: - line = '%s//' % mm.group(1) - - else: - # Replace $lf by the right linefeed character - line = self._LINE_FEED_PH.sub(r'\\n', line) - - # Deal with IDS_COMMAND_MACRO stuff - mo = self._IDS_COMMAND_MACRO.search(line) - if mo: - line = '%s_%s_%s%s' % (mo.group(1), mo.group(2), mo.group(3), mo.group(4)) - - ret += (line + '\n') - - return ret - -
diff --git a/tools/mb/mb_config.pyl b/tools/mb/mb_config.pyl index 0d0a608..f1b58c9 100644 --- a/tools/mb/mb_config.pyl +++ b/tools/mb/mb_config.pyl
@@ -115,15 +115,15 @@ 'CrWinAsan(dll)': 'asan_clang_shared_v8_heap_x86_full_symbols_release', 'CrWinAsanCov': 'asan_clang_edge_fuzzer_static_v8_heap_x86_full_symbols_release', - # If CrWinClang is modified, please update CrWinClangGoma on chromium.fyi - # in the same way. - 'CrWinClang': 'clang_official_release_bot_minimal_symbols_x86', + # TODO(crbug.com/751220): These are MSVC bots. Rename the buildbots at + # some point. + 'CrWinClang': 'win_msvc_release_bot_x86', + 'CrWinClang(dbg)': 'win_msvc_debug_bot_x86', + 'CrWinClang(shared)': 'win_msvc_shared_release_bot_x86', + 'CrWinClang64': 'win_msvc_release_bot', + 'CrWinClang64(dbg)': 'win_msvc_debug_bot', + 'CrWinClang64(dll)': 'win_msvc_shared_release_bot', - 'CrWinClang(dbg)': 'clang_debug_bot_minimal_symbols_x86', - 'CrWinClang(shared)': 'clang_minimal_symbols_shared_release_bot_x86_dcheck', - 'CrWinClang64': 'clang_official_release_bot_minimal_symbols', - 'CrWinClang64(dbg)': 'win_clang_debug_bot', - 'CrWinClang64(dll)': 'clang_shared_release_bot_dcheck', 'CrWinClangLLD': 'clang_tot_official_static_use_lld_x86', 'CrWinClangLLD64': 'clang_tot_shared_release_use_lld_dcheck', 'CrWinClngLLD64dbg': 'clang_tot_full_symbols_shared_debug_use_lld', @@ -468,7 +468,7 @@ 'chromium.webrtc': { 'Linux Builder': 'release_bot_chrome_with_codecs', 'Mac Builder': 'release_bot_chrome_with_codecs', - 'Win Builder': 'release_bot_x86_minimal_symbols', + 'Win Builder': 'release_bot_x86_minimal_symbols_no_com_init_hooks', }, 'chromium.webrtc.fyi': { @@ -479,8 +479,8 @@ 'Linux Builder (dbg)': 'debug_bot', 'Mac Builder': 'release_bot_chrome_with_codecs', 'Mac Builder (dbg)': 'debug_bot', - 'Win Builder': 'release_bot_x86_minimal_symbols', - 'Win Builder (dbg)': 'debug_bot_x86_minimal_symbols', + 'Win Builder': 'release_bot_x86_minimal_symbols_no_com_init_hooks', + 'Win Builder (dbg)': 'debug_bot_x86_minimal_symbols_no_com_init_hooks', }, 'chromium.win': { @@ -1124,38 +1124,10 @@ 'clang', 'debug_trybot', 'x86', ], - 'clang_debug_bot_minimal_symbols_x86': [ - # Now that the default win bots use clang, use a "clang" bot to make sure - # things stay compilable with msvc. TODO(thakis): Having a "clang" bot - # check that is very confusing, so rename to "msvc", crbug.com/751220 - 'no_clang', 'debug_bot', 'minimal_symbols', 'x86', - ], - 'clang_release_bot_minimal_symbols_x86': [ 'clang', 'release_bot', 'minimal_symbols', 'x86', ], - 'clang_minimal_symbols_shared_release_bot_x86_dcheck': [ - # Now that the default win bots use clang, use a "clang" bot to make sure - # things stay compilable with msvc. TODO(thakis): Having a "clang" bot - # check that is very confusing, so rename to "msvc", crbug.com/751220 - 'no_clang', 'minimal_symbols', 'shared_release_bot', 'x86', 'dcheck_always_on', - ], - - 'clang_official_release_bot_minimal_symbols': [ - # Now that the default win bots use clang, use a "clang" bot to make sure - # things stay compilable with msvc. TODO(thakis): Having a "clang" bot - # check that is very confusing, so rename to "msvc", crbug.com/751220 - 'no_clang', 'official', 'release_bot', 'minimal_symbols', - ], - - 'clang_official_release_bot_minimal_symbols_x86': [ - # Now that the default win bots use clang, use a "clang" bot to make sure - # things stay compilable with msvc. TODO(thakis): Having a "clang" bot - # check that is very confusing, so rename to "msvc", crbug.com/751220 - 'no_clang', 'official', 'release_bot', 'minimal_symbols', 'x86', - ], - 'clang_official_release_bot_minimal_symbols_x86_clang': [ # force clang enabled for clang_official_release_bot_minimal_symbols_x86 # for CrWinClangGoma @@ -1171,13 +1143,6 @@ 'clang', 'official', 'release_trybot', 'x86', ], - 'clang_shared_release_bot_dcheck': [ - # Now that the default win bots use clang, use a "clang" bot to make sure - # things stay compilable with msvc. TODO(thakis): Having a "clang" bot - # check that is very confusing, so rename to "msvc", crbug.com/751220 - 'no_clang', 'shared_release_bot', 'dcheck_always_on', - ], - 'clang_tot_asan_lsan_static_release': [ 'clang_tot', 'asan', 'lsan', 'static', 'release', ], @@ -1315,6 +1280,10 @@ 'debug_bot_minimal_symbols': [ 'debug_bot', 'minimal_symbols' ], 'debug_bot_x86_minimal_symbols': [ 'debug_bot', 'x86', 'minimal_symbols' ], + 'debug_bot_x86_minimal_symbols_no_com_init_hooks': [ + 'debug_bot', 'x86', 'minimal_symbols', 'no_com_init_hooks' + ], + 'debug_libfuzzer_asan': [ 'debug', 'libfuzzer', 'asan', 'chromeos_codecs', 'pdf_xfa', 'disable_nacl', ], @@ -1587,6 +1556,10 @@ 'release_bot_minimal_symbols': [ 'release_bot', 'minimal_symbols' ], 'release_bot_x86_minimal_symbols': [ 'release_bot', 'x86', 'minimal_symbols' ], + 'release_bot_x86_minimal_symbols_no_com_init_hooks': [ + 'release_bot', 'x86', 'minimal_symbols', 'no_com_init_hooks' + ], + # TODO(tikuta): Remove this once gcp goma backend supports all windows nacl compilers. 'release_bot_x86_minimal_symbols_disable_nacl_no_clang': [ 'release_bot_x86_minimal_symbols_disable_nacl', 'no_clang' @@ -1719,11 +1692,27 @@ ], 'win_msvc_release_bot': [ - 'no_clang', 'release_bot', 'minimal_symbols', + 'no_clang', 'minimal_symbols', 'release_bot', + ], + + 'win_msvc_release_bot_x86': [ + 'no_clang', 'minimal_symbols', 'release_bot', 'x86', ], 'win_msvc_debug_bot': [ - 'no_clang', 'debug_bot', 'minimal_symbols', + 'no_clang', 'minimal_symbols', 'debug_bot', + ], + + 'win_msvc_debug_bot_x86': [ + 'no_clang', 'minimal_symbols', 'debug_bot', 'x86', + ], + + 'win_msvc_shared_release_bot': [ + 'no_clang', 'minimal_symbols', 'shared_release_bot', 'dcheck_always_on', + ], + + 'win_msvc_shared_release_bot_x86': [ + 'no_clang', 'minimal_symbols', 'shared_release_bot', 'dcheck_always_on', 'x86', ], # TODO(tikuta): Remove this once gcp goma backend supports all windows nacl compilers. @@ -2017,6 +2006,10 @@ 'gn_args': 'android_ndk_version="r13b" android_ndk_major_version=13', }, + 'no_com_init_hooks': { + 'gn_args': 'com_init_check_hook_disabled=true', + }, + 'no_gnome_keyring': { 'gn_args': 'use_gnome_keyring=false', },
diff --git a/tools/metrics/actions/actions.xml b/tools/metrics/actions/actions.xml index 9ce1eab..7c0e0cb2 100644 --- a/tools/metrics/actions/actions.xml +++ b/tools/metrics/actions/actions.xml
@@ -5409,6 +5409,9 @@ </action> <action name="Hotword.HotwordTrigger"> + <obsolete> + Deprecated as of 10/2017. Feature removed with crbug/761426. + </obsolete> <owner>amistry@chromium.org</owner> <owner>rlp@chromium.org</owner> <owner>somast@chromium.org</owner>
diff --git a/tools/metrics/actions/extract_actions.py b/tools/metrics/actions/extract_actions.py index 04d938d2..c572f7b 100755 --- a/tools/metrics/actions/extract_actions.py +++ b/tools/metrics/actions/extract_actions.py
@@ -286,9 +286,6 @@ actions.add('ConnectivityDiagnostics.UA.TestResultExpanded') actions.add('ConnectivityDiagnostics.UA.TestSuiteRun') - # Actions sent by 'Ok Google' Hotwording. - actions.add('Hotword.HotwordTrigger') - class InvalidStatementException(Exception): """Indicates an invalid statement was found."""
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 4adaade1..6f08098 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -1840,6 +1840,10 @@ <int value="25" label="Kerberos ticket expired while renewing credentials"/> <int value="26" label="klist exited with unspecified error"/> <int value="27" label="kinit failed because of bad machine name."/> + <int value="28" label="New password was rejected during password change."/> + <int value="29" + label="Could not store device policy since install attributes are not + locked yet; stored policy in cache instead."/> </enum> <enum name="AutocheckoutBubble"> @@ -2269,6 +2273,12 @@ label="Submitted with unknown card without selecting suggestions (once)"/> <int value="23" label="Submitted with no card without selecting suggestions (once)"/> + <int value="24" + label="Submitted with wrong-length card without selecting suggestions + (once)"/> + <int value="25" + label="Submitted with fail-luhn-check card without selecting + suggestions (once)"/> </enum> <enum name="AutofillFormSubmittedState"> @@ -3756,6 +3766,11 @@ <int value="1" label="Panel was open"/> </enum> +<enum name="BooleanPasswordSavedWithFallback"> + <int value="0" label="Automatic prompt"/> + <int value="1" label="Manual fallback"/> +</enum> + <enum name="BooleanPending"> <int value="0" label="Decided"/> <int value="1" label="Pending"/> @@ -8359,6 +8374,13 @@ <int value="3" label="NeedInjectEntropy"/> </enum> +<enum name="DetachableBasePendingRWUpdate"> + <int value="0" label="CommunicationError"/> + <int value="1" label="NoUpdate"/> + <int value="2" label="CriticalUpdate"/> + <int value="3" label="NonCriticalUpdate"/> +</enum> + <enum name="DetachableBaseROUpdateResult"> <int value="1" label="Succeeded"/> <int value="2" label="TransferFailed"/> @@ -21325,6 +21347,9 @@ <int value="2" label="InternalsPage"> A forced close was requested from the indexeddb-internals page. </int> + <int value="3" label="CopyOrigin"> + The database is force closed so that it can be copied. + </int> </enum> <enum name="IDBException"> @@ -22480,6 +22505,13 @@ <int value="1" label="Remote suggestions"/> </enum> +<enum name="IOSPageLoadCountNavigationType"> + <int value="0" label="Chrome URL Navigation"/> + <int value="1" label="Same Document Web Navigation"/> + <int value="2" label="Page Load Navigation"/> + <int value="3" label="Obsolete - Loading Started"/> +</enum> + <enum name="IOSRepeatedExternalAppPromptResponse"> <int value="0" label="Blocked"> User selected to block the application for the current session. @@ -43088,9 +43120,9 @@ <enum name="VRUnsupportedMode"> <int value="0" label="Unhandled code point in URL"/> - <int value="1" label="Could not elide URL"/> + <int value="1" label="Could not elide URL (obsolete)"/> <int value="2" label="Unhandled PageInfo"/> - <int value="3" label="URL contained strong RTL chars"/> + <int value="3" label="URL contained strong RTL chars (obsolete)"/> <int value="4" label="Chrome needs audio permission for voice input"/> </enum>
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index 73e4c66..83aba22 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -10527,6 +10527,16 @@ </summary> </histogram> +<histogram + name="Compositing.SurfaceAggregator.SurfaceDrawQuad.UsingFallbackSurface"> + <owner>fsamuel@chromium.org</owner> + <summary> + The number of SurfaceDrawQuads where the primary SurfaceId doe not have a + corresponding active CompositorFrame and so the fallback surface is used + instead. This is logged for each call to Aggregate(). + </summary> +</histogram> + <histogram name="Compositing.SurfaceAggregator.SurfaceDrawQuad.ValidSurface"> <owner>kylechar@chromium.org</owner> <summary> @@ -10535,6 +10545,24 @@ </summary> </histogram> +<histogram name="Compositing.SurfaceDependencyDeadline.DeadlineHit" + units="Boolean"> + <owner>fsamuel@chromium.org</owner> + <summary> + Tracks whether an activation of a surface was due to due to a deadline or + the resolution of dependencies. + </summary> +</histogram> + +<histogram name="Compositing.SurfaceDependencyDeadline.Duration" units="ms"> + <owner>fsamuel@chromium.org</owner> + <summary> + The amount of time it took for a Surface with unresolved dependencies to + activate. Note that some activations may be triggered due to a deadline + hitting. That is tracked in the DeadlineHit histogram. + </summary> +</histogram> + <histogram name="Compositing.SurfaceManager.NumOldTemporaryReferences"> <owner>kylechar@chromium.org</owner> <summary> @@ -28216,6 +28244,9 @@ </histogram> <histogram name="Hotword.AudioLoggingEnabled" enum="BooleanEnabled"> + <obsolete> + Deprecated as of 10/2017. Feature removed with crbug/761426. + </obsolete> <owner>rlp@chromium.org</owner> <summary> The state of the hotword audio logging preference. This value is emitted @@ -28226,6 +28257,9 @@ </histogram> <histogram name="Hotword.Enabled" enum="HotwordPrefState"> + <obsolete> + Deprecated as of 10/2017. Feature removed with crbug/761426. + </obsolete> <owner>rlp@chromium.org</owner> <summary> The state of the hotword preference. This value is emitted during @@ -28234,6 +28268,9 @@ </histogram> <histogram name="Hotword.ExtensionAvailability" enum="HotwordAvailability"> + <obsolete> + Deprecated as of 10/2017. Feature removed with crbug/761426. + </obsolete> <owner>rlp@chromium.org</owner> <summary> Whether the external component hotword extension exists (i.e., not pending @@ -28244,6 +28281,9 @@ </histogram> <histogram name="Hotword.HotwordError" enum="HotwordError"> + <obsolete> + Deprecated as of 10/2017. Feature removed with crbug/761426. + </obsolete> <owner>rlp@chromium.org</owner> <summary> Errors reported by the hotword service when determining if hotwording is @@ -28254,6 +28294,9 @@ <histogram name="Hotword.HotwordMediaStreamResult" enum="HotwordMediaStreamResult"> + <obsolete> + Deprecated as of 10/2017. Feature removed with crbug/761426. + </obsolete> <owner>amistry@chromium.org</owner> <owner>rlp@chromium.org</owner> <owner>somast@chromium.org</owner> @@ -28265,6 +28308,9 @@ <histogram name="Hotword.HotwordNaClMessageTimeout" enum="HotwordNaClMessageTimeout"> + <obsolete> + Deprecated as of 10/2017. Feature removed with crbug/761426. + </obsolete> <owner>amistry@chromium.org</owner> <owner>rlp@chromium.org</owner> <owner>somast@chromium.org</owner> @@ -28277,6 +28323,9 @@ <histogram name="Hotword.HotwordNaClPluginLoadResult" enum="HotwordNaClPluginLoadResult"> + <obsolete> + Deprecated as of 10/2017. Feature removed with crbug/761426. + </obsolete> <owner>amistry@chromium.org</owner> <owner>rlp@chromium.org</owner> <owner>somast@chromium.org</owner> @@ -28286,6 +28335,9 @@ </histogram> <histogram name="Hotword.HotwordTriggerSource" enum="HotwordTriggerSource"> + <obsolete> + Deprecated as of 10/2017. Feature removed with crbug/761426. + </obsolete> <owner>amistry@chromium.org</owner> <owner>rlp@chromium.org</owner> <owner>somast@chromium.org</owner> @@ -28296,6 +28348,9 @@ </histogram> <histogram name="Hotword.SharedModuleReinstallLanguage" enum="LanguageCode"> + <obsolete> + Deprecated as of 10/2017. Feature removed with crbug/761426. + </obsolete> <owner>amistry@chromium.org</owner> <owner>rlp@chromium.org</owner> <owner>somast@chromium.org</owner> @@ -30446,6 +30501,32 @@ </summary> </histogram> +<histogram name="IOS.PageLoadCount.Counts" + enum="IOSPageLoadCountNavigationType"> + <owner>danyao@chromium.org</owner> + <summary>The number of navigation started events by navigation type.</summary> +</histogram> + +<histogram name="IOS.PageLoadCount.LoadingStarted"> + <owner>danyao@chromium.org</owner> + <summary> + The "true" value of this boolean histogram counts the number of + page loading started events. The "false" value will never be seen. + </summary> +</histogram> + +<histogram name="IOS.PageLoadCountMigration.Counts" + enum="IOSPageLoadCountNavigationType"> + <obsolete> + Deprecated 2017-11. + </obsolete> + <owner>danyao@chromium.org</owner> + <summary> + Counts different types of navigation and loading events that are relevant to + counting page loads. + </summary> +</histogram> + <histogram name="IOS.PageLoadTiming.OmnibarToPageLoaded" units="ms"> <owner>danyao@chromium.org</owner> <summary> @@ -34242,6 +34323,9 @@ </histogram> <histogram name="Media.Remoting.CapacityOverMediaBitrate" units="kbps"> + <obsolete> + Deprecated 11/2017 in issue 788940. + </obsolete> <owner>miu@chromium.org</owner> <summary> The difference between the estimated transmission capacity and the media @@ -34250,6 +34334,9 @@ </histogram> <histogram name="Media.Remoting.MediaBitrateOverCapacity" units="kbps"> + <obsolete> + Deprecated 11/2017 in issue 788940. + </obsolete> <owner>miu@chromium.org</owner> <summary> The difference between the media bitrate and the estimated transmission @@ -34307,6 +34394,9 @@ </histogram> <histogram name="Media.Remoting.StartMediaBitrate" units="kbps"> + <obsolete> + Deprecated 11/2017 in issue 788940. + </obsolete> <owner>miu@chromium.org</owner> <summary> The estimated content bitrate (including both audio and video) when starting @@ -34337,6 +34427,9 @@ </histogram> <histogram name="Media.Remoting.TransmissionCapacity" units="kbps"> + <obsolete> + Deprecated 11/2017 in issue 788940. + </obsolete> <owner>miu@chromium.org</owner> <summary> The estimated transmission capacity when starting a remoting session. @@ -58790,6 +58883,15 @@ </summary> </histogram> +<histogram name="PasswordManager.PasswordSavedWithManualFallback" + enum="BooleanPasswordSavedWithFallback"> + <owner>kolos@chromium.org</owner> + <summary> + Measures whether users save passwords with automatic prompt or manual + fallback. + </summary> +</histogram> + <histogram name="PasswordManager.PasswordSyncState" enum="PasswordSyncState"> <owner>gcasto@chromium.org</owner> <owner>rouslan@chromium.org</owner> @@ -58799,6 +58901,15 @@ </summary> </histogram> +<histogram name="PasswordManager.PasswordUpdatedWithManualFallback" + enum="BooleanPasswordSavedWithFallback"> + <owner>kolos@chromium.org</owner> + <summary> + Measures whether users update passwords with automatic prompt or manual + fallback. + </summary> +</histogram> + <histogram name="PasswordManager.ProvisionalSaveFailure" enum="ProvisionalSaveFailure"> <owner>vabr@chromium.org</owner> @@ -60610,6 +60721,23 @@ <summary>Result of a detachable base pair operation.</summary> </histogram> +<histogram name="Platform.DetachableBase.PendingRWUpdate" + enum="DetachableBasePendingRWUpdate"> + <owner>kitching@google.com</owner> + <summary> + Detachable base firmware updates can be configured to only occur on boot. In + this mode, any update will be considered "pending" until the + system is rebooted, at which point the update may take place. Every time a + detachable base is connected to the system, a metric representing the + pending update status is recorded. Its possible values are as follows: (0) + communication error; (1) no update available; (2) critical update available; + or (3) non-critical update available. The definition of + "critical" is up to the software performing updates, and would + typically be used in the case of a security issue, or broken functionality + in a previous firmware version. + </summary> +</histogram> + <histogram name="Platform.DetachableBase.ROUpdateResult" enum="DetachableBaseROUpdateResult"> <owner>kitching@google.com</owner> @@ -72651,6 +72779,17 @@ </summary> </histogram> +<histogram name="SB2.RemoteCall.CheckDelta" units="microseconds"> + <owner>csharrison@chromium.org</owner> + <owner>vakh@chromium.org</owner> + <summary> + The microseconds between sending the Safe Browsing API call and receiving + the response. Logged in java code and does not include any thread hops or + extra work. Note that this does include task queue time to respond to the + IPC (and that queue time is often non-trivial). + </summary> +</histogram> + <histogram name="SB2.RemoteCall.ChecksPending" units="calls"> <obsolete> Deprecated in M64 (Nov 2017). No longer generated. @@ -72924,6 +73063,15 @@ </summary> </histogram> +<histogram name="SBClientDownload.DmgFileArchivedBinariesCount" units="count"> + <owner>nparker@chromium.org</owner> + <summary> + The original number of archived_binaries found in a DMG-like file when it's + scanned, if at least one is found. The actual number sent in the download + request may be capped below this value. + </summary> +</histogram> + <histogram name="SBClientDownload.DmgFileFailureByType" enum="SBClientDownloadExtensions"> <owner>nparker@chromium.org</owner> @@ -73180,6 +73328,15 @@ </summary> </histogram> +<histogram name="SBClientDownload.ZipFileArchivedBinariesCount" units="count"> + <owner>nparker@chromium.org</owner> + <summary> + The original number of archived_binaries found in a zip-like file when it's + scanned, if at least one is found. The actual number sent in the download + request may be capped below this value. + </summary> +</histogram> + <histogram name="SBClientDownload.ZipFileContainsAppDirectory" enum="Boolean"> <owner>jialiul@chromium.org</owner> <summary> @@ -74330,6 +74487,17 @@ </summary> </histogram> +<histogram name="Scheduling.ImageInvalidationUpdateDuration" + units="microseconds"> + <owner>khushalsagar@chromium.org</owner> + <summary> + Duration for updating animated images and invalidating layers for images + invalidated on the sync tree in the compositor. This interval is recorded + each time the sync tree is updated after a commit or an impl-side + invalidation. + </summary> +</histogram> + <histogram name="Scheduling.InvalidationToReadyToActivateDuration2" units="microseconds"> <owner>brianderson@chromium.org</owner> @@ -89289,6 +89457,14 @@ </summary> </histogram> +<histogram name="UI.CompositorResizeLock.TimedOut" units="Boolean"> + <owner>fsamuel@chromium.org</owner> + <summary> + Tracks whether the CompositorResizeLock is being released due to timing out + or not. + </summary> +</histogram> + <histogram name="UI.DeviceScale" units="%"> <owner>bsep@chromium.org</owner> <summary> @@ -89390,12 +89566,30 @@ </summary> </histogram> -<histogram name="UKM.Sources.SerializedCount"> +<histogram name="UKM.Sources.KeptSourcesCount" units="sources"> + <owner>asvitkine@chromium.org</owner> + <owner>bmcquade@chromium.org</owner> + <summary> + Number of unsent UKM sources that were kept in-memory to be potentially + transmitted in the next log. + </summary> +</histogram> + +<histogram name="UKM.Sources.SerializedCount" units="sources"> <owner>holte@chromium.org</owner> <owner>rkaplow@chromium.org</owner> <summary>Number of serialized UKM sources when storing a UKM log.</summary> </histogram> +<histogram name="UKM.Sources.UnsentSourcesCount" units="sources"> + <owner>asvitkine@chromium.org</owner> + <owner>bmcquade@chromium.org</owner> + <summary> + Number of UKM sources that were not sent because they had no associated + entries. + </summary> +</histogram> + <histogram name="UKM.UnsentLogs.DroppedSize" units="bytes"> <owner>holte@chromium.org</owner> <owner>rkaplow@chromium.org</owner> @@ -95352,6 +95546,15 @@ </summary> </histogram> +<histogram name="WebRTC.Audio.EchoCanceller.Erl" units="dB (shifted)"> + <owner>gustaf@chromium.org</owner> + <summary> + This histogram logs the echo return loss achieved by the WebRTC echo + canceller as described in ITU G.168. When the echo canceller is being used, + one value is logged every 10 seconds per ongoing WebRTC call. + </summary> +</histogram> + <histogram name="WebRTC.Audio.EchoCanceller.ErlBand0" units="dB (shifted)"> <owner>peah@chromium.org</owner> <summary> @@ -95368,6 +95571,15 @@ </summary> </histogram> +<histogram name="WebRTC.Audio.EchoCanceller.Erle" units="dB"> + <owner>gustaf@chromium.org</owner> + <summary> + This histogram logs the echo return loss enhancement achieved by the WebRTC + echo canceller as described in ITU G.168. When the echo canceller is being + used, one value is logged every 10 seconds per ongoing WebRTC call. + </summary> +</histogram> + <histogram name="WebRTC.Audio.EchoCanceller.ErleBand0" units="dB (shifted)"> <owner>peah@chromium.org</owner> <summary> @@ -95558,6 +95770,14 @@ </summary> </histogram> +<histogram name="WebRTC.Audio.TargetJitterBufferDelayMs" units="ms"> + <owner>hlundin@chromium.org</owner> + <summary> + The target jitter buffer delay for the receiving side. Sampled once every 10 + ms per WebRTC receive stream when WebRTC audio is playing. + </summary> +</histogram> + <histogram name="WebRTC.AudioCaptureTime" units="ms"> <obsolete> Removed from code 2014/2/25. @@ -99255,6 +99475,7 @@ ordering="prefix"> <suffix name="Browser"/> <suffix name="Renderer"/> + <affected-histogram name="Scheduling.ImageInvalidationUpdateDuration"/> <affected-histogram name="Scheduling.PendingTreeDuration"/> <affected-histogram name="Scheduling.PendingTreeRasterDuration"/> </histogram_suffixes> @@ -101682,9 +101903,10 @@ </histogram_suffixes> <histogram_suffixes name="JSDialogs.DialogType" separator="."> - <suffix name="Alert"/> - <suffix name="Confirm"/> - <suffix name="Prompt"/> + <suffix name="Alert" label="window.alert() dialog"/> + <suffix name="Confirm" label="window.confirm() dialog"/> + <suffix name="Prompt" label="window.prompt() dialog"/> + <suffix name="BeforeUnload" label="dialog caused by window.onbeforeunload"/> <affected-histogram name="JSDialogs.DismissalCause"/> <affected-histogram name="JSDialogs.IsForemost"/> <affected-histogram name="JSDialogs.Scheme"/> @@ -108809,6 +109031,14 @@ <affected-histogram name="WebFont.DownloadTime.1.10KBTo50KB"/> </histogram_suffixes> +<histogram_suffixes name="WebRTCEchoCancellerEstimate" separator="."> + <suffix name="Value" label="The last estimated value of the time interval"/> + <suffix name="Max" label="The maximum over the time interval"/> + <suffix name="Min" label="The minimum over the time interval"/> + <affected-histogram name="WebRTC.Audio.EchoCanceller.Erl"/> + <affected-histogram name="WebRTC.Audio.EchoCanceller.Erle"/> +</histogram_suffixes> + <histogram_suffixes name="WebRTCEchoCancellerStatisticType" separator="."> <suffix name="Average" label="The average over the time interval"/> <suffix name="Max" label="The maximum over the time interval"/>
diff --git a/tools/metrics/ukm/ukm.xml b/tools/metrics/ukm/ukm.xml index 9d94efc7..aff47ed 100644 --- a/tools/metrics/ukm/ukm.xml +++ b/tools/metrics/ukm/ukm.xml
@@ -674,6 +674,22 @@ </metric> </event> +<event name="Media.Engagement.ShortPlaybackIgnored"> + <owner>beccahughes@chromium.org</owner> + <owner>media-dev@chromium.org</owner> + <summary> + The Media Engagement index stores the number of significant media playbacks + per origin and the number of audible players. From that we calculate a Media + Engagement Score. + + Media with a short playback length is ignored so we are logging any time the + player is ignored with the length in msec. This will allow us to identify + whether sites are being penalized or there is abuse and allow us to tweak + the length considered "short". + </summary> + <metric name="Length"/> +</event> + <event name="Media.Engagement.SessionFinished"> <owner>beccahughes@chromium.org</owner> <owner>media-dev@chromium.org</owner> @@ -689,7 +705,12 @@ <metric name="Engagement.IsHigh"/> <metric name="Engagement.Score"/> <metric name="Playbacks.Delta"/> + <metric name="Playbacks.SecondsSinceLast"/> <metric name="Playbacks.Total"/> + <metric name="Player.Audible.Delta"/> + <metric name="Player.Audible.Total"/> + <metric name="Player.Significant.Delta"/> + <metric name="Player.Significant.Total"/> <metric name="Visits.Total"/> </event>
diff --git a/tools/perf/benchmarks/v8_browsing.py b/tools/perf/benchmarks/v8_browsing.py index 68f8251..dd5a7a9 100644 --- a/tools/perf/benchmarks/v8_browsing.py +++ b/tools/perf/benchmarks/v8_browsing.py
@@ -122,6 +122,10 @@ 'browse:tools:maps', [story.expectations.ALL_MAC], 'crbug.com/773084') + self.DisableStory( + 'browse:media:imgur', + [story.expectations.ALL_LINUX], + 'crbug.com/788796') return StoryExpectations() def SetExtraBrowserOptions(self, options):
diff --git a/tools/perf/contrib/leak_detection/leak_detection.py b/tools/perf/contrib/leak_detection/leak_detection.py index 6e3c906..01925b5a 100644 --- a/tools/perf/contrib/leak_detection/leak_detection.py +++ b/tools/perf/contrib/leak_detection/leak_detection.py
@@ -24,6 +24,9 @@ tbm_options.AddTimelineBasedMetric('leakDetectionMetric') return tbm_options + def CustomizeBrowserOptions(self, options): + options.AppendExtraBrowserArgs('--js-flags=--expose-gc') + @benchmark.Owner(emails=['yuzus@chromium.org']) class MemoryLeakDetectionBenchmark(_LeakDetectionBase):
diff --git a/ui/accessibility/BUILD.gn b/ui/accessibility/BUILD.gn index 6bd91df..5337ae74c 100644 --- a/ui/accessibility/BUILD.gn +++ b/ui/accessibility/BUILD.gn
@@ -176,6 +176,8 @@ "ax_tree_combiner_unittest.cc", "ax_tree_serializer_unittest.cc", "ax_tree_unittest.cc", + "platform/ax_platform_node_unittest.cc", + "platform/ax_platform_node_unittest.h", "platform/ax_platform_node_win_unittest.cc", ]
diff --git a/ui/accessibility/ax_enums.idl b/ui/accessibility/ax_enums.idl index bbdf85e..4615dfc 100644 --- a/ui/accessibility/ax_enums.idl +++ b/ui/accessibility/ax_enums.idl
@@ -498,7 +498,11 @@ scrollable, // A hint to clients that the node is clickable. - clickable + clickable, + + // Indicates that this node clips its children, i.e. may have + // overflow: hidden or clip children by default. + clips_children }; [cpp_enum_prefix_override="ax_attr"] enum AXIntListAttribute {
diff --git a/ui/accessibility/ax_node_data.cc b/ui/accessibility/ax_node_data.cc index a9ac738..f212a38 100644 --- a/ui/accessibility/ax_node_data.cc +++ b/ui/accessibility/ax_node_data.cc
@@ -946,6 +946,9 @@ case AX_ATTR_CLICKABLE: result += " clickable=" + value; break; + case AX_ATTR_CLIPS_CHILDREN: + result += " clips_children=" + value; + break; case AX_BOOL_ATTRIBUTE_NONE: break; }
diff --git a/ui/accessibility/ax_tree.cc b/ui/accessibility/ax_tree.cc index 66739ee..90dfa7d 100644 --- a/ui/accessibility/ax_tree.cc +++ b/ui/accessibility/ax_tree.cc
@@ -256,8 +256,8 @@ } } - if (container->data().role != ui::AX_ROLE_DESKTOP && clipped.IsEmpty() && - !bounds.IsEmpty()) { + if (container->data().GetBoolAttribute(ui::AX_ATTR_CLIPS_CHILDREN) && + clipped.IsEmpty() && !bounds.IsEmpty()) { // If it is offscreen with respect to its parent, and the node itself is // not empty, label it offscreen. // Here we are extending the definition of offscreen to include elements
diff --git a/ui/accessibility/ax_tree_unittest.cc b/ui/accessibility/ax_tree_unittest.cc index 789f674..d75581c1 100644 --- a/ui/accessibility/ax_tree_unittest.cc +++ b/ui/accessibility/ax_tree_unittest.cc
@@ -843,6 +843,7 @@ tree_update.nodes[0].id = 1; tree_update.nodes[0].location = gfx::RectF(0, 0, 800, 600); tree_update.nodes[0].role = AX_ROLE_ROOT_WEB_AREA; + tree_update.nodes[0].AddBoolAttribute(ui::AX_ATTR_CLIPS_CHILDREN, true); tree_update.nodes[0].child_ids.push_back(2); tree_update.nodes[1].id = 2; tree_update.nodes[1].location = gfx::RectF(); // Deliberately empty. @@ -936,6 +937,7 @@ tree_update.nodes.resize(3); tree_update.nodes[0].id = 1; tree_update.nodes[0].location = gfx::RectF(0, 0, 800, 600); + tree_update.nodes[1].AddBoolAttribute(ui::AX_ATTR_CLIPS_CHILDREN, true); tree_update.nodes[0].child_ids.push_back(2); tree_update.nodes[1].id = 2; tree_update.nodes[1].location = gfx::RectF(300, 200, 100, 100); @@ -983,6 +985,41 @@ EXPECT_EQ("(50, 599) size (150 x 1)", GetBoundsAsString(tree, 5)); } +TEST(AXTreeTest, GetBoundsSetsOffscreenIfClipsChildren) { + AXTreeUpdate tree_update; + tree_update.root_id = 1; + tree_update.nodes.resize(5); + tree_update.nodes[0].id = 1; + tree_update.nodes[0].location = gfx::RectF(0, 0, 800, 600); + tree_update.nodes[0].AddBoolAttribute(ui::AX_ATTR_CLIPS_CHILDREN, true); + tree_update.nodes[0].child_ids.push_back(2); + tree_update.nodes[0].child_ids.push_back(3); + + tree_update.nodes[1].id = 2; + tree_update.nodes[1].location = gfx::RectF(0, 0, 200, 200); + tree_update.nodes[1].AddBoolAttribute(ui::AX_ATTR_CLIPS_CHILDREN, true); + tree_update.nodes[1].child_ids.push_back(4); + + tree_update.nodes[2].id = 3; + tree_update.nodes[2].location = gfx::RectF(0, 0, 200, 200); + tree_update.nodes[2].child_ids.push_back(5); + + // Clipped by its parent + tree_update.nodes[3].id = 4; + tree_update.nodes[3].location = gfx::RectF(250, 250, 100, 100); + tree_update.nodes[3].offset_container_id = 2; + + // Outside of its parent, but its parent does not clip children, + // so it should not be offscreen. + tree_update.nodes[4].id = 5; + tree_update.nodes[4].location = gfx::RectF(250, 250, 100, 100); + tree_update.nodes[4].offset_container_id = 3; + + AXTree tree(tree_update); + EXPECT_TRUE(IsNodeOffscreen(tree, 4)); + EXPECT_FALSE(IsNodeOffscreen(tree, 5)); +} + TEST(AXTreeTest, GetBoundsUpdatesOffscreen) { AXTreeUpdate tree_update; tree_update.root_id = 1; @@ -990,6 +1027,7 @@ tree_update.nodes[0].id = 1; tree_update.nodes[0].location = gfx::RectF(0, 0, 800, 600); tree_update.nodes[0].role = AX_ROLE_ROOT_WEB_AREA; + tree_update.nodes[0].AddBoolAttribute(ui::AX_ATTR_CLIPS_CHILDREN, true); tree_update.nodes[0].child_ids.push_back(2); tree_update.nodes[0].child_ids.push_back(3); tree_update.nodes[0].child_ids.push_back(4);
diff --git a/ui/accessibility/platform/ax_platform_node_auralinux.cc b/ui/accessibility/platform/ax_platform_node_auralinux.cc index 793d6935..258fd0c 100644 --- a/ui/accessibility/platform/ax_platform_node_auralinux.cc +++ b/ui/accessibility/platform/ax_platform_node_auralinux.cc
@@ -547,6 +547,8 @@ if (!obj) return; + memset(value, 0, sizeof(*value)); + g_value_init(value, G_TYPE_FLOAT); g_value_set_float(value, obj->GetStepAttribute()); } @@ -1232,7 +1234,7 @@ void AXPlatformNodeAuraLinux::GetFloatAttributeInGValue(AXFloatAttribute attr, GValue* value) { float float_val; - if (GetFloatAttribute(ui::AX_ATTR_MAX_VALUE_FOR_RANGE, &float_val)) { + if (GetFloatAttribute(attr, &float_val)) { memset(value, 0, sizeof(*value)); g_value_init(value, G_TYPE_FLOAT); g_value_set_float(value, float_val);
diff --git a/ui/accessibility/platform/ax_platform_node_unittest.cc b/ui/accessibility/platform/ax_platform_node_unittest.cc new file mode 100644 index 0000000..de42471 --- /dev/null +++ b/ui/accessibility/platform/ax_platform_node_unittest.cc
@@ -0,0 +1,257 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ui/accessibility/platform/ax_platform_node_unittest.h" + +namespace ui { + +AXPlatformNodeTest::AXPlatformNodeTest() {} + +AXPlatformNodeTest::~AXPlatformNodeTest() {} + +void AXPlatformNodeTest::Init(const AXTreeUpdate& initial_state) { + tree_.reset(new AXTree(initial_state)); +} + +void AXPlatformNodeTest::Init(const AXNodeData& node1) { + AXTreeUpdate update; + update.root_id = node1.id; + update.nodes.push_back(node1); + Init(update); +} + +void AXPlatformNodeTest::Init(const AXNodeData& node1, + const AXNodeData& node2) { + AXTreeUpdate update; + update.root_id = node1.id; + update.nodes.push_back(node1); + update.nodes.push_back(node2); + Init(update); +} + +void AXPlatformNodeTest::Init(const AXNodeData& node1, + const AXNodeData& node2, + const AXNodeData& node3) { + AXTreeUpdate update; + update.root_id = node1.id; + update.nodes.push_back(node1); + update.nodes.push_back(node2); + update.nodes.push_back(node3); + Init(update); +} + +void AXPlatformNodeTest::Init(const AXNodeData& node1, + const AXNodeData& node2, + const AXNodeData& node3, + const AXNodeData& node4) { + AXTreeUpdate update; + update.root_id = node1.id; + update.nodes.push_back(node1); + update.nodes.push_back(node2); + update.nodes.push_back(node3); + update.nodes.push_back(node4); + Init(update); +} + +AXTreeUpdate AXPlatformNodeTest::BuildTextField() { + AXNodeData text_field_node; + text_field_node.id = 1; + text_field_node.role = AX_ROLE_TEXT_FIELD; + text_field_node.AddState(AX_STATE_EDITABLE); + text_field_node.SetValue("How now brown cow."); + + AXTreeUpdate update; + update.root_id = text_field_node.id; + update.nodes.push_back(text_field_node); + return update; +} + +AXTreeUpdate AXPlatformNodeTest::BuildTextFieldWithSelectionRange( + int32_t start, + int32_t stop) { + AXNodeData text_field_node; + text_field_node.id = 1; + text_field_node.role = AX_ROLE_TEXT_FIELD; + text_field_node.AddState(AX_STATE_EDITABLE); + text_field_node.AddState(AX_STATE_SELECTED); + text_field_node.AddIntAttribute(ui::AX_ATTR_TEXT_SEL_START, start); + text_field_node.AddIntAttribute(ui::AX_ATTR_TEXT_SEL_END, stop); + text_field_node.SetValue("How now brown cow."); + + AXTreeUpdate update; + update.root_id = text_field_node.id; + update.nodes.push_back(text_field_node); + return update; +} + +AXTreeUpdate AXPlatformNodeTest::BuildContentEditable() { + AXNodeData content_editable_node; + content_editable_node.id = 1; + content_editable_node.role = AX_ROLE_GROUP; + content_editable_node.AddState(AX_STATE_RICHLY_EDITABLE); + content_editable_node.AddBoolAttribute(ui::AX_ATTR_EDITABLE_ROOT, true); + content_editable_node.SetValue("How now brown cow."); + + AXTreeUpdate update; + update.root_id = content_editable_node.id; + update.nodes.push_back(content_editable_node); + return update; +} + +AXTreeUpdate AXPlatformNodeTest::BuildContentEditableWithSelectionRange( + int32_t start, + int32_t end) { + AXNodeData content_editable_node; + content_editable_node.id = 1; + content_editable_node.role = AX_ROLE_GROUP; + content_editable_node.AddState(AX_STATE_RICHLY_EDITABLE); + content_editable_node.AddState(AX_STATE_SELECTED); + content_editable_node.AddBoolAttribute(ui::AX_ATTR_EDITABLE_ROOT, true); + content_editable_node.SetValue("How now brown cow."); + + AXTreeUpdate update; + update.root_id = content_editable_node.id; + update.nodes.push_back(content_editable_node); + + update.has_tree_data = true; + update.tree_data.sel_anchor_object_id = content_editable_node.id; + update.tree_data.sel_focus_object_id = content_editable_node.id; + update.tree_data.sel_anchor_offset = start; + update.tree_data.sel_focus_offset = end; + + return update; +} + +AXTreeUpdate AXPlatformNodeTest::AXPlatformNodeTest::Build3X3Table() { + /* + Build a table that looks like: + + ---------------------- (A) Column Header + | | (A) | (B) | (B) Column Header + ---------------------- (C) Row Header + | (C) | 1 | 2 | (D) Row Header + ---------------------- + | (D) | 3 | 4 | + ---------------------- + */ + + AXNodeData table; + table.id = 0; + table.role = AX_ROLE_TABLE; + + table.AddIntAttribute(AX_ATTR_TABLE_ROW_COUNT, 3); + table.AddIntAttribute(AX_ATTR_TABLE_COLUMN_COUNT, 3); + + // Ordering in this list matters. It is used in the calculation + // of where cells are by the following: + // int position = row * GetTableColumnCount() + column; + + std::vector<int32_t> ids{51, 52, 53, 2, 3, 4, 11, 12, 13}; + table.AddIntListAttribute(AX_ATTR_CELL_IDS, ids); + table.AddIntListAttribute(AX_ATTR_UNIQUE_CELL_IDS, ids); + + table.child_ids.push_back(50); // Header + table.child_ids.push_back(1); // Row 1 + table.child_ids.push_back(10); // Row 2 + + // Table column header + AXNodeData table_row_header; + table_row_header.id = 50; + table_row_header.role = AX_ROLE_ROW; + table_row_header.child_ids.push_back(51); + table_row_header.child_ids.push_back(52); + table_row_header.child_ids.push_back(53); + + AXNodeData table_column_header_1; + table_column_header_1.id = 51; + table_column_header_1.role = AX_ROLE_COLUMN_HEADER; + + AXNodeData table_column_header_2; + table_column_header_2.id = 52; + table_column_header_2.role = AX_ROLE_COLUMN_HEADER; + table_column_header_2.SetName("column header 1"); + + AXNodeData table_column_header_3; + table_column_header_3.id = 53; + table_column_header_3.role = AX_ROLE_COLUMN_HEADER; + // Either AX_ATTR_NAME -or- AX_ATTR_DESCRIPTION is acceptable for a + // description + table_column_header_3.AddStringAttribute(AX_ATTR_DESCRIPTION, + "column header 2"); + + // Row 1 + AXNodeData table_row_1; + table_row_1.id = 1; + table_row_1.role = AX_ROLE_ROW; + table_row_1.child_ids.push_back(2); + table_row_1.child_ids.push_back(3); + table_row_1.child_ids.push_back(4); + + AXNodeData table_row_header_1; + table_row_header_1.id = 2; + table_row_header_1.role = AX_ROLE_ROW_HEADER; + table_row_header_1.SetName("row header 1"); + + AXNodeData table_cell_1; + table_cell_1.id = 3; + table_cell_1.role = AX_ROLE_CELL; + table_cell_1.SetName("1"); + + AXNodeData table_cell_2; + table_cell_2.id = 4; + table_cell_2.role = AX_ROLE_CELL; + table_cell_2.SetName("2"); + + // Row 2 + AXNodeData table_row_2; + table_row_2.id = 10; + table_row_2.role = AX_ROLE_ROW; + table_row_2.child_ids.push_back(11); + table_row_2.child_ids.push_back(12); + table_row_2.child_ids.push_back(13); + + AXNodeData table_row_header_2; + table_row_header_2.id = 11; + table_row_header_2.role = AX_ROLE_ROW_HEADER; + // Either AX_ATTR_NAME -or- AX_ATTR_DESCRIPTION is acceptable for a + // description + table_row_header_2.AddStringAttribute(AX_ATTR_DESCRIPTION, "row header 2"); + + AXNodeData table_cell_3; + table_cell_3.id = 12; + table_cell_3.role = AX_ROLE_CELL; + table_cell_3.SetName("3"); + + AXNodeData table_cell_4; + table_cell_4.id = 13; + table_cell_4.role = AX_ROLE_CELL; + table_cell_4.SetName("4"); + + AXTreeUpdate update; + update.root_id = table.id; + + // Some of the table testing code will index into |nodes| + // and change the state of the given node. If you reorder + // these, you're going to need to update the tests. + update.nodes.push_back(table); // 0 + + update.nodes.push_back(table_row_header); // 1 + update.nodes.push_back(table_column_header_1); // 2 + update.nodes.push_back(table_column_header_2); // 3 + update.nodes.push_back(table_column_header_3); // 4 + + update.nodes.push_back(table_row_1); // 5 + update.nodes.push_back(table_row_header_1); // 6 + update.nodes.push_back(table_cell_1); // 7 + update.nodes.push_back(table_cell_2); // 8 + + update.nodes.push_back(table_row_2); // 9 + update.nodes.push_back(table_row_header_2); // 10 + update.nodes.push_back(table_cell_3); // 11 + update.nodes.push_back(table_cell_4); // 12 + + return update; +} + +} // namespace ui
diff --git a/ui/accessibility/platform/ax_platform_node_unittest.h b/ui/accessibility/platform/ax_platform_node_unittest.h new file mode 100644 index 0000000..d2f8189 --- /dev/null +++ b/ui/accessibility/platform/ax_platform_node_unittest.h
@@ -0,0 +1,50 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef UI_ACCESSIBILITY_AX_PLATFORM_NODE_UNITTEST_H_ +#define UI_ACCESSIBILITY_AX_PLATFORM_NODE_UNITTEST_H_ + +#include "testing/gtest/include/gtest/gtest.h" +#include "ui/accessibility/ax_node.h" +#include "ui/accessibility/ax_node_data.h" +#include "ui/accessibility/ax_tree.h" +#include "ui/accessibility/ax_tree_update.h" + +namespace ui { + +class AXPlatformNodeTest : public testing::Test { + public: + AXPlatformNodeTest(); + ~AXPlatformNodeTest() override; + + // Initialize given an AXTreeUpdate. + void Init(const AXTreeUpdate& initial_state); + + // Convenience functions to initialize directly from a few AXNodeData objects. + void Init(const AXNodeData& node1); + void Init(const AXNodeData& node1, const AXNodeData& node2); + void Init(const AXNodeData& node1, + const AXNodeData& node2, + const AXNodeData& node3); + void Init(const AXNodeData& node1, + const AXNodeData& node2, + const AXNodeData& node3, + const AXNodeData& node4); + + protected: + AXNode* GetRootNode() { return tree_->root(); } + + AXTreeUpdate BuildTextField(); + AXTreeUpdate BuildTextFieldWithSelectionRange(int32_t start, int32_t stop); + AXTreeUpdate BuildContentEditable(); + AXTreeUpdate BuildContentEditableWithSelectionRange(int32_t start, + int32_t end); + AXTreeUpdate Build3X3Table(); + + std::unique_ptr<AXTree> tree_; +}; + +} // namespace ui + +#endif // UI_ACCESSIBILITY_AX_PLATFORM_NODE_UNITTEST_H_
diff --git a/ui/accessibility/platform/ax_platform_node_win_unittest.cc b/ui/accessibility/platform/ax_platform_node_win_unittest.cc index 989b810..32b67e0 100644 --- a/ui/accessibility/platform/ax_platform_node_win_unittest.cc +++ b/ui/accessibility/platform/ax_platform_node_win_unittest.cc
@@ -16,6 +16,7 @@ #include "testing/gtest/include/gtest/gtest.h" #include "third_party/iaccessible2/ia2_api_all.h" #include "ui/accessibility/ax_node_data.h" +#include "ui/accessibility/platform/ax_platform_node_unittest.h" #include "ui/accessibility/platform/ax_platform_node_win.h" #include "ui/accessibility/platform/test_ax_node_wrapper.h" #include "ui/base/win/atl_module.h" @@ -34,7 +35,7 @@ } // namespace -class AXPlatformNodeWinTest : public testing::Test { +class AXPlatformNodeWinTest : public ui::AXPlatformNodeTest { public: AXPlatformNodeWinTest() {} ~AXPlatformNodeWinTest() override {} @@ -43,56 +44,7 @@ win::CreateATLModuleIfNeeded(); } - // Initialize given an AXTreeUpdate. - void Init(const AXTreeUpdate& initial_state) { - tree_.reset(new AXTree(initial_state)); - } - - // Convenience functions to initialize directly from a few AXNodeData objects. - void Init(const AXNodeData& node1) { - AXTreeUpdate update; - update.root_id = node1.id; - update.nodes.push_back(node1); - Init(update); - } - - void Init(const AXNodeData& node1, - const AXNodeData& node2) { - AXTreeUpdate update; - update.root_id = node1.id; - update.nodes.push_back(node1); - update.nodes.push_back(node2); - Init(update); - } - - void Init(const AXNodeData& node1, - const AXNodeData& node2, - const AXNodeData& node3) { - AXTreeUpdate update; - update.root_id = node1.id; - update.nodes.push_back(node1); - update.nodes.push_back(node2); - update.nodes.push_back(node3); - Init(update); - } - void Init(const AXNodeData& node1, - const AXNodeData& node2, - const AXNodeData& node3, - const AXNodeData& node4) { - AXTreeUpdate update; - update.root_id = node1.id; - update.nodes.push_back(node1); - update.nodes.push_back(node2); - update.nodes.push_back(node3); - update.nodes.push_back(node4); - Init(update); - } - protected: - AXNode* GetRootNode() { - return tree_->root(); - } - void BuildRelationships(ComPtr<IAccessible2> accessible) { CHECK(accessible); AXPlatformNodeWin* node = static_cast<AXPlatformNodeWin*>(accessible.Get()); @@ -155,203 +107,6 @@ EXPECT_STREQ(expected_name, name); } - AXTreeUpdate BuildTextField() { - AXNodeData text_field_node; - text_field_node.id = 1; - text_field_node.role = AX_ROLE_TEXT_FIELD; - text_field_node.AddState(AX_STATE_EDITABLE); - text_field_node.SetValue("How now brown cow."); - - AXTreeUpdate update; - update.root_id = text_field_node.id; - update.nodes.push_back(text_field_node); - return update; - } - - AXTreeUpdate BuildTextFieldWithSelectionRange(int32_t start, int32_t stop) { - AXNodeData text_field_node; - text_field_node.id = 1; - text_field_node.role = AX_ROLE_TEXT_FIELD; - text_field_node.AddState(AX_STATE_EDITABLE); - text_field_node.AddState(AX_STATE_SELECTED); - text_field_node.AddIntAttribute(ui::AX_ATTR_TEXT_SEL_START, start); - text_field_node.AddIntAttribute(ui::AX_ATTR_TEXT_SEL_END, stop); - text_field_node.SetValue("How now brown cow."); - - AXTreeUpdate update; - update.root_id = text_field_node.id; - update.nodes.push_back(text_field_node); - return update; - } - - AXTreeUpdate BuildContentEditable() { - AXNodeData content_editable_node; - content_editable_node.id = 1; - content_editable_node.role = AX_ROLE_GROUP; - content_editable_node.AddState(AX_STATE_RICHLY_EDITABLE); - content_editable_node.AddBoolAttribute(ui::AX_ATTR_EDITABLE_ROOT, true); - content_editable_node.SetValue("How now brown cow."); - - AXTreeUpdate update; - update.root_id = content_editable_node.id; - update.nodes.push_back(content_editable_node); - return update; - } - - AXTreeUpdate BuildContentEditableWithSelectionRange(int32_t start, - int32_t end) { - AXNodeData content_editable_node; - content_editable_node.id = 1; - content_editable_node.role = AX_ROLE_GROUP; - content_editable_node.AddState(AX_STATE_RICHLY_EDITABLE); - content_editable_node.AddState(AX_STATE_SELECTED); - content_editable_node.AddBoolAttribute(ui::AX_ATTR_EDITABLE_ROOT, true); - content_editable_node.SetValue("How now brown cow."); - - AXTreeUpdate update; - update.root_id = content_editable_node.id; - update.nodes.push_back(content_editable_node); - - update.has_tree_data = true; - update.tree_data.sel_anchor_object_id = content_editable_node.id; - update.tree_data.sel_focus_object_id = content_editable_node.id; - update.tree_data.sel_anchor_offset = start; - update.tree_data.sel_focus_offset = end; - - return update; - } - - AXTreeUpdate Build3X3Table() { - /* - Build a table that looks like: - - ---------------------- (A) Column Header - | | (A) | (B) | (B) Column Header - ---------------------- (C) Row Header - | (C) | 1 | 2 | (D) Row Header - ---------------------- - | (D) | 3 | 4 | - ---------------------- - */ - - AXNodeData table; - table.id = 0; - table.role = AX_ROLE_TABLE; - - table.AddIntAttribute(AX_ATTR_TABLE_ROW_COUNT, 3); - table.AddIntAttribute(AX_ATTR_TABLE_COLUMN_COUNT, 3); - - // Ordering in this list matters. It is used in the calculation - // of where cells are by the following: - // int position = row * GetTableColumnCount() + column; - - std::vector<int32_t> ids{51, 52, 53, 2, 3, 4, 11, 12, 13}; - table.AddIntListAttribute(AX_ATTR_CELL_IDS, ids); - table.AddIntListAttribute(AX_ATTR_UNIQUE_CELL_IDS, ids); - - table.child_ids.push_back(50); // Header - table.child_ids.push_back(1); // Row 1 - table.child_ids.push_back(10); // Row 2 - - // Table column header - AXNodeData table_row_header; - table_row_header.id = 50; - table_row_header.role = AX_ROLE_ROW; - table_row_header.child_ids.push_back(51); - table_row_header.child_ids.push_back(52); - table_row_header.child_ids.push_back(53); - - AXNodeData table_column_header_1; - table_column_header_1.id = 51; - table_column_header_1.role = AX_ROLE_COLUMN_HEADER; - - AXNodeData table_column_header_2; - table_column_header_2.id = 52; - table_column_header_2.role = AX_ROLE_COLUMN_HEADER; - table_column_header_2.SetName("column header 1"); - - AXNodeData table_column_header_3; - table_column_header_3.id = 53; - table_column_header_3.role = AX_ROLE_COLUMN_HEADER; - // Either AX_ATTR_NAME -or- AX_ATTR_DESCRIPTION is acceptable for a - // description - table_column_header_3.AddStringAttribute(AX_ATTR_DESCRIPTION, - "column header 2"); - - // Row 1 - AXNodeData table_row_1; - table_row_1.id = 1; - table_row_1.role = AX_ROLE_ROW; - table_row_1.child_ids.push_back(2); - table_row_1.child_ids.push_back(3); - table_row_1.child_ids.push_back(4); - - AXNodeData table_row_header_1; - table_row_header_1.id = 2; - table_row_header_1.role = AX_ROLE_ROW_HEADER; - table_row_header_1.SetName("row header 1"); - - AXNodeData table_cell_1; - table_cell_1.id = 3; - table_cell_1.role = AX_ROLE_CELL; - table_cell_1.SetName("1"); - - AXNodeData table_cell_2; - table_cell_2.id = 4; - table_cell_2.role = AX_ROLE_CELL; - table_cell_2.SetName("2"); - - // Row 2 - AXNodeData table_row_2; - table_row_2.id = 10; - table_row_2.role = AX_ROLE_ROW; - table_row_2.child_ids.push_back(11); - table_row_2.child_ids.push_back(12); - table_row_2.child_ids.push_back(13); - - AXNodeData table_row_header_2; - table_row_header_2.id = 11; - table_row_header_2.role = AX_ROLE_ROW_HEADER; - // Either AX_ATTR_NAME -or- AX_ATTR_DESCRIPTION is acceptable for a - // description - table_row_header_2.AddStringAttribute(AX_ATTR_DESCRIPTION, "row header 2"); - - AXNodeData table_cell_3; - table_cell_3.id = 12; - table_cell_3.role = AX_ROLE_CELL; - table_cell_3.SetName("3"); - - AXNodeData table_cell_4; - table_cell_4.id = 13; - table_cell_4.role = AX_ROLE_CELL; - table_cell_4.SetName("4"); - - AXTreeUpdate update; - update.root_id = table.id; - - // Some of the table testing code will index into |nodes| - // and change the state of the given node. If you reorder - // these, you're going to need to update the tests. - update.nodes.push_back(table); // 0 - - update.nodes.push_back(table_row_header); // 1 - update.nodes.push_back(table_column_header_1); // 2 - update.nodes.push_back(table_column_header_2); // 3 - update.nodes.push_back(table_column_header_3); // 4 - - update.nodes.push_back(table_row_1); // 5 - update.nodes.push_back(table_row_header_1); // 6 - update.nodes.push_back(table_cell_1); // 7 - update.nodes.push_back(table_cell_2); // 8 - - update.nodes.push_back(table_row_2); // 9 - update.nodes.push_back(table_row_header_2); // 10 - update.nodes.push_back(table_cell_3); // 11 - update.nodes.push_back(table_cell_4); // 12 - - return update; - } - ComPtr<IAccessibleTableCell> GetCellInTable() { ComPtr<IAccessible> root_obj(GetRootIAccessible()); @@ -369,8 +124,6 @@ cell.CopyTo(table_cell.GetAddressOf()); return table_cell; } - - std::unique_ptr<AXTree> tree_; }; TEST_F(AXPlatformNodeWinTest, TestIAccessibleDetachedObject) {
diff --git a/ui/app_list/speech_ui_model_observer.h b/ui/app_list/speech_ui_model_observer.h index 29ae46f1..e4e2e7c 100644 --- a/ui/app_list/speech_ui_model_observer.h +++ b/ui/app_list/speech_ui_model_observer.h
@@ -15,7 +15,6 @@ enum SpeechRecognitionState { SPEECH_RECOGNITION_OFF = 0, SPEECH_RECOGNITION_READY, - SPEECH_RECOGNITION_HOTWORD_LISTENING, SPEECH_RECOGNITION_RECOGNIZING, SPEECH_RECOGNITION_IN_SPEECH, SPEECH_RECOGNITION_STOPPING,
diff --git a/ui/app_list/views/search_box_view.cc b/ui/app_list/views/search_box_view.cc index 7fdd291..d25a23b 100644 --- a/ui/app_list/views/search_box_view.cc +++ b/ui/app_list/views/search_box_view.cc
@@ -5,6 +5,8 @@ #include "ui/app_list/views/search_box_view.h" #include <algorithm> +#include <memory> +#include <vector> #include "ash/app_list/model/search_box_model.h" #include "base/macros.h" @@ -879,14 +881,7 @@ gfx::CreateVectorIcon(kIcMicBlackIcon, kMicIconSize, kDefaultSearchboxColor)); - // TODO(warx): consider removing on_tooltip as it is not accessible due to - // the overlap of speech UI. - if (view_delegate_->GetSpeechUI()->state() == - SPEECH_RECOGNITION_HOTWORD_LISTENING) { - speech_button_->SetTooltipText(speech_button_prop->on_tooltip); - } else { - speech_button_->SetTooltipText(speech_button_prop->off_tooltip); - } + speech_button_->SetTooltipText(speech_button_prop->tooltip); } else { if (speech_button_) { // Deleting a view will detach it from its parent.
diff --git a/ui/arc/notification/arc_notification_content_view_unittest.cc b/ui/arc/notification/arc_notification_content_view_unittest.cc index 1262fed..248783d 100644 --- a/ui/arc/notification/arc_notification_content_view_unittest.cc +++ b/ui/arc/notification/arc_notification_content_view_unittest.cc
@@ -136,13 +136,6 @@ removed_ids_.insert(notification_id); } - std::unique_ptr<ui::MenuModel> CreateMenuModel( - const message_center::Notification& notification) override { - // For this test, this method should not be invoked. - NOTREACHED(); - return nullptr; - } - void ClickOnNotificationButton(const std::string& notification_id, int button_index) override { // For this test, this method should not be invoked.
diff --git a/ui/arc/notification/arc_notification_view_unittest.cc b/ui/arc/notification/arc_notification_view_unittest.cc index 952dfa9..a0e9485 100644 --- a/ui/arc/notification/arc_notification_view_unittest.cc +++ b/ui/arc/notification/arc_notification_view_unittest.cc
@@ -110,13 +110,6 @@ removed_ids_.insert(notification_id); } - std::unique_ptr<ui::MenuModel> CreateMenuModel( - const message_center::Notification& notification) override { - // For this test, this method should not be invoked. - NOTREACHED(); - return nullptr; - } - void ClickOnNotificationButton(const std::string& notification_id, int button_index) override { // For this test, this method should not be invoked.
diff --git a/ui/aura/BUILD.gn b/ui/aura/BUILD.gn index f4514a4..b0ca56a 100644 --- a/ui/aura/BUILD.gn +++ b/ui/aura/BUILD.gn
@@ -223,10 +223,15 @@ "test/aura_mus_test_base.h", "test/aura_test_base.cc", "test/aura_test_base.h", + "test/aura_test_context_factory.cc", + "test/aura_test_context_factory.h", "test/aura_test_helper.cc", "test/aura_test_helper.h", + "test/aura_test_suite_setup.cc", + "test/aura_test_suite_setup.h", "test/aura_test_utils.cc", "test/aura_test_utils.h", + "test/env_test_helper.cc", "test/env_test_helper.h", "test/event_generator_delegate_aura.cc", "test/event_generator_delegate_aura.h", @@ -235,8 +240,12 @@ "test/mus/input_method_mus_test_api.h", "test/mus/test_window_manager_client.cc", "test/mus/test_window_manager_client.h", + "test/mus/test_window_manager_delegate.cc", + "test/mus/test_window_manager_delegate.h", "test/mus/test_window_tree.cc", "test/mus/test_window_tree.h", + "test/mus/test_window_tree_client_delegate.cc", + "test/mus/test_window_tree_client_delegate.h", "test/mus/test_window_tree_client_setup.cc", "test/mus/test_window_tree_client_setup.h", "test/mus/window_tree_client_private.cc", @@ -267,9 +276,15 @@ public_deps = [ ":aura", + + # Must be public as headers include ui_features.h. + "//ui/base:ui_features", ] deps = [ "//base/test:test_support", + "//cc:test_support", + "//components/viz/test:test_support", + "//services/ui/public/cpp/input_devices", "//services/ui/public/interfaces", "//skia", "//testing/gtest",
diff --git a/ui/aura/env.h b/ui/aura/env.h index 52b2c9e..a1870db 100644 --- a/ui/aura/env.h +++ b/ui/aura/env.h
@@ -48,6 +48,7 @@ namespace aura { namespace test { class EnvTestHelper; +class EnvWindowTreeClientSetter; } class EnvInputStateController; @@ -137,6 +138,7 @@ private: friend class test::EnvTestHelper; + friend class test::EnvWindowTreeClientSetter; friend class EventInjector; friend class MusMouseLocationUpdater; friend class Window;
diff --git a/ui/aura/mus/window_port_mus.cc b/ui/aura/mus/window_port_mus.cc index ef36bf6..d3e9db5 100644 --- a/ui/aura/mus/window_port_mus.cc +++ b/ui/aura/mus/window_port_mus.cc
@@ -18,6 +18,7 @@ #include "ui/aura/window_delegate.h" #include "ui/aura/window_observer.h" #include "ui/base/class_property.h" +#include "ui/base/ui_base_switches_util.h" #include "ui/display/display.h" #include "ui/display/screen.h" #include "ui/gfx/geometry/dip_util.h" @@ -591,6 +592,8 @@ } void WindowPortMus::UpdateClientSurfaceEmbedder() { + if (!switches::IsMusHostingViz()) + return; if (window_mus_type() != WindowMusType::TOP_LEVEL_IN_WM && window_mus_type() != WindowMusType::EMBED_IN_OWNER && window_mus_type() != WindowMusType::DISPLAY_MANUALLY_CREATED &&
diff --git a/ui/aura/mus/window_tree_client.cc b/ui/aura/mus/window_tree_client.cc index 28eb5e3..e9b770f2 100644 --- a/ui/aura/mus/window_tree_client.cc +++ b/ui/aura/mus/window_tree_client.cc
@@ -57,6 +57,7 @@ #include "ui/aura/window_port_for_shutdown.h" #include "ui/aura/window_tracker.h" #include "ui/base/layout.h" +#include "ui/base/ui_base_switches_util.h" #include "ui/base/ui_base_types.h" #include "ui/display/screen.h" #include "ui/display/types/display_constants.h" @@ -208,7 +209,9 @@ // Allow for a null request in tests. if (request.is_pending()) binding_.Bind(std::move(request)); - client::GetTransientWindowClient()->AddObserver(this); + // Some tests may not create a TransientWindowClient. + if (client::GetTransientWindowClient()) + client::GetTransientWindowClient()->AddObserver(this); if (window_manager_delegate) window_manager_delegate->SetWindowManagerClient(this); if (connector) { // |connector| can be null in tests. @@ -222,11 +225,15 @@ io_task_runner = io_thread_->task_runner(); } - gpu_ = ui::Gpu::Create(connector, ui::mojom::kServiceName, io_task_runner); - compositor_context_factory_ = - std::make_unique<MusContextFactory>(gpu_.get()); - initial_context_factory_ = Env::GetInstance()->context_factory(); - Env::GetInstance()->set_context_factory(compositor_context_factory_.get()); + if (switches::IsMusHostingViz()) { + gpu_ = + ui::Gpu::Create(connector, ui::mojom::kServiceName, io_task_runner); + compositor_context_factory_ = + std::make_unique<MusContextFactory>(gpu_.get()); + initial_context_factory_ = Env::GetInstance()->context_factory(); + Env::GetInstance()->set_context_factory( + compositor_context_factory_.get()); + } // WindowServerTest will create more than one WindowTreeClient. We will not // create the discardable memory manager for those tests. @@ -253,7 +260,9 @@ capture_synchronizer_.reset(); - client::GetTransientWindowClient()->RemoveObserver(this); + // Some tests may not create a TransientWindowClient. + if (client::GetTransientWindowClient()) + client::GetTransientWindowClient()->RemoveObserver(this); Env* env = Env::GetInstance(); if (compositor_context_factory_ && @@ -515,9 +524,13 @@ if (window_data.transient_parent_id == kInvalidServerId) return; - // Adjust the transient parent if necessary. + // Some tests may not create a TransientWindowClient. client::TransientWindowClient* transient_window_client = client::GetTransientWindowClient(); + if (!transient_window_client) + return; + + // Adjust the transient parent if necessary. Window* existing_transient_parent = transient_window_client->GetTransientParent(window->GetWindow()); WindowMus* new_transient_parent =
diff --git a/ui/aura/mus/window_tree_client_unittest.cc b/ui/aura/mus/window_tree_client_unittest.cc index 6a9c1863..f17cf5f 100644 --- a/ui/aura/mus/window_tree_client_unittest.cc +++ b/ui/aura/mus/window_tree_client_unittest.cc
@@ -43,6 +43,7 @@ #include "ui/aura/window_tracker.h" #include "ui/aura/window_tree_host_observer.h" #include "ui/base/class_property.h" +#include "ui/base/ui_base_switches.h" #include "ui/compositor/compositor.h" #include "ui/display/display.h" #include "ui/display/display_switches.h" @@ -67,7 +68,7 @@ const char kTestPropertyServerKey3[] = "test-property-server3"; Id server_id(Window* window) { - return WindowMus::Get(window)->server_id(); + return window ? WindowMus::Get(window)->server_id() : 0; } std::unique_ptr<Window> CreateWindowUsingId( @@ -137,7 +138,51 @@ } // namespace using WindowTreeClientWmTest = test::AuraMusWmTestBase; -using WindowTreeClientClientTest = test::AuraMusClientTestBase; + +class WindowTreeClientClientTest : public test::AuraMusClientTestBase { + public: + WindowTreeClientClientTest() = default; + ~WindowTreeClientClientTest() override = default; + + struct TopLevel { + std::unique_ptr<client::DefaultCaptureClient> capture_client; + std::unique_ptr<WindowTreeHostMus> host; + }; + + std::unique_ptr<TopLevel> CreateWindowTreeHostForTopLevel() { + std::unique_ptr<TopLevel> top_level = std::make_unique<TopLevel>(); + top_level->host = std::make_unique<WindowTreeHostMus>( + CreateInitParamsForTopLevel(window_tree_client_impl())); + top_level->host->InitHost(); + Window* top_level_window = top_level->host->window(); + top_level->capture_client = + std::make_unique<client::DefaultCaptureClient>(); + client::SetCaptureClient(top_level_window, top_level->capture_client.get()); + window_tree_client_impl()->capture_synchronizer()->AttachToCaptureClient( + top_level->capture_client.get()); + + // Ack the request to the windowtree to create the new window. + uint32_t change_id = 0; + EXPECT_TRUE(window_tree()->GetAndRemoveFirstChangeOfType( + WindowTreeChangeType::NEW_TOP_LEVEL, &change_id)); + EXPECT_EQ(window_tree()->window_id(), server_id(top_level_window)); + + ui::mojom::WindowDataPtr data = ui::mojom::WindowData::New(); + data->window_id = server_id(top_level_window); + data->visible = true; + window_tree_client()->OnTopLevelCreated( + change_id, std::move(data), next_display_id_++, true, base::nullopt); + EXPECT_EQ(0u, window_tree()->GetChangeCountForType( + WindowTreeChangeType::VISIBLE)); + EXPECT_TRUE(top_level_window->TargetVisibility()); + return top_level; + } + + private: + int64_t next_display_id_ = 1; + + DISALLOW_COPY_AND_ASSIGN(WindowTreeClientClientTest); +}; class WindowTreeClientWmTestSurfaceSync : public WindowTreeClientWmTest, @@ -148,6 +193,8 @@ // WindowTreeClientWmTest: void SetUp() override { + base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( + switches::kMus, switches::kMusHostVizValue); if (GetParam()) { base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kForceDeviceScaleFactor, "2"); @@ -546,65 +593,69 @@ // server replies with a new bounds and the original bounds change fails. // The server bounds change takes hold along with the associated // viz::LocalSurfaceId. -TEST_F(WindowTreeClientWmTest, SetBoundsFailedWithPendingChange) { - const gfx::Rect original_bounds(root_window()->bounds()); +TEST_F(WindowTreeClientClientTest, SetBoundsFailedWithPendingChange) { + aura::Window root_window(nullptr); + root_window.Init(ui::LAYER_NOT_DRAWN); + const gfx::Rect original_bounds(root_window.bounds()); const gfx::Rect new_bounds(gfx::Rect(0, 0, 100, 100)); - ASSERT_NE(new_bounds, root_window()->bounds()); - root_window()->SetBounds(new_bounds); - EXPECT_EQ(new_bounds, root_window()->bounds()); + ASSERT_NE(new_bounds, root_window.bounds()); + root_window.SetBounds(new_bounds); + EXPECT_EQ(new_bounds, root_window.bounds()); // Simulate the server responding with a bounds change. const gfx::Rect server_changed_bounds(gfx::Rect(0, 0, 101, 102)); const viz::LocalSurfaceId server_changed_local_surface_id( 1, base::UnguessableToken::Create()); window_tree_client()->OnWindowBoundsChanged( - server_id(root_window()), original_bounds, server_changed_bounds, + server_id(&root_window), original_bounds, server_changed_bounds, server_changed_local_surface_id); - WindowMus* root_window_mus = WindowMus::Get(root_window()); + WindowMus* root_window_mus = WindowMus::Get(&root_window); ASSERT_NE(nullptr, root_window_mus); // This shouldn't trigger the bounds changing yet. - EXPECT_EQ(new_bounds, root_window()->bounds()); + EXPECT_EQ(new_bounds, root_window.bounds()); EXPECT_FALSE(root_window_mus->GetLocalSurfaceId().is_valid()); // Tell the client the change failed, which should trigger failing to the // most recent bounds from server. ASSERT_TRUE(window_tree()->AckSingleChangeOfType(WindowTreeChangeType::BOUNDS, false)); - EXPECT_EQ(server_changed_bounds, root_window()->bounds()); + EXPECT_EQ(server_changed_bounds, root_window.bounds()); EXPECT_EQ(server_changed_local_surface_id, root_window_mus->GetLocalSurfaceId()); // Simulate server changing back to original bounds. Should take immediately. - window_tree_client()->OnWindowBoundsChanged(server_id(root_window()), + window_tree_client()->OnWindowBoundsChanged(server_id(&root_window), server_changed_bounds, original_bounds, base::nullopt); - EXPECT_EQ(original_bounds, root_window()->bounds()); + EXPECT_EQ(original_bounds, root_window.bounds()); EXPECT_FALSE(root_window_mus->GetLocalSurfaceId().is_valid()); } -TEST_F(WindowTreeClientWmTest, TwoInFlightBoundsChangesBothCanceled) { - const gfx::Rect original_bounds(root_window()->bounds()); +TEST_F(WindowTreeClientClientTest, TwoInFlightBoundsChangesBothCanceled) { + aura::Window root_window(nullptr); + root_window.Init(ui::LAYER_NOT_DRAWN); + const gfx::Rect original_bounds(root_window.bounds()); const gfx::Rect bounds1(gfx::Rect(0, 0, 100, 100)); const gfx::Rect bounds2(gfx::Rect(0, 0, 100, 102)); - root_window()->SetBounds(bounds1); - EXPECT_EQ(bounds1, root_window()->bounds()); + root_window.SetBounds(bounds1); + EXPECT_EQ(bounds1, root_window.bounds()); - root_window()->SetBounds(bounds2); - EXPECT_EQ(bounds2, root_window()->bounds()); + root_window.SetBounds(bounds2); + EXPECT_EQ(bounds2, root_window.bounds()); // Tell the client the first bounds failed. As there is a still a change in // flight nothing should happen. ASSERT_TRUE( window_tree()->AckFirstChangeOfType(WindowTreeChangeType::BOUNDS, false)); - EXPECT_EQ(bounds2, root_window()->bounds()); + EXPECT_EQ(bounds2, root_window.bounds()); // Tell the client the seconds bounds failed. Should now fallback to original // value. ASSERT_TRUE(window_tree()->AckSingleChangeOfType(WindowTreeChangeType::BOUNDS, false)); - EXPECT_EQ(original_bounds, root_window()->bounds()); + EXPECT_EQ(original_bounds, root_window.bounds()); } TEST_F(WindowTreeClientWmTest, TwoInFlightTransformsChangesBothCanceled) { @@ -1646,7 +1697,6 @@ window_tree_host->InitHost(); EXPECT_FALSE(window_tree_host->window()->TargetVisibility()); aura::Window* top_level = window_tree_host->window(); - EXPECT_NE(server_id(top_level), server_id(root_window())); EXPECT_EQ(initial_root_count + 1, window_tree_client_impl()->GetRoots().size()); EXPECT_TRUE(window_tree_client_impl()->GetRoots().count(top_level) > 0u); @@ -1809,14 +1859,16 @@ // Assertions around transient windows. TEST_F(WindowTreeClientClientTest, Transients) { + aura::Window root_window(nullptr); + root_window.Init(ui::LAYER_NOT_DRAWN); client::TransientWindowClient* transient_client = client::GetTransientWindowClient(); Window parent(nullptr); parent.Init(ui::LAYER_NOT_DRAWN); - root_window()->AddChild(&parent); + root_window.AddChild(&parent); Window transient(nullptr); transient.Init(ui::LAYER_NOT_DRAWN); - root_window()->AddChild(&transient); + root_window.AddChild(&transient); window_tree()->AckAllChanges(); transient_client->AddTransientChild(&parent, &transient); ASSERT_EQ(1u, window_tree()->GetChangeCountForType( @@ -1885,23 +1937,25 @@ // when the change originates from the server. TEST_F(WindowTreeClientClientTest, TransientChildServerMutateNotifiesOfRestack) { + aura::Window root_window(nullptr); + root_window.Init(ui::LAYER_NOT_DRAWN); Window* w1 = new Window(nullptr); w1->Init(ui::LAYER_NOT_DRAWN); - root_window()->AddChild(w1); + root_window.AddChild(w1); Window* w2 = new Window(nullptr); w2->Init(ui::LAYER_NOT_DRAWN); - root_window()->AddChild(w2); + root_window.AddChild(w2); Window* w3 = new Window(nullptr); w3->Init(ui::LAYER_NOT_DRAWN); - root_window()->AddChild(w3); + root_window.AddChild(w3); // Three children of root: |w1|, |w2| and |w3| (in that order). Make |w1| a // transient child of |w2|. Should trigger moving |w1| on top of |w2|, but not // notify the server of the reorder. window_tree()->AckAllChanges(); window_tree_client()->OnTransientWindowAdded(server_id(w2), server_id(w1)); - EXPECT_EQ(w2, root_window()->children()[0]); - EXPECT_EQ(w1, root_window()->children()[1]); - EXPECT_EQ(w3, root_window()->children()[2]); + EXPECT_EQ(w2, root_window.children()[0]); + EXPECT_EQ(w1, root_window.children()[1]); + EXPECT_EQ(w3, root_window.children()[2]); // Only reorders should be generated. EXPECT_NE(0u, window_tree()->number_of_changes()); window_tree()->AckAllChangesOfType(WindowTreeChangeType::REORDER, true); @@ -1909,9 +1963,9 @@ // Make |w3| also a transient child of |w2|. window_tree_client()->OnTransientWindowAdded(server_id(w2), server_id(w3)); - EXPECT_EQ(w2, root_window()->children()[0]); - EXPECT_EQ(w1, root_window()->children()[1]); - EXPECT_EQ(w3, root_window()->children()[2]); + EXPECT_EQ(w2, root_window.children()[0]); + EXPECT_EQ(w1, root_window.children()[1]); + EXPECT_EQ(w3, root_window.children()[2]); // Only reorders should be generated. EXPECT_NE(0u, window_tree()->number_of_changes()); window_tree()->AckAllChangesOfType(WindowTreeChangeType::REORDER, true); @@ -1919,9 +1973,9 @@ // Remove |w1| as a transient child, this should move |w3| on top of |w2|. window_tree_client()->OnTransientWindowRemoved(server_id(w2), server_id(w1)); - EXPECT_EQ(w2, root_window()->children()[0]); - EXPECT_EQ(w3, root_window()->children()[1]); - EXPECT_EQ(w1, root_window()->children()[2]); + EXPECT_EQ(w2, root_window.children()[0]); + EXPECT_EQ(w3, root_window.children()[1]); + EXPECT_EQ(w1, root_window.children()[2]); // Only reorders should be generated. EXPECT_NE(0u, window_tree()->number_of_changes()); window_tree()->AckAllChangesOfType(WindowTreeChangeType::REORDER, true); @@ -1932,25 +1986,28 @@ // restacks; TEST_F(WindowTreeClientClientTest, TransientChildClientMutateNotifiesOfRestack) { + aura::Window root_window(nullptr); + root_window.Init(ui::LAYER_NOT_DRAWN); + client::TransientWindowClient* transient_client = client::GetTransientWindowClient(); Window* w1 = new Window(nullptr); w1->Init(ui::LAYER_NOT_DRAWN); - root_window()->AddChild(w1); + root_window.AddChild(w1); Window* w2 = new Window(nullptr); w2->Init(ui::LAYER_NOT_DRAWN); - root_window()->AddChild(w2); + root_window.AddChild(w2); Window* w3 = new Window(nullptr); w3->Init(ui::LAYER_NOT_DRAWN); - root_window()->AddChild(w3); + root_window.AddChild(w3); // Three children of root: |w1|, |w2| and |w3| (in that order). Make |w1| a // transient child of |w2|. Should trigger moving |w1| on top of |w2|, and // notify notify the server of the reorder. window_tree()->AckAllChanges(); transient_client->AddTransientChild(w2, w1); - EXPECT_EQ(w2, root_window()->children()[0]); - EXPECT_EQ(w1, root_window()->children()[1]); - EXPECT_EQ(w3, root_window()->children()[2]); + EXPECT_EQ(w2, root_window.children()[0]); + EXPECT_EQ(w1, root_window.children()[1]); + EXPECT_EQ(w3, root_window.children()[2]); EXPECT_TRUE(window_tree()->AckSingleChangeOfType( WindowTreeChangeType::ADD_TRANSIENT, true)); EXPECT_TRUE(window_tree()->AckSingleChangeOfType( @@ -1959,9 +2016,9 @@ // Make |w3| also a transient child of |w2|. Order shouldn't change. transient_client->AddTransientChild(w2, w3); - EXPECT_EQ(w2, root_window()->children()[0]); - EXPECT_EQ(w1, root_window()->children()[1]); - EXPECT_EQ(w3, root_window()->children()[2]); + EXPECT_EQ(w2, root_window.children()[0]); + EXPECT_EQ(w1, root_window.children()[1]); + EXPECT_EQ(w3, root_window.children()[2]); EXPECT_TRUE(window_tree()->AckSingleChangeOfType( WindowTreeChangeType::ADD_TRANSIENT, true)); // While the order doesn't change, internally aura shuffles things around, @@ -1972,9 +2029,9 @@ // Remove |w1| as a transient child, this should move |w3| on top of |w2|. transient_client->RemoveTransientChild(w2, w1); - EXPECT_EQ(w2, root_window()->children()[0]); - EXPECT_EQ(w3, root_window()->children()[1]); - EXPECT_EQ(w1, root_window()->children()[2]); + EXPECT_EQ(w2, root_window.children()[0]); + EXPECT_EQ(w3, root_window.children()[1]); + EXPECT_EQ(w1, root_window.children()[2]); EXPECT_TRUE(window_tree()->AckSingleChangeOfType( WindowTreeChangeType::REMOVE_TRANSIENT, true)); EXPECT_TRUE(window_tree()->AckSingleChangeOfType( @@ -1982,20 +2039,20 @@ EXPECT_EQ(0u, window_tree()->number_of_changes()); // Make |w1| the first child and ensure a REORDER was scheduled. - root_window()->StackChildAtBottom(w1); - EXPECT_EQ(w1, root_window()->children()[0]); - EXPECT_EQ(w2, root_window()->children()[1]); - EXPECT_EQ(w3, root_window()->children()[2]); + root_window.StackChildAtBottom(w1); + EXPECT_EQ(w1, root_window.children()[0]); + EXPECT_EQ(w2, root_window.children()[1]); + EXPECT_EQ(w3, root_window.children()[2]); EXPECT_TRUE(window_tree()->AckSingleChangeOfType( WindowTreeChangeType::REORDER, true)); EXPECT_EQ(0u, window_tree()->number_of_changes()); // Try stacking |w2| above |w3|. This should be disallowed as that would // result in placing |w2| above its transient child. - root_window()->StackChildAbove(w2, w3); - EXPECT_EQ(w1, root_window()->children()[0]); - EXPECT_EQ(w2, root_window()->children()[1]); - EXPECT_EQ(w3, root_window()->children()[2]); + root_window.StackChildAbove(w2, w3); + EXPECT_EQ(w1, root_window.children()[0]); + EXPECT_EQ(w2, root_window.children()[1]); + EXPECT_EQ(w3, root_window.children()[2]); // The stack above is followed by a reorder from TransientWindowManager, // hence multiple changes. EXPECT_NE(0u, window_tree()->number_of_changes()); @@ -2310,76 +2367,50 @@ } TEST_F(WindowTreeClientClientTest, TwoWindowTreesRequestCapture) { - // Creating a WindowTreeHost so we can have two root windows: top_level - // and root_window(). - std::unique_ptr<WindowTreeHostMus> window_tree_host = - std::make_unique<WindowTreeHostMus>( - CreateInitParamsForTopLevel(window_tree_client_impl())); - window_tree_host->InitHost(); - Window* top_level = window_tree_host->window(); - std::unique_ptr<client::DefaultCaptureClient> capture_client( - std::make_unique<client::DefaultCaptureClient>()); - client::SetCaptureClient(top_level, capture_client.get()); - window_tree_client_impl()->capture_synchronizer()->AttachToCaptureClient( - capture_client.get()); - EXPECT_NE(server_id(top_level), server_id(root_window())); + std::unique_ptr<TopLevel> top_level1 = CreateWindowTreeHostForTopLevel(); + std::unique_ptr<TopLevel> top_level2 = CreateWindowTreeHostForTopLevel(); - // Ack the request to the windowtree to create the new window. - uint32_t change_id; - ASSERT_TRUE(window_tree()->GetAndRemoveFirstChangeOfType( - WindowTreeChangeType::NEW_TOP_LEVEL, &change_id)); - EXPECT_EQ(window_tree()->window_id(), server_id(top_level)); - - ui::mojom::WindowDataPtr data = ui::mojom::WindowData::New(); - data->window_id = server_id(top_level); - data->visible = true; - const int64_t display_id = 1; - window_tree_client()->OnTopLevelCreated(change_id, std::move(data), - display_id, true, base::nullopt); - EXPECT_EQ( - 0u, window_tree()->GetChangeCountForType(WindowTreeChangeType::VISIBLE)); - EXPECT_TRUE(top_level->TargetVisibility()); - + aura::Window* root_window1 = top_level1->host->window(); + aura::Window* root_window2 = top_level2->host->window(); std::unique_ptr<CaptureRecorder> capture_recorder1( - std::make_unique<CaptureRecorder>(root_window())); + std::make_unique<CaptureRecorder>(root_window1)); std::unique_ptr<CaptureRecorder> capture_recorder2( - std::make_unique<CaptureRecorder>(top_level)); - EXPECT_NE(client::GetCaptureClient(root_window()), - client::GetCaptureClient(top_level)); + std::make_unique<CaptureRecorder>(root_window2)); + EXPECT_NE(client::GetCaptureClient(root_window1), + client::GetCaptureClient(root_window2)); EXPECT_EQ(0, capture_recorder1->capture_changed_count()); EXPECT_EQ(0, capture_recorder2->capture_changed_count()); - // Give capture to top_level and ensure everyone is notified correctly. - top_level->SetCapture(); + // Give capture to root_window2 and ensure everyone is notified correctly. + root_window2->SetCapture(); ASSERT_TRUE(window_tree()->AckSingleChangeOfType( WindowTreeChangeType::CAPTURE, true)); EXPECT_EQ(0, capture_recorder1->capture_changed_count()); EXPECT_EQ(1, capture_recorder2->capture_changed_count()); - EXPECT_EQ(top_level->id(), + EXPECT_EQ(root_window2->id(), capture_recorder2->last_gained_capture_window_id()); EXPECT_EQ(0, capture_recorder2->last_lost_capture_window_id()); - top_level->ReleaseCapture(); + root_window2->ReleaseCapture(); capture_recorder1->reset_capture_captured_count(); capture_recorder2->reset_capture_captured_count(); - // Release capture of top_level shouldn't affect the capture of root_window(). - top_level->SetCapture(); - root_window()->SetCapture(); - top_level->ReleaseCapture(); + // Release capture of shouldn't affect the capture of root_window1. + root_window2->SetCapture(); + root_window1->SetCapture(); + root_window2->ReleaseCapture(); EXPECT_EQ(1, capture_recorder1->capture_changed_count()); EXPECT_EQ(2, capture_recorder2->capture_changed_count()); - EXPECT_EQ(root_window()->id(), + EXPECT_EQ(root_window1->id(), capture_recorder1->last_gained_capture_window_id()); EXPECT_EQ(0, capture_recorder1->last_lost_capture_window_id()); EXPECT_EQ(0, capture_recorder2->last_gained_capture_window_id()); - EXPECT_EQ(top_level->id(), capture_recorder2->last_lost_capture_window_id()); + EXPECT_EQ(root_window2->id(), + capture_recorder2->last_lost_capture_window_id()); capture_recorder1->reset_capture_captured_count(); capture_recorder2->reset_capture_captured_count(); capture_recorder1.reset(); capture_recorder2.reset(); - window_tree_host.reset(); - capture_client.reset(); } TEST_F(WindowTreeClientClientTest, ModalTypeWindowFail) {
diff --git a/ui/aura/test/DEPS b/ui/aura/test/DEPS index 796878c..8732326 100644 --- a/ui/aura/test/DEPS +++ b/ui/aura/test/DEPS
@@ -1,5 +1,8 @@ include_rules = [ + "+cc/test", + "+components/viz/test", "+mojo/edk/embedder/embedder.h", + "+services/ui/public/cpp/input_devices", "+ui/gl", "+ui/wm/core/wm_state.h", ]
diff --git a/ui/aura/test/aura_mus_test_base.cc b/ui/aura/test/aura_mus_test_base.cc index b1f9770..4611eda 100644 --- a/ui/aura/test/aura_mus_test_base.cc +++ b/ui/aura/test/aura_mus_test_base.cc
@@ -16,16 +16,6 @@ // in env. EnableMusWithTestWindowTree(); AuraTestBase::SetUp(); - - aura::Env* env = aura::Env::GetInstance(); - DCHECK(env); - context_factory_to_restore_ = env->context_factory(); - env->set_context_factory(&context_factory_); -} - -void AuraMusWmTestBase::TearDown() { - aura::Env::GetInstance()->set_context_factory(context_factory_to_restore_); - AuraTestBase::TearDown(); } AuraMusClientTestBase::AuraMusClientTestBase() {} @@ -38,16 +28,6 @@ EnableMusWithTestWindowTree(); set_window_manager_delegate(nullptr); AuraTestBase::SetUp(); - - aura::Env* env = aura::Env::GetInstance(); - DCHECK(env); - context_factory_to_restore_ = env->context_factory(); - env->set_context_factory(&context_factory_); -} - -void AuraMusClientTestBase::TearDown() { - aura::Env::GetInstance()->set_context_factory(context_factory_to_restore_); - AuraTestBase::TearDown(); } } // namespace test
diff --git a/ui/aura/test/aura_mus_test_base.h b/ui/aura/test/aura_mus_test_base.h index 4d700c3..8964dfba 100644 --- a/ui/aura/test/aura_mus_test_base.h +++ b/ui/aura/test/aura_mus_test_base.h
@@ -7,7 +7,6 @@ #include "base/macros.h" #include "ui/aura/test/aura_test_base.h" -#include "ui/compositor/test/fake_context_factory.h" namespace aura { namespace test { @@ -24,12 +23,8 @@ // AuraTestBase: void SetUp() override; - void TearDown() override; private: - ui::FakeContextFactory context_factory_; - ui::ContextFactory* context_factory_to_restore_ = nullptr; - DISALLOW_COPY_AND_ASSIGN(AuraMusWmTestBase); }; @@ -46,12 +41,8 @@ // AuraTestBase: void SetUp() override; - void TearDown() override; private: - ui::FakeContextFactory context_factory_; - ui::ContextFactory* context_factory_to_restore_ = nullptr; - DISALLOW_COPY_AND_ASSIGN(AuraMusClientTestBase); };
diff --git a/ui/aura/test/aura_test_base.cc b/ui/aura/test/aura_test_base.cc index a0729da..5f15513 100644 --- a/ui/aura/test/aura_test_base.cc +++ b/ui/aura/test/aura_test_base.cc
@@ -9,6 +9,7 @@ #include "ui/aura/mus/property_utils.h" #include "ui/aura/mus/window_tree_client.h" #include "ui/aura/mus/window_tree_host_mus.h" +#include "ui/aura/test/aura_test_context_factory.h" #include "ui/aura/test/test_window_delegate.h" #include "ui/aura/window.h" #include "ui/base/ime/input_method_initializer.h" @@ -77,11 +78,16 @@ ui::VelocityTracker::Strategy::LSQ2_RESTRICTED); // The ContextFactory must exist before any Compositors are created. - bool enable_pixel_output = false; ui::ContextFactory* context_factory = nullptr; ui::ContextFactoryPrivate* context_factory_private = nullptr; - ui::InitializeContextFactoryForTests(enable_pixel_output, &context_factory, - &context_factory_private); + if (use_mus_) { + mus_context_factory_ = std::make_unique<AuraTestContextFactory>(); + context_factory = mus_context_factory_.get(); + } else { + const bool enable_pixel_output = false; + ui::InitializeContextFactoryForTests(enable_pixel_output, &context_factory, + &context_factory_private); + } helper_ = std::make_unique<AuraTestHelper>(); if (use_mus_) { @@ -98,9 +104,18 @@ // and these tasks if un-executed would upset Valgrind. RunAllPendingInMessageLoop(); - window_tree_hosts_.clear(); + // AuraTestHelper may own a WindowTreeHost, don't delete it here else + // AuraTestHelper will have use after frees. + for (size_t i = window_tree_hosts_.size(); i > 0; --i) { + if (window_tree_hosts_[i - 1].get() == helper_->host()) { + window_tree_hosts_[i - 1].release(); + window_tree_hosts_.erase(window_tree_hosts_.begin() + i - 1); + break; + } + } helper_->TearDown(); + window_tree_hosts_.clear(); ui::TerminateContextFactoryForTests(); ui::ShutdownInputMethodForTesting(); testing::Test::TearDown();
diff --git a/ui/aura/test/aura_test_base.h b/ui/aura/test/aura_test_base.h index 4f337c15..5f3a8e3f 100644 --- a/ui/aura/test/aura_test_base.h +++ b/ui/aura/test/aura_test_base.h
@@ -35,6 +35,8 @@ namespace test { +class AuraTestContextFactory; + enum class BackendType { CLASSIC, MUS }; // A base class for aura unit tests. @@ -169,6 +171,7 @@ bool teardown_called_ = false; PropertyConverter property_converter_; std::unique_ptr<AuraTestHelper> helper_; + std::unique_ptr<AuraTestContextFactory> mus_context_factory_; std::vector<std::unique_ptr<WindowTreeHostMus>> window_tree_hosts_; std::vector<std::unique_ptr<ui::PointerEvent>> observed_pointer_events_;
diff --git a/ui/aura/test/aura_test_context_factory.cc b/ui/aura/test/aura_test_context_factory.cc new file mode 100644 index 0000000..4782070 --- /dev/null +++ b/ui/aura/test/aura_test_context_factory.cc
@@ -0,0 +1,69 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ui/aura/test/aura_test_context_factory.h" + +#include "cc/test/fake_output_surface.h" +#include "cc/test/test_context_provider.h" +#include "components/viz/test/test_layer_tree_frame_sink.h" + +namespace aura { +namespace test { +namespace { + +class FrameSinkClient : public viz::TestLayerTreeFrameSinkClient { + public: + explicit FrameSinkClient( + scoped_refptr<viz::ContextProvider> display_context_provider) + : display_context_provider_(std::move(display_context_provider)) {} + + // viz::TestLayerTreeFrameSinkClient: + std::unique_ptr<viz::OutputSurface> CreateDisplayOutputSurface( + scoped_refptr<viz::ContextProvider> compositor_context_provider) + override { + return cc::FakeOutputSurface::Create3d( + std::move(display_context_provider_)); + } + void DisplayReceivedLocalSurfaceId( + const viz::LocalSurfaceId& local_surface_id) override {} + void DisplayReceivedCompositorFrame( + const viz::CompositorFrame& frame) override {} + void DisplayWillDrawAndSwap( + bool will_draw_and_swap, + const viz::RenderPassList& render_passes) override {} + void DisplayDidDrawAndSwap() override {} + + private: + scoped_refptr<viz::ContextProvider> display_context_provider_; + + DISALLOW_COPY_AND_ASSIGN(FrameSinkClient); +}; + +} // namespace + +AuraTestContextFactory::AuraTestContextFactory() = default; + +AuraTestContextFactory::~AuraTestContextFactory() = default; + +void AuraTestContextFactory::CreateLayerTreeFrameSink( + base::WeakPtr<ui::Compositor> compositor) { + scoped_refptr<cc::TestContextProvider> context_provider = + cc::TestContextProvider::Create(); + std::unique_ptr<FrameSinkClient> frame_sink_client = + std::make_unique<FrameSinkClient>(context_provider); + constexpr bool synchronous_composite = false; + constexpr bool disable_display_vsync = false; + const double refresh_rate = GetRefreshRate(); + auto frame_sink = std::make_unique<viz::TestLayerTreeFrameSink>( + context_provider, cc::TestContextProvider::CreateWorker(), nullptr, + GetGpuMemoryBufferManager(), renderer_settings(), + base::ThreadTaskRunnerHandle::Get().get(), synchronous_composite, + disable_display_vsync, refresh_rate); + frame_sink->SetClient(frame_sink_client.get()); + compositor->SetLayerTreeFrameSink(std::move(frame_sink)); + frame_sink_clients_.insert(std::move(frame_sink_client)); +} + +} // namespace test +} // namespace aura
diff --git a/ui/aura/test/aura_test_context_factory.h b/ui/aura/test/aura_test_context_factory.h new file mode 100644 index 0000000..52c582b --- /dev/null +++ b/ui/aura/test/aura_test_context_factory.h
@@ -0,0 +1,39 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef UI_AURA_TEST_AURA_TEST_CONTEXT_FACTORY_H_ +#define UI_AURA_TEST_AURA_TEST_CONTEXT_FACTORY_H_ + +#include <memory> + +#include "base/macros.h" +#include "ui/compositor/test/fake_context_factory.h" + +namespace viz { +class TestLayerTreeFrameSinkClient; +} + +namespace aura { +namespace test { + +class AuraTestContextFactory : public ui::FakeContextFactory { + public: + AuraTestContextFactory(); + ~AuraTestContextFactory() override; + + // ui::FakeContextFactory + void CreateLayerTreeFrameSink( + base::WeakPtr<ui::Compositor> compositor) override; + + private: + std::set<std::unique_ptr<viz::TestLayerTreeFrameSinkClient>> + frame_sink_clients_; + + DISALLOW_COPY_AND_ASSIGN(AuraTestContextFactory); +}; + +} // namespace test +} // namespace aura + +#endif // UI_AURA_TEST_AURA_TEST_CONTEXT_FACTORY_H_<
diff --git a/ui/aura/test/aura_test_helper.cc b/ui/aura/test/aura_test_helper.cc index 3a6f1e9..07ac3ce 100644 --- a/ui/aura/test/aura_test_helper.cc +++ b/ui/aura/test/aura_test_helper.cc
@@ -18,7 +18,9 @@ #include "ui/aura/mus/window_tree_client.h" #include "ui/aura/test/env_test_helper.h" #include "ui/aura/test/event_generator_delegate_aura.h" +#include "ui/aura/test/mus/test_window_manager_delegate.h" #include "ui/aura/test/mus/test_window_tree.h" +#include "ui/aura/test/mus/test_window_tree_client_delegate.h" #include "ui/aura/test/mus/test_window_tree_client_setup.h" #include "ui/aura/test/test_focus_client.h" #include "ui/aura/test/test_screen.h" @@ -29,6 +31,7 @@ #include "ui/base/ime/input_method_factory.h" #include "ui/base/ime/input_method_initializer.h" #include "ui/base/platform_window_defaults.h" +#include "ui/base/ui_base_switches.h" #include "ui/compositor/compositor.h" #include "ui/compositor/layer_animator.h" #include "ui/compositor/scoped_animation_duration_scale_mode.h" @@ -93,6 +96,19 @@ void AuraTestHelper::SetUp(ui::ContextFactory* context_factory, ui::ContextFactoryPrivate* context_factory_private) { + // |mode_| defaults to LOCAL, but test suites may enable MUS. If this happens + // enable mus. + if (Env::GetInstanceDontCreate() && + Env::GetInstanceDontCreate()->mode() == Env::Mode::MUS && + mode_ == Mode::LOCAL) { + test_window_tree_client_delegate_ = + std::make_unique<TestWindowTreeClientDelegate>(); + test_window_manager_delegate_ = + std::make_unique<TestWindowManagerDelegate>(); + EnableMusWithTestWindowTree(test_window_tree_client_delegate_.get(), + test_window_manager_delegate_.get()); + } + setup_called_ = true; if (mode_ != Mode::MUS) { @@ -105,18 +121,31 @@ capture_client_ = std::make_unique<client::DefaultCaptureClient>(); const Env::Mode env_mode = (mode_ == Mode::LOCAL) ? Env::Mode::LOCAL : Env::Mode::MUS; + if (env_mode == Env::Mode::MUS) { + base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( + switches::kMus, switches::kMusHostVizValue); + } + if (mode_ == Mode::MUS_CREATE_WINDOW_TREE_CLIENT) InitWindowTreeClient(); if (!Env::GetInstanceDontCreate()) env_ = Env::CreateInstance(env_mode); + else + env_mode_to_restore_ = Env::GetInstance()->mode(); EnvTestHelper env_helper; // Always reset the mode. This really only matters for if Env was created // above. env_helper.SetMode(env_mode); - env_helper.SetWindowTreeClient(window_tree_client_); + if (env_mode == Env::Mode::MUS) { + env_window_tree_client_setter_ = + std::make_unique<EnvWindowTreeClientSetter>(window_tree_client_); + } // Tests assume they can set the mouse location on Env() and have it reflected // in tests. env_helper.SetAlwaysUseLastMouseLocation(true); + context_factory_to_restore_ = Env::GetInstance()->context_factory(); + context_factory_private_to_restore_ = + Env::GetInstance()->context_factory_private(); Env::GetInstance()->set_context_factory(context_factory); Env::GetInstance()->set_context_factory_private(context_factory_private); // Unit tests generally don't want to query the system, rather use the state @@ -133,20 +162,22 @@ // This must be reset before creating TestScreen, which sets up the display // scale factor for this test iteration. display::Display::ResetForceDeviceScaleFactorForTesting(); - test_screen_.reset(TestScreen::Create(host_size)); + test_screen_.reset(TestScreen::Create(host_size, window_tree_client_)); if (!screen) display::Screen::SetScreenInstance(test_screen_.get()); - host_.reset(test_screen_->CreateHostForPrimaryDisplay()); - host_->window()->SetEventTargeter( - std::unique_ptr<ui::EventTargeter>(new WindowTargeter())); + if (env_mode == Env::Mode::LOCAL || window_manager_delegate_) { + host_.reset(test_screen_->CreateHostForPrimaryDisplay()); + host_->window()->SetEventTargeter( + std::unique_ptr<ui::EventTargeter>(new WindowTargeter())); - client::SetFocusClient(root_window(), focus_client_.get()); - client::SetCaptureClient(root_window(), capture_client()); - parenting_client_.reset(new TestWindowParentingClient(root_window())); + client::SetFocusClient(root_window(), focus_client_.get()); + client::SetCaptureClient(root_window(), capture_client()); + parenting_client_.reset(new TestWindowParentingClient(root_window())); - root_window()->Show(); - // Ensure width != height so tests won't confuse them. - host()->SetBoundsInPixels(gfx::Rect(host_size)); + root_window()->Show(); + // Ensure width != height so tests won't confuse them. + host()->SetBoundsInPixels(gfx::Rect(host_size)); + } } if (mode_ == Mode::MUS_CREATE_WINDOW_TREE_CLIENT) { @@ -162,7 +193,8 @@ g_instance = nullptr; teardown_called_ = true; parenting_client_.reset(); - if (mode_ != Mode::MUS) { + env_window_tree_client_setter_.reset(); + if (mode_ != Mode::MUS && root_window()) { client::SetFocusClient(root_window(), nullptr); client::SetCaptureClient(root_window(), nullptr); host_.reset(); @@ -174,12 +206,23 @@ window_tree_client_setup_.reset(); focus_client_.reset(); capture_client_.reset(); + } else { + if (display::Screen::GetScreen() == test_screen_.get()) + display::Screen::SetScreenInstance(nullptr); + test_screen_.reset(); + window_tree_client_setup_.reset(); } ui::GestureRecognizer::Reset(); ui::ShutdownInputMethodForTesting(); - if (env_) + if (env_) { env_.reset(); + } else { + Env::GetInstance()->set_context_factory(context_factory_to_restore_); + Env::GetInstance()->set_context_factory_private( + context_factory_private_to_restore_); + EnvTestHelper().SetMode(env_mode_to_restore_); + } wm_state_.reset(); }
diff --git a/ui/aura/test/aura_test_helper.h b/ui/aura/test/aura_test_helper.h index 8bc1912..162188a 100644 --- a/ui/aura/test/aura_test_helper.h +++ b/ui/aura/test/aura_test_helper.h
@@ -14,6 +14,7 @@ namespace ui { class ContextFactory; +class ContextFactoryPrivate; class ScopedAnimationDurationScaleMode; } @@ -24,7 +25,9 @@ namespace aura { class Env; class TestScreen; +class TestWindowManagerDelegate; class TestWindowTree; +class TestWindowTreeClientDelegate; class TestWindowTreeClientSetup; class Window; class WindowManagerDelegate; @@ -37,6 +40,7 @@ class FocusClient; } namespace test { +class EnvWindowTreeClientSetter; class TestWindowParentingClient; // A helper class owned by tests that does common initialization required for @@ -76,7 +80,7 @@ // Flushes message loop. void RunAllPendingInMessageLoop(); - Window* root_window() { return host_->window(); } + Window* root_window() { return host_ ? host_->window() : nullptr; } ui::EventSink* event_sink() { return host_->event_sink(); } WindowTreeHost* host() { return host_.get(); } @@ -114,7 +118,16 @@ Mode mode_ = Mode::LOCAL; bool setup_called_; bool teardown_called_; + ui::ContextFactory* context_factory_to_restore_ = nullptr; + ui::ContextFactoryPrivate* context_factory_private_to_restore_ = nullptr; + std::unique_ptr<EnvWindowTreeClientSetter> env_window_tree_client_setter_; + // This is only created if Env has already been created and it's Mode is MUS. + std::unique_ptr<TestWindowTreeClientDelegate> + test_window_tree_client_delegate_; + // This is only created if Env has already been created and it's Mode is MUS. + std::unique_ptr<TestWindowManagerDelegate> test_window_manager_delegate_; std::unique_ptr<TestWindowTreeClientSetup> window_tree_client_setup_; + Env::Mode env_mode_to_restore_ = Env::Mode::LOCAL; std::unique_ptr<aura::Env> env_; std::unique_ptr<wm::WMState> wm_state_; std::unique_ptr<WindowTreeHost> host_;
diff --git a/ui/aura/test/aura_test_suite_setup.cc b/ui/aura/test/aura_test_suite_setup.cc new file mode 100644 index 0000000..8f20e537 --- /dev/null +++ b/ui/aura/test/aura_test_suite_setup.cc
@@ -0,0 +1,76 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ui/aura/test/aura_test_suite_setup.h" + +#include "base/command_line.h" +#include "ui/aura/env.h" +#include "ui/aura/test/aura_test_context_factory.h" +#include "ui/base/ui_base_switches.h" + +#if defined(USE_OZONE) +#include "services/ui/public/cpp/input_devices/input_device_client.h" +#endif + +#if BUILDFLAG(ENABLE_MUS) +#include "ui/aura/test/mus/test_window_tree_client_delegate.h" +#include "ui/aura/test/mus/test_window_tree_client_setup.h" +#endif + +namespace aura { +namespace { + +#if defined(USE_OZONE) +class TestInputDeviceClient : public ui::InputDeviceClient { + public: + TestInputDeviceClient() = default; + ~TestInputDeviceClient() override = default; + + using InputDeviceClient::GetIntefacePtr; + + private: + DISALLOW_COPY_AND_ASSIGN(TestInputDeviceClient); +}; +#endif + +} // namespace + +AuraTestSuiteSetup::AuraTestSuiteSetup() { + DCHECK(!Env::GetInstanceDontCreate()); +#if BUILDFLAG(ENABLE_MUS) + const Env::Mode env_mode = + base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kMus) + ? Env::Mode::MUS + : Env::Mode::LOCAL; + env_ = Env::CreateInstance(env_mode); + if (env_mode == Env::Mode::MUS) + ConfigureMus(); +#else + env_ = Env::CreateInstance(Env::Mode::LOCAL); +#endif +} + +AuraTestSuiteSetup::~AuraTestSuiteSetup() = default; + +#if BUILDFLAG(ENABLE_MUS) +void AuraTestSuiteSetup::ConfigureMus() { + // Configure the WindowTreeClient in a mode similar to that of connecting via + // a WindowTreeFactory. This gives WindowTreeClient a mock WindowTree. + test_window_tree_client_delegate_ = + std::make_unique<TestWindowTreeClientDelegate>(); + window_tree_client_setup_ = std::make_unique<TestWindowTreeClientSetup>(); + window_tree_client_setup_->InitWithoutEmbed( + test_window_tree_client_delegate_.get()); + env_->SetWindowTreeClient(window_tree_client_setup_->window_tree_client()); + +#if defined(USE_OZONE) + input_device_client_ = std::make_unique<TestInputDeviceClient>(); +#endif + context_factory_ = std::make_unique<test::AuraTestContextFactory>(); + env_->set_context_factory(context_factory_.get()); + env_->set_context_factory_private(nullptr); +} +#endif + +} // namespace aura
diff --git a/ui/aura/test/aura_test_suite_setup.h b/ui/aura/test/aura_test_suite_setup.h new file mode 100644 index 0000000..afa4eda8 --- /dev/null +++ b/ui/aura/test/aura_test_suite_setup.h
@@ -0,0 +1,57 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef UI_AURA_TEST_AURA_TEST_SUITE_SETUP_H_ +#define UI_AURA_TEST_AURA_TEST_SUITE_SETUP_H_ + +#include <memory> + +#include "base/macros.h" +#include "ui/base/ui_features.h" + +namespace ui { +class ContextFactory; +class InputDeviceClient; +} // namespace ui + +namespace aura { + +class Env; + +#if BUILDFLAG(ENABLE_MUS) +class TestWindowTreeClientDelegate; +class TestWindowTreeClientSetup; +#endif + +// Use this in TestSuites that use aura. It configures aura appropriately based +// on the command line. +class AuraTestSuiteSetup { + public: + AuraTestSuiteSetup(); + ~AuraTestSuiteSetup(); + + private: +#if BUILDFLAG(ENABLE_MUS) + void ConfigureMus(); +#endif + + std::unique_ptr<aura::Env> env_; + +#if BUILDFLAG(ENABLE_MUS) + std::unique_ptr<ui::ContextFactory> context_factory_; + std::unique_ptr<TestWindowTreeClientDelegate> + test_window_tree_client_delegate_; + std::unique_ptr<TestWindowTreeClientSetup> window_tree_client_setup_; +#endif + +#if defined(USE_OZONE) + std::unique_ptr<ui::InputDeviceClient> input_device_client_; +#endif + + DISALLOW_COPY_AND_ASSIGN(AuraTestSuiteSetup); +}; + +} // namespace aura + +#endif // UI_AURA_TEST_AURA_TEST_SUITE_SETUP_H_
diff --git a/ui/aura/test/env_test_helper.cc b/ui/aura/test/env_test_helper.cc new file mode 100644 index 0000000..b356d2b --- /dev/null +++ b/ui/aura/test/env_test_helper.cc
@@ -0,0 +1,31 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ui/aura/test/env_test_helper.h" + +namespace aura { +namespace test { + +EnvWindowTreeClientSetter::EnvWindowTreeClientSetter(WindowTreeClient* client) + : supplied_client_(client), + previous_client_(Env::GetInstance()->window_tree_client_) { + DCHECK(client); + SetWindowTreeClient(client); +} + +EnvWindowTreeClientSetter::~EnvWindowTreeClientSetter() { + // |supplied_client_| may have already been deleted. + DCHECK(Env::GetInstance()->window_tree_client_ == nullptr || + Env::GetInstance()->window_tree_client_ == supplied_client_); + SetWindowTreeClient(previous_client_); +} + +void EnvWindowTreeClientSetter::SetWindowTreeClient(WindowTreeClient* client) { + Env* env = Env::GetInstance(); + env->window_tree_client_ = client; + env->in_mus_shutdown_ = client ? false : true; +} + +} // namespace test +} // namespace aura
diff --git a/ui/aura/test/env_test_helper.h b/ui/aura/test/env_test_helper.h index 5cbdc73..a696acf 100644 --- a/ui/aura/test/env_test_helper.h +++ b/ui/aura/test/env_test_helper.h
@@ -15,6 +15,23 @@ namespace aura { namespace test { +// Used to set the WindowTreeClient of Env. The constructor installs the +// supplied WindowTreeClient and the destructor restores the WindowTreeClient +// to what it previously was. +class EnvWindowTreeClientSetter { + public: + explicit EnvWindowTreeClientSetter(WindowTreeClient* client); + ~EnvWindowTreeClientSetter(); + + private: + void SetWindowTreeClient(WindowTreeClient* client); + + WindowTreeClient* supplied_client_; + WindowTreeClient* previous_client_; + + DISALLOW_COPY_AND_ASSIGN(EnvWindowTreeClientSetter); +}; + class EnvTestHelper { public: EnvTestHelper() : EnvTestHelper(Env::GetInstance()) {} @@ -39,15 +56,6 @@ env_->EnableMusOSExchangeDataProvider(); } - WindowTreeClient* GetWindowTreeClient() { return env_->window_tree_client_; } - - // This circumvents the DCHECKs in Env::SetWindowTreeClient() and should - // only be used for tests where Env is long lived. - void SetWindowTreeClient(WindowTreeClient* window_tree_client) { - env_->window_tree_client_ = window_tree_client; - env_->in_mus_shutdown_ = window_tree_client ? false : true; - } - // Use to force Env::last_mouse_location() to return the value last set. // This matters for MUS, which may not return the last explicitly set // location. @@ -55,6 +63,8 @@ env_->always_use_last_mouse_location_ = value; } + WindowTreeClient* GetWindowTreeClient() { return env_->window_tree_client_; } + private: Env* env_;
diff --git a/ui/aura/test/mus/test_window_manager_delegate.cc b/ui/aura/test/mus/test_window_manager_delegate.cc new file mode 100644 index 0000000..588cba9 --- /dev/null +++ b/ui/aura/test/mus/test_window_manager_delegate.cc
@@ -0,0 +1,106 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ui/aura/test/mus/test_window_manager_delegate.h" + +#include "ui/aura/mus/window_tree_host_mus.h" + +namespace aura { + +TestWindowManagerDelegate::TestWindowManagerDelegate() = default; + +TestWindowManagerDelegate::~TestWindowManagerDelegate() = default; + +void TestWindowManagerDelegate::SetWindowManagerClient( + aura::WindowManagerClient* client) {} + +void TestWindowManagerDelegate::OnWmAcceleratedWidgetAvailableForDisplay( + int64_t display_id, + gfx::AcceleratedWidget widget) {} + +void TestWindowManagerDelegate::OnWmConnected() {} + +void TestWindowManagerDelegate::OnWmSetBounds(aura::Window* window, + const gfx::Rect& bounds) {} + +bool TestWindowManagerDelegate::OnWmSetProperty( + aura::Window* window, + const std::string& name, + std::unique_ptr<std::vector<uint8_t>>* new_data) { + return false; +} + +void TestWindowManagerDelegate::OnWmSetModalType(aura::Window* window, + ui::ModalType type) {} + +void TestWindowManagerDelegate::OnWmSetCanFocus(aura::Window* window, + bool can_focus) {} + +aura::Window* TestWindowManagerDelegate::OnWmCreateTopLevelWindow( + ui::mojom::WindowType window_type, + std::map<std::string, std::vector<uint8_t>>* properties) { + return nullptr; +} + +void TestWindowManagerDelegate::OnWmClientJankinessChanged( + const std::set<aura::Window*>& client_windows, + bool not_responding) {} + +void TestWindowManagerDelegate::OnWmBuildDragImage( + const gfx::Point& screen_location, + const SkBitmap& drag_image, + const gfx::Vector2d& drag_image_offset, + ui::mojom::PointerKind source) {} + +void TestWindowManagerDelegate::OnWmMoveDragImage( + const gfx::Point& screen_location) {} + +void TestWindowManagerDelegate::OnWmDestroyDragImage() {} + +void TestWindowManagerDelegate::OnWmWillCreateDisplay( + const display::Display& display) {} + +void TestWindowManagerDelegate::OnWmNewDisplay( + std::unique_ptr<aura::WindowTreeHostMus> window_tree_host, + const display::Display& display) { + // We assume someone else is taking ownership (which is the case for + // AuraTestHelper). + window_tree_hosts_.push_back(window_tree_host.release()); +} + +void TestWindowManagerDelegate::OnWmDisplayRemoved( + aura::WindowTreeHostMus* window_tree_host) {} + +void TestWindowManagerDelegate::OnWmDisplayModified( + const display::Display& display) {} + +ui::mojom::EventResult TestWindowManagerDelegate::OnAccelerator( + uint32_t accelerator_id, + const ui::Event& event, + std::unordered_map<std::string, std::vector<uint8_t>>* properties) { + return ui::mojom::EventResult::UNHANDLED; +} + +void TestWindowManagerDelegate::OnCursorTouchVisibleChanged(bool enabled) {} + +void TestWindowManagerDelegate::OnWmPerformMoveLoop( + aura::Window* window, + ui::mojom::MoveLoopSource source, + const gfx::Point& cursor_location, + const base::Callback<void(bool)>& on_done) {} + +void TestWindowManagerDelegate::OnWmCancelMoveLoop(aura::Window* window) {} + +void TestWindowManagerDelegate::OnWmSetClientArea( + aura::Window* window, + const gfx::Insets& insets, + const std::vector<gfx::Rect>& additional_client_areas) {} + +bool TestWindowManagerDelegate::IsWindowActive(aura::Window* window) { + return true; +} + +void TestWindowManagerDelegate::OnWmDeactivateWindow(aura::Window* window) {} + +} // namespace aura
diff --git a/ui/aura/test/mus/test_window_manager_delegate.h b/ui/aura/test/mus/test_window_manager_delegate.h new file mode 100644 index 0000000..b96956d --- /dev/null +++ b/ui/aura/test/mus/test_window_manager_delegate.h
@@ -0,0 +1,76 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef UI_AURA_TEST_MUS_TEST_WINDOW_MANAGER_DELEGATE_H_ +#define UI_AURA_TEST_MUS_TEST_WINDOW_MANAGER_DELEGATE_H_ + +#include <memory> +#include <vector> + +#include "base/macros.h" +#include "ui/aura/mus/window_manager_delegate.h" + +namespace aura { + +class TestWindowManagerDelegate : public aura::WindowManagerDelegate { + public: + TestWindowManagerDelegate(); + ~TestWindowManagerDelegate() override; + + // WindowManagerDelegate: + void SetWindowManagerClient(aura::WindowManagerClient* client) override; + void OnWmAcceleratedWidgetAvailableForDisplay( + int64_t display_id, + gfx::AcceleratedWidget widget) override; + void OnWmConnected() override; + void OnWmSetBounds(aura::Window* window, const gfx::Rect& bounds) override; + bool OnWmSetProperty( + aura::Window* window, + const std::string& name, + std::unique_ptr<std::vector<uint8_t>>* new_data) override; + void OnWmSetModalType(aura::Window* window, ui::ModalType type) override; + void OnWmSetCanFocus(aura::Window* window, bool can_focus) override; + aura::Window* OnWmCreateTopLevelWindow( + ui::mojom::WindowType window_type, + std::map<std::string, std::vector<uint8_t>>* properties) override; + void OnWmClientJankinessChanged(const std::set<aura::Window*>& client_windows, + bool not_responding) override; + void OnWmBuildDragImage(const gfx::Point& screen_location, + const SkBitmap& drag_image, + const gfx::Vector2d& drag_image_offset, + ui::mojom::PointerKind source) override; + void OnWmMoveDragImage(const gfx::Point& screen_location) override; + void OnWmDestroyDragImage() override; + void OnWmWillCreateDisplay(const display::Display& display) override; + void OnWmNewDisplay(std::unique_ptr<aura::WindowTreeHostMus> window_tree_host, + const display::Display& display) override; + void OnWmDisplayRemoved(aura::WindowTreeHostMus* window_tree_host) override; + void OnWmDisplayModified(const display::Display& display) override; + ui::mojom::EventResult OnAccelerator( + uint32_t accelerator_id, + const ui::Event& event, + std::unordered_map<std::string, std::vector<uint8_t>>* properties) + override; + void OnCursorTouchVisibleChanged(bool enabled) override; + void OnWmPerformMoveLoop(aura::Window* window, + ui::mojom::MoveLoopSource source, + const gfx::Point& cursor_location, + const base::Callback<void(bool)>& on_done) override; + void OnWmCancelMoveLoop(aura::Window* window) override; + void OnWmSetClientArea( + aura::Window* window, + const gfx::Insets& insets, + const std::vector<gfx::Rect>& additional_client_areas) override; + bool IsWindowActive(aura::Window* window) override; + void OnWmDeactivateWindow(aura::Window* window) override; + + private: + std::vector<WindowTreeHostMus*> window_tree_hosts_; + + DISALLOW_COPY_AND_ASSIGN(TestWindowManagerDelegate); +}; + +} // namespace aura + +#endif // UI_AURA_TEST_MUS_TEST_WINDOW_MANAGER_DELEGATE_H_
diff --git a/ui/aura/test/mus/test_window_tree_client_delegate.cc b/ui/aura/test/mus/test_window_tree_client_delegate.cc new file mode 100644 index 0000000..b89604e --- /dev/null +++ b/ui/aura/test/mus/test_window_tree_client_delegate.cc
@@ -0,0 +1,35 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ui/aura/test/mus/test_window_tree_client_delegate.h" + +#include "ui/aura/mus/property_converter.h" +#include "ui/aura/mus/window_tree_host_mus.h" + +namespace aura { + +TestWindowTreeClientDelegate::TestWindowTreeClientDelegate() + : property_converter_(std::make_unique<PropertyConverter>()) {} + +TestWindowTreeClientDelegate::~TestWindowTreeClientDelegate() = default; + +void TestWindowTreeClientDelegate::OnEmbed( + std::unique_ptr<WindowTreeHostMus> window_tree_host) {} + +void TestWindowTreeClientDelegate::OnUnembed(Window* root) {} + +void TestWindowTreeClientDelegate::OnEmbedRootDestroyed( + WindowTreeHostMus* window_tree_host) {} + +void TestWindowTreeClientDelegate::OnLostConnection(WindowTreeClient* client) {} + +void TestWindowTreeClientDelegate::OnPointerEventObserved( + const ui::PointerEvent& event, + Window* target) {} + +PropertyConverter* TestWindowTreeClientDelegate::GetPropertyConverter() { + return property_converter_.get(); +} + +} // namespace aura
diff --git a/ui/aura/test/mus/test_window_tree_client_delegate.h b/ui/aura/test/mus/test_window_tree_client_delegate.h new file mode 100644 index 0000000..766cffc --- /dev/null +++ b/ui/aura/test/mus/test_window_tree_client_delegate.h
@@ -0,0 +1,38 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef UI_AURA_TEST_MUS_TEST_WINDOW_TREE_CLIENT_DELEGATE_H_ +#define UI_AURA_TEST_MUS_TEST_WINDOW_TREE_CLIENT_DELEGATE_H_ + +#include <memory> + +#include "ui/aura/mus/window_tree_client_delegate.h" + +namespace aura { + +class PropertyConverter; + +class TestWindowTreeClientDelegate : public WindowTreeClientDelegate { + public: + TestWindowTreeClientDelegate(); + ~TestWindowTreeClientDelegate() override; + + // WindowTreeClientDelegate: + void OnEmbed(std::unique_ptr<WindowTreeHostMus> window_tree_host) override; + void OnUnembed(Window* root) override; + void OnEmbedRootDestroyed(WindowTreeHostMus* window_tree_host) override; + void OnLostConnection(WindowTreeClient* client) override; + void OnPointerEventObserved(const ui::PointerEvent& event, + Window* target) override; + PropertyConverter* GetPropertyConverter() override; + + private: + std::unique_ptr<PropertyConverter> property_converter_; + + DISALLOW_COPY_AND_ASSIGN(TestWindowTreeClientDelegate); +}; + +} // namespace aura + +#endif // UI_AURA_TEST_MUS_TEST_WINDOW_TREE_CLIENT_DELEGATE_H_
diff --git a/ui/aura/test/mus/test_window_tree_client_setup.cc b/ui/aura/test/mus/test_window_tree_client_setup.cc index ab2ae5d..b36eb36f 100644 --- a/ui/aura/test/mus/test_window_tree_client_setup.cc +++ b/ui/aura/test/mus/test_window_tree_client_setup.cc
@@ -35,6 +35,13 @@ test_window_manager_client_.get()); } +void TestWindowTreeClientSetup::InitWithoutEmbed( + WindowTreeClientDelegate* window_tree_delegate) { + CommonInit(window_tree_delegate, nullptr); + WindowTreeClientPrivate(window_tree_client_.get()) + .SetTree(window_tree_.get()); +} + std::unique_ptr<WindowTreeClient> TestWindowTreeClientSetup::OwnWindowTreeClient() { DCHECK(window_tree_client_);
diff --git a/ui/aura/test/mus/test_window_tree_client_setup.h b/ui/aura/test/mus/test_window_tree_client_setup.h index 5a679eb3..d133415 100644 --- a/ui/aura/test/mus/test_window_tree_client_setup.h +++ b/ui/aura/test/mus/test_window_tree_client_setup.h
@@ -28,6 +28,8 @@ void Init(WindowTreeClientDelegate* window_tree_delegate); void InitForWindowManager(WindowTreeClientDelegate* window_tree_delegate, WindowManagerDelegate* window_manager_delegate); + // TODO(sky): see if can combine with Init(). + void InitWithoutEmbed(WindowTreeClientDelegate* window_tree_delegate); // The WindowTree that WindowTreeClient talks to. TestWindowTree* window_tree() { return window_tree_.get(); }
diff --git a/ui/aura/test/mus/window_tree_client_private.cc b/ui/aura/test/mus/window_tree_client_private.cc index 6769903..e6250437 100644 --- a/ui/aura/test/mus/window_tree_client_private.cc +++ b/ui/aura/test/mus/window_tree_client_private.cc
@@ -38,7 +38,9 @@ const display::Display& display) { ui::mojom::WindowDataPtr root_data(ui::mojom::WindowData::New()); root_data->parent_id = 0; - root_data->window_id = next_window_id_++; + // Windows representing displays are owned by mus, which is identified by + // non-zero high word. + root_data->window_id = next_window_id_++ | 0x00010000; root_data->visible = true; root_data->bounds = gfx::Rect(display.bounds().size()); const bool parent_drawn = true;
diff --git a/ui/aura/test/test_screen.cc b/ui/aura/test/test_screen.cc index d7796a6..5a04335 100644 --- a/ui/aura/test/test_screen.cc +++ b/ui/aura/test/test_screen.cc
@@ -55,7 +55,9 @@ // Makes sure InputMethod is default focused so that IME basics can work. host_->GetInputMethod()->OnFocus(); host_->window()->AddObserver(this); - host_->InitHost(); + // Other test code may have already initialized the compositor. + if (!host_->compositor()->root_layer()) + host_->InitHost(); host_->window()->Show(); return host_; }
diff --git a/ui/base/ui_base_switches.cc b/ui/base/ui_base_switches.cc index ddecf81..910a369 100644 --- a/ui/base/ui_base_switches.cc +++ b/ui/base/ui_base_switches.cc
@@ -127,7 +127,7 @@ const char kSlowDownCompositingScaleFactor[] = "slow-down-compositing-scale-factor"; -#if BUILDFLAG(ENABLE_MUS) +#if defined(USE_AURA) // Used to enable the mus service (aka the UI service). This makes mus run in // process. It is also used to notify the clients that the UI service is being // used. If the value of this flag is set to kMusHostVizValue, then that means
diff --git a/ui/base/ui_base_switches.h b/ui/base/ui_base_switches.h index 76bb09a..93af32b 100644 --- a/ui/base/ui_base_switches.h +++ b/ui/base/ui_base_switches.h
@@ -57,7 +57,7 @@ UI_BASE_EXPORT extern const char kDisallowNonExactResourceReuse[]; UI_BASE_EXPORT extern const char kMangleLocalizedStrings[]; -#if BUILDFLAG(ENABLE_MUS) +#if defined(USE_AURA) UI_BASE_EXPORT extern const char kMus[]; UI_BASE_EXPORT extern const char kMusHostVizValue[]; #endif
diff --git a/ui/base/ui_base_switches_util.cc b/ui/base/ui_base_switches_util.cc index a3932a56..e4bc15eb 100644 --- a/ui/base/ui_base_switches_util.cc +++ b/ui/base/ui_base_switches_util.cc
@@ -20,4 +20,13 @@ #endif } +bool IsMusHostingViz() { +#if defined(USE_AURA) + auto* cmd = base::CommandLine::ForCurrentProcess(); + return cmd->GetSwitchValueASCII(switches::kMus) == switches::kMusHostVizValue; +#else + return false; +#endif +} + } // namespace switches
diff --git a/ui/base/ui_base_switches_util.h b/ui/base/ui_base_switches_util.h index 612a5be..4b78215 100644 --- a/ui/base/ui_base_switches_util.h +++ b/ui/base/ui_base_switches_util.h
@@ -12,6 +12,10 @@ UI_BASE_EXPORT bool IsLinkDisambiguationPopupEnabled(); UI_BASE_EXPORT bool IsTouchDragDropEnabled(); +// Returns whether mus is hosting viz. Mus is hosting viz only if --mus flag +// is set to 'viz'. +UI_BASE_EXPORT bool IsMusHostingViz(); + } // namespace switches #endif // UI_BASE_UI_BASE_SWITCHES_UTIL_H_
diff --git a/ui/file_manager/file_manager/foreground/js/file_manager_commands.js b/ui/file_manager/file_manager/foreground/js/file_manager_commands.js index 0ccab25..ef792f2b 100644 --- a/ui/file_manager/file_manager/foreground/js/file_manager_commands.js +++ b/ui/file_manager/file_manager/foreground/js/file_manager_commands.js
@@ -442,9 +442,15 @@ * @param {!CommandHandlerDeps} fileManager The file manager instance. */ execute: function(event, fileManager) { - var errorCallback = function() { - fileManager.ui.alertDialog.showHtml( - '', str('UNMOUNT_FAILED'), null, null, null); + /** @param {VolumeManagerCommon.VolumeType=} opt_volumeType */ + var errorCallback = function(opt_volumeType) { + if (opt_volumeType === VolumeManagerCommon.VolumeType.REMOVABLE) { + fileManager.ui.alertDialog.showHtml( + '', str('UNMOUNT_FAILED'), null, null, null); + } else { + fileManager.ui.alertDialog.showHtml( + '', str('UNMOUNT_PROVIDED_FAILED'), null, null, null); + } }; var volumeInfo = @@ -455,7 +461,8 @@ return; } - fileManager.volumeManager.unmount(volumeInfo, function() {}, errorCallback); + fileManager.volumeManager.unmount(volumeInfo, function() { + }, errorCallback.bind(null, volumeInfo.volumeType)); }, /** * @param {!Event} event Command event. @@ -1693,7 +1700,7 @@ reject(fileReader.error); }; fileReader.readAsArrayBuffer(blob); - }) + }); }).then(function(/** @type {!ArrayBuffer} */ arrayBuffer) { return new Promise(function(resolve, reject) { chrome.wallpaper.setWallpaper({
diff --git a/ui/gl/gl_context.cc b/ui/gl/gl_context.cc index 66fb9a6..40e2f95c 100644 --- a/ui/gl/gl_context.cc +++ b/ui/gl/gl_context.cc
@@ -9,6 +9,8 @@ #include "base/bind.h" #include "base/cancelable_callback.h" #include "base/command_line.h" +#include "base/debug/crash_logging.h" +#include "base/debug/stack_trace.h" #include "base/lazy_instance.h" #include "base/logging.h" #include "base/memory/ptr_util.h" @@ -251,6 +253,9 @@ // to create and make current a context. if (!surface && GetGLImplementation() != kGLImplementationMockGL && GetGLImplementation() != kGLImplementationStubGL) { + // TODO(sunnyps): Remove after fixing crbug.com/724999. + base::debug::SetCrashKeyToStackTrace("gl-context-set-current-stack-trace", + base::debug::StackTrace()); SetCurrentGL(nullptr); } }
diff --git a/ui/message_center/BUILD.gn b/ui/message_center/BUILD.gn index efc63bb4..d0faf6f 100644 --- a/ui/message_center/BUILD.gn +++ b/ui/message_center/BUILD.gn
@@ -137,6 +137,8 @@ "views/notification_control_buttons_view.h", "views/notification_header_view.cc", "views/notification_header_view.h", + "views/notification_menu_model.cc", + "views/notification_menu_model.h", "views/notification_view.cc", "views/notification_view.h", "views/notification_view_md.cc", @@ -261,6 +263,7 @@ sources += [ "views/bounded_label_unittest.cc", "views/message_popup_collection_unittest.cc", + "views/notification_menu_model_unittest.cc", "views/notification_view_md_unittest.cc", "views/notification_view_unittest.cc", ]
diff --git a/ui/message_center/ui_controller.cc b/ui/message_center/ui_controller.cc index d99a846..3fd67d1 100644 --- a/ui/message_center/ui_controller.cc +++ b/ui/message_center/ui_controller.cc
@@ -17,83 +17,11 @@ #include "ui/message_center/message_center_types.h" #include "ui/message_center/notification_blocker.h" #include "ui/message_center/ui_delegate.h" +#include "ui/message_center/views/notification_menu_model.h" #include "ui/strings/grit/ui_strings.h" namespace message_center { -namespace { - -// Menu constants -const int kTogglePermissionCommand = 0; -const int kShowSettingsCommand = 1; - -// The model of the context menu for a notification card. -class NotificationMenuModel : public ui::SimpleMenuModel, - public ui::SimpleMenuModel::Delegate { - public: - NotificationMenuModel(UiController* controller, - const Notification& notification); - ~NotificationMenuModel() override; - - // Overridden from ui::SimpleMenuModel::Delegate: - bool IsCommandIdChecked(int command_id) const override; - bool IsCommandIdEnabled(int command_id) const override; - void ExecuteCommand(int command_id, int event_flags) override; - - private: - UiController* controller_; - Notification notification_; - DISALLOW_COPY_AND_ASSIGN(NotificationMenuModel); -}; - -NotificationMenuModel::NotificationMenuModel(UiController* controller, - const Notification& notification) - : ui::SimpleMenuModel(this), - controller_(controller), - notification_(notification) { - DCHECK(!notification.display_source().empty()); - AddItem(kTogglePermissionCommand, - l10n_util::GetStringFUTF16(IDS_MESSAGE_CENTER_NOTIFIER_DISABLE, - notification.display_source())); - -#if defined(OS_CHROMEOS) - // Add settings menu item. - AddItem(kShowSettingsCommand, - l10n_util::GetStringUTF16(IDS_MESSAGE_CENTER_SETTINGS)); -#endif -} - -NotificationMenuModel::~NotificationMenuModel() {} - -bool NotificationMenuModel::IsCommandIdChecked(int command_id) const { - return false; -} - -bool NotificationMenuModel::IsCommandIdEnabled(int command_id) const { - // TODO(estade): commands shouldn't always be enabled. For example, a - // notification's enabled state might be controlled by policy. See - // http://crbug.com/771269 - return true; -} - -void NotificationMenuModel::ExecuteCommand(int command_id, int event_flags) { - switch (command_id) { - case kTogglePermissionCommand: - notification_.delegate()->DisableNotification(); - // TODO(estade): this will not close other open notifications from the - // same site. - MessageCenter::Get()->RemoveNotification(notification_.id(), false); - break; - case kShowSettingsCommand: - controller_->ShowNotifierSettingsBubble(); - break; - default: - NOTREACHED(); - } -} - -} // namespace - UiController::UiController(UiDelegate* delegate) : message_center_(MessageCenter::Get()), message_center_visible_(false), @@ -194,11 +122,6 @@ NotifyUiControllerChanged(); } -std::unique_ptr<ui::MenuModel> UiController::CreateNotificationMenuModel( - const Notification& notification) { - return std::make_unique<NotificationMenuModel>(this, notification); -} - void UiController::OnNotificationAdded(const std::string& notification_id) { OnMessageCenterChanged(); }
diff --git a/ui/message_center/ui_controller.h b/ui/message_center/ui_controller.h index d5974ef8..bbe26ca 100644 --- a/ui/message_center/ui_controller.h +++ b/ui/message_center/ui_controller.h
@@ -14,14 +14,9 @@ #include "ui/message_center/notifier_id.h" #include "ui/message_center/ui_delegate.h" -namespace ui { -class MenuModel; -} - namespace message_center { class MessageCenter; -class Notification; // Class that observes a MessageCenter and reacts to changes in the list of // notifications. Manages the popup and message center bubbles. Tells the @@ -55,10 +50,6 @@ // Toggles the visibility of the settings view in the message center bubble. void ShowNotifierSettingsBubble(); - // Creates a model for the context menu for a notification card. - std::unique_ptr<ui::MenuModel> CreateNotificationMenuModel( - const Notification& notification); - bool message_center_visible() { return message_center_visible_; } bool popups_visible() { return popups_visible_; } UiDelegate* delegate() { return delegate_; }
diff --git a/ui/message_center/ui_controller_unittest.cc b/ui/message_center/ui_controller_unittest.cc index 953788e5..75795f7 100644 --- a/ui/message_center/ui_controller_unittest.cc +++ b/ui/message_center/ui_controller_unittest.cc
@@ -248,47 +248,4 @@ ASSERT_FALSE(ui_controller_->message_center_visible()); } -TEST_F(UiControllerTest, ContextMenuTestWithMessageCenter) { - const std::string id1 = "id1"; - const std::string id2 = "id2"; - const std::string id3 = "id3"; - Notification* notification1 = AddNotification(id1); - - base::string16 display_source = ASCIIToUTF16("www.test.org"); - NotifierId notifier_id = DummyNotifierId(); - - NotifierId notifier_id2(NotifierId::APPLICATION, "sample-app"); - std::unique_ptr<Notification> notification(new Notification( - message_center::NOTIFICATION_TYPE_SIMPLE, id2, - ASCIIToUTF16("Test Web Notification"), - ASCIIToUTF16("Notification message body."), gfx::Image(), display_source, - GURL(), notifier_id2, message_center::RichNotificationData(), - new TestNotificationDelegate())); - message_center_->AddNotification(std::move(notification)); - - AddNotification(id3); - - std::unique_ptr<ui::MenuModel> model( - ui_controller_->CreateNotificationMenuModel(*notification1)); -#if defined(OS_CHROMEOS) - EXPECT_EQ(2, model->GetItemCount()); - - // The second item is to open the settings. - EXPECT_TRUE(model->IsEnabledAt(0)); - EXPECT_TRUE(model->IsEnabledAt(1)); - model->ActivatedAt(1); - EXPECT_TRUE(ui_controller_->message_center_visible()); -#else - EXPECT_EQ(1, model->GetItemCount()); -#endif - - ui_controller_->HideMessageCenterBubble(); - - // The first item is to disable notifications from the notifier id. It also - // removes the notification. - EXPECT_EQ(3u, message_center_->GetVisibleNotifications().size()); - model->ActivatedAt(0); - EXPECT_EQ(2u, message_center_->GetVisibleNotifications().size()); -} - } // namespace message_center
diff --git a/ui/message_center/views/message_popup_collection.cc b/ui/message_center/views/message_popup_collection.cc index af1b546..4fa28767 100644 --- a/ui/message_center/views/message_popup_collection.cc +++ b/ui/message_center/views/message_popup_collection.cc
@@ -58,7 +58,7 @@ latest_toast_entered_(NULL), user_is_closing_toasts_by_clicking_(false), target_top_edge_(0), - context_menu_controller_(new MessageViewContextMenuController(this)), + context_menu_controller_(new MessageViewContextMenuController()), weak_factory_(this) { DCHECK(message_center_); defer_timer_.reset(new base::OneShotTimer); @@ -103,11 +103,6 @@ } } -std::unique_ptr<ui::MenuModel> MessagePopupCollection::CreateMenuModel( - const Notification& notification) { - return tray_->CreateNotificationMenuModel(notification); -} - void MessagePopupCollection::ClickOnNotificationButton( const std::string& notification_id, int button_index) {
diff --git a/ui/message_center/views/message_popup_collection.h b/ui/message_center/views/message_popup_collection.h index 019c50e..e02ea7ed 100644 --- a/ui/message_center/views/message_popup_collection.h +++ b/ui/message_center/views/message_popup_collection.h
@@ -61,8 +61,6 @@ void ClickOnNotification(const std::string& notification_id) override; void RemoveNotification(const std::string& notification_id, bool by_user) override; - std::unique_ptr<ui::MenuModel> CreateMenuModel( - const Notification& notification) override; void ClickOnNotificationButton(const std::string& notification_id, int button_index) override; void ClickOnNotificationButtonWithReply(const std::string& notification_id,
diff --git a/ui/message_center/views/message_view_context_menu_controller.cc b/ui/message_center/views/message_view_context_menu_controller.cc index 892da69d..fb871b6 100644 --- a/ui/message_center/views/message_view_context_menu_controller.cc +++ b/ui/message_center/views/message_view_context_menu_controller.cc
@@ -8,18 +8,16 @@ #include "ui/message_center/message_center.h" #include "ui/message_center/views/message_view.h" #include "ui/message_center/views/message_view_delegate.h" +#include "ui/message_center/views/notification_menu_model.h" #include "ui/views/controls/menu/menu_model_adapter.h" #include "ui/views/controls/menu/menu_runner.h" #include "ui/views/widget/widget.h" namespace message_center { -MessageViewContextMenuController::MessageViewContextMenuController( - MessageViewDelegate* controller) - : controller_(controller) {} +MessageViewContextMenuController::MessageViewContextMenuController() = default; -MessageViewContextMenuController::~MessageViewContextMenuController() { -} +MessageViewContextMenuController::~MessageViewContextMenuController() = default; void MessageViewContextMenuController::ShowContextMenuForView( views::View* source, @@ -30,7 +28,7 @@ Notification* notification = MessageCenter::Get()->FindVisibleNotificationById( message_view->notification_id()); - menu_model_ = controller_->CreateMenuModel(*notification); + menu_model_ = std::make_unique<NotificationMenuModel>(*notification); if (!menu_model_ || menu_model_->GetItemCount() == 0) return;
diff --git a/ui/message_center/views/message_view_context_menu_controller.h b/ui/message_center/views/message_view_context_menu_controller.h index 83816d6..49596008 100644 --- a/ui/message_center/views/message_view_context_menu_controller.h +++ b/ui/message_center/views/message_view_context_menu_controller.h
@@ -22,12 +22,11 @@ } // namespace views namespace message_center { -class MessageViewDelegate; class MESSAGE_CENTER_EXPORT MessageViewContextMenuController : public views::ContextMenuController { public: - explicit MessageViewContextMenuController(MessageViewDelegate* controller); + explicit MessageViewContextMenuController(); ~MessageViewContextMenuController() override; private: @@ -39,8 +38,6 @@ // Callback for MenuModelAdapter void OnMenuClosed(); - MessageViewDelegate* controller_; - std::unique_ptr<ui::MenuModel> menu_model_; std::unique_ptr<views::MenuModelAdapter> menu_model_adapter_; std::unique_ptr<views::MenuRunner> menu_runner_;
diff --git a/ui/message_center/views/message_view_delegate.h b/ui/message_center/views/message_view_delegate.h index 653852c4..b4bee17 100644 --- a/ui/message_center/views/message_view_delegate.h +++ b/ui/message_center/views/message_view_delegate.h
@@ -12,8 +12,6 @@ namespace message_center { -class Notification; - // Interface used by views to report clicks and other user actions. The views // by themselves do not know how to perform those operations, they ask // MessageViewDelegate to do them. Implemented by MessageCenterView and @@ -23,8 +21,6 @@ virtual void ClickOnNotification(const std::string& notification_id) = 0; virtual void RemoveNotification(const std::string& notification_id, bool by_user) = 0; - virtual std::unique_ptr<ui::MenuModel> CreateMenuModel( - const Notification& notification) = 0; virtual void ClickOnNotificationButton(const std::string& notification_id, int button_index) = 0; virtual void ClickOnNotificationButtonWithReply(
diff --git a/ui/message_center/views/notification_menu_model.cc b/ui/message_center/views/notification_menu_model.cc new file mode 100644 index 0000000..de4219d --- /dev/null +++ b/ui/message_center/views/notification_menu_model.cc
@@ -0,0 +1,69 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ui/message_center/views/notification_menu_model.h" + +#include <memory> + +#include "base/macros.h" +#include "base/strings/utf_string_conversions.h" +#include "ui/base/l10n/l10n_util.h" +#include "ui/base/models/simple_menu_model.h" +#include "ui/message_center/message_center.h" +#include "ui/strings/grit/ui_strings.h" + +namespace message_center { + +namespace { + +// Menu constants +const int kTogglePermissionCommand = 0; +const int kShowSettingsCommand = 1; + +} // namespace + +NotificationMenuModel::NotificationMenuModel(const Notification& notification) + : ui::SimpleMenuModel(this), notification_(notification) { + DCHECK(!notification.display_source().empty()); + AddItem(kTogglePermissionCommand, + l10n_util::GetStringFUTF16(IDS_MESSAGE_CENTER_NOTIFIER_DISABLE, + notification.display_source())); + +#if defined(OS_CHROMEOS) + // Add settings menu item. + AddItem(kShowSettingsCommand, + l10n_util::GetStringUTF16(IDS_MESSAGE_CENTER_SETTINGS)); +#endif +} + +NotificationMenuModel::~NotificationMenuModel() {} + +bool NotificationMenuModel::IsCommandIdChecked(int command_id) const { + return false; +} + +bool NotificationMenuModel::IsCommandIdEnabled(int command_id) const { + // TODO(estade): commands shouldn't always be enabled. For example, a + // notification's enabled state might be controlled by policy. See + // http://crbug.com/771269 + return true; +} + +void NotificationMenuModel::ExecuteCommand(int command_id, int event_flags) { + switch (command_id) { + case kTogglePermissionCommand: + notification_.delegate()->DisableNotification(); + // TODO(estade): this will not close other open notifications from the + // same site. + MessageCenter::Get()->RemoveNotification(notification_.id(), false); + break; + case kShowSettingsCommand: + MessageCenter::Get()->ClickOnSettingsButton(notification_.id()); + break; + default: + NOTREACHED(); + } +} + +} // namespace message_center
diff --git a/ui/message_center/views/notification_menu_model.h b/ui/message_center/views/notification_menu_model.h new file mode 100644 index 0000000..324b989 --- /dev/null +++ b/ui/message_center/views/notification_menu_model.h
@@ -0,0 +1,35 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef UI_MESSAGE_CENTER_NOTIFICATION_MENU_MODEL_H_ +#define UI_MESSAGE_CENTER_NOTIFICATION_MENU_MODEL_H_ + +#include "base/macros.h" +#include "ui/base/models/simple_menu_model.h" +#include "ui/message_center/message_center_export.h" +#include "ui/message_center/notification.h" + +namespace message_center { + +// The model of the context menu for a notification card. +class MESSAGE_CENTER_EXPORT NotificationMenuModel + : public ui::SimpleMenuModel, + public ui::SimpleMenuModel::Delegate { + public: + NotificationMenuModel(const Notification& notification); + ~NotificationMenuModel() override; + + // Overridden from ui::SimpleMenuModel::Delegate: + bool IsCommandIdChecked(int command_id) const override; + bool IsCommandIdEnabled(int command_id) const override; + void ExecuteCommand(int command_id, int event_flags) override; + + private: + Notification notification_; + DISALLOW_COPY_AND_ASSIGN(NotificationMenuModel); +}; + +} // namespace message_center + +#endif // UI_MESSAGE_CENTER_UI_CONTROLLER_H_
diff --git a/ui/message_center/views/notification_menu_model_unittest.cc b/ui/message_center/views/notification_menu_model_unittest.cc new file mode 100644 index 0000000..1ba2f38b --- /dev/null +++ b/ui/message_center/views/notification_menu_model_unittest.cc
@@ -0,0 +1,113 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ui/message_center/views/notification_menu_model.h" + +#include <utility> + +#include "base/macros.h" +#include "base/strings/utf_string_conversions.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "ui/base/models/menu_model.h" +#include "ui/message_center/message_center.h" +#include "ui/message_center/notification.h" +#include "ui/message_center/notification_types.h" +#include "ui/message_center/ui_controller.h" + +namespace message_center { +namespace { + +class TestNotificationDelegate : public message_center::NotificationDelegate { + public: + TestNotificationDelegate() = default; + + private: + ~TestNotificationDelegate() override = default; + + DISALLOW_COPY_AND_ASSIGN(TestNotificationDelegate); +}; + +} // namespace + +class NotificationMenuModelTest : public testing::Test { + public: + NotificationMenuModelTest() = default; + ~NotificationMenuModelTest() override = default; + + void SetUp() override { + MessageCenter::Initialize(); + message_center_ = MessageCenter::Get(); + } + + void TearDown() override { + message_center_ = NULL; + MessageCenter::Shutdown(); + } + + protected: + NotifierId DummyNotifierId() { return NotifierId(); } + + Notification* AddNotification(const std::string& id) { + return AddNotification(id, DummyNotifierId()); + } + + Notification* AddNotification(const std::string& id, NotifierId notifier_id) { + std::unique_ptr<Notification> notification(new Notification( + message_center::NOTIFICATION_TYPE_SIMPLE, id, + base::ASCIIToUTF16("Test Web Notification"), + base::ASCIIToUTF16("Notification message body."), gfx::Image(), + base::ASCIIToUTF16("www.test.org"), GURL(), notifier_id, + message_center::RichNotificationData(), + new TestNotificationDelegate())); + Notification* notification_ptr = notification.get(); + message_center_->AddNotification(std::move(notification)); + return notification_ptr; + } + MessageCenter* message_center_; + + private: + DISALLOW_COPY_AND_ASSIGN(NotificationMenuModelTest); +}; + +TEST_F(NotificationMenuModelTest, ContextMenuTestWithMessageCenter) { + const std::string id1 = "id1"; + const std::string id2 = "id2"; + const std::string id3 = "id3"; + AddNotification(id1); + + base::string16 display_source = base::ASCIIToUTF16("www.test.org"); + NotifierId notifier_id = DummyNotifierId(); + + NotifierId notifier_id2(NotifierId::APPLICATION, "sample-app"); + std::unique_ptr<Notification> notification = std::make_unique<Notification>( + message_center::NOTIFICATION_TYPE_SIMPLE, id2, + base::ASCIIToUTF16("Test Web Notification"), + base::ASCIIToUTF16("Notification message body."), gfx::Image(), + display_source, GURL(), notifier_id2, + message_center::RichNotificationData(), new TestNotificationDelegate()); + + std::unique_ptr<ui::MenuModel> model( + std::make_unique<NotificationMenuModel>(*notification)); + message_center_->AddNotification(std::move(notification)); + + AddNotification(id3); +#if defined(OS_CHROMEOS) + EXPECT_EQ(2, model->GetItemCount()); + + // The second item is to open the settings. + EXPECT_TRUE(model->IsEnabledAt(0)); + EXPECT_TRUE(model->IsEnabledAt(1)); + model->ActivatedAt(1); +#else + EXPECT_EQ(1, model->GetItemCount()); +#endif + + // The first item is to disable notifications from the notifier id. It also + // removes the notification. + EXPECT_EQ(3u, message_center_->GetVisibleNotifications().size()); + model->ActivatedAt(0); + EXPECT_EQ(2u, message_center_->GetVisibleNotifications().size()); +} + +} // namespace message_center
diff --git a/ui/message_center/views/notification_view_md.cc b/ui/message_center/views/notification_view_md.cc index 9167723..fc7883e 100644 --- a/ui/message_center/views/notification_view_md.cc +++ b/ui/message_center/views/notification_view_md.cc
@@ -533,8 +533,20 @@ } gfx::NativeCursor NotificationViewMD::GetCursor(const ui::MouseEvent& event) { - return clickable_ ? views::GetNativeHandCursor() - : views::View::GetCursor(event); + // Do not change the cursor on a notification that isn't clickable. + if (!clickable_) + return views::View::GetCursor(event); + + // Do not change the cursor on the actions row. + if (expanded_) { + DCHECK(actions_row_); + gfx::Point point_in_child = event.location(); + ConvertPointToTarget(this, actions_row_, &point_in_child); + if (actions_row_->HitTestPoint(point_in_child)) + return views::View::GetCursor(event); + } + + return views::GetNativeHandCursor(); } void NotificationViewMD::OnMouseEntered(const ui::MouseEvent& event) {
diff --git a/ui/message_center/views/notification_view_md_unittest.cc b/ui/message_center/views/notification_view_md_unittest.cc index 0b28482..dfafa21 100644 --- a/ui/message_center/views/notification_view_md_unittest.cc +++ b/ui/message_center/views/notification_view_md_unittest.cc
@@ -46,8 +46,6 @@ void ClickOnNotification(const std::string& notification_id) override; void RemoveNotification(const std::string& notification_id, bool by_user) override; - std::unique_ptr<ui::MenuModel> CreateMenuModel( - const Notification& notification) override; void ClickOnNotificationButton(const std::string& notification_id, int button_index) override; void ClickOnNotificationButtonWithReply(const std::string& notification_id, @@ -145,13 +143,6 @@ removed_ids_.insert(notification_id); } -std::unique_ptr<ui::MenuModel> NotificationViewMDTest::CreateMenuModel( - const Notification& notification) { - // For this test, this method should not be invoked. - NOTREACHED(); - return nullptr; -} - void NotificationViewMDTest::ClickOnNotificationButton( const std::string& notification_id, int button_index) {
diff --git a/ui/message_center/views/notification_view_unittest.cc b/ui/message_center/views/notification_view_unittest.cc index 13e2e366..a394a89d 100644 --- a/ui/message_center/views/notification_view_unittest.cc +++ b/ui/message_center/views/notification_view_unittest.cc
@@ -67,8 +67,6 @@ void ClickOnNotification(const std::string& notification_id) override; void RemoveNotification(const std::string& notification_id, bool by_user) override; - std::unique_ptr<ui::MenuModel> CreateMenuModel( - const Notification& notification) override; void ClickOnNotificationButton(const std::string& notification_id, int button_index) override; void ClickOnNotificationButtonWithReply(const std::string& notification_id, @@ -279,13 +277,6 @@ removed_ids_.insert(notification_id); } -std::unique_ptr<ui::MenuModel> NotificationViewTest::CreateMenuModel( - const Notification& notification) { - // For this test, this method should not be invoked. - NOTREACHED(); - return nullptr; -} - void NotificationViewTest::ClickOnNotificationButton( const std::string& notification_id, int button_index) {
diff --git a/ui/message_center/views/toast_contents_view.cc b/ui/message_center/views/toast_contents_view.cc index 7987a17..d8a2cf6 100644 --- a/ui/message_center/views/toast_contents_view.cc +++ b/ui/message_center/views/toast_contents_view.cc
@@ -357,14 +357,6 @@ collection_->RemoveNotification(notification_id, by_user); } -std::unique_ptr<ui::MenuModel> ToastContentsView::CreateMenuModel( - const Notification& notification) { - // Should not reach, the context menu should be handled in - // MessagePopupCollection. - NOTREACHED(); - return nullptr; -} - void ToastContentsView::ClickOnNotificationButton( const std::string& notification_id, int button_index) {
diff --git a/ui/message_center/views/toast_contents_view.h b/ui/message_center/views/toast_contents_view.h index 009e1e4..441c9d3f 100644 --- a/ui/message_center/views/toast_contents_view.h +++ b/ui/message_center/views/toast_contents_view.h
@@ -97,8 +97,6 @@ void ClickOnNotification(const std::string& notification_id) override; void RemoveNotification(const std::string& notification_id, bool by_user) override; - std::unique_ptr<ui::MenuModel> CreateMenuModel( - const Notification& notification) override; void ClickOnNotificationButton(const std::string& notification_id, int button_index) override; void ClickOnNotificationButtonWithReply(const std::string& notification_id,
diff --git a/ui/platform_window/x11/x11_window_manager_ozone.cc b/ui/platform_window/x11/x11_window_manager_ozone.cc index f29cf9e..d47d1725e 100644 --- a/ui/platform_window/x11/x11_window_manager_ozone.cc +++ b/ui/platform_window/x11/x11_window_manager_ozone.cc
@@ -4,24 +4,22 @@ #include "ui/platform_window/x11/x11_window_manager_ozone.h" -#include <X11/Xlib.h> - namespace ui { -X11WindowManagerOzone::X11WindowManagerOzone() : event_grabber_(None) {} +X11WindowManagerOzone::X11WindowManagerOzone() : event_grabber_(nullptr) {} X11WindowManagerOzone::~X11WindowManagerOzone() {} -void X11WindowManagerOzone::GrabEvents(XID xwindow) { - if (event_grabber_ != None) +void X11WindowManagerOzone::GrabEvents(X11WindowOzone* window) { + if (event_grabber_ != window) return; - event_grabber_ = xwindow; + event_grabber_ = window; } -void X11WindowManagerOzone::UngrabEvents(XID xwindow) { - if (event_grabber_ != xwindow) +void X11WindowManagerOzone::UngrabEvents(X11WindowOzone* window) { + if (event_grabber_ != window) return; - event_grabber_ = None; + event_grabber_ = nullptr; } } // namespace ui
diff --git a/ui/platform_window/x11/x11_window_manager_ozone.h b/ui/platform_window/x11/x11_window_manager_ozone.h index 1cb6bd1b..e3cfca3 100644 --- a/ui/platform_window/x11/x11_window_manager_ozone.h +++ b/ui/platform_window/x11/x11_window_manager_ozone.h
@@ -7,27 +7,28 @@ #include "base/macros.h" #include "ui/platform_window/x11/x11_window_export.h" -#include "ui/platform_window/x11/x11_window_ozone.h" namespace ui { +class X11WindowOzone; + class X11_WINDOW_EXPORT X11WindowManagerOzone { public: X11WindowManagerOzone(); ~X11WindowManagerOzone(); - // Tries to set a given XWindow as the recipient for events. It will fail if - // there is already another XWindow as recipient. - void GrabEvents(XID xwindow); + // Tries to set a given X11WindowOzone as the recipient for events. It will + // fail if there is already another X11WindowOzone as recipient. + void GrabEvents(X11WindowOzone* window); - // Unsets a given XWindow as the recipient for events. - void UngrabEvents(XID xwindow); + // Unsets a given X11WindowOzone as the recipient for events. + void UngrabEvents(X11WindowOzone* window); - // Gets the current XWindow recipient of mouse events. - XID event_grabber() const { return event_grabber_; } + // Gets the current X11WindowOzone recipient of mouse events. + X11WindowOzone* event_grabber() const { return event_grabber_; } private: - XID event_grabber_; + X11WindowOzone* event_grabber_; DISALLOW_COPY_AND_ASSIGN(X11WindowManagerOzone); };
diff --git a/ui/platform_window/x11/x11_window_ozone.cc b/ui/platform_window/x11/x11_window_ozone.cc index 32c2045..09a8364 100644 --- a/ui/platform_window/x11/x11_window_ozone.cc +++ b/ui/platform_window/x11/x11_window_ozone.cc
@@ -37,11 +37,11 @@ } void X11WindowOzone::SetCapture() { - window_manager_->GrabEvents(xwindow()); + window_manager_->GrabEvents(this); } void X11WindowOzone::ReleaseCapture() { - window_manager_->UngrabEvents(xwindow()); + window_manager_->UngrabEvents(this); } void X11WindowOzone::SetCursor(PlatformCursor cursor) {
diff --git a/ui/views/controls/button/radio_button.cc b/ui/views/controls/button/radio_button.cc index 8a5f8aff..0dbf396 100644 --- a/ui/views/controls/button/radio_button.cc +++ b/ui/views/controls/button/radio_button.cc
@@ -19,8 +19,10 @@ // static const char RadioButton::kViewClassName[] = "RadioButton"; -RadioButton::RadioButton(const base::string16& label, int group_id) - : Checkbox(label) { +RadioButton::RadioButton(const base::string16& label, + int group_id, + bool force_md) + : Checkbox(label, force_md) { SetGroup(group_id); if (!UseMd()) {
diff --git a/ui/views/controls/button/radio_button.h b/ui/views/controls/button/radio_button.h index 02dc311..a0af347 100644 --- a/ui/views/controls/button/radio_button.h +++ b/ui/views/controls/button/radio_button.h
@@ -18,7 +18,8 @@ // The button's class name. static const char kViewClassName[]; - RadioButton(const base::string16& label, int group_id); + // |force_md| forces MD even when --secondary-ui-md flag is not set. + RadioButton(const base::string16& label, int group_id, bool force_md = false); ~RadioButton() override; // Overridden from View:
diff --git a/ui/views/mus/views_mus_test_suite.cc b/ui/views/mus/views_mus_test_suite.cc index 19ad6be06..24e983a 100644 --- a/ui/views/mus/views_mus_test_suite.cc +++ b/ui/views/mus/views_mus_test_suite.cc
@@ -24,10 +24,11 @@ #include "services/service_manager/public/cpp/service_context.h" #include "services/ui/common/switches.h" #include "testing/gtest/include/gtest/gtest.h" +#include "ui/aura/env.h" #include "ui/aura/mus/window_tree_host_mus.h" -#include "ui/aura/test/env_test_helper.h" #include "ui/aura/test/mus/input_method_mus_test_api.h" #include "ui/aura/window.h" +#include "ui/base/ui_base_switches.h" #include "ui/compositor/test/fake_context_factory.h" #include "ui/gl/gl_switches.h" #include "ui/views/mus/desktop_window_tree_host_mus.h" @@ -68,16 +69,13 @@ public: PlatformTestHelperMus(service_manager::Connector* connector, const service_manager::Identity& identity) { - aura::test::EnvTestHelper().SetWindowTreeClient(nullptr); // It is necessary to recreate the MusClient for each test, // since a new MessageLoop is created for each test. mus_client_ = test::MusClientTestApi::Create(connector, identity); ViewsDelegate::GetInstance()->set_native_widget_factory(base::Bind( &PlatformTestHelperMus::CreateNativeWidget, base::Unretained(this))); } - ~PlatformTestHelperMus() override { - aura::test::EnvTestHelper().SetWindowTreeClient(nullptr); - } + ~PlatformTestHelperMus() override {} // PlatformTestHelper: void OnTestHelperCreated(ViewsTestHelper* helper) override { @@ -251,6 +249,8 @@ EnsureCommandLineSwitch(ui::switches::kUseTestConfig); EnsureCommandLineSwitch(switches::kOverrideUseSoftwareGLForTests); + base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( + switches::kMus, switches::kMusHostVizValue); ViewsTestSuite::Initialize(); service_manager_connections_ = std::make_unique<ServiceManagerConnection>();
diff --git a/ui/views/window/dialog_client_view.cc b/ui/views/window/dialog_client_view.cc index 8bb3bf03..a2f8feb6 100644 --- a/ui/views/window/dialog_client_view.cc +++ b/ui/views/window/dialog_client_view.cc
@@ -445,7 +445,7 @@ return; extra_view_ = GetDialogDelegate()->CreateExtraView(); - if (extra_view_) + if (extra_view_ && Button::AsButton(extra_view_)) extra_view_->SetGroup(kButtonGroup); }
diff --git a/ui/webui/resources/cr_elements/cr_toolbar/cr_toolbar.html b/ui/webui/resources/cr_elements/cr_toolbar/cr_toolbar.html index 39c050e5..9b8c633 100644 --- a/ui/webui/resources/cr_elements/cr_toolbar/cr_toolbar.html +++ b/ui/webui/resources/cr_elements/cr_toolbar/cr_toolbar.html
@@ -10,7 +10,7 @@ <template> <style include="cr-icons cr-hidden-style"> :host { - --cr-toolbar-field-width: 580px; + --cr-toolbar-field-width: 680px; --cr-toolbar-height: 56px; --paper-icon-button-ink-color: white; align-items: center;
diff --git a/ui/webui/resources/cr_elements/policy/cr_tooltip_icon.html b/ui/webui/resources/cr_elements/policy/cr_tooltip_icon.html index 73b39dd..5f9958ed 100644 --- a/ui/webui/resources/cr_elements/policy/cr_tooltip_icon.html +++ b/ui/webui/resources/cr_elements/policy/cr_tooltip_icon.html
@@ -13,13 +13,7 @@ } paper-tooltip { - --paper-tooltip: { - font-size: 92.31%; /* Effectively 12px if the host default is 13px. */ - font-weight: 500; - max-width: 330px; - min-width: 200px; - padding: 10px 8px; - }; + --paper-tooltip: var(--cr-tooltip); } iron-icon {
diff --git a/ui/webui/resources/cr_elements/shared_vars_css.html b/ui/webui/resources/cr_elements/shared_vars_css.html index d6f0ad9..da562860 100644 --- a/ui/webui/resources/cr_elements/shared_vars_css.html +++ b/ui/webui/resources/cr_elements/shared_vars_css.html
@@ -75,6 +75,14 @@ --cr-toggle-color: var(--google-blue-500); + --cr-tooltip: { + font-size: 92.31%; /* Effectively 12px if the host default is 13px. */ + font-weight: 500; + max-width: 330px; + min-width: 200px; + padding: 10px 8px; + } + --cr-selectable-focus: { background-color: var(--cr-focused-item-color); outline: none;
diff --git a/ui/wm/test/wm_test_helper.cc b/ui/wm/test/wm_test_helper.cc index df497091..a040ee49 100644 --- a/ui/wm/test/wm_test_helper.cc +++ b/ui/wm/test/wm_test_helper.cc
@@ -27,7 +27,8 @@ service_manager::Connector* connector, ui::ContextFactory* context_factory) { wm_state_ = std::make_unique<WMState>(); - aura::Env::GetInstance()->set_context_factory(context_factory); + if (context_factory) + aura::Env::GetInstance()->set_context_factory(context_factory); if (aura::Env::GetInstance()->mode() == aura::Env::Mode::LOCAL) InitLocalHost(default_window_size); else
diff --git a/url/gurl.cc b/url/gurl.cc index ce0cb49..cec69c7 100644 --- a/url/gurl.cc +++ b/url/gurl.cc
@@ -133,8 +133,7 @@ #endif } -GURL::~GURL() { -} +GURL::~GURL() = default; GURL& GURL::operator=(const GURL& other) { spec_ = other.spec_;
diff --git a/url/origin.cc b/url/origin.cc index 738e9278..b6592dc 100644 --- a/url/origin.cc +++ b/url/origin.cc
@@ -97,8 +97,7 @@ Origin::Origin(Origin&&) = default; Origin& Origin::operator=(Origin&&) = default; -Origin::~Origin() { -} +Origin::~Origin() = default; // static Origin Origin::UnsafelyCreateOriginWithoutNormalization(
diff --git a/url/scheme_host_port.cc b/url/scheme_host_port.cc index f0f56850..eb2905d 100644 --- a/url/scheme_host_port.cc +++ b/url/scheme_host_port.cc
@@ -151,8 +151,7 @@ port_ = port; } -SchemeHostPort::~SchemeHostPort() { -} +SchemeHostPort::~SchemeHostPort() = default; bool SchemeHostPort::IsInvalid() const { return scheme_.empty() && host_.empty() && !port_;
diff --git a/url/url_canon_icu.cc b/url/url_canon_icu.cc index 19c5c23..9513fc6 100644 --- a/url/url_canon_icu.cc +++ b/url/url_canon_icu.cc
@@ -118,8 +118,7 @@ : converter_(converter) { } -ICUCharsetConverter::~ICUCharsetConverter() { -} +ICUCharsetConverter::~ICUCharsetConverter() = default; void ICUCharsetConverter::ConvertFromUTF16(const base::char16* input, int input_len,