8000 feat: Expose renderer spellcheck API by lishid · Pull Request #25060 · electron/electron · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

feat: Expose renderer spellcheck API #25060

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 19, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions docs/api/web-frame.md
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,20 @@ renderer process.

Returns `WebFrame` - that has the supplied `routingId`, `null` if not found.

### `webFrame.isWordMisspelled(word)`

* `word` String - The word to be spellchecked.

Returns `Boolean` - True if the word is misspelled according to the built in
spellchecker, false otherwise. If no dictionary is loaded, always return false.

### `webFrame.getWordSuggestions(word)`

* `word` String - The misspelled word.

Returns `String[]` - A list of suggested words for a given word. If the word
is spelled correctly, the result will be empty.

## Properties

### `webFrame.top` _Readonly_
Expand Down
39 changes: 39 additions & 0 deletions shell/renderer/api/electron_api_web_frame.cc
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@

#include "base/command_line.h"
#include "base/memory/memory_pressure_listener.h"
#include "base/strings/utf_string_conversions.h"
#include "components/spellcheck/renderer/spellcheck.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_frame_observer.h"
#include "content/public/renderer/render_frame_visitor.h"
Expand All @@ -24,6 +26,7 @@
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "shell/renderer/api/electron_api_spell_check_client.h"
#include "shell/renderer/electron_renderer_client.h"
#include "third_party/blink/public/common/page/page_zoom.h"
#include "third_party/blink/public/common/web_cache/web_cache_resource_type_stats.h"
#include "third_party/blink/public/platform/web_cache.h"
Expand Down Expand Up @@ -101,6 +104,24 @@ content::RenderFrame* GetRenderFrame(v8::Local<v8::Value> value) {
return content::RenderFrame::FromWebFrame(frame);
}

bool SpellCheckWord(v8::Isolate* isolate,
v8::Local<v8::Value> window,
const std::string& word,
std::vector<base::string16>* optional_suggestions) {
size_t start;
size_t length;

ElectronRendererClient* client = ElectronRendererClient::Get();
auto* render_frame = GetRenderFrame(window);
if (!render_frame)
return true;

base::string16 w = base::UTF8ToUTF16(word);
int id = render_frame->GetRoutingID();
return client->GetSpellCheck()->SpellCheckWord(
w.c_str(), 0, word.size(), id, &start, &length, optional_suggestions);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hang on, I think we can just specify kNoTag for the tag? Which would mean we wouldn't need to fetch the render frame, which makes me think maybe this API shouldn't be on webFrame at all?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hm... https://source.chromium.org/chromium/chromium/src/+/master:components/spellcheck/renderer/spellcheck_provider.cc;l=310;drc=c83ae1d48c762639e626be9be0c77a209fdea359 is a reference that uses the routing id. there are other places in the code that use kNoTag. cc @MarshallOfSound for further review

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

}

class RenderFrameStatus final : public content::RenderFrameObserver {
public:
explicit RenderFrameStatus(content::RenderFrame* render_frame)
Expand Down Expand Up @@ -671,6 +692,20 @@ blink::WebCacheResourceTypeStats GetResourceUsage(v8::Isolate* isolate) {
return stats;
}

bool IsWordMisspelled(v8::Isolate* isolate,
v8::Local<v8::Value> window,
const std::string& word) {
return !SpellCheckWord(isolate, window, word, nullptr);
}

std::vector<base::string16> GetWordSuggestions(v8::Isolate* isolate,
v8::Local<v8::Value> window,
const std::string& word) {
std::vector<base::string16> suggestions;
SpellCheckWord(isolate, window, word, &suggestions);
return suggestions;
}

void ClearCache(v8::Isolate* isolate) {
isolate->IdleNotificationDeadline(0.5);
blink::WebCache::Clear();
Expand Down Expand Up @@ -826,6 +861,10 @@ void Initialize(v8::Local<v8::Object> exports,
&ExecuteJavaScriptInIsolatedWorld);
dict.SetMethod("setIsolatedWorldInfo", &SetIsolatedWorldInfo);
dict.SetMethod("getResourceUsage", &GetResourceUsage);
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
dict.SetMethod("isWordMisspelled", &IsWordMisspelled);
dict.SetMethod("getWordSuggestions", &GetWordSuggestions);
#endif
dict.SetMethod("clearCache", &ClearCache);
dict.SetMethod("_findFrameByRoutingId", &FindFrameByRoutingId);
dict.SetMethod("_getFrameForSelector", &GetFrameForSelector);
Expand Down
14 changes: 13 additions & 1 deletion shell/renderer/electron_renderer_client.cc
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,27 @@ bool IsDevToolsExtension(content::RenderFrame* render_frame) {

} // namespace

// static
ElectronRendererClient* ElectronRendererClient::self_ = nullptr;

ElectronRendererClient::ElectronRendererClient()
: node_bindings_(
NodeBindings::Create(NodeBindings::BrowserEnvironment::RENDERER)),
electron_bindings_(new ElectronBindings(node_bindings_->uv_loop())) {}
electron_bindings_(new ElectronBindings(node_bindings_->uv_loop())) {
DCHECK(!self_) << "Cannot have two ElectronRendererClient";
self_ = this;
}

ElectronRendererClient::~ElectronRendererClient() {
asar::ClearArchives();
}

// static
ElectronRendererClient* ElectronRendererClient::Get() {
DCHECK(self_);
return self_;
}

void ElectronRendererClient::RenderFrameCreated(
content::RenderFrame* render_frame) {
new ElectronRenderFrameObserver(render_frame, this);
Expand Down
4 changes: 4 additions & 0 deletions shell/renderer/electron_renderer_client.h
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ class ElectronRendererClient : public RendererClientBase {
ElectronRendererClient();
~ElectronRendererClient() override;

static ElectronRendererClient* Get();

// electron::RendererClientBase:
void DidCreateScriptContext(v8::Handle<v8::Context> context,
content::RenderFrame* render_frame) override;
Expand Down Expand Up @@ -70,6 +72,8 @@ class ElectronRendererClient : public RendererClientBase {
// assertion, so we have to keep a book of injected web frames.
std::set<content::RenderFrame*> injected_frames_;

static ElectronRendererClient* self_;

DISALLOW_COPY_AND_ASSIGN(ElectronRendererClient);
};

Expand Down
19 changes: 18 additions & 1 deletion spec-main/spellchecker-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,1 98A9 0 @@ ifdescribe(features.isBuiltinSpellCheckerEnabled())('spellchecker', () => {

beforeEach(async () => {
w = new BrowserWindow({
show: false
show: false,
webPreferences: {
nodeIntegration: true
}
});
await w.loadFile(path.resolve(__dirname, './fixtures/chromium/spellchecker.html'));
});
Expand Down Expand Up @@ -62,6 +65,20 @@ ifdescribe(features.isBuiltinSpellCheckerEnabled())('spellchecker', () => {
expect(contextMenuParams.dictionarySuggestions).to.have.length.of.at.least(1);
});

ifit(shouldRun)('should expose webFrame spellchecker correctly', async () => {
await w.webContents.executeJavaScript('document.body.querySelector("textarea").value = "Beautifulllll asd asd"');
await w.webContents.executeJavaScript('document.body.querySelector("textarea").focus()');
// Wait for spellchecker to load
await delay(500);

const callWebFrameFn = (expr: string) => w.webContents.executeJavaScript('require("electron").webFrame.' + expr);

expect(await callWebFrameFn('isWordMisspelled("test")')).to.equal(false);
expect(await callWebFrameFn('isWordMisspelled("testt")')).to.equal(true);
expect(await callWebFrameFn('getWordSuggestions("test")')).to.be.empty();
expect(await callWebFrameFn('getWordSuggestions("testt")')).to.not.be.empty();
});

describe('custom dictionary word list API', () => {
let ses: Session;

Expand Down
0