Qml strange behavior with cyrillic symbols - windows

I am experiencing very strange behavior with cyrillic letters. I'm using Qt 5.12.6, Windows 10 (64 bit).
The whole application wrote with QML, as you can see some words don't make any sense they are not Russian. All QML Text elements behave the wrong way.
The top login buttons underlied red look like this
import QtQuick 2.7
import QtQuick.Controls 2.0
Button {
id: loginPageButton
font.capitalization: Font.AllUppercase
checkable: true
flat: true
contentItem: Text {
text: loginPageButton.text
font: loginPageButton.font
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
elide: Text.ElideRight
}
}
using
LoginPageButton {
id: newAccountButton
text: qsTr("CREATE AN ACCOUNT")
font.pixelSize: 16
ButtonGroup.group: btnGroup
checked: false
Layout.alignment: Qt.AlignCenter | Qt.AlignVCenter
}
retranslate is made in such way
QGuiApplication::removeTranslator(&m_currentTranslator);
bool isLoaded = m_currentTranslator.load(QString("tr_%1").arg(locale), QCoreApplication::applicationDirPath() + "/translations/");
if (isLoaded)
QGuiApplication::installTranslator(&m_currentTranslator);
m_engine.retranslate(); // QQmlApplicationEngine
and i have to say that the bug is reproduced only on some machines not all...

A "Ḱ" indicates Macedonian language. So your string encoding is wrong, if you want Russian.
Quoting from the Qt docs:
"The application may occasionally require encodings other than the default local 8-bit encoding. For example, an application in a Cyrillic KOI8-R locale (the de-facto standard locale in Russia) might need to output Cyrillic in the ISO 8859-5 encoding. Code for this would be:
QString string = ...; // some Unicode text
QTextCodec *codec = QTextCodec::codecForName("ISO 8859-5");
QByteArray encodedString = codec->fromUnicode(string);
For converting Unicode to local 8-bit encodings, a shortcut is available: the QString::toLocal8Bit() function returns such 8-bit data. Another useful shortcut is QString::toUtf8(), which returns text in the 8-bit UTF-8 encoding: this perfectly preserves Unicode information while looking like plain ASCII if the text is wholly ASCII.
For converting the other way, there are the QString::fromUtf8() and QString::fromLocal8Bit() convenience functions, or the general code, demonstrated by this conversion from ISO 8859-5 Cyrillic to Unicode conversion:
QByteArray encodedString = ...; // some ISO 8859-5 encoded text
QTextCodec *codec = QTextCodec::codecForName("ISO 8859-5");
QString string = codec->toUnicode(encodedString);
" (1)

Related

How to type subscripts/superscripts in Xcode string literals?

I have seen this code in Xcode editor :
How can I type these strings with different character position and font size ?
With these string literals, it's not a question of character position or font size. These are special unicode superscript/subscript characters. If you go to the macOS keyboard preferences and choose "Show keyboard and emoji viewers in menu bar", you'll have a new option in your menu bar "Show emoji & symbols". You can then, for example, type "2" in the searchbox and you'll then see subscript and superscript rendition in the "related characters" section:
So, this is not a general subscript/subscripting feature, but dedicated unicode characters for just a few common subscripts/superscripts (e.g. "2", "x", etc.).
Note, if you need more fine grained control over fonts, baseline adjustments, etc., many user interface controls support the use of attributed strings, e.g.:
let bigFont = UIFont.systemFont(ofSize: 20)
let smallFont = UIFont.systemFont(ofSize: 12)
let title = NSMutableAttributedString(string: "foo", attributes: [.font: bigFont])
title.append(NSMutableAttributedString(string: "bar", attributes: [.font: smallFont, .baselineOffset: 10]))
button.setAttributedTitle(title, for: .normal)
Yielding:
Or, as described in this answer, you can apparently also do:
let string = "foobar"
let range = NSRange(location: 3, length: 3)
let title = NSMutableAttributedString(string: string)
let superscript = NSAttributedStringKey(rawValue: kCTSuperscriptAttributeName as String)
title.addAttributes([superscript: 1], range: range) // Use 1 for superscript; use -1 for subscript
But your code snippet is clearly just using the predefined unicode superscript/subscript characters. These various programmatic approaches can be useful, though, if you need to render something that doesn't already exist in unicode.

Cocoa Converting RTFD to ASCII and back

Is it possible to convert an NSattributedString with attachments (RTFD not RTF) to ASCII, edit the stream, and convert it back? So far I am able to convert an RTFD to a String stream. But turning it back into an NSData object does not work. Here's the code I'm using in a playground.
import Cocoa
func stream(attr: NSAttributedString) -> String? {
if let d = attr.rtfd(from: NSMakeRange(0, attr.length), documentAttributes: [NSDocumentTypeDocumentAttribute: NSRTFDTextDocumentType]) {
if let str = String(data: d, encoding: .ascii) { return str }
else {
print("Unable to produce RTFD string")
return nil
}
}
print("Unable to produce RTFD data stream")
return nil
}
if let im = NSImage(named: "image.png") {
let a = NSTextAttachment()
a.image = im
let s = NSAttributedString(attachment: a)
if let str = stream(attr: s) {
print("\(str)\n") //prints a string, which contains RTF code combined with NSTextAttachment string representation
if let data = str.data(using: .ascii) { //this is where things stop working
if let newRTF = NSAttributedString(rtfd: data as Data, documentAttributes: nil) {
print(newRTF)
}
else { print("rtfd was not created") }
}
else { print("could not make data") }
}
}
What am I missing? Or is my entire concept wrong here? I am doing this to get around a limitation of the way OS X handles images attached in RTF documents.
Edit:
The limitation I am trying to address is to set the size of an image in an RTF stream. The text handling system requires that we use NSTextAttachment. Whenever an image is pasted from that, it automatically sizes the image to whatever the pixel height and width are. Unfortunately there is no way to control this property. I have tried here and also using all the techniques here.
As far as the ASCII stream, I'm not trying to edit the image attachment itself. When the stream is printed, the actual RTF code is visible and editable. This works and would be a good workaround for this limitation. All I need is to edit the RTF code and change the \width and \height properties that Apple uses.
After your edit I can see what you are trying to do, interesting idea, but it won't work - at least not easily.
Take a look at the value of d, it is not an ASCII string stored as a value of type Data (or NSData). It is a serialised representation of multiple items; the RTF stream (text), the image data (binary). If you convert this to an ASCII string and back again it is not going to work, you can't represent arbitrary binary data as ASCII unless you encode it (e.g. something like base 64 encoding).
Now you could attempt what you are trying a slightly different way, skip the conversion to ASCII and edit the Data value directly. That is certainly possible, but as you are editing a format you don't know (the serialised representation) you would have to be careful... And even if you succeed in editing the representation there is no guarantee that converting back to an NSAttributedString with an NSTextAttachment will preserve your edits.
I suggest you tackle this another way. You have an NSAttributedString and you don't like the RTF produced after you write this to a file. So edit the RTF after it is written, e.g. open up the RTFD package, open the contained RTF file (TXT.rtf), edit it, write it back.
HTH

Pango select multiples fonts

I have three fonts i want to use in my software with pango:
Font1: latin, Cryllic characters
Font2: Korean characters
Font3: Japanese characters
Pango render the text correctly but i want select a font
There any way to indicate this preference pango font?
I use: linux and pango 1.29
The simplest way is to use PangoMarkup to set the fonts you want:
// See documentation for Pango markup for details
char *pszMarkup = "<span face=\"{font family name goes here}\">"
"{text requiring font goes here}"
"</span>"; // Split for clarity
char *pszText; // Pointer for text without markup tags
PangoAttrList *pAttr; // Attribute list - will be populated with tag info
pango_parse_markup (pszMarkup, -1, 0, &attr_list, &pszText, NULL, NULL);
You now have a buffer of regular text and an attribute list. If you want to set these up by hand (without going through the parser), you will need one PangoAttribute per instance of the font and set PangoAttribute.start_index and PangoAttribute.end_index by hand.
However you get them, you now give them to a PangoLayout:
// pWidget is the windowed widget in which the text is displayed:
PangoContext *pCtxt = gtk_widget_get_pango_context (pWidget);
PangoLayout *pLayout = pango_layout_new (pCtxt);
pango_layout_set_attributes(pLayout, pAttr);
pango_layout_set_text (pLayout, pszText, -1);
That's it. Use pango_cairo_show_layout (cr, pLayout) to display the results. The setup only needs changing when the content changes - it maintains the values across draw signals.

Arabic font in Web UI and itextsharp

I'm not able to find a reason why my MVC 3 web site shows arabic font correctly and my pdf not.
I use a bliss font in my web site;
#font-face {
font-family: 'blissregular';
src: url('/Fonts/blissregular-webfont.eot');
src: url('/Fonts/blissregular-webfont.eot?#iefix') format('embedded-opentype'),
url('/Fonts/blissregular-webfont.ttf') format('truetype');
font-weight: normal;
font-style: normal;}
All working fine.
After that I want to create the pdf of the output but arabic fonts does not appears.
I've googled and understand that the font must have the arabic character to show up correctly. I've changed to arial font (that contains arabic character) and... pdf worked.
So... How is possible that with bliss font (that does NOT have arabic characters) I see arabic font in web site?
I'm really confused....
thanks a lot to everybody!
For every character your browser encounters it looks for a matching glyph in the current font. If the font doesn't have that glyph it looks for any fallback fonts to see if they have that glyph. Ultimately every browser has a core set of default fonts that are the ultimate fallback. When you specify the font Bliss but use Arabic characters you are probably just seeing your browser's fallback fonts.
PDFs don't work that way. If you say something is using font XYZ then it will try to render it using that font or fail.
The easiest way probably is to just add a font to your CSS that supports those characters.
.myclass{font-family: blissregular, Arial}
If that doesn't work you might need to inject the fonts manually. (Actually, I'm not 100% certain the iText support #font-face, either.) iText has a helper class that can figure things out for you that Bruno talks about it here but unfortunately the C# link isn't working anymore. It's very simple, you just create an instance of the FontSelector class, call AddFont in the order that you want characters to be looked up up in and then pass a string to the Process() method which spits back a Phrase that you can add. Below is basic sample code that shows this off. I apologize for my sample text, I'm English-native so I just searched for something to use, I hope I didn't mangle it or get it backwards.
You'll need to jump through a couple of extra hoops when processing the HTML but you should be able to work it out, hopefully.
//Sample string. I apologize, this is from a Google search so I hope it isn't backward
var testString = "يوم الاثنين \"monday\" in Arabic";
var outputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf");
//Standard PDF setup
using (var fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
using (var doc = new Document()) {
using (var writer = PdfWriter.GetInstance(doc, fs)) {
doc.Open();
//This is a font that I know *does not* support Arabic characters, substitute with your own font if you don't have it
var gishaFontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "gisha.ttf");
var gishaBaseFont = BaseFont.CreateFont(gishaFontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
var gishaFont = new iTextSharp.text.Font(gishaBaseFont, 20);
//Add our test string using just a normal font, this *will not* display the Arabic characters
doc.Add(new Phrase(testString, gishaFont));
//This is a font that I know *does* support Arabic characters
var arialFontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF");
var arialBaseFont = BaseFont.CreateFont(arialFontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
var arialFont = new iTextSharp.text.Font(arialBaseFont, 20);
//Create our font selector specifying our most specific font first
var Sel = new FontSelector();
Sel.AddFont(gishaFont);
Sel.AddFont(arialFont);
//Have the font selector process our text into a series of chunks wrapped in a phrase
var newPhrase = Sel.Process(testString);
//Add the phrase, this will display both characters
doc.Add(newPhrase);
//Clean up
doc.Close();
}
}
}

Multilingual text with rmagick

I'm using rmagick to annotate images programatically with text. The text will need to support a range of languages including Chinese, Korean, English among others. The font requirements I'm dealing with are very specific, and the font chosen for English supports a wide variety of western languages, but it doesn't support Chinese or Korean. I'll have other fonts for those languages.
The approach I have in mind is to map character ranges to particular fonts and programmatically tell rmagick what font to use based on that. Am I missing anything obvious, or is this a good approach to take?
Here is how I ended up solving this:
def font_for(verb)
return "#{Rails.root}/app/uploaders/fonts/Gotham-Bold.ttf" if verb =~ /\p{Latin}/
return "#{Rails.root}/app/uploaders/fonts/ArialUnicode.ttf"
end
That method will take some text and return the path to an appropriate font face. Regex's character property matching comes in handy here! Then i can use the font_for method inside my rmagick script for annotating an image.
def create_image_with_text
canvas = Magick::ImageList.new
canvas.new_image(640, 480) {self.background_color = "white"}
text = Magick::Draw.new
text.font = font_for "english"
text.pointsize = 23
text.gravity = ::Magick::NorthGravity
text.annotate(canvas, 0,0,0,28, "ENGLISH") { self.fill = '#343434' }
text.font = font_for self.verb
text.pointsize = 65
text.gravity = ::Magick::CenterGravity
text.annotate(canvas, 0,0,0,18, self.verb.upcase) { self.fill = '#343434' }
tempfile = Tempfile.new(['new_center_stripe', '.jpg'])
canvas.write tempfile.path
self.image.store!(tempfile)
end
It is worth noting that this simplistic approach wouldn't handle input with mixed languages.

Resources