Sign in Join
Wiki copytemporary

Custom Drawn Interface/Android/ru: what changed

Revision 2 to 3. Removed lines have a minus sign; added lines have a plus sign.

OldNewLine
11Вернуться к [[Custom Drawn Interface]]
22
33## Архитектура
44
55LCL-CustomDrawn-Android использует маленькое Java приложение, которое сообщается с нашей Pascal библиотекой, отправляет ей все события и выполняет все команды от неё. Общение обеспечивается JNI, так как Google поддерживает это. Элементы управления не являются родными, вместо этого они нарисованы в TRawImage+TLazIntfImage+TLazCanvas и события, и рисование сокращается с помощью LazRegions. Рисование делается в Pascal, используя jnigraphics для рисования на Bitmap Java объекте, что в последствии сокращает активность Java на внешнем виде.
66
77Наши предыдущие и недолгая попытка написать LCL интерфейс для Android (LCL-Android), который использовал не стандартный метод использования родной исполняемой системы, чтобы сообщаться с Java при помощи "труб". Мы отказались от этой системы, потому что это было не продумано и не поддерживалось Google. Это считается устаревшим и люди должны вместо этого использовать LCL-CustomDrawn-Android. Этот старый интерфейс был описан в [[Android Interface]].
88
99## Roadmap
1010
11111. Build the set of [[Lazarus Custom Drawn Controls]]
12122. Initial bindings for the Android APIs
13133. Create an application to automatically generate the bindings
14144. Start the new widgetset
15155. Implement support for JNI
16166. Merge the Lazarus Custom Drawn Controls into the LCL and use them to implement all basic controls
17177. Add text support for Android
18188. Implement basic window client area scrolling
19199. Add mobile emulator for desktop platforms
202010. Improve the mobile scrolling
212111. Add text support in X11
222212. Add DPI awareness and adaptation in the LCL
232313. Add non-native text support via pasfreetype
2424
2525## Использование Android SDK, эмулятора и телефона
2626
2727[[Android Interface/Using the Android SDK, Emulator and Phones/ru]]
2828
2929## Программирование для Андроид
3030
3131Смотрите раздел [[Android Programming/ru]], который также включает в себя важные для программирования особенности телефонов.
3232
3333## Настройка Free Pascal Compiler для Android
3434
3535### Используйте готовый образ Virtual Box с FPC и Lazarus
3636
3737Самый быстрый способ настройки Free Pascal и Lazarus для разработки под Андроид - просто использовать заранее настроенный образ для виртуальной машины который уже содержит Mageia Linux 1, KDE, Lazarus 0.9.31, Subversion, Free Pascal для обоих Linux: x86-linux и arm-linux (targetting Android), Android SDK, Android NDK, Java, Ant, Gtk2, и все его разрабатываемые пакеты, GNU debugger (GDB) и все остальное необходимое для создания приложений для Андроид в Lazarus.
3838
3939Загрузить образ виртуальной машины: <https://sourceforge.net/projects/p-tools/files/Lazarus_for_Android_VM_Image/snapshot_30_dez_2011/>
4040
4141Образ виртуальной машины состоит из двух файлов: “Android Devel VM.vbox” и “Android Devel VM.hdd”. Оба файла должны находиться в одной папке и следует отметить то, что source forge архив и его надо разархивировать. После распаковки образ будет весить 5,2GB. Для использования этой виртуальной машины, нужно установить Virtual Box и при помощи этой программы открыть .vbox файл. После этого можно использовать эту Linux виртуальную машину для создания Android приложений. Процесс создания приложения включает в себя первое открытие Lazarus и создания приложения в Lazarus, примеры проектов доступны в ~/Programas/lazarus/example/androidlcl/ и после идите в терминал linux и перейдите в ~/Programas/lazarus/example/androidlcl/android и выполните команду “ant debug”, которая генерирует APK файл в ~/Programas/ lazarus/example/androidlcl/android/bin/LCLExample-debug.apk. Виртуальная машина имеет два пользователя: “root” и “pascaldev” и у обоих из них пароль: “root”.
4242
4343Обратим внимание, что виртуальная машина уже имеет встроенный код приложения Lazarus, но также можно это приложение обновить. Но это предполагает определенный риск т.к. версия из интернета может содержать проблемы.
4444
4545### Как самому сделать компилятор в Windows?
4646
4747**Шаг 1** -Установить Android SDK и NDK
4848
4949Загрузите с сайта Google и установите SDK и NDK для Windows.
5050
5151Проверьте путь к binutils в установленном NDK. Например для NDK r7 установленном в C:\Programas\android-ndk-r7\\ путь будет такой: C:\Programas\android-ndk-r7\toolchains\arm-linux-androideabi-4.4.3\prebuilt\windows\bin
5252
5353Также проверьте путь к библиотекам NDK. Например, для NDK r7 установленном в C:\Programas\android-ndk-r7\\ путь будут такой: C:\Programas\android-ndk-r7\platforms\android-8\arch-arm\usr
5454
5555**Шаг 2** - Скачайте FPC 2.5.1 от 19 января. Создайте каталог для хранения исходного кода FPC и з Create a folder to store the FPC trunk source code and создайте рабочую копию ревизии 16790
5656
5757**Шаг 3** - Установите FPC 2.4.4
5858
5959Самый простой способ получить хороший FPC 2.4.4 это установить Lazarus 0.9.30.2. Для примера, предположим что вы установили эту версию в C:\Programas\lazarusfpc244
6060
6161**Шаг 4** - Создание скрипта и его написание
6262
6363Создайте выходную папку, например: C:\Programas\fpcandroid\output
6464
6565Далее создайте файл, называющийся "build.bat"(без кавычек) в корневой папке FPC, например C:\Programas\fpcandroid и скопируйте в неё:
6666
6767 SET PATH=C:\Programas\lazarusfpc244\fpc\2.4.4\bin\i386-win32\
6868 make crossinstall CPU_TARGET=arm OS_TARGET=linux CROSSBINDIR=C:\Programas\android-ndk-r7\toolchains\arm-linux-androideabi-4.4.3\prebuilt\windows\bin OPT=-dFPC_ARMEL BINUTILSPREFIX=arm-linux-androideabi- INSTALL_PREFIX=C:\Programas\fpcandroid\output
6969 pause
7070
7171Далее, запустите этот файл, и вы должны иметь FPC установлен в C:\Programas\fpcandroid\output
7272
7373**Шаг 5** - Скопируйте некоторые cross-binutils в bin
7474
7575Вы должны иметь FPC bin'овские файлы in C:\Programas\fpcandroid\output\bin\i386-win32
7676
7777Теперь возьмите 3 файла:
7878
7979C:\Programas\android-ndk-r7\toolchains\arm-linux-androideabi-4.4.3\prebuilt\windows\bin\arm-linux-androideabi-as.exe C:\Programas\android-ndk-r7\toolchains\arm-linux-androideabi-4.4.3\prebuilt\windows\bin\arm-linux-androideabi-ld.exe C:\Programas\android-ndk-r7\toolchains\arm-linux-androideabi-4.4.3\prebuilt\windows\bin\arm-linux-androideabi-strip.exe
8080
8181Скопируйте и переименуйте файлы:
8282
8383C:\Programas\fpcandroid\output\bin\i386-win32\arm-linux-as.exe C:\Programas\fpcandroid\output\bin\i386-win32\arm-linux-ld.exe C:\Programas\fpcandroid\output\bin\i386-win32\arm-linux-strip.exe
8484
8585**Шаг 6** - Соедините в настройках Lazarus FPC
8686
8787Допустим, у вас есть следующий Lazarus C:\Programas\lazarus31 с установленным внутри FPC: C:\Programas\lazarus31\fpc\2.5.1\bin\i386-win32 и C:\Programas\lazarus31\fpc\2.5.1\units\\
8888
8989Сейчас скопируйте C:\Programas\fpcandroid\output\units\arm-linux в C:\Programas\lazarus31\fpc\2.5.1\units\\
9090
9191Скопируйте все .exe файлы из C:\Programas\fpcandroid\output\bin\i386-win32\\ в C:\Programas\lazarus31\fpc\2.5.1\bin\i386-win32
9292
9393Сейчас Вы можете собрать пример проекта androidlcltest.lpi используя режим Windows-Release build
9494
9595### Создание вашего компилятора в Linux
9696
9797Просмотрите [[Setup Cross Compile For ARM]] и убедитесь, что используете опцию OPT="-dFPC_ARMEL" для создания компилятора.
9898
9999### Использование пре-компилятора в Linux
100100
101101Пре-компилятор был сделан для удобства пользователей. Следующие шаги были испытаны в Mandriva Linux 2010.0 и 2010.1:
102102
103103**Необходимые окружающие среды**
104104
105105- Последняя и стабильная FPC, установленная с помощью RPM / DEB / TAR пакетов
106106
107107**Step 1** - Install the cross-binutils
108108
109109For Mandriva Linux the RPM package containing arm-linux-as, arm-linux-ld, etc, which are the cross-binutils can be found here: <http://rpm.pbone.net/index.php3/stat/4/idpl/14252825/dir/mandriva_2010/com/cross-arm-binutils-2.20.51.0.4-2mnb2.i586.rpm.html>
110110
111111Just download the RPM package and install it using:
112112
113-`rpm -ivh cross-arm-binutils-2.20.51.0.4-2mnb2.i586.rpm `
113+```text
114+rpm -ivh cross-arm-binutils-2.20.51.0.4-2mnb2.i586.rpm
115+```
114116
115117In Mandriva Linux 2010.0 the dependencies won't match, as the package is for 2010.1, but one can simply ignore this problem and it works fine using --nodeps:
116118
117-`rpm -ivh --nodeps cross-arm-binutils-2.20.51.0.4-2mnb2.i586.rpm `
119+```text
120+rpm -ivh --nodeps cross-arm-binutils-2.20.51.0.4-2mnb2.i586.rpm
121+```
118122
119123For other distributions use the corresponding package, or else read the instructions for building the cross-binutils yourself at [[Setup Cross Compile For ARM]]
120124
121125**Step 2** - Configure the cross-binutils
122126
123127The assembler needs a parameter to tell it which ARM ABI to use. A choice which works good is EABI-5, which is compatible with all Android devices available as of Jan 2011. To set this, we will rename the original assembler and substitute it with a shell script which passes the desired parameter. These commands will do it:
124128
125-`su`\
126-`mv /usr/bin/arm-linux-as /usr/bin/arm-linux-as_org`\
127-`gedit /usr/bin/arm-linux-as`
129+```text
130+su
131+mv /usr/bin/arm-linux-as /usr/bin/arm-linux-as_org
132+gedit /usr/bin/arm-linux-as
133+```
128134
129135Now paste into the editor this code:
130136
131-`#!/bin/sh`\
132-`/usr/bin/arm-linux-as_org -meabi=5 $@`
137+```text
138+#!/bin/sh
139+/usr/bin/arm-linux-as_org -meabi=5 $@
140+```
133141
134142And don't forget to then make it executable:
135143
136-`chmod 755 /usr/bin/arm-linux-as`
144+```text
145+chmod 755 /usr/bin/arm-linux-as
146+```
137147
138148**Step 3** - Install the Free Pascal Cross-Compiler
139149
140150At this point the pre-compiled FPC can be download from here: <http://sourceforge.net/projects/p-tools/files/Free%20Pascal%20for%20ARM/>
141151
142152Then use these commands to install the pre-compiled Free Pascal cross-compiler into /usr:
143153
144-`[felipe@localhost Programas]$ ls -l`\
145-`total 20664`\
146-`-rw-rw-r--  1 felipe felipe 17098552 2010-10-25 08:17 fpc-2.5.1.arm-linux.tar.gz`\
147-`[felipe@localhost Programas]$ su`\
148-`Password: `\
149-`[root@localhost Programas]# cp fpc-2.5.1.arm-linux.tar.gz /usr/`\
150-`[root@localhost Programas]# cd /usr/`\
151-`[root@localhost usr]# tar -xvf fpc-2.5.1.arm-linux.tar.gz `\
152-`[root@localhost usr]# ln -s /usr/lib/fpc/2.5.1/ppcrossarm /usr/bin/ppcrossarm`
154+```text
155+[felipe@localhost Programas]$ ls -l
156+total 20664
157+-rw-rw-r-- 1 felipe felipe 17098552 2010-10-25 08:17 fpc-2.5.1.arm-linux.tar.gz
158+[felipe@localhost Programas]$ su
159+Password:
160+[root@localhost Programas]# cp fpc-2.5.1.arm-linux.tar.gz /usr/
161+[root@localhost Programas]# cd /usr/
162+[root@localhost usr]# tar -xvf fpc-2.5.1.arm-linux.tar.gz
163+[root@localhost usr]# ln -s /usr/lib/fpc/2.5.1/ppcrossarm /usr/bin/ppcrossarm
164+```
153165
154166**Step 4** - Verify if your Cross-Compiler works
155167
156168If you made no errors in the previous steps, it should work, so try to call it like this:
157169
158-`[felipe@localhost Programas]$ /usr/bin/ppcrossarm`
170+```text
171+[felipe@localhost Programas]$ /usr/bin/ppcrossarm
172+```
159173
160174If this command works and fpc shows its options, then you configured the cross-compiler correctly, if not, then try to find out if your symbolic link points to a correct location with this command:
161175
162176\[felipe@localhost Programas\]\$ ls -ls /usr/bin/ppc*
163177
164178Now we are ready to compile Android applications using the Lazarus IDE! Configuring the fpc.cfg file isn't necessary, the old compiler will automatically find the new compiler and it's object files.
165179
166180## Компиляция примера LCL Android приложения
167181
168182**Шаг 1 - Загрузите исходный код**
169183
170184Исходный код примера находится внутри Lazarus источник в lazarus/examples/androidlcl/androidlcltest.lpi
171185
172186**Шаг 2 - Сборка проекта с использованием Lazarus IDE**
173187
174188Configuring Lazarus itself to use the new compiler should not normally be necessary because fpc should be able to find the symlink created, but if you have trouble in this part you can try to hard code the compiler path to use the new crosscompiler. To hardcode the compiler path in cause of trouble go to the menu "Tools-\>Options" and change the "Compiler Path" to "/usr/bin/ppcrossarm"
175189
176190But it is necessary to configure the LPI file to build the example. Open the Project Options dialog of the androidlcltest.lpi project and go to the section Paths and change the libraries path to reflect the correct paths of where your Android NDK was installed and where your jnigraphics.so, libc.so, etc, libraries are located for your target Android API level. For LCL-CustomDrawn-Android API level 8 is the best choice, because it supports Android 2.2+ like the LCL. The image bellow shows where to configure this:
177191
178192![](/wiki-images/b/b0/Configure_androidlcl_libraries.jpg)
179193
180194**Step 3 - Build the APK**
181195
182196Before going to the command line to build the APK open the file lazarus/examples/androidlcl/android/local.properties and change it to reflect your Android SDK path. The file says you should not modify it, but ignore that and modify it anyway. Here is how the file looks like:
183197
184198 # This file is automatically generated by Android Tools.
185199 # Do not modify this file -- YOUR CHANGES WILL BE ERASED!
186200 #
187201 # This file must *NOT* be checked in Version Control Systems,
188202 # as it contains information specific to your local configuration.
189203
190204 # location of the SDK. This is only used by Ant
191205 # For customization when using a Version Control System, please read the
192206 # header note.
193207 sdk.dir=/home/felipe/Programas/android-sdk-linux
194208
195209After configuring that one, go to the command line and issue these commands:
196210
197-` cd lazarus/examples/androidlcl/android`\
198-` ant debug`
211+```text
212+ cd lazarus/examples/androidlcl/android
213+ ant debug
214+```
199215
200216The APK will be located in lazarus/examples/androidlcl/android/bin
201217
202218**Step 4 - Install the APK in your phone and run it**
203219
204220You can install via ADB or by copying the file to the sdcard. You should see this:
205221
206222![](/wiki-images/6/6a/Custom_drawn_android_test1.png)
207223
208224## How to create an LCL Android Application
209225
210226To create a new LCL-CustomDrawn-Android application simply copy all of the file structure and build and java files from the example project called "androidlcl". This example can be obtained from the Lazarus source tree in lazarus/examples/androidlcl
211227
212228Then you will need to modify the build files to change them to your new project name and your new Java package name.
213229
214230### Step 1 - Creating the LPI
215231
216232You need a separate LPI at the moment for the Android version of the application but all the rest of the code can be shared. Create it using the template for a "Library" and then adapt the code from the example located in the lazarus source code in lazarus/examples/androidlcl
217233
218234You need to adapt the exported JNI method names to your Android Package Name.
219235
220236### Step 2 - Building the library
221237
222238First of all, build the Pascal executable without debug information. This debug information is not so useful in Android and makes the executable much bigger. Open the menu Project-\>Project Options and set the build mode, widgetset, architecture and operating system targets, as shown in these screenshots:
223239
224240![](/wiki-images/6/64/Android_project_options_1.png)
225241
226242![](/wiki-images/f/f7/Android_project_options_2.png)
227243
228244![](/wiki-images/9/9f/Android_project_options_3.png)
229245
230246### Step 3 - Create the Android project structure
231247
232248Besides the LCL project building, such as configuring a proper LPI and having a library main project file, one also needs to add all of the android project structure. Simply copy from the example project in lazarus/examples/androidlcl and adapt it to the new project. Things to change are the path to the SDK, the package name. The package name needs to be updated in the build files, in the directory structure android/src/packagename, in the activity java source code and also in the main library pascal source in the exports section.
233249
234250### Building an LCL Android application with debug info
235251
236252It is useful to add another Android build mode which has debug info. Use all of the same options as shown above, except for the debug information:
237253
238254![](/wiki-images/1/11/Android_project_options_4.png)
239255
240256## Oh no! My LCL Android application doesn't work
241257
242258There are various reasons why the app may not work. The most important thing to do when an app doesn't work is to open the logcat and see what the log says. This can be done by running this command line command:
243259
244-`./adb logcat`
260+```text
261+./adb logcat
262+```
245263
246264And then test one of the hipotesis in the next subsections.
247265
248266### The Pascal executable was compiled for a wrong architecture, operating system and/or widgetset
249267
250268This is the leading cause of executables not running. Always verify that you compiled the program to the "android" widgetset, "linux" operating system and "arm" architecture. This is done by going into the menu Project-\>Project Options. Then set these in the dialog all options as explained in this section:
251269
252270[[How to build an LCL Android application]]
253271
254272To check if you library is arm-linux or not, execute the following commands:
255273
256-`cd libs/armeabi`\
257-`ls -l`\
258-`file liblclapp.so`\
259-`ldd liblclapp.so`\
274+```text
275+cd libs/armeabi
276+ls -l
277+file liblclapp.so
278+ldd liblclapp.so
279+```
260280
261281If it mentions anything like 80386 or gtk, then your program was compiled for linux-x86 and gtk2, not for Android like it should.
262282
263283### My Pascal application crashed. How to get a stacktrace?
264284
265285If a Pascal application crashes you should use the command "adb logcat" to obtain the stack
266286
267287### The indispensable build options
268288
269289- -Xd This build option is indispensable when cross-compiling from x86-linux to Android or else FPC will try to link the application against for example /usr/lib/libc.so instead of the libc.so in the NDK, even if you specify a -Fl library path
270290- -CpARMV6 This build option is indispensable because code generated for older ARM versions is unsupported by Android and might crash in some devices. See <http://groups.google.com/group/android-ndk/browse_thread/thread/ba542483f062a828>
271291- -dAndroid in the package LCLBase.lpk
272292- -Parm -Tlinux for the process and target operating system
273293- -Fl should contain the path to the NDK directory with the target link shared object, such as libc.so, liblog.so, libjni.so, etc
274294
275295## Free Pascal Bugs on Android Support
276296
277297The following summarizes the state of Android Support in Free Pascal:
278298
279299- The pre-compiled snapshot for x86-linux -\> Android is known to work very well and it was built on 19th January 2011: <https://sourceforge.net/projects/p-tools/files/Free%20Pascal%20for%20ARM/>
280300- On February this revision <http://svn.freepascal.org/cgi-bin/viewvc.cgi?view=rev&revision=16981> introduced this bug: <http://mantis.freepascal.org/view.php?id=18833>
281301- In the end of 2011 this revision <http://svn.freepascal.org/cgi-bin/viewvc.cgi?view=rev&revision=19036> broke linking Android projects
282302
283303We are in contact with FPC developers to fix the situation as can be seen in: <http://mantis.freepascal.org/view.php?id=20726>
284304
285305## Development Notes
286306
287307### The misterious JNI Crash
288308
289309See the thread: <http://groups.google.com/group/android-ndk/browse_thread/thread/ba542483f062a828>
290310
291311The problem was that vm^^.GetEnv would crash in HTC Wildfire, Alcatel and in the emulator with SIGILL but not in Xperia Mini, HTC Desire HD, Motorola Atrix and other smartphones.
292312
293313The answer was that one needs to specify -CpARMV6 when building because older instructions might fail in some devices
294314
295315### NDK Libraries available in Android 2.2 (API level 8)
296316
297317LCL-CustomDrawn targets Android 2.2+ and in this API level the following libraries are supported by the NDK:
298318
2993191. libc.so
3003202. libdl.so (linker)
3013213. OpenGL ES 1
3023224. OpenGL ES 2
3033235. libjnigraphics.so
3043246. liblog.so
3053257. libm.so
3063268. libz.so
3073279. libthread_db.so
30832810. libstdc++.so
309329
310330LCL-CustomDrawn-Android uses libjnigraphics.so and liblog.so at the moment.
311331
312332### Native text drawing
313333
314334Native text drawing is a bit convoluted in Android and the documentation is quite bad too. Some gotchas already found:
315335
316336- It draws text starting on a Y coordinate which represents the baseline, which is the bottom of strings like "abc", but not the bottom of strings like "qg". See <http://code.google.com/p/android/issues/detail?id=393>
317337- There is no documentation about what the size in Paint.setTextSize represents. Some people say it is pixels, but to me it looks something else because it seams to differ across devices.
318338
319339But there are also good things about it:
320340
321341- It can draw on a transparent bitmap and use alpha transparency to implement anti-aliasing and subpixel rendering. The text gets quite beaultiful.
322342- It can draw on the ARGB 32-bits non-premultiplied format which is a pretty good one
323343
324344### Flood of garbage collector messages when the caret is visible
325345
326346Something like this:
327347
328348 D/dalvikvm( 6364): GC_EXTERNAL_ALLOC freed 188 objects / 6664 bytes in 94ms
329349 D/dalvikvm( 6364): GC_EXTERNAL_ALLOC freed 170 objects / 6160 bytes in 78ms
330350 D/dalvikvm( 6364): GC_EXTERNAL_ALLOC freed 162 objects / 5904 bytes in 82ms
331351 D/dalvikvm( 6364): GC_EXTERNAL_ALLOC freed 162 objects / 5856 bytes in 78ms
332352 D/dalvikvm( 6364): GC_EXTERNAL_ALLOC freed 162 objects / 5872 bytes in 80ms
333353 D/dalvikvm( 2825): GC_EXPLICIT freed 371 objects / 18480 bytes in 91ms
334354 D/dalvikvm( 6364): GC_EXTERNAL_ALLOC freed 162 objects / 5896 bytes in 78ms
335355 D/dalvikvm( 6364): GC_EXTERNAL_ALLOC freed 162 objects / 5896 bytes in 78ms
336356 D/dalvikvm( 6364): GC_EXTERNAL_ALLOC freed 162 objects / 5896 bytes in 81ms
337357 D/dalvikvm( 6364): GC_EXTERNAL_ALLOC freed 162 objects / 5920 bytes in 78ms
338358 D/dalvikvm( 6364): GC_EXTERNAL_ALLOC freed 162 objects / 5920 bytes in 83ms
339359
340360In my investigation this happens probably because the TCDEdit will request a full control invalidate on each timer tick, which currently will main a full form invalidate, so the GC needs to collect the bitmaps and other paint objects when painting that often.
341361
342362### Why the caret of a TEdit keeps blinking after clicking on the form
343363
344364When clicking on the form the LCL focus will refuse to move from the Edit to the Form because this behavior seams to be hard coded in the LCL, although maybe we might change this for Android. So even while we set focus into the form, the LCL refuses to do that and keeps its focus in the Edit, thus we have a focus missmatch. This might eventually be fixed in the future.
345365
346366---
347367*From the Free Pascal wiki, page "Custom Drawn Interface/Android/ru", as it stood on 2015-05-14 after a change by FTurtle, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*
348368Category: Android/ru
349369Category: Custom Drawn/ru
350370Category: Russian
351371Category: Russian (unfinished translation)

Back to history