repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
syang2forever/jos
jos/user/faultdie.c
// test user-level fault handler -- just exit when we fault #include <inc/lib.h> void handler(struct UTrapframe *utf) { void *addr = (void*)utf->utf_fault_va; uint32_t err = utf->utf_err; cprintf("i faulted at va %x, err %x\n", addr, err & 7); sys_env_destroy(sys_getenvid()); } void umain(int argc, char **argv) { set_pgfault_handler(handler); *(int*)0xDeadBeef = 0; }
syang2forever/jos
jos/user/spin.c
// Test preemption by forking off a child process that just spins forever. // Let it run for a couple time slices, then kill it. #include <inc/lib.h> void umain(int argc, char **argv) { envid_t env; cprintf("I am the parent. Forking the child...\n"); if ((env = fork()) == 0) { cprintf("I am the child. Spinning...\n"); while (1) /* do nothing */; } cprintf("I am the parent. Running the child...\n"); sys_yield(); sys_yield(); sys_yield(); sys_yield(); sys_yield(); sys_yield(); sys_yield(); sys_yield(); cprintf("I am the parent. Killing the child...\n"); sys_env_destroy(env); }
syang2forever/jos
jos/kern/monitor.c
<filename>jos/kern/monitor.c // Simple command-line kernel monitor useful for // controlling the kernel and exploring the system interactively. #include <inc/stdio.h> #include <inc/string.h> #include <inc/memlayout.h> #include <inc/assert.h> #include <inc/x86.h> #include <kern/console.h> #include <kern/monitor.h> #include <kern/kdebug.h> #include <kern/trap.h> #include <kern/pmap.h> #define CMDBUF_SIZE 80 // enough for one VGA text line struct Command { const char *name; const char *desc; // return -1 to force monitor to exit int (*func)(int argc, char** argv, struct Trapframe* tf); }; static struct Command commands[] = { { "help", "Display this list of commands", mon_help }, { "kerninfo", "Display information about the kernel", mon_kerninfo }, { "backtrace", "Display backtrace about the kernel", mon_backtrace }, { "showmappings", "Display information about physical page mappings", mon_showmappings }, { "setpermissions", "Set, clear, or change the permissions of any mapping", mon_setpermissions }, { "dumpmemory", "Dump the memory by given virtual or physical address", mon_dumpmemory }, { "step", "step into", mon_step }, { "continue", "continue exec", mon_continue }, }; /***** Implementations of basic kernel monitor commands *****/ int mon_help(int argc, char **argv, struct Trapframe *tf) { int i; for (i = 0; i < ARRAY_SIZE(commands); i++) cprintf("%s - %s\n", commands[i].name, commands[i].desc); return 0; } int mon_kerninfo(int argc, char **argv, struct Trapframe *tf) { extern char _start[], entry[], etext[], edata[], end[]; cprintf("Special kernel symbols:\n"); cprintf(" _start %08x (phys)\n", _start); cprintf(" entry %08x (virt) %08x (phys)\n", entry, entry - KERNBASE); cprintf(" etext %08x (virt) %08x (phys)\n", etext, etext - KERNBASE); cprintf(" edata %08x (virt) %08x (phys)\n", edata, edata - KERNBASE); cprintf(" end %08x (virt) %08x (phys)\n", end, end - KERNBASE); cprintf("Kernel executable memory footprint: %dKB\n", ROUNDUP(end - entry, 1024) / 1024); return 0; } int mon_backtrace(int argc, char **argv, struct Trapframe *tf) { cprintf("Stack backtrace:\n"); uint32_t *ebp = (uint32_t *)read_ebp(); uint32_t *eip = NULL; while(ebp) { eip = (uint32_t *)*(ebp + 1); cprintf(" ebp %08x eip %08x args %08x %08x %08x %08x %08x\n", ebp, eip, *(ebp + 2), *(ebp + 3), *(ebp + 4), *(ebp + 5), *(ebp + 6)); struct Eipdebuginfo info; debuginfo_eip((uintptr_t)eip, &info); cprintf(" %s:%d: %.*s+%d\n", info.eip_file, info.eip_line, info.eip_fn_namelen, info.eip_fn_name, eip - info.eip_fn_addr); ebp = (uint32_t *)*(ebp); } return 0; } int mon_showmappings(int argc, char **argv, struct Trapframe *tf) { if(argc < 3) { cprintf("Usage: showmappings lower_addr upper_addr\n"); return 0; } char *endptr; uintptr_t lower_addr = strtol(argv[1], &endptr, 16); if(*endptr) { cprintf("lower_addr format wrong!\n"); return 0; } uintptr_t upper_addr = strtol(argv[2], &endptr, 16); if(*endptr) { cprintf("upper_addr format wrong!\n"); return 0; } if(lower_addr < 0 || upper_addr > 0xFFFFFFFF) { cprintf("Error! The address is error!\n"); return 0; } if(lower_addr > upper_addr){ cprintf("Error! The lower_addr <= upper_addr doesn't hold!\n"); return 0; } if(lower_addr != ROUNDDOWN(lower_addr, PGSIZE) || upper_addr != ROUNDUP(upper_addr, PGSIZE)) { lower_addr = ROUNDDOWN(lower_addr, PGSIZE); upper_addr = ROUNDUP(upper_addr, PGSIZE); cprintf("The address is formatted: %08x, %08x\n", lower_addr, upper_addr); } for(;lower_addr<upper_addr;lower_addr+=PGSIZE){ pte_t *pte = pgdir_walk(kern_pgdir, (void *)lower_addr, 0); cprintf("0x%08x - 0x%08x\t", lower_addr, lower_addr+PGSIZE-1); if(pte == NULL || !(*pte & PTE_P)) { cprintf("page not mapped!\n"); } else { physaddr_t phys_addr = PTE_ADDR(*pte); cprintf("0x%08x - 0x%08x\t", phys_addr, phys_addr+PGSIZE-1); if(*pte&PTE_U) { cprintf("user\t"); } else { cprintf("kern\t"); } if(*pte&PTE_W) { cprintf("rw\n"); } else { cprintf("ro\n"); } } } return 0; } int mon_setpermissions(int argc, char **argv, struct Trapframe *tf) { /* argc must equals to 3 or more */ if(argc < 3) { cprintf("Usage: setpermissions addr permission_bits\n"); cprintf("permission_bits: U|W|P, from 000 to 111\n"); return 0; } /* read argv */ char *endptr; uintptr_t addr = strtol(argv[1], &endptr, 16); if(*endptr) { cprintf("address format wrong!\n"); return 0; } int bits = (int)strtol(argv[2], &endptr, 2); if(*endptr) { cprintf("bits format wrong!\n"); return 0; } /* check input and align */ if(addr != ROUNDDOWN(addr, PGSIZE)) { addr = ROUNDDOWN(addr, PGSIZE); cprintf("The address is formatted: %08x\n", addr); } if(bits > 7) { bits &= 7; cprintf("bits are formatted: %03b\n", bits); } pte_t *pte = pgdir_walk(kern_pgdir, (void *)addr, 1); *pte = (*pte&0xFFFFFFF8) + bits; return 0; } int mon_dumpmemory(int argc, char **argv, struct Trapframe *tf) { if(argc < 4) { cprintf("Usage: dumpmemory [V|P] lower_addr upper_addr\n"); cprintf("V: virtual address; P: physical address\n"); return 0; } char *endptr; int flag = 0; if(argv[1][0] == 'V'){ flag = 1; } else if(argv[1][0] == 'P') { flag = 2; } if(flag == 0) { cprintf("wrong address type\n"); return 0; } uintptr_t lower_addr = strtol(argv[2], &endptr, 16); if(*endptr) { cprintf("lower_addr format wrong!\n"); return 0; } uintptr_t upper_addr = strtol(argv[3], &endptr, 16); if(*endptr) { cprintf("upper_addr format wrong!\n"); return 0; } if(lower_addr < 0 || upper_addr > 0xFFFFFFFF) { cprintf("Error! The address is error!\n"); return 0; } if(flag == 2){ if(PGNUM(upper_addr) >= npages){ panic("Wrong!"); } lower_addr = (uintptr_t)KADDR((physaddr_t)lower_addr); upper_addr = (uintptr_t)KADDR((physaddr_t)upper_addr); } for(;lower_addr < upper_addr; lower_addr++) { cprintf("address: %08x, value: %02x\n", lower_addr, *((char *)lower_addr)&0xFF); } return 0; } /* lab3 step and continue */ int mon_step(int argc, char **argv, struct Trapframe *tf) { if (tf == NULL || !(tf->tf_trapno == T_BRKPT || tf->tf_trapno == T_DEBUG)) { return 0; } tf->tf_eflags |= FL_TF; cprintf("eip at\t%08x\n", tf->tf_eip); return 0; } int mon_continue(int argc, char **argv, struct Trapframe *tf) { if (tf == NULL || !(tf->tf_trapno == T_BRKPT || tf->tf_trapno == T_DEBUG)) { return 0; } tf->tf_eflags &= ~FL_TF; return 0; } /***** Kernel monitor command interpreter *****/ #define WHITESPACE "\t\r\n " #define MAXARGS 16 static int runcmd(char *buf, struct Trapframe *tf) { int argc; char *argv[MAXARGS]; int i; // Parse the command buffer into whitespace-separated arguments argc = 0; argv[argc] = 0; while (1) { // gobble whitespace while (*buf && strchr(WHITESPACE, *buf)) *buf++ = 0; if (*buf == 0) break; // save and scan past next arg if (argc == MAXARGS-1) { cprintf("Too many arguments (max %d)\n", MAXARGS); return 0; } argv[argc++] = buf; while (*buf && !strchr(WHITESPACE, *buf)) buf++; } argv[argc] = 0; // Lookup and invoke the command if (argc == 0) return 0; for (i = 0; i < ARRAY_SIZE(commands); i++) { if (strcmp(argv[0], commands[i].name) == 0) return commands[i].func(argc, argv, tf); } cprintf("Unknown command '%s'\n", argv[0]); return 0; } void monitor(struct Trapframe *tf) { char *buf; cprintf("%Cs %Cs %Cs %Cs %Cs %Cs!\n",2, "Welcome", 8, "to", 11, "the", 4, "JOS", 15, "kernel", 6, "monitor"); cprintf("Type 'help' for a list of commands.\n"); if (tf != NULL) print_trapframe(tf); while (1) { buf = readline("K> "); if (buf != NULL) if (runcmd(buf, tf) < 0) break; } }
syang2forever/jos
jos/kern/console.c
/* See COPYRIGHT for copyright information. */ #include <inc/x86.h> #include <inc/memlayout.h> #include <inc/kbdreg.h> #include <inc/string.h> #include <inc/assert.h> #include <kern/console.h> #include <kern/trap.h> #include <kern/picirq.h> static void cons_intr(int (*proc)(void)); static void cons_putc(int c); // Stupid I/O delay routine necessitated by historical PC design flaws static void delay(void) { inb(0x84); inb(0x84); inb(0x84); inb(0x84); } /***** Serial I/O code *****/ #define COM1 0x3F8 #define COM_RX 0 // In: Receive buffer (DLAB=0) #define COM_TX 0 // Out: Transmit buffer (DLAB=0) #define COM_DLL 0 // Out: Divisor Latch Low (DLAB=1) #define COM_DLM 1 // Out: Divisor Latch High (DLAB=1) #define COM_IER 1 // Out: Interrupt Enable Register #define COM_IER_RDI 0x01 // Enable receiver data interrupt #define COM_IIR 2 // In: Interrupt ID Register #define COM_FCR 2 // Out: FIFO Control Register #define COM_LCR 3 // Out: Line Control Register #define COM_LCR_DLAB 0x80 // Divisor latch access bit #define COM_LCR_WLEN8 0x03 // Wordlength: 8 bits #define COM_MCR 4 // Out: Modem Control Register #define COM_MCR_RTS 0x02 // RTS complement #define COM_MCR_DTR 0x01 // DTR complement #define COM_MCR_OUT2 0x08 // Out2 complement #define COM_LSR 5 // In: Line Status Register #define COM_LSR_DATA 0x01 // Data available #define COM_LSR_TXRDY 0x20 // Transmit buffer avail #define COM_LSR_TSRE 0x40 // Transmitter off static bool serial_exists; static int serial_proc_data(void) { if (!(inb(COM1+COM_LSR) & COM_LSR_DATA)) return -1; return inb(COM1+COM_RX); } void serial_intr(void) { if (serial_exists) cons_intr(serial_proc_data); } static void serial_putc(int c) { int i; for (i = 0; !(inb(COM1 + COM_LSR) & COM_LSR_TXRDY) && i < 12800; i++) delay(); outb(COM1 + COM_TX, c); } static void serial_init(void) { // Turn off the FIFO outb(COM1+COM_FCR, 0); // Set speed; requires DLAB latch outb(COM1+COM_LCR, COM_LCR_DLAB); outb(COM1+COM_DLL, (uint8_t) (115200 / 9600)); outb(COM1+COM_DLM, 0); // 8 data bits, 1 stop bit, parity off; turn off DLAB latch outb(COM1+COM_LCR, COM_LCR_WLEN8 & ~COM_LCR_DLAB); // No modem controls outb(COM1+COM_MCR, 0); // Enable rcv interrupts outb(COM1+COM_IER, COM_IER_RDI); // Clear any preexisting overrun indications and interrupts // Serial port doesn't exist if COM_LSR returns 0xFF serial_exists = (inb(COM1+COM_LSR) != 0xFF); (void) inb(COM1+COM_IIR); (void) inb(COM1+COM_RX); } /***** Parallel port output code *****/ // For information on PC parallel port programming, see the class References // page. static void lpt_putc(int c) { int i; for (i = 0; !(inb(0x378+1) & 0x80) && i < 12800; i++) delay(); outb(0x378+0, c); outb(0x378+2, 0x08|0x04|0x01); outb(0x378+2, 0x08); } /***** Text-mode CGA/VGA display output *****/ static unsigned addr_6845; static uint16_t *crt_buf; static uint16_t crt_pos; static void cga_init(void) { volatile uint16_t *cp; uint16_t was; unsigned pos; cp = (uint16_t*) (KERNBASE + CGA_BUF); was = *cp; *cp = (uint16_t) 0xA55A; if (*cp != 0xA55A) { cp = (uint16_t*) (KERNBASE + MONO_BUF); addr_6845 = MONO_BASE; } else { *cp = was; addr_6845 = CGA_BASE; } /* Extract cursor location */ outb(addr_6845, 14); pos = inb(addr_6845 + 1) << 8; outb(addr_6845, 15); pos |= inb(addr_6845 + 1); crt_buf = (uint16_t*) cp; crt_pos = pos; } static void cga_putc(int c) { // if no attribute given, then use black on white if (!(c & ~0xFF)) c |= 0x0700; switch (c & 0xff) { case '\b': if (crt_pos > 0) { crt_pos--; crt_buf[crt_pos] = (c & ~0xff) | ' '; } break; case '\n': crt_pos += CRT_COLS; /* fallthru */ case '\r': crt_pos -= (crt_pos % CRT_COLS); break; case '\t': cons_putc(' '); cons_putc(' '); cons_putc(' '); cons_putc(' '); cons_putc(' '); break; default: crt_buf[crt_pos++] = c; /* write the character */ break; } // What is the purpose of this? if (crt_pos >= CRT_SIZE) { int i; memmove(crt_buf, crt_buf + CRT_COLS, (CRT_SIZE - CRT_COLS) * sizeof(uint16_t)); for (i = CRT_SIZE - CRT_COLS; i < CRT_SIZE; i++) crt_buf[i] = 0x0700 | ' '; crt_pos -= CRT_COLS; } /* move that little blinky thing */ outb(addr_6845, 14); outb(addr_6845 + 1, crt_pos >> 8); outb(addr_6845, 15); outb(addr_6845 + 1, crt_pos); } /***** Keyboard input code *****/ #define NO 0 #define SHIFT (1<<0) #define CTL (1<<1) #define ALT (1<<2) #define CAPSLOCK (1<<3) #define NUMLOCK (1<<4) #define SCROLLLOCK (1<<5) #define E0ESC (1<<6) static uint8_t shiftcode[256] = { [0x1D] = CTL, [0x2A] = SHIFT, [0x36] = SHIFT, [0x38] = ALT, [0x9D] = CTL, [0xB8] = ALT }; static uint8_t togglecode[256] = { [0x3A] = CAPSLOCK, [0x45] = NUMLOCK, [0x46] = SCROLLLOCK }; static uint8_t normalmap[256] = { NO, 0x1B, '1', '2', '3', '4', '5', '6', // 0x00 '7', '8', '9', '0', '-', '=', '\b', '\t', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', // 0x10 'o', 'p', '[', ']', '\n', NO, 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', // 0x20 '\'', '`', NO, '\\', 'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/', NO, '*', // 0x30 NO, ' ', NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, '7', // 0x40 '8', '9', '-', '4', '5', '6', '+', '1', '2', '3', '0', '.', NO, NO, NO, NO, // 0x50 [0xC7] = KEY_HOME, [0x9C] = '\n' /*KP_Enter*/, [0xB5] = '/' /*KP_Div*/, [0xC8] = KEY_UP, [0xC9] = KEY_PGUP, [0xCB] = KEY_LF, [0xCD] = KEY_RT, [0xCF] = KEY_END, [0xD0] = KEY_DN, [0xD1] = KEY_PGDN, [0xD2] = KEY_INS, [0xD3] = KEY_DEL }; static uint8_t shiftmap[256] = { NO, 033, '!', '@', '#', '$', '%', '^', // 0x00 '&', '*', '(', ')', '_', '+', '\b', '\t', 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', // 0x10 'O', 'P', '{', '}', '\n', NO, 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ':', // 0x20 '"', '~', NO, '|', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', '<', '>', '?', NO, '*', // 0x30 NO, ' ', NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, '7', // 0x40 '8', '9', '-', '4', '5', '6', '+', '1', '2', '3', '0', '.', NO, NO, NO, NO, // 0x50 [0xC7] = KEY_HOME, [0x9C] = '\n' /*KP_Enter*/, [0xB5] = '/' /*KP_Div*/, [0xC8] = KEY_UP, [0xC9] = KEY_PGUP, [0xCB] = KEY_LF, [0xCD] = KEY_RT, [0xCF] = KEY_END, [0xD0] = KEY_DN, [0xD1] = KEY_PGDN, [0xD2] = KEY_INS, [0xD3] = KEY_DEL }; #define C(x) (x - '@') static uint8_t ctlmap[256] = { NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, C('Q'), C('W'), C('E'), C('R'), C('T'), C('Y'), C('U'), C('I'), C('O'), C('P'), NO, NO, '\r', NO, C('A'), C('S'), C('D'), C('F'), C('G'), C('H'), C('J'), C('K'), C('L'), NO, NO, NO, NO, C('\\'), C('Z'), C('X'), C('C'), C('V'), C('B'), C('N'), C('M'), NO, NO, C('/'), NO, NO, [0x97] = KEY_HOME, [0xB5] = C('/'), [0xC8] = KEY_UP, [0xC9] = KEY_PGUP, [0xCB] = KEY_LF, [0xCD] = KEY_RT, [0xCF] = KEY_END, [0xD0] = KEY_DN, [0xD1] = KEY_PGDN, [0xD2] = KEY_INS, [0xD3] = KEY_DEL }; static uint8_t *charcode[4] = { normalmap, shiftmap, ctlmap, ctlmap }; /* * Get data from the keyboard. If we finish a character, return it. Else 0. * Return -1 if no data. */ static int kbd_proc_data(void) { int c; uint8_t stat, data; static uint32_t shift; stat = inb(KBSTATP); if ((stat & KBS_DIB) == 0) return -1; // Ignore data from mouse. if (stat & KBS_TERR) return -1; data = inb(KBDATAP); if (data == 0xE0) { // E0 escape character shift |= E0ESC; return 0; } else if (data & 0x80) { // Key released data = (shift & E0ESC ? data : data & 0x7F); shift &= ~(shiftcode[data] | E0ESC); return 0; } else if (shift & E0ESC) { // Last character was an E0 escape; or with 0x80 data |= 0x80; shift &= ~E0ESC; } shift |= shiftcode[data]; shift ^= togglecode[data]; c = charcode[shift & (CTL | SHIFT)][data]; if (shift & CAPSLOCK) { if ('a' <= c && c <= 'z') c += 'A' - 'a'; else if ('A' <= c && c <= 'Z') c += 'a' - 'A'; } // Process special keys // Ctrl-Alt-Del: reboot if (!(~shift & (CTL | ALT)) && c == KEY_DEL) { cprintf("Rebooting!\n"); outb(0x92, 0x3); // courtesy of <NAME> } return c; } void kbd_intr(void) { cons_intr(kbd_proc_data); } static void kbd_init(void) { // Drain the kbd buffer so that QEMU generates interrupts. kbd_intr(); irq_setmask_8259A(irq_mask_8259A & ~(1<<IRQ_KBD)); } /***** General device-independent console code *****/ // Here we manage the console input buffer, // where we stash characters received from the keyboard or serial port // whenever the corresponding interrupt occurs. #define CONSBUFSIZE 512 static struct { uint8_t buf[CONSBUFSIZE]; uint32_t rpos; uint32_t wpos; } cons; // called by device interrupt routines to feed input characters // into the circular console input buffer. static void cons_intr(int (*proc)(void)) { int c; while ((c = (*proc)()) != -1) { if (c == 0) continue; cons.buf[cons.wpos++] = c; if (cons.wpos == CONSBUFSIZE) cons.wpos = 0; } } // return the next input character from the console, or 0 if none waiting int cons_getc(void) { int c; // poll for any pending input characters, // so that this function works even when interrupts are disabled // (e.g., when called from the kernel monitor). serial_intr(); kbd_intr(); // grab the next character from the input buffer. if (cons.rpos != cons.wpos) { c = cons.buf[cons.rpos++]; if (cons.rpos == CONSBUFSIZE) cons.rpos = 0; return c; } return 0; } // output a character to the console static void cons_putc(int c) { serial_putc(c); lpt_putc(c); cga_putc(c); } // initialize the console devices void cons_init(void) { cga_init(); kbd_init(); serial_init(); if (!serial_exists) cprintf("Serial port does not exist!\n"); } // `High'-level console I/O. Used by readline and cprintf. void cputchar(int c) { cons_putc(c); } int getchar(void) { int c; while ((c = cons_getc()) == 0) /* do nothing */; return c; } int iscons(int fdnum) { // used by readline return 1; }
syang2forever/jos
jos/user/faultbadhandler.c
// test bad pointer for user-level fault handler // this is going to fault in the fault handler accessing eip (always!) // so eventually the kernel kills it (PFM_KILL) because // we outrun the stack with invocations of the user-level handler #include <inc/lib.h> void umain(int argc, char **argv) { sys_page_alloc(0, (void*) (UXSTACKTOP - PGSIZE), PTE_P|PTE_U|PTE_W); sys_env_set_pgfault_upcall(0, (void*) 0xDeadBeef); *(int*)0 = 0; }
NewLukasz/KsiazkaAdresowaPPP
AdresatMenedzer.h
#ifndef ADRESATMENEDZER_H #define ADRESATMENEDZER_H #include <iostream> #include <vector> #include <cstdlib> #include "Adresat.h" #include "MetodyPomocnicze.h" #include "PlikZAdresatami.h" using namespace std; class AdresatMenedzer{ Adresat adresat; vector <Adresat> adresaci; PlikZAdresatami plikZAdresatami; int idOstatniegoAdresta; const int ID_ZALOGOWANEGO_UZYTKOWNIKA; public: AdresatMenedzer(string nazwaPlikuZAdresatami, int idZalogowanegoUzytkownika) : plikZAdresatami(nazwaPlikuZAdresatami), ID_ZALOGOWANEGO_UZYTKOWNIKA(idZalogowanegoUzytkownika){ adresaci=plikZAdresatami.wczytajAdresatowZalogowanegoUzytkownikaZPliku(ID_ZALOGOWANEGO_UZYTKOWNIKA); idOstatniegoAdresta=plikZAdresatami.pobierzIdOstatniegoAdresata(); }; void dodajAdresata(); void wypiszWszystkichAdresatow(); int przeslijIdOstatniegoAdresata(); void wyswietlKontaktyWyszukanePoImieniu(); void wyswietlKontaktyWyszukanePoNazwisku(); void usunWybranegoAdresata(); void edytujAdresata(); }; #endif
NewLukasz/KsiazkaAdresowaPPP
Adresat.h
#ifndef ADRESAT_H #define ADRESAT_H #include <iostream> using namespace std; class Adresat{ int id, idUzytkownika; string imie,nazwisko,numerTelefonu,email,adres; public: int pobierzId(); int pobierzIdUzytkownika(); string pobierzImie(); string pobierzNazwisko(); string pobierzNumerTelefonu(); string pobierzEmail(); string pobierzAdres(); void ustawId(int idDoUstawienia); void ustawIdUzytkownika(int idUzytkownikaDoUstawienia); void ustawImie(string imieDoUstawienia); void ustawNazwisko(string nazwiskoDoUstawienia); void ustawNumerTelefonu(string numerTelefonuDoUstawienia); void ustawEmail(string emailDoUstawienia); void ustawAdres(string adresDoUstawienia); Adresat(int =0,int =0, string ="", string ="", string ="", string ="",string ="" ); void wypiszDaneAdresata(); }; #endif
NewLukasz/KsiazkaAdresowaPPP
KsiazkaAdresowa.h
#ifndef KSIAZKAADRESOWA_H #define KSIAZKAADRESOWA_H #include <iostream> #include "UzytkownikMenedzer.h" #include "AdresatMenedzer.h" using namespace std; class KsiazkaAdresowa { UzytkownikMenedzer uzytkownikMenedzer; AdresatMenedzer *adresatMenedzer; const string NAZWA_PLIKU_Z_ADRESATAMI; vector <Uzytkownik> uzytkownicy; public: KsiazkaAdresowa(string nazwaPlikuZUzytkownikami, string nazwaPlikuZAdresatami) : uzytkownikMenedzer(nazwaPlikuZUzytkownikami), NAZWA_PLIKU_Z_ADRESATAMI(nazwaPlikuZAdresatami) { adresatMenedzer= NULL; }; ~KsiazkaAdresowa(){ delete adresatMenedzer; adresatMenedzer=NULL; } void rejestracjaUzytkownika(); void wypiszWszystkichUzytkownikow(); char wybierzOpcjeZMenuUzytkownika(); char wybierzOpcjeZMenuGlownego(); int logowanieUzytkownika(); void dodajAdresata(); void wypiszDaneWszytkichAdresatow(); int przeslijIdOstatniegoAdresata(); void wyswietlKontaktyWyszukanePoImieniu(); void wyswietlKontaktyWyszukanePoNazwisku(); void usunWybranegoAdresata(); void zaladujUzytkownikowPonownieZPliku(); void edytujAdresata(); void edytujHasloUzytkownika(); }; #endif
NewLukasz/KsiazkaAdresowaPPP
PlikZAdresatami.h
<gh_stars>0 #ifndef PLIKZADRESATAMI_H #define PLIKZADRESATAMI_H #include <iostream> #include <fstream> #include <cstdlib> #include <vector> #include <stdio.h> #include "Adresat.h" #include "MetodyPomocnicze.h" using namespace std; class PlikZAdresatami { Adresat adresat; string zamienDaneAdresataNaLinieZDanymiOddzielonymiPionowymiKreskami(Adresat adresat); bool czyPlikJestPusty(fstream &plikTekstowy); string nazwaPlikuZAdresatami; int idOstatniegoAdresata; public: PlikZAdresatami(string nazwaPlikuZAdresatamiWyslana); void dopiszAdrestaDoPliku(Adresat adresat); vector <Adresat> wczytajAdresatowZalogowanegoUzytkownikaZPliku(int idZalogowanegoUzytkownika); int pobierzIdUzytkownikaZDanychOddzielonychPionowymiKreskami(string daneJednegoAdresataOddzielonePionowymiKreskami); Adresat pobierzDaneAdresata(string daneAdresataOddzielonePionowymiKreskami); int pobierzIdAdresataZDanychOddzielonychPionowymiKreskami(string daneJednegoAdresataOddzielonePionowymiKreskami); string pobierzLiczbe(string tekst, int pozycjaZnaku); int pobierzIdOstatniegoAdresata(); void usuwanieAdresataZPliku(int iDAdresataDoUsuniecia); void modyfikacjaAdresataWPliku(int idAdresataDoEdycji,Adresat adresat); }; #endif
NewLukasz/KsiazkaAdresowaPPP
PlikZUzytkownikami.h
<filename>PlikZUzytkownikami.h<gh_stars>0 #ifndef PLIKZUZYTKOWNIKAMI_H #define PLIKZUZYTKOWNIKAMI_H #include <iostream> #include <vector> #include <fstream> #include <cstdlib> #include "Uzytkownik.h" #include "MetodyPomocnicze.h" using namespace std; class PlikZUzytkownikami { const string nazwaPlikuZUzytkownikami; Uzytkownik uzytkownik; string daneJednegoUzytkownikaOddzielonePionowymiKreskami; bool czyPlikJestPusty(fstream &plikTekstowy); string zamienDaneUzytkownikaNaLinieZDanymiOddzielonaPionowymiKreskami(Uzytkownik uzytkownik); Uzytkownik pobierzDaneUzytkownika(); public: PlikZUzytkownikami(string NAZWAPLIKUZUZYTKOWNIKAMI) : nazwaPlikuZUzytkownikami(NAZWAPLIKUZUZYTKOWNIKAMI){daneJednegoUzytkownikaOddzielonePionowymiKreskami = "";} ; void dopiszUzytkownikaDoPliku(Uzytkownik uzytkownik); vector <Uzytkownik> wczytajUzytkownikowZPliku(); void zmianaHasloUzytkownika(int idZalogowaneUzytkownika, Uzytkownik uzytkownik); int pobierzIdUzytkownikaZDanychOddzielonychPionowymiKreskami(string daneJednegoUzytkownikaOddzielonePionowymiKreskami); string pobierzLiczbe(string tekst, int pozycjaZnaku); }; #endif
NewLukasz/KsiazkaAdresowaPPP
MetodyPomocnicze.h
#ifndef METODYPOMOCNICZE_H #define METODYPOMOCNICZE_H #include <iostream> #include <sstream> #include <cstdlib> using namespace std; class MetodyPomocnicze{ public: static string konwerjsaIntNaString(int liczba); static char wczytajZnak(); static string wczytajLinie(); static int konwersjaStringNaInt(string liczba); }; #endif
blueboxd/chromium-legacy
chrome/browser/ui/autofill/chrome_autofill_client.h
// 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_AUTOFILL_CHROME_AUTOFILL_CLIENT_H_ #define CHROME_BROWSER_UI_AUTOFILL_CHROME_AUTOFILL_CLIENT_H_ #include <memory> #include <string> #include <vector> #include "base/callback.h" #include "base/compiler_specific.h" #include "base/i18n/rtl.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "build/build_config.h" #include "chrome/browser/autofill/autofill_gstatic_reader.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/autofill/payments/autofill_error_dialog_controller_impl.h" #include "chrome/browser/ui/autofill/payments/autofill_progress_dialog_controller_impl.h" #include "components/autofill/core/browser/autofill_client.h" #include "components/autofill/core/browser/logging/log_manager.h" #include "components/autofill/core/browser/payments/legal_message_line.h" #include "components/autofill/core/browser/ui/payments/card_unmask_prompt_controller_impl.h" #include "components/signin/public/identity_manager/account_info.h" #include "content/public/browser/visibility.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/browser/web_contents_user_data.h" #if defined(OS_ANDROID) #include "chrome/browser/autofill/android/save_update_address_profile_flow_manager.h" #include "chrome/browser/ui/android/autofill/save_card_message_controller_android.h" #include "components/autofill/core/browser/ui/payments/card_expiration_date_fix_flow_controller_impl.h" #include "components/autofill/core/browser/ui/payments/card_name_fix_flow_controller_impl.h" #else // !OS_ANDROID #include "chrome/browser/ui/autofill/payments/manage_migration_ui_controller.h" #include "chrome/browser/ui/autofill/payments/save_card_bubble_controller.h" #include "components/zoom/zoom_observer.h" #endif namespace autofill { class AutofillPopupControllerImpl; // Chrome implementation of AutofillClient. class ChromeAutofillClient : public AutofillClient, public content::WebContentsUserData<ChromeAutofillClient>, public content::WebContentsObserver #if !defined(OS_ANDROID) , public zoom::ZoomObserver #endif // !defined(OS_ANDROID) { public: ChromeAutofillClient(const ChromeAutofillClient&) = delete; ChromeAutofillClient& operator=(const ChromeAutofillClient&) = delete; ~ChromeAutofillClient() override; // AutofillClient: version_info::Channel GetChannel() const override; PersonalDataManager* GetPersonalDataManager() override; AutocompleteHistoryManager* GetAutocompleteHistoryManager() override; PrefService* GetPrefs() override; const PrefService* GetPrefs() const override; syncer::SyncService* GetSyncService() override; signin::IdentityManager* GetIdentityManager() override; FormDataImporter* GetFormDataImporter() override; payments::PaymentsClient* GetPaymentsClient() override; StrikeDatabase* GetStrikeDatabase() override; ukm::UkmRecorder* GetUkmRecorder() override; ukm::SourceId GetUkmSourceId() override; AddressNormalizer* GetAddressNormalizer() override; AutofillOfferManager* GetAutofillOfferManager() override; const GURL& GetLastCommittedURL() const override; security_state::SecurityLevel GetSecurityLevelForUmaHistograms() override; const translate::LanguageState* GetLanguageState() override; translate::TranslateDriver* GetTranslateDriver() override; std::string GetVariationConfigCountryCode() const override; profile_metrics::BrowserProfileType GetProfileType() const override; std::unique_ptr<webauthn::InternalAuthenticator> CreateCreditCardInternalAuthenticator(content::RenderFrameHost* rfh) override; void ShowAutofillSettings(bool show_credit_card_settings) override; void ShowCardUnmaskOtpInputDialog( const size_t& otp_length, base::WeakPtr<OtpUnmaskDelegate> delegate) override; void OnUnmaskOtpVerificationResult(OtpUnmaskResult unmask_result) override; void ShowUnmaskPrompt(const CreditCard& card, UnmaskCardReason reason, base::WeakPtr<CardUnmaskDelegate> delegate) override; void OnUnmaskVerificationResult(PaymentsRpcResult result) override; void ShowUnmaskAuthenticatorSelectionDialog( const std::vector<CardUnmaskChallengeOption>& challenge_options, base::OnceCallback<void(const std::string&)> confirm_unmask_challenge_option_callback, base::OnceClosure cancel_unmasking_closure) override; void DismissUnmaskAuthenticatorSelectionDialog() override; #if !defined(OS_ANDROID) std::vector<std::string> GetAllowedMerchantsForVirtualCards() override; std::vector<std::string> GetAllowedBinRangesForVirtualCards() override; void ShowLocalCardMigrationDialog( base::OnceClosure show_migration_dialog_closure) override; void ConfirmMigrateLocalCardToCloud( const LegalMessageLines& legal_message_lines, const std::string& user_email, const std::vector<MigratableCreditCard>& migratable_credit_cards, LocalCardMigrationCallback start_migrating_cards_callback) override; void ShowLocalCardMigrationResults( const bool has_server_error, const std::u16string& tip_message, const std::vector<MigratableCreditCard>& migratable_credit_cards, MigrationDeleteCardCallback delete_local_card_callback) override; void ShowWebauthnOfferDialog( WebauthnDialogCallback offer_dialog_callback) override; void ShowWebauthnVerifyPendingDialog( WebauthnDialogCallback verify_pending_dialog_callback) override; void UpdateWebauthnOfferDialogWithError() override; bool CloseWebauthnDialog() override; void ConfirmSaveUpiIdLocally( const std::string& upi_id, base::OnceCallback<void(bool accept)> callback) override; void OfferVirtualCardOptions( const std::vector<CreditCard*>& candidates, base::OnceCallback<void(const std::string&)> callback) override; #else // defined(OS_ANDROID) void ConfirmAccountNameFixFlow( base::OnceCallback<void(const std::u16string&)> callback) override; void ConfirmExpirationDateFixFlow( const CreditCard& card, base::OnceCallback<void(const std::u16string&, const std::u16string&)> callback) override; #endif void ConfirmSaveCreditCardLocally( const CreditCard& card, SaveCreditCardOptions options, LocalSaveCardPromptCallback callback) override; void ConfirmSaveCreditCardToCloud( const CreditCard& card, const LegalMessageLines& legal_message_lines, SaveCreditCardOptions options, UploadSaveCardPromptCallback callback) override; void CreditCardUploadCompleted(bool card_saved) override; void ConfirmCreditCardFillAssist(const CreditCard& card, base::OnceClosure callback) override; void ConfirmSaveAddressProfile( const AutofillProfile& profile, const AutofillProfile* original_profile, SaveAddressProfilePromptOptions options, AddressProfileSavePromptCallback callback) override; bool HasCreditCardScanFeature() override; void ScanCreditCard(CreditCardScanCallback callback) override; void ShowAutofillPopup( const PopupOpenArgs& open_args, base::WeakPtr<AutofillPopupDelegate> delegate) override; void UpdateAutofillPopupDataListValues( const std::vector<std::u16string>& values, const std::vector<std::u16string>& labels) override; base::span<const Suggestion> GetPopupSuggestions() const override; void PinPopupView() override; PopupOpenArgs GetReopenPopupArgs() const override; void UpdatePopup(const std::vector<Suggestion>& suggestions, PopupType popup_type) override; void HideAutofillPopup(PopupHidingReason reason) override; void ShowOfferNotificationIfApplicable( const AutofillOfferData* offer) override; void OnVirtualCardDataAvailable( const std::u16string& masked_card_identifier_string, const CreditCard* credit_card, const std::u16string& cvc, const gfx::Image& card_image) override; void ShowVirtualCardErrorDialog(bool is_permanent_error) override; void ShowAutofillProgressDialog(base::OnceClosure cancel_callback) override; void CloseAutofillProgressDialog( bool show_confirmation_before_closing) override; bool IsAutofillAssistantShowing() override; bool IsAutocompleteEnabled() override; void PropagateAutofillPredictions( content::RenderFrameHost* rfh, const std::vector<FormStructure*>& forms) override; void DidFillOrPreviewField(const std::u16string& autofilled_value, const std::u16string& profile_full_name) override; bool IsContextSecure() const override; bool ShouldShowSigninPromo() override; bool AreServerCardsSupported() const override; void ExecuteCommand(int id) override; LogManager* GetLogManager() const override; // RiskDataLoader: void LoadRiskData( base::OnceCallback<void(const std::string&)> callback) override; // content::WebContentsObserver implementation. void PrimaryMainFrameWasResized(bool width_changed) override; void WebContentsDestroyed() override; void OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) override; base::WeakPtr<AutofillPopupControllerImpl> popup_controller_for_testing() { return popup_controller_; } void KeepPopupOpenForTesting() { keep_popup_open_for_testing_ = true; } #if !defined(OS_ANDROID) // ZoomObserver implementation. void OnZoomChanged( const zoom::ZoomController::ZoomChangedEventData& data) override; #endif // !defined(OS_ANDROID) private: friend class content::WebContentsUserData<ChromeAutofillClient>; explicit ChromeAutofillClient(content::WebContents* web_contents); Profile* GetProfile() const; bool IsMultipleAccountUser(); std::u16string GetAccountHolderName(); std::unique_ptr<payments::PaymentsClient> payments_client_; std::unique_ptr<FormDataImporter> form_data_importer_; base::WeakPtr<AutofillPopupControllerImpl> popup_controller_; std::unique_ptr<LogManager> log_manager_; // If set to true, the popup will stay open regardless of external changes on // the test machine, that may normally cause the popup to be hidden bool keep_popup_open_for_testing_ = false; #if defined(OS_ANDROID) CardExpirationDateFixFlowControllerImpl card_expiration_date_fix_flow_controller_; CardNameFixFlowControllerImpl card_name_fix_flow_controller_; SaveCardMessageControllerAndroid save_card_message_controller_android_; SaveUpdateAddressProfileFlowManager save_update_address_profile_flow_manager_; #endif CardUnmaskPromptControllerImpl unmask_controller_; AutofillErrorDialogControllerImpl autofill_error_dialog_controller_; std::unique_ptr<AutofillProgressDialogControllerImpl> autofill_progress_dialog_controller_; WEB_CONTENTS_USER_DATA_KEY_DECL(); }; } // namespace autofill #endif // CHROME_BROWSER_UI_AUTOFILL_CHROME_AUTOFILL_CLIENT_H_
blueboxd/chromium-legacy
chrome/test/media_router/media_router_cast_ui_for_test.h
<reponame>blueboxd/chromium-legacy // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_TEST_MEDIA_ROUTER_MEDIA_ROUTER_CAST_UI_FOR_TEST_H_ #define CHROME_TEST_MEDIA_ROUTER_MEDIA_ROUTER_CAST_UI_FOR_TEST_H_ #include "base/callback_forward.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/ui/views/media_router/media_router_dialog_controller_views.h" #include "chrome/test/media_router/media_router_ui_for_test_base.h" #include "components/media_router/common/media_sink.h" #include "components/media_router/common/media_source.h" #include "content/public/browser/web_contents_user_data.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace media_router { class MediaRouterCastUiForTest : public MediaRouterUiForTestBase, public content::WebContentsUserData<MediaRouterCastUiForTest>, public CastDialogView::Observer { public: static MediaRouterCastUiForTest* GetOrCreateForWebContents( content::WebContents* web_contents); MediaRouterCastUiForTest(const MediaRouterCastUiForTest&) = delete; MediaRouterCastUiForTest& operator=(const MediaRouterCastUiForTest&) = delete; ~MediaRouterCastUiForTest() override; // MediaRouterUiForTestBase: void SetUp() override; void ShowDialog() override; bool IsDialogShown() const override; void HideDialog() override; void ChooseSourceType(CastDialogView::SourceType source_type) override; CastDialogView::SourceType GetChosenSourceType() const override; void WaitForSink(const std::string& sink_name) override; void WaitForSinkAvailable(const std::string& sink_name) override; void WaitForAnyIssue() override; void WaitForAnyRoute() override; void WaitForDialogShown() override; void WaitForDialogHidden() override; void SetLocalFile(const GURL& file_url) override; void SetLocalFileSelectionIssue(const IssueInfo& issue) override; void OnDialogCreated() override; private: friend class content::WebContentsUserData<MediaRouterCastUiForTest>; explicit MediaRouterCastUiForTest(content::WebContents* web_contents); // CastDialogView::Observer: void OnDialogModelUpdated(CastDialogView* dialog_view) override; void OnDialogWillClose(CastDialogView* dialog_view) override; // MediaRouterUiForTestBase: CastDialogSinkButton* GetSinkButton( const std::string& sink_name) const override; // Registers itself as an observer to the dialog, and waits until an event // of |watch_type| is observed. |sink_name| should be set only if observing // for a sink. void ObserveDialog( WatchType watch_type, absl::optional<std::string> sink_name = absl::nullopt) override; WEB_CONTENTS_USER_DATA_KEY_DECL(); }; } // namespace media_router #endif // CHROME_TEST_MEDIA_ROUTER_MEDIA_ROUTER_CAST_UI_FOR_TEST_H_
blueboxd/chromium-legacy
media/gpu/vaapi/vp9_vaapi_video_encoder_delegate.h
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MEDIA_GPU_VAAPI_VP9_VAAPI_VIDEO_ENCODER_DELEGATE_H_ #define MEDIA_GPU_VAAPI_VP9_VAAPI_VIDEO_ENCODER_DELEGATE_H_ #include <list> #include <memory> #include <utility> #include <vector> #include "base/macros.h" #include "media/base/video_bitrate_allocation.h" #include "media/filters/vp9_parser.h" #include "media/gpu/vaapi/vaapi_video_encoder_delegate.h" #include "media/gpu/vaapi/vpx_rate_control.h" #include "media/gpu/vp9_picture.h" #include "media/gpu/vp9_reference_frame_vector.h" namespace libvpx { struct VP9FrameParamsQpRTC; class VP9RateControlRTC; struct VP9RateControlRtcConfig; } // namespace libvpx namespace media { class VaapiWrapper; class VP9SVCLayers; class VP9VaapiVideoEncoderDelegate : public VaapiVideoEncoderDelegate { public: struct EncodeParams { EncodeParams(); // Produce a keyframe at least once per this many frames. size_t kf_period_frames; // Bitrate allocation in bps. VideoBitrateAllocation bitrate_allocation; // Framerate in FPS. uint32_t framerate; // Quantization parameter. They are vp9 ac/dc indices and their ranges are // 0-255. uint8_t min_qp; uint8_t max_qp; }; VP9VaapiVideoEncoderDelegate(scoped_refptr<VaapiWrapper> vaapi_wrapper, base::RepeatingClosure error_cb); VP9VaapiVideoEncoderDelegate(const VP9VaapiVideoEncoderDelegate&) = delete; VP9VaapiVideoEncoderDelegate& operator=(const VP9VaapiVideoEncoderDelegate&) = delete; ~VP9VaapiVideoEncoderDelegate() override; // VaapiVideoEncoderDelegate implementation. bool Initialize(const VideoEncodeAccelerator::Config& config, const VaapiVideoEncoderDelegate::Config& ave_config) override; bool UpdateRates(const VideoBitrateAllocation& bitrate_allocation, uint32_t framerate) override; gfx::Size GetCodedSize() const override; size_t GetMaxNumOfRefFrames() const override; std::vector<gfx::Size> GetSVCLayerResolutions() override; private: friend class VP9VaapiVideoEncoderDelegateTest; friend class VaapiVideoEncodeAcceleratorTest; using VP9RateControl = VPXRateControl<libvpx::VP9RateControlRtcConfig, libvpx::VP9RateControlRTC, libvpx::VP9FrameParamsQpRTC>; void set_rate_ctrl_for_testing(std::unique_ptr<VP9RateControl> rate_ctrl); bool ApplyPendingUpdateRates(); bool PrepareEncodeJob(EncodeJob& encode_job) override; BitstreamBufferMetadata GetMetadata(const EncodeJob& encode_job, size_t payload_size) override; void BitrateControlUpdate(uint64_t encoded_chunk_size_bytes) override; Vp9FrameHeader GetDefaultFrameHeader(const bool keyframe) const; void SetFrameHeader(bool keyframe, VP9Picture* picture, std::array<bool, kVp9NumRefsPerFrame>* ref_frames_used); void UpdateReferenceFrames(scoped_refptr<VP9Picture> picture); bool SubmitFrameParameters( EncodeJob& job, const EncodeParams& encode_params, scoped_refptr<VP9Picture> pic, const Vp9ReferenceFrameVector& ref_frames, const std::array<bool, kVp9NumRefsPerFrame>& ref_frames_used); gfx::Size visible_size_; gfx::Size coded_size_; // Macroblock-aligned. // Frame count since last keyframe, reset to 0 every keyframe period. size_t frame_num_ = 0; size_t ref_frame_index_ = 0; EncodeParams current_params_; Vp9ReferenceFrameVector reference_frames_; std::unique_ptr<VP9SVCLayers> svc_layers_; absl::optional<std::pair<VideoBitrateAllocation, uint32_t>> pending_update_rates_; std::unique_ptr<VP9RateControl> rate_ctrl_; }; } // namespace media #endif // MEDIA_GPU_VAAPI_VP9_VAAPI_VIDEO_ENCODER_DELEGATE_H_
blueboxd/chromium-legacy
ash/system/time/calendar_utils.h
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_SYSTEM_TIME_CALENDAR_UTILS_H_ #define ASH_SYSTEM_TIME_CALENDAR_UTILS_H_ #include "base/time/time.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/gfx/geometry/insets.h" namespace views { class ColumnSet; } // namespace views namespace ash { namespace calendar_utils { // Number of days in one week. constexpr int kDateInOneWeek = 7; // The padding in each date cell view. constexpr int kDateVerticalPadding = 13; constexpr int kDateHorizontalPadding = 2; constexpr int kColumnSetPadding = 2; // The insets within a Date cell. constexpr gfx::Insets kDateCellInsets{kDateVerticalPadding, kDateHorizontalPadding}; // Checks if the `selected_date` is local time today. bool IsToday(const base::Time::Exploded& selected_date); // Gets the given `date`'s `Exploded` instance, in local time. base::Time::Exploded GetExplodedLocal(const base::Time& date); // Gets the given `date`'s `Exploded` instance, in UTC time. base::Time::Exploded GetExplodedUTC(const base::Time& date); // Gets the given `date`'s month name in string in the current language. std::u16string GetMonthName(const base::Time date); // Set up the `GridLayout` to have 7 columns, which is one week row (7 days). void SetUpWeekColumnSets(views::ColumnSet* column_set); // Colors. SkColor GetPrimaryTextColor(); SkColor GetSecondaryTextColor(); // Get local midnight on the first day of the month that includes |date|. base::Time GetStartOfMonthLocal(const base::Time& date); // Get local midnight on the first day of the month before the one that includes // |date|. base::Time GetStartOfPreviousMonthLocal(base::Time date); // Get local midnight on the first day of the month after the one that includes // |date|. base::Time GetStartOfNextMonthLocal(base::Time date); // Get UTC midnight on the first day of the month that includes |date|. base::Time GetStartOfMonthUTC(const base::Time& date); // Get UTC midnight on the first day of the month before the one that includes // |date|. base::Time GetStartOfPreviousMonthUTC(base::Time date); // Get UTC midnight on the first day of the month after the one that includes // |date|. base::Time GetStartOfNextMonthUTC(base::Time date); } // namespace calendar_utils } // namespace ash #endif // ASH_SYSTEM_TIME_CALENDAR_UTILS_H_
blueboxd/chromium-legacy
chrome/browser/ash/crosapi/crosapi_ash.h
<reponame>blueboxd/chromium-legacy // Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_ASH_CROSAPI_CROSAPI_ASH_H_ #define CHROME_BROWSER_ASH_CROSAPI_CROSAPI_ASH_H_ #include <map> #include <memory> #include "base/callback.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/ash/crosapi/crosapi_id.h" #include "chromeos/crosapi/mojom/crosapi.mojom.h" #include "chromeos/crosapi/mojom/task_manager.mojom.h" #include "mojo/public/cpp/bindings/generic_pending_receiver.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/receiver_set.h" namespace media { class StableVideoDecoderFactoryService; } // namespace media namespace crosapi { class AutomationAsh; class BrowserServiceHostAsh; class BrowserVersionServiceAsh; class CertDatabaseAsh; class ChromeAppWindowTrackerAsh; class ClipboardAsh; class ClipboardHistoryAsh; class ContentProtectionAsh; class DeviceAttributesAsh; class DeviceSettingsAsh; class DownloadControllerAsh; class DriveIntegrationServiceAsh; class FeedbackAsh; class FieldTrialServiceAsh; class FileManagerAsh; class ForceInstalledTrackerAsh; class GeolocationServiceAsh; class IdentityManagerAsh; class IdleServiceAsh; class ImageWriterAsh; class KeystoreServiceAsh; class KioskSessionServiceAsh; class LocalPrinterAsh; class LoginStateAsh; class MessageCenterAsh; class MetricsReportingAsh; class NativeThemeServiceAsh; class NetworkingAttributesAsh; class PolicyServiceAsh; class PowerAsh; class PrefsAsh; class RemotingAsh; class ResourceManagerAsh; class ScreenManagerAsh; class SelectFileAsh; class StructuredMetricsServiceAsh; class SystemDisplayAsh; class TaskManagerAsh; class TtsAsh; class WebPageInfoFactoryAsh; class UrlHandlerAsh; class VideoCaptureDeviceFactoryAsh; class NetworkSettingsServiceAsh; // Implementation of Crosapi in Ash. It provides a set of APIs that // crosapi clients, such as lacros-chrome, can call into. class CrosapiAsh : public mojom::Crosapi { public: CrosapiAsh(); ~CrosapiAsh() override; // Abstract base class to support dependency injection for tests. class TestControllerReceiver { public: virtual void BindReceiver( mojo::PendingReceiver<mojom::TestController> receiver) = 0; }; // Binds the given receiver to this instance. // |disconnected_handler| is called on the connection lost. void BindReceiver(mojo::PendingReceiver<mojom::Crosapi> pending_receiver, CrosapiId crosapi_id, base::OnceClosure disconnect_handler); // crosapi::mojom::Crosapi: void BindAutomationDeprecated( mojo::PendingReceiver<mojom::Automation> receiver) override; void BindAutomationFactory( mojo::PendingReceiver<mojom::AutomationFactory> receiver) override; void BindAccountManager( mojo::PendingReceiver<mojom::AccountManager> receiver) override; void BindAppServiceProxy( mojo::PendingReceiver<mojom::AppServiceProxy> receiver) override; void BindBrowserAppInstanceRegistry( mojo::PendingReceiver<mojom::BrowserAppInstanceRegistry> receiver) override; void BindBrowserServiceHost( mojo::PendingReceiver<mojom::BrowserServiceHost> receiver) override; void BindBrowserCdmFactory(mojo::GenericPendingReceiver receiver) override; void BindBrowserVersionService( mojo::PendingReceiver<mojom::BrowserVersionService> receiver) override; void BindCertDatabase( mojo::PendingReceiver<mojom::CertDatabase> receiver) override; void BindChromeAppPublisher( mojo::PendingReceiver<mojom::AppPublisher> receiver) override; void BindChromeAppWindowTracker( mojo::PendingReceiver<mojom::AppWindowTracker> receiver) override; void BindClipboard(mojo::PendingReceiver<mojom::Clipboard> receiver) override; void BindClipboardHistory( mojo::PendingReceiver<mojom::ClipboardHistory> receiver) override; void BindContentProtection( mojo::PendingReceiver<mojom::ContentProtection> receiver) override; void BindDeviceAttributes( mojo::PendingReceiver<mojom::DeviceAttributes> receiver) override; void BindDeviceSettingsService( mojo::PendingReceiver<mojom::DeviceSettingsService> receiver) override; void BindHoldingSpaceService( mojo::PendingReceiver<mojom::HoldingSpaceService> receiver) override; void BindDownloadController( mojo::PendingReceiver<mojom::DownloadController> receiver) override; void BindDriveIntegrationService( mojo::PendingReceiver<mojom::DriveIntegrationService> receiver) override; void BindFieldTrialService( mojo::PendingReceiver<mojom::FieldTrialService> receiver) override; void BindFileManager( mojo::PendingReceiver<mojom::FileManager> receiver) override; void BindForceInstalledTracker( mojo::PendingReceiver<mojom::ForceInstalledTracker> receiver) override; void BindGeolocationService( mojo::PendingReceiver<mojom::GeolocationService> receiver) override; void BindIdentityManager( mojo::PendingReceiver<mojom::IdentityManager> receiver) override; void BindIdleService( mojo::PendingReceiver<mojom::IdleService> receiver) override; void BindImageWriter( mojo::PendingReceiver<mojom::ImageWriter> receiver) override; void BindKeystoreService( mojo::PendingReceiver<mojom::KeystoreService> receiver) override; void BindKioskSessionService( mojo::PendingReceiver<mojom::KioskSessionService> receiver) override; void BindLocalPrinter( mojo::PendingReceiver<mojom::LocalPrinter> receiver) override; void BindLoginState( mojo::PendingReceiver<mojom::LoginState> receiver) override; void BindMessageCenter( mojo::PendingReceiver<mojom::MessageCenter> receiver) override; void BindMetricsReporting( mojo::PendingReceiver<mojom::MetricsReporting> receiver) override; void BindNativeThemeService( mojo::PendingReceiver<mojom::NativeThemeService> receiver) override; void BindNetworkingAttributes( mojo::PendingReceiver<mojom::NetworkingAttributes> receiver) override; void BindPolicyService( mojo::PendingReceiver<mojom::PolicyService> receiver) override; void BindPower(mojo::PendingReceiver<mojom::Power> receiver) override; void BindPrefs(mojo::PendingReceiver<mojom::Prefs> receiver) override; void BindRemoting(mojo::PendingReceiver<mojom::Remoting> receiver) override; void BindResourceManager( mojo::PendingReceiver<mojom::ResourceManager> receiver) override; void BindScreenManager( mojo::PendingReceiver<mojom::ScreenManager> receiver) override; void BindSelectFile( mojo::PendingReceiver<mojom::SelectFile> receiver) override; void BindSensorHalClient( mojo::PendingRemote<chromeos::sensors::mojom::SensorHalClient> remote) override; void BindStableVideoDecoderFactory( mojo::GenericPendingReceiver receiver) override; void BindHidManager( mojo::PendingReceiver<device::mojom::HidManager> receiver) override; void BindFeedback(mojo::PendingReceiver<mojom::Feedback> receiver) override; void OnBrowserStartup(mojom::BrowserInfoPtr browser_info) override; void BindMediaSessionController( mojo::PendingReceiver<media_session::mojom::MediaControllerManager> receiver) override; void BindMediaSessionAudioFocus( mojo::PendingReceiver<media_session::mojom::AudioFocusManager> receiver) override; void BindMediaSessionAudioFocusDebug( mojo::PendingReceiver<media_session::mojom::AudioFocusManagerDebug> receiver) override; void BindSystemDisplay( mojo::PendingReceiver<mojom::SystemDisplay> receiver) override; void BindWebPageInfoFactory( mojo::PendingReceiver<mojom::WebPageInfoFactory> receiver) override; void BindTaskManager( mojo::PendingReceiver<mojom::TaskManager> receiver) override; void BindTestController( mojo::PendingReceiver<mojom::TestController> receiver) override; void BindTts(mojo::PendingReceiver<mojom::Tts> receiver) override; void BindUrlHandler( mojo::PendingReceiver<mojom::UrlHandler> receiver) override; void BindMachineLearningService( mojo::PendingReceiver< chromeos::machine_learning::mojom::MachineLearningService> receiver) override; void BindVideoCaptureDeviceFactory( mojo::PendingReceiver<mojom::VideoCaptureDeviceFactory> receiver) override; void BindWebAppPublisher( mojo::PendingReceiver<mojom::AppPublisher> receiver) override; void BindNetworkSettingsService( ::mojo::PendingReceiver<::crosapi::mojom::NetworkSettingsService> receiver) override; void BindStructuredMetricsService( ::mojo::PendingReceiver<::crosapi::mojom::StructuredMetricsService> receiver) override; BrowserServiceHostAsh* browser_service_host_ash() { return browser_service_host_ash_.get(); } AutomationAsh* automation_ash() { return automation_ash_.get(); } DownloadControllerAsh* download_controller_ash() { return download_controller_ash_.get(); } ForceInstalledTrackerAsh* force_installed_tracker_ash() { return force_installed_tracker_ash_.get(); } KioskSessionServiceAsh* kiosk_session_service() { return kiosk_session_service_ash_.get(); } WebPageInfoFactoryAsh* web_page_info_factory_ash() { return web_page_info_factory_ash_.get(); } ImageWriterAsh* image_writer_ash() { return image_writer_ash_.get(); } LocalPrinterAsh* local_printer_ash() { return local_printer_ash_.get(); } NetworkingAttributesAsh* networking_attributes_ash() { return networking_attributes_ash_.get(); } TaskManagerAsh* task_manager_ash() { return task_manager_ash_.get(); } TtsAsh* tts_ash() { return tts_ash_.get(); } KeystoreServiceAsh* keystore_service_ash() { return keystore_service_ash_.get(); } LoginStateAsh* login_state_ash() { return login_state_ash_.get(); } StructuredMetricsServiceAsh* structured_metrics_service_ash() { return structured_metrics_service_ash_.get(); } // Caller is responsible for ensuring that the pointer stays valid. void SetTestControllerForTesting(TestControllerReceiver* test_controller); private: // Called when a connection is lost. void OnDisconnected(); std::unique_ptr<AutomationAsh> automation_ash_; std::unique_ptr<BrowserServiceHostAsh> browser_service_host_ash_; std::unique_ptr<BrowserVersionServiceAsh> browser_version_service_ash_; std::unique_ptr<CertDatabaseAsh> cert_database_ash_; std::unique_ptr<ChromeAppWindowTrackerAsh> chrome_app_window_tracker_ash_; std::unique_ptr<ClipboardAsh> clipboard_ash_; std::unique_ptr<ClipboardHistoryAsh> clipboard_history_ash_; std::unique_ptr<ContentProtectionAsh> content_protection_ash_; std::unique_ptr<DeviceAttributesAsh> device_attributes_ash_; std::unique_ptr<DeviceSettingsAsh> device_settings_ash_; std::unique_ptr<DownloadControllerAsh> download_controller_ash_; std::unique_ptr<DriveIntegrationServiceAsh> drive_integration_service_ash_; std::unique_ptr<FeedbackAsh> feedback_ash_; std::unique_ptr<FieldTrialServiceAsh> field_trial_service_ash_; std::unique_ptr<FileManagerAsh> file_manager_ash_; std::unique_ptr<ForceInstalledTrackerAsh> force_installed_tracker_ash_; std::unique_ptr<GeolocationServiceAsh> geolocation_service_ash_; std::unique_ptr<IdentityManagerAsh> identity_manager_ash_; std::unique_ptr<IdleServiceAsh> idle_service_ash_; std::unique_ptr<ImageWriterAsh> image_writer_ash_; std::unique_ptr<KeystoreServiceAsh> keystore_service_ash_; std::unique_ptr<KioskSessionServiceAsh> kiosk_session_service_ash_; std::unique_ptr<LocalPrinterAsh> local_printer_ash_; std::unique_ptr<LoginStateAsh> login_state_ash_; std::unique_ptr<MessageCenterAsh> message_center_ash_; std::unique_ptr<MetricsReportingAsh> metrics_reporting_ash_; std::unique_ptr<NativeThemeServiceAsh> native_theme_service_ash_; std::unique_ptr<NetworkingAttributesAsh> networking_attributes_ash_; std::unique_ptr<NetworkSettingsServiceAsh> network_settings_service_ash_; std::unique_ptr<PolicyServiceAsh> policy_service_ash_; std::unique_ptr<PowerAsh> power_ash_; std::unique_ptr<PrefsAsh> prefs_ash_; std::unique_ptr<RemotingAsh> remoting_ash_; std::unique_ptr<ResourceManagerAsh> resource_manager_ash_; std::unique_ptr<ScreenManagerAsh> screen_manager_ash_; std::unique_ptr<SelectFileAsh> select_file_ash_; std::unique_ptr<media::StableVideoDecoderFactoryService> stable_video_decoder_factory_ash_; std::unique_ptr<StructuredMetricsServiceAsh> structured_metrics_service_ash_; std::unique_ptr<SystemDisplayAsh> system_display_ash_; std::unique_ptr<WebPageInfoFactoryAsh> web_page_info_factory_ash_; std::unique_ptr<TaskManagerAsh> task_manager_ash_; std::unique_ptr<TtsAsh> tts_ash_; std::unique_ptr<UrlHandlerAsh> url_handler_ash_; std::unique_ptr<VideoCaptureDeviceFactoryAsh> video_capture_device_factory_ash_; // Only set in the test ash chrome binary. In production ash this is always // nullptr. TestControllerReceiver* test_controller_ = nullptr; mojo::ReceiverSet<mojom::Crosapi, CrosapiId> receiver_set_; std::map<mojo::ReceiverId, base::OnceClosure> disconnect_handler_map_; base::WeakPtrFactory<CrosapiAsh> weak_factory_{this}; }; } // namespace crosapi #endif // CHROME_BROWSER_ASH_CROSAPI_CROSAPI_ASH_H_
blueboxd/chromium-legacy
ash/webui/projector_app/projector_app_client.h
<gh_stars>10-100 // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_WEBUI_PROJECTOR_APP_PROJECTOR_APP_CLIENT_H_ #define ASH_WEBUI_PROJECTOR_APP_PROJECTOR_APP_CLIENT_H_ #include "base/observer_list_types.h" namespace network { namespace mojom { class URLLoaderFactory; } // namespace mojom } // namespace network namespace signin { class IdentityManager; } // namespace signin namespace chromeos { // Defines interface to access Browser side functionalities for the // ProjectorApp. class ProjectorAppClient { public: // Interface for observing events on the ProjectorAppClient. class Observer : public base::CheckedObserver { public: // Observes the pending screencast state change events. // TODO(b/201468756): Add list PendingScreencast as argument. virtual void OnScreencastsStateChange() = 0; // Used to notify the Projector SWA app on whether it can start a new // screencast session. virtual void OnNewScreencastPreconditionChanged(bool can_start) = 0; }; ProjectorAppClient(const ProjectorAppClient&) = delete; ProjectorAppClient& operator=(const ProjectorAppClient&) = delete; static ProjectorAppClient* Get(); virtual void AddObserver(Observer* observer) = 0; virtual void RemoveObserver(Observer* observer) = 0; // Returns the IdentityManager for the primary user profile. virtual signin::IdentityManager* GetIdentityManager() = 0; // Returns the URLLoaderFactory for the primary user profile. virtual network::mojom::URLLoaderFactory* GetUrlLoaderFactory() = 0; // Used to notify the Projector SWA app on whether it can start a new // screencast session. virtual void OnNewScreencastPreconditionChanged(bool can_start) = 0; protected: ProjectorAppClient(); virtual ~ProjectorAppClient(); }; } // namespace chromeos #endif // ASH_WEBUI_PROJECTOR_APP_PROJECTOR_APP_CLIENT_H_
blueboxd/chromium-legacy
components/feed/feed_feature_list.h
<filename>components/feed/feed_feature_list.h // Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_FEED_FEED_FEATURE_LIST_H_ #define COMPONENTS_FEED_FEED_FEATURE_LIST_H_ #include <string> #include "base/feature_list.h" #include "base/metrics/field_trial_params.h" #include "build/build_config.h" // TODO(crbug.com/1165828): Clean up feedv1 features. namespace feed { extern const base::Feature kInterestFeedContentSuggestions; extern const base::Feature kInterestFeedV2; extern const base::Feature kInterestFeedV2Autoplay; extern const base::Feature kInterestFeedV2Hearts; extern const base::Feature kInterestFeedV2Scrolling; extern const base::FeatureParam<std::string> kDisableTriggerTypes; extern const base::FeatureParam<int> kSuppressRefreshDurationMinutes; extern const base::FeatureParam<int> kTimeoutDurationSeconds; extern const base::FeatureParam<bool> kThrottleBackgroundFetches; extern const base::FeatureParam<bool> kOnlySetLastRefreshAttemptOnSuccess; // Determines whether conditions should be reached before enabling the upload of // click and view actions in the feed (e.g., the user needs to view X cards). // For example, this is needed when the notice card is at the second position in // the feed. extern const base::Feature kInterestFeedV1ClicksAndViewsConditionalUpload; extern const base::Feature kInterestFeedV2ClicksAndViewsConditionalUpload; // Feature that allows the client to automatically dismiss the notice card based // on the clicks and views on the notice card. #if defined(OS_IOS) extern const base::Feature kInterestFeedNoticeCardAutoDismiss; #endif // Used for A:B testing of a bug fix (crbug.com/1151391). extern const base::Feature kInterestFeedSpinnerAlwaysAnimate; // Feature that allows users to keep up with and consume web content. extern const base::Feature kWebFeed; // Use the new DiscoFeed endpoint. extern const base::Feature kDiscoFeedEndpoint; // Feature that enables xsurface to provide the metrics reporting state to an // xsurface feed. extern const base::Feature kXsurfaceMetricsReporting; // Whether to log reliability events. extern const base::Feature kReliabilityLogging; // Feature that enables refreshing feeds triggered by the users. extern const base::Feature kFeedInteractiveRefresh; // Feature that shows placeholder cards instead of a loading spinner at first // load. extern const base::Feature kFeedLoadingPlaceholder; // Feature that allows tuning the size of the image memory cache. Value is a // percentage of the maximum size calculated for the device. extern const base::Feature kFeedImageMemoryCacheSizePercentage; // Feature that enables clearing the image memory cache when the feed is // destroyed. extern const base::Feature kFeedClearImageMemoryCache; // Feature that enables showing a callout to help users return to the top of the // feeds quickly. extern const base::Feature kFeedBackToTop; // Feature that enables the 'X' in the signin promo in the Feed. Without the 'X' // the signin promo is not dismissible without opting to sign in. extern const base::Feature kFeedSignInPromoDismiss; // Feature that enables StAMP cards in the feed. extern const base::Feature kFeedStamp; // Feature that enables sorting by different heuristics in the web feed. extern const base::Feature kWebFeedSort; // Feature that causes the "open in new tab" menu item to appear on feed items // on Start Surface. extern const base::Feature kEnableOpenInNewTabFromStartSurfaceFeed; std::string GetFeedReferrerUrl(); } // namespace feed #endif // COMPONENTS_FEED_FEED_FEATURE_LIST_H_
blueboxd/chromium-legacy
ash/login/ui/login_user_view.h
// 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 ASH_LOGIN_UI_LOGIN_USER_VIEW_H_ #define ASH_LOGIN_UI_LOGIN_USER_VIEW_H_ #include "ash/ash_export.h" #include "ash/login/ui/login_base_bubble_view.h" #include "ash/login/ui/login_display_style.h" #include "ash/login/ui/login_remove_account_dialog.h" #include "ash/public/cpp/login_types.h" #include "base/macros.h" #include "base/scoped_observation.h" #include "ui/display/manager/display_configurator.h" #include "ui/views/view.h" namespace ash { class HoverNotifier; class LoginButton; // Display the user's profile icon, name, and a remove_account_dialog icon in // various layout styles. class ASH_EXPORT LoginUserView : public views::View, public display::DisplayConfigurator::Observer { public: // TestApi is used for tests to get internal implementation details. class ASH_EXPORT TestApi { public: explicit TestApi(LoginUserView* view); ~TestApi(); LoginDisplayStyle display_style() const; const std::u16string& displayed_name() const; views::View* user_label() const; views::View* tap_button() const; views::View* dropdown() const; LoginRemoveAccountDialog* remove_account_dialog() const; views::View* enterprise_icon() const; void OnTap() const; bool is_opaque() const; private: LoginUserView* const view_; }; using OnTap = base::RepeatingClosure; using OnRemoveWarningShown = base::RepeatingClosure; using OnRemove = base::RepeatingClosure; // Returns the width of this view for the given display style. static int WidthForLayoutStyle(LoginDisplayStyle style); // Use null callbacks for |on_remove_warning_shown| and |on_remove| when // |show_dropdown| arg is false. LoginUserView(LoginDisplayStyle style, bool show_dropdown, const OnTap& on_tap, const OnRemoveWarningShown& on_remove_warning_shown, const OnRemove& on_remove); LoginUserView(const LoginUserView&) = delete; LoginUserView& operator=(const LoginUserView&) = delete; ~LoginUserView() override; // Update the user view to display the given user information. void UpdateForUser(const LoginUserInfo& user, bool animate); // Set if the view must be opaque. void SetForceOpaque(bool force_opaque); // Enables or disables tapping the view. void SetTapEnabled(bool enabled); // DisplayConfigurator::Observer void OnPowerStateChanged(chromeos::DisplayPowerState power_state) override; const LoginUserInfo& current_user() const { return current_user_; } void UpdateDropdownIcon(); // views::View: const char* GetClassName() const override; gfx::Size CalculatePreferredSize() const override; void Layout() override; void RequestFocus() override; void OnThemeChanged() override; private: class UserImage; class UserLabel; class TapButton; // Called when hover state changes. void OnHover(bool has_hover); void DropdownButtonPressed(); // Updates UI element values so they reflect the data in |current_user_|. void UpdateCurrentUserState(); // Updates view opacity based on input state and |force_opaque_|. void UpdateOpacity(); void SetLargeLayout(); void SetSmallishLayout(); void DeleteDialog(); // Executed when the user view is pressed. OnTap on_tap_; // Executed when the user has seen the remove user warning. OnRemoveWarningShown on_remove_warning_shown_; // Executed when a user-remove has been requested. OnRemove on_remove_; // The user that is currently being displayed (or will be displayed when an // animation completes). LoginUserInfo current_user_; // Used to dispatch opacity update events. std::unique_ptr<HoverNotifier> hover_notifier_; LoginDisplayStyle display_style_; UserImage* user_image_ = nullptr; UserLabel* user_label_ = nullptr; LoginButton* dropdown_ = nullptr; TapButton* tap_button_ = nullptr; // Bubble used for displaying the user remove account dialog. Its parent is // the top level view, either LockContentsView or LockDebugView. This allows // the remove account dialog to be clicked outside the bounds of the user // view. LoginRemoveAccountDialog* remove_account_dialog_ = nullptr; // True iff the view is currently opaque (ie, opacity = 1). bool is_opaque_ = false; // True if the view must be opaque (ie, opacity = 1) regardless of input // state. bool force_opaque_ = false; base::ScopedObservation<display::DisplayConfigurator, display::DisplayConfigurator::Observer> display_observation_{this}; }; } // namespace ash #endif // ASH_LOGIN_UI_LOGIN_USER_VIEW_H_
blueboxd/chromium-legacy
third_party/blink/renderer/core/mobile_metrics/mobile_metrics_test_helpers.h
<gh_stars>10-100 // Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_MOBILE_METRICS_MOBILE_METRICS_TEST_HELPERS_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_MOBILE_METRICS_MOBILE_METRICS_TEST_HELPERS_H_ #include "third_party/blink/public/common/mobile_metrics/mobile_friendliness.h" #include "third_party/blink/renderer/core/frame/frame_test_helpers.h" #include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h" #include "third_party/blink/renderer/platform/wtf/vector.h" namespace blink { namespace mobile_metrics_test_helpers { // Collect MobileFriendliness metrics with tree structure which reflects // tree structure of subframe. struct MobileFriendlinessTree { MobileFriendliness mf; WTF::Vector<MobileFriendlinessTree> children; static MobileFriendlinessTree GetMobileFriendlinessTree(LocalFrameView* view, int scroll_y_offset) { mobile_metrics_test_helpers::MobileFriendlinessTree result; view->UpdateLifecycleToPrePaintClean(DocumentUpdateReason::kTest); view->GetMobileFriendlinessChecker()->NotifyPaint(); // Scroll the view to specified offset view->LayoutViewport()->SetScrollOffsetUnconditionally( ScrollOffset(0, scroll_y_offset)); // Do MobileFriendliness evaluation recursively. view->GetMobileFriendlinessChecker()->EvaluateNow(nullptr); result.mf = view->GetMobileFriendlinessChecker()->GetMobileFriendliness(); for (Frame* child = view->GetFrame().FirstChild(); child; child = child->NextSibling()) { if (LocalFrame* local_frame = DynamicTo<LocalFrame>(child)) { result.children.push_back( GetMobileFriendlinessTree(local_frame->View(), scroll_y_offset)); } } return result; } }; } // namespace mobile_metrics_test_helpers } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_MOBILE_METRICS_MOBILE_METRICS_TEST_HELPERS_H_
blueboxd/chromium-legacy
components/arc/input_overlay/actions/dependent_position.h
<gh_stars>10-100 // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_ARC_INPUT_OVERLAY_ACTIONS_DEPENDENT_POSITION_H_ #define COMPONENTS_ARC_INPUT_OVERLAY_ACTIONS_DEPENDENT_POSITION_H_ #include "components/arc/input_overlay/actions/position.h" namespace arc { namespace input_overlay { // For dependent position, it can be height-dependent or width-dependent. // If y_on_x is set, it is width-dependent. // If x_on_y is set, it is height-dependent. // If aspect_ratio is set, it is aspect_ratio dependent. class DependentPosition : public Position { public: DependentPosition(); DependentPosition(const DependentPosition&) = delete; DependentPosition& operator=(const DependentPosition&) = delete; ~DependentPosition() override; // Override from Position. // // Parse position from Json. // Json value format: // { // "anchor": [, ], // "anchor_to_target": [, ], // "x_on_y": 1.5, // Can be null for width-dependent position. // "y_on_x": 2 // Can be null for height-dependent position. // "aspect_ratio": 1.5 // Can be null for height- or width-dependent // // position. // } bool ParseFromJson(const base::Value& value) override; gfx::PointF CalculatePosition(const gfx::RectF& window_bounds) override; absl::optional<float> x_on_y() const { return x_on_y_; } absl::optional<float> y_on_x() const { return y_on_x_; } absl::optional<float> aspect_ratio() const { return aspect_ratio_; } private: // This is for height-dependent position. // The length on the direction X to the anchor depends on the direction Y to // the anchor. If both x_on_y_ and y_on_x_ are not set, x_on_y_ is set to // default -1. absl::optional<float> x_on_y_; // This is for width-dependent position. // The length on the direction Y to the anchor depends on the direction X to // the anchor. absl::optional<float> y_on_x_; // The is for aspect-ratio-dependent position. Both x_on_y_ and y_on_x_ should // be set if aspect_ratio_ is set. If the window aspect ratio >= // aspect_ratio_, it becomes height-dependent position. Otherwise, it is // width-dependent position. absl::optional<float> aspect_ratio_; }; } // namespace input_overlay } // namespace arc #endif // COMPONENTS_ARC_INPUT_OVERLAY_ACTIONS_DEPENDENT_POSITION_H_
blueboxd/chromium-legacy
chrome/browser/apps/app_service/subscriber_crosapi.h
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_APPS_APP_SERVICE_SUBSCRIBER_CROSAPI_H_ #define CHROME_BROWSER_APPS_APP_SERVICE_SUBSCRIBER_CROSAPI_H_ #include <memory> #include <string> #include <vector> #include "chromeos/crosapi/mojom/app_service.mojom.h" #include "components/keyed_service/core/keyed_service.h" #include "components/services/app_service/public/cpp/preferred_apps_list.h" #include "components/services/app_service/public/mojom/app_service.mojom.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/receiver_set.h" #include "mojo/public/cpp/bindings/remote.h" class Profile; namespace apps { // App service subscriber to support App Service Proxy in Lacros. // This object is used as a proxy to communicate between the // crosapi and App Service. // // See components/services/app_service/README.md. class SubscriberCrosapi : public KeyedService, public apps::mojom::Subscriber, public crosapi::mojom::AppServiceProxy { public: explicit SubscriberCrosapi(Profile* profile); SubscriberCrosapi(const SubscriberCrosapi&) = delete; SubscriberCrosapi& operator=(const SubscriberCrosapi&) = delete; ~SubscriberCrosapi() override; void RegisterAppServiceProxyFromCrosapi( mojo::PendingReceiver<crosapi::mojom::AppServiceProxy> receiver); protected: // apps::mojom::Subscriber overrides. void OnApps(std::vector<apps::mojom::AppPtr> deltas, apps::mojom::AppType app_type, bool should_notify_initialized) override; void OnCapabilityAccesses( std::vector<apps::mojom::CapabilityAccessPtr> deltas) override; void Clone(mojo::PendingReceiver<apps::mojom::Subscriber> receiver) override; void OnPreferredAppsChanged( apps::mojom::PreferredAppChangesPtr changes) override; void InitializePreferredApps( PreferredAppsList::PreferredApps preferred_apps) override; void OnCrosapiDisconnected(); // crosapi::mojom::AppServiceProxy overrides. void RegisterAppServiceSubscriber( mojo::PendingRemote<crosapi::mojom::AppServiceSubscriber> subscriber) override; void Launch(crosapi::mojom::LaunchParamsPtr launch_params) override; void LoadIcon(const std::string& app_id, apps::mojom::IconKeyPtr icon_key, apps::mojom::IconType icon_type, int32_t size_hint_in_dip, LoadIconCallback callback) override; void AddPreferredApp(const std::string& app_id, crosapi::mojom::IntentPtr intent) override; void OnSubscriberDisconnected(); mojo::Receiver<crosapi::mojom::AppServiceProxy> crosapi_receiver_{this}; mojo::ReceiverSet<apps::mojom::Subscriber> receivers_; mojo::Remote<crosapi::mojom::AppServiceSubscriber> subscriber_; Profile* profile_; }; } // namespace apps #endif // CHROME_BROWSER_APPS_APP_SERVICE_SUBSCRIBER_CROSAPI_H_
blueboxd/chromium-legacy
ios/chrome/browser/flags/ios_chrome_flag_descriptions.h
<reponame>blueboxd/chromium-legacy<filename>ios/chrome/browser/flags/ios_chrome_flag_descriptions.h<gh_stars>10-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. #ifndef IOS_CHROME_BROWSER_FLAGS_IOS_CHROME_FLAG_DESCRIPTIONS_H_ #define IOS_CHROME_BROWSER_FLAGS_IOS_CHROME_FLAG_DESCRIPTIONS_H_ #include "Availability.h" // Please add names and descriptions in alphabetical order. namespace flag_descriptions { // Title and description for the flag to enable // kSupportForAddPasswordsInSettings flag on iOS. extern const char kAddPasswordsInSettingsName[]; extern const char kAddPasswordsInSettingsDescription[]; // Title and description for the flag to control upstreaming credit cards. extern const char kAutofillCreditCardUploadName[]; extern const char kAutofillCreditCardUploadDescription[]; // Title and description for the flag to control offers in downstream. extern const char kAutofillEnableOffersInDownstreamName[]; extern const char kAutofillEnableOffersInDownstreamDescription[]; // Title and description for the flag to fill promo code fields with Autofill. extern const char kAutofillFillMerchantPromoCodeFieldsName[]; extern const char kAutofillFillMerchantPromoCodeFieldsDescription[]; // Title and description for the flag to control the autofill delay. extern const char kAutofillIOSDelayBetweenFieldsName[]; extern const char kAutofillIOSDelayBetweenFieldsDescription[]; // Title and description for the flag to parse promo code fields in Autofill. extern const char kAutofillParseMerchantPromoCodeFieldsName[]; extern const char kAutofillParseMerchantPromoCodeFieldsDescription[]; // Title and description for the flag that controls whether the maximum number // of Autofill suggestions shown is pruned. extern const char kAutofillPruneSuggestionsName[]; extern const char kAutofillPruneSuggestionsDescription[]; // Title and description for the flag to control dismissing the Save Card // Infobar on Navigation. extern const char kAutofillSaveCardDismissOnNavigationName[]; extern const char kAutofillSaveCardDismissOnNavigationDescription[]; // Title and description for the flag that controls whether Autofill's // suggestions' labels are formatting with a mobile-friendly approach. extern const char kAutofillUseMobileLabelDisambiguationName[]; extern const char kAutofillUseMobileLabelDisambiguationDescription[]; // Title and description for the flag that controls whether Autofill's // logic is using numeric unique renderer IDs instead of string IDs for // form and field elements. extern const char kAutofillUseRendererIDsName[]; extern const char kAutofillUseRendererIDsDescription[]; // Title and description for the flag that controls whether event breadcrumbs // are captured. extern const char kLogBreadcrumbsName[]; extern const char kLogBreadcrumbsDescription[]; // Title and description for the flag that controls synthetic crash reports // generation for Unexplained Termination Events. extern const char kSyntheticCrashReportsForUteName[]; extern const char kSyntheticCrashReportsForUteDescription[]; // Title and description for the flag to control if initial uploading of crash // reports is delayed. extern const char kBreakpadNoDelayInitialUploadName[]; extern const char kBreakpadNoDelayInitialUploadDescription[]; // Title and description for the flag to control which crash generation tool // is used. extern const char kCrashpadIOSName[]; extern const char kCrashpadIOSDescription[]; // Title and description for the flag to enable context menu actions refresh. extern const char kContextMenuActionsRefreshName[]; extern const char kContextMenuActionsRefreshDescription[]; #if defined(DCHECK_IS_CONFIGURABLE) // Title and description for the flag to enable configurable DCHECKs. extern const char kDcheckIsFatalName[]; extern const char kDcheckIsFatalDescription[]; #endif // defined(DCHECK_IS_CONFIGURABLE) // Title and description for the flag to have the web client choosing the // default user agent. extern const char kUseDefaultUserAgentInWebClientName[]; extern const char kUseDefaultUserAgentInWebClientDescription[]; // Title and description for the flag to use default WebKit context menu in web // content. extern const char kDefaultWebViewContextMenuName[]; extern const char kDefaultWebViewContextMenuDescription[]; // Title and description for the flag to control the delay (in minutes) for // polling for the existence of Gaia cookies for google.com. extern const char kDelayThresholdMinutesToUpdateGaiaCookieName[]; extern const char kDelayThresholdMinutesToUpdateGaiaCookieDescription[]; // Title and description for the flag to detect change password form // submisison when the form is cleared by the website. extern const char kDetectFormSubmissionOnFormClearIOSName[]; extern const char kDetectFormSubmissionOnFormClearIOSDescription[]; // Title and description for the flag to control if a crash report is generated // on main thread freeze. extern const char kDetectMainThreadFreezeName[]; extern const char kDetectMainThreadFreezeDescription[]; // Title and description for the flag to replace the Zine feed with the // Discover feed in the Bling NTP. extern const char kDiscoverFeedInNtpName[]; extern const char kDiscoverFeedInNtpDescription[]; // Title and description for the flag to enable .mobileconfig file downloads. extern const char kDownloadMobileConfigFileName[]; extern const char kDownloadMobileConfigFileDescription[]; // Title and description for the flag to enable Vcard support. extern const char kDownloadVcardName[]; extern const char kDownloadVcardDescription[]; // Title and description for the flag to enable kEditPasswordsInSettings flag on // iOS. extern const char kEditPasswordsInSettingsName[]; extern const char kEditPasswordsInSettingsDescription[]; // Title and description for the flag to native restore web states. extern const char kRestoreSessionFromCacheName[]; extern const char kRestoreSessionFromCacheDescription[]; extern const char kEnableAutofillAccountWalletStorageName[]; extern const char kEnableAutofillAccountWalletStorageDescription[]; // Title and description for the flag to enable address verification support in // autofill address save prompts. extern const char kEnableAutofillAddressSavePromptAddressVerificationName[]; extern const char kEnableAutofillAddressSavePromptAddressVerificationDescription[]; // Title and description for the flag to enable autofill address save prompts. extern const char kEnableAutofillAddressSavePromptName[]; extern const char kEnableAutofillAddressSavePromptDescription[]; // Title and description for the flag to enable account indication in the save // card dialog. extern const char kEnableAutofillSaveCardInfoBarAccountIndicationFooterName[]; extern const char kEnableAutofillSaveCardInfoBarAccountIndicationFooterDescription[]; // Title and description for the flag to enable the discover feed discofeed // endpoint. extern const char kEnableDiscoverFeedDiscoFeedEndpointName[]; extern const char kEnableDiscoverFeedDiscoFeedEndpointDescription[]; // Title and description for the flag to enable the discover feed live preview // in long-press feed context menu. extern const char kEnableDiscoverFeedPreviewName[]; extern const char kEnableDiscoverFeedPreviewDescription[]; // Title and description for the flag to shorten the cache. extern const char kEnableDiscoverFeedShorterCacheName[]; extern const char kEnableDiscoverFeedShorterCacheDescription[]; // Title and description for the flag to enable the discover feed static // resource serving. extern const char kEnableDiscoverFeedStaticResourceServingName[]; extern const char kEnableDiscoverFeedStaticResourceServingDescription[]; // Title and description for the flag to test the FRE default browser promo // experiment. extern const char kEnableFREDefaultBrowserScreenTestingName[]; extern const char kEnableFREDefaultBrowserScreenTestingDescription[]; // Title and description for the flag to enable FRE UI module. extern const char kEnableFREUIModuleIOSName[]; extern const char kEnableFREUIModuleIOSDescription[]; // Title and description for the flag to enable long message duration. extern const char kEnableLongMessageDurationName[]; extern const char kEnableLongMessageDurationDescription[]; // Title and description for the flag to enable UI that allows the user to // create a strong password even if the field wasn't parsed as a new password // field. extern const char kEnableManualPasswordGenerationName[]; extern const char kEnableManualPasswordGenerationDescription[]; // Title and description for the flag to enable the NTP memory enhancements. extern const char kEnableNTPMemoryEnhancementName[]; extern const char kEnableNTPMemoryEnhancementDescription[]; // Title and description for the flag to enable optimization guide. extern const char kEnableOptimizationGuideName[]; extern const char kEnableOptimizationGuideDescription[]; // Title and description for the flag to enable optimization guide metadata // validation. extern const char kEnableOptimizationGuideMetadataValidationName[]; extern const char kEnableOptimizationGuideMetadataValidationDescription[]; // Title and description for the flag to enable optimization guide hints // fetching for MSBB users. extern const char kEnableOptimizationHintsFetchingMSBBName[]; extern const char kEnableOptimizationHintsFetchingMSBBDescription[]; // Title and description for the flag to enable an expanded tab strip. extern const char kExpandedTabStripName[]; extern const char kExpandedTabStripDescription[]; // Title and description for the flag to enable filling across affiliated // websites. extern const char kFillingAcrossAffiliatedWebsitesName[]; extern const char kFillingAcrossAffiliatedWebsitesDescription[]; // Title and description for the flag to introduce a Following feed in the // Chrome iOS NTP. extern const char kFollowingFeedInNtpName[]; extern const char kFollowingFeedInNtpDescription[]; // Title and description for the flag to disable all extended sync promos. extern const char kForceDisableExtendedSyncPromosName[]; extern const char kForceDisableExtendedSyncPromosDescription[]; // Title and description for the flag to trigger the startup sign-in promo. extern const char kForceStartupSigninPromoName[]; extern const char kForceStartupSigninPromoDescription[]; // Title and description for the flag to trigger credentials provider extension // promo. extern const char kCredentialProviderExtensionPromoName[]; extern const char kCredentialProviderExtensionPromoDescription[]; // Enables the user to track prices of the Shopping URLs they are visiting. // The first variation is to display price drops in the Tab Switching UI when // they are identified. extern const char kCommercePriceTrackingName[]; extern const char kCommercePriceTrackingDescription[]; // Title and description for the flag to set the major version the UA string to // 100. extern const char kForceMajorVersion100InUserAgentName[]; extern const char kForceMajorVersion100InUserAgentDescription[]; // Title and description for the command line switch used to determine the // active fullscreen viewport adjustment mode. extern const char kFullscreenSmoothScrollingName[]; extern const char kFullscreenSmoothScrollingDescription[]; // Title and description for the flag to enable dark mode colors while in // Incognito mode. extern const char kIncognitoBrandConsistencyForIOSName[]; extern const char kIncognitoBrandConsistencyForIOSDescription[]; // Title and description for the flag to enable revamped Incognito NTP page. extern const char kIncognitoNtpRevampName[]; extern const char kIncognitoNtpRevampDescription[]; // Title and description for the flag to auto-dismiss the privacy notice card. extern const char kInterestFeedNoticeCardAutoDismissName[]; extern const char kInterestFeedNoticeCardAutoDismissDescription[]; // Title and description for the flag that conditionally uploads clicks and view // actions in the feed (e.g., the user needs to view X cards). extern const char kInterestFeedV2ClickAndViewActionsConditionalUploadName[]; extern const char kInterestFeedV2ClickAndViewActionsConditionalUploadDescription[]; // Title and description for the flag to enable feature_engagement::Tracker // demo mode. extern const char kInProductHelpDemoModeName[]; extern const char kInProductHelpDemoModeDescription[]; // Title and description for the flag to enable interstitials on legacy TLS // connections. extern const char kIOSLegacyTLSInterstitialsName[]; extern const char kIOSLegacyTLSInterstitialsDescription[]; // Title and description for the flag to persist the Crash Restore Infobar // across navigations. extern const char kIOSPersistCrashRestoreName[]; extern const char kIOSPersistCrashRestoreDescription[]; // Title and description for the flag to enable Shared Highlighting color // change in iOS. extern const char kIOSSharedHighlightingColorChangeName[]; extern const char kIOSSharedHighlightingColorChangeDescription[]; // Title and description for the flag to enable Shared Highlighting on AMP pages // in iOS. extern const char kIOSSharedHighlightingAmpName[]; extern const char kIOSSharedHighlightingAmpDescription[]; // Title and description for the flag to enable browser-layer improvements to // the text fragments UI. extern const char kIOSSharedHighlightingV2Name[]; extern const char kIOSSharedHighlightingV2Description[]; // Title and description for the flag to lock the bottom toolbar into place. extern const char kLockBottomToolbarName[]; extern const char kLockBottomToolbarDescription[]; // Title and description for the flag that controls sending metrickit crash // reports. extern const char kMetrickitCrashReportName[]; extern const char kMetrickitCrashReportDescription[]; // TODO(crbug.com/1128242): Remove this flag after the refactoring work is // finished. // Title and description for the flag used to test the newly // implemented tabstrip. extern const char kModernTabStripName[]; extern const char kModernTabStripDescription[]; // Title and description for the flag to enable the new overflow menu. extern const char kNewOverflowMenuName[]; extern const char kNewOverflowMenuDescription[]; // Title and description for the flag to use the previous sync screen in the new // FRE. extern const char kOldSyncStringFREName[]; extern const char kOldSyncStringFREDescription[]; // Title and description for the flag to change the max number of autocomplete // matches in the omnibox popup. extern const char kOmniboxUIMaxAutocompleteMatchesName[]; extern const char kOmniboxUIMaxAutocompleteMatchesDescription[]; // Title and description for the flag to enable Omnibox On Device Head // suggestions (incognito). extern const char kOmniboxOnDeviceHeadSuggestionsIncognitoName[]; extern const char kOmniboxOnDeviceHeadSuggestionsIncognitoDescription[]; // Title and description for the flag to enable Omnibox On Device Head // suggestions (non incognito). extern const char kOmniboxOnDeviceHeadSuggestionsNonIncognitoName[]; extern const char kOmniboxOnDeviceHeadSuggestionsNonIncognitoDescription[]; // Title and description for the flag to control Omnibox on-focus suggestions. extern const char kOmniboxOnFocusSuggestionsName[]; extern const char kOmniboxOnFocusSuggestionsDescription[]; // Title and description for the flag to control Omnibox Local zero-prefix // suggestions. extern const char kOmniboxLocalHistoryZeroSuggestName[]; extern const char kOmniboxLocalHistoryZeroSuggestDescription[]; // Title and description for the flag to swap Omnibox Textfield implementation // to a new experimental one. extern const char kOmniboxNewImplementationName[]; extern const char kOmniboxNewImplementationDescription[]; // Title and description for the flag to enable PhishGuard password reuse // detection. extern const char kPasswordReuseDetectionName[]; extern const char kPasswordReuseDetectionDescription[]; // Title and description for the flag to enable the Reading List Messages. extern const char kReadingListMessagesName[]; extern const char kReadingListMessagesDescription[]; // Title and description for the flag that makes Safe Browsing available. extern const char kSafeBrowsingAvailableName[]; extern const char kSafeBrowsingAvailableDescription[]; // Title and description for the flag to enable real-time Safe Browsing lookups. extern const char kSafeBrowsingRealTimeLookupName[]; extern const char kSafeBrowsingRealTimeLookupDescription[]; // Title and description for the flag to enable integration with the ScreenTime // system. extern const char kScreenTimeIntegrationName[]; extern const char kScreenTimeIntegrationDescription[]; // Title and description for the flag to enable the Search History Link feature. extern const char kSearchHistoryLinkIOSName[]; extern const char kSearchHistoryLinkIOSDescription[]; // Title and description for the flag to enable the send-tab-to-self for a // signed-in user (non-syncing). extern const char kSendTabToSelfWhenSignedInName[]; extern const char kSendTabToSelfWhenSignedInDescription[]; // Title and description for the flag to enable the "Manage devices" link in // the send-tab-to-self feature UI. extern const char kSendTabToSelfManageDevicesLinkName[]; extern const char kSendTabToSelfManageDevicesLinkDescription[]; // Title and description for the flag to send UMA data over any network. extern const char kSendUmaOverAnyNetwork[]; extern const char kSendUmaOverAnyNetworkDescription[]; // Title and description for the flag to enable Shared Highlighting (Link to // Text Edit Menu option). extern const char kSharedHighlightingIOSName[]; extern const char kSharedHighlightingIOSDescription[]; // Title and description for the flag to use a sites blocklist when generating // URLs for Shared Highlighting (Link to Text). extern const char kSharedHighlightingUseBlocklistIOSName[]; extern const char kSharedHighlightingUseBlocklistIOSDescription[]; // Title and description for the flag to enable annotating web forms with // Autofill field type predictions as placeholder. extern const char kShowAutofillTypePredictionsName[]; extern const char kShowAutofillTypePredictionsDescription[]; // Title and description for the flag to enable the Start Surface. extern const char kStartSurfaceName[]; extern const char kStartSurfaceDescription[]; // Title and description for the flag to control if Chrome Sync should use the // sandbox servers. extern const char kSyncSandboxName[]; extern const char kSyncSandboxDescription[]; // Title and description for the flag to control if Chrome Sync should support // trusted vault RPC. extern const char kSyncTrustedVaultPassphraseiOSRPCName[]; extern const char kSyncTrustedVaultPassphraseiOSRPCDescription[]; // Title and description for the flag to control if Chrome Sync should support // trusted vault passphrase promos. extern const char kSyncTrustedVaultPassphrasePromoName[]; extern const char kSyncTrustedVaultPassphrasePromoDescription[]; // Title and description for the flag to control if Chrome Sync should support // trusted vault passphrase type with improved recovery. extern const char kSyncTrustedVaultPassphraseRecoveryName[]; extern const char kSyncTrustedVaultPassphraseRecoveryDescription[]; // Title and description for the flag to enable tabs bulk actions feature. extern const char kTabsBulkActionsName[]; extern const char kTabsBulkActionsDescription[]; // Title and description for the flag to enable the toolbar container // implementation. extern const char kToolbarContainerName[]; extern const char kToolbarContainerDescription[]; // Title and description for the flag to enable removing any entry points to the // history UI from Incognito mode. extern const char kUpdateHistoryEntryPointsInIncognitoName[]; extern const char kUpdateHistoryEntryPointsInIncognitoDescription[]; // Title and description for the flag to enable URLBlocklist/URLAllowlist // enterprise policy. extern const char kURLBlocklistIOSName[]; extern const char kURLBlocklistIOSDescription[]; // Title and description for the flag to enable using Lens to search for an // image from the long press context menu. extern const char kUseLensToSearchForImageName[]; extern const char kUseLensToSearchForImageDescription[]; // Title and description for the flag to control the maximum wait time (in // seconds) for a response from the Account Capabilities API. extern const char kWaitThresholdMillisecondsForCapabilitiesApiName[]; extern const char kWaitThresholdMillisecondsForCapabilitiesApiDescription[]; // Title and description for the flag to control if Google Payments API calls // should use the sandbox servers. extern const char kWalletServiceUseSandboxName[]; extern const char kWalletServiceUseSandboxDescription[]; // Title and description for the flag to enable the new download API. extern const char kEnableNewDownloadAPIName[]; extern const char kEnableNewDownloadAPIDescription[]; // Title and description for the flag to tie the default text zoom level to // the dynamic type setting. extern const char kWebPageDefaultZoomFromDynamicTypeName[]; extern const char kWebPageDefaultZoomFromDynamicTypeDescription[]; // Title and description for the flag to enable a different method of zooming // web pages. extern const char kWebPageAlternativeTextZoomName[]; extern const char kWebPageAlternativeTextZoomDescription[]; // Title and description for the flag to enable the native context menus in the // WebView. extern const char kWebViewNativeContextMenuName[]; extern const char kWebViewNativeContextMenuDescription[]; // Title and description for the flag to enable the phase 2 of context menus in // the WebView. extern const char kWebViewNativeContextMenuPhase2Name[]; extern const char kWebViewNativeContextMenuPhase2Description[]; // Title and description for the flag to restore Gaia cookies when the user // explicitly requests to be signed in to a Google service. extern const char kRestoreGaiaCookiesOnUserActionName[]; extern const char kRestoreGaiaCookiesOnUserActionDescription[]; extern const char kRecordSnapshotSizeName[]; extern const char kRecordSnapshotSizeDescription[]; // Title and description for the flag to show a modified fullscreen modal promo // with a button that would send the users in the Settings.app to update the // default browser. extern const char kDefaultBrowserFullscreenPromoExperimentName[]; extern const char kDefaultBrowserFullscreenPromoExperimentDescription[]; // Please add names and descriptions above in alphabetical order. } // namespace flag_descriptions #endif // IOS_CHROME_BROWSER_FLAGS_IOS_CHROME_FLAG_DESCRIPTIONS_H_
blueboxd/chromium-legacy
components/signin/core/browser/account_reconcilor.h
<gh_stars>10-100 // 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 COMPONENTS_SIGNIN_CORE_BROWSER_ACCOUNT_RECONCILOR_H_ #define COMPONENTS_SIGNIN_CORE_BROWSER_ACCOUNT_RECONCILOR_H_ #include <memory> #include <vector> #include "base/compiler_specific.h" #include "base/gtest_prod_util.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/threading/thread_checker.h" #include "base/time/time.h" #include "base/timer/timer.h" #include "build/build_config.h" #include "components/content_settings/core/browser/content_settings_observer.h" #include "components/content_settings/core/common/content_settings_pattern.h" #include "components/keyed_service/core/keyed_service.h" #include "components/signin/core/browser/account_reconcilor_delegate.h" #include "components/signin/core/browser/account_reconcilor_throttler.h" #include "components/signin/core/browser/signin_header_helper.h" #include "components/signin/public/base/signin_client.h" #include "components/signin/public/base/signin_metrics.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "google_apis/gaia/google_service_auth_error.h" namespace signin { class AccountReconcilorDelegate; enum class SetAccountsInCookieResult; } class SigninClient; class AccountReconcilor : public KeyedService, public content_settings::Observer, public signin::IdentityManager::Observer { public: // When an instance of this class exists, the account reconcilor is suspended. // It will automatically restart when all instances of Lock have been // destroyed. class Lock final { public: explicit Lock(AccountReconcilor* reconcilor); Lock(const Lock&) = delete; Lock& operator=(const Lock&) = delete; ~Lock(); private: base::WeakPtr<AccountReconcilor> reconcilor_; THREAD_CHECKER(thread_checker_); }; // Helper class to indicate that synced data is being deleted. The object // must be destroyed when the data deletion is complete. class ScopedSyncedDataDeletion { public: ScopedSyncedDataDeletion(const ScopedSyncedDataDeletion&) = delete; ScopedSyncedDataDeletion& operator=(const ScopedSyncedDataDeletion&) = delete; ~ScopedSyncedDataDeletion(); private: friend class AccountReconcilor; explicit ScopedSyncedDataDeletion(AccountReconcilor* reconcilor); base::WeakPtr<AccountReconcilor> reconcilor_; }; class Observer { public: virtual ~Observer() = default; // The typical order of events is: // - When reconcile is blocked: // 1. current reconcile is aborted with AbortReconcile(), // 2. OnStateChanged() is called with SCHEDULED. // 3. OnBlockReconcile() is called. // - When reconcile is unblocked: // 1. OnUnblockReconcile() is called, // 2. reconcile is restarted if needed with StartReconcile(), which // triggers a call to OnStateChanged() with RUNNING. // Called whe reconcile starts. virtual void OnStateChanged(signin_metrics::AccountReconcilorState state) {} // Called when the AccountReconcilor is blocked. virtual void OnBlockReconcile() {} // Called when the AccountReconcilor is unblocked. virtual void OnUnblockReconcile() {} }; AccountReconcilor( signin::IdentityManager* identity_manager, SigninClient* client, std::unique_ptr<signin::AccountReconcilorDelegate> delegate); AccountReconcilor(const AccountReconcilor&) = delete; AccountReconcilor& operator=(const AccountReconcilor&) = delete; ~AccountReconcilor() override; // Initializes the account reconcilor. Should be called once after // construction. void Initialize(bool start_reconcile_if_tokens_available); // Enables and disables the reconciliation. void EnableReconcile(); void DisableReconcile(bool logout_all_gaia_accounts); // Signal that an X-Chrome-Manage-Accounts was received from GAIA. Pass the // ServiceType specified by GAIA in the 204 response. // Virtual for testing. virtual void OnReceivedManageAccountsResponse( signin::GAIAServiceType service_type); // KeyedService implementation. void Shutdown() override; // Determine what the reconcilor is currently doing. signin_metrics::AccountReconcilorState GetState(); // Adds ands removes observers. void AddObserver(Observer* observer); void RemoveObserver(Observer* observer); // ScopedSyncedDataDeletion can be created when synced data is being removed // and destroyed when the deletion is complete. It prevents the Sync account // from being invalidated during the deletion. std::unique_ptr<ScopedSyncedDataDeletion> GetScopedSyncDataDeletion(); // Returns true if reconcilor is blocked. bool IsReconcileBlocked() const; protected: void OnSetAccountsInCookieCompleted(signin::SetAccountsInCookieResult result); void OnLogOutFromCookieCompleted(const GoogleServiceAuthError& error); private: friend class AccountReconcilorTest; friend class DiceBrowserTest; friend class BaseAccountReconcilorTestTable; friend class AccountReconcilorThrottlerTest; friend class AccountReconcilorTestForceDiceMigration; FRIEND_TEST_ALL_PREFIXES(AccountReconcilorTestForceDiceMigration, TableRowTestCheckNoOp); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMirrorTest, IdentityManagerRegistration); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMirrorTest, Reauth); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMirrorTest, ProfileAlreadyConnected); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorTestTable, TableRowTest); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorTestTable, InconsistencyReasonLogging); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorTestDiceMultilogin, TableRowTest); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorTestMirrorMultilogin, TableRowTest); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorTestMiceMultilogin, TableRowTest); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMiceTest, AccountReconcilorStateScheduled); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorDiceTest, DiceTokenServiceRegistration); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorDiceTest, DiceReconcileWithoutSignin); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorDiceTest, DiceReconcileNoop); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorDiceTest, DiceLastKnownFirstAccount); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorDiceTest, UnverifiedAccountNoop); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorDiceTest, UnverifiedAccountMerge); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorDiceTest, HandleSigninDuringReconcile); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorDiceTest, DiceReconcileReuseGaiaFirstAccount); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorTest, DiceDeleteCookie); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMirrorTest, TokensNotLoaded); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMirrorTest, StartReconcileCookiesDisabled); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMirrorTest, StartReconcileContentSettings); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMirrorTest, StartReconcileContentSettingsGaiaUrl); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMirrorTest, StartReconcileContentSettingsNonGaiaUrl); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMirrorTest, StartReconcileContentSettingsWildcardPattern); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMirrorTest, GetAccountsFromCookieSuccess); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMirrorTest, EnableReconcileWhileAlreadyRunning); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMirrorTest, GetAccountsFromCookieFailure); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMirrorTest, ExtraCookieChangeNotification); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMirrorTest, StartReconcileNoop); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMirrorTest, StartReconcileNoopWithDots); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMirrorTest, StartReconcileNoopMultiple); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMirrorTest, StartReconcileAddToCookie); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorTest, AuthErrorTriggersListAccount); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMirrorTest, SignoutAfterErrorDoesNotRecordUma); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMirrorTest, TokenErrorOnPrimary); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMirrorTest, StartReconcileRemoveFromCookie); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMirrorTest, StartReconcileAddToCookieTwice); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMirrorTest, StartReconcileBadPrimary); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMirrorTest, StartReconcileOnlyOnce); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMirrorTest, Lock); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMethodParamTest, StartReconcileWithSessionInfoExpiredDefault); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMethodParamTest, AccountReconcilorStateScheduled); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMirrorTest, AddAccountToCookieCompletedWithBogusAccount); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMirrorTest, NoLoopWithBadPrimary); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMirrorTest, WontMergeAccountsWithError); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorTest, DelegateTimeoutIsCalled); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorMirrorTest, DelegateTimeoutIsNotCalled); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorTest, DelegateTimeoutIsNotCalledIfTimeoutIsNotReached); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorTest, MultiloginLogout); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorTestForceDiceMigration, TableRowTest); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorTestActiveDirectory, TableRowTestMergeSession); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorTestActiveDirectory, TableRowTestMultilogin); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorTest, ReconcileAfterShutdown); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorTest, UnlockAfterShutdown); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorThrottlerTest, RefillOneRequest); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorThrottlerTest, RefillFiveRequests); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorThrottlerTest, NewRequestParamsPasses); FRIEND_TEST_ALL_PREFIXES(AccountReconcilorThrottlerTest, BlockFiveRequests); // Operation executed by the reconcilor. // These values are persisted to logs. Entries should not be renumbered and // numeric values should never be reused. enum class Operation { kNoop = 0, kLogout = 1, kMultilogin = 2, kThrottled = 3, kMaxValue = kThrottled }; // Event triggering a call to StartReconcile(). // These values are persisted to logs. Entries should not be renumbered and // numeric values should never be reused. enum class Trigger { kInitialized = 0, kTokensLoaded = 1, kEnableReconcile = 2, kUnblockReconcile = 3, kTokenChange = 4, kTokenChangeDuringReconcile = 5, kCookieChange = 6, kCookieSettingChange = 7, kMaxValue = kCookieSettingChange }; void set_timer_for_testing(std::unique_ptr<base::OneShotTimer> timer); bool IsRegisteredWithIdentityManager() const { return registered_with_identity_manager_; } // Register and unregister with dependent services. void RegisterWithAllDependencies(); void UnregisterWithAllDependencies(); void RegisterWithIdentityManager(); void UnregisterWithIdentityManager(); void RegisterWithContentSettings(); void UnregisterWithContentSettings(); // All actions with side effects, only doing meaningful work if account // consistency is enabled. Virtual so that they can be overridden in tests. virtual void PerformLogoutAllAccountsAction(); virtual void PerformSetCookiesAction( const signin::MultiloginParameters& parameters); // Used during periodic reconciliation. void StartReconcile(Trigger trigger); // |gaia_accounts| are the accounts in the Gaia cookie. void FinishReconcile(const CoreAccountId& primary_account, const std::vector<CoreAccountId>& chrome_accounts, std::vector<gaia::ListedAccount>&& gaia_accounts); void AbortReconcile(); void ScheduleStartReconcileIfChromeAccountsChanged(); // Returns the list of valid accounts from the TokenService. std::vector<CoreAccountId> LoadValidAccountsFromTokenService() const; // The reconcilor only starts when the token service is ready. bool IsIdentityManagerReady(); // Overridden from content_settings::Observer. void OnContentSettingChanged( const ContentSettingsPattern& primary_pattern, const ContentSettingsPattern& secondary_pattern, ContentSettingsTypeSet content_type_set) override; // Overridden from signin::IdentityManager::Observer. void OnEndBatchOfRefreshTokenStateChanges() override; void OnRefreshTokensLoaded() override; void OnErrorStateOfRefreshTokenUpdatedForAccount( const CoreAccountInfo& account_info, const GoogleServiceAuthError& error) override; void OnAccountsInCookieUpdated( const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info, const GoogleServiceAuthError& error) override; void OnAccountsCookieDeletedByUserAction() override; void FinishReconcileWithMultiloginEndpoint( const CoreAccountId& primary_account, const std::vector<CoreAccountId>& chrome_accounts, std::vector<gaia::ListedAccount>&& gaia_accounts); void CalculateIfMultiloginReconcileIsDone(); // Lock related methods. void IncrementLockCount(); void DecrementLockCount(); void BlockReconcile(); void UnblockReconcile(); void HandleReconcileTimeout(); // Returns true if current array of existing accounts in cookie is different // from the desired one. If this returns false, the multilogin call would be a // no-op. bool CookieNeedsUpdate( const signin::MultiloginParameters& parameters, const std::vector<gaia::ListedAccount>& existing_accounts); // Sets the reconcilor state and calls Observer::OnStateChanged() if needed. void SetState(signin_metrics::AccountReconcilorState state); // Returns whether Shutdown() was called. bool WasShutDown() const; static void RecordReconcileOperation(Trigger trigger, Operation operation); // Histogram names. static const char kOperationHistogramName[]; static const char kTriggerLogoutHistogramName[]; static const char kTriggerMultiloginHistogramName[]; static const char kTriggerNoopHistogramName[]; static const char kTriggerThrottledHistogramName[]; std::unique_ptr<signin::AccountReconcilorDelegate> delegate_; AccountReconcilorThrottler throttler_; // The IdentityManager associated with this reconcilor. signin::IdentityManager* identity_manager_; // The SigninClient associated with this reconcilor. SigninClient* client_; bool registered_with_identity_manager_ = false; bool registered_with_content_settings_ = false; // True while the reconcilor is busy checking or managing the accounts in // this profile. bool is_reconcile_started_ = false; base::Time reconcile_start_time_; Trigger trigger_ = Trigger::kInitialized; // True iff this is the first time the reconcilor is executing. bool first_execution_ = true; // 'Most severe' error encountered during the last attempt to reconcile. If // the last reconciliation attempt was successful, this will be // |GoogleServiceAuthError::State::NONE|. // Severity of an error is defined on the basis of // |GoogleServiceAuthError::IsPersistentError()| only, i.e. any persistent // error is considered more severe than all non-persistent errors, but // persistent (or non-persistent) errors do not have an internal severity // ordering among themselves. GoogleServiceAuthError error_during_last_reconcile_ = GoogleServiceAuthError::AuthErrorNone(); // Used for Dice migration: migration can happen if the accounts are // consistent, which is indicated by reconcile being a no-op. bool reconcile_is_noop_ = true; // Used during reconcile action. bool set_accounts_in_progress_ = false; // Progress of SetAccounts calls. bool log_out_in_progress_ = false; // Progress of LogOut calls. bool chrome_accounts_changed_ = false; // Used for the Lock. // StartReconcile() is blocked while this is > 0. int account_reconcilor_lock_count_ = 0; // StartReconcile() should be started when the reconcilor is unblocked. bool reconcile_on_unblock_ = false; base::ObserverList<Observer, true>::Unchecked observer_list_; // A timer to set off reconciliation timeout handlers, if account // reconciliation does not happen in a given |timeout_| duration. // Any delegate that wants to use this feature must override // |AccountReconcilorDelegate::GetReconcileTimeout|. // Note: This is intended as a safeguard for delegates that want a 'guarantee' // of reconciliation completing within a finite time. It is technically // possible for account reconciliation to be running/waiting forever in cases // such as a network connection not being present. std::unique_ptr<base::OneShotTimer> timer_ = std::make_unique<base::OneShotTimer>(); base::TimeDelta timeout_; // Greater than 0 when synced data is being deleted, and it is important to // not invalidate the primary token while this is happening. int synced_data_deletion_in_progress_count_ = 0; signin_metrics::AccountReconcilorState state_ = signin_metrics::ACCOUNT_RECONCILOR_OK; // Set to true when Shutdown() is called. bool was_shut_down_ = false; base::WeakPtrFactory<AccountReconcilor> weak_factory_{this}; }; #endif // COMPONENTS_SIGNIN_CORE_BROWSER_ACCOUNT_RECONCILOR_H_
blueboxd/chromium-legacy
ash/components/fwupd/firmware_update_manager.h
<reponame>blueboxd/chromium-legacy // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_COMPONENTS_FWUPD_FIRMWARE_UPDATE_MANAGER_H_ #define ASH_COMPONENTS_FWUPD_FIRMWARE_UPDATE_MANAGER_H_ #include "base/component_export.h" namespace ash { // FirmwareUpdateManager contains all logic that runs the firmware update SWA. class COMPONENT_EXPORT(ASH_FIRMWARE_UPDATE_MANAGER) FirmwareUpdateManager { public: FirmwareUpdateManager(); FirmwareUpdateManager(const FirmwareUpdateManager&) = delete; FirmwareUpdateManager& operator=(const FirmwareUpdateManager&) = delete; ~FirmwareUpdateManager(); // Gets the global instance pointer. static FirmwareUpdateManager* Get(); }; } // namespace ash #endif // ASH_COMPONENTS_FWUPD_FIRMWARE_UPDATE_MANAGER_H_
blueboxd/chromium-legacy
third_party/blink/renderer/core/timing/window_performance.h
/* * Copyright (C) 2010 Google Inc. All rights reserved. * Copyright (C) 2012 Intel Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_TIMING_WINDOW_PERFORMANCE_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_TIMING_WINDOW_PERFORMANCE_H_ #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/events/pointer_event.h" #include "third_party/blink/renderer/core/execution_context/execution_context_lifecycle_observer.h" #include "third_party/blink/renderer/core/frame/performance_monitor.h" #include "third_party/blink/renderer/core/page/page_visibility_observer.h" #include "third_party/blink/renderer/core/timing/event_counts.h" #include "third_party/blink/renderer/core/timing/memory_info.h" #include "third_party/blink/renderer/core/timing/performance.h" #include "third_party/blink/renderer/core/timing/performance_event_timing.h" #include "third_party/blink/renderer/core/timing/performance_navigation.h" #include "third_party/blink/renderer/core/timing/performance_timing.h" #include "third_party/blink/renderer/core/timing/responsiveness_metrics.h" #include "third_party/blink/renderer/platform/heap/heap_allocator.h" #include "third_party/blink/renderer/platform/wtf/wtf_size_t.h" namespace blink { class IntSize; class CORE_EXPORT WindowPerformance final : public Performance, public PerformanceMonitor::Client, public ExecutionContextClient, public PageVisibilityObserver { friend class WindowPerformanceTest; friend class ResponsivenessMetrics; class EventData : public GarbageCollected<EventData> { public: EventData(PerformanceEventTiming* event_timing, uint64_t frame, base::TimeTicks event_timestamp, absl::optional<int> key_code, absl::optional<PointerId> pointer_id) : event_timing_(event_timing), frame_(frame), event_timestamp_(event_timestamp), key_code_(key_code), pointer_id_(pointer_id) {} static EventData* Create(PerformanceEventTiming* event_timing, uint64_t frame, base::TimeTicks event_timestamp, absl::optional<int> key_code, absl::optional<PointerId> pointer_id) { return MakeGarbageCollected<EventData>( event_timing, frame, event_timestamp, key_code, pointer_id); } ~EventData() = default; void Trace(Visitor*) const; PerformanceEventTiming* GetEventTiming() const { return event_timing_; } uint64_t GetFrameIndex() const { return frame_; } base::TimeTicks GetEventTimestamp() const { return event_timestamp_; } absl::optional<int> GetKeyCode() const { return key_code_; } absl::optional<PointerId> GetPointerId() const { return pointer_id_; } private: // Event PerformanceEventTiming entry that has not been sent to observers // yet: the event dispatch has been completed but the presentation promise // used to determine |duration| has not yet been resolved. Member<PerformanceEventTiming> event_timing_; // Frame index in which the entry in |event_timing_| were added. uint64_t frame_; // The event creation timestamp. base::TimeTicks event_timestamp_; // Keycode for the event. If the event is not a keyboard event, the keycode // wouldn't be set. absl::optional<int> key_code_; // PointerId for the event. If the event is not a pointer event, the // PointerId wouldn't be set. absl::optional<PointerId> pointer_id_; }; public: explicit WindowPerformance(LocalDOMWindow*); ~WindowPerformance() override; ExecutionContext* GetExecutionContext() const override; PerformanceTiming* timing() const override; PerformanceNavigation* navigation() const override; MemoryInfo* memory(ScriptState*) const override; EventCounts* eventCounts() override; bool FirstInputDetected() const { return !!first_input_timing_; } // This method creates a PerformanceEventTiming and if needed creates a // presentation promise to calculate the |duration| attribute when such // promise is resolved. void RegisterEventTiming(const Event& event, base::TimeTicks start_time, base::TimeTicks processing_start, base::TimeTicks processing_end); void OnPaintFinished(); void AddElementTiming(const AtomicString& name, const String& url, const FloatRect& rect, base::TimeTicks start_time, base::TimeTicks load_time, const AtomicString& identifier, const IntSize& intrinsic_size, const AtomicString& id, Element*); void AddLayoutShiftEntry(LayoutShift*); void AddVisibilityStateEntry(bool is_visible, base::TimeTicks start_time); // PageVisibilityObserver void PageVisibilityChanged() override; void OnLargestContentfulPaintUpdated( base::TimeTicks paint_time, uint64_t paint_size, base::TimeTicks load_time, base::TimeTicks first_animated_frame_time, const AtomicString& id, const String& url, Element*); void Trace(Visitor*) const override; ResponsivenessMetrics& GetResponsivenessMetrics() { return *responsiveness_metrics_; } void NotifyPotentialDrag(PointerId pointer_id); void SetCurrentEventTimingEvent(const Event* event) { current_event_ = event; } const Event* GetCurrentEventTimingEvent() { return current_event_; } private: PerformanceNavigationTiming* CreateNavigationTimingInstance() override; static std::pair<AtomicString, DOMWindow*> SanitizedAttribution( ExecutionContext*, bool has_multiple_contexts, LocalFrame* observer_frame); // PerformanceMonitor::Client implementation. void ReportLongTask(base::TimeTicks start_time, base::TimeTicks end_time, ExecutionContext* task_context, bool has_multiple_contexts) override; void BuildJSONValue(V8ObjectBuilder&) const override; // Method called once presentation promise for a frame is resolved. It will // add all event timings that have not been added since the last presentation // promise. void ReportEventTimings(uint64_t frame_index, base::TimeTicks presentation_timestamp); void DispatchFirstInputTiming(PerformanceEventTiming* entry); // Assign an interaction id to an event timing entry if needed. Also records // the interaction latency. Returns true if the entry is ready to be surfaced // in PerformanceObservers and the Performance Timeline bool SetInteractionIdAndRecordLatency( PerformanceEventTiming* entry, absl::optional<int> key_code, absl::optional<PointerId> pointer_id, ResponsivenessMetrics::EventTimestamps event_timestamps); // Notify observer that an event timing entry is ready and add it to the event // timing buffer if needed. void NotifyAndAddEventTimingBuffer(PerformanceEventTiming* entry); // NotifyAndAddEventTimingBuffer() when interactionId feature is enabled. void MaybeNotifyInteractionAndAddEventTimingBuffer( PerformanceEventTiming* entry); // The last time the page visibility was changed. base::TimeTicks last_visibility_change_timestamp_; // Counter of the current frame index, based on calls to OnPaintFinished(). uint64_t frame_index_ = 1; // Monotonically increasing value with the last frame index on which a // presentation promise was queued; uint64_t last_registered_frame_index_ = 0; // Number of pending presentation promises. uint16_t pending_presentation_promise_count_ = 0; // Store all event timing and latency related data, including // PerformanceEventTiming, frame_index, keycode and pointerId. We use the data // to calculate events latencies. HeapDeque<Member<EventData>> events_data_; Member<PerformanceEventTiming> first_pointer_down_event_timing_; Member<EventCounts> event_counts_; mutable Member<PerformanceNavigation> navigation_; mutable Member<PerformanceTiming> timing_; absl::optional<base::TimeDelta> pending_pointer_down_input_delay_; absl::optional<base::TimeDelta> pending_pointer_down_processing_time_; absl::optional<base::TimeDelta> pending_pointer_down_time_to_next_paint_; // Calculate responsiveness metrics and record UKM for them. Member<ResponsivenessMetrics> responsiveness_metrics_; // The event we are currently processing. WeakMember<const Event> current_event_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_TIMING_WINDOW_PERFORMANCE_H_
blueboxd/chromium-legacy
chrome/browser/enterprise/connectors/device_trust/key_management/browser/key_rotation_launcher.h
<filename>chrome/browser/enterprise/connectors/device_trust/key_management/browser/key_rotation_launcher.h // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_ENTERPRISE_CONNECTORS_DEVICE_TRUST_KEY_MANAGEMENT_BROWSER_KEY_ROTATION_LAUNCHER_H_ #define CHROME_BROWSER_ENTERPRISE_CONNECTORS_DEVICE_TRUST_KEY_MANAGEMENT_BROWSER_KEY_ROTATION_LAUNCHER_H_ #include <string> #include "base/compiler_specific.h" namespace policy { class BrowserDMTokenStorage; class DeviceManagementService; } // namespace policy namespace enterprise_connectors { // Builds a key rotation payload using `dm_token_storage`, // `device_management_service` and `nonce`, and then kicks off a key rotation // command. Returns true if the command was correctly triggered. bool LaunchKeyRotation( policy::BrowserDMTokenStorage* dm_token_storage, policy::DeviceManagementService* device_management_service, const std::string& nonce) WARN_UNUSED_RESULT; } // namespace enterprise_connectors #endif // CHROME_BROWSER_ENTERPRISE_CONNECTORS_DEVICE_TRUST_KEY_MANAGEMENT_BROWSER_KEY_ROTATION_LAUNCHER_H_
blueboxd/chromium-legacy
components/optimization_guide/content/browser/test_page_content_annotator.h
<gh_stars>10-100 // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_OPTIMIZATION_GUIDE_CONTENT_BROWSER_TEST_PAGE_CONTENT_ANNOTATOR_H_ #define COMPONENTS_OPTIMIZATION_GUIDE_CONTENT_BROWSER_TEST_PAGE_CONTENT_ANNOTATOR_H_ #include "base/containers/flat_map.h" #include "components/optimization_guide/content/browser/page_content_annotator.h" #include "components/optimization_guide/core/page_content_annotations_common.h" namespace optimization_guide { // Pass this to // |PageContentAnnotationsService::OverridePageContentAnnotatorForTesting| for // unit testing, or just build this into the prod binary for local development // manual testing and hard code the desired output. class TestPageContentAnnotator : public PageContentAnnotator { public: TestPageContentAnnotator(); ~TestPageContentAnnotator() override; // The given |status| is used in every BatchAnnotationResult. Only the success // status will also populate any corresponding model output given below. void UseExecutionStatus(ExecutionStatus status); // The given page topics are used for the matching BatchAnnotationResults by // input string. If the input is not found, the output is left as nullopt. void UsePageTopics( const base::flat_map<std::string, std::vector<WeightedString>>& topics_by_input); // The given page entities are used for the matching BatchAnnotationResults by // input string. If the input is not found, the output is left as nullopt. void UsePageEntities( const base::flat_map<std::string, std::vector<WeightedString>>& entities_by_input); // The given visibility score is used for the matching BatchAnnotationResults // by input string. If the input is not found, the output is left as nullopt. void UseVisibilityScores( const base::flat_map<std::string, double>& visibility_scores_for_input); // PageContentAnnotator: void Annotate(BatchAnnotationCallback callback, const std::vector<std::string>& inputs, AnnotationType annotation_type) override; private: ExecutionStatus status_ = ExecutionStatus::kUnknown; base::flat_map<std::string, std::vector<WeightedString>> topics_by_input_; base::flat_map<std::string, std::vector<WeightedString>> entities_by_input_; base::flat_map<std::string, double> visibility_scores_for_input_; }; } // namespace optimization_guide #endif // COMPONENTS_OPTIMIZATION_GUIDE_CONTENT_BROWSER_TEST_PAGE_CONTENT_ANNOTATOR_H_
blueboxd/chromium-legacy
device/bluetooth/floss/fake_floss_adapter_client.h
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef DEVICE_BLUETOOTH_FLOSS_FAKE_FLOSS_ADAPTER_CLIENT_H_ #define DEVICE_BLUETOOTH_FLOSS_FAKE_FLOSS_ADAPTER_CLIENT_H_ #include "base/logging.h" #include "device/bluetooth/bluetooth_export.h" #include "device/bluetooth/floss/floss_adapter_client.h" namespace floss { class DEVICE_BLUETOOTH_EXPORT FakeFlossAdapterClient : public FlossAdapterClient { public: FakeFlossAdapterClient(); ~FakeFlossAdapterClient() override; // The address of a device without Keyboard nor Display IO capability, // triggering Just Works pairing when used in tests. static const char kJustWorksAddress[]; // Fake overrides. void Init(dbus::Bus* bus, const std::string& service_name, const std::string& adapter_path) override; void StartDiscovery(ResponseCallback callback) override; void CancelDiscovery(ResponseCallback callback) override; void CreateBond(ResponseCallback callback, FlossDeviceId device, BluetoothTransport transport) override; // Helper for posting a delayed task. void PostDelayedTask(base::OnceClosure callback); private: base::WeakPtrFactory<FakeFlossAdapterClient> weak_ptr_factory_{this}; }; } // namespace floss #endif // DEVICE_BLUETOOTH_FLOSS_FAKE_FLOSS_ADAPTER_CLIENT_H_
blueboxd/chromium-legacy
chrome/browser/extensions/api/passwords_private/passwords_private_utils_chromeos.h
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_EXTENSIONS_API_PASSWORDS_PRIVATE_PASSWORDS_PRIVATE_UTILS_CHROMEOS_H_ #define CHROME_BROWSER_EXTENSIONS_API_PASSWORDS_PRIVATE_PASSWORDS_PRIVATE_UTILS_CHROMEOS_H_ #include "base/time/time.h" #include "build/chromeos_buildflags.h" #include "components/password_manager/core/browser/reauth_purpose.h" class Profile; namespace extensions { // Returns the lifetime of an auth token for a given |purpose|. base::TimeDelta GetAuthTokenLifetimeForPurpose( password_manager::ReauthPurpose purpose); #if BUILDFLAG(IS_CHROMEOS_ASH) // Returns whether |profile| has been authorized for password access, and // whether the auth token is no older than |auth_token_lifespan|. Authorization // is automatic if no password is needed. bool IsOsReauthAllowedAsh(Profile* profile, base::TimeDelta auth_token_lifespan); #endif // BUILDFLAG(IS_CHROMEOS_ASH) } // namespace extensions #endif // CHROME_BROWSER_EXTENSIONS_API_PASSWORDS_PRIVATE_PASSWORDS_PRIVATE_UTILS_CHROMEOS_H_
blueboxd/chromium-legacy
components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.h
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_VIZ_SERVICE_DISPLAY_EMBEDDER_SKIA_OUTPUT_SURFACE_IMPL_ON_GPU_H_ #define COMPONENTS_VIZ_SERVICE_DISPLAY_EMBEDDER_SKIA_OUTPUT_SURFACE_IMPL_ON_GPU_H_ #include <map> #include <memory> #include <utility> #include <vector> #include "base/containers/span.h" #include "base/macros.h" #include "base/threading/thread_checker.h" #include "base/types/id_type.h" #include "base/types/pass_key.h" #include "build/build_config.h" #include "components/viz/common/display/renderer_settings.h" #include "components/viz/common/gpu/context_lost_reason.h" #include "components/viz/common/quads/compositor_render_pass.h" #include "components/viz/common/resources/release_callback.h" #include "components/viz/service/display/external_use_client.h" #include "components/viz/service/display/output_surface.h" #include "components/viz/service/display/output_surface_frame.h" #include "components/viz/service/display/overlay_processor_interface.h" #include "components/viz/service/display_embedder/skia_output_device.h" #include "components/viz/service/display_embedder/skia_output_surface_dependency.h" #include "components/viz/service/display_embedder/skia_render_copy_results.h" #include "gpu/command_buffer/common/mailbox.h" #include "gpu/command_buffer/common/sync_token.h" #include "gpu/command_buffer/service/shared_context_state.h" #include "gpu/command_buffer/service/shared_image_representation.h" #include "gpu/command_buffer/service/sync_point_manager.h" #include "gpu/ipc/service/context_url.h" #include "gpu/ipc/service/display_context.h" #include "gpu/ipc/service/image_transport_surface_delegate.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/skia/include/core/SkDeferredDisplayList.h" #include "third_party/skia/include/core/SkPromiseImageTexture.h" #include "third_party/skia/include/core/SkSurface.h" #include "third_party/skia/include/gpu/GrBackendSemaphore.h" namespace gfx { namespace mojom { class DelegatedInkPointRenderer; } // namespace mojom class ColorSpace; } namespace gl { class GLSurface; } namespace gpu { class SharedImageRepresentationFactory; class SharedImageFactory; class SyncPointClientState; } // namespace gpu namespace ui { #if defined(USE_OZONE) class PlatformWindowSurface; #endif } // namespace ui namespace viz { class AsyncReadResultHelper; class AsyncReadResultLock; class DawnContextProvider; class ImageContextImpl; class VulkanContextProvider; namespace copy_output { struct RenderPassGeometry; } // namespace copy_output // The SkiaOutputSurface implementation running on the GPU thread. This class // should be created, used and destroyed on the GPU thread. class SkiaOutputSurfaceImplOnGpu : public gpu::ImageTransportSurfaceDelegate, public gpu::SharedContextState::ContextLostObserver { public: using DidSwapBufferCompleteCallback = base::RepeatingCallback<void(gpu::SwapBuffersCompleteParams, const gfx::Size& pixel_size, gfx::GpuFenceHandle release_fence)>; using BufferPresentedCallback = base::RepeatingCallback<void(const gfx::PresentationFeedback& feedback)>; using ContextLostCallback = base::OnceClosure; // |gpu_vsync_callback| must be safe to call on any thread. The other // callbacks will only be called via |deps->PostTaskToClientThread|. static std::unique_ptr<SkiaOutputSurfaceImplOnGpu> Create( SkiaOutputSurfaceDependency* deps, const RendererSettings& renderer_settings, const gpu::SequenceId sequence_id, gpu::DisplayCompositorMemoryAndTaskControllerOnGpu* shared_gpu_deps, DidSwapBufferCompleteCallback did_swap_buffer_complete_callback, BufferPresentedCallback buffer_presented_callback, ContextLostCallback context_lost_callback, GpuVSyncCallback gpu_vsync_callback); SkiaOutputSurfaceImplOnGpu( base::PassKey<SkiaOutputSurfaceImplOnGpu> pass_key, SkiaOutputSurfaceDependency* deps, scoped_refptr<gpu::gles2::FeatureInfo> feature_info, const RendererSettings& renderer_settings, const gpu::SequenceId sequence_id, gpu::DisplayCompositorMemoryAndTaskControllerOnGpu* shared_gpu_deps, DidSwapBufferCompleteCallback did_swap_buffer_complete_callback, BufferPresentedCallback buffer_presented_callback, ContextLostCallback context_lost_callback, GpuVSyncCallback gpu_vsync_callback); SkiaOutputSurfaceImplOnGpu(const SkiaOutputSurfaceImplOnGpu&) = delete; SkiaOutputSurfaceImplOnGpu& operator=(const SkiaOutputSurfaceImplOnGpu&) = delete; ~SkiaOutputSurfaceImplOnGpu() override; gpu::CommandBufferId command_buffer_id() const { return shared_gpu_deps_->command_buffer_id(); } const OutputSurface::Capabilities& capabilities() const { return output_device_->capabilities(); } const base::WeakPtr<SkiaOutputSurfaceImplOnGpu>& weak_ptr() const { return weak_ptr_; } gl::GLSurface* gl_surface() const { return gl_surface_.get(); } void Reshape(const gfx::Size& size, float device_scale_factor, const gfx::ColorSpace& color_space, gfx::BufferFormat format, bool use_stencil, gfx::OverlayTransform transform); void FinishPaintCurrentFrame(sk_sp<SkDeferredDisplayList> ddl, sk_sp<SkDeferredDisplayList> overdraw_ddl, std::vector<ImageContextImpl*> image_contexts, std::vector<gpu::SyncToken> sync_tokens, base::OnceClosure on_finished, absl::optional<gfx::Rect> draw_rectangle, bool allocate_frame_buffer); void ScheduleOutputSurfaceAsOverlay( const OverlayProcessorInterface::OutputSurfaceOverlayPlane& output_surface_plane); void SwapBuffers(OutputSurfaceFrame frame, bool release_frame_buffer); void ReleaseFrameBuffers(int n); void SetDependenciesResolvedTimings(base::TimeTicks task_ready); void SetDrawTimings(base::TimeTicks task_ready); // Runs |deferred_framebuffer_draw_closure| when SwapBuffers() or CopyOutput() // will not. void SwapBuffersSkipped(); void EnsureBackbuffer(); void DiscardBackbuffer(); void FinishPaintRenderPass(const gpu::Mailbox& mailbox, sk_sp<SkDeferredDisplayList> ddl, std::vector<ImageContextImpl*> image_contexts, std::vector<gpu::SyncToken> sync_tokens, base::OnceClosure on_finished); // Deletes resources for RenderPasses in |ids|. Also takes ownership of // |images_contexts| and destroys them on GPU thread. void RemoveRenderPassResource( std::vector<AggregatedRenderPassId> ids, std::vector<std::unique_ptr<ImageContextImpl>> image_contexts); void CopyOutput(AggregatedRenderPassId id, copy_output::RenderPassGeometry geometry, const gfx::ColorSpace& color_space, std::unique_ptr<CopyOutputRequest> request, const gpu::Mailbox& mailbox); void BeginAccessImages(const std::vector<ImageContextImpl*>& image_contexts, std::vector<GrBackendSemaphore>* begin_semaphores, std::vector<GrBackendSemaphore>* end_semaphores); void ResetStateOfImages(); void EndAccessImages(const base::flat_set<ImageContextImpl*>& image_contexts); sk_sp<GrContextThreadSafeProxy> GetGrContextThreadSafeProxy(); size_t max_resource_cache_bytes() const { return max_resource_cache_bytes_; } void ReleaseImageContexts( std::vector<std::unique_ptr<ExternalUseClient::ImageContext>> image_contexts); void ScheduleOverlays(SkiaOutputSurface::OverlayList overlays, std::vector<ImageContextImpl*> image_contexts, base::OnceClosure on_finished); void SetEnableDCLayers(bool enable); void SetGpuVSyncEnabled(bool enabled); void SetFrameRate(float frame_rate); bool was_context_lost() { return context_state_->context_lost(); } void SetCapabilitiesForTesting( const OutputSurface::Capabilities& capabilities); bool IsDisplayedAsOverlay(); // gpu::SharedContextState::ContextLostObserver implementation: void OnContextLost() override; // gpu::ImageTransportSurfaceDelegate implementation: #if defined(OS_WIN) void DidCreateAcceleratedSurfaceChildWindow( gpu::SurfaceHandle parent_window, gpu::SurfaceHandle child_window) override; #endif const gpu::gles2::FeatureInfo* GetFeatureInfo() const override; const gpu::GpuPreferences& GetGpuPreferences() const override; void DidSwapBuffersComplete(gpu::SwapBuffersCompleteParams params, gfx::GpuFenceHandle release_fence) override; void BufferPresented(const gfx::PresentationFeedback& feedback) override; GpuVSyncCallback GetGpuVSyncCallback() override; base::TimeDelta GetGpuBlockedTimeSinceLastSwap() override; void PostTaskToClientThread(base::OnceClosure closure) { dependency_->PostTaskToClientThread(std::move(closure)); } void ReadbackDone() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK_GT(num_readbacks_pending_, 0); num_readbacks_pending_--; } // Make context current for GL, and return false if the context is lost. // It will do nothing when Vulkan is used. bool MakeCurrent(bool need_framebuffer); void ReleaseFenceSync(uint64_t sync_fence_release); void PreserveChildSurfaceControls(); void InitDelegatedInkPointRendererReceiver( mojo::PendingReceiver<gfx::mojom::DelegatedInkPointRenderer> pending_receiver); const scoped_refptr<AsyncReadResultLock> GetAsyncReadResultLock() const; void AddAsyncReadResultHelper(AsyncReadResultHelper* helper); void RemoveAsyncReadResultHelper(AsyncReadResultHelper* helper); private: class DisplayContext; struct PlaneAccessData { PlaneAccessData(); PlaneAccessData(PlaneAccessData&& other); PlaneAccessData& operator=(PlaneAccessData&& other); ~PlaneAccessData(); SkISize size; gpu::Mailbox mailbox; std::unique_ptr<gpu::SharedImageRepresentationSkia> representation; std::unique_ptr<gpu::SharedImageRepresentationSkia::ScopedWriteAccess> scoped_write; std::vector<GrBackendSemaphore> begin_semaphores; std::vector<GrBackendSemaphore> end_semaphores; }; bool Initialize(); bool InitializeForGL(); bool InitializeForVulkan(); bool InitializeForDawn(); // Provided as a callback to |device_|. void DidSwapBuffersCompleteInternal(gpu::SwapBuffersCompleteParams params, const gfx::Size& pixel_size, gfx::GpuFenceHandle release_fence); DidSwapBufferCompleteCallback GetDidSwapBuffersCompleteCallback(); void MarkContextLost(ContextLostReason reason); void RunDestroyCopyOutputResourcesOnGpuThread( ReleaseCallback* callback, const gpu::SyncToken& sync_token, bool is_lost); void DestroyCopyOutputResourcesOnGpuThread( std::unique_ptr<gpu::SharedImageRepresentationSkia> representation, scoped_refptr<gpu::SharedContextState> context_state, const gpu::SyncToken& sync_token, bool is_lost); void SwapBuffersInternal(absl::optional<OutputSurfaceFrame> frame); void PostSubmit(absl::optional<OutputSurfaceFrame> frame); GrDirectContext* gr_context() { return context_state_->gr_context(); } bool is_using_vulkan() const { return !!vulkan_context_provider_ && gpu_preferences_.gr_context_type == gpu::GrContextType::kVulkan; } bool is_using_dawn() const { return !!dawn_context_provider_ && gpu_preferences_.gr_context_type == gpu::GrContextType::kDawn; } // Helper for `CopyOutput()` method, handles the RGBA format. void CopyOutputRGBA(SkSurface* surface, copy_output::RenderPassGeometry geometry, const gfx::ColorSpace& color_space, const SkIRect& src_rect, SkSurface::RescaleMode rescale_mode, bool is_downscale_or_identity_in_both_dimensions, std::unique_ptr<CopyOutputRequest> request); void CopyOutputRGBAInMemory(SkSurface* surface, copy_output::RenderPassGeometry geometry, const gfx::ColorSpace& color_space, const SkIRect& src_rect, SkSurface::RescaleMode rescale_mode, bool is_downscale_or_identity_in_both_dimensions, std::unique_ptr<CopyOutputRequest> request); void CopyOutputNV12(SkSurface* surface, copy_output::RenderPassGeometry geometry, const gfx::ColorSpace& color_space, const SkIRect& src_rect, SkSurface::RescaleMode rescale_mode, bool is_downscale_or_identity_in_both_dimensions, std::unique_ptr<CopyOutputRequest> request); // Helper for `CopyOutputNV12()` & `CopyOutputRGBA()` methods: std::unique_ptr<gpu::SharedImageRepresentationSkia> CreateSharedImageRepresentationSkia(ResourceFormat resource_format, const gfx::Size& size, const gfx::ColorSpace& color_space); // Helper for `CopyOutputNV12()` & `CopyOutputRGBA()` methods, renders // |surface| into |dest_surface|'s canvas, cropping and scaling the results // appropriately. |source_selection| is the area of the |surface| that will be // rendered to the destination. // |begin_semaphores| will be submitted to the GPU backend prior to issuing // draw calls to the |dest_surface|. // |end_semaphores| will be submitted to the GPU backend alongside the draw // calls to the |dest_surface|. bool RenderSurface(SkSurface* surface, const SkIRect& source_selection, absl::optional<SkVector> scaling, bool is_downscale_or_identity_in_both_dimensions, SkSurface* dest_surface, std::vector<GrBackendSemaphore>& begin_semaphores, std::vector<GrBackendSemaphore>& end_semaphores); // Creates surfaces needed to store the data in NV12 format. // |plane_access_datas| will be populated with information needed to access // the NV12 planes. bool CreateSurfacesForNV12Planes( const SkYUVAInfo& yuva_info, const gfx::ColorSpace& color_space, std::array<PlaneAccessData, CopyOutputResult::kNV12MaxPlanes>& plane_access_datas); // Schedules a task to check if any skia readback requests have completed // after a short delay. Will not schedule a task if there is already a // scheduled task or no readback requests are pending. void ScheduleCheckReadbackCompletion(); // Checks if any skia readback requests have completed. If there are still // pending readback requests after checking then it will reschedule itself // after a short delay. void CheckReadbackCompletion(); void ReleaseAsyncReadResultHelpers(); #if defined(OS_APPLE) || defined(USE_OZONE) std::unique_ptr<gpu::SharedImageRepresentationSkia> GetOrCreateRenderPassOverlayBacking( const SkSurfaceCharacterization& characterization); #endif class ReleaseCurrent { public: ReleaseCurrent(scoped_refptr<gl::GLSurface> gl_surface, scoped_refptr<gpu::SharedContextState> context_state); ~ReleaseCurrent(); private: scoped_refptr<gl::GLSurface> gl_surface_; scoped_refptr<gpu::SharedContextState> context_state_; }; // This must remain the first member variable to ensure that other member // dtors are called first. absl::optional<ReleaseCurrent> release_current_last_; SkiaOutputSurfaceDependency* const dependency_; gpu::DisplayCompositorMemoryAndTaskControllerOnGpu* shared_gpu_deps_; scoped_refptr<gpu::gles2::FeatureInfo> feature_info_; scoped_refptr<gpu::SyncPointClientState> sync_point_client_state_; std::unique_ptr<gpu::SharedImageFactory> shared_image_factory_; std::unique_ptr<gpu::SharedImageRepresentationFactory> shared_image_representation_factory_; VulkanContextProvider* const vulkan_context_provider_; DawnContextProvider* const dawn_context_provider_; const RendererSettings renderer_settings_; // Should only be run on the client thread with PostTaskToClientThread(). DidSwapBufferCompleteCallback did_swap_buffer_complete_callback_; BufferPresentedCallback buffer_presented_callback_; ContextLostCallback context_lost_callback_; GpuVSyncCallback gpu_vsync_callback_; // ImplOnGpu::CopyOutput can create SharedImages via ImplOnGpu's // SharedImageFactory. Clients can use these images via CopyOutputResult and // when done, release the resources by invoking the provided callback. If // ImplOnGpu is already destroyed, however, there is no way of running the // release callback from the client, so this vector holds all pending release // callbacks so resources can still be cleaned up in the dtor. std::vector<std::unique_ptr<ReleaseCallback>> release_on_gpu_callbacks_; // Helper, creates a release callback for the passed in |representation|. ReleaseCallback CreateDestroyCopyOutputResourcesOnGpuThreadCallback( std::unique_ptr<gpu::SharedImageRepresentationSkia> representation); #if defined(USE_OZONE) // This should outlive gl_surface_ and vulkan_surface_. std::unique_ptr<ui::PlatformWindowSurface> window_surface_; #endif gpu::GpuPreferences gpu_preferences_; gfx::Size size_; gfx::ColorSpace color_space_; scoped_refptr<gl::GLSurface> gl_surface_; scoped_refptr<gpu::SharedContextState> context_state_; size_t max_resource_cache_bytes_ = 0u; std::unique_ptr<DisplayContext> display_context_; bool context_is_lost_ = false; class PromiseImageAccessHelper { public: explicit PromiseImageAccessHelper(SkiaOutputSurfaceImplOnGpu* impl_on_gpu); PromiseImageAccessHelper(const PromiseImageAccessHelper&) = delete; PromiseImageAccessHelper& operator=(const PromiseImageAccessHelper&) = delete; ~PromiseImageAccessHelper(); void BeginAccess(std::vector<ImageContextImpl*> image_contexts, std::vector<GrBackendSemaphore>* begin_semaphores, std::vector<GrBackendSemaphore>* end_semaphores); void EndAccess(); private: SkiaOutputSurfaceImplOnGpu* const impl_on_gpu_; base::flat_set<ImageContextImpl*> image_contexts_; }; PromiseImageAccessHelper promise_image_access_helper_{this}; base::flat_set<ImageContextImpl*> image_contexts_with_end_access_state_; std::unique_ptr<SkiaOutputDevice> output_device_; std::unique_ptr<SkiaOutputDevice::ScopedPaint> scoped_output_device_paint_; absl::optional<OverlayProcessorInterface::OutputSurfaceOverlayPlane> output_surface_plane_; // Micro-optimization to get to issuing GPU SwapBuffers as soon as possible. std::vector<sk_sp<SkDeferredDisplayList>> destroy_after_swap_; bool waiting_for_full_damage_ = false; int num_readbacks_pending_ = 0; bool readback_poll_pending_ = false; // Lock for |async_read_result_helpers_|. scoped_refptr<AsyncReadResultLock> async_read_result_lock_; // Tracking for ongoing AsyncReadResults. base::flat_set<AsyncReadResultHelper*> async_read_result_helpers_; #if defined(OS_APPLE) || defined(USE_OZONE) using UniqueBackingPtr = std::unique_ptr<gpu::SharedImageRepresentationSkia>; class BackingComparator { public: using is_transparent = void; bool operator()(const UniqueBackingPtr& lhs, const UniqueBackingPtr& rhs) const { return lhs->mailbox() < rhs->mailbox(); } bool operator()(const UniqueBackingPtr& lhs, const gpu::Mailbox& rhs) const { return lhs->mailbox() < rhs; } bool operator()(const gpu::Mailbox& lhs, const UniqueBackingPtr& rhs) const { return lhs < rhs->mailbox(); } }; // Render pass overlay backings are in flight. // The base::flat_set uses backing->mailbox() as the unique key. base::flat_set<UniqueBackingPtr, BackingComparator> in_flight_render_pass_overlay_backings_; // Render pass overlay backings are available for reusing. std::vector<std::unique_ptr<gpu::SharedImageRepresentationSkia>> available_render_pass_overlay_backings_; #endif THREAD_CHECKER(thread_checker_); base::WeakPtr<SkiaOutputSurfaceImplOnGpu> weak_ptr_; base::WeakPtrFactory<SkiaOutputSurfaceImplOnGpu> weak_ptr_factory_{this}; }; } // namespace viz #endif // COMPONENTS_VIZ_SERVICE_DISPLAY_EMBEDDER_SKIA_OUTPUT_SURFACE_IMPL_ON_GPU_H_
blueboxd/chromium-legacy
third_party/blink/renderer/core/html/forms/html_select_menu_element.h
<reponame>blueboxd/chromium-legacy // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_HTML_FORMS_HTML_SELECT_MENU_ELEMENT_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_FORMS_HTML_SELECT_MENU_ELEMENT_H_ #include "third_party/blink/renderer/core/dom/events/native_event_listener.h" #include "third_party/blink/renderer/core/html/forms/html_form_control_element_with_state.h" namespace blink { class Document; // The HTMLSelectMenuElement implements the <selectmenu> HTML element. // The <selectmenu> element is similar to <select>, but allows site authors // freedom to customize the element's appearance and shadow DOM structure. // This feature is still under development, and is not part of the HTML // standard. It can be enabled by passing // --enable-blink-features=HTMLSelectMenuElement. See // https://groups.google.com/u/1/a/chromium.org/g/blink-dev/c/9TcfjaOs5zg/m/WAiv6WpUAAAJ // for more details. class CORE_EXPORT HTMLSelectMenuElement final : public HTMLFormControlElementWithState { DEFINE_WRAPPERTYPEINFO(); public: explicit HTMLSelectMenuElement(Document&); String value(); void setValue(const String&, bool send_events = false); bool open() const; void Trace(Visitor*) const override; enum class PartType { kNone, kButton, kListBox, kOption }; // If node is a flat tree descendant of an HTMLSelectMenuElement // and is registered as a part of that HTMLSelectMenuElement, // returns that HTMLSelectMenuElement. Else returns null. static HTMLSelectMenuElement* OwnerSelectMenu(Node* node); PartType AssignedPartType(Node* node) const; Element* ButtonPart() const { return button_part_; } private: class SelectMutationCallback; void DidAddUserAgentShadowRoot(ShadowRoot&) override; void OpenListbox(); void CloseListbox(); void UpdatePartElements(); Element* FirstOptionPart() const; Element* FirstValidButtonPart() const; Element* FirstValidListboxPart() const; Element* FirstValidSelectedValuePart() const; void EnsureSelectedOptionIsValid(); Element* SelectedOption(); void SetSelectedOption(Element* selected_option); void SelectNextOption(); void SelectPreviousOption(); void UpdateSelectedValuePartContents(); void ButtonPartInserted(Element*); void ButtonPartRemoved(Element*); void UpdateButtonPart(); void SelectedValuePartInserted(Element*); void SelectedValuePartRemoved(Element*); void UpdateSelectedValuePart(); void ListboxPartInserted(Element*); void ListboxPartRemoved(Element*); void UpdateListboxPart(); void OptionPartInserted(Element*); void OptionPartRemoved(Element*); void ResetOptionParts(); bool IsValidButtonPart(const Node* node, bool show_warning) const; bool IsValidListboxPart(const Node* node, bool show_warning) const; bool IsValidOptionPart(const Node* node, bool show_warning) const; void SetButtonPart(Element* new_button_part); void SetListboxPart(HTMLPopupElement* new_listbox_part); // HTMLFormControlElementWithState overrides: const AtomicString& FormControlType() const override; bool MayTriggerVirtualKeyboard() const override; bool AlwaysCreateUserAgentShadowRoot() const override { return false; } void AppendToFormData(FormData&) override; bool SupportsFocus() const override { return HTMLElement::SupportsFocus(); } // TODO(crbug.com/1121840) Add support for saving form control state FormControlState SaveFormControlState() const override; void RestoreFormControlState(const FormControlState&) override; class ButtonPartEventListener : public NativeEventListener { public: explicit ButtonPartEventListener(HTMLSelectMenuElement* select_menu_element) : select_menu_element_(select_menu_element) {} void Invoke(ExecutionContext*, Event*) override; void Trace(Visitor* visitor) const override { visitor->Trace(select_menu_element_); NativeEventListener::Trace(visitor); } private: Member<HTMLSelectMenuElement> select_menu_element_; }; class OptionPartEventListener : public NativeEventListener { public: explicit OptionPartEventListener(HTMLSelectMenuElement* select_menu_element) : select_menu_element_(select_menu_element) {} void Invoke(ExecutionContext*, Event*) override; void Trace(Visitor* visitor) const override { visitor->Trace(select_menu_element_); NativeEventListener::Trace(visitor); } private: Member<HTMLSelectMenuElement> select_menu_element_; }; static constexpr char kButtonPartName[] = "button"; static constexpr char kSelectedValuePartName[] = "selected-value"; static constexpr char kListboxPartName[] = "listbox"; static constexpr char kOptionPartName[] = "option"; Member<ButtonPartEventListener> button_part_listener_; Member<OptionPartEventListener> option_part_listener_; Member<SelectMutationCallback> select_mutation_callback_; Member<Element> button_part_; Member<Element> selected_value_part_; Member<HTMLPopupElement> listbox_part_; HeapLinkedHashSet<Member<Element>> option_parts_; Member<HTMLSlotElement> button_slot_; Member<HTMLSlotElement> listbox_slot_; Member<Element> selected_option_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_HTML_FORMS_HTML_SELECT_MENU_ELEMENT_H_
blueboxd/chromium-legacy
ui/accessibility/ax_role_properties.h
// 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_ROLE_PROPERTIES_H_ #define UI_ACCESSIBILITY_AX_ROLE_PROPERTIES_H_ #include "ui/accessibility/ax_base_export.h" #include "ui/accessibility/ax_enums.mojom-forward.h" namespace ui { // This file contains various helper functions that determine whether a // specific accessibility role meets certain criteria. // // Please keep these functions in alphabetic order. // When using these functions in Blink, it's necessary to add the function names // to third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py, in // order to pass presubmit. // Returns true for text parents that can have inline text box children. AX_BASE_EXPORT bool CanHaveInlineTextBoxChildren(ax::mojom::Role role); // Returns true for object roles that have the attribute "Children // Presentational: True" as defined in the ARIA Specification. // https://www.w3.org/TR/wai-aria-1.1/#childrenArePresentational. AX_BASE_EXPORT bool HasPresentationalChildren(const ax::mojom::Role role); // Returns true if the given role is an alert or alert-dialog type. AX_BASE_EXPORT bool IsAlert(const ax::mojom::Role role); // Returns true if the given role is a candidate to be labeled with a classname // of TextView on Android. AX_BASE_EXPORT bool IsAndroidTextViewCandidate(const ax::mojom::Role role); // Returns true if the provided role belongs to a native or an ARIA button. AX_BASE_EXPORT bool IsButton(const ax::mojom::Role role); // Returns true if the provided role belongs to a cell or a table header. AX_BASE_EXPORT bool IsCellOrTableHeader(const ax::mojom::Role role); // Returns true if the provided role belongs to an object on which a click // handler is commonly attached, or to an object that carries out an action when // clicked, such as activating itself, opening a dialog or closing a menu. // // A button and a checkbox fall in the first category, whilst a color well and a // list menu option in the second. Note that a text field, or a similar element, // also carries out an action when clicked. It focuses itself, so the action // verb is "activate". Not all roles that inherently support a click handler or // that can potentially be focused are included, because in that case even a div // could be made clickable or focusable. // // The reason for the existence of this function is that certain screen readers, // such as Jaws, might need to report such objects as clickable to their users, // so that users will know that they could activate them if they so choose. AX_BASE_EXPORT bool IsClickable(const ax::mojom::Role role); // Returns true if the provided role is any of the combobox-related roles. AX_BASE_EXPORT bool IsComboBox(ax::mojom::Role role); // Returns true if the provided role belongs to a container with selectable // children. AX_BASE_EXPORT bool IsContainerWithSelectableChildren( const ax::mojom::Role role); // Returns true if the provided role is a control. AX_BASE_EXPORT bool IsControl(const ax::mojom::Role role); // Returns true if the provided role is a control on the Android platform. AX_BASE_EXPORT bool IsControlOnAndroid(const ax::mojom::Role role, bool isFocusable); // Returns true for an <input> used for a date or time. AX_BASE_EXPORT bool IsDateOrTimeInput(const ax::mojom::Role role); // Returns true if the provided role represents a dialog. AX_BASE_EXPORT bool IsDialog(const ax::mojom::Role role); // Returns true if the provided role is a form. AX_BASE_EXPORT bool IsForm(const ax::mojom::Role role); // Returns true if crossing into or out of the provided role should count as // crossing a format boundary. AX_BASE_EXPORT bool IsFormatBoundary(const ax::mojom::Role role); // Returns true if the provided role belongs to a heading. AX_BASE_EXPORT bool IsHeading(const ax::mojom::Role role); // Returns true if the provided role belongs to a heading or a table header. AX_BASE_EXPORT bool IsHeadingOrTableHeader(const ax::mojom::Role role); // Returns true if the provided role belongs to an iframe. AX_BASE_EXPORT bool IsIframe(const ax::mojom::Role role); // Returns true if the provided role belongs to an image, graphic, canvas, etc. AX_BASE_EXPORT bool IsImage(const ax::mojom::Role role); // Returns true if the provided role is for any kind of image or video. AX_BASE_EXPORT bool IsImageOrVideo(const ax::mojom::Role role); // Returns true if the provided role is item-like, specifically if it can hold // pos_in_set and set_size values. Roles that are item-like are not set-like. AX_BASE_EXPORT bool IsItemLike(const ax::mojom::Role role); // Returns true if the role is a subclass of the ARIA Landmark abstract role. AX_BASE_EXPORT bool IsLandmark(const ax::mojom::Role role); // Returns true if the provided role belongs to a link. AX_BASE_EXPORT bool IsLink(const ax::mojom::Role role); // Returns true if the provided role belongs to a list. AX_BASE_EXPORT bool IsList(const ax::mojom::Role role); // Returns true if the provided role belongs to a list item. AX_BASE_EXPORT bool IsListItem(const ax::mojom::Role role); // Returns true if the provided role belongs to a menu item, including menu item // checkbox and menu item radio buttons. AX_BASE_EXPORT bool IsMenuItem(ax::mojom::Role role); // Returns true if the provided role belongs to a menu or related control. AX_BASE_EXPORT bool IsMenuRelated(const ax::mojom::Role role); // Returns true if the provided role belongs to a node that is at the root of // what most accessibility APIs consider to be a document, such as the root of a // webpage, an iframe, or a PDF. AX_BASE_EXPORT bool IsPlatformDocument(const ax::mojom::Role role); // Returns true if the provided role is presentational in nature, i.e. a node // whose implicit native role semantics will not be mapped to the accessibility // API. AX_BASE_EXPORT bool IsPresentational(const ax::mojom::Role role); // Returns true if the provided role belongs to a radio. AX_BASE_EXPORT bool IsRadio(const ax::mojom::Role role); // Returns true if the provided role supports a range-based value, such as a // slider. AX_BASE_EXPORT bool IsRangeValueSupported(const ax::mojom::Role role); // Returns true if this object supports readonly. // // Note: This returns false for table cells and headers, it is up to the // caller to make sure that they are included IFF they are within an // ARIA-1.1+ role='grid' or 'treegrid', and not role='table'. AX_BASE_EXPORT bool IsReadOnlySupported(const ax::mojom::Role role); // Returns true if the provided role is at the root of a window-like container, // (AKA a widget in Views terminology), such as the root of the web contents, a // window, a dialog or the whole desktop. AX_BASE_EXPORT bool IsRootLike(ax::mojom::Role role); // Returns true if the provided role belongs to a widget that can contain a // table or grid row. AX_BASE_EXPORT bool IsRowContainer(const ax::mojom::Role role); // Returns true if the role is a subclass of the ARIA Section abstract role. AX_BASE_EXPORT bool IsSection(const ax::mojom::Role role); // Returns true if the role is a subclass of the ARIA Sectionhead role. AX_BASE_EXPORT bool IsSectionhead(const ax::mojom::Role role); // Returns true if the role is a subclass of the ARIA Select abstract role. AX_BASE_EXPORT bool IsSelect(const ax::mojom::Role role); // Returns true if the role is one of those exposed by the HTML <select> // element. AX_BASE_EXPORT bool IsSelectElement(const ax::mojom::Role role); // Returns true if the provided role either requires or has an implicit value // for aria-selected state. AX_BASE_EXPORT bool IsSelectRequiredOrImplicit(const ax::mojom::Role role); // Returns true if the provided role supports aria-selected state. AX_BASE_EXPORT bool IsSelectSupported(const ax::mojom::Role role); // Returns true if the provided role is ordered-set like, specifically if it // can hold set_size values. Roles that are set-like are not item-like. AX_BASE_EXPORT bool IsSetLike(const ax::mojom::Role role); // Returns true if the provided role belongs to a non-interactive list. AX_BASE_EXPORT bool IsStaticList(const ax::mojom::Role role); // Returns true if the role is a subclass of the ARIA Structure abstract role. AX_BASE_EXPORT bool IsStructure(const ax::mojom::Role role); // Returns true if the provided role belongs to a table or grid column, and the // table is not used for layout purposes. AX_BASE_EXPORT bool IsTableColumn(ax::mojom::Role role); // Returns true if the provided role belongs to a table header. AX_BASE_EXPORT bool IsTableHeader(ax::mojom::Role role); // Returns true if the provided role belongs to a table, a grid or a treegrid. AX_BASE_EXPORT bool IsTableLike(const ax::mojom::Role role); // Returns true if the provided role belongs to a table or grid row, and the // table is not used for layout purposes. AX_BASE_EXPORT bool IsTableRow(ax::mojom::Role role); // Returns true if the provided role is text-related, e.g., static text, line // break, or inline text box. AX_BASE_EXPORT bool IsText(ax::mojom::Role role); // Returns true if the provided role belongs to a native text field, i.e. // <input> or <textarea>. AX_BASE_EXPORT bool IsTextField(ax::mojom::Role role); // Returns true if the provided role fits the description of a UIA embedded // objects. See the method definition for more details. AX_BASE_EXPORT bool IsUIAEmbeddedObject(ax::mojom::Role role); // Returns true if the node should be read only by default AX_BASE_EXPORT bool ShouldHaveReadonlyStateByDefault( const ax::mojom::Role role); // Returns true if the role supports expand/collapse. AX_BASE_EXPORT bool SupportsExpandCollapse(const ax::mojom::Role role); // Returns true if the role supports hierarchical level. AX_BASE_EXPORT bool SupportsHierarchicalLevel(const ax::mojom::Role role); // Returns true if the provided role can have an orientation. AX_BASE_EXPORT bool SupportsOrientation(const ax::mojom::Role role); // Returns true if the provided role supports toggle. AX_BASE_EXPORT bool SupportsToggle(const ax::mojom::Role role); } // namespace ui #endif // UI_ACCESSIBILITY_AX_ROLE_PROPERTIES_H_
blueboxd/chromium-legacy
chrome/browser/ui/app_list/chrome_app_list_item_manager.h
<filename>chrome/browser/ui/app_list/chrome_app_list_item_manager.h // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_APP_LIST_CHROME_APP_LIST_ITEM_MANAGER_H_ #define CHROME_BROWSER_UI_APP_LIST_CHROME_APP_LIST_ITEM_MANAGER_H_ #include <map> #include <string> #include "ash/public/cpp/app_list/app_list_types.h" class ChromeAppListItem; // The class to manage chrome app list items and never talks to Ash. class ChromeAppListItemManager { public: ChromeAppListItemManager(); ChromeAppListItemManager(const ChromeAppListItemManager&) = delete; ChromeAppListItemManager& operator=(const ChromeAppListItemManager&) = delete; ~ChromeAppListItemManager(); // Methods to find/add/update/remove an item. ChromeAppListItem* FindItem(const std::string& id); ChromeAppListItem* AddChromeItem(std::unique_ptr<ChromeAppListItem> app_item); void UpdateChromeItem(const std::string& id, std::unique_ptr<ash::AppListItemMetadata>); void RemoveChromeItem(const std::string& id); // Implement `ChromeAppListModelUpdater` methods. size_t ItemCount() const; int BadgedItemCount() const; std::vector<ChromeAppListItem*> GetTopLevelItems() const; // Returns a position that is greater than all valid positions in `items_`. syncer::StringOrdinal CreateChromePositionOnLast() const; const auto& items() const { return items_; } private: // A map from a ChromeAppListItem's id to its unique pointer. This item set // matches the one in AppListModel. std::map<std::string, std::unique_ptr<ChromeAppListItem>> items_; }; #endif // CHROME_BROWSER_UI_APP_LIST_CHROME_APP_LIST_ITEM_MANAGER_H_
blueboxd/chromium-legacy
ash/webui/projector_app/trusted_projector_ui.h
<gh_stars>10-100 // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_WEBUI_PROJECTOR_APP_TRUSTED_PROJECTOR_UI_H_ #define ASH_WEBUI_PROJECTOR_APP_TRUSTED_PROJECTOR_UI_H_ #include "content/public/browser/web_ui_controller.h" #include "ui/webui/mojo_bubble_web_ui_controller.h" class GURL; namespace chromeos { // The implementation for the Projector selfie cam and player app WebUI. // TODO(b/193670945): Migrate to ash/components and ash/webui. class TrustedProjectorUI : public ui::MojoBubbleWebUIController { public: TrustedProjectorUI(content::WebUI* web_ui, const GURL& url); ~TrustedProjectorUI() override; TrustedProjectorUI(const TrustedProjectorUI&) = delete; TrustedProjectorUI& operator=(const TrustedProjectorUI&) = delete; private: WEB_UI_CONTROLLER_TYPE_DECL(); }; } // namespace chromeos #endif // ASH_WEBUI_PROJECTOR_APP_TRUSTED_PROJECTOR_UI_H_
blueboxd/chromium-legacy
content/browser/accessibility/browser_accessibility_mac.h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_BROWSER_ACCESSIBILITY_BROWSER_ACCESSIBILITY_MAC_H_ #define CONTENT_BROWSER_ACCESSIBILITY_BROWSER_ACCESSIBILITY_MAC_H_ #include "base/macros.h" #include "content/browser/accessibility/browser_accessibility.h" #include "content/common/content_export.h" #include "ui/accessibility/ax_node.h" @class BrowserAccessibilityCocoa; namespace ui { class AXPlatformNodeMac; } // namespace ui namespace content { #if __OBJC__ CONTENT_EXPORT const BrowserAccessibilityCocoa* ToBrowserAccessibilityCocoa( const BrowserAccessibility* obj); CONTENT_EXPORT BrowserAccessibilityCocoa* ToBrowserAccessibilityCocoa( BrowserAccessibility* obj); #endif class BrowserAccessibilityMac : public BrowserAccessibility { public: ~BrowserAccessibilityMac() override; BrowserAccessibilityMac(const BrowserAccessibilityMac&) = delete; BrowserAccessibilityMac& operator=(const BrowserAccessibilityMac&) = delete; // BrowserAccessibility overrides. void OnDataChanged() override; uint32_t PlatformChildCount() const override; BrowserAccessibility* PlatformGetChild(uint32_t child_index) const override; BrowserAccessibility* PlatformGetFirstChild() const override; BrowserAccessibility* PlatformGetLastChild() const override; BrowserAccessibility* PlatformGetNextSibling() const override; BrowserAccessibility* PlatformGetPreviousSibling() const override; // The BrowserAccessibilityCocoa associated with us. BrowserAccessibilityCocoa* GetNativeWrapper() const; // Refresh the native object associated with this. // Useful for re-announcing the current focus when properties have changed. void ReplaceNativeObject(); protected: BrowserAccessibilityMac(BrowserAccessibilityManager* manager, ui::AXNode* node); friend class BrowserAccessibility; // Needs access to our constructor. private: // Creates platform and cocoa node if not yet created. void CreatePlatformNodes(); // Creates a new cocoa node. Returns an old node in the swap_node. BrowserAccessibilityCocoa* CreateNativeWrapper(); // Manager of the native cocoa node. We own this object. ui::AXPlatformNodeMac* platform_node_ = nullptr; }; } // namespace content #endif // CONTENT_BROWSER_ACCESSIBILITY_BROWSER_ACCESSIBILITY_MAC_H_
blueboxd/chromium-legacy
components/autofill/core/browser/payments/credit_card_otp_authenticator.h
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_AUTOFILL_CORE_BROWSER_PAYMENTS_CREDIT_CARD_OTP_AUTHENTICATOR_H_ #define COMPONENTS_AUTOFILL_CORE_BROWSER_PAYMENTS_CREDIT_CARD_OTP_AUTHENTICATOR_H_ #include <string> #include "base/strings/utf_string_conversions.h" #include "components/autofill/core/browser/autofill_client.h" #include "components/autofill/core/browser/data_model/credit_card.h" #include "components/autofill/core/browser/payments/otp_unmask_delegate.h" #include "components/autofill/core/browser/payments/payments_client.h" namespace autofill { // TODO(crbug.com/1220990): Extract common functions to a parent class after // full card request is removed from the flow. // Authenticates credit card unmasking through OTP (One-Time Password) // verification. class CreditCardOtpAuthenticator : public OtpUnmaskDelegate { public: struct OtpAuthenticationResponse { OtpAuthenticationResponse(); ~OtpAuthenticationResponse(); OtpAuthenticationResponse& with_did_succeed(bool b) { did_succeed = b; return *this; } // The credit card object must outlive |this|. OtpAuthenticationResponse& with_card(const CreditCard* c) { card = c; return *this; } OtpAuthenticationResponse& with_cvc(const std::u16string s) { cvc = std::u16string(s); return *this; } bool did_succeed = false; const CreditCard* card; std::u16string cvc; }; // The requester which delegates the authentication task to |this|. class Requester { public: virtual ~Requester() = default; // Invoked when OTP authentication is completed, regardless of whether it // succeeded. virtual void OnOtpAuthenticationComplete( const OtpAuthenticationResponse& response) = 0; }; explicit CreditCardOtpAuthenticator(AutofillClient* client); virtual ~CreditCardOtpAuthenticator(); CreditCardOtpAuthenticator(const CreditCardOtpAuthenticator&) = delete; CreditCardOtpAuthenticator& operator=(const CreditCardOtpAuthenticator&) = delete; // OtpUnmaskDelegate: void OnUnmaskPromptAccepted(const std::u16string& otp) override; void OnUnmaskPromptClosed(bool user_closed_dialog) override; void OnNewOtpRequested() override; // Start the OTP authentication for the |card| with // |selected_challenge_option|. Will invoke // |SendSelectChallengeOptionRequest()| to send the selected challenge option // to server. virtual void OnChallengeOptionSelected( const CreditCard* card, const CardUnmaskChallengeOption& selected_challenge_option, base::WeakPtr<Requester> requester, const std::string& context_token, int64_t billing_customer_number); // Have PaymentsClient send a SelectChallengeOptionRequest. This will also be // invoked when user requests to get a new OTP code. The response's callback // function is |OnDidSelectChallengeOption()| when server response returns. void SendSelectChallengeOptionRequest(); // Callback function invoked when the client receives the select challenge // option response from the server. Updates locally-cached |context_token_| to // the latest version. On a success, this will trigger the otp dialog by // calling |ShowOtpDialog()|. If server returns error, show the error dialog // and end session. void OnDidSelectChallengeOption(AutofillClient::PaymentsRpcResult result, const std::string& context_token); // Callback function invoked when the client receives a response from the // server. Updates locally-cached |context_token_| to the latest version. If // the request was successful, dismiss the UI and pass the full card // information to the CreditCardAccessManager, otherwise update the UI to show // the correct error message and end the session. void OnDidGetRealPan( AutofillClient::PaymentsRpcResult result, payments::PaymentsClient::UnmaskResponseDetails& response_details); private: friend class CreditCardOtpAuthenticatorTest; // Display the OTP dialog UI. // Once user confirms the OTP, we wil invoke |OnUnmaskPromptAccepted(otp)|. // If user asks for a new OTP code, we will invoke // |SendSelectChallengeOptionRequest()| again. void ShowOtpDialog(); // Invoked when risk data is fetched. void OnDidGetUnmaskRiskData(const std::string& risk_data); // Have PaymentsClient send a UnmaskCardRequest for this card. The response's // callback function is |OnDidGetRealPan()|. void SendUnmaskCardRequest(); // Reset the authenticator to initial states. void Reset(); // Card being unmasked. const CreditCard* card_; // User-entered OTP value. std::u16string otp_; // User-selected challenge option. CardUnmaskChallengeOption selected_challenge_option_; // Stores the latest version of the context token, passed between Payments // calls and unmodified by Chrome. std::string context_token_; std::string risk_data_; int64_t billing_customer_number_; // Whether there is a SelectChallengeOption request ongoing. bool selected_challenge_option_request_ongoing_ = false; // The associated autofill client. AutofillClient* autofill_client_; // The associated payments client. payments::PaymentsClient* payments_client_; // Weak pointer to object that is requesting authentication. base::WeakPtr<Requester> requester_; // This contains the details of the SelectChallengeOption request to be sent // to the server. std::unique_ptr<payments::PaymentsClient::SelectChallengeOptionRequestDetails> select_challenge_option_request_; // This contains the details of the Unmask request to be sent to the server. std::unique_ptr<payments::PaymentsClient::UnmaskRequestDetails> unmask_request_; // The timestamps when the requests are sent. Used for logging. absl::optional<base::TimeTicks> select_challenge_option_request_timestamp_; absl::optional<base::TimeTicks> unmask_card_request_timestamp_; base::WeakPtrFactory<CreditCardOtpAuthenticator> weak_ptr_factory_{this}; }; } // namespace autofill #endif // COMPONENTS_AUTOFILL_CORE_BROWSER_PAYMENTS_CREDIT_CARD_OTP_AUTHENTICATOR_H_
blueboxd/chromium-legacy
chrome/browser/ash/preferences.h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_ASH_PREFERENCES_H_ #define CHROME_BROWSER_ASH_PREFERENCES_H_ #include <string> #include "ash/public/mojom/cros_display_config.mojom.h" #include "base/macros.h" #include "chrome/browser/ash/language_preferences.h" #include "components/prefs/pref_change_registrar.h" #include "components/prefs/pref_member.h" #include "components/sync_preferences/pref_service_syncable_observer.h" #include "components/user_manager/user_manager.h" #include "mojo/public/cpp/bindings/remote.h" #include "ui/base/ime/ash/input_method_manager.h" class ContentTracingManager; class PrefRegistrySimple; namespace ash { namespace input_method { class InputMethodSyncer; } // namespace input_method } // namespace ash namespace sync_preferences { class PrefServiceSyncable; } // namespace sync_preferences namespace user_prefs { class PrefRegistrySyncable; } // namespace user_prefs namespace chromeos { class User; // The Preferences class handles Chrome OS preferences. When the class // is first initialized, it will initialize the OS settings to what's stored in // the preferences. These include touchpad settings, etc. // When the preferences change, we change the settings to reflect the new value. class Preferences : public sync_preferences::PrefServiceSyncableObserver, public user_manager::UserManager::UserSessionStateObserver { public: Preferences(); explicit Preferences( input_method::InputMethodManager* input_method_manager); // for testing Preferences(const Preferences&) = delete; Preferences& operator=(const Preferences&) = delete; ~Preferences() override; // These method will register the prefs associated with Chrome OS settings. static void RegisterPrefs(PrefRegistrySimple* registry); static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry); // This method will initialize Chrome OS settings to values in user prefs. // |user| is the user owning this preferences. void Init(Profile* profile, const user_manager::User* user); void InitUserPrefsForTesting( sync_preferences::PrefServiceSyncable* prefs, const user_manager::User* user, scoped_refptr<input_method::InputMethodManager::State> ime_state); void SetInputMethodListForTesting(); private: enum ApplyReason { REASON_INITIALIZATION, REASON_ACTIVE_USER_CHANGED, REASON_PREF_CHANGED }; // Initializes all member prefs. void InitUserPrefs(sync_preferences::PrefServiceSyncable* prefs); // Callback method for preference changes. void OnPreferenceChanged(const std::string& pref_name); // Add a sample to the appropriate UMA histogram for a boolean preference. void ReportBooleanPrefApplication(ApplyReason reason, const std::string& changed_histogram_name, const std::string& started_histogram_name, bool sample); // Add a sample to the appropriate UMA histogram for a sensitivity preference. void ReportSensitivityPrefApplication( ApplyReason reason, const std::string& changed_histogram_name, const std::string& started_histogram_name, int sensitivity_int); // This will set the OS settings when the preference changed or the user // owning these preferences became active. Also this method is called on // initialization. The reason of the call is stored as the |reason| parameter. // |pref_name| is the name of the changed preference if the |reason| is // |REASON_PREF_CHANGED|, otherwise it is empty. void ApplyPreferences(ApplyReason reason, const std::string& pref_name); // A variant of SetLanguageConfigStringList. You can pass comma-separated // values. Examples of |value|: "", "Control+space,Hiragana" void SetLanguageConfigStringListAsCSV(const char* section, const char* name, const std::string& value); // Restores the user's preferred input method / keyboard layout on signing in. void SetInputMethodList(); // Updates the initial key repeat delay and key repeat interval following // current prefs values. We set the delay and interval at once since an // underlying XKB API requires it. void UpdateAutoRepeatRate(); // Force natural scroll to on if --enable-natural-scroll-default is specified // on the cmd line. void ForceNaturalScrollDefault(); // sync_preferences::PrefServiceSyncableObserver implementation. void OnIsSyncingChanged() override; // Overriden form user_manager::UserManager::UserSessionStateObserver. void ActiveUserChanged(user_manager::User* active_user) override; sync_preferences::PrefServiceSyncable* prefs_; input_method::InputMethodManager* input_method_manager_; std::unique_ptr<ContentTracingManager> tracing_manager_; BooleanPrefMember performance_tracing_enabled_; BooleanPrefMember tap_to_click_enabled_; BooleanPrefMember three_finger_click_enabled_; BooleanPrefMember unified_desktop_enabled_by_default_; BooleanPrefMember natural_scroll_; BooleanPrefMember vert_edge_scroll_enabled_; IntegerPrefMember speed_factor_; IntegerPrefMember mouse_sensitivity_; IntegerPrefMember mouse_scroll_sensitivity_; IntegerPrefMember pointing_stick_sensitivity_; IntegerPrefMember touchpad_sensitivity_; IntegerPrefMember touchpad_scroll_sensitivity_; BooleanPrefMember primary_mouse_button_right_; BooleanPrefMember primary_pointing_stick_button_right_; BooleanPrefMember mouse_reverse_scroll_; BooleanPrefMember mouse_acceleration_; BooleanPrefMember mouse_scroll_acceleration_; BooleanPrefMember pointing_stick_acceleration_; BooleanPrefMember touchpad_acceleration_; BooleanPrefMember touchpad_scroll_acceleration_; BooleanPrefMember touchpad_haptic_feedback_; IntegerPrefMember touchpad_haptic_click_sensitivity_; FilePathPrefMember download_default_directory_; StringListPrefMember allowed_languages_; StringPrefMember preferred_languages_; // Input method preferences. StringPrefMember preload_engines_; StringPrefMember current_input_method_; StringPrefMember previous_input_method_; StringListPrefMember allowed_input_methods_; StringPrefMember enabled_imes_; BooleanPrefMember ime_menu_activated_; BooleanPrefMember xkb_auto_repeat_enabled_; IntegerPrefMember xkb_auto_repeat_delay_pref_; IntegerPrefMember xkb_auto_repeat_interval_pref_; BooleanPrefMember pci_data_access_enabled_pref_; PrefChangeRegistrar pref_change_registrar_; // User owning these preferences. const user_manager::User* user_; // Whether user is a primary user. bool user_is_primary_; // Input Methods state for this user. scoped_refptr<input_method::InputMethodManager::State> ime_state_; std::unique_ptr<ash::input_method::InputMethodSyncer> input_method_syncer_; mojo::Remote<ash::mojom::CrosDisplayConfigController> cros_display_config_; }; } // namespace chromeos #endif // CHROME_BROWSER_ASH_PREFERENCES_H_
blueboxd/chromium-legacy
components/feed/core/v2/config.h
<reponame>blueboxd/chromium-legacy // Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_FEED_CORE_V2_CONFIG_H_ #define COMPONENTS_FEED_CORE_V2_CONFIG_H_ #include "base/containers/flat_set.h" #include "base/time/time.h" #include "components/feed/core/proto/v2/wire/capability.pb.h" namespace feed { class StreamType; // The Feed configuration. Default values appear below. Always use // |GetFeedConfig()| to get the current configuration. struct Config { // Maximum number of requests per day for FeedQuery, NextPage, and // ActionUpload. int max_feed_query_requests_per_day = 20; int max_next_page_requests_per_day = 20; int max_action_upload_requests_per_day = 20; int max_list_recommended_web_feeds_requests_per_day = 20; int max_list_web_feeds_requests_per_day = 20; // We'll always attempt to refresh content older than this. base::TimeDelta stale_content_threshold = base::Hours(4); // Content older than this threshold will not be shown to the user. base::TimeDelta content_expiration_threshold = base::Hours(48); // How long the window is for background refresh tasks. If the task cannot be // scheduled in the window, the background refresh is aborted. base::TimeDelta background_refresh_window_length = base::Hours(24); // The time between background refresh attempts. Ignored if a server-defined // fetch schedule has been assigned. base::TimeDelta default_background_refresh_interval = base::Hours(24); // Maximum number of times to attempt to upload a pending action before // deleting it. int max_action_upload_attempts = 3; // Maximum age for a pending action. Actions older than this are deleted. base::TimeDelta max_action_age = base::Hours(24); // Maximum payload size for one action upload batch. size_t max_action_upload_bytes = 20000; // If no surfaces are attached, the stream model is unloaded after this // timeout. base::TimeDelta model_unload_timeout = base::Seconds(1); // How far ahead in number of items from last visible item to final item // before attempting to load more content. int load_more_trigger_lookahead = 5; // How far does the user have to scroll the feed before the feed begins // to consider loading more data. The scrolling threshold is a proxy // measure for deciding whether the user has engaged with the feed. int load_more_trigger_scroll_distance_dp = 100; // Whether to attempt uploading actions when Chrome is hidden. bool upload_actions_on_enter_background = true; // Whether to send (pseudonymous) logs for signed-out sessions. bool send_signed_out_session_logs = false; // The max age of a signed-out session token. base::TimeDelta session_id_max_age = base::Days(30); // Maximum number of images prefetched per refresh. int max_prefetch_image_requests_per_refresh = 50; // Configuration for Web Feeds. // How long before Web Feed content is considered stale. base::TimeDelta web_feed_stale_content_threshold = base::Hours(1); // TimeDelta after startup to fetch recommended and subscribed Web Feeds if // they are stale. If zero, no fetching is done. base::TimeDelta fetch_web_feed_info_delay = base::Seconds(40); // How long before cached recommended feed data on the device is considered // stale and refetched. base::TimeDelta recommended_feeds_staleness_threshold = base::Days(28); // How long before cached subscribed feed data on the device is considered // stale and refetched. base::TimeDelta subscribed_feeds_staleness_threshold = base::Days(7); // Number of days of history to query when determining whether to show the // follow accelerator. int webfeed_accelerator_recent_visit_history_days = 14; // Configuration for `PersistentKeyValueStore`. // Maximum total database size before items are evicted. int64_t persistent_kv_store_maximum_size_before_eviction = 1000000; // Eviction task is performed after this many bytes are written. int persistent_kv_store_cleanup_interval_in_written_bytes = 1000000; // Until we get the new list contents API working, keep using FeedQuery. // TODO(crbug/1152592): remove this when new endpoint is tested enough. bool use_feed_query_requests_for_web_feeds = false; // Set of optional capabilities included in requests. See // CreateFeedQueryRequest() for required capabilities. base::flat_set<feedwire::Capability> experimental_capabilities = { feedwire::Capability::DISMISS_COMMAND, feedwire::Capability::DOWNLOAD_LINK, feedwire::Capability::INFINITE_FEED, feedwire::Capability::MATERIAL_NEXT_BASELINE, feedwire::Capability::PREFETCH_METADATA, feedwire::Capability::REQUEST_SCHEDULE, feedwire::Capability::UI_THEME_V2, feedwire::Capability::UNDO_FOR_DISMISS_COMMAND, feedwire::Capability::CONTENT_LIFETIME, }; Config(); Config(const Config& other); ~Config(); base::TimeDelta GetStalenessThreshold(const StreamType& stream_type) const; }; // Gets the current configuration. const Config& GetFeedConfig(); // Sets whether the legacy feed endpoint should be used for Web Feed content // fetches. void SetUseFeedQueryRequestsForWebFeeds(const bool use_legacy); void SetFeedConfigForTesting(const Config& config); void OverrideConfigWithFinchForTesting(); } // namespace feed #endif // COMPONENTS_FEED_CORE_V2_CONFIG_H_
blueboxd/chromium-legacy
chrome/browser/media/router/media_router_feature.h
<gh_stars>10-100 // 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_MEDIA_ROUTER_MEDIA_ROUTER_FEATURE_H_ #define CHROME_BROWSER_MEDIA_ROUTER_MEDIA_ROUTER_FEATURE_H_ #include "base/feature_list.h" #include "base/time/time.h" #include "build/build_config.h" #include "third_party/abseil-cpp/absl/types/optional.h" class PrefRegistrySimple; class PrefService; namespace content { class BrowserContext; } namespace media_router { // Returns true if Media Router is enabled for |context|. bool MediaRouterEnabled(content::BrowserContext* context); // Clears stored prefs so they don't leak between tests running in the same // process. void ClearMediaRouterStoredPrefsForTesting(); #if !defined(OS_ANDROID) // Enables the media router. Can be disabled in tests unrelated to // Media Router where it interferes. Can also be useful to disable for local // development on Mac because DIAL local discovery opens a local port // and triggers a permission prompt. extern const base::Feature kMediaRouter; // If enabled, allows Media Router to connect to Cast devices on all IP // addresses, not just RFC1918/RFC4193 private addresses. Workaround for // https://crbug.com/813974. extern const base::Feature kCastAllowAllIPsFeature; // Determine whether global media controls are used to start and stop casting. extern const base::Feature kGlobalMediaControlsCastStartStop; // If enabled, allows all websites to request to start mirroring via // Presentation API. If disabled, only the allowlisted sites can do so. extern const base::Feature kAllowAllSitesToInitiateMirroring; namespace prefs { // Pref name for the enterprise policy for allowing Cast devices on all IPs. constexpr char kMediaRouterCastAllowAllIPs[] = "media_router.cast_allow_all_ips"; // Pref name for the per-profile randomly generated token to include with the // hash when externalizing MediaSink IDs. constexpr char kMediaRouterReceiverIdHashToken[] = "media_router.receiver_id_hash_token"; // Pref name that allows the AccessCode/QR code scanning dialog button to be // shown. constexpr char kAccessCodeCastEnabled[] = "media_router.access_code_cast_enabled"; // Pref name for the pref that determines how long a scanned receiver remains in // the receiver list. constexpr char kAccessCodeCastDeviceDuration[] = "media_router.access_code_cast_device_duration"; } // namespace prefs // Registers |kMediaRouterCastAllowAllIPs| with local state pref |registry|. void RegisterLocalStatePrefs(PrefRegistrySimple* registry); // Registers Media Router related preferences with per-profile pref |registry|. void RegisterProfilePrefs(PrefRegistrySimple* registry); // Returns true if CastMediaSinkService can connect to Cast devices on // all IPs, as determined by local state |pref_service| / feature flag. bool GetCastAllowAllIPsPref(PrefService* pref_service); // Returns the hash token to use for externalizing MediaSink IDs from // |pref_service|. If the token does not exist, the token will be created from a // randomly generated string and stored in |pref_service|. std::string GetReceiverIdHashToken(PrefService* pref_service); // Returns true if browser side DIAL Media Route Provider is enabled. bool DialMediaRouteProviderEnabled(); // Returns true if global media controls are used to start and stop casting. bool GlobalMediaControlsCastStartStopEnabled(); // Returns true if this user is allowed to use Access Codes & QR codes to // discover cast devices. bool GetAccessCodeCastEnabledPref(PrefService* pref_service); // Returns the duration that a scanned cast device is allowed to remain // in the cast list. base::TimeDelta GetAccessCodeDeviceDurationPref(PrefService* pref_service); #endif // !defined(OS_ANDROID) } // namespace media_router #endif // CHROME_BROWSER_MEDIA_ROUTER_MEDIA_ROUTER_FEATURE_H_
blueboxd/chromium-legacy
chrome/browser/ui/views/autofill/payments/card_unmask_otp_input_dialog_views.h
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_VIEWS_AUTOFILL_PAYMENTS_CARD_UNMASK_OTP_INPUT_DIALOG_VIEWS_H_ #define CHROME_BROWSER_UI_VIEWS_AUTOFILL_PAYMENTS_CARD_UNMASK_OTP_INPUT_DIALOG_VIEWS_H_ #include <string> #include "chrome/browser/ui/autofill/payments/card_unmask_otp_input_dialog_view.h" #include "ui/views/controls/textfield/textfield_controller.h" #include "ui/views/window/dialog_delegate.h" namespace views { class BoxLayoutView; class Label; class Throbber; } // namespace views namespace autofill { class CardUnmaskOtpInputDialogController; class CardUnmaskOtpInputDialogViews : public CardUnmaskOtpInputDialogView, public views::DialogDelegateView, public views::TextfieldController { public: explicit CardUnmaskOtpInputDialogViews( CardUnmaskOtpInputDialogController* controller); CardUnmaskOtpInputDialogViews(const CardUnmaskOtpInputDialogViews&) = delete; CardUnmaskOtpInputDialogViews& operator=( const CardUnmaskOtpInputDialogViews&) = delete; ~CardUnmaskOtpInputDialogViews() override; // CardUnmaskOtpInputDialogView: void ShowPendingState() override; void ShowInvalidState(const std::u16string& invalid_label_text) override; void Dismiss(bool show_confirmation_before_closing, bool user_closed_dialog) override; // views::DialogDelegateView: std::u16string GetWindowTitle() const override; void AddedToWidget() override; bool Accept() override; void OnThemeChanged() override; // views::TextfieldController: void ContentsChanged(views::Textfield* sender, const std::u16string& new_contents) override; private: // Initializes the contents of the view and all of its child views. void InitViews(); // Creates |otp_input_view_|, which is a child of the main view. Originally // set to visible as it is the first view of the dialog. void CreateOtpInputView(); // Creates |progress_view_|, which is a child of the main view. Originally set // to not visible as it should only be visible once the user has submitted an // otp. void CreateHiddenProgressView(); void HideInvalidState(); void CloseWidget(bool user_closed_dialog); CardUnmaskOtpInputDialogController* controller_ = nullptr; // Elements related to the otp part of the view. views::BoxLayoutView* otp_input_view_ = nullptr; views::Textfield* otp_input_textfield_ = nullptr; views::Label* otp_input_textfield_invalid_label_ = nullptr; // Adds padding to the view's layout so that the layout allows room for // |otp_input_textfield_invalid_label_| to appear if necessary. This padding's // visibility will always be the opposite of // |otp_input_textfield_invalid_label_|'s visibility. views::View* otp_input_textfield_invalid_label_padding_ = nullptr; // Elements related to progress or error when the request is being made. views::BoxLayoutView* progress_view_ = nullptr; views::Label* progress_label_ = nullptr; views::Throbber* progress_throbber_ = nullptr; base::WeakPtrFactory<CardUnmaskOtpInputDialogViews> weak_ptr_factory_{this}; }; } // namespace autofill #endif // CHROME_BROWSER_UI_VIEWS_AUTOFILL_PAYMENTS_CARD_UNMASK_OTP_INPUT_DIALOG_VIEWS_H_
blueboxd/chromium-legacy
chromeos/components/eche_app_ui/pref_names.h
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROMEOS_COMPONENTS_ECHE_APP_UI_PREF_NAMES_H_ #define CHROMEOS_COMPONENTS_ECHE_APP_UI_PREF_NAMES_H_ namespace chromeos { namespace eche_app { namespace prefs { extern const char kAppsAccessStatus[]; } // namespace prefs } // namespace eche_app } // namespace chromeos #endif // CHROMEOS_COMPONENTS_ECHE_APP_UI_PREF_NAMES_H_
blueboxd/chromium-legacy
content/browser/webui/web_ui_impl.h
<reponame>blueboxd/chromium-legacy // Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_BROWSER_WEBUI_WEB_UI_IMPL_H_ #define CONTENT_BROWSER_WEBUI_WEB_UI_IMPL_H_ #include <map> #include <memory> #include <set> #include <string> #include <vector> #include "base/compiler_specific.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "content/common/web_ui.mojom.h" #include "content/public/browser/web_ui.h" #include "mojo/public/cpp/bindings/associated_receiver.h" #include "mojo/public/cpp/bindings/associated_remote.h" namespace content { class RenderFrameHost; class RenderFrameHostImpl; class WebContentsImpl; class WebUIMainFrameObserver; class CONTENT_EXPORT WebUIImpl : public WebUI, public mojom::WebUIHost, public base::SupportsWeakPtr<WebUIImpl> { public: explicit WebUIImpl(WebContentsImpl* contents, RenderFrameHostImpl* frame_host); ~WebUIImpl() override; WebUIImpl(const WebUIImpl&) = delete; WebUIImpl& operator=(const WebUIImpl&) = delete; // Called when a RenderFrame is created for a WebUI (reload after a renderer // crash) or when a WebUI is created for a RenderFrame (i.e. navigating from // chrome://downloads to chrome://bookmarks) or when both are new (i.e. // opening a new tab). void WebUIRenderFrameCreated(RenderFrameHost* render_frame_host); // Called when a RenderFrame is reused for the same WebUI type (i.e. reload). void RenderFrameReused(RenderFrameHost* render_frame_host); // Called when the owning RenderFrameHost has started unloading. void RenderFrameHostUnloading(); // Called when the renderer-side frame is destroyed, along with any mojo // connections to it. The browser can not attempt to communicate with the // renderer afterward. void RenderFrameDeleted(); // Called right after AllowBindings is notified to a RenderFrame. void SetUpMojoConnection(); // Called when a RenderFrame is deleted for a WebUI (i.e. a renderer crash). void TearDownMojoConnection(); // Add a property to the WebUI binding object. void SetProperty(const std::string& name, const std::string& value); // WebUI implementation: WebContents* GetWebContents() override; WebUIController* GetController() override; void SetController(std::unique_ptr<WebUIController> controller) override; float GetDeviceScaleFactor() override; const std::u16string& GetOverriddenTitle() override; void OverrideTitle(const std::u16string& title) override; int GetBindings() override; void SetBindings(int bindings) override; const std::vector<std::string>& GetRequestableSchemes() override; void AddRequestableScheme(const char* scheme) override; void AddMessageHandler(std::unique_ptr<WebUIMessageHandler> handler) override; void RegisterMessageCallback(base::StringPiece message, MessageCallback callback) override; void RegisterDeprecatedMessageCallback( base::StringPiece message, const DeprecatedMessageCallback& callback) override; void ProcessWebUIMessage(const GURL& source_url, const std::string& message, const base::ListValue& args) override; bool CanCallJavascript() override; void CallJavascriptFunctionUnsafe(const std::string& function_name) override; void CallJavascriptFunctionUnsafe(const std::string& function_name, const base::Value& arg) override; void CallJavascriptFunctionUnsafe(const std::string& function_name, const base::Value& arg1, const base::Value& arg2) override; void CallJavascriptFunctionUnsafe(const std::string& function_name, const base::Value& arg1, const base::Value& arg2, const base::Value& arg3) override; void CallJavascriptFunctionUnsafe(const std::string& function_name, const base::Value& arg1, const base::Value& arg2, const base::Value& arg3, const base::Value& arg4) override; void CallJavascriptFunctionUnsafe( const std::string& function_name, const std::vector<const base::Value*>& args) override; std::vector<std::unique_ptr<WebUIMessageHandler>>* GetHandlersForTesting() override; const mojo::AssociatedRemote<mojom::WebUI>& GetRemoteForTest() const { return remote_; } WebUIMainFrameObserver* GetWebUIMainFrameObserverForTest() const { return web_contents_observer_.get(); } RenderFrameHostImpl* frame_host() const { return frame_host_; } private: friend class WebUIMainFrameObserver; // mojom::WebUIHost void Send(const std::string& message, base::Value args) override; // Execute a string of raw JavaScript on the page. void ExecuteJavascript(const std::u16string& javascript); // Called internally and by the owned WebUIMainFrameObserver. void DisallowJavascriptOnAllHandlers(); // A map of message name -> message handling callback. std::map<std::string, MessageCallback> message_callbacks_; // A map of message name -> message handling callback. std::map<std::string, DeprecatedMessageCallback> deprecated_message_callbacks_; // Options that may be overridden by individual Web UI implementations. The // bool options default to false. See the public getters for more information. std::u16string overridden_title_; // Defaults to empty string. int bindings_; // The bindings from BindingsPolicy that should be enabled for // this page. // The URL schemes that can be requested by this document. std::vector<std::string> requestable_schemes_; // RenderFrameHost associated with |this|. RenderFrameHostImpl* frame_host_; // Non-owning pointer to the WebContentsImpl this WebUI is associated with. WebContentsImpl* web_contents_; // The WebUIMessageHandlers we own. std::vector<std::unique_ptr<WebUIMessageHandler>> handlers_; // Notifies this WebUI about notifications in the main frame. std::unique_ptr<WebUIMainFrameObserver> web_contents_observer_; std::unique_ptr<WebUIController> controller_; mojo::AssociatedRemote<mojom::WebUI> remote_; mojo::AssociatedReceiver<mojom::WebUIHost> receiver_{this}; }; } // namespace content #endif // CONTENT_BROWSER_WEBUI_WEB_UI_IMPL_H_
blueboxd/chromium-legacy
chrome/browser/ui/views/web_apps/web_app_protocol_handler_intent_picker_dialog_view.h
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_VIEWS_WEB_APPS_WEB_APP_PROTOCOL_HANDLER_INTENT_PICKER_DIALOG_VIEW_H_ #define CHROME_BROWSER_UI_VIEWS_WEB_APPS_WEB_APP_PROTOCOL_HANDLER_INTENT_PICKER_DIALOG_VIEW_H_ #include <memory> #include <vector> #include "base/callback_forward.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/ui/browser_dialogs.h" #include "chrome/browser/web_applications/web_app_id.h" #include "chrome/browser/web_applications/web_application_info.h" #include "ui/views/window/dialog_delegate.h" #include "url/gurl.h" class Profile; namespace views { class Checkbox; class ImageView; } // namespace views // This class extends DialogDelegateView and needs to be owned // by the views framework. class WebAppProtocolHandlerIntentPickerView : public views::DialogDelegateView { public: METADATA_HEADER(WebAppProtocolHandlerIntentPickerView); WebAppProtocolHandlerIntentPickerView( const GURL& url, Profile* profile, const web_app::AppId& app_id, chrome::WebAppProtocolHandlerAcceptanceCallback close_callback); WebAppProtocolHandlerIntentPickerView( const WebAppProtocolHandlerIntentPickerView&) = delete; WebAppProtocolHandlerIntentPickerView& operator=( const WebAppProtocolHandlerIntentPickerView&) = delete; ~WebAppProtocolHandlerIntentPickerView() override; static void Show( const GURL& url, Profile* profile, const web_app::AppId& app_id, chrome::WebAppProtocolHandlerAcceptanceCallback close_callback); static void SetDefaultRememberSelectionForTesting(bool remember_state); private: // views::DialogDelegateView: gfx::Size CalculatePreferredSize() const override; const web_app::AppId& GetSelectedAppId() const; void OnAccepted(); void OnCanceled(); void OnClosed(); void InitChildViews(); void OnIconsRead(std::map<SquareSizePx, SkBitmap> icon_bitmaps); // Runs the close_callback_ provided during Show() if it exists. void RunCloseCallback(bool allowed, bool remember_user_choice); const GURL url_; Profile* const profile_; const web_app::AppId app_id_; views::Checkbox* remember_selection_checkbox_; views::ImageView* icon_image_view_; chrome::WebAppProtocolHandlerAcceptanceCallback close_callback_; base::WeakPtrFactory<WebAppProtocolHandlerIntentPickerView> weak_ptr_factory_{ this}; }; #endif // CHROME_BROWSER_UI_VIEWS_WEB_APPS_WEB_APP_PROTOCOL_HANDLER_INTENT_PICKER_DIALOG_VIEW_H_
blueboxd/chromium-legacy
components/global_media_controls/public/media_session_item_producer.h
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_GLOBAL_MEDIA_CONTROLS_PUBLIC_MEDIA_SESSION_ITEM_PRODUCER_H_ #define COMPONENTS_GLOBAL_MEDIA_CONTROLS_PUBLIC_MEDIA_SESSION_ITEM_PRODUCER_H_ #include "base/component_export.h" #include "base/observer_list.h" #include "components/global_media_controls/public/media_item_manager_observer.h" #include "components/global_media_controls/public/media_item_producer.h" #include "components/global_media_controls/public/media_item_ui_observer.h" #include "components/global_media_controls/public/media_item_ui_observer_set.h" #include "components/global_media_controls/public/media_session_notification_item.h" #include "mojo/public/cpp/bindings/remote.h" #include "services/media_session/public/mojom/audio_focus.mojom.h" #include "services/media_session/public/mojom/media_controller.mojom.h" namespace global_media_controls { class MediaItemManager; class MediaItemUI; class MediaSessionItemProducerObserver; // These values are persisted to logs. Entries should not be renumbered and // numeric values should never be reused. enum class GlobalMediaControlsDismissReason { kUserDismissedNotification = 0, kInactiveTimeout = 1, kTabClosed = 2, kMediaSessionStopped = 3, kMaxValue = kMediaSessionStopped, }; class COMPONENT_EXPORT(GLOBAL_MEDIA_CONTROLS) MediaSessionItemProducer : public MediaItemProducer, public MediaSessionNotificationItem::Delegate, public media_session::mojom::AudioFocusObserver, public MediaItemUIObserver { public: // When given a |source_id|, the MediaSessionItemProducer will only // produce MediaItems for the given source (i.e. profile). When empty, it will // produce MediaItems for the Media Sessions on all sources (profiles). MediaSessionItemProducer( mojo::Remote<media_session::mojom::AudioFocusManager> audio_focus_remote, mojo::Remote<media_session::mojom::MediaControllerManager> controller_manager_remote, MediaItemManager* item_manager, absl::optional<base::UnguessableToken> source_id); MediaSessionItemProducer(const MediaSessionItemProducer&) = delete; MediaSessionItemProducer& operator=(const MediaSessionItemProducer&) = delete; ~MediaSessionItemProducer() override; // MediaItemProducer: base::WeakPtr<media_message_center::MediaNotificationItem> GetMediaItem( const std::string& id) override; std::set<std::string> GetActiveControllableItemIds() override; bool HasFrozenItems() override; void OnItemShown(const std::string& id, MediaItemUI* item_ui) override; bool IsItemActivelyPlaying(const std::string& id) override; // MediaSessionNotificationItem::Delegate: void ActivateItem(const std::string& id) override; void HideItem(const std::string& id) override; void RemoveItem(const std::string& id) override; void LogMediaSessionActionButtonPressed( const std::string& id, media_session::mojom::MediaSessionAction action) override; // media_session::mojom::AudioFocusObserver: void OnFocusGained( media_session::mojom::AudioFocusRequestStatePtr session) override; void OnFocusLost( media_session::mojom::AudioFocusRequestStatePtr session) override; void OnRequestIdReleased(const base::UnguessableToken& request_id) override; // MediaItemUIObserver implementation. void OnMediaItemUIClicked(const std::string& id) override; void OnMediaItemUIDismissed(const std::string& id) override; void AddObserver(MediaSessionItemProducerObserver* observer); void RemoveObserver(MediaSessionItemProducerObserver* observer); bool HasSession(const std::string& id) const; void SetAudioSinkId(const std::string& id, const std::string& sink_id); base::CallbackListSubscription RegisterIsAudioOutputDeviceSwitchingSupportedCallback( const std::string& id, base::RepeatingCallback<void(bool)> callback); private: friend class MediaSessionItemProducerTest; class COMPONENT_EXPORT(GLOBAL_MEDIA_CONTROLS) Session : public media_session::mojom::MediaControllerObserver { public: Session(MediaSessionItemProducer* owner, const std::string& id, std::unique_ptr<MediaSessionNotificationItem> item, mojo::Remote<media_session::mojom::MediaController> controller); Session(const Session&) = delete; Session& operator=(const Session&) = delete; ~Session() override; // media_session::mojom::MediaControllerObserver: void MediaSessionInfoChanged( media_session::mojom::MediaSessionInfoPtr session_info) override; void MediaSessionMetadataChanged( const absl::optional<media_session::MediaMetadata>& metadata) override { } void MediaSessionActionsChanged( const std::vector<media_session::mojom::MediaSessionAction>& actions) override; void MediaSessionChanged( const absl::optional<base::UnguessableToken>& request_id) override {} void MediaSessionPositionChanged( const absl::optional<media_session::MediaPosition>& position) override; // Called when the request ID associated with this session is released (i.e. // when the tab is closed). void OnRequestIdReleased(); MediaSessionNotificationItem* item() { return item_.get(); } // Called when a new MediaController is given to the item. We need to // observe the same session as our underlying item. void SetController( mojo::Remote<media_session::mojom::MediaController> controller); // Sets the reason why this session was dismissed/removed. Can only be // called if the value has not already been set. void set_dismiss_reason(GlobalMediaControlsDismissReason reason); // Called when a session is interacted with (to reset |inactive_timer_|). void OnSessionInteractedWith(); bool IsPlaying() const; void SetAudioSinkId(const std::string& id); base::CallbackListSubscription RegisterIsAudioDeviceSwitchingSupportedCallback( base::RepeatingCallback<void(bool)> callback); private: static void RecordDismissReason(GlobalMediaControlsDismissReason reason); void StartInactiveTimer(); void OnInactiveTimerFired(); void RecordInteractionDelayAfterPause(); void MarkActiveIfNecessary(); MediaSessionItemProducer* const owner_; const std::string id_; std::unique_ptr<MediaSessionNotificationItem> item_; // Used to stop/hide a paused session after a period of inactivity. base::OneShotTimer inactive_timer_; base::TimeTicks last_interaction_time_ = base::TimeTicks::Now(); // The reason why this session was dismissed/removed. absl::optional<GlobalMediaControlsDismissReason> dismiss_reason_; // True if the session's playback state is "playing". bool is_playing_ = false; // True if we're currently marked inactive. bool is_marked_inactive_ = false; // True if the audio output device can be switched. bool is_audio_device_switching_supported_ = true; // Used to notify changes in audio output device switching capabilities. base::RepeatingCallbackList<void(bool)> is_audio_device_switching_supported_callback_list_; // Used to receive updates to the Media Session playback state. mojo::Receiver<media_session::mojom::MediaControllerObserver> observer_receiver_{this}; // Used to request audio output be routed to a different device. mojo::Remote<media_session::mojom::MediaController> controller_; }; // Looks up a Session object by its ID. Returns null if not found. Session* GetSession(const std::string& id); // Called by a Session when it becomes active. void OnSessionBecameActive(const std::string& id); // Called by a Session when it becomes inactive. void OnSessionBecameInactive(const std::string& id); void HideMediaDialog(); void OnReceivedAudioFocusRequests( std::vector<media_session::mojom::AudioFocusRequestStatePtr> sessions); void OnItemUnfrozen(const std::string& id); // Used to track whether there are any active controllable sessions. std::set<std::string> active_controllable_session_ids_; // Tracks the sessions that are currently frozen. If there are only frozen // sessions, we will disable the toolbar icon and wait to hide it. std::set<std::string> frozen_session_ids_; // Tracks the sessions that are currently inactive. Sessions become inactive // after a period of time of being paused with no user interaction. Inactive // sessions are hidden from the dialog until the user interacts with them // again (e.g. by playing the session). std::set<std::string> inactive_session_ids_; // Connections with the media session service to listen for audio focus // updates and control media sessions. mojo::Remote<media_session::mojom::AudioFocusManager> audio_focus_remote_; mojo::Remote<media_session::mojom::MediaControllerManager> controller_manager_remote_; mojo::Receiver<media_session::mojom::AudioFocusObserver> audio_focus_observer_receiver_{this}; MediaItemManager* const item_manager_; // Keeps track of all the items we're currently observing. MediaItemUIObserverSet item_ui_observer_set_; // Stores a Session for each media session keyed by its |request_id| in string // format. std::map<std::string, Session> sessions_; base::ObserverList<MediaSessionItemProducerObserver> observers_; base::WeakPtrFactory<MediaSessionItemProducer> weak_ptr_factory_{this}; }; } // namespace global_media_controls #endif // COMPONENTS_GLOBAL_MEDIA_CONTROLS_PUBLIC_MEDIA_SESSION_ITEM_PRODUCER_H_
blueboxd/chromium-legacy
ash/wm/desks/templates/desks_templates_presenter.h
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_WM_DESKS_TEMPLATES_DESKS_TEMPLATES_PRESENTER_H_ #define ASH_WM_DESKS_TEMPLATES_DESKS_TEMPLATES_PRESENTER_H_ #include <vector> #include "ash/ash_export.h" #include "base/memory/weak_ptr.h" #include "base/scoped_observation.h" #include "components/desks_storage/core/desk_model.h" #include "components/desks_storage/core/desk_model_observer.h" namespace ash { class DeskTemplate; class OverviewSession; // DesksTemplatesPresenter is the presenter for the desks templates UI. It // handles all calls to the model, and lets the UI know what to show or update. // OverviewSession will create and own an instance of this object. It will be // created after the desks bar is visible and destroyed once we receive an // overview shutdown signal, to prevent calls to the model during shutdown. class ASH_EXPORT DesksTemplatesPresenter : desks_storage::DeskModelObserver { public: explicit DesksTemplatesPresenter(OverviewSession* overview_session); DesksTemplatesPresenter(const DesksTemplatesPresenter&) = delete; DesksTemplatesPresenter& operator=(const DesksTemplatesPresenter&) = delete; ~DesksTemplatesPresenter() override; // Convenience function to get the presenter instance, which is created and // owned by `OverviewSession`. static DesksTemplatesPresenter* Get(); // Calls the DeskModel to get all the template entries, with a callback to // `OnGetAllEntries`. void GetAllEntries(); // Calls the DeskModel to delete the template with the provided uuid. void DeleteEntry(const std::string& template_uuid); // Launches the desk template with 'template_uuid' as a new desk. void LaunchDeskTemplate(const std::string& template_uuid); // desks_storage::DeskModelObserver: // TODO(sammiequon): Implement these once the model starts sending these // messages. void DeskModelLoaded() override; void OnDeskModelDestroying() override; void EntriesAddedOrUpdatedRemotely( const std::vector<const DeskTemplate*>& new_entries) override {} void EntriesRemovedRemotely(const std::vector<std::string>& uuids) override {} void EntriesAddedOrUpdatedLocally( const std::vector<const DeskTemplate*>& new_entries) override {} void EntriesRemovedLocally(const std::vector<std::string>& uuids) override {} private: friend class DesksTemplatesPresenterTestApi; // Callback ran after querying the model for a list of entries. This function // also contains logic for updating the UI. void OnGetAllEntries(desks_storage::DeskModel::GetAllEntriesStatus status, std::vector<DeskTemplate*> entries); // Callback after deleting an entry. Will then call `GetAllEntries` to update // the UI with the most up to date list of templates. void OnDeleteEntry(desks_storage::DeskModel::DeleteEntryStatus status); // Launches DeskTemplate after retrieval from storage. void OnGetTemplateForDeskLaunch( desks_storage::DeskModel::GetEntryByUuidStatus status, std::unique_ptr<DeskTemplate> entry); // Pointer to the session which owns `this`. OverviewSession* const overview_session_; base::ScopedObservation<desks_storage::DeskModel, desks_storage::DeskModelObserver> desk_model_observation_{this}; // Test closure that runs after the UI has been updated async after a call to // the model. base::OnceClosure on_update_ui_closure_for_testing_; base::WeakPtrFactory<DesksTemplatesPresenter> weak_ptr_factory_{this}; }; } // namespace ash #endif // ASH_WM_DESKS_TEMPLATES_DESKS_TEMPLATES_PRESENTER_H_
blueboxd/chromium-legacy
components/page_load_metrics/browser/observers/core/uma_page_load_metrics_observer.h
<gh_stars>10-100 // 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 COMPONENTS_PAGE_LOAD_METRICS_BROWSER_OBSERVERS_CORE_UMA_PAGE_LOAD_METRICS_OBSERVER_H_ #define COMPONENTS_PAGE_LOAD_METRICS_BROWSER_OBSERVERS_CORE_UMA_PAGE_LOAD_METRICS_OBSERVER_H_ #include "components/page_load_metrics/browser/observers/click_input_tracker.h" #include "components/page_load_metrics/browser/page_load_metrics_observer.h" #include "services/metrics/public/cpp/ukm_source.h" namespace internal { // NOTE: Some of these histograms are separated into a separate histogram // specified by the ".Background" suffix. For these events, we put them into the // background histogram if the web contents was ever in the background from // navigation start to the event in question. extern const char kHistogramAverageUserInteractionLatencyOverBudgetMaxEventDuration[]; extern const char kHistogramSlowUserInteractionLatencyOverBudgetHighPercentileMaxEventDuration []; extern const char kHistogramSlowUserInteractionLatencyOverBudgetHighPercentile2MaxEventDuration []; extern const char kHistogramSumOfUserInteractionLatencyOverBudgetMaxEventDuration[]; extern const char kHistogramWorstUserInteractionLatencyMaxEventDuration[]; extern const char kHistogramWorstUserInteractionLatencyOverBudgetMaxEventDuration[]; extern const char kHistogramAverageUserInteractionLatencyOverBudgetTotalEventDuration[]; extern const char kHistogramSlowUserInteractionLatencyOverBudgetHighPercentileTotalEventDuration []; extern const char kHistogramSlowUserInteractionLatencyOverBudgetHighPercentile2TotalEventDuration []; extern const char kHistogramSumOfUserInteractionLatencyOverBudgetTotalEventDuration[]; extern const char kHistogramWorstUserInteractionLatencyTotalEventDuration[]; extern const char kHistogramWorstUserInteractionLatencyOverBudgetTotalEventDuration[]; extern const char kHistogramFirstInputDelay[]; extern const char kHistogramFirstInputTimestamp[]; extern const char kHistogramFirstInputDelay4[]; extern const char kHistogramFirstInputTimestamp4[]; extern const char kHistogramLongestInputDelay[]; extern const char kHistogramLongestInputTimestamp[]; extern const char kHistogramFirstPaint[]; extern const char kHistogramFirstImagePaint[]; extern const char kHistogramDomContentLoaded[]; extern const char kHistogramLoad[]; extern const char kHistogramFirstContentfulPaint[]; extern const char kHistogramFirstMeaningfulPaint[]; extern const char kHistogramLargestContentfulPaint[]; extern const char kHistogramLargestContentfulPaintContentType[]; extern const char kHistogramLargestContentfulPaintMainFrame[]; extern const char kHistogramLargestContentfulPaintMainFrameContentType[]; extern const char kHistogramLargestContentfulPaintCrossSiteSubFrame[]; extern const char kDeprecatedHistogramLargestContentfulPaint[]; extern const char kHistogramExperimentalLargestContentfulPaintContentType[]; extern const char kDeprecatedHistogramLargestContentfulPaintMainFrame[]; extern const char kHistogramExperimentalLargestContentfulPaintMainFrameContentType[]; extern const char kHistogramParseDuration[]; extern const char kHistogramParseBlockedOnScriptLoad[]; extern const char kHistogramParseBlockedOnScriptExecution[]; extern const char kHistogramParseStartToFirstMeaningfulPaint[]; extern const char kBackgroundHistogramFirstImagePaint[]; extern const char kBackgroundHistogramDomContentLoaded[]; extern const char kBackgroundHistogramLoad[]; extern const char kBackgroundHistogramFirstPaint[]; extern const char kHistogramLoadTypeFirstContentfulPaintReload[]; extern const char kHistogramLoadTypeFirstContentfulPaintForwardBack[]; extern const char kHistogramLoadTypeFirstContentfulPaintNewNavigation[]; extern const char kHistogramLoadTypeParseStartReload[]; extern const char kHistogramLoadTypeParseStartForwardBack[]; extern const char kHistogramLoadTypeParseStartNewNavigation[]; extern const char kHistogramFailedProvisionalLoad[]; extern const char kHistogramUserGestureNavigationToForwardBack[]; extern const char kHistogramPageTimingForegroundDuration[]; extern const char kHistogramPageTimingForegroundDurationNoCommit[]; extern const char kHistogramFirstMeaningfulPaintStatus[]; extern const char kHistogramCachedResourceLoadTimePrefix[]; extern const char kHistogramCommitSentToFirstSubresourceLoadStart[]; extern const char kHistogramNavigationToFirstSubresourceLoadStart[]; extern const char kHistogramResourceLoadTimePrefix[]; extern const char kHistogramTotalSubresourceLoadTimeAtFirstContentfulPaint[]; extern const char kHistogramFirstEligibleToPaint[]; extern const char kHistogramFirstEligibleToPaintToFirstPaint[]; extern const char kHistogramFirstNonScrollInputAfterFirstPaint[]; extern const char kHistogramFirstScrollInputAfterFirstPaint[]; extern const char kHistogramPageLoadTotalBytes[]; extern const char kHistogramPageLoadNetworkBytes[]; extern const char kHistogramPageLoadCacheBytes[]; extern const char kHistogramPageLoadNetworkBytesIncludingHeaders[]; extern const char kHistogramPageLoadUnfinishedBytes[]; extern const char kHistogramPageLoadCpuTotalUsage[]; extern const char kHistogramPageLoadCpuTotalUsageForegrounded[]; extern const char kHistogramLoadTypeTotalBytesForwardBack[]; extern const char kHistogramLoadTypeNetworkBytesForwardBack[]; extern const char kHistogramLoadTypeCacheBytesForwardBack[]; extern const char kHistogramLoadTypeTotalBytesReload[]; extern const char kHistogramLoadTypeNetworkBytesReload[]; extern const char kHistogramLoadTypeCacheBytesReload[]; extern const char kHistogramLoadTypeTotalBytesNewNavigation[]; extern const char kHistogramLoadTypeNetworkBytesNewNavigation[]; extern const char kHistogramLoadTypeCacheBytesNewNavigation[]; extern const char kHistogramTotalCompletedResources[]; extern const char kHistogramNetworkCompletedResources[]; extern const char kHistogramCacheCompletedResources[]; extern const char kHistogramInputToNavigation[]; extern const char kBackgroundHistogramInputToNavigation[]; extern const char kHistogramInputToNavigationLinkClick[]; extern const char kHistogramInputToNavigationOmnibox[]; extern const char kHistogramInputToFirstPaint[]; extern const char kBackgroundHistogramInputToFirstPaint[]; extern const char kHistogramInputToFirstContentfulPaint[]; extern const char kBackgroundHistogramInputToFirstContentfulPaint[]; extern const char kHistogramBackForwardCacheEvent[]; // Navigation metrics from the navigation start. extern const char kHistogramNavigationTimingNavigationStartToFirstRequestStart[]; extern const char kHistogramNavigationTimingNavigationStartToFirstResponseStart[]; extern const char kHistogramNavigationTimingNavigationStartToFirstLoaderCallback[]; extern const char kHistogramNavigationTimingNavigationStartToFinalRequestStart[]; extern const char kHistogramNavigationTimingNavigationStartToFinalResponseStart[]; extern const char kHistogramNavigationTimingNavigationStartToFinalLoaderCallback[]; extern const char kHistogramNavigationTimingNavigationStartToNavigationCommitSent[]; // Navigation metrics between milestones. extern const char kHistogramNavigationTimingFirstRequestStartToFirstResponseStart[]; extern const char kHistogramNavigationTimingFirstResponseStartToFirstLoaderCallback[]; extern const char kHistogramNavigationTimingFinalRequestStartToFinalResponseStart[]; extern const char kHistogramNavigationTimingFinalResponseStartToFinalLoaderCallback[]; extern const char kHistogramNavigationTimingFinalLoaderCallbackToNavigationCommitSent[]; // V8 memory usage metrics. extern const char kHistogramMemoryMainframe[]; extern const char kHistogramMemorySubframeAggregate[]; extern const char kHistogramMemoryTotal[]; extern const char kHistogramMemoryUpdateReceived[]; enum FirstMeaningfulPaintStatus { FIRST_MEANINGFUL_PAINT_RECORDED, FIRST_MEANINGFUL_PAINT_BACKGROUNDED, FIRST_MEANINGFUL_PAINT_DID_NOT_REACH_NETWORK_STABLE, FIRST_MEANINGFUL_PAINT_USER_INTERACTION_BEFORE_FMP, FIRST_MEANINGFUL_PAINT_DID_NOT_REACH_FIRST_CONTENTFUL_PAINT, FIRST_MEANINGFUL_PAINT_LAST_ENTRY }; // Please keep in sync with PageLoadBackForwardCacheEvent in // tools/metrics/histograms/enums.xml. These values should not be renumbered. enum class PageLoadBackForwardCacheEvent { kEnterBackForwardCache = 0, kRestoreFromBackForwardCache = 1, kMaxValue = kRestoreFromBackForwardCache, }; } // namespace internal // Observer responsible for recording 'core' UMA page load metrics. Core metrics // are maintained by loading-dev team, typically the metrics under // PageLoad.(Document|Paint|Parse)Timing.*. class UmaPageLoadMetricsObserver : public page_load_metrics::PageLoadMetricsObserver { public: UmaPageLoadMetricsObserver(); UmaPageLoadMetricsObserver(const UmaPageLoadMetricsObserver&) = delete; UmaPageLoadMetricsObserver& operator=(const UmaPageLoadMetricsObserver&) = delete; ~UmaPageLoadMetricsObserver() override; // page_load_metrics::PageLoadMetricsObserver: ObservePolicy OnRedirect( content::NavigationHandle* navigation_handle) override; ObservePolicy OnCommit(content::NavigationHandle* navigation_handle, ukm::SourceId source_id) override; void OnDomContentLoadedEventStart( const page_load_metrics::mojom::PageLoadTiming& timing) override; void OnLoadEventStart( const page_load_metrics::mojom::PageLoadTiming& timing) override; void OnFirstPaintInPage( const page_load_metrics::mojom::PageLoadTiming& timing) override; void OnFirstImagePaintInPage( const page_load_metrics::mojom::PageLoadTiming& timing) override; void OnFirstContentfulPaintInPage( const page_load_metrics::mojom::PageLoadTiming& timing) override; void OnFirstMeaningfulPaintInMainFrameDocument( const page_load_metrics::mojom::PageLoadTiming& timing) override; void OnFirstInputInPage( const page_load_metrics::mojom::PageLoadTiming& timing) override; void OnParseStart( const page_load_metrics::mojom::PageLoadTiming& timing) override; void OnParseStop( const page_load_metrics::mojom::PageLoadTiming& timing) override; void OnComplete( const page_load_metrics::mojom::PageLoadTiming& timing) override; void OnFailedProvisionalLoad( const page_load_metrics::FailedProvisionalLoadInfo& failed_load_info) override; void OnLoadedResource(const page_load_metrics::ExtraRequestCompleteInfo& extra_request_complete_info) override; ObservePolicy FlushMetricsOnAppEnterBackground( const page_load_metrics::mojom::PageLoadTiming& timing) override; void OnUserInput( const blink::WebInputEvent& event, const page_load_metrics::mojom::PageLoadTiming& timing) override; void OnResourceDataUseObserved( content::RenderFrameHost* rfh, const std::vector<page_load_metrics::mojom::ResourceDataUpdatePtr>& resources) override; void OnCpuTimingUpdate( content::RenderFrameHost* subframe_rfh, const page_load_metrics::mojom::CpuTiming& timing) override; ObservePolicy OnEnterBackForwardCache( const page_load_metrics::mojom::PageLoadTiming& timing) override; void OnRestoreFromBackForwardCache( const page_load_metrics::mojom::PageLoadTiming& timing, content::NavigationHandle* navigation_handle) override; void OnV8MemoryChanged(const std::vector<page_load_metrics::MemoryUpdate>& memory_updates) override; private: // Class to keep track of per-frame memory usage by V8. class MemoryUsage { public: void UpdateUsage(int64_t delta_bytes); uint64_t current_bytes_used() { return current_bytes_used_; } uint64_t max_bytes_used() { return max_bytes_used_; } private: uint64_t current_bytes_used_ = 0U; uint64_t max_bytes_used_ = 0U; }; void RecordNavigationTimingHistograms(); void RecordTimingHistograms( const page_load_metrics::mojom::PageLoadTiming& main_frame_timing); void RecordByteAndResourceHistograms( const page_load_metrics::mojom::PageLoadTiming& timing); void RecordCpuUsageHistograms(); void RecordForegroundDurationHistograms( const page_load_metrics::mojom::PageLoadTiming& timing, base::TimeTicks app_background_time); void RecordV8MemoryHistograms(); void RecordNormalizedResponsivenessMetrics(); content::NavigationHandleTiming navigation_handle_timing_; ui::PageTransition transition_; bool was_no_store_main_resource_; // Number of complete resources loaded by the page. int num_cache_resources_; int num_network_resources_; // The number of body (not header) prefilter bytes consumed by completed // requests for the page. int64_t cache_bytes_; int64_t network_bytes_; // The number of prefilter bytes consumed by completed and partial network // requests for the page. int64_t network_bytes_including_headers_; // The CPU usage attributed to this page. base::TimeDelta total_cpu_usage_; base::TimeDelta foreground_cpu_usage_; // Size of the redirect chain, which excludes the first URL. int redirect_chain_size_; // True if we've received a non-scroll input (touch tap or mouse up) // after first paint has happened. bool received_non_scroll_input_after_first_paint_ = false; // True if we've received a scroll input after first paint has happened. bool received_scroll_input_after_first_paint_ = false; base::TimeTicks first_paint_; // Tracks user input clicks for possible click burst. page_load_metrics::ClickInputTracker click_tracker_; // V8 Memory Usage: whether a memory update was received, the usage of the // mainframe, the aggregate usage of all subframes on the page, and the // aggregate usage of all frames on the page (including the main frame), // respectively. bool memory_update_received_ = false; MemoryUsage main_frame_memory_usage_; MemoryUsage aggregate_subframe_memory_usage_; MemoryUsage aggregate_total_memory_usage_; bool received_first_subresource_load_ = false; base::TimeDelta total_subresource_load_time_; }; #endif // COMPONENTS_PAGE_LOAD_METRICS_BROWSER_OBSERVERS_CORE_UMA_PAGE_LOAD_METRICS_OBSERVER_H_
blueboxd/chromium-legacy
chrome/browser/ash/chrome_browser_main_parts_ash.h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_ASH_CHROME_BROWSER_MAIN_PARTS_ASH_H_ #define CHROME_BROWSER_ASH_CHROME_BROWSER_MAIN_PARTS_ASH_H_ #include <memory> // TODO(https://crbug.com/1164001): remove and use forward declaration. #include "ash/components/power/dark_resume_controller.h" // TODO(https://crbug.com/1164001): remove and use forward declaration. #include "ash/components/device_activity/device_activity_controller.h" #include "base/macros.h" #include "base/task/cancelable_task_tracker.h" // TODO(https://crbug.com/1164001): remove and use forward declaration. #include "chrome/browser/ash/app_mode/arc/arc_kiosk_app_manager.h" // TODO(https://crbug.com/1164001): remove and use forward declaration. #include "chrome/browser/ash/app_mode/web_app/web_kiosk_app_manager.h" // TODO(https://crbug.com/1164001): remove and use forward declaration. #include "chrome/browser/ash/events/event_rewriter_delegate_impl.h" // TODO(https://crbug.com/1164001): remove and use forward declaration. #include "chrome/browser/ash/login/demo_mode/demo_mode_resources_remover.h" // TODO(https://crbug.com/1164001): remove and use forward declaration. #include "chrome/browser/ash/login/login_screen_extensions_lifetime_manager.h" // TODO(https://crbug.com/1164001): remove and use forward declaration. #include "chrome/browser/ash/login/login_screen_extensions_storage_cleaner.h" // TODO(https://crbug.com/1164001): remove and use forward declaration. #include "chrome/browser/ash/notifications/gnubby_notification.h" // TODO(https://crbug.com/1164001): remove and use forward declaration. #include "chrome/browser/ash/notifications/low_disk_notification.h" // TODO(https://crbug.com/1164001): remove and use forward declaration. #include "chrome/browser/ash/power/auto_screen_brightness/controller.h" // TODO(https://crbug.com/1164001): remove and use forward declaration. #include "chrome/browser/ash/power/idle_action_warning_observer.h" // TODO(https://crbug.com/1164001): remove and use forward declaration. #include "chrome/browser/ash/power/ml/adaptive_screen_brightness_manager.h" // TODO(https://crbug.com/1164001): remove and use forward declaration. #include "chrome/browser/ash/power/power_metrics_reporter.h" // TODO(https://crbug.com/1164001): remove and use forward declaration. #include "chrome/browser/ash/power/renderer_freezer.h" // TODO(https://crbug.com/1164001): remove and use forward declaration. #include "chrome/browser/ash/power/smart_charging/smart_charging_manager.h" // TODO(https://crbug.com/1164001): remove and use forward declaration. #include "chrome/browser/ash/settings/shutdown_policy_forwarder.h" // TODO(https://crbug.com/1164001): remove and use forward declaration. #include "chrome/browser/ash/system/breakpad_consent_watcher.h" // TODO(https://crbug.com/1164001): remove and use forward declaration. #include "chrome/browser/ash/usb/cros_usb_detector.h" // TODO(https://crbug.com/1164001): remove and use forward declaration. #include "chrome/browser/ash/external_metrics.h" #include "chrome/browser/ash/pcie_peripheral/ash_usb_detector.h" #include "chrome/browser/ash/wilco_dtc_supportd/wilco_dtc_supportd_manager.h" #include "chrome/browser/chrome_browser_main_linux.h" #include "chrome/browser/memory/memory_kills_monitor.h" class AssistantBrowserDelegateImpl; class AssistantStateClient; class ChromeKeyboardControllerClient; class ImageDownloaderImpl; namespace arc { namespace data_snapshotd { class ArcDataSnapshotdManager; } // namespace data_snapshotd class ArcServiceLauncher; } // namespace arc namespace ash { class AccessibilityEventRewriterDelegateImpl; class BulkPrintersCalculatorFactory; class DebugdNotificationHandler; class FirmwareUpdateManager; namespace quick_pair { class QuickPairBrowserDelegateImpl; } namespace platform_keys { class KeyPermissionsManager; } } // namespace ash namespace crosapi { class BrowserManager; class CrosapiManager; } // namespace crosapi namespace crostini { class CrostiniUnsupportedActionNotifier; class CrosvmMetrics; } // namespace crostini namespace lock_screen_apps { class StateController; } namespace policy { class LockToSingleUserManager; } // namespace policy namespace chromeos { class BluetoothPrefStateObserver; class FastTransitionObserver; class NetworkChangeManagerClient; class NetworkPrefStateObserver; class NetworkThrottlingObserver; class SessionTerminationManager; class SystemTokenCertDBInitializer; namespace default_app_order { class ExternalLoader; } namespace internal { class DBusServices; } // namespace internal // ChromeBrowserMainParts implementation for chromeos specific code. // NOTE: Chromeos UI (Ash) support should be added to // ChromeBrowserMainExtraPartsAsh instead. This class should not depend on // src/ash or chrome/browser/ui/ash. class ChromeBrowserMainPartsAsh : public ChromeBrowserMainPartsLinux { public: ChromeBrowserMainPartsAsh(const content::MainFunctionParams& parameters, StartupData* startup_data); ChromeBrowserMainPartsAsh(const ChromeBrowserMainPartsAsh&) = delete; ChromeBrowserMainPartsAsh& operator=(const ChromeBrowserMainPartsAsh&) = delete; ~ChromeBrowserMainPartsAsh() override; // ChromeBrowserMainParts overrides. int PreEarlyInitialization() override; void PreCreateMainMessageLoop() override; void PostCreateMainMessageLoop() override; int PreMainMessageLoopRun() override; // Stages called from PreMainMessageLoopRun. void PreProfileInit() override; void PostProfileInit() override; void PreBrowserStart() override; void PostBrowserStart() override; // After initialization is finished. void OnFirstIdle() override; void PostMainMessageLoopRun() override; void PostDestroyThreads() override; private: std::unique_ptr<default_app_order::ExternalLoader> app_order_loader_; std::unique_ptr<NetworkPrefStateObserver> network_pref_state_observer_; std::unique_ptr<BluetoothPrefStateObserver> bluetooth_pref_state_observer_; std::unique_ptr<IdleActionWarningObserver> idle_action_warning_observer_; std::unique_ptr<RendererFreezer> renderer_freezer_; std::unique_ptr<PowerMetricsReporter> power_metrics_reporter_; std::unique_ptr<FastTransitionObserver> fast_transition_observer_; std::unique_ptr<NetworkThrottlingObserver> network_throttling_observer_; std::unique_ptr<NetworkChangeManagerClient> network_change_manager_client_; std::unique_ptr<ash::DebugdNotificationHandler> debugd_notification_handler_; std::unique_ptr<internal::DBusServices> dbus_services_; std::unique_ptr<SystemTokenCertDBInitializer> system_token_certdb_initializer_; std::unique_ptr<ShutdownPolicyForwarder> shutdown_policy_forwarder_; std::unique_ptr<EventRewriterDelegateImpl> event_rewriter_delegate_; // Handles event dispatch to the accessibility component extensions. std::unique_ptr<ash::AccessibilityEventRewriterDelegateImpl> accessibility_event_rewriter_delegate_; scoped_refptr<chromeos::ExternalMetrics> external_metrics_; std::unique_ptr<arc::ArcServiceLauncher> arc_service_launcher_; std::unique_ptr<ImageDownloaderImpl> image_downloader_; std::unique_ptr<AssistantStateClient> assistant_state_client_; std::unique_ptr<AssistantBrowserDelegateImpl> assistant_delegate_; std::unique_ptr<LowDiskNotification> low_disk_notification_; std::unique_ptr<ArcKioskAppManager> arc_kiosk_app_manager_; std::unique_ptr<WebKioskAppManager> web_kiosk_app_manager_; std::unique_ptr<ChromeKeyboardControllerClient> chrome_keyboard_controller_client_; std::unique_ptr<lock_screen_apps::StateController> lock_screen_apps_state_controller_; std::unique_ptr<crosapi::CrosapiManager> crosapi_manager_; std::unique_ptr<crosapi::BrowserManager> browser_manager_; std::unique_ptr<power::SmartChargingManager> smart_charging_manager_; std::unique_ptr<power::ml::AdaptiveScreenBrightnessManager> adaptive_screen_brightness_manager_; std::unique_ptr<power::auto_screen_brightness::Controller> auto_screen_brightness_controller_; std::unique_ptr<DemoModeResourcesRemover> demo_mode_resources_remover_; std::unique_ptr<crostini::CrosvmMetrics> crosvm_metrics_; std::unique_ptr<ash::AshUsbDetector> ash_usb_detector_; std::unique_ptr<CrosUsbDetector> cros_usb_detector_; std::unique_ptr<ash::device_activity::DeviceActivityController> device_activity_controller_; std::unique_ptr<crostini::CrostiniUnsupportedActionNotifier> crostini_unsupported_action_notifier_; std::unique_ptr<chromeos::system::DarkResumeController> dark_resume_controller_; std::unique_ptr<ash::BulkPrintersCalculatorFactory> bulk_printers_calculator_factory_; std::unique_ptr<SessionTerminationManager> session_termination_manager_; // Set when PreProfileInit() is called. If PreMainMessageLoopRun() exits // early, this will be false during PostMainMessageLoopRun(), etc. // Used to prevent shutting down classes that were not initialized. bool pre_profile_init_called_ = false; std::unique_ptr<policy::LockToSingleUserManager> lock_to_single_user_manager_; std::unique_ptr<WilcoDtcSupportdManager> wilco_dtc_supportd_manager_; std::unique_ptr<LoginScreenExtensionsLifetimeManager> login_screen_extensions_lifetime_manager_; std::unique_ptr<LoginScreenExtensionsStorageCleaner> login_screen_extensions_storage_cleaner_; std::unique_ptr<ash::FirmwareUpdateManager> firmware_update_manager_; std::unique_ptr<GnubbyNotification> gnubby_notification_; std::unique_ptr<system::BreakpadConsentWatcher> breakpad_consent_watcher_; std::unique_ptr<arc::data_snapshotd::ArcDataSnapshotdManager> arc_data_snapshotd_manager_; std::unique_ptr<ash::platform_keys::KeyPermissionsManager> system_token_key_permissions_manager_; std::unique_ptr<ash::quick_pair::QuickPairBrowserDelegateImpl> quick_pair_delegate_; }; } // namespace chromeos #endif // CHROME_BROWSER_ASH_CHROME_BROWSER_MAIN_PARTS_ASH_H_
blueboxd/chromium-legacy
chrome/browser/ash/system/fake_input_device_settings.h
// 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_ASH_SYSTEM_FAKE_INPUT_DEVICE_SETTINGS_H_ #define CHROME_BROWSER_ASH_SYSTEM_FAKE_INPUT_DEVICE_SETTINGS_H_ #include "base/compiler_specific.h" #include "base/macros.h" #include "chrome/browser/ash/system/input_device_settings.h" namespace ash { namespace system { // This fake just memorizes current values of input devices settings. class FakeInputDeviceSettings : public InputDeviceSettings, public InputDeviceSettings::FakeInterface { public: FakeInputDeviceSettings(); FakeInputDeviceSettings(const FakeInputDeviceSettings&) = delete; FakeInputDeviceSettings& operator=(const FakeInputDeviceSettings&) = delete; ~FakeInputDeviceSettings() override; // Overridden from InputDeviceSettings. void TouchpadExists(DeviceExistsCallback callback) override; void UpdateTouchpadSettings(const TouchpadSettings& settings) override; void SetTouchpadSensitivity(int value) override; void SetTouchpadScrollSensitivity(int value) override; void SetTouchpadHapticFeedback(bool enabled) override; void SetTouchpadHapticClickSensitivity(int value) override; void SetTapToClick(bool enabled) override; void SetThreeFingerClick(bool enabled) override; void SetTapDragging(bool enabled) override; void MouseExists(DeviceExistsCallback callback) override; void UpdateMouseSettings(const MouseSettings& settings) override; void SetMouseSensitivity(int value) override; void SetMouseScrollSensitivity(int value) override; void SetPrimaryButtonRight(bool right) override; void SetMouseReverseScroll(bool enabled) override; void SetMouseAcceleration(bool enabled) override; void SetMouseScrollAcceleration(bool enabled) override; void PointingStickExists(DeviceExistsCallback callback) override; void UpdatePointingStickSettings( const PointingStickSettings& settings) override; void SetPointingStickSensitivity(int value) override; void SetPointingStickPrimaryButtonRight(bool right) override; void SetPointingStickAcceleration(bool enabled) override; void SetTouchpadAcceleration(bool enabled) override; void SetTouchpadScrollAcceleration(bool enabled) override; void SetNaturalScroll(bool enabled) override; void ReapplyTouchpadSettings() override; void ReapplyMouseSettings() override; void ReapplyPointingStickSettings() override; InputDeviceSettings::FakeInterface* GetFakeInterface() override; // Overridden from InputDeviceSettings::FakeInterface. void set_touchpad_exists(bool exists) override; void set_mouse_exists(bool exists) override; void set_pointing_stick_exists(bool exists) override; const TouchpadSettings& current_touchpad_settings() const override; const MouseSettings& current_mouse_settings() const override; const PointingStickSettings& current_pointing_stick_settings() const override; private: TouchpadSettings current_touchpad_settings_; MouseSettings current_mouse_settings_; PointingStickSettings current_pointing_stick_settings_; bool touchpad_exists_ = true; bool mouse_exists_ = true; bool pointing_stick_exists_ = true; }; } // namespace system } // namespace ash #endif // CHROME_BROWSER_ASH_SYSTEM_FAKE_INPUT_DEVICE_SETTINGS_H_
blueboxd/chromium-legacy
ui/ozone/platform/flatland/flatland_sysmem_buffer_collection.h
<reponame>blueboxd/chromium-legacy // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_OZONE_PLATFORM_FLATLAND_FLATLAND_SYSMEM_BUFFER_COLLECTION_H_ #define UI_OZONE_PLATFORM_FLATLAND_FLATLAND_SYSMEM_BUFFER_COLLECTION_H_ #include <fuchsia/sysmem/cpp/fidl.h> #include <fuchsia/ui/composition/cpp/fidl.h> #include <vulkan/vulkan.h> #include "base/callback.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/task/single_thread_task_runner.h" #include "base/threading/thread_checker.h" #include "gpu/ipc/common/vulkan_ycbcr_info.h" #include "gpu/vulkan/fuchsia/vulkan_fuchsia_ext.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/gfx/buffer_types.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/native_pixmap_handle.h" namespace gfx { class NativePixmap; } // namespace gfx namespace ui { class FlatlandSurfaceFactory; // FlatlandSysmemBufferCollection keeps sysmem.BufferCollection interface along // with the corresponding VkBufferCollectionFUCHSIA. It allows to create either // gfx::NativePixmap or VkImage from the buffers in the collection. // A collection can be initialized and used on any thread. CreateVkImage() must // be called on the same thread (because it may be be safe to use // VkBufferCollectionFUCHSIA concurrently on different threads). class FlatlandSysmemBufferCollection : public base::RefCountedThreadSafe<FlatlandSysmemBufferCollection> { public: static bool IsNativePixmapConfigSupported(gfx::BufferFormat format, gfx::BufferUsage usage); FlatlandSysmemBufferCollection(); explicit FlatlandSysmemBufferCollection(gfx::SysmemBufferCollectionId id); FlatlandSysmemBufferCollection(const FlatlandSysmemBufferCollection&) = delete; FlatlandSysmemBufferCollection& operator=( const FlatlandSysmemBufferCollection&) = delete; // Initializes the buffer collection and registers it with Vulkan using the // specified |vk_device|. If |token_handle| is null then a new collection // collection is created. |size| may be empty. In that case |token_handle| // must not be null and the image size is determined by the other sysmem // participants. // If usage has SCANOUT, |token_handle| gets duplicated and registered with // the Scenic Allocator. bool Initialize(fuchsia::sysmem::Allocator_Sync* sysmem_allocator, fuchsia::ui::composition::Allocator* flatland_allocator, FlatlandSurfaceFactory* flatland_surface_factory, zx::channel token_handle, gfx::Size size, gfx::BufferFormat format, gfx::BufferUsage usage, VkDevice vk_device, size_t min_buffer_count); // Creates a NativePixmap the buffer with the specified index. Returned // NativePixmap holds a reference to the collection, so the collection is not // deleted until all NativePixmap are destroyed. scoped_refptr<gfx::NativePixmap> CreateNativePixmap(size_t buffer_index); // Creates a new Vulkan image for the buffer with the specified index. bool CreateVkImage(size_t buffer_index, VkDevice vk_device, gfx::Size size, VkImage* vk_image, VkImageCreateInfo* vk_image_info, VkDeviceMemory* vk_device_memory, VkDeviceSize* mem_allocation_size, absl::optional<gpu::VulkanYCbCrInfo>* ycbcr_info); gfx::SysmemBufferCollectionId id() const { return id_; } size_t num_buffers() const { return buffers_info_.buffer_count; } gfx::Size size() const { return image_size_; } gfx::BufferFormat format() const { return format_; } size_t buffer_size() const { return buffers_info_.settings.buffer_settings.size_bytes; } // Returns a duplicate of |flatland_import_token_| so Images can be created. fuchsia::ui::composition::BufferCollectionImportToken GetFlatlandImportToken() const; void AddOnDeletedCallback(base::OnceClosure on_deleted); private: friend class base::RefCountedThreadSafe<FlatlandSysmemBufferCollection>; ~FlatlandSysmemBufferCollection(); bool InitializeInternal( fuchsia::sysmem::Allocator_Sync* sysmem_allocator, fuchsia::ui::composition::Allocator* flatland_allocator, fuchsia::sysmem::BufferCollectionTokenSyncPtr collection_token, bool register_with_flatland_allocator, size_t min_buffer_count); void InitializeImageCreateInfo(VkImageCreateInfo* vk_image_info, gfx::Size size); bool is_mappable() const { return usage_ == gfx::BufferUsage::SCANOUT_CPU_READ_WRITE || usage_ == gfx::BufferUsage::GPU_READ_CPU_READ_WRITE; } const gfx::SysmemBufferCollectionId id_; // Image size passed to vkSetBufferCollectionConstraintsFUCHSIA(). The actual // buffers size may be larger depending on constraints set by other // sysmem clients. Size of the image is passed to CreateVkImage(). gfx::Size min_size_; gfx::BufferFormat format_ = gfx::BufferFormat::RGBA_8888; gfx::BufferUsage usage_ = gfx::BufferUsage::GPU_READ_CPU_READ_WRITE; fuchsia::sysmem::BufferCollectionSyncPtr collection_; fuchsia::sysmem::BufferCollectionInfo_2 buffers_info_; fuchsia::ui::composition::BufferCollectionImportToken flatland_import_token_; // Vulkan device for which the collection was initialized. VkDevice vk_device_ = VK_NULL_HANDLE; // Handle for the Vulkan object that holds the same logical buffer collection // that is referenced by |collection_|. VkBufferCollectionFUCHSIAX vk_buffer_collection_ = VK_NULL_HANDLE; // Thread checker used to verify that CreateVkImage() is always called from // the same thread. It may be unsafe to use vk_buffer_collection_ on different // threads. THREAD_CHECKER(vulkan_thread_checker_); gfx::Size image_size_; size_t buffer_size_ = 0; bool is_protected_ = false; std::vector<base::OnceClosure> on_deleted_; }; } // namespace ui #endif // UI_OZONE_PLATFORM_FLATLAND_FLATLAND_SYSMEM_BUFFER_COLLECTION_H_
blueboxd/chromium-legacy
chrome/browser/extensions/api/quick_unlock_private/quick_unlock_private_api_lacros.h
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_EXTENSIONS_API_QUICK_UNLOCK_PRIVATE_QUICK_UNLOCK_PRIVATE_API_LACROS_H_ #define CHROME_BROWSER_EXTENSIONS_API_QUICK_UNLOCK_PRIVATE_QUICK_UNLOCK_PRIVATE_API_LACROS_H_ #include "extensions/browser/extension_function.h" namespace extensions { class QuickUnlockPrivateGetAuthTokenFunction : public ExtensionFunction { public: QuickUnlockPrivateGetAuthTokenFunction(); QuickUnlockPrivateGetAuthTokenFunction( const QuickUnlockPrivateGetAuthTokenFunction&) = delete; const QuickUnlockPrivateGetAuthTokenFunction& operator=( const QuickUnlockPrivateGetAuthTokenFunction&) = delete; DECLARE_EXTENSION_FUNCTION("quickUnlockPrivate.getAuthToken", QUICKUNLOCKPRIVATE_GETAUTHTOKEN) protected: ~QuickUnlockPrivateGetAuthTokenFunction() override; // ExtensionFunction overrides. ResponseAction Run() override; }; } // namespace extensions #endif // CHROME_BROWSER_EXTENSIONS_API_QUICK_UNLOCK_PRIVATE_QUICK_UNLOCK_PRIVATE_API_LACROS_H_
blueboxd/chromium-legacy
chrome/browser/ui/views/global_media_controls/media_toolbar_button_contextual_menu.h
<gh_stars>10-100 // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_VIEWS_GLOBAL_MEDIA_CONTROLS_MEDIA_TOOLBAR_BUTTON_CONTEXTUAL_MENU_H_ #define CHROME_BROWSER_UI_VIEWS_GLOBAL_MEDIA_CONTROLS_MEDIA_TOOLBAR_BUTTON_CONTEXTUAL_MENU_H_ #include "build/branding_buildflags.h" #include "ui/base/models/simple_menu_model.h" class Browser; // The contextual menu of the media toolbar button has only one item, which is // to open the Cast feedback page. So this class should be instantiated when: // (1) It is a Chrome branded build. // (2) GlobalMediaControlsCastStartStop is enabled. class MediaToolbarButtonContextualMenu : public ui::SimpleMenuModel::Delegate { public: static std::unique_ptr<MediaToolbarButtonContextualMenu> Create( Browser* browser); explicit MediaToolbarButtonContextualMenu(Browser* browser); MediaToolbarButtonContextualMenu(const MediaToolbarButtonContextualMenu&) = delete; MediaToolbarButtonContextualMenu& operator=( const MediaToolbarButtonContextualMenu&) = delete; ~MediaToolbarButtonContextualMenu() override; std::unique_ptr<ui::SimpleMenuModel> CreateMenuModel(); private: // ui::SimpleMenuModel::Delegate: void ExecuteCommand(int command_id, int event_flags) override; #if BUILDFLAG(GOOGLE_CHROME_BRANDING) // Opens the Cast feedback page. void ReportIssue(); Browser* const browser_; #endif // BUILDFLAG(GOOGLE_CHROME_BRANDING) }; #endif // CHROME_BROWSER_UI_VIEWS_GLOBAL_MEDIA_CONTROLS_MEDIA_TOOLBAR_BUTTON_CONTEXTUAL_MENU_H_
blueboxd/chromium-legacy
content/browser/worker_host/dedicated_worker_host.h
<gh_stars>10-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. #ifndef CONTENT_BROWSER_WORKER_HOST_DEDICATED_WORKER_HOST_H_ #define CONTENT_BROWSER_WORKER_HOST_DEDICATED_WORKER_HOST_H_ #include <memory> #include "base/scoped_observation.h" #include "build/build_config.h" #include "content/browser/browser_interface_broker_impl.h" #include "content/browser/renderer_host/code_cache_host_impl.h" #include "content/public/browser/global_routing_id.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_process_host_observer.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote.h" #include "mojo/public/cpp/bindings/unique_receiver_set.h" #include "net/base/isolation_info.h" #include "services/network/public/cpp/cross_origin_embedder_policy.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/public/common/service_worker/service_worker_status_code.h" #include "third_party/blink/public/common/storage_key/storage_key.h" #include "third_party/blink/public/common/tokens/tokens.h" #include "third_party/blink/public/mojom/frame/back_forward_cache_controller.mojom.h" #include "third_party/blink/public/mojom/idle/idle_manager.mojom-forward.h" #include "third_party/blink/public/mojom/loader/code_cache.mojom.h" #include "third_party/blink/public/mojom/loader/content_security_notifier.mojom.h" #include "third_party/blink/public/mojom/usb/web_usb_service.mojom-forward.h" #include "third_party/blink/public/mojom/wake_lock/wake_lock.mojom-forward.h" #include "third_party/blink/public/mojom/websockets/websocket_connector.mojom-forward.h" #include "third_party/blink/public/mojom/webtransport/web_transport_connector.mojom-forward.h" #include "third_party/blink/public/mojom/worker/dedicated_worker_host.mojom.h" #include "third_party/blink/public/mojom/worker/dedicated_worker_host_factory.mojom.h" #include "third_party/blink/public/mojom/worker/subresource_loader_updater.mojom.h" #include "url/origin.h" #if !defined(OS_ANDROID) #include "third_party/blink/public/mojom/serial/serial.mojom-forward.h" #endif namespace content { class ServiceWorkerContainerHost; class ServiceWorkerRegistration; class DedicatedWorkerServiceImpl; class ServiceWorkerMainResourceHandle; class ServiceWorkerObjectHost; class StoragePartitionImpl; class CrossOriginEmbedderPolicyReporter; // A host for a single dedicated worker. It deletes itself upon Mojo // disconnection from the worker in the renderer or when the RenderProcessHost // of the worker is destroyed. This lives on the UI thread. // TODO(crbug.com/1177652): Align this class's lifetime with the associated // frame. class DedicatedWorkerHost final : public blink::mojom::DedicatedWorkerHost, public blink::mojom::BackForwardCacheControllerHost, public RenderProcessHostObserver { public: DedicatedWorkerHost( DedicatedWorkerServiceImpl* service, const blink::DedicatedWorkerToken& token, RenderProcessHost* worker_process_host, absl::optional<GlobalRenderFrameHostId> creator_render_frame_host_id, absl::optional<blink::DedicatedWorkerToken> creator_worker_token, GlobalRenderFrameHostId ancestor_render_frame_host_id, const blink::StorageKey& creator_storage_key, const net::IsolationInfo& isolation_info, const network::CrossOriginEmbedderPolicy& cross_origin_embedder_policy, base::WeakPtr<CrossOriginEmbedderPolicyReporter> creator_coep_reporter, base::WeakPtr<CrossOriginEmbedderPolicyReporter> ancestor_coep_reporter, mojo::PendingReceiver<blink::mojom::DedicatedWorkerHost> host); DedicatedWorkerHost(const DedicatedWorkerHost&) = delete; DedicatedWorkerHost& operator=(const DedicatedWorkerHost&) = delete; ~DedicatedWorkerHost() final; void BindBrowserInterfaceBrokerReceiver( mojo::PendingReceiver<blink::mojom::BrowserInterfaceBroker> receiver); const blink::DedicatedWorkerToken& GetToken() const { return token_; } RenderProcessHost* GetProcessHost() const { return worker_process_host_; } const blink::StorageKey& GetStorageKey() const { return storage_key_; } const GlobalRenderFrameHostId& GetAncestorRenderFrameHostId() const { return ancestor_render_frame_host_id_; } const absl::optional<GURL>& GetFinalResponseURL() const { return final_response_url_; } void CreateContentSecurityNotifier( mojo::PendingReceiver<blink::mojom::ContentSecurityNotifier> receiver); void CreateIdleManager( mojo::PendingReceiver<blink::mojom::IdleManager> receiver); void CreateNestedDedicatedWorker( mojo::PendingReceiver<blink::mojom::DedicatedWorkerHostFactory> receiver); void CreateWebUsbService( mojo::PendingReceiver<blink::mojom::WebUsbService> receiver); void CreateWebSocketConnector( mojo::PendingReceiver<blink::mojom::WebSocketConnector> receiver); void CreateWebTransportConnector( mojo::PendingReceiver<blink::mojom::WebTransportConnector> receiver); void CreateWakeLockService( mojo::PendingReceiver<blink::mojom::WakeLockService> receiver); void BindCacheStorage( mojo::PendingReceiver<blink::mojom::CacheStorage> receiver); void CreateCodeCacheHost( mojo::PendingReceiver<blink::mojom::CodeCacheHost> receiver); #if !defined(OS_ANDROID) void BindSerialService( mojo::PendingReceiver<blink::mojom::SerialService> receiver); #endif // PlzDedicatedWorker: void StartScriptLoad( const GURL& script_url, network::mojom::CredentialsMode credentials_mode, blink::mojom::FetchClientSettingsObjectPtr outside_fetch_client_settings_object, mojo::PendingRemote<blink::mojom::BlobURLToken> blob_url_token, mojo::Remote<blink::mojom::DedicatedWorkerHostFactoryClient> client); void ReportNoBinderForInterface(const std::string& error); // TODO(crbug.com/906991): Remove this method once PlzDedicatedWorker is // enabled by default. void MaybeCountWebFeature(const GURL& script_url); // TODO(crbug.com/906991): Remove this method once PlzDedicatedWorker is // enabled by default. void ContinueOnMaybeCountWebFeature( const GURL& script_url, base::WeakPtr<ServiceWorkerContainerHost> container_host, blink::ServiceWorkerStatusCode status, const std::vector<scoped_refptr<ServiceWorkerRegistration>>& registrations); const net::NetworkIsolationKey& GetNetworkIsolationKey() const { return isolation_info_.network_isolation_key(); } const base::UnguessableToken& GetReportingSource() const { return reporting_source_; } const network::CrossOriginEmbedderPolicy& cross_origin_embedder_policy() const { DCHECK(worker_cross_origin_embedder_policy_.has_value()); return worker_cross_origin_embedder_policy_.value(); } ServiceWorkerMainResourceHandle* service_worker_handle() { return service_worker_handle_.get(); } // blink::mojom::BackForwardCacheControllerHost: void EvictFromBackForwardCache( blink::mojom::RendererEvictionReason reason) override; void DidChangeBackForwardCacheDisablingFeatures( uint64_t features_mask) override; base::WeakPtr<DedicatedWorkerHost> GetWeakPtr() { return weak_factory_.GetWeakPtr(); } private: // RenderProcessHostObserver: void RenderProcessExited(RenderProcessHost* render_process_host, const ChildProcessTerminationInfo& info) override; void RenderProcessHostDestroyed(RenderProcessHost* host) override; // Called from WorkerScriptFetchInitiator. Continues starting the dedicated // worker in the renderer process. // // |success| is true only when the script fetch succeeded. // // Note: None of the following parameters are valid if |success| is false. // // |main_script_load_params| is sent to the renderer process and to be used to // load the dedicated worker main script pre-requested by the browser process. // // |subresource_loader_factories| is sent to the renderer process and is to be // used to request subresources where applicable. For example, this allows the // dedicated worker to load chrome-extension:// URLs which the renderer's // default loader factory can't load. // // |controller| contains information about the service worker controller. Once // a ServiceWorker object about the controller is prepared, it is registered // to |controller_service_worker_object_host|. // // |final_response_url| is the URL calculated from the initial request URL, // redirect chain, and URLs fetched via service worker. // https://fetch.spec.whatwg.org/#concept-response-url void DidStartScriptLoad( bool success, std::unique_ptr<blink::PendingURLLoaderFactoryBundle> subresource_loader_factories, blink::mojom::WorkerMainScriptLoadParamsPtr main_script_load_params, blink::mojom::ControllerServiceWorkerInfoPtr controller, base::WeakPtr<ServiceWorkerObjectHost> controller_service_worker_object_host, const GURL& final_response_url); // Sets up the observer of network service crash. void ObserveNetworkServiceCrash(StoragePartitionImpl* storage_partition_impl); // Creates a network factory for subresource requests from this worker. The // network factory is meant to be passed to the renderer. mojo::PendingRemote<network::mojom::URLLoaderFactory> CreateNetworkFactoryForSubresources( RenderFrameHostImpl* ancestor_render_frame_host, bool* bypass_redirect_checks); // Updates subresource loader factories. This is supposed to be called when // out-of-process Network Service crashes. void UpdateSubresourceLoaderFactories(); void OnMojoDisconnect(); // Returns true if creator and worker's COEP values are valid. bool CheckCrossOriginEmbedderPolicy( network::CrossOriginEmbedderPolicy creator_cross_origin_embedder_policy, network::CrossOriginEmbedderPolicy worker_cross_origin_embedder_policy); base::WeakPtr<CrossOriginEmbedderPolicyReporter> GetWorkerCoepReporter(); // This outlives `this` as follows: // - StoragePartitionImpl owns DedicatedWorkerServiceImpl until its dtor. // - StoragePartitionImpl outlives RenderProcessHostImpl. // - RenderProcessHostImpl outlives DedicatedWorkerHost. // As the conclusion of the above, DedicatedWorkerServiceImpl outlives // DedicatedWorkerHost. DedicatedWorkerServiceImpl* const service_; // The renderer generated ID of this worker, unique across all processes. const blink::DedicatedWorkerToken token_; // The RenderProcessHost that hosts this worker. This outlives `this`. RenderProcessHost* const worker_process_host_; base::ScopedObservation<RenderProcessHost, RenderProcessHostObserver> scoped_process_host_observation_{this}; // The ID of the frame that directly starts this worker. This is absl::nullopt // when this worker is nested. const absl::optional<GlobalRenderFrameHostId> creator_render_frame_host_id_; // The token of the dedicated worker that directly starts this worker. This is // absl::nullopt when this worker is created from a frame. const absl::optional<blink::DedicatedWorkerToken> creator_worker_token_; // The ID of the frame that owns this worker, either directly, or (in the case // of nested workers) indirectly via a tree of dedicated workers. const GlobalRenderFrameHostId ancestor_render_frame_host_id_; // The origin of the frame or dedicated worker that starts this worker. const url::Origin creator_origin_; // The storage key of this worker. This is used for storage partitioning and // for retrieving the origin of this worker // (https://html.spec.whatwg.org/C/#concept-settings-object-origin). const blink::StorageKey storage_key_; // The IsolationInfo associated with this worker. Same as that of the // frame or the worker that created this worker. const net::IsolationInfo isolation_info_; const base::UnguessableToken reporting_source_; // The frame/worker's Cross-Origin-Embedder-Policy (COEP) that directly starts // this worker. const network::CrossOriginEmbedderPolicy creator_cross_origin_embedder_policy_; // The DedicatedWorker's Cross-Origin-Embedder-Policy (COEP). This is set when // the script's response head is loaded. absl::optional<network::CrossOriginEmbedderPolicy> worker_cross_origin_embedder_policy_; // This is kept alive during the lifetime of the dedicated worker, since it's // associated with Mojo interfaces (ServiceWorkerContainer and // URLLoaderFactory) that are needed to stay alive while the worker is // starting or running. mojo::Remote<blink::mojom::DedicatedWorkerHostFactoryClient> client_; std::unique_ptr<ServiceWorkerMainResourceHandle> service_worker_handle_; // BrowserInterfaceBroker implementation through which this // DedicatedWorkerHost exposes worker-scoped Mojo services to the // corresponding worker in the renderer. // // The interfaces that can be requested from this broker are defined in the // content/browser/browser_interface_binders.cc file, in the functions which // take a `DedicatedWorkerHost*` parameter. BrowserInterfaceBrokerImpl<DedicatedWorkerHost, const url::Origin&> broker_{ this}; mojo::Receiver<blink::mojom::BrowserInterfaceBroker> broker_receiver_{ &broker_}; mojo::Receiver<blink::mojom::DedicatedWorkerHost> host_receiver_; mojo::Receiver<blink::mojom::BackForwardCacheControllerHost> back_forward_cache_controller_host_receiver_{this}; // Indicates if subresource loaders of this worker support file URLs. bool file_url_support_ = false; // For observing Network Service connection errors only. mojo::Remote<network::mojom::URLLoaderFactory> network_service_connection_error_handler_holder_; mojo::Remote<blink::mojom::SubresourceLoaderUpdater> subresource_loader_updater_; // For the PlzDedicatedWorker case. `coep_reporter_` is valid after // DidStartScriptLoad() and remains non-null for the lifetime of `this`. std::unique_ptr<CrossOriginEmbedderPolicyReporter> coep_reporter_; // TODO(crbug.com/1177652): Remove `creator_coep_reporter_` after this class's // lifetime is aligned with the associated frame. base::WeakPtr<CrossOriginEmbedderPolicyReporter> creator_coep_reporter_; // For the non-PlzDedicatedWorker case. Sending reports to the ancestor frame // is not the behavior defined in the spec, but keep the current behavior and // not to lose reports. // TODO(crbug.com/906991): Remove `ancestor_coep_reporter_` once // PlzDedicatedWorker is enabled by default. base::WeakPtr<CrossOriginEmbedderPolicyReporter> ancestor_coep_reporter_; // Will be set once the worker script started loading. absl::optional<GURL> final_response_url_; // CodeCacheHost processes requests to fetch / write generated code for // JavaScript / WebAssembly resources. CodeCacheHostImpl::ReceiverSet code_cache_host_receivers_; base::WeakPtrFactory<DedicatedWorkerHost> weak_factory_{this}; }; } // namespace content #endif // CONTENT_BROWSER_WORKER_HOST_DEDICATED_WORKER_HOST_H_
blueboxd/chromium-legacy
chrome/browser/ash/phonehub/camera_roll_download_manager_impl.h
<filename>chrome/browser/ash/phonehub/camera_roll_download_manager_impl.h // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_ASH_PHONEHUB_CAMERA_ROLL_DOWNLOAD_MANAGER_IMPL_H_ #define CHROME_BROWSER_ASH_PHONEHUB_CAMERA_ROLL_DOWNLOAD_MANAGER_IMPL_H_ #include <string> #include "base/containers/flat_map.h" #include "base/files/file_path.h" #include "base/files/safe_base_name.h" #include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" #include "base/task/sequenced_task_runner.h" #include "chrome/browser/ui/ash/holding_space/holding_space_keyed_service.h" #include "chromeos/components/phonehub/camera_roll_download_manager.h" #include "chromeos/components/phonehub/proto/phonehub_api.pb.h" #include "chromeos/services/secure_channel/public/mojom/secure_channel_types.mojom.h" namespace ash { namespace phonehub { // CameraRollDownloadManager implementation. class CameraRollDownloadManagerImpl : public chromeos::phonehub::CameraRollDownloadManager { public: CameraRollDownloadManagerImpl( const base::FilePath& download_path, ash::HoldingSpaceKeyedService* holding_space_keyed_service); ~CameraRollDownloadManagerImpl() override; // CameraRollDownloadManager: void CreatePayloadFiles( int64_t payload_id, const chromeos::phonehub::proto::CameraRollItemMetadata& item_metadata, CreatePayloadFilesCallback payload_files_callback) override; void UpdateDownloadProgress( chromeos::secure_channel::mojom::FileTransferUpdatePtr update) override; void DeleteFile(int64_t payload_id) override; private: // Internal representation of an item being downloaded. struct DownloadItem { DownloadItem(int64_t payload_id, const base::FilePath& file_path); DownloadItem(const DownloadItem&); DownloadItem& operator=(const DownloadItem&); ~DownloadItem(); int64_t payload_id; base::FilePath file_path; std::string holding_space_item_id; }; void OnDiskSpaceCheckComplete( const base::SafeBaseName& base_name, int64_t payload_id, CreatePayloadFilesCallback payload_files_callback, bool has_enough_disk_space); void OnUniquePathFetched(int64_t payload_id, CreatePayloadFilesCallback payload_files_callback, const base::FilePath& unique_path); void OnPayloadFilesCreated( CreatePayloadFilesCallback payload_files_callback, chromeos::secure_channel::mojom::PayloadFilesPtr payload_files); const base::FilePath download_path_; ash::HoldingSpaceKeyedService* holding_space_keyed_service_; // Performs blocking I/O operations for creating and deleting payload files. const scoped_refptr<base::SequencedTaskRunner> task_runner_; // Item downloads that are still in progress, keyed by payload IDs. base::flat_map<int64_t, DownloadItem> pending_downloads_; base::WeakPtrFactory<CameraRollDownloadManagerImpl> weak_ptr_factory_{this}; }; } // namespace phonehub } // namespace ash #endif // CHROME_BROWSER_ASH_PHONEHUB_CAMERA_ROLL_DOWNLOAD_MANAGER_IMPL_H_
blueboxd/chromium-legacy
ui/accessibility/platform/test_ax_node_wrapper.h
// 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 UI_ACCESSIBILITY_PLATFORM_TEST_AX_NODE_WRAPPER_H_ #define UI_ACCESSIBILITY_PLATFORM_TEST_AX_NODE_WRAPPER_H_ #include <set> #include <string> #include <vector> #include "base/auto_reset.h" #include "build/build_config.h" #include "ui/accessibility/ax_node.h" #include "ui/accessibility/ax_tree.h" #include "ui/accessibility/platform/ax_platform_node.h" #include "ui/accessibility/platform/ax_platform_node_delegate_base.h" #if defined(OS_WIN) namespace gfx { const AcceleratedWidget kMockAcceleratedWidget = reinterpret_cast<HWND>(-1); } #endif namespace ui { // For testing, a TestAXNodeWrapper wraps an AXNode, implements // AXPlatformNodeDelegate, and owns an AXPlatformNode. class TestAXNodeWrapper : public AXPlatformNodeDelegateBase { public: // Create TestAXNodeWrapper instances on-demand from an AXTree and AXNode. static TestAXNodeWrapper* GetOrCreate(AXTree* tree, AXNode* node); // Set a global coordinate offset for testing. static void SetGlobalCoordinateOffset(const gfx::Vector2d& offset); // Get the last node which ShowContextMenu was called from for testing. static const AXNode* GetNodeFromLastShowContextMenu(); // Get the last node which AccessibilityPerformAction default action was // called from for testing. static const AXNode* GetNodeFromLastDefaultAction(); // Set the last node which AccessibilityPerformAction default action was // called for testing. static void SetNodeFromLastDefaultAction(AXNode* node); // Set a global scale factor for testing. static std::unique_ptr<base::AutoReset<float>> SetScaleFactor(float value); // Set a global indicating that AXPlatformNodeDelegates are for web content. static void SetGlobalIsWebContent(bool is_web_content); // When a hit test is called on |src_node_id|, return |dst_node_id| as // the result. static void SetHitTestResult(AXNodeID src_node_id, AXNodeID dst_node_id); // This is used to make sure global state doesn't persist across tests. static void ResetGlobalState(); ~TestAXNodeWrapper() override; AXPlatformNode* ax_platform_node() const { return platform_node_; } void set_minimized(bool minimized) { minimized_ = minimized; } // Test helpers. void BuildAllWrappers(AXTree* tree, AXNode* node); void ResetNativeEventTarget(); // AXPlatformNodeDelegate. const AXNodeData& GetData() const override; const AXTreeData& GetTreeData() const override; const AXTree::Selection GetUnignoredSelection() const override; AXNodePosition::AXPositionInstance CreatePositionAt( int offset, ax::mojom::TextAffinity affinity = ax::mojom::TextAffinity::kDownstream) const override; AXNodePosition::AXPositionInstance CreateTextPositionAt( int offset, ax::mojom::TextAffinity affinity = ax::mojom::TextAffinity::kDownstream) const override; gfx::NativeViewAccessible GetNativeViewAccessible() override; gfx::NativeViewAccessible GetParent() override; int GetChildCount() const override; gfx::NativeViewAccessible ChildAtIndex(int index) override; gfx::Rect GetBoundsRect(const AXCoordinateSystem coordinate_system, const AXClippingBehavior clipping_behavior, AXOffscreenResult* offscreen_result) const override; gfx::Rect GetInnerTextRangeBoundsRect( const int start_offset, const int end_offset, const AXCoordinateSystem coordinate_system, const AXClippingBehavior clipping_behavior, AXOffscreenResult* offscreen_result) const override; gfx::Rect GetHypertextRangeBoundsRect( const int start_offset, const int end_offset, const AXCoordinateSystem coordinate_system, const AXClippingBehavior clipping_behavior, AXOffscreenResult* offscreen_result) const override; gfx::NativeViewAccessible HitTestSync( int screen_physical_pixel_x, int screen_physical_pixel_y) const override; gfx::NativeViewAccessible GetFocus() const override; bool IsMinimized() const override; bool IsWebContent() const override; AXPlatformNode* GetFromNodeID(int32_t id) override; AXPlatformNode* GetFromTreeIDAndNodeID(const ui::AXTreeID& ax_tree_id, int32_t id) override; int GetIndexInParent() override; bool IsTable() const override; absl::optional<int> GetTableRowCount() const override; absl::optional<int> GetTableColCount() const override; absl::optional<int> GetTableAriaColCount() const override; absl::optional<int> GetTableAriaRowCount() const override; absl::optional<int> GetTableCellCount() const override; absl::optional<bool> GetTableHasColumnOrRowHeaderNode() const override; std::vector<int32_t> GetColHeaderNodeIds() const override; std::vector<int32_t> GetColHeaderNodeIds(int col_index) const override; std::vector<int32_t> GetRowHeaderNodeIds() const override; std::vector<int32_t> GetRowHeaderNodeIds(int row_index) const override; bool IsTableRow() const override; absl::optional<int> GetTableRowRowIndex() const override; bool IsTableCellOrHeader() const override; absl::optional<int> GetTableCellIndex() const override; absl::optional<int> GetTableCellColIndex() const override; absl::optional<int> GetTableCellRowIndex() const override; absl::optional<int> GetTableCellColSpan() const override; absl::optional<int> GetTableCellRowSpan() const override; absl::optional<int> GetTableCellAriaColIndex() const override; absl::optional<int> GetTableCellAriaRowIndex() const override; absl::optional<int32_t> GetCellId(int row_index, int col_index) const override; absl::optional<int32_t> CellIndexToId(int cell_index) const override; bool IsCellOrHeaderOfAriaGrid() const override; gfx::AcceleratedWidget GetTargetForNativeAccessibilityEvent() override; bool AccessibilityPerformAction(const AXActionData& data) override; std::u16string GetLocalizedRoleDescriptionForUnlabeledImage() const override; std::u16string GetLocalizedStringForLandmarkType() const override; std::u16string GetLocalizedStringForRoleDescription() const override; std::u16string GetLocalizedStringForImageAnnotationStatus( ax::mojom::ImageAnnotationStatus status) const override; std::u16string GetStyleNameAttributeAsLocalizedString() const override; bool ShouldIgnoreHoveredStateForTesting() override; const ui::AXUniqueId& GetUniqueId() const override; bool HasVisibleCaretOrSelection() const override; std::set<AXPlatformNode*> GetReverseRelations( ax::mojom::IntAttribute attr) override; std::set<AXPlatformNode*> GetReverseRelations( ax::mojom::IntListAttribute attr) override; bool IsOrderedSetItem() const override; bool IsOrderedSet() const override; absl::optional<int> GetPosInSet() const override; absl::optional<int> GetSetSize() const override; SkColor GetColor() const override; SkColor GetBackgroundColor() const override; const std::vector<gfx::NativeViewAccessible> GetUIADirectChildrenInRange( ui::AXPlatformNodeDelegate* start, ui::AXPlatformNodeDelegate* end) override; gfx::RectF GetLocation() const; int InternalChildCount() const; TestAXNodeWrapper* InternalGetChild(int index) const; private: TestAXNodeWrapper(AXTree* tree, AXNode* node); void ReplaceIntAttribute(int32_t node_id, ax::mojom::IntAttribute attribute, int32_t value); void ReplaceFloatAttribute(ax::mojom::FloatAttribute attribute, float value); void ReplaceBoolAttribute(ax::mojom::BoolAttribute attribute, bool value); void ReplaceStringAttribute(ax::mojom::StringAttribute attribute, std::string value); void ReplaceTreeDataTextSelection(int32_t anchor_node_id, int32_t anchor_offset, int32_t focus_node_id, int32_t focus_offset); TestAXNodeWrapper* HitTestSyncInternal(int x, int y); void UIADescendants( const AXNode* node, std::vector<gfx::NativeViewAccessible>* descendants) const; static bool ShouldHideChildrenForUIA(const AXNode* node); // Return the bounds of inline text in this node's coordinate system (which is // relative to its container node specified in AXRelativeBounds). gfx::RectF GetInlineTextRect(const int start_offset, const int end_offset) const; // Helper for determining if the two rects, including empty rects, intersect // each other. bool Intersects(gfx::RectF rect1, gfx::RectF rect2) const; // Determine the offscreen status of a particular element given its bounds. AXOffscreenResult DetermineOffscreenResult(gfx::RectF bounds) const; AXTree* tree_; AXNode* node_; ui::AXUniqueId unique_id_; AXPlatformNode* platform_node_; gfx::AcceleratedWidget native_event_target_; bool minimized_ = false; }; } // namespace ui #endif // UI_ACCESSIBILITY_PLATFORM_TEST_AX_NODE_WRAPPER_H_
blueboxd/chromium-legacy
chrome/browser/policy/messaging_layer/upload/dm_server_upload_service.h
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_POLICY_MESSAGING_LAYER_UPLOAD_DM_SERVER_UPLOAD_SERVICE_H_ #define CHROME_BROWSER_POLICY_MESSAGING_LAYER_UPLOAD_DM_SERVER_UPLOAD_SERVICE_H_ #include <memory> #include <vector> #include "base/sequence_checker.h" #include "base/task/post_task.h" #include "base/task/task_runner.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "components/policy/core/common/cloud/cloud_policy_client.h" #include "components/reporting/proto/synced/record.pb.h" #include "components/reporting/proto/synced/record_constants.pb.h" #include "components/reporting/util/status.h" #include "components/reporting/util/statusor.h" #include "components/reporting/util/task_runner_context.h" #include "net/base/backoff_entry.h" #if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/profiles/profile.h" #endif // BUILDFLAG(IS_CHROMEOS_ASH) namespace reporting { // DmServerUploadService uploads events to the DMServer. It does not manage // sequencing information, instead reporting the highest sequencing id for each // generation id and priority. // // DmServerUploadService relies on DmServerUploader for uploading. A // DmServerUploader is provided with RecordHandlers for each Destination. An // |EnqueueUpload| call creates a DmServerUploader and provides it with the // flags and records for upload and the result handlers. DmServerUploader uses // the RecordHandlers to upload each record. class DmServerUploadService { public: // ReportSuccessfulUploadCallback is used to pass server responses back to // the owner of |this| (the respone consists of sequencing information and // force_confirm flag). using ReportSuccessfulUploadCallback = base::OnceCallback<void(SequencingInformation, /*force_confirm*/ bool)>; // ReceivedEncryptionKeyCallback is called if server attached encryption key // to the response. using EncryptionKeyAttachedCallback = base::OnceCallback<void(SignedEncryptionInfo)>; // Successful response consists of Sequencing information that may be // accompanied with force_confirm flag. struct SuccessfulUploadResponse { SequencingInformation sequencing_information; bool force_confirm; }; using CompletionResponse = StatusOr<SuccessfulUploadResponse>; using CompletionCallback = base::OnceCallback<void(CompletionResponse)>; // Handles sending records to the server. class RecordHandler { public: virtual ~RecordHandler() = default; // Will iterate over |records| and ensure they are in ascending sequence // order, and within the same generation. Any out of order records will be // discarded. // |need_encryption_key| is set to `true` if the client needs to request // the encryption key from the server (either because it does not have it // or because the one it has is old and may be outdated). In that case // it is ok for |records| to be empty (otherwise at least one record must // be present). If response has the key info attached, it is decoded and // handed over to |encryption_key_attached_cb|. // Once the server has responded |upload_complete| is called with either the // highest accepted SequencingInformation, or an error detailing the failure // cause. // Any errors will result in |upload_complete| being called with a Status. virtual void HandleRecords( bool need_encryption_key, std::unique_ptr<std::vector<EncryptedRecord>> records, DmServerUploadService::CompletionCallback upload_complete, DmServerUploadService::EncryptionKeyAttachedCallback encryption_key_attached_cb) = 0; protected: explicit RecordHandler(policy::CloudPolicyClient* client); policy::CloudPolicyClient* GetClient() const { return client_; } private: policy::CloudPolicyClient* const client_; }; // Context runner for handling the upload of events passed to the // DmServerUploadService. Will process records by verifying that they are // parseable and sending them to the appropriate handler. class DmServerUploader : public TaskRunnerContext<CompletionResponse> { public: DmServerUploader( bool need_encryption_key, std::unique_ptr<std::vector<EncryptedRecord>> records, RecordHandler* handler, ReportSuccessfulUploadCallback report_success_upload_cb, EncryptionKeyAttachedCallback encryption_key_attached_cb, CompletionCallback completion_cb, scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner); private: ~DmServerUploader() override; // OnStart checks to ensure that our record set isn't empty, and requests // handler size status from |handlers_|. void OnStart() override; // ProcessRecords verifies that the records provided are parseable and sets // the |Record|s up for handling by the |RecordHandlers|s. On // completion, ProcessRecords |Schedule|s |HandleRecords|. void ProcessRecords(); // HandleRecords sends the records to the |record_handlers_|, allowing them // to upload to DmServer. void HandleRecords(); // Processes |completion_response| and call |Response|. void Finalize(CompletionResponse completion_response); // Complete schedules |Finalize| with the provided |completion_response|. void Complete(CompletionResponse completion_response); // Helper function for determining if an EncryptedRecord is valid. Status IsRecordValid(const EncryptedRecord& encrypted_record, const int64_t expected_generation_id, const int64_t expected_sequencing_id) const; const bool need_encryption_key_; std::unique_ptr<std::vector<EncryptedRecord>> encrypted_records_; ReportSuccessfulUploadCallback report_success_upload_cb_; EncryptionKeyAttachedCallback encryption_key_attached_cb_; RecordHandler* handler_; SEQUENCE_CHECKER(sequence_checker_); }; // Will asynchronously create a DMServerUploadService with handlers. // On successful completion will call |created_cb| with DMServerUploadService. // If |client| is null, will call |created_cb| with error::INVALID_ARGUMENT. // If any handlers fail to create, will call |created_cb| with // error::UNAVAILABLE. // // |report_upload_success_cb| should report back to the holder of the created // object whenever a record set is successfully uploaded. // |encryption_key_attached_cb| if called would update the encryption key with // the one received from the server. static void Create( policy::CloudPolicyClient* client, base::OnceCallback<void(StatusOr<std::unique_ptr<DmServerUploadService>>)> created_cb); ~DmServerUploadService(); Status EnqueueUpload( bool need_encryption_key, std::unique_ptr<std::vector<EncryptedRecord>> records, ReportSuccessfulUploadCallback report_upload_success_cb, EncryptionKeyAttachedCallback encryption_key_attached_cb); private: explicit DmServerUploadService(policy::CloudPolicyClient* client); static void InitRecordHandler( std::unique_ptr<DmServerUploadService> uploader, base::OnceCallback<void(StatusOr<std::unique_ptr<DmServerUploadService>>)> created_cb); policy::CloudPolicyClient* GetClient(); policy::CloudPolicyClient* client_; std::unique_ptr<RecordHandler> handler_; scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner_; }; } // namespace reporting #endif // CHROME_BROWSER_POLICY_MESSAGING_LAYER_UPLOAD_DM_SERVER_UPLOAD_SERVICE_H_
blueboxd/chromium-legacy
chromeos/components/eche_app_ui/apps_access_manager_impl.h
<reponame>blueboxd/chromium-legacy // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROMEOS_COMPONENTS_ECHE_APP_UI_APPS_ACCESS_MANAGER_IMPL_H_ #define CHROMEOS_COMPONENTS_ECHE_APP_UI_APPS_ACCESS_MANAGER_IMPL_H_ #include <ostream> #include "chromeos/components/eche_app_ui/apps_access_manager.h" #include "chromeos/components/eche_app_ui/eche_connector.h" #include "chromeos/components/eche_app_ui/eche_message_receiver.h" #include "chromeos/components/eche_app_ui/feature_status.h" #include "chromeos/components/eche_app_ui/feature_status_provider.h" class PrefRegistrySimple; class PrefService; namespace chromeos { namespace eche_app { // Implements AppsAccessManager by persisting the last-known // apps access value to user prefs. class AppsAccessManagerImpl : public AppsAccessManager, public EcheMessageReceiver::Observer, public FeatureStatusProvider::Observer { public: static void RegisterPrefs(PrefRegistrySimple* registry); explicit AppsAccessManagerImpl(EcheConnector* eche_connector, EcheMessageReceiver* message_receiver, FeatureStatusProvider* feature_status_provider, PrefService* pref_service); ~AppsAccessManagerImpl() override; // AppsAccessManager: AccessStatus GetAccessStatus() const override; void OnSetupRequested() override; private: friend class AppsAccessManagerImplTest; // EcheMessageReceiver::Observer: void OnGetAppsAccessStateResponseReceived( proto::GetAppsAccessStateResponse apps_access_state_response) override; void OnSendAppsSetupResponseReceived( proto::SendAppsSetupResponse apps_setup_response) override; void OnStatusChange(proto::StatusChangeType status_change_type) override {} // FeatureStatusProvider::Observer: void OnFeatureStatusChanged() override; void AttemptAppsAccessStateRequest(); void GetAppsAccessStateRequest(); void SendShowAppsAccessSetupRequest(); // Sets the internal AccessStatus but does not send a request for a new // status to the remote phone device. void SetAccessStatusInternal(AccessStatus access_status); AppsAccessManager::AccessStatus ComputeAppsAccessState( proto::AppsAccessState apps_access_state); FeatureStatus current_feature_status_; EcheConnector* eche_connector_; EcheMessageReceiver* message_receiver_; FeatureStatusProvider* feature_status_provider_; PrefService* pref_service_; bool initialized_ = false; }; } // namespace eche_app } // namespace chromeos #endif // CHROMEOS_COMPONENTS_ECHE_APP_UI_APPS_ACCESS_MANAGER_IMPL_H_
blueboxd/chromium-legacy
chrome/browser/android/autofill_assistant/ui_controller_android_utils.h
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_ANDROID_AUTOFILL_ASSISTANT_UI_CONTROLLER_ANDROID_UTILS_H_ #define CHROME_BROWSER_ANDROID_AUTOFILL_ASSISTANT_UI_CONTROLLER_ANDROID_UTILS_H_ #include <map> #include <string> #include <vector> #include "base/android/jni_android.h" #include "components/autofill_assistant/browser/autofill_assistant_tts_controller.h" #include "components/autofill_assistant/browser/bottom_sheet_state.h" #include "components/autofill_assistant/browser/service.pb.h" #include "components/autofill_assistant/browser/trigger_context.h" #include "components/autofill_assistant/browser/user_model.h" #include "components/autofill_assistant/browser/view_layout.pb.h" #include "content/public/browser/web_contents.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "url/gurl.h" namespace autofill_assistant { class Service; class ServiceRequestSender; class ClientAndroid; namespace ui_controller_android_utils { // Returns a 32-bit Integer representing |color_string| in Java, or null if // |color_string| is invalid. // TODO(806868): Get rid of this overload and always use GetJavaColor(proto). base::android::ScopedJavaLocalRef<jobject> GetJavaColor( JNIEnv* env, const std::string& color_string); // Returns a 32-bit Integer representing |proto| in Java, or null if // |proto| is invalid. base::android::ScopedJavaLocalRef<jobject> GetJavaColor( JNIEnv* env, const base::android::ScopedJavaLocalRef<jobject>& jcontext, const ColorProto& proto); // Returns the pixelsize of |proto| in |jcontext|, or |nullopt| if |proto| is // invalid. absl::optional<int> GetPixelSize( JNIEnv* env, const base::android::ScopedJavaLocalRef<jobject>& jcontext, const ClientDimensionProto& proto); // Returns the pixelsize of |proto| in |jcontext|, or |default_value| if |proto| // is invalid. int GetPixelSizeOrDefault( JNIEnv* env, const base::android::ScopedJavaLocalRef<jobject>& jcontext, const ClientDimensionProto& proto, int default_value); // Returns an instance of an |AssistantDrawable| or nullptr if it could not // be created. base::android::ScopedJavaLocalRef<jobject> CreateJavaDrawable( JNIEnv* env, const base::android::ScopedJavaLocalRef<jobject>& jcontext, const DrawableProto& proto, const UserModel* user_model = nullptr); // Returns the java equivalent of |proto|. base::android::ScopedJavaLocalRef<jobject> ToJavaValue(JNIEnv* env, const ValueProto& proto); // Returns the native equivalent of |jvalue|. Returns an empty ValueProto if // |jvalue| is null. ValueProto ToNativeValue(JNIEnv* env, const base::android::JavaParamRef<jobject>& jvalue); // Returns an instance of |AssistantInfoPopup| for |proto|. // close_display_str is used to provide a Close button when a button is not // configured in proto. base::android::ScopedJavaLocalRef<jobject> CreateJavaInfoPopup( JNIEnv* env, const InfoPopupProto& proto, const std::string& close_display_str); // Shows an instance of |AssistantInfoPopup| on the screen. void ShowJavaInfoPopup(JNIEnv* env, base::android::ScopedJavaLocalRef<jobject> jinfo_popup, base::android::ScopedJavaLocalRef<jobject> jcontext); // Converts a java string to native. Returns an empty string if input is null. std::string SafeConvertJavaStringToNative( JNIEnv* env, const base::android::JavaRef<jstring>& jstring); // Converts an optional native string to java. Returns null if the optional is // not present. base::android::ScopedJavaLocalRef<jstring> ConvertNativeOptionalStringToJava( JNIEnv* env, const absl::optional<std::string> optional_string); // Creates a BottomSheetState from the Android SheetState enum defined in // components/browser_ui/bottomsheet/BottomSheetController.java. BottomSheetState ToNativeBottomSheetState(int state); // Converts a BottomSheetState to the Android SheetState enum. int ToJavaBottomSheetState(BottomSheetState state); // Returns an instance of |AssistantChip| or nullptr if the chip type is // invalid. base::android::ScopedJavaLocalRef<jobject> CreateJavaAssistantChip( JNIEnv* env, const ChipProto& chip); // Returns a list of |AssistantChip| instances or nullptr if any of the chips // in |chips| has an invalid type. base::android::ScopedJavaLocalRef<jobject> CreateJavaAssistantChipList( JNIEnv* env, const std::vector<ChipProto>& chips); // Creates a std::map from an incoming set of Java string keys and values. std::map<std::string, std::string> CreateStringMapFromJava( JNIEnv* env, const base::android::JavaRef<jobjectArray>& keys, const base::android::JavaRef<jobjectArray>& values); // Creates a C++ trigger context for the specified java inputs. std::unique_ptr<TriggerContext> CreateTriggerContext( JNIEnv* env, content::WebContents* web_contents, const base::android::JavaRef<jstring>& jexperiment_ids, const base::android::JavaRef<jobjectArray>& jparameter_names, const base::android::JavaRef<jobjectArray>& jparameter_values, const base::android::JavaRef<jobjectArray>& jdevice_only_parameter_names, const base::android::JavaRef<jobjectArray>& jdevice_only_parameter_values, jboolean onboarding_shown, jboolean is_direct_action, const base::android::JavaRef<jstring>& jinitial_url); // Returns true if |web_contents| is owned by a custom tab. Assumes that // |web_contents| is valid and currently owned by a tab. bool IsCustomTab(content::WebContents* web_contents); // Returns the service to inject, if any, for |client_android|. This is used for // integration tests, which provide a test service to communicate with. std::unique_ptr<Service> GetServiceToInject(JNIEnv* env, ClientAndroid* client_android); // Returns the service request sender to inject, if any. This is used for // integration tests which provide a test service request sender to communicate // with. std::unique_ptr<ServiceRequestSender> GetServiceRequestSenderToInject( JNIEnv* env); // Returns the TTS controller to inject, if any. This is used for integration // tests which provide a test TTS controller. std::unique_ptr<AutofillAssistantTtsController> GetTtsControllerToInject( JNIEnv* env); } // namespace ui_controller_android_utils } // namespace autofill_assistant #endif // CHROME_BROWSER_ANDROID_AUTOFILL_ASSISTANT_UI_CONTROLLER_ANDROID_UTILS_H_
blueboxd/chromium-legacy
chrome/browser/ui/webui/about_ui.h
// 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 CHROME_BROWSER_UI_WEBUI_ABOUT_UI_H_ #define CHROME_BROWSER_UI_WEBUI_ABOUT_UI_H_ #include <string> #include "base/compiler_specific.h" #include "base/macros.h" #include "content/public/browser/url_data_source.h" #include "content/public/browser/web_ui_controller.h" class Profile; // We expose this class because the OOBE flow may need to explicitly add the // chrome://terms source outside of the normal flow. class AboutUIHTMLSource : public content::URLDataSource { public: // Construct a data source for the specified |source_name|. AboutUIHTMLSource(const std::string& source_name, Profile* profile); AboutUIHTMLSource(const AboutUIHTMLSource&) = delete; AboutUIHTMLSource& operator=(const AboutUIHTMLSource&) = delete; ~AboutUIHTMLSource() override; // content::URLDataSource implementation. std::string GetSource() override; void StartDataRequest( const GURL& url, const content::WebContents::Getter& wc_getter, content::URLDataSource::GotDataCallback callback) override; std::string GetMimeType(const std::string& path) override; bool ShouldAddContentSecurityPolicy() override; std::string GetAccessControlAllowOriginForOrigin( const std::string& origin) override; // Send the response data. void FinishDataRequest(const std::string& html, content::URLDataSource::GotDataCallback callback); Profile* profile() { return profile_; } private: std::string source_name_; Profile* profile_; }; class AboutUI : public content::WebUIController { public: explicit AboutUI(content::WebUI* web_ui, const std::string& host); AboutUI(const AboutUI&) = delete; AboutUI& operator=(const AboutUI&) = delete; ~AboutUI() override {} }; namespace about_ui { // Helper functions void AppendHeader(std::string* output, const std::string& unescaped_title); void AppendBody(std::string *output); void AppendFooter(std::string *output); } // namespace about_ui #endif // CHROME_BROWSER_UI_WEBUI_ABOUT_UI_H_
blueboxd/chromium-legacy
ash/wm/desks/templates/desks_templates_dialog_controller.h
<reponame>blueboxd/chromium-legacy // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_WM_DESKS_TEMPLATES_DESKS_TEMPLATES_DIALOG_CONTROLLER_H_ #define ASH_WM_DESKS_TEMPLATES_DESKS_TEMPLATES_DIALOG_CONTROLLER_H_ #include "ash/ash_export.h" #include "base/scoped_observation.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_observer.h" namespace aura { class Window; } namespace ash { class DesksTemplatesDialog; // DesksTemplatesDialogController controls when to show the various confirmation // dialogs for modifying desk templates. class ASH_EXPORT DesksTemplatesDialogController : public views::WidgetObserver { public: DesksTemplatesDialogController(); DesksTemplatesDialogController(const DesksTemplatesDialogController&) = delete; DesksTemplatesDialogController& operator=( const DesksTemplatesDialogController&) = delete; ~DesksTemplatesDialogController() override; // Convenience function to get the controller instance, which is created and // owned by OverviewSession. static DesksTemplatesDialogController* Get(); const views::Widget* dialog_widget() const { return dialog_widget_; } // Shows the dialog. The dialog will look slightly different depending on the // type. The `template_name` is used for the replace and delete dialogs, which // show the name of the template which will be replaced and deleted in the // dialog description. void ShowUnsupportedAppsDialog(aura::Window* root_window); void ShowReplaceDialog(aura::Window* root_window, const std::u16string& template_name); void ShowDeleteDialog(aura::Window* root_window, const std::u16string& template_name); // views::WidgetObserver: void OnWidgetDestroying(views::Widget* widget) override; private: // Creates and shows the dialog on `root_window`. void CreateDialogWidget(std::unique_ptr<DesksTemplatesDialog> dialog, aura::Window* root_window); // Pointer to the widget (if any) that contains the current dialog. views::Widget* dialog_widget_ = nullptr; base::ScopedObservation<views::Widget, views::WidgetObserver> dialog_widget_observation_{this}; }; } // namespace ash #endif // ASH_WM_DESKS_TEMPLATES_DESKS_TEMPLATES_DIALOG_CONTROLLER_H_
blueboxd/chromium-legacy
ash/system/message_center/message_center_scroll_bar.h
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_SYSTEM_MESSAGE_CENTER_MESSAGE_CENTER_SCROLL_BAR_H_ #define ASH_SYSTEM_MESSAGE_CENTER_MESSAGE_CENTER_SCROLL_BAR_H_ #include "ash/public/cpp/presentation_time_recorder.h" #include "ui/events/event.h" #include "ui/views/controls/scrollbar/overlay_scroll_bar.h" namespace ash { class PresentationTimeRecorder; // The scroll bar for message center. This is basically views::OverlayScrollBar // but also records the metrics for the type of scrolling (only the first event // after the message center opens is recorded) and scrolling performance. class MessageCenterScrollBar : public views::OverlayScrollBar { public: class Observer { public: // Called when scroll event is triggered. virtual void OnMessageCenterScrolled() = 0; virtual ~Observer() = default; }; // |observer| can be null. explicit MessageCenterScrollBar(Observer* observer); MessageCenterScrollBar(const MessageCenterScrollBar&) = delete; MessageCenterScrollBar& operator=(const MessageCenterScrollBar&) = delete; ~MessageCenterScrollBar() override; // views::ScrollBar: bool OverlapsContent() const override; private: // View: bool OnKeyPressed(const ui::KeyEvent& event) override; bool OnMouseWheel(const ui::MouseWheelEvent& event) override; const char* GetClassName() const override; // ui::EventHandler: void OnGestureEvent(ui::GestureEvent* event) override; // views::ScrollDelegate: bool OnScroll(float dx, float dy) override; // False if no event is recorded yet. True if the first event is recorded. bool stats_recorded_ = false; Observer* const observer_; // Presentation time recorder for scrolling through notification list. std::unique_ptr<PresentationTimeRecorder> presentation_time_recorder_; }; } // namespace ash #endif // ASH_SYSTEM_MESSAGE_CENTER_MESSAGE_CENTER_SCROLL_BAR_H_
blueboxd/chromium-legacy
components/viz/common/quads/shared_element_draw_quad.h
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_VIZ_COMMON_QUADS_SHARED_ELEMENT_DRAW_QUAD_H_ #define COMPONENTS_VIZ_COMMON_QUADS_SHARED_ELEMENT_DRAW_QUAD_H_ #include "components/viz/common/quads/draw_quad.h" #include "components/viz/common/shared_element_resource_id.h" #include "components/viz/common/viz_common_export.h" namespace viz { class VIZ_COMMON_EXPORT SharedElementDrawQuad : public DrawQuad { public: SharedElementDrawQuad(); SharedElementDrawQuad(const SharedElementDrawQuad& other); ~SharedElementDrawQuad() override; SharedElementDrawQuad& operator=(const SharedElementDrawQuad& other); void SetNew(const SharedQuadState* shared_quad_state, const gfx::Rect& rect, const gfx::Rect& visible_rect, const SharedElementResourceId& resource_id); void SetAll(const SharedQuadState* shared_quad_state, const gfx::Rect& rect, const gfx::Rect& visible_rect, bool needs_blending, const SharedElementResourceId& resource_id); SharedElementResourceId resource_id; static const SharedElementDrawQuad* MaterialCast(const DrawQuad* quad); private: void ExtendValue(base::trace_event::TracedValue* value) const override; }; } // namespace viz #endif // COMPONENTS_VIZ_COMMON_QUADS_SHARED_ELEMENT_DRAW_QUAD_H_
blueboxd/chromium-legacy
media/base/media_switches.h
// 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. // Defines all the "media" command-line switches. #ifndef MEDIA_BASE_MEDIA_SWITCHES_H_ #define MEDIA_BASE_MEDIA_SWITCHES_H_ #include <string> #include "base/feature_list.h" #include "base/metrics/field_trial_params.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "media/base/media_export.h" #include "media/media_buildflags.h" namespace base { class CommandLine; } namespace switches { MEDIA_EXPORT extern const char kAudioBufferSize[]; MEDIA_EXPORT extern const char kAudioServiceQuitTimeoutMs[]; MEDIA_EXPORT extern const char kAutoplayPolicy[]; MEDIA_EXPORT extern const char kDisableAudioOutput[]; MEDIA_EXPORT extern const char kFailAudioStreamCreation[]; MEDIA_EXPORT extern const char kVideoThreads[]; MEDIA_EXPORT extern const char kDisableBackgroundMediaSuspend[]; MEDIA_EXPORT extern const char kReportVp9AsAnUnsupportedMimeType[]; #if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_FREEBSD) || \ defined(OS_SOLARIS) MEDIA_EXPORT extern const char kAlsaInputDevice[]; MEDIA_EXPORT extern const char kAlsaOutputDevice[]; #endif #if defined(OS_WIN) MEDIA_EXPORT extern const char kEnableExclusiveAudio[]; MEDIA_EXPORT extern const char kForceWaveAudio[]; MEDIA_EXPORT extern const char kTrySupportedChannelLayouts[]; MEDIA_EXPORT extern const char kWaveOutBuffers[]; #endif #if defined(OS_FUCHSIA) MEDIA_EXPORT extern const char kEnableProtectedVideoBuffers[]; MEDIA_EXPORT extern const char kForceProtectedVideoOutputBuffers[]; MEDIA_EXPORT extern const char kDisableAudioInput[]; MEDIA_EXPORT extern const char kUseOverlaysForVideo[]; #endif #if defined(USE_CRAS) MEDIA_EXPORT extern const char kUseCras[]; #endif MEDIA_EXPORT extern const char kUnsafelyAllowProtectedMediaIdentifierForDomain[]; MEDIA_EXPORT extern const char kUseFakeDeviceForMediaStream[]; MEDIA_EXPORT extern const char kUseFileForFakeVideoCapture[]; MEDIA_EXPORT extern const char kUseFileForFakeAudioCapture[]; MEDIA_EXPORT extern const char kUseFakeMjpegDecodeAccelerator[]; MEDIA_EXPORT extern const char kDisableAcceleratedMjpegDecode[]; MEDIA_EXPORT extern const char kRequireAudioHardwareForTesting[]; MEDIA_EXPORT extern const char kMuteAudio[]; MEDIA_EXPORT extern const char kVideoUnderflowThresholdMs[]; MEDIA_EXPORT extern const char kDisableRTCSmoothnessAlgorithm[]; MEDIA_EXPORT extern const char kForceVideoOverlays[]; MEDIA_EXPORT extern const char kMSEAudioBufferSizeLimitMb[]; MEDIA_EXPORT extern const char kMSEVideoBufferSizeLimitMb[]; MEDIA_EXPORT extern const char kClearKeyCdmPathForTesting[]; MEDIA_EXPORT extern const char kOverrideEnabledCdmInterfaceVersion[]; MEDIA_EXPORT extern const char kOverrideHardwareSecureCodecsForTesting[]; MEDIA_EXPORT extern const char kEnableLiveCaptionPrefForTesting[]; #if BUILDFLAG(ENABLE_PLATFORM_HEVC) MEDIA_EXPORT extern const char kEnableClearHevcForTesting[]; #endif #if defined(OS_CHROMEOS) MEDIA_EXPORT extern const char kLacrosEnablePlatformEncryptedHevc[]; MEDIA_EXPORT extern const char kLacrosEnablePlatformHevc[]; MEDIA_EXPORT extern const char kLacrosUseChromeosProtectedMedia[]; MEDIA_EXPORT extern const char kLacrosUseChromeosProtectedAv1[]; #endif // defined(OS_CHROMEOS) namespace autoplay { MEDIA_EXPORT extern const char kDocumentUserActivationRequiredPolicy[]; MEDIA_EXPORT extern const char kNoUserGestureRequiredPolicy[]; MEDIA_EXPORT extern const char kUserGestureRequiredPolicy[]; } // namespace autoplay #if BUILDFLAG(USE_CHROMEOS_MEDIA_ACCELERATION) MEDIA_EXPORT extern const char kHardwareVideoDecodeFrameRate[]; #endif } // namespace switches namespace media { // All features in alphabetical order. The features should be documented // alongside the definition of their values in the .cc file. MEDIA_EXPORT extern const base::Feature kAudioFocusDuckFlash; MEDIA_EXPORT extern const base::Feature kAudioFocusLossSuspendMediaSession; MEDIA_EXPORT extern const base::Feature kAutoplayIgnoreWebAudio; MEDIA_EXPORT extern const base::Feature kAutoplayDisableSettings; MEDIA_EXPORT extern const base::Feature kBackgroundVideoPauseOptimization; MEDIA_EXPORT extern const base::Feature kBresenhamCadence; MEDIA_EXPORT extern const base::Feature kCdmHostVerification; MEDIA_EXPORT extern const base::Feature kCdmProcessSiteIsolation; MEDIA_EXPORT extern const base::Feature kD3D11PrintCodecOnCrash; MEDIA_EXPORT extern const base::Feature kD3D11VideoDecoder; MEDIA_EXPORT extern const base::Feature kD3D11VideoDecoderIgnoreWorkarounds; MEDIA_EXPORT extern const base::Feature kD3D11VideoDecoderVP9Profile2; MEDIA_EXPORT extern const base::Feature kD3D11VideoDecoderAV1; MEDIA_EXPORT extern const base::Feature kD3D11VideoDecoderUseSharedHandle; MEDIA_EXPORT extern const base::Feature kEnableMediaInternals; MEDIA_EXPORT extern const base::Feature kEnableTabMuting; MEDIA_EXPORT extern const base::Feature kExposeSwDecodersToWebRTC; MEDIA_EXPORT extern const base::Feature kExternalClearKeyForTesting; MEDIA_EXPORT extern const base::Feature kFFmpegDecodeOpaqueVP8; MEDIA_EXPORT extern const base::Feature kFailUrlProvisionFetcherForTesting; MEDIA_EXPORT extern const base::Feature kFallbackAfterDecodeError; MEDIA_EXPORT extern const base::Feature kGav1VideoDecoder; MEDIA_EXPORT extern const base::Feature kGlobalMediaControls; MEDIA_EXPORT extern const base::Feature kGlobalMediaControlsAutoDismiss; MEDIA_EXPORT extern const base::Feature kGlobalMediaControlsForCast; MEDIA_EXPORT extern const base::Feature kGlobalMediaControlsForChromeOS; MEDIA_EXPORT extern const base::Feature kGlobalMediaControlsPictureInPicture; MEDIA_EXPORT extern const base::Feature kGlobalMediaControlsSeamlessTransfer; MEDIA_EXPORT extern const base::Feature kGlobalMediaControlsModernUI; MEDIA_EXPORT extern const base::Feature kHardwareMediaKeyHandling; MEDIA_EXPORT extern const base::Feature kHardwareSecureDecryption; MEDIA_EXPORT extern const base::Feature kInternalMediaSession; MEDIA_EXPORT extern const base::Feature kKeepRvfcFrameAlive; MEDIA_EXPORT extern const base::Feature kKeyPressMonitoring; MEDIA_EXPORT extern const base::Feature kLiveCaption; MEDIA_EXPORT extern const base::Feature kLiveCaptionMultiLanguage; MEDIA_EXPORT extern const base::Feature kLiveCaptionSystemWideOnChromeOS; MEDIA_EXPORT extern const base::Feature kLowDelayVideoRenderingOnLiveStream; MEDIA_EXPORT extern const base::Feature kMediaCapabilitiesQueryGpuFactories; MEDIA_EXPORT extern const base::Feature kMediaCapabilitiesWithParameters; MEDIA_EXPORT extern const base::Feature kMediaCastOverlayButton; MEDIA_EXPORT extern const base::Feature kMediaEngagementBypassAutoplayPolicies; MEDIA_EXPORT extern const base::Feature kMediaEngagementHTTPSOnly; MEDIA_EXPORT extern const base::Feature kMediaLearningExperiment; MEDIA_EXPORT extern const base::Feature kMediaLearningFramework; MEDIA_EXPORT extern const base::Feature kMediaLearningSmoothnessExperiment; MEDIA_EXPORT extern const base::Feature kMediaOptimizer; MEDIA_EXPORT extern const base::Feature kMediaPowerExperiment; MEDIA_EXPORT extern const base::Feature kMediaSessionWebRTC; MEDIA_EXPORT extern const base::Feature kMemoryPressureBasedSourceBufferGC; MEDIA_EXPORT extern const base::Feature kMultiPlaneVideoCaptureSharedImages; MEDIA_EXPORT extern const base::Feature kOverlayFullscreenVideo; MEDIA_EXPORT extern const base::Feature kPictureInPicture; MEDIA_EXPORT extern const base::Feature kPlaybackSpeedButton; MEDIA_EXPORT extern const base::Feature kPreloadMediaEngagementData; MEDIA_EXPORT extern const base::Feature kPreloadMetadataLazyLoad; MEDIA_EXPORT extern const base::Feature kPreloadMetadataSuspend; MEDIA_EXPORT extern const base::Feature kRecordMediaEngagementScores; MEDIA_EXPORT extern const base::Feature kRecordWebAudioEngagement; MEDIA_EXPORT extern const base::Feature kResumeBackgroundVideo; MEDIA_EXPORT extern const base::Feature kReuseMediaPlayer; MEDIA_EXPORT extern const base::Feature kRevokeMediaSourceObjectURLOnAttach; MEDIA_EXPORT extern const base::Feature kSpeakerChangeDetection; MEDIA_EXPORT extern const base::Feature kSpecCompliantCanPlayThrough; MEDIA_EXPORT extern const base::Feature kSurfaceLayerForMediaStreams; MEDIA_EXPORT extern const base::Feature kSuspendMutedAudio; MEDIA_EXPORT extern const base::Feature kUnifiedAutoplay; MEDIA_EXPORT extern const base::Feature kUseAndroidOverlayForSecureOnly; MEDIA_EXPORT extern const base::Feature kUseDecoderStreamForWebRTC; MEDIA_EXPORT extern const base::Feature kUseFakeDeviceForMediaStream; MEDIA_EXPORT extern const base::Feature kUseMediaHistoryStore; MEDIA_EXPORT extern const base::Feature kUseR16Texture; MEDIA_EXPORT extern const base::Feature kUseSodaForLiveCaption; #if defined(OS_LINUX) MEDIA_EXPORT extern const base::Feature kVaapiVideoDecodeLinux; MEDIA_EXPORT extern const base::Feature kVaapiVideoEncodeLinux; #endif // defined(OS_LINUX) MEDIA_EXPORT extern const base::Feature kVaapiAV1Decoder; MEDIA_EXPORT extern const base::Feature kVaapiLowPowerEncoderGen9x; MEDIA_EXPORT extern const base::Feature kVaapiEnforceVideoMinMaxResolution; MEDIA_EXPORT extern const base::Feature kVaapiVideoMinResolutionForPerformance; MEDIA_EXPORT extern const base::Feature kVaapiVP8Encoder; MEDIA_EXPORT extern const base::Feature kVaapiVP9Encoder; #if defined(ARCH_CPU_X86_FAMILY) && BUILDFLAG(IS_CHROMEOS_ASH) MEDIA_EXPORT extern const base::Feature kVaapiH264TemporalLayerHWEncoding; MEDIA_EXPORT extern const base::Feature kVaapiVp9kSVCHWDecoding; MEDIA_EXPORT extern const base::Feature kVaapiVp9kSVCHWEncoding; #endif // defined(ARCH_CPU_X86_FAMILY) && BUILDFLAG(IS_CHROMEOS_ASH) MEDIA_EXPORT extern const base::Feature kVideoBlitColorAccuracy; MEDIA_EXPORT extern const base::Feature kWakeLockOptimisationHiddenMuted; MEDIA_EXPORT extern const base::Feature kResolutionBasedDecoderPriority; MEDIA_EXPORT extern const base::Feature kForceHardwareVideoDecoders; MEDIA_EXPORT extern const base::Feature kForceHardwareAudioDecoders; #if defined(OS_ANDROID) MEDIA_EXPORT extern const base::Feature kAllowNonSecureOverlays; MEDIA_EXPORT extern const base::Feature kMediaControlsExpandGesture; MEDIA_EXPORT extern const base::Feature kMediaDrmPersistentLicense; MEDIA_EXPORT extern const base::Feature kMediaDrmPreprovisioning; MEDIA_EXPORT extern const base::Feature kMediaDrmPreprovisioningAtStartup; MEDIA_EXPORT extern const base::Feature kCanPlayHls; MEDIA_EXPORT extern const base::Feature kPictureInPictureAPI; MEDIA_EXPORT extern const base::Feature kHlsPlayer; MEDIA_EXPORT extern const base::Feature kRequestSystemAudioFocus; MEDIA_EXPORT extern const base::Feature kUseAudioLatencyFromHAL; MEDIA_EXPORT extern const base::Feature kUsePooledSharedImageVideoProvider; MEDIA_EXPORT extern const base::Feature kUseRealColorSpaceForAndroidVideo; #endif // defined(OS_ANDROID) #if defined(OS_CHROMEOS) && BUILDFLAG(USE_CHROMEOS_MEDIA_ACCELERATION) MEDIA_EXPORT extern const base::Feature kUseChromeOSDirectVideoDecoder; MEDIA_EXPORT extern const base::Feature kUseAlternateVideoDecoderImplementation; #endif // defined(OS_CHROMEOS) && BUILDFLAG(USE_CHROMEOS_MEDIA_ACCELERATION) #if defined(OS_MAC) MEDIA_EXPORT extern const base::Feature kMultiPlaneVideoToolboxSharedImages; #endif #if defined(OS_WIN) MEDIA_EXPORT extern const base::Feature kDelayCopyNV12Textures; MEDIA_EXPORT extern const base::Feature kDirectShowGetPhotoState; MEDIA_EXPORT extern const base::Feature kIncludeIRCamerasInDeviceEnumeration; MEDIA_EXPORT extern const base::Feature kMediaFoundationAV1Decoding; MEDIA_EXPORT extern const base::Feature kMediaFoundationAV1Encoding; MEDIA_EXPORT extern const base::Feature kMediaFoundationVideoCapture; MEDIA_EXPORT extern const base::Feature kMediaFoundationVP8Decoding; MEDIA_EXPORT extern const base::Feature kMediaFoundationD3D11VideoCapture; MEDIA_EXPORT extern const base::Feature kWasapiRawAudioCapture; #endif // defined(OS_WIN) #if defined(OS_CHROMEOS) MEDIA_EXPORT extern const base::Feature kDeprecateLowUsageCodecs; #endif // Based on a |command_line| and the current platform, returns the effective // autoplay policy. In other words, it will take into account the default policy // if none is specified via the command line and options passed for testing. // Returns one of the possible autoplay policy switches from the // switches::autoplay namespace. MEDIA_EXPORT std::string GetEffectiveAutoplayPolicy( const base::CommandLine& command_line); MEDIA_EXPORT bool IsVideoCaptureAcceleratedJpegDecodingEnabled(); MEDIA_EXPORT bool IsLiveCaptionFeatureEnabled(); enum class kCrosGlobalMediaControlsPinOptions { kPin, kNotPin, kHeuristic, }; // Feature param used to force default pin/unpin for global media controls in // CrOS. MEDIA_EXPORT extern const base::FeatureParam<kCrosGlobalMediaControlsPinOptions> kCrosGlobalMediaControlsPinParam; } // namespace media #endif // MEDIA_BASE_MEDIA_SWITCHES_H_
blueboxd/chromium-legacy
services/device/generic_sensor/platform_sensor.h
<filename>services/device/generic_sensor/platform_sensor.h // 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 SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_H_ #define SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_H_ #include <list> #include <map> #include <memory> #include "base/callback_forward.h" #include "base/location.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/synchronization/lock.h" #include "base/task/sequenced_task_runner.h" #include "base/thread_annotations.h" #include "mojo/public/cpp/system/buffer.h" #include "services/device/public/cpp/generic_sensor/sensor_reading.h" #include "services/device/public/mojom/sensor.mojom.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace device { class PlatformSensorProvider; class PlatformSensorConfiguration; // Base class for the sensors provided by the platform. Concrete instances of // this class are created by platform specific PlatformSensorProvider. class PlatformSensor : public base::RefCountedThreadSafe<PlatformSensor> { public: // The interface that must be implemented by PlatformSensor clients. class Client { public: virtual void OnSensorReadingChanged(mojom::SensorType type) = 0; virtual void OnSensorError() = 0; virtual bool IsSuspended() = 0; protected: virtual ~Client() {} }; virtual mojom::ReportingMode GetReportingMode() = 0; virtual PlatformSensorConfiguration GetDefaultConfiguration() = 0; virtual bool CheckSensorConfiguration( const PlatformSensorConfiguration& configuration) = 0; // Can be overridden to return the sensor maximum sampling frequency // value obtained from the platform if it is available. If platform // does not provide maximum sampling frequency this method must // return default frequency. // The default implementation returns default frequency. virtual double GetMaximumSupportedFrequency(); // Can be overridden to return the sensor minimum sampling frequency. // The default implementation returns '1.0 / (60 * 60)', i.e. once per hour. virtual double GetMinimumSupportedFrequency(); // Can be overridden to reset this sensor by the PlatformSensorProvider. virtual void SensorReplaced(); mojom::SensorType GetType() const; bool StartListening(Client* client, const PlatformSensorConfiguration& config); bool StopListening(Client* client, const PlatformSensorConfiguration& config); // Stops all the configurations tied to the |client|, but the |client| still // gets notification. bool StopListening(Client* client); void UpdateSensor(); void AddClient(Client*); void RemoveClient(Client*); bool GetLatestReading(SensorReading* result); // Return the last raw (i.e. unrounded) sensor reading. bool GetLatestRawReading(SensorReading* result) const; // Returns 'true' if the sensor is started; returns 'false' otherwise. bool IsActiveForTesting() const; using ConfigMap = std::map<Client*, std::list<PlatformSensorConfiguration>>; const ConfigMap& GetConfigMapForTesting() const; // Called by API users to post a task on |main_task_runner_| when run from a // different sequence. void PostTaskToMainSequence(const base::Location& location, base::OnceClosure task); protected: virtual ~PlatformSensor(); PlatformSensor(mojom::SensorType type, SensorReadingSharedBuffer* reading_buffer, PlatformSensorProvider* provider); using ReadingBuffer = SensorReadingSharedBuffer; virtual bool UpdateSensorInternal(const ConfigMap& configurations); virtual bool StartSensor( const PlatformSensorConfiguration& configuration) = 0; virtual void StopSensor() = 0; // Updates the shared buffer with new sensor reading data and posts a task to // invoke NotifySensorReadingChanged() on |main_task_runner_|. // Note: this method is thread-safe. void UpdateSharedBufferAndNotifyClients(const SensorReading& reading); void NotifySensorReadingChanged(); void NotifySensorError(); void ResetReadingBuffer(); // Returns the task runner where this object has been created. Subclasses can // use it to post tasks to the right sequence when running on a different task // runner. scoped_refptr<base::SequencedTaskRunner> main_task_runner() const { return main_task_runner_; } base::ObserverList<Client, true>::Unchecked clients_; private: friend class base::RefCountedThreadSafe<PlatformSensor>; // Updates shared buffer with provided SensorReading // Note: this method is thread-safe. void UpdateSharedBuffer(const SensorReading& reading); scoped_refptr<base::SequencedTaskRunner> main_task_runner_; SensorReadingSharedBuffer* reading_buffer_; // NOTE: Owned by |provider_|. mojom::SensorType type_; ConfigMap config_map_; PlatformSensorProvider* provider_; bool is_active_ = false; absl::optional<SensorReading> last_raw_reading_ GUARDED_BY(lock_); mutable base::Lock lock_; // Protect last_raw_reading_. base::WeakPtrFactory<PlatformSensor> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PlatformSensor); }; } // namespace device #endif // SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_H_
blueboxd/chromium-legacy
chrome/browser/ui/ash/projector/projector_app_client_impl.h
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_ASH_PROJECTOR_PROJECTOR_APP_CLIENT_IMPL_H_ #define CHROME_BROWSER_UI_ASH_PROJECTOR_PROJECTOR_APP_CLIENT_IMPL_H_ #include "ash/webui/projector_app/projector_app_client.h" #include "base/observer_list.h" namespace network { namespace mojom { class URLLoaderFactory; } } // namespace network namespace user_prefs { class PrefRegistrySyncable; } // namespace user_prefs // Implements the interface for Projector App. class ProjectorAppClientImpl : public chromeos::ProjectorAppClient { public: static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry); ProjectorAppClientImpl(); ProjectorAppClientImpl(const ProjectorAppClientImpl&) = delete; ProjectorAppClientImpl& operator=(const ProjectorAppClientImpl&) = delete; ~ProjectorAppClientImpl() override; // chromeos::ProjectorAppClient: void AddObserver(Observer* observer) override; void RemoveObserver(Observer* observer) override; signin::IdentityManager* GetIdentityManager() override; network::mojom::URLLoaderFactory* GetUrlLoaderFactory() override; void OnNewScreencastPreconditionChanged(bool can_start) override; private: base::ObserverList<Observer> observers_; }; #endif // CHROME_BROWSER_UI_ASH_PROJECTOR_PROJECTOR_APP_CLIENT_IMPL_H_
blueboxd/chromium-legacy
ash/app_list/views/app_list_folder_view.h
// 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 ASH_APP_LIST_VIEWS_APP_LIST_FOLDER_VIEW_H_ #define ASH_APP_LIST_VIEWS_APP_LIST_FOLDER_VIEW_H_ #include <memory> #include <string> #include <vector> #include "ash/app_list/model/app_list_item_list_observer.h" #include "ash/app_list/views/apps_grid_view.h" #include "ash/app_list/views/apps_grid_view_folder_delegate.h" #include "ash/app_list/views/folder_header_view.h" #include "ash/app_list/views/folder_header_view_delegate.h" #include "ash/app_list/views/paged_apps_grid_view.h" #include "base/memory/weak_ptr.h" #include "base/scoped_observation.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/compositor/throughput_tracker.h" #include "ui/views/controls/button/button.h" #include "ui/views/view.h" namespace ash { class AppListA11yAnnouncer; class AppListFolderController; class AppListFolderItem; class AppListItemView; class AppListModel; class AppListViewDelegate; class AppsContainerView; class AppsGridView; class FolderHeaderView; class PageSwitcher; class ScrollViewGradientHelper; // Displays folder contents via an AppsGridView. App items can be dragged out // of the folder to the main apps grid. class ASH_EXPORT AppListFolderView : public views::View, public FolderHeaderViewDelegate, public AppListModelObserver, public views::ViewObserver, public AppsGridViewFolderDelegate, public PagedAppsGridView::ContainerDelegate { public: METADATA_HEADER(AppListFolderView); // The maximum number of columns a folder can have. static constexpr int kMaxFolderColumns = 4; // When using paged folder item grid, the maximum number of rows a folder // items grid can have. static constexpr int kMaxPagedFolderRows = 4; AppListFolderView(AppListFolderController* folder_controller, AppsGridView* root_apps_grid_view, AppListModel* model, ContentsView* contents_view, AppListA11yAnnouncer* a11y_announcer, AppListViewDelegate* view_delegate); AppListFolderView(const AppListFolderView&) = delete; AppListFolderView& operator=(const AppListFolderView&) = delete; ~AppListFolderView() override; // An interface for the folder opening and closing animations. class Animation { public: virtual ~Animation() = default; // `completion_callback` is an optional callback to be run when the // animation completes. Not run if the animation gets reset before // completion. virtual void ScheduleAnimation(base::OnceClosure completion_callback) = 0; virtual bool IsAnimationRunning() = 0; }; // Sets the `AppListConfig` that should be used to configure app list item // size within the folder items grid. void UpdateAppListConfig(const AppListConfig* config); // Configures AppListFolderView to show the contents for the folder item // associated with `folder_item_view`. The folder view will be anchored at // `folder_item_view`. void ConfigureForFolderItemView(AppListItemView* folder_item_view); // Schedules an animation to show or hide the view. // If |show| is false, the view should be set to invisible after the // animation is done unless |hide_for_reparent| is true. void ScheduleShowHideAnimation(bool show, bool hide_for_reparent); // Hides the view immediately without animation. void HideViewImmediately(); // Prepares folder item grid for closing the folder - it ends any in-progress // drag, and clears any selected view. void ResetItemsGridForClose(); // Closes the folder page and goes back the top level page. void CloseFolderPage(); // Focuses the first app item. Does not set the selection or perform a11y // announce if `silently` is true. void FocusFirstItem(bool silently); // views::View void Layout() override; void ChildPreferredSizeChanged(View* child) override; void GetAccessibleNodeData(ui::AXNodeData* node_data) override; // AppListModelObserver void OnAppListItemWillBeDeleted(AppListItem* item) override; // Updates preferred bounds of this view based on the activated folder item // icon's bounds. void UpdatePreferredBounds(); // Returns the Y-offset that would move a folder out from under a visible // Virtual keyboard int GetYOffsetForFolder(); // Returns true if this view's child views are in animation for opening or // closing the folder. bool IsAnimationRunning() const; // Sets the bounding box for the folder view bounds. The bounds are expected // to be in the parent view's coordinate system. void SetBoundingBox(const gfx::Rect& bounding_box); AppsGridView* items_grid_view() { return items_grid_view_; } FolderHeaderView* folder_header_view() { return folder_header_view_; } views::View* background_view() { return background_view_; } views::View* contents_container() { return contents_container_; } const AppListFolderItem* folder_item() const { return folder_item_; } const gfx::Rect& folder_item_icon_bounds() const { return folder_item_icon_bounds_; } const gfx::Rect& preferred_bounds() const { return preferred_bounds_; } // Records the smoothness of folder show/hide animations mixed with the // BackgroundAnimation, FolderItemTitleAnimation, TopIconAnimation, and // ContentsContainerAnimation. void RecordAnimationSmoothness(); // Called when tablet mode starts and ends. void OnTabletModeChanged(bool started); // views::View: void OnScrollEvent(ui::ScrollEvent* event) override; void OnMouseEvent(ui::MouseEvent* event) override; // Overridden from FolderHeaderViewDelegate: void SetItemName(AppListFolderItem* item, const std::string& name) override; // Overridden from AppsGridViewFolderDelegate: void ReparentItem(AppListItemView* original_drag_view, const gfx::Point& drag_point_in_folder_grid) override; void DispatchDragEventForReparent( AppsGridView::Pointer pointer, const gfx::Point& drag_point_in_folder_grid) override; void DispatchEndDragEventForReparent( bool events_forwarded_to_drag_drop_host, bool cancel_drag, std::unique_ptr<AppDragIconProxy> drag_icon_proxy) override; bool IsDragPointOutsideOfFolder(const gfx::Point& drag_point) override; bool IsOEMFolder() const override; void HandleKeyboardReparent(AppListItemView* reparented_view, ui::KeyboardCode key_code) override; // PagedAppsGridView::ContainerDelegate: bool IsPointWithinPageFlipBuffer(const gfx::Point& point) const override; bool IsPointWithinBottomDragBuffer(const gfx::Point& point, int page_flip_zone_size) const override; const AppListConfig* GetAppListConfig() const; views::ScrollView* scroll_view_for_test() { return scroll_view_; } private: // Creates an apps grid view with fixed-size pages. void CreatePagedAppsGrid(ContentsView* contents_view); // Creates a vertically scrollable apps grid view. void CreateScrollableAppsGrid(); // Returns the compositor associated to the widget containing this view. // Returns nullptr if there isn't one associated with this widget. ui::Compositor* GetCompositor(); // Called from the root apps grid view to cancel reparent drag from the root // apps grid. void CancelReparentDragFromRootGrid(); // Calculates whether the folder would fit in the bounding box if it had the // max allowed number of rows, and condenses the margins between grid items if // this is not the case. The goal is to prevent a portion of folder UI from // getting laid out outside the bounding box. Tile size scaling done for the // top level apps grid should ensure the folder UI reasonably fits within the // bounding box with no item margins. At certain screen sizes, this approach // also fails, but at that point the top level apps grid doesn't work too well // either. // No-op if the productivity launcher is enabled, in which case folder grid is // scrollable, and should handle the case where grid bounds overflow bounding // box size gracefully. void ShrinkGridTileMarginsWhenNeeded(); // Resets the folder view state. Called when the folder view gets hidden (and // hide animations finish) to disassociate the folder view with the current // folder item (if any). // `restore_folder_item_view_state` - whether the folder item view state // should be restored to the default state (icon and title shown). Set to // false when resetting the folder state due to folder item view deletion. void ResetState(bool restore_folder_item_view_state); // Controller interface implemented by the container for this view. AppListFolderController* const folder_controller_; // The root (non-folder) apps grid view. AppsGridView* const root_apps_grid_view_; // Used to send accessibility alerts. Owned by the parent apps container. AppListA11yAnnouncer* const a11y_announcer_; // The view is used to draw a background with corner radius. views::View* background_view_; // Owned by views hierarchy. // The view is used as a container for all following views. views::View* contents_container_; // Owned by views hierarchy. FolderHeaderView* folder_header_view_; // Owned by views hierarchy. AppsGridView* items_grid_view_; // Owned by views hierarchy. // Only used for non-ProductivityLauncher. Owned by views hierarchy. PageSwitcher* page_switcher_ = nullptr; // Only used for ProductivityLauncher. Owned by views hierarchy. views::ScrollView* scroll_view_ = nullptr; // Adds fade in/out gradients to `scroll_view_`. // Only used for ProductivityLauncher. std::unique_ptr<ScrollViewGradientHelper> gradient_helper_; AppListModel* const model_; AppListViewDelegate* const view_delegate_; AppListFolderItem* folder_item_ = nullptr; // Not owned. // The folder item in the root apps grid associated with this folder. AppListItemView* folder_item_view_ = nullptr; // The bounds of the activated folder item icon relative to this view. gfx::Rect folder_item_icon_bounds_; // The preferred bounds of this view relative to AppsContainerView. gfx::Rect preferred_bounds_; // The bounds of the box within which the folder view can be shown. The bounds // are relative the the parent view's coordinate system. gfx::Rect bounding_box_; bool hide_for_reparent_ = false; std::vector<std::unique_ptr<Animation>> folder_visibility_animations_; // Records smoothness of the folder show/hide animation. absl::optional<ui::ThroughputTracker> show_hide_metrics_tracker_; // Observes `folder_item_view_` deletion, so the folder state can be cleared // if the folder item view is destroyed (for example, the view may get deleted // during folder hide animation if the backing item gets deleted from the // model, and animations depend on the folder item view). base::ScopedObservation<views::View, views::ViewObserver> folder_item_view_observer_{this}; base::WeakPtrFactory<AppListFolderView> weak_ptr_factory_{this}; }; } // namespace ash #endif // ASH_APP_LIST_VIEWS_APP_LIST_FOLDER_VIEW_H_
blueboxd/chromium-legacy
chrome/browser/ui/user_education/feature_promo_bubble_params.h
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_USER_EDUCATION_FEATURE_PROMO_BUBBLE_PARAMS_H_ #define CHROME_BROWSER_UI_USER_EDUCATION_FEATURE_PROMO_BUBBLE_PARAMS_H_ #include <memory> #include <string> #include "base/time/time.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/accelerators/accelerator.h" #include "ui/gfx/vector_icon_types.h" // Describes the content and appearance of an in-product help bubble. // |body_string_specifier| and |arrow| are required, all other fields have good // defaults. The anchor UI element is supplied in the framework-specific // factory. For consistency between different in-product help flows, avoid // changing more fields than necessary. struct FeaturePromoBubbleParams { FeaturePromoBubbleParams(); ~FeaturePromoBubbleParams(); FeaturePromoBubbleParams(const FeaturePromoBubbleParams&); // Promo contents: // The main promo text. Must be set to a valid string specifier. int body_string_specifier = -1; // If |body_string_specifier| is not set, this will be used instead. // Only use if your string has placeholders that need to be filled in // dynamically. // // TODO(crbug.com/1143971): enable filling placeholders in // |body_string_specifier| with context-specific information then // remove this. std::u16string body_text_raw; // Title shown larger at top of bubble. Optional. absl::optional<int> title_string_specifier; // String to be announced when bubble is shown. Optional. absl::optional<int> screenreader_string_specifier; // The icon to display in the bubble next to the text. const gfx::VectorIcon* body_icon = nullptr; // A keyboard accelerator to access the feature. If // |screenreader_string_specifier| is set and contains a placeholder, // this is filled in and announced to the user. // // One of |feature_accelerator| or |feature_command_id|, or neither, // can be filled in. If |feature_command_id| is specified this ID is // looked up on BrowserView and the associated accelerator is fetched. absl::optional<ui::Accelerator> feature_accelerator; absl::optional<int> feature_command_id; // Positioning and sizing: // Mirrors most values of views::BubbleBorder::Arrow enum class Arrow { TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT, LEFT_TOP, RIGHT_TOP, LEFT_BOTTOM, RIGHT_BOTTOM, TOP_CENTER, BOTTOM_CENTER, LEFT_CENTER, RIGHT_CENTER, }; // Determines position relative to the anchor element, and where the bubble's // arrow points. Required. Arrow arrow = Arrow::TOP_LEFT; // If set, determines the width of the bubble. Prefer the default if // possible. absl::optional<int> preferred_width; // Determines if the bubble will get focused on creation. bool focus_on_create = false; // Determines if this bubble will be dismissed when it loses focus. // Only meaningful when |focus_on_create| is true. If it's false then it // starts out blurred. bool persist_on_blur = true; // Determines if this IPH can be snoozed and reactivated later. // If true, |allow_focus| must be true for keyboard accessibility. bool allow_snooze = false; // Changes the bubble timeout before and after hovering the bubble, // respectively. If a timeout is not provided a default will be used. If // |timeout_after_interaction| is 0, |timeout_no_interaction| is used in // both cases. If both are 0, the bubble never times out. A bubble with // buttons never times out regardless of the values. absl::optional<base::TimeDelta> timeout_no_interaction; absl::optional<base::TimeDelta> timeout_after_interaction; }; #endif // CHROME_BROWSER_UI_USER_EDUCATION_FEATURE_PROMO_BUBBLE_PARAMS_H_
blueboxd/chromium-legacy
ash/webui/projector_app/test/mock_app_client.h
<reponame>blueboxd/chromium-legacy // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_WEBUI_PROJECTOR_APP_TEST_MOCK_APP_CLIENT_H_ #define ASH_WEBUI_PROJECTOR_APP_TEST_MOCK_APP_CLIENT_H_ #include <string> #include "ash/webui/projector_app/projector_app_client.h" #include "base/time/time.h" #include "components/signin/public/identity_manager/identity_test_environment.h" #include "services/network/test/test_url_loader_factory.h" #include "testing/gmock/include/gmock/gmock.h" namespace network { namespace mojom { class URLLoaderFactory; } // namespace mojom } // namespace network namespace signin { class IdentityManager; } // namespace signin namespace chromeos { class MockAppClient : public ProjectorAppClient { public: MockAppClient(); MockAppClient(const MockAppClient&) = delete; MockAppClient& operator=(const MockAppClient&) = delete; ~MockAppClient() override; network::TestURLLoaderFactory& test_url_loader_factory() { return test_url_loader_factory_; } // ProjectorAppClient: signin::IdentityManager* GetIdentityManager() override; network::mojom::URLLoaderFactory* GetUrlLoaderFactory() override; MOCK_METHOD1(AddObserver, void(Observer*)); MOCK_METHOD1(RemoveObserver, void(Observer*)); MOCK_METHOD1(OnNewScreencastPreconditionChanged, void(bool)); void SetAutomaticIssueOfAccessTokens(bool success); void WaitForAccessRequest(const std::string& account_email); void GrantOAuthTokenFor(const std::string& account_email, const base::Time& expiry_time); void AddSecondaryAccount(const std::string& account_email); private: signin::IdentityTestEnvironment identity_test_environment_; network::TestURLLoaderFactory test_url_loader_factory_; }; } // namespace chromeos #endif // ASH_WEBUI_PROJECTOR_APP_TEST_MOCK_APP_CLIENT_H_
blueboxd/chromium-legacy
cc/layers/region_capture_bounds.h
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CC_LAYERS_REGION_CAPTURE_BOUNDS_H_ #define CC_LAYERS_REGION_CAPTURE_BOUNDS_H_ #include "base/containers/flat_map.h" #include "base/token.h" #include "cc/cc_export.h" #include "ui/gfx/geometry/rect.h" namespace cc { using RegionCaptureCropId = base::Token; // Represents a map from a region capture crop identifier, which is a // randomly generated token, to a rectangle representing the bounds // of the HTML element associated with the crop identifier. // See the design document at: // https://docs.google.com/document/d/1dULARMnMZggfWqa_Ti_GrINRNYXGIli3XK9brzAKEV8 class CC_EXPORT RegionCaptureBounds final { public: RegionCaptureBounds(); RegionCaptureBounds(const RegionCaptureBounds& regions); RegionCaptureBounds(RegionCaptureBounds&& regions); ~RegionCaptureBounds(); // We currently only support a single set of bounds for a given crop id. // Multiple calls with the same crop id will update the bounds. void Set(const RegionCaptureCropId& crop_id, const gfx::Rect& bounds); const base::flat_map<RegionCaptureCropId, gfx::Rect>& bounds() const { return bounds_; } RegionCaptureBounds& operator=(const RegionCaptureBounds& other); RegionCaptureBounds& operator=(RegionCaptureBounds&& other); bool operator==(const RegionCaptureBounds& other) const; private: base::flat_map<RegionCaptureCropId, gfx::Rect> bounds_; }; } // namespace cc #endif // CC_LAYERS_REGION_CAPTURE_BOUNDS_H_
blueboxd/chromium-legacy
components/autofill_assistant/browser/java_tts_controller.h
<reponame>blueboxd/chromium-legacy<filename>components/autofill_assistant/browser/java_tts_controller.h<gh_stars>10-100 // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_AUTOFILL_ASSISTANT_BROWSER_JAVA_TTS_CONTROLLER_H_ #define COMPONENTS_AUTOFILL_ASSISTANT_BROWSER_JAVA_TTS_CONTROLLER_H_ #include <memory> #include <string> #include "base/android/jni_array.h" #include "base/android/scoped_java_ref.h" #include "components/autofill_assistant/browser/autofill_assistant_tts_controller.h" #include "url/gurl.h" namespace autofill_assistant { // Thin C++ wrapper around a TTS controller implemented in Java. // Intended for use in integration tests to inject as a mock TTS controller. class TtsControllerAndroid : public AutofillAssistantTtsController { public: TtsControllerAndroid( const base::android::JavaParamRef<jobject>& jtts_controller); ~TtsControllerAndroid() override; TtsControllerAndroid(const TtsControllerAndroid&) = delete; TtsControllerAndroid& operator=(const TtsControllerAndroid&) = delete; // Overrides AutofillAssistantTtsController. void Speak(const std::string& message, const std::string& locale) override; void Stop() override; // Overrides UtteranceEventDelegate. void OnTtsEvent(content::TtsUtterance* utterance, content::TtsEventType event_type, int char_index, int char_length, const std::string& error_message) override; private: base::android::ScopedJavaGlobalRef<jobject> java_tts_controller_; }; } // namespace autofill_assistant #endif // COMPONENTS_AUTOFILL_ASSISTANT_BROWSER_JAVA_TTS_CONTROLLER_H_
blueboxd/chromium-legacy
ash/wm/desks/templates/desks_templates_icon_view.h
<filename>ash/wm/desks/templates/desks_templates_icon_view.h // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_WM_DESKS_TEMPLATES_DESKS_TEMPLATES_ICON_VIEW_H_ #define ASH_WM_DESKS_TEMPLATES_DESKS_TEMPLATES_ICON_VIEW_H_ #include <string> #include "base/memory/weak_ptr.h" #include "base/task/cancelable_task_tracker.h" #include "components/favicon_base/favicon_types.h" #include "components/services/app_service/public/mojom/types.mojom.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/views/controls/image_view.h" namespace ash { // A class for loading and displaying the icon of apps/urls used in a // DesksTemplatesItemView. class DesksTemplatesIconView : public views::ImageView { public: METADATA_HEADER(DesksTemplatesIconView); DesksTemplatesIconView(); DesksTemplatesIconView(const DesksTemplatesIconView&) = delete; DesksTemplatesIconView& operator=(const DesksTemplatesIconView&) = delete; ~DesksTemplatesIconView() override; // The size of an icon. static constexpr int kIconSize = 28; void SetIconIdentifier(const std::string& icon_identifier) { icon_identifier_ = icon_identifier; } void SetIsUrl(bool is_url) { is_url_ = is_url; } // Fetches the icon for the provided `icon_identifier_`. void LoadIcon(); private: // Callbacks for when the app icon/favicon has been fetched. If the result is // non-null/empty then we'll set this's image to the result. Otherwise, we'll // use a placeholder icon. void OnFaviconLoaded(const favicon_base::FaviconImageResult& image_result); void OnAppIconLoaded(apps::mojom::IconValuePtr icon_value); // The identifier for an icon. For a favicon, this will be a url. For an app, // this will be an app id. std::string icon_identifier_; // If true, `icon_identifier_` is a url. Otherwise, `icon_identifier_` is an // app id. bool is_url_ = false; // Used for favicon loading tasks. base::CancelableTaskTracker cancelable_task_tracker_; base::WeakPtrFactory<DesksTemplatesIconView> weak_ptr_factory_{this}; }; BEGIN_VIEW_BUILDER(/* no export */, DesksTemplatesIconView, views::ImageView) VIEW_BUILDER_PROPERTY(std::string, IconIdentifier) VIEW_BUILDER_PROPERTY(bool, IsUrl) END_VIEW_BUILDER } // namespace ash DEFINE_VIEW_BUILDER(/* no export */, ash::DesksTemplatesIconView) #endif // ASH_WM_DESKS_TEMPLATES_DESKS_TEMPLATES_ICON_VIEW_H_
blueboxd/chromium-legacy
media/gpu/vaapi/h264_vaapi_video_encoder_delegate.h
<reponame>blueboxd/chromium-legacy // Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MEDIA_GPU_VAAPI_H264_VAAPI_VIDEO_ENCODER_DELEGATE_H_ #define MEDIA_GPU_VAAPI_H264_VAAPI_VIDEO_ENCODER_DELEGATE_H_ #include <stddef.h> #include <list> #include "base/containers/circular_deque.h" #include "base/macros.h" #include "media/filters/h264_bitstream_buffer.h" #include "media/gpu/h264_dpb.h" #include "media/gpu/vaapi/vaapi_video_encoder_delegate.h" namespace media { class VaapiWrapper; // This class provides an H264 encoder functionality, generating stream headers, // managing encoder state, reference frames, and other codec parameters, while // requiring support from an Accelerator to encode frame data based on these // parameters. // // This class must be created, called and destroyed on a single sequence. // // Names used in documentation of this class refer directly to naming used // in the H.264 specification (http://www.itu.int/rec/T-REC-H.264). class H264VaapiVideoEncoderDelegate : public VaapiVideoEncoderDelegate { public: struct EncodeParams { EncodeParams(); VideoBitrateAllocation bitrate_allocation; // Framerate in FPS. uint32_t framerate; // Bitrate window size in ms. uint32_t cpb_window_size_ms; // Bitrate window size in bits. unsigned int cpb_size_bits; // Quantization parameter. Their ranges are 0-51. uint8_t initial_qp; uint8_t min_qp; uint8_t max_qp; // Maxium Number of Reference frames. size_t max_num_ref_frames; // Maximum size of reference picture list 0. size_t max_ref_pic_list0_size; }; H264VaapiVideoEncoderDelegate(scoped_refptr<VaapiWrapper> vaapi_wrapper, base::RepeatingClosure error_cb); H264VaapiVideoEncoderDelegate(const H264VaapiVideoEncoderDelegate&) = delete; H264VaapiVideoEncoderDelegate& operator=( const H264VaapiVideoEncoderDelegate&) = delete; ~H264VaapiVideoEncoderDelegate() override; // VaapiVideoEncoderDelegate implementation. bool Initialize(const VideoEncodeAccelerator::Config& config, const VaapiVideoEncoderDelegate::Config& ave_config) override; bool UpdateRates(const VideoBitrateAllocation& bitrate_allocation, uint32_t framerate) override; gfx::Size GetCodedSize() const override; size_t GetMaxNumOfRefFrames() const override; std::vector<gfx::Size> GetSVCLayerResolutions() override; private: class TemporalLayers; friend class H264VaapiVideoEncoderDelegateTest; bool PrepareEncodeJob(EncodeJob& encode_job) override; BitstreamBufferMetadata GetMetadata(const EncodeJob& encode_job, size_t payload_size) override; // Fill current_sps_ and current_pps_ with current encoding state parameters. void UpdateSPS(); void UpdatePPS(); // Generate packed SPS and PPS in packed_sps_ and packed_pps_, using values // in current_sps_ and current_pps_. void GeneratePackedSPS(); void GeneratePackedPPS(); // Generate packed slice header from |pic_param|, |slice_param| and |pic|. scoped_refptr<H264BitstreamBuffer> GeneratePackedSliceHeader( const VAEncPictureParameterBufferH264& pic_param, const VAEncSliceParameterBufferH264& sliice_param, const H264Picture& pic); // Check if |bitrate| and |framerate| and current coded size are supported by // current profile and level. bool CheckConfigValidity(uint32_t bitrate, uint32_t framerate); // Submits a H264BitstreamBuffer |buffer| to the driver. bool SubmitH264BitstreamBuffer(const H264BitstreamBuffer& buffer); // Submits a VAEncMiscParameterBuffer |data| whose size and type are |size| // and |type| to the driver. bool SubmitVAEncMiscParamBuffer(VAEncMiscParameterType type, const void* data, size_t size); bool SubmitPackedHeaders(scoped_refptr<H264BitstreamBuffer> packed_sps, scoped_refptr<H264BitstreamBuffer> packed_pps); bool SubmitFrameParameters( EncodeJob& job, const H264VaapiVideoEncoderDelegate::EncodeParams& encode_params, const H264SPS& sps, const H264PPS& pps, scoped_refptr<H264Picture> pic, const base::circular_deque<scoped_refptr<H264Picture>>& ref_pic_list0, const absl::optional<size_t>& ref_frame_index); // Current SPS, PPS and their packed versions. Packed versions are NALUs // in AnnexB format *without* emulation prevention three-byte sequences // (those are expected to be added by the client as needed). H264SPS current_sps_; scoped_refptr<H264BitstreamBuffer> packed_sps_; H264PPS current_pps_; scoped_refptr<H264BitstreamBuffer> packed_pps_; bool submit_packed_headers_; // Current encoding parameters being used. EncodeParams curr_params_; // H264 profile currently used. VideoCodecProfile profile_ = VIDEO_CODEC_PROFILE_UNKNOWN; // H264 level currently used. uint8_t level_ = 0; // Current visible and coded sizes in pixels. gfx::Size visible_size_; gfx::Size coded_size_; // Width/height in macroblocks. unsigned int mb_width_ = 0; unsigned int mb_height_ = 0; // The number of encoded frames. Resets to 0 on IDR frame. unsigned int num_encoded_frames_ = 0; // frame_num (spec section 7.4.3). unsigned int frame_num_ = 0; // idr_pic_id (spec section 7.4.3) to be used for the next frame. unsigned int idr_pic_id_ = 0; // True if encoding parameters have changed that affect decoder process, then // we need to submit a keyframe with updated parameters. bool encoding_parameters_changed_ = false; // Currently active reference frames. // RefPicList0 per spec (spec section 8.2.4.2). base::circular_deque<scoped_refptr<H264Picture>> ref_pic_list0_; // Sets true if and only if testing. // TODO(b/199487660): Remove once all drivers support temporal layers. bool supports_temporal_layer_for_testing_ = false; uint8_t num_temporal_layers_ = 1; }; } // namespace media #endif // MEDIA_GPU_VAAPI_H264_VAAPI_VIDEO_ENCODER_DELEGATE_H_
blueboxd/chromium-legacy
ash/system/time/calendar_view.h
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_SYSTEM_TIME_CALENDAR_VIEW_H_ #define ASH_SYSTEM_TIME_CALENDAR_VIEW_H_ #include "ash/ash_export.h" #include "ash/system/time/calendar_view_controller.h" #include "ash/system/tray/tray_detailed_view.h" #include "ash/system/unified/unified_system_tray_controller.h" #include "base/callback_list.h" #include "base/scoped_multi_source_observation.h" #include "base/timer/timer.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/views/controls/scroll_view.h" #include "ui/views/view.h" namespace views { class Label; } // namespace views namespace ash { class CalendarMonthView; // This view displays a scrollable calendar. class ASH_EXPORT CalendarView : public CalendarViewController::Observer, public TrayDetailedView, public views::ViewObserver { public: METADATA_HEADER(CalendarView); CalendarView(DetailedViewDelegate* delegate, UnifiedSystemTrayController* controller); CalendarView(const CalendarView& other) = delete; CalendarView& operator=(const CalendarView& other) = delete; ~CalendarView() override; void Init(); // CalendarViewController::Observer: void OnMonthChanged(const base::Time::Exploded current_month) override; void OnEventsFetched(const google_apis::calendar::EventList* events) override; // views::ViewObserver: void OnViewBoundsChanged(views::View* observed_view) override; void OnViewFocused(View* observed_view) override; // views::View: void OnThemeChanged() override; void OnEvent(ui::Event* event) override; // TrayDetailedView: void CreateExtraTitleRowButtons() override; views::Button* CreateInfoButton(views::Button::PressedCallback callback, int info_accessible_name_id) override; CalendarViewController* calendar_view_controller() { return calendar_view_controller_.get(); } private: // The header of each month view which shows the month's name. If the year of // this month is not the same as the current month, the year is also shown in // this view. class MonthYearHeaderView; // The types to create the `MonthYearHeaderView` which are in corresponding to // the 3 months: `previous_month_`, `current_month_` and `next_month_`. enum LabelType { PREVIOUS, CURRENT, NEXT }; friend class CalendarViewTest; // Assigns month views and labels based on the current date on screen. void SetMonthViews(); // Returns the current month first row position. int PositionOfCurrentMonth(); // Returns the today's row position. int PositionOfToday(); // Adds a month label. views::View* AddLabelWithId(LabelType type, bool add_at_front = false); // Adds a `CalendarMonthView`. CalendarMonthView* AddMonth(base::Time month_first_date, bool add_at_front = false); // Deletes the current next month and add a new month at the top of the // `content_view_`. void ScrollUpOneMonth(); // Deletes the current previous month and adds a new month at the bottom of // the `content_view_`. void ScrollDownOneMonth(); // Scrolls up one month then auto scroll to the current month's first row. void ScrollUpOneMonthAndAutoScroll(); // Scrolls down one month then auto scroll to the current month's first row. void ScrollDownOneMonthAndAutoScroll(); // Back to the landing view. void ResetToToday(); // Auto scrolls to today. If the view is big enough we scroll to the first row // of today's month, otherwise we scroll to the position of today's row. void ScrollToToday(); // If currently focusing on any date cell. bool IsDateCellViewFocused(); // If focusing on `CalendarDateCellView` is interrupted (by scrolling or by // today's button), resets the content view's `FocusBehavior` to `ALWAYS`. void MaybeResetContentViewFocusBehavior(); // We only fetch events after we've "settled" on the current on-screen month. void OnScrollingSettledTimerFired(); // ScrollView callback. void OnContentsScrolled(); // Unowned. UnifiedSystemTrayController* controller_; std::unique_ptr<CalendarViewController> calendar_view_controller_; // The content of the `scroll_view_`, which carries months and month labels. // Owned by `CalendarView`. views::View* content_view_ = nullptr; // The following is owned by `CalendarView`. views::ScrollView* scroll_view_ = nullptr; views::View* current_label_ = nullptr; views::View* previous_label_ = nullptr; views::View* next_label_ = nullptr; CalendarMonthView* previous_month_ = nullptr; CalendarMonthView* current_month_ = nullptr; CalendarMonthView* next_month_ = nullptr; views::Label* header_ = nullptr; views::Label* header_year_ = nullptr; views::Button* reset_to_today_button_ = nullptr; views::Button* settings_button_ = nullptr; // If it `is_resetting_scroll_`, we don't calculate the scroll position and we // don't need to check if we need to update the month or not. bool is_resetting_scroll_ = false; // Timer that fires when we've "settled" on, i.e. finished scrolling to, a // currently-visible month base::RetainingOneShotTimer scrolling_settled_timer_; base::CallbackListSubscription on_contents_scrolled_subscription_; base::ScopedObservation<CalendarViewController, CalendarViewController::Observer> scoped_calendar_view_controller_observer_{this}; base::ScopedMultiSourceObservation<views::View, views::ViewObserver> scoped_view_observer_{this}; }; } // namespace ash #endif // ASH_SYSTEM_TIME_CALENDAR_VIEW_H_
blueboxd/chromium-legacy
cc/trees/layer_tree_host_impl.h
// Copyright 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 CC_TREES_LAYER_TREE_HOST_IMPL_H_ #define CC_TREES_LAYER_TREE_HOST_IMPL_H_ #include <stddef.h> #include <memory> #include <set> #include <string> #include <unordered_map> #include <utility> #include <vector> #include "base/callback.h" #include "base/containers/flat_map.h" #include "base/containers/flat_set.h" #include "base/containers/lru_cache.h" #include "base/memory/memory_pressure_listener.h" #include "base/memory/shared_memory_mapping.h" #include "base/task/sequenced_task_runner.h" #include "base/time/time.h" #include "cc/base/synced_property.h" #include "cc/benchmarks/micro_benchmark_controller_impl.h" #include "cc/cc_export.h" #include "cc/input/actively_scrolling_type.h" #include "cc/input/browser_controls_offset_manager_client.h" #include "cc/input/input_handler.h" #include "cc/input/scrollbar_animation_controller.h" #include "cc/input/scrollbar_controller.h" #include "cc/input/threaded_input_handler.h" #include "cc/layers/layer_collections.h" #include "cc/metrics/average_lag_tracking_manager.h" #include "cc/metrics/dropped_frame_counter.h" #include "cc/metrics/event_metrics.h" #include "cc/metrics/events_metrics_manager.h" #include "cc/metrics/frame_sequence_tracker_collection.h" #include "cc/metrics/total_frame_counter.h" #include "cc/paint/discardable_image_map.h" #include "cc/paint/paint_worklet_job.h" #include "cc/raster/raster_query_queue.h" #include "cc/resources/ui_resource_client.h" #include "cc/scheduler/begin_frame_tracker.h" #include "cc/scheduler/commit_earlyout_reason.h" #include "cc/scheduler/draw_result.h" #include "cc/scheduler/scheduler.h" #include "cc/scheduler/video_frame_controller.h" #include "cc/tiles/decoded_image_tracker.h" #include "cc/tiles/image_decode_cache.h" #include "cc/tiles/tile_manager.h" #include "cc/trees/animated_paint_worklet_tracker.h" #include "cc/trees/de_jelly_state.h" #include "cc/trees/frame_rate_estimator.h" #include "cc/trees/layer_tree_frame_sink_client.h" #include "cc/trees/layer_tree_host.h" #include "cc/trees/layer_tree_mutator.h" #include "cc/trees/layer_tree_settings.h" #include "cc/trees/managed_memory_policy.h" #include "cc/trees/mutator_host_client.h" #include "cc/trees/presentation_time_callback_buffer.h" #include "cc/trees/render_frame_metadata.h" #include "cc/trees/task_runner_provider.h" #include "cc/trees/throttle_decider.h" #include "cc/trees/ukm_manager.h" #include "components/viz/client/client_resource_provider.h" #include "components/viz/common/frame_sinks/begin_frame_args.h" #include "components/viz/common/gpu/context_cache_controller.h" #include "components/viz/common/quads/compositor_render_pass.h" #include "components/viz/common/surfaces/child_local_surface_id_allocator.h" #include "components/viz/common/surfaces/local_surface_id.h" #include "components/viz/common/surfaces/surface_id.h" #include "components/viz/common/surfaces/surface_range.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/events/types/scroll_input_type.h" #include "ui/gfx/geometry/rect.h" namespace gfx { class Vector2dF; } namespace viz { class CompositorFrame; class CompositorFrameMetadata; struct FrameTimingDetails; } // namespace viz namespace cc { enum class ActivelyScrollingType; class BrowserControlsOffsetManager; class CompositorFrameReportingController; class RasterDarkModeFilter; class DebugRectHistory; class EvictionTilePriorityQueue; class DroppedFrameCounter; class ImageAnimationController; class LCDTextMetricsReporter; class LayerImpl; class LayerTreeFrameSink; class LayerTreeImpl; class PaintWorkletLayerPainter; class MemoryHistory; class MutatorEvents; class MutatorHost; class PageScaleAnimation; class PendingTreeRasterDurationHistogramTimer; class RasterTilePriorityQueue; class RasterBufferProvider; class RenderFrameMetadataObserver; class RenderingStatsInstrumentation; class ResourcePool; class SwapPromise; class SwapPromiseMonitor; class SynchronousTaskGraphRunner; class TaskGraphRunner; class UIResourceBitmap; class Viewport; enum class GpuRasterizationStatus { ON, OFF_FORCED, OFF_DEVICE, }; // LayerTreeHost->Proxy callback interface. class LayerTreeHostImplClient { public: virtual void DidLoseLayerTreeFrameSinkOnImplThread() = 0; virtual void SetBeginFrameSource(viz::BeginFrameSource* source) = 0; virtual void DidReceiveCompositorFrameAckOnImplThread() = 0; virtual void OnCanDrawStateChanged(bool can_draw) = 0; virtual void NotifyReadyToActivate() = 0; virtual void NotifyReadyToDraw() = 0; // Please call these 2 functions through // LayerTreeHostImpl's SetNeedsRedraw() and SetNeedsOneBeginImplFrame(). virtual void SetNeedsRedrawOnImplThread() = 0; virtual void SetNeedsOneBeginImplFrameOnImplThread() = 0; virtual void SetNeedsCommitOnImplThread() = 0; virtual void SetNeedsPrepareTilesOnImplThread() = 0; virtual void SetVideoNeedsBeginFrames(bool needs_begin_frames) = 0; virtual bool IsInsideDraw() = 0; virtual void RenewTreePriority() = 0; virtual void PostDelayedAnimationTaskOnImplThread(base::OnceClosure task, base::TimeDelta delay) = 0; virtual void DidActivateSyncTree() = 0; virtual void WillPrepareTiles() = 0; virtual void DidPrepareTiles() = 0; // Called when page scale animation has completed on the impl thread. virtual void DidCompletePageScaleAnimationOnImplThread() = 0; // Called when output surface asks for a draw. virtual void OnDrawForLayerTreeFrameSink(bool resourceless_software_draw, bool skip_draw) = 0; virtual void NeedsImplSideInvalidation( bool needs_first_draw_on_activation) = 0; // Called when a requested image decode completes. virtual void NotifyImageDecodeRequestFinished() = 0; virtual void RequestBeginMainFrameNotExpected(bool new_state) = 0; // Called when a presentation time is requested. |frame_token| identifies // the frame that was presented. |callbacks| holds both impl side and main // side callbacks to be called. virtual void DidPresentCompositorFrameOnImplThread( uint32_t frame_token, PresentationTimeCallbackBuffer::PendingCallbacks callbacks, const viz::FrameTimingDetails& details) = 0; // Returns whether the main-thread is expected to receive a BeginMainFrame. virtual bool IsBeginMainFrameExpected() = 0; virtual void NotifyAnimationWorkletStateChange( AnimationWorkletMutationState state, ElementListType tree_type) = 0; virtual void NotifyPaintWorkletStateChange( Scheduler::PaintWorkletState state) = 0; virtual void NotifyThroughputTrackerResults(CustomTrackerResults results) = 0; virtual void DidObserveFirstScrollDelay( base::TimeDelta first_scroll_delay, base::TimeTicks first_scroll_timestamp) = 0; // Returns true if the client is currently compositing synchronously. This is // only true in tests, but some behavior needs to be synchronized in non-test // code as a result. virtual bool IsInSynchronousComposite() const = 0; virtual void FrameSinksToThrottleUpdated( const base::flat_set<viz::FrameSinkId>& ids) = 0; protected: virtual ~LayerTreeHostImplClient() = default; }; // LayerTreeHostImpl owns the LayerImpl trees as well as associated rendering // state. class CC_EXPORT LayerTreeHostImpl : public TileManagerClient, public LayerTreeFrameSinkClient, public BrowserControlsOffsetManagerClient, public ScrollbarAnimationControllerClient, public VideoFrameControllerClient, public MutatorHostClient, public ImageAnimationController::Client, public CompositorDelegateForInput { public: // This structure is used to build all the state required for producing a // single CompositorFrame. The |render_passes| list becomes the set of // RenderPasses in the quad, and the other fields are used for computation // or become part of the CompositorFrameMetadata. struct CC_EXPORT FrameData { FrameData(); FrameData(const FrameData&) = delete; ~FrameData(); FrameData& operator=(const FrameData&) = delete; void AsValueInto(base::trace_event::TracedValue* value) const; std::string ToString() const; // frame_token is populated by the LayerTreeHostImpl when submitted. uint32_t frame_token = 0; bool has_missing_content = false; std::vector<viz::SurfaceId> activation_dependencies; absl::optional<uint32_t> deadline_in_frames; bool use_default_lower_bound_deadline = false; viz::CompositorRenderPassList render_passes; const RenderSurfaceList* render_surface_list = nullptr; LayerImplList will_draw_layers; bool has_no_damage = false; bool may_contain_video = false; viz::BeginFrameAck begin_frame_ack; // The original BeginFrameArgs that triggered the latest update from the // main thread. viz::BeginFrameArgs origin_begin_main_frame_args; bool has_shared_element_resources = false; }; // A struct of data for a single UIResource, including the backing // pixels, and metadata about it. struct CC_EXPORT UIResourceData { UIResourceData(); UIResourceData(const UIResourceData&) = delete; UIResourceData(UIResourceData&&) noexcept; ~UIResourceData(); UIResourceData& operator=(const UIResourceData&) = delete; UIResourceData& operator=(UIResourceData&&); bool opaque; viz::ResourceFormat format; // Backing for software compositing. viz::SharedBitmapId shared_bitmap_id; base::WritableSharedMemoryMapping shared_mapping; // Backing for gpu compositing. gpu::Mailbox mailbox; // The name with which to refer to the resource in frames submitted to the // display compositor. viz::ResourceId resource_id_for_export; }; static std::unique_ptr<LayerTreeHostImpl> Create( const LayerTreeSettings& settings, LayerTreeHostImplClient* client, TaskRunnerProvider* task_runner_provider, RenderingStatsInstrumentation* rendering_stats_instrumentation, TaskGraphRunner* task_graph_runner, std::unique_ptr<MutatorHost> mutator_host, RasterDarkModeFilter* dark_mode_filter, int id, scoped_refptr<base::SequencedTaskRunner> image_worker_task_runner, LayerTreeHostSchedulingClient* scheduling_client); LayerTreeHostImpl(const LayerTreeHostImpl&) = delete; ~LayerTreeHostImpl() override; LayerTreeHostImpl& operator=(const LayerTreeHostImpl&) = delete; // TODO(bokan): This getter is an escape-hatch for code that hasn't yet been // cleaned up to decouple input from graphics. Callers should be cleaned up // to avoid calling it and it should be removed. ThreadedInputHandler& GetInputHandler(); const ThreadedInputHandler& GetInputHandler() const; void StartPageScaleAnimation(const gfx::Vector2d& target_offset, bool anchor_point, float page_scale, base::TimeDelta duration); void SetNeedsAnimateInput(); std::unique_ptr<SwapPromiseMonitor> CreateLatencyInfoSwapPromiseMonitor( ui::LatencyInfo* latency); std::unique_ptr<EventsMetricsManager::ScopedMonitor> GetScopedEventMetricsMonitor( EventsMetricsManager::ScopedMonitor::DoneCallback done_callback); void NotifyInputEvent(); // BrowserControlsOffsetManagerClient implementation. float TopControlsHeight() const override; float TopControlsMinHeight() const override; float BottomControlsHeight() const override; float BottomControlsMinHeight() const override; void SetCurrentBrowserControlsShownRatio(float top_ratio, float bottom_ratio) override; float CurrentTopControlsShownRatio() const override; float CurrentBottomControlsShownRatio() const override; gfx::Vector2dF ViewportScrollOffset() const override; void DidChangeBrowserControlsPosition() override; void DidObserveScrollDelay(base::TimeDelta scroll_delay, base::TimeTicks scroll_timestamp); bool OnlyExpandTopControlsAtPageTop() const override; bool HaveRootScrollNode() const override; void SetNeedsCommit() override; // ImageAnimationController::Client implementation. void RequestBeginFrameForAnimatedImages() override; void RequestInvalidationForAnimatedImages() override; EventMetricsSet TakeEventsMetrics(); void AppendEventsMetricsFromMainThread( std::vector<EventMetrics> events_metrics); base::WeakPtr<LayerTreeHostImpl> AsWeakPtr(); void set_resourceless_software_draw_for_testing() { resourceless_software_draw_ = true; } const gfx::Rect& viewport_damage_rect_for_testing() const { return viewport_damage_rect_; } virtual void WillSendBeginMainFrame(); virtual void DidSendBeginMainFrame(const viz::BeginFrameArgs& args); virtual void BeginMainFrameAborted( CommitEarlyOutReason reason, std::vector<std::unique_ptr<SwapPromise>> swap_promises, const viz::BeginFrameArgs& args, bool scroll_and_viewport_changes_synced); virtual void ReadyToCommit( const viz::BeginFrameArgs& commit_args, const BeginMainFrameMetrics* begin_main_frame_metrics); virtual void BeginCommit(int source_frame_number); virtual void CommitComplete(); virtual void UpdateAnimationState(bool start_ready_animations); bool Mutate(base::TimeTicks monotonic_time); void ActivateAnimations(); void Animate(); void AnimatePendingTreeAfterCommit(); void DidAnimateScrollOffset(); void SetFullViewportDamage(); void SetViewportDamage(const gfx::Rect& damage_rect); void SetEnableFrameRateThrottling(bool enable_frame_rate_throttling); // Interface for ThreadedInputHandler void BindToInputHandler( std::unique_ptr<InputDelegateForCompositor> delegate) override; ScrollTree& GetScrollTree() const override; bool HasAnimatedScrollbars() const override; // Already overridden for BrowserControlsOffsetManagerClient which declares a // method of the same name. // void SetNeedsCommit(); void SetNeedsFullViewportRedraw() override; void DidUpdateScrollAnimationCurve() override; void AccumulateScrollDeltaForTracing(const gfx::Vector2dF& delta) override; void DidStartPinchZoom() override; void DidUpdatePinchZoom() override; void DidEndPinchZoom() override; void DidStartScroll() override; void DidEndScroll() override; void DidMouseLeave() override; bool IsInHighLatencyMode() const override; void WillScrollContent(ElementId element_id) override; void DidScrollContent(ElementId element_id, bool animated) override; float DeviceScaleFactor() const override; float PageScaleFactor() const override; gfx::Size VisualDeviceViewportSize() const override; const LayerTreeSettings& GetSettings() const override; LayerTreeHostImpl& GetImplDeprecated() override; const LayerTreeHostImpl& GetImplDeprecated() const override; bool CanInjectJankOnMain() const; FrameSequenceTrackerCollection& frame_trackers() { return frame_trackers_; } // VisualDeviceViewportSize is the size of the global viewport across all // compositors that are part of the scene that this compositor contributes to // (i.e. the visual viewport), allowing for that scene to be broken up into // multiple compositors that each contribute to the whole (e.g. cross-origin // iframes are isolated from each other). This is a size instead of a rect // because each compositor doesn't know its position relative to other // compositors. This is specified in device viewport coordinate space. void SetVisualDeviceViewportSize(const gfx::Size&); void set_viewport_mobile_optimized(bool viewport_mobile_optimized) { is_viewport_mobile_optimized_ = viewport_mobile_optimized; } bool viewport_mobile_optimized() const { return is_viewport_mobile_optimized_; } void SetPrefersReducedMotion(bool prefers_reduced_motion); void SetMayThrottleIfUndrawnFrames(bool may_throttle_if_undrawn_frames); // Updates registered ElementIds present in |changed_list|. Call this after // changing the property trees for the |changed_list| trees. void UpdateElements(ElementListType changed_list); // Analogous to a commit, this function is used to create a sync tree and // add impl-side invalidations to it. // virtual for testing. virtual void InvalidateContentOnImplSide(); virtual void InvalidateLayerTreeFrameSink(bool needs_redraw); void SetTreeLayerScrollOffsetMutated(ElementId element_id, LayerTreeImpl* tree, const gfx::Vector2dF& scroll_offset); void SetNeedUpdateGpuRasterizationStatus(); bool NeedUpdateGpuRasterizationStatusForTesting() const { return need_update_gpu_rasterization_status_; } // MutatorHostClient implementation. bool IsElementInPropertyTrees(ElementId element_id, ElementListType list_type) const override; void SetMutatorsNeedCommit() override; void SetMutatorsNeedRebuildPropertyTrees() override; void SetElementFilterMutated(ElementId element_id, ElementListType list_type, const FilterOperations& filters) override; void SetElementBackdropFilterMutated( ElementId element_id, ElementListType list_type, const FilterOperations& backdrop_filters) override; void SetElementOpacityMutated(ElementId element_id, ElementListType list_type, float opacity) override; void SetElementTransformMutated(ElementId element_id, ElementListType list_type, const gfx::Transform& transform) override; void SetElementScrollOffsetMutated( ElementId element_id, ElementListType list_type, const gfx::Vector2dF& scroll_offset) override; void ElementIsAnimatingChanged(const PropertyToElementIdMap& element_id_map, ElementListType list_type, const PropertyAnimationState& mask, const PropertyAnimationState& state) override; void MaximumScaleChanged(ElementId element_id, ElementListType list_type, float maximum_scale) override; void OnCustomPropertyMutated( PaintWorkletInput::PropertyKey property_key, PaintWorkletInput::PropertyValue property_value) override; void ScrollOffsetAnimationFinished() override; gfx::Vector2dF GetScrollOffsetForAnimation( ElementId element_id) const override; void NotifyAnimationWorkletStateChange(AnimationWorkletMutationState state, ElementListType tree_type) override; virtual bool PrepareTiles(); // Returns DRAW_SUCCESS unless problems occured preparing the frame, and we // should try to avoid displaying the frame. If PrepareToDraw is called, // DidDrawAllLayers must also be called, regardless of whether DrawLayers is // called between the two. virtual DrawResult PrepareToDraw(FrameData* frame); virtual bool DrawLayers(FrameData* frame); viz::CompositorFrame GenerateCompositorFrame(FrameData* frame); // Must be called if and only if PrepareToDraw was called. void DidDrawAllLayers(const FrameData& frame); const LayerTreeSettings& settings() const { return settings_; } // Evict all textures by enforcing a memory policy with an allocation of 0. void EvictTexturesForTesting(); // When blocking, this prevents client_->NotifyReadyToActivate() from being // called. When disabled, it calls client_->NotifyReadyToActivate() // immediately if any notifications had been blocked while blocking. virtual void BlockNotifyReadyToActivateForTesting(bool block); // Prevents notifying the |client_| when an impl side invalidation request is // made. When unblocked, the disabled request will immediately be called. virtual void BlockImplSideInvalidationRequestsForTesting(bool block); // Resets all of the trees to an empty state. void ResetTreesForTesting(); size_t SourceAnimationFrameNumberForTesting() const; void RegisterScrollbarAnimationController(ElementId scroll_element_id, float initial_opacity); void DidUnregisterScrollbarLayer(ElementId scroll_element_id, ScrollbarOrientation orientation); ScrollbarAnimationController* ScrollbarAnimationControllerForElementId( ElementId scroll_element_id) const; void FlashAllScrollbars(bool did_scroll); DrawMode GetDrawMode() const; void DidNotNeedBeginFrame(); // TileManagerClient implementation. void NotifyReadyToActivate() override; void NotifyReadyToDraw() override; void NotifyAllTileTasksCompleted() override; void NotifyTileStateChanged(const Tile* tile) override; std::unique_ptr<RasterTilePriorityQueue> BuildRasterQueue( TreePriority tree_priority, RasterTilePriorityQueue::Type type) override; std::unique_ptr<EvictionTilePriorityQueue> BuildEvictionQueue( TreePriority tree_priority) override; void SetIsLikelyToRequireADraw(bool is_likely_to_require_a_draw) override; gfx::ColorSpace GetRasterColorSpace( gfx::ContentColorUsage content_color_usage) const override; float GetSDRWhiteLevel() const override; void RequestImplSideInvalidationForCheckerImagedTiles() override; size_t GetFrameIndexForImage(const PaintImage& paint_image, WhichTree tree) const override; int GetMSAASampleCountForRaster( const scoped_refptr<DisplayItemList>& display_list) override; bool HasPendingTree() override; // ScrollbarAnimationControllerClient implementation. void PostDelayedScrollbarAnimationTask(base::OnceClosure task, base::TimeDelta delay) override; void SetNeedsAnimateForScrollbarAnimation() override; void SetNeedsRedrawForScrollbarAnimation() override; ScrollbarSet ScrollbarsFor(ElementId scroll_element_id) const override; void DidChangeScrollbarVisibility() override; // VideoBeginFrameSource implementation. void AddVideoFrameController(VideoFrameController* controller) override; void RemoveVideoFrameController(VideoFrameController* controller) override; // LayerTreeFrameSinkClient implementation. void SetBeginFrameSource(viz::BeginFrameSource* source) override; void SetExternalTilePriorityConstraints( const gfx::Rect& viewport_rect, const gfx::Transform& transform) override; absl::optional<viz::HitTestRegionList> BuildHitTestData() override; void DidLoseLayerTreeFrameSink() override; void DidReceiveCompositorFrameAck() override; void DidPresentCompositorFrame( uint32_t frame_token, const viz::FrameTimingDetails& details) override; void ReclaimResources(std::vector<viz::ReturnedResource> resources) override; void SetMemoryPolicy(const ManagedMemoryPolicy& policy) override; void SetTreeActivationCallback(base::RepeatingClosure callback) override; void OnDraw(const gfx::Transform& transform, const gfx::Rect& viewport, bool resourceless_software_draw, bool skip_draw) override; void OnCompositorFrameTransitionDirectiveProcessed( uint32_t sequence_id) override; // Called from LayerTreeImpl. void OnCanDrawStateChangedForTree(); // Implementation. int id() const { return id_; } bool CanDraw() const; LayerTreeFrameSink* layer_tree_frame_sink() const { return layer_tree_frame_sink_; } int max_texture_size() const { return max_texture_size_; } void ReleaseLayerTreeFrameSink(); int RequestedMSAASampleCount() const; virtual bool InitializeFrameSink(LayerTreeFrameSink* layer_tree_frame_sink); TileManager* tile_manager() { return &tile_manager_; } void GetGpuRasterizationCapabilities(bool* gpu_rasterization_enabled, bool* gpu_rasterization_supported, int* max_msaa_samples, bool* supports_disable_msaa); bool use_gpu_rasterization() const { return use_gpu_rasterization_; } bool can_use_oop_rasterization() const { return can_use_oop_rasterization_; } bool use_oop_rasterization() const { return use_gpu_rasterization_ && can_use_oop_rasterization_; } GpuRasterizationStatus gpu_rasterization_status() const { return gpu_rasterization_status_; } bool create_low_res_tiling() const { return settings_.create_low_res_tiling && !use_gpu_rasterization_; } ResourcePool* resource_pool() { return resource_pool_.get(); } ImageDecodeCache* image_decode_cache() { return image_decode_cache_.get(); } ImageAnimationController* image_animation_controller() { return &image_animation_controller_; } uint32_t next_frame_token() const { return *next_frame_token_; } // Buffers `callback` until a relevant presentation feedback arrives, at which // point the callback will be posted to run on the main thread. A presentation // feedback is considered relevant if the frame's token is greater than or // equal to `frame_token`. void RegisterMainThreadPresentationTimeCallbackForTesting( uint32_t frame_token, PresentationTimeCallbackBuffer::MainCallback callback); // Buffers `callback` until a relevant successful presentation occurs, at // which point the callback will be run on the compositor thread. A successful // presentation is considered relevant if the presented frame's token is // greater than or equal to `frame_token`. void RegisterCompositorPresentationTimeCallback( uint32_t frame_token, PresentationTimeCallbackBuffer::CompositorCallback callback); virtual bool WillBeginImplFrame(const viz::BeginFrameArgs& args); virtual void DidFinishImplFrame(const viz::BeginFrameArgs& args); void DidNotProduceFrame(const viz::BeginFrameAck& ack, FrameSkippedReason reason); void DidModifyTilePriorities(); // Requests that we do not produce frames until the new viz::LocalSurfaceId // has been activated. void SetTargetLocalSurfaceId( const viz::LocalSurfaceId& target_local_surface_id); const viz::LocalSurfaceId& target_local_surface_id() const { return target_local_surface_id_; } const viz::LocalSurfaceId& last_draw_local_surface_id() const { return last_draw_local_surface_id_; } LayerTreeImpl* active_tree() { return active_tree_.get(); } const LayerTreeImpl* active_tree() const { return active_tree_.get(); } LayerTreeImpl* pending_tree() { return pending_tree_.get(); } const LayerTreeImpl* pending_tree() const { return pending_tree_.get(); } LayerTreeImpl* recycle_tree() { return recycle_tree_.get(); } const LayerTreeImpl* recycle_tree() const { return recycle_tree_.get(); } // Returns the tree LTH synchronizes with. LayerTreeImpl* sync_tree() const { return CommitToActiveTree() ? active_tree_.get() : pending_tree_.get(); } virtual void CreatePendingTree(); virtual void ActivateSyncTree(); // Shortcuts to layers/nodes on the active tree. ScrollNode* InnerViewportScrollNode() const; ScrollNode* OuterViewportScrollNode() const; ScrollNode* CurrentlyScrollingNode(); const ScrollNode* CurrentlyScrollingNode() const; void QueueSwapPromiseForMainThreadScrollUpdate( std::unique_ptr<SwapPromise> swap_promise); // TODO(bokan): These input-related methods shouldn't be part of // LayerTreeHostImpl's interface. bool IsPinchGestureActive() const; // See comment in equivalent ThreadedInputHandler method for what this means. ActivelyScrollingType GetActivelyScrollingType() const; bool ScrollAffectsScrollHandler() const; bool CurrentScrollCheckerboardsDueToNoRecording() const { return current_scroll_did_checkerboard_large_area_; } void SetCurrentScrollCheckerboardsDueToNoRecording() { current_scroll_did_checkerboard_large_area_ = true; } void SetExternalPinchGestureActive(bool active); void set_force_smooth_wheel_scrolling_for_testing(bool enabled) { GetInputHandler().set_force_smooth_wheel_scrolling_for_testing(enabled); } virtual void SetVisible(bool visible); bool visible() const { return visible_; } void SetNeedsOneBeginImplFrame(); void SetNeedsRedraw(); ManagedMemoryPolicy ActualManagedMemoryPolicy() const; const gfx::Transform& DrawTransform() const; // During commit, processes and returns changes in the compositor since the // last commit. std::unique_ptr<CompositorCommitData> ProcessCompositorDeltas(); DroppedFrameCounter* dropped_frame_counter() { return &dropped_frame_counter_; } MemoryHistory* memory_history() { return memory_history_.get(); } DebugRectHistory* debug_rect_history() { return debug_rect_history_.get(); } viz::ClientResourceProvider* resource_provider() { return &resource_provider_; } BrowserControlsOffsetManager* browser_controls_manager() { return browser_controls_offset_manager_.get(); } const GlobalStateThatImpactsTilePriority& global_tile_state() { return global_tile_state_; } TaskRunnerProvider* task_runner_provider() const { return task_runner_provider_; } MutatorHost* mutator_host() const { return mutator_host_.get(); } void SetDebugState(const LayerTreeDebugState& new_debug_state); const LayerTreeDebugState& debug_state() const { return debug_state_; } void SetTreePriority(TreePriority priority); TreePriority GetTreePriority() const; // TODO(mithro): Remove this methods which exposes the internal // viz::BeginFrameArgs to external callers. virtual const viz::BeginFrameArgs& CurrentBeginFrameArgs() const; // Expected time between two begin impl frame calls. base::TimeDelta CurrentBeginFrameInterval() const; void AsValueWithFrameInto(FrameData* frame, base::trace_event::TracedValue* value) const; std::unique_ptr<base::trace_event::ConvertableToTraceFormat> AsValueWithFrame( FrameData* frame) const; void ActivationStateAsValueInto(base::trace_event::TracedValue* value) const; bool page_scale_animation_active() const { return !!page_scale_animation_; } virtual void CreateUIResource(UIResourceId uid, const UIResourceBitmap& bitmap); // Deletes a UI resource. May safely be called more than once. virtual void DeleteUIResource(UIResourceId uid); // Evict all UI resources. This differs from ClearUIResources in that this // will not immediately delete the resources' backing textures. void EvictAllUIResources(); bool EvictedUIResourcesExist() const; virtual viz::ResourceId ResourceIdForUIResource(UIResourceId uid) const; virtual bool IsUIResourceOpaque(UIResourceId uid) const; void ScheduleMicroBenchmark(std::unique_ptr<MicroBenchmarkImpl> benchmark); viz::CompositorFrameMetadata MakeCompositorFrameMetadata(); RenderFrameMetadata MakeRenderFrameMetadata(FrameData* frame); const gfx::Rect& external_viewport() const { return external_viewport_; } // Viewport rect to be used for tiling prioritization instead of the // DeviceViewport(). const gfx::Rect& viewport_rect_for_tile_priority() const { return viewport_rect_for_tile_priority_; } // When a SwapPromiseMonitor is created on the impl thread, it calls // InsertSwapPromiseMonitor() to register itself with LayerTreeHostImpl. // When the monitor is destroyed, it calls RemoveSwapPromiseMonitor() // to unregister itself. void InsertSwapPromiseMonitor(SwapPromiseMonitor* monitor); void RemoveSwapPromiseMonitor(SwapPromiseMonitor* monitor); // TODO(weiliangc): Replace RequiresHighResToDraw with scheduler waits for // ReadyToDraw. crbug.com/469175 void SetRequiresHighResToDraw() { requires_high_res_to_draw_ = true; } void ResetRequiresHighResToDraw() { requires_high_res_to_draw_ = false; } bool RequiresHighResToDraw() const { return requires_high_res_to_draw_; } // Only valid for synchronous (non-scheduled) single-threaded case. void SynchronouslyInitializeAllTiles(); bool CommitToActiveTree() const; // Virtual so tests can inject their own. virtual std::unique_ptr<RasterBufferProvider> CreateRasterBufferProvider(); bool prepare_tiles_needed() const { return tile_priorities_dirty_; } base::SingleThreadTaskRunner* GetTaskRunner() const { DCHECK(task_runner_provider_); return task_runner_provider_->HasImplThread() ? task_runner_provider_->ImplThreadTaskRunner() : task_runner_provider_->MainThreadTaskRunner(); } // Returns true if a scroll offset animation is created and false if we scroll // by the desired amount without an animation. bool ScrollAnimationCreate(const ScrollNode& scroll_node, const gfx::Vector2dF& scroll_amount, base::TimeDelta delayed_by); bool AutoScrollAnimationCreate(const ScrollNode& scroll_node, const gfx::Vector2dF& scroll_amount, float autoscroll_velocity); void SetLayerTreeMutator(std::unique_ptr<LayerTreeMutator> mutator); void SetPaintWorkletLayerPainter( std::unique_ptr<PaintWorkletLayerPainter> painter); PaintWorkletLayerPainter* GetPaintWorkletLayerPainterForTesting() const { return paint_worklet_painter_.get(); } void QueueImageDecode(int request_id, const PaintImage& image); std::vector<std::pair<int, bool>> TakeCompletedImageDecodeRequests(); // Returns mutator events to be handled by BeginMainFrame. std::unique_ptr<MutatorEvents> TakeMutatorEvents(); // Returns all of the transition request sequence ids that were finished. std::vector<uint32_t> TakeFinishedTransitionRequestSequenceIds(); void ClearCaches(); void UpdateImageDecodingHints( base::flat_map<PaintImage::Id, PaintImage::DecodingMode> decoding_mode_map); void InitializeUkm(std::unique_ptr<ukm::UkmRecorder> recorder); UkmManager* ukm_manager() { return ukm_manager_.get(); } ActiveFrameSequenceTrackers FrameSequenceTrackerActiveTypes() { return frame_trackers_.FrameSequenceTrackerActiveTypes(); } void RenewTreePriorityForTesting() { client_->RenewTreePriority(); } void SetRenderFrameObserver( std::unique_ptr<RenderFrameMetadataObserver> observer); void SetActiveURL(const GURL& url, ukm::SourceId source_id); void SetUkmSmoothnessDestination( base::WritableSharedMemoryMapping ukm_smoothness_data); // Notifies FrameTrackers, impl side callbacks that the compsitor frame // was presented. void NotifyDidPresentCompositorFrameOnImplThread( uint32_t frame_token, std::vector<PresentationTimeCallbackBuffer::CompositorCallback> callbacks, const viz::FrameTimingDetails& details); CompositorFrameReportingController* compositor_frame_reporting_controller() const { return compositor_frame_reporting_controller_.get(); } void set_pending_tree_fully_painted_for_testing(bool painted) { pending_tree_fully_painted_ = painted; } AnimatedPaintWorkletTracker& paint_worklet_tracker() { return paint_worklet_tracker_; } bool can_use_msaa() const { return can_use_msaa_; } Viewport& viewport() const { return *viewport_.get(); } TotalFrameCounter* total_frame_counter_for_testing() { return &total_frame_counter_; } DroppedFrameCounter* dropped_frame_counter_for_testing() { return &dropped_frame_counter_; } // Returns true if the client is currently compositing synchronously. bool IsInSynchronousComposite() const { return client_->IsInSynchronousComposite(); } RasterQueryQueue* GetRasterQueryQueueForTesting() const { return pending_raster_queries_.get(); } base::flat_set<viz::FrameSinkId> GetFrameSinksToThrottleForTesting() const { return throttle_decider_.ids(); } protected: LayerTreeHostImpl( const LayerTreeSettings& settings, LayerTreeHostImplClient* client, TaskRunnerProvider* task_runner_provider, RenderingStatsInstrumentation* rendering_stats_instrumentation, TaskGraphRunner* task_graph_runner, std::unique_ptr<MutatorHost> mutator_host, RasterDarkModeFilter* dark_mode_filter, int id, scoped_refptr<base::SequencedTaskRunner> image_worker_task_runner, LayerTreeHostSchedulingClient* scheduling_client); // Virtual for testing. virtual bool AnimateLayers(base::TimeTicks monotonic_time, bool is_active_tree); bool is_likely_to_require_a_draw() const { return is_likely_to_require_a_draw_; } // Removes empty or orphan RenderPasses from the frame. static void RemoveRenderPasses(FrameData* frame); LayerTreeHostImplClient* const client_; LayerTreeHostSchedulingClient* const scheduling_client_; TaskRunnerProvider* const task_runner_provider_; BeginFrameTracker current_begin_frame_tracker_; std::unique_ptr<CompositorFrameReportingController> compositor_frame_reporting_controller_; private: void CollectScrollbarUpdatesForCommit( CompositorCommitData* commit_data) const; bool ScrollAnimationCreateInternal(const ScrollNode& scroll_node, const gfx::Vector2dF& delta, base::TimeDelta delayed_by, absl::optional<float> autoscroll_velocity); void CleanUpTileManagerResources(); void CreateTileManagerResources(); void ReleaseTreeResources(); void ReleaseTileResources(); void RecreateTileResources(); void AnimateInternal(); // The function is called to update state on the sync tree after a commit // finishes or after the sync tree was created to invalidate content on the // impl thread. void UpdateSyncTreeAfterCommitOrImplSideInvalidation(); // Returns a job map for all 'dirty' PaintWorklets, e.g. PaintWorkletInputs // that do not map to a PaintRecord. PaintWorkletJobMap GatherDirtyPaintWorklets(PaintImageIdFlatSet*) const; // Called when all PaintWorklet results are ready (i.e. have been painted) for // the current pending tree. void OnPaintWorkletResultsReady(PaintWorkletJobMap results); // Called when the pending tree has been fully painted, i.e. all required data // is available to raster the tree. void NotifyPendingTreeFullyPainted(); // Returns true if status changed. bool UpdateGpuRasterizationStatus(); void UpdateTreeResourcesForGpuRasterizationIfNeeded(); bool AnimatePageScale(base::TimeTicks monotonic_time); bool AnimateScrollbars(base::TimeTicks monotonic_time); bool AnimateBrowserControls(base::TimeTicks monotonic_time); void UpdateTileManagerMemoryPolicy(const ManagedMemoryPolicy& policy); // Returns true if the damage rect is non-empty. This check includes damage // from the HUD. Should only be called when the active tree's draw properties // are valid and after updating the damage. bool HasDamage() const; // This function should only be called from PrepareToDraw, as DidDrawAllLayers // must be called if this helper function is called. Returns DRAW_SUCCESS if // the frame should be drawn. DrawResult CalculateRenderPasses(FrameData* frame); void StartScrollbarFadeRecursive(LayerImpl* layer); void SetManagedMemoryPolicy(const ManagedMemoryPolicy& policy); // Once a resource is uploaded or deleted, it is no longer an evicted id, this // removes it from the evicted set, and updates if we're able to draw now that // all UIResources are valid. void MarkUIResourceNotEvicted(UIResourceId uid); // Deletes all UIResource backings, and marks all the ids as evicted. void ClearUIResources(); // Frees the textures/bitmaps backing the UIResource, held in the // UIResourceData. void DeleteUIResourceBacking(UIResourceData data, const gpu::SyncToken& sync_token); // Callback for when a UIResource is deleted *and* no longer in use by the // display compositor. It will DeleteUIResourceBacking() if the backing was // not already deleted preemptively. void OnUIResourceReleased(UIResourceId uid, const gpu::SyncToken& sync_token, bool lost); void NotifySwapPromiseMonitorsOfSetNeedsRedraw(); private: void SetContextVisibility(bool is_visible); void ImageDecodeFinished(int request_id, bool decode_succeeded); void ShowScrollbarsForImplScroll(ElementId element_id); // Copy any opacity values already in the active tree to the pending // tree, because the active tree value always takes precedence for scrollbars. void PushScrollbarOpacitiesFromActiveToPending(); // Pushes state for image animations and checkerboarded images from the // pending to active tree. This is called during activation when a pending // tree exists, and during the commit if we are committing directly to the // active tree. void ActivateStateForImages(); void OnMemoryPressure( base::MemoryPressureListener::MemoryPressureLevel level); void AllocateLocalSurfaceId(); // Log the AverageLag events from the frame identified by |frame_token| and // the information in |details|. void LogAverageLagEvents(uint32_t frame_token, const viz::FrameTimingDetails& details); // Notifies client about the custom tracker results. void NotifyThroughputTrackerResults(const CustomTrackerResults& results); // Wrapper for checking and updating |contains_srgb_cache_|. bool CheckColorSpaceContainsSrgb(const gfx::ColorSpace& color_space) const; // Once bound, this instance owns the InputHandler. However, an InputHandler // need not be bound so this should be null-checked before dereferencing. std::unique_ptr<InputDelegateForCompositor> input_delegate_; const LayerTreeSettings settings_; // This is set to true only if: // . The compositor is running single-threaded (i.e. there is no separate // compositor/impl thread). // . There is no scheduler (which means layer-update, composite, etc. steps // happen explicitly via. synchronous calls to appropriate functions). // This is usually turned on only in some tests (e.g. web-tests). const bool is_synchronous_single_threaded_; viz::ClientResourceProvider resource_provider_; std::unordered_map<UIResourceId, UIResourceData> ui_resource_map_; // UIResources are held here once requested to be deleted until they are // released from the display compositor, then the backing can be deleted. std::unordered_map<UIResourceId, UIResourceData> deleted_ui_resources_; // Resources that were evicted by EvictAllUIResources. Resources are removed // from this when they are touched by a create or destroy from the UI resource // request queue. The resource IDs held in here do not have any backing // associated with them anymore, as that is freed at the time of eviction. std::set<UIResourceId> evicted_ui_resources_; // These are valid when has_valid_layer_tree_frame_sink_ is true. // // A pointer used for communicating with and submitting output to the display // compositor. LayerTreeFrameSink* layer_tree_frame_sink_ = nullptr; // The maximum size (either width or height) that any texture can be. Also // holds a reasonable value for software compositing bitmaps. int max_texture_size_ = 0; // The following scoped variables must not outlive the // |layer_tree_frame_sink_|. // These should be transfered to viz::ContextCacheController's // ClientBecameNotVisible() before the output surface is destroyed. std::unique_ptr<viz::ContextCacheController::ScopedVisibility> compositor_context_visibility_; std::unique_ptr<viz::ContextCacheController::ScopedVisibility> worker_context_visibility_; bool can_use_msaa_ = false; bool supports_disable_msaa_ = false; bool need_update_gpu_rasterization_status_ = false; bool use_gpu_rasterization_ = false; bool can_use_oop_rasterization_ = false; GpuRasterizationStatus gpu_rasterization_status_ = GpuRasterizationStatus::OFF_DEVICE; std::unique_ptr<RasterBufferProvider> raster_buffer_provider_; std::unique_ptr<ResourcePool> resource_pool_; std::unique_ptr<RasterQueryQueue> pending_raster_queries_; std::unique_ptr<ImageDecodeCache> image_decode_cache_; GlobalStateThatImpactsTilePriority global_tile_state_; // Tree currently being drawn. std::unique_ptr<LayerTreeImpl> active_tree_; // In impl-side painting mode, tree with possibly incomplete rasterized // content. May be promoted to active by ActivateSyncTree(). std::unique_ptr<LayerTreeImpl> pending_tree_; // In impl-side painting mode, inert tree with layers that can be recycled // by the next sync from the main thread. std::unique_ptr<LayerTreeImpl> recycle_tree_; // Tracks, for debugging purposes, the amount of scroll received (not // necessarily applied) in this compositor frame. This will be reset each // time a CompositorFrame is generated. gfx::Vector2dF scroll_accumulated_this_frame_; std::vector<std::unique_ptr<SwapPromise>> swap_promises_for_main_thread_scroll_update_; bool tile_priorities_dirty_ = false; LayerTreeDebugState debug_state_; bool visible_ = false; ManagedMemoryPolicy cached_managed_memory_policy_; TileManager tile_manager_; std::unique_ptr<BrowserControlsOffsetManager> browser_controls_offset_manager_; std::unique_ptr<PageScaleAnimation> page_scale_animation_; DroppedFrameCounter dropped_frame_counter_; TotalFrameCounter total_frame_counter_; std::unique_ptr<MemoryHistory> memory_history_; std::unique_ptr<DebugRectHistory> debug_rect_history_; // The maximum memory that would be used by the prioritized resource // manager, if there were no limit on memory usage. size_t max_memory_needed_bytes_ = 0; // Optional top-level constraints that can be set by the LayerTreeFrameSink. // - external_transform_ applies a transform above the root layer // - external_viewport_ is used DrawProperties, tile management and // glViewport/window projection matrix. // - viewport_rect_for_tile_priority_ is the rect in view space used for // tiling priority. gfx::Transform external_transform_; gfx::Rect external_viewport_; gfx::Rect viewport_rect_for_tile_priority_; bool resourceless_software_draw_ = false; gfx::Rect viewport_damage_rect_; std::unique_ptr<MutatorHost> mutator_host_; std::unique_ptr<MutatorEvents> mutator_events_; std::set<VideoFrameController*> video_frame_controllers_; RasterDarkModeFilter* const dark_mode_filter_; // Map from scroll element ID to scrollbar animation controller. // There is one animation controller per pair of overlay scrollbars. std::unordered_map<ElementId, std::unique_ptr<ScrollbarAnimationController>, ElementIdHash> scrollbar_animation_controllers_; RenderingStatsInstrumentation* rendering_stats_instrumentation_; MicroBenchmarkControllerImpl micro_benchmark_controller_; std::unique_ptr<SynchronousTaskGraphRunner> single_thread_synchronous_task_graph_runner_; // Optional callback to notify of new tree activations. base::RepeatingClosure tree_activation_callback_; TaskGraphRunner* task_graph_runner_; int id_; std::set<SwapPromiseMonitor*> swap_promise_monitor_; bool requires_high_res_to_draw_ = false; bool is_likely_to_require_a_draw_ = false; // TODO(danakj): Delete the LayerTreeFrameSink and all resources when // it's lost instead of having this bool. bool has_valid_layer_tree_frame_sink_ = false; // If it is enabled in the LayerTreeSettings, we can check damage in // WillBeginImplFrame and abort early if there is no damage. We only check // damage in WillBeginImplFrame if a recent frame had no damage. We keep // track of this with |consecutive_frame_with_damage_count_|. int consecutive_frame_with_damage_count_; std::unique_ptr<Viewport> viewport_; gfx::Size visual_device_viewport_size_; // Set to true if viewport is mobile optimized by using meta tag // <meta name="viewport" content="width=device-width"> // or // <meta name="viewport" content="initial-scale=1.0"> bool is_viewport_mobile_optimized_ = false; bool prefers_reduced_motion_ = false; bool may_throttle_if_undrawn_frames_ = true; std::unique_ptr<PendingTreeRasterDurationHistogramTimer> pending_tree_raster_duration_timer_; // These completion states to be transfered to the main thread when we // begin main frame. The pair represents a request id and the completion (ie // success) state. std::vector<std::pair<int, bool>> completed_image_decode_requests_; enum class ImplThreadPhase { IDLE, INSIDE_IMPL_FRAME, }; ImplThreadPhase impl_thread_phase_ = ImplThreadPhase::IDLE; ImageAnimationController image_animation_controller_; std::unique_ptr<UkmManager> ukm_manager_; // Provides RenderFrameMetadata to the Browser process upon the submission of // each CompositorFrame. std::unique_ptr<RenderFrameMetadataObserver> render_frame_metadata_observer_; viz::FrameTokenGenerator next_frame_token_; viz::LocalSurfaceId last_draw_local_surface_id_; base::flat_set<viz::SurfaceRange> last_draw_referenced_surfaces_; absl::optional<RenderFrameMetadata> last_draw_render_frame_metadata_; // The viz::LocalSurfaceId to unthrottle drawing for. viz::LocalSurfaceId target_local_surface_id_; viz::ChildLocalSurfaceIdAllocator child_local_surface_id_allocator_; // Indicates the direction of the last vertical scroll of the root layer. // Until the first vertical scroll occurs, this value is |kNull|. Note that // once this value is updated, it will never return to |kNull|. viz::VerticalScrollDirection last_vertical_scroll_direction_ = viz::VerticalScrollDirection::kNull; std::unique_ptr<base::MemoryPressureListener> memory_pressure_listener_; PresentationTimeCallbackBuffer presentation_time_callbacks_; const PaintImage::GeneratorClientId paint_image_generator_client_id_; FrameSequenceTrackerCollection frame_trackers_; // PaintWorklet painting is controlled from the LayerTreeHostImpl, dispatched // to the worklet thread via |paint_worklet_painter_|. std::unique_ptr<PaintWorkletLayerPainter> paint_worklet_painter_; // While PaintWorklet painting is ongoing the PendingTree is not yet fully // painted and cannot be rastered or activated. This boolean tracks whether or // not we are in that state. bool pending_tree_fully_painted_ = false; #if DCHECK_IS_ON() // Use to track when doing a synchronous draw. bool doing_sync_draw_ = false; #endif // This is used to tell the scheduler there are active scroll handlers on the // page so we should prioritize latency during a scroll to try to keep // scroll-linked effects up to data. // TODO(bokan): This is quite old and scheduling has become much more // sophisticated since so it's not clear how much value it's still providing. bool scroll_affects_scroll_handler_ = false; // Whether at least 30% of the viewport at the time of draw was // checkerboarded during a scroll. This bit can get set during a scroll and // is sticky for the duration of the scroll. bool current_scroll_did_checkerboard_large_area_ = false; // Provides support for PaintWorklets which depend on input properties that // are being animated by the compositor (aka 'animated' PaintWorklets). // Responsible for storing animated custom property values and for // invalidating PaintWorklets as the property values change. AnimatedPaintWorkletTracker paint_worklet_tracker_; AverageLagTrackingManager lag_tracking_manager_; // Helper for de-jelly logic. DeJellyState de_jelly_state_; EventsMetricsManager events_metrics_manager_; std::unique_ptr<LCDTextMetricsReporter> lcd_text_metrics_reporter_; FrameRateEstimator frame_rate_estimator_; bool has_observed_first_scroll_delay_ = false; bool enable_frame_rate_throttling_ = false; // True if we are measuring smoothness in TotalFrameCounter and // DroppedFrameCounter. Currently true when first contentful paint is done. bool is_measuring_smoothness_ = false; base::WritableSharedMemoryMapping ukm_smoothness_mapping_; // Cache for the results of calls to gfx::ColorSpace::Contains() on sRGB. This // computation is deterministic for a given color space, can be called // multiple times per frame, and incurs a non-trivial cost. // mutable because |contains_srgb_cache_| is accessed in a const method. mutable base::LRUCache<gfx::ColorSpace, bool> contains_srgb_cache_; // When enabled, calculates which frame sinks can be throttled based on // some pre-defined criteria. ThrottleDecider throttle_decider_; std::vector<uint32_t> finished_transition_request_sequence_ids_; // Must be the last member to ensure this is destroyed first in the // destruction order and invalidates all weak pointers. base::WeakPtrFactory<LayerTreeHostImpl> weak_factory_{this}; }; } // namespace cc #endif // CC_TREES_LAYER_TREE_HOST_IMPL_H_
blueboxd/chromium-legacy
media/gpu/vaapi/vp8_vaapi_video_encoder_delegate.h
<filename>media/gpu/vaapi/vp8_vaapi_video_encoder_delegate.h<gh_stars>10-100 // Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MEDIA_GPU_VAAPI_VP8_VAAPI_VIDEO_ENCODER_DELEGATE_H_ #define MEDIA_GPU_VAAPI_VP8_VAAPI_VIDEO_ENCODER_DELEGATE_H_ #include <list> #include <vector> #include "base/macros.h" #include "media/base/video_bitrate_allocation.h" #include "media/gpu/vaapi/vaapi_video_encoder_delegate.h" #include "media/gpu/vaapi/vpx_rate_control.h" #include "media/gpu/vp8_picture.h" #include "media/gpu/vp8_reference_frame_vector.h" #include "media/parsers/vp8_parser.h" namespace libvpx { struct VP8FrameParamsQpRTC; class VP8RateControlRTC; struct VP8RateControlRtcConfig; } // namespace libvpx namespace media { class VaapiWrapper; class VP8VaapiVideoEncoderDelegate : public VaapiVideoEncoderDelegate { public: struct EncodeParams { EncodeParams(); // Produce a keyframe at least once per this many frames. size_t kf_period_frames; // Bitrate allocation in bps. VideoBitrateAllocation bitrate_allocation; // Framerate in FPS. uint32_t framerate; // Quantization parameter. They are vp8 ac/dc indices and their ranges are // 0-127. uint8_t min_qp; uint8_t max_qp; }; VP8VaapiVideoEncoderDelegate(scoped_refptr<VaapiWrapper> vaapi_wrapper, base::RepeatingClosure error_cb); VP8VaapiVideoEncoderDelegate(const VP8VaapiVideoEncoderDelegate&) = delete; VP8VaapiVideoEncoderDelegate& operator=(const VP8VaapiVideoEncoderDelegate&) = delete; ~VP8VaapiVideoEncoderDelegate() override; // VaapiVideoEncoderDelegate implementation. bool Initialize(const VideoEncodeAccelerator::Config& config, const VaapiVideoEncoderDelegate::Config& ave_config) override; bool UpdateRates(const VideoBitrateAllocation& bitrate_allocation, uint32_t framerate) override; gfx::Size GetCodedSize() const override; size_t GetMaxNumOfRefFrames() const override; std::vector<gfx::Size> GetSVCLayerResolutions() override; private: void InitializeFrameHeader(); void SetFrameHeader(VP8Picture& picture, bool keyframe); void UpdateReferenceFrames(scoped_refptr<VP8Picture> picture); void Reset(); bool PrepareEncodeJob(EncodeJob& encode_job) override; void BitrateControlUpdate(uint64_t encoded_chunk_size_bytes) override; bool SubmitFrameParameters( EncodeJob& job, const EncodeParams& encode_params, scoped_refptr<VP8Picture> pic, const Vp8ReferenceFrameVector& ref_frames, const std::array<bool, kNumVp8ReferenceBuffers>& ref_frames_used); gfx::Size visible_size_; gfx::Size coded_size_; // Macroblock-aligned. // Frame count since last keyframe, reset to 0 every keyframe period. size_t frame_num_ = 0; EncodeParams current_params_; Vp8ReferenceFrameVector reference_frames_; using VP8RateControl = VPXRateControl<libvpx::VP8RateControlRtcConfig, libvpx::VP8RateControlRTC, libvpx::VP8FrameParamsQpRTC>; std::unique_ptr<VP8RateControl> rate_ctrl_; }; } // namespace media #endif // MEDIA_GPU_VAAPI_VP8_VAAPI_VIDEO_ENCODER_DELEGATE_H_
blueboxd/chromium-legacy
chrome/browser/ui/android/autofill/autofill_progress_dialog_view_android.h
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_ANDROID_AUTOFILL_AUTOFILL_PROGRESS_DIALOG_VIEW_ANDROID_H_ #define CHROME_BROWSER_UI_ANDROID_AUTOFILL_AUTOFILL_PROGRESS_DIALOG_VIEW_ANDROID_H_ #include <jni.h> #include <stddef.h> #include "base/android/scoped_java_ref.h" #include "chrome/browser/ui/autofill/payments/autofill_progress_dialog_controller.h" #include "chrome/browser/ui/autofill/payments/autofill_progress_dialog_view.h" namespace autofill { // Android implementation of the AutofillProgressDialogView. This view is owned // by the `AutofillProgressDialogControllerImpl` which lives for the duration of // the tab. class AutofillProgressDialogViewAndroid : public AutofillProgressDialogView { public: explicit AutofillProgressDialogViewAndroid( AutofillProgressDialogController* controller); ~AutofillProgressDialogViewAndroid() override; // AutofillProgressDialogView. void Dismiss(bool show_confirmation_before_closing, bool is_canceled_by_user) override; // Called by the Java code when the progress dialog is dismissed. void OnDismissed(JNIEnv* env); // Show the dialog view. void ShowDialog(); // Show the confirmation icon and text. void ShowConfirmation(); private: AutofillProgressDialogController* controller_; // The corresponding java object. base::android::ScopedJavaGlobalRef<jobject> java_object_; }; } // namespace autofill #endif // CHROME_BROWSER_UI_ANDROID_AUTOFILL_AUTOFILL_PROGRESS_DIALOG_VIEW_ANDROID_H_
blueboxd/chromium-legacy
chrome/browser/ui/autofill/payments/card_unmask_authentication_selection_dialog_view.h
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_AUTOFILL_PAYMENTS_CARD_UNMASK_AUTHENTICATION_SELECTION_DIALOG_VIEW_H_ #define CHROME_BROWSER_UI_AUTOFILL_PAYMENTS_CARD_UNMASK_AUTHENTICATION_SELECTION_DIALOG_VIEW_H_ namespace content { class WebContents; } namespace autofill { class CardUnmaskAuthenticationSelectionDialogController; // Interface that exposes the view to // CardUnmaskAuthenticationSelectionDialogControllerImpl. class CardUnmaskAuthenticationSelectionDialogView { public: // Creates a dialog and displays it as a modal on top of the web contents of // CardUnmaskAuthenticationSelectionDialogController. static CardUnmaskAuthenticationSelectionDialogView* CreateAndShow( CardUnmaskAuthenticationSelectionDialogController* controller, content::WebContents* web_contents); // Method to safely close this dialog (this also includes the case where the // controller is destroyed first). |user_closed_dialog| indicates whether the // dismissal was triggered by user closing the dialog. virtual void Dismiss(bool user_closed_dialog) = 0; }; } // namespace autofill #endif // CHROME_BROWSER_UI_AUTOFILL_PAYMENTS_CARD_UNMASK_AUTHENTICATION_SELECTION_DIALOG_VIEW_H_
blueboxd/chromium-legacy
chrome/browser/ui/toolbar/app_menu_model.h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_TOOLBAR_APP_MENU_MODEL_H_ #define CHROME_BROWSER_UI_TOOLBAR_APP_MENU_MODEL_H_ #include <memory> #include "base/macros.h" #include "base/timer/elapsed_timer.h" #include "build/chromeos_buildflags.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/ui/tabs/tab_strip_model_observer.h" #include "components/prefs/pref_change_registrar.h" #include "content/public/browser/host_zoom_map.h" #include "content/public/browser/web_contents_observer.h" #include "ui/base/accelerators/accelerator.h" #include "ui/base/interaction/element_identifier.h" #include "ui/base/models/button_menu_item_model.h" #include "ui/base/models/simple_menu_model.h" class AppMenuIconController; class BookmarkSubMenuModel; class Browser; namespace { class MockAppMenuModel; } // namespace // Values should correspond to 'WrenchMenuAction' enum in enums.xml. enum AppMenuAction { MENU_ACTION_NEW_TAB = 0, MENU_ACTION_NEW_WINDOW = 1, MENU_ACTION_NEW_INCOGNITO_WINDOW = 2, MENU_ACTION_SHOW_BOOKMARK_BAR = 3, MENU_ACTION_SHOW_BOOKMARK_MANAGER = 4, MENU_ACTION_IMPORT_SETTINGS = 5, MENU_ACTION_BOOKMARK_THIS_TAB = 6, MENU_ACTION_BOOKMARK_ALL_TABS = 7, MENU_ACTION_PIN_TO_START_SCREEN = 8, MENU_ACTION_RESTORE_TAB = 9, MENU_ACTION_DISTILL_PAGE = 13, MENU_ACTION_SAVE_PAGE = 14, MENU_ACTION_FIND = 15, MENU_ACTION_PRINT = 16, MENU_ACTION_CUT = 17, MENU_ACTION_COPY = 18, MENU_ACTION_PASTE = 19, MENU_ACTION_CREATE_HOSTED_APP = 20, MENU_ACTION_MANAGE_EXTENSIONS = 22, MENU_ACTION_TASK_MANAGER = 23, MENU_ACTION_CLEAR_BROWSING_DATA = 24, MENU_ACTION_VIEW_SOURCE = 25, MENU_ACTION_DEV_TOOLS = 26, MENU_ACTION_DEV_TOOLS_CONSOLE = 27, MENU_ACTION_DEV_TOOLS_DEVICES = 28, MENU_ACTION_PROFILING_ENABLED = 29, MENU_ACTION_ZOOM_MINUS = 30, MENU_ACTION_ZOOM_PLUS = 31, MENU_ACTION_FULLSCREEN = 32, MENU_ACTION_SHOW_HISTORY = 33, MENU_ACTION_SHOW_DOWNLOADS = 34, MENU_ACTION_SHOW_SYNC_SETUP = 35, MENU_ACTION_OPTIONS = 36, MENU_ACTION_ABOUT = 37, MENU_ACTION_HELP_PAGE_VIA_MENU = 38, MENU_ACTION_FEEDBACK = 39, MENU_ACTION_TOGGLE_REQUEST_TABLET_SITE = 40, MENU_ACTION_EXIT = 43, MENU_ACTION_RECENT_TAB = 41, MENU_ACTION_BOOKMARK_OPEN = 42, MENU_ACTION_UPGRADE_DIALOG = 44, MENU_ACTION_CAST = 45, MENU_ACTION_BETA_FORUM = 46, MENU_ACTION_COPY_URL = 47, MENU_ACTION_OPEN_IN_CHROME = 48, MENU_ACTION_SITE_SETTINGS = 49, MENU_ACTION_APP_INFO = 50, // Only used by WebAppMenuModel: MENU_ACTION_UNINSTALL_APP = 51, MENU_ACTION_CHROME_TIPS = 53, MENU_ACTION_CHROME_WHATS_NEW = 54, LIMIT_MENU_ACTION }; // Function to record WrenchMenu.MenuAction histogram void LogWrenchMenuAction(AppMenuAction action_id); // A menu model that builds the contents of the zoom menu. class ZoomMenuModel : public ui::SimpleMenuModel { public: explicit ZoomMenuModel(ui::SimpleMenuModel::Delegate* delegate); ZoomMenuModel(const ZoomMenuModel&) = delete; ZoomMenuModel& operator=(const ZoomMenuModel&) = delete; ~ZoomMenuModel() override; private: void Build(); }; class ToolsMenuModel : public ui::SimpleMenuModel { public: ToolsMenuModel(ui::SimpleMenuModel::Delegate* delegate, Browser* browser); ToolsMenuModel(const ToolsMenuModel&) = delete; ToolsMenuModel& operator=(const ToolsMenuModel&) = delete; ~ToolsMenuModel() override; private: void Build(Browser* browser); }; // A menu model that builds the contents of the app menu. class AppMenuModel : public ui::SimpleMenuModel, public ui::SimpleMenuModel::Delegate, public ui::ButtonMenuItemModel::Delegate, public TabStripModelObserver, public content::WebContentsObserver { public: DECLARE_CLASS_ELEMENT_IDENTIFIER_VALUE(AppMenuModel, kHistoryMenuItem); // First command ID to use for the recent tabs menu. This is one higher than // the first command id used for the bookmarks menus, as the command ids for // these menus should be offset to avoid conflicts. static const int kMinRecentTabsCommandId = IDC_FIRST_UNBOUNDED_MENU + 1; // Number of menus within the app menu with an arbitrarily high (variable) // number of menu items. For example, the number of bookmarks menu items // varies depending upon the underlying model. Currently, this accounts for // the bookmarks and recent tabs menus. static const int kNumUnboundedMenuTypes = 2; // Creates an app menu model for the given browser. Init() must be called // before passing this to an AppMenu. |app_menu_icon_controller|, if provided, // is used to decide whether or not to include an item for opening the upgrade // dialog. AppMenuModel(ui::AcceleratorProvider* provider, Browser* browser, AppMenuIconController* app_menu_icon_controller = nullptr); AppMenuModel(const AppMenuModel&) = delete; AppMenuModel& operator=(const AppMenuModel&) = delete; ~AppMenuModel() override; // Runs Build() and registers observers. void Init(); // Overridden for ButtonMenuItemModel::Delegate: bool DoesCommandIdDismissMenu(int command_id) const override; // Overridden for both ButtonMenuItemModel::Delegate and SimpleMenuModel: bool IsItemForCommandIdDynamic(int command_id) const override; std::u16string GetLabelForCommandId(int command_id) const override; ui::ImageModel GetIconForCommandId(int command_id) const override; void ExecuteCommand(int command_id, int event_flags) override; bool IsCommandIdChecked(int command_id) const override; bool IsCommandIdEnabled(int command_id) const override; bool IsCommandIdVisible(int command_id) const override; bool GetAcceleratorForCommandId(int command_id, ui::Accelerator* accelerator) const override; // Overridden from TabStripModelObserver: void OnTabStripModelChanged( TabStripModel* tab_strip_model, const TabStripModelChange& change, const TabStripSelectionChange& selection) override; // content::WebContentsObserver: void NavigationEntryCommitted( const content::LoadCommittedDetails& load_details) override; // Getters. Browser* browser() const { return browser_; } BookmarkSubMenuModel* bookmark_sub_menu_model() const { return bookmark_sub_menu_model_.get(); } // Calculates |zoom_label_| in response to a zoom change. void UpdateZoomControls(); protected: // Helper function to record the menu action in a UMA histogram. virtual void LogMenuAction(AppMenuAction action_id); // Builds the menu model, adding appropriate menu items. virtual void Build(); // Appends a clipboard menu (without separators). void CreateCutCopyPasteMenu(); // Appends a zoom menu (without separators). void CreateZoomMenu(); private: friend class ::MockAppMenuModel; bool ShouldShowNewIncognitoWindowMenuItem(); // Adds actionable global error menu items to the menu. // Examples: Extension permissions and sign in errors. // Returns a boolean indicating whether any menu items were added. bool AddGlobalErrorMenuItems(); void OnZoomLevelChanged(const content::HostZoomMap::ZoomLevelChange& change); // Called when a command is selected. // Logs UMA metrics about which command was chosen and how long the user // took to select the command. void LogMenuMetrics(int command_id); #if BUILDFLAG(IS_CHROMEOS_ASH) // Disables/Enables the settings item based on kSystemFeaturesDisableList // pref. void UpdateSettingsItemState(); #endif // BUILDFLAG(IS_CHROMEOS_ASH) // Time menu has been open. Used by LogMenuMetrics() to record the time // to action when the user selects a menu item. base::ElapsedTimer timer_; // Whether a UMA menu action has been recorded since the menu is open. // Only the first time to action is recorded since some commands // (zoom controls) don't dimiss the menu. bool uma_action_recorded_; // Models for the special menu items with buttons. std::unique_ptr<ui::ButtonMenuItemModel> edit_menu_item_model_; std::unique_ptr<ui::ButtonMenuItemModel> zoom_menu_item_model_; // Label of the zoom label in the zoom menu item. std::u16string zoom_label_; // Bookmark submenu. std::unique_ptr<BookmarkSubMenuModel> bookmark_sub_menu_model_; // Other submenus. std::vector<std::unique_ptr<ui::SimpleMenuModel>> sub_menus_; ui::AcceleratorProvider* provider_; // weak Browser* const browser_; // weak AppMenuIconController* const app_menu_icon_controller_; base::CallbackListSubscription browser_zoom_subscription_; PrefChangeRegistrar local_state_pref_change_registrar_; }; #endif // CHROME_BROWSER_UI_TOOLBAR_APP_MENU_MODEL_H_
blueboxd/chromium-legacy
third_party/blink/renderer/core/layout/geometry/physical_offset.h
// 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_BLINK_RENDERER_CORE_LAYOUT_GEOMETRY_PHYSICAL_OFFSET_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_GEOMETRY_PHYSICAL_OFFSET_H_ #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/platform/geometry/layout_point.h" #include "third_party/blink/renderer/platform/geometry/layout_size.h" #include "third_party/blink/renderer/platform/geometry/layout_unit.h" #include "third_party/blink/renderer/platform/text/writing_direction_mode.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/point_f.h" #include "ui/gfx/geometry/vector2d.h" #include "ui/gfx/geometry/vector2d_f.h" namespace blink { class LayoutPoint; class LayoutSize; struct LogicalOffset; struct PhysicalSize; // PhysicalOffset is the position of a rect (typically a fragment) relative to // its parent rect in the physical coordinate system. // For more information about physical and logical coordinate systems, see: // https://chromium.googlesource.com/chromium/src/+/master/third_party/blink/renderer/core/layout/README.md#coordinate-spaces struct CORE_EXPORT PhysicalOffset { constexpr PhysicalOffset() = default; constexpr PhysicalOffset(LayoutUnit left, LayoutUnit top) : left(left), top(top) {} // For testing only. It's defined in core/testing/core_unit_test_helper.h. inline PhysicalOffset(int left, int top); LayoutUnit left; LayoutUnit top; // Converts a physical offset to a logical offset. See: // https://drafts.csswg.org/css-writing-modes-3/#logical-to-physical // @param outer_size the size of the rect (typically a fragment). // @param inner_size the size of the inner rect (typically a child fragment). LogicalOffset ConvertToLogical(WritingDirectionMode writing_direction, PhysicalSize outer_size, PhysicalSize inner_size) const; constexpr bool IsZero() const { return !left && !top; } constexpr bool HasFraction() const { return left.HasFraction() || top.HasFraction(); } void ClampNegativeToZero() { left = std::max(left, LayoutUnit()); top = std::max(top, LayoutUnit()); } PhysicalOffset operator+(const PhysicalOffset& other) const { return PhysicalOffset{this->left + other.left, this->top + other.top}; } PhysicalOffset& operator+=(const PhysicalOffset& other) { *this = *this + other; return *this; } PhysicalOffset operator-() const { return PhysicalOffset{-this->left, -this->top}; } PhysicalOffset operator-(const PhysicalOffset& other) const { return PhysicalOffset{this->left - other.left, this->top - other.top}; } PhysicalOffset& operator-=(const PhysicalOffset& other) { *this = *this - other; return *this; } constexpr bool operator==(const PhysicalOffset& other) const { return other.left == left && other.top == top; } constexpr bool operator!=(const PhysicalOffset& other) const { return !(*this == other); } // Conversions from/to existing code. New code prefers type safety for // logical/physical distinctions. constexpr explicit PhysicalOffset(const LayoutPoint& point) : left(point.X()), top(point.Y()) {} constexpr explicit PhysicalOffset(const LayoutSize& size) : left(size.Width()), top(size.Height()) {} // Conversions from/to existing code. New code prefers type safety for // logical/physical distinctions. constexpr LayoutPoint ToLayoutPoint() const { return {left, top}; } constexpr LayoutSize ToLayoutSize() const { return {left, top}; } explicit PhysicalOffset(const IntPoint& point) : left(point.x()), top(point.y()) {} explicit PhysicalOffset(const IntSize& size) : left(size.width()), top(size.height()) {} explicit PhysicalOffset(const gfx::Point& point) : left(point.x()), top(point.y()) {} explicit PhysicalOffset(const gfx::Vector2d& vector) : left(vector.x()), top(vector.y()) {} static PhysicalOffset FromFloatPointFloor(const FloatPoint& point) { return {LayoutUnit::FromFloatFloor(point.x()), LayoutUnit::FromFloatFloor(point.y())}; } static PhysicalOffset FromFloatPointRound(const FloatPoint& point) { return {LayoutUnit::FromFloatRound(point.x()), LayoutUnit::FromFloatRound(point.y())}; } static PhysicalOffset FromFloatSizeFloor(const FloatSize& size) { return {LayoutUnit::FromFloatFloor(size.width()), LayoutUnit::FromFloatFloor(size.height())}; } static PhysicalOffset FromFloatSizeRound(const FloatSize& size) { return {LayoutUnit::FromFloatRound(size.width()), LayoutUnit::FromFloatRound(size.height())}; } static PhysicalOffset FromPointFFloor(const gfx::PointF& point) { return {LayoutUnit::FromFloatFloor(point.x()), LayoutUnit::FromFloatFloor(point.y())}; } static PhysicalOffset FromPointFRound(const gfx::PointF& point) { return {LayoutUnit::FromFloatRound(point.x()), LayoutUnit::FromFloatRound(point.y())}; } static PhysicalOffset FromVector2dFFloor(const gfx::Vector2dF& vector) { return {LayoutUnit::FromFloatFloor(vector.x()), LayoutUnit::FromFloatFloor(vector.y())}; } static PhysicalOffset FromVector2dFRound(const gfx::Vector2dF& vector) { return {LayoutUnit::FromFloatRound(vector.x()), LayoutUnit::FromFloatRound(vector.y())}; } void Scale(float s) { left *= s; top *= s; } constexpr explicit operator FloatPoint() const { return {left, top}; } constexpr explicit operator FloatSize() const { return {left, top}; } constexpr explicit operator gfx::PointF() const { return {left, top}; } constexpr explicit operator gfx::Vector2dF() const { return {left, top}; } String ToString() const; }; // TODO(crbug.com/962299): These functions should upgraded to force correct // pixel snapping in a type-safe way. inline IntPoint RoundedIntPoint(const PhysicalOffset& o) { return {o.left.Round(), o.top.Round()}; } inline IntPoint FlooredIntPoint(const PhysicalOffset& o) { return {o.left.Floor(), o.top.Floor()}; } inline IntPoint CeiledIntPoint(const PhysicalOffset& o) { return {o.left.Ceil(), o.top.Ceil()}; } // TODO(wangxianzhu): For temporary conversion from LayoutPoint/LayoutSize to // PhysicalOffset, where the input will be changed to PhysicalOffset soon, to // avoid redundant PhysicalOffset() which can't be discovered by the compiler. inline PhysicalOffset PhysicalOffsetToBeNoop(const LayoutPoint& p) { return PhysicalOffset(p); } inline PhysicalOffset PhysicalOffsetToBeNoop(const LayoutSize& s) { return PhysicalOffset(s); } CORE_EXPORT std::ostream& operator<<(std::ostream&, const PhysicalOffset&); } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_GEOMETRY_PHYSICAL_OFFSET_H_
blueboxd/chromium-legacy
chromecast/cast_core/runtime_application_base.h
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROMECAST_CAST_CORE_RUNTIME_APPLICATION_BASE_H_ #define CHROMECAST_CAST_CORE_RUNTIME_APPLICATION_BASE_H_ #include <memory> #include <string> #include "base/callback.h" #include "base/memory/weak_ptr.h" #include "chromecast/browser/cast_web_view.h" #include "chromecast/cast_core/grpc_server.h" #include "chromecast/cast_core/runtime_application.h" #include "chromecast/cast_core/runtime_application_service_grpc_impl.h" #include "chromecast/cast_core/runtime_message_port_application_service_grpc_impl.h" #include "third_party/cast_core/public/src/proto/v2/core_application_service.grpc.pb.h" namespace chromecast { class CastWebService; // This class is for sharing code between Web and streaming RuntimeApplication // implementations, including Load and Launch behavior. class RuntimeApplicationBase : public RuntimeApplication, public GrpcServer, public RuntimeApplicationServiceDelegate, public RuntimeMessagePortApplicationServiceDelegate, public CastWebView::Delegate { public: ~RuntimeApplicationBase() override; protected: using CoreApplicationServiceGrpc = cast::v2::CoreApplicationService::Stub; // |web_service| is expected to exist for the lifetime of this instance. RuntimeApplicationBase(mojom::RendererType renderer_type_used, CastWebService* web_service, scoped_refptr<base::SequencedTaskRunner> task_runner); // Processes an incoming |message|, returning the status of this processing in // |response| after being received over gRPC. virtual void HandleMessage(const cast::web::Message& message, cast::web::MessagePortStatus* response) = 0; // Called when a new CastWebView is created. virtual CastWebView::Scoped CreateWebView( CoreApplicationServiceGrpc* grpc_stub); // Called following the creation of a CastWebView, with which // |cast_web_contents is associated. Returns the GURL to which the // CastWebView should navigate. virtual GURL ProcessWebView(CoreApplicationServiceGrpc* grpc_stub, CastWebContents* cast_web_contents) = 0; // Stops the running application. Must be called before destruction of any // instance of the implementing object. virtual void StopApplication(); // Sets that the application has been started - the meaning of which is // application-specific. void SetApplicationStarted(); scoped_refptr<base::SequencedTaskRunner> task_runner() { return task_runner_; } // Returns a pointer to CastWebService. CastWebService* cast_web_service() const { return web_service_; } // RuntimeApplication implementation: bool Load(const cast::runtime::LoadApplicationRequest& request) override; bool Launch(const cast::runtime::LaunchApplicationRequest& request) override; // RuntimeApplicationServiceDelegate implementation: void SetUrlRewriteRules(const cast::v2::SetUrlRewriteRulesRequest& request, cast::v2::SetUrlRewriteRulesResponse* response, GrpcMethod* callback) override; private: // Called following Launch() on |task_runner_|. void FinishLaunch(std::string core_application_service_endpoint); // RuntimeMessagePortApplicationServiceDelegate implementation: void PostMessage(const cast::web::Message& request, cast::web::MessagePortStatus* response, GrpcMethod* callback) override; // gRPC RPC Wrappers. cast::v2::RuntimeApplicationService::AsyncService grpc_app_service_; cast::v2::RuntimeMessagePortApplicationService::AsyncService grpc_message_port_service_; std::unique_ptr<CoreApplicationServiceGrpc> core_app_stub_; // The |web_service_| used to create |cast_web_view_|. CastWebService* const web_service_; // The WebView associated with the window in which the Cast application is // displayed. CastWebView::Scoped cast_web_view_; scoped_refptr<base::SequencedTaskRunner> task_runner_; // Set to true when StopApplication() is called. This variable is required // rather than always executing StopApplication() in the dtor due to how // virtual function calls are handled during destruction. bool is_application_stopped_ = false; // Renderer type used by this application. mojom::RendererType renderer_type_; base::WeakPtrFactory<RuntimeApplicationBase> weak_factory_{this}; }; } // namespace chromecast #endif // CHROMECAST_CAST_CORE_RUNTIME_APPLICATION_BASE_H_
blueboxd/chromium-legacy
services/viz/public/cpp/compositing/compositor_render_pass_mojom_traits.h
// 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 SERVICES_VIZ_PUBLIC_CPP_COMPOSITING_COMPOSITOR_RENDER_PASS_MOJOM_TRAITS_H_ #define SERVICES_VIZ_PUBLIC_CPP_COMPOSITING_COMPOSITOR_RENDER_PASS_MOJOM_TRAITS_H_ #include <memory> #include <vector> #include "base/check.h" #include "components/viz/common/quads/compositor_render_pass.h" #include "components/viz/common/surfaces/region_capture_bounds.h" #include "components/viz/common/surfaces/subtree_capture_id.h" #include "services/viz/public/cpp/compositing/copy_output_request_mojom_traits.h" #include "services/viz/public/cpp/compositing/quads_mojom_traits.h" #include "services/viz/public/mojom/compositing/compositor_render_pass.mojom-shared.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/gfx/ipc/color/gfx_param_traits.h" #include "ui/gfx/mojom/rrect_f_mojom_traits.h" #include "ui/gfx/mojom/transform_mojom_traits.h" namespace mojo { template <> struct StructTraits<viz::mojom::CompositorRenderPassDataView, std::unique_ptr<viz::CompositorRenderPass>> { static viz::CompositorRenderPassId id( const std::unique_ptr<viz::CompositorRenderPass>& input) { DCHECK(input->id); return input->id; } static const gfx::Rect& output_rect( const std::unique_ptr<viz::CompositorRenderPass>& input) { return input->output_rect; } static const gfx::Rect& damage_rect( const std::unique_ptr<viz::CompositorRenderPass>& input) { return input->damage_rect; } static const gfx::Transform& transform_to_root_target( const std::unique_ptr<viz::CompositorRenderPass>& input) { return input->transform_to_root_target; } static const cc::FilterOperations& filters( const std::unique_ptr<viz::CompositorRenderPass>& input) { return input->filters; } static const cc::FilterOperations& backdrop_filters( const std::unique_ptr<viz::CompositorRenderPass>& input) { return input->backdrop_filters; } static absl::optional<gfx::RRectF> backdrop_filter_bounds( const std::unique_ptr<viz::CompositorRenderPass>& input) { return input->backdrop_filter_bounds; } static viz::SubtreeCaptureId subtree_capture_id( const std::unique_ptr<viz::CompositorRenderPass>& input) { DCHECK_LE(input->subtree_size.width(), input->output_rect.size().width()); DCHECK_LE(input->subtree_size.height(), input->output_rect.size().height()); return input->subtree_capture_id; } static gfx::Size subtree_size( const std::unique_ptr<viz::CompositorRenderPass>& input) { return input->subtree_size; } // TODO(https://crbug.com/1129604): figure out a better way to handle // this optional value. static const absl::optional<viz::RegionCaptureBounds> capture_bounds( const std::unique_ptr<viz::CompositorRenderPass>& input) { return input->capture_bounds ? absl::optional<viz::RegionCaptureBounds>( *input->capture_bounds) : absl::nullopt; } static viz::SharedElementResourceId shared_element_resource_id( const std::unique_ptr<viz::CompositorRenderPass>& input) { return input->shared_element_resource_id; } static bool has_transparent_background( const std::unique_ptr<viz::CompositorRenderPass>& input) { return input->has_transparent_background; } static bool has_per_quad_damage( const std::unique_ptr<viz::CompositorRenderPass>& input) { return input->has_per_quad_damage; } static bool cache_render_pass( const std::unique_ptr<viz::CompositorRenderPass>& input) { return input->cache_render_pass; } static bool has_damage_from_contributing_content( const std::unique_ptr<viz::CompositorRenderPass>& input) { return input->has_damage_from_contributing_content; } static bool generate_mipmap( const std::unique_ptr<viz::CompositorRenderPass>& input) { return input->generate_mipmap; } static const std::vector<std::unique_ptr<viz::CopyOutputRequest>>& copy_requests(const std::unique_ptr<viz::CompositorRenderPass>& input) { return input->copy_requests; } static const viz::QuadList& quad_list( const std::unique_ptr<viz::CompositorRenderPass>& input) { return input->quad_list; } static bool Read(viz::mojom::CompositorRenderPassDataView data, std::unique_ptr<viz::CompositorRenderPass>* out); }; } // namespace mojo #endif // SERVICES_VIZ_PUBLIC_CPP_COMPOSITING_COMPOSITOR_RENDER_PASS_MOJOM_TRAITS_H_
blueboxd/chromium-legacy
ash/webui/projector_app/annotator_tool.h
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_WEBUI_PROJECTOR_APP_ANNOTATOR_TOOL_H_ #define ASH_WEBUI_PROJECTOR_APP_ANNOTATOR_TOOL_H_ #include "base/component_export.h" #include "third_party/skia/include/core/SkColor.h" namespace base { class Value; } // namespace base namespace chromeos { // The annotator tool type. enum class COMPONENT_EXPORT(PROJECTOR) AnnotatorToolType { kMarker = 0, kPen, kHighlighter, kEraser, // TODO(b/196245932) Add support for laser pointer after confirming we are // implementing it inside the annotator. }; // The tool that the annotator will use. struct COMPONENT_EXPORT(PROJECTOR) AnnotatorTool { static AnnotatorTool FromValue(const base::Value& value); base::Value ToValue() const; bool operator==(const AnnotatorTool& rhs) const; // The color of of the annotator. SkColor color = SK_ColorBLACK; // The size of the annotator stroke tip. int size = 16; // The type of the annotator tool. AnnotatorToolType type = AnnotatorToolType::kMarker; }; } // namespace chromeos #endif // ASH_WEBUI_PROJECTOR_APP_ANNOTATOR_TOOL_H_
blueboxd/chromium-legacy
chromeos/components/eche_app_ui/eche_presence_manager.h
<filename>chromeos/components/eche_app_ui/eche_presence_manager.h // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROMEOS_COMPONENTS_ECHE_APP_UI_ECHE_PRESENCE_MANAGER_H_ #define CHROMEOS_COMPONENTS_ECHE_APP_UI_ECHE_PRESENCE_MANAGER_H_ #include <memory> #include "base/memory/weak_ptr.h" #include "base/timer/timer.h" #include "chromeos/components/eche_app_ui/eche_feature_status_provider.h" #include "chromeos/components/eche_app_ui/eche_message_receiver.h" #include "chromeos/components/eche_app_ui/feature_status_provider.h" namespace chromeos { namespace device_sync { class DeviceSyncClient; } // namespace device_sync namespace multidevice_setup { class MultiDeviceSetupClient; } // namespace multidevice_setup namespace secure_channel { class PresenceMonitorClient; } // namespace secure_channel namespace eche_app { class EcheConnector; // Control presence monitoring and the sending of keepalives. class EchePresenceManager : public FeatureStatusProvider::Observer, public EcheMessageReceiver::Observer { public: EchePresenceManager( EcheFeatureStatusProvider* eche_feature_status_provider, device_sync::DeviceSyncClient* device_sync_client, multidevice_setup::MultiDeviceSetupClient* multidevice_setup_client, std::unique_ptr<secure_channel::PresenceMonitorClient> presence_monitor_client, EcheConnector* eche_connector, EcheMessageReceiver* eche_message_receiver); ~EchePresenceManager() override; EchePresenceManager(const EchePresenceManager&) = delete; EchePresenceManager& operator=(const EchePresenceManager&) = delete; private: // FeatureStatusProvider::Observer: void OnFeatureStatusChanged() override; // EcheMessageReceiver::Observer: void OnStatusChange(proto::StatusChangeType status_change_type) override; void OnSendAppsSetupResponseReceived( proto::SendAppsSetupResponse apps_setup_response) override {} void OnGetAppsAccessStateResponseReceived( proto::GetAppsAccessStateResponse apps_access_state_response) override {} void OnReady(); void OnDeviceSeen(); void UpdateMonitoringStatus(); void StartMonitoring(); void StopMonitoring(); void OnTimerExpired(); EcheFeatureStatusProvider* eche_feature_status_provider_; device_sync::DeviceSyncClient* device_sync_client_; multidevice_setup::MultiDeviceSetupClient* multidevice_setup_client_; std::unique_ptr<secure_channel::PresenceMonitorClient> presence_monitor_client_; EcheConnector* eche_connector_; EcheMessageReceiver* eche_message_receiver_; base::RepeatingTimer timer_; bool stream_running_ = false; bool is_monitoring_ = false; base::TimeTicks device_last_seen_time_; base::WeakPtrFactory<EchePresenceManager> weak_ptr_factory_{this}; }; } // namespace eche_app } // namespace chromeos #endif // CHROMEOS_COMPONENTS_ECHE_APP_UI_ECHE_PRESENCE_MANAGER_H_
blueboxd/chromium-legacy
media/parsers/vp8_parser.h
// 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. // // This file contains an implementation of a VP8 raw stream parser, // as defined in RFC 6386. #ifndef MEDIA_PARSERS_VP8_PARSER_H_ #define MEDIA_PARSERS_VP8_PARSER_H_ #include <stddef.h> #include <stdint.h> #include "base/macros.h" #include "media/parsers/media_parsers_export.h" #include "media/parsers/vp8_bool_decoder.h" namespace media { // See spec for definitions of values/fields. const size_t kMaxMBSegments = 4; const size_t kNumMBFeatureTreeProbs = 3; // Member of Vp8FrameHeader and will be 0-initialized // in Vp8FrameHeader's constructor. struct Vp8SegmentationHeader { enum SegmentFeatureMode { FEATURE_MODE_DELTA = 0, FEATURE_MODE_ABSOLUTE = 1 }; bool segmentation_enabled; bool update_mb_segmentation_map; bool update_segment_feature_data; SegmentFeatureMode segment_feature_mode; int8_t quantizer_update_value[kMaxMBSegments]; int8_t lf_update_value[kMaxMBSegments]; static const int kDefaultSegmentProb = 255; uint8_t segment_prob[kNumMBFeatureTreeProbs]; }; const size_t kNumBlockContexts = 4; // Member of Vp8FrameHeader and will be 0-initialized // in Vp8FrameHeader's constructor. struct Vp8LoopFilterHeader { enum Type { LOOP_FILTER_TYPE_NORMAL = 0, LOOP_FILTER_TYPE_SIMPLE = 1 }; Type type; uint8_t level; uint8_t sharpness_level; bool loop_filter_adj_enable; bool mode_ref_lf_delta_update; int8_t ref_frame_delta[kNumBlockContexts]; int8_t mb_mode_delta[kNumBlockContexts]; }; // Member of Vp8FrameHeader and will be 0-initialized // in Vp8FrameHeader's constructor. struct Vp8QuantizationHeader { uint8_t y_ac_qi; int8_t y_dc_delta; int8_t y2_dc_delta; int8_t y2_ac_delta; int8_t uv_dc_delta; int8_t uv_ac_delta; }; const size_t kNumBlockTypes = 4; const size_t kNumCoeffBands = 8; const size_t kNumPrevCoeffContexts = 3; const size_t kNumEntropyNodes = 11; const size_t kNumMVContexts = 2; const size_t kNumMVProbs = 19; const size_t kNumYModeProbs = 4; const size_t kNumUVModeProbs = 3; // Member of Vp8FrameHeader and will be 0-initialized // in Vp8FrameHeader's constructor. struct Vp8EntropyHeader { uint8_t coeff_probs[kNumBlockTypes][kNumCoeffBands][kNumPrevCoeffContexts] [kNumEntropyNodes]; uint8_t y_mode_probs[kNumYModeProbs]; uint8_t uv_mode_probs[kNumUVModeProbs]; uint8_t mv_probs[kNumMVContexts][kNumMVProbs]; }; const size_t kMaxDCTPartitions = 8; const size_t kNumVp8ReferenceBuffers = 3; enum Vp8RefType : size_t { VP8_FRAME_LAST = 0, VP8_FRAME_GOLDEN = 1, VP8_FRAME_ALTREF = 2, }; struct MEDIA_PARSERS_EXPORT Vp8FrameHeader { Vp8FrameHeader(); ~Vp8FrameHeader(); Vp8FrameHeader& operator=(const Vp8FrameHeader&); Vp8FrameHeader(const Vp8FrameHeader&); enum FrameType { KEYFRAME = 0, INTERFRAME = 1 }; bool IsKeyframe() const { return frame_type == KEYFRAME; } enum GoldenRefreshMode { NO_GOLDEN_REFRESH = 0, COPY_LAST_TO_GOLDEN = 1, COPY_ALT_TO_GOLDEN = 2, }; enum AltRefreshMode { NO_ALT_REFRESH = 0, COPY_LAST_TO_ALT = 1, COPY_GOLDEN_TO_ALT = 2, }; FrameType frame_type; uint8_t version; bool is_experimental; bool show_frame; size_t first_part_size; uint16_t width; uint8_t horizontal_scale; uint16_t height; uint8_t vertical_scale; Vp8SegmentationHeader segmentation_hdr; Vp8LoopFilterHeader loopfilter_hdr; Vp8QuantizationHeader quantization_hdr; size_t num_of_dct_partitions; Vp8EntropyHeader entropy_hdr; bool refresh_entropy_probs; bool refresh_golden_frame; bool refresh_alternate_frame; GoldenRefreshMode copy_buffer_to_golden; AltRefreshMode copy_buffer_to_alternate; uint8_t sign_bias_golden; uint8_t sign_bias_alternate; bool refresh_last; bool mb_no_skip_coeff; uint8_t prob_skip_false; uint8_t prob_intra; uint8_t prob_last; uint8_t prob_gf; const uint8_t* data; size_t frame_size; size_t dct_partition_sizes[kMaxDCTPartitions]; // Offset in bytes from data. off_t first_part_offset; // Offset in bits from first_part_offset. off_t macroblock_bit_offset; // Bool decoder state uint8_t bool_dec_range; uint8_t bool_dec_value; uint8_t bool_dec_count; // Color range information. bool is_full_range; }; // A parser for raw VP8 streams as specified in RFC 6386. class MEDIA_PARSERS_EXPORT Vp8Parser { public: Vp8Parser(); Vp8Parser(const Vp8Parser&) = delete; Vp8Parser& operator=(const Vp8Parser&) = delete; ~Vp8Parser(); // Try to parse exactly one VP8 frame starting at |ptr| and of size |size|, // filling the parsed data in |fhdr|. Return true on success. // Size has to be exactly the size of the frame and coming from the caller, // who needs to acquire it from elsewhere (normally from a container). bool ParseFrame(const uint8_t* ptr, size_t size, Vp8FrameHeader* fhdr); private: bool ParseFrameTag(Vp8FrameHeader* fhdr); bool ParseFrameHeader(Vp8FrameHeader* fhdr); bool ParseSegmentationHeader(bool keyframe); bool ParseLoopFilterHeader(bool keyframe); bool ParseQuantizationHeader(Vp8QuantizationHeader* qhdr); bool ParseTokenProbs(Vp8EntropyHeader* ehdr, bool update_curr_probs); bool ParseIntraProbs(Vp8EntropyHeader* ehdr, bool update_curr_probs, bool keyframe); bool ParseMVProbs(Vp8EntropyHeader* ehdr, bool update_curr_probs); bool ParsePartitions(Vp8FrameHeader* fhdr); void ResetProbs(); // These persist across calls to ParseFrame() and may be used and/or updated // for subsequent frames if the stream instructs us to do so. Vp8SegmentationHeader curr_segmentation_hdr_; Vp8LoopFilterHeader curr_loopfilter_hdr_; Vp8EntropyHeader curr_entropy_hdr_; const uint8_t* stream_; size_t bytes_left_; Vp8BoolDecoder bd_; }; } // namespace media #endif // MEDIA_PARSERS_VP8_PARSER_H_
blueboxd/chromium-legacy
ash/webui/projector_app/public/cpp/projector_app_constants.h
<filename>ash/webui/projector_app/public/cpp/projector_app_constants.h // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_WEBUI_PROJECTOR_APP_PUBLIC_CPP_PROJECTOR_APP_CONSTANTS_H_ #define ASH_WEBUI_PROJECTOR_APP_PUBLIC_CPP_PROJECTOR_APP_CONSTANTS_H_ namespace chromeos { // TODO(b/193670945): Migrate to ash/components and ash/webui. extern const char kChromeUIProjectorAppHost[]; extern const char kChromeUIUntrustedProjectorAppUrl[]; extern const char kChromeUIUntrustedProjectorPwaUrl[]; extern const char kChromeUITrustedProjectorUrl[]; extern const char kChromeUITrustedProjectorAppUrl[]; extern const char kChromeUITrustedProjectorSelfieCamUrl[]; extern const char kChromeUITrustedAnnotatorUrl[]; extern const char kChromeUITrustedProjectorSwaAppId[]; } // namespace chromeos #endif // ASH_WEBUI_PROJECTOR_APP_PUBLIC_CPP_PROJECTOR_APP_CONSTANTS_H_
blueboxd/chromium-legacy
ui/ozone/platform/flatland/flatland_surface.h
<reponame>blueboxd/chromium-legacy // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_OZONE_PLATFORM_FLATLAND_FLATLAND_SURFACE_H_ #define UI_OZONE_PLATFORM_FLATLAND_FLATLAND_SURFACE_H_ #include <fuchsia/ui/composition/cpp/fidl.h> #include <vulkan/vulkan.h> #include "base/containers/circular_deque.h" #include "base/containers/flat_map.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/threading/thread_checker.h" #include "mojo/public/cpp/platform/platform_handle.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/rect_f.h" #include "ui/gfx/geometry/size_f.h" #include "ui/gfx/native_pixmap.h" #include "ui/gfx/native_pixmap_handle.h" #include "ui/gfx/native_widget_types.h" #include "ui/gfx/overlay_transform.h" #include "ui/ozone/platform/flatland/flatland_connection.h" #include "ui/ozone/public/platform_window_surface.h" namespace ui { class FlatlandSurfaceFactory; // Holder for Flatland resources backing rendering surface. // // This object creates some simple Flatland resources for containing a window's // texture, and attaches them to the parent View (by sending an IPC to the // browser process). // // The texture is updated through an image pipe. class FlatlandSurface : public ui::PlatformWindowSurface { public: FlatlandSurface(FlatlandSurfaceFactory* flatland_surface_factory, gfx::AcceleratedWidget window); ~FlatlandSurface() override; FlatlandSurface(const FlatlandSurface&) = delete; FlatlandSurface& operator=(const FlatlandSurface&) = delete; // PlatformWindowSurface overrides. void Present(scoped_refptr<gfx::NativePixmap> primary_plane_pixmap, std::vector<ui::OverlayPlane> overlays, std::vector<gfx::GpuFenceHandle> acquire_fences, std::vector<gfx::GpuFenceHandle> release_fences, SwapCompletionCallback completion_callback, BufferPresentedCallback presentation_callback) override; // Creates a View for this surface, and returns a ViewHolderToken handle // that can be used to attach it into a scene graph. mojo::PlatformHandle CreateView(); void AssertBelongsToCurrentThread() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); } private: struct PresentationState { base::TimeTicks presentation_time; base::TimeDelta interval; }; struct PresentedFrame { PresentedFrame(fuchsia::ui::composition::ContentId image_id, scoped_refptr<gfx::NativePixmap> primary_plane, SwapCompletionCallback completion_callback, BufferPresentedCallback presentation_callback); ~PresentedFrame(); PresentedFrame(PresentedFrame&& other); PresentedFrame& operator=(PresentedFrame&& other); fuchsia::ui::composition::ContentId image_id; // Ensures the pixmap is not destroyed until after frame is presented. scoped_refptr<gfx::NativePixmap> primary_plane; SwapCompletionCallback completion_callback; BufferPresentedCallback presentation_callback; }; void OnGetLayout(fuchsia::ui::composition::LayoutInfo info); void RemoveBufferCollection( gfx::SysmemBufferCollectionId buffer_collection_id); void OnPresentComplete(zx_time_t actual_presentation_time); fuchsia::ui::composition::AllocatorPtr flatland_allocator_; FlatlandConnection flatland_; // Mapping between the SysmemBufferCollectionId stored in NativePixmapHandles // and ContentId id registered with FlatlandConnection. base::flat_map<gfx::SysmemBufferCollectionId, fuchsia::ui::composition::ContentId> buffer_collection_to_image_id_; base::circular_deque<PresentedFrame> pending_frames_; std::vector<zx::event> release_fences_from_last_present_; // Flatland resources used for the primary plane, that is not an overlay. fuchsia::ui::composition::TransformId root_transform_id_; fuchsia::ui::composition::TransformId primary_plane_transform_id_; fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher_; fuchsia::ui::composition::ChildViewWatcherPtr main_plane_view_watcher_; fuchsia::ui::composition::LayoutInfo layout_info_; FlatlandSurfaceFactory* const flatland_surface_factory_; const gfx::AcceleratedWidget window_; THREAD_CHECKER(thread_checker_); base::WeakPtrFactory<FlatlandSurface> weak_ptr_factory_{this}; }; } // namespace ui #endif // UI_OZONE_PLATFORM_FLATLAND_FLATLAND_SURFACE_H_
blueboxd/chromium-legacy
components/viz/common/frame_sinks/copy_output_result.h
// 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 COMPONENTS_VIZ_COMMON_FRAME_SINKS_COPY_OUTPUT_RESULT_H_ #define COMPONENTS_VIZ_COMMON_FRAME_SINKS_COPY_OUTPUT_RESULT_H_ #include <array> #include <vector> #include "base/threading/thread_checker.h" #include "components/viz/common/resources/release_callback.h" #include "components/viz/common/viz_common_export.h" #include "gpu/command_buffer/common/mailbox_holder.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/color_space.h" #include "ui/gfx/geometry/rect.h" class SkBitmap; namespace viz { // Base class for providing the result of a CopyOutputRequest. Implementations // that execute CopyOutputRequests will use a subclass implementation to define // data storage, access and ownership semantics relative to the lifetime of the // CopyOutputResult instance. class VIZ_COMMON_EXPORT CopyOutputResult { public: enum class Format : uint8_t { // A normal bitmap. When the results are returned in system memory, the // AsSkBitmap() will return a bitmap in "N32Premul" form. When the results // are returned in a texture, it will be an GL_RGBA texture referred to by // a gpu::Mailbox. Client code can optionally take ownership of the texture // (via a call to |TakeTextureOwnership()|) if it is needed beyond the // lifetime of the CopyOutputResult. RGBA, // I420 format planes. This is intended to be used internally within the VIZ // component to support video capture. When requesting this format, results // can only be delivered on the same task runner sequence that runs the // DirectRenderer implementation. For now, I420 format can be requested only // for system memory. I420_PLANES, // NV12 format planes. This is intended to be used internally within the VIZ // component to support video capture. When requesting this format, results // can only be delivered on the same task runner sequence that runs the // DirectRenderer implementation. For now, NV12 format can be requested only // for system memory. NV12_PLANES, }; // Specifies how the results are delivered to the issuer of the request. // This should usually (but not always!) correspond to the value found in // CopyOutputRequest::result_destination() of the request that caused this // result to be produced. For details, see the comment on // CopyOutputRequest::ResultDestination. enum class Destination : uint8_t { // Place the results in system memory. kSystemMemory, // Place the results in native textures. The GPU textures are returned via a // mailbox. The caller can use |GetTextureResult()| and // |TakeTextureOwnership()| to access the results. kNativeTextures, }; // Maximum number of planes allowed when returning results in native textures. // We need at most 3 planes to support the formats we're interested in (RGBA // format requires 1 plane, NV12 requires 2, I420 requires 3 planes). static constexpr size_t kMaxPlanes = 3; static constexpr size_t kNV12MaxPlanes = 2; CopyOutputResult(Format format, Destination destination, const gfx::Rect& rect, bool needs_lock_for_bitmap); CopyOutputResult(const CopyOutputResult&) = delete; CopyOutputResult& operator=(const CopyOutputResult&) = delete; virtual ~CopyOutputResult(); // Returns false if the request succeeded and the data accessors will return // valid references. bool IsEmpty() const; // Returns the format of this result. Format format() const { return format_; } // Returns the destination of this result. Destination destination() const { return destination_; } // Returns the result Rect, which is the position and size of the image data // within the surface/layer (see CopyOutputRequest::set_area()). If a scale // ratio was set in the request, this will be in the scaled, NOT the original, // coordinate space. const gfx::Rect& rect() const { return rect_; } const gfx::Size& size() const { return rect_.size(); } class ScopedSkBitmap; // Return a ScopedSkBitmap object. The scoped_sk_bitmap.bitmap() can be used // to access the SkBitmap. The API user should not keep a copy of // scoped_sk_bitmap.bitmap(), since the content SkBitmap could become invalid // after ScopedSkBitmap is released. ScopedSkBitmap ScopedAccessSkBitmap() const; // Returns a pointer with a set of gpu::MailboxHolders referencing a // texture-backed result, or null if this is not a texture-backed result. // Clients can either: // 1. Let CopyOutputResult retain ownership and the texture will only be // valid for use during CopyOutputResult's lifetime. // 2. Take over ownership of the texture by calling TakeTextureOwnership(), // and the client must guarantee all the release callbacks will be run at // some point. // Even when the returned pointer is non-null, the object that it points to // can be default-constructed (the resulting mailboxes can be empty) in the // case of a failed reply, in which case IsEmpty() would report true. struct VIZ_COMMON_EXPORT TextureResult { // |texture_target| is guaranteed to be GL_TEXTURE_2D for each returned // plane. The planes are placed continuously from the beginning of the array // - i.e. if k planes are valid, indices from 0 (inclusive), to k // (exclusive) will contain the data. If the result is not empty, at least // one plane must be filled out (non-zero). std::array<gpu::MailboxHolder, kMaxPlanes> planes; gfx::ColorSpace color_space; // Single plane variant: TextureResult(const gpu::Mailbox& mailbox, const gpu::SyncToken& sync_token, const gfx::ColorSpace& color_space); // General purpose variant: TextureResult(const std::array<gpu::MailboxHolder, kMaxPlanes>& planes, const gfx::ColorSpace& color_space); TextureResult(const TextureResult& other); TextureResult& operator=(const TextureResult& other); }; virtual const TextureResult* GetTextureResult() const; using ReleaseCallbacks = std::vector<ReleaseCallback>; // Returns a vector of release callbacks for the textures in |planes| array of // TextureResult. `i`th element in this collection is a release callback for // the `i`th element in |planes| array. // The size of the collection must match the number of valid entries in // |planes| array. The vector will be empty iff the CopyOutputResult // |IsEmpty()| is true. virtual ReleaseCallbacks TakeTextureOwnership(); // // Subsampled YUV format result description // (valid for I420 and for NV12 formats) // // Since I420 and NV12 pixel formats subsample chroma planes and the results // are returned in a planar manner, care must be taken when interpreting the // results and when calculating sizes of memory regions for `ReadI420Planes()` // and `ReadNV12()` methods. // // Callers should follow the memory region size requirements specified in // `ReadI420Planes()` and `ReadNV12()` methods, and are advised to call // `set_result_selection()` with an even-sized, even-offset gfx::Rect // if they intend to "stitch" the results into a subregion of an existing // buffer by copying them. Memory region size calculation helpers are // available in copy_output_util.h. // // Copies the image planes of an I420_PLANES result to the caller-provided // memory. Returns true if successful, or false if: 1) this result is empty, // or 2) the result format is not I420_PLANES and does not provide a // conversion implementation. // // |y_out|, |u_out| and |v_out| point to the start of the memory regions to // receive each plane. These memory regions must have the following sizes: // // Y plane: y_out_stride * size().height() bytes, with // y_out_stride >= size().width() // U plane: u_out_stride * CEIL(size().height() / 2) bytes, with // u_out_stride >= CEIL(size().width() / 2) // V plane: v_out_stride * CEIL(size().height() / 2) bytes, with // v_out_stride >= CEIL(size().width() / 2) // // The color space is always Rec.709 (see gfx::ColorSpace::CreateREC709()). virtual bool ReadI420Planes(uint8_t* y_out, int y_out_stride, uint8_t* u_out, int u_out_stride, uint8_t* v_out, int v_out_stride) const; // Copies the image planes of an NV12_PLANES result to the caller-provided // memory. Returns true if successful, or false if: 1) this result is empty, // or 2) the result format is not NV12_PLANES and does not provide a // conversion implementation. // // |y_out| and |uv_out| point to the start of the memory regions to // receive each plane. These memory regions must have the following sizes: // // Y plane: y_out_stride * size().height() bytes, with // y_out_stride >= size().width() // UV plane: uv_out_stride * CEIL(size().height() / 2) bytes, with // uv_out_stride >= 2 * CEIL(size().width() / 2) // // The color space is always Rec.709 (see gfx::ColorSpace::CreateREC709()). virtual bool ReadNV12Planes(uint8_t* y_out, int y_out_stride, uint8_t* uv_out, int uv_out_stride) const; // Copies the result into |dest|. The result is in N32Premul form. Returns // true if successful, or false if: 1) the result is empty, or 2) the result // format is not RGBA and conversion is not implemented. virtual bool ReadRGBAPlane(uint8_t* dest, int stride) const; // Returns the color space of the image data returned by ReadRGBAPlane(). virtual gfx::ColorSpace GetRGBAColorSpace() const; protected: // Lock the content of SkBitmap returned from AsSkBitmap() call. // Return true, if lock operation is successful, implementations should // keep SkBitmap content validate until UnlockSkBitmap() is called. virtual bool LockSkBitmap() const; // Unlock the content of SkBitmap returned from AsSkBitmap() call. virtual void UnlockSkBitmap() const; // Convenience to provide this result in SkBitmap form. Returns a // !readyToDraw() bitmap if this result is empty or if a conversion is not // possible in the current implementation. The returned SkBitmap also carries // its color space information. virtual const SkBitmap& AsSkBitmap() const; // Accessor for subclasses to initialize the cached SkBitmap. SkBitmap* cached_bitmap() const { return &cached_bitmap_; } private: const Format format_; const Destination destination_; const gfx::Rect rect_; const bool needs_lock_for_bitmap_; // Cached bitmap returned by the default implementation of AsSkBitmap(). mutable SkBitmap cached_bitmap_; }; // Subclass of CopyOutputResult that provides a RGBA result from an // SkBitmap (or an I420_PLANES result based on a SkBitmap). Implies that the // destination is kSystemMemory. class VIZ_COMMON_EXPORT CopyOutputSkBitmapResult : public CopyOutputResult { public: CopyOutputSkBitmapResult(Format format, const gfx::Rect& rect, SkBitmap bitmap); CopyOutputSkBitmapResult(const gfx::Rect& rect, SkBitmap bitmap); CopyOutputSkBitmapResult(const CopyOutputSkBitmapResult&) = delete; CopyOutputSkBitmapResult& operator=(const CopyOutputSkBitmapResult&) = delete; ~CopyOutputSkBitmapResult() override; const SkBitmap& AsSkBitmap() const override; }; // Subclass of CopyOutputResult that holds references to textures (via // mailboxes). The owner of the result must take ownership of the textures if it // wants to use them by calling |TakeTextureOwnership()|, and then call the // ReleaseCallbacks when the textures will no longer be used to release // ownership and allow the textures to be reused or destroyed. If ownership is // not claimed, it will be released when this class is destroyed. class VIZ_COMMON_EXPORT CopyOutputTextureResult : public CopyOutputResult { public: // Construct a non-empty texture result: CopyOutputTextureResult(Format format, const gfx::Rect& rect, TextureResult texture_result, ReleaseCallbacks release_callbacks); CopyOutputTextureResult(const CopyOutputTextureResult&) = delete; CopyOutputTextureResult& operator=(const CopyOutputTextureResult&) = delete; ~CopyOutputTextureResult() override; const TextureResult* GetTextureResult() const override; ReleaseCallbacks TakeTextureOwnership() override; private: TextureResult texture_result_; ReleaseCallbacks release_callbacks_; }; // Scoped class for accessing SkBitmap in CopyOutputRequest. // It cannot be used across threads. class VIZ_COMMON_EXPORT CopyOutputResult::ScopedSkBitmap { public: ScopedSkBitmap(); ScopedSkBitmap(ScopedSkBitmap&& other); ~ScopedSkBitmap(); ScopedSkBitmap& operator=(ScopedSkBitmap&& other); void reset(); // Accesses SkBitmap which can only be used in the scope of the // ScopedSkBitmap. const SkBitmap bitmap() const { return result_ ? result_->AsSkBitmap() : SkBitmap(); } // Returns a SkBitmap which can be used out the scope of the ScopedSkBitmap. // It makes a copy of the content in CopyOutputResult if it is needed. SkBitmap GetOutScopedBitmap() const; private: friend class CopyOutputResult; explicit ScopedSkBitmap(const CopyOutputResult* result); const CopyOutputResult* result_ = nullptr; THREAD_CHECKER(thread_checker_); }; } // namespace viz #endif // COMPONENTS_VIZ_COMMON_FRAME_SINKS_COPY_OUTPUT_RESULT_H_
blueboxd/chromium-legacy
chrome/browser/ui/media_router/media_router_ui.h
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_MEDIA_ROUTER_MEDIA_ROUTER_UI_H_ #define CHROME_BROWSER_UI_MEDIA_ROUTER_MEDIA_ROUTER_UI_H_ #include <memory> #include <set> #include <string> #include <utility> #include <vector> #include "base/gtest_prod_util.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "build/build_config.h" #include "chrome/browser/ui/media_router/cast_dialog_controller.h" #include "chrome/browser/ui/media_router/cast_dialog_model.h" #include "chrome/browser/ui/media_router/media_cast_mode.h" #include "chrome/browser/ui/media_router/media_router_file_dialog.h" #include "chrome/browser/ui/media_router/media_router_ui_helper.h" #include "chrome/browser/ui/media_router/media_sink_with_cast_modes.h" #include "chrome/browser/ui/media_router/query_result_manager.h" #include "chrome/browser/ui/webui/media_router/web_contents_display_observer.h" #include "components/media_router/browser/issues_observer.h" #include "components/media_router/browser/media_router_dialog_controller.h" #include "components/media_router/browser/presentation/start_presentation_context.h" #include "components/media_router/browser/presentation/web_contents_presentation_manager.h" #include "components/media_router/common/issue.h" #include "components/media_router/common/media_source.h" #include "url/origin.h" class GURL; namespace content { struct PresentationRequest; class WebContents; } // namespace content namespace U_ICU_NAMESPACE { class Collator; } namespace media_router { class MediaRoute; class MediaRouter; class MediaRoutesObserver; class MediaSink; class RouteRequestResult; // Functions as an intermediary between MediaRouter and Views Cast dialog. class MediaRouterUI : public CastDialogController, public QueryResultManager::Observer, public WebContentsPresentationManager::Observer, public MediaRouterFileDialog::MediaRouterFileDialogDelegate { public: explicit MediaRouterUI(content::WebContents* initiator); MediaRouterUI(const MediaRouterUI&) = delete; MediaRouterUI& operator=(const MediaRouterUI&) = delete; ~MediaRouterUI() override; // CastDialogController: void AddObserver(CastDialogController::Observer* observer) override; void RemoveObserver(CastDialogController::Observer* observer) override; void StartCasting(const std::string& sink_id, MediaCastMode cast_mode) override; void StopCasting(const std::string& route_id) override; void ChooseLocalFile( base::OnceCallback<void(const ui::SelectedFileInfo*)> callback) override; void ClearIssue(const Issue::Id& issue_id) override; // Initializes internal state (e.g. starts listening for MediaSinks) for // targeting the default MediaSource (if any) of |initiator_|. The contents of // the UI will change as the default MediaSource changes. If there is a // default MediaSource, then PRESENTATION MediaCastMode will be added to // |cast_modes_|. Init* methods can only be called once. void InitWithDefaultMediaSource(); // Initializes mirroring sources of the tab in addition to what is done by // |InitWithDefaultMediaSource()|. void InitWithDefaultMediaSourceAndMirroring(); // Initializes internal state targeting the presentation specified in // |context|. This is different from InitWithDefaultMediaSource*() in that it // does not listen for default media source changes, as the UI is fixed to the // source in |context|. Init* methods can only be called once. // |context|: Context object for the PresentationRequest. This instance will // take ownership of it. Must not be null. void InitWithStartPresentationContext( std::unique_ptr<StartPresentationContext> context); // Initializes mirroring sources of the tab in addition to what is done by // |InitWithStartPresentationContext()|. void InitWithStartPresentationContextAndMirroring( std::unique_ptr<StartPresentationContext> context); // Requests a route be created from the source mapped to // |cast_mode|, to the sink given by |sink_id|. // Returns true if a route request is successfully submitted. // |OnRouteResponseReceived()| will be invoked when the route request // completes. virtual bool CreateRoute(const MediaSink::Id& sink_id, MediaCastMode cast_mode); // Calls MediaRouter to terminate the given route. void TerminateRoute(const MediaRoute::Id& route_id); // Returns a subset of |sinks_| that should be listed in the dialog. This // excludes the wired display that the initiator WebContents is on. // Also filters cloud sinks in incognito windows. std::vector<MediaSinkWithCastModes> GetEnabledSinks() const; // Returns a PresentationRequest source name that can be shown in the dialog. std::u16string GetPresentationRequestSourceName() const; // Calls MediaRouter to add the given issue. void AddIssue(const IssueInfo& issue); // Calls MediaRouter to remove the given issue. void RemoveIssue(const Issue::Id& issue_id); // Opens a file picker for when the user selected local file casting. void OpenFileDialog(); // Uses LoggerImpl to log current available sinks. void LogMediaSinkStatus(); const std::vector<MediaRoute>& routes() const { return routes_; } content::WebContents* initiator() const { return initiator_; } void SimulateDocumentAvailableForTest(); #if defined(OS_MAC) void set_screen_capture_allowed_for_testing(bool allowed) { screen_capture_allowed_for_testing_ = allowed; } #endif private: friend class MediaRouterViewsUITest; friend class MediaRouterCastUiForTest; FRIEND_TEST_ALL_PREFIXES(MediaRouterViewsUITest, SetDialogHeader); FRIEND_TEST_ALL_PREFIXES(MediaRouterViewsUITest, UpdateSinksWhenDialogMovesToAnotherDisplay); FRIEND_TEST_ALL_PREFIXES(MediaRouterViewsUITest, NotifyObserver); FRIEND_TEST_ALL_PREFIXES(MediaRouterViewsUITest, SinkFriendlyName); FRIEND_TEST_ALL_PREFIXES(MediaRouterViewsUITest, ConnectingState); FRIEND_TEST_ALL_PREFIXES(MediaRouterViewsUITest, DisconnectingState); FRIEND_TEST_ALL_PREFIXES(MediaRouterViewsUITest, AddAndRemoveIssue); FRIEND_TEST_ALL_PREFIXES(MediaRouterViewsUITest, ShowDomainForHangouts); FRIEND_TEST_ALL_PREFIXES(MediaRouterViewsUIIncognitoTest, HidesCloudSinksForIncognito); FRIEND_TEST_ALL_PREFIXES(MediaRouterViewsUITest, RouteCreationTimeoutForPresentation); FRIEND_TEST_ALL_PREFIXES(MediaRouterViewsUITest, DesktopMirroringFailsWhenDisallowedOnMac); FRIEND_TEST_ALL_PREFIXES(MediaRouterViewsUITest, RouteCreationLocalFileModeInTab); FRIEND_TEST_ALL_PREFIXES(MediaRouterUITest, UIMediaRoutesObserverAssignsCurrentCastModes); FRIEND_TEST_ALL_PREFIXES(MediaRouterUITest, UIMediaRoutesObserverSkipsUnavailableCastModes); FRIEND_TEST_ALL_PREFIXES(MediaRouterUITest, UpdateSinksWhenDialogMovesToAnotherDisplay); class WebContentsFullscreenOnLoadedObserver; struct RouteRequest { public: explicit RouteRequest(const MediaSink::Id& sink_id); ~RouteRequest(); int id; MediaSink::Id sink_id; }; // This class calls to refresh the UI when the highest priority issue is // updated. class UiIssuesObserver : public IssuesObserver { public: UiIssuesObserver(IssueManager* issue_manager, MediaRouterUI* ui); UiIssuesObserver(const UiIssuesObserver&) = delete; UiIssuesObserver& operator=(const UiIssuesObserver&) = delete; ~UiIssuesObserver() override; // IssuesObserver: void OnIssue(const Issue& issue) override; void OnIssuesCleared() override; private: // Reference back to the owning MediaRouterUI instance. MediaRouterUI* const ui_; }; class UIMediaRoutesObserver : public MediaRoutesObserver { public: using RoutesUpdatedCallback = base::RepeatingCallback<void(const std::vector<MediaRoute>&, const std::vector<MediaRoute::Id>&)>; UIMediaRoutesObserver(MediaRouter* router, const MediaSource::Id& source_id, const RoutesUpdatedCallback& callback); UIMediaRoutesObserver(const UIMediaRoutesObserver&) = delete; UIMediaRoutesObserver& operator=(const UIMediaRoutesObserver&) = delete; ~UIMediaRoutesObserver() override; // MediaRoutesObserver: void OnRoutesUpdated( const std::vector<MediaRoute>& routes, const std::vector<MediaRoute::Id>& joinable_route_ids) override; private: // Callback to the owning MediaRouterUI instance. RoutesUpdatedCallback callback_; }; std::vector<MediaSource> GetSourcesForCastMode(MediaCastMode cast_mode) const; // Closes the dialog after receiving a route response when using // |start_presentation_context_|. This prevents the dialog from trying to use // the same presentation request again. virtual void HandleCreateSessionRequestRouteResponse( const RouteRequestResult&); // Initializes the dialog with mirroring sources derived from |initiator_|. virtual void InitCommon(); void InitMirroring(); // WebContentsPresentationManager::Observer void OnDefaultPresentationChanged( const content::PresentationRequest* presentation_request) override; void OnDefaultPresentationRemoved(); // Called to update the dialog with the current list of of enabled sinks. void UpdateSinks(); // Populates common route-related parameters for calls to MediaRouter. absl::optional<RouteParameters> GetRouteParameters( const MediaSink::Id& sink_id, MediaCastMode cast_mode); // Returns the default PresentationRequest's frame origin if there is one. // Otherwise returns an opaque origin. url::Origin GetFrameOrigin() const; // Creates and sends an issue if route creation timed out. void SendIssueForRouteTimeout( MediaCastMode cast_mode, const MediaSink::Id& sink_id, const std::u16string& presentation_request_source_name); // Creates and sends an issue if casting fails due to lack of screen // permissions. #if defined(OS_MAC) void SendIssueForScreenPermission(const MediaSink::Id& sink_id); #endif // Creates and sends an issue if casting fails for any reason other than // those above. void SendIssueForUnableToCast(MediaCastMode cast_mode, const MediaSink::Id& sink_id); // Creates and sends an issue for notifying the user that the tab audio cannot // be mirrored from their device. void SendIssueForTabAudioNotSupported(const MediaSink::Id& sink_id); // Returns the IssueManager associated with |router_|. IssueManager* GetIssueManager(); // Instantiates and initializes the issues observer. void StartObservingIssues(); void OnIssue(const Issue& issue); void OnIssueCleared(); // Called by |routes_observer_| when the set of active routes has changed. void OnRoutesUpdated(const std::vector<MediaRoute>& routes, const std::vector<MediaRoute::Id>& joinable_route_ids); // QueryResultManager::Observer: void OnResultsUpdated( const std::vector<MediaSinkWithCastModes>& sinks) override; // Callback passed to MediaRouter to receive response to route creation // requests. virtual void OnRouteResponseReceived( int route_request_id, const MediaSink::Id& sink_id, MediaCastMode cast_mode, const std::u16string& presentation_request_source_name, const RouteRequestResult& result); // Update the header text in the dialog model and notify observers. void UpdateModelHeader(); UIMediaSink ConvertToUISink(const MediaSinkWithCastModes& sink, const MediaRoute* route, const absl::optional<Issue>& issue); // MediaRouterFileDialogDelegate: void FileDialogFileSelected(const ui::SelectedFileInfo& file_info) override; void FileDialogSelectionFailed(const IssueInfo& issue) override; void FileDialogSelectionCanceled() override; // Populates route-related parameters for CreateRoute() when doing file // casting. absl::optional<RouteParameters> GetLocalFileRouteParameters( const MediaSink::Id& sink_id, const GURL& file_url, content::WebContents* tab_contents); // If the current URL for |web_contents| is |file_url|, requests the first // video in it to be shown fullscreen. void FullScreenFirstVideoElement(const GURL& file_url, content::WebContents* web_contents, const RouteRequestResult& result); // Sends a request to the file dialog to log UMA stats for the file that was // cast if the result is successful. void MaybeReportFileInformation(const RouteRequestResult& result); // Opens the URL in a tab, returns the tab it was opened in. content::WebContents* OpenTabWithUrl(const GURL& url); // Returns the MediaRouter for this instance's BrowserContext. virtual MediaRouter* GetMediaRouter() const; // Retrieves the browser associated with this UI. Browser* GetBrowser(); const absl::optional<RouteRequest> current_route_request() const { return current_route_request_; } StartPresentationContext* start_presentation_context() const { return start_presentation_context_.get(); } QueryResultManager* query_result_manager() const { return query_result_manager_.get(); } void set_media_router_file_dialog_for_test( std::unique_ptr<MediaRouterFileDialog> file_dialog) { media_router_file_dialog_ = std::move(file_dialog); } void set_start_presentation_context_for_test( std::unique_ptr<StartPresentationContext> start_presentation_context) { start_presentation_context_ = std::move(start_presentation_context); } content::WebContentsObserver* web_contents_observer_for_test_ = nullptr; // This value is set whenever there is an outstanding issue. absl::optional<Issue> issue_; // Contains up-to-date data to show in the dialog. CastDialogModel model_; // This value is set when the user opens a file picker, and used when a file // is selected and casting starts. absl::optional<MediaSink::Id> local_file_sink_id_; // This value is set when the UI requests a route to be terminated, and gets // reset when the route is removed. absl::optional<MediaRoute::Id> terminating_route_id_; // Observers for dialog model updates. // TODO(takumif): CastDialogModel should manage the observers. base::ObserverList<CastDialogController::Observer>::Unchecked observers_; base::OnceCallback<void(const ui::SelectedFileInfo*)> file_selection_callback_; // This is non-null while this instance is registered to receive // updates from them. std::unique_ptr<MediaRoutesObserver> routes_observer_; // This contains a value only when tracking a pending route request. absl::optional<RouteRequest> current_route_request_; // Used for locale-aware sorting of sinks by name. Set during // InitCommon() using the current locale. std::unique_ptr<icu::Collator> collator_; std::vector<MediaSinkWithCastModes> sinks_; std::vector<MediaRoute> routes_; // Monitors and reports sink availability. std::unique_ptr<QueryResultManager> query_result_manager_; // If set, then the result of the next presentation route request will // be handled by this object. std::unique_ptr<StartPresentationContext> start_presentation_context_; // Set to the presentation request corresponding to the presentation cast // mode, if supported. Otherwise set to nullopt. absl::optional<content::PresentationRequest> presentation_request_; // |presentation_manager_| notifies |this| whenever there is an update to the // default PresentationRequest or MediaRoutes associated with |initiator_|. base::WeakPtr<WebContentsPresentationManager> presentation_manager_; // WebContents for the tab for which the Cast dialog is shown. content::WebContents* const initiator_; // The dialog that handles opening the file dialog and validating and // returning the results. std::unique_ptr<MediaRouterFileDialog> media_router_file_dialog_; std::unique_ptr<IssuesObserver> issues_observer_; // Keeps track of which display the initiator WebContents is on. This is used // to make sure we don't show a wired display presentation over the // controlling window. std::unique_ptr<WebContentsDisplayObserver> display_observer_; #if defined(OS_MAC) absl::optional<bool> screen_capture_allowed_for_testing_; #endif LoggerImpl* logger_; // NOTE: Weak pointers must be invalidated before all other member variables. // Therefore |weak_factory_| must be placed at the end. base::WeakPtrFactory<MediaRouterUI> weak_factory_{this}; }; } // namespace media_router #endif // CHROME_BROWSER_UI_MEDIA_ROUTER_MEDIA_ROUTER_UI_H_
blueboxd/chromium-legacy
third_party/blink/renderer/core/css/css_font_selector_base.h
<reponame>blueboxd/chromium-legacy // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_FONT_SELECTOR_BASE_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_FONT_SELECTOR_BASE_H_ #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/css/font_face_cache.h" #include "third_party/blink/renderer/platform/fonts/font_selector.h" #include "third_party/blink/renderer/platform/fonts/generic_font_family_settings.h" #include "third_party/blink/renderer/platform/wtf/forward.h" namespace blink { class FontDescription; class FontFamily; class CORE_EXPORT CSSFontSelectorBase : public FontSelector { public: bool IsPlatformFamilyMatchAvailable(const FontDescription&, const FontFamily& family) override; void WillUseFontData(const FontDescription&, const FontFamily& family, const String& text) override; void WillUseRange(const FontDescription&, const AtomicString& family_name, const FontDataForRangeSet&) override; void Trace(Visitor*) const override; protected: virtual UseCounter* GetUseCounter() = 0; AtomicString FamilyNameFromSettings(const FontDescription&, const FontFamily& generic_family_name); using FontSelector::FamilyNameFromSettings; Member<FontFaceCache> font_face_cache_; GenericFontFamilySettings generic_font_family_settings_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_FONT_SELECTOR_BASE_H_
blueboxd/chromium-legacy
chrome/browser/ash/policy/reporting/metrics_reporting/network/https_latency_sampler.h
<filename>chrome/browser/ash/policy/reporting/metrics_reporting/network/https_latency_sampler.h<gh_stars>10-100 // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_ASH_POLICY_REPORTING_METRICS_REPORTING_NETWORK_HTTPS_LATENCY_SAMPLER_H_ #define CHROME_BROWSER_ASH_POLICY_REPORTING_METRICS_REPORTING_NETWORK_HTTPS_LATENCY_SAMPLER_H_ #include "base/callback.h" #include "base/containers/queue.h" #include "chromeos/services/network_health/public/mojom/network_diagnostics.mojom.h" #include "components/reporting/metrics/sampler.h" namespace chromeos { namespace network_diagnostics { class HttpsLatencyRoutine; } // namespace network_diagnostics } // namespace chromeos namespace reporting { using HttpsLatencyRoutineGetter = base::RepeatingCallback< std::unique_ptr<chromeos::network_diagnostics::HttpsLatencyRoutine>()>; // `HttpsLatencySampler` collects a sample of the current network latency by // invoking the `HttpsLatencyRoutine` and parsing its results, no info is // collected by this sampler only telemetry is collected. class HttpsLatencySampler : public Sampler { using HttpsLatencyRoutine = chromeos::network_diagnostics::HttpsLatencyRoutine; using RoutineResultPtr = chromeos::network_diagnostics::mojom::RoutineResultPtr; public: HttpsLatencySampler(); HttpsLatencySampler(const HttpsLatencySampler&) = delete; HttpsLatencySampler& operator=(const HttpsLatencySampler&) = delete; ~HttpsLatencySampler() override; void Collect(MetricCallback callback) override; void SetHttpsLatencyRoutineGetterForTest( HttpsLatencyRoutineGetter https_latency_routine_getter); private: void OnHttpsLatencyRoutineCompleted(RoutineResultPtr routine_result); bool is_routine_running_ = false; HttpsLatencyRoutineGetter https_latency_routine_getter_; std::unique_ptr<HttpsLatencyRoutine> https_latency_routine_; base::queue<MetricCallback> metric_callbacks_; SEQUENCE_CHECKER(sequence_checker_); base::WeakPtrFactory<HttpsLatencySampler> weak_ptr_factory_{this}; }; } // namespace reporting #endif // CHROME_BROWSER_ASH_POLICY_REPORTING_METRICS_REPORTING_NETWORK_HTTPS_LATENCY_SAMPLER_H_
blueboxd/chromium-legacy
third_party/blink/renderer/core/loader/web_bundle/web_bundle_loader.h
<reponame>blueboxd/chromium-legacy<gh_stars>10-100 // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_WEB_BUNDLE_WEB_BUNDLE_LOADER_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_WEB_BUNDLE_WEB_BUNDLE_LOADER_H_ #include "services/network/public/mojom/web_bundle_handle.mojom-blink.h" #include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.h" #include "third_party/blink/renderer/core/html/cross_origin_attribute.h" #include "third_party/blink/renderer/core/loader/threadable_loader_client.h" #include "third_party/blink/renderer/platform/mojo/heap_mojo_receiver_set.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" namespace base { class SingleThreadTaskRunner; } // namespace base namespace blink { class SecurityOrigin; class SubresourceWebBundle; class Document; class ThreadableLoader; // A loader which is used to load a resource from webbundle. class WebBundleLoader : public GarbageCollected<WebBundleLoader>, public ThreadableLoaderClient, public network::mojom::blink::WebBundleHandle { public: WebBundleLoader(SubresourceWebBundle& subresource_web_bundle, Document& document, const KURL& url, network::mojom::CredentialsMode credentials_mode); void Trace(Visitor* visitor) const override; bool HasLoaded() const { return !failed_; } // ThreadableLoaderClient void DidStartLoadingResponseBody(BytesConsumer& consumer) override; void DidFail(uint64_t, const ResourceError&) override; void DidFailRedirectCheck(uint64_t) override; // network::mojom::blink::WebBundleHandle void Clone(mojo::PendingReceiver<network::mojom::blink::WebBundleHandle> receiver) override; void OnWebBundleError(network::mojom::blink::WebBundleErrorType type, const String& message) override; void OnWebBundleLoadFinished(bool success) override; const KURL& url() const { return url_; } scoped_refptr<SecurityOrigin> GetSecurityOrigin() const { return security_origin_; } const base::UnguessableToken& WebBundleToken() const { return web_bundle_token_; } void ClearReceivers(); private: void DidFailInternal(); Member<SubresourceWebBundle> subresource_web_bundle_; Member<ThreadableLoader> loader_; bool failed_ = false; KURL url_; scoped_refptr<SecurityOrigin> security_origin_; base::UnguessableToken web_bundle_token_; scoped_refptr<base::SingleThreadTaskRunner> task_runner_; // We need ReceiverSet here because WebBundleHandle is cloned when // ResourceRequest is copied. HeapMojoReceiverSet<network::mojom::blink::WebBundleHandle, WebBundleLoader> receivers_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_WEB_BUNDLE_WEB_BUNDLE_LOADER_H_
blueboxd/chromium-legacy
chrome/browser/chromeos/extensions/login_screen/login_state/session_state_changed_event_dispatcher.h
<reponame>blueboxd/chromium-legacy // Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_CHROMEOS_EXTENSIONS_LOGIN_SCREEN_LOGIN_STATE_SESSION_STATE_CHANGED_EVENT_DISPATCHER_H_ #define CHROME_BROWSER_CHROMEOS_EXTENSIONS_LOGIN_SCREEN_LOGIN_STATE_SESSION_STATE_CHANGED_EVENT_DISPATCHER_H_ #include "base/macros.h" #include "chromeos/crosapi/mojom/login_state.mojom.h" #include "extensions/browser/browser_context_keyed_api_factory.h" #include "extensions/browser/event_router_factory.h" #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote.h" namespace content { class BrowserContext; } // namespace content namespace extensions { class EventRouter; // |SessionStateChangedEventDispatcher| dispatches changes in the session state // to extensions listening on the |loginState.onSessionStateChanged| event. class SessionStateChangedEventDispatcher : public crosapi::mojom::SessionStateChangedEventObserver, public BrowserContextKeyedAPI { public: // BrowserContextKeyedAPI implementation. static BrowserContextKeyedAPIFactory<SessionStateChangedEventDispatcher>* GetFactoryInstance(); void Shutdown() override; explicit SessionStateChangedEventDispatcher( content::BrowserContext* browser_context_); SessionStateChangedEventDispatcher( const SessionStateChangedEventDispatcher&) = delete; SessionStateChangedEventDispatcher& operator=( const SessionStateChangedEventDispatcher&) = delete; ~SessionStateChangedEventDispatcher() override; bool IsBoundForTesting(); void SetEventRouterForTesting(EventRouter* event_router); // crosapi::mojom::SessionStateChangedEventObserver: void OnSessionStateChanged(crosapi::mojom::SessionState state) override; private: // Needed for BrowserContextKeyedAPI implementation. friend class BrowserContextKeyedAPIFactory< SessionStateChangedEventDispatcher>; // BrowserContextKeyedAPI implementation. static const char* service_name() { return "SessionStateChangedEventDispatcher"; } static const bool kServiceIsNULLWhileTesting = true; content::BrowserContext* browser_context_; EventRouter* event_router_; // Receives mojo messages from ash. mojo::Receiver<crosapi::mojom::SessionStateChangedEventObserver> receiver_{ this}; }; template <> struct BrowserContextFactoryDependencies<SessionStateChangedEventDispatcher> { static void DeclareFactoryDependencies( BrowserContextKeyedAPIFactory<SessionStateChangedEventDispatcher>* factory) { factory->DependsOn(EventRouterFactory::GetInstance()); } }; } // namespace extensions #endif // CHROME_BROWSER_CHROMEOS_EXTENSIONS_LOGIN_SCREEN_LOGIN_STATE_SESSION_STATE_CHANGED_EVENT_DISPATCHER_H_
blueboxd/chromium-legacy
base/allocator/partition_allocator/partition_alloc_check.h
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef BASE_ALLOCATOR_PARTITION_ALLOCATOR_PARTITION_ALLOC_CHECK_H_ #define BASE_ALLOCATOR_PARTITION_ALLOCATOR_PARTITION_ALLOC_CHECK_H_ #include "base/allocator/buildflags.h" #include "base/allocator/partition_allocator/page_allocator_constants.h" #include "base/check.h" #include "base/debug/alias.h" #include "base/immediate_crash.h" #define PA_STRINGIFY_IMPL(s) #s #define PA_STRINGIFY(s) PA_STRINGIFY_IMPL(s) // When PartitionAlloc is used as the default allocator, we cannot use the // regular (D)CHECK() macros, as they allocate internally. When an assertion is // triggered, they format strings, leading to reentrancy in the code, which none // of PartitionAlloc is designed to support (and especially not for error // paths). // // As a consequence: // - When PartitionAlloc is not malloc(), use the regular macros // - Otherwise, crash immediately. This provides worse error messages though. #if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) // For official build discard log strings to reduce binary bloat. #if defined(OFFICIAL_BUILD) && defined(NDEBUG) // See base/check.h for implementation details. #define PA_CHECK(condition) \ UNLIKELY(!(condition)) ? IMMEDIATE_CRASH() : EAT_CHECK_STREAM_PARAMS() #else // PartitionAlloc uses async-signal-safe RawCheck() for error reporting. // Async-signal-safe functions are guaranteed to not allocate as otherwise they // could operate with inconsistent allocator state. #define PA_CHECK(condition) \ UNLIKELY(!(condition)) \ ? logging::RawCheck( \ __FILE__ "(" PA_STRINGIFY(__LINE__) ") Check failed: " #condition) \ : EAT_CHECK_STREAM_PARAMS() #endif // defined(OFFICIAL_BUILD) && defined(NDEBUG) #if DCHECK_IS_ON() #define PA_DCHECK(condition) PA_CHECK(condition) #else #define PA_DCHECK(condition) EAT_CHECK_STREAM_PARAMS(!(condition)) #endif // DCHECK_IS_ON() #define PA_PCHECK(condition) \ if (!(condition)) { \ int error = errno; \ base::debug::Alias(&error); \ IMMEDIATE_CRASH(); \ } #else #define PA_CHECK(condition) CHECK(condition) #define PA_DCHECK(condition) DCHECK(condition) #define PA_PCHECK(condition) PCHECK(condition) #endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) // Expensive dchecks that run within *Scan. These checks are only enabled in // debug builds with dchecks enabled. #if !defined(NDEBUG) #define PA_SCAN_DCHECK_IS_ON() DCHECK_IS_ON() #else #define PA_SCAN_DCHECK_IS_ON() 0 #endif #if PA_SCAN_DCHECK_IS_ON() #define PA_SCAN_DCHECK(expr) PA_DCHECK(expr) #else #define PA_SCAN_DCHECK(expr) EAT_CHECK_STREAM_PARAMS(!(expr)) #endif #if defined(PAGE_ALLOCATOR_CONSTANTS_ARE_CONSTEXPR) // Use this macro to assert on things that are conditionally constexpr as // determined by PAGE_ALLOCATOR_CONSTANTS_ARE_CONSTEXPR or // PAGE_ALLOCATOR_CONSTANTS_DECLARE_CONSTEXPR. Where fixed at compile time, this // is a static_assert. Where determined at run time, this is a PA_CHECK. // Therefore, this macro must only be used where both a static_assert and a // PA_CHECK would be viable, that is, within a function, and ideally a function // that executes only once, early in the program, such as during initialization. #define STATIC_ASSERT_OR_PA_CHECK(condition, message) \ static_assert(condition, message) #else #define STATIC_ASSERT_OR_PA_CHECK(condition, message) \ do { \ PA_CHECK(condition) << (message); \ } while (false) #endif namespace pa { // Used for PA_DEBUG_DATA_ON_STACK, below. struct DebugKv { char k[8] = {}; // Not necessarily 0-terminated. size_t v = 0; DebugKv(const char* key, size_t value) { for (int index = 0; index < 8; index++) { k[index] = key[index]; if (key[index] == '\0') break; } v = value; } }; } // namespace pa #define PA_CONCAT(x, y) x##y #define PA_CONCAT2(x, y) PA_CONCAT(x, y) #define PA_DEBUG_UNIQUE_NAME PA_CONCAT2(kv, __LINE__) // Puts a key-value pair on the stack for debugging. `base::debug::Alias()` // makes sure a local variable is saved on the stack, but the variables can be // hard to find in crash reports, particularly if the frame pointer is not // present / invalid. // // This puts a key right before the value on the stack. The key has to be a C // string, which gets truncated if it's longer than 8 characters. // Example use: // PA_DEBUG_DATA_ON_STACK("size", 0x42) // // Sample output in lldb: // (lldb) x 0x00007fffffffd0d0 0x00007fffffffd0f0 // 0x7fffffffd0d0: 73 69 7a 65 00 00 00 00 42 00 00 00 00 00 00 00 // size............ // // With gdb, one can use: // x/8g <STACK_POINTER> // to see the data. With lldb, "x <STACK_POINTER> <FRAME_POJNTER>" can be used. #define PA_DEBUG_DATA_ON_STACK(name, value) \ pa::DebugKv PA_DEBUG_UNIQUE_NAME{name, value}; \ base::debug::Alias(&PA_DEBUG_UNIQUE_NAME); #endif // BASE_ALLOCATOR_PARTITION_ALLOCATOR_PARTITION_ALLOC_CHECK_H_
blueboxd/chromium-legacy
ios/chrome/browser/ui/popup_menu/overflow_menu/overflow_menu_mediator.h
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef IOS_CHROME_BROWSER_UI_POPUP_MENU_OVERFLOW_MENU_OVERFLOW_MENU_MEDIATOR_H_ #define IOS_CHROME_BROWSER_UI_POPUP_MENU_OVERFLOW_MENU_OVERFLOW_MENU_MEDIATOR_H_ #import <UIKit/UIKit.h> namespace bookmarks { class BookmarkModel; } @protocol ApplicationCommands; @protocol BrowserCommands; @class OverflowMenuModel; class PrefService; @protocol FindInPageCommands; @protocol TextZoomCommands; class WebNavigationBrowserAgent; class WebStateList; // Mediator for the overflow menu. This object is in charge of creating and // updating the items of the overflow menu. @interface OverflowMenuMediator : NSObject // The data model for the overflow menu. @property(nonatomic, readonly) OverflowMenuModel* overflowMenuModel; // The WebStateList that this mediator listens for any changes on the current // WebState. @property(nonatomic, assign) WebStateList* webStateList; // Dispatcher. @property(nonatomic, weak) id<ApplicationCommands, BrowserCommands, FindInPageCommands, TextZoomCommands> dispatcher; // Navigation agent for reloading pages. @property(nonatomic, assign) WebNavigationBrowserAgent* navigationAgent; // If the current session is off the record or not. @property(nonatomic, assign) bool isIncognito; // BaseViewController for presenting some UI. @property(nonatomic, weak) UIViewController* baseViewController; // The bookmarks model to know if the page is bookmarked. @property(nonatomic, assign) bookmarks::BookmarkModel* bookmarkModel; // Pref service to retrieve preference values. @property(nonatomic, assign) PrefService* prefService; @end #endif // IOS_CHROME_BROWSER_UI_POPUP_MENU_OVERFLOW_MENU_OVERFLOW_MENU_MEDIATOR_H_
blueboxd/chromium-legacy
chrome/browser/ui/views/autofill/autofill_popup_base_view.h
<filename>chrome/browser/ui/views/autofill/autofill_popup_base_view.h // 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_VIEWS_AUTOFILL_AUTOFILL_POPUP_BASE_VIEW_H_ #define CHROME_BROWSER_UI_VIEWS_AUTOFILL_AUTOFILL_POPUP_BASE_VIEW_H_ #include <memory> #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/time/time.h" #include "build/build_config.h" #include "chrome/browser/ui/autofill/autofill_popup_view_delegate.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/views/focus/widget_focus_manager.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_delegate.h" #include "ui/views/widget/widget_observer.h" namespace gfx { class Point; } namespace autofill { // Class that deals with the event handling for Autofill-style popups. This // class should only be instantiated by sub-classes. class AutofillPopupBaseView : public views::WidgetDelegateView, public views::WidgetFocusChangeListener, public views::WidgetObserver { public: METADATA_HEADER(AutofillPopupBaseView); // Consider the input element is |kElementBorderPadding| pixels larger at the // top and at the bottom in order to reposition the dropdown, so that it // doesn't look too close to the element. static const int kElementBorderPadding = 1; AutofillPopupBaseView(const AutofillPopupBaseView&) = delete; AutofillPopupBaseView& operator=(const AutofillPopupBaseView&) = delete; static int GetCornerRadius(); // views::View: void VisibilityChanged(View* starting_from, bool is_visible) override; // Notify accessibility that an item has been selected. void NotifyAXSelection(View*); // Get colors used throughout various popup UIs, based on the current native // theme. SkColor GetBackgroundColor() const; SkColor GetForegroundColor() const; SkColor GetSelectedBackgroundColor() const; SkColor GetSelectedForegroundColor() const; SkColor GetFooterBackgroundColor() const; SkColor GetSeparatorColor() const; SkColor GetWarningColor() const; protected: explicit AutofillPopupBaseView(AutofillPopupViewDelegate* delegate, views::Widget* parent_widget); ~AutofillPopupBaseView() override; // Show this popup. Idempotent. Returns |true| if popup is shown, |false| // otherwise. bool DoShow(); // Hide the widget and delete |this|. void DoHide(); // Ensure the child views are not rendered beyond the bubble border // boundaries. Should be overridden together with CreateBorder. void UpdateClipPath(); // Returns the bounds of the containing browser window in screen space. gfx::Rect GetTopWindowBounds() const; // Returns the bounds of the content area in screen space. gfx::Rect GetContentAreaBounds() const; // Update size of popup and paint. If there is insufficient height to draw the // popup, it hides and thus deletes |this| and returns false. (virtual for // testing). virtual bool DoUpdateBoundsAndRedrawPopup(); const AutofillPopupViewDelegate* delegate() const { return delegate_; } private: friend class AutofillPopupBaseViewTest; // views::Views implementation. void GetAccessibleNodeData(ui::AXNodeData* node_data) override; // views::WidgetFocusChangeListener implementation. void OnNativeFocusChanged(gfx::NativeView focused_now) override; // views::WidgetObserver implementation. void OnWidgetBoundsChanged(views::Widget* widget, const gfx::Rect& new_bounds) override; void OnWidgetDestroying(views::Widget* widget) override; // Stop observing the widget. void RemoveWidgetObservers(); // Hide the controller of this view. This assumes that doing so will // eventually hide this view in the process. void HideController(PopupHidingReason reason); // Returns the border to be applied to the popup. std::unique_ptr<views::Border> CreateBorder(); // Must return the container view for this popup. gfx::NativeView container_view(); // Controller for this popup. Weak reference. AutofillPopupViewDelegate* delegate_; // The widget of the window that triggered this popup. Weak reference. views::Widget* parent_widget_; // The time when the popup was shown. base::Time show_time_; // Ensures that the menu start event is not fired redundantly. bool is_ax_menu_start_event_fired_ = false; base::WeakPtrFactory<AutofillPopupBaseView> weak_ptr_factory_{this}; }; } // namespace autofill #endif // CHROME_BROWSER_UI_VIEWS_AUTOFILL_AUTOFILL_POPUP_BASE_VIEW_H_
blueboxd/chromium-legacy
chrome/updater/win/win_constants.h
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_UPDATER_WIN_WIN_CONSTANTS_H_ #define CHROME_UPDATER_WIN_WIN_CONSTANTS_H_ #include <windows.h> #include "chrome/updater/updater_branding.h" namespace updater { // The prefix to use for global names in WIN32 API's. The prefix is necessary // to avoid collision on kernel object names. extern const wchar_t kGlobalPrefix[]; // Serializes access to prefs. extern const wchar_t kPrefsAccessMutex[]; // Registry keys and value names. #define COMPANY_KEY L"Software\\" COMPANY_SHORTNAME_STRING L"\\" // Use |Update| instead of PRODUCT_FULLNAME_STRING for the registry key name // to be backward compatible with Google Update / Omaha. #define UPDATER_KEY COMPANY_KEY L"Update\\" #define CLIENTS_KEY UPDATER_KEY L"Clients\\" #define CLIENT_STATE_KEY UPDATER_KEY L"ClientState\\" #define COMPANY_POLICIES_KEY \ L"Software\\Policies\\" COMPANY_SHORTNAME_STRING L"\\" #define UPDATER_POLICIES_KEY COMPANY_POLICIES_KEY L"Update\\" #define USER_REG_VISTA_LOW_INTEGRITY_HKCU \ L"Software\\Microsoft\\Internet Explorer\\" \ L"InternetRegistry\\REGISTRY\\USER" extern const wchar_t kRegValuePV[]; extern const wchar_t kRegValueName[]; // Installer API registry names. extern const wchar_t kRegValueInstallerError[]; extern const wchar_t kRegValueInstallerExtraCode1[]; extern const wchar_t kRegValueInstallerProgress[]; extern const wchar_t kRegValueInstallerResult[]; extern const wchar_t kRegValueInstallerResultUIString[]; extern const wchar_t kRegValueInstallerSuccessLaunchCmdLine[]; // Device management. // // Registry for enrollment token. extern const wchar_t kRegKeyCompanyCloudManagement[]; extern const wchar_t kRegValueEnrollmentToken[]; // Registry for DM token. extern const wchar_t kRegKeyCompanyEnrollment[]; extern const wchar_t kRegValueDmToken[]; extern const wchar_t kWindowsServiceName[]; extern const wchar_t kWindowsInternalServiceName[]; // crbug.com/1259178: there is a race condition on activating the COM service // and the service shutdown. The race condition is likely to occur when a new // instance of an updater coclass is created right after the last reference // to an object hosted by the COM service is released. The execution flow inside // the updater is sequential, for the most part. Therefore, introducing a slight // delay before creating coclasses reduces (but it does not eliminate) the // probability of running into this race condition, until a better soulution is // found. constexpr int kCreateUpdaterInstanceDelayMs = 100; } // namespace updater #endif // CHROME_UPDATER_WIN_WIN_CONSTANTS_H_
blueboxd/chromium-legacy
components/app_restore/app_restore_utils.h
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_APP_RESTORE_APP_RESTORE_UTILS_H_ #define COMPONENTS_APP_RESTORE_APP_RESTORE_UTILS_H_ #include "base/component_export.h" #include "ui/views/widget/widget.h" namespace app_restore { struct WindowInfo; // For ARC session id, 1 ~ 1000000000 is used as the window id for all new app // launching. 1000000001 - INT_MAX is used as the session id for all restored // app launching read from the full restore file. // // Assuming each day the new windows launched account is 1M, the above scope is // enough for 3 years (1000 days). So there should be enough number to be // assigned for ARC session ids. constexpr int32_t kArcSessionIdOffsetForRestoredLaunching = 1000000000; // If the ARC task is not created when the window is initialized, set the // restore window id as -1, to add the ARC app window to the hidden container. constexpr int32_t kParentToHiddenContainer = -1; // Applies properties from `window_info` to the given `property_handler`. // This is called from `GetWindowInfo()` when window is // created, or from the ArcReadHandler when a task is ready for a full // restore window that has already been created. COMPONENT_EXPORT(APP_RESTORE) void ApplyProperties(WindowInfo* window_info, ui::PropertyHandler* property_handler); // Modifies `out_params` based on the window info associated with // `restore_window_id`. COMPONENT_EXPORT(APP_RESTORE) void ModifyWidgetParams(int32_t restore_window_id, views::Widget::InitParams* out_params); // Generates the ARC session id (1,000,000,001 - INT_MAX) for restored ARC // apps. COMPONENT_EXPORT(APP_RESTORE) int32_t GetArcSessionId(); // Sets `arc_session_id` for `window_id`. `arc session id` is assigned when ARC // apps are restored. COMPONENT_EXPORT(APP_RESTORE) void SetArcSessionIdForWindowId(int32_t arc_session_id, int32_t window_id); // Returns the restore window id for the ARC app's `task_id`. COMPONENT_EXPORT(APP_RESTORE) int32_t GetArcRestoreWindowIdForTaskId(int32_t task_id); // Returns the restore window id for the ARC app's `session_id`. COMPONENT_EXPORT(APP_RESTORE) int32_t GetArcRestoreWindowIdForSessionId(int32_t session_id); } // namespace app_restore #endif // COMPONENTS_APP_RESTORE_APP_RESTORE_UTILS_H_
blueboxd/chromium-legacy
third_party/blink/renderer/core/layout/ng/flex/ng_flex_layout_algorithm.h
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_FLEX_NG_FLEX_LAYOUT_ALGORITHM_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_FLEX_NG_FLEX_LAYOUT_ALGORITHM_H_ #include "third_party/blink/renderer/core/layout/ng/ng_layout_algorithm.h" #include "third_party/blink/renderer/core/layout/flexible_box_algorithm.h" #include "third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h" namespace blink { class NGBlockNode; class NGBlockBreakToken; class NGBoxFragment; struct DevtoolsFlexInfo; class CORE_EXPORT NGFlexLayoutAlgorithm : public NGLayoutAlgorithm<NGBlockNode, NGBoxFragmentBuilder, NGBlockBreakToken> { public: explicit NGFlexLayoutAlgorithm(const NGLayoutAlgorithmParams& params, DevtoolsFlexInfo* devtools = nullptr); MinMaxSizesResult ComputeMinMaxSizes(const MinMaxSizesFloatInput&) override; scoped_refptr<const NGLayoutResult> Layout() override; private: scoped_refptr<const NGLayoutResult> RelayoutIgnoringChildScrollbarChanges(); scoped_refptr<const NGLayoutResult> LayoutInternal(); Length GetUsedFlexBasis(const NGBlockNode& child) const; // This has an optional out parameter so that callers can avoid a subsequent // redundant call to GetUsedFlexBasis. bool IsUsedFlexBasisDefinite(const NGBlockNode& child, Length* flex_basis) const; bool DoesItemCrossSizeComputeToAuto(const NGBlockNode& child) const; bool IsItemCrossAxisLengthDefinite(const NGBlockNode& child, const Length& length) const; bool AspectRatioProvidesMainSize(const NGBlockNode& child) const; bool DoesItemStretch(const NGBlockNode& child) const; // This checks for one of the scenarios where a flex-item box has a definite // size that would be indefinite if the box weren't a flex item. // See https://drafts.csswg.org/css-flexbox/#definite-sizes bool WillChildCrossSizeBeContainerCrossSize(const NGBlockNode& child) const; LayoutUnit AdjustChildSizeForAspectRatioCrossAxisMinAndMax( const NGBlockNode& child, LayoutUnit content_suggestion, const MinMaxSizes& cross_min_max, const NGBoxStrut& border_padding_in_child_writing_mode); bool IsColumnContainerMainSizeDefinite() const; bool IsContainerCrossSizeDefinite() const; NGConstraintSpace BuildSpaceForFlexBasis(const NGBlockNode& flex_item) const; NGConstraintSpace BuildSpaceForIntrinsicBlockSize( const NGBlockNode& flex_item) const; // |block_offset_for_fragmentation| should only be set when running the final // layout pass for fragmentation. NGConstraintSpace BuildSpaceForLayout( const FlexItem& flex_item, absl::optional<LayoutUnit> block_offset_for_fragmentation = absl::nullopt) const; void ConstructAndAppendFlexItems(); void ApplyStretchAlignmentToChild(FlexItem& flex_item); bool GiveLinesAndItemsFinalPositionAndSize(); void LayoutColumnReverse(LayoutUnit main_axis_content_size); // This is same method as FlexItem but we need that logic before FlexItem is // constructed. bool MainAxisIsInlineAxis(const NGBlockNode& child) const; LayoutUnit MainAxisContentExtent(LayoutUnit sum_hypothetical_main_size) const; void HandleOutOfFlowPositioned(NGBlockNode child); void AdjustButtonBaseline(LayoutUnit final_content_cross_size); // Propagates the baseline from the given flex-item if needed. void PropagateBaselineFromChild( const FlexItem&, const NGBoxFragment&, LayoutUnit block_offset, absl::optional<LayoutUnit>* fallback_baseline); // Re-layout a given flex item, taking fragmentation into account. void LayoutWithBlockFragmentation(FlexItem& flex_item, LayoutUnit block_offset, const NGBlockBreakToken* item_break_token); const bool is_column_; const bool is_horizontal_flow_; const bool is_cross_size_definite_; const LogicalSize child_percentage_size_; bool has_column_percent_flex_basis_ = false; bool ignore_child_scrollbar_changes_ = false; bool has_block_fragmentation_ = false; FlexLayoutAlgorithm algorithm_; DevtoolsFlexInfo* layout_info_for_devtools_; // The block size of the entire flex container (ignoring any fragmentation). LayoutUnit total_block_size_; // This will be the intrinsic block size in the current fragmentainer, if // inside a fragmentation context. Otherwise, it will represent the intrinsic // block size for the entire flex container. LayoutUnit intrinsic_block_size_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_FLEX_NG_FLEX_LAYOUT_ALGORITHM_H_
blueboxd/chromium-legacy
sandbox/policy/mac/sandbox_mac.h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SANDBOX_POLICY_MAC_SANDBOX_MAC_H_ #define SANDBOX_POLICY_MAC_SANDBOX_MAC_H_ #include <string> #include "base/files/file_path.h" #include "base/macros.h" #include "sandbox/policy/export.h" namespace base { class FilePath; } namespace sandbox { namespace mojom { enum class Sandbox; } // namespace mojom } // namespace sandbox namespace sandbox { namespace policy { // Convert provided path into a "canonical" path matching what the Sandbox // expects i.e. one without symlinks. // This path is not necessarily unique e.g. in the face of hardlinks. SANDBOX_POLICY_EXPORT base::FilePath GetCanonicalPath( const base::FilePath& path); // Returns the sandbox profile string for a given sandbox type. // It CHECKs that the sandbox profile is a valid type, so it always returns a // valid result, or crashes. SANDBOX_POLICY_EXPORT std::string GetSandboxProfile( sandbox::mojom::Sandbox sandbox_type); class SANDBOX_POLICY_EXPORT SandboxMac { public: // Warm up System APIs that empirically need to be accessed before the // sandbox is turned on. |sandbox_type| is the type of sandbox to warm up. // Valid |sandbox_type| values are defined by the enum SandboxType, or can be // defined by the embedder via // ContentClient::GetSandboxProfileForProcessType(). static void Warmup(sandbox::mojom::Sandbox sandbox_type); // Turns on the OS X sandbox for this process. // |sandbox_type| - type of Sandbox to use. See SandboxWarmup() for legal // values. // // Returns true on success, false if an error occurred enabling the sandbox. static bool Enable(sandbox::mojom::Sandbox sandbox_type); private: DISALLOW_IMPLICIT_CONSTRUCTORS(SandboxMac); }; } // namespace policy } // namespace sandbox #endif // SANDBOX_POLICY_MAC_SANDBOX_MAC_H_
blueboxd/chromium-legacy
ash/wm/overview/overview_test_base.h
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_WM_OVERVIEW_OVERVIEW_TEST_BASE_H_ #define ASH_WM_OVERVIEW_OVERVIEW_TEST_BASE_H_ #include <memory> #include <string> #include <vector> #include "ash/shelf/shelf_view_test_api.h" #include "ash/test/ash_test_base.h" #include "base/files/scoped_temp_dir.h" #include "base/test/scoped_feature_list.h" #include "components/desks_storage/core/local_desk_data_manager.h" namespace views { class ImageButton; class Label; } // namespace views namespace ash { class OverviewController; class OverviewGrid; class OverviewItem; class OverviewSession; class ScopedOverviewTransformWindow; class SplitViewController; class WindowPreviewView; // The base test fixture for testing Overview Mode. class OverviewTestBase : public AshTestBase { public: template <typename... TaskEnvironmentTraits> explicit OverviewTestBase(TaskEnvironmentTraits&&... traits) : AshTestBase(std::forward<TaskEnvironmentTraits>(traits)...) {} OverviewTestBase(const OverviewTestBase&) = delete; OverviewTestBase& operator=(const OverviewTestBase&) = delete; ~OverviewTestBase() override; // Enters tablet mode. Needed by tests that test dragging and or splitview, // which are tablet mode only. void EnterTabletMode(); bool InOverviewSession(); bool WindowsOverlapping(aura::Window* window1, aura::Window* window2); // Creates a window which cannot be snapped by splitview. std::unique_ptr<aura::Window> CreateUnsnappableWindow( const gfx::Rect& bounds = gfx::Rect()); void ClickWindow(aura::Window* window); OverviewController* GetOverviewController(); OverviewSession* GetOverviewSession(); SplitViewController* GetSplitViewController(); gfx::Rect GetTransformedBounds(aura::Window* window); gfx::Rect GetTransformedTargetBounds(aura::Window* window); gfx::Rect GetTransformedBoundsInRootWindow(aura::Window* window); OverviewItem* GetDropTarget(int grid_index); views::ImageButton* GetCloseButton(OverviewItem* item); views::Label* GetLabelView(OverviewItem* item); views::View* GetBackdropView(OverviewItem* item); WindowPreviewView* GetPreviewView(OverviewItem* item); float GetCloseButtonOpacity(OverviewItem* item); float GetTitlebarOpacity(OverviewItem* item); const ScopedOverviewTransformWindow& GetTransformWindow( OverviewItem* item) const; bool HasRoundedCorner(OverviewItem* item); // Tests that a window is contained within a given OverviewItem, and that both // the window and its matching close button are within the same screen. void CheckWindowAndCloseButtonInScreen(aura::Window* window, OverviewItem* window_item); gfx::Rect GetGridBounds(); void SetGridBounds(OverviewGrid* grid, const gfx::Rect& bounds); desks_storage::DeskModel* desk_model() { return desk_model_.get(); } // AshTestBase: void SetUp() override; void TearDown() override; protected: void CheckForDuplicateTraceName(const char* trace); private: std::unique_ptr<desks_storage::LocalDeskDataManager> desk_model_; base::ScopedTempDir desk_model_temp_dir_; base::test::ScopedFeatureList scoped_feature_list_; std::unique_ptr<ShelfViewTestAPI> shelf_view_test_api_; std::vector<std::string> trace_names_; }; } // namespace ash #endif // ASH_WM_OVERVIEW_OVERVIEW_TEST_BASE_H_