How can I send and receive a signal when a file loads in my GJS app? - gtk

I have an app that needs to open a file and update UI elements accordingly. I can select and open the file (and log the file contents), but I can't tell the UI elements to update.
I have tried read that I can create and add signals to just about any object, but I need to emit a signal from a function in an imported library.
I'm trying to do something like this:
(in my function that has read a file from disk)
try {
Signals.addSignalMethods(this);
this.emit('update_ui', true);
} catch(e) {
print(e);
}
(and in the main app class)
Signals.addSignalMethods(this);
this.connect('update_ui',() => {
try {
print('>>> updating UI');
this.ui.updateUI();
} catch (e) {
print(e);
}
});
I don't get any errors when I run the app, but the update function is never called.
How can I get the signal to go through?
Here's the code from the main.js file that should catch the signal :
#!/usr/bin/gjs
Gio = imports.gi.Gio;
GLib = imports.gi.GLib;
Gtk = imports.gi.Gtk;
Lang = imports.lang;
Webkit = imports.gi.WebKit2;
Signals = imports.signals;
GObject = imports.gi.GObject;
Pango = imports.gi.Pango;
//
// add app folder to path
//
function getAppFileInfo() {
let stack = (new Error()).stack,
stackLine = stack.split('\n')[1],
coincidence, path, file;
if (!stackLine) throw new Error('Could not find current file (1)');
coincidence = new RegExp('#(.+):\\d+').exec(stackLine);
if (!coincidence) throw new Error('Could not find current file (2)');
path = coincidence[1];
file = Gio.File.new_for_path(path);
return [file.get_path(), file.get_parent().get_path(), file.get_basename()];
}
const path = getAppFileInfo()[1];
imports.searchPath.push(path);
const myApp = new Lang.Class({
Name: 'My Application',
// Create the application itself
_init: function() {
this.application = new Gtk.Application();
// Connect 'activate' and 'startup' signals to the callback functions
this.application.connect('activate', Lang.bind(this, this._onActivate));
this.application.connect('startup', Lang.bind(this, this._onStartup));
},
// Callback function for 'activate' signal presents windows when active
_onActivate: function() {
this._window.present();
},
// Callback function for 'startup' signal builds the UI
_onStartup: function() {
this._buildUI();
},
// Build the application's UI
_buildUI: function() {
// Create the application window
this._window = new Gtk.ApplicationWindow({
application: this.application,
title: "My App",
default_height: 200,
default_width: 400,
window_position: Gtk.WindowPosition.CENTER
});
//
// menu bar
//
const Menubar = imports.lib.menubar;
this._window.set_titlebar(Menubar.getHeader());
Signals.addSignalMethods(this);
this.connect('update_ui', () => {
try {
print('>>> updating UI');
//this.ui.updateUI();
} catch (e) {
print(e);
}
});
// Vbox to hold the switcher and stack.
this._Vbox = new Gtk.VBox({
spacing: 6
});
this._Hbox = new Gtk.HBox({
spacing: 6,
homogeneous: true
});
// const UI = imports.UI.UI;
// this.ui = new UI.UIstack();
// this.ui._buildStack();
// this._Hbox.pack_start(this.ui._stack_switcher, true, true, 0);
this._Vbox.pack_start(this._Hbox, false, false, 0);
// this._Vbox.pack_start(this.ui._Stack, true, true, 0);
// Show the vbox widget
this._window.add(this._Vbox);
// Show the window and all child widgets
this._window.show_all();
},
});
// Run the application
const app = new myApp();
app.application.run(ARGV);
and here's the header bar file that emits the signal:
const GLib = imports.gi.GLib;
const Gtk = imports.gi.Gtk;
const File = imports.lib.file;
const PopWidget = function(properties) {
let label = new Gtk.Label({
label: properties.label
});
let image = new Gtk.Image({
icon_name: 'pan-down-symbolic',
icon_size: Gtk.IconSize.SMALL_TOOLBAR
});
let widget = new Gtk.Grid();
widget.attach(label, 0, 0, 1, 1);
widget.attach(image, 1, 0, 1, 1);
this.pop = new Gtk.Popover();
this.button = new Gtk.ToggleButton();
this.button.add(widget);
this.button.connect('clicked', () => {
if (this.button.get_active()) {
this.pop.show_all();
}
});
this.pop.connect('closed', () => {
if (this.button.get_active()) {
this.button.set_active(false);
}
});
this.pop.set_relative_to(this.button);
this.pop.set_size_request(-1, -1);
this.pop.set_border_width(8);
this.pop.add(properties.widget);
};
const getHeader = function() {
let headerBar, headerStart, imageNew, buttonNew, popMenu, imageMenu, buttonMenu;
headerBar = new Gtk.HeaderBar();
headerBar.set_title("My App");
headerBar.set_subtitle("Some subtitle text here");
headerBar.set_show_close_button(true);
headerStart = new Gtk.Grid({
column_spacing: headerBar.spacing
});
// this.widgetOpen = new PopWidget({ label: "Open", widget: this.getPopOpen() });
imageNew = new Gtk.Image({
icon_name: 'document-open-symbolic',
icon_size: Gtk.IconSize.SMALL_TOOLBAR
});
buttonNew = new Gtk.Button({
image: imageNew
});
buttonNew.connect('clicked', () => {
const opener = new Gtk.FileChooserDialog({
title: 'Select a file'
});
opener.set_action(Gtk.FileChooserAction.OPEN);
opener.add_button('open', Gtk.ResponseType.ACCEPT);
opener.add_button('cancel', Gtk.ResponseType.CANCEL);
const res = opener.run();
if (res == Gtk.ResponseType.ACCEPT) {
const filename = opener.get_filename();
print(filename);
const fileData = File.open(filename);
print(JSON.stringify(fileData, null, 2));
File.unRoll(fileData);
//
// SHOULD SEND A SIGNAL
//
try {
Signals.addSignalMethods(this);
this.emit('update_ui', true);
} catch (e) {
print(e);
}
// this._window.ui.updateUI();
}
opener.destroy();
});
// headerStart.attach(this.widgetOpen.button, 0, 0, 1, 1);
headerStart.attach(buttonNew, 1, 0, 1, 1);
headerBar.pack_start(headerStart);
popMenu = new Gtk.Popover();
imageMenu = new Gtk.Image({
icon_name: 'document-save-symbolic',
icon_size: Gtk.IconSize.SMALL_TOOLBAR
});
buttonMenu = new Gtk.MenuButton({
image: imageMenu
});
buttonMenu.set_popover(popMenu);
popMenu.set_size_request(-1, -1);
buttonMenu.set_menu_model(this.getMenu());
headerBar.pack_end(buttonMenu);
return headerBar;
};
const getPopOpen = function() {
/* Widget popover */
let widget = new Gtk.Grid(),
label = new Gtk.Label({
label: "Label 1"
}),
button = new Gtk.Button({
label: "Other Documents ..."
});
button.connect('clicked', () => {
this.widgetOpen.pop.hide();
this.printText('Open other documents');
});
button.set_size_request(200, -1);
widget.attach(label, 0, 0, 1, 1);
widget.attach(button, 0, 1, 1, 1);
widget.set_halign(Gtk.Align.CENTER);
return widget;
};
const getMenu = function() {
/* GMenu popover */
let menu, section, submenu;
menu = new Gio.Menu();
section = new Gio.Menu();
section.append("Save As...", 'app.saveAs');
section.append("Save All", 'app.saveAll');
menu.append_section(null, section);
section = new Gio.Menu();
submenu = new Gio.Menu();
section.append_submenu('View', submenu);
submenu.append("View something", 'app.toggle');
submenu = new Gio.Menu();
section.append_submenu('Select', submenu);
submenu.append("Selection 1", 'app.select::one');
submenu.append("Selection 2", 'app.select::two');
submenu.append("Selection 3", 'app.select::thr');
menu.append_section(null, section);
section = new Gio.Menu();
section.append("Close All", 'app.close1');
section.append("Close", 'app.close2');
menu.append_section(null, section);
// Set menu actions
let actionSaveAs = new Gio.SimpleAction({
name: 'saveAs'
});
actionSaveAs.connect('activate', () => {
const saver = new Gtk.FileChooserDialog({
title: 'Select a destination'
});
saver.set_action(Gtk.FileChooserAction.SAVE);
saver.add_button('save', Gtk.ResponseType.ACCEPT);
saver.add_button('cancel', Gtk.ResponseType.CANCEL);
const res = saver.run();
if (res == Gtk.ResponseType.ACCEPT) {
const filename = saver.get_filename();
print(filename);
const data = File.rollUp();
File.save(filename, data);
// let data = JSON.stringify(<FILE DATA>, null, '\t');
// GLib.file_set_contents(filename, data);
}
saver.destroy();
});
APP.add_action(actionSaveAs);
let actionSaveAll = new Gio.SimpleAction({
name: 'saveAll'
});
actionSaveAll.connect('activate', () => {
Gtk.FileChooserAction.OPEN
});
APP.add_action(actionSaveAll);
let actionClose1 = new Gio.SimpleAction({
name: 'close1'
});
actionClose1.connect('activate', () => {
this.printText('Action close all');
});
APP.add_action(actionClose1);
let actionClose2 = new Gio.SimpleAction({
name: 'close2'
});
actionClose2.connect('activate', () => {
this.printText('Action close');
});
APP.add_action(actionClose2);
let actionToggle = new Gio.SimpleAction({
name: 'toggle',
state: new GLib.Variant('b', true)
});
actionToggle.connect('activate', (action) => {
let state = action.get_state().get_boolean();
if (state) {
action.set_state(new GLib.Variant('b', false));
} else {
action.set_state(new GLib.Variant('b', true));
}
this.printText('View ' + state);
});
APP.add_action(actionToggle);
let variant = new GLib.Variant('s', 'one');
let actionSelect = new Gio.SimpleAction({
name: 'select',
state: variant,
parameter_type: variant.get_type()
});
actionSelect.connect('activate', (action, parameter) => {
let str = parameter.get_string()[0];
if (str === 'one') {
action.set_state(new GLib.Variant('s', 'one'));
}
if (str === 'two') {
action.set_state(new GLib.Variant('s', 'two'));
}
if (str === 'thr') {
action.set_state(new GLib.Variant('s', 'thr'));
}
this.printText('Selection ' + str);
});
APP.add_action(actionSelect);
return menu;
};
it's not a class, just a static library... it's imported by the main.js file, so I would think the scope would be the same, but maybe not...

I'm going to over-answer while I get to your question again, because I see some difficulties and some "best practices" you could be using. I think it's much preferrable to use a direct subclass of GtkApplication and use ES6 classes.
const Gio = imports.gi.Gio;
const GObject = imports.gi.GObject;
const Gtk = imports.gi.Gtk;
var MyApp = GObject.registerClass({
// This must be unique, although I don't believe you have to specify it
GTypeName: 'MyApp',
// GObject already have their own signal system, so invoking addSignalMethods()
// will override the existing methods and could cause you problems. Here's a
// simple example of how you'd add a GObject signal to a subclass; the resulting
// callback would look like:
//
// myapp.connect('update-ui', (application, bool) => { ... });
Signals: {
'update-ui': {
param_types: [GObject.TYPE_BOOLEAN]
},
}
}, class MyApp extends Gtk.Application {
_init(params) {
// You could pass the regular params straight through
//super._init(params);
// Or setup your class to be initted without having to pass any args in your
// constructor
super._init({
// This will also become your well-known name on DBus, with the matching
// object path of /org/github/username/MyApp.
//
// GApplication framework will also use these for other things like any
// GResource you bundle with your application.
application_id: 'com.github.username.MyApp',
// There are other flags you can set to allow your app to be a target for
// "Open with...", but that's not what you're asking about today :)
flags: Gio.ApplicationFlags.HANDLES_OPEN
});
// You can also do other setup , however it's important to note that
// GApplication's are generally "single-instance" processes, so you want most
// of that setup in ::startup which will only run if this is the primary
// instance.
//
// On the other hand if you pass HANDLES_OPEN, for example, that signal/vfunc
// will still be invoked.
GLib.set_prgname(this.application_id);
GLib.set_application_name('MyApp');
}
_buildUI() {
// ...
}
// defining a virtual function usually means overriding the default handler for a
// a signal. In this case, it's not much of an issue but for frequently emitted
// signals it avoids "marshalling" the C values into JS values and back again.
//
// In other words, defining this function means it will be called as if you
// connected to the ::activate signal.
vfunc_activate() {
this._window.present();
}
// ::activate is a special case, but for most vfunc's is necessary to "chain up",
// which really just means calling the super class's original function inside your
// override.
vfunc_startup() {
// In ::startup we need to chain up first since GApplication does important
// setup checks here
super.vfunc_startup();
// your stuff after
this._buildUI();
// In _buildUI() you correctly passed your GtkApplication as the application
// property, which will keep the application running so long as that window
// is open.
//
// If you wanted your application to stay open regardless, you call hold()
this.hold();
}
vfunc_shutdown() {
// ::shutdown on the other hand is the reverse; first we do our stuff, then
// chain up to super class. This is a good time to do any cleanup you need
// before the process exits.
this._destroyUI();
// chain up
super.vfunc_shutdown();
}
});
// For technical reasons, this is the proper way you should start your application
(new MyApp()).run([imports.system.programInvocationName].concat(ARGV));
The addSignalMethods() function only needs to be called once, but as mentioned it will override the existing signal methods and that could cause you problems if you call it on a GObject that already has signals defined. It basically does this:
addSignalMethods(obj) {
obj.emit = function() {
// custom signal code
}
...
It was really meant for pure JS classes that don't have a signal system already.
// SHOULD SEND A SIGNAL
//
try {
Signals.addSignalMethods(this);
this.emit('update_ui', true);
} catch (e) {
print(e);
}
The reason why this wasn't working for you is that getHeaderbar() is a top-level function in imports.lib.menubar so when you called addSignalMethods(this), this === imports.lib.menubar. Therefore to catch that signal you would had to call:
imports.lib.menubar.connect('update_ui', () => {});
When you called it in _buildUI():
Signals.addSignalMethods(this);
this.connect('update_ui', () => {
try {
print('>>> updating UI');
//this.ui.updateUI();
} catch (e) {
print(e);
}
});
this === MyApp, so you were first overriding MyApp's signal methods, then connecting to itself. The Signals import is fairly lax so it doesn't require a signal to be defined before use; you just connect to what you want and emit what you want. This is why you weren't getting any errors or warnings.
There are couple ways you can solve your problem:
// (1) Pick an object to emit and connect from and only add the signal methods once
Signals.addSignalMethods(headerBar);
// Since you're using an arrow function you can call this in the same place since it
// should still be in scope
headerBar.emit('update_ui', true);
// You can connect by grabbing the headerbar widget from your constructed window
this._window.get_titlebar().connect('update_ui', (headerBar, bool) => {});
// (2) Define a signal *on* your GtkApplication and use it as a relay
// Connect from a function in MyApp (so in `this.connect`, `this === MyApp`)
// To set `this` for the callback itself, use `Function.bind()`
this.connect('update-ui', this.ui.updateUI.bind(ui));
// You can always grab the primary instance of your GtkApplication (from anywhere)
// and emit the signal to invoke the MyApp.ui.updateUI() function
let myApp = Gio.Application.get_default();
myApp.emit('update-ui', true);
// (3) How I'd probably do it; just invoke the method directly
let myApp = Gio.Application.get_default();
myApp.ui.updateUI();

Related

Failed to add new elements when set initialState as an empty object

I try to use redux toolkit and I have this as menu-slice.js
I try to use property accessors to add a new property to fileItems, its initial value is an empty object.
import { createSlice } from "#reduxjs/toolkit";
const menuSlice = createSlice({
name: "ui",
initialState: {
fileItems: {},
},
reducers: {
setFileDate: (state, action) => {
state.FileDate = action.payload;
},
replaceFileItems: (state, action) => {
const filesList = action.payload.map((fileName) =>
fileName.slice(fileName.indexOf("/") + 1)
);
state.fileItems[state.FileDate] = filesList;
console.log(`filesList: ${filesList}`);
console.log(`state.fileItems: ${JSON.stringify(state.fileItems)}`);
console.log(`state.FileDate: ${state.FileDate}`);
state.fileContents = null;
},
I call dispatch with the api return value ( dispatch(menuActions.replaceFileItems(fileResponse.data));)
in menu-action.js:
the return value is an array of strings.
export const fetchFiles = (fileDate) => {
return async (dispatch) => {
const fetchFilesList = async () => {
const response = await fetch(
"some url" +
new URLSearchParams({
env: "https://env.com",
date: fileDate,
})
);
if (!response.ok) {
throw new Error("Fail to fetch files list!");
}
const data = await response.json();
return data;
};
try {
const fileResponse = await fetchFilesList();
dispatch(menuActions.setFileDate(FileDate));
dispatch(menuActions.replaceFileItems(fileResponse.data));
} catch (error) {
dispatch(
menuActions.showNotification({....
})
);
}
};
};
But it never prints console logs and didn't display where went wrong in the console or in the chrome redux extension.
I want to add data into state.fileItems on each click that triggers fetchFiles() when it returns a new array:
from state.fileItems = {}
check if state.fileItems already has the date as key,
if not already has the date as key,
change to ex: state.fileItems = {"2022-01-01": Array(2)}
and so on..
ex: state.fileItems = { "2022-01-01": Array(2), "2022-01-02": Array(2) }
I also tried to set state.fileItems as an empty array, and use push, but it didn't work either, nothing printed out, state.fileItems value was always undefined.
Can anyone please tell me why this didn't work?
Thanks for your time to read my question.

Draft-JS - Entity component doesn't re-render when data changes

I would like to have my text editor display how many times a content block has been selected and executed though a key command.
I'm doing this by applying an entity to the selected block with a evaluatedTimes property.
The data is changed correctly but the entity component doesn't re-render until I insert new characters in the block of text.
The decorator strategy of the entity doesn't get called, so the only way out I found is to update the editor state with a new decorator instance. This way the entity components get re-rendered but the solution fills a bit hacky.
dependencies:
"draft-js": "^0.11.3",
"draft-js-plugins-editor": "^3.0.0",
"draftjs-utils": "^0.10.2"
code:
// plugin.js
import { EditorState } from "draft-js";
import { getSelectionText, getSelectionEntity } from "draftjs-utils";
import { EvaluatedSpan } from "./components";
import { findEvaluatedEntities, createEvaluatedEntity } from "./entities";
export function createCodeEvaluationPlugin({ onEvaluate = () => {} }) {
return {
decorators: [
{
strategy: findEvaluatedEntities,
component: EvaluatedSpan
}
],
keyBindingFn: e => {
// CMD + ENTER
if (e.metaKey && e.keyCode === 13) {
return "evaluate";
}
},
handleKeyCommand: (command, editorState, _, { setEditorState }) => {
if (command === "evaluate") {
const selectionState = editorState.getSelection();
const contentState = editorState.getCurrentContent();
const entityKey = getSelectionEntity(editorState);
// If selection contains an entity:
if (!entityKey) {
// Create new entity and update editor.
setEditorState(createEvaluatedEntity(editorState, selectionState));
} else {
// Modify entity data.
const entity = contentState.getEntity(entityKey);
const nextContentState = contentState.mergeEntityData(entityKey, {
evaluatedTimes: entity.data.evaluatedTimes + 1
});
// Update editor.
setEditorState(
EditorState.push(editorState, nextContentState, "change-block-data")
);
}
// Pass text to callback handle
const selectionText = getSelectionText(editorState);
onEvaluate(selectionText);
return "handled";
}
return "not-handled";
}
};
}
According to this (https://github.com/facebook/draft-js/issues/1702) you could also update the selection state, which may be sufficient for you.
Works for me:
function forceRerender(editorState: EditorState): EditorState {
const selectionState = editorState.getSelection();
return EditorState.forceSelection(editorState, selectionState);
}

Actions on Google: How To Implement Database & User Entities (Session) using NodeJS

I'm looking to have a database which contain the devices data that each user has. When the user connects to the Node server, it will somehow retrieve all the devices names and return it to AoG for the NLB engine recognise those names.
How would I go about implementing this?
My current code is attached below (built from sample code from Google):
'use strict';
const util = require('util');
const functions = require('firebase-functions');
const {
dialogflow,
Suggestions,
BasicCard,
Button,
SimpleResponse,
} = require('actions-on-google');
const {values, concat, random, randomPop} = require('./util');
const responses = require('./responses');
/** Dialogflow Contexts {#link https://dialogflow.com/docs/contexts} */
const AppContexts = {
FACT: 'choose_fact-followup',
CATS: 'choose_cats-followup',
XXX: 'choose_xxx-followup',
};
/** Dialogflow Context Lifespans {#link https://dialogflow.com/docs/contexts#lifespan} */
const Lifespans = {
DEFAULT: 5,
};
const app = dialogflow({
debug: true,
init: () => ({
data: {
// Convert array of facts to map
facts: responses.categories.reduce((o, c) => {
o[c.category] = c.facts.slice();
return o;
}, {}),
cats: responses.cats.facts.slice(), // copy cat facts
},
}),
});
/**
* Greet the user and direct them to next turn
* #param {DialogflowConversation} conv DialogflowConversation instance
* #return {void}
*/
app.intent('Unrecognized Deep Link Fallback', (conv) => {
const response = util.format(responses.general.unhandled, conv.query);
const suggestions = responses.categories.map((c) => c.suggestion);
conv.ask(response, new Suggestions(suggestions));
});
// redirect to the intent handler for tell_fact
app.intent('choose_fact', 'tell_fact');
// Say a fact
app.intent('tell_fact', (conv, {category}) => {
const {facts, cats, xxx} = conv.data;
if (values(facts).every((c) => !c.length)) {
// If every fact category facts stored in conv.data is empty,
// close the conversation
return conv.close(responses.general.heardItAll);
}
const categoryResponse =
responses.categories.find((c) => c.category === category);
const fact = randomPop(facts[categoryResponse.category]);
if (!fact) {
const otherCategory =
responses.categories.find((other) => other !== categoryResponse);
const redirect = otherCategory.category;
const parameters = {
category: redirect,
};
// Add facts context to outgoing context list
conv.contexts.set(AppContexts.FACT, Lifespans.DEFAULT, parameters);
const response = [
util.format(responses.transitions.content.heardItAll, category, redirect),
];
// If cat facts not loaded or there still are cat facts left
if (cats.length) {
response.push(responses.transitions.content.alsoCats);
}
response.push(responses.general.wantWhat);
conv.ask(concat(...response));
conv.ask(new Suggestions(otherCategory.suggestion));
if (cats.length) {
conv.ask(new Suggestions(responses.cats.suggestion));
}
return;
}
const {factPrefix} = categoryResponse;
// conv.ask can be called multiple times to have the library construct
// a single response itself the response will get sent at the end of
// the function or if the function returns a promise, after the promise
// is resolved.
conv.ask(new SimpleResponse({
speech: concat(factPrefix, fact),
text: factPrefix,
}));
conv.ask(responses.general.nextFact);
conv.ask(new BasicCard({
title: fact,
image: random(responses.content.images),
buttons: new Button({
title: responses.general.linkOut,
url: responses.content.link,
}),
}));
console.log('hiwwxxxxxww thi is aaron');
conv.ask(responses.general.suggestions.confirmation);
});
// Redirect to the intent handler for tell_cat_fact
app.intent('choose_cats', 'tell_cat_fact');
// Say a cat fact
app.intent('tell_cat_fact', (conv) => {
const {cats} = conv.data;
console.log('this is cats data' + {cats});
const fact = randomPop(cats);
if (!fact) {
conv.contexts.delete(AppContexts.FACT);
conv.contexts.delete(AppContexts.CATS);
conv.ask(responses.transitions.cats.heardItAll);
return conv.ask(responses.general.suggestions.confirmation);
}
const {factPrefix, audio} = responses.cats;
// conv.ask can be called multiple times to have the library construct
// a single response itself. The response will get sent at the end of
// the function or if the function returns a promise, after the promise
// is resolved.
const sound = util.format(audio, random(responses.cats.sounds));
conv.ask(new SimpleResponse({
// <speak></speak> is needed here since factPrefix is a SSML string
// and contains audio.
speech: `<speak>${concat(factPrefix, sound, fact)}</speak>`,
text: factPrefix,
}));
conv.ask(responses.general.nextFact);
conv.ask(new BasicCard({
title: fact,
image: random(responses.cats.images),
buttons: new Button({
title: responses.general.linkOut,
url: responses.cats.link,
}),
}));
console.log('hiwwxxxxxww thi is aaron');
conv.ask(responses.general.suggestions.confirmation);
});
//say a tv channel
app.intent('volume', (conv, {device_name,device_action, value}) => {
var no_device_name = device_name;
var no_value = value;
var no_device_action = device_action;
var this_device_value = util.inspect(value, false, null);
var this_device_name = util.inspect(device_name, false, null);
var this_device_action = util.inspect(device_action, false, null);
console.log(this_device_action[0]);
if (no_device_name[0] == 'channel'){
console.log('inside tv but CHANNEL');
}
else{
console.log('VOLUME');
}
console.log('THIS IS VOL');
console.log(no_device_action[0]);
conv.ask(`Alright, ${device_name} VOLUM is now ${value}! `);
console.log('inside volume ' + value[0]);
console.log('inside volume' + device_name[0]);
console.log('inside volume' + device_action[0]);
console.log('hiwwxxxxxww thi is aaron');
});
//say a tv channel
app.intent('channel', (conv, {device_channel_name, device_channel_action, channel_value}) => {
console.log('THIS IS CHANNEL');
conv.ask(`Alright, ${device_channel_name} CHANNEL is now ${channel_value}! `);
console.log('inside CHANNEL ' + channel_value[0]);
console.log('inside CHANNEL' + device_channel_name[0]);
console.log('inside CHANNEL' + device_channel_action[0]);
console.log('hiwwxxxxxww thi is aaron');
});
app.intent('no_input', (conv) => {
const repromptCount = parseInt(conv.arguments.get('REPROMPT_COUNT'));
if (repromptCount === 0) {
conv.ask(`What was that?`);
} else if (repromptCount === 1) {
conv.ask(`Sorry I didn't catch that. Could you repeat yourself?`);
} else if (conv.arguments.get('IS_FINAL_REPROMPT')) {
conv.close(`Okay let's try this again later.`);
}
});
// The entry point to handle a http request
exports.factsAboutGoogle = functions.https.onRequest(app);
conv.user.storage is supposed to persist for up to 30 days of non-use, indefinitely for regular use, and pretty much linked to the relevant 'Google account', across devices. Note the user can also FORCIBLY disassociate themselves from the data manually (via the assistant app, if they dig into options to find your app).
All that as described here at the time of writing:
https://developers.google.com/actions/identity/user-info
conv.user.id seems to remain constant similarly - So could be used to 'key' into an external database if you want to do that.
But you might as well just use userStorage - It seems to have the same lifespan and reliability as the user.id key anyway, and saves you hassle/latency of hitting a DB.
As far as I can tell, if you want a more reliable mechanism than this, then Account Linking is the only other way to go. I will leave you to dig into that yourself...

Why TextDocumentContentProvider dont call provideTextDocumentContent on update when query params changes?

as title says, when i wanna update TextDocumentContentProvider with different query params by calling update method provideTextDocumentContent is not called...
only way i managed to get it working was with same URI as in calling
vscode.commands.executeCommand('vscode.previewHtml', URI, 2, 'Storybook');
relevant part of code:
// calculates uri based on editor state - depends on actual caret position
// all uris will start with 'storybook://preview'
function getPreviewUri(editor: vscode.TextEditor): vscode.Uri;
// transforms uri, so web server will understand
// ex: 'storybook://preview?name=fred' -> 'http://localhost:12345/preview/fred?full=1'
function transformUri(uri: vscode.Uri): vscode.Uri;
class StorybookContentProvider implements vscode.TextDocumentContentProvider
{
provideTextDocumentContent(uri: vscode.Uri): string {
var httpUri = transformUri(uri);
return `<iframe src="${httpUri}" />`;
}
onDidChange = new vscode.EventEmitter<vscode.Uri>();
update(uri: vscode.Uri) {
this.onDidChange(uri);
}
}
export function activate(context: vscode.ExtensionContext)
{
vscode.workspace.onDidChangeTextDocument(
(e: vscode.TextDocumentChangeEvent) => {
if (e.document === vscode.window.activeTextEditor.document) {
const previewUri = getPreviewUri(vscode.window.activeTextEditor);
provider.update(previewUri);
}
}
);
vscode.window.onDidChangeTextEditorSelection(
(e: vscode.TextEditorSelectionChangeEvent) => {
if (e.textEditor === vscode.window.activeTextEditor) {
const previewUri = getPreviewUri(vscode.window.activeTextEditor);
provider.update(previewUri);
}
}
);
const provider = new StorybookContentProvider();
context.subscriptions.push(
vscode.commands.registerCommand('extension.showStorybook', () => {
vscode.commands.executeCommand('vscode.previewHtml', vscode.Uri.parse('storybook://preview'), 2, 'Storybook')
}),
vscode.workspace.registerTextDocumentContentProvider('storybook', provider)
);
}

With Chrome FileSystem, let the user choose a Directory, load files inside. And save files in that directory without prompting again

I could not found any examples with this scenario so here we go:
I want the user choose a directory, load all files inside it, change them, and save this file overriding it or saving a new file in that same directory without asking where he want to save.
I don't know how to list the files of the directory
I don't know how to save a file in a directory without prompting the filechooser window
I believe it is possible because I see something similar here (last paragraph):
http://www.developer.com/lang/using-the-file-api-outside-the-sandbox-in-chrome-packaged-apps.html
Any answer will be appreciated, Thank you
EDIT: Thanks to Chris Johnsen for giving me this great answer:
var fileHandler = function() {
var _entry = null;
this.open = function(cb) {
chrome.fileSystem.chooseEntry({
type: 'openDirectory'
}, function(dirEntry) {
if (!dirEntry || !dirEntry.isDirectory) {
cb && cb(null);
return;
}
_entry = dirEntry;
listDir(_entry, cb);
});
};
this.save = function(filename, source) {
chrome.fileSystem.getWritableEntry(_entry, function(entry) {
entry.getFile(filename, {
create: true
}, function(entry) {
entry.createWriter(function(writer) {
writer.onwrite = function() {
writer.onwrite = null;
writer.truncate(writer.position);
};
writer.write(new Blob([source], {
type: 'text/javascript'
}));
});
});
});
};
this.saveAs = function(filename, source) {
chrome.fileSystem.chooseEntry({
type: 'openDirectory'
}, function(entry) {
chrome.fileSystem.getWritableEntry(entry, function(entry) {
entry.getFile(filename, {
create: true
}, function(entry) {
entry.createWriter(function(writer) {
writer.onwrite = function() {
writer.onwrite = null;
writer.truncate(writer.position);
};
writer.write(new Blob([source], {
type: 'text/javascript'
}));
});
});
});
});
};
var listDir = function(dirent, cb, listing) {
if (listing === undefined) {
listing = [];
}
var reader = dirent.createReader();
var read_some = reader.readEntries.bind(reader, function(ents) {
if (ents.length === 0) {
return cb && cb(listing);
}
var process_some = function(ents, i) {
for (; i < ents.length; i++) {
listing.push(ents[i]);
if (ents[i].isDirectory) {
return listDir(ents[i], process_some.bind(null, ents, i + 1), listing);
}
}
read_some();
};
process_some(ents, 0);
}, function() {
console.error('error reading directory');
});
read_some();
};
};
Your save method should work fine (mostly, see below) for your second requirement (write to a code-chosen filename without another user prompt), but there are a couple of bugs in open (at least as presented in the question):
Inside the chooseEntry callback, this !== fileHandler because the callback is invoked with a different this (probably the background page’s window object).
You can work around this in several ways:
Use fileHandler instead of this (if you are not using it as any kind of prototype).
Use .bind(this) to bind each of your callback functions to the same context.
Use var self = this; at the top of open and use self.entry (et cetera) in the callbacks.
You may want to call cb for the success case. Maybe you have another way of postponing calls to (e.g.) fileHandler.save (clicking on some element to trigger the save?), but adding something like
⋮
cb && cb(self.entry);
⋮
after self.entry = dirEntry makes it easy to (e.g.) chain open and save:
fileHandler.open(function(ent) {
fileHandler.save('newfile','This is the text\nto save in the (possibly) new file.');
});
There is a latent bug in save: if you ever overwrite an existing file, then you will want to call writer.truncate() (unless you always write more bytes than the file originally held).
⋮
writer.onwrite = function() {
writer.onwrite = null;
writer.truncate(writer.position);
};
writer.write(…);
⋮
It looks like you have a good start on the file listing part. If you want to reference the list of files later, then you might want to save them in your object instead of just logging them; this can get a bit hairy if you want to recurse into subdirectories (and also not assume that readEntries returns everything for its first call).
function list_dir(dirent, cb, listing) {
if (listing === undefined) listing = [];
var reader = dirent.createReader();
var read_some = reader.readEntries.bind(reader, function(ents) {
if (ents.length === 0)
return cb && cb(listing);
process_some(ents, 0);
function process_some(ents, i) {
for(; i < ents.length; i++) {
listing.push(ents[i]);
if (ents[i].isDirectory)
return list_dir(ents[i], process_some.bind(null, ents, i + 1), listing);
}
read_some();
}
}, function() {
console.error('error reading directory');
});
read_some();
}
You could use it in the open callback (assuming you add its success callback) like this:
fileHandler.open(function(ent) {
ent && list_dir(ent, function(listing) {
fileHandler.listing = listing;
console.log('listing', fileHandler.listing.map(function(ent){return ent.fullPath}).join('\n'));
fileHandler.save('a_dir/somefile','This is some data.');
});
});