How to change the chromium default language by modify the source code? - chromium

I'm working on a Chromium project, which requires change the default language from english to Chinese from the source code,and now open a Chinese page will appear garbled situation.
I modify the method GetApplicationLocale() in src/content/public/browser/content_browser_client.cc: return "en-US" to return "zh-CN", but it doesn't work.
I want to change the language by modifing the source code rather than the setting button "Language and input settings".

It is not possible to change the language of browser from source code. You can detect which language it is currently using and then ask user to change it.
Here is how you can do it using javaScript:
var language = navigator.language || navigator.userLanguage;

Related

Can vscode's markdown preview scripts trigger actions directly in an extension?

I'm writing a vscode extension where I'm hoping to squeeze more dynamic functionality out of markdown preview. Effectively the problem I'm trying to solve is:
In markdown preview, there's a checkbox
When user clicks the checkbox in markdown preview, send a message/event to the vscode extension runtime
Vscode extension can listen for this message/event and store the action in local storage
Checkbox state is saved - and subsequent renders of the markdown preview can use this action
Ideally, I'd like to do this while keeping the default markdown preview security (https://code.visualstudio.com/Docs/languages/markdown#_strict). After all, I don't need the extension to or markdown preview script to talk to a remote server - I just want them to be able to talk to one another.
Problem as code
To write the problem as sudo code, I want my markdown preview script to contain something like:
const button = ... // get button element
button.addEventListener('click', () => {
... /*
* Send a message to the vscode extension. Something like:
* `vscode.postMessage('vscode.my-extension.preview-action' + value)`
* (which I can't get to work, I'll discuss why)
*/
});
where then my extension can listen for messages like 'vscode.my-extension.preview-action'.
What I've Tried Already
I have tried acquireVsCodeApi() but because the markdown extension already does that, I can't do it again in the subsequent loaded script. I've also tried registering a uri handler but as far as I can try out the preview script still needs to fetch to that uri, which is still blocked by the default markdown security settings.
Perhaps markdown preview scripts are not the place to do this kind of thing, but I just wanted to leverage as much as possible that's already there with the vscode markdown extension. I want to supplement markdown but not replace it, the functionality I want to add is just icing on markdown documentation.
I've read https://code.visualstudio.com/api/extension-guides/markdown-extension#adding-advanced-functionality-with-scripts and it doesn't tell me much about markdown extension scripts capabilities and limitations.
Thanks to #LexLi I looked at some of the source code in the markdown extension and was able to come up with an ugly hack to make this work in preview scripts. Markdown allows normal clicks. And vscode extensions can handle normal clicks. I've paraphrased the code so there could be small syntax errors.
In the extension I did this:
vscode.window.registerUriHandler({
handleUri(uri: vscode.Uri): vscode.ProviderResult<void> {
console.log(`EXTENSION GOT URL: ${uri.toString()}`);
},
});
Then I made sure my extension/preview script put this in the document
<!-- in the preview script I place a button like this -->
<!-- it even works with hidden :) so I can do more app customization -->
<a
hidden
id="my-extension-messager"
href="vscode://publisher-id.my-extension"
>
cant see me but I'm there
</a>
Then my preview script I can even set href before faking a click:
const aMessager = document.querySelector("#my-extension-messager");
console.log('client is setting attribute and clicking...')
aMessager.setAttribute('href', 'vscode://publisher-id.my-extension?action=do-something');
aMessager.click();
console.log('client clicked');
Logs I saw (trimmed/tweaked from my particular extension to match the contrived example):
client is setting attribute and clicking...
client clicked
[Extension Host] EXTENSION GOT URL: vscode://publisher-id.my-extension?action%3Ddo-something
It's a hack but I can do a lot with this. Within the URL I can encode data back to the extension and kind of pass whatever I want (as long as data is relatively small).

pyqt5 - qtextedit - Input Language

Is there a way to change the input keyboard layout in a Qt app? I want to be able to input in the same QTextEdit Widget in English and Russian by switching between languages frequently. One option is to have the cyrillic keyboard activated on Windows and switching between input languages using the windows key and the spacebar.
I want to bypass the feature though on the os level and implement it directly in my app by defining a shortcut or a push button to select the input language. The reason being that the end users (Russian speakers) will be using the app on an English language PC and they should not have to fiddle around with OS settings in a foreign language. The keyboards in use have an English layout with additional Cyrillic characters so typing should not be a problem.
I want to ask if there is a direct method (it would make sense to have one, i hope I am just unable to find it). I could overload the keyPressEvent for my widget as a last alternative. I just hope that there is a better way to do it since I am switching between standard languages.
Overriding keyPressEvent.
Returning cyril characters instead of the texts of QKeyEvent.
Making QMenu for switching the language.
for example,
#class QTextEdit
def keyPresEvent(self, event):
if self.isCurrentWritingSystem == "Russian":
#If you use english keyboard...
if event.key() == Qt.Key_A:
tc = self.textCursor()
tc.insertText("ф")
return
... for others ↓
else:
#codes for normal russian keyboard you don't need to do anything.
return super().keyPressEvent(event)
On the other hand, if you use russian keyboard as default.
if self.isCurrentWritingSystem == "English":
#if you use russian keyboard...
if event.key() == Qt.Key_A:
tc = self.textCursor()
tc.insertText("a")
return
else:
#codes for normal english keyboard. you don't need to do anything.
return super().keyPressEvent(event)

switching between languages in same file

I recently attended a user group meeting where the IntelliJ representative was demonstrating version 13.
He demonstrated how to switch the code completion view of a file. I do not exactly remember what the file extension of this particular file was, probably java.
The concept was that if the file is html with embedded javascript he could then switch the code completion between html and javascript with a shortcut. If he says treat the file as html then all code in file was treated for code completion purposes as html, and vice versa for javascript.
Does anybody know what shortcut he might have been using to enable the language switch?
Sounds like you may be referring to the IntelliLang feature. IntelliJ IDEA can be aware of other languages embedded within a file.
A simple example is in an HTML file that has CSS and JavaScript.
Notice when I am inside the HTML markup:
or inside an HTML element:
The code complete shows HTML completion options. However, when I am inside the style attribute, I get CSS code completion:
I also get CSS code completion if I am inside a <style> element. So even though I am in an HTML file, I see CSS code completion because of my location.
Same case with JavaScript. When I invoke code completion inside a <script> element, I get JavaScript completion, even though I am in an HTML file.
Anytime IntelliJ IDEA can determine that another embedded language is present, it provides, via IntelliLang, the appropriate syntax highlighting, error highlighting, and code completion. The same holds true for Java. Notice here that IDEA knows the method I am competing takes an SQL statement and therefore highlights the String value using SQL highlighting, and provides SQL code completion:
So even though I am in a .java file, I get SQL code completion. The reason is that IntelliLang comes pre-configured knowing the embedded language of some methods. You modify them, or add more, in File > Settings > [Project Settings] > Language Injections.
In addition, you can use an annotation to tell IntelliJ IDEA (as well as developers looking at the code) that a String must be valid in a particular language. For example, I can annotate a String field, variable, or parameter, to indicate it must be valid HTML:
Notice I get HTML syntax highlighting, HTML code completions, and the CSS color shows in the left gutter. If I annotate a method parameter, then any time I call the method, I get the appropriate syntax highlighting, code completion, and error/warning highlighting:
The #Language annotation is inside the annotations.jar that is contained in the redist directory inside the IntelliJ IDEA installation directory. It is also available in maven central, or IDEA will offer to attach it as a Library if you use the annotation without it being attached.
IntelliLang and the #Language annotation supports a large number of languages. Just use code Completion inside the quotes after typing #Language("") to see a list. (Inline search works in the list as well.) One of the most useful is Regexp. For example, if you have a method that expects the string passed in to be a valid Regular Expression, annotating it as such will give anyone that calls it Regex code completion and error highlighting if they are passing in an invalid Regex pattern. Even for developers using other IDEs it is useful as a form of documentation.
As for a shortcut to change the the language on the fly for code completion, the only thing I can think that you might be referring to is the "Inject Language" intention. If I am entering a String value, and I bring up the quick-fix/intention menu via Alt+Enter, I am given an option to inject a language:
If I select that, IntelliJ IDEA will ask me what language I want to use:
After making my selection, IntelliJ IDEA will give me temporary language injection (including code completion) for the selected language.
It also gives me an option to add the #Language annotation for permanent injection.
To the best of my knowledge (as a 10 year IntelliJ IDEA user) that is the only way to switch code completion language types. So hopefully that is what you are looking for. To me, IntelliLang is one of the coolest features in IntelliJ. (It actually started as a third party plug-in and JetBrains then absorbed it into the product.)

Automatic text translation at MSDN pages - How to turn off?

Is there a way to turn off the automatic text translation at the MSDN library pages ?
I do prefer English text but due to having a German IP address Microsoft activates the automatic translation on every new page load which gives me a yellow box with a German translation of the text I am currently hovering over with the mouse.
This happens regardless what language is initially set in the right upper corner and regardless of whether I am logged in or not.
I can't tell how annoying this is !!
Any ideas, anyone ?
When you hit the "Original" radio button at the top, you see English, with German in the yellow hover box.
If you visit the original English site, you don't see a translation, not even on hover.
You switch to English by replacing /de-de/ in the URL with /en-us/. As in
German (translation or original with translation on hover):
http://msdn.microsoft.com/de-de/library/system.diagnostics.contracts.contractargumentvalidatorattribute(v=vs.110).aspx
English only (no translation):
http://msdn.microsoft.com/en-us/library/system.diagnostics.contracts.contractargumentvalidatorattribute(v=vs.110).aspx
If you are a firefox user, you can use Redirector addon. Create a new redirect and set it up like this:
It will automatically redirect all msdn requests to english non-translated versions.
Found it! I mean, it's 2016, 3 years late, and maybe they just added it recently, but when you scroll all the way down there's a small button in the left bottom corner where you can choose language you want to use (more specifically a country "you're from").
MSDN uses the prefered language from your web browser settings.
http://social.msdn.microsoft.com/Forums/en-US/6543407d-f743-48fb-965b-b8af9f9a0cb1/howto-disable-automatic-translation-into-german?forum=msdnfeedback
This is due to the Accept-Language header:
http://www.w3.org/International/questions/qa-accept-lang-locales
So setting your browser to prefer English language websites should fix this problem. W3C has an overview how to do that on different browsers here:
http://www.w3.org/International/questions/qa-lang-priorities.en.php
There is a chrome addon aswell
Switcheroo-Redirector
I got tired of replacing manually the url of the MSDN docs to target en-us in the url, so I came up with this little user script for the very handy Tampermonkey extension (available on Chrome, Microsoft Edge, Opera, and Firefox)
// ==UserScript==
// #name MSDN docs [en-us] redirect
// #version 0.1
// #description Redirects to the en-us version of the current MSDN doc page
// #grant none
// #match https://learn.microsoft.com/*
// ==/UserScript==
(function () {
let pathname = window.location.pathname.split('/');
if (pathname[1].toLowerCase() !== 'en-us') {
pathname[1] = 'en-us';
pathname = pathname.join('/');
window.location.href = window.location.origin + pathname + window.location.search;
}
})();
Once you have the extension installed,
Click on its icon
Click on Create a new script...
Paste the previous code
Save it (Ctrl + S or File > Save).
Test the redirection: https://learn.microsoft.com/fr-fr/dotnet/csharp/programming-guide/classes-and-structs/classes
The #match property will ensure that this script is only run against MSDN doc pages.
Recently I came across the same problem. And I solved it with Chrome extension ModHeader.
I configured and it works:
I know it's an old question, by maybe this insight will be useful to someone.
I almost always open msdn through a search in google. It most of the time offered me site translated to my local language (through a part of the address with locale), sometimes accompanied by original (English) version next to it. If I click on the original language link, it does not translate anything, so it is not automatic translation based on my localization.
What solved my problem was to change google search settings to prefer English, rather than my native language. Go to google search settings, set Which language should Google products use? to English, then in Currently showing search results in: click Edit and check other languages you are likely to search in.
It will also change the UI language for google. I know it might be a high price to pay, but I believe it is worth it. If you search for a query typed in given language, results will most likely result in this language pages anyway.
Instead of extensions, which will consume memory and are a bit overkill for that kind of thing, you can use a custom search query.
Chrome
Settings => Manage Search Engines, add this entry:
Engine: MSDN US
Keyword: ms
URL: https://social.msdn.microsoft.com/Search/en-US?query=%s (or whatever the proper url is at the time of your reading, just use %s wherever it needs the actual query string)
Now, in the address bar, just type ms [SPACE]. As soon as you press the space, it will prompt you with Search on MSDN US:. Just type your query now. For instance ms string will redirect you to the MSDN-US version of the search results for string. Of course you can change the title and keyword.
I'm sure the other common browsers expose that kind of functionality too. On Firefox, I used to plug custom search engines on the search bar.
This is a neat trick that I use for all kinds of searches (SO, Amazon, Wikipedia in different languages, etc.). It's very efficient.
Usually there is a language link at the bottom of the page where you can change language (even though a permanent site specific setting would be much nicer).
In IE in Internet Options Panel you have Apperrance part in General Tab. Add preffered language as a first and from now on all pages from MSDN will be presented in choosen language
I'm using NoScript addon with Firefox (actually Waterfox), just forbib "m-msft.com", the translator will be turned off. I think you can use other plugins in other browser to forbid the domain too. NoScript is a must have addon for any serious web user, and UserStyles, of course.

How to set MSDN to be always in English

I know that this isn't exactly programming question, but it is tightly related -
How the hell do I set MSDN to display everything in English? I'm Czech, and every KB or documentation article it automatically translates it to Czech with their translator, which result just in gibberish, and switching it to English requires couple of searching and clicks.
I wrote a simple dedicated browser extension for this. Unlike the Redirector plugin, no configuration is required.
It's called "FFS MSDN in English" and is available for:
Chrome
Firefox
Opera
It simply redirects any localised MSDN (or docs.microsoft) page to the english (en-us) version.
The rather trivial sources can be found at https://github.com/AirLancer/ffs_msdn_in_english
Very legitimate question, I think.
You need to modify the url like explained here. In your case change cz-cz to en-us.
Or better, let it do a browser plugin like Redirector for firefox:
You can select your default language from bottom left of the page.
Edit
New docs site has an easier option to view in English. However, the setting is not permanent.
I've fixed it by installing a redirector plugin for chrome:
http://bendavis78.github.io/chrome-extension-redirector/
If you are using Google search, you need to change language preferences for Google itself (you don't need to be logged in)1:
Go to https://google.com
Click Settings > Search settings on the bottom right corner.
Proceed to Languages tab.
Choose English as preferred.
1 You might also need to do what pr0gg3r and Beachwalker advise.
One solution is to rewrite google's search engine links using this Tampermonkey userscript:
// ==UserScript==
// #name Fix learn.microsoft.com links on google.com
// #description Changes all links to en-us versions.
// #include /^http[s]?:\/\/(www\.)?google\.[a-z]{2,3}\/.*$/
// #noframes
// #grant none
// ==/UserScript==
(function() {
'use strict';
let re = /^(https?:\/\/(docs|msdn).microsoft.com)\/(\w+\-\w+)\/(.*)/i;
const links = document.querySelectorAll("a");
for (const link of links) {
let m = re.exec(link.href);
if (!m) continue;
const clone = link.cloneNode(true);
clone.removeAttribute('onmousedown');
clone.href = `${m[1]}/en-us/${m[4]}`;
link.replaceWith(clone);
}
})();
Edit 2021-01-28: Remove onmousedown attribute event from link. Stops link capture and substitution of google's own redirect link.
I do not want to use extensions because I consider their required permissions to be a major security risk. Furthermore MSDN is not the only site where translations sucks. So for me the best solution was to change the language settings in Windows 10. Add English to your "Preferred languages" and set it to be 1st. Apps and websites will appear in the first language in the list that they support.
I like to have the choice between the translated and en-us version.
I authored the following UserScript... to be used in TamperMonkey for instance.
It does what it pretends in the #description.
// ==UserScript==
// #name Link to MSDN in en-us
// #description Adds a link in the top left corner of the translated MSDN pages allowing to jump to en-us version.
// #match http*://learn.microsoft.com/*
// #match http*://msdn.microsoft.com/*
// ==/UserScript==
(function() {
'use strict';
let url = location.href;
let rx = /^http([s]?):\/\/(docs|msdn)\.microsoft\.com\/(\w+\-\w+)\/(.*)$/i;
let match;
if ( match = rx.exec(url) ) {
if (match[3] !== 'en-us') {
var targetUrl = url.replace(rx, "http$1://$2.microsoft.com/en-us/$4");
jQuery("body").prepend(
jQuery('<a>en-us</a>').attr('href', targetUrl)
);
}
}
})();
In Firefox > Settings > "Language and Appearance" section there is below some Language settings a button next to a label that says:
"Choose your preferred language for displaying pages"
There you can setup a ordered list of languages. I have added english and moved it to the top of the list.
Now after a restart the same, previously opened msdn links do not auto translate.
I don't know the browser you're using but most browsers send info about the client to the server (incl. preferred language). So one option might be to set the default language to english (as done here for Firefox).