1// Copyright (C) 2023 The Android Open Source Project 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14 15import { 16 createStore, 17 Plugin, 18 PluginContextTrace, 19 PluginDescriptor, 20 Store, 21} from '../../public'; 22 23interface State { 24 counter: number; 25} 26 27// This example plugin shows using state that is persisted in the 28// permalink. 29class ExampleState implements Plugin { 30 private store: Store<State> = createStore({counter: 0}); 31 32 private migrate(initialState: unknown): State { 33 if ( 34 initialState && 35 typeof initialState === 'object' && 36 'counter' in initialState && 37 typeof initialState.counter === 'number' 38 ) { 39 return {counter: initialState.counter}; 40 } else { 41 return {counter: 0}; 42 } 43 } 44 45 async onTraceLoad(ctx: PluginContextTrace): Promise<void> { 46 this.store = ctx.mountStore((init: unknown) => this.migrate(init)); 47 48 ctx.registerCommand({ 49 id: 'dev.perfetto.ExampleState#ShowCounter', 50 name: 'Show ExampleState counter', 51 callback: () => { 52 const counter = this.store.state.counter; 53 ctx.tabs.openQuery( 54 `SELECT ${counter} as counter;`, 55 `Show counter ${counter}`, 56 ); 57 this.store.edit((draft) => { 58 ++draft.counter; 59 }); 60 }, 61 }); 62 } 63 64 async onTraceUnload(_: PluginContextTrace): Promise<void> { 65 this.store.dispose(); 66 } 67} 68 69export const plugin: PluginDescriptor = { 70 pluginId: 'dev.perfetto.ExampleState', 71 plugin: ExampleState, 72}; 73