LibGDX: FreeTypeFont - how to display multilingual (сyrillic) ttf - libgdx

LibGDX FreeTypeFont does not generate Cyrillic characters (this ttf file supports cyrillic)
lateinit var font: BitmapFont
val generator = FreeTypeFontGenerator(Gdx.files.internal("Font.ttf"))
val parameters = FreeTypeFontGenerator.FreeTypeFontParameter().apply { size = 100 }
init {
font = generator.generateFont(parameters)
private val helloLabel = Label("Привет", Label.LabelStyle(font, null))
}

SOLUTION 1:
FreeTypeFontParameter().applay {
characters = "Привет"
}
default characters contains value:
DEFAULT_CHARS - строка содержащая символы ASKII (this suggests that the Cyrillic alphabet is not included there)
SOLUTION 2:
FreeTypeFontParameter().applay {
incremental = true
}
I don't know how it works but it works

Related

Display hyphen after 5 characters in text box for zip code - not working as expected

I have a requirement to display a hyphen after 5 characters in a text box for zip code. On entering more than 5 characters, a hyphen is displayed, as expected. However, when a user enters a hyphen symbol manually, the code should automatically remove the hyphen added manually. That is not working as expected. The hyphens added manually are not getting removed. When I debugged the typescript code in browser developer tools, I could see that the extra hyphen was removed from the property 'zipCode', but that change is not getting reflected in the UI.
Here is the code for the typescript file:
export class AppComponent {
zipCode: string = '';
public setValue(val: any) {
if(val.indexOf('-') >= 0)
val = val.replaceAll('-', '');
if(val.length > 5)
val = val.substr(0,5) + '-' + val.substr(5, val.length - 5);
this.zipCode = val;
}
}
Here is the code for html file:
<input type="text" name="zipField" [(value)] = "zipCode" (input)="setValue($event.target.value)">
Can someone please let me know why this code is not working. Also, please suggest any alternate way of achieving the removal of extra hyphen added manually. Thanks in advance.
Instead of passing the value of the input alone you should pass the element itself.
That way you will be able to change the text in the input tag too
<input type="text" name="zipField" [(value)] = "zipCode" (input)="setValue($event.target)">
Then in your typescript file
export class AppComponent {
...
public setValue(element: any) {
let val = element.value;
if(val.contains('-'))
val = val.replaceAll('-', '');
if(val.length > 5)
val = val.substr(0,5) + '-' + val.substr(5, val.length - 5);
this.zipCode = val;
element.value = val;
}
}

How to utilize PropertyName in Geotools for a user-defined function?

I am attempting to use the geotools.org library (Version 24) to write a user-defined function to style my GIS map according to an external data source. The documentation for the GeoTools library includes this tantalizing paragraph in the section on Functions:
When a function is used as part of a Style users often want to calculate a value based on the attributes of the Feature being drawn. The Expression PropertyName is used in this fashion to extract values out of a Feature and pass them into the function for evaluation.
This is exactly what I want to do. However, the documentation includes no actual example of how to do this.
I have spent several days trying various permutations of the Function definition, and I get the same result every time: My user-defined function only receives the geometry attribute, not the extra attributes I have specified.
I have verified that everything else works:
The features are read correctly from the shapefile
The function is actually called
The Feature geometry is passed into the function
Upon completion, the map is drawn
But I cannot get the Geotools library to pass in the additional Feature properties from the shapefile. Has anyone gotten this working, or can you even point me to an example of where this is used?
My current function definition:
package org.geotools.tutorial.function;
import mycode.data.dao.MyTableDao;
import mycode.data.model.MyTable;
import org.geotools.filter.FunctionExpressionImpl;
import org.geotools.filter.capability.FunctionNameImpl;
import org.opengis.feature.Feature;
import org.opengis.filter.capability.FunctionName;
import org.opengis.filter.expression.PropertyName;
import org.opengis.filter.expression.VolatileFunction;
import org.springframework.beans.factory.annotation.Autowired;
import java.awt.*;
import java.beans.Expression;
import java.util.Random;
public class DataFunction extends FunctionExpressionImpl {
#Autowired
MyTableDao myTableDao;
public static FunctionName NAME =
new FunctionNameImpl(
"DataFunction",
Color.class,
FunctionNameImpl.parameter("featureData1", PropertyName.class),
FunctionNameImpl.parameter("featureData2", PropertyName.class));
public DataFunction() {
super("DataFunction");
}
public int getArgCount() {
return 2;
}
#Override
public Object evaluate(Object feature) {
Feature f = (Feature) feature;
// fallback definition
float pct = 0.5F;
if (f.getProperty("featureData1") != null) {
MyTable temp = myTableDao.read(
f.getProperty("featureData1").getValue().toString(),
f.getProperty("featureData2").getValue().toString());
pct = temp.getColumnValue();
}
Color color = new Color(pct, pct, pct);
return color;
}
}
EDIT: I am invoking the function programmatically through a Style that is created in code. This Style is then added to the Layer which is added to the Map during the drawing process.
private Style createMagicStyle(File file, FeatureSource featureSource) {
FeatureType schema = (FeatureType) featureSource.getSchema();
// create a partially opaque outline stroke
Stroke stroke =
styleFactory.createStroke(
filterFactory.literal(Color.BLUE),
filterFactory.literal(1),
filterFactory.literal(0.5));
// create a partial opaque fill
Fill fill =
styleFactory.createFill(
filterFactory.function("DataFunction",
new AttributeExpressionImpl("featureData1"),
new AttributeExpressionImpl("featureData2")));
/*
* Setting the geometryPropertyName arg to null signals that we want to
* draw the default geomettry of features
*/
PolygonSymbolizer sym = styleFactory.createPolygonSymbolizer(stroke, fill, null);
Rule rule = styleFactory.createRule();
rule.symbolizers().add(sym);
FeatureTypeStyle fts = styleFactory.createFeatureTypeStyle(new Rule[] {rule});
Style style = styleFactory.createStyle();
style.featureTypeStyles().add(fts);
return style;
}
I think you want to set up your function to take a pair of Strings or Doubles (or whatever those attributes are) so something like:
public static FunctionName NAME =
new FunctionNameImpl(
"DataFunction",
Color.class,
FunctionNameImpl.parameter("featureData1", Double.class),
FunctionNameImpl.parameter("featureData2", Double.class));
public DataFunction(List<Expression> params, Literal fallback) {
this.params = params;
this.fallback = fallback;
}
then your evaluate method becomes:
#Override
public Object evaluate(Object feature) {
Feature f = (Feature) feature;
// fallback definition
float pct = 0.5F;
Expression exp1 = params.get(0);
Expression exp2 = params.get(1);
if (f.getProperty("featureData1") != null) {
MyTable temp = myTableDao.read(
exp1.evaluate(f, Double.class),
exp2.evaluate(f, Double.class));
pct = temp.getColumnValue();
}
Color color = new Color(pct, pct, pct);
return color;
}
and you would use it in the style using something like:
Fill fill =
styleFactory.createFill(
filterFactory.function("DataFunction",
filterFactory.propertyName("featureData1"),
filterFactory.propertyName("featureData2")));

MFC: Using CHtmlView with memory string via about: or data:?

I am trying out CHtmlView to display html from memory variables. After having dealt with the various exceptions you get in debug mode, have it working for very small strings via the about: uri.
Example:
Navigate(_T("about:<html><head></head><body>Hello</body></html>"))
works for small items but not larger strings. Does anyone know the documented limitation for about: ?
Now I found a new item that supposed to be available for IE, the data: entry, but when I try
Navigate(_T("data:text/html, <html><head></head><body>Hello</body></html>"))
It doesn't work, comes up with the fancy webpage can't be displayed page. Does anyone know why CHtmlView doesn't support data: and if there is any other trick that can be used to use memory variable data for html display in CHtmlView?
One option for setting HTML content directly, is to read from memory using IStream
MFC's CHtmlEditCtrl uses a similar method to set document html content, except MFC uses CStreamOnCString.
You may need to set the content to UTF8 for compatibility. To use UTF8,
change CString to CStringA in the code below, and pass UTF8 string to the function SetHTMLContent(htmlview, u8"<html>...")
HRESULT SetHTMLContent(CHtmlView* htmlview, CString html)
{
if(!html.GetLength()) return E_FAIL;
CComPtr<IDispatch> disp = htmlview->GetHtmlDocument();
if(!disp)
{
//not initialized, try again
htmlview->Navigate(_T("about:"));
disp = htmlview->GetHtmlDocument();
if(!disp)
return E_NOINTERFACE;
}
CComQIPtr<IHTMLDocument2> doc2 = disp;
if(!doc2) return E_NOINTERFACE;
int charsize = sizeof(html.GetAt(0));
IStream *istream = SHCreateMemStream(
reinterpret_cast<const BYTE*>(html.GetBuffer()), charsize * html.GetLength());
HRESULT hr = E_FAIL;
if(istream)
{
CComQIPtr<IPersistStreamInit> psi = doc2;
if(psi)
hr = psi->Load(istream);
istream->Release();
}
html.ReleaseBuffer();
return hr;
}
Usage:
CString str = _T("<html><head></head><body>Hello</body></html>");
SetHTMLContent(m_chtmlview, str);

Partial replace in docs what matches only and preserve formatting

Let's assume that we have first paragraph in our google document:
Wo1rd word so2me word he3re last.
We need to search and replace some parts of text but it must be highlighted in editions history just like we changed only that parts and we must not loose our format (bold, italic, color etc).
What i have/understood for that moment: capturing groups didn't work in replaceText() as described in documentation. We can use pure js replace(), but it can be used only for strings. Our google document is array of objects, not strings. So i did a lot of tries and stopped at that code, attached in this message later.
Can't beat: how i can replace only part of what i've found. Capturing groups is very powerful and suitable instrument, but i can't use it for replacement. They didn't work or i can replace whole paragraph, that is unacceptable because of editions history will show full paragraph replace and paragraphs will lose formatting. What if what we searching will be in each and every paragraph, but only one letter must be changed? We will see full document replacement in history and it will be hard to find what really changed.
My first idea was to compare strings, that replace() gives to me with contents of paragraph then compare symbol after symbol and replace what is different, but i understand, that it will work only if we are sure that only one letter changed. But what if replace will delete/add some words, how it can be synced? It will be a lot bigger problem.
All topics that i've found and read triple times didn't helped and didn't moved me from the dead point.
So, is there any ideas how to beat that problem?
function RegExp_test() {
var docParagraphs = DocumentApp.getActiveDocument().getBody().getParagraphs();
var i = 0, text0, text1, test1, re, rt, count;
// equivalent of .asText() ???
text0 = docParagraphs[i].editAsText(); // obj
// equivalent of .editAsText().getText(), .asText().getText()
text1 = docParagraphs[i].getText(); // str
if (text1 !== '') {
re = new RegExp(/(?:([Ww]o)\d(rd))|(?:([Ss]o)\d(me))|(?:([Hh]e)\d(re))/g); // v1
// re = new RegExp(/(?:([Ww]o)\d(rd))/); // v2
count = (text1.match(re) || []).length; // re v1: 7, re v2: 3
if (count) {
test1 = text1.match(re); // v1: ["Wo1rd", "Wo", "rd", , , , , ]
// for (var j = 0; j < count; j++) {
// test1 = text1.match(re)[j];
// }
text0.replaceText("(?:([Ww]o)\\d(rd))", '\1-A-\2'); // GAS func
// #1: \1, \2 etc - didn't work: " -A- word so2me word he3re last."
test1 = text0.getText();
// js func, text2 OK: "Wo1rd word so-B-me word he3re last.", just in memory now
text1 = text1.replace(/(?:([Ss]o)\d(me))/, '$1-B-$2'); // working with str, not obj
// rt OK: "Wo1rd word so-B-me word he-C-re last."
rt = text1.replace(/(?:([Hh]e)\d(re))/, '$1-C-$2');
// #2: we used capturing groups ok, but replaced whole line and lost all formatting
text0.replaceText(".*", rt);
test1 = text0.getText();
}
}
Logger.log('Test finished')
}
Found a solution. It's a primitive enough but it can be a base for a more complex procedure that can fix all occurrences of capture groups, detect them, mix them etc. If someone wants to improve that - you are welcome!
function replaceTextCG(text0, re, to) {
var res, pos_f, pos_l;
var matches = text0.getText().match(re);
var count = (matches || []).length;
to = to.replace(/(\$\d+)/g, ',$1,').replace(/^,/, '').replace(/,$/, '').split(",");
for (var i = 0; i < count; i++) {
res = re.exec(text0.getText())
for (var j = 1; j < res.length - 1; j++) {
pos_f = res.index + res[j].length;
pos_l = re.lastIndex - res[j + 1].length - 1;
text0.deleteText(pos_f, pos_l);
text0.insertText(pos_f, to[1]);
}
}
return count;
}
function RegExp_test() {
var docParagraphs = DocumentApp.getActiveDocument().getBody().getParagraphs();
var i = 0, text0, count;
// equivalent of .asText() ???
text0 = docParagraphs[i].editAsText(); // obj
if (text0.getText() !== '') {
count = replaceTextCG(text0, /(?:([Ww]o)\d(rd))/g, '$1A$2');
count = replaceTextCG(text0, /(?:([Ss]o)\d(me))/g, '$1B$2');
count = replaceTextCG(text0, /(?:([Hh]e)\d(re))/g, '$1C$2');
}
Logger.log('Test finished')
}

Taking a screenshot of a page in InDesign Extension Builder

For my current assignment I need to make an extension for Adobe InDesign using Adobe Creative Suit Extension Builder and Flash Builder. I guess this is more of a question for ones that know Extension Builder and InDesign API.
The point of this extension is to load some data and send some data to a server. I need to make a screenshot of a page, then send it in jpg to a server. But, there are no (or at least i couldnt find any) ways to create a bitmap(to cast it on a object seems impossible, because this Objects are just Objects, and not DisplayObjects).
I managed to silently export pages as jpegs, now I'm thinking about loading them and sending but that will require building an AIR app to handle it all, so this will be a bit bulky.
So to sum up the question, how to take a screencapture of all elements on a page in InDesign using CS Ext.Builder?
what is the problem with export to JPG ? You can choose to export the page or the objects themselves.
Here is a snippet I wrote in a recent project. Hope it helps.
public static function getFilePath():String {
var app:com.adobe.indesign.Application = InDesign.app;
var sel:* = app.selection, oldResolution:Number, oldColorSpace:JpegColorSpaceEnum, groupItems:Array = [], i:int = 0, n:int = sel.length;
if (!sel || !n )
{
Alert.show("Pas de selection !", "title", Alert.OK, Sprite(mx.core.Application.application));
return "";
}
for ( i = 0 ; i < n ; i ++ )
{
groupItems [ groupItems.length ] = sel[i];
}
sel = ( sel.length > 1 )? app.activeDocument.groups.add ( sel ) : sel[0] ;
var tempFolder:File = File.createTempDirectory();
AppModel.getInstance().jpgFolder = tempFolder;
var jpgFile:File = new File ();
jpgFile.nativePath = tempFolder.nativePath + "/temp.jpg";
oldResolution = app.jpegExportPreferences.exportResolution;
app.jpegExportPreferences.exportResolution = 72;
oldColorSpace = app.jpegExportPreferences.jpegColorSpace;
app.jpegExportPreferences.jpegColorSpace = JpegColorSpaceEnum.GRAY;
sel.exportFile ( ExportFormat.jpg, jpgFile );
app.jpegExportPreferences.jpegColorSpace = oldColorSpace;
app.jpegExportPreferences.exportResolution = oldResolution;
if ( sel is Group )
{
sel.ungroup();
app.select ( groupItems );
}
return jpgFile.nativePath;
}