diff --git a/.classpath b/.classpath deleted file mode 100644 index 95dc717..0000000 --- a/.classpath +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/.idea/copyright/profiles_settings.xml b/.idea/copyright/profiles_settings.xml new file mode 100644 index 0000000..e7bedf3 --- /dev/null +++ b/.idea/copyright/profiles_settings.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/.idea/libraries/libs.xml b/.idea/libraries/libs.xml new file mode 100644 index 0000000..dc5f78e --- /dev/null +++ b/.idea/libraries/libs.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..1a0d457 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/.idea/scopes/scope_settings.xml b/.idea/scopes/scope_settings.xml new file mode 100644 index 0000000..922003b --- /dev/null +++ b/.idea/scopes/scope_settings.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/.idea/uiDesigner.xml b/.idea/uiDesigner.xml new file mode 100644 index 0000000..3b00020 --- /dev/null +++ b/.idea/uiDesigner.xml @@ -0,0 +1,125 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.project b/.project deleted file mode 100644 index 7193920..0000000 --- a/.project +++ /dev/null @@ -1,33 +0,0 @@ - - - ReLaunch - - - - - - com.android.ide.eclipse.adt.ResourceManagerBuilder - - - - - com.android.ide.eclipse.adt.PreCompilerBuilder - - - - - org.eclipse.jdt.core.javabuilder - - - - - com.android.ide.eclipse.adt.ApkBuilder - - - - - - com.android.ide.eclipse.adt.AndroidNature - org.eclipse.jdt.core.javanature - - diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 6473c0e..0000000 --- a/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,5 +0,0 @@ -#Wed Aug 03 15:49:35 PDT 2011 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 -org.eclipse.jdt.core.compiler.compliance=1.5 -org.eclipse.jdt.core.compiler.source=1.5 diff --git a/AndroidManifest.xml b/AndroidManifest.xml index 23a74cb..e9d09f3 100644 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -1,21 +1,28 @@ - + package="com.harasoft.relaunch" + android:versionName="1.3.9.0" android:versionCode="100309000"> + - + - - + + + + + + android:stateNotNeeded="true" + android:exported="false" + android:configChanges="orientation|locale"> @@ -25,99 +32,119 @@ + android:stateNotNeeded="true" + android:exported="false" + android:configChanges="orientation|locale"> - - - - - - - + - - - - - - - - + android:label="@string/app_name" + android:configChanges="orientation|locale"> - + - + + + + + + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + + + + + + + + + + + + - + - + - + + - \ No newline at end of file + diff --git a/Main.iml b/Main.iml new file mode 100644 index 0000000..11d403f --- /dev/null +++ b/Main.iml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/gen/com/harasoft/relaunch/BuildConfig.java b/gen/com/harasoft/relaunch/BuildConfig.java new file mode 100644 index 0000000..5f46cb8 --- /dev/null +++ b/gen/com/harasoft/relaunch/BuildConfig.java @@ -0,0 +1,8 @@ +/*___Generated_by_IDEA___*/ + +package com.harasoft.relaunch; + +/* This stub is only used by the IDE. It is NOT the BuildConfig class actually packed into the APK */ +public final class BuildConfig { + public final static boolean DEBUG = Boolean.parseBoolean(null); +} \ No newline at end of file diff --git a/gen/com/harasoft/relaunch/Manifest.java b/gen/com/harasoft/relaunch/Manifest.java new file mode 100644 index 0000000..a788da3 --- /dev/null +++ b/gen/com/harasoft/relaunch/Manifest.java @@ -0,0 +1,7 @@ +/*___Generated_by_IDEA___*/ + +package com.harasoft.relaunch; + +/* This stub is only used by the IDE. It is NOT the Manifest class actually packed into the APK */ +public final class Manifest { +} \ No newline at end of file diff --git a/gen/com/harasoft/relaunch/R.java b/gen/com/harasoft/relaunch/R.java new file mode 100644 index 0000000..8eda8ff --- /dev/null +++ b/gen/com/harasoft/relaunch/R.java @@ -0,0 +1,7 @@ +/*___Generated_by_IDEA___*/ + +package com.harasoft.relaunch; + +/* This stub is only used by the IDE. It is NOT the R class actually packed into the APK */ +public final class R { +} \ No newline at end of file diff --git a/libs/dropbox-android-sdk-1.5.4.jar b/libs/dropbox-android-sdk-1.5.4.jar new file mode 100644 index 0000000..38a3602 Binary files /dev/null and b/libs/dropbox-android-sdk-1.5.4.jar differ diff --git a/libs/ebookParser-1.3.jar b/libs/ebookParser-1.3.jar deleted file mode 100644 index 78dc0a4..0000000 Binary files a/libs/ebookParser-1.3.jar and /dev/null differ diff --git a/libs/httpmime-4.0.3.jar b/libs/httpmime-4.0.3.jar new file mode 100644 index 0000000..0dfd331 Binary files /dev/null and b/libs/httpmime-4.0.3.jar differ diff --git a/libs/json_simple-1.1.jar b/libs/json_simple-1.1.jar new file mode 100644 index 0000000..f395f41 Binary files /dev/null and b/libs/json_simple-1.1.jar differ diff --git a/proguard.cfg b/proguard.cfg deleted file mode 100644 index b1cdf17..0000000 --- a/proguard.cfg +++ /dev/null @@ -1,40 +0,0 @@ --optimizationpasses 5 --dontusemixedcaseclassnames --dontskipnonpubliclibraryclasses --dontpreverify --verbose --optimizations !code/simplification/arithmetic,!field/*,!class/merging/* - --keep public class * extends android.app.Activity --keep public class * extends android.app.Application --keep public class * extends android.app.Service --keep public class * extends android.content.BroadcastReceiver --keep public class * extends android.content.ContentProvider --keep public class * extends android.app.backup.BackupAgentHelper --keep public class * extends android.preference.Preference --keep public class com.android.vending.licensing.ILicensingService - --keepclasseswithmembernames class * { - native ; -} - --keepclasseswithmembers class * { - public (android.content.Context, android.util.AttributeSet); -} - --keepclasseswithmembers class * { - public (android.content.Context, android.util.AttributeSet, int); -} - --keepclassmembers class * extends android.app.Activity { - public void *(android.view.View); -} - --keepclassmembers enum * { - public static **[] values(); - public static ** valueOf(java.lang.String); -} - --keep class * implements android.os.Parcelable { - public static final android.os.Parcelable$Creator *; -} diff --git a/res/drawable-mdpi/book.png b/res/drawable-mdpi/book.png new file mode 100644 index 0000000..4da28c1 Binary files /dev/null and b/res/drawable-mdpi/book.png differ diff --git a/res/drawable-mdpi/ci_dropbox.png b/res/drawable-mdpi/ci_dropbox.png new file mode 100644 index 0000000..559e398 Binary files /dev/null and b/res/drawable-mdpi/ci_dropbox.png differ diff --git a/res/drawable-mdpi/folder_books.png b/res/drawable-mdpi/folder_books.png new file mode 100644 index 0000000..f4d464e Binary files /dev/null and b/res/drawable-mdpi/folder_books.png differ diff --git a/res/layout-hdpi/editor_layout.xml b/res/layout-hdpi/editor_layout.xml index efd5011..7cb5cff 100644 --- a/res/layout-hdpi/editor_layout.xml +++ b/res/layout-hdpi/editor_layout.xml @@ -86,7 +86,7 @@ android:drawableLeft="@drawable/ci_del" android:minWidth="64dp" android:paddingRight="5.3dp" - android:text="@string/editor_layout_cancel" > + android:text="@string/app_cancel" > diff --git a/res/layout-hdpi/filters_view.xml b/res/layout-hdpi/filters_view.xml index f036bc1..d4a77c5 100644 --- a/res/layout-hdpi/filters_view.xml +++ b/res/layout-hdpi/filters_view.xml @@ -79,7 +79,7 @@ android:background="@drawable/main_button" android:drawableLeft="@drawable/ci_ok" android:gravity="center" - android:text="@string/filters_view_layout_ok" > + android:text="@string/app_ok" > diff --git a/res/layout-hdpi/main.xml b/res/layout-hdpi/main.xml index 5643c72..15ee301 100644 --- a/res/layout-hdpi/main.xml +++ b/res/layout-hdpi/main.xml @@ -66,8 +66,7 @@ android:src="@drawable/ci_gear2" > - - - + + + + - + + - + + android:layout_width="fill_parent" + android:layout_height="fill_parent" + android:background="@color/normal_bg" + android:orientation="vertical" + android:padding="8dp" > + android:id="@+id/LinearLayoutTitle" + android:layout_width="fill_parent" + android:layout_height="56dp" + android:minHeight="32dp" > + android:id="@+id/imageView1" + android:layout_width="wrap_content" + android:layout_height="fill_parent" + android:background="@color/normal_bg_gray" + android:src="@drawable/ci_gear2" /> + android:id="@+id/prefernces_title" + android:layout_width="fill_parent" + android:layout_height="fill_parent" + android:layout_weight="1" + android:background="@color/normal_bg_gray" + android:editable="false" + android:focusable="false" + android:gravity="left|center_vertical" + android:inputType="textMultiLine" + android:paddingLeft="8dp" + android:text="@string/prefs_layout_title" + android:textAppearance="?android:attr/textAppearanceMedium" + android:textColor="@color/normal_fg" + android:textStyle="bold" > + android:id="@+id/back_btn" + android:layout_width="fill_parent" + android:layout_height="fill_parent" + android:layout_gravity="center" + android:layout_marginLeft="4dp" + android:layout_marginRight="1dp" + android:layout_weight="2.8" + android:background="@drawable/main_button" + android:minWidth="96dp" + android:src="@drawable/ci_exit" /> + - - + android:orientation="horizontal" android:layout_weight="10" android:layout_marginTop="8dp"> + + - + + android:layout_height="56dp" + android:layout_marginTop="8dp"> - - - - \ No newline at end of file diff --git a/res/layout-hdpi/service_details.xml b/res/layout-hdpi/service_details.xml index c328f1d..5303d2d 100644 --- a/res/layout-hdpi/service_details.xml +++ b/res/layout-hdpi/service_details.xml @@ -34,7 +34,7 @@ android:background="@drawable/main_button" android:drawableLeft="@drawable/ci_ok" android:gravity="center" - android:text="@string/service_details_layout_ok" > + android:text="@string/app_ok" > diff --git a/res/layout-hdpi/task_details.xml b/res/layout-hdpi/task_details.xml index cfa30d4..2bee0b3 100644 --- a/res/layout-hdpi/task_details.xml +++ b/res/layout-hdpi/task_details.xml @@ -34,7 +34,7 @@ android:background="@drawable/main_button" android:drawableLeft="@drawable/ci_ok" android:gravity="center" - android:text="@string/service_details_layout_ok" > + android:text="@string/app_ok" > diff --git a/res/layout-hdpi/types_view.xml b/res/layout-hdpi/types_view.xml index 534abc9..c360dda 100644 --- a/res/layout-hdpi/types_view.xml +++ b/res/layout-hdpi/types_view.xml @@ -76,7 +76,7 @@ android:layout_weight="1" android:background="@drawable/main_button" android:drawableLeft="@drawable/ci_ok" - android:text="@string/types_view_layout_ok" > + android:text="@string/app_ok" > diff --git a/res/layout-mdpi/advanced_layout.xml b/res/layout-mdpi/advanced_layout.xml deleted file mode 100644 index b90fc55..0000000 --- a/res/layout-mdpi/advanced_layout.xml +++ /dev/null @@ -1,198 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/res/layout-mdpi/button_dropbox_select.xml b/res/layout-mdpi/button_dropbox_select.xml new file mode 100644 index 0000000..d857ec4 --- /dev/null +++ b/res/layout-mdpi/button_dropbox_select.xml @@ -0,0 +1,30 @@ + + + + + + + \ No newline at end of file diff --git a/res/layout-mdpi/button_opds.xml b/res/layout-mdpi/button_opds.xml new file mode 100644 index 0000000..f2f07d8 --- /dev/null +++ b/res/layout-mdpi/button_opds.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/res/layout-mdpi/dropsync.xml b/res/layout-mdpi/dropsync.xml new file mode 100644 index 0000000..40985bd --- /dev/null +++ b/res/layout-mdpi/dropsync.xml @@ -0,0 +1,106 @@ + + + + + + + + + + + + diff --git a/res/layout-mdpi/filters_view.xml b/res/layout-mdpi/filters_view.xml index 3343645..433eaf2 100644 --- a/res/layout-mdpi/filters_view.xml +++ b/res/layout-mdpi/filters_view.xml @@ -79,7 +79,7 @@ android:background="@drawable/main_button" android:drawableLeft="@drawable/ci_ok" android:gravity="center" - android:text="@string/filters_view_layout_ok" > + android:text="@string/app_ok" > diff --git a/res/layout-mdpi/flist_layout.xml b/res/layout-mdpi/flist_layout.xml index dbc8600..3c3ee73 100644 --- a/res/layout-mdpi/flist_layout.xml +++ b/res/layout-mdpi/flist_layout.xml @@ -6,7 +6,7 @@ android:background="@color/normal_bg" android:orientation="vertical" android:paddingBottom="0dp" - android:paddingTop="0dp" > + android:paddingTop="0dp" android:id="@+id/grid_cell"> @@ -29,7 +29,7 @@ android:layout_height="wrap_content" android:layout_gravity="top|left" android:layout_marginLeft="4dp" - android:background="@color/normal_bg" + android:background="@android:color/transparent" android:src="@drawable/dir_ok" > @@ -37,10 +37,10 @@ android:id="@+id/fl_holder" android:layout_width="fill_parent" android:layout_height="wrap_content" - android:layout_gravity="top|left" + android:layout_gravity="center_vertical|left" android:layout_marginLeft="4dp" android:layout_marginRight="4dp" - android:background="@color/normal_bg" + android:background="@android:color/transparent" android:orientation="vertical" > - + + - + + + + android:orientation="horizontal" android:layout_weight="10" android:layout_marginTop="8dp"> + android:fadingEdge="none" android:footerDividersEnabled="true"> - + + android:layout_marginTop="8dp"> - - - - \ No newline at end of file diff --git a/res/layout-mdpi/results_layout.xml b/res/layout-mdpi/results_layout.xml index 8914529..d90eb45 100644 --- a/res/layout-mdpi/results_layout.xml +++ b/res/layout-mdpi/results_layout.xml @@ -119,7 +119,7 @@ + android:text="@string/app_ok" > diff --git a/res/layout-mdpi/task_details.xml b/res/layout-mdpi/task_details.xml index b9c6196..43e0abb 100644 --- a/res/layout-mdpi/task_details.xml +++ b/res/layout-mdpi/task_details.xml @@ -34,7 +34,7 @@ android:background="@drawable/main_button" android:drawableLeft="@drawable/ci_ok" android:gravity="center" - android:text="@string/service_details_layout_ok" > + android:text="@string/app_ok" > diff --git a/res/layout-mdpi/types_view.xml b/res/layout-mdpi/types_view.xml index 3e69185..94bdd26 100644 --- a/res/layout-mdpi/types_view.xml +++ b/res/layout-mdpi/types_view.xml @@ -76,7 +76,7 @@ android:layout_weight="1" android:background="@drawable/main_button" android:drawableLeft="@drawable/ci_ok" - android:text="@string/types_view_layout_ok" > + android:text="@string/app_ok" > diff --git a/res/layout-mdpi/viewer_layout.xml b/res/layout-mdpi/viewer_layout.xml index 8c2360c..3347be7 100644 --- a/res/layout-mdpi/viewer_layout.xml +++ b/res/layout-mdpi/viewer_layout.xml @@ -4,7 +4,7 @@ android:layout_height="fill_parent" android:background="@color/normal_bg" android:orientation="vertical" - android:padding="8dp" > + android:padding="8dp" android:id="@+id/linLayForAdd"> diff --git a/res/values-es/arrays.xml b/res/values-es/arrays.xml index a4eb75a..67e4846 100644 --- a/res/values-es/arrays.xml +++ b/res/values-es/arrays.xml @@ -54,18 +54,6 @@ sysfs cgroup - - 3 - 4 - 5 - 6 - - - Calidad (CLEAR; mode 3) - Lento (ACTIVE_ALL; mode 4) - Rápido (ONESHOT_ALL; mode 5) - Calidad (CLEAR_ALL; mode 6) - -1 0 @@ -78,106 +66,6 @@ Rápida (GU+ONESHOT_ALL) Rápida (GL16+ACTIVE_ALL) - - NOTHING - OPENN - OPENMENU - OPENSCREEN - - - No hacer nada - Abrir carpeta incial # - Abrir menú de carpetas inicial - Abrir ventana de carpetas inicial - - - NOTHING - OPENN - OPENMENU - OPENSCREEN - - - No hacer nada - Abrir Última abierto # - Abra el menú abrió por última vez - Abrir la pantalla abrió por última vez - - - NOTHING - OPENN - OPENMENU - OPENSCREEN - - - No hacer nada - Abrir Favoritos # - Abrir el menú Favoritos - Favoritos pantalla abierta - - - NOTHING - RELAUNCH - LOCK - POWEROFF - SWITCHWIFI - RUN - - - No hacer nada - Abierto \"Funciones avanzadas\" ventana - Bloqueo del dispositivo - Apague el dispositivo - Interruptor WiFi estado - Ejecutar la aplicación - - - NOTHING - RELAUNCH - LOCK - POWEROFF - SWITCHWIFI - RUN - - - No hacer nada - Abierto \"Configuración\" ventana - Bloqueo del dispositivo - Apague el dispositivo - Interruptor WiFi estado - Ejecutar la aplicación - - - NOTHING - RELAUNCH - LOCK - POWEROFF - SWITCHWIFI - RUN - - - No hacer nada - Abierto \"Gestor de aplicaciones\" de la ventana - Bloqueo del dispositivo - Apague el dispositivo - Interruptor WiFi estado - Ejecutar la aplicación - - - NOTHING - RELAUNCH - LOCK - POWEROFF - SWITCHWIFI - RUN - - - No hacer nada - Abierto \"el consumo de la batería\" ventana - Bloqueo del dispositivo - Apague el dispositivo - Interruptor WiFi estado - Ejecutar la aplicación - -1 1 @@ -214,5 +102,16 @@ Fuerza a vertical Fuerza al paisaje - + + Sistema + English + Русский + Español + + + default + en + ru + es + \ No newline at end of file diff --git a/res/values-es/strings.xml b/res/values-es/strings.xml index f8e3c87..57c4aeb 100644 --- a/res/values-es/strings.xml +++ b/res/values-es/strings.xml @@ -1,7 +1,33 @@ ReLaunch - <h2>Esta aplicación está diseñada sólo para + OK + Cancelar + + NO + + OPDS + Dropbox + Bloqueo del dispositivo + Apague el dispositivo + Interruptor WiFi estado + Ejecutar la aplicación + No hacer nada + Abierto \"el consumo de la batería\" ventana + Abierto \"Gestor de aplicaciones\" de la ventana + Favoritos pantalla abierta + Abrir el menú Favoritos + Abrir Favoritos № + Abrir la pantalla abrió por última vez + Abra el menú abrió por última vez + Abrir Última abierto № + Abrir ventana de carpetas inicial + Abrir menú de carpetas inicial + Abrir carpeta incial № + Abierto \"Configuración\" ventana + Abierto \"Funciones avanzadas\" ventana + + <h2>Esta aplicación está diseñada sólo para el Nook Simple Touch y el Sony PRS-T1</h2><br><center><b>¿Desea continuar?</b></center> @@ -13,29 +39,18 @@ Apagar Guardar == EDICIÓN == - Cancelar Condición: Valor: Y Filtrar ajustes - OK Añadir nuevo Y - Cancelar Subir un nivel Memoria Mem: Batería B Ajustes - Personalizar: Filtros - Personalizar: Asociaciones - Cancelar - OK - Guardar configuraciones y reiniciar ReLaunch - (algunos ajustes solo trabajan después de reiniciar) - Revertir todas las configuraciones a los valores - por defecto Direfenciar mayusculas/minúsculas Buscar sólo extensiones conocidas Ordenar resultados de búsquedas @@ -46,12 +61,11 @@ comas Cadena de búsqueda Búsqueda - Cancelar + Mostrar todos los libros(extensiones conocidas) búsqueda desde root Búsqueda Matar - OK PID/UID: Etiqueta: Nombre: @@ -69,18 +83,16 @@ Ordenar alfabéticamente Tareas Servicios - Esperar... + Esperar… Archivo sufijo: Aplicación: - OK Añadir nuevo - Cancelar Ajustar Asociaciones Editar -- Visualizador integrado -- - REINICIAR\n\nEspere... + REINICIAR\n\nEspere… Dispositivo apagado\n\nUsar botón de encendido para - comenzar de nuevo... + comenzar de nuevo… Conectado, IP: Nivel: No está en rango @@ -92,8 +104,6 @@ Funciones avanzadas, info, etc. Confirmar reinicio ¿Estás seguro de reiniciar el dispositivo? - - NO Confirmación de apagado ¿Estás seguro de que apagar el dispositivo? @@ -106,27 +116,20 @@ RO/RW Sólo lectura RO Lectura/escritura RW - Implementar en los NOOK Simple Touch. Implementar en los dispositivos arraigados. Mover una posición hacia arriba Mover una posición hacia abajo Borrar de favoritos Desinstalar - Cancelar Añadir a favoritos Archivo demasiado grande Archivo es demasiado grande para editar bytes El tamaño máximo permitido es - OK Guardar cambios en alertas ¿Quiere guardar los cambios? - - NO - Cancelar - Cancelar Fallo de apertura No se puede abrir el archivo por escribir @@ -136,27 +139,19 @@ No se puede cerrar el archivo Valores de filtrado: ¡No puede estar vacío! - OK - Cancelar Y OR Seleccione el número de Seleccione la aplicación - OK Cambios disminución de alerta ¿Desea guardar los cambios de configuración de todos los? Configuración por defecto de advertencia ¿Está seguro de restaurar la configuración por defecto? - - No - Cancelar Database operations Do you really want to cleanup cache? ¡Modelo erroneo! - - NO M libre WiFi OFF WiFi ON @@ -165,20 +160,18 @@ Todas las aplicaciones Aplicaciones favoritas Lista de cambios - OK Añadir a favoritos Marcar como leído Quitar marca de leído Olvidar todas las marcas - Obrir con ... - Crear cadena de eventos ... + Obrir con … + Crear cadena de eventos … Copy Move Paste Eliminar ¡No eliminar carpetas vacías! Eliminar carpetas vacías - Cancelar Seleccionar tipo de evento Acción no encontrada Acción no encontrada @@ -217,7 +210,6 @@ fuente: <a href=\"https://github.com/yiselieren/ReLaunch\">git://github.com/yiselieren/ReLaunch.git</a></center> - OK Ver histórico de cambios (changelog) Histórico de cambios Acción @@ -227,7 +219,6 @@ Subir Bajar Eliminar carpeta - Cancelar Eliminar archivo Marcar como leído Eliminar marca de \"leído\" @@ -235,8 +226,6 @@ Eliminar advertencias de archivo ¿Estás seguro de eliminar el archivo \? - - NO Borrar de favoritos Eliminar advertencias de carpeta vacía ¿Estás seguro de eliminar la carpeta vacía @@ -247,7 +236,6 @@ (acciones potencialmente peligrosas) Acción no encontrada Búsqueda en progreso - Cancelar Buscar resultados Archivos (encontrados / búsqueda completa) Total: @@ -260,8 +248,6 @@ Mem: Extensión Extensión de archivo - OK - Cancelar ¡Debe especificar la extensión! ¿Aplicación o acción general? Cuando haces clic sobre un archivo con una @@ -278,7 +264,6 @@ bytes El máximo tamaño de archivo permitido es - OK Resultados filtrados Filtrar resultados de acuerdo a definiciones de filtros @@ -321,18 +306,18 @@ de dir Mostrar los nombres de directorios completos (incluso en los directorios de inicio) - Elemento de menú contextual \'Abrir con...\' + Elemento de menú contextual \'Abrir con…\' - Mostrar \'Abrir con...\' en menú contextual + Mostrar \'Abrir con…\' en menú contextual - No volver a mostrar \'Abrir con...\' en menú + No volver a mostrar \'Abrir con…\' en menú contextual de archivo - Elemento de menú contextual \'Crear evento...\' + Elemento de menú contextual \'Crear evento…\' - Mostrar \'Crear evento...\' en menú contextual - - Ocultar \'Crear evento...\' en menú contextual de - archivo + Mostrar \'Crear evento…\' en menú contextual + + Ocultar \'Crear evento…\' en menú contextual de + archivo Orientación de la pantalla Modo de refresco de pantalla eInk Frecuencia de una completa actualización de la @@ -342,15 +327,15 @@ Tamaño de fuente en nombres de archivos/carpetas Tamaño de fuente en nobres de archivos y - directorios de cualquer lista... px + directorios de cualquer lista… px Tamaño de fuente para nombres de directorios adicionales Tamaño de fuente para de otros directorios como - Favoritos y otras listas... px + Favoritos y otras listas… px Archivos y el tamaño de los iconos de directorios - Icono de tamaño para los archivos y directorios ... - px (0 - desactivar el icono) + Icono de tamaño para los archivos y directorios … + px (0 - desactivar el icono) Lista de archivos y carpetas (por defecto) Lista de carpetas inicial Lista de reciente apertura @@ -427,8 +412,8 @@ Tamaño máximo de resultado en la lista de búsqueda Notificación del estado de la búsqueda - Informe sobre el estado de búsqueda cada ... - archivos + Informe sobre el estado de búsqueda cada … + archivos Carpeta de búsqueda inicial Comenzar búsquedas desde aquí Tamaño máximo de archivo abierto con visor interno @@ -467,4 +452,8 @@ carpetas no vacías Eliminar carpetas vacías recursivamente sin confirmación (¡peligroso!) + + Idioma + Elija un idioma: + Idioma app.\nReinicie Relaunch!. diff --git a/res/values-ru/arrays.xml b/res/values-ru/arrays.xml new file mode 100644 index 0000000..ee5af5c --- /dev/null +++ b/res/values-ru/arrays.xml @@ -0,0 +1,16 @@ + + + + Системный + English + Русский + Español + + + default + en + ru + es + + Системные настройки + \ No newline at end of file diff --git a/res/values-ru/strings.xml b/res/values-ru/strings.xml index 69507d7..7d873b3 100644 --- a/res/values-ru/strings.xml +++ b/res/values-ru/strings.xml @@ -1,6 +1,36 @@ ReLaunch + OK + Отмена + Да + Нет + + OPDS + Dropbox + Заблокировать устройство + Выключить устройство + Переключить состояние WiFi + Выполнить приложение + Ничего не делать + Открыть окно \"Расход батареи\" + Открыть окно \"Менеджер приложений\" + Открыть окно избранного + Открыть меню Избранного + Открыть Избранное № + Открыть окно Недавно открытых + Открыть меню Недавно открытых + Открыть Недавно открытый № + Открыть окно списка начальных папок + Открыть меню выбора начальной папки + Открыть начальную папку № + Открыть окно \"Настройки\" + Открыть окно \"Дополнительные функции\" + Открыть \"Избранные приложения\" + Открыть \"Все приложения\" + Открыть \"Недавно запущеные приложения\" + Открыть окно \"Поиск\" + <h2>Эта программа разработана для Nook Simple Touch или Sony PRS-T1!</h2><br><center><b>Хотите продолжить?</b></center> @@ -12,27 +42,18 @@ Выключить Сохр. == РЕДАКТИРОВАНИЕ == - Отм. Условие: Значение: И Настройки файлового фильтра - OK Новый И - Отмена На уровень выше Memory Mem: Battery B Настройки - Настройка:\nФайловый фильтр - Настройка:\nАссоциации файлов - Отмена - OK - Сохранить и перезапустить - Сброс/Сохр./Восст.\n настроек Регистр различается Только файлы известных расширений Отсортировать результаты @@ -42,12 +63,10 @@ Папка или список папок через запятую Строка поиска Искать - Отмена Показать все книги (известных расширений) в папках для поиска Поиск Завершить - OK PID / UID: Имя: Сист.имя: @@ -65,18 +84,16 @@ Сортировать по алфавиту Задачи Сервисы - Ожидайте... + Ожидайте… Расширение файла: Приложение: - OK Новая - Отмена Настройка ассоциаций Ред. -- ПРОСМОТР -- - ПЕРЕЗАГРУЗКА\n\nОжидайте... - ВЫКЛЮЧЕНО\n\nНажмите кнопку Power для включения... - + ПЕРЕЗАГРУЗКА\n\nОжидайте… + ВЫКЛЮЧЕНО\n\nНажмите кнопку Power для включения… + IP: Сигнал: Недоступно @@ -88,8 +105,6 @@ Дополн. функции и информация Подтверждение перезагруки Вы действительно хотите перезагрузиться? - Да - Нет Подтверждение выключения Вы действительно хотите выключиться? Диски/Разделы @@ -101,26 +116,19 @@ RO/RW RO RW - Только для устройств NOOK Simple touch. Только для устройств с root-доступом. Переместить вверх Переместить вниз Удалить из \"Избранных приложений\" Удалить программу - Отмена Добавить в \"Избранные приложения\" Файл слишком большой Файл слишком большой килобайт Максимальный размер файла - OK Сохранение изменений Вы хотите сохранить изменения? - Да - Нет - Отм. - Отм. Ошибка открытия Невозможно открыть файл для записи @@ -130,25 +138,16 @@ Невозможно закрыть файл Значение: Необходимо указать значение! - OK - Отмена И ИЛИ Укажите порядковый № Выберите приложение - OK Предупреждение Вы хотите сохранить все внесенные изменения? Предупреждение Вы ДЕЙСТВИТЕЛЬНО хотите восстановить настройки по умолчанию? - Да - Нет - Отмена - Вернуть настройки по умолчанию - Сохранить настройки на карту памяти - Восстановить настройки с карты памяти Выполнено! Операция выполнена успешно Операция выполнена успешно\nПрограмма будет @@ -163,8 +162,6 @@ Вы действительно хотите очистить список \"Избранное\"? Не верная модель устройства! - Да - Нет M своб. WiFi выкл. WiFi ВКЛ. @@ -173,26 +170,25 @@ Все приложения Избранные приложения Список изменений - OK Добавить в \"Избранное\" Отметить как прочтенное Снять пометку о прочтении Снять все пометки - Открыть с помощью... - Создать событие... + Открыть с помощью… + Создать событие… Копировать + Копировать папку Переместить - Переместить Вставить - Создать новую папку... + Создать новую папку… Введите имя новой папки Не удалось создать папку - Переименовать... + Переименовать… Введите новое имя файла Удалить Удалить НЕ ПУСТУЮ папку! Удалить пустую папку - Отмена + Копировать в папку Dropbox Выберите вид события Действие не найдено Действие не найдено @@ -226,8 +222,6 @@ WiFi выключен пред. след. - Показать названия книг - Показать файлы Переименовать по тегам fb2/epub… Сортировать файлы по имени файла А-Я @@ -236,7 +230,6 @@ алфавиту Я-А Аннотация Свойства - Свойства файла Имя: Размер: Дата: @@ -252,7 +245,6 @@ code: <a href=\"https://github.com/yiselieren/ReLaunch\">git://github.com/yiselieren/ReLaunch.git</a></center> - OK Справка Справка Действие @@ -262,7 +254,6 @@ Переместить вверх Переместить вниз Удалить папку - Отмена Удалить файл Пометить как прочитанное Снять пометку о прочтении @@ -270,8 +261,6 @@ Предупреждение Вы действительно хотите удалить файл \? - Да - Нет Удалить из "Избранного" Предупреждение Вы действительно хотите удалить пустую папку @@ -283,9 +272,7 @@ (потенциально опасное действие)\? Действие не найдено Выберите файл - Отмена Производится поиск - Отмена Результаты поиска Файлов (найдено / просмотрено) @@ -298,8 +285,6 @@ Mem: Расширение Расширение файла - OK - Отмена Необходимо указать расширение! Конкретное приложение или общее действие? Когда Вы нажимаете на файл с определенным @@ -315,7 +300,6 @@ слишком большой килобайт Максимальный размер файла - OK Файловый фильтр Показывать только файлы, соответствующие фильтру @@ -366,29 +350,29 @@ Для папок внутри начальных не показывать первую часть имени Всегда показывать полные имена папок - Пункт меню \"Открыть с помощью...\" - Показывать пункт \"Открыть с помощью...\" в - контекстом меню файла - Не показывать пункт \"Открыть с помощью...\" в - контекстом меню файла - Пункт меню \"Создать событие...\" - Показывать пункт \"Создать событие...\" в - контекстном меню файла - Не показывать пункт \"Создать событие...\" в - контекстном меню файла + Пункт меню \"Открыть с помощью…\" + Показывать пункт \"Открыть с помощью…\" в + контекстом меню файла + Не показывать пункт \"Открыть с помощью…\" в + контекстом меню файла + Пункт меню \"Создать событие…\" + Показывать пункт \"Создать событие…\" в + контекстном меню файла + Не показывать пункт \"Создать событие…\" в + контекстном меню файла Ориентация экрана Режим обновления экрана EInk Частота полного обновления экрана EInk - Как часто экран будет обновляться полностью... - (обновлений) + Как часто экран будет обновляться полностью… + (обновлений) Размер шрифта имен файлов/папок Размер шрифта основной строки имен файлов и папок во всех - списках... px + списках… px Дополнительный размер шрифта имен файлов Размер шрифта дополнительной строки имен файлов Размер иконок имен файлов/папок Размер иконок для имен файлов и папок во всех - списках... px (0 - без иконок) + списках… px (0 - без иконок) Вывод названия файла в несколько строк Вывод названия файла в одну строку Однострочный режим вывода @@ -400,17 +384,13 @@ Алгоритм определения числа колонок Все приложения Избранные приложения - Показывать разделитель строк в списке файлов - + Показывать разделитель строк в списке файлов Одиночное нажатие кнопки \"К Началу\" Двойное нажатие кнопки \"К Началу\" Длительное нажатие кнопки \"К Началу\" - Одиночное нажатие кнопки \"Недавно открытые\" - - Двойное нажатие кнопки \"Недавно открытые\" - - Длительное нажатие кнопки \"Недавно открытые\" - + Одиночное нажатие кнопки \"Недавно открытые\" + Двойное нажатие кнопки \"Недавно открытые\" + Длительное нажатие кнопки \"Недавно открытые\" Одиночное нажатие кнопки \"Избранное\" Двойное нажатие кнопки \"Избранное\" Длительное нажатие кнопки \"Избранное\" @@ -426,12 +406,20 @@ Одиночное нажатие кнопки \"Ост. батареи\" Двойное нажатие кнопки \"Ост. батареи\" Длительное нажатие кнопки \"Ост. батареи\" - Одиночное нажатие кнопки Избранные приложения - - Двойное нажатие кнопки Избранные приложения - - Длительное нажатие кнопки Избранные приложения - + Одиночное нажатие кнопки \"Избранные приложения\" + Двойное нажатие кнопки \"Избранные приложения\" + Длительное нажатие кнопки \"Избранные приложения\" + + Одиночное нажатие кнопки \"Все приложения\" + Двойное нажатие кнопки \"Все приложения\" + Длительное нажатие кнопки \"Все приложения\" + Одиночное нажатие кнопки \"Недавно запущенные приложения\" + Двойное нажатие кнопки \"Недавно запущенные приложения\" + Длительное нажатие кнопки \"Недавно запущенные приложения\" + Одиночное нажатие кнопки \"Поиск\" + Двойное нажатие кнопки \"Поиск\" + Длительное нажатие кнопки \"Поиск\" + Режим работы при вызове кнопкой Home Запускаться как рабочий стол Запускаться как обычное приложение @@ -452,48 +440,45 @@ "Европейский" (dd.mm.yyyy) Запрет быстрой прокрутки кнопками Быстрая прокрутка запрещена - Быстрая прокрутка разрешена (часто неточно!) - + Быстрая прокрутка разрешена (часто неточно!) Шаг "быстрой" прокрутки - Шаг "быстрой" прокрутки кнопками (проценты) - + Шаг "быстрой" прокрутки кнопками (проценты) Собственная полоса прокрутки Использовать собственную полосу прокрутки Ширина полосы прокрутки - Ширина собственной полосы прокрутки... (пикс.) - + Ширина собственной полосы прокрутки… (пикс.) Отступ полосы прокрутки Кнопка \"Back\" завершает программу Кнопка \"Back\" открывает родительскую папку Использовать кнопку \"Back\" для навигации - Левый отступ собственной полосы прокрутки... - (пикс.) + Левый отступ собственной полосы прокрутки… + (пикс.) Количество результатов поиска Количество выдаваемых результатов поиска, не более - чем... (файлов) + чем… (файлов) Уведомление о состоянии поиска - Сообщать о состоянии поиска каждые... (файлов) - + Сообщать о состоянии поиска каждые… (файлов) + Начальные папки поиска - Поиск всегда начинается с папок... + Поиск всегда начинается с папок… Ограничение просмотра файлов Размер просматриваемого файла не может быть больше - чем... (КБ) + чем… (КБ) Ограничение редактирования файлов Размер редактируемого файла не может быть больше - чем... (КБ) + чем… (КБ) Недавно открытые - Сохранять в списке "Недавно открытых" последние... - (файлов) + Сохранять в списке "Недавно открытых" последние… + (файлов) Избранное - Сохранять в списке "Избранного"... (файлов) - + Сохранять в списке "Избранного"… (файлов) + Недавно запущенные приложения Сохранять в списке "Недавно запущенных приложений" - последние... (приложений) + последние… (приложений) Избранные приложения - Сохранять в списке "Избранных приложений"... - (приложений) + Сохранять в списке "Избранных приложений"…(приложений) + Использовать функции файлового менеджера Показывать пункты меню файлового менеджера Не показывать пункты меню файлового менеджера @@ -520,7 +505,7 @@ Размер шрифта Размер шрифта элементов списка файлов Настройка файлового фильтра - Настройка ассоциций файлов + Настройка ассоциаций файлов Вернуть настройки по умолчанию Сохранить настройки на карту памяти Загрузить настройки с карты памяти @@ -557,42 +542,7 @@ Качественный (GC+ONESHOT_ALL) Быстрый (GU+ONESHOT_ALL) Быстрый (GL16+ACTIVE_ALL) - Ничего не делать - Открыть начальную папку № - Открыть меню выбора начальной папки - Открыть окно списка начальных папок - Ничего не делать - Открыть Недавно открытый # - Открыть меню Недавно открытых - Открыть окно Недавно открытых - Ничего не делать - Открыть Избранное # - Открыть меню Избранного - Открыть окно избранного - Ничего не делать - Открыть окно \"Дополнительные функции\" - Заблокировать устройство - Выключить устройство - Переключить состояние WiFi - Выполнить приложение - Ничего не делать Открыть окно \"Настройки\" - Заблокировать устройство - Выключить устройство - Переключить состояние WiFi - Выполнить приложение - Ничего не делать - Открыть окно \"Менеджер приложений\" - Заблокировать устройство - Выключить устройство - Переключить состояние WiFi - Выполнить приложение - Ничего не делать - Открыть окно \"Расход батареи\" - Заблокировать устройство - Выключить устройство - Переключить состояние WiFi - Выполнить приложение Автоматическое число колонок 1 колонка 2 колонки @@ -616,11 +566,100 @@ Полный путь к папке Добавить к Начальным папкам Установить Начальной папкой - Ничего не делать - Открыть \"Избранные приложения\" - Выполнить приложение Авторы: Серия: Название: - + + Язык + Выберите язык: + Язык приложения.\nПерегрузите ReLaunch. + Скачать файлы + > Настройка Dropbox + Папка Dropbox + Скачиваемая папка Dropbox + Локальная папка + Локальная папка для скачиваемых файлов + > Настройка OPDS + OPDS каталог для подключения + OPDS каталог + Локальная папка для скачиваемых файлов + Локальная папка + Информация о книге + Cкачать книгу в формате: + Выбрать и скачать + Загрузить файлы + Оставлять отсутствующие на сервере файлы + Удалять отсутствующие на сервере файлы + Удаление локальных файлов + Оставлять отсутствующие на устройстве файлы + Удалять отсутствующие на устройстве файлы + Удаление файлов на сервере. + Внимание! Необходимо выполнить настройку. + Ошибка аутентификации + Ошибка соединения + Ошибка скачивания с сервера + Ошибка загрузки файлов на сервер + Скачать + Дождитесь окончания операции скачивания файлов! + Скачать выбранное? + Скопировано   +   файлов + Введите имя пользователя + Имя пользователя + Введите пароль пользователя + Пароль + Копировать в Dropbox + Кнопка для запуска + Больше + Расширенная информация + Выбор файла + - Данные о книге -\n + - Данные об исходнике книги -\n + - Информация об FB2-документе -\n + - Сведения об издании книги -\n + Серия:\n + Жанр:\n + Название произведения:\n + Список ключевых слов к книге:\n + Дата:\n + Язык книги:\n + Язык оригинала:\n + Программы использованные при подготовке:\n + Оригинальный документ:\n + Автор OCR или оригинального документа:\n + Версия FB2-документа:\n + Правообладатель:\n + Год издания:\n + Автор:\n + Переводчик:\n + Переписать… + Удалить выбранное? + Показывать Dropbox как корневую папку + Панель 1: Домой, Документы, Поиск, Нстройка + Панель видна + Панель скрыта + Панель 2: текущая папка + Панель 3: кнопки навигации, Дополнительные настройки + Панель 4: Память, Программы, Аккумулятор + Ошибка создания папки + Отсутствует соединение с интернетом! + Невозможно создать локальный каталог или неверный путь + Неполный адрес каталога + Открыть папку с файлом + Добавить OPDS каталог + Адрес OPDS каталога + Имя каталога + OPDS каталоги + Изменить + Список OPDS каталогов + Сохранять в списке \"Список OPDS каталогов\"… + Пароль пользователя + Имя пользователя + Использовать пароль + Очистить список OPDS каталогов + Удалить базу OPDS каталогов + Выделить + Удаление выбранных файлов + Удалить следующие файлы: + Снять выделение diff --git a/res/values/arrays.xml b/res/values/arrays.xml index d577576..b18c293 100644 --- a/res/values/arrays.xml +++ b/res/values/arrays.xml @@ -54,18 +54,6 @@ sysfs cgroup - - 3 - 4 - 5 - 6 - - - CLEAR (mode 3) - ACTIVE_ALL (mode 4) - ONESHOT_ALL (mode 5) - CLEAR_ALL (mode 6) - -1 0 @@ -78,105 +66,59 @@ @string/arr_einkUpdateMode_names_3 @string/arr_einkUpdateMode_names_4 - - NOTHING - OPENN - OPENMENU - OPENSCREEN - - - @string/arr_home_button_actions_names_1 - @string/arr_home_button_actions_names_2 - @string/arr_home_button_actions_names_3 - @string/arr_home_button_actions_names_4 - - - NOTHING - OPENN - OPENMENU - OPENSCREEN - - - @string/arr_lru_button_actions_names_1 - @string/arr_lru_button_actions_names_2 - @string/arr_lru_button_actions_names_3 - @string/arr_lru_button_actions_names_4 - - - NOTHING - OPENN - OPENMENU - OPENSCREEN - - - @string/arr_fav_button_actions_names_1 - @string/arr_fav_button_actions_names_2 - @string/arr_fav_button_actions_names_3 - @string/arr_fav_button_actions_names_4 - - - NOTHING - RELAUNCH - LOCK - POWEROFF - SWITCHWIFI - RUN - - - @string/arr_advanced_button_actions_names_1 - @string/arr_advanced_button_actions_names_2 - @string/arr_advanced_button_actions_names_3 - @string/arr_advanced_button_actions_names_4 - @string/arr_advanced_button_actions_names_5 - @string/arr_advanced_button_actions_names_6 - - + NOTHING - RELAUNCH + HOMEN + HOMEMENU + HOMESCREEN + LRUN + LRUMENU + LRUSCREEN + FAVDOCN + FAVDOCMENU + FAVDOCSCREEN + ADVANCED + SETTINGS + APPMANAGER + BATTERY + FAVAPP + ALLAPP + LASTAPP + SEARCH LOCK POWEROFF SWITCHWIFI RUN - - - @string/arr_settings_button_actions_names_1 - @string/arr_settings_button_actions_names_2 - @string/arr_settings_button_actions_names_3 - @string/arr_settings_button_actions_names_4 - @string/arr_settings_button_actions_names_5 - @string/arr_settings_button_actions_names_6 - - - NOTHING - RELAUNCH - LOCK - POWEROFF - SWITCHWIFI - RUN - - - @string/arr_mem_button_actions_names_1 - @string/arr_mem_button_actions_names_2 - @string/arr_mem_button_actions_names_3 - @string/arr_mem_button_actions_names_4 - @string/arr_mem_button_actions_names_5 - @string/arr_mem_button_actions_names_6 - - - NOTHING - RELAUNCH - LOCK - POWEROFF - SWITCHWIFI - RUN - - - @string/arr_bat_button_actions_names_1 - @string/arr_bat_button_actions_names_2 - @string/arr_bat_button_actions_names_3 - @string/arr_bat_button_actions_names_4 - @string/arr_bat_button_actions_names_5 - @string/arr_bat_button_actions_names_6 + DROPBOX + OPDS + SYSSETTINGS + + + @string/app_settings_nothing + @string/app_settings_home_number + @string/app_settings_home_menu + @string/app_settings_home + @string/app_settings_lru_doc_number + @string/app_settings_lru_doc_menu + @string/app_settings_lru_doc + @string/app_settings_favorites_doc_number + @string/app_settings_favorites_doc_menu + @string/app_settings_favorites_doc + @string/app_settings_advanced + @string/app_settings_settings + @string/app_settings_app_manager + @string/app_settings_battery + @string/app_settings_favorites_app + @string/app_settings_all_app + @string/app_settings_last_app + @string/app_settings_search + @string/app_settings_lock + @string/app_settings_power_off + @string/app_settings_switch_wifi + @string/app_settings_run + @string/app_settings_dropbox + @string/app_settings_opds + @string/app_settings_sys_settings -1 @@ -235,16 +177,68 @@ @string/arr_work_mode_names_2 @string/arr_work_mode_names_3 - + + + System + English + Русский + Español + + + default + en + ru + es + + NOTHING - RELAUNCH - RUN - - - @string/arr_appfav_button_actions_names_1 - @string/arr_appfav_button_actions_names_2 - @string/arr_appfav_button_actions_names_3 - - - + homeButtonDT + homeButtonLT + lruButtonDT + lruButtonLT + favButtonDT + favButtonLT + settingsButtonDT + settingsButtonLT + advancedButtonDT + advancedButtonLT + memButtonDT + memButtonLT + batButtonDT + batButtonLT + appFavButtonDT + appFavButtonLT + appAllButtonDT + appAllButtonLT + appLastButtonDT + appLastButtonLT + searchButtonDT + searchButtonLT + + + @string/arr_einkUpdateMode_names_1 + @string/pref_i_homeButtonDT_title + @string/pref_i_homeButtonLT_title + @string/pref_i_lruButtonDT_title + @string/pref_i_lruButtonLT_title + @string/pref_i_favButtonDT_title + @string/pref_i_favButtonLT_title + @string/pref_i_settingsButtonDT_title + @string/pref_i_settingsButtonLT_title + @string/pref_i_advancedButtonDT_title + @string/pref_i_advancedButtonLT_title + @string/pref_i_memButtonDT_title + @string/pref_i_memButtonLT_title + @string/pref_i_batButtonDT_title + @string/pref_i_batButtonLT_title + @string/pref_i_appFavButtonDT_title + @string/pref_i_appFavButtonLT_title + @string/pref_i_appAllButtonDT_title + @string/pref_i_appAllButtonLT_title + @string/pref_i_appLastButtonDT_title + @string/pref_i_appLastButtonLT_title + @string/pref_i_searchButtonDT_title + @string/pref_i_searchButtonLT_title + + Системные настройки \ No newline at end of file diff --git a/res/values/changelog.xml b/res/values/changelog.xml index 46fb868..8f9bf40 100644 --- a/res/values/changelog.xml +++ b/res/values/changelog.xml @@ -30,6 +30,20 @@ <b>CHANGELOG</b><br> + <b>1.3.9</b><br> + - fixed NST identification on firmware versions 1.2.0 and 1.2.1<br> + - fixed hanging up when re-entering WiFi settings, this fixes opening settings on Sony ebooks, calls Android system settings applet on other devices<br> + - fixed problems with file filtering<br> + - fixed hanging up when calling empty application link<br> + - updated English translation (tivasyk)<br> + - added option to manually swith language<br> + - added possibility to optionally hide button panels<br> + - added option to assign buttons to any of the available actions<br> + - added possibility to call Android system settings applets<br> + - added displaying additional info about FB2 files<br> + - added possibility to connect to Dropbox (fataddams)<br> + - added possibility to work with OPDS Catalogs (fataddams)<br> + - numerous code rewrites<br> <b>1.3.8</b><br> - added file properties dialog<br> - rewritten book annotation dialog<br> diff --git a/res/values/colors.xml b/res/values/colors.xml index 8873e52..6a215a2 100644 --- a/res/values/colors.xml +++ b/res/values/colors.xml @@ -1,6 +1,5 @@ - #FFFFFFFF #FF000000 #FFD0D0D0 @@ -25,5 +24,4 @@ #FFFFFFFF #FF808080 #FF000000 - \ No newline at end of file diff --git a/res/values/strings.xml b/res/values/strings.xml index f927e87..51dd36b 100644 --- a/res/values/strings.xml +++ b/res/values/strings.xml @@ -1,6 +1,36 @@ ReLaunch + OK + Cancel + Yes + No + + OPDS + Dropbox + Lock device + Power Off device + Switch WiFi state + Run application + Nothing + Open \"battery consumption\" window + Open \"Application manager\" window + Open Favorites screen + Open Favorites menu + Open Favorites № + Open Last opened screen + Open Last opened menu + Open Last opened № + Open home directories screen + Open home directories menu + Open home directory № + Open \"Settings\" window + Open \"Advanced functions\" window + Open \"Favorite applications\" window + Open \"All applications\" window + Open \"Last recently used applications\" window + Open \"Search\" window + <h2>The tool is for Nook Simple Touch or Sony PRS-T1 only!</h2><br><center><b>Continue anyway ?</b></center> @@ -12,28 +42,18 @@ Power Off Save == EDITOR == - Cancel Rule: Value: AND Filter Settings - OK Add new AND - Cancel One level up Memory Mem: Battery B Settings - Filter setting - Associations - Cancel - OK - Save settings and restart ReLaunch (some settings - work only after restart) - Reset/Backup\n/Restore Settings Case sensitive Search known extensions only Sort search results @@ -44,12 +64,10 @@ list Search string Search - Cancel Show all books (known extensions) from search root Search Kill - OK PID/UID: Label: Name: @@ -67,31 +85,27 @@ Sort alphabetically Tasks Services - Wait... + Wait… File suffix: Application: - OK Add new - Cancel Associations Settings Edit -- VIEWER -- - REBOOT\n\nWait... - Powered Off\n\nUse Power button to start again... - + REBOOT\n\nWait… + Powered Off\n\nUse Power button to start again… + Connected, IP: Level: Not in range not configured - WiFi off... + WiFi off… WiFi off - WiFi on... + WiFi on… WiFi on Advanced functions, info, etc. Reboot confirmation Are you sure to reboot your device ? - YES - NO Power Off confirmation Are you sure to power off your device ? Disks/partitions @@ -103,26 +117,19 @@ RO/RW RO RW - Implemented only on NOOK Simple Touch. Implemented only on rooted device. Move one position up Move one position down Remove from favorites Uninstall - Cancel Add to favorites File too big File is too big for editor kilobytes Maximal allowed size is - OK Save changes warning Do you want to save changes? - YES - NO - Cancel - Cancel Open failure Can\'t open file for writting @@ -132,24 +139,15 @@ Can\'t close file Filter value: Can\'t be empty! - OK - Cancel AND OR Select number Select application - OK Decline changes warning Do you want to save all configuration\'s changes? Default settings warning Are you sure to restore default settings? - Yes - No - Cancel - Revert all settings to default values - Save settings to SD Card - Restore settings from SD Card Success! Operation finished successfully Operation finished successfully\nProgram will be @@ -164,8 +162,6 @@ Do you really want to clear Favorites list? Wrong model! - YES - NO M free WiFi is off WiFi is ON @@ -174,26 +170,25 @@ All applications Favorite applications What\'s new - OK Add to favorites Mark as read Remove \"read\" mark Forget all marks - Open with ... - Create Intent ... + Open with … + Create Intent … Copy + Copy Move - Move Paste - Rename... - Create new folder... + Rename… + Create new folder… Enter the name of new folder Unable to create the folder Enter new name of file Delete Delete NON-EMPTY directory! Delete empty directory - Cancel + Copy to dir of Dropbox Select intent type Activity not found Activity not found @@ -225,9 +220,7 @@ WiFi is off prev next - Show book titles - Show file names - Rename file with fb2/epub tags... + Rename file with fb2/epub tags… Sort the files in the order by filename A-Z filename Z-A @@ -235,7 +228,6 @@ by alphabetical order Z-A Show annotation Properties - File Properties Name: Size: Date: @@ -251,7 +243,6 @@ code: <a href=\"https://github.com/yiselieren/ReLaunch\">git://github.com/yiselieren/ReLaunch.git</a></center> - OK Information Information Activity @@ -261,7 +252,6 @@ Move one position up Move one position down Delete directory - Cancel Delete file Mark as read Remove \"read\" mark @@ -270,9 +260,6 @@ Are you sure to delete file \? Select file - Cancel - YES - NO Remove from favorites Delete empty directory warning Are you sure to delete empty directory @@ -282,7 +269,6 @@ (dangerous) \? Activity not found Search in progress - Cancel Search results Files (found / total searched) Total: @@ -295,8 +281,6 @@ Mem: Suffix File suffix - OK - Cancel Can\'t be empty! Explicit application or general intent? When you tap on file with specified suffix ReLaunch @@ -311,7 +295,6 @@ is too big for viewer kilobytes Maximal allowed size is - OK Filter results Filter results according to filter definitions @@ -356,28 +339,28 @@ Hide known part of directories Hide known part (start dir) from dir name Hide known part of directories - \'Open with...\' context menu item - Show \'Open with...\' context menu item - Do not show \'Open with...\' context menu item - - \'Create intent...\' context menu item - Show \'Create intent...\' context menu item - - Do not show \'Create intent...\' context menu item - + \'Open with…\' context menu item + Show \'Open with…\' context menu item + Do not show \'Open with…\' context menu item + + \'Create intent…\' context menu item + Show \'Create intent…\' context menu item + + Do not show \'Create intent…\' context menu item + Screen Orientation EInk Screen Update Mode EInk Screen Full Update Interval How often EInk will be fully updated Files and directories names font size Font size for files and directories names in all - lists... px - Additional font size for files... px - + lists… px + Additional font size for files… px + Font size for additional line in file names Files and directories icons size - Icon size for files and directories... px (0 - - disable icon) + Icon size for files and directories… px (0 - + disable icon) Files and directories list (default) Output filename in multi lines Output filename in single line @@ -414,6 +397,15 @@ Favorite applications Button Single Tap Favorite applications Button Double Tap Favorite applications Button Long Tap + All applications Button Single Tap + All applications Button Double Tap + All applications Button Long Tap + Last applications Button Single Tap + Last applications Button Double Tap + Last applications Button Long Tap + Search Button Single Tap + Search Button Double Tap + Search Button Long Tap Work mode when invoked by Home button Work as launcher when invoked by Home button @@ -458,7 +450,7 @@ Maximal amount of search results Maximal size of search results list How often report search progress - Report search progress every ... files + Report search progress every … files Root search directory Search always start here Maximal file size for viewer @@ -533,42 +525,6 @@ Quality (GC+ONESHOT_ALL) Speed (GU+ONESHOT_ALL) Speed (GL16+ACTIVE_ALL) - Nothing - Open home directory # - Open home directories menu - Open home directories screen - Nothing - Open Last opened # - Open Last opened menu - Open Last opened screen - Nothing - Open Favorites # - Open Favorites menu - Open Favorites screen - Nothing - Open \"Advanced functions\" window - Lock device - Power Off device - Switch WiFi state - Run application - Nothing - Open \"Settings\" window - Lock device - Power Off device - Switch WiFi state - Run application - Nothing - Open \"Application manager\" window - Lock device - Power Off device - Switch WiFi state - Run application - Nothing - Open \"battery consumption\" window - Lock device - Power Off device - Switch WiFi state - Run application Detect automatically 1 column 2 columns @@ -594,11 +550,102 @@ Show full directory path in title Add to Start folders Set as Start folder - Nothing - Open \"Favorite applications\" window - Run application Authors: Series: Title: - + + Language + Select the language: + Language app.\nRestart Relaunch!. + Link Dropbox + Unlink Dropbox + Download + > Dropbox settings + Dropbox folder + DropBox folder to download from + Local folder + Local folder for downloading. + > OPDS settings + OPDS catalog to connect to + OPDS catalog + Local folder to download to + Local folder + Book info + Download the book in the format: + Select and download + Upload + Keep files not on server + Remove files not on server + Remove local files? + Keep files not on reader + Remove files not on reader + Remove files on server? + Attention! Configure before attempting to connect + Error authenticating + Error connecting + Error downloading + Error uploading + Download + Please wait until current download finishes! + Download selected? + Downloaded   +   files + Enter login + Login + Enter password + Password + Copy to Dropbox + Button to start + More + Additional info + Select file + - Book info -\n + - Book source info -\n + - About FB2 document -\n + - Edition info -\n + Series:\n + Genre:\n + Title:\n + Keywords list:\n + Date:\n + Language:\n + Language of original:\n + Software used:\n + Original document:\n + Author of original document or OCR:\n + FB2 version:\n + Copyright:\n + Year of publishing:\n + Author:\n + Translator:\n + Rewrite… + Delete selected? + Show Dropbox as root folder + Panel 1: Home, Documents, Search, Settings + Panel visible + Panel hidden + Panel 2: Current folder + Panel 3: Navigation buttons, Additional settings + Panel 4: Memory, Applications, Battery + Error creating folder + No internet connection! + Can\'t create local folder or invalid path + Incomplete folder address + Open folder with file + Add OPDS Catalog + OPDS Catalog address + Catalog name + OPDS Catalogs + Edit + OPDS Catalogs list + Save to \"OPDS Catalogs list\"… + User password + User login + Use password + Clear OPDS Catalogs list + Delete OPDS Catalogs database + Select + Delete selected files + Delete following files: + Cancel selection diff --git a/res/values/styles.xml b/res/values/styles.xml index 720012d..ffe3950 100644 --- a/res/values/styles.xml +++ b/res/values/styles.xml @@ -1,11 +1,5 @@ - - diff --git a/res/xml/prefs.xml b/res/xml/prefs.xml index f7bdd19..90b295f 100644 --- a/res/xml/prefs.xml +++ b/res/xml/prefs.xml @@ -8,7 +8,7 @@ android:entries="@array/start_mode_names" android:entryValues="@array/start_mode_values" android:key="startMode" - android:layout="@+layout/pref_child" + android:layout="@layout/pref_child" android:persistent="true" android:selectable="true" android:title="@string/pref_i_startMode_title" /> @@ -18,7 +18,7 @@ android:entries="@array/work_mode_names" android:entryValues="@array/work_mode_values" android:key="workMode" - android:layout="@+layout/pref_child" + android:layout="@layout/pref_child" android:persistent="true" android:selectable="true" android:title="@string/pref_i_workMode_title" /> @@ -28,7 +28,7 @@ android:entries="@array/screen_orientation_names" android:entryValues="@array/screen_orientation_values" android:key="screenOrientation" - android:layout="@+layout/pref_child" + android:layout="@layout/pref_child" android:persistent="true" android:selectable="true" android:title="@string/pref_i_screenOrientation_title" /> @@ -36,7 +36,7 @@ + - + + + + @@ -172,7 +183,7 @@ android:defaultValue="10" android:enabled="true" android:key="einkUpdateInterval" - android:layout="@+layout/pref_child" + android:layout="@layout/pref_child" android:persistent="true" android:selectable="true" android:summary="@string/pref_i_einkUpdateInterval_sum" @@ -181,7 +192,7 @@ @@ -262,7 +273,7 @@ android:entries="@array/output_columns_names" android:entryValues="@array/output_columns_values" android:key="columnsHomeList" - android:layout="@+layout/pref_child" + android:layout="@layout/pref_child" android:persistent="true" android:selectable="true" android:title="@string/pref_i_columnsHomeList_title" /> @@ -272,7 +283,7 @@ android:entries="@array/output_columns_names" android:entryValues="@array/output_columns_values" android:key="columnsLRU" - android:layout="@+layout/pref_child" + android:layout="@layout/pref_child" android:persistent="true" android:selectable="true" android:title="@string/pref_i_columnsLRU_title" /> @@ -282,7 +293,7 @@ android:entries="@array/output_columns_names" android:entryValues="@array/output_columns_values" android:key="columnsFAV" - android:layout="@+layout/pref_child" + android:layout="@layout/pref_child" android:persistent="true" android:selectable="true" android:title="@string/pref_i_columnsFAV_title" /> @@ -292,7 +303,7 @@ android:entries="@array/output_columns_names" android:entryValues="@array/output_columns_values" android:key="columnsSearch" - android:layout="@+layout/pref_child" + android:layout="@layout/pref_child" android:persistent="true" android:selectable="true" android:title="@string/pref_i_columnsSearch_title" /> @@ -302,7 +313,7 @@ android:entries="@array/output_columns_names" android:entryValues="@array/output_columns_values" android:key="columnsAppAll" - android:layout="@+layout/pref_child" + android:layout="@layout/pref_child" android:persistent="true" android:selectable="true" android:title="@string/pref_i_columnsAppAll_title" /> @@ -312,7 +323,7 @@ android:entries="@array/output_columns_names" android:entryValues="@array/output_columns_values" android:key="columnsAppFav" - android:layout="@+layout/pref_child" + android:layout="@layout/pref_child" android:persistent="true" android:selectable="true" android:title="@string/pref_i_columnsAppFav_title" /> @@ -322,7 +333,7 @@ android:entries="@array/output_columns_intensity_names" android:entryValues="@array/output_columns_intensity_values" android:key="columnsAlgIntensity" - android:layout="@+layout/pref_child" + android:layout="@layout/pref_child" android:persistent="true" android:selectable="true" android:title="@string/pref_i_columnsAlgIntensity_title" /> @@ -330,19 +341,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/com/harasoft/relaunch/Advanced.java b/src/com/harasoft/relaunch/Advanced.java index e13cedb..6244bae 100644 --- a/src/com/harasoft/relaunch/Advanced.java +++ b/src/com/harasoft/relaunch/Advanced.java @@ -1,24 +1,7 @@ package com.harasoft.relaunch; -import java.io.BufferedReader; -import java.io.DataInputStream; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - import android.app.Activity; -import android.content.BroadcastReceiver; -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.content.SharedPreferences; +import android.content.*; import android.graphics.Typeface; import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; @@ -31,15 +14,14 @@ import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; -import android.widget.AbsListView; -import android.widget.BaseAdapter; -import android.widget.Button; -import android.widget.ImageButton; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.ListView; -import android.widget.TextView; -import android.widget.Toast; +import android.widget.*; + +import java.io.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; public class Advanced extends Activity { final static String TAG = "Advanced"; @@ -54,7 +36,7 @@ public class Advanced extends Activity { boolean addSView = true; WifiManager wfm; - boolean wifiOn = false; + public static boolean wifiOn = false; Button wifiOnOff; Button wifiScan; List wifiNetworks = new ArrayList(); @@ -66,36 +48,6 @@ public class Advanced extends Activity { BroadcastReceiver b2; String connectedSSID; - private void setEinkController() { - if (prefs != null) { - Integer einkUpdateMode = 1; - try { - einkUpdateMode = Integer.parseInt(prefs.getString( - "einkUpdateMode", "1")); - } catch (Exception e) { - einkUpdateMode = 1; - } - if (einkUpdateMode < -1 || einkUpdateMode > 2) - einkUpdateMode = 1; - if (einkUpdateMode >= 0) { - EinkScreen.UpdateMode = einkUpdateMode; - - Integer einkUpdateInterval = 10; - try { - einkUpdateInterval = Integer.parseInt(prefs.getString( - "einkUpdateInterval", "10")); - } catch (Exception e) { - einkUpdateInterval = 10; - } - if (einkUpdateInterval < 0 || einkUpdateInterval > 100) - einkUpdateInterval = 10; - EinkScreen.UpdateModeInterval = einkUpdateInterval; - - EinkScreen.PrepareController(null, false); - } - } - } - static class NetInfo { static int unknownLevel = -5000; String SSID; @@ -170,18 +122,6 @@ static class Info { String used; String free; boolean ro; - - public void dump(String p) { - /* - * Log.d(TAG, p + " dev=\"" + dev + "\" mpoint=\"" + mpoint + - * "\" fs=\"" + fs + "\" used=\"" + used + " total=\"" + total + - * "\" free=\"" + free + "\" ro=" + ro); - */ - } - } - - private void Trace(String t, String s) { - // Log.d(t, s); } static class ViewHolder { @@ -426,18 +366,19 @@ private void createInfo() { String flags = f[3]; String[] f1 = flags.split(","); boolean ignore = false; - for (int i = 0; i < ingnoreFs.length; i++) + for (int i = 0; i < ingnoreFs.length; i++){ if (ingnoreFs[i].equals(fs)) { ignore = true; break; } + } if (ignore) continue; Info in = new Info(); in.dev = f[0]; in.mpoint = f[1]; in.fs = fs; - for (int i = 0; i < f1.length; i++) + for (int i = 0; i < f1.length; i++){ if (f1[i].equals("ro")) { in.ro = true; break; @@ -445,6 +386,7 @@ private void createInfo() { in.ro = false; break; } + } in.total = "0"; in.used = "0"; in.free = "0"; @@ -466,6 +408,7 @@ private void createInfo() { // Wifi wfm = (WifiManager) getSystemService(Context.WIFI_SERVICE); wifiOn = wfm.isWifiEnabled(); + wfm.getWifiState(); wifiNetworks = readScanResults(wfm); } @@ -552,7 +495,7 @@ public void onClick(View v) { } }); wifiNetworks = readScanResults(wfm); - setEinkController(); + EinkScreen.PrepareController(null, false); adapter.notifyDataSetChanged(); wifiScan.setEnabled(true); } else { @@ -573,7 +516,7 @@ public void onClick(View v) { } }); wifiNetworks.clear(); - setEinkController(); + EinkScreen.PrepareController(null, false); adapter.notifyDataSetChanged(); wifiScan.setEnabled(false); } @@ -585,7 +528,7 @@ protected void onCreate(Bundle savedInstanceState) { prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); - setEinkController(); + EinkScreen.setEinkController(prefs); ingnoreFs = getResources() .getStringArray(R.array.filesystems_to_ignore); @@ -598,12 +541,12 @@ protected void onCreate(Bundle savedInstanceState) { // "Advanced functions, info, etc." ((TextView) findViewById(R.id.results_title)).setText(getResources() .getString(R.string.jv_advanced_title)); - ((ImageButton) findViewById(R.id.results_btn)) + findViewById(R.id.results_btn) .setOnClickListener(new View.OnClickListener() { - public void onClick(View v) { - finish(); - } - }); + public void onClick(View v) { + finish(); + } + }); // Wifi info lv_wifi = (ListView) findViewById(R.id.wifi_lv); @@ -633,8 +576,8 @@ public void onScroll(AbsListView view, sv.total = totalItemCount; sv.count = visibleItemCount; sv.first = firstVisibleItem; - setEinkController(); - sv.invalidate(); + EinkScreen.PrepareController(null, false); + sv.invalidate(); } public void onScrollStateChanged(AbsListView view, @@ -647,7 +590,7 @@ public void onScrollStateChanged(AbsListView view, lv_wifi.setOnScrollListener(new AbsListView.OnScrollListener() { public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { - setEinkController(); + EinkScreen.PrepareController(null, false); } public void onScrollStateChanged(AbsListView view, @@ -670,7 +613,6 @@ public void onClick(View v) { b1 = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { - Trace(TAG, "--- Broadcast receiver B1"); wifiNetworks = readScanResults(wfm); wifiScan.setEnabled(true); adapter.notifyDataSetChanged(); @@ -688,7 +630,6 @@ public void onReceive(Context context, Intent intent) { b2 = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { - Trace(TAG, "--- Broadcast receiver B2"); wifiOn = wfm.isWifiEnabled(); wifiNetworks = readScanResults(wfm); wifiScan.setEnabled(true); @@ -705,7 +646,18 @@ public void onReceive(Context context, Intent intent) { wifiSetup.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { - if (DeviceInfo.EINK_NOOK) { + + if (N2DeviceInfo.EINK_SONY) { + final Intent intent = new Intent(Intent.ACTION_MAIN, null); + intent.addCategory(Intent.CATEGORY_LAUNCHER); + // SONY PRS-Tx only! + final ComponentName cn = new ComponentName( + "com.sony.drbd.ebook.NetworkManagerSettings", + "com.sony.drbd.ebook.NetworkManagerSettings.NMWirelessSetting"); + intent.setComponent(cn); + intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + startActivity(intent); + } else if (N2DeviceInfo.EINK_NOOK) { final Intent intent = new Intent(Intent.ACTION_MAIN, null); intent.addCategory(Intent.CATEGORY_LAUNCHER); // NOOK ST only! @@ -716,11 +668,9 @@ public void onClick(View v) { intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } else { - Toast.makeText( - Advanced.this, - getResources().getString( - R.string.jv_advanced_nook_only), - Toast.LENGTH_LONG).show(); + final Intent intent = new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS); + intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + startActivity(intent); } } }); @@ -832,20 +782,16 @@ public void onClick(View v) { @Override protected void onDestroy() { super.onDestroy(); + unregisterReceiver(b1); + unregisterReceiver(b2); } - @Override - protected void onStop() { - super.onStop(); - unregisterReceiver(b1); - unregisterReceiver(b2); - } @Override protected void onResume() { super.onResume(); - setEinkController(); - app.generalOnResume(TAG, this); + EinkScreen.setEinkController(prefs); + app.generalOnResume(TAG); } } diff --git a/src/com/harasoft/relaunch/AllApplications.java b/src/com/harasoft/relaunch/AllApplications.java index 577f3ef..0d4f471 100644 --- a/src/com/harasoft/relaunch/AllApplications.java +++ b/src/com/harasoft/relaunch/AllApplications.java @@ -1,9 +1,5 @@ package com.harasoft.relaunch; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Context; @@ -15,25 +11,16 @@ import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; -import android.view.ContextMenu; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; +import android.view.*; import android.view.ContextMenu.ContextMenuInfo; -import android.widget.AbsListView; -import android.widget.AdapterView; -import android.widget.ArrayAdapter; -import android.widget.GridView; -import android.widget.ImageButton; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.TextView; -import android.widget.Toast; +import android.widget.*; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + public class AllApplications extends Activity { final String TAG = "AllApps"; @@ -48,7 +35,7 @@ public class AllApplications extends Activity { ReLaunchApp app; HashMap icons; - Boolean rereadOnStart = false; + //Boolean rereadOnStart = false; List itemsArray = new ArrayList(); AppAdapter adapter; GridView lv; @@ -57,36 +44,8 @@ public class AllApplications extends Activity { SharedPreferences prefs; boolean addSView = true; int gcols = 2; + LayoutInflater vi; - private void setEinkController() { - if (prefs != null) { - Integer einkUpdateMode = 1; - try { - einkUpdateMode = Integer.parseInt(prefs.getString( - "einkUpdateMode", "1")); - } catch (Exception e) { - einkUpdateMode = 1; - } - if (einkUpdateMode < -1 || einkUpdateMode > 2) - einkUpdateMode = 1; - if (einkUpdateMode >= 0) { - EinkScreen.UpdateMode = einkUpdateMode; - - Integer einkUpdateInterval = 10; - try { - einkUpdateInterval = Integer.parseInt(prefs.getString( - "einkUpdateInterval", "10")); - } catch (Exception e) { - einkUpdateInterval = 10; - } - if (einkUpdateInterval < 0 || einkUpdateInterval > 100) - einkUpdateInterval = 10; - EinkScreen.UpdateModeInterval = einkUpdateInterval; - - EinkScreen.PrepareController(null, false); - } - } - } static class ViewHolder { TextView tv; @@ -108,9 +67,11 @@ public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; View v = convertView; if (v == null) { - LayoutInflater vi = (LayoutInflater) getApplicationContext() - .getSystemService(Context.LAYOUT_INFLATER_SERVICE); + //LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.applications_item, null); + if(v == null){ + return null; + } holder = new ViewHolder(); holder.tv = (TextView) v.findViewById(R.id.app_name); holder.iv = (ImageView) v.findViewById(R.id.app_icon); @@ -137,6 +98,7 @@ private void saveLast() { try { appLruMax = Integer.parseInt(prefs.getString("appLruSize", "30")); } catch (NumberFormatException e) { + //emply } app.writeFile("app_last", ReLaunch.APP_LRU_FILE, appLruMax, ":"); } @@ -146,6 +108,7 @@ private void saveFav() { try { appFavMax = Integer.parseInt(prefs.getString("appFavSize", "30")); } catch (NumberFormatException e) { + //emply } app.writeFile("app_favorites", ReLaunch.APP_FAV_FILE, appFavMax, ":"); } @@ -202,12 +165,13 @@ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); - setEinkController(); app = ((ReLaunchApp) getApplicationContext()); - app.setFullScreenIfNecessary(this); - setContentView(R.layout.all_applications); + if (app != null) { + app.setFullScreenIfNecessary(this); + } + setContentView(R.layout.all_applications); icons = app.getIcons(); - + vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); // Create applications list final Intent data = getIntent(); if (data.getExtras() == null) { @@ -236,7 +200,7 @@ public void onCreate(Bundle savedInstanceState) { gcols = Integer.parseInt(cols); } - ((ImageButton) findViewById(R.id.app_btn)) + (findViewById(R.id.app_btn)) .setOnClickListener(new View.OnClickListener() { public void onClick(View v) { finish(); @@ -289,8 +253,8 @@ public void onScroll(AbsListView view, sv.total = totalItemCount; sv.count = visibleItemCount; sv.first = firstVisibleItem; - setEinkController(); - sv.invalidate(); + EinkScreen.PrepareController(null, false); + sv.invalidate(); } public void onScrollStateChanged(AbsListView view, @@ -303,7 +267,7 @@ public void onScrollStateChanged(AbsListView view, lv.setOnScrollListener(new AbsListView.OnScrollListener() { public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { - setEinkController(); + EinkScreen.PrepareController(null, false); } public void onScrollStateChanged(AbsListView view, @@ -361,18 +325,10 @@ public void onItemClick(AdapterView parent, View view, ScreenOrientation.set(this, prefs); } - @Override - protected void onRestart() { - super.onRestart(); - setEinkController(); - if (listName.equals("app_all")) - rereadAppList(); - } - @Override protected void onStart() { super.onStart(); - setEinkController(); + EinkScreen.setEinkController(prefs); if (listName.equals("app_all")) rereadAppList(); } @@ -380,10 +336,10 @@ protected void onStart() { @Override protected void onResume() { super.onResume(); - setEinkController(); + EinkScreen.PrepareController(null, false); if (listName.equals("app_all")) rereadAppList(); - app.generalOnResume(TAG, this); + app.generalOnResume(TAG); } @Override @@ -410,7 +366,7 @@ public void onCreateContextMenu(ContextMenu menu, View v, .getString(R.string.jv_allapp_uninstall)); // "Cancel" menu.add(Menu.NONE, CNTXT_MENU_CANCEL, Menu.NONE, getResources() - .getString(R.string.jv_allapp_cancel)); + .getString(R.string.app_cancel)); } else { List lit = app.getList("app_favorites"); boolean in_fav = false; @@ -429,7 +385,7 @@ public void onCreateContextMenu(ContextMenu menu, View v, .getString(R.string.jv_allapp_uninstall)); // "Cancel" menu.add(Menu.NONE, CNTXT_MENU_CANCEL, Menu.NONE, getResources() - .getString(R.string.jv_allapp_cancel)); + .getString(R.string.app_cancel)); } } @@ -438,8 +394,10 @@ public boolean onContextItemSelected(MenuItem item) { if (item.getItemId() == CNTXT_MENU_CANCEL) return true; - AdapterContextMenuInfo info = (AdapterContextMenuInfo) item - .getMenuInfo(); + AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); + if(info == null){ + return false; + } final int pos = info.position; String it = itemsArray.get(pos); @@ -490,11 +448,15 @@ public boolean onContextItemSelected(MenuItem item) { break; case CNTXT_MENU_UNINSTALL: PackageManager pm = getPackageManager(); + if(pm == null){ + return false; + } PackageInfo pi = null; String[] itp = it.split("\\%"); try { pi = pm.getPackageInfo(itp[0], 0); } catch (Exception e) { + //emply } if (pi == null) // "PackageInfo not found for label \"" + it + "\"" @@ -538,7 +500,7 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) { rereadAppList(); break; default: - return; + //return; } } } diff --git a/src/com/harasoft/relaunch/Base64Coder.java b/src/com/harasoft/relaunch/Base64Coder.java new file mode 100644 index 0000000..920446c --- /dev/null +++ b/src/com/harasoft/relaunch/Base64Coder.java @@ -0,0 +1,144 @@ +package com.harasoft.relaunch; +/** + * A Base64 Encoder/Decoder. + * + *

+ * This class is used to encode and decode data in Base64 format as described in RFC 1521. + * + *

+ * This is "Open Source" software and released under the GNU/LGPL license.
+ * It is provided "as is" without warranty of any kind.
+ * Copyright 2003: Christian d'Heureuse, Inventec Informatik AG, Switzerland.
+ * Home page: www.source-code.biz
+ * + *

+ * Version history:
+ * 2003-07-22 Christian d'Heureuse (chdh): Module created.
+ * 2005-08-11 chdh: Lincense changed from GPL to LGPL.
+ * 2006-11-21 chdh:
+ *   Method encode(String) renamed to encodeString(String).
+ *   Method decode(String) renamed to decodeString(String).
+ *   New method encode(byte[],int) added.
+ *   New method decode(String) added.
+ */ + +public class Base64Coder { + + // Mapping table from 6-bit nibbles to Base64 characters. + private static char[] map1 = new char[64]; + static { + int i=0; + for (char c='A'; c<='Z'; c++) map1[i++] = c; + for (char c='a'; c<='z'; c++) map1[i++] = c; + for (char c='0'; c<='9'; c++) map1[i++] = c; + map1[i++] = '+'; map1[i++] = '/'; } + + // Mapping table from Base64 characters to 6-bit nibbles. + private static byte[] map2 = new byte[128]; + static { + for (int i=0; iin. + * @return A character array with the Base64 encoded data. + */ + public static char[] encode (byte[] in, int iLen) { + int oDataLen = (iLen*4+2)/3; // output length without padding + int oLen = ((iLen+2)/3)*4; // output length including padding + char[] out = new char[oLen]; + int ip = 0; + int op = 0; + while (ip < iLen) { + int i0 = in[ip++] & 0xff; + int i1 = ip < iLen ? in[ip++] & 0xff : 0; + int i2 = ip < iLen ? in[ip++] & 0xff : 0; + int o0 = i0 >>> 2; + int o1 = ((i0 & 3) << 4) | (i1 >>> 4); + int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6); + int o3 = i2 & 0x3F; + out[op++] = map1[o0]; + out[op++] = map1[o1]; + out[op] = op < oDataLen ? map1[o2] : '='; op++; + out[op] = op < oDataLen ? map1[o3] : '='; op++; } + return out; } + + /** + * Decodes a string from Base64 format. + * @param s a Base64 String to be decoded. + * @return A String containing the decoded data. + * @throws IllegalArgumentException if the input is not valid Base64 encoded data. + */ + public static String decodeString (String s) { + return new String(decode(s)); } + + /** + * Decodes a byte array from Base64 format. + * @param s a Base64 String to be decoded. + * @return An array containing the decoded data bytes. + * @throws IllegalArgumentException if the input is not valid Base64 encoded data. + */ + public static byte[] decode (String s) { + return decode(s.toCharArray()); } + + /** + * Decodes a byte array from Base64 format. + * No blanks or line breaks are allowed within the Base64 encoded data. + * @param in a character array containing the Base64 encoded data. + * @return An array containing the decoded data bytes. + * @throws IllegalArgumentException if the input is not valid Base64 encoded data. + */ + public static byte[] decode (char[] in) { + int iLen = in.length; + if (iLen%4 != 0) throw new IllegalArgumentException ("Length of Base64 encoded input string is not a multiple of 4."); + while (iLen > 0 && in[iLen-1] == '=') iLen--; + int oLen = (iLen*3) / 4; + byte[] out = new byte[oLen]; + int ip = 0; + int op = 0; + while (ip < iLen) { + int i0 = in[ip++]; + int i1 = in[ip++]; + int i2 = ip < iLen ? in[ip++] : 'A'; + int i3 = ip < iLen ? in[ip++] : 'A'; + if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127) + throw new IllegalArgumentException ("Illegal character in Base64 encoded data."); + int b0 = map2[i0]; + int b1 = map2[i1]; + int b2 = map2[i2]; + int b3 = map2[i3]; + if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0) + throw new IllegalArgumentException ("Illegal character in Base64 encoded data."); + int o0 = ( b0 <<2) | (b1>>>4); + int o1 = ((b1 & 0xf)<<4) | (b2>>>2); + int o2 = ((b2 & 3)<<6) | b3; + out[op++] = (byte)o0; + if (op mDBApi; + ReLaunchApp app; + + Button droplink_btn; + Button dropunlink_btn; + Button download_btn; + Button upload_btn; + Button dbselect_btn; + TextView str_dropbox_folder; + TextView str_local_folder; + static private int flag_download=0; + SharedPreferences prefs; + String DBLocalPath; + String DBPath; + int count_download_files = 0; + boolean flagDelDB; + boolean flagDelLocFile; + + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + if(!ReLaunch.haveNetworkConnection(getApplicationContext())){ + app.showToast(getString(R.string.srt_dbactivity_no_inet));//"No internet connection!"); + finish(); + }else{ + prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); + app = ((ReLaunchApp) getApplicationContext()); + app.setFullScreenIfNecessary(this); + setContentView(R.layout.dropsync); + final Download_Dropbox[] downdrop = new Download_Dropbox[1]; + final Upload_Dropbox[] uploaddrop = new Upload_Dropbox[1]; + String str_f; + Locale locale; + + N2EpdController.n2MainActivity = this; + + str_f = prefs.getString("lang", "default"); + if (!str_f.equals("default")) { + locale = new Locale(str_f); + Locale.setDefault(locale); + Configuration config = new Configuration(); + config.locale = locale; + getBaseContext().getResources().updateConfiguration(config, null); + } + + DBPath = prefs.getString("DropBoxfolder", "none"); + str_f = DBPath.trim(); + if(str_f.lastIndexOf("/") == str_f.length()-1){ + DBPath = str_f.substring(0, str_f.length()-1); + }else{ + DBPath = str_f; + } + DBLocalPath = prefs.getString("LocalfolderDropbox", "none"); + str_f = DBLocalPath.trim(); + if(str_f.lastIndexOf("/") == str_f.length()-1){ + DBLocalPath = str_f.substring(0, str_f.length()-1); + }else{ + DBLocalPath = str_f; + } + flagDelDB = prefs.getBoolean("deleteDropboxFiles", false); + flagDelLocFile = prefs.getBoolean("deleteLocalFiles", false); + + droplink_btn = (Button) findViewById(R.id.dblink_btn); + dropunlink_btn = (Button) findViewById(R.id.bdunlink_btn); + download_btn = (Button) findViewById(R.id.dowload_btn); + upload_btn = (Button) findViewById(R.id.upload_btn); + dbselect_btn = (Button) findViewById(R.id.select_and_dowload); + + ImageButton exit_btn = (ImageButton) findViewById(R.id.exitdb_btn); + str_dropbox_folder = (TextView) findViewById(R.id.tV_dropbox_folder); + str_local_folder = (TextView) findViewById(R.id.tV_local_folder); + + str_f = getString(R.string.pref_i_DropBox_folder); + str_dropbox_folder.setText(str_f + ": " + DBPath); + str_f = getString(R.string.pref_i_Local_folder_DropBox); + str_local_folder.setText(str_f + ": " + DBLocalPath); + checkAppKeySetup(); + AndroidAuthSession session = buildSession(); + + mDBApi = new DropboxAPI(session); + + droplink_btn.setOnClickListener( new View.OnClickListener() { + public void onClick(View v) { + mDBApi.getSession().startAuthentication(DropBoxActivity.this); + } + } ); + + dropunlink_btn.setOnClickListener( new View.OnClickListener() { + public void onClick(View v) { + logOut(); + droplink_btn.setEnabled(true); + dropunlink_btn.setEnabled(false); + download_btn.setEnabled(false); + upload_btn.setEnabled(false); + dbselect_btn.setEnabled(false); + } + } ); + exit_btn.setOnClickListener( new View.OnClickListener() { + public void onClick(View v) { + if(N2DeviceInfo.EINK_NOOK){ + ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE); + am.restartPackage("Browser"); + } + finish(); + } + } ); + + download_btn.setOnClickListener( new View.OnClickListener() { + public void onClick(View v) { + File folder_check; + folder_check = new File(DBLocalPath); + if (!folder_check.exists()) { + if(!folder_check.mkdirs()){ + app.showToast(getString(R.string.srt_dbactivity_warn_create_folder));//"Error create folder"); + finish(); + } + } + downdrop[0] = new Download_Dropbox(); + downdrop[0].execute(); + } + } ); + + upload_btn.setOnClickListener( new View.OnClickListener() { + public void onClick(View v) { + uploaddrop[0] = new Upload_Dropbox(); + uploaddrop[0].execute(); + } + } ); + + if (DBPath.equals("none") || DBLocalPath.equals("none")){ + droplink_btn.setEnabled(false); + dropunlink_btn.setEnabled(false); + download_btn.setEnabled(false); + upload_btn.setEnabled(false); + dbselect_btn.setEnabled(false); + app.showToast(getString(R.string.srt_dbactivity_warn_no_config));//WARNING! No configure! Exit for configure. + } + if (flag_download == 1){ + download_btn.setEnabled(false); + upload_btn.setEnabled(false); + dbselect_btn.setEnabled(false); + } + dbselect_btn.setOnClickListener( new View.OnClickListener() { + public void onClick(View v) { + Intent intent = new Intent(DropBoxActivity.this, DropboxSelect.class); + intent.putExtra("DBLocalPath", DBLocalPath); + startActivity(intent); + } + } ); + } + } + + protected void onResume() { + super.onResume(); + + if (mDBApi.getSession().authenticationSuccessful()) { + try { + // Required to complete auth, sets the access token on the session + mDBApi.getSession().finishAuthentication(); + + AccessTokenPair tokens = mDBApi.getSession().getAccessTokenPair(); + storeKeys(tokens.key, tokens.secret); + + droplink_btn.setEnabled(false); + dropunlink_btn.setEnabled(true); + if (flag_download == 1){ + download_btn.setEnabled(false); + upload_btn.setEnabled(false); + dbselect_btn.setEnabled(false); + }else{ + download_btn.setEnabled(true); + upload_btn.setEnabled(true); + dbselect_btn.setEnabled(true); + } + } catch (IllegalStateException e) { + app.showToast(getString(R.string.srt_dbactivity_err_authent));//"Error connect for Authentication"); + finish(); + } + } + } + + private void storeKeys(String key, String secret) { + // Save the access key for later + prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0); + SharedPreferences.Editor edit = prefs.edit(); + edit.putString(ACCESS_KEY_NAME, key); + edit.putString(ACCESS_SECRET_NAME, secret); + edit.commit(); + } + private String[] getKeys() { + prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0); + String key = prefs.getString(ACCESS_KEY_NAME, null); + String secret = prefs.getString(ACCESS_SECRET_NAME, null); + if (key != null && secret != null) { + String[] ret = new String[2]; + ret[0] = key; + ret[1] = secret; + return ret; + } else { + return null; + } + } + private void clearKeys() { + prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0); + SharedPreferences.Editor edit = prefs.edit(); + edit.clear(); + edit.commit(); + } + public AndroidAuthSession buildSession() { + AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET); + AndroidAuthSession session; + + String[] stored = getKeys(); + if (stored != null) { + droplink_btn.setEnabled(false); + dropunlink_btn.setEnabled(true); + if (flag_download == 0){ + download_btn.setEnabled(true); + upload_btn.setEnabled(true); + dbselect_btn.setEnabled(true); + } + AccessTokenPair accessToken = new AccessTokenPair(stored[0], stored[1]); + session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE, accessToken); + } else { + droplink_btn.setEnabled(true); + dropunlink_btn.setEnabled(false); + download_btn.setEnabled(false); + upload_btn.setEnabled(false); + dbselect_btn.setEnabled(false); + session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE); + } + + return session; + } + private void logOut() { + // Remove credentials from the session + mDBApi.getSession().unlink(); + // Clear our stored keys + clearKeys(); + } + public void checkAppKeySetup() { + // Check to make sure that we have a valid app key + if (APP_KEY.startsWith("CHANGE") || + APP_SECRET.startsWith("CHANGE")) { + app.showToast("You must apply for an app key and secret from developers.dropbox.com, and add them to the DBRoulette ap before trying it."); + finish(); + return; + } + + // Check if the app has set up its manifest properly. + Intent testIntent = new Intent(Intent.ACTION_VIEW); + String scheme = "db-" + APP_KEY; + String uri = scheme + "://" + AuthActivity.AUTH_VERSION + "/test"; + testIntent.setData(Uri.parse(uri)); + PackageManager pm = getPackageManager(); + if (0 == pm.queryIntentActivities(testIntent, 0).size()) { + app.showToast("URL scheme in your app's " + + "manifest is not set up correctly. You should have a " + + "com.dropbox.client2.android.AuthActivity with the " + + "scheme: " + scheme); + finish(); + } + } + + private class Download_Dropbox extends AsyncTask { + boolean flagErrorDownload = false; + + protected Void doInBackground(Void... params) { + ArrayList fullListFiles = new ArrayList(); + + listFiles(DBLocalPath + File.separator, fullListFiles, DBLocalPath.length()); + + count_download_files = 0; + if(!loadFiles(DBPath + File.separator, fullListFiles, DBPath.length())) + flagErrorDownload = true; + Log.i("Relaunch", "flagDelLocFile: "+ flagDelLocFile); + if(flagDelLocFile && !flagErrorDownload){ + + for (String fullListFile : fullListFiles) { + (new File(DBLocalPath + fullListFile)).delete(); + } + } + fullListFiles.clear(); + return null; + } + + protected void onPreExecute() { + super.onPreExecute(); + download_btn.setEnabled(false); + dropunlink_btn.setEnabled(false); + upload_btn.setEnabled(false); + dbselect_btn.setEnabled(false); + flag_download = 1; + } + + @Override + protected void onPostExecute(Void result) { + super.onPostExecute(result); + download_btn.setEnabled(true); + dropunlink_btn.setEnabled(true); + upload_btn.setEnabled(true); + dbselect_btn.setEnabled(true); + if(flagErrorDownload){ + app.showToast(getString(R.string.srt_dbactivity_err_down_dropbox));//"Error dowload files from DropBox"); + } + app.showToast(getString(R.string.srt_dbactivity_file_down) + Integer.toString(count_download_files) + getString(R.string.srt_dbactivity_file_down2));//"Download " +" files" + + flag_download = 0; + } + + } + private boolean loadFiles(String DropBox_Path, ArrayList fullListFiles, int start_pos_path_db) { + DropboxAPI.Entry entries; + FileOutputStream mFos; + File file; + + try { + entries = mDBApi.metadata(DropBox_Path, 0, null, true, null); + } catch (DropboxException e) { + return false; + } + String FullPath; + for (DropboxAPI.Entry e : entries.contents) { + if (!e.isDeleted) { + FullPath = e.path.substring(start_pos_path_db); + file=new File(DBLocalPath+FullPath); + + if(e.isDir){ + if (!file.exists()) { + if(!file.mkdirs()){ + return false; + } + } + if(!loadFiles(e.path + File.separator, fullListFiles, start_pos_path_db)){ + return false; + } + }else{ + if(fullListFiles.contains(FullPath)){ + fullListFiles.remove(FullPath); + }else{ + try { + mFos = new FileOutputStream(file); + } catch (FileNotFoundException e1) { + return false; + } + try { + mDBApi.getFile(e.path, null, mFos, null); + } catch (DropboxException e1) { + file.delete(); + return false; + } + try { + mFos.close(); + } catch (IOException e1) { + return false; + } + count_download_files++; + } + } + } + } + return true; + } + private void listFiles(String Path, ArrayList fullListFiles, int start_pos_path){ + String[] strDirList = (new File(Path)).list(); + String strPath = Path.substring(start_pos_path); + + for (String aStrDirList : strDirList) { + File f1 = new File(Path + aStrDirList); + if (f1.isFile()) { + fullListFiles.add(strPath + aStrDirList); + } else { + listFiles(Path + aStrDirList + File.separator, fullListFiles, start_pos_path); + } + } + } + + private class Upload_Dropbox extends AsyncTask { + boolean flagErrorDownload = false; + + protected Void doInBackground(Void... params) { + ArrayList fullListFilesDB = new ArrayList(); + + if(!listFilesDB(DBPath+File.separator, fullListFilesDB, DBPath.length())){ + flagErrorDownload = true; + } + count_download_files = 0; + if(!uploadFiles(DBLocalPath +File.separator, fullListFilesDB, DBLocalPath.length()) && !flagErrorDownload) + flagErrorDownload = true; + if(flagDelDB && !flagErrorDownload){ + for (String aFullListFilesDB : fullListFilesDB) { + try { + mDBApi.delete(DBPath + aFullListFilesDB); + } catch (DropboxException e) { + flagErrorDownload = true; + break; + } + } + } + fullListFilesDB.clear(); + return null; + } + + protected void onPreExecute() { + super.onPreExecute(); + download_btn.setEnabled(false); + dropunlink_btn.setEnabled(false); + upload_btn.setEnabled(false); + dbselect_btn.setEnabled(false); + flag_download = 1; + } + + @Override + protected void onPostExecute(Void result) { + super.onPostExecute(result); + download_btn.setEnabled(true); + dropunlink_btn.setEnabled(true); + upload_btn.setEnabled(true); + dbselect_btn.setEnabled(true); + if(flagErrorDownload){ + app.showToast(getString(R.string.srt_dbactivity_err_upl_dropbox));//"Error upload files from DropBox"); + } + app.showToast(getString(R.string.srt_dbactivity_file_down) + Integer.toString(count_download_files) + getString(R.string.srt_dbactivity_file_down2)); + flag_download = 0; + } + } + private boolean uploadFiles(String Path, ArrayList fullListFilesDB, int start_pos_path) { + String[] strDirList = (new File(Path)).list(); + String strPath = Path.substring(start_pos_path); + FileInputStream mFos; + + for (String aStrDirList : strDirList) { + File f1 = new File(Path + aStrDirList); + if (f1.isFile()) { + if (!fullListFilesDB.contains(strPath + f1.getName())) { + + try { + mFos = new FileInputStream(f1); + } catch (FileNotFoundException e) { + return false; + } + try { + mDBApi.putFile(DBPath + "/" + strPath + File.separator + f1.getName(), mFos, f1.length(), null, null); + } catch (DropboxException e) { + return false; + } + count_download_files++; + } else { + fullListFilesDB.remove(strPath + f1.getName()); + } + } else { + if (!uploadFiles(Path + aStrDirList + File.separator, fullListFilesDB, start_pos_path)) { + return false; + } + } + } + return true; + } + private boolean listFilesDB(String PathDB, ArrayList fullListFilesDB, int start_pos_path_db){ + String strPath = PathDB.substring(start_pos_path_db); + DropboxAPI.Entry entries; + try { + entries = mDBApi.metadata(PathDB, 0, null, true, null); + } catch (DropboxException e) { + return false; + } + + for (DropboxAPI.Entry e : entries.contents) { + if (!e.isDeleted) { + if(e.isDir){ + if(!listFilesDB(e.path+File.separator, fullListFilesDB, start_pos_path_db)){ + return false; + } + }else{ + fullListFilesDB.add(strPath +e.fileName()); + } + } + } + return true; + } + + +} \ No newline at end of file diff --git a/src/com/harasoft/relaunch/DropboxSelect.java b/src/com/harasoft/relaunch/DropboxSelect.java new file mode 100644 index 0000000..a516179 --- /dev/null +++ b/src/com/harasoft/relaunch/DropboxSelect.java @@ -0,0 +1,617 @@ +package com.harasoft.relaunch; + +import android.app.Activity; +import android.app.AlertDialog; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.os.AsyncTask; +import android.os.Bundle; +import android.os.SystemClock; +import android.preference.PreferenceManager; +import android.util.Log; +import android.util.TypedValue; +import android.view.LayoutInflater; +import android.view.MotionEvent; +import android.view.View; +import android.view.ViewGroup; +import android.widget.*; +import com.dropbox.client2.DropboxAPI; +import com.dropbox.client2.android.AndroidAuthSession; +import com.dropbox.client2.exception.DropboxException; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.ArrayList; + +public class DropboxSelect extends Activity { + DropboxAPI mDBApiDB; + private ArrayList names = new ArrayList(); + private ArrayList list_path_steps = new ArrayList(); + + ImageButton btn_exit; + ReLaunchApp app; + Activity test; + String DBLocalPath; + int count_download_files = 0; + static private boolean flag_download=false; + DropboxAdapter adapter; + SharedPreferences prefs; + int size_icon; + int size_text; + boolean flag_rt; + boolean addSView = true; + + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + app = ((ReLaunchApp) getApplicationContext()); + if (app != null) { + app.setFullScreenIfNecessary(this); + } + prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); + + setContentView(R.layout.prefs_main); + ((ImageView) findViewById(R.id.imageView1)).setImageResource(R.drawable.ci_dropbox); + ((EditText) findViewById(R.id.prefernces_title)).setText("Dropbox"); + size_icon = Integer.parseInt(prefs.getString("firstLineIconSizePx", "48")); + size_text = Integer.parseInt(prefs.getString("firstLineFontSizePx", "20")); + test = this; + mDBApiDB = DropBoxActivity.mDBApi; + + Intent intent = getIntent(); + DBLocalPath = intent.getStringExtra("DBLocalPath"); + + if(!listFilesDB("/", names)){ + app.showToast(getString(R.string.srt_dbactivity_err_con_dropbox));//"Ошибка доступа к дропбоксу"); + } + // создаем адаптер + adapter = new DropboxAdapter(this,names); + final ListView lvDropB = (ListView) findViewById(android.R.id.list); + + lvDropB.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView parent, View itemClicked, int position, long id) { + if(!names.get(position).getfFile()){ + String PathDB =names.get(position).getfullName(); + list_path_steps.add(PathDB); + names.clear(); + if(!listFilesDB(PathDB, names)){ + app.showToast(getString(R.string.srt_dbactivity_err_con_dropbox));//"Ошибка доступа к дропбоксу"); + } + lvDropB.clearChoices(); + adapter.notifyDataSetChanged(); + if(flag_download) + flag_rt = true; + } + } + }); + lvDropB.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { + @Override + public boolean onItemLongClick(AdapterView parent, View itemClicked, int position, long id) { + AlertDialog dialog = DowloadSelDialog(test, position); + dialog.show(); + return false; + } + }); + lvDropB.setAdapter(adapter); + + if (prefs.getBoolean("customScroll", app.customScrollDef)) { + if (addSView) { + int scrollW; + try { + scrollW = Integer.parseInt(prefs.getString("scrollWidth", + "25")); + } catch (NumberFormatException e) { + scrollW = 25; + } + + LinearLayout ll = (LinearLayout) findViewById(R.id.LLlist); + final SView sv = new SView(getBaseContext()); + LinearLayout.LayoutParams pars = new LinearLayout.LayoutParams( + scrollW, ViewGroup.LayoutParams.FILL_PARENT, 2f); + sv.setLayoutParams(pars); + ll.addView(sv); + lvDropB.setOnScrollListener(new AbsListView.OnScrollListener() { + public void onScroll(AbsListView view, + int firstVisibleItem, int visibleItemCount, + int totalItemCount) { + sv.total = totalItemCount; + sv.count = visibleItemCount; + sv.first = firstVisibleItem; + EinkScreen.PrepareController(null, false); + sv.invalidate(); + } + + public void onScrollStateChanged(AbsListView view, + int scrollState) { + } + }); + addSView = false; + } + } else { + lvDropB.setOnScrollListener(new AbsListView.OnScrollListener() { + public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { + EinkScreen.PrepareController(null, false); + } + + public void onScrollStateChanged(AbsListView view, int scrollState) { + } + }); + } + //============================================================================ + + btn_exit = (ImageButton) findViewById(R.id.back_btn); + + btn_exit.setOnClickListener( new View.OnClickListener() { + public void onClick(View v) { + String PathDB; + if(list_path_steps.size() > 1){ + PathDB = list_path_steps.get(list_path_steps.size()-2); + list_path_steps.remove(list_path_steps.size()-1); + }else{ + PathDB = "/"; + list_path_steps.clear(); + } + names.clear(); + if(!listFilesDB(PathDB, names)){ + app.showToast(getString(R.string.srt_dbactivity_err_con_dropbox));//"Ошибка доступа к дропбоксу"); + } + + lvDropB.clearChoices(); + adapter.notifyDataSetChanged(); + if(flag_download) + flag_rt = true; + } + } ); + btn_exit.setOnLongClickListener(new View.OnLongClickListener() { + public boolean onLongClick(View v) { + names.clear(); + list_path_steps.clear(); + finish(); + return true; + } + }); + ImageButton bu = (ImageButton) findViewById(R.id.btn_scrollup); + bu.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) { + if (N2DeviceInfo.EINK_NOOK) { + MotionEvent ev; + ev = MotionEvent.obtain(SystemClock.uptimeMillis(), + SystemClock.uptimeMillis(), + MotionEvent.ACTION_DOWN, 200, 100, 0); + lvDropB.dispatchTouchEvent(ev); + ev = MotionEvent.obtain(SystemClock.uptimeMillis(), + SystemClock.uptimeMillis() + 100, + MotionEvent.ACTION_MOVE, 200, 200, 0); + lvDropB.dispatchTouchEvent(ev); + SystemClock.sleep(100); + ev = MotionEvent.obtain(SystemClock.uptimeMillis(), + SystemClock.uptimeMillis(), + MotionEvent.ACTION_UP, 200, 200, 0); + lvDropB.dispatchTouchEvent(ev); + } else { + int first = lvDropB.getFirstVisiblePosition(); + int visible = lvDropB.getLastVisiblePosition() + - lvDropB.getFirstVisiblePosition() + 1; + first -= visible; + if (first < 0) + first = 0; + final int finfirst = first; + lvDropB.clearFocus(); + lvDropB.post(new Runnable() { + + public void run() { + lvDropB.setSelection(finfirst); + } + }); + } + } + }); + + ImageButton bd = (ImageButton) findViewById(R.id.btn_scrolldown); + bd.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) { + if (N2DeviceInfo.EINK_NOOK) { + MotionEvent ev; + ev = MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis(),MotionEvent.ACTION_DOWN, 200, 200, 0); + lvDropB.dispatchTouchEvent(ev); + ev = MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis() + 100,MotionEvent.ACTION_MOVE, 200, 100, 0); + lvDropB.dispatchTouchEvent(ev); + SystemClock.sleep(100); + ev = MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),MotionEvent.ACTION_UP, 200, 100, 0); + lvDropB.dispatchTouchEvent(ev); + } else { + int total = lvDropB.getCount(); + int last = lvDropB.getLastVisiblePosition(); + if (total == last + 1) + return; + int target = last + 1; + if (target > (total - 1)) + target = total - 1; + final int ftarget = target; + lvDropB.clearFocus(); + lvDropB.post(new Runnable() { + public void run() { + lvDropB.setSelection(ftarget); + } + }); + } + + } + }); + } + + private boolean listFilesDB(String PathDB, ArrayList fullListFilesDB){ + DropboxAPI.Entry entries; + try { + entries = mDBApiDB.metadata(PathDB, 0, null, true, null); + } catch (DropboxException e) { + app.showToast(getString(R.string.srt_dbactivity_err_con_dropbox));//"Error connect from DropBox"); + return false; + } + + for (DropboxAPI.Entry e : entries.contents) { + if (!e.isDeleted) { + if(e.isDir){ + fullListFilesDB.add(new DropboxItems(false, e.fileName(), e.path)); + } + } + } + for (DropboxAPI.Entry e : entries.contents) { + if (!e.isDeleted) { + if(!e.isDir){ + fullListFilesDB.add(new DropboxItems(true, e.fileName(), e.path)); + } + } + } + return true; + } + private class DropboxItems { + private boolean fFile; + private String name; + private String fullName; + private boolean selected; + + public DropboxItems(boolean fFile, String name, String fullName) { + this.fFile = fFile; + this.name = name; + this.fullName = fullName; + selected = false; + } + + public boolean getfFile() { + return fFile; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + public String getfullName() { + return fullName; + } + + public boolean isSelected() { + return selected; + } + + public void setSelected(boolean selected) { + this.selected = selected; + } + + } + public class DropboxAdapter extends ArrayAdapter { + + private final ArrayList list; + private final Activity context; + + public DropboxAdapter(Activity context, ArrayList list) { + super(context, R.layout.button_dropbox_select, list); + this.context = context; + this.list = list; + } + + class ViewHolder { + protected ImageView icon; + protected TextView text; + protected CheckBox checkbox; + } + + @Override + public View getView(int position, View convertView, ViewGroup parent) { + View view; + if (convertView == null) { + LayoutInflater inflator = LayoutInflater.from(context); + view = inflator.inflate(R.layout.button_dropbox_select, null); + final ViewHolder viewHolder = new ViewHolder(); + viewHolder.icon = (ImageView) view.findViewById(R.id.icon_item); + viewHolder.text = (TextView) view.findViewById(R.id.dropItem); + viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check); + viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { + @Override + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { + DropboxItems element = (DropboxItems) viewHolder.checkbox.getTag(); + element.setSelected(buttonView.isChecked()); + } + }); + view.setTag(viewHolder); + viewHolder.checkbox.setTag(list.get(position)); + } else { + view = convertView; + ((ViewHolder) view.getTag()).checkbox.setTag(list.get(position)); + } + ViewHolder holder = (ViewHolder) view.getTag(); + if(list.get(position).getfFile()){ + holder.icon.setImageBitmap(scaleDrawableById(R.drawable.ci_dropbox, size_icon)); + }else{ + holder.icon.setImageBitmap(scaleDrawableById(R.drawable.dir_ok, size_icon)); + } + holder.text.setTextSize(TypedValue.COMPLEX_UNIT_PX, size_text); + holder.text.setText(list.get(position).getName()); + holder.checkbox.setChecked(list.get(position).isSelected()); + return view; + } + private Bitmap scaleDrawableById(int id, int size) { + return Bitmap.createScaledBitmap( + BitmapFactory.decodeResource(getResources(), id), size, size, + true); + } + } + private AlertDialog DowloadSelDialog(final Activity activity, int position){ + boolean selFlag = false; + final String[] list_url = new String[2]; + + for (DropboxItems name : names) { + if (name.isSelected()) { + selFlag = true; + break; + } + } + if(!selFlag){ + names.get(position).setSelected(true); + } + + final AlertDialog.Builder builder = new AlertDialog.Builder(activity); + builder.setTitle(getString(R.string.srt_dbactivity_file_down_title));//"Скачать файлы"); + if(flag_download){ + builder.setMessage(getString(R.string.srt_dbactivity_file_down_mess));//"Дождитесь окончания скачки!"); + }else { + list_url[0] = getString(R.string.srt_dbactivity_file_down_mess_2); + list_url[1] = getString(R.string.srt_dbactivity_file_del);//"Удалить выбранное"; + builder.setItems(list_url, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int item) { + if(item == 0){ + Download_Dropbox downloadFile = new Download_Dropbox(); + downloadFile.execute(); + }else if(item == 1){ + AlertDialog seldel = SelDel(test); + seldel.show(); + } + dialog.dismiss(); // Отпускает диалоговое окно + } + }); + } + builder.setCancelable(true); + builder.setNegativeButton(getResources().getString(R.string.app_cancel), new DialogInterface.OnClickListener() { // Кнопка ОК + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); // Отпускает диалоговое окно + } + }); + return builder.create(); + } + private boolean loadFiles(String DropBox_Path, int start_pos_path_db, String startFolder, ArrayList fullListFiles) { + DropboxAPI.Entry entries; + FileOutputStream mFos; + File file; + + try { + entries = mDBApiDB.metadata(DropBox_Path, 0, null, true, null); + } catch (DropboxException e) { + app.showToast(getString(R.string.srt_dbactivity_err_con_dropbox));//"Error connect from DropBox"); + return false; + } + String FullPath; + for (DropboxAPI.Entry e : entries.contents) { + if (!e.isDeleted) { + FullPath = "/" + startFolder + e.path.substring(start_pos_path_db); + if(!fullListFiles.contains(FullPath)){ + file=new File(DBLocalPath + FullPath); + + if(e.isDir){ + if (!file.exists()) { file.mkdirs(); } + if(!loadFiles(e.path, start_pos_path_db, startFolder, fullListFiles)){ return false; } + }else{ + try { + mFos = new FileOutputStream(file); + } catch (FileNotFoundException e1) { return false; } + + try { + mDBApiDB.getFile(e.path, null, mFos, null); + } catch (DropboxException e1) { + file.delete(); + return false; + } + try { + mFos.close(); + } catch (IOException e1) { return false; } + count_download_files++; + } + } + } + } + return true; + } + private class Download_Dropbox extends AsyncTask { + boolean flagErrorDowload = false; + ArrayList fullListFiles = new ArrayList(); + ArrayList load_names = new ArrayList(); + protected Void doInBackground(Void... params) { + count_download_files = 0; + FileOutputStream mFos = null; + File file; + int start_pos_path_db; + listFiles(DBLocalPath, fullListFiles, DBLocalPath.length()); + for(int i=0; i < load_names.size(); i++){ + if(load_names.get(i).getfFile()){ + if(!fullListFiles.contains(File.separator + load_names.get(i).getName())){ + file = new File(DBLocalPath + File.separator + load_names.get(i).getName()); + try { + mFos = new FileOutputStream(file); + } catch (FileNotFoundException e1) { + flagErrorDowload = true; + } + try { + mDBApiDB.getFile(load_names.get(i).fullName, null, mFos, null); + } catch (DropboxException e1) { + file.delete(); + flagErrorDowload = true; + } + try { + mFos.close(); + } catch (IOException e1) { + flagErrorDowload = true; + } + count_download_files++; + } + }else{ + start_pos_path_db = load_names.get(i).fullName.length(); + file = new File(DBLocalPath +"/" + load_names.get(i).name); + if (!file.exists()) { file.mkdirs(); } + if(!loadFiles(load_names.get(i).fullName, start_pos_path_db, load_names.get(i).name, fullListFiles)) + flagErrorDowload = true; + } + } + return null; + } + + protected void onPreExecute() { + super.onPreExecute(); + for (DropboxItems name : names) { + if (name.isSelected()) { + load_names.add(name); + } + } + load_names.trimToSize(); + flag_download = true; + flag_rt =false; + } + + @Override + protected void onPostExecute(Void result) { + super.onPostExecute(result); + + if(flagErrorDowload){ + app.showToast(getString(R.string.srt_dbactivity_err_down_dropbox));//"Error dowload files from DropBox"); + } + app.showToast(getString(R.string.srt_dbactivity_file_down) + Integer.toString(count_download_files) + getString(R.string.srt_dbactivity_file_down2));//"Download " +" files" + if(!flag_rt){ + for (DropboxItems name : names) { + if (name.isSelected()) { + name.setSelected(false); + } + } + adapter.notifyDataSetChanged(); + } + + flag_download = false; + fullListFiles.clear(); + flag_rt = false; + } + private void listFiles(String Path, ArrayList fullListFiles, int start_pos_path){ + File openDir = new File(Path); + String[] strDirList = openDir.list(); + String strPath = Path.substring(start_pos_path); + + for (String aStrDirList : strDirList) { + File f1 = new File(Path + File.separator + aStrDirList); + + if (f1.isFile()) { + fullListFiles.add(strPath + File.separator + aStrDirList); + } else { + listFiles(Path + File.separator + aStrDirList, fullListFiles, start_pos_path); + } + } + } + } + private class Delete_Dropbox extends AsyncTask { + boolean flagErrorDowload = false; + ArrayList load_names = new ArrayList(); + protected Void doInBackground(Void... params) { + + for (DropboxItems load_name : load_names) { + Log.i("Relaunch", load_name.fullName); + try { + mDBApiDB.delete(load_name.fullName); + } catch (DropboxException e1) { + flagErrorDowload = true; + } + } + return null; + } + + protected void onPreExecute() { + super.onPreExecute(); + + for (DropboxItems name : names) { + if (name.isSelected()) { + load_names.add(name); + } + } + load_names.trimToSize(); + flag_download = true; + flag_rt =false; + } + + @Override + protected void onPostExecute(Void result) { + super.onPostExecute(result); + + if(flagErrorDowload){ + app.showToast(getString(R.string.srt_dbactivity_err_down_dropbox));//"Error dowload files from DropBox"); + } + if(!flag_rt){ + for(int i = names.size()-1; i > -1; i--){ + if(names.get(i).isSelected()){ + names.get(i).setSelected(false); + names.remove(i); + } + } + adapter.notifyDataSetChanged(); + } + app.showToast(getString(R.string.jv_prefs_rsr_ok_text));//"Удаление закончено"); + flag_download = false; + flag_rt = false; + } + } + private AlertDialog SelDel(final Activity activity){ + + AlertDialog.Builder selDel = new AlertDialog.Builder(activity); + selDel.setTitle("Удаление"); + selDel.setMessage(getString(R.string.srt_dbactivity_file_del));//"Вы хотите удалить выбранное?"); + selDel.setPositiveButton(getString(R.string.jv_relaunch_delete), new DialogInterface.OnClickListener() { // Кнопка ОК + @Override + public void onClick(DialogInterface dialog, int which) { + Delete_Dropbox deleteFile = new Delete_Dropbox(); + deleteFile.execute(); + dialog.dismiss(); // Отпускает диалоговое окно + } + }); + selDel.setNegativeButton(getResources().getString(R.string.app_cancel), new DialogInterface.OnClickListener() { // Кнопка ОК + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); // Отпускает диалоговое окно + } + }); + + return selDel.create(); + } +} \ No newline at end of file diff --git a/src/com/harasoft/relaunch/Editor.java b/src/com/harasoft/relaunch/Editor.java index 610a22b..a07e30a 100644 --- a/src/com/harasoft/relaunch/Editor.java +++ b/src/com/harasoft/relaunch/Editor.java @@ -81,7 +81,7 @@ private boolean saveChanges(String newBuf, final String fname) { .getString(R.string.jv_editor_openerr_text2)); // "OK" builder.setPositiveButton( - getResources().getString(R.string.jv_editor_ok), + getResources().getString(R.string.app_ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -107,7 +107,7 @@ public void onClick(DialogInterface dialog, + " \"" + fname + "\""); // "OK" builder.setPositiveButton( - getResources().getString(R.string.jv_editor_ok), + getResources().getString(R.string.app_ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -133,7 +133,7 @@ public void onClick(DialogInterface dialog, + " \"" + fname + "\""); // "OK" builder.setPositiveButton( - getResources().getString(R.string.jv_editor_ok), + getResources().getString(R.string.app_ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -199,7 +199,7 @@ protected void onCreate(Bundle savedInstanceState) { + " " + getResources().getString(R.string.jv_editor_bytes)); builder.setPositiveButton( - getResources().getString(R.string.jv_editor_ok), + getResources().getString(R.string.app_ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -244,7 +244,7 @@ public void onClick(View v) { // "YES" builder.setPositiveButton( getResources() - .getString(R.string.jv_editor_yes), + .getString(R.string.app_yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -256,7 +256,7 @@ public void onClick(DialogInterface dialog, }); // "NO" builder.setNegativeButton( - getResources().getString(R.string.jv_editor_no), + getResources().getString(R.string.app_no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -281,7 +281,7 @@ public void onClick(DialogInterface dialog, @Override protected void onResume() { super.onResume(); - app.generalOnResume(TAG, this); + app.generalOnResume(TAG); } public void afterTextChanged(Editable s) { @@ -290,12 +290,12 @@ public void afterTextChanged(Editable s) { saveBtn.setEnabled(false); // "Back" cancelBtn - .setText(getResources().getString(R.string.jv_editor_back)); + .setText(getResources().getString(R.string.app_cancel)); } else { saveBtn.setEnabled(true); // "Cancel" cancelBtn.setText(getResources().getString( - R.string.jv_editor_cancel)); + R.string.app_cancel)); } } diff --git a/src/com/harasoft/relaunch/EinkScreen.java b/src/com/harasoft/relaunch/EinkScreen.java index e5e1581..ef5a930 100644 --- a/src/com/harasoft/relaunch/EinkScreen.java +++ b/src/com/harasoft/relaunch/EinkScreen.java @@ -5,7 +5,7 @@ * http://http://sourceforge.net/projects/crengine/ */ -import com.harasoft.relaunch.N2EpdController; +import android.content.SharedPreferences; import android.view.View; public class EinkScreen { @@ -24,7 +24,7 @@ public class EinkScreen { public final static int cmodeActive = 2; public static void PrepareController(View view, boolean isPartially) { - if (DeviceInfo.EINK_NOOK) { + if (N2DeviceInfo.EINK_NOOK) { // System.err.println("Sleep = " + isPartially); if (isPartially || IsSleep != isPartially) { SleepController(isPartially, view); @@ -69,7 +69,6 @@ public static void PrepareController(View view, boolean isPartially) { } } - return; /* * if (UpdateMode == 1 && UpdateModeInterval != 0) { if * (RefreshNumber == 0) { // быстрый режим, один @@ -84,10 +83,10 @@ public static void PrepareController(View view, boolean isPartially) { * RefreshNumber = -1; } RefreshNumber ++; } */ } - } + } public static void ResetController(int mode, View view) { - if (!DeviceInfo.EINK_NOOK) { + if (!N2DeviceInfo.EINK_NOOK) { return; } System.err.println("+++ResetController " + mode); @@ -110,7 +109,7 @@ public static void ResetController(int mode, View view) { } public static void ResetController(View view) { - if (!DeviceInfo.EINK_NOOK || UpdateMode == cmodeClear) { + if (!N2DeviceInfo.EINK_NOOK || UpdateMode == cmodeClear) { return; } System.err.println("+++Soft reset Controller "); @@ -119,7 +118,7 @@ public static void ResetController(View view) { } public static void SleepController(boolean toSleep, View view) { - if (!DeviceInfo.EINK_NOOK || toSleep == IsSleep) { + if (!N2DeviceInfo.EINK_NOOK || toSleep == IsSleep) { return; } System.err.println("+++SleepController " + toSleep); @@ -137,7 +136,6 @@ public static void SleepController(boolean toSleep, View view) { } else { ResetController(UpdateMode, view); } - return; } private static void SetMode(View view, int mode) { @@ -159,4 +157,34 @@ private static void SetMode(View view, int mode) { break; } } + + public static void setEinkController(SharedPreferences prefs) { + if (prefs != null) { + Integer einkUpdateMode; + try { + einkUpdateMode = Integer.parseInt(prefs.getString( + "einkUpdateMode", "1")); + } catch (Exception e) { + einkUpdateMode = 1; + } + if (einkUpdateMode < -1 || einkUpdateMode > 2) + einkUpdateMode = 1; + if (einkUpdateMode >= 0) { + EinkScreen.UpdateMode = einkUpdateMode; + + Integer einkUpdateInterval; + try { + einkUpdateInterval = Integer.parseInt(prefs.getString( + "einkUpdateInterval", "10")); + } catch (Exception e) { + einkUpdateInterval = 10; + } + if (einkUpdateInterval < 0 || einkUpdateInterval > 100) + einkUpdateInterval = 10; + EinkScreen.UpdateModeInterval = einkUpdateInterval; + + PrepareController(null, false); + } + } + } } diff --git a/src/com/harasoft/relaunch/ExtendedInfoBook.java b/src/com/harasoft/relaunch/ExtendedInfoBook.java new file mode 100644 index 0000000..86913dc --- /dev/null +++ b/src/com/harasoft/relaunch/ExtendedInfoBook.java @@ -0,0 +1,640 @@ +package com.harasoft.relaunch; + +import android.app.Activity; +import android.app.AlertDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.graphics.Color; +import android.graphics.Typeface; +import android.os.Bundle; +import android.text.Layout; +import android.text.Spannable; +import android.text.SpannableString; +import android.text.method.ScrollingMovementMethod; +import android.text.style.AlignmentSpan; +import android.text.style.RelativeSizeSpan; +import android.text.style.StyleSpan; +import android.text.style.UnderlineSpan; +import android.view.View; +import android.view.ViewGroup; +import android.widget.*; +import org.xmlpull.v1.XmlPullParser; +import org.xmlpull.v1.XmlPullParserException; +import org.xmlpull.v1.XmlPullParserFactory; + +import java.io.*; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; +import java.util.zip.ZipInputStream; + +public class ExtendedInfoBook extends Activity { + ReLaunchApp app; + ImageButton backBtn; + TextView viewTxt; + String fileName; + XmlPullParser xpp; + BufferedReader fileRead; + + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + app = (ReLaunchApp) getApplicationContext(); + app.setFullScreenIfNecessary(this); + setContentView(R.layout.viewer_layout); + // убираем не нужные нам кнопку редактирования и область редактирования + // кнопка + ViewGroup layout = (ViewGroup) ( findViewById(R.id.viewedit_btn)).getParent(); + if(null!=layout) + layout.removeView((findViewById(R.id.viewedit_btn))); + // область редактирования + layout = (ViewGroup) (findViewById(R.id.view_txt)).getParent(); + if(null!=layout) + layout.removeView((findViewById(R.id.view_txt))); + // klwjhre + layout = (ViewGroup) (findViewById(R.id.textViewExtInfo)).getParent(); + if(null!=layout) + layout.removeView((findViewById(R.id.textViewExtInfo))); + //================================================================================ + LinearLayout ll = (LinearLayout)findViewById(R.id.linLayForAdd); + LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( + LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT); + ScrollView scroolTV = new ScrollView(this); + ll.addView(scroolTV); + // TV + viewTxt = new TextView(this); + viewTxt.setBackgroundColor(Color.WHITE); + viewTxt.setLayoutParams(new TableLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT, 1f)); + viewTxt.setTextColor(Color.BLACK); + scroolTV.addView(viewTxt); + + // получаем файл для чтения инфо + final Intent data = getIntent(); + if (data.getExtras() == null) + finish(); + + final String fname = data.getStringExtra("filename"); + if (fname == null) + finish(); + fileName = fname; + // немножко правим заголовок + ((TextView) findViewById(R.id.view_title1)).setText(getString(R.string.srt_title_more_info_book));//"Расширенная информация"); + ((EditText) findViewById(R.id.view_title)).setText(fileName); + + // Set back button + backBtn = (ImageButton) findViewById(R.id.view_btn); + backBtn.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) { + // удаляем файлы если они остались + String[] SavedFiles; + SavedFiles = getApplicationContext().fileList(); + if(SavedFiles.length > 0){ + for (String SavedFile : SavedFiles) { + getApplicationContext().deleteFile(SavedFile); + } + } + finish(); + } + }); + // получаем поток с данными + if(fileName.lastIndexOf("fb2.zip") > -1){ + selectFileInArh(fileName); + } + fileRead = getInputStream(fileName); + getHeaderBook(); + } + private void selectFileInArh(String nameZipFile) { + ZipFile zipFile = null; + ArrayList listFiles = new ArrayList(); + + try { + // open a zip file for reading + zipFile = new ZipFile(nameZipFile); + + // get an enumeration of the ZIP file entries + Enumeration e = zipFile.entries(); + + while (e.hasMoreElements()) { + ZipEntry entry = e.nextElement(); + // get the name of the entry + int lenght = entry.getName().length(); + if(!entry.isDirectory() && lenght > 3 && entry.getName().substring(lenght-3, lenght).equals("fb2")){ + listFiles.add(entry.getName()); + } + } + }catch (IOException ioe) { + System.out.println("Error opening zip file" + ioe); + }finally { + try { + if (zipFile!=null) { + zipFile.close(); + } + }catch (IOException ioe) { + System.out.println("Error while closing zip file" + ioe); + } + } + // получив список файлов в архиве выводим диалог выбора + int count_url = listFiles.size(); + if(count_url > 1){ + String[] list_files = new String[count_url]; + for(short i=0; i -1){ + int stop; + temp = line.substring(start+9); + stop = temp.indexOf("\""); + temp = temp.substring(stop+1); + stop = temp.indexOf("\""); + temp = temp.substring(0, stop); + temp = temp.toUpperCase(); + if("WINDOWS-1251".equals(temp)){ + temp = "CP-1251"; + } + } + if(nameFile.contains("/")){ + try { + r = new BufferedReader(new InputStreamReader(new FileInputStream(nameFile), temp )); + } catch (FileNotFoundException e) { + return null; + } catch (UnsupportedEncodingException e) { + return null; + } + }else{ + try { + r = new BufferedReader(new InputStreamReader(openFileInput(nameFile), temp)); + } catch (FileNotFoundException e) { + return null; + } catch (UnsupportedEncodingException e) { + return null; + } + } + return r; + } + public void getHeaderBook(){ + String fileBookName; + String date_book; + //================================================================================ + try { + // получаем поток и настраиваем парсер + //========================================= + int eventType; + + XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); + factory.setNamespaceAware(true); + xpp = factory.newPullParser(); + xpp.setInput(fileRead); + //================================================= + eventType = xpp.getEventType(); + + String nameTag = ""; + boolean flagDescription = true; + boolean f_genre = false; + boolean f_date = false; + + String genre; + String genre_match = ""; + String first_name = ""; + String middle_name = ""; + String last_name = ""; + String nickname = ""; + String home_page = ""; + String email = ""; + + viewTxt.setMovementMethod(new ScrollingMovementMethod()); + Spannable text; + while (eventType != XmlPullParser.END_DOCUMENT && flagDescription) { + switch (eventType) { + case XmlPullParser.START_TAG: + nameTag = xpp.getName(); + // обозначаем начало разделов + if("title-info".equalsIgnoreCase(nameTag)){ + text = new SpannableString(getString(R.string.srt_info_book_title_info));//"- Данные о книге -\n"); + text.setSpan(new RelativeSizeSpan(1.3f), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + text.setSpan(new StyleSpan(Typeface.BOLD), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + text.setSpan(new UnderlineSpan(), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + text.setSpan(new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + viewTxt.append(text); + } + if("src-title-info".equalsIgnoreCase(nameTag)){ + text = new SpannableString(getString(R.string.srt_info_book_src_title_info));//"- Данные об исходнике книги -\n"); + text.setSpan(new RelativeSizeSpan(1.3f), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + text.setSpan(new StyleSpan(Typeface.BOLD), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + text.setSpan(new UnderlineSpan(), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + text.setSpan(new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + viewTxt.append(text); + } + if("document-info".equalsIgnoreCase(nameTag)){ + text = new SpannableString(getString(R.string.srt_info_book_document_info));//"- Информация об FB2-документе -\n"); + text.setSpan(new RelativeSizeSpan(1.3f), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + text.setSpan(new StyleSpan(Typeface.BOLD), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + text.setSpan(new UnderlineSpan(), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + text.setSpan(new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + viewTxt.append(text); + } + if("publish-info".equalsIgnoreCase(nameTag)){ + text = new SpannableString(getString(R.string.srt_info_book_publish_info));//"- Сведения об издании книги -\n"); + text.setSpan(new RelativeSizeSpan(1.3f), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + text.setSpan(new StyleSpan(Typeface.BOLD), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + text.setSpan(new UnderlineSpan(), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + text.setSpan(new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + viewTxt.append(text); + } + // ---------------------------------------------------------------- + // жанр + if("genre".equals(nameTag)){ + for (short i = 0; i < xpp.getAttributeCount(); i++) { + if("match".equals(xpp.getAttributeName(i))){ + genre_match = xpp.getAttributeValue(i); + } + } + f_genre = true; + } + // дата + if("date".equals(nameTag)){ + for (short i = 0; i < xpp.getAttributeCount(); i++) { + if("value".equals(xpp.getAttributeName(i))){ + genre_match = xpp.getAttributeValue(i); + } + } + f_date = true; + } + // серия и номер в серии + if("sequence".equals(nameTag)){ + String name = "", number = ""; + for (short i = 0; i < xpp.getAttributeCount(); i++) { + if("name".equals(xpp.getAttributeName(i))){ + name = xpp.getAttributeValue(i); + } + if("number".equals(xpp.getAttributeName(i))){ + number = xpp.getAttributeValue(i); + } + } + if(name.length() > 0){ + String temp = name; + viewTxt.append(getString(R.string.srt_info_book_sequence_info));//"Серия:\n"); + if(number.length() > 0){ + temp += ", №"; + temp += number; + } + text = new SpannableString(temp+"\n"); + text.setSpan(new RelativeSizeSpan(1.2f), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + text.setSpan(new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + viewTxt.append(text); + } + } + break; + case XmlPullParser.TEXT: + // жанры + if(f_genre){ + genre = xpp.getText().trim(); + if(genre_match.length() > 0){ + genre += " ("; + genre += genre_match; + genre += "%)"; + genre_match = ""; + } + viewTxt.append(getString(R.string.srt_info_book_genre_info));//"Жанр:\n"); + text = new SpannableString(genre+"\n"); + text.setSpan(new RelativeSizeSpan(1.2f), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + text.setSpan(new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + viewTxt.append(text); + f_genre = false; + } + // авторы и переводчики + if("first-name".equals(nameTag)){ + first_name = xpp.getText(); + } + if("middle-name".equals(nameTag)){ + middle_name = xpp.getText(); + } + if("last-name".equals(nameTag)){ + last_name = xpp.getText(); + } + if("nickname".equals(nameTag)){ + nickname = xpp.getText(); + } + if("home-page".equals(nameTag)){ + home_page = xpp.getText().trim(); + } + if("email".equals(nameTag)){ + email = xpp.getText().trim(); + } + // название книги + if("book-title".equals(nameTag)){ + fileBookName = xpp.getText(); + viewTxt.append(getString(R.string.srt_info_book_book_title_info));//"Название произведения:\n"); + text = new SpannableString(fileBookName+"\n"); + text.setSpan(new RelativeSizeSpan(1.2f), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + text.setSpan(new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + viewTxt.append(text); + } + // Список ключевых слов к книге + if("keywords".equals(nameTag)){ + fileBookName = xpp.getText(); + viewTxt.append(getString(R.string.srt_info_book_keywords_info));//"Список ключевых слов к книге:\n"); + text = new SpannableString(fileBookName+"\n"); + text.setSpan(new RelativeSizeSpan(1.2f), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + text.setSpan(new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + viewTxt.append(text); + } + // дата + if(f_date){ + date_book = xpp.getText(); + if(date_book.trim().length()> 0){ + if(genre_match.trim().length() > 0){ + date_book += " ("; + date_book += genre_match; + date_book += ")"; + genre_match = ""; + } + viewTxt.append(getString(R.string.srt_info_book_data_info));//"Дата:\n"); + text = new SpannableString(date_book+"\n"); + text.setSpan(new RelativeSizeSpan(1.2f), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + text.setSpan(new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + viewTxt.append(text); + } + f_date = false; + } + // язык книги + if("lang".equals(nameTag)){ + genre_match = xpp.getText().trim(); + if(genre_match.length() > 0){ + viewTxt.append(getString(R.string.srt_info_book_lang_info));//"Язык книги:\n"); + text = new SpannableString(genre_match+"\n"); + text.setSpan(new RelativeSizeSpan(1.2f), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + text.setSpan(new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + viewTxt.append(text); + genre_match = ""; + } + } + // язык оригинала + if("src-lang".equals(nameTag)){ + genre_match = xpp.getText().trim(); + if(genre_match.length() > 0){ + viewTxt.append(getString(R.string.srt_info_book_src_lang_info));//"Язык оригинала:\n"); + text = new SpannableString(genre_match+"\n"); + text.setSpan(new RelativeSizeSpan(1.2f), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + text.setSpan(new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + viewTxt.append(text); + genre_match = ""; + } + } + // Перечисляются программы, которые использовались при подготовке документа. + if("program-used".equals(nameTag)){ + genre_match = xpp.getText().trim(); + if(genre_match.length() > 0){ + viewTxt.append(getString(R.string.srt_info_book_program_used_info));//"Программы использованные при подготовке:\n"); + text = new SpannableString(genre_match+"\n"); + text.setSpan(new RelativeSizeSpan(1.2f), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + text.setSpan(new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + viewTxt.append(text); + genre_match = ""; + } + } + // Откуда взят оригинальный документ, доступный в online + if("src-url".equals(nameTag)){ + genre_match = xpp.getText().trim(); + if(genre_match.length() > 0){ + viewTxt.append(getString(R.string.srt_info_book_src_url_info));//"Оригинальный документ:\n"); + text = new SpannableString(genre_match+"\n"); + text.setSpan(new RelativeSizeSpan(1.2f), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + text.setSpan(new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + viewTxt.append(text); + genre_match = ""; + } + } + // Автор OCR или оригинального документа + if("src-ocr".equals(nameTag)){ + genre_match = xpp.getText().trim(); + if(genre_match.length() > 0){ + viewTxt.append(getString(R.string.srt_info_book_src_ocr_info));//"Автор OCR или оригинального документа:\n"); + text = new SpannableString(genre_match+"\n"); + text.setSpan(new RelativeSizeSpan(1.2f), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + text.setSpan(new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + viewTxt.append(text); + genre_match = ""; + } + } + // Версия FB2-документа + if("version".equals(nameTag)){ + genre_match = xpp.getText().trim(); + if(genre_match.length() > 0){ + viewTxt.append(getString(R.string.srt_info_book_version_info));//"Версия FB2-документа:\n"); + text = new SpannableString(genre_match+"\n"); + text.setSpan(new RelativeSizeSpan(1.2f), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + text.setSpan(new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + viewTxt.append(text); + genre_match = ""; + } + } + // Правообладатель + if("publisher".equals(nameTag)){ + genre_match = xpp.getText().trim(); + if(genre_match.length() > 0){ + viewTxt.append(getString(R.string.srt_info_book_publisher_info));//"Правообладатель:\n"); + text = new SpannableString(genre_match+"\n"); + text.setSpan(new RelativeSizeSpan(1.2f), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + text.setSpan(new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + viewTxt.append(text); + genre_match = ""; + } + } + // Год издания оригинальной (бумажной) книги + if("year".equals(nameTag)){ + genre_match = xpp.getText().trim(); + if(genre_match.length() > 0){ + viewTxt.append(getString(R.string.srt_info_book_year_info));//"Год издания:\n"); + text = new SpannableString(genre_match+"\n"); + text.setSpan(new RelativeSizeSpan(1.2f), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + text.setSpan(new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + viewTxt.append(text); + genre_match = ""; + } + } + // ISBN оригинальной (бумажной) книги. + if("isbn".equals(nameTag)){ + genre_match = xpp.getText().trim(); + if(genre_match.length() > 0){ + viewTxt.append("ISBN:\n"); + text = new SpannableString(genre_match+"\n"); + text.setSpan(new RelativeSizeSpan(1.2f), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + text.setSpan(new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + viewTxt.append(text); + genre_match = ""; + } + } + break; + case XmlPullParser.END_TAG: + nameTag = xpp.getName(); + // авторы и переводчики + if("author".equalsIgnoreCase(nameTag) || "translator".equalsIgnoreCase(nameTag)){ + String str = null; + if("author".equalsIgnoreCase(nameTag)){ + str = getString(R.string.srt_info_book_author_info);//"Автор:\n"; + } + if("translator".equalsIgnoreCase(nameTag)){ + str = getString(R.string.srt_info_book_translator_info);//"Переводчик:\n"; + } + viewTxt.append(str); + str = ""; + if(last_name.length() != 0){ + str = last_name; + last_name = ""; + } + if(first_name.length() != 0){ + str += " "; + str += first_name; + first_name = ""; + } + if(middle_name.length() != 0){ + str += " "; + str += middle_name; + middle_name = ""; + } + if(nickname.length() != 0){ + if(str.length() == 0){ + + str += nickname; + }else{ + str += (" ("); + str += (nickname); + str += (")"); + } + nickname = ""; + } + text = new SpannableString(str+"\n"); + text.setSpan(new RelativeSizeSpan(1.2f), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + text.setSpan(new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + viewTxt.append(text); + + if(home_page.length()> 0){ + text = new SpannableString(home_page+"\n"); + text.setSpan(new RelativeSizeSpan(1.2f), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + text.setSpan(new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + viewTxt.append(text); + home_page = ""; + } + if(email.length() > 0){ + text = new SpannableString(email+"\n"); + text.setSpan(new RelativeSizeSpan(1.2f), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + text.setSpan(new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + viewTxt.append(text); + email = ""; + } + } + // конец заголовка + if("description".equalsIgnoreCase(nameTag)){ + flagDescription = false; + } + nameTag = ""; + break; + } + xpp.next(); + eventType = xpp.getEventType(); + + } + } catch (XmlPullParserException e) { + //return true; + } catch (IOException e) { + //return true; + } + try { + fileRead.close(); + } catch (IOException e) { + //e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. + } + } +} \ No newline at end of file diff --git a/src/com/harasoft/relaunch/FiltersActivity.java b/src/com/harasoft/relaunch/FiltersActivity.java index 1bd920f..13e7da9 100644 --- a/src/com/harasoft/relaunch/FiltersActivity.java +++ b/src/com/harasoft/relaunch/FiltersActivity.java @@ -43,8 +43,7 @@ public class myOnItemSelectedListener implements OnItemSelectedListener { public void onItemSelected(AdapterView parent, View v1, int pos, long row) { if (position >= 0 && position < itemsArray.size()) { - itemsArray.set(position, new String[] { Integer.toString(pos), - itemsArray.get(position)[1] }); + itemsArray.set(position, new String[] { Integer.toString(pos),itemsArray.get(position)[1] }); adapter.notifyDataSetChanged(); } } @@ -78,11 +77,9 @@ public View getView(final int position, View convertView, View v = vi.inflate(R.layout.filters_item, null); Spinner methodSpn = (Spinner) v.findViewById(R.id.filters_method); - ImageButton rmBtn = (ImageButton) v - .findViewById(R.id.filters_delete); + ImageButton rmBtn = (ImageButton) v.findViewById(R.id.filters_delete); Button valBtn = (Button) v.findViewById(R.id.filters_type); - TextView condTxt = (TextView) v - .findViewById(R.id.filters_condition); + TextView condTxt = (TextView) v.findViewById(R.id.filters_condition); final String[] item = itemsArray.get(position); if (item == null) @@ -93,10 +90,10 @@ public View getView(final int position, View convertView, try { spos = Integer.parseInt(item[0]); } catch (NumberFormatException e) { + // } - ArrayAdapter sadapter = ArrayAdapter - .createFromResource(cntx, R.array.filter_values, + ArrayAdapter sadapter = ArrayAdapter.createFromResource(cntx, R.array.filter_values, android.R.layout.simple_spinner_item); sadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); methodSpn.setAdapter(sadapter); @@ -113,45 +110,37 @@ public void onClick(View v) { }); // Set value button - if (spos == app.FLT_SELECT || spos == app.FLT_NEW - || spos == app.FLT_NEW_AND_READING) { + if (spos == app.FLT_SELECT) { valBtn.setText(""); valBtn.setEnabled(false); - } else { + }else if(spos == app.FLT_NEW|| spos == app.FLT_NEW_AND_READING){ + valBtn.setText(""); + valBtn.setEnabled(false); + itemsArray.set(position,new String[] { item[0]," " }); + adapter.notifyDataSetChanged(); + }else{ valBtn.setText(item[1]); valBtn.setEnabled(true); + valBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { - AlertDialog.Builder builder = new AlertDialog.Builder( - cntx); + AlertDialog.Builder builder = new AlertDialog.Builder(cntx); // "Filter value:" - builder.setTitle(getResources().getString( - R.string.jv_filters_value)); + builder.setTitle(getResources().getString(R.string.jv_filters_value)); final EditText input = new EditText(cntx); input.setText(item[1]); builder.setView(input); - // "Ok" - builder.setPositiveButton( - getResources() - .getString(R.string.jv_filters_ok), + builder.setPositiveButton(getResources().getString(R.string.app_ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { - String value = input.getText() - .toString(); + String value = input.getText().toString(); if (value.equals("")) // "Can't be empty!" - Toast.makeText( - cntx, - getResources() - .getString( - R.string.jv_filters_cant_be_empty), - Toast.LENGTH_LONG).show(); + Toast.makeText(cntx,getResources().getString(R.string.jv_filters_cant_be_empty),Toast.LENGTH_LONG).show(); else { - itemsArray.set(position, - new String[] { item[0], - value }); + itemsArray.set(position,new String[] { item[0],value }); adapter.notifyDataSetChanged(); dialog.dismiss(); } @@ -159,21 +148,16 @@ public void onClick(DialogInterface dialog, }); // "Cancel" - builder.setNegativeButton( - getResources().getString( - R.string.jv_filters_cancel), - new DialogInterface.OnClickListener() { + builder.setNegativeButton(getResources().getString(R.string.app_cancel),new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); - builder.show(); } }); - } - + } // Set condition text if (position >= itemsArray.size() - 1) condTxt.setText(""); @@ -215,8 +199,7 @@ public void onClick(View v) { app.writeFile("filters", ReLaunch.FILT_FILE, 0, ":"); // Save and/or flag - SharedPreferences prefs = PreferenceManager - .getDefaultSharedPreferences(getBaseContext()); + SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean("filtersAnd", app.filters_and); editor.commit(); @@ -281,6 +264,6 @@ public void onClick(View v) { @Override protected void onResume() { super.onResume(); - app.generalOnResume(TAG, this); + app.generalOnResume(TAG); } } diff --git a/src/com/harasoft/relaunch/Home.java b/src/com/harasoft/relaunch/Home.java index 66241a1..9a943b3 100644 --- a/src/com/harasoft/relaunch/Home.java +++ b/src/com/harasoft/relaunch/Home.java @@ -1,18 +1,41 @@ package com.harasoft.relaunch; +import java.util.Locale; + import android.app.Activity; import android.app.PendingIntent; import android.content.Intent; +import android.content.SharedPreferences; +import android.content.res.Configuration; import android.os.Bundle; +import android.preference.PreferenceManager; public class Home extends Activity { final String TAG = "Home"; ReLaunchApp app; + @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); + SharedPreferences preferences; + Locale locale; + String lang; + + preferences = PreferenceManager.getDefaultSharedPreferences(this); + lang = preferences.getString("lang", "default"); + if (lang.equals("default")) { + locale = getResources().getConfiguration().locale.getDefault();} + else { + locale = new Locale(lang);} + Locale.setDefault(locale); + Configuration config = new Configuration(); + config.locale = locale; + getBaseContext().getResources().updateConfiguration(config, null); + + N2EpdController.n2MainActivity = this; + app = ((ReLaunchApp) getApplicationContext()); app.RestartIntent = PendingIntent.getActivity(this, 0, getIntent(), getIntent().getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK); diff --git a/src/com/harasoft/relaunch/Home1.java b/src/com/harasoft/relaunch/Home1.java index e462d92..191d1f5 100644 --- a/src/com/harasoft/relaunch/Home1.java +++ b/src/com/harasoft/relaunch/Home1.java @@ -1,9 +1,14 @@ package com.harasoft.relaunch; +import java.util.Locale; + import android.app.Activity; import android.app.PendingIntent; import android.content.Intent; +import android.content.SharedPreferences; +import android.content.res.Configuration; import android.os.Bundle; +import android.preference.PreferenceManager; public class Home1 extends Activity { final String TAG = "Home"; @@ -13,6 +18,23 @@ public class Home1 extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); + SharedPreferences preferences; + Locale locale; + String lang; + + preferences = PreferenceManager.getDefaultSharedPreferences(this); + lang = preferences.getString("lang", "default"); + if (lang.equals("default")) { + locale=getResources().getConfiguration().locale.getDefault();} + else { + locale = new Locale(lang);} + Locale.setDefault(locale); + Configuration config = new Configuration(); + config.locale = locale; + getBaseContext().getResources().updateConfiguration(config, null); + + N2EpdController.n2MainActivity = this; + app = ((ReLaunchApp) getApplicationContext()); app.RestartIntent = PendingIntent.getActivity(this, 0, getIntent(), getIntent().getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK); diff --git a/src/com/harasoft/relaunch/HttpBasicAuthentication.java b/src/com/harasoft/relaunch/HttpBasicAuthentication.java new file mode 100644 index 0000000..444c4f3 --- /dev/null +++ b/src/com/harasoft/relaunch/HttpBasicAuthentication.java @@ -0,0 +1,70 @@ +package com.harasoft.relaunch; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.ProtocolException; +import java.net.URL; + +public class HttpBasicAuthentication { + + private String StrUrl, Username, Password; + + public HttpBasicAuthentication(String strUrl, String username, String password){ + + StrUrl=strUrl; + Username=username; + Password=password; + } + public HttpURLConnection Connect(){ + + HttpURLConnection result; + URL url; + String base64EncodedCredentials; + int responseCode; + + try { + url = new URL(StrUrl); + } catch (MalformedURLException e) { + return null; + } + + try { + result = (HttpURLConnection)url.openConnection(); + } catch (IOException e) { + return null; + } + + + if(!Username.equals("") && !Username.trim().equals("") && !Password.equals("")){ + base64EncodedCredentials = Base64Coder.encodeString(Username + ":" + Password); + result.setRequestProperty("Authorization", "Basic " + base64EncodedCredentials); + try { + result.setRequestMethod("POST"); + } catch (ProtocolException e) { + return null; + } + result.setDoOutput(true); + result.setDoInput(true); + try { + responseCode = result.getResponseCode(); + } catch (IOException e) { + return null; + } + + if (responseCode != HttpURLConnection.HTTP_OK) { + return null; + } + }else{ + result.setReadTimeout(10000); + result.setConnectTimeout(15000); + try { + result.setRequestMethod("GET"); + } catch (ProtocolException e) { + return null; + } + result.setDoInput(true); + } + return result; + } +} \ No newline at end of file diff --git a/src/com/harasoft/relaunch/Library.java b/src/com/harasoft/relaunch/Library.java deleted file mode 100644 index fbeaf4c..0000000 --- a/src/com/harasoft/relaunch/Library.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.harasoft.relaunch; - -import android.app.Activity; -import android.app.PendingIntent; -import android.content.Intent; -import android.os.Bundle; - -public class Library extends Activity { - final String TAG = "Library"; - ReLaunchApp app; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - app = ((ReLaunchApp) getApplicationContext()); - app.RestartIntent = PendingIntent.getActivity(this, 0, getIntent(), - getIntent().getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK); - - Intent intent = new Intent(Library.this, ReLaunch.class); - intent.putExtra("home", false); - intent.putExtra("home1", false); - intent.putExtra("shop", false); - intent.putExtra("library", true); - intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); - startActivityForResult(intent, 0); - } - - @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) { - finish(); - } -} diff --git a/src/com/harasoft/relaunch/ListActions.java b/src/com/harasoft/relaunch/ListActions.java index 1514cbb..53f1eeb 100644 --- a/src/com/harasoft/relaunch/ListActions.java +++ b/src/com/harasoft/relaunch/ListActions.java @@ -1,12 +1,5 @@ package com.harasoft.relaunch; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - import android.app.Activity; import android.app.AlertDialog; import android.content.ActivityNotFoundException; @@ -16,6 +9,8 @@ import android.preference.PreferenceManager; import android.widget.Toast; +import java.util.*; + public class ListActions { String TAG = "ListActions"; List> itemsArray = new ArrayList>(); @@ -73,7 +68,7 @@ public void showMenu(String listName) { createItemsArray(); if (itemsArray.size() > 0) { // exts dirs sorter - final class ExtsComparator implements java.util.Comparator { + final class ExtsComparator implements Comparator { public int compare(String a, String b) { if (a == null && b == null) return 0; @@ -103,15 +98,7 @@ public int compare(String a, String b) { exts = new ArrayList(tkeys); Collections.sort(exts, new ExtsComparator()); } - // known dirs - ArrayList dirs = new ArrayList(); - if (prefs.getBoolean("hideKnownDirs", false)) { - String[] home_dirs = prefs.getString("startDir", - "/sdcard,/media/My Files").split("\\,"); - for (int i = 0; i < home_dirs.length; i++) - dirs.add(home_dirs[i]); - Collections.sort(dirs, new ExtsComparator()); - } + final CharSequence[] lnames = new CharSequence[itemsArray.size()]; for (int i = 0; i < itemsArray.size(); i++) { HashMap item = itemsArray.get(i); @@ -149,7 +136,7 @@ public void onClick(DialogInterface dialog, int i) { dialog.dismiss(); } }); - builder.setNegativeButton(app.getResources().getString(R.string.jv_results_menu_button), + builder.setNegativeButton(app.getResources().getString(R.string.app_cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -174,12 +161,9 @@ public void runItem(String listName, int position) { String fullName = item.get("dname") + "/" + item.get("fname"); if (item.get("type").equals("dir")) { Intent intent = new Intent(act, ReLaunch.class); - intent.putExtra("dirviewer", false); intent.putExtra("start_dir", fullName); intent.putExtra("home", ReLaunch.useHome); intent.putExtra("home1", ReLaunch.useHome1); - intent.putExtra("shop", ReLaunch.useShop); - intent.putExtra("library", ReLaunch.useLibrary); act.startActivityForResult(intent, ReLaunch.DIR_ACT); } else { String fileName = item.get("fname"); diff --git a/src/com/harasoft/relaunch/Main.java b/src/com/harasoft/relaunch/Main.java index 44aad42..fe6a9c6 100644 --- a/src/com/harasoft/relaunch/Main.java +++ b/src/com/harasoft/relaunch/Main.java @@ -3,16 +3,59 @@ import android.app.Activity; import android.app.PendingIntent; import android.content.Intent; +import android.content.SharedPreferences; +import android.content.res.Configuration; import android.os.Bundle; +import android.preference.PreferenceManager; + +import java.util.Locale; + +//import android.app.Application; public class Main extends Activity { final String TAG = "Main"; ReLaunchApp app; + private Locale locale; + + @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); + SharedPreferences preferences; + String lang; + String tmp_startDir; + + preferences = PreferenceManager.getDefaultSharedPreferences(this); + lang = preferences.getString("lang", "default"); + if (lang.equals("default")) { + locale = getResources().getConfiguration().locale.getDefault();} + else { + locale = new Locale(lang);} + Locale.setDefault(locale); + Configuration config = new Configuration(); + config.locale = locale; + getBaseContext().getResources().updateConfiguration(config, null); + + if(N2DeviceInfo.EINK_ONYX){ + tmp_startDir = preferences.getString("startDir", "/sdcard,/media/My Files"); + + if(tmp_startDir.equals("/sdcard,/media/My Files")){ + SharedPreferences.Editor editor = preferences.edit(); + editor.putString("startDir","/mnt/storage"); + editor.commit(); + } + + tmp_startDir = preferences.getString("searchRoot", "/sdcard"); + if(tmp_startDir.equals("/sdcard")){ + SharedPreferences.Editor editor = preferences.edit(); + editor.putString("searchRoot","/mnt/storage"); + editor.commit(); + } + } + N2EpdController.n2MainActivity = this; + app = ((ReLaunchApp) getApplicationContext()); app.RestartIntent = PendingIntent.getActivity(this, 0, getIntent(), getIntent().getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK); @@ -30,4 +73,15 @@ public void onCreate(Bundle savedInstanceState) { protected void onActivityResult(int requestCode, int resultCode, Intent data) { finish(); } + @Override + public void onConfigurationChanged(Configuration newConfig) + { + super.onConfigurationChanged(newConfig); + + Locale.setDefault(locale); + Configuration config = new Configuration(); + config.locale = locale; + getBaseContext().getResources().updateConfiguration(config, null); + } + } diff --git a/src/com/harasoft/relaunch/DeviceInfo.java b/src/com/harasoft/relaunch/N2DeviceInfo.java similarity index 68% rename from src/com/harasoft/relaunch/DeviceInfo.java rename to src/com/harasoft/relaunch/N2DeviceInfo.java index 7e27a36..8c2ad0f 100644 --- a/src/com/harasoft/relaunch/DeviceInfo.java +++ b/src/com/harasoft/relaunch/N2DeviceInfo.java @@ -8,7 +8,7 @@ import android.os.Build; import android.util.Log; -public class DeviceInfo { +public class N2DeviceInfo { public final static String MANUFACTURER; public final static String MODEL; @@ -18,11 +18,14 @@ public class DeviceInfo { public final static boolean EINK_SCREEN_UPDATE_MODES_SUPPORTED; public final static boolean NOOK_NAVIGATION_KEYS; public final static boolean EINK_NOOK; + public final static boolean EINK_NOOK_120; + public final static boolean EINK_ONYX; public final static boolean FORCE_LIGHT_THEME; public final static boolean EINK_SONY; public final static boolean SONY_NAVIGATION_KEYS; public final static boolean USE_CUSTOM_TOAST; public final static boolean AMOLED_SCREEN; + //public static SharedPreferences preferences; static { MANUFACTURER = getBuildField("MANUFACTURER"); @@ -36,10 +39,13 @@ public class DeviceInfo { && (MODEL.toLowerCase().startsWith("gt-i")); // AMOLED screens: // GT-IXXXX EINK_NOOK = MANUFACTURER.toLowerCase().contentEquals("barnesandnoble") - && (MODEL.contentEquals("NOOK")|| MODEL.contentEquals("BNRV300") || MODEL.contentEquals("BNRV350")) + && (MODEL.contentEquals("NOOK") || MODEL.contentEquals("BNRV300") || MODEL.contentEquals("BNRV350")) && DEVICE.toLowerCase().contentEquals("zoom2"); - EINK_SONY = MANUFACTURER.toLowerCase().contentEquals("sony") - && MODEL.contentEquals("PRS-T1"); + EINK_NOOK_120 = EINK_NOOK && (MODEL.contentEquals("BNRV300") || MODEL.contentEquals("BNRV350")); + EINK_SONY = MANUFACTURER.toLowerCase().contentEquals("sony")&& MODEL.contentEquals("PRS-T1"); + EINK_ONYX = (MODEL.toLowerCase().contentEquals("i63sml_hd") && DEVICE.toLowerCase().contentEquals("i63sml_hd")) || + (MODEL.toLowerCase().contentEquals("i63ml_hd") && DEVICE.toLowerCase().contentEquals("i63ml_hd")) || + (MODEL.toLowerCase().contentEquals("i63sl_hd") && DEVICE.toLowerCase().contentEquals("i63sl_hd")); EINK_SCREEN = EINK_SONY || EINK_NOOK; // TODO: set to true for eink // devices like Nook Touch @@ -57,7 +63,7 @@ private static String getBuildField(String fieldName) { try { return (String) Build.class.getField(fieldName).get(null); } catch (Exception e) { - Log.d("cr3", "Exception while trying to check Build." + fieldName); + Log.d("relaunch", "Exception while trying to check Build." + fieldName); return ""; } } diff --git a/src/com/harasoft/relaunch/N2EpdController.java b/src/com/harasoft/relaunch/N2EpdController.java index 56104b2..a1b149a 100644 --- a/src/com/harasoft/relaunch/N2EpdController.java +++ b/src/com/harasoft/relaunch/N2EpdController.java @@ -5,9 +5,10 @@ * http://http://sourceforge.net/projects/crengine/ */ -import java.lang.reflect.Method; -import java.lang.reflect.Constructor; +import android.app.Activity; +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; /** * Nook Touch EPD controller interface wrapper. This class is created by * DairyKnight for Nook Touch screen support in FBReaderJ. @@ -42,25 +43,34 @@ public class N2EpdController { private static Method mtSetRegion = null; private static Constructor RegionParamsConstructor = null; + private static Constructor EpdControllerConstructors[] = null; + public static Activity n2MainActivity = null; + private static Object mEpdController = null; private static Object[] enumsWave = null; private static Object[] enumsRegion = null; private static Object[] enumsMode = null; static { - if (DeviceInfo.EINK_NOOK) { + if (N2DeviceInfo.EINK_NOOK) { try { Class clEpdController = Class .forName("android.hardware.EpdController"); - Class clEpdControllerWave = Class - .forName("android.hardware.EpdController$Wave"); + Class clEpdControllerWave; + if (N2DeviceInfo.EINK_NOOK_120) + clEpdControllerWave = Class.forName("android.hardware.EpdRegionParams$Wave"); + else + clEpdControllerWave = Class.forName("android.hardware.EpdController$Wave"); Class clEpdControllerMode = Class .forName("android.hardware.EpdController$Mode"); Class clEpdControllerRegion = Class .forName("android.hardware.EpdController$Region"); - Class clEpdControllerRegionParams = Class - .forName("android.hardware.EpdController$RegionParams"); + Class clEpdControllerRegionParams; + if (N2DeviceInfo.EINK_NOOK_120) + clEpdControllerRegionParams = Class.forName("android.hardware.EpdRegionParams"); + else + clEpdControllerRegionParams = Class.forName("android.hardware.EpdController$RegionParams"); enumsWave = clEpdControllerWave.getEnumConstants(); @@ -68,9 +78,6 @@ public class N2EpdController { enumsRegion = clEpdControllerRegion.getEnumConstants(); - // mtSetRegion = clEpdController.getMethod("setRegion", - // String.class, clEpdControllerRegion, View.class, - // clEpdControllerWave, clEpdControllerMode); RegionParamsConstructor = clEpdControllerRegionParams .getConstructor(new Class[] { Integer.TYPE, Integer.TYPE, Integer.TYPE, Integer.TYPE, @@ -78,7 +85,8 @@ public class N2EpdController { mtSetRegion = clEpdController.getMethod("setRegion", String.class, clEpdControllerRegion, clEpdControllerRegionParams, clEpdControllerMode); - + if (N2DeviceInfo.EINK_NOOK_120) + EpdControllerConstructors = clEpdController.getConstructors(); strN2EpdInit += "Ok!"; } catch (Exception e) { System.err.println("Failed to init refresh EPD"); @@ -89,17 +97,15 @@ public class N2EpdController { } } - // public static void setMode(int region, int wave, int mode, View view) { public static void setMode(int region, int wave, int mode) { if (mtSetRegion != null) { try { + if (N2DeviceInfo.EINK_NOOK_120 && mEpdController == null) + mEpdController = EpdControllerConstructors[0].newInstance(new Object[] { n2MainActivity }); Object regionParams = RegionParamsConstructor .newInstance(new Object[] { 0, 0, 600, 800, enumsWave[wave] }); - // mtSetRegion.invoke(null, "CoolReader", enumsRegion[region], - // view, enumsWave[wave], enumsMode[mode]); - mtSetRegion.invoke(null, "ReLaunch", enumsRegion[region], - regionParams, enumsMode[mode]); + mtSetRegion.invoke(mEpdController, "ReLaunch", enumsRegion[region], regionParams, enumsMode[mode]); } catch (Exception e) { System.err.println("Failed: SetMode"); System.err.println(e.toString()); diff --git a/src/com/harasoft/relaunch/OPDSActivity.java b/src/com/harasoft/relaunch/OPDSActivity.java new file mode 100644 index 0000000..dfa50ca --- /dev/null +++ b/src/com/harasoft/relaunch/OPDSActivity.java @@ -0,0 +1,1402 @@ +package com.harasoft.relaunch; + +import android.app.Activity; +import android.app.AlertDialog; +import android.app.Dialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.res.Configuration; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.graphics.drawable.BitmapDrawable; +import android.graphics.drawable.Drawable; +import android.os.AsyncTask; +import android.os.Bundle; +import android.os.SystemClock; +import android.preference.PreferenceManager; +import android.text.Html; +import android.util.TypedValue; +import android.view.*; +import android.widget.*; +import ebook.EBook; +import ebook.parser.InstantParser; +import ebook.parser.Parser; +import org.xmlpull.v1.XmlPullParser; +import org.xmlpull.v1.XmlPullParserException; +import org.xmlpull.v1.XmlPullParserFactory; + +import java.io.*; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Locale; + +public class OPDSActivity extends Activity { + public ArrayList names = new ArrayList(); + public ArrayList books = new ArrayList(); + public ArrayList names_tmp = new ArrayList(); + public ArrayList books_tmp = new ArrayList(); + public ArrayList list_book_steps = new ArrayList(); + public ArrayList list_path_steps = new ArrayList(); + String_Search_Tag search_site; + String login_opds; + String pass_opds; + int eventType; + XmlPullParser xpp; + private boolean flag_book = false; + public static String URLstr; + public static String URLdomen = ""; + public static String URLtemp = ""; + public String OPDS_Path_Download = "/sdcard/"; + //private SharedPreferences prefs; + Activity test; + ReLaunchApp app; + int size_icon; + int size_text; + int size_text2; + OPDS_adapter adapter; + int count_login = 0; + boolean addSView = true; + + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + if(!ReLaunch.haveNetworkConnection(getApplicationContext())){ + app.showToast(getString(R.string.srt_dbactivity_no_inet)); + finish(); + }else{ + app = ((ReLaunchApp) getApplicationContext()); + if (app != null) { + app.setFullScreenIfNecessary(this); + } + SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); + size_icon = Integer.parseInt(prefs.getString("firstLineIconSizePx", "48")); + size_text = Integer.parseInt(prefs.getString("firstLineFontSizePx", "20")); + size_text2 = Integer.parseInt(prefs.getString("secondLineFontSizePx", "16")); + + setContentView(R.layout.prefs_main); + ((ImageView) findViewById(R.id.imageView1)).setImageResource(R.drawable.ci_books); + + N2EpdController.n2MainActivity = this; + test = this; + Locale locale; + String lang; + lang = prefs.getString("lang", "default"); + if (lang.equals("default")) { + locale = getResources().getConfiguration().locale.getDefault(); + }else { + locale = new Locale(lang); + } + Locale.setDefault(locale); + Configuration config = new Configuration(); + config.locale = locale; + getBaseContext().getResources().updateConfiguration(config, null); + login_opds = prefs.getString("OPDS login", ""); + pass_opds = prefs.getString("OPDS password", ""); + if(N2DeviceInfo.EINK_ONYX){ + OPDS_Path_Download = "/mnt/storage"; + } + String OPDSPath; + String OPDSLocalPath; + final Intent data = getIntent(); + if (data.getExtras() == null) { + setResult(Activity.RESULT_CANCELED); + finish(); + } + OPDSPath = data.getExtras().getString("opdscat"); + login_opds = data.getExtras().getString("login"); + pass_opds = data.getExtras().getString("password"); + + OPDSLocalPath = prefs.getString("Local folder OPDS", "none").trim(); + if(OPDSPath == null || OPDSPath.equals("none")){ + app.showToast(getString(R.string.srt_opdsactivity_err_url)); + finish(); + } + URLstr = OPDSPath; + if(!OPDSLocalPath.equals("none")){ + File folder_check; + folder_check = new File(OPDSLocalPath); + if (!folder_check.exists()) { + if(!folder_check.mkdirs()){ + app.showToast(getString(R.string.srt_opdsactivity_err_folder));//"Невозможно создать локальный каталог или неверный путь"); + finish(); + } + } + OPDS_Path_Download = OPDSLocalPath; + } + + URLdomen = URLstr.substring(0,URLstr.lastIndexOf("/")); + if(!(URLdomen.contains("http://"))){ + app.showToast(getString(R.string.srt_opdsactivity_err_url));//"Неполный адрес каталога"); + finish(); + } + final ListView lvMain = (ListView) findViewById(android.R.id.list); + + // создаем адаптер + adapter = new OPDS_adapter(this, names); + lvMain.setAdapter(adapter); + lvMain.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView parent, View itemClicked, int position, long id) { + String url_next; + if(names.get(position).imgHeader.equals("2")){ + try { + showBookInfo(position); + } catch (MalformedURLException e) { + //e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. + } + }else if(names.get(position).header.equalsIgnoreCase("Моя полка") || names.get(position).subHeader.equalsIgnoreCase("Вход для зарегистрированных пользователей")){ + url_next = names.get(position).urllink; + + + if(load_opds(url_next, names_tmp, books_tmp, login_opds, pass_opds)){ + names_tmp.clear(); + books_tmp.clear(); + }else{ + count_login = 1; + list_path_steps.add(url_next); + URLtemp = url_next; + names.clear(); + books.clear(); + names.addAll(names_tmp); + books.addAll(books_tmp); + names_tmp.clear(); + books_tmp.clear(); + adapter.notifyDataSetChanged(); + lvMain.setSelection(0); + } + }else{ + url_next = names.get(position).urllink; + + boolean start_pos = true; + if(names.get(position).header.equalsIgnoreCase("Далее")){ + list_book_steps.add(URLtemp); + }else if(names.get(position).header.equalsIgnoreCase("Назад")){ + list_book_steps.remove(list_book_steps.size()-1); + start_pos = false; + }else { + list_path_steps.add(url_next); + count_login ++; + } + + if(load_opds(url_next, names_tmp, books_tmp, login_opds, pass_opds)){ + names_tmp.clear(); + books_tmp.clear(); + if(names.get(position).header.equalsIgnoreCase("Далее")){ + list_book_steps.remove(list_book_steps.size()-1); + }else if(names.get(position).header.equalsIgnoreCase("Назад")){ + list_book_steps.add(URLtemp); + }else { + list_path_steps.remove(list_path_steps.size()-1); + } + }else{ + URLtemp = url_next; + names.clear(); + books.clear(); + names.addAll(names_tmp); + books.addAll(books_tmp); + names_tmp.clear(); + books_tmp.clear(); + adapter.notifyDataSetChanged(); + if(start_pos){ + lvMain.setSelection(0); + }else{ + lvMain.setSelection(names.size()-1); + } + } + } + + } + }); + + lvMain.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { + @Override + public boolean onItemLongClick(AdapterView parent, View itemClicked, int position, long id) { + if(flag_book){ + AlertDialog dialog = DowloadDialog(test, position); + dialog.show(); + }else{ + AlertDialog dialog = ViewDialog(test, position); + dialog.show(); + } + return false; + } + }); + //=========================================================================== + if (prefs.getBoolean("customScroll", app.customScrollDef)) { + if (addSView) { + int scrollW; + try { + scrollW = Integer.parseInt(prefs.getString("scrollWidth", + "25")); + } catch (NumberFormatException e) { + scrollW = 25; + } + + LinearLayout ll = (LinearLayout) findViewById(R.id.LLlist); + final SView sv = new SView(getBaseContext()); + LinearLayout.LayoutParams pars = new LinearLayout.LayoutParams( + scrollW, ViewGroup.LayoutParams.FILL_PARENT, 2f); + sv.setLayoutParams(pars); + ll.addView(sv); + lvMain.setOnScrollListener(new AbsListView.OnScrollListener() { + public void onScroll(AbsListView view, + int firstVisibleItem, int visibleItemCount, + int totalItemCount) { + sv.total = totalItemCount; + sv.count = visibleItemCount; + sv.first = firstVisibleItem; + EinkScreen.PrepareController(null, false); + sv.invalidate(); + } + + public void onScrollStateChanged(AbsListView view, + int scrollState) { + } + }); + addSView = false; + } + } else { + lvMain.setOnScrollListener(new AbsListView.OnScrollListener() { + public void onScroll(AbsListView view, int firstVisibleItem, + int visibleItemCount, int totalItemCount) { + EinkScreen.PrepareController(null, false); + } + + public void onScrollStateChanged(AbsListView view, + int scrollState) { + } + }); + } + //============================================================================ + ImageButton back_btn = (ImageButton) findViewById(R.id.back_btn); + back_btn.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) { + String url_next; + + if (list_path_steps.size() > 1) { + url_next = list_path_steps.get(list_path_steps.size() - 2); + } else { + url_next = URLstr; + } + + if (load_opds(url_next, names_tmp, books_tmp, login_opds, pass_opds)) { + names_tmp.clear(); + books_tmp.clear(); + } else { + if (list_path_steps.size() > 1) { + list_path_steps.remove(list_path_steps.size() - 1); + if (count_login > 0) + count_login--; + } else { + list_path_steps.clear(); + count_login = 0; + login_opds = ""; + pass_opds = ""; + } + names.clear(); + books.clear(); + names.addAll(names_tmp); + books.addAll(books_tmp); + names_tmp.clear(); + books_tmp.clear(); + list_book_steps.clear(); + adapter.notifyDataSetChanged(); + } + } + }); + back_btn.setOnLongClickListener(new View.OnLongClickListener() { + public boolean onLongClick(View v) { + names.clear(); + books.clear(); + list_book_steps.clear(); + list_path_steps.clear(); + names_tmp.clear(); + books_tmp.clear(); + count_login = 0; + login_opds = ""; + pass_opds = ""; + finish(); + return true; + } + }); + ImageButton bu = (ImageButton) findViewById(R.id.btn_scrollup); + bu.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) { + if (N2DeviceInfo.EINK_NOOK) { + MotionEvent ev; + ev = MotionEvent.obtain(SystemClock.uptimeMillis(), + SystemClock.uptimeMillis(), + MotionEvent.ACTION_DOWN, 200, 100, 0); + lvMain.dispatchTouchEvent(ev); + ev = MotionEvent.obtain(SystemClock.uptimeMillis(), + SystemClock.uptimeMillis() + 100, + MotionEvent.ACTION_MOVE, 200, 200, 0); + lvMain.dispatchTouchEvent(ev); + SystemClock.sleep(100); + ev = MotionEvent.obtain(SystemClock.uptimeMillis(), + SystemClock.uptimeMillis(), + MotionEvent.ACTION_UP, 200, 200, 0); + lvMain.dispatchTouchEvent(ev); + } else { + int first = lvMain.getFirstVisiblePosition(); + int visible = lvMain.getLastVisiblePosition() + - lvMain.getFirstVisiblePosition() + 1; + first -= visible; + if (first < 0) + first = 0; + final int finfirst = first; + lvMain.clearFocus(); + lvMain.post(new Runnable() { + + public void run() { + lvMain.setSelection(finfirst); + } + }); + } + } + }); + + ImageButton bd = (ImageButton) findViewById(R.id.btn_scrolldown); + bd.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) { + if (N2DeviceInfo.EINK_NOOK) { + MotionEvent ev; + ev = MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis(),MotionEvent.ACTION_DOWN, 200, 200, 0); + lvMain.dispatchTouchEvent(ev); + ev = MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis() + 100,MotionEvent.ACTION_MOVE, 200, 100, 0); + lvMain.dispatchTouchEvent(ev); + SystemClock.sleep(100); + ev = MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),MotionEvent.ACTION_UP, 200, 100, 0); + lvMain.dispatchTouchEvent(ev); + } else { + int total = lvMain.getCount(); + int last = lvMain.getLastVisiblePosition(); + if (total == last + 1) + return; + int target = last + 1; + if (target > (total - 1)) + target = total - 1; + final int ftarget = target; + lvMain.clearFocus(); + lvMain.post(new Runnable() { + public void run() { + lvMain.setSelection(ftarget); + } + }); + } + + } + }); + + if(load_opds(URLstr, names_tmp, books_tmp, login_opds, pass_opds)){ + names.clear(); + books.clear(); + list_book_steps.clear(); + list_path_steps.clear(); + names_tmp.clear(); + books_tmp.clear(); + finish(); + }else{ + names.clear(); + books.clear(); + names.addAll(names_tmp); + books.addAll(books_tmp); + names_tmp.clear(); + books_tmp.clear(); + adapter.notifyDataSetChanged(); + } + } + } + //=========================================================================================================== + private boolean load_opds(String URLstr, ArrayList names_tmp, ArrayList books_tmp, String login, String pass){ + InputStream inputStream1; + InputStreamReader in; + + try { + HttpURLConnection conn; + conn = (new HttpBasicAuthentication(URLstr, login, pass)).Connect(); + if(conn == null){ + return true; + }else { + inputStream1 = conn.getInputStream(); + } + + } catch (MalformedURLException e) { + app.showToast(getString(R.string.srt_dbactivity_err_con_dropbox)); + return true; + } catch (IOException e) { + app.showToast(getString(R.string.srt_dbactivity_err_con_dropbox)); + return true; + } + + try { + XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); + factory.setNamespaceAware(true); + xpp = factory.newPullParser(); + in = new InputStreamReader(inputStream1); + xpp.setInput(in); + eventType = xpp.getEventType(); + String_Link_Tag tmp_link; + String link_next = ""; + String url_pref; + + if(list_book_steps.size() != 0){ + names_tmp.add(new Item("Назад", "",list_book_steps.get(list_book_steps.size()-1),"up", null)); + books_tmp.add(new BookInfo(null,null,"","","",null)); + } + while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) { + switch (xpp.getEventType()) { + case XmlPullParser.START_TAG: + if(xpp.getName().equalsIgnoreCase("title")){ + ((EditText) findViewById(R.id.prefernces_title)).setText(Title_Tag(xpp)); + } + if(xpp.getName().equalsIgnoreCase("entry")){ + if(Entry_Tag(xpp, names_tmp, books_tmp)){ + return true; + } + } + if(xpp.getName().equalsIgnoreCase("link")){ + tmp_link = Link_Tag(xpp); + if(tmp_link.rel != null){ + if(!(tmp_link.href.contains("http://"))){ + url_pref = URLdomen; + }else{ + url_pref = ""; + } + if(tmp_link.rel.equalsIgnoreCase("next")){ + link_next = url_pref + tmp_link.href; + } + if(tmp_link.rel.equals("search") && tmp_link.type.equals("application/atom+xml")){ + search_site =new String_Search_Tag("Search", url_pref + tmp_link.href); + } + } + } + break; + } + xpp.next(); + } + if(link_next.length() != 0){ + names_tmp.add(new Item("ДАЛЕЕ", "",link_next,"down", null)); + } + } catch (XmlPullParserException e) { + return true; + } catch (IOException e) { + return true; + } + try { + in.close(); + } catch (IOException e) { + // + } + names_tmp.trimToSize(); + books_tmp.trimToSize(); + return false; + } + //==================================================================================== + private void showBookInfo(int count_book) throws MalformedURLException { + + final int book_numbe = count_book; + + final Dialog dialog = new Dialog(this, android.R.style.Theme_Light_NoTitleBar_Fullscreen); + dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE); + dialog.setContentView(R.layout.bookinfo); + + ((ImageView) dialog.findViewById(R.id.book_icon)).setImageResource(R.drawable.book); + ImageView img = (ImageView) dialog.findViewById(R.id.cover); + + if(books.get(count_book).url_cover != null && books.get(count_book).url_cover.length() != 0){ + DownloadImageTask downloadImage = new DownloadImageTask(img, books.get(count_book).url_cover); + downloadImage.execute(); + } + img.setImageResource(R.drawable.book); + img.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + AlertDialog dialog = DowloadDialog(test, book_numbe); + dialog.show(); + } + }); + // ================= название книги ======================= + if(books.get(count_book).book_name != null) + ((TextView) dialog.findViewById(R.id.tvTitle)).setText(books.get(count_book).book_name); + + //==================== бред про книгу =========================== + if(books.get(count_book).book_annotation != null) + ((TextView) dialog.findViewById(R.id.tvAnnotation)).setText(books.get(count_book).book_annotation); + + // ================== авторы книги ========================= + if(books.get(count_book).book_authors != null){ + ListView lv = (ListView) dialog.findViewById(R.id.authors); + + lv.setDivider(null); + final int count_author; + count_author = books.get(count_book).book_authors.size(); + final String[] authors = new String[count_author]; + for (int i = 0; i < count_author; i++) { + authors[i] = books.get(count_book).book_authors.get(i); + } + + final ArrayAdapter lvAdapter = new ArrayAdapter(getApplicationContext(), R.layout.simple_list_item_1, authors); + lv.setAdapter(lvAdapter); + } + ///====================== серия книги ========================================== + if(books.get(count_book).book_series != null){ + ((TextView) dialog.findViewById(R.id.tvSeries)).setText(books.get(count_book).book_series);} + //================================== заголовок окна =========================== + if(books.get(count_book).book_name != null) + ((TextView) dialog.findViewById(R.id.book_title)).setText(getString(R.string.str_book_info)); + + ImageButton btn = (ImageButton) dialog.findViewById(R.id.btnExit); + btn.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) { + dialog.dismiss(); + } + }); + + dialog.show(); + } + //============================================================================================================ + private class BookInfo { + String url_cover = null; + ArrayList book_authors = null; + String book_series = null; + String book_name = null; + String book_annotation = null; + ArrayList book_link = null; + + BookInfo(String uc, ArrayList ba, String bs, String bn, String ban, ArrayList bl){ + url_cover = uc; + book_authors=ba; + book_series = bs; + book_name = bn; + book_annotation = ban; + book_link = bl; + } + } + //============================================================================================= + public Bitmap getImageBitmap(String url, int type_image) { + Bitmap bm = null; + Bitmap cover = null; + int COVER_MAX_W = 0; + if(type_image == 1) + COVER_MAX_W = 280; + if(type_image == 2) + COVER_MAX_W = 48; + + Drawable image = ImageOperations(url); + if (image != null) + bm = ((BitmapDrawable)image).getBitmap(); + if (bm != null) { + int width = Math.min(COVER_MAX_W, bm.getWidth()); + int height = width * bm.getHeight() /bm.getWidth(); + cover = Bitmap.createScaledBitmap(bm, width, height, true); + } + return cover; + } + //================================================================================================= + private Drawable ImageOperations(String url1) { + try { + InputStream is = (InputStream) new URL(url1).getContent(); + //Drawable d = Drawable.createFromStream(is, "src"); + return Drawable.createFromStream(is, "src"); + } catch (MalformedURLException e) { + e.printStackTrace(); + return null; + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + //============================================================================ + private class BookLink { + String url_type = null; + String booklink = null; + + BookLink(String ut,String l){ + url_type = ut; + booklink = l; + } + } + + private AlertDialog DowloadDialog(Activity activity, int item){ + final int book_item = item; + final ArrayList bookItem = books.get(item).book_link; + int count_url = bookItem.size(); + final String[] list_url = new String[count_url]; + + for(int i=0; i|]","_"); + //namefile = namefile.replaceAll(":\\/*?","_"); + namefile = namefile+"."+ bookItem.get(item).url_type; + + DownloadTask downloadFile = new DownloadTask(getBaseContext(),namefile,url); + downloadFile.execute(); + } + }); + builder.setCancelable(true); + builder.setPositiveButton(getResources().getString(R.string.app_cancel), new DialogInterface.OnClickListener() { // Кнопка ОК + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); // Отпускает диалоговое окно + } + }); + + return builder.create(); + } + private AlertDialog ViewDialog(Activity activity, int item){ + int count_url = names.get(item).list_link.size(); + final int numbe_item = item; + String[] list_url = new String[count_url]; + + AlertDialog.Builder builder = new AlertDialog.Builder(activity); + builder.setTitle("Перейти"); + + if(count_url != 0){ + for(int i=0; i { + + private Context context; + private String name_file; + private String strUrl; + + public DownloadTask(Context context, String namefile, String url) { + this.context = context; + this.name_file = namefile; + this.strUrl = url; + } + + @Override + protected String doInBackground(String... sUrl) { + + InputStream input = null; + OutputStream output = null; + HttpURLConnection connection = null; + String base64EncodedCredentials; + + try { + URL url = new URL(strUrl); + + try { + connection = (HttpURLConnection) url.openConnection(); + } catch (IOException e) { + return "Невозможно установить Интернет-соединение с источником данных"; + } + + if(login_opds != null && pass_opds != null && !login_opds.equals("") && !pass_opds.equals("")){ + base64EncodedCredentials = Base64Coder.encodeString(login_opds + ":" + pass_opds); + connection.setRequestProperty("Authorization", "Basic " + base64EncodedCredentials); + } + + connection.connect(); + + // expect HTTP 200 OK, so we don't mistakenly save error report + // instead of the file + if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) + return "Server returned HTTP " + connection.getResponseCode() + " " + connection.getResponseMessage(); + + // download the file + input = connection.getInputStream(); + + output = new FileOutputStream(OPDS_Path_Download +"/" + name_file); + + byte data[] = new byte[4096]; + int count; + while ((count = input.read(data)) != -1) { + // allow canceling with back button + if (isCancelled()) + return null; + // publishing the progress.... + output.write(data, 0, count); + } + } catch (Exception e) { + return e.toString(); + } finally { + try { + if (output != null) + output.close(); + if (input != null) + input.close(); + } + catch (IOException ignored) { } + + if (connection != null) + connection.disconnect(); + } + return null; + } + + @Override + protected void onPostExecute(String result) { + if (result != null) + Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show(); + else{ + Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show(); + if (name_file.endsWith("fb2") || name_file.endsWith("fb2.zip") || name_file.endsWith("epub")) { + Parser parser = new InstantParser(); + EBook eBook = parser.parse(OPDS_Path_Download + File.separator + name_file, true); + if (eBook.isOk) { + String fileMoveDir = ""; + if (eBook.authors.size() > 0) { + // проверить/создать папку по имени автора + String author = ""; + if (eBook.authors.get(0).lastName != null){ + author += eBook.authors.get(0).lastName;//; + } + if (eBook.authors.get(0).firstName != null){ + if (eBook.authors.get(0).firstName.length() > 0){ + author += " " + eBook.authors.get(0).firstName; + } + } + if (eBook.authors.get(0).middleName != null){ + if (eBook.authors.get(0).middleName.length() > 0){ + author += " " + eBook.authors.get(0).middleName; + } + } + author = author.trim(); + // замена недопустимых файлов + author = author.replaceAll("[\\\\/:*?\"<>|]", "_"); + + fileMoveDir = OPDS_Path_Download + File.separator + author + File.separator; + File newDir = new File(fileMoveDir); + if(!newDir.isDirectory()){ + if (!app.createDir(fileMoveDir)){ + return; + } + } + if (eBook.sequenceName != null && eBook.sequenceName.length() != 0) { + // проверить/создать папку серии + String sequenceN = eBook.sequenceName.trim(); + sequenceN = sequenceN.replaceAll("[\\\\/:*?\"<>|]", "_"); + newDir = new File(fileMoveDir + sequenceN + File.separator); + if(!newDir.isDirectory()){ + if (app.createDir(fileMoveDir + sequenceN + File.separator)){ + fileMoveDir += sequenceN + File.separator; + } + }else{ + fileMoveDir += sequenceN + File.separator; + } + } + } + app.moveFile(OPDS_Path_Download + File.separator + name_file, fileMoveDir + File.separator + name_file); + } + } + } + } + + } + + private class String_Link_Tag{ + String href=null; + String rel=null; + String type=null; + String title=null; + + String_Link_Tag(String h, String r, String t, String i){ + href = h; + rel = r; + type = t; + title = i; + } + } + + private String_Link_Tag Link_Tag(XmlPullParser xpp){ + String href = null; + String rel1 = null; + String type=null; + String title=null; + + String attr_val; + String attr_name; + try { + if(xpp.getEventType() == XmlPullParser.START_TAG) { + if(xpp.getAttributeCount()>0) + for (int i = 0; i < xpp.getAttributeCount(); i++) { + attr_name = xpp.getAttributeName(i); + attr_val = xpp.getAttributeValue(i); + if(attr_name.equalsIgnoreCase("href")) + href = attr_val; + else if(attr_name.equalsIgnoreCase("rel")) + rel1 = attr_val; + else if(attr_name.equalsIgnoreCase("type")) + type = attr_val; + else if(attr_name.equalsIgnoreCase("title")) + title = attr_val; + } + } + do { + xpp.next(); + } while (xpp.getEventType() != XmlPullParser.END_TAG); + } catch (XmlPullParserException e) { + return null; + }catch (IOException e) { + return null; + } + return (new String_Link_Tag(href, rel1, type, title)); + } + + private class String_Author_Tag{ + String name=null; + String uri=null; + + String_Author_Tag(String n, String u){ + name = n; + uri = u; + } + } + + private String_Author_Tag Author_Tag(XmlPullParser xpp){ + String name = null; + String uri = null; + + try { + while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) { + switch (xpp.getEventType()) { + case XmlPullParser.START_TAG: + if(xpp.getName().equalsIgnoreCase("name")) { + name = Name_Tag(xpp); + if (name != null) { + name = name.trim(); + } + } + if(xpp.getName().equalsIgnoreCase("uri")) { + uri = Uri_Tag(xpp); + if (uri != null) { + uri = uri.trim(); + } + } + break; + case XmlPullParser.END_TAG: + if(xpp.getName().equalsIgnoreCase("author")) + return (new String_Author_Tag(name, uri)); + break; + default: + break; + } + xpp.next(); + } + } catch (XmlPullParserException e) { + return null; + } catch (IOException e) { + return null; + } + return null; + } + + private String Title_Tag(XmlPullParser xpp){ + String title = null; + try { + while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) { + switch (xpp.getEventType()) { + case XmlPullParser.TEXT: + + title = xpp.getText(); + break; + case XmlPullParser.END_TAG: + if(xpp.getName().equalsIgnoreCase("title")) + return title; + break; + + default: + break; + } + xpp.next(); + } + } catch (XmlPullParserException e) { + return null; + } catch (IOException e) { + return null; + } + return null; + } + private class String_Category_Tag{ + String term=null; + String label=null; + + String_Category_Tag(String t, String l){ + term = t; + label = l; + } + } + private String_Category_Tag Category_Tag(XmlPullParser xpp){ + String term = null; + String label = null; + + String attr_val; + String attr_name; + try { + switch (xpp.getEventType()) { + + case XmlPullParser.START_TAG: + if(xpp.getAttributeCount()>0){ + for (int i = 0; i < xpp.getAttributeCount(); i++) { + attr_name = xpp.getAttributeName(i); + attr_val = xpp.getAttributeValue(i); + if(attr_name.equalsIgnoreCase("term")) + term = attr_val; + else if(attr_name.equalsIgnoreCase("label")) + label = attr_val; + } + } + break; + default: + break; + } + do { + xpp.next(); + } while (xpp.getEventType() != XmlPullParser.END_TAG); + } catch (XmlPullParserException e) { + return null; + }catch (IOException e) { + return null; + } + return (new String_Category_Tag(term, label)); + } + private String Content_Tag(XmlPullParser xpp){ + String content = null; + String tag_type = ""; + + + String attr_name; + try { + while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) { + switch (xpp.getEventType()) { + case XmlPullParser.START_TAG: + if(xpp.getAttributeCount()>0){ + for (int i = 0; i < xpp.getAttributeCount(); i++) { + attr_name = xpp.getAttributeName(i); + if(attr_name.equalsIgnoreCase("type")) + tag_type = xpp.getAttributeValue(i); + } + } + break; + case XmlPullParser.TEXT: + if(tag_type.equals("text/html")){ + content = Html.fromHtml(xpp.getText()).toString().trim(); + }else + content = xpp.getText().trim(); + break; + case XmlPullParser.END_TAG: + if(xpp.getName().equalsIgnoreCase("content")) + return content; + break; + } + xpp.next(); + } + } catch (XmlPullParserException e) { + return null; + } catch (IOException e) { + return null; + } + return null; + } + private String Summary_Tag(XmlPullParser xpp){ + String summary = null; + + try { + while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) { + switch (xpp.getEventType()) { + case XmlPullParser.TEXT: + summary = xpp.getText().trim(); + break; + case XmlPullParser.END_TAG: + if(xpp.getName().equalsIgnoreCase("summary")) + return summary; + break; + } + xpp.next(); + } + } catch (XmlPullParserException e) { + return null; + } catch (IOException e) { + return null; + } + return null; + } + private boolean Entry_Tag(XmlPullParser xpp, ArrayList names_tmp, ArrayList books_tmp){ + String bt_header; + String bt_subHeader = ""; + String bt_cover; + String bt_url = null; + String_Link_Tag tmp_link; + + String entry_title = null; + String entry_author = null; + String entry_content = null; + String entry_summary = null; + String entry_category = null; + String entry_cover2 = null; + ArrayList entry_authors_list = new ArrayList(); + ArrayList entry_books_link = new ArrayList(); + ArrayList tmp_list_link = new ArrayList(); + String url_pref; + flag_book = true; + try { + while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) { + switch (xpp.getEventType()) { + case XmlPullParser.START_TAG: + if(xpp.getName().equalsIgnoreCase("link")){ + tmp_link = Link_Tag(xpp); + if(!(tmp_link.href.contains("http://"))){ + url_pref = URLdomen; + }else{ + url_pref = ""; + } + if(tmp_link.type != null){ + if(tmp_link.type.contains("image") && tmp_link.rel.contains("image")){ + entry_cover2 = url_pref + tmp_link.href; + } + if(tmp_link.type.contains("profile=opds-catalog") ){ + if(tmp_link.rel == null & tmp_link.title == null){ + bt_url = url_pref + tmp_link.href; + flag_book = false; + } + if(tmp_link.title != null){ + tmp_list_link.add(new String_Search_Tag(tmp_link.title, url_pref + tmp_link.href)); + } + }else if(tmp_link.type.equals("application/fb2+zip")){ + entry_books_link.add(new BookLink("fb2.zip", url_pref + tmp_link.href)); + }else if(tmp_link.type.equals("application/fb2")){ + entry_books_link.add(new BookLink("fb2",url_pref + tmp_link.href)); + }else if(tmp_link.type.equals("application/txt+zip")){ + entry_books_link.add(new BookLink("txt.zip",url_pref + tmp_link.href)); + }else if(tmp_link.type.equals("application/txt")){ + entry_books_link.add(new BookLink("txt",url_pref + tmp_link.href)); + }else if(tmp_link.type.equals("application/epub")){ + entry_books_link.add(new BookLink("epub",url_pref + tmp_link.href)); + }else if(tmp_link.type.equals("application/epub+zip")){ + if(URLstr.contains("dimonvideo.ru") || URLstr.contains("coollib.net") || URLstr.contains("zone4iphone.ru")){ + entry_books_link.add(new BookLink("epub",url_pref + tmp_link.href)); + }else + entry_books_link.add(new BookLink("epub.zip",url_pref + tmp_link.href)); + }else if(tmp_link.type.equals("application/html+zip")){ + entry_books_link.add(new BookLink("html.zip",url_pref + tmp_link.href)); + }else if(tmp_link.type.equals("application/html")){ + entry_books_link.add(new BookLink("html",url_pref + tmp_link.href)); + }else if(tmp_link.type.equals("application/rtf+zip")){ + entry_books_link.add(new BookLink("rtf.zip",url_pref + tmp_link.href)); + }else if(tmp_link.type.equals("application/rtf")){ + entry_books_link.add(new BookLink("rtf",url_pref + tmp_link.href)); + }else if(tmp_link.type.equals("application/doc+zip")){ + entry_books_link.add(new BookLink("doc.zip",url_pref + tmp_link.href)); + }else if(tmp_link.type.equals("application/doc")){ + entry_books_link.add(new BookLink("doc",url_pref + tmp_link.href)); + }else if(tmp_link.type.equals("application/pdf+zip")){ + entry_books_link.add(new BookLink("pdf.zip",url_pref + tmp_link.href)); + }else if(tmp_link.type.equals("application/pdf")){ + entry_books_link.add(new BookLink("pdf",url_pref + tmp_link.href)); + }else if(tmp_link.type.equals("application/djvu+zip")){ + entry_books_link.add(new BookLink("djvu.zip",url_pref + tmp_link.href)); + }else if(tmp_link.type.equals("application/djvu")){ + entry_books_link.add(new BookLink("djvu",url_pref + tmp_link.href)); + }else if(tmp_link.type.equals("application/x-mobipocket-ebook+zip")){ + entry_books_link.add(new BookLink("mobi.zip",url_pref + tmp_link.href)); + }else if(tmp_link.type.equals("application/x-mobipocket-ebook")){ + entry_books_link.add(new BookLink("mobi",url_pref + tmp_link.href)); + }else{ + if(tmp_link.rel == null & tmp_link.title == null){ + bt_url = url_pref + tmp_link.href; + flag_book = false; + } + if(tmp_link.title != null){ + tmp_list_link.add(new String_Search_Tag(tmp_link.title, url_pref + tmp_link.href)); + } + } + } + }else if(xpp.getName().equalsIgnoreCase("author")){ + String_Author_Tag author1 = Author_Tag(xpp); + + if(author1!=null){ + entry_authors_list.add(author1.name); + if(entry_author == null){ + entry_author = author1.name; + }else { + entry_author = entry_author.concat(", "); + entry_author = entry_author.concat(author1.name); + } + } + }else if(xpp.getName().equalsIgnoreCase("title")){ + entry_title = Title_Tag(xpp); + + }else if(xpp.getName().equalsIgnoreCase("category")){ + String_Category_Tag category = Category_Tag(xpp); + entry_category = category.label; + }else if(xpp.getName().equalsIgnoreCase("content")){ + entry_content = Content_Tag(xpp); + }else if(xpp.getName().equalsIgnoreCase("summary")){ + entry_summary = Summary_Tag(xpp); + } + break; + case XmlPullParser.END_TAG: + if(xpp.getName().equalsIgnoreCase("entry")){ + bt_header = entry_title; + if(entry_books_link.size() != 0){ + flag_book = true; + } + if(flag_book){ + bt_cover = "2"; + if(entry_author != null){ + bt_subHeader = entry_author; + } + if(entry_category !=null){ + bt_subHeader = bt_subHeader.concat(" (") + entry_category + ")"; + } + }else{ + bt_cover ="1"; + if(entry_content != null){ + bt_subHeader = entry_content; + } + } + + names_tmp.add(new Item(bt_header, bt_subHeader , bt_url, bt_cover, tmp_list_link)); + + if((entry_content == null || entry_content.length() == 0) && (entry_summary != null && entry_summary.length() > 0)){ + entry_content = entry_summary; + } + + if(flag_book){ + books_tmp.add(new BookInfo(entry_cover2,entry_authors_list,entry_category,entry_title,entry_content,entry_books_link)); + } + + return false; + } + break; + + + default: + break; + } + xpp.next(); + } + } catch (XmlPullParserException e) { + return true; + } catch (IOException e) { + return true; + } + return false; + } + + private String Name_Tag(XmlPullParser xpp){ + String name = null; + try { + while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) { + switch (xpp.getEventType()) { + case XmlPullParser.TEXT: + name = xpp.getText().trim(); + break; + case XmlPullParser.END_TAG: + if(xpp.getName().equalsIgnoreCase("name")) + return name; + break; + + default: + break; + } + xpp.next(); + } + } catch (XmlPullParserException e) { + return null; + } catch (IOException e) { + return null; + } + return null; + } + private String Uri_Tag(XmlPullParser xpp){ + String uri = null; + try { + while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) { + switch (xpp.getEventType()) { + case XmlPullParser.TEXT: + uri = xpp.getText().trim(); + break; + case XmlPullParser.END_TAG: + if(xpp.getName().equalsIgnoreCase("uri")) + return uri; + break; + + default: + break; + } + xpp.next(); + } + } catch (XmlPullParserException e) { + return null; + } catch (IOException e) { + return null; + } + return null; + } + + private class OPDS_adapter extends BaseAdapter { + + ArrayList data = new ArrayList(); + Context context; + + public OPDS_adapter(Context context, ArrayList arr) { + if (arr != null) { + data = arr; + } + this.context = context; + } + + @Override + public int getCount() { + // TODO Auto-generated method stub + return data.size(); + } + + @Override + public Object getItem(int num) { + // TODO Auto-generated method stub + return data.get(num); + } + + @Override + public long getItemId(int arg0) { + return arg0; + } + + @Override + public View getView(int i, View someView, ViewGroup arg2) { + LayoutInflater inflater = LayoutInflater.from(context); + if (someView == null) { + someView = inflater.inflate(R.layout.button_opds, arg2, false); + } + TextView header = (TextView) someView.findViewById(R.id.item_headerText); + TextView subHeader = (TextView) someView.findViewById(R.id.item_subHeaderText); + ImageView imgHeader = (ImageView) someView.findViewById((R.id.iV_cover)); + header.setTextSize(TypedValue.COMPLEX_UNIT_PX, size_text); + header.setText(data.get(i).header); + subHeader.setTextSize(TypedValue.COMPLEX_UNIT_PX, size_text2); + subHeader.setText(data.get(i).subHeader); + if(data.get(i).imgHeader.equals("1")) + imgHeader.setImageBitmap(scaleDrawableById(R.drawable.folder_books, size_icon));//.setImageResource(R.drawable.folder_books); + else if(data.get(i).imgHeader.equals("2")) + imgHeader.setImageBitmap(scaleDrawableById(R.drawable.book, size_icon));//.setImageResource(R.drawable.book); + else if(data.get(i).imgHeader.equals("down")) + imgHeader.setImageBitmap(scaleDrawableById(R.drawable.arrow_down, size_icon));//.setImageResource(R.drawable.arrow_down); + else if(data.get(i).imgHeader.equals("up")) + imgHeader.setImageBitmap(scaleDrawableById(R.drawable.arrow_up, size_icon));//.setImageResource(R.drawable.arrow_up); + return someView; + } + + private Bitmap scaleDrawableById(int id, int size) { + return Bitmap.createScaledBitmap( + BitmapFactory.decodeResource(getResources(), id), size, size, + true); + } + } + private class String_Search_Tag{ + String name=null; + String uri=null; + + String_Search_Tag(String n, String u){ + name = n; + uri = u; + } + } + public class Item { + String header; + String subHeader; + String urllink; + String imgHeader; + ArrayList list_link = new ArrayList(); + + Item(String h, String s, String u, String i, ArrayList ll){ + this.header=h; + this.subHeader=s; + this.urllink=u; + this.imgHeader=i; + if(ll != null && ll.size() != 0){ + this.list_link.addAll(ll); + } + } + + } + + public class DownloadImageTask extends AsyncTask{ + + // запускаем ProgressBar в момент запуска потока + ImageView img; + String urlImage; + + public DownloadImageTask(ImageView source, String url) { + this.img = source; + this.urlImage = url; + } + + protected Bitmap doInBackground(Void... params) { + Bitmap cover; + try { + cover = getImageBitmap(urlImage, 1); + } catch (Exception e) { + e.printStackTrace(); + cover = null; + } + return cover; + } + + protected void onPostExecute(Bitmap cover) { + super.onPostExecute(cover); + if(cover != null){ + img.setImageBitmap(cover); + } + } + } +} diff --git a/src/com/harasoft/relaunch/PowerFunctions.java b/src/com/harasoft/relaunch/PowerFunctions.java index 544ce7d..45e2623 100644 --- a/src/com/harasoft/relaunch/PowerFunctions.java +++ b/src/com/harasoft/relaunch/PowerFunctions.java @@ -58,7 +58,7 @@ public static void actionReboot(Activity act) { // "YES" final Activity fact = act; builder.setPositiveButton( - act.getResources().getString(R.string.jv_advanced_yes), + act.getResources().getString(R.string.app_yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -88,7 +88,7 @@ public void run() { }); // "NO" builder.setNegativeButton( - act.getResources().getString(R.string.jv_advanced_no), + act.getResources().getString(R.string.app_no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -118,7 +118,7 @@ public static void actionPowerOff(Activity act) { // "YES" final Activity fact = act; builder.setPositiveButton( - act.getResources().getString(R.string.jv_advanced_yes), + act.getResources().getString(R.string.app_yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -148,7 +148,7 @@ public void run() { }); // "NO" builder.setNegativeButton( - act.getResources().getString(R.string.jv_advanced_no), + act.getResources().getString(R.string.app_no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { diff --git a/src/com/harasoft/relaunch/PrefsActivity.java b/src/com/harasoft/relaunch/PrefsActivity.java index 56c691f..07debb4 100644 --- a/src/com/harasoft/relaunch/PrefsActivity.java +++ b/src/com/harasoft/relaunch/PrefsActivity.java @@ -1,11 +1,5 @@ package com.harasoft.relaunch; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import android.R.integer; import android.app.Activity; import android.app.AlarmManager; import android.app.AlertDialog; @@ -15,24 +9,18 @@ import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Bundle; -import android.preference.CheckBoxPreference; -import android.preference.EditTextPreference; -import android.preference.ListPreference; -import android.preference.Preference; -import android.preference.PreferenceActivity; -import android.preference.PreferenceCategory; -import android.preference.PreferenceManager; -import android.preference.PreferenceScreen; +import android.os.SystemClock; +import android.preference.*; import android.text.InputType; -import android.view.LayoutInflater; -import android.view.View; +import android.view.*; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.ImageButton; -import android.widget.ListAdapter; import android.widget.ListView; -import android.os.SystemClock; -import android.view.MotionEvent; + +import java.util.List; +import java.util.Map; +import java.util.Set; public class PrefsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener { @@ -68,13 +56,13 @@ private void cancel() { for (String key : keys) { Object value = oldPrefs.get(key); if (value instanceof Boolean) { - editor.putBoolean(key, ((Boolean) value).booleanValue()); + editor.putBoolean(key, (Boolean) value); } else if (value instanceof Float) { - editor.putFloat(key, ((Float) value).floatValue()); + editor.putFloat(key, (Float) value); } else if (value instanceof Integer) { - editor.putInt(key, ((Integer) value).intValue()); + editor.putInt(key, (Integer) value); } else if (value instanceof Long) { - editor.putLong(key, ((Long) value).longValue()); + editor.putLong(key, (Long) value); } else if (value instanceof String) { editor.putString(key, (String) value); } @@ -86,120 +74,20 @@ private void cancel() { private void updatePrefSummary(Preference p) { if (p instanceof ListPreference) { ListPreference listPref = (ListPreference) p; - if (p.getKey().equals("homeButtonST") - && listPref.getValue().toString().equals("OPENN")) { - p.setSummary(listPref.getEntry() - + prefs.getString("homeButtonSTopenN", "1")); - } else if (p.getKey().equals("homeButtonDT") - && listPref.getValue().toString().equals("OPENN")) { - p.setSummary(listPref.getEntry() - + prefs.getString("homeButtonDTopenN", "1")); - } else if (p.getKey().equals("homeButtonLT") - && listPref.getValue().toString().equals("OPENN")) { - p.setSummary(listPref.getEntry() - + prefs.getString("homeButtonLTopenN", "1")); - } else if (p.getKey().equals("lruButtonST") - && listPref.getValue().toString().equals("OPENN")) { - p.setSummary(listPref.getEntry() - + prefs.getString("lruButtonSTopenN", "1")); - } else if (p.getKey().equals("lruButtonDT") - && listPref.getValue().toString().equals("OPENN")) { - p.setSummary(listPref.getEntry() - + prefs.getString("lruButtonDTopenN", "1")); - } else if (p.getKey().equals("lruButtonLT") - && listPref.getValue().toString().equals("OPENN")) { - p.setSummary(listPref.getEntry() - + prefs.getString("lruButtonLTopenN", "1")); - } else if (p.getKey().equals("favButtonST") - && listPref.getValue().toString().equals("OPENN")) { - p.setSummary(listPref.getEntry() - + prefs.getString("favButtonSTopenN", "1")); - } else if (p.getKey().equals("favButtonDT") - && listPref.getValue().toString().equals("OPENN")) { - p.setSummary(listPref.getEntry() - + prefs.getString("favButtonDTopenN", "1")); - } else if (p.getKey().equals("favButtonLT") - && listPref.getValue().toString().equals("OPENN")) { - p.setSummary(listPref.getEntry() - + prefs.getString("favButtonLTopenN", "1")); - } else if (p.getKey().equals("settingsButtonST") - && listPref.getValue().toString().equals("RUN")) { - String[] appa = prefs.getString("settingsButtonSTapp", "%%") - .split("\\%"); - p.setSummary(listPref.getEntry() + " \"" + appa[2] + "\""); - } else if (p.getKey().equals("settingsButtonDT") - && listPref.getValue().toString().equals("RUN")) { - String[] appa = prefs.getString("settingsButtonDTapp", "%%") - .split("\\%"); - p.setSummary(listPref.getEntry() + " \"" + appa[2] + "\""); - } else if (p.getKey().equals("settingsButtonLT") - && listPref.getValue().toString().equals("RUN")) { - String[] appa = prefs.getString("settingsButtonLTapp", "%%") - .split("\\%"); - p.setSummary(listPref.getEntry() + " \"" + appa[2] + "\""); - } else if (p.getKey().equals("advancedButtonST") - && listPref.getValue().toString().equals("RUN")) { - String[] appa = prefs.getString("advancedButtonSTapp", "%%") - .split("\\%"); - p.setSummary(listPref.getEntry() + " \"" + appa[2] + "\""); - } else if (p.getKey().equals("advancedButtonDT") - && listPref.getValue().toString().equals("RUN")) { - String[] appa = prefs.getString("advancedButtonDTapp", "%%") - .split("\\%"); - p.setSummary(listPref.getEntry() + " \"" + appa[2] + "\""); - } else if (p.getKey().equals("advancedButtonLT") - && listPref.getValue().toString().equals("RUN")) { - String[] appa = prefs.getString("advancedButtonLTapp", "%%") - .split("\\%"); - p.setSummary(listPref.getEntry() + " \"" + appa[2] + "\""); - } else if (p.getKey().equals("memButtonST") - && listPref.getValue().toString().equals("RUN")) { - String[] appa = prefs.getString("memButtonSTapp", "%%").split( - "\\%"); - p.setSummary(listPref.getEntry() + " \"" + appa[2] + "\""); - } else if (p.getKey().equals("memButtonDT") - && listPref.getValue().toString().equals("RUN")) { - String[] appa = prefs.getString("memButtonDTapp", "%%").split( - "\\%"); - p.setSummary(listPref.getEntry() + " \"" + appa[2] + "\""); - } else if (p.getKey().equals("memButtonLT") - && listPref.getValue().toString().equals("RUN")) { - String[] appa = prefs.getString("memButtonLTapp", "%%").split( - "\\%"); - p.setSummary(listPref.getEntry() + " \"" + appa[2] + "\""); - } else if (p.getKey().equals("batButtonST") - && listPref.getValue().toString().equals("RUN")) { - String[] appa = prefs.getString("batButtonSTapp", "%%").split( - "\\%"); - p.setSummary(listPref.getEntry() + " \"" + appa[2] + "\""); - } else if (p.getKey().equals("batButtonDT") - && listPref.getValue().toString().equals("RUN")) { - String[] appa = prefs.getString("batButtonDTapp", "%%").split( - "\\%"); - p.setSummary(listPref.getEntry() + " \"" + appa[2] + "\""); - } else if (p.getKey().equals("batButtonLT") - && listPref.getValue().toString().equals("RUN")) { - String[] appa = prefs.getString("batButtonLTapp", "%%").split( - "\\%"); - p.setSummary(listPref.getEntry() + " \"" + appa[2] + "\""); - } else if (p.getKey().equals("appFavButtonST") - && listPref.getValue().toString().equals("RUN")) { - String[] appa = prefs.getString("appFavButtonSTapp", "%%").split( - "\\%"); - p.setSummary(listPref.getEntry() + " \"" + appa[2] + "\""); - } else if (p.getKey().equals("appFavButtonDT") - && listPref.getValue().toString().equals("RUN")) { - String[] appa = prefs.getString("appFavButtonDTapp", "%%").split( - "\\%"); - p.setSummary(listPref.getEntry() + " \"" + appa[2] + "\""); - } else if (p.getKey().equals("appFavButtonLT") - && listPref.getValue().toString().equals("RUN")) { - String[] appa = prefs.getString("appFavButtonLTapp", "%%").split( - "\\%"); - p.setSummary(listPref.getEntry() + " \"" + appa[2] + "\""); - } else { - p.setSummary(listPref.getEntry()); - } + if(listPref.getValue().equals("OPENN")){ + p.setSummary(listPref.getEntry() + prefs.getString(p.getKey()+"openN", "1")); + }else if(listPref.getValue().equals("RUN")){ + + String[] appa = prefs.getString(p.getKey()+"app", "%%").split("\\%"); + + if(appa.length > 2 && appa[2] != null && appa[2].length() > 0){ + p.setSummary(listPref.getEntry() + " \"" + appa[2] + "\""); + } + + }else{ + p.setSummary(listPref.getEntry()); + } + } // For future - even more intellectual Settings // if (p instanceof EditTextPreference) { @@ -226,22 +114,19 @@ private void initSummary(Preference p) { @Override protected void onCreate(Bundle savedInstanceState) { - app = ((ReLaunchApp) getApplicationContext()); -// app.setFullScreenIfNecessary(this); + app.setFullScreenIfNecessary(this); applicationsArray = app.getApps(); - applications = applicationsArray - .toArray(new CharSequence[applicationsArray.size()]); - happlications = app.getApps().toArray( - new CharSequence[app.getApps().size()]); + applications = applicationsArray.toArray(new CharSequence[applicationsArray.size()]); + happlications = app.getApps().toArray(new CharSequence[app.getApps().size()]); for (int j = 0; j < happlications.length; j++) { String happ = (String) happlications[j]; String[] happp = happ.split("\\%"); happlications[j] = happp[2]; } - prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); + prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.prefs); @@ -252,8 +137,9 @@ protected void onCreate(Bundle savedInstanceState) { for (int i = 0; i < prefAdvancedScreen.getPreferenceCount(); i++) { Preference p = prefAdvancedScreen.getPreference(i); - if (p instanceof PreferenceScreen) + if (p instanceof PreferenceScreen){ p.setOnPreferenceClickListener(prefScreenListener); + } } // Save items value @@ -273,7 +159,7 @@ public boolean onPreferenceClick(Preference pref) { builder.setMessage(getResources().getString( R.string.jv_prefs_cleanup_database_text)); builder.setPositiveButton( - getResources().getString(R.string.jv_prefs_yes), + getResources().getString(R.string.app_yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -283,7 +169,7 @@ public void onClick(DialogInterface dialog, }); builder.setNegativeButton( getResources().getString( - R.string.jv_relaunch_no), + R.string.app_no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -305,7 +191,7 @@ public boolean onPreferenceClick(Preference pref) { builder.setMessage(getResources().getString( R.string.jv_prefs_clear_lru_text)); builder.setPositiveButton( - getResources().getString(R.string.jv_prefs_yes), + getResources().getString(R.string.app_yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -315,7 +201,7 @@ public void onClick(DialogInterface dialog, }); builder.setNegativeButton( getResources().getString( - R.string.jv_relaunch_no), + R.string.app_no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -337,7 +223,7 @@ public boolean onPreferenceClick(Preference pref) { builder.setMessage(getResources().getString( R.string.jv_prefs_clear_favorites_text)); builder.setPositiveButton( - getResources().getString(R.string.jv_prefs_yes), + getResources().getString(R.string.app_yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -347,7 +233,7 @@ public void onClick(DialogInterface dialog, }); builder.setNegativeButton( getResources().getString( - R.string.jv_relaunch_no), + R.string.app_no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -382,8 +268,7 @@ public boolean onPreferenceClick(Preference pref) { findPreference("resetSettings").setOnPreferenceClickListener( new Preference.OnPreferenceClickListener() { public boolean onPreferenceClick(Preference pref) { - AlertDialog.Builder builder = new AlertDialog.Builder( - context); + AlertDialog.Builder builder = new AlertDialog.Builder(context); // "Default settings warning" builder.setTitle(getResources().getString( R.string.jv_prefs_default_settings_title)); @@ -392,7 +277,7 @@ public boolean onPreferenceClick(Preference pref) { R.string.jv_prefs_default_settings_text)); // "Yes" builder.setPositiveButton( - getResources().getString(R.string.jv_prefs_yes), + getResources().getString(R.string.app_yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -406,7 +291,7 @@ public void onClick(DialogInterface dialog, }); // "No" builder.setNegativeButton( - getResources().getString(R.string.jv_prefs_no), + getResources().getString(R.string.app_no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -417,12 +302,11 @@ public void onClick(DialogInterface dialog, return true; } }); - findPreference("saveSettings").setOnPreferenceClickListener( new Preference.OnPreferenceClickListener() { public boolean onPreferenceClick(Preference pref) { boolean ret = app.copyPrefs(app.DATA_DIR, - app.BACKUP_DIR); + ReLaunch.BACKUP_DIR); AlertDialog.Builder builder = new AlertDialog.Builder( context); if (ret) { @@ -437,7 +321,7 @@ public boolean onPreferenceClick(Preference pref) { R.string.jv_prefs_rsr_fail_text)); } builder.setNeutralButton( - getResources().getString(R.string.jv_prefs_ok), + getResources().getString(R.string.app_ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -452,7 +336,7 @@ public void onClick(DialogInterface dialog, findPreference("loadSettings").setOnPreferenceClickListener( new Preference.OnPreferenceClickListener() { public boolean onPreferenceClick(Preference pref) { - boolean ret = app.copyPrefs(app.BACKUP_DIR, + boolean ret = app.copyPrefs(ReLaunch.BACKUP_DIR, app.DATA_DIR); AlertDialog.Builder builder = new AlertDialog.Builder( context); @@ -468,7 +352,7 @@ public boolean onPreferenceClick(Preference pref) { R.string.jv_prefs_rsr_fail_text)); } builder.setNeutralButton( - getResources().getString(R.string.jv_prefs_ok), + getResources().getString(R.string.app_ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -500,7 +384,7 @@ public boolean onPreferenceClick(Preference pref) { // final Activity pact = this; // back button - work as cancel - ((ImageButton) findViewById(R.id.back_btn)) + ( findViewById(R.id.back_btn)) .setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (isPreferencesChanged()) { @@ -515,7 +399,7 @@ public void onClick(View v) { // "Yes" builder.setPositiveButton( getResources().getString( - R.string.jv_prefs_yes), + R.string.app_yes), new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, @@ -530,7 +414,7 @@ public void onClick( // "No" builder.setNegativeButton( getResources().getString( - R.string.jv_prefs_cancel), + R.string.app_cancel), new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, @@ -541,7 +425,7 @@ public void onClick( // "Cancel" builder.setNeutralButton( getResources().getString( - R.string.jv_prefs_no), + R.string.app_no), new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, @@ -558,85 +442,6 @@ public void onClick( } }); - ImageButton upScroll = (ImageButton) findViewById(R.id.btn_scrollup); - upScroll.setOnClickListener(new View.OnClickListener() { - - public void onClick(View v) { - if (DeviceInfo.EINK_NOOK) { - MotionEvent ev; - ev = MotionEvent.obtain(SystemClock.uptimeMillis(), - SystemClock.uptimeMillis(), - MotionEvent.ACTION_DOWN, 200, 100, 0); - getListView().dispatchTouchEvent(ev); - ev = MotionEvent.obtain(SystemClock.uptimeMillis(), - SystemClock.uptimeMillis() + 100, - MotionEvent.ACTION_MOVE, 200, 200, 0); - getListView().dispatchTouchEvent(ev); - SystemClock.sleep(100); - ev = MotionEvent.obtain(SystemClock.uptimeMillis(), - SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, - 200, 200, 0); - getListView().dispatchTouchEvent(ev); - } else { - final ListView lv = (ListView) getListView(); - int first = lv.getFirstVisiblePosition(); - int visible = lv.getLastVisiblePosition() - - lv.getFirstVisiblePosition() + 1; - first -= visible; - if (first < 0) - first = 0; - final int finfirst = first; - lv.clearFocus(); - lv.post(new Runnable() { - - public void run() { - lv.setSelection(finfirst); - } - }); - } - } - }); - - ImageButton downScroll = (ImageButton) findViewById(R.id.btn_scrolldown); - downScroll.setOnClickListener(new View.OnClickListener() { - - public void onClick(View v) { - if (DeviceInfo.EINK_NOOK) { - MotionEvent ev; - ev = MotionEvent.obtain(SystemClock.uptimeMillis(), - SystemClock.uptimeMillis(), - MotionEvent.ACTION_DOWN, 200, 200, 0); - getListView().dispatchTouchEvent(ev); - ev = MotionEvent.obtain(SystemClock.uptimeMillis(), - SystemClock.uptimeMillis() + 100, - MotionEvent.ACTION_MOVE, 200, 100, 0); - getListView().dispatchTouchEvent(ev); - SystemClock.sleep(100); - ev = MotionEvent.obtain(SystemClock.uptimeMillis(), - SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, - 200, 100, 0); - getListView().dispatchTouchEvent(ev); - } else { - final ListView lv = (ListView) getListView(); - int total = lv.getCount(); - int last = lv.getLastVisiblePosition(); - if (total == last + 1) - return; - int target = last + 1; - if (target > (total - 1)) - target = total - 1; - final int ftarget = target; - lv.clearFocus(); - lv.post(new Runnable() { - public void run() { - lv.setSelection(ftarget); - } - }); - } - - } - }); - for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); i++) { initSummary(getPreferenceScreen().getPreference(i)); } @@ -649,7 +454,7 @@ protected void onResume() { super.onResume(); getPreferenceScreen().getSharedPreferences() .registerOnSharedPreferenceChangeListener(this); - app.generalOnResume(TAG, this); + app.generalOnResume(TAG); } @Override @@ -675,12 +480,10 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) { editor.commit(); break; default: - return; - } + } } - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, - String key) { + public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,final String key) { final Preference pref = findPreference(key); // update summary @@ -772,7 +575,7 @@ public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, } else if (key.equals("fileFontSize")) { do_pref_subrequest = false; String sValue = sharedPreferences.getString("fileFontSize", "20"); - int f1Size = (new Integer(sValue)).intValue(); + int f1Size = new Integer(sValue); int f2Size = f1Size*4/5; ((EditTextPreference) findPreference("firstLineFontSizePx")) .setText(((Integer) f1Size).toString()); @@ -795,684 +598,137 @@ public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, } // special cases - // HOME - if (key.equals("homeButtonST")) { - if (sharedPreferences.getString(key, "OPENN").equals("OPENN")) { - AlertDialog.Builder builder1 = new AlertDialog.Builder( - PrefsActivity.this); - // "Select number" - builder1.setTitle(getResources().getString( - R.string.jv_prefs_select_number)); - final EditText input = new EditText(PrefsActivity.this); - input.setInputType(InputType.TYPE_CLASS_NUMBER); - input.setText(sharedPreferences.getString( - "homeButtonSTopenN", "1")); - builder1.setView(input); - // "OK" - builder1.setPositiveButton( - getResources().getString(R.string.jv_prefs_ok), - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int whichButton) { - InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); - imm.hideSoftInputFromWindow( - input.getWindowToken(), 0); - dialog.dismiss(); - SharedPreferences.Editor editor = prefs - .edit(); - editor.putString("homeButtonSTopenN", input - .getText().toString()); - editor.commit(); - updatePrefSummary(pref); - } - }); - InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); - imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); - builder1.show(); - } - } - if (key.equals("homeButtonDT")) { - if (sharedPreferences.getString(key, "OPENMENU") - .equals("OPENN")) { - AlertDialog.Builder builder1 = new AlertDialog.Builder( - PrefsActivity.this); - // "Select number" - builder1.setTitle(getResources().getString( - R.string.jv_prefs_select_number)); - final EditText input = new EditText(PrefsActivity.this); - input.setInputType(InputType.TYPE_CLASS_NUMBER); - input.setText(sharedPreferences.getString( - "homeButtonDTopenN", "1")); - builder1.setView(input); - // "Ok" - builder1.setPositiveButton("OK", - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int whichButton) { - InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); - imm.hideSoftInputFromWindow( - input.getWindowToken(), 0); - dialog.dismiss(); - SharedPreferences.Editor editor = prefs - .edit(); - editor.putString("homeButtonDTopenN", input - .getText().toString()); - editor.commit(); - updatePrefSummary(pref); - } - }); - InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); - imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); - builder1.show(); - } - } - if (key.equals("homeButtonLT")) { - if (sharedPreferences.getString(key, "OPENSCREEN").equals( - "OPENN")) { - AlertDialog.Builder builder1 = new AlertDialog.Builder( - PrefsActivity.this); - // "Select number" - builder1.setTitle(getResources().getString( - R.string.jv_prefs_select_number)); - final EditText input = new EditText(PrefsActivity.this); - input.setInputType(InputType.TYPE_CLASS_NUMBER); - input.setText(sharedPreferences.getString( - "homeButtonLTopenN", "1")); - builder1.setView(input); - // "Ok" - builder1.setPositiveButton("OK", - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int whichButton) { - InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); - imm.hideSoftInputFromWindow( - input.getWindowToken(), 0); - dialog.dismiss(); - SharedPreferences.Editor editor = prefs - .edit(); - editor.putString("homeButtonLTopenN", input - .getText().toString()); - editor.commit(); - updatePrefSummary(pref); - } - }); - InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); - imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); - builder1.show(); - } - } - // LRU - if (key.equals("lruButtonST")) { - if (sharedPreferences.getString(key, "OPENSCREEN").equals( - "OPENN")) { - AlertDialog.Builder builder1 = new AlertDialog.Builder( - PrefsActivity.this); - // "Select number" - builder1.setTitle(getResources().getString( - R.string.jv_prefs_select_number)); - final EditText input = new EditText(PrefsActivity.this); - input.setInputType(InputType.TYPE_CLASS_NUMBER); - input.setText(sharedPreferences.getString( - "lruButtonSTopenN", "1")); - builder1.setView(input); - // "OK" - builder1.setPositiveButton( - getResources().getString(R.string.jv_prefs_ok), - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int whichButton) { - InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); - imm.hideSoftInputFromWindow( - input.getWindowToken(), 0); - dialog.dismiss(); - SharedPreferences.Editor editor = prefs - .edit(); - editor.putString("lruButtonSTopenN", input - .getText().toString()); - editor.commit(); - updatePrefSummary(pref); - } - }); - InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); - imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); - builder1.show(); - } - } - if (key.equals("lruButtonDT")) { - if (sharedPreferences.getString(key, "NOTHING").equals("OPENN")) { - AlertDialog.Builder builder1 = new AlertDialog.Builder( - PrefsActivity.this); - // "Select number" - builder1.setTitle(getResources().getString( - R.string.jv_prefs_select_number)); - final EditText input = new EditText(PrefsActivity.this); - input.setInputType(InputType.TYPE_CLASS_NUMBER); - input.setText(sharedPreferences.getString( - "lruButtonDTopenN", "1")); - builder1.setView(input); - // "Ok" - builder1.setPositiveButton("OK", - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int whichButton) { - InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); - imm.hideSoftInputFromWindow( - input.getWindowToken(), 0); - dialog.dismiss(); - SharedPreferences.Editor editor = prefs - .edit(); - editor.putString("lruButtonDTopenN", input - .getText().toString()); - editor.commit(); - updatePrefSummary(pref); - } - }); - InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); - imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); - builder1.show(); - } - } - if (key.equals("lruButtonLT")) { - if (sharedPreferences.getString(key, "NOTHING").equals("OPENN")) { - AlertDialog.Builder builder1 = new AlertDialog.Builder( - PrefsActivity.this); - // "Select number" - builder1.setTitle(getResources().getString( - R.string.jv_prefs_select_number)); - final EditText input = new EditText(PrefsActivity.this); - input.setInputType(InputType.TYPE_CLASS_NUMBER); - input.setText(sharedPreferences.getString( - "lruButtonLTopenN", "1")); - builder1.setView(input); - // "Ok" - builder1.setPositiveButton("OK", - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int whichButton) { - InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); - imm.hideSoftInputFromWindow( - input.getWindowToken(), 0); - dialog.dismiss(); - SharedPreferences.Editor editor = prefs - .edit(); - editor.putString("lruButtonLTopenN", input - .getText().toString()); - editor.commit(); - updatePrefSummary(pref); - } - }); - InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); - imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); - builder1.show(); - } - } - // FAV - if (key.equals("favButtonST")) { - if (sharedPreferences.getString(key, "OPENSCREEN").equals( - "OPENN")) { - AlertDialog.Builder builder1 = new AlertDialog.Builder( - PrefsActivity.this); - // "Select number" - builder1.setTitle(getResources().getString( - R.string.jv_prefs_select_number)); - final EditText input = new EditText(PrefsActivity.this); - input.setInputType(InputType.TYPE_CLASS_NUMBER); - input.setText(sharedPreferences.getString( - "favButtonSTopenN", "1")); - builder1.setView(input); - // "OK" - builder1.setPositiveButton( - getResources().getString(R.string.jv_prefs_ok), - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int whichButton) { - InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); - imm.hideSoftInputFromWindow( - input.getWindowToken(), 0); - dialog.dismiss(); - SharedPreferences.Editor editor = prefs - .edit(); - editor.putString("favButtonSTopenN", input - .getText().toString()); - editor.commit(); - updatePrefSummary(pref); - } - }); - InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); - imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); - builder1.show(); - } - } - if (key.equals("favButtonDT")) { - if (sharedPreferences.getString(key, "NOTHING").equals("OPENN")) { - AlertDialog.Builder builder1 = new AlertDialog.Builder( - PrefsActivity.this); - // "Select number" - builder1.setTitle(getResources().getString( - R.string.jv_prefs_select_number)); - final EditText input = new EditText(PrefsActivity.this); - input.setInputType(InputType.TYPE_CLASS_NUMBER); - input.setText(sharedPreferences.getString( - "favButtonDTopenN", "1")); - builder1.setView(input); - // "Ok" - builder1.setPositiveButton("OK", - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int whichButton) { - InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); - imm.hideSoftInputFromWindow( - input.getWindowToken(), 0); - dialog.dismiss(); - SharedPreferences.Editor editor = prefs - .edit(); - editor.putString("favButtonDTopenN", input - .getText().toString()); - editor.commit(); - updatePrefSummary(pref); - } - }); - InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); - imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); - builder1.show(); - } - } - if (key.equals("favButtonLT")) { - if (sharedPreferences.getString(key, "NOTHING").equals("OPENN")) { - AlertDialog.Builder builder1 = new AlertDialog.Builder( - PrefsActivity.this); - // "Select number" - builder1.setTitle(getResources().getString( - R.string.jv_prefs_select_number)); - final EditText input = new EditText(PrefsActivity.this); - input.setInputType(InputType.TYPE_CLASS_NUMBER); - input.setText(sharedPreferences.getString( - "favButtonLTopenN", "1")); - builder1.setView(input); - // "Ok" - builder1.setPositiveButton("OK", - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int whichButton) { - InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); - imm.hideSoftInputFromWindow( - input.getWindowToken(), 0); - dialog.dismiss(); - SharedPreferences.Editor editor = prefs - .edit(); - editor.putString("favButtonLTopenN", input - .getText().toString()); - editor.commit(); - updatePrefSummary(pref); - } - }); - InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); - imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); - builder1.show(); - } - } - if (key.equals("settingsButtonST")) { - if (sharedPreferences.getString(key, "RELAUNCH").equals("RUN")) { - AlertDialog.Builder builder = new AlertDialog.Builder( - PrefsActivity.this); - // "Select application" - builder.setTitle(getResources().getString( - R.string.jv_prefs_select_application)); - builder.setSingleChoiceItems(happlications, -1, - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int i) { - SharedPreferences.Editor editor = prefs - .edit(); - editor.putString("settingsButtonSTapp", - (String) applications[i]); - editor.commit(); - updatePrefSummary(pref); - dialog.dismiss(); - } - }); - builder.show(); - } - } - if (key.equals("settingsButtonDT")) { - if (sharedPreferences.getString(key, "NOTHING").equals("RUN")) { - AlertDialog.Builder builder = new AlertDialog.Builder( - PrefsActivity.this); - // "Select application" - builder.setTitle(getResources().getString( - R.string.jv_prefs_select_application)); - builder.setSingleChoiceItems(happlications, -1, - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int i) { - SharedPreferences.Editor editor = prefs - .edit(); - editor.putString("settingsButtonDTapp", - (String) applications[i]); - editor.commit(); - updatePrefSummary(pref); - dialog.dismiss(); - } - }); - builder.show(); - } - } - if (key.equals("settingsButtonLT")) { - if (sharedPreferences.getString(key, "NOTHING").equals("RUN")) { - AlertDialog.Builder builder = new AlertDialog.Builder( - PrefsActivity.this); - // "Select application" - builder.setTitle(getResources().getString( - R.string.jv_prefs_select_application)); - builder.setSingleChoiceItems(happlications, -1, - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int i) { - SharedPreferences.Editor editor = prefs - .edit(); - editor.putString("settingsButtonLTapp", - (String) applications[i]); - editor.commit(); - updatePrefSummary(pref); - dialog.dismiss(); - } - }); - builder.show(); - } - } - if (key.equals("advancedButtonST")) { - if (sharedPreferences.getString(key, "RELAUNCH").equals("RUN")) { - AlertDialog.Builder builder = new AlertDialog.Builder( - PrefsActivity.this); - // "Select application" - builder.setTitle(getResources().getString( - R.string.jv_prefs_select_application)); - builder.setSingleChoiceItems(happlications, -1, - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int i) { - SharedPreferences.Editor editor = prefs - .edit(); - editor.putString("advancedButtonSTapp", - (String) applications[i]); - editor.commit(); - updatePrefSummary(pref); - dialog.dismiss(); - } - }); - builder.show(); - } - } - if (key.equals("advancedButtonDT")) { - if (sharedPreferences.getString(key, "NOTHING").equals("RUN")) { - AlertDialog.Builder builder = new AlertDialog.Builder( - PrefsActivity.this); - // "Select application" - builder.setTitle(getResources().getString( - R.string.jv_prefs_select_application)); - builder.setSingleChoiceItems(happlications, -1, - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int i) { - SharedPreferences.Editor editor = prefs - .edit(); - editor.putString("advancedButtonDTapp", - (String) applications[i]); - editor.commit(); - updatePrefSummary(pref); - dialog.dismiss(); - } - }); - builder.show(); - } - } - if (key.equals("advancedButtonLT")) { - if (sharedPreferences.getString(key, "NOTHING").equals("RUN")) { - AlertDialog.Builder builder = new AlertDialog.Builder( - PrefsActivity.this); - // "Select application" - builder.setTitle(getResources().getString( - R.string.jv_prefs_select_application)); - builder.setSingleChoiceItems(happlications, -1, - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int i) { - SharedPreferences.Editor editor = prefs - .edit(); - editor.putString("advancedButtonLTapp", - (String) applications[i]); - editor.commit(); - updatePrefSummary(pref); - dialog.dismiss(); - } - }); - builder.show(); - } - } - if (key.equals("memButtonST")) { - if (sharedPreferences.getString(key, "RELAUNCH").equals("RUN")) { - AlertDialog.Builder builder = new AlertDialog.Builder( - PrefsActivity.this); - // "Select application" - builder.setTitle(getResources().getString( - R.string.jv_prefs_select_application)); - builder.setSingleChoiceItems(happlications, -1, - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int i) { - SharedPreferences.Editor editor = prefs - .edit(); - editor.putString("memButtonSTapp", - (String) applications[i]); - editor.commit(); - updatePrefSummary(pref); - dialog.dismiss(); - } - }); - builder.show(); - } - } - if (key.equals("memButtonDT")) { - if (sharedPreferences.getString(key, "NOTHING").equals("RUN")) { - AlertDialog.Builder builder = new AlertDialog.Builder( - PrefsActivity.this); - // "Select application" - builder.setTitle(getResources().getString( - R.string.jv_prefs_select_application)); - builder.setSingleChoiceItems(happlications, -1, - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int i) { - SharedPreferences.Editor editor = prefs - .edit(); - editor.putString("memButtonDTapp", - (String) applications[i]); - editor.commit(); - updatePrefSummary(pref); - dialog.dismiss(); - } - }); - builder.show(); - } - } - if (key.equals("memButtonLT")) { - if (sharedPreferences.getString(key, "NOTHING").equals("RUN")) { - AlertDialog.Builder builder = new AlertDialog.Builder( - PrefsActivity.this); - // "Select application" - builder.setTitle(getResources().getString( - R.string.jv_prefs_select_application)); - builder.setSingleChoiceItems(happlications, -1, - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int i) { - SharedPreferences.Editor editor = prefs - .edit(); - editor.putString("memButtonLTapp", - (String) applications[i]); - editor.commit(); - updatePrefSummary(pref); - dialog.dismiss(); - } - }); - builder.show(); - } - } - if (key.equals("batButtonST")) { - if (sharedPreferences.getString(key, "RELAUNCH").equals("RUN")) { - AlertDialog.Builder builder = new AlertDialog.Builder( - PrefsActivity.this); - // "Select application" - builder.setTitle(getResources().getString( - R.string.jv_prefs_select_application)); - builder.setSingleChoiceItems(happlications, -1, - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int i) { - SharedPreferences.Editor editor = prefs - .edit(); - editor.putString("batButtonSTapp", - (String) applications[i]); - editor.commit(); - updatePrefSummary(pref); - dialog.dismiss(); - } - }); - builder.show(); - } - } - if (key.equals("batButtonDT")) { - if (sharedPreferences.getString(key, "NOTHING").equals("RUN")) { - AlertDialog.Builder builder = new AlertDialog.Builder( - PrefsActivity.this); - // "Select application" - builder.setTitle(getResources().getString( - R.string.jv_prefs_select_application)); - builder.setSingleChoiceItems(happlications, -1, - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int i) { - SharedPreferences.Editor editor = prefs - .edit(); - editor.putString("batButtonDTapp", - (String) applications[i]); - editor.commit(); - updatePrefSummary(pref); - dialog.dismiss(); - } - }); - builder.show(); - } - } - if (key.equals("batButtonLT")) { - if (sharedPreferences.getString(key, "NOTHING").equals("RUN")) { - AlertDialog.Builder builder = new AlertDialog.Builder( - PrefsActivity.this); - // "Select application" - builder.setTitle(getResources().getString( - R.string.jv_prefs_select_application)); - builder.setSingleChoiceItems(happlications, -1, - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int i) { - SharedPreferences.Editor editor = prefs - .edit(); - editor.putString("batButtonLTapp", - (String) applications[i]); - editor.commit(); - updatePrefSummary(pref); - dialog.dismiss(); - } - }); - builder.show(); - } - } - if (key.equals("appFavButtonST")) { - if (sharedPreferences.getString(key, "RELAUNCH").equals("RUN")) { - AlertDialog.Builder builder = new AlertDialog.Builder( - PrefsActivity.this); - // "Select application" - builder.setTitle(getResources().getString( - R.string.jv_prefs_select_application)); - builder.setSingleChoiceItems(happlications, -1, - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int i) { - SharedPreferences.Editor editor = prefs - .edit(); - editor.putString("appFavButtonSTapp", - (String) applications[i]); - editor.commit(); - updatePrefSummary(pref); - dialog.dismiss(); - } - }); - builder.show(); - } - } - if (key.equals("appFavButtonDT")) { - if (sharedPreferences.getString(key, "RELAUNCH").equals("RUN")) { - AlertDialog.Builder builder = new AlertDialog.Builder( - PrefsActivity.this); - // "Select application" - builder.setTitle(getResources().getString( - R.string.jv_prefs_select_application)); - builder.setSingleChoiceItems(happlications, -1, - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int i) { - SharedPreferences.Editor editor = prefs - .edit(); - editor.putString("appFavButtonDTapp", - (String) applications[i]); - editor.commit(); - updatePrefSummary(pref); - dialog.dismiss(); - } - }); - builder.show(); - } - } - if (key.equals("appFavButtonLT")) { - if (sharedPreferences.getString(key, "RELAUNCH").equals("RUN")) { - AlertDialog.Builder builder = new AlertDialog.Builder( - PrefsActivity.this); - // "Select application" - builder.setTitle(getResources().getString( - R.string.jv_prefs_select_application)); - builder.setSingleChoiceItems(happlications, -1, - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int i) { - SharedPreferences.Editor editor = prefs - .edit(); - editor.putString("appFavButtonLTapp", - (String) applications[i]); - editor.commit(); - updatePrefSummary(pref); - dialog.dismiss(); - } - }); - builder.show(); - } - } - + //======================================================================================================= + if (key.equals("dropboxSetButton")) { + checkSetDropboxAndOpds("dropboxSetButton", sharedPreferences.getString(key, "none"), sharedPreferences); + + }else if (key.equals("opdsSetButton")) { + checkSetDropboxAndOpds("opdsSetButton", sharedPreferences.getString(key, "none"), sharedPreferences); + + }else if(key.equals("homeButtonST") || key.equals("homeButtonDT") || key.equals("homeButtonLT") || + key.equals("lruButtonST") || key.equals("lruButtonDT") || key.equals("lruButtonLT") || + key.equals("favButtonST") || key.equals("favButtonDT") || key.equals("favButtonLT") || + key.equals("settingsButtonST") || key.equals("settingsButtonDT") || key.equals("settingsButtonLT") || + key.equals("advancedButtonST") || key.equals("advancedButtonDT") || key.equals("advancedButtonLT") || + key.equals("memButtonST") || key.equals("memButtonDT") || key.equals("memButtonLT") || + key.equals("batButtonST") || key.equals("batButtonDT") || key.equals("batButtonLT") || + key.equals("appFavButtonST") || key.equals("appFavButtonDT") || key.equals("appFavButtonLT") || + key.equals("appAllButtonST") || key.equals("appAllButtonDT") || key.equals("appAllButtonLT") || + key.equals("appLastButtonST") || key.equals("appLastButtonDT") || key.equals("appLastButtonLT") || + key.equals("searchButtonST") || key.equals("searchButtonDT") || key.equals("searchButtonLT")) + { + if (sharedPreferences.getString(key, "NOTHING").equals("RUN")) { + AlertDialog.Builder builder = new AlertDialog.Builder(PrefsActivity.this); + // "Select application" + builder.setTitle(getResources().getString(R.string.jv_prefs_select_application)); + builder.setSingleChoiceItems(happlications, -1, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog,int i) { + SharedPreferences.Editor editor = prefs.edit(); + editor.putString(key + "app", (String) applications[i]); + editor.commit(); + updatePrefSummary(pref); + dialog.dismiss(); + } + }); + builder.show(); + }else if (sharedPreferences.getString(key, "NOTHING").equals("FAVN")) { + AlertDialog.Builder builder1 = new AlertDialog.Builder(PrefsActivity.this); + // "Select number" + builder1.setTitle(getResources().getString( R.string.jv_prefs_select_number)); + final EditText input = new EditText(PrefsActivity.this); + input.setInputType(InputType.TYPE_CLASS_NUMBER); + input.setText(sharedPreferences.getString(key + "fav", "1")); + builder1.setView(input); + // "Ok" + builder1.setPositiveButton("OK", + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, + int whichButton) { + InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); + imm.hideSoftInputFromWindow(input.getWindowToken(), 0); + dialog.dismiss(); + SharedPreferences.Editor editor = prefs.edit(); + editor.putString(key + "fav", String.valueOf(input.getText())); + editor.commit(); + updatePrefSummary(pref); + } + }); + InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); + imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); + builder1.show(); + }else if (sharedPreferences.getString(key, "NOTHING").equals("LRUN")) { + AlertDialog.Builder builder1 = new AlertDialog.Builder(PrefsActivity.this); + // "Select number" + builder1.setTitle(getResources().getString(R.string.jv_prefs_select_number)); + final EditText input = new EditText(PrefsActivity.this); + input.setInputType(InputType.TYPE_CLASS_NUMBER); + input.setText(sharedPreferences.getString(key + "lru", "1")); + builder1.setView(input); + // "Ok" + builder1.setPositiveButton("OK", + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, + int whichButton) { + InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); + imm.hideSoftInputFromWindow( input.getWindowToken(), 0); + dialog.dismiss(); + SharedPreferences.Editor editor = prefs.edit(); + editor.putString(key + "lru", String.valueOf(input.getText())); + editor.commit(); + updatePrefSummary(pref); + } + }); + InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); + imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); + builder1.show(); + }else if (sharedPreferences.getString(key, "OPENMENU").equals("HOMEN")) { + AlertDialog.Builder builder1 = new AlertDialog.Builder( + PrefsActivity.this); + // "Select number" + builder1.setTitle(getResources().getString(R.string.jv_prefs_select_number)); + final EditText input = new EditText(PrefsActivity.this); + input.setInputType(InputType.TYPE_CLASS_NUMBER); + input.setText(sharedPreferences.getString(key + "home", "1")); + builder1.setView(input); + // "Ok" + builder1.setPositiveButton("OK", + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, + int whichButton) { + InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); + imm.hideSoftInputFromWindow(input.getWindowToken(), 0); + dialog.dismiss(); + SharedPreferences.Editor editor = prefs.edit(); + editor.putString(key + "home", String.valueOf(input.getText())); + editor.commit(); + updatePrefSummary(pref); + } + }); + InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); + imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); + builder1.show(); + } + checkSetDropboxAndOpds(key, sharedPreferences.getString(key, "none"), sharedPreferences); + } + } } public Preference.OnPreferenceClickListener prefScreenListener = new Preference.OnPreferenceClickListener() { public boolean onPreferenceClick(Preference pref) { - final PreferenceScreen prefScreen = (PreferenceScreen) pref; - LayoutInflater inflater = (LayoutInflater) getApplicationContext() - .getSystemService(Context.LAYOUT_INFLATER_SERVICE); + final PreferenceScreen prefScreen = (PreferenceScreen) pref; + + prefScreen.getDialog().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); + + LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); final View prefView = inflater.inflate(R.layout.prefs_main, null); + prefScreen.getDialog().setContentView(prefView); - final ListView prefListView = (ListView) prefView - .findViewById(android.R.id.list); + + final ListView prefListView = (ListView) prefView.findViewById(android.R.id.list); prefScreen.bind(prefListView); - EditText tEdit = (EditText) prefView - .findViewById(R.id.prefernces_title); + EditText tEdit = (EditText) prefView.findViewById(R.id.prefernces_title); tEdit.setText(pref.getTitle()); ImageButton b = (ImageButton) prefView.findViewById(R.id.back_btn); @@ -1482,12 +738,11 @@ public void onClick(View v) { } }); - ImageButton bu = (ImageButton) prefView - .findViewById(R.id.btn_scrollup); + ImageButton bu = (ImageButton) prefView.findViewById(R.id.btn_scrollup); bu.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { - if (DeviceInfo.EINK_NOOK) { + if (N2DeviceInfo.EINK_NOOK) { MotionEvent ev; ev = MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), @@ -1526,7 +781,7 @@ public void run() { bd.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { - if (DeviceInfo.EINK_NOOK) { + if (N2DeviceInfo.EINK_NOOK) { MotionEvent ev; ev = MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), @@ -1585,8 +840,8 @@ private boolean isPreferencesChanged() { private boolean isEqual(Object o1, Object o2) { boolean equal = true; if ((o1 instanceof Boolean) && (o2 instanceof Boolean)) { - boolean v1 = ((Boolean) o1).booleanValue(); - boolean v2 = ((Boolean) o2).booleanValue(); + boolean v1 = (Boolean) o1; + boolean v2 = (Boolean) o2; if (v1 != v2) equal = false; } else if ((o1 instanceof String) && (o2 instanceof String)) { @@ -1595,22 +850,140 @@ private boolean isEqual(Object o1, Object o2) { if (!v1.equalsIgnoreCase(v2)) equal = false; } else if ((o1 instanceof Integer) && (o2 instanceof Integer)) { - int v1 = ((Integer) o1).intValue(); - int v2 = ((Integer) o2).intValue(); + int v1 = (Integer) o1; + int v2 = (Integer) o2; if (v1 != v2) equal = false; } else if ((o1 instanceof Float) && (o2 instanceof Float)) { - float v1 = ((Float) o1).floatValue(); - float v2 = ((Float) o2).floatValue(); + float v1 = (Float) o1; + float v2 = (Float) o2; if (v1 != v2) equal = false; } else if ((o1 instanceof Long) && (o2 instanceof Long)) { - long v1 = ((Long) o1).longValue(); - long v2 = ((Long) o2).longValue(); + long v1 = (Long) o1; + long v2 = (Long) o2; if (v1 != v2) equal = false; } return equal; } + private void checkSetDropboxAndOpds(String button, String key, SharedPreferences sharedPreferences) { + String[] buttonName = {"homeButtonDT", "homeButtonLT", + "lruButtonDT", "lruButtonLT", + "favButtonDT", "favButtonLT", + "settingsButtonDT", "settingsButtonLT", + "advancedButtonDT", "advancedButtonLT", + "memButtonDT", "memButtonLT", + "batButtonDT", "batButtonLT", + "appFavButtonDT", "appFavButtonLT", + "appAllButtonDT", "appAllButtonLT", + "appLastButtonDT", "appLastButtonLT", + "searchButtonDT", "searchButtonLT", + "opdsSetButton", "dropboxSetButton"}; + boolean f_butt = false; + for (String aButtonName : buttonName) { + if (aButtonName.equals(button)) { + f_butt = true; + break; + } + } + if(!f_butt){ + return; + } + + boolean newOPDS = false; + boolean newDropbox = false; + SharedPreferences.Editor editor = prefs.edit(); + + if("OPDS".equals(key)){ + newOPDS = true; + } + if("DROPBOX".equals(key)){ + newDropbox = true; + } + if(!"dropboxSetButton".equals(button) && !"opdsSetButton".equals(button)){ + // действия при выборе из меню кнопок экрана + do_pref_subrequest = false; + String tempValue = ((ListPreference) findPreference("dropboxSetButton")).getValue(); + if(button.equals(tempValue)){ + if(!key.equals("DROPBOX")){ + ((ListPreference) findPreference("dropboxSetButton")).setValueIndex(0); + editor.putString("dropboxSetButton", "NOTHING"); + } + } + if(button.equals(((ListPreference) findPreference("opdsSetButton")).getValue())){ + if(!key.equals("OPDS")){ + ((ListPreference) findPreference("opdsSetButton")).setValueIndex(0); + editor.putString("opdsSetButton", "NOTHING"); + } + } + + // если новые настройки + if(newDropbox || newOPDS){ + //сбрасываем на всех остальных настройки + for (int i = 0, j=buttonName.length; i < j; i++) { + if(!buttonName[i].equals(button)){ + // сбрасываем настройки если совпадают с проверяемыми + if(sharedPreferences.getString(buttonName[i], "none").equals(key)){ + ((ListPreference) findPreference(buttonName[i])).setValueIndex(0); + editor.putString(buttonName[i], "NOTHING"); + } + }else{ // сохраняем настройки в модулях + if(newOPDS){ + ((ListPreference) findPreference("opdsSetButton")).setValueIndex(i); + editor.putString("opdsSetButton",buttonName[i]); + } + if(newDropbox){ + ((ListPreference) findPreference("dropboxSetButton")).setValueIndex(i); + editor.putString("dropboxSetButton",buttonName[i]); + } + } + } + } + editor.commit(); + do_pref_subrequest = true; + }else { + // действия при выборе в самих настройках модулей + do_pref_subrequest = false; + int indexValue = 0; + if("dropboxSetButton".equals(button)){ + indexValue = ((ListPreference) findPreference(key)).findIndexOfValue("DROPBOX"); + editor.putString(key, "DROPBOX"); + if(sharedPreferences.getString("opdsSetButton", "none").equals(key)){ + ((ListPreference) findPreference("opdsSetButton")).setValueIndex(0); + editor.putString("opdsSetButton", "NOTHING"); + } + button = key; + key = "DROPBOX"; + } + if("opdsSetButton".equals(button)){ + indexValue = ((ListPreference) findPreference(key)).findIndexOfValue("OPDS"); + editor.putString(key, "OPDS"); + if(sharedPreferences.getString("dropboxSetButton", "none").equals(key)){ + ((ListPreference) findPreference("dropboxSetButton")).setValueIndex(0); + editor.putString("dropboxSetButton", "NOTHING"); + } + button = key; + key = "OPDS"; + } + //сбрасываем на всех остальных настройки + if("OPDS".equals(key) || "DROPBOX".equals(key)){ + for (String aButtonName : buttonName) { + if (!aButtonName.equals(button)) { + // сбрасываем настройки если совпадают с проверяемыми + if (sharedPreferences.getString(aButtonName, "NOTHING").equals(key)) { + ((ListPreference) findPreference(aButtonName)).setValueIndex(0); + editor.putString(aButtonName, "NOTHING"); + } + } + } + ((ListPreference) findPreference(button)).setValueIndex(indexValue); + editor.commit(); + } + do_pref_subrequest = true; + } + + } + } diff --git a/src/com/harasoft/relaunch/ReLaunch.java b/src/com/harasoft/relaunch/ReLaunch.java index 110ca32..79f51fa 100644 --- a/src/com/harasoft/relaunch/ReLaunch.java +++ b/src/com/harasoft/relaunch/ReLaunch.java @@ -1,39 +1,8 @@ package com.harasoft.relaunch; -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Calendar; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.Stack; - -import ebook.EBook; -import ebook.parser.InstantParser; -import ebook.parser.Parser; -import android.R.style; -import android.app.Activity; -import android.app.ActivityManager; -import android.app.AlertDialog; +import android.app.*; import android.app.ActivityManager.MemoryInfo; -import android.app.Dialog; -import android.content.ActivityNotFoundException; -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.content.IntentFilter; -import android.content.SharedPreferences; +import android.content.*; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.Bitmap; @@ -42,6 +11,7 @@ import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.ConnectivityManager; +import android.net.NetworkInfo; import android.net.Uri; import android.net.wifi.WifiManager; import android.os.BatteryManager; @@ -52,38 +22,27 @@ import android.text.SpannableString; import android.text.TextUtils.TruncateAt; import android.text.style.StyleSpan; -import android.util.Log; + import android.util.TypedValue; -import android.view.GestureDetector; +import android.view.*; import android.view.GestureDetector.SimpleOnGestureListener; -import android.view.KeyEvent; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.MenuItem; -import android.view.MotionEvent; -import android.view.View; import android.view.View.MeasureSpec; import android.view.View.OnTouchListener; -import android.view.ViewGroup; -import android.view.Window; -import android.view.WindowManager; import android.webkit.WebView; -import android.widget.AdapterView; -import android.view.LayoutInflater; -import android.widget.AbsListView; -import android.widget.ArrayAdapter; -import android.widget.Button; -import android.widget.EditText; -import android.widget.GridView; -import android.widget.ImageButton; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.ListView; -import android.widget.LinearLayout.LayoutParams; -import android.widget.ListAdapter; -import android.widget.SimpleAdapter; -import android.widget.TextView; -import android.widget.Toast; +import android.widget.*; +import com.dropbox.client2.DropboxAPI; +import com.dropbox.client2.android.AndroidAuthSession; +import com.dropbox.client2.android.AuthActivity; +import com.dropbox.client2.exception.DropboxException; +import com.dropbox.client2.session.AccessTokenPair; +import com.dropbox.client2.session.AppKeyPair; +import com.dropbox.client2.session.Session; +import ebook.EBook; +import ebook.parser.InstantParser; +import ebook.parser.Parser; + +import java.io.*; +import java.util.*; public class ReLaunch extends Activity { @@ -96,11 +55,18 @@ public class ReLaunch extends Activity { static public final String HIST_FILE = "History.txt"; static public final String FILT_FILE = "Filters.txt"; static public final String COLS_FILE = "Columns.txt"; - final String defReaders = ".fb2,.fb2.zip:org.coolreader%org.coolreader.CoolReader%Cool Reader|.epub:Intent:application/epub|.jpg,.jpeg:Intent:image/jpeg" - + "|.png:Intent:image/png|.pdf:Intent:application/pdf" - + "|.djv,.djvu:Intent:image/vnd.djvu|.doc:Intent:application/msword" + final String defReaders = ".epub:Intent:application/epub" + + "|.fb2:Intent:application/fb2" + + "|.fb2.zip:Intent:application/fb2.zip" + + "|.jpg,.jpeg:Intent:image/jpeg" + + "|.png:Intent:image/png" + + "|.pdf:Intent:application/pdf" + + "|.djvu:Intent:application/djvu" + + "|.djv:Intent:application/djvu" + + "|.doc:Intent:application/msword" + "|.chm,.pdb,.prc,.mobi,.azw:org.coolreader%org.coolreader.CoolReader%Cool Reader" - + "|.cbz,.cb7:Intent:application/x-cbz|.cbr:Intent:application/x-cbr"; + + "|.cbz,.cb7:Intent:application/x-cbz" + + "|.cbr:Intent:application/x-cbr"; final static public String defReader = "org.coolreader%org.coolreader.CoolReader%Cool Reader"; final static public int TYPES_ACT = 1; final static public int DIR_ACT = 2; @@ -119,33 +85,33 @@ public class ReLaunch extends Activity { final static int CNTXT_MENU_PASTE = 13; final static int CNTXT_MENU_RENAME = 14; final static int CNTXT_MENU_CREATE_DIR = 15; - final static int CNTXT_MENU_COPY_DIR = 16; - final static int CNTXT_MENU_MOVE_DIR = 17; - final static int CNTXT_MENU_SWITCH_TITLES = 18; - final static int CNTXT_MENU_TAGS_RENAME = 19; - final static int CNTXT_MENU_ADD_STARTDIR = 20; - final static int CNTXT_MENU_SHOW_BOOKINFO = 21; - final static int CNTXT_MENU_FILE_INFO = 22; - final static int CNTXT_MENU_SET_STARTDIR = 23; - final static int BROWSE_FILES = 0; - final static int BROWSE_TITLES = 1; - final static int BROWSE_COVERS = 2; + final static int CNTXT_MENU_SWITCH_TITLES = 16; + final static int CNTXT_MENU_TAGS_RENAME = 17; + final static int CNTXT_MENU_ADD_STARTDIR = 18; + final static int CNTXT_MENU_SHOW_BOOKINFO = 19; + final static int CNTXT_MENU_FILE_INFO = 20; + final static int CNTXT_MENU_SET_STARTDIR = 21; + final static int CNTXT_MENU_COPY_DROPBOX = 22; + final static int CNTXT_MENU_COPY_DIR_DROPBOX = 23; + final static int CNTXT_MENU_SETTINGS = 24; + final static int CNTXT_MENU_SELECTE = 25; + final static int SORT_FILES_ASC = 0; final static int SORT_FILES_DESC = 1; final static int SORT_TITLES_ASC = 2; final static int SORT_TITLES_DESC = 3; - String currentRoot = "/sdcard"; - Integer currentPosition = -1; + public static String BACKUP_DIR = "/sdcard/.relaunch"; + static String currentRoot = "/sdcard"; + static int currentPosition = -1; List> itemsArray; Stack positions = new Stack(); SimpleAdapter adapter; - SharedPreferences prefs; + static SharedPreferences prefs; + static SharedPreferences.Editor prefsEditor; ReLaunchApp app; static public boolean useHome = false; static boolean useHome1 = false; - static boolean useShop = false; - static boolean useLibrary = false; - boolean useDirViewer = false; + static public boolean filterMyself = true; static public String selfName = "com.harasoft.relaunch.Main"; String[] allowedModels; @@ -153,10 +119,11 @@ public class ReLaunch extends Activity { String[] allowedManufacts; String[] allowedProducts; boolean addSView = true; + static boolean disableScrollJump; // multicolumns per directory configuration - List columnsArray = new ArrayList(); - Integer currentColsNum = -1; + //List columnsArray = new ArrayList(); + int currentColsNum = -1; // Bottom info panel BroadcastReceiver batteryLevelReceiver = null; @@ -169,12 +136,69 @@ public class ReLaunch extends Activity { TextView battTitle; TextView battLevel; IntentFilter batteryLevelFilter; - - String fileOpFile; - String fileOpDir; + + String fileOpFile[]; + String fileOpDir[]; int fileOp; final String[] sortType = new String[] {"sname"}; final boolean[] sortOrder = new boolean[] {true}; + ArrayList arrIcon = new ArrayList(); + ArrayList arrSelItem = new ArrayList(); + + //=================== Show panel ============== + boolean showOnePanel = true; + boolean showTwoPanel = true; + boolean showThreePanel = true; + boolean showFourPanel = true; + // ====== FLSimpleAdapter================================================================== + boolean useFaces; + int firstLineIconSizePx; + int firstLineFontSizePx; + int secondLineFontSizePx; + boolean doNotHyph; + boolean hideKnownExts; + boolean showBookTitles; + boolean rowSeparator; + static ArrayList exts; + String intentStartDir = null; + LayoutInflater vi; + //================================================================================= + // ====== refreshBottomInfo================================================================== + boolean dateUS; + //================================================================================= + // ====== getAutoColsNum================================================================== + static String columnsAlgIntensity; + //================================================================================= + // ====== redrawList================================================================== + boolean filterResults; + //================================================================================= + // ====== setUpButton================================================================== + boolean notLeaveStartDir; + static String[] startDir; + Button upButton; + String upDir = ""; + //================================================================================= + // ====== drawDirectory================================================================== + boolean showFullDirPath; + boolean showHidden; + String bookTitleFormat; + Button tv_title; + GridView gvList; + Button upScroll; + Button downScroll; + String lastdir; + //================================================================================= + // for dropbox + public static DropboxAPI mDBApi; + final static private String APP_KEY = "2vfpyoojj4rsi5t"; + final static private String APP_SECRET = "m6okqlqhi1nugq1"; + final static private Session.AccessType ACCESS_TYPE = Session.AccessType.DROPBOX; + + final static public String ACCOUNT_PREFS_NAME = "prefs"; + final static public String ACCESS_KEY_NAME = "ACCESS_KEY"; + final static public String ACCESS_SECRET_NAME = "ACCESS_SECRET"; + + //=================================================== private void actionSwitchWiFi() { WifiManager wifiManager; @@ -212,6 +236,7 @@ private void saveLast() { try { appLruMax = Integer.parseInt(prefs.getString("appLruSize", "30")); } catch (NumberFormatException e) { + // emply } app.writeFile("app_last", ReLaunch.APP_LRU_FILE, appLruMax, ":"); } @@ -255,45 +280,15 @@ private void actionRun(String appspec) { } } - private void setEinkController() { - if (prefs != null) { - Integer einkUpdateMode = 1; - try { - einkUpdateMode = Integer.parseInt(prefs.getString( - "einkUpdateMode", "1")); - } catch (Exception e) { - einkUpdateMode = 1; - } - if (einkUpdateMode < -1 || einkUpdateMode > 2) - einkUpdateMode = 1; - if (einkUpdateMode >= 0) { - EinkScreen.UpdateMode = einkUpdateMode; - - Integer einkUpdateInterval = 10; - try { - einkUpdateInterval = Integer.parseInt(prefs.getString( - "einkUpdateInterval", "10")); - } catch (Exception e) { - einkUpdateInterval = 10; - } - if (einkUpdateInterval < 0 || einkUpdateInterval > 100) - einkUpdateInterval = 10; - EinkScreen.UpdateModeInterval = einkUpdateInterval; - - EinkScreen.PrepareController(null, false); - } - } - } - private boolean checkField(String[] a, String f) { - for (int i = 0; i < a.length; i++) - if (a[i].equals("*") || a[i].equals(f)) - return true; + for (String anA : a) { + if (anA.equals("*") || anA.equals(f)) + return true; + } return false; } - private void checkDevice(String dev, String man, String model, - String product) { + private void checkDevice(String dev, String man, String model,String product) { if (checkField(allowedModels, model)) return; if (checkField(allowedDevices, dev)) @@ -310,24 +305,22 @@ private void checkDevice(String dev, String man, String model, getResources().getString(R.string.model_warning), "text/html", "utf-8", null); // "Wrong model !" - builder.setTitle(getResources().getString( - R.string.jv_relaunch_wrong_model)); + builder.setTitle(getResources().getString(R.string.jv_relaunch_wrong_model)); builder.setView(wv); // "YES" builder.setPositiveButton( - getResources().getString(R.string.jv_relaunch_yes), + getResources().getString(R.string.app_yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { - SharedPreferences.Editor editor = prefs.edit(); - editor.putBoolean("allowDevice", true); - editor.commit(); + prefsEditor.putBoolean("allowDevice", true); + prefsEditor.commit(); dialog.dismiss(); } }); // "NO" builder.setNegativeButton( - getResources().getString(R.string.jv_relaunch_no), + getResources().getString(R.string.app_no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -358,338 +351,178 @@ private Bitmap scaleDrawable(Drawable d, int size) { size, size, true); } - class FLSimpleAdapter extends SimpleAdapter { + class FLSimpleAdapter1 extends SimpleAdapter { - FLSimpleAdapter(Context context, List> data, - int resource, String[] from, int[] to) { + FLSimpleAdapter1(Context context, List> data, int resource, String[] from, int[] to) { super(context, data, resource, from, to); } @Override public int getCount() { - return itemsArray.size(); + if(itemsArray == null){ + return 0; + }else{ + return itemsArray.size(); + } } @Override public View getView(int position, View convertView, ViewGroup parent) { - ViewHolder holder; - View v = convertView; -// if ((prefs.getBoolean("showBookTiles", false)) || (v == null)) { - if (v == null) { - LayoutInflater vi = (LayoutInflater) getApplicationContext() - .getSystemService(Context.LAYOUT_INFLATER_SERVICE); + ViewHolder holder; // перечень элементов на создаваемом объекте + View v = convertView; // передаваемый тэг ?????? + HashMap item = itemsArray.get(position); // получаем карту для указанной позиции + if (v == null) { // если нет объекта то создаем его + //LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.flist_layout, null); + if(v == null){ + return null; + } holder = new ViewHolder(); holder.tv = (TextView) v.findViewById(R.id.fl_text); holder.tv2 = (TextView) v.findViewById(R.id.fl_text2); holder.iv = (ImageView) v.findViewById(R.id.fl_icon); holder.is = (ImageView) v.findViewById(R.id.fl_separator); - holder.tvHolder = (LinearLayout) v.findViewById(R.id.fl_holder); + holder.tvHolder = (LinearLayout) v.findViewById(R.id.grid_cell); + // проверяем на однострочный режим + if (doNotHyph) { + holder.tv.setLines(1); // первой - только одна строка + holder.tv.setHorizontallyScrolling(true); // разрешить прокрутку по горизонтали + holder.tv.setEllipsize(TruncateAt.END); // многоточие на конце видимой части + holder.tv2.setLines(1); // только одна строка + holder.tv2.setHorizontallyScrolling(true); // прокрутка + holder.tv2.setEllipsize(TruncateAt.END); // многоточие + } + // если разделитель запрещен + if (!rowSeparator){ + holder.is.setVisibility(View.GONE);// выключаем его + } + v.setTag(holder); - } else + } else{ holder = (ViewHolder) v.getTag(); - if (prefs.getBoolean("doNotHyph", false)) { - holder.tv.setLines(1); - holder.tv.setHorizontallyScrolling(true); - holder.tv.setEllipsize(TruncateAt.END); - holder.tv2.setLines(1); - holder.tv2.setHorizontallyScrolling(true); - holder.tv2.setEllipsize(TruncateAt.END); - } - // known extensions - List> rc; - ArrayList exts = new ArrayList(); - - if (prefs.getBoolean("hideKnownExts", false)) { - rc = app.getReaders(); - Set tkeys = new HashSet(); - for (int i = 0; i < rc.size(); i++) { - Object[] keys = rc.get(i).keySet().toArray(); - for (int j = 0; j < keys.length; j++) { - tkeys.add(keys[j].toString()); - } - } - exts = new ArrayList(tkeys); - final class ExtsComparator implements - java.util.Comparator { - public int compare(String a, String b) { - if (a == null && b == null) - return 0; - if (a == null && b != null) - return 1; - if (a != null && b == null) - return -1; - if (a.length() < b.length()) - return 1; - if (a.length() > b.length()) - return -1; - return a.compareTo(b); - } - } - Collections.sort(exts, new ExtsComparator()); - } - - HashMap item = itemsArray.get(position); + } + if (firstLineIconSizePx == 0) { // если отключены картинки + holder.iv.setVisibility(View.GONE); // скрываем поле с ними + }else { + String temp_nameIcon = item.get("nameIcon"); + for (imageIcon anArrIcon : arrIcon) { + if (anArrIcon.nameIcon.equals(temp_nameIcon)) { + holder.iv.setImageBitmap(anArrIcon.icon); + break; + } + } + } + // проверяем на существование if (item != null) { - TextView tv = holder.tv; - TextView tv2 = holder.tv2; - LinearLayout tvHolder = holder.tvHolder; - ImageView iv = holder.iv; - ImageView is = holder.is; - if (!prefs.getBoolean("rowSeparator", false)) - is.setVisibility(View.GONE); - - String sname = item.get("sname"); - // clean extension, if needed - if (prefs.getBoolean("hideKnownExts", false) && !prefs.getBoolean("showBookTitles", false)) { - for (int i = 0; i < exts.size(); i++) { - if (sname.endsWith(exts.get(i))) { - sname = sname.substring(0, sname.length() - - exts.get(i).length()); - } - } - } - + // ============================================ + // получаем полное имя файла с путем String fname = item.get("fname"); + // выделение жирым boolean setBold = false; - boolean useFaces = prefs.getBoolean("showNew", true); - tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, Integer - .parseInt(prefs.getString("firstLineFontSizePx", "20"))); - tv2.setTextSize(TypedValue.COMPLEX_UNIT_PX, Integer - .parseInt(prefs.getString("secondLineFontSizePx", "16"))); + // устанавливаем размеры шрифтов + holder.tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, firstLineFontSizePx); + holder.tv2.setTextSize(TypedValue.COMPLEX_UNIT_PX, secondLineFontSizePx); + + // определяем папка это или файл + int color_txt = getResources().getColor(R.color.file_new_fg); + int backgroung_txt = getResources().getColor(R.color.file_new_bg); if (item.get("type").equals("dir")) { - tv2.setVisibility(View.GONE); - tv2.getLayoutParams().height = 0; - if (useFaces) { - tvHolder.setBackgroundColor(getResources().getColor( - R.color.dir_bg)); - tv.setTextColor(getResources().getColor(R.color.dir_fg)); - } - if (prefs.getString("firstLineIconSizePx", "48") - .equals("0")) { - iv.setVisibility(View.GONE); - } else { - iv.setImageBitmap(scaleDrawableById(R.drawable.dir_ok, - Integer.parseInt(prefs.getString( - "firstLineIconSizePx", "48")))); - } + holder.tv2.setVisibility(View.GONE); // скрываем вторую строку } else { - if (useFaces) { - if (app.history.containsKey(fname)) { - if (app.history.get(fname) == app.READING) { - tvHolder.setBackgroundColor(getResources() - .getColor(R.color.file_reading_bg)); - tv.setTextColor(getResources().getColor( - R.color.file_reading_fg)); - tv2.setTextColor(getResources().getColor( - R.color.file_reading_fg)); - } else if (app.history.get(fname) == app.FINISHED) { - tvHolder.setBackgroundColor(getResources() - .getColor(R.color.file_finished_bg)); - tv.setTextColor(getResources().getColor( - R.color.file_finished_fg)); - tv2.setTextColor(getResources().getColor( - R.color.file_finished_fg)); - } else { - tvHolder.setBackgroundColor(getResources() - .getColor(R.color.file_unknown_bg)); - tv.setTextColor(getResources().getColor( - R.color.file_unknown_fg)); - tv2.setTextColor(getResources().getColor( - R.color.file_unknown_fg)); + if (useFaces) { // прочитанные/новые + if (app.history.containsKey(fname)) { // смотрим историю по файлу + int baseHistory = app.history.get(fname); + if (baseHistory == app.READING) { // если в базе - читается + color_txt = getResources().getColor(R.color.file_reading_fg); + backgroung_txt = getResources().getColor(R.color.file_reading_bg); + } else if (baseHistory == app.FINISHED) { // если в базе прочитано + color_txt = getResources().getColor(R.color.file_finished_fg); + backgroung_txt = getResources().getColor(R.color.file_finished_bg); + } else { // при других раскладах + color_txt = getResources().getColor(R.color.file_unknown_fg); + backgroung_txt = getResources().getColor(R.color.file_unknown_bg); } - } else { - tvHolder.setBackgroundColor(getResources() - .getColor(R.color.file_new_bg)); - tv.setTextColor(getResources().getColor( - R.color.file_new_fg)); - tv2.setTextColor(getResources().getColor( - R.color.file_new_fg)); - if (getResources().getBoolean( - R.bool.show_new_as_bold)) - setBold = true; + } else { // если файл определен как новый + color_txt = getResources().getColor(R.color.file_new_fg); + backgroung_txt = getResources().getColor(R.color.file_new_bg); + //if (getResources().getBoolean(R.bool.show_new_as_bold)) + setBold = true; } } - // setup icon - if (prefs.getString("firstLineIconSizePx", "48") - .equals("0")) { - iv.setVisibility(View.GONE); - } else { - Drawable d = app.specialIcon(item.get("fname"), false); - if (d != null) - iv.setImageBitmap(scaleDrawable(d, Integer - .parseInt(prefs.getString( - "firstLineIconSizePx", "48")))); - else { - String rdrName = item.get("reader"); - if (rdrName.equals("Nope")) { - File f = new File(item.get("fname")); - if (f.length() > app.viewerMax*1024) - iv.setImageBitmap(scaleDrawableById( - R.drawable.file_notok, - Integer.parseInt(prefs - .getString( - "firstLineIconSizePx", - "48")))); - else - iv.setImageBitmap(scaleDrawableById( - R.drawable.file_ok, - Integer.parseInt(prefs - .getString( - "firstLineIconSizePx", - "48")))); - } else if (rdrName.startsWith("Intent:")) - iv.setImageBitmap(scaleDrawableById( - R.drawable.icon, Integer.parseInt(prefs - .getString( - "firstLineIconSizePx", - "48")))); - else { - if (app.getIcons().containsKey(rdrName)) - iv.setImageBitmap(scaleDrawable( - app.getIcons().get(rdrName), - Integer.parseInt(prefs - .getString( - "firstLineIconSizePx", - "48")))); - else - iv.setImageBitmap(scaleDrawableById( - R.drawable.file_ok, - Integer.parseInt(prefs - .getString( - "firstLineIconSizePx", - "48")))); - } - } - } } - + if(arrSelItem.contains(position)){ + holder.tv.setTextColor(backgroung_txt); + holder.tv2.setTextColor(backgroung_txt); + holder.tvHolder.setBackgroundColor(getResources().getColor(R.color.file_finished_bg)); + }else{ + holder.tv.setTextColor(color_txt); + holder.tv2.setTextColor(color_txt); + holder.tvHolder.setBackgroundColor(backgroung_txt); + } + + String sname = item.get("sname"); // получаем имя + // делаем копию в первую строку String sname1 = sname; + // пустая вторая String sname2 = ""; + // находим номер места с символом перевода каретки ??? накуя? int newLinePos = sname.indexOf('\n'); - if ((newLinePos != -1) && (newLinePos != 0)) { + + if (newLinePos > 0) {// если есть такой, то разбиваем на подстроки sname1 = sname.substring(0, newLinePos).trim(); sname2 = sname.substring(newLinePos, sname.length()).trim(); } + // если идет отображение прочитанных/новых if (useFaces) { SpannableString s1 = new SpannableString(sname1); - s1.setSpan(new StyleSpan(setBold ? Typeface.BOLD - : Typeface.NORMAL), 0, sname1.length(), 0); - tv.setText(s1); + s1.setSpan(new StyleSpan(setBold ? Typeface.BOLD : Typeface.NORMAL), 0, sname1.length(), 0); + holder.tv.setText(s1); if (!sname2.equalsIgnoreCase("")) { SpannableString s2 = new SpannableString(sname2); - s2.setSpan(new StyleSpan(setBold ? Typeface.BOLD - : Typeface.NORMAL), 0, sname2.length(), 0); - tv2.setText(s2); + s2.setSpan(new StyleSpan(setBold ? Typeface.BOLD : Typeface.NORMAL), 0, sname2.length(), 0); + holder.tv2.setText(s2); } } else { - tvHolder.setBackgroundColor(getResources().getColor( - R.color.normal_bg)); - tv.setTextColor(getResources().getColor(R.color.normal_fg)); - tv.setText(sname1); - tv2.setTextColor(getResources().getColor(R.color.normal_fg)); - tv2.setText(sname2); + holder.tv.setText(sname1); + holder.tv2.setText(sname2); } + // если есть вторая строка, то вытаскиваем ее??? иначе скрываем if (sname2.equalsIgnoreCase("")) { - tv2.setVisibility(View.GONE); + holder.tv2.setVisibility(View.GONE); } else { - tv2.setVisibility(View.VISIBLE); + holder.tv2.setVisibility(View.VISIBLE); } + } // fixes on rows height in grid + // если у грида не одна колонка, то выравниваем ячейки по высоте в одной строке if (currentColsNum != 1) { - GridView pgv = (GridView) parent; - Integer gcols = currentColsNum; - Integer between_columns = 0; // configure ??? - Integer after_row_space = 0; // configure ??? - Integer colw = (pgv.getWidth() - (gcols - 1) * between_columns) - / gcols; - Integer recalc_num = position; - Integer recalc_height = 0; - while (recalc_num % gcols != 0) { + int colw = (gvList.getWidth()) / currentColsNum; // получаем ширину колонки + int recalc_num = position; // номер позиции + int recalc_height = 0; + View temp_v; + while (recalc_num % currentColsNum != 0) { // находим последний элемент в строке recalc_num = recalc_num - 1; - View temp_v = getView(recalc_num, null, parent); - temp_v.measure(MeasureSpec.EXACTLY | colw, - MeasureSpec.UNSPECIFIED); - Integer p_height = temp_v.getMeasuredHeight(); - if (p_height > recalc_height) - recalc_height = p_height; + temp_v = getView(recalc_num, null, parent); + if(temp_v != null){ + temp_v.measure(MeasureSpec.EXACTLY | colw, MeasureSpec.UNSPECIFIED); + int p_height = temp_v.getMeasuredHeight(); + if (p_height > 0) + recalc_height = p_height; + } } if (recalc_height > 0) { - v.setMinimumHeight(recalc_height + after_row_space); + v.setMinimumHeight(recalc_height); } } return v; } } - private Integer Percentile(ArrayList values, Integer Quantile) - // not fully "mathematical proof", but not too difficult and working - { - Collections.sort(values); - Integer index = (values.size() * Quantile) / 100; - return values.get(index); - } - - private Integer getAutoColsNum() { - // implementation - via percentiles len - Integer auto_cols_num = 1; - ArrayList tmp = new ArrayList(); - if (itemsArray.size() > 0) { - Integer factor = 0; - for (Integer i = 0; i < itemsArray.size(); i++) { - tmp.add(itemsArray.get(i).get("sname").length()); - } - String pattern = prefs.getString("columnsAlgIntensity", - "70 3:5 7:4 15:3 48:2"); // default - medium - String[] spat = pattern.split("[\\s\\:]+"); - Integer quantile = Integer.parseInt(spat[0]); - factor = Percentile(tmp, quantile); - for (Integer i = 1; i < spat.length; i = i + 2) { - try { - double fval = Double.parseDouble(spat[i]); - int cval = Integer.parseInt(spat[i + 1]); - if (factor <= fval) { - auto_cols_num = cval; - break; - } - } catch (Exception e) { - } - } - } - if (auto_cols_num > itemsArray.size()) - auto_cols_num = itemsArray.size(); - return auto_cols_num; - } - - private void redrawList() { - setEinkController(); - GridView gv = (GridView) findViewById(useDirViewer ? R.id.results_list - : R.id.gl_list); - if (prefs.getBoolean("filterResults", false)) { - List> newItemsArray = new ArrayList>(); - - for (HashMap item : itemsArray) { - if (item.get("type").equals("dir") - || app.filterFile(item.get("dname"), item.get("name"))) - newItemsArray.add(item); - } - itemsArray = newItemsArray; - } - adapter.notifyDataSetChanged(); - int curPos = prefs.getInt("posInFolder", 0); - SharedPreferences.Editor editor = prefs.edit(); - editor.putInt("posInFolder", 0); - editor.commit(); - gv.setSelection(curPos); -// gv.invalidate(); - } - - private static List> parseReadersString( - String readerList) { + private static List> parseReadersString(String readerList) { List> rc = new ArrayList>(); String[] rdrs = readerList.split("\\|"); for (int i = 0; i < rdrs.length; i++) { @@ -698,8 +531,9 @@ private static List> parseReadersString( case 2: String rName = re[1]; String[] exts = re[0].split(","); + String ext; for (int j = 0; j < exts.length; j++) { - String ext = exts[j]; + ext = exts[j]; HashMap r = new HashMap(); r.put(ext, rName); rc.add(r); @@ -709,10 +543,11 @@ private static List> parseReadersString( if (re[1].equals("Intent")) { String iType = re[2]; String[] exts1 = re[0].split(","); + String ext1; for (int j = 0; j < exts1.length; j++) { - String ext = exts1[j]; + ext1 = exts1[j]; HashMap r = new HashMap(); - r.put(ext, "Intent:" + iType); + r.put(ext1, "Intent:" + iType); rc.add(r); } } @@ -723,8 +558,7 @@ private static List> parseReadersString( } public static String createReadersString(List> rdrs) { - String rc = new String(); - + String rc = ""; for (HashMap r : rdrs) { for (String key : r.keySet()) { if (!rc.equals("")) @@ -742,58 +576,30 @@ private void pushCurrentPos(AdapterView parent, boolean push_to_stack) { currentPosition = p1; } - private void setUpButton(final Button up, final String upDir, String currDir) { - if (up != null) { + private void setUpButton(String currDir) { + + String tempDB = currDir; + if (upButton != null) { // more versatile check against home, if needed boolean enabled = !upDir.equals(""); - if (enabled && !currDir.equals("/") - && prefs.getBoolean("notLeaveStartDir", false)) { + if(currDir.startsWith("Dropbox| ")){ + tempDB = currDir.substring("Dropbox| ".length()); + if("Dropbox| ".length() == upDir.length()){ + enabled = false; + } + + } + if (enabled && !tempDB.equals("/") && notLeaveStartDir) { enabled = false; - String[] homes = prefs.getString("startDir", - "/sdcard,/media/My Files").split("\\,"); - for (int i = 0; i < homes.length; i++) { - if (homes[i].length() < currDir.length() - && currDir.startsWith(homes[i])) { - enabled = true; - break; - } - } - } - up.setEnabled(enabled); - // gesture listener - class UpSimpleOnGestureListener extends SimpleOnGestureListener { - @Override - public boolean onSingleTapConfirmed(MotionEvent e) { - if (!upDir.equals("")) { - Integer p = -1; - if (!positions.empty()) - p = positions.pop(); - drawDirectory(upDir, p); - } - return true; - } - @Override - public boolean onDoubleTap(MotionEvent e) { - return true; - } - - @Override - public void onLongPress(MotionEvent e) { - if (up.hasWindowFocus()) { - - } - } + for (String home : startDir) { + if (home.length() < currDir.length() && currDir.startsWith(home)) { + enabled = true; + break; + } + } } - ; - UpSimpleOnGestureListener up_gl = new UpSimpleOnGestureListener(); - final GestureDetector up_gd = new GestureDetector(up_gl); - up.setOnTouchListener(new OnTouchListener() { - public boolean onTouch(View v, MotionEvent event) { - up_gd.onTouchEvent(event); - return false; - } - }); + upButton.setEnabled( enabled); } } @@ -801,7 +607,7 @@ private void refreshBottomInfo() { // Date String d; Calendar c = Calendar.getInstance(); - if (prefs.getBoolean("dateUS", false)) + if (dateUS) d = String.format("%02d:%02d%s %02d/%02d/%02d", c.get(Calendar.HOUR), c.get(Calendar.MINUTE), ((c.get(Calendar.AM_PM) == 0) ? "AM" : "PM"), @@ -812,14 +618,14 @@ private void refreshBottomInfo() { c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.MONTH) + 1, (c.get(Calendar.YEAR) - 2000)); - if (memTitle != null) + if (memTitle != null && useHome && showFourPanel) memTitle.setText(d); // Memory MemoryInfo mi = new MemoryInfo(); ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); activityManager.getMemoryInfo(mi); - if (memLevel != null) { + if (memLevel != null && useHome && showFourPanel) { // "M free" memLevel.setText(mi.availMem / 1048576L + getResources().getString(R.string.jv_relaunch_m_free)); @@ -829,22 +635,20 @@ private void refreshBottomInfo() { // Wifi status WifiManager wfm = (WifiManager) getSystemService(Context.WIFI_SERVICE); - if (battTitle != null) { + if (battTitle != null && useHome && showFourPanel) { if (wfm.isWifiEnabled()) { String nowConnected = wfm.getConnectionInfo().getSSID(); if (nowConnected != null && !nowConnected.equals("")) { battTitle.setText(nowConnected); } else { - battTitle.setText(getResources().getString( - R.string.jv_relaunch_wifi_is_on)); + battTitle.setText(getResources().getString(R.string.jv_relaunch_wifi_is_on)); } battTitle.setCompoundDrawablesWithIntrinsicBounds( getResources().getDrawable(R.drawable.wifi_on), null, null, null); } else { // "WiFi is off" - battTitle.setText(getResources().getString( - R.string.jv_relaunch_wifi_is_off)); + battTitle.setText(getResources().getString(R.string.jv_relaunch_wifi_is_off)); battTitle.setCompoundDrawablesWithIntrinsicBounds( getResources().getDrawable(R.drawable.wifi_off), null, null, null); @@ -852,7 +656,7 @@ private void refreshBottomInfo() { } // Battery - if (batteryLevelReceiver == null) { + if (batteryLevelReceiver == null && useHome && showFourPanel) { batteryLevelReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { try { @@ -896,828 +700,227 @@ else if (level < 75) R.drawable.bat3), null, null, null); else - battLevel - .setCompoundDrawablesWithIntrinsicBounds( + battLevel.setCompoundDrawablesWithIntrinsicBounds( getResources().getDrawable( R.drawable.bat4), null, null, null); } } catch (IllegalArgumentException e) { - Log.v("ReLaunch", "Battery intent illegal arguments"); + //Log.v("ReLaunch", "Battery intent illegal arguments"); } } }; } - if (!batteryLevelRegistered) { + if (!batteryLevelRegistered && useHome && showFourPanel) { registerReceiver(batteryLevelReceiver, batteryLevelFilter); batteryLevelRegistered = true; } } - private void drawDirectory(String root, Integer startPosition) { - File dir = new File(root); - File[] allEntries = dir.listFiles(); - List files = new ArrayList(); - List dirs = new ArrayList(); - - setEinkController(); - - currentRoot = root; - currentPosition = (startPosition == -1) ? 0 : startPosition; - SharedPreferences.Editor editor = prefs.edit(); - editor.putString("lastdir", currentRoot); - editor.commit(); - - final Button tv = (Button) findViewById(useDirViewer ? R.id.results_title - : R.id.title_txt); - final String dirAbsPath = dir.getAbsolutePath(); - if (prefs.getBoolean("showFullDirPath", true)) - tv.setText(dirAbsPath + " (" - + ((allEntries == null) ? 0 : allEntries.length) + ")"); - else - tv.setText(dir.getName()); - class TvSimpleOnGestureListener extends SimpleOnGestureListener { - @Override - public boolean onSingleTapConfirmed(MotionEvent e) { - final String[] columns = getResources().getStringArray( - R.array.output_columns_names); - final CharSequence[] columnsmode = new CharSequence[columns.length + 1]; - columnsmode[0] = getResources().getString( - R.string.jv_relaunch_default); - for (int i = 0; i < columns.length; i++) { - columnsmode[i + 1] = columns[i]; - } - Integer checked = -1; - if (app.columns.containsKey(currentRoot)) { - if (app.columns.get(currentRoot) == -1) { - checked = 1; - } else { - checked = app.columns.get(currentRoot) + 1; - } - } else { - checked = 0; - } - // get checked - AlertDialog.Builder builder = new AlertDialog.Builder( - ReLaunch.this); - // "Select application" - builder.setTitle(getResources().getString( - R.string.jv_relaunch_select_columns)); - builder.setSingleChoiceItems(columnsmode, checked, - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int i) { - if (i == 0) { - app.columns.remove(currentRoot); - } else { - if (i == 1) { - app.columns.put(currentRoot, -1); - } else { - app.columns.put(currentRoot, i - 1); - } - } - app.saveList("columns"); - drawDirectory(currentRoot, currentPosition); - dialog.dismiss(); - } - }); - AlertDialog alert = builder.create(); - alert.show(); - return true; - } - - @Override - public boolean onDoubleTap(MotionEvent e) { - return true; - } - - @Override - public void onLongPress(MotionEvent e) { - menuSort(); - } - } - ; - TvSimpleOnGestureListener tv_gl = new TvSimpleOnGestureListener(); - final GestureDetector tv_gd = new GestureDetector(tv_gl); - tv.setOnTouchListener(new OnTouchListener() { - public boolean onTouch(View v, MotionEvent event) { - tv_gd.onTouchEvent(event); - return false; - } - }); - - final Button up = (Button) findViewById(R.id.goup_btn); - final ImageButton adv = (ImageButton) findViewById(R.id.advanced_btn); - if (adv != null) { - class advSimpleOnGestureListener extends SimpleOnGestureListener { - @Override - public boolean onSingleTapConfirmed(MotionEvent e) { - if (prefs.getString("advancedButtonST", "RELAUNCH").equals( - "RELAUNCH")) { - Intent i = new Intent(ReLaunch.this, Advanced.class); - startActivity(i); - } else if (prefs.getString("advancedButtonST", "RELAUNCH") - .equals("LOCK")) { - actionLock(); - } else if (prefs.getString("advancedButtonST", "RELAUNCH") - .equals("POWEROFF")) { - actionPowerOff(); - } else if (prefs.getString("advancedButtonST", "RELAUNCH") - .equals("SWITCHWIFI")) { - actionSwitchWiFi(); - } else if (prefs.getString("advancedButtonST", "RELAUNCH") - .equals("RUN")) { - actionRun(prefs.getString("advancedButtonSTapp", "%%")); - } - return true; - } - - @Override - public boolean onDoubleTap(MotionEvent e) { - if (prefs.getString("advancedButtonDT", "NOTHING").equals( - "RELAUNCH")) { - Intent i = new Intent(ReLaunch.this, Advanced.class); - startActivity(i); - } else if (prefs.getString("advancedButtonDT", "NOTHING") - .equals("LOCK")) { - actionLock(); - } else if (prefs.getString("advancedButtonDT", "NOTHING") - .equals("POWEROFF")) { - actionPowerOff(); - } else if (prefs.getString("advancedButtonDT", "NOTHING") - .equals("SWITCHWIFI")) { - actionSwitchWiFi(); - } else if (prefs.getString("advancedButtonDT", "NOTHING") - .equals("RUN")) { - actionRun(prefs.getString("advancedButtonDTapp", "%%")); - } - return true; - } - - @Override - public void onLongPress(MotionEvent e) { - if (adv.hasWindowFocus()) { - if (prefs.getString("advancedButtonLT", "NOTHING") - .equals("RELAUNCH")) { - Intent i = new Intent(ReLaunch.this, Advanced.class); - startActivity(i); - } else if (prefs.getString("advancedButtonLT", - "NOTHING").equals("LOCK")) { - actionLock(); - } else if (prefs.getString("advancedButtonLT", - "NOTHING").equals("POWEROFF")) { - actionPowerOff(); - } else if (prefs.getString("advancedButtonLT", - "NOTHING").equals("SWITCHWIFI")) { - actionSwitchWiFi(); - } else if (prefs.getString("advancedButtonLT", - "NOTHING").equals("RUN")) { - actionRun(prefs.getString("advancedButtonLTapp", - "%%")); - } - } - } - } - ; - advSimpleOnGestureListener adv_gl = new advSimpleOnGestureListener(); - final GestureDetector adv_gd = new GestureDetector(adv_gl); - adv.setOnTouchListener(new OnTouchListener() { - public boolean onTouch(View v, MotionEvent event) { - adv_gd.onTouchEvent(event); - return false; - } - }); - } - - itemsArray = new ArrayList>(); - if (dir.getParent() != null) - dirs.add(".."); - if (allEntries != null) { - for (File entry : allEntries) { - if (entry.isDirectory()) - dirs.add(entry.getName()); - else if (!prefs.getBoolean("filterResults", false) - || app.filterFile(dir.getAbsolutePath(), - entry.getName())) - files.add(entry.getName()); - } - } - Collections.sort(dirs); -// Collections.sort(files); - String upDir = ""; - for (String f : dirs) { - if ((f.charAt(0) == '.') && (f.charAt(1) != '.') && (!prefs.getBoolean("showHidden", false))) - continue; - HashMap item = new HashMap(); - item.put("name", f); - item.put("sname", f); - item.put("dname", dir.getAbsolutePath()); - if (f.equals("..")) { - upDir = dir.getParent(); - continue; - } else - item.put("fname", dir.getAbsolutePath() + "/" + f); - item.put("type", "dir"); - item.put("reader", "Nope"); - itemsArray.add(item); - } - List> fileItemsArray = new ArrayList>(); - for (String f : files) { - if ((f.startsWith(".")) && (!prefs.getBoolean("showHidden", false))) - continue; - HashMap item = new HashMap(); - if (prefs.getBoolean("showBookTitles", false)) - item.put("sname", app.dataBase.getEbookName(dir.getAbsolutePath(), f, prefs.getString("bookTitleFormat", "%t[\n%a][. %s][-%n]"))); - else - item.put("sname", f); - item.put("name", f); - item.put("dname", dir.getAbsolutePath()); - item.put("fname", dir.getAbsolutePath() + "/" + f); - item.put("type", "file"); - item.put("reader", app.readerName(f)); - fileItemsArray.add(item); - } - - setSortMode(prefs.getInt("sortMode", 0)); - fileItemsArray = sortFiles(fileItemsArray, sortType[0], sortOrder[0]); - itemsArray.addAll(fileItemsArray); - - String[] from = new String[] { "name" }; - int[] to = new int[] { R.id.fl_text }; - setUpButton(up, upDir, currentRoot); - - final GridView gv = (GridView) findViewById(useDirViewer ? R.id.results_list - : R.id.gl_list); - adapter = new FLSimpleAdapter(this, itemsArray, - useDirViewer ? R.layout.results_layout : R.layout.flist_layout, - from, to); - gv.setAdapter(adapter); - - gv.setHorizontalSpacing(0); - Integer colsNum = -1; - if (getDirectoryColumns(currentRoot) != 0) { - colsNum = getDirectoryColumns(currentRoot); - } else { - colsNum = Integer.parseInt(prefs - .getString("columnsDirsFiles", "-1")); - } - // override auto (not working fine in adnroid) - if (colsNum == -1) { - colsNum = getAutoColsNum(); - } - currentColsNum = colsNum; - gv.setNumColumns(colsNum); - if (prefs.getBoolean("customScroll", app.customScrollDef)) { - if (addSView) { - int scrollW; - try { - scrollW = Integer.parseInt(prefs.getString("scrollWidth", - "25")); - } catch (NumberFormatException e) { - scrollW = 25; - } - LinearLayout ll = (LinearLayout) findViewById(useDirViewer ? R.id.results_fl - : R.id.gl_layout); - final SView sv = new SView(getBaseContext()); - LinearLayout.LayoutParams pars = new LinearLayout.LayoutParams( - scrollW, ViewGroup.LayoutParams.FILL_PARENT, 1f); - sv.setLayoutParams(pars); - ll.addView(sv); - gv.setOnScrollListener(new AbsListView.OnScrollListener() { - public void onScroll(AbsListView view, - int firstVisibleItem, int visibleItemCount, - int totalItemCount) { - sv.total = totalItemCount; - sv.count = visibleItemCount; - sv.first = firstVisibleItem; - setEinkController(); - sv.invalidate(); - } - - public void onScrollStateChanged(AbsListView view, - int scrollState) { - } - }); - addSView = false; - } - } else { - gv.setOnScrollListener(new AbsListView.OnScrollListener() { - public void onScroll(AbsListView view, int firstVisibleItem, - int visibleItemCount, int totalItemCount) { - setEinkController(); - } - - public void onScrollStateChanged(AbsListView view, - int scrollState) { - } - }); - } - - if (startPosition != -1) - gv.setSelection(startPosition); - - class GlSimpleOnGestureListener extends SimpleOnGestureListener { - Context context; - - public GlSimpleOnGestureListener(Context context) { - super(); - this.context = context; - } - public int findViewByXY(MotionEvent e) { - int location[] = new int[2]; - float x = e.getRawX(); - float y = e.getRawY(); - int first = gv.getFirstVisiblePosition(); - int last = gv.getLastVisiblePosition(); - int count = last -first + 1; - for (int i = 0; i viewX && x < (viewX + v.getWidth())) && - ( y > viewY && y < (viewY + v.getHeight()))){ - return first + i; - } - } - return -1; - } - - @Override - public boolean onSingleTapConfirmed(MotionEvent e) { - int position = findViewByXY(e); - if (position == -1) - return true; - HashMap item = itemsArray.get(position); - - if (item.get("type").equals("dir")) { - // Goto directory - pushCurrentPos(gv, true); - drawDirectory(item.get("fname"), -1); - } else if (app.specialAction(ReLaunch.this, item.get("fname"))) - pushCurrentPos(gv, false); - else { - SharedPreferences.Editor editor = prefs.edit(); - editor.putInt("posInFolder", gv.getFirstVisiblePosition()); - editor.commit(); - pushCurrentPos(gv, false); - if (item.get("reader").equals("Nope")) - app.defaultAction(ReLaunch.this, item.get("fname")); - else { - // Launch reader - if (app.askIfAmbiguous) { - List rdrs = app.readerNames(item - .get("fname")); - if (rdrs.size() < 1) - return true; - else if (rdrs.size() == 1) - start(app.launchReader(rdrs.get(0), - item.get("fname"))); - else { - final CharSequence[] applications = rdrs - .toArray(new CharSequence[rdrs.size()]); - final String rdr1 = item.get("fname"); - AlertDialog.Builder builder = new AlertDialog.Builder( - ReLaunch.this); - // "Select application" - builder.setTitle(getResources() - .getString( - R.string.jv_relaunch_select_application)); - builder.setSingleChoiceItems(applications, -1, - new DialogInterface.OnClickListener() { - public void onClick( - DialogInterface dialog, - int i) { - start(app - .launchReader( - (String) applications[i], - rdr1)); - dialog.dismiss(); - } - }); - AlertDialog alert = builder.create(); - alert.show(); - } - } else - start(app.launchReader(item.get("reader"), - item.get("fname"))); - } - } - return true; - } - - @Override - public boolean onDoubleTap(MotionEvent e) { - int position = findViewByXY(e); - if (position != -1) { - HashMap item = itemsArray.get(position); - String file = item.get("dname") + "/" + item.get("name"); - if (file.endsWith("fb2") || file.endsWith("fb2.zip") || file.endsWith("epub")) { - SharedPreferences.Editor editor = prefs.edit(); - editor.putInt("posInFolder", gv.getFirstVisiblePosition()); - editor.commit(); - pushCurrentPos(gv, false); - showBookInfo(file); - } - } - return true; - } - - - @Override - public void onLongPress(MotionEvent e) { - if (!ReLaunch.this.hasWindowFocus()) - return; - int menuType = 0; - int position = findViewByXY(e); - HashMap item; - String fn = null; - String dr = null; - String tp = null; - String fullName = null; - ArrayList aList = new ArrayList(10); - if (position == -1) - menuType = 0; - else { - item = itemsArray.get(position); - fn = item.get("name"); - dr = item.get("dname"); - tp = item.get("type"); - fullName = dr + "/" + fn; - if (tp == "dir") - menuType = 1; - else if (fn.endsWith("fb2") || fn.endsWith("fb2.zip") || fn.endsWith("epub")) - menuType = 2; - else - menuType = 3; - } - if (menuType == 0) { - if (prefs.getBoolean("useFileManagerFunctions", true)) { - aList.add(getString(R.string.jv_relaunch_create_folder)); - if (fileOp != 0) { - aList.add(getString(R.string.jv_relaunch_paste)); - } - } - } else if (menuType == 1) { - if ((!app.isStartDir(fullName)) && (prefs.getBoolean("showAddStartDir", false))) { - aList.add(getString(R.string.jv_relaunch_set_startdir)); - aList.add(getString(R.string.jv_relaunch_add_startdir)); - } - if (!app.contains("favorites", fullName, app.DIR_TAG)) - aList.add(getString(R.string.jv_relaunch_add)); - if (prefs.getBoolean("useFileManagerFunctions", true)) { - File d = new File(fullName); - String[] allEntries = d.list(); - aList.add(getString(R.string.jv_relaunch_create_folder)); - aList.add(getString(R.string.jv_relaunch_rename)); - aList.add(getString(R.string.jv_relaunch_move)); - if (fileOp != 0) { - aList.add(getString(R.string.jv_relaunch_paste)); - } - if (allEntries != null && allEntries.length > 0) { - aList.add(getString(R.string.jv_relaunch_delete_non_emp_dir)); - } else { - aList.add(getString(R.string.jv_relaunch_delete_emp_dir)); - } - } - aList.add(getString(R.string.jv_relaunch_fileinfo)); - } else if (menuType == 2) { - aList.add(getString(R.string.jv_relaunch_bookinfo)); - if (!app.contains("favorites", dr, fn)) { - aList.add(getString(R.string.jv_relaunch_add)); - } - if (app.history.containsKey(fullName)) { - if (app.history.get(fullName) == app.READING) { - aList.add(getString(R.string.jv_relaunch_mark)); - } else if (app.history.get(fullName) == app.FINISHED) { - aList.add(getString(R.string.jv_relaunch_unmark)); - } - aList.add(getString(R.string.jv_relaunch_unmarkall)); - } else { - aList.add(getString(R.string.jv_relaunch_mark)); - } - if (prefs.getBoolean("openWith", true)) - aList.add(getString(R.string.jv_relaunch_openwith)); - if (prefs.getBoolean("createIntent", false)) - aList.add(getString(R.string.jv_relaunch_createintent)); - if (prefs.getBoolean("useFileManagerFunctions", true)) { - if (!prefs.getBoolean("showBookTitles", false)) - aList.add(getString(R.string.jv_relaunch_tags_rename)); - aList.add(getString(R.string.jv_relaunch_create_folder)); - if (!prefs.getBoolean("showBookTitles", false)) - aList.add(getString(R.string.jv_relaunch_rename)); - aList.add(getString(R.string.jv_relaunch_copy)); - aList.add(getString(R.string.jv_relaunch_move)); - if (fileOp != 0) - aList.add(getString(R.string.jv_relaunch_paste)); - aList.add(getString(R.string.jv_relaunch_delete)); - } - aList.add(getString(R.string.jv_relaunch_fileinfo)); - } else if (menuType == 3) { - if (!app.contains("favorites", dr, fn)) { - aList.add(getString(R.string.jv_relaunch_add)); - } - if (app.history.containsKey(fullName)) { - if (app.history.get(fullName) == app.READING) { - aList.add(getString(R.string.jv_relaunch_mark)); - } else if (app.history.get(fullName) == app.FINISHED) { - aList.add(getString(R.string.jv_relaunch_unmark)); - } - aList.add(getString(R.string.jv_relaunch_unmarkall)); - } else { - aList.add(getString(R.string.jv_relaunch_mark)); - } - if (prefs.getBoolean("openWith", true)) - aList.add(getString(R.string.jv_relaunch_openwith)); - if (prefs.getBoolean("createIntent", false)) - aList.add(getString(R.string.jv_relaunch_createintent)); - if (prefs.getBoolean("useFileManagerFunctions", true)) { - aList.add(getString(R.string.jv_relaunch_create_folder)); - if (!prefs.getBoolean("showBookTitles", false)) - aList.add(getString(R.string.jv_relaunch_rename)); - aList.add(getString(R.string.jv_relaunch_copy)); - aList.add(getString(R.string.jv_relaunch_move)); - if (fileOp != 0) - aList.add(getString(R.string.jv_relaunch_paste)); - aList.add(getString(R.string.jv_relaunch_delete)); - } - aList.add(getString(R.string.jv_relaunch_fileinfo)); - } - aList.add(getString(R.string.jv_relaunch_cancel)); - final int pos = position; - final String[] list = aList.toArray(new String[aList.size()]); - - ListAdapter cmAdapter = new ArrayAdapter( - getApplicationContext(), R.layout.cmenu_list_item, list); - - AlertDialog.Builder builder = new AlertDialog.Builder(context); - builder.setAdapter(cmAdapter, new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int item) { - String s = list[item]; - if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_cancel))) - onContextMenuSelected(CNTXT_MENU_CANCEL, pos); - else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_delete))) - onContextMenuSelected(CNTXT_MENU_DELETE_F, pos); - else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_delete_emp_dir))) - onContextMenuSelected(CNTXT_MENU_DELETE_D_EMPTY, pos); - else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_delete_non_emp_dir))) - onContextMenuSelected(CNTXT_MENU_DELETE_D_NON_EMPTY, pos); - else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_add))) - onContextMenuSelected(CNTXT_MENU_ADD, pos); - else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_mark))) - onContextMenuSelected(CNTXT_MENU_MARK_FINISHED, pos); - else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_unmark))) - onContextMenuSelected(CNTXT_MENU_MARK_READING, pos); - else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_unmarkall))) - onContextMenuSelected(CNTXT_MENU_MARK_FORGET, pos); - else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_createintent))) - onContextMenuSelected(CNTXT_MENU_INTENT, pos); - else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_openwith))) - onContextMenuSelected(CNTXT_MENU_OPENWITH, pos); - else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_copy))) - onContextMenuSelected(CNTXT_MENU_COPY_FILE, pos); - else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_move))) - onContextMenuSelected(CNTXT_MENU_MOVE_FILE, pos); - else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_paste))) - onContextMenuSelected(CNTXT_MENU_PASTE, pos); - else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_rename))) - onContextMenuSelected(CNTXT_MENU_RENAME, pos); - else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_create_folder))) - onContextMenuSelected(CNTXT_MENU_CREATE_DIR, pos); - else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_move_dir))) - onContextMenuSelected(CNTXT_MENU_MOVE_DIR, pos); - else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_tags_rename))) - onContextMenuSelected(CNTXT_MENU_TAGS_RENAME, pos); - else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_set_startdir))) - onContextMenuSelected(CNTXT_MENU_SET_STARTDIR, pos); - else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_add_startdir))) - onContextMenuSelected(CNTXT_MENU_ADD_STARTDIR, pos); - else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_bookinfo))) - onContextMenuSelected(CNTXT_MENU_SHOW_BOOKINFO, pos); - else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_fileinfo))) - onContextMenuSelected(CNTXT_MENU_FILE_INFO, pos); - } - }); - AlertDialog alert = builder.create(); - alert.requestWindowFeature(Window.FEATURE_NO_TITLE); - alert.show(); - } - }; - - GlSimpleOnGestureListener gv_gl = new GlSimpleOnGestureListener(this); - final GestureDetector gv_gd = new GestureDetector(gv_gl); - gv.setOnTouchListener(new OnTouchListener() { - public boolean onTouch(View v, MotionEvent event) { - gv_gd.onTouchEvent(event); - return false; - } - }); - - final Button upScroll = (Button) findViewById(R.id.upscroll_btn); - if (prefs.getBoolean("disableScrollJump", true) == false) { - upScroll.setText(app.scrollStep + "%"); - } else { - upScroll.setText(getResources() - .getString(R.string.jv_relaunch_prev)); - } - class upScrlSimpleOnGestureListener extends SimpleOnGestureListener { - @Override - public boolean onSingleTapConfirmed(MotionEvent e) { - if (DeviceInfo.EINK_NOOK) { // nook - MotionEvent ev; - ev = MotionEvent.obtain(SystemClock.uptimeMillis(), - SystemClock.uptimeMillis(), - MotionEvent.ACTION_DOWN, 200, 100, 0); - gv.dispatchTouchEvent(ev); - ev = MotionEvent.obtain(SystemClock.uptimeMillis(), - SystemClock.uptimeMillis() + 100, - MotionEvent.ACTION_MOVE, 200, 200, 0); - gv.dispatchTouchEvent(ev); - SystemClock.sleep(100); - ev = MotionEvent.obtain(SystemClock.uptimeMillis(), - SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, - 200, 200, 0); - gv.dispatchTouchEvent(ev); - } else { // other devices - int first = gv.getFirstVisiblePosition(); - int visible = gv.getLastVisiblePosition() - - gv.getFirstVisiblePosition() + 1; - int total = itemsArray.size(); - first -= visible; - if (first < 0) - first = 0; - gv.setSelection(first); - // some hack workaround against not scrolling in some cases - if (total > 0) { - gv.requestFocusFromTouch(); - gv.setSelection(first); - } - } - return true; - } - - @Override - public boolean onDoubleTap(MotionEvent e) { - if (prefs.getBoolean("disableScrollJump", true) == false) { - int first = gv.getFirstVisiblePosition(); - int total = itemsArray.size(); - first -= (total * app.scrollStep) / 100; - if (first < 0) - first = 0; - gv.setSelection(first); - // some hack workaround against not scrolling in some cases - if (total > 0) { - gv.requestFocusFromTouch(); - gv.setSelection(first); - } - } - return true; - } - - @Override - public void onLongPress(MotionEvent e) { - if (upScroll.hasWindowFocus()) { - if (prefs.getBoolean("disableScrollJump", true) == false) { - int first = gv.getFirstVisiblePosition(); - int total = itemsArray.size(); - first = 0; - gv.setSelection(first); - // some hack workaround against not scrolling in some - // cases - if (total > 0) { - gv.requestFocusFromTouch(); - gv.setSelection(first); - } - } - } - } - } - ; - upScrlSimpleOnGestureListener upscrl_gl = new upScrlSimpleOnGestureListener(); - final GestureDetector upscrl_gd = new GestureDetector(upscrl_gl); - upScroll.setOnTouchListener(new OnTouchListener() { - public boolean onTouch(View v, MotionEvent event) { - upscrl_gd.onTouchEvent(event); - return false; - } - }); - - class RepeatedDownScroll { - public void doIt(int first, int target, int shift) { - final GridView gv = (GridView) findViewById(R.id.gl_list); - int total = gv.getCount(); - int last = gv.getLastVisiblePosition(); - if (total == last + 1) - return; - final int ftarget = target + shift; - gv.clearFocus(); - gv.post(new Runnable() { - public void run() { - gv.setSelection(ftarget); - } - }); - final int ffirst = first; - final int fshift = shift; - gv.postDelayed(new Runnable() { - public void run() { - int nfirst = gv.getFirstVisiblePosition(); - if (nfirst == ffirst) { - RepeatedDownScroll ds = new RepeatedDownScroll(); - ds.doIt(ffirst, ftarget, fshift + 1); - } - } - }, 150); - } - } - - final Button downScroll = (Button) findViewById(R.id.downscroll_btn); - if (prefs.getBoolean("disableScrollJump", true) == false) { - downScroll.setText(app.scrollStep + "%"); - } else { - downScroll.setText(getResources().getString( - R.string.jv_relaunch_next)); - } - class dnScrlSimpleOnGestureListener extends SimpleOnGestureListener { - @Override - public boolean onSingleTapConfirmed(MotionEvent e) { - if (DeviceInfo.EINK_NOOK) { // nook special - MotionEvent ev; - ev = MotionEvent.obtain(SystemClock.uptimeMillis(), - SystemClock.uptimeMillis(), - MotionEvent.ACTION_DOWN, 200, 200, 0); - gv.dispatchTouchEvent(ev); - ev = MotionEvent.obtain(SystemClock.uptimeMillis(), - SystemClock.uptimeMillis() + 100, - MotionEvent.ACTION_MOVE, 200, 100, 0); - gv.dispatchTouchEvent(ev); - SystemClock.sleep(100); - ev = MotionEvent.obtain(SystemClock.uptimeMillis(), - SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, - 200, 100, 0); - gv.dispatchTouchEvent(ev); - } else { // other devices - int first = gv.getFirstVisiblePosition(); - int total = itemsArray.size(); - int last = gv.getLastVisiblePosition(); - if (total == last + 1) - return true; - int target = last + 1; - if (target > (total - 1)) - target = total - 1; - RepeatedDownScroll ds = new RepeatedDownScroll(); - ds.doIt(first, target, 0); - } - return true; - } - - @Override - public boolean onDoubleTap(MotionEvent e) { - if (prefs.getBoolean("disableScrollJump", true) == false) { - int first = gv.getFirstVisiblePosition(); - int total = itemsArray.size(); - int last = gv.getLastVisiblePosition(); - if (total == last + 1) - return true; - int target = first + (total * app.scrollStep) / 100; - if (target <= last) - target = last + 1; // Special for NOOK, otherwise it - // won't redraw the listview - if (target > (total - 1)) - target = total - 1; - RepeatedDownScroll ds = new RepeatedDownScroll(); - ds.doIt(first, target, 0); - } - return true; - } - - @Override - public void onLongPress(MotionEvent e) { - if (downScroll.hasWindowFocus()) { - if (prefs.getBoolean("disableScrollJump", true) == false) { - int first = gv.getFirstVisiblePosition(); - int total = itemsArray.size(); - int last = gv.getLastVisiblePosition(); - if (total == last + 1) - return; - int target = total - 1; - RepeatedDownScroll ds = new RepeatedDownScroll(); - ds.doIt(first, target, 0); - } - } - } - } - ; - dnScrlSimpleOnGestureListener dnscrl_gl = new dnScrlSimpleOnGestureListener(); - final GestureDetector dnscrl_gd = new GestureDetector(dnscrl_gl); - downScroll.setOnTouchListener(new OnTouchListener() { - public boolean onTouch(View v, MotionEvent event) { - dnscrl_gd.onTouchEvent(event); - return false; - } - }); - - refreshBottomInfo(); - } + private void drawDirectory(String root, Integer startPosition) { + // организуем два массива для хранения имен папок и имен файлов + List files = new ArrayList(); + List dirs = new ArrayList(); + // вычищаем иконки из массива. оставляем только стандартные + for(int i = 4, j = arrIcon.size(); i< j; j--){ + arrIcon.remove(j-1); + } + // очищаем массив выделений + arrSelItem.clear(); + // устанавливаем текущую папку корневой + currentRoot = root; + //сохраняем имя папки + lastdir = currentRoot; + + // текущая позиция неизвестна (-1) или задана при вызове + currentPosition = (startPosition == -1) ? 0 : startPosition; + // создаем массив элементов списка + itemsArray = new ArrayList>(); + upDir = ""; + // выясняем что обрабатываем - локальную папку или аккаунт Dropbox + if(root.startsWith("Dropbox| ")){ + root = root.substring("Dropbox| ".length()); + if(root.equals("/")){ + currentRoot = "Dropbox| "; + } + // список файлов и папок + DropboxAPI.Entry entries; + try { + entries = mDBApi.metadata(root, 0, null, true, null);// может быть ошибка при получении коллекции + for (DropboxAPI.Entry e : entries.contents) { + if (!e.isDeleted) { + if(e.isDir){ + dirs.add(e.fileName()); + }else if (!filterResults || app.filterFile(e.path, e.fileName())){ + files.add(e.fileName()); + } + } + } + + // заполняем заголовок + if (showTwoPanel){ + if (showFullDirPath){ // в зависимости от настроек + // полный путь к текущей папки + ( число элементов в ней) + tv_title.setText("Dropbox| " + entries.fileName() + " (" + entries.contents.size() + ")"); + }else{ + // имя папки + tv_title.setText("Dropbox| " + entries.path); + } + } + if (entries.parentPath() != null){ + upDir = "Dropbox| " + entries.parentPath(); + } + } catch (DropboxException e) { + drawDirectory(startDir[0], -1); + return; + } + }else{ + // получаем папку как объект + File dir = new File(root); + // получаем список подпапок и файлов + File[] allEntries = dir.listFiles(); + + + // заполняем заголовок + if (showTwoPanel){ + if (showFullDirPath){ // в зависимости от настроек + // полный путь к текущей папки + ( число элементов в ней) + tv_title.setText(currentRoot + " (" + ((allEntries == null) ? 0 : allEntries.length) + ")"); + }else{ + // имя папки + tv_title.setText(dir.getName()); + } + } + // определяем папку родитель + + if (dir.getParent() != null){ + upDir = dir.getParent(); + } + // полученный массив элементов разбиваем на папки и файлы + if (allEntries != null) { + for (File entry : allEntries) { + if (entry.isDirectory()){ + dirs.add(entry.getName()); + }else if (!filterResults || app.filterFile(dir.getAbsolutePath(), entry.getName())){ + files.add(entry.getName()); + } + } + } + } + + + // сортируем папки + Collections.sort(dirs); + + // перебираем папки + for (String f : dirs) { + if ((f.startsWith(".")) && (!showHidden)){ // если скрытая и указано не показывать - пропускаем + continue; + } + HashMap item = new HashMap(); //создаем карту и начинаем ее заполнять + item.put("name", f); // имя папки + item.put("sname", f);// имя папки + item.put("dname", currentRoot); // полный путь к папке + item.put("fname", currentRoot + File.separator + f); // полный путь папки + item.put("type", "dir"); // тип - папка + item.put("reader", "Nope"); // программа обработчик не назначена + if (firstLineIconSizePx != 0) { + item.put("nameIcon", "dir_ok"); + } + itemsArray.add(item); // помещаем элемент в массив + } + // создаем массив карт для файлов + List> fileItemsArray = new ArrayList>(); + // перебираем файлы + String sname; + for (String f : files) { + if ((f.startsWith(".")) && (!showHidden)){ // если скрытый и указано не показывать - пропускаем + continue; + } + HashMap item = new HashMap();//создаем карту и начинаем ее заполнять + sname = f; + if (showBookTitles){ // показывать имена книг + sname = app.dataBase.getEbookName(currentRoot, f, bookTitleFormat); // bvz bp ,fps + }else if(hideKnownExts){ // скрываем расширение + for (String ext : exts) { // прогоняем все расширения через имя файла + if (sname.endsWith(ext)) { + sname = sname.substring(0, sname.length() - ext.length());// удаляем если нашли совпадение + } + } + } + + item.put("sname", sname);// имя файла + item.put("name", f); // имя файла + item.put("dname", currentRoot); // путь к файлу + item.put("fname", currentRoot + File.separator + f); // полное имя файла + item.put("type", "file"); // тип - файл + item.put("reader", app.readerName(f)); // программа обработчик + if (firstLineIconSizePx != 0) { + String nameIcon; + Drawable d = app.specialIcon(f, false); // получаем иконку + if (d != null){ // если удалось + imageIcon temp_icon = new imageIcon(); + temp_icon.nameIcon = f; + temp_icon.icon = scaleDrawable(d, firstLineIconSizePx); + arrIcon.add(temp_icon); + nameIcon = f; + }else { // иначе + String rdrName = app.readerName(f); // в поле реадера читаем обработчик + + if (rdrName.startsWith("Intent:")){ // если ответ начинается с ... + nameIcon = "icon"; + }else if (rdrName.equals("Nope")) { // если не известен + File fil = new File(currentRoot + "/" + f); // получаем файл + if (fil.length() > app.viewerMax*1024){ // больше определенного размера + nameIcon = "file_notok"; + }else{ // иначе + nameIcon = "file_ok"; + } + } else { // во всех остальных случаях + + if (app.getIcons().containsKey(rdrName)){ // у программы есть иконка? + imageIcon temp_icon = new imageIcon(); + temp_icon.nameIcon = rdrName; + temp_icon.icon = scaleDrawable(app.getIcons().get(rdrName),firstLineIconSizePx); + arrIcon.add(temp_icon); + nameIcon = rdrName; + }else{ + nameIcon = "file_notok"; + } + } + } + item.put("nameIcon", nameIcon); // тип - файл + } + + fileItemsArray.add(item); // добавляем в массив + } + // производим сортировку файлов + fileItemsArray = sortFiles(fileItemsArray, sortType[0], sortOrder[0]); + // добавляем в массив карт предназначенный для отображения + itemsArray.addAll(fileItemsArray); + // скрываем или показываем кнопку переход в родительскую папку + setUpButton(currentRoot); + // определяем число колонок для отображения + Integer colsNum = getDirectoryColumns(currentRoot); + if (colsNum == 0) { // проверяем не назначено ли пользователем отображение определенного числа колонок для этой папки + colsNum = Integer.parseInt(prefs.getString("columnsDirsFiles", "-1")); + } + // override auto (not working fine in adnroid) судя по всему работает дерьмого автоколлумнилование + if (colsNum == -1) { + colsNum = app.getAutoColsNum(itemsArray, "sname", columnsAlgIntensity); + } + // устанавливаем число колонок для отображения + currentColsNum = 1;//colsNum; + // устанавливаем число колонок у View + gvList.setNumColumns(colsNum); + + // устанавливаем стартовый элемент + if (startPosition != -1){ + gvList.setSelection(startPosition); + } + reDraw(); + } private HashMap createIconsList(PackageManager pm) { Drawable d = null; @@ -1725,10 +928,9 @@ private HashMap createIconsList(PackageManager pm) { Intent componentSearchIntent = new Intent(); componentSearchIntent.addCategory(Intent.CATEGORY_LAUNCHER); componentSearchIntent.setAction(Intent.ACTION_MAIN); - List ril = pm.queryIntentActivities(componentSearchIntent, - 0); - String pname = ""; - String aname = ""; + List ril = pm.queryIntentActivities(componentSearchIntent, 0); + String pname; + String aname; String hname = ""; for (ResolveInfo ri : ril) { if (ri.activityInfo != null) { @@ -1746,6 +948,7 @@ private HashMap createIconsList(PackageManager pm) { d = ri.loadIcon(pm); } } catch (Exception e) { + // emply } if (d != null) { rc.put(pname + "%" + aname + "%" + hname, d); @@ -1755,7 +958,7 @@ private HashMap createIconsList(PackageManager pm) { return rc; } - private static class AppComparator implements java.util.Comparator { + private static class AppComparator implements Comparator { public int compare(String a, String b) { if (a == null && b == null) { return 0; @@ -1777,10 +980,9 @@ static public List createAppList(PackageManager pm) { Intent componentSearchIntent = new Intent(); componentSearchIntent.addCategory(Intent.CATEGORY_LAUNCHER); componentSearchIntent.setAction(Intent.ACTION_MAIN); - List ril = pm.queryIntentActivities(componentSearchIntent, - 0); - String pname = ""; - String aname = ""; + List ril = pm.queryIntentActivities(componentSearchIntent, 0); + String pname; + String aname ; String hname = ""; for (ResolveInfo ri : ril) { if (ri.activityInfo != null) { @@ -1793,8 +995,9 @@ static public List createAppList(PackageManager pm) { hname = (String) ri.loadLabel(pm); } } catch (Exception e) { + // emply } - if (!filterMyself || !aname.equals(selfName)) + if (!filterMyself || (aname != null && !aname.equals(selfName))) rc.add(pname + "%" + aname + "%" + hname); } } @@ -1807,10 +1010,7 @@ private void start(Intent i) { try { startActivity(i); } catch (ActivityNotFoundException e) { - Toast.makeText( - ReLaunch.this, - getResources().getString( - R.string.jv_relaunch_activity_not_found), + Toast.makeText(ReLaunch.this,getResources().getString(R.string.jv_relaunch_activity_not_found), Toast.LENGTH_LONG).show(); } } @@ -1822,8 +1022,6 @@ public void onReceive(Context context, Intent intent) { Intent i = new Intent(context, ReLaunch.class); i.putExtra("home", useHome); i.putExtra("home1", useHome1); - i.putExtra("shop", useShop); - i.putExtra("library", useLibrary); startActivity(i); } }; @@ -1845,72 +1043,61 @@ public void onReceive(Context context, Intent intent) { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - - // If we called from Home launcher? - final Intent data = getIntent(); - if (data.getExtras() == null) { - useHome = false; - useHome1 = false; - useShop = false; - useLibrary = false; - useDirViewer = false; - } else { - useHome = data.getBooleanExtra("home", false); - useHome1 = data.getBooleanExtra("home1", false); - useShop = data.getBooleanExtra("shop", false); - useLibrary = data.getBooleanExtra("library", false); - useDirViewer = data.getBooleanExtra("dirviewer", false); - } - - // Global arrays - allowedModels = getResources().getStringArray(R.array.allowed_models); - allowedDevices = getResources().getStringArray(R.array.allowed_devices); - allowedManufacts = getResources().getStringArray( - R.array.allowed_manufacturers); - allowedProducts = getResources().getStringArray( - R.array.allowed_products); - - // Create global storage with values - app = (ReLaunchApp) getApplicationContext(); - - app.FLT_SELECT = getResources().getInteger(R.integer.FLT_SELECT); - app.FLT_STARTS = getResources().getInteger(R.integer.FLT_STARTS); - app.FLT_ENDS = getResources().getInteger(R.integer.FLT_ENDS); - app.FLT_CONTAINS = getResources().getInteger(R.integer.FLT_CONTAINS); - app.FLT_MATCHES = getResources().getInteger(R.integer.FLT_MATCHES); - app.FLT_NEW = getResources().getInteger(R.integer.FLT_NEW); - app.FLT_NEW_AND_READING = getResources().getInteger( - R.integer.FLT_NEW_AND_READING); - - // Preferences - prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); - if (prefs.getString("startMode", "UNKNOWN").equalsIgnoreCase("LAUNCHER")) - useHome = true; - String typesString = prefs.getString("types", defReaders); - try { - app.scrollStep = Integer.parseInt(prefs.getString("scrollPerc", - "10")); - app.viewerMax = Integer.parseInt(prefs.getString("viewerMaxSize", - "1024")); - app.editorMax = Integer.parseInt(prefs.getString("editorMaxSize", - "256")); - } catch (NumberFormatException e) { - app.scrollStep = 10; - app.viewerMax = 1024; - app.editorMax = 256; - } - if (app.scrollStep < 1) - app.scrollStep = 1; - if (app.scrollStep > 100) - app.scrollStep = 100; - - filterMyself = prefs.getBoolean("filterSelf", true); - if (useHome1 && prefs.getBoolean("homeMode", true)) - useHome = true; - if (useShop && prefs.getBoolean("shopMode", true)) - useHome = true; - if (useLibrary && prefs.getBoolean("libraryMode", true)) - useHome = true; + if(N2DeviceInfo.EINK_ONYX){ + currentRoot = "/mnt/storage"; + BACKUP_DIR = "/mnt/storage/.relaunch"; + } + + // ------ загружаем глобальные массивы и переменные --------------------- + initGlobalVariable(); + // ------ загружаем настройки программы в переменные ----------------------- + initPrefsVariable(); + // ------ загружаем стандартные иконки для отображения в менеджере ---------- + loadStandartIcons(); + + // If we called from Home launcher? + final Intent data = getIntent(); + if (data.getExtras() == null) { + useHome = false; + useHome1 = false; + } else { + useHome = data.getBooleanExtra("home", false); + useHome1 = data.getBooleanExtra("home1", false); + intentStartDir = data.getStringExtra("start_dir"); + } + filterMyself = prefs.getBoolean("filterSelf", true); + if (useHome1 && prefs.getBoolean("homeMode", true)) + useHome = true; + if (prefs.getString("startMode", "UNKNOWN").equalsIgnoreCase("LAUNCHER")) + useHome = true; + + + if(prefs.getBoolean("showDropbox", false)){ + boolean f_show = false; + for (String aStartDir : startDir) { + if (aStartDir.equals("Dropbox| ")) { + f_show = true; + } + } + if(!f_show){ + String temp = prefs.getString("startDir", "/sdcard,/media/My Files"); + temp += ",Dropbox| "; + startDir = temp.split("\\,"); + } + }else{ + boolean f_show = false; + for (String aStartDir : startDir) { + if (aStartDir.equals("Dropbox| ")) { + f_show = true; + } + } + if(f_show){ + String temp = prefs.getString("startDir", "/sdcard,/media/My Files"); + String temp2 = temp.substring(0, temp.indexOf(",Dropbox| ")) + temp.substring(temp.indexOf(",Dropbox| ") + ",Dropbox| ".length()); + startDir = temp2.split("\\,"); + } + } + //================================================================================= app.fullScreen = prefs.getBoolean("fullScreen", true); app.setFullScreenIfNecessary(this); @@ -1922,12 +1109,7 @@ public void onCreate(Bundle savedInstanceState) { // Create applications label list app.setApps(createAppList(getPackageManager())); - // Readers list - app.setReaders(parseReadersString(typesString)); - // Miscellaneous lists list - app.readFile("lastOpened", LRU_FILE); - app.readFile("favorites", FAV_FILE); app.readFile("filters", FILT_FILE, ":"); app.filters_and = prefs.getBoolean("filtersAnd", true); app.readFile("columns", COLS_FILE, ":"); @@ -1938,766 +1120,1187 @@ public void onCreate(Bundle savedInstanceState) { app.readFile("history", HIST_FILE, ":"); app.history.clear(); for (String[] r : app.getList("history")) { - if (r[1].equals("READING")) + if (r[1].equals("READING")){ app.history.put(r[0], app.READING); - else if (r[1].equals("FINISHED")) + }else if (r[1].equals("FINISHED")){ app.history.put(r[0], app.FINISHED); + } } setSortMode(prefs.getInt("sortMode", 0)); - if (useDirViewer) { - String start_dir = null; - setContentView(R.layout.results_layout); - if (data.getExtras() != null) - start_dir = data.getStringExtra("start_dir"); - ((ImageButton) findViewById(R.id.results_btn)) - .setOnClickListener(new View.OnClickListener() { - public void onClick(View v) { - finish(); - } - }); - if (start_dir != null) - drawDirectory(start_dir, -1); - } else { - // Main layout - setContentView(R.layout.main); - if (!prefs.getBoolean("showButtons", true)) { - hideLayout(R.id.linearLayoutTop); - } - if (useHome) { - app.readFile("app_last", APP_LRU_FILE, ":"); - app.readFile("app_favorites", APP_FAV_FILE, ":"); - - final ImageButton lrua_button = ((ImageButton) findViewById(R.id.app_last)); - class LruaSimpleOnGestureListener extends - SimpleOnGestureListener { - @Override - public boolean onSingleTapConfirmed(MotionEvent e) { - Intent intent = new Intent(ReLaunch.this, - AllApplications.class); - intent.putExtra("list", "app_last"); - // "Last recently used applications" - intent.putExtra( - "title", - getResources().getString( - R.string.jv_relaunch_lru_a)); - startActivity(intent); - return true; - } - @Override - public boolean onDoubleTap(MotionEvent e) { - return true; - } - - @Override - public void onLongPress(MotionEvent e) { - if (lrua_button.hasWindowFocus()) { - } - } - } - ; - LruaSimpleOnGestureListener lrua_gl = new LruaSimpleOnGestureListener(); - final GestureDetector lrua_gd = new GestureDetector(lrua_gl); - lrua_button.setOnTouchListener(new OnTouchListener() { - public boolean onTouch(View v, MotionEvent event) { - lrua_gd.onTouchEvent(event); - return false; - } - }); - final ImageButton alla_button = ((ImageButton) findViewById(R.id.all_applications_btn)); - class AllaSimpleOnGestureListener extends - SimpleOnGestureListener { - @Override - public boolean onSingleTapConfirmed(MotionEvent e) { - Intent intent = new Intent(ReLaunch.this, - AllApplications.class); - intent.putExtra("list", "app_all"); - // "All applications" - intent.putExtra( - "title", - getResources().getString( - R.string.jv_relaunch_all_a)); - startActivity(intent); - return true; - } - - @Override - public boolean onDoubleTap(MotionEvent e) { - return true; - } - - @Override - public void onLongPress(MotionEvent e) { - if (alla_button.hasWindowFocus()) { - - } - } - } - ; - AllaSimpleOnGestureListener alla_gl = new AllaSimpleOnGestureListener(); - final GestureDetector alla_gd = new GestureDetector(alla_gl); - alla_button.setOnTouchListener(new OnTouchListener() { - public boolean onTouch(View v, MotionEvent event) { - alla_gd.onTouchEvent(event); - return false; - } - }); - final ImageButton fava_button = ((ImageButton) findViewById(R.id.app_favorites)); - class FavaSimpleOnGestureListener extends - SimpleOnGestureListener { - - private boolean processEvent(String action) { - if (prefs.getString(action, "RELAUNCH").equals("RELAUNCH")) { - Intent intent = new Intent(ReLaunch.this, AllApplications.class); - intent.putExtra("list", "app_favorites"); - intent.putExtra("title", getResources().getString(R.string.jv_relaunch_fav_a)); - startActivity(intent); - } else if (prefs.getString(action, "RELAUNCH").equals("RUN")) { - actionRun(prefs.getString(action + "app", "%%")); - } - return true; - } - - @Override - public boolean onSingleTapConfirmed(MotionEvent e) { - return processEvent("appFavButtonST"); - } - - @Override - public boolean onDoubleTap(MotionEvent e) { - return processEvent("appFavButtonDT"); - } - - @Override - public void onLongPress(MotionEvent e) { - if (ReLaunch.this.hasWindowFocus()) - processEvent("appFavButtonLT"); - } - }; - FavaSimpleOnGestureListener fava_gl = new FavaSimpleOnGestureListener(); - final GestureDetector fava_gd = new GestureDetector(this, fava_gl); - fava_button.setOnTouchListener(new OnTouchListener() { - public boolean onTouch(View v, MotionEvent event) { - fava_gd.onTouchEvent(event); - return false; - } - }); - } else { - hideLayout(R.id.linearLayoutBottom); - } - - if (prefs.getBoolean("showButtons", true)) { - - final ImageButton home_button = (ImageButton) findViewById(R.id.home_btn); - class HomeSimpleOnGestureListener extends - SimpleOnGestureListener { - @Override - public boolean onSingleTapConfirmed(MotionEvent e) { - if (prefs.getString("homeButtonST", "OPENN").equals( - "OPENN")) { - openHome(Integer.parseInt(prefs.getString( - "homeButtonSTopenN", "1"))); - } else if (prefs.getString("homeButtonST", "OPENN") - .equals("OPENMENU")) { - menuHome(); - } else if (prefs.getString("homeButtonST", "OPENN") - .equals("OPENSCREEN")) { - screenHome(); - } - return true; - } - - @Override - public boolean onDoubleTap(MotionEvent e) { - if (prefs.getString("homeButtonDT", "OPENMENU").equals( - "OPENN")) { - openHome(Integer.parseInt(prefs.getString( - "homeButtonDTopenN", "1"))); - } else if (prefs.getString("homeButtonDT", "OPENMENU") - .equals("OPENMENU")) { - menuHome(); - } else if (prefs.getString("homeButtonDT", "OPENMENU") - .equals("OPENSCREEN")) { - screenHome(); - } - return true; - } - - @Override - public void onLongPress(MotionEvent e) { - if (home_button.hasWindowFocus()) { - if (prefs.getString("homeButtonLT", "OPENSCREEN") - .equals("OPENN")) { - openHome(Integer.parseInt(prefs.getString( - "homeButtonLTopenN", "1"))); - } else if (prefs.getString("homeButtonLT", - "OPENSCREEN").equals("OPENMENU")) { - menuHome(); - } else if (prefs.getString("homeButtonLT", - "OPENSCREEN").equals("OPENSCREEN")) { - screenHome(); - } - } - } - } - ; - HomeSimpleOnGestureListener home_gl = new HomeSimpleOnGestureListener(); - final GestureDetector home_gd = new GestureDetector(home_gl); - home_button.setOnTouchListener(new OnTouchListener() { - public boolean onTouch(View v, MotionEvent event) { - home_gd.onTouchEvent(event); - return false; - } - }); - - final ImageButton settings_button = (ImageButton) findViewById(R.id.settings_btn); - class SettingsSimpleOnGestureListener extends - SimpleOnGestureListener { - @Override - public boolean onSingleTapConfirmed(MotionEvent e) { - if (prefs.getString("settingsButtonST", "RELAUNCH") - .equals("RELAUNCH")) { - menuSettings(); - } else if (prefs.getString("settingsButtonST", - "RELAUNCH").equals("LOCK")) { - actionLock(); - } else if (prefs.getString("settingsButtonST", - "RELAUNCH").equals("POWEROFF")) { - actionPowerOff(); - } else if (prefs.getString("settingsButtonST", - "RELAUNCH").equals("SWITCHWIFI")) { - actionSwitchWiFi(); - } else if (prefs.getString("settingsButtonST", - "RELAUNCH").equals("RUN")) { - actionRun(prefs.getString("settingsButtonSTapp", - "%%")); - } - return true; - } - - @Override - public boolean onDoubleTap(MotionEvent e) { - if (prefs.getString("settingsButtonDT", "RELAUNCH") - .equals("RELAUNCH")) { - menuSettings(); - } else if (prefs.getString("settingsButtonDT", - "RELAUNCH").equals("LOCK")) { - actionLock(); - } else if (prefs.getString("settingsButtonDT", - "RELAUNCH").equals("POWEROFF")) { - actionPowerOff(); - } else if (prefs.getString("settingsButtonDT", - "RELAUNCH").equals("SWITCHWIFI")) { - actionSwitchWiFi(); - } else if (prefs.getString("settingsButtonDT", - "RELAUNCH").equals("RUN")) { - actionRun(prefs.getString("settingsButtonDTapp", - "%%")); - } - return true; - } - - @Override - public void onLongPress(MotionEvent e) { - if (settings_button.hasWindowFocus()) { - if (prefs.getString("settingsButtonLT", "RELAUNCH") - .equals("RELAUNCH")) { - menuSettings(); - } else if (prefs.getString("settingsButtonLT", - "RELAUNCH").equals("LOCK")) { - actionLock(); - } else if (prefs.getString("settingsButtonLT", - "RELAUNCH").equals("POWEROFF")) { - actionPowerOff(); - } else if (prefs.getString("settingsButtonLT", - "RELAUNCH").equals("SWITCHWIFI")) { - actionSwitchWiFi(); - } else if (prefs.getString("settingsButtonLT", - "RELAUNCH").equals("RUN")) { - actionRun(prefs.getString( - "settingsButtonLTapp", "%%")); - } - } - } - } - ; - SettingsSimpleOnGestureListener settings_gl = new SettingsSimpleOnGestureListener(); - final GestureDetector settings_gd = new GestureDetector( - settings_gl); - settings_button.setOnTouchListener(new OnTouchListener() { - public boolean onTouch(View v, MotionEvent event) { - settings_gd.onTouchEvent(event); - return false; - } - }); - - final ImageButton search_button = (ImageButton) findViewById(R.id.search_btn); - class SearchSimpleOnGestureListener extends - SimpleOnGestureListener { - @Override - public boolean onSingleTapConfirmed(MotionEvent e) { - menuSearch(); - return true; - } - - @Override - public boolean onDoubleTap(MotionEvent e) { - return true; - } - - @Override - public void onLongPress(MotionEvent e) { - if (search_button.hasWindowFocus()) { - } - } - } - ; - SearchSimpleOnGestureListener search_gl = new SearchSimpleOnGestureListener(); - final GestureDetector search_gd = new GestureDetector(search_gl); - search_button.setOnTouchListener(new OnTouchListener() { - public boolean onTouch(View v, MotionEvent event) { - search_gd.onTouchEvent(event); - return false; - } - }); - - final ImageButton lru_button = (ImageButton) findViewById(R.id.lru_btn); - class LruSimpleOnGestureListener extends - SimpleOnGestureListener { - @Override - public boolean onSingleTapConfirmed(MotionEvent e) { - if (prefs.getString("lruButtonST", "OPENSCREEN") - .equals("OPENN")) { - ListActions la = new ListActions(app, ReLaunch.this); - la.runItem("lastOpened", Integer.parseInt(prefs - .getString("lruButtonSTopenN", "1")) - 1); - } else if (prefs.getString("lruButtonST", "OPENSCREEN") - .equals("OPENMENU")) { - ListActions la = new ListActions(app, ReLaunch.this); - la.showMenu("lastOpened"); - } else if (prefs.getString("lruButtonST", "OPENSCREEN") - .equals("OPENSCREEN")) { - menuLastopened(); - } - return true; - } - - @Override - public boolean onDoubleTap(MotionEvent e) { - if (prefs.getString("lruButtonDT", "NOTHING").equals( - "OPENN")) { - ListActions la = new ListActions(app, ReLaunch.this); - la.runItem("lastOpened", Integer.parseInt(prefs - .getString("lruButtonDTopenN", "1")) - 1); - } else if (prefs.getString("lruButtonDT", "NOTHING") - .equals("OPENMENU")) { - ListActions la = new ListActions(app, ReLaunch.this); - la.showMenu("lastOpened"); - } else if (prefs.getString("lruButtonDT", "NOTHING") - .equals("OPENSCREEN")) { - menuLastopened(); - } - return true; - } - - @Override - public void onLongPress(MotionEvent e) { - if (lru_button.hasWindowFocus()) { - if (prefs.getString("lruButtonLT", "NOTHING") - .equals("OPENN")) { - ListActions la = new ListActions(app, - ReLaunch.this); - la.runItem("lastOpened", - Integer.parseInt(prefs.getString( - "lruButtonLTopenN", "1")) - 1); - } else if (prefs - .getString("lruButtonLT", "NOTHING") - .equals("OPENMENU")) { - ListActions la = new ListActions(app, - ReLaunch.this); - la.showMenu("lastOpened"); - } else if (prefs - .getString("lruButtonLT", "NOTHING") - .equals("OPENSCREEN")) { - menuLastopened(); - } - } - } - } - ; - LruSimpleOnGestureListener lru_gl = new LruSimpleOnGestureListener(); - final GestureDetector lru_gd = new GestureDetector(lru_gl); - lru_button.setOnTouchListener(new OnTouchListener() { - public boolean onTouch(View v, MotionEvent event) { - lru_gd.onTouchEvent(event); - return false; - } - }); - - final ImageButton fav_button = (ImageButton) findViewById(R.id.favor_btn); - class FavSimpleOnGestureListener extends - SimpleOnGestureListener { - @Override - public boolean onSingleTapConfirmed(MotionEvent e) { - if (prefs.getString("favButtonST", "OPENSCREEN") - .equals("OPENN")) { - ListActions la = new ListActions(app, ReLaunch.this); - la.runItem("favorites", Integer.parseInt(prefs - .getString("favButtonSTopenN", "1")) - 1); - } else if (prefs.getString("favButtonST", "OPENSCREEN") - .equals("OPENMENU")) { - ListActions la = new ListActions(app, ReLaunch.this); - la.showMenu("favorites"); - } else if (prefs.getString("favButtonST", "OPENSCREEN") - .equals("OPENSCREEN")) { - menuFavorites(); - } - return true; - } - - @Override - public boolean onDoubleTap(MotionEvent e) { - if (prefs.getString("favButtonDT", "NOTHING").equals( - "OPENN")) { - ListActions la = new ListActions(app, ReLaunch.this); - la.runItem("favorites", Integer.parseInt(prefs - .getString("favButtonDTopenN", "1")) - 1); - } else if (prefs.getString("favButtonDT", "NOTHING") - .equals("OPENMENU")) { - ListActions la = new ListActions(app, ReLaunch.this); - la.showMenu("favorites"); - } else if (prefs.getString("favButtonDT", "NOTHING") - .equals("OPENSCREEN")) { - menuFavorites(); - } - return true; - } - - @Override - public void onLongPress(MotionEvent e) { - if (fav_button.hasWindowFocus()) { - if (prefs.getString("favButtonLT", "NOTHING") - .equals("OPENN")) { - ListActions la = new ListActions(app, - ReLaunch.this); - la.runItem("favorites", - Integer.parseInt(prefs.getString( - "favButtonLTopenN", "1")) - 1); - } else if (prefs - .getString("favButtonLT", "NOTHING") - .equals("OPENMENU")) { - ListActions la = new ListActions(app, - ReLaunch.this); - la.showMenu("favorites"); - } else if (prefs - .getString("favButtonLT", "NOTHING") - .equals("OPENSCREEN")) { - menuFavorites(); - } - } - } - } - ; - FavSimpleOnGestureListener fav_gl = new FavSimpleOnGestureListener(); - final GestureDetector fav_gd = new GestureDetector(fav_gl); - fav_button.setOnTouchListener(new OnTouchListener() { - public boolean onTouch(View v, MotionEvent event) { - fav_gd.onTouchEvent(event); - return false; - } - }); - } - - // Memory buttons (task manager activity) - final LinearLayout mem_l = (LinearLayout) findViewById(R.id.mem_layout); - if (mem_l != null) { - class MemlSimpleOnGestureListener extends - SimpleOnGestureListener { - @Override - public boolean onSingleTapConfirmed(MotionEvent e) { - if (prefs.getString("memButtonST", "RELAUNCH").equals( - "RELAUNCH")) { - Intent intent = new Intent(ReLaunch.this, - TaskManager.class); - startActivity(intent); - } else if (prefs.getString("memButtonST", "RELAUNCH") - .equals("LOCK")) { - actionLock(); - } else if (prefs.getString("memButtonST", "RELAUNCH") - .equals("POWEROFF")) { - actionPowerOff(); - } else if (prefs.getString("memButtonST", "RELAUNCH") - .equals("SWITCHWIFI")) { - actionSwitchWiFi(); - } else if (prefs.getString("memButtonST", "RELAUNCH") - .equals("RUN")) { - actionRun(prefs.getString("memButtonSTapp", "%%")); - } - return true; - } - - @Override - public boolean onDoubleTap(MotionEvent e) { - if (prefs.getString("memButtonDT", "NOTHING").equals( - "RELAUNCH")) { - Intent intent = new Intent(ReLaunch.this, - TaskManager.class); - startActivity(intent); - } else if (prefs.getString("memButtonDT", "NOTHING") - .equals("LOCK")) { - actionLock(); - } else if (prefs.getString("memButtonDT", "NOTHING") - .equals("POWEROFF")) { - actionPowerOff(); - } else if (prefs.getString("memButtonDT", "NOTHING") - .equals("SWITCHWIFI")) { - actionSwitchWiFi(); - } else if (prefs.getString("memButtonDT", "NOTHING") - .equals("RUN")) { - actionRun(prefs.getString("memButtonDTapp", "%%")); - } - return true; - } - - @Override - public void onLongPress(MotionEvent e) { - if (mem_l.hasWindowFocus()) { - if (prefs.getString("memButtonLT", "NOTHING") - .equals("RELAUNCH")) { - Intent intent = new Intent(ReLaunch.this, - TaskManager.class); - startActivity(intent); - } else if (prefs - .getString("memButtonLT", "NOTHING") - .equals("LOCK")) { - actionLock(); - } else if (prefs - .getString("memButtonLT", "NOTHING") - .equals("POWEROFF")) { - actionPowerOff(); - } else if (prefs - .getString("memButtonLT", "NOTHING") - .equals("SWITCHWIFI")) { - actionSwitchWiFi(); - } else if (prefs - .getString("memButtonLT", "NOTHING") - .equals("RUN")) { - actionRun(prefs.getString("memButtonLTapp", - "%%")); - } - } - } - } - ; - MemlSimpleOnGestureListener meml_gl = new MemlSimpleOnGestureListener(); - final GestureDetector meml_gd = new GestureDetector(meml_gl); - mem_l.setOnTouchListener(new View.OnTouchListener() { - public boolean onTouch(View v, MotionEvent event) { - meml_gd.onTouchEvent(event); - return false; - } - }); - } - memLevel = (TextView) findViewById(R.id.mem_level); - memTitle = (TextView) findViewById(R.id.mem_title); - - // Battery Layout - final LinearLayout bat_l = (LinearLayout) findViewById(R.id.bat_layout); - if (bat_l != null) { - class BatlSimpleOnGestureListener extends - SimpleOnGestureListener { - @Override - public boolean onSingleTapConfirmed(MotionEvent e) { - if (prefs.getString("batButtonST", "RELAUNCH").equals( - "RELAUNCH")) { - Intent intent = new Intent( - Intent.ACTION_POWER_USAGE_SUMMARY); - startActivity(intent); - } else if (prefs.getString("batButtonST", "RELAUNCH") - .equals("LOCK")) { - actionLock(); - } else if (prefs.getString("batButtonST", "RELAUNCH") - .equals("POWEROFF")) { - actionPowerOff(); - } else if (prefs.getString("batButtonST", "RELAUNCH") - .equals("SWITCHWIFI")) { - actionSwitchWiFi(); - } else if (prefs.getString("batButtonST", "RELAUNCH") - .equals("RUN")) { - actionRun(prefs.getString("batButtonSTapp", "%%")); - } - return true; - } - - @Override - public boolean onDoubleTap(MotionEvent e) { - if (prefs.getString("batButtonDT", "NOTHING").equals( - "RELAUNCH")) { - Intent intent = new Intent( - Intent.ACTION_POWER_USAGE_SUMMARY); - startActivity(intent); - } else if (prefs.getString("batButtonDT", "NOTHING") - .equals("LOCK")) { - actionLock(); - } else if (prefs.getString("batButtonDT", "NOTHING") - .equals("POWEROFF")) { - actionPowerOff(); - } else if (prefs.getString("batButtonDT", "NOTHING") - .equals("SWITCHWIFI")) { - actionSwitchWiFi(); - } else if (prefs.getString("batButtonDT", "NOTHING") - .equals("RUN")) { - actionRun(prefs.getString("batButtonDTapp", "%%")); - } - return true; - } - - @Override - public void onLongPress(MotionEvent e) { - if (mem_l.hasWindowFocus()) { - if (prefs.getString("batButtonLT", "NOTHING") - .equals("RELAUNCH")) { - Intent intent = new Intent( - Intent.ACTION_POWER_USAGE_SUMMARY); - startActivity(intent); - } else if (prefs - .getString("batButtonLT", "NOTHING") - .equals("LOCK")) { - actionLock(); - } else if (prefs - .getString("batButtonLT", "NOTHING") - .equals("POWEROFF")) { - actionPowerOff(); - } else if (prefs - .getString("batButtonLT", "NOTHING") - .equals("SWITCHWIFI")) { - actionSwitchWiFi(); - } else if (prefs - .getString("batButtonLT", "NOTHING") - .equals("RUN")) { - actionRun(prefs.getString("batButtonLTapp", - "%%")); - } - } - } - } - ; - BatlSimpleOnGestureListener batl_gl = new BatlSimpleOnGestureListener(); - final GestureDetector batl_gd = new GestureDetector(batl_gl); - bat_l.setOnTouchListener(new View.OnTouchListener() { - public boolean onTouch(View v, MotionEvent event) { - batl_gd.onTouchEvent(event); - return false; - } - }); - } - // Battery buttons - battLevel = (TextView) findViewById(R.id.bat_level); - battTitle = (TextView) findViewById(R.id.bat_title); - batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); - - // What's new processing - final int latestVersion = prefs.getInt("latestVersion", 0); - int tCurrentVersion = 0; - try { - tCurrentVersion = getPackageManager().getPackageInfo( - getPackageName(), 0).versionCode; - } catch (Exception e) { - } - final int currentVersion = tCurrentVersion; - if (currentVersion > latestVersion) { - AlertDialog.Builder builder = new AlertDialog.Builder(this); - WebView wv = new WebView(this); - wv.loadDataWithBaseURL(null, - getResources().getString(R.string.about_help) - + getResources().getString(R.string.about_appr) - + getResources().getString(R.string.whats_new), - "text/html", "utf-8", null); - // "What's new" - builder.setTitle(getResources().getString( - R.string.jv_relaunch_whats_new)); - builder.setView(wv); - builder.setPositiveButton( - getResources().getString(R.string.jv_relaunch_ok), - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int whichButton) { - SharedPreferences.Editor editor = prefs.edit(); - editor.putInt("latestVersion", currentVersion); - editor.commit(); - dialog.dismiss(); - } - }); - builder.show(); - } - - // incorrect device warning - checkDevice(Build.DEVICE, Build.MANUFACTURER, Build.MODEL, - Build.PRODUCT); - - setEinkController(); - - // First directory to get to - if (data.getExtras() != null - && data.getExtras().getString("start_dir") != null) { - drawDirectory(data.getExtras().getString("start_dir"), -1); - } else { - if (prefs.getBoolean("saveDir", true)) - drawDirectory(prefs.getString("lastdir", "/sdcard"), -1); - else { - String[] startDirs = prefs.getString("startDir", - "/sdcard,/media/My Files").split("\\,"); - drawDirectory(startDirs[0], -1); - } - } - } + // Main layout + setContentView(R.layout.main); + vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); + + if (useHome && showFourPanel) { + app.readFile("app_last", APP_LRU_FILE, ":"); + app.readFile("app_favorites", APP_FAV_FILE, ":"); + // last applications button + final ImageButton lrua_button = ((ImageButton) findViewById(R.id.app_last)); + class LruaSimpleOnGestureListener extends + SimpleOnGestureListener { + @Override + public boolean onSingleTapConfirmed(MotionEvent e) { + tapButton("appLastButtonST"); + return true; + } + + @Override + public boolean onDoubleTap(MotionEvent e) { + tapButton("appLastButtonDT"); + return true; + } + + @Override + public void onLongPress(MotionEvent e) { + if (ReLaunch.this.hasWindowFocus()) + tapButton("appLastButtonLT"); + } + } + + LruaSimpleOnGestureListener lrua_gl = new LruaSimpleOnGestureListener(); + final GestureDetector lrua_gd = new GestureDetector(lrua_gl); + lrua_button.setOnTouchListener(new OnTouchListener() { + public boolean onTouch(View v, MotionEvent event) { + lrua_gd.onTouchEvent(event); + return false; + } + }); + // all applications button + final ImageButton alla_button = ((ImageButton) findViewById(R.id.all_applications_btn)); + class AllaSimpleOnGestureListener extends + SimpleOnGestureListener { + @Override + public boolean onSingleTapConfirmed(MotionEvent e) { + tapButton("appAllButtonST"); + return true; + } + + @Override + public boolean onDoubleTap(MotionEvent e) { + tapButton("appAllButtonDT"); + return true; + } + + @Override + public void onLongPress(MotionEvent e) { + if (ReLaunch.this.hasWindowFocus()) + tapButton("appAllButtonLT"); + } + + } + + AllaSimpleOnGestureListener alla_gl = new AllaSimpleOnGestureListener(); + final GestureDetector alla_gd = new GestureDetector(alla_gl); + alla_button.setOnTouchListener(new OnTouchListener() { + public boolean onTouch(View v, MotionEvent event) { + alla_gd.onTouchEvent(event); + return false; + } + }); + // applications favorites button + final ImageButton fava_button = ((ImageButton) findViewById(R.id.app_favorites)); + class FavaSimpleOnGestureListener extends + SimpleOnGestureListener { + + @Override + public boolean onSingleTapConfirmed(MotionEvent e) { + tapButton("appFavButtonST"); + return true; + } + + @Override + public boolean onDoubleTap(MotionEvent e) { + tapButton("appFavButtonDT"); + return true; + } + + @Override + public void onLongPress(MotionEvent e) { + if (ReLaunch.this.hasWindowFocus()) + tapButton("appFavButtonLT"); + } + } + FavaSimpleOnGestureListener fava_gl = new FavaSimpleOnGestureListener(); + final GestureDetector fava_gd = new GestureDetector(this, fava_gl); + fava_button.setOnTouchListener(new OnTouchListener() { + public boolean onTouch(View v, MotionEvent event) { + fava_gd.onTouchEvent(event); + return false; + } + }); + // Memory buttons (task manager activity) + final LinearLayout mem_l = (LinearLayout) findViewById(R.id.mem_layout); + if (mem_l != null) { + class MemlSimpleOnGestureListener extends + SimpleOnGestureListener { + @Override + public boolean onSingleTapConfirmed(MotionEvent e) { + tapButton("memButtonST"); + return true; + } + + @Override + public boolean onDoubleTap(MotionEvent e) { + tapButton("memButtonDT"); + return true; + } + + @Override + public void onLongPress(MotionEvent e) { + if (mem_l.hasWindowFocus()) { + tapButton("memButtonLT"); + } + } + } + + MemlSimpleOnGestureListener meml_gl = new MemlSimpleOnGestureListener(); + final GestureDetector meml_gd = new GestureDetector(meml_gl); + mem_l.setOnTouchListener(new OnTouchListener() { + public boolean onTouch(View v, MotionEvent event) { + meml_gd.onTouchEvent(event); + return false; + } + }); + } + memLevel = (TextView) findViewById(R.id.mem_level); + memTitle = (TextView) findViewById(R.id.mem_title); + + // Battery Layout + final LinearLayout bat_l = (LinearLayout) findViewById(R.id.bat_layout); + if (bat_l != null) { + class BatlSimpleOnGestureListener extends + SimpleOnGestureListener { + @Override + public boolean onSingleTapConfirmed(MotionEvent e) { + tapButton("batButtonST"); + return true; + } + + @Override + public boolean onDoubleTap(MotionEvent e) { + tapButton("batButtonDT"); + return true; + } + + @Override + public void onLongPress(MotionEvent e) { + if (mem_l.hasWindowFocus()) { + tapButton("batButtonLT"); + } + } + } + + BatlSimpleOnGestureListener batl_gl = new BatlSimpleOnGestureListener(); + final GestureDetector batl_gd = new GestureDetector(batl_gl); + bat_l.setOnTouchListener(new OnTouchListener() { + public boolean onTouch(View v, MotionEvent event) { + batl_gd.onTouchEvent(event); + return false; + } + }); + } + // Battery buttons + battLevel = (TextView) findViewById(R.id.bat_level); + battTitle = (TextView) findViewById(R.id.bat_title); + batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); + } else { + hideLayout(R.id.linearLayoutBottom); + } + + if (showOnePanel) { + app.readFile("lastOpened", LRU_FILE, "/"); + app.readFile("favorites", FAV_FILE, "/"); + // Home button + final ImageButton home_button = (ImageButton) findViewById(R.id.home_btn); + class HomeSimpleOnGestureListener extends + SimpleOnGestureListener { + @Override + public boolean onSingleTapConfirmed(MotionEvent e) { + tapButton("homeButtonST"); + return true; + } + + @Override + public boolean onDoubleTap(MotionEvent e) { + tapButton("homeButtonDT"); + return true; + } + + @Override + public void onLongPress(MotionEvent e) { + if (home_button.hasWindowFocus()) { + tapButton("homeButtonLT"); + } + } + } + + HomeSimpleOnGestureListener home_gl = new HomeSimpleOnGestureListener(); + final GestureDetector home_gd = new GestureDetector(home_gl); + home_button.setOnTouchListener(new OnTouchListener() { + public boolean onTouch(View v, MotionEvent event) { + home_gd.onTouchEvent(event); + return false; + } + }); + // Settings button + final ImageButton settings_button = (ImageButton) findViewById(R.id.settings_btn); + class SettingsSimpleOnGestureListener extends + SimpleOnGestureListener { + @Override + public boolean onSingleTapConfirmed(MotionEvent e) { + tapButton("settingsButtonST"); + return true; + } + + @Override + public boolean onDoubleTap(MotionEvent e) { + tapButton("settingsButtonDT"); + return true; + } + + @Override + public void onLongPress(MotionEvent e) { + if (settings_button.hasWindowFocus()) { + tapButton("settingsButtonLT"); + } + } + } + + SettingsSimpleOnGestureListener settings_gl = new SettingsSimpleOnGestureListener(); + final GestureDetector settings_gd = new GestureDetector( + settings_gl); + settings_button.setOnTouchListener(new OnTouchListener() { + public boolean onTouch(View v, MotionEvent event) { + settings_gd.onTouchEvent(event); + return false; + } + }); + // Search button + final ImageButton search_button = (ImageButton) findViewById(R.id.search_btn); + class SearchSimpleOnGestureListener extends + SimpleOnGestureListener { + @Override + public boolean onSingleTapConfirmed(MotionEvent e) { + tapButton("searchButtonST"); + return true; + } + + @Override + public boolean onDoubleTap(MotionEvent e) { + tapButton("searchButtonDT"); + return true; + } + + @Override + public void onLongPress(MotionEvent e) { + if (settings_button.hasWindowFocus()) { + tapButton("searchButtonLT"); + } + } + } + + SearchSimpleOnGestureListener search_gl = new SearchSimpleOnGestureListener(); + final GestureDetector search_gd = new GestureDetector(search_gl); + search_button.setOnTouchListener(new OnTouchListener() { + public boolean onTouch(View v, MotionEvent event) { + search_gd.onTouchEvent(event); + return false; + } + }); + // Last open book + final ImageButton lru_button = (ImageButton) findViewById(R.id.lru_btn); + class LruSimpleOnGestureListener extends + SimpleOnGestureListener { + @Override + public boolean onSingleTapConfirmed(MotionEvent e) { + tapButton("lruButtonST"); + return true; + } + + @Override + public boolean onDoubleTap(MotionEvent e) { + tapButton("lruButtonDT"); + return true; + } + + @Override + public void onLongPress(MotionEvent e) { + if (lru_button.hasWindowFocus()) { + tapButton("lruButtonLT"); + } + } + } + + LruSimpleOnGestureListener lru_gl = new LruSimpleOnGestureListener(); + final GestureDetector lru_gd = new GestureDetector(lru_gl); + lru_button.setOnTouchListener(new OnTouchListener() { + public boolean onTouch(View v, MotionEvent event) { + lru_gd.onTouchEvent(event); + return false; + } + }); + // Favorites book + final ImageButton fav_button = (ImageButton) findViewById(R.id.favor_btn); + class FavSimpleOnGestureListener extends + SimpleOnGestureListener { + @Override + public boolean onSingleTapConfirmed(MotionEvent e) { + tapButton("favButtonST"); + return true; + } + + @Override + public boolean onDoubleTap(MotionEvent e) { + tapButton("favButtonDT"); + return true; + } + + @Override + public void onLongPress(MotionEvent e) { + if (fav_button.hasWindowFocus()) { + tapButton("favButtonLT"); + } + } + } + + FavSimpleOnGestureListener fav_gl = new FavSimpleOnGestureListener(); + final GestureDetector fav_gd = new GestureDetector(fav_gl); + fav_button.setOnTouchListener(new OnTouchListener() { + public boolean onTouch(View v, MotionEvent event) { + fav_gd.onTouchEvent(event); + return false; + } + }); + } else { + hideLayout(R.id.linearLayoutTop); + } + + if (showTwoPanel) { + // кнопка заголовка на которой отображается текущая папка + tv_title = (Button) findViewById(R.id.title_txt); + class TvSimpleOnGestureListener extends SimpleOnGestureListener { + @Override + public boolean onSingleTapConfirmed(MotionEvent e) { + final String[] columns = getResources().getStringArray( + R.array.output_columns_names); + final CharSequence[] columnsmode = new CharSequence[columns.length + 1]; + columnsmode[0] = getResources().getString( + R.string.jv_relaunch_default); + System.arraycopy(columns, 0, columnsmode, 1, columns.length); + Integer checked; + if (app.columns.containsKey(currentRoot)) { + if (app.columns.get(currentRoot) == -1) { + checked = 1; + } else { + checked = app.columns.get(currentRoot) + 1; + } + } else { + checked = 0; + } + // get checked + AlertDialog.Builder builder = new AlertDialog.Builder( ReLaunch.this); + // "Select application" + builder.setTitle(getResources().getString(R.string.jv_relaunch_select_columns)); + builder.setSingleChoiceItems(columnsmode, checked, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int i) { + if (i == 0) { + app.columns.remove(currentRoot); + } else { + if (i == 1) { + app.columns.put(currentRoot, -1); + } else { + app.columns.put(currentRoot, i - 1); + } + } + app.saveList("columns"); + drawDirectory(currentRoot, currentPosition); + dialog.dismiss(); + } + }); + AlertDialog alert = builder.create(); + alert.show(); + return true; + } + + @Override + public boolean onDoubleTap(MotionEvent e) { + return true; + } + + @Override + public void onLongPress(MotionEvent e) { + menuSort(); + } + } + + TvSimpleOnGestureListener tv_gl = new TvSimpleOnGestureListener(); + final GestureDetector tv_gd = new GestureDetector(tv_gl); + tv_title.setOnTouchListener(new OnTouchListener() { + public boolean onTouch(View v, MotionEvent event) { + tv_gd.onTouchEvent(event); + return false; + } + }); + } else { + hideLayout(R.id.title_txt); + } + if (showThreePanel) { + // Advanced button + final ImageButton adv = (ImageButton) findViewById(R.id.advanced_btn); + if (adv != null) { + class advSimpleOnGestureListener extends SimpleOnGestureListener { + @Override + public boolean onSingleTapConfirmed(MotionEvent e) { + tapButton("advancedButtonST"); + return true; + } + + @Override + public boolean onDoubleTap(MotionEvent e) { + tapButton("advancedButtonDT"); + return true; + } + + @Override + public void onLongPress(MotionEvent e) { + if (adv.hasWindowFocus()) { + tapButton("advancedButtonLT"); + } + } + } + + advSimpleOnGestureListener adv_gl = new advSimpleOnGestureListener(); + final GestureDetector adv_gd = new GestureDetector(adv_gl); + adv.setOnTouchListener(new OnTouchListener() { + public boolean onTouch(View v, MotionEvent event) { + adv_gd.onTouchEvent(event); + return false; + } + }); + } + + // кнопка перехода в родительскую папку + upButton = (Button) findViewById(R.id.goup_btn); + // gesture listener + class UpSimpleOnGestureListener extends SimpleOnGestureListener { + @Override + public boolean onSingleTapConfirmed(MotionEvent e) { + if (!upDir.equals("")) { + Integer p = -1; + if (!positions.empty()){ + p = positions.pop(); + } + drawDirectory(upDir, p); + } + return true; + } + } + + UpSimpleOnGestureListener up_gl = new UpSimpleOnGestureListener(); + final GestureDetector up_gd = new GestureDetector(up_gl); + upButton.setOnTouchListener(new OnTouchListener() { + public boolean onTouch(View v, MotionEvent event) { + up_gd.onTouchEvent(event); + return false; + } + }); + + // up scroll button + upScroll = (Button) findViewById(R.id.upscroll_btn); + if (!disableScrollJump) { + upScroll.setText(app.scrollStep + "%"); + } else { + upScroll.setText(getResources().getString(R.string.jv_relaunch_prev)); + } + class upScrlSimpleOnGestureListener extends SimpleOnGestureListener { + @Override + public boolean onSingleTapConfirmed(MotionEvent e) { + if (N2DeviceInfo.EINK_NOOK) { // nook + MotionEvent ev; + ev = MotionEvent.obtain(SystemClock.uptimeMillis(), + SystemClock.uptimeMillis(), + MotionEvent.ACTION_DOWN, 200, 100, 0); + if (ev != null) { + gvList.dispatchTouchEvent(ev); + } + + ev = MotionEvent.obtain(SystemClock.uptimeMillis(), + SystemClock.uptimeMillis() + 100, + MotionEvent.ACTION_MOVE, 200, 200, 0); + if (ev != null) { + gvList.dispatchTouchEvent(ev); + } + SystemClock.sleep(100); + ev = MotionEvent.obtain(SystemClock.uptimeMillis(), + SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, + 200, 200, 0); + if (ev != null) { + gvList.dispatchTouchEvent(ev); + } + } else { // other devices + int first = gvList.getFirstVisiblePosition(); + int visible = gvList.getLastVisiblePosition() - gvList.getFirstVisiblePosition() + 1; + int total = itemsArray.size(); + first -= visible; + if (first < 0) + first = 0; + gvList.setSelection(first); + // some hack workaround against not scrolling in some cases + if (total > 0) { + gvList.requestFocusFromTouch(); + gvList.setSelection(first); + } + } + return true; + } + + @Override + public boolean onDoubleTap(MotionEvent e) { + if (!disableScrollJump) { + int first = gvList.getFirstVisiblePosition(); + int total = itemsArray.size(); + first -= (total * app.scrollStep) / 100; + if (first < 0) + first = 0; + gvList.setSelection(first); + // some hack workaround against not scrolling in some cases + if (total > 0) { + gvList.requestFocusFromTouch(); + gvList.setSelection(first); + } + } + return true; + } + + @Override + public void onLongPress(MotionEvent e) { + if (upScroll.hasWindowFocus()) { + if (!disableScrollJump) { + int total = itemsArray.size(); + gvList.setSelection(0); + // some hack workaround against not scrolling in some + // cases + if (total > 0) { + gvList.requestFocusFromTouch(); + gvList.setSelection(0); + } + } + } + } + } + + upScrlSimpleOnGestureListener upscrl_gl = new upScrlSimpleOnGestureListener(); + final GestureDetector upscrl_gd = new GestureDetector(upscrl_gl); + upScroll.setOnTouchListener(new OnTouchListener() { + public boolean onTouch(View v, MotionEvent event) { + upscrl_gd.onTouchEvent(event); + return false; + } + }); + + // down scroll button + downScroll = (Button) findViewById(R.id.downscroll_btn); + if (!disableScrollJump) { + downScroll.setText(app.scrollStep + "%"); + } else { + downScroll.setText(getResources().getString(R.string.jv_relaunch_next)); + } + class dnScrlSimpleOnGestureListener extends SimpleOnGestureListener { + @Override + public boolean onSingleTapConfirmed(MotionEvent e) { + if (N2DeviceInfo.EINK_NOOK) { // nook special + MotionEvent ev; + ev = MotionEvent.obtain(SystemClock.uptimeMillis(), + SystemClock.uptimeMillis(), + MotionEvent.ACTION_DOWN, 200, 200, 0); + if (ev != null) { + gvList.dispatchTouchEvent(ev); + } + ev = MotionEvent.obtain(SystemClock.uptimeMillis(), + SystemClock.uptimeMillis() + 100, + MotionEvent.ACTION_MOVE, 200, 100, 0); + if (ev != null) { + gvList.dispatchTouchEvent(ev); + } + SystemClock.sleep(100); + ev = MotionEvent.obtain(SystemClock.uptimeMillis(), + SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, + 200, 100, 0); + if (ev != null) { + gvList.dispatchTouchEvent(ev); + } + } else { // other devices + int first = gvList.getFirstVisiblePosition(); + int total = itemsArray.size(); + int last = gvList.getLastVisiblePosition(); + if (total == last + 1) + return true; + int target = last + 1; + if (target > (total - 1)) + target = total - 1; + RepeatedDownScroll ds = new RepeatedDownScroll(); + ds.doIt(first, target, 0); + } + return true; + } + + @Override + public boolean onDoubleTap(MotionEvent e) { + if (!disableScrollJump) { + int first = gvList.getFirstVisiblePosition(); + int total = itemsArray.size(); + int last = gvList.getLastVisiblePosition(); + if (total == last + 1) + return true; + int target = first + (total * app.scrollStep) / 100; + if (target <= last) + target = last + 1; // Special for NOOK, otherwise it + // won't redraw the listview + if (target > (total - 1)) + target = total - 1; + RepeatedDownScroll ds = new RepeatedDownScroll(); + ds.doIt(first, target, 0); + } + return true; + } + + @Override + public void onLongPress(MotionEvent e) { + if (downScroll.hasWindowFocus()) { + if (!disableScrollJump) { + int first = gvList.getFirstVisiblePosition(); + int total = itemsArray.size(); + int last = gvList.getLastVisiblePosition(); + if (total == last + 1) + return; + int target = total - 1; + RepeatedDownScroll ds = new RepeatedDownScroll(); + ds.doIt(first, target, 0); + } + } + } + } + + dnScrlSimpleOnGestureListener dnscrl_gl = new dnScrlSimpleOnGestureListener(); + final GestureDetector dnscrl_gd = new GestureDetector(dnscrl_gl); + downScroll.setOnTouchListener(new OnTouchListener() { + public boolean onTouch(View v, MotionEvent event) { + dnscrl_gd.onTouchEvent(event); + return false; + } + }); + } else { + hideLayout(R.id.linearLayoutNavigate); + } + + + + // список файлов и папок + String[] from = new String[] { "name" }; + int[] to = new int[] { R.id.fl_text }; + gvList = (GridView) findViewById(R.id.gl_list); + adapter = new FLSimpleAdapter1(this, itemsArray, R.layout.flist_layout, from, to); + gvList.setAdapter(adapter); + gvList.setHorizontalSpacing(0); + if (prefs.getBoolean("customScroll", app.customScrollDef)) { + if (addSView) { + int scrollW; + try { + scrollW = Integer.parseInt(prefs.getString("scrollWidth", "25")); + } catch (NumberFormatException e) { + scrollW = 25; + } + LinearLayout ll = (LinearLayout) findViewById(R.id.gl_layout); + final SView sv = new SView(getBaseContext()); + LinearLayout.LayoutParams pars = new LinearLayout.LayoutParams(scrollW, ViewGroup.LayoutParams.FILL_PARENT, 1f); + sv.setLayoutParams(pars); + ll.addView(sv); + gvList.setOnScrollListener(new AbsListView.OnScrollListener() { + public void onScroll(AbsListView view, + int firstVisibleItem, int visibleItemCount, + int totalItemCount) { + sv.total = totalItemCount; + sv.count = visibleItemCount; + sv.first = firstVisibleItem; + EinkScreen.PrepareController(null, false); + sv.invalidate(); + } + + public void onScrollStateChanged(AbsListView view, + int scrollState) { + } + }); + addSView = false; + } + } else { + gvList.setOnScrollListener(new AbsListView.OnScrollListener() { + public void onScroll(AbsListView view, int firstVisibleItem, + int visibleItemCount, int totalItemCount) { + EinkScreen.PrepareController(null, false); + } + + public void onScrollStateChanged(AbsListView view, int scrollState) { + } + }); + } + class GlSimpleOnGestureListener extends SimpleOnGestureListener { + Context context; + + public GlSimpleOnGestureListener(Context context) { + super(); + this.context = context; + } + public int findViewByXY(MotionEvent e) { + int location[] = new int[2]; + float x = e.getRawX(); + float y = e.getRawY(); + int first = gvList.getFirstVisiblePosition(); + int last = gvList.getLastVisiblePosition(); + int count = last -first + 1; + for (int i = 0; i viewX && x < (viewX + v.getWidth())) && + ( y > viewY && y < (viewY + v.getHeight()))){ + return first + i; + } + } + return -1; + } + + @Override + public boolean onSingleTapConfirmed(MotionEvent e) { + int position = findViewByXY(e); + if (position == -1){ + return true; + } + HashMap item = itemsArray.get(position); + if (item.get("type").equals("dir")) { + // Goto directory + pushCurrentPos(gvList, true); + drawDirectory(item.get("fname"), -1); + }else{ + String tempName = item.get("fname"); + String fname; + if(tempName.startsWith("Dropbox| ")){ + fname = loadFileDB(tempName, item.get("name")); + }else{ + fname = tempName; + } + if (app.specialAction(ReLaunch.this, fname)){ + pushCurrentPos(gvList, false); + }else { + prefsEditor.putInt("posInFolder", gvList.getFirstVisiblePosition()); + prefsEditor.commit(); + pushCurrentPos(gvList, false); + if (item.get("reader").equals("Nope")){ + app.defaultAction(ReLaunch.this, fname); + }else { + // Launch reader + if (app.askIfAmbiguous) { + List rdrs = app.readerNames(fname); + if (rdrs.size() < 1) + return true; + else if (rdrs.size() == 1) + start(app.launchReader(rdrs.get(0), fname)); + else { + final CharSequence[] applications = rdrs.toArray(new CharSequence[rdrs.size()]); + final String rdr1 = fname; + AlertDialog.Builder builder = new AlertDialog.Builder(ReLaunch.this); + // "Select application" + builder.setTitle(getResources().getString( R.string.jv_relaunch_select_application)); + builder.setSingleChoiceItems(applications, -1, + new DialogInterface.OnClickListener() { + public void onClick( + DialogInterface dialog, + int i) { + start(app.launchReader((String) applications[i],rdr1)); + dialog.dismiss(); + } + }); + AlertDialog alert = builder.create(); + alert.show(); + } + } else{ + start(app.launchReader(item.get("reader"),fname)); + } + } + } + } + return true; + } + + @Override + public boolean onDoubleTap(MotionEvent e) { + int position = findViewByXY(e); + if (position != -1) { + HashMap item = itemsArray.get(position); + String file = item.get("dname") + "/" + item.get("name"); + if (file.endsWith("fb2") || file.endsWith("fb2.zip") || file.endsWith("epub")) { + prefsEditor.putInt("posInFolder", gvList.getFirstVisiblePosition()); + prefsEditor.commit(); + pushCurrentPos(gvList, false); + String temp = file; + if(temp.startsWith("Dropbox| ")) { + temp = loadFileDB(temp, item.get("name")); + } + showBookInfo(temp); + } + } + return true; + } + + + @Override + public void onLongPress(MotionEvent e) { + if (!ReLaunch.this.hasWindowFocus()) + return; + int menuType; + int position = findViewByXY(e); + HashMap item; + String fn = null; + String dr = null; + String tp; + String fullName = null; + ArrayList aList = new ArrayList(10); + if (position == -1) + menuType = 0; + else { + item = itemsArray.get(position); + fn = item.get("name"); + dr = item.get("dname"); + tp = item.get("type"); + fullName = dr + "/" + fn; + if (tp.equals("dir")) + menuType = 1; + else if (fn.endsWith("fb2") || fn.endsWith("fb2.zip") || fn.endsWith("epub")) + menuType = 2; + else + menuType = 3; + } + if (menuType == 0) { + if (prefs.getBoolean("useFileManagerFunctions", true)) { + aList.add(getString(R.string.jv_relaunch_create_folder)); + if (fileOp != 0) { + aList.add(getString(R.string.jv_relaunch_paste)); + } + } + } else if (menuType == 1) { + if ((!app.isStartDir(fullName)) && (prefs.getBoolean("showAddStartDir", false))) { + aList.add(getString(R.string.jv_relaunch_set_startdir)); + aList.add(getString(R.string.jv_relaunch_add_startdir)); + } + if (!app.contains("favorites", fullName, app.DIR_TAG)) + aList.add(getString(R.string.jv_relaunch_add)); + if (prefs.getBoolean("useFileManagerFunctions", true)) { + File d = new File(fullName); + String[] allEntries = d.list(); + aList.add(getString(R.string.jv_relaunch_create_folder)); + aList.add(getString(R.string.jv_relaunch_rename)); + aList.add(getString(R.string.jv_relaunch_move)); + aList.add(getString(R.string.jv_relaunch_copy)); + if (fileOp != 0) { + aList.add(getString(R.string.jv_relaunch_paste)); + } + if (allEntries != null && allEntries.length > 0) { + aList.add(getString(R.string.jv_relaunch_delete_non_emp_dir)); + } else { + aList.add(getString(R.string.jv_relaunch_delete_emp_dir)); + } + if(arrSelItem.contains(position)){ + aList.add(getString(R.string.jv_relaunch_unselecte)); + }else { + aList.add(getString(R.string.jv_relaunch_selecte)); + } + } + aList.add(getString(R.string.jv_relaunch_fileinfo)); + } else if (menuType == 2) { + aList.add(getString(R.string.jv_relaunch_bookinfo)); + if (!app.contains("favorites", dr, fn)) { + aList.add(getString(R.string.jv_relaunch_add)); + } + if (app.history.containsKey(fullName)) { + if (app.history.get(fullName) == app.READING) { + aList.add(getString(R.string.jv_relaunch_mark)); + } else if (app.history.get(fullName) == app.FINISHED) { + aList.add(getString(R.string.jv_relaunch_unmark)); + } + aList.add(getString(R.string.jv_relaunch_unmarkall)); + } else { + aList.add(getString(R.string.jv_relaunch_mark)); + } + if (prefs.getBoolean("openWith", true)) + aList.add(getString(R.string.jv_relaunch_openwith)); + if (prefs.getBoolean("createIntent", false)) + aList.add(getString(R.string.jv_relaunch_createintent)); + if (prefs.getBoolean("useFileManagerFunctions", true)) { + if (!showBookTitles) + aList.add(getString(R.string.jv_relaunch_tags_rename)); + aList.add(getString(R.string.jv_relaunch_create_folder)); + if (!showBookTitles) + aList.add(getString(R.string.jv_relaunch_rename)); + aList.add(getString(R.string.jv_relaunch_copy)); + aList.add(getString(R.string.jv_relaunch_move)); + if (fileOp != 0) + aList.add(getString(R.string.jv_relaunch_paste)); + aList.add(getString(R.string.jv_relaunch_delete)); + } + aList.add(getString(R.string.jv_relaunch_fileinfo)); + if(arrSelItem.contains(position)){ + aList.add(getString(R.string.jv_relaunch_unselecte)); + }else { + aList.add(getString(R.string.jv_relaunch_selecte)); + } + + } else if (menuType == 3) { + if (!app.contains("favorites", dr, fn)) { + aList.add(getString(R.string.jv_relaunch_add)); + } + if (app.history.containsKey(fullName)) { + if (app.history.get(fullName) == app.READING) { + aList.add(getString(R.string.jv_relaunch_mark)); + } else if (app.history.get(fullName) == app.FINISHED) { + aList.add(getString(R.string.jv_relaunch_unmark)); + } + aList.add(getString(R.string.jv_relaunch_unmarkall)); + } else { + aList.add(getString(R.string.jv_relaunch_mark)); + } + if (prefs.getBoolean("openWith", true)) + aList.add(getString(R.string.jv_relaunch_openwith)); + if (prefs.getBoolean("createIntent", false)) + aList.add(getString(R.string.jv_relaunch_createintent)); + if (prefs.getBoolean("useFileManagerFunctions", true)) { + aList.add(getString(R.string.jv_relaunch_create_folder)); + if (!showBookTitles) + aList.add(getString(R.string.jv_relaunch_rename)); + aList.add(getString(R.string.jv_relaunch_copy)); + aList.add(getString(R.string.jv_relaunch_move)); + if (fileOp != 0) + aList.add(getString(R.string.jv_relaunch_paste)); + aList.add(getString(R.string.jv_relaunch_delete)); + } + aList.add(getString(R.string.jv_relaunch_fileinfo)); + if(arrSelItem.contains(position)){ + aList.add(getString(R.string.jv_relaunch_unselecte)); + }else { + aList.add(getString(R.string.jv_relaunch_selecte)); + } + } + if(menuType > 0 && !fullName.startsWith("Dropbox| ")){ + aList.add(getString(R.string.jv_relaunch_add_Dropbox)); + aList.add(getString(R.string.jv_relaunch_add_dir_Dropbox)); + } + if(!showOnePanel && !showTwoPanel && !showThreePanel && !showFourPanel){ + aList.add(getString(R.string.app_settings_settings)); + } + aList.add(getString(R.string.app_cancel)); + final int pos = position; + final String[] list = aList.toArray(new String[aList.size()]); + + ListAdapter cmAdapter = new ArrayAdapter( + getApplicationContext(), R.layout.cmenu_list_item, list); + + AlertDialog.Builder builder = new AlertDialog.Builder(context); + builder.setAdapter(cmAdapter, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int item) { + String s = list[item]; + if (s.equalsIgnoreCase(getString(R.string.app_cancel))) + onContextMenuSelected(CNTXT_MENU_CANCEL, pos); + else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_delete))) + onContextMenuSelected(CNTXT_MENU_DELETE_F, pos); + else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_delete_emp_dir))) + onContextMenuSelected(CNTXT_MENU_DELETE_D_EMPTY, pos); + else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_delete_non_emp_dir))) + onContextMenuSelected(CNTXT_MENU_DELETE_D_NON_EMPTY, pos); + else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_add))) + onContextMenuSelected(CNTXT_MENU_ADD, pos); + else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_mark))) + onContextMenuSelected(CNTXT_MENU_MARK_FINISHED, pos); + else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_unmark))) + onContextMenuSelected(CNTXT_MENU_MARK_READING, pos); + else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_unmarkall))) + onContextMenuSelected(CNTXT_MENU_MARK_FORGET, pos); + else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_createintent))) + onContextMenuSelected(CNTXT_MENU_INTENT, pos); + else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_openwith))) + onContextMenuSelected(CNTXT_MENU_OPENWITH, pos); + else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_copy))) + onContextMenuSelected(CNTXT_MENU_COPY_FILE, pos); + else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_move))) + onContextMenuSelected(CNTXT_MENU_MOVE_FILE, pos); + else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_paste))) + onContextMenuSelected(CNTXT_MENU_PASTE, pos); + else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_rename))) + onContextMenuSelected(CNTXT_MENU_RENAME, pos); + else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_create_folder))) + onContextMenuSelected(CNTXT_MENU_CREATE_DIR, pos); + else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_tags_rename))) + onContextMenuSelected(CNTXT_MENU_TAGS_RENAME, pos); + else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_set_startdir))) + onContextMenuSelected(CNTXT_MENU_SET_STARTDIR, pos); + else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_add_startdir))) + onContextMenuSelected(CNTXT_MENU_ADD_STARTDIR, pos); + else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_bookinfo))) + onContextMenuSelected(CNTXT_MENU_SHOW_BOOKINFO, pos); + else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_fileinfo))) + onContextMenuSelected(CNTXT_MENU_FILE_INFO, pos); + else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_add_Dropbox))) + onContextMenuSelected(CNTXT_MENU_COPY_DROPBOX, pos); + else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_add_dir_Dropbox))) + onContextMenuSelected(CNTXT_MENU_COPY_DIR_DROPBOX, pos); + else if (s.equalsIgnoreCase(getString(R.string.app_settings_settings))) + onContextMenuSelected(CNTXT_MENU_SETTINGS, pos); + else if (s.equalsIgnoreCase(getString(R.string.jv_relaunch_selecte)) || s.equalsIgnoreCase(getString(R.string.jv_relaunch_unselecte))) + onContextMenuSelected(CNTXT_MENU_SELECTE, pos); + } + }); + AlertDialog alert = builder.create(); + alert.requestWindowFeature(Window.FEATURE_NO_TITLE); + alert.show(); + } + } + + GlSimpleOnGestureListener gv_gl = new GlSimpleOnGestureListener(this); + final GestureDetector gv_gd = new GestureDetector(gv_gl); + gvList.setOnTouchListener(new OnTouchListener() { + public boolean onTouch(View v, MotionEvent event) { + gv_gd.onTouchEvent(event); + return false; + } + }); + + // What's new processing + int latestVersion = prefs.getInt("latestVersion", 0); + int tCurrentVersion = 0; + try { + tCurrentVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode; + } catch (Exception e) { + //emply + } + if (tCurrentVersion > latestVersion) { + AlertDialog.Builder builder = new AlertDialog.Builder(this); + WebView wv = new WebView(this); + wv.loadDataWithBaseURL(null, + getResources().getString(R.string.about_help) + + getResources().getString(R.string.about_appr) + + getResources().getString(R.string.whats_new), + "text/html", "utf-8", null); + // "What's new" + builder.setTitle(getResources().getString(R.string.jv_relaunch_whats_new)); + builder.setView(wv); + builder.setPositiveButton( + getResources().getString(R.string.app_ok), + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, + int whichButton) { + try { + int tCurrentVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode; + prefsEditor.putInt("latestVersion", tCurrentVersion); + prefsEditor.commit(); + } catch (Exception e) { + //emply + } + + dialog.dismiss(); + } + }); + builder.show(); + } + + // incorrect device warning + checkDevice(Build.DEVICE, Build.MANUFACTURER, Build.MODEL, Build.PRODUCT); + + EinkScreen.setEinkController(prefs); app.booted = true; - if (!mountReceiverRegistered) { - IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED); - filter.addDataScheme("file"); - registerReceiver(this.SDCardChangeReceiver, - new IntentFilter(filter)); - mountReceiverRegistered = true; - } - - if (!powerReceiverRegistered) { - IntentFilter filter = new IntentFilter(); - filter.addAction(Intent.ACTION_POWER_CONNECTED); - filter.addAction(Intent.ACTION_POWER_DISCONNECTED); - registerReceiver(this.PowerChangeReceiver, new IntentFilter(filter)); - powerReceiverRegistered = true; - } - - if (!wifiReceiverRegistered) { - IntentFilter filter = new IntentFilter(); - filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); - registerReceiver(this.WiFiChangeReceiver, new IntentFilter(filter)); - wifiReceiverRegistered = true; - } - ScreenOrientation.set(this, prefs); } @Override protected void onStart() { super.onStart(); + // register Receiver + if (!mountReceiverRegistered) { + IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED); + filter.addDataScheme("file"); + registerReceiver(this.SDCardChangeReceiver, + new IntentFilter(filter)); + mountReceiverRegistered = true; + } + + if (!powerReceiverRegistered) { + IntentFilter filter = new IntentFilter(); + filter.addAction(Intent.ACTION_POWER_CONNECTED); + filter.addAction(Intent.ACTION_POWER_DISCONNECTED); + registerReceiver(this.PowerChangeReceiver, new IntentFilter(filter)); + powerReceiverRegistered = true; + } + + if (!wifiReceiverRegistered) { + IntentFilter filter = new IntentFilter(); + filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); + registerReceiver(this.WiFiChangeReceiver, new IntentFilter(filter)); + wifiReceiverRegistered = true; + } + //===================================================================== if (app.dataBase == null) app.dataBase = new BooksBase(this); // Reread preferences - prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); String typesString = prefs.getString("types", defReaders); // Recreate readers list app.setReaders(parseReadersString(typesString)); + // known extensions + List> rc; // массив карт расширений + exts = new ArrayList(); // массив строк + // скрываем известные расширения + if (hideKnownExts) { + rc = app.getReaders(); // получаем массив карт + Set tkeys = new HashSet(); + for (HashMap aRc : rc) { + Object[] keys = aRc.keySet().toArray(); + for (Object key : keys) { + tkeys.add(key.toString()); + } + } + // получаем массив расширений + exts = new ArrayList(tkeys); + // сортируем массив расширений + Collections.sort(exts, new ExtsComparator()); + } app.askIfAmbiguous = prefs.getBoolean("askAmbig", false); + if (prefs.getBoolean("saveDir", true)) + if(N2DeviceInfo.EINK_ONYX){ + lastdir = prefs.getString("lastdir", "/mnt/storage"); + }else{ + lastdir = prefs.getString("lastdir", "/sdcard"); + } + else { + lastdir = startDir[0]; + } + if(intentStartDir != null && intentStartDir.length() > 0){ + lastdir = intentStartDir; + intentStartDir = null; + } + currentRoot = lastdir; + // при запуске учитывать работу с дропбоксом + if(currentRoot.startsWith("Dropbox| ")){ + connectDropbox(); + } drawDirectory(currentRoot, currentPosition); } @Override public boolean onCreateOptionsMenu(Menu menu) { - ; MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.mainmenu, menu); return true; @@ -2736,26 +2339,25 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case TYPES_ACT: String newTypes = createReadersString(app.getReaders()); - SharedPreferences.Editor editor = prefs.edit(); - editor.putString("types", newTypes); - editor.commit(); + prefsEditor.putString("types", newTypes); + prefsEditor.commit(); drawDirectory(currentRoot, currentPosition); break; default: - return; + //return; } } public boolean onContextMenuSelected(int itemId, int mPos) { - if (itemId == CNTXT_MENU_CANCEL) + if (itemId == CNTXT_MENU_CANCEL){ return true; + } HashMap i; int tpos = 0; -// AdapterContextMenuInfo info = (AdapterContextMenuInfo) item -// .getMenuInfo(); + if (mPos == -1) { i = new HashMap(); - i.put("dname", prefs.getString("lastdir", ".")); + i.put("dname", lastdir); i.put("name", ""); } else { tpos = mPos; @@ -2764,7 +2366,7 @@ public boolean onContextMenuSelected(int itemId, int mPos) { final int pos = tpos; final String fname = i.get("name"); final String dname = i.get("dname"); - final String fullName = dname + "/" + fname; + final String fullName = i.get("fname"); final String type = i.get("type"); switch (itemId) { @@ -2784,17 +2386,17 @@ public boolean onContextMenuSelected(int itemId, int mPos) { case CNTXT_MENU_MARK_READING: app.history.put(fullName, app.READING); app.saveList("history"); - redrawList(); + reDraw(); break; case CNTXT_MENU_MARK_FINISHED: app.history.put(fullName, app.FINISHED); app.saveList("history"); - redrawList(); + reDraw(); break; case CNTXT_MENU_MARK_FORGET: app.history.remove(fullName); app.saveList("history"); - redrawList(); + reDraw(); break; case CNTXT_MENU_OPENWITH: { final CharSequence[] applications = app.getApps().toArray( @@ -2808,18 +2410,19 @@ public boolean onContextMenuSelected(int itemId, int mPos) { } AlertDialog.Builder builder = new AlertDialog.Builder(ReLaunch.this); // "Select application" - builder.setTitle(getResources().getString( - R.string.jv_relaunch_select_application)); + builder.setTitle(getResources().getString(R.string.jv_relaunch_select_application)); builder.setSingleChoiceItems(happlications, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int i) { - start(app.launchReader((String) applications[i], - fullName)); + String temp = fullName; + if(temp.startsWith("Dropbox| ")) { + temp = loadFileDB(temp, fname); + } + start(app.launchReader((String) applications[i], temp)); dialog.dismiss(); } }); - builder.setNegativeButton( - getResources().getString(R.string.jv_relaunch_cancel), + builder.setNegativeButton(getResources().getString(R.string.app_cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -2849,32 +2452,29 @@ public void onClick(DialogInterface dialog, } } } - - final CharSequence[] intents = ilist.toArray(new CharSequence[ilist - .size()]); + final CharSequence[] intents = ilist.toArray(new CharSequence[ilist.size()]); AlertDialog.Builder builder = new AlertDialog.Builder(ReLaunch.this); // "Select intent type" - builder.setTitle(getResources().getString( - R.string.jv_relaunch_select_intent_type)); + builder.setTitle(getResources().getString(R.string.jv_relaunch_select_intent_type)); builder.setSingleChoiceItems(intents, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int i) { + String temp = fullName; + if(temp.startsWith("Dropbox| ")) { + temp = loadFileDB(temp, fname); + } Intent in = new Intent(); in.setAction(Intent.ACTION_VIEW); - in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK - | Intent.FLAG_ACTIVITY_CLEAR_TOP); - in.setDataAndType(Uri.parse("file://" + fullName), - (String) intents[i]); + in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); + in.setDataAndType(Uri.parse("file://" + temp),(String) intents[i]); dialog.dismiss(); try { startActivity(in); } catch (ActivityNotFoundException e) { - AlertDialog.Builder builder1 = new AlertDialog.Builder( - ReLaunch.this); + AlertDialog.Builder builder1 = new AlertDialog.Builder(ReLaunch.this); // "Activity not found" builder1.setTitle(getResources() - .getString( - R.string.jv_relaunch_activity_not_found_title)); + .getString(R.string.jv_relaunch_activity_not_found_title)); // "Activity for file \"" + fullName + // "\" with type \"" + intents[i] + // "\" not found" @@ -2882,7 +2482,7 @@ public void onClick(DialogInterface dialog, int i) { .getString( R.string.jv_relaunch_activity_not_found_text1) + " \"" - + fullName + + temp + "\" " + getResources() .getString( @@ -2894,7 +2494,7 @@ public void onClick(DialogInterface dialog, int i) { .getString( R.string.jv_relaunch_activity_not_found_text3)); builder1.setPositiveButton(getResources() - .getString(R.string.jv_relaunch_ok), + .getString(R.string.app_ok), new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, @@ -2911,30 +2511,31 @@ public void onClick( new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { - AlertDialog.Builder builder1 = new AlertDialog.Builder( - ReLaunch.this); + AlertDialog.Builder builder1 = new AlertDialog.Builder(ReLaunch.this); // "Intent type" - builder1.setTitle(getResources().getString( - R.string.jv_relaunch_intent_type)); + builder1.setTitle(getResources().getString(R.string.jv_relaunch_intent_type)); final EditText input = new EditText(ReLaunch.this); input.setText("application/"); builder1.setView(input); // "Ok" builder1.setPositiveButton(getResources() - .getString(R.string.jv_relaunch_ok), + .getString(R.string.app_ok), new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int whichButton) { + String temp = fullName; + if(temp.startsWith("Dropbox| ")) { + temp = loadFileDB(temp, fname); + } Intent in = new Intent(); in.setAction(Intent.ACTION_VIEW); in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); in.setDataAndType( Uri.parse("file://" - + fullName), input - .getText() - .toString()); + + temp), String.valueOf(input.getText()) + ); dialog.dismiss(); try { startActivity(in); @@ -2953,7 +2554,7 @@ public void onClick( .getString( R.string.jv_relaunch_activity_not_found_text1) + " \"" - + fullName + + temp + "\" " + getResources() .getString( @@ -2968,7 +2569,7 @@ public void onClick( builder2.setPositiveButton( getResources() .getString( - R.string.jv_relaunch_ok), + R.string.app_ok), new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, @@ -2984,7 +2585,7 @@ public void onClick( }); // "Cancel" builder.setNegativeButton( - getResources().getString(R.string.jv_relaunch_cancel), + getResources().getString(R.string.app_cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -2996,207 +2597,238 @@ public void onClick(DialogInterface dialog, break; } case CNTXT_MENU_DELETE_F: - if (prefs.getBoolean("confirmFileDelete", true)) { - AlertDialog.Builder builder = new AlertDialog.Builder(this); - // "Delete file warning" - builder.setTitle(getResources().getString( - R.string.jv_relaunch_del_file_title)); - // "Are you sure to delete file \"" + fname + "\" ?" - builder.setMessage(getResources().getString( - R.string.jv_relaunch_del_file_text1) - + " \"" - + fname - + "\" " - + getResources().getString( - R.string.jv_relaunch_del_file_text2)); - // "Yes" - builder.setPositiveButton( - getResources().getString(R.string.jv_relaunch_yes), - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int whichButton) { - dialog.dismiss(); - if (app.removeFile(dname, fname)) { - itemsArray.remove(pos); - redrawList(); - } - } - }); - // "No" - builder.setNegativeButton( - getResources().getString(R.string.jv_relaunch_no), - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int whichButton) { - dialog.dismiss(); - } - }); - builder.show(); - } else if (app.removeFile(dname, fname)) { - itemsArray.remove(pos); - redrawList(); - } + if(arrSelItem.size() < 1) { + if (prefs.getBoolean("confirmFileDelete", true)) { + AlertDialog.Builder builder = new AlertDialog.Builder(this); + // "Delete file warning" + builder.setTitle(getResources().getString(R.string.jv_relaunch_del_file_title)); + // "Are you sure to delete file \"" + fname + "\" ?" + builder.setMessage(getResources().getString( + R.string.jv_relaunch_del_file_text1) + + " \"" + + fname + + "\" " + + getResources().getString(R.string.jv_relaunch_del_file_text2)); + // "Yes" + builder.setPositiveButton(getResources().getString(R.string.app_yes), + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, + int whichButton) { + dialog.dismiss(); + delAll(fullName, dname, fname); + } + } + ); + // "No" + builder.setNegativeButton(getResources().getString(R.string.app_no), + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, + int whichButton) { + dialog.dismiss(); + } + } + ); + builder.show(); + } else { + delAll(fullName, dname, fname); + } + }else{ + delSelect(); + } break; case CNTXT_MENU_DELETE_D_EMPTY: - if (prefs.getBoolean("confirmDirDelete", true)) { - AlertDialog.Builder builder = new AlertDialog.Builder(this); - // "Delete empty directory warning" - builder.setTitle(getResources().getString( - R.string.jv_relaunch_del_em_dir_title)); - // "Are you sure to delete empty directory \"" + fname + "\" ?" - builder.setMessage(getResources().getString( - R.string.jv_relaunch_del_em_dir_text1) - + " \"" - + fname - + "\" " - + getResources().getString( - R.string.jv_relaunch_del_em_dir_text2)); - // "Yes" - builder.setPositiveButton( - getResources().getString(R.string.jv_relaunch_yes), - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int whichButton) { - dialog.dismiss(); - if (app.removeFile(dname, fname)) { - itemsArray.remove(pos); - redrawList(); - } - } - }); - // "No" - builder.setNegativeButton( - getResources().getString(R.string.jv_relaunch_no), - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int whichButton) { - dialog.dismiss(); - } - }); - builder.show(); - } else if (app.removeFile(dname, fname)) { - itemsArray.remove(pos); - redrawList(); - } + if(arrSelItem.size() < 1) { + if (prefs.getBoolean("confirmDirDelete", true)) { + AlertDialog.Builder builder = new AlertDialog.Builder(this); + // "Delete empty directory warning" + builder.setTitle(getResources().getString(R.string.jv_relaunch_del_em_dir_title)); + // "Are you sure to delete empty directory \"" + fname + "\" ?" + builder.setMessage(getResources().getString( + R.string.jv_relaunch_del_em_dir_text1) + + " \"" + + fname + + "\" " + + getResources().getString(R.string.jv_relaunch_del_em_dir_text2)); + // "Yes" + builder.setPositiveButton(getResources().getString(R.string.app_yes), + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, + int whichButton) { + dialog.dismiss(); + delAll(fullName, dname, fname); + } + }); + // "No" + builder.setNegativeButton(getResources().getString(R.string.app_no), + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, + int whichButton) { + dialog.dismiss(); + } + }); + builder.show(); + } else { + delAll(fullName, dname, fname); + } + }else{ + delSelect(); + } break; case CNTXT_MENU_DELETE_D_NON_EMPTY: - if (prefs.getBoolean("confirmNonEmptyDirDelete", true)) { - AlertDialog.Builder builder = new AlertDialog.Builder(this); - // "Delete non empty directory warning" - builder.setTitle(getResources().getString( - R.string.jv_relaunch_del_ne_dir_title)); - // "Are you sure to delete non-empty directory \"" + fname + - // "\" (dangerous) ?" - builder.setMessage(getResources().getString( - R.string.jv_relaunch_del_ne_dir_text1) - + " \"" - + fname - + "\" " - + getResources().getString( - R.string.jv_relaunch_del_ne_dir_text2)); - // "Yes" - builder.setPositiveButton( - getResources().getString(R.string.jv_relaunch_yes), - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int whichButton) { - dialog.dismiss(); - if (app.removeDirectory(dname, fname)) { - itemsArray.remove(pos); - redrawList(); - } - } - }); - // "No" - builder.setNegativeButton( - getResources().getString(R.string.jv_relaunch_no), - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int whichButton) { - dialog.dismiss(); - } - }); - builder.show(); - } else if (app.removeDirectory(dname, fname)) { - itemsArray.remove(pos); - redrawList(); - } + if(arrSelItem.size() < 1) { + if (prefs.getBoolean("confirmNonEmptyDirDelete", true)) { + AlertDialog.Builder builder = new AlertDialog.Builder(this); + // "Delete non empty directory warning" + builder.setTitle(getResources().getString(R.string.jv_relaunch_del_ne_dir_title)); + // "Are you sure to delete non-empty directory \"" + fname + + // "\" (dangerous) ?" + builder.setMessage(getResources().getString( + R.string.jv_relaunch_del_ne_dir_text1) + + " \"" + + fname + + "\" " + + getResources().getString(R.string.jv_relaunch_del_ne_dir_text2)); + // "Yes" + builder.setPositiveButton( + getResources().getString(R.string.app_yes), + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, + int whichButton) { + dialog.dismiss(); + delAll(fullName, dname, fname); + } + }); + // "No" + builder.setNegativeButton( + getResources().getString(R.string.app_no), + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, + int whichButton) { + dialog.dismiss(); + } + }); + builder.show(); + } else{ + delAll(fullName, dname, fname); + } + }else{ + delSelect(); + } break; - case CNTXT_MENU_COPY_FILE: - fileOpFile = fname; - fileOpDir = dname; - fileOp = CNTXT_MENU_COPY_FILE; + if(arrSelItem.size() < 1) { + fileOpFile = new String[1]; + fileOpDir = new String[1]; + fileOpFile[0] = fname; + fileOpDir[0] = dname; + }else{ + HashMap i2; + int k = arrSelItem.size(); + fileOpFile = new String[k]; + fileOpDir = new String[k]; + + for(int i1=0; i1 < k; i1++){ + i2 = itemsArray.get(arrSelItem.get(i1)); + fileOpDir[i1] = i2.get("dname"); + fileOpFile[i1] = i2.get("name"); + } + } + fileOp = CNTXT_MENU_COPY_FILE; break; case CNTXT_MENU_MOVE_FILE: - fileOpFile = fname; - fileOpDir = dname; - fileOp = CNTXT_MENU_MOVE_FILE; - break; - - case CNTXT_MENU_MOVE_DIR: - fileOpFile = fname; - fileOpDir = dname; - fileOp = CNTXT_MENU_MOVE_DIR; + if(arrSelItem.size() < 1) { + fileOpFile = new String[1]; + fileOpDir = new String[1]; + fileOpFile[0] = fname; + fileOpDir[0] = dname; + }else{ + HashMap i2; + int k = arrSelItem.size(); + fileOpFile = new String[k]; + fileOpDir = new String[k]; + for(int i1=0; i1 < k; i1++){ + i2 = itemsArray.get(arrSelItem.get(i1)); + fileOpDir[i1] = i2.get("dname"); + fileOpFile[i1] = i2.get("name"); + } + } + fileOp = CNTXT_MENU_MOVE_FILE; break; case CNTXT_MENU_PASTE: - String src; - if (fileOpDir.equalsIgnoreCase("/")) - src = fileOpDir + fileOpFile; - else - src = fileOpDir + "/" + fileOpFile; - String dst = dname + "/" + fileOpFile; - boolean retCode = false; - if (fileOp == CNTXT_MENU_COPY_FILE) - retCode = app.copyFile(src, dst, false); - else if ((fileOp == CNTXT_MENU_MOVE_FILE) || (fileOp == CNTXT_MENU_MOVE_DIR)) - retCode = app.moveFile(src, dst); - if (retCode) { - HashMap fitem = new HashMap(); - fitem.put("name", fileOpFile); - fitem.put("dname", dname); - fitem.put("fname", dname + "/" + fileOpFile); - if ((fileOp == CNTXT_MENU_MOVE_FILE) || (fileOp == CNTXT_MENU_COPY_FILE)) { - fitem.put("type", "file"); - fitem.put("reader", app.readerName(fileOpFile)); - if (prefs.getBoolean("showBookTitles", false)) - fitem.put("sname", app.dataBase.getEbookName(dname, fileOpFile, prefs.getString("bookTitleFormat", "%t[\n%a][. %s][-%n]"))); - else - fitem.put("sname", fileOpFile); - } else if (fileOp == CNTXT_MENU_MOVE_DIR) { - fitem.put("sname", fileOpFile); - fitem.put("type", "dir"); - fitem.put("reader", "nope"); - } - itemsArray.add(fitem); - fileOp = 0; -// redrawList(); - drawDirectory(dname, currentPosition); - } else { - AlertDialog.Builder builder = new AlertDialog.Builder(this); - builder.setTitle(getResources().getString( - R.string.jv_relaunch_error_title)); - builder.setMessage(getResources().getString( - R.string.jv_relaunch_paste_fail_text) - + " " + fileOpFile); - builder.setNeutralButton( - getResources().getString(R.string.jv_relaunch_ok), - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int whichButton) { - dialog.dismiss(); - } - }); - builder.show(); - } + String src; + String dst; + + for(int l=0; l < fileOpDir.length; l++) { + if (fileOpDir[l].equalsIgnoreCase("/")) + src = fileOpDir[l] + fileOpFile[l]; + else + src = fileOpDir[l] + "/" + fileOpFile[l]; + dst = dname + "/" + fileOpFile[l]; + + boolean dropSrc = src.startsWith("Dropbox| ");// источник в дропе? + boolean dropDst = dst.startsWith("Dropbox| ");// приемник в дропе? + + boolean retCode = false; + // если источник и приемник в дропе. + if (dropSrc && dropDst) { + if (fileOp == CNTXT_MENU_COPY_FILE) { + retCode = DBmoveORcopy(src, dst, true); + } else if (fileOp == CNTXT_MENU_MOVE_FILE) { + retCode = DBmoveORcopy(src, dst, false); + } + } + // если источник лосально, а приемник в дропе. + if (!dropSrc && dropDst) { + retCode = DBupload(src, dname); + if (fileOp == CNTXT_MENU_MOVE_FILE) { + app.removeFile(fileOpDir[l], fileOpFile[l]); + } + } + // если источник в дропе, а приемник локально. + if (dropSrc && !dropDst) { + retCode = DBdownload(src, dname); + if (fileOp == CNTXT_MENU_MOVE_FILE) { + DBdelete(src); + } + } + // если файлы находяться локально + if (!dropDst && !dropSrc) { + if (fileOp == CNTXT_MENU_COPY_FILE) { + retCode = app.copyDirOrFile(src, dst, false); + } else if (fileOp == CNTXT_MENU_MOVE_FILE) { + retCode = app.moveFile(src, dst); + } + } + if (!retCode) { + AlertDialog.Builder builder = new AlertDialog.Builder(this); + builder.setTitle(getResources().getString(R.string.jv_relaunch_error_title)); + builder.setMessage(getResources().getString(R.string.jv_relaunch_paste_fail_text) + " " + fileOpFile[l]); + builder.setNeutralButton(getResources().getString(R.string.app_ok), + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, + int whichButton) { + dialog.dismiss(); + } + } + ); + builder.show(); + } + } + fileOp = 0; + drawDirectory(dname, currentPosition); break; case CNTXT_MENU_TAGS_RENAME: { final Context mThis = this; - final String oldFullName = dname + "/" + fname; - String newName = app.dataBase.getEbookName(dname, fname, prefs.getString("bookTitleFormat", "%t[\n%a][. %s][-%n]")); + String oldFullName = dname + "/" + fname; + String temp_dname = dname; + if(oldFullName.startsWith("Dropbox| ")) { + oldFullName = loadFileDB(fullName, fname); + temp_dname = oldFullName.substring(0, oldFullName.length() - (fname.length()+1)); + } + String newName = app.dataBase.getEbookName(temp_dname, fname, bookTitleFormat); newName = newName.replaceAll("[\n\r]", ". "); if (fname.endsWith("fb2")) newName = newName.concat(".fb2"); @@ -3211,28 +2843,28 @@ else if (fname.endsWith("epub")) builder.setTitle(getResources().getString( R.string.jv_relaunch_rename_title)); // "OK" - builder.setPositiveButton( - getResources().getString(R.string.jv_relaunch_ok), + final String finalOldFullName = oldFullName; + final String finalTemp_dname = temp_dname; + builder.setPositiveButton( + getResources().getString(R.string.app_ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); - String newName = input.getText().toString().trim(); - String newFullName = dname + "/" + newName; - if (app.moveFile(oldFullName, newFullName)) { - itemsArray.get(pos).put("name", newName); - itemsArray.get(pos).put("sname", newName); - itemsArray.get(pos).put("fname", newFullName); + String newName = String.valueOf(input.getText()).trim(); + String newFullName = finalTemp_dname + "/" + newName; + if(dname.startsWith("Dropbox| ")) { + DBmoveORcopy(dname + "/" + fname, dname + "/" + newName, false); + } + if (app.moveFile(finalOldFullName, newFullName)) { drawDirectory(dname, currentPosition); } else { AlertDialog.Builder builder = new AlertDialog.Builder(mThis); - builder.setTitle(getResources().getString( - R.string.jv_relaunch_error_title)); - builder.setMessage(getResources().getString( - R.string.jv_relaunch_rename_fail_text) - + " " + fname); + builder.setTitle(getResources().getString(R.string.jv_relaunch_error_title)); + builder.setMessage(getResources().getString(R.string.jv_relaunch_rename_fail_text) + + " " + fname); builder.setNeutralButton( - getResources().getString(R.string.jv_relaunch_ok), + getResources().getString(R.string.app_ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -3245,7 +2877,7 @@ public void onClick(DialogInterface dialog, }); // "Cancel" builder.setNegativeButton( - getResources().getString(R.string.jv_relaunch_cancel), + getResources().getString(R.string.app_cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -3265,31 +2897,28 @@ public void onClick(DialogInterface dialog, input.setText(fname); input.selectAll(); builder.setView(input); - builder.setTitle(getResources().getString( - R.string.jv_relaunch_rename_title)); + builder.setTitle(getResources().getString(R.string.jv_relaunch_rename_title)); // "OK" builder.setPositiveButton( - getResources().getString(R.string.jv_relaunch_ok), + getResources().getString(R.string.app_ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); - String newName = input.getText().toString().trim(); + String newName = String.valueOf(input.getText()).trim(); String newFullName = dname + "/" + newName; - if (app.moveFile(oldFullName, newFullName)) { - itemsArray.get(pos).put("name", newName); - itemsArray.get(pos).put("sname", newName); - itemsArray.get(pos).put("fname", newFullName); + if(dname.startsWith("Dropbox| ")) { + DBmoveORcopy(oldFullName, newFullName, false); + drawDirectory(dname, currentPosition); + }else if (app.moveFile(oldFullName, newFullName)) { drawDirectory(dname, currentPosition); } else { AlertDialog.Builder builder = new AlertDialog.Builder(mThis); - builder.setTitle(getResources().getString( - R.string.jv_relaunch_error_title)); + builder.setTitle(getResources().getString(R.string.jv_relaunch_error_title)); builder.setMessage(getResources().getString( - R.string.jv_relaunch_rename_fail_text) - + " " + fname); + R.string.jv_relaunch_rename_fail_text)+ " " + fname); builder.setNeutralButton( - getResources().getString(R.string.jv_relaunch_ok), + getResources().getString(R.string.app_ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -3302,7 +2931,7 @@ public void onClick(DialogInterface dialog, }); // "Cancel" builder.setNegativeButton( - getResources().getString(R.string.jv_relaunch_cancel), + getResources().getString(R.string.app_cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -3319,41 +2948,36 @@ public void onClick(DialogInterface dialog, AlertDialog.Builder builder = new AlertDialog.Builder(this); final EditText input = new EditText(this); builder.setView(input); - builder.setTitle(getResources().getString( - R.string.jv_relaunch_create_folder_title)); + builder.setTitle(getResources().getString(R.string.jv_relaunch_create_folder_title)); // "OK" builder.setPositiveButton( - getResources().getString(R.string.jv_relaunch_ok), + getResources().getString(R.string.app_ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); - String dname = prefs.getString("lastdir", "."); - String newName = input.getText().toString().trim(); + String dname = lastdir; + String newName = String.valueOf(input.getText()).trim(); if (newName.equalsIgnoreCase("")) { return; } String newFullName = dname + "/" + newName; - if (app.createDir(newFullName)) { - HashMap fitem = new HashMap(); - fitem.put("name", newName); - fitem.put("sname", newName); - fitem.put("dname", dname); - fitem.put("fname", newFullName); - fitem.put("type", "dir"); - fitem.put("reader", "nope"); - itemsArray.add(fitem); -// redrawList(); + if(dname.startsWith("Dropbox| ")) { + dname = dname.substring("Dropbox| ".length()); + try { + mDBApi.createFolder(dname + "/" + newName); + } catch (DropboxException e) { + e.printStackTrace(); + } + }else if (app.createDir(newFullName)) { drawDirectory(dname, currentPosition); } else { AlertDialog.Builder builder = new AlertDialog.Builder(mThis); - builder.setTitle(getResources().getString( - R.string.jv_relaunch_error_title)); + builder.setTitle(getResources().getString(R.string.jv_relaunch_error_title)); builder.setMessage(getResources().getString( - R.string.jv_relaunch_create_folder_fail_text) - + " " + newFullName); + R.string.jv_relaunch_create_folder_fail_text)+ " " + newFullName); builder.setNeutralButton( - getResources().getString(R.string.jv_relaunch_ok), + getResources().getString(R.string.app_ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -3366,7 +2990,7 @@ public void onClick(DialogInterface dialog, }); // "Cancel" builder.setNegativeButton( - getResources().getString(R.string.jv_relaunch_cancel), + getResources().getString(R.string.app_cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -3379,33 +3003,62 @@ public void onClick(DialogInterface dialog, break; case CNTXT_MENU_SWITCH_TITLES: - SharedPreferences.Editor editor = prefs.edit(); - editor.putBoolean("showBookTitles", !prefs.getBoolean("showBookTitles", false)); - editor.commit(); + prefsEditor.putBoolean("showBookTitles", !showBookTitles); + prefsEditor.commit(); + showBookTitles = !showBookTitles; drawDirectory(dname, currentPosition); break; case CNTXT_MENU_SHOW_BOOKINFO: - showBookInfo(dname + "/" + fname); + String temp = fullName; + if(temp.startsWith("Dropbox| ")) { + temp = loadFileDB(fullName, fname); + } + showBookInfo(temp); break; case CNTXT_MENU_FILE_INFO: - showFileInfo(dname + "/" + fname); + showFileInfo(fullName); break; + case CNTXT_MENU_COPY_DROPBOX: + copyFileToDropbox(dname, fname); + break; + + case CNTXT_MENU_COPY_DIR_DROPBOX: + copyFileToLocalDirDropbox(dname, fname); + break; + case CNTXT_MENU_SETTINGS: + menuSettings(); + break; + case CNTXT_MENU_SELECTE: + if(arrSelItem.contains(mPos)){ + // пункт уже отмечен. надо снять отметку + arrSelItem.remove(arrSelItem.indexOf(mPos)); + }else{ + // добавить отмеченный новый пункт в массив + arrSelItem.add(mPos); + } + reDraw(); + break; } + return true; } - @Override + @Override protected void onResume() { - setEinkController(); + prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); + prefsEditor = prefs.edit(); + if(currentRoot.startsWith("Dropbox| ")){ + endconnectDropbox(); + } + EinkScreen.setEinkController(prefs); super.onResume(); if (app.dataBase == null) app.dataBase = new BooksBase(this); - app.generalOnResume(TAG, this); + app.generalOnResume(TAG); refreshBottomInfo(); - redrawList(); } @Override @@ -3415,15 +3068,18 @@ protected void onStop() { int favMax = 30; int appLruMax = 30; int appFavMax = 30; + int opdsMax = 30; try { lruMax = Integer.parseInt(prefs.getString("lruSize", "30")); favMax = Integer.parseInt(prefs.getString("favSize", "30")); appLruMax = Integer.parseInt(prefs.getString("appLruSize", "30")); appFavMax = Integer.parseInt(prefs.getString("appFavSize", "30")); + opdsMax = Integer.parseInt(prefs.getString("opdsSize", "30")); } catch (NumberFormatException e) { + //emply } - app.writeFile("lastOpened", LRU_FILE, lruMax); - app.writeFile("favorites", FAV_FILE, favMax); + app.writeFile("lastOpened", LRU_FILE, lruMax, "/"); + app.writeFile("favorites", FAV_FILE, favMax, "/"); app.writeFile("app_last", APP_LRU_FILE, appLruMax, ":"); app.writeFile("app_favorites", APP_FAV_FILE, appFavMax, ":"); List h = new ArrayList(); @@ -3441,24 +3097,31 @@ else if (app.history.get(k) == app.FINISHED) } app.setList("columns", c); app.writeFile("columns", ReLaunch.COLS_FILE, 0, ":"); - // unregisterReceiver(this.SDReceiver); + // unregister Receiver + unregisterReceiver(this.SDCardChangeReceiver); + unregisterReceiver(this.PowerChangeReceiver); + unregisterReceiver(this.WiFiChangeReceiver); + wifiReceiverRegistered = false; + powerReceiverRegistered = false; + mountReceiverRegistered = false; + prefsEditor.putString("lastdir", currentRoot); + prefsEditor.commit(); super.onStop(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { - boolean isRoot = false; + boolean isRoot = false; if (!useHome) return super.onKeyDown(keyCode, event); if (keyCode == KeyEvent.KEYCODE_HOME) return true; if (keyCode == KeyEvent.KEYCODE_BACK) { if (prefs.getBoolean("useBackButton", true)) { - String[] rootDirs = prefs.getString("startDir", "/sdcard").split(","); - for (int i = 0; i < rootDirs.length; i++) { - if (rootDirs[i].equalsIgnoreCase(currentRoot)) - isRoot = true; - } + for (String aStartDir : startDir) { + if (aStartDir.equalsIgnoreCase(currentRoot)) + isRoot = true; + } if (currentRoot.equalsIgnoreCase("/")) isRoot = true; if (!isRoot) { @@ -3468,29 +3131,20 @@ public boolean onKeyDown(int keyCode, KeyEvent event) { } if ((isRoot) || (!prefs.getBoolean("useBackButton", true))) { // Ask the user if they want to quit - new AlertDialog.Builder(this) - .setIcon(android.R.drawable.ic_dialog_alert) + new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert) // "This is a launcher!" - .setTitle( - getResources().getString( - R.string.jv_relaunch_launcher)) + .setTitle(getResources().getString(R.string.jv_relaunch_launcher)) // "Are you sure you want to quit ?" - .setMessage( - getResources().getString( - R.string.jv_relaunch_launcher_text)) + .setMessage(getResources().getString(R.string.jv_relaunch_launcher_text)) // "YES" - .setPositiveButton( - getResources().getString(R.string.jv_relaunch_yes), + .setPositiveButton(getResources().getString(R.string.app_yes), new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int which) { + public void onClick(DialogInterface dialog,int which) { finish(); } }) // "NO" - .setNegativeButton( - getResources().getString(R.string.jv_relaunch_no), - null).show(); + .setNegativeButton(getResources().getString(R.string.app_no),null).show(); } return true; } else { @@ -3517,8 +3171,7 @@ private void menuLastopened() { Intent intent = new Intent(ReLaunch.this, ResultsActivity.class); intent.putExtra("list", "lastOpened"); // "Last opened" - intent.putExtra("title", - getResources().getString(R.string.jv_relaunch_lru)); + intent.putExtra("title",getResources().getString(R.string.jv_relaunch_lru)); intent.putExtra("rereadOnStart", true); startActivity(intent); } @@ -3527,31 +3180,25 @@ private void menuFavorites() { Intent intent = new Intent(ReLaunch.this, ResultsActivity.class); intent.putExtra("list", "favorites"); // "Favorites" - intent.putExtra("title", - getResources().getString(R.string.jv_relaunch_fav)); + intent.putExtra("title",getResources().getString(R.string.jv_relaunch_fav)); intent.putExtra("rereadOnStart", true); - setEinkController(); // ??? not needed startActivity(intent); } private void openHome(Integer order_num) { - String[] startDirs = prefs.getString("startDir", - "/sdcard,/media/My Files").split("\\,"); - if (order_num > 0 && order_num <= startDirs.length) { - drawDirectory(startDirs[order_num - 1], -1); + if (order_num > 0 && order_num <= startDir.length) { + drawDirectory(startDir[order_num - 1], -1); } } private void menuHome() { - final String[] homesList = prefs.getString("startDir", - "/sdcard,/media/My Files").split("\\,"); - final CharSequence[] hhomes = new CharSequence[homesList.length]; - for (int j = 0; j < homesList.length; j++) { - int ind = homesList[j].lastIndexOf('/'); - if (ind == -1) { + final CharSequence[] hhomes = new CharSequence[startDir.length]; + for (int j = 0; j < startDir.length; j++) { + int ind = startDir[j].lastIndexOf('/'); + if (ind == -1 && !startDir[j].equals("Dropbox| ")) { hhomes[j] = ""; } else { - hhomes[j] = homesList[j].substring(ind + 1); + hhomes[j] = startDir[j].substring(ind + 1); if (hhomes[j].equals("")) { hhomes[j] = "/"; } @@ -3563,12 +3210,18 @@ private void menuHome() { builder.setSingleChoiceItems(hhomes, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int i) { - drawDirectory(homesList[i], -1); + if(startDir[i].equals("Dropbox| ")){ + if(connectDropbox()){ + drawDirectory("Dropbox| /", -1); + } + }else{ + drawDirectory(startDir[i], -1); + } dialog.dismiss(); } }); builder.setNegativeButton( - getResources().getString(R.string.jv_relaunch_cancel), + getResources().getString(R.string.app_cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); @@ -3580,23 +3233,34 @@ public void onClick(DialogInterface dialog, int whichButton) { private void screenHome() { // make home list List homeList = new ArrayList(); - String[] startDirs = prefs.getString("startDir", - "/sdcard,/media/My Files").split("\\,"); - for (Integer i = 0; i < startDirs.length; i++) { - String[] homeEl = new String[2]; - homeEl[0] = startDirs[i]; - homeEl[1] = app.DIR_TAG; - homeList.add(homeEl); - } + for (String aStartDir : startDir) { + String[] homeEl = new String[2]; + homeEl[0] = aStartDir; + homeEl[1] = app.DIR_TAG; + homeList.add(homeEl); + } app.setList("homeList", homeList); Intent intent = new Intent(ReLaunch.this, ResultsActivity.class); intent.putExtra("list", "homeList"); - intent.putExtra("title", - getResources().getString(R.string.jv_relaunch_home)); + intent.putExtra("title", getResources().getString(R.string.jv_relaunch_home)); intent.putExtra("rereadOnStart", true); startActivity(intent); } + private void screenDropbox() { + Intent intent = new Intent(ReLaunch.this, DropBoxActivity.class); + startActivity(intent); + } + + private void screenOPDS() { + // + Intent intent = new Intent(ReLaunch.this, ResultsActivity.class); + intent.putExtra("list", "opdslist"); + intent.putExtra("title", getResources().getString(R.string.jv_relaunch_OPDS_catalogs)); + intent.putExtra("rereadOnStart", true); + startActivity(intent); + + } private void menuAbout() { app.About(this); } @@ -3608,18 +3272,14 @@ private Integer getDirectoryColumns(String dir) { } return columns; } - + private void hideLayout(int id) { - View v = (View) findViewById(id); - LayoutParams p = (LayoutParams) v.getLayoutParams(); - p.height = 0; - p.width = 0; - v.setLayoutParams(p); + View v = findViewById(id); + v.setVisibility(View.GONE); } @SuppressWarnings("unchecked") - private List> sortFiles( - List> array, String field, boolean order) { + private List> sortFiles(List> array, String field, boolean order) { class ArrayComparator implements Comparator { String key; @@ -3638,8 +3298,9 @@ public int compare(Object lhs, Object rhs) { Arrays.sort(arr, comparator); List> ret = new ArrayList>(); if (order) { - for (int i = 0; i < arr.length; i++) - ret.add((HashMap) arr[i]); + for (Object anArr : arr) { + ret.add((HashMap) anArr); + } } else { for (int i = arr.length - 1; i >=0; i--) ret.add((HashMap) arr[i]); @@ -3649,7 +3310,7 @@ public int compare(Object lhs, Object rhs) { private void menuSort() { final String[] orderList; - if (prefs.getBoolean("showBookTitles", false)) { + if (showBookTitles) { orderList = new String[4]; orderList[0] = getString(R.string.jv_relaunch_sort_file_dir); orderList[1] = getString(R.string.jv_relaunch_sort_file_rev); @@ -3668,16 +3329,15 @@ private void menuSort() { builder.setSingleChoiceItems(orderList, sortMode, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int i) { - SharedPreferences.Editor editor = prefs.edit(); - editor.putInt("sortMode", i); - editor.commit(); + prefsEditor.putInt("sortMode", i); + prefsEditor.commit(); setSortMode(i); dialog.dismiss(); drawDirectory(currentRoot, -1); } }); builder.setNegativeButton( - getResources().getString(R.string.jv_relaunch_cancel), + getResources().getString(R.string.app_cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); @@ -3686,20 +3346,8 @@ public void onClick(DialogInterface dialog, int whichButton) { builder.show(); } - @Override - public void onDestroy() { -// app.dataBase.db.close(); - unregisterReceiver(this.SDCardChangeReceiver); - unregisterReceiver(this.PowerChangeReceiver); - unregisterReceiver(this.WiFiChangeReceiver); - wifiReceiverRegistered = false; - powerReceiverRegistered = false; - mountReceiverRegistered = false; - super.onDestroy(); - } - private void setSortMode(int i) { - if ((!prefs.getBoolean("showBookTitles", false)) && (i > 1)) + if ((!showBookTitles) && (i > 1)) i = 0; if (i == SORT_FILES_ASC) { sortType[0] = "name"; @@ -3718,57 +3366,27 @@ private void setSortMode(int i) { @Override public boolean dispatchKeyEvent(KeyEvent event) { - class RepeatedDownScroll { - public void doIt(int first, int target, int shift) { - final GridView gv = (GridView) findViewById(R.id.gl_list); - int total = gv.getCount(); - int last = gv.getLastVisiblePosition(); - if (total == last + 1) - return; - final int ftarget = target + shift; - gv.clearFocus(); - gv.post(new Runnable() { - public void run() { - gv.setSelection(ftarget); - } - }); - final int ffirst = first; - final int fshift = shift; - gv.postDelayed(new Runnable() { - public void run() { - int nfirst = gv.getFirstVisiblePosition(); - if (nfirst == ffirst) { - RepeatedDownScroll ds = new RepeatedDownScroll(); - ds.doIt(ffirst, ftarget, fshift + 1); - } - } - }, 150); - } - } - - if (DeviceInfo.EINK_SONY) { + if (N2DeviceInfo.EINK_SONY) { int prevCode = 0x0069; int nextCode = 0x006a; - GridView gv = (GridView) findViewById(R.id.gl_list); if ((event.getScanCode() == prevCode) && (event.getAction() == KeyEvent.ACTION_DOWN)) { - int first = gv.getFirstVisiblePosition(); - int visible = gv.getLastVisiblePosition() - - gv.getFirstVisiblePosition() + 1; + int first = gvList.getFirstVisiblePosition(); + int visible = gvList.getLastVisiblePosition() - first + 1; int total = itemsArray.size(); first -= visible; if (first < 0) first = 0; - gv.setSelection(first); + gvList.setSelection(first); // some hack workaround against not scrolling in some cases if (total > 0) { - gv.requestFocusFromTouch(); - gv.setSelection(first); + //gvList.requestFocusFromTouch(); + gvList.setSelection(first); } } if ((event.getScanCode() == nextCode) && (event.getAction() == KeyEvent.ACTION_DOWN)) { - int first = gv.getFirstVisiblePosition(); + int first = gvList.getFirstVisiblePosition(); int total = itemsArray.size(); - int last = gv.getLastVisiblePosition(); + int last = gvList.getLastVisiblePosition(); if (total == last + 1) return true; int target = last + 1; @@ -3781,13 +3399,34 @@ public void run() { return super.dispatchKeyEvent(event); } - private void showBookInfo(String file) { + private void showBookInfo(final String file) { final int COVER_MAX_W = 280; Bitmap cover = null; final Dialog dialog = new Dialog(this, android.R.style.Theme_Light_NoTitleBar_Fullscreen); dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.bookinfo); - + if(file.endsWith(".fb2") || file.endsWith(".fb2.zip")){ + // добавляем кнопку дополнительной информации о файле + Button btnMore = new Button(this); + btnMore.setText(getString(R.string.srt_btn_more_info_book));//"More"); + btnMore.setTextSize(24); + btnMore.setBackgroundResource(R.drawable.main_button); + btnMore.setPadding(20,10,20,10); + LinearLayout ll = (LinearLayout)dialog.findViewById(R.id.linearLayout4); + LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( + LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); + lp.gravity = Gravity.RIGHT; + ll.addView(btnMore, lp); + btnMore.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) { + Intent intent = new Intent(app, ExtendedInfoBook.class); + intent.putExtra("filename", file); + startActivity(intent); + } + }); + + //============================================================================= + } Parser parser = new InstantParser(); EBook eBook = parser.parse(file, true); if (eBook.cover != null) { @@ -3795,7 +3434,7 @@ private void showBookInfo(String file) { eBook.cover.length); if (bitmap != null) { int width = Math.min(COVER_MAX_W, bitmap.getWidth()); - int height = (int) (width * bitmap.getHeight())/bitmap.getWidth(); + int height = (width * bitmap.getHeight())/bitmap.getWidth(); cover = Bitmap.createScaledBitmap(bitmap, width, height, true); } } @@ -3849,52 +3488,87 @@ public void onClick(View v) { dialog.dismiss(); } }); - dialog.show(); } private void showFileInfo(String filename) { - File file = new File(filename); + File file; + String fileName = ""; + String fileSize = ""; + String fileTime = ""; + String filePerm = ""; + String fileOwn = ""; + + final Dialog dialog = new Dialog(this); + dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE); + dialog.setContentView(R.layout.fileinfo); + + LinearLayout llSize = (LinearLayout) dialog.findViewById(R.id.llSize); + + if(filename.startsWith("Dropbox| ")) { + String temp; + DropboxAPI.Entry entries; + temp = filename.substring("Dropbox| ".length()); + try { + entries = mDBApi.metadata(temp, 0, null, true, null); + fileName = entries.fileName(); + fileSize = entries.size; + fileTime = entries.modified; + fileOwn = "Dropbox.com"; + } catch (DropboxException e) { + //emply + } + }else{ + file = new File(filename); + fileName = file.getName(); + fileSize = String.valueOf(file.length()); + fileTime = (new Date(file.lastModified())).toLocaleString(); + + if (file.isDirectory()) + llSize.setVisibility(View.GONE); + + String fileAttr = null; + try { + Runtime rt = Runtime.getRuntime(); + String[] args = {"ls", "-l", filename}; + Process proc = rt.exec(args); + //String str = filename.replace(" ", "\\ "); + BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream())); + int read; + char[] buffer = new char[4096]; + StringBuilder output = new StringBuilder(); + while ((read = br.read(buffer)) > 0) { + output.append(buffer, 0, read); + } + br.close(); + proc.waitFor(); + fileAttr = output.toString(); + } catch (Throwable t) { + //emply + } + fileAttr = fileAttr.replaceAll(" +", " "); + int iPerm = fileAttr.indexOf(" "); + int iOwner = fileAttr.indexOf(" ", iPerm+1); + int iGroup = fileAttr.indexOf(" ", iOwner+1); + filePerm = fileAttr.substring(1, iPerm); + fileOwn = fileAttr.substring(iPerm + 1, iOwner)+ "/" + fileAttr.substring(iOwner + 1, iGroup); + } + + - final Dialog dialog = new Dialog(this); - dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE); -// dialog.setTitle(getString(R.string.jv_relaunch_fileinfo_title)); - dialog.setContentView(R.layout.fileinfo); - LinearLayout llSize = (LinearLayout) dialog.findViewById(R.id.llSize); - if (file.isDirectory()) - llSize.setVisibility(View.GONE); TextView tv = (TextView) dialog.findViewById(R.id.tvName); - tv.setText(file.getName()); + tv.setText(fileName); tv = (TextView) dialog.findViewById(R.id.tvSize); - tv.setText(file.length() + " bytes"); + tv.setText(fileSize + " bytes"); tv = (TextView) dialog.findViewById(R.id.tvTime); - tv.setText((new Date(file.lastModified())).toLocaleString()); - String fileAttr = null; - try { - Runtime rt = Runtime.getRuntime(); - String[] args = {"ls", "-l", filename}; - Process proc = rt.exec(args); - String str = filename.replace(" ", "\\ "); - BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream())); - int read; - char[] buffer = new char[4096]; - StringBuffer output = new StringBuffer(); - while ((read = br.read(buffer)) > 0) { - output.append(buffer, 0, read); - } - br.close(); - proc.waitFor(); - fileAttr = output.toString(); - } catch (Throwable t) { - } - fileAttr = fileAttr.replaceAll(" +", " "); - int iPerm = fileAttr.indexOf(" "); - int iOwner = fileAttr.indexOf(" ", iPerm+1); - int iGroup = fileAttr.indexOf(" ", iOwner+1); + tv.setText(fileTime); + + + tv = (TextView) dialog.findViewById(R.id.tvPerm); - tv.setText(fileAttr.substring(1, iPerm)); + tv.setText(filePerm); tv = (TextView) dialog.findViewById(R.id.tvOwner); - tv.setText(fileAttr.substring(iPerm + 1, iOwner)+ "/" + fileAttr.substring(iOwner + 1, iGroup)); + tv.setText(fileOwn); Button btn = (Button) dialog.findViewById(R.id.btnOk); btn.setOnClickListener(new View.OnClickListener() { @@ -3906,5 +3580,813 @@ public void onClick(View v) { dialog.show(); } - + private void copyFileToLocalDirDropbox(String dirname, String filename) { + String src, str_f, locDirDrop; + + locDirDrop = prefs.getString("LocalfolderDropbox", "none"); + if(!"none".equals(locDirDrop)){ + str_f = locDirDrop.trim(); + if(str_f.lastIndexOf("/") == str_f.length()-1) { + locDirDrop = str_f.substring(0, str_f.length()-1); + }else{ + locDirDrop = str_f; + } + String dst = locDirDrop + "/" + filename; + src = dirname + "/" + filename; + File toDir = new File(src); + if(toDir.isDirectory()){ + app.copyDirOrFile(src, dst, false); + }else{ + app.copyDirOrFile(src, dst, false); + } + } + } + + + private void copyFileToDropbox(final String dirname, String filename) { + // получаем имя папки Dropbox, куда будем закидывать выделенное + String str_f; + String DBPath; + final Activity activity = this; + DBPath = prefs.getString("DropBoxfolder", "none"); + str_f = DBPath.trim(); + if(str_f.lastIndexOf("/") == str_f.length()-1){ + DBPath = str_f.substring(0, str_f.length()-1); + }else{ + DBPath = str_f; + } + //--------------------------------------------------------------------- + // проверяем наличие подключения к сервису Dropbox + if(mDBApi == null){ + if(!connectDropbox()){ + app.showToast(getString(R.string.srt_dbactivity_err_con_dropbox));//" Нет подключения к серверу"); + return; // нет подключения к сервису + } + } + //------------------------------------------------------------------------ + // проверяем наличие на сервере и если такое уже есть - выдаем диалог с вариантами + int checkRez = checkFileDB(DBPath, filename, mDBApi); + if(checkRez == 1){ + + // выбор действия + String[] list_url = new String[2]; + final String[] tempNameFile = {filename}; + final AlertDialog.Builder builder = new AlertDialog.Builder(activity); + builder.setTitle(getString(R.string.jv_relaunch_activity_not_found_text1));//"На сервере уже есть такой файл.");//"Скачать файлы"); + list_url[0] = getString(R.string.jv_relaunch_rename);//"Переименовать"; + list_url[1] = getString(R.string.jv_relaunch_rewrite);//"Заменить"; + final String finalDBPath = DBPath; + builder.setItems(list_url, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int item) { + + if(item == 0){ + final AlertDialog.Builder builder2 = new AlertDialog.Builder(activity); + builder2.setTitle(getString(R.string.jv_relaunch_rename_title));//"Введите новое имя"); + final EditText input = new EditText(activity); + builder2.setView(input); + builder2.setCancelable(true); + builder2.setNegativeButton(getResources().getString(R.string.app_cancel), new DialogInterface.OnClickListener() { // Кнопка Отмена + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); // Отпускает диалоговое окно + } + }); + builder2.setPositiveButton(getResources().getString(R.string.app_ok), new DialogInterface.OnClickListener() { // Кнопка Отмена + @Override + public void onClick(DialogInterface dialog, int which) { + String newName = String.valueOf(input.getText()).trim(); + + if (newName.length() > 0) { + uploadFilesOrDir(dirname, tempNameFile[0], finalDBPath, mDBApi, newName); + }else{ + uploadFilesOrDir(dirname, tempNameFile[0], finalDBPath, mDBApi, ""); + } + dialog.dismiss(); // Отпускает диалоговое окно + } + }); + builder2.show(); + } + if(item == 1){ + try { + mDBApi.delete(finalDBPath + "/" +tempNameFile[0]); + } catch (DropboxException e) { + app.showToast(getString(R.string.srt_dbactivity_err_upl_dropbox));//"Ошибка при перезаписи."); + } + + uploadFilesOrDir(dirname, tempNameFile[0], finalDBPath, mDBApi, ""); + } + dialog.dismiss(); // Отпускает диалоговое окно + } + }); + builder.setCancelable(true); + builder.setNegativeButton(getResources().getString(R.string.app_cancel), new DialogInterface.OnClickListener() { // Кнопка Отмена + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); // Отпускает диалоговое окно + } + }); + builder.show(); + + }else if(checkRez == 0){ + uploadFilesOrDir(dirname, filename, DBPath, mDBApi, ""); + } + + } + private boolean uploadFilesOrDir(String dirname, String filename, String DBPath, DropboxAPI mDBApi, String newfilename) { + //------------------------------------------------------------------------ + // выясняем чего копируем - папку или файл + FileInputStream mFos; + if(newfilename.equals("")){ + newfilename = filename; + } + String src = dirname + "/" + filename; + File toDir = new File(src); + if(toDir.isDirectory()){ + if (!uploadFiles(dirname + "/" + filename, (dirname + "/" ).length(), DBPath, mDBApi)) { + return false; + } + }else{ // копирование одиночного файла + File f1 = new File(src); + try { + mFos = new FileInputStream(src); + } catch (FileNotFoundException e) { + return false; + } + try { + mDBApi.putFile(DBPath + "/" + newfilename, mFos, f1.length(), null, null); + } catch (DropboxException e) { + app.showToast(getString(R.string.srt_dbactivity_err_upl_dropbox));//" Ошибка при записи файла на сервер"); + return false; + } + } + //----------------------------------------------------------------------- + app.showToast(getString(R.string.jv_prefs_rsr_ok_text));//" Успешно выполнено"); + return true; + } + private boolean uploadFiles(String Path, int start_pos_path, String DBPath, DropboxAPI mDBApi) { + String[] strDirList = (new File(Path)).list(); + String strPath = Path.substring(start_pos_path); + FileInputStream mFos; + + for (String aStrDirList : strDirList) { + + File f1 = new File(Path+ File.separator + aStrDirList); + if (f1.isFile()) { + try { + mFos = new FileInputStream(f1); + } catch (FileNotFoundException e) { + app.showToast(getString(R.string.jv_editor_openerr_text1));//" Ошибка при открытии файла"); + return false; + } + try { + mDBApi.putFile(DBPath + "/" + strPath + File.separator + f1.getName(), mFos, f1.length(), null, null); + } catch (DropboxException e) { + app.showToast(getString(R.string.srt_dbactivity_err_upl_dropbox));//" Ошибка при записи на сервер"); + return false; + } + } else { + if (!uploadFiles(Path + File.separator + aStrDirList , start_pos_path, DBPath, mDBApi)) { + return false; + } + } + } + return true; + } + + private int checkFileDB(String PathDB, String filenameOrDirname, DropboxAPI mDBApi){ + DropboxAPI.Entry entries; + try { + entries = mDBApi.metadata(PathDB, 0, null, true, null); + } catch (DropboxException e) { + return -1; + } + for (DropboxAPI.Entry e : entries.contents) { + if (!e.isDeleted) { + if(e.fileName().equals(filenameOrDirname)){ + return 1; + } + } + } + return 0; + } + + private void tapButton(String buttonName) { + // battery button + prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); + String putSettingButton = prefs.getString(buttonName, "NOTHING"); + // если действие не назначено + // проверяеим стандартные кнопки + if(putSettingButton.equals("NOTHING")){ + if(buttonName.equals("homeButtonST")){ + putSettingButton = "HOMEN"; + }else if(buttonName.equals("homeButtonDT")){ + putSettingButton = "HOMEMENU"; + }else if(buttonName.equals("homeButtonLT")){ + putSettingButton = "HOMESCREEN"; + }else if(buttonName.equals("lruButtonST")){ + putSettingButton = "LRUSCREEN"; + }else if(buttonName.equals("favButtonST")){ + putSettingButton = "FAVDOCSCREEN"; + }else if(buttonName.equals("settingsButtonST") || buttonName.equals("settingsButtonDT") || buttonName.equals("settingsButtonLT")){ + putSettingButton = "SETTINGS"; + }else if(buttonName.equals("advancedButtonST")){ + putSettingButton = "ADVANCED"; + }else if(buttonName.equals("memButtonST")){ + putSettingButton = "APPMANAGER"; + }else if(buttonName.equals("batButtonST")){ + putSettingButton = "SWITCHWIFI"; + }else if(buttonName.equals("appFavButtonST")){ + putSettingButton = "FAVAPP"; + }else if(buttonName.equals("appAllButtonST")){ + putSettingButton = "ALLAPP"; + }else if(buttonName.equals("appLastButtonST")){ + putSettingButton = "LASTAPP"; + }else if(buttonName.equals("searchButtonST")){ + putSettingButton = "SEARCH"; + } + } + if(putSettingButton.equals("NOTHING")){ + return; + } + if (putSettingButton.equals("LOCK")) { + actionLock(); + } else if (putSettingButton.equals("POWEROFF")) { + actionPowerOff(); + } else if (putSettingButton.equals("SWITCHWIFI")) { + actionSwitchWiFi(); + } else if (putSettingButton.equals("RUN")) { + if(prefs.getString(buttonName + "app", "%%") != null && prefs.getString(buttonName + "app", "%%").length() > 0) { + actionRun(prefs.getString(buttonName + "app", "%%")); + } + } else if (putSettingButton.equals("DROPBOX")) { + screenDropbox(); + } else if (putSettingButton.equals("OPDS")) { + screenOPDS(); + } else if (putSettingButton.equals("BATTERY")) { + Intent intent = new Intent(Intent.ACTION_POWER_USAGE_SUMMARY); + startActivity(intent); + } else if (putSettingButton.equals("APPMANAGER")) { + Intent intent = new Intent(ReLaunch.this, TaskManager.class); + startActivity(intent); + } else if (putSettingButton.equals("FAVDOCN")) { + ListActions la = new ListActions(app, ReLaunch.this); + la.runItem("favorites", Integer.parseInt(prefs.getString(buttonName + "fav", "1")) - 1); + } else if (putSettingButton.equals("FAVDOCMENU")) { + ListActions la = new ListActions(app, ReLaunch.this); + la.showMenu("favorites"); + } else if (putSettingButton.equals("FAVDOCSCREEN")) { + menuFavorites(); + } else if (putSettingButton.equals("LRUN")) { + ListActions la = new ListActions(app,ReLaunch.this); + la.runItem("lastOpened",Integer.parseInt(prefs.getString(buttonName + "lru", "1")) - 1); + } else if (putSettingButton.equals("LRUMENU")) { + ListActions la = new ListActions(app,ReLaunch.this); + la.showMenu("lastOpened"); + } else if (putSettingButton.equals("LRUSCREEN")) { + menuLastopened(); + } else if (putSettingButton.equals("HOMEN")) { + openHome(Integer.parseInt(prefs.getString(buttonName + "home", "1"))); + } else if (putSettingButton.equals("HOMEMENU")) { + menuHome(); + } else if (putSettingButton.equals("HOMESCREEN")) { + screenHome(); + } else if (putSettingButton.equals("SETTINGS")) { + menuSettings(); + } else if (putSettingButton.equals("ADVANCED")) { + Intent i = new Intent(ReLaunch.this, Advanced.class); + startActivity(i); + } else if (putSettingButton.equals("FAVAPP")) { + Intent intent = new Intent(ReLaunch.this, AllApplications.class); + intent.putExtra("list", "app_favorites"); + intent.putExtra("title", getResources().getString(R.string.jv_relaunch_fav_a)); + startActivity(intent); + } else if (putSettingButton.equals("ALLAPP")) { + Intent intent = new Intent(ReLaunch.this,AllApplications.class); + intent.putExtra("list", "app_all"); + // "All applications" + intent.putExtra("title",getResources().getString(R.string.jv_relaunch_all_a)); + startActivity(intent); + } else if (putSettingButton.equals("LASTAPP")) { + Intent intent = new Intent(ReLaunch.this,AllApplications.class); + intent.putExtra("list", "app_last"); + // "Last recently used applications" + intent.putExtra("title",getResources().getString(R.string.jv_relaunch_lru_a)); + startActivity(intent); + } else if (putSettingButton.equals("SEARCH")) { + menuSearch(); + } else if (putSettingButton.equals("SYSSETTINGS")) { + startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS)); + } + + } + class ExtsComparator implements Comparator { + public int compare(String a, String b) { + if (a == null && b == null) + return 0; + if (a == null && b != null) + return 1; + if (a != null && b == null) + return -1; + if (a.length() < b.length()) + return 1; + if (a.length() > b.length()) + return -1; + return a.compareTo(b); + } + } + // down scroll button + private class RepeatedDownScroll { + public void doIt(int first, int target, int shift) { + int total = gvList.getCount(); + int last = gvList.getLastVisiblePosition(); + if (total == last + 1) + return; + final int ftarget = target + shift; + gvList.clearFocus(); + gvList.post(new Runnable() { + public void run() { + gvList.setSelection(ftarget); + } + }); + final int ffirst = first; + final int fshift = shift; + gvList.postDelayed(new Runnable() { + public void run() { + int nfirst = gvList.getFirstVisiblePosition(); + if (nfirst == ffirst) { + RepeatedDownScroll ds = new RepeatedDownScroll(); + ds.doIt(ffirst, ftarget, fshift + 1); + } + } + }, 150); + } + } + + private class imageIcon { + String nameIcon; + Bitmap icon; + } + + private void reDraw(){ + // режим обновления экрана + EinkScreen.PrepareController(null, false); + // говорим что данные изменились и нужно перерисовать данные + adapter.notifyDataSetChanged(); + } + + //============= dropbox ========================== + public void checkAppKeySetup() { + // Check to make sure that we have a valid app key + if (APP_KEY.startsWith("CHANGE") || + APP_SECRET.startsWith("CHANGE")) { + app.showToast("You must apply for an app key and secret from developers.dropbox.com, and add them to the DBRoulette ap before trying it."); + finish(); + return; + } + + // Check if the app has set up its manifest properly. + Intent testIntent = new Intent(Intent.ACTION_VIEW); + String scheme = "db-" + APP_KEY; + String uri = scheme + "://" + AuthActivity.AUTH_VERSION + "/test"; + testIntent.setData(Uri.parse(uri)); + PackageManager pm = getPackageManager(); + if (0 == pm.queryIntentActivities(testIntent, 0).size()) { + app.showToast("URL scheme in your app's " + + "manifest is not set up correctly. You should have a " + + "com.dropbox.client2.android.AuthActivity with the " + + "scheme: " + scheme); + finish(); + } + } + public boolean connectDropbox() { + if(haveNetworkConnection(getApplicationContext())){ + checkAppKeySetup(); + AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET); + AndroidAuthSession session; + + String[] stored = getKeys(); + if (stored != null) { + AccessTokenPair accessToken = new AccessTokenPair(stored[0], stored[1]); + session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE, accessToken); + + } else { + session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE); + } + mDBApi = new DropboxAPI(session); + if(stored == null){ + mDBApi.getSession().startAuthentication(this); + } + return true; + }else{ + return false; + } + } + private void storeKeys(String key, String secret) { + // Save the access key for later + SharedPreferences prefs1 = getSharedPreferences(ACCOUNT_PREFS_NAME, 0); + SharedPreferences.Editor edit = prefs1.edit(); + edit.putString(ACCESS_KEY_NAME, key); + edit.putString(ACCESS_SECRET_NAME, secret); + edit.commit(); + } + private String[] getKeys() { + prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0); + String key = prefs.getString(ACCESS_KEY_NAME, null); + String secret = prefs.getString(ACCESS_SECRET_NAME, null); + if (key != null && secret != null) { + String[] ret = new String[2]; + ret[0] = key; + ret[1] = secret; + return ret; + } else { + return null; + } + } + // проверка интернет соединения взята отседова: + // http://stackoverflow.com/questions/7071578/connectivitymanager-to-verify-internet-connection + public static boolean haveNetworkConnection(Context context){ + ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo netInfoMob = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); + NetworkInfo netInfoWifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI); + return ((netInfoMob != null && netInfoMob.isConnectedOrConnecting()) || (netInfoWifi != null) && netInfoWifi.isConnectedOrConnecting()); + } + //---------------------------------------------------------------------------------------------- + public boolean endconnectDropbox() { + if (mDBApi.getSession().authenticationSuccessful()) { + try { + // Required to complete auth, sets the access token on the session + mDBApi.getSession().finishAuthentication(); + + AccessTokenPair tokens = mDBApi.getSession().getAccessTokenPair(); + storeKeys(tokens.key, tokens.secret); + + } catch (IllegalStateException e) { + app.showToast(getString(R.string.srt_dbactivity_err_authent));//"Error connect for Authentication"); + return false; + } + return true; + }else{ + return false; + } + } + private String loadFileDB(String DropBox_Path_File, String nameFile) { + + SharedPreferences prefs2 = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); + String DBLocalPath = prefs2.getString("LocalfolderDropbox", "none"); + String str_f = DBLocalPath.trim(); + + if(str_f.lastIndexOf("/") == str_f.length()-1){ + DBLocalPath = str_f.substring(0, str_f.length()-1); + }else{ + DBLocalPath = str_f; + } + if(nameFile.startsWith("Dropbox| ")){ + nameFile = nameFile.substring("Dropbox| ".length()); + } + File checkDir = new File(DBLocalPath); + if(!checkDir.exists()){ + if(!checkDir.mkdirs()){ + return ""; + } + } + if(!DBdownload(DropBox_Path_File, DBLocalPath)){ + return ""; + } + return (DBLocalPath + File.separator + nameFile); + } + private boolean DBdelete(String fullName) { + DropboxAPI.Entry entries; + + String temp; + temp = fullName.substring("Dropbox| ".length()); + + try { + entries = mDBApi.metadata(temp, 0, null, true, null);// может быть ошибка при получении коллекции + if(entries.isDir){ + mDBApi.delete(entries.path + "/"); + }else { + mDBApi.delete(entries.path); + } + } catch (DropboxException e) { + return false; + } + + return true; + } + private boolean DBdownload(String fullName, String localPath) { + DropboxAPI.Entry entries; + FileOutputStream mFos; + File file; + String temp; + temp = fullName.substring("Dropbox| ".length()); + + try { + entries = mDBApi.metadata(temp, 0, null, true, null); + } catch (DropboxException e) { + return false; + } + if(entries.isDir){ + file=new File(localPath + File.separator + entries.fileName()); + if (!file.exists()) { + if(!file.mkdirs()){ + return false; + } + } + localPath +=File.separator + entries.fileName(); + for (DropboxAPI.Entry e : entries.contents) { + if (!e.isDeleted) { + file=new File(localPath + File.separator + e.fileName()); + if(e.isDir){ + if (!file.exists()) { + if(!file.mkdirs()){ + return false; + } + } + if(!DBdownload(fullName + File.separator + e.fileName(), localPath + File.separator + e.fileName())){ + return false; + } + }else{ + try { + mFos = new FileOutputStream(file); + } catch (FileNotFoundException e1) { + return false; + } + try { + mDBApi.getFile(e.path, null, mFos, null); + } catch (DropboxException e1) { + file.delete(); + return false; + } + try { + mFos.close(); + } catch (IOException e1) { + return false; + } + } + } + } + }else{ + file=new File(localPath + File.separator + entries.fileName()); + try { + mFos = new FileOutputStream(file); + } catch (FileNotFoundException e1) { + return false; + } + try { + mDBApi.getFile(entries.path, null, mFos, null); + } catch (DropboxException e1) { + file.delete(); + return false; + } + try { + mFos.close(); + } catch (IOException e1) { + return false; + } + } + + return true; + } + private boolean DBupload(String fullNameL, String DBPath) { + File file = new File(fullNameL); + FileInputStream mFos; + String temp; + temp = DBPath.substring("Dropbox| ".length()); + if(file.isDirectory()){ + try { + mDBApi.createFolder(temp + File.separator + file.getName()); + } catch (DropboxException e) { + e.printStackTrace(); + } + String[] strDirList = file.list(); + for (String aStrDirList : strDirList) { + File f1 = new File(aStrDirList); + if (f1.isFile()) { + try { + mFos = new FileInputStream(f1); + } catch (FileNotFoundException e) { + return false; + } + try { + mDBApi.putFile(temp + File.separator + f1.getName(), mFos, f1.length(), null, null); + } catch (DropboxException e) { + return false; + } + } else { + try { + mDBApi.createFolder(temp + File.separator + f1.getName()); + } catch (DropboxException e) { + e.printStackTrace(); + } + if (!DBupload(fullNameL + File.separator + f1.getName(), DBPath + File.separator + f1.getName())) { + return false; + } + } + } + }else{ + try { + mFos = new FileInputStream(file); + } catch (FileNotFoundException e) { + return false; + } + try { + mDBApi.putFile(temp + File.separator + file.getName(), mFos, file.length(), null, null); + } catch (DropboxException e) { + return false; + } + } + return true; + } + private boolean DBmoveORcopy(String DBPathSRC, String DBPathDst, boolean f_copy) { + + String tempSrc, tempDst; + if(DBPathSRC.startsWith("Dropbox| ")){ + tempSrc = DBPathSRC.substring("Dropbox| ".length()); + }else{ + tempSrc = DBPathSRC; + } + if(DBPathDst.startsWith("Dropbox| ")){ + tempDst = DBPathDst.substring("Dropbox| ".length()); + }else{ + tempDst = DBPathDst; + } + + if(f_copy){ + try { + mDBApi.copy(tempSrc, tempDst); + } catch (DropboxException e) { + e.printStackTrace(); + } + }else{ + try { + mDBApi.move(tempSrc, tempDst); + } catch (DropboxException e) { + e.printStackTrace(); + } + } + return true; + } + //============================================== + // ========= load settings ======================== + private void loadStandartIcons() { + // иконки для файлов заранее заносим в массив======================== + imageIcon temp_icon = new imageIcon(); + temp_icon.icon = scaleDrawableById(R.drawable.dir_ok, firstLineIconSizePx); + temp_icon.nameIcon = "dir_ok"; + arrIcon.add(temp_icon); + temp_icon = new imageIcon(); + temp_icon.icon = scaleDrawableById(R.drawable.file_ok, firstLineIconSizePx); + temp_icon.nameIcon = "file_ok"; + arrIcon.add(temp_icon); + temp_icon = new imageIcon(); + temp_icon.icon = scaleDrawableById(R.drawable.file_notok, firstLineIconSizePx); + temp_icon.nameIcon = "file_notok"; + arrIcon.add(temp_icon); + temp_icon = new imageIcon(); + temp_icon.icon = scaleDrawableById(R.drawable.icon, firstLineIconSizePx); + temp_icon.nameIcon = "icon"; + arrIcon.add(temp_icon); + } + private void initGlobalVariable() { + // Global arrays + allowedModels = getResources().getStringArray(R.array.allowed_models); + allowedDevices = getResources().getStringArray(R.array.allowed_devices); + allowedManufacts = getResources().getStringArray(R.array.allowed_manufacturers); + allowedProducts = getResources().getStringArray(R.array.allowed_products); + + // Create global storage with values + app = (ReLaunchApp) getApplicationContext(); + + if (app != null) { + app.FLT_SELECT = getResources().getInteger(R.integer.FLT_SELECT); + app.FLT_STARTS = getResources().getInteger(R.integer.FLT_STARTS); + app.FLT_ENDS = getResources().getInteger(R.integer.FLT_ENDS); + app.FLT_CONTAINS = getResources().getInteger(R.integer.FLT_CONTAINS); + app.FLT_MATCHES = getResources().getInteger(R.integer.FLT_MATCHES); + app.FLT_NEW = getResources().getInteger(R.integer.FLT_NEW); + app.FLT_NEW_AND_READING = getResources().getInteger(R.integer.FLT_NEW_AND_READING); + }else{ + finish(); + } + + } + private void initPrefsVariable() { + prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); + prefsEditor = prefs.edit(); + + // ====== FLSimpleAdapter================================================================== + useFaces = prefs.getBoolean("showNew", true); + firstLineIconSizePx = Integer.parseInt(prefs.getString("firstLineIconSizePx", "48")); // по возможности вынести из адаптера + firstLineFontSizePx = Integer.parseInt(prefs.getString("firstLineFontSizePx", "20")); + secondLineFontSizePx = Integer.parseInt(prefs.getString("secondLineFontSizePx", "16")); + doNotHyph = prefs.getBoolean("doNotHyph", false); + hideKnownExts = prefs.getBoolean("hideKnownExts", false); + showBookTitles = prefs.getBoolean("showBookTitles", false); + rowSeparator = prefs.getBoolean("rowSeparator", false); + disableScrollJump = prefs.getBoolean("disableScrollJump", true); + //================================================================================= + // ====== refreshBottomInfo================================================================== + dateUS = prefs.getBoolean("dateUS", false); + //================================================================================= + // ====== getAutoColsNum================================================================== + columnsAlgIntensity = prefs.getString("columnsAlgIntensity", "70 3:5 7:4 15:3 48:2"); + //================================================================================= + // ====== redrawList================================================================== + filterResults = prefs.getBoolean("filterResults", false); + //================================================================================= + // ====== setUpButton================================================================== + notLeaveStartDir = prefs.getBoolean("notLeaveStartDir", false); + startDir = prefs.getString("startDir", "/sdcard,/media/My Files").split("\\,"); + // ====== drawDirectory================================================================== + showFullDirPath = prefs.getBoolean("showFullDirPath", true); + showHidden = prefs.getBoolean("showHidden", false); + bookTitleFormat = prefs.getString("bookTitleFormat", "%t[\n%a][. %s][-%n]"); + //=================================================================== + // параметры прокрутки экрана + try { + app.scrollStep = Integer.parseInt(prefs.getString("scrollPerc","10")); + app.viewerMax = Integer.parseInt(prefs.getString("viewerMaxSize","1024")); + app.editorMax = Integer.parseInt(prefs.getString("editorMaxSize","256")); + } catch (NumberFormatException e) { + app.scrollStep = 10; + app.viewerMax = 1024; + app.editorMax = 256; + } + if (app.scrollStep < 1){ + app.scrollStep = 1; + } + if (app.scrollStep > 100){ + app.scrollStep = 100; + } + //====================================================================== + showOnePanel = prefs.getBoolean("showOnePanel", true); + showTwoPanel = prefs.getBoolean("showTwoPanel", true); + showThreePanel = prefs.getBoolean("showThreePanel", true); + showFourPanel = prefs.getBoolean("showFourPanel", true); + } + // ================ ============================= + // небольшой модуль для удалени файла или папки + private void delAll(String fullName, String dname, String fname) { + if(fullName.startsWith("Dropbox| ")) { + DBdelete(fullName); + }else{ + app.removeDirAndFile(dname, fname); + } + drawDirectory(currentRoot, currentPosition); + } + //================================================ + private void delSelect (){ + HashMap i; + int j = arrSelItem.size(); + final String arrFullName[] = new String[j]; + final String arrDName[] = new String[j]; + final String arrFName[] = new String[j]; + + String listFiles = ""; + + for(int i1=0; i1 < j; i1++){ + i = itemsArray.get(arrSelItem.get(i1)); + arrFullName[i1] = i.get("fname"); + arrDName[i1] = i.get("dname"); + arrFName[i1] = i.get("name"); + listFiles = listFiles + "\n" + arrFName[i1]; + } + + if (prefs.getBoolean("confirmFileDelete", true)) { + AlertDialog.Builder builder = new AlertDialog.Builder(this); + // "Delete file warning" + builder.setTitle(getResources().getString(R.string.jv_relaunch_del_sel_file_title)); + // "Are you sure to delete file \"" + fname + "\" ?" + builder.setMessage(getResources().getString( + R.string.jv_relaunch_del_sel_file_text1) + + listFiles + + getResources().getString(R.string.jv_relaunch_del_file_text2)); + // "Yes" + builder.setPositiveButton(getResources().getString(R.string.app_yes), + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int whichButton) { + dialog.dismiss(); + for(int h = 0, k = arrFullName.length; h < k; h++) { + delAll(arrFullName[h], arrDName[h], arrFName[h]); + } + } + } + ); + // "No" + builder.setNegativeButton(getResources().getString(R.string.app_no), + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int whichButton) { + dialog.dismiss(); + } + } + ); + builder.show(); + } else { + for(int h = 0, k = arrFullName.length; h < k; h++) { + delAll(arrFullName[h], arrDName[h], arrFName[h]); + } + } + + } } diff --git a/src/com/harasoft/relaunch/ReLaunchApp.java b/src/com/harasoft/relaunch/ReLaunchApp.java index 6bb56fd..0be945f 100644 --- a/src/com/harasoft/relaunch/ReLaunchApp.java +++ b/src/com/harasoft/relaunch/ReLaunchApp.java @@ -1,29 +1,10 @@ package com.harasoft.relaunch; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; -import java.nio.channels.FileChannel; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.regex.Pattern; - import android.app.Activity; import android.app.AlertDialog; import android.app.Application; import android.app.PendingIntent; -import android.content.ComponentName; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.content.SharedPreferences; +import android.content.*; import android.graphics.drawable.Drawable; import android.net.Uri; import android.preference.PreferenceManager; @@ -33,6 +14,10 @@ import android.webkit.WebView; import android.widget.Toast; +import java.io.*; +import java.nio.channels.FileChannel; +import java.util.*; + public class ReLaunchApp extends Application { final String TAG = "ReLaunchApp"; @@ -73,8 +58,7 @@ public class ReLaunchApp extends Application { public int FLT_NEW; public int FLT_NEW_AND_READING; public boolean filters_and; - - public final String BACKUP_DIR = "/sdcard/.relaunch"; + public final String DATA_DIR = "/data/data/com.harasoft.relaunch"; public HashMap history = new HashMap(); @@ -133,18 +117,6 @@ public List readerNames(String file) { } return rc; } - - public List extNames() { - List rc = new ArrayList(); - for (HashMap r : readers) { - for (String key : r.keySet()) { - if (!rc.contains(key)) - rc.add(key); - } - } - return rc; - } - /* * Misc lists management (list is identified by name) * -------------------------------------------------- @@ -166,56 +138,32 @@ public void setList(String name, List l) { public void setDefault(String name) { // Set list default List nl = new ArrayList(); - if (name.equals("lastOpened")) { + /*if (name.equals("lastOpened")) { } else if (name.equals("favorites")) { - } + } */ m.put(name, nl); } - // dump all lists to log (debug) - public void dumpLists() { - /* - * for (String k : m.keySet()) { Log.d(TAG, "LIST: \"" + k + "\""); for - * (String[] n : m.get(k)) Log.d(TAG, " \"" + n[0] + "\"; \"" + n[1] - * + "\""); } - */ - } - - // dump specified lists to log (debug) - public void dumpList(String name) { - /* - * Log.d(TAG, "LIST: \"" + name + "\""); for (String[] n : m.get(name)) - * Log.d(TAG, " \"" + n[0] + "\"; \"" + n[1] + "\""); - */ - } - - // dump lists to log (debug) - public void dumpList(String name, List l) { - /* - * Log.d(TAG, "LIST: \"" + name + "\""); for (String[] n : l) Log.d(TAG, - * " \"" + n[0] + "\"; \"" + n[1] + "\""); - */ - } - // save list public void saveList(String listName) { - SharedPreferences prefs = PreferenceManager - .getDefaultSharedPreferences(getBaseContext()); + SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); if (listName.equals("favorites")) { int favMax = 30; try { favMax = Integer.parseInt(prefs.getString("favSize", "30")); } catch (NumberFormatException e) { + //emply } - this.writeFile("favorites", ReLaunch.FAV_FILE, favMax); + this.writeFile("favorites", ReLaunch.FAV_FILE, favMax, "/"); } if (listName.equals("lastOpened")) { int lruMax = 30; try { lruMax = Integer.parseInt(prefs.getString("lruSize", "30")); } catch (NumberFormatException e) { + //emply } - this.writeFile("lastOpened", ReLaunch.LRU_FILE, lruMax); + this.writeFile("lastOpened", ReLaunch.LRU_FILE, lruMax, "/"); } if (listName.equals("app_last")) { int appLruMax = 30; @@ -223,6 +171,7 @@ public void saveList(String listName) { appLruMax = Integer.parseInt(prefs .getString("appLruSize", "30")); } catch (NumberFormatException e) { + //emply } this.writeFile("app_last", ReLaunch.APP_LRU_FILE, appLruMax, ":"); } @@ -232,9 +181,9 @@ public void saveList(String listName) { appFavMax = Integer.parseInt(prefs .getString("appFavSize", "30")); } catch (NumberFormatException e) { + //emply } - this.writeFile("app_favorites", ReLaunch.APP_FAV_FILE, appFavMax, - ":"); + this.writeFile("app_favorites", ReLaunch.APP_FAV_FILE, appFavMax, ":"); } if (listName.equals("history")) { List h = new ArrayList(); @@ -256,12 +205,8 @@ else if (this.history.get(k) == this.FINISHED) this.writeFile("columns", ReLaunch.COLS_FILE, 0, ":"); } } - // Add to list - public void addToList(String listName, String dr, String fn, - Boolean addToEnd) { - // Log.d(TAG, "addToList(" + listName + ", " + dr + ":" + fn + ", " + - // addToEnd + ")"); + public void addToList(String listName, String dr, String fn, Boolean addToEnd) { addToList_internal(listName, dr, fn, addToEnd); } @@ -269,10 +214,7 @@ public void addToList(String listName, String fullName, Boolean addToEnd) { addToList(listName, fullName, addToEnd, "/"); } - public void addToList(String listName, String fullName, Boolean addToEnd, - String delimiter) { - // Log.d(TAG, "addToList(" + listName + ", " + fullName + ", " + - // addToEnd + ", " + delimiter + ")"); + public void addToList(String listName, String fullName, Boolean addToEnd, String delimiter) { if (delimiter.equals("/")) { if (fullName.endsWith("/" + DIR_TAG)) { @@ -312,16 +254,14 @@ public void addToList(String listName, String fullName, Boolean addToEnd, } - public void addToList_internal(String listName, String dr, String fn, - Boolean addToEnd) { + public void addToList_internal(String listName, String dr, String fn, Boolean addToEnd) { if (!m.containsKey(listName)) m.put(listName, new ArrayList()); List resultList = m.get(listName); String[] entry = new String[] { dr, fn }; for (int i = 0; i < resultList.size(); i++) { - if (resultList.get(i)[0].equals(dr) - && resultList.get(i)[1].equals(fn)) { + if (resultList.get(i)[0].equals(dr) && resultList.get(i)[1].equals(fn)) { resultList.remove(i); break; } @@ -331,70 +271,55 @@ public void addToList_internal(String listName, String dr, String fn, else resultList.add(0, entry); } - // Remove from list public void removeFromList(String listName, String dr, String fn) { removeFromList_internal(listName, dr, fn); } - public void removeFromList(String listName, String fullName) { - File f = new File(fullName); - if (!f.exists()) - return; - removeFromList_internal(listName, f.getParent(), f.getName()); - - } - public void removeFromList_internal(String listName, String dr, String fn) { if (!m.containsKey(listName)) return; List resultList = m.get(listName); for (int i = 0; i < resultList.size(); i++) { - if (resultList.get(i)[0].equals(dr) - && resultList.get(i)[1].equals(fn)) { + if (resultList.get(i)[0].equals(dr) && resultList.get(i)[1].equals(fn)) { resultList.remove(i); saveList(listName); return; } } } - // If list contains public boolean contains(String listName, String dr, String fn) { if (!m.containsKey(listName)) return false; List resultList = m.get(listName); - for (int i = 0; i < resultList.size(); i++) { - if (resultList.get(i)[0].equals(dr) - && resultList.get(i)[1].equals(fn)) - return true; - } + for (String[] aResultList : resultList) { + if (aResultList[0].equals(dr) && aResultList[1].equals(fn)) + return true; + } return false; } // Read misc. lists - public boolean readFile(String listName, String fileName) { - return readFile(listName, fileName, "/"); - } - public boolean readFile(String listName, String fileName, String delimiter) { FileInputStream fis = null; try { fis = openFileInput(fileName); } catch (FileNotFoundException e) { + //emply } if (fis == null) return false; else { - InputStreamReader insr = null; + InputStreamReader insr; try { insr = new InputStreamReader(fis, "utf8"); } catch (UnsupportedEncodingException e) { return false; } BufferedReader bufr = new BufferedReader(insr, FileBufferSize); - String l = new String(); + String l; while (true) { try { l = bufr.readLine(); @@ -412,23 +337,19 @@ public boolean readFile(String listName, String fileName, String delimiter) { insr.close(); fis.close(); } catch (IOException e) { + //emply } } return true; } // Save to file miscellaneous lists - public void writeFile(String listName, String fileName, int maxEntries) { - writeFile(listName, fileName, maxEntries, "/"); - } - - public void writeFile(String listName, String fileName, int maxEntries, - String delimiter) { + public void writeFile(String listName, String fileName, int maxEntries, String delimiter) { if (!m.containsKey(listName)) return; List resultList = m.get(listName); - FileOutputStream fos = null; + FileOutputStream fos; try { fos = openFileOutput(fileName, Context.MODE_PRIVATE); } catch (FileNotFoundException e) { @@ -437,25 +358,21 @@ public void writeFile(String listName, String fileName, int maxEntries, for (int i = 0; i < resultList.size(); i++) { if (maxEntries != 0 && i >= maxEntries) break; - String line = resultList.get(i)[0] + delimiter - + resultList.get(i)[1] + "\n"; + String line = resultList.get(i)[0] + delimiter + resultList.get(i)[1] + "\n"; try { fos.write(line.getBytes()); } catch (IOException e) { + //emply } } try { fos.close(); } catch (IOException e) { + //emply } } // Remove file - public boolean removeFile(String fullname) { - File f = new File(fullname); - return removeFile(f.getParent(), f.getName()); - } - public boolean removeFile(String dr, String fn) { boolean rc = false; String fullName = dr + "/" + fn; @@ -471,17 +388,19 @@ public boolean removeFile(String dr, String fn) { try { rc = f.delete(); } catch (SecurityException e) { + //emply } } return rc; } - - // Remove directory public boolean removeDirectory(String dr, String fn) { boolean rc = false; String dname = dr + "/" + fn; File d = new File(dname); File[] allEntries = d.listFiles(); + if(allEntries == null){ + return false; + } for (File f : allEntries) { if (f.isDirectory()) { if (!removeDirectory(dname, f.getName())) @@ -494,34 +413,81 @@ public boolean removeDirectory(String dr, String fn) { try { rc = d.delete(); } catch (SecurityException e) { + //emply } return rc; } + public boolean removeDirAndFile(String dir, String file) { + String dname = dir + "/" + file; + File d = new File(dname); + if (d.isDirectory()) { + if (!removeDirectory(dir, file)) + return false; + } else { + if (!removeFile(dir, file)) + return false; + } + return true; + } //Copy file src to dst public boolean copyFile(String from, String to, boolean rewrite) { File srcFile = new File(from); File dstFile = new File(to); - FileChannel src = null; - FileChannel dst = null; - boolean ret; -// if ((!srcFile.canRead()) || (!dstFile.canWrite()) || (dstFile.exists())) + FileChannel src; + FileChannel dst; + if ((!srcFile.canRead()) || ((dstFile.exists()) && (!rewrite))) return false; try { - dstFile.createNewFile(); - src = new FileInputStream(srcFile).getChannel(); - dst = new FileOutputStream(dstFile).getChannel(); - dst.transferFrom(src, 0, src.size()); - src.close(); - dst.close(); - ret = true; + if(dstFile.createNewFile()) { + src = new FileInputStream(srcFile).getChannel(); + dst = new FileOutputStream(dstFile).getChannel(); + dst.transferFrom(src, 0, src.size()); + src.close(); + dst.close(); + } } catch (IOException e) { - ret = false; + return false; } - return ret; + return true; } - + public boolean copyDir(String from, String to) { + File toDir = new File(to); + String[] strDirList = (new File(from)).list(); + + if(!toDir.exists()){ + if(!toDir.mkdirs()){ + return false; + } + } + for (String aStrDirList1 : strDirList) { + File f1 = new File(from +"/" + aStrDirList1); + if (f1.isFile()) { + if (!copyFile(from +"/" + aStrDirList1, to +"/" + aStrDirList1, false)){ + return false; + } + } else { + if (!copyDir(from +"/" + aStrDirList1, to + "/" +aStrDirList1)){ + return false; + } + } + } + return true; + } + public boolean copyDirOrFile(String from, String to, boolean rewrite) { + File source = new File(from); + if (source.isFile()) { + if (!copyFile(from, to, rewrite)){ + return false; + } + } else { + if (!copyDir(from, to)){ + return false; + } + } + return true; + } //Move file src to dst public boolean moveFile(String from, String to) { boolean ret = false; @@ -530,25 +496,29 @@ public boolean moveFile(String from, String to) { File dst = new File(to); ret = src.renameTo(dst); } else { - if (copyFile(from, to, false)) - ret = removeFile(from); + if (copyFile(from, to, false)) { + File f = new File(from); + ret = removeFile(f.getParent(), f.getName()); + } } return ret; } - + // public boolean createDir(String dst) { File dir = new File(dst); - return dir.mkdir(); + return dir.mkdirs(); } // common utility - get intent by label, null if not found public Intent getIntentByLabel(String label) { String[] labelp = label.split("\\%"); - Intent i = new Intent(); - i.setComponent(new ComponentName(labelp[0], labelp[1])); - i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK - | Intent.FLAG_ACTIVITY_CLEAR_TOP); - return i; + if(labelp.length > 1 && labelp[0] != null && labelp[1] != null) { + Intent i = new Intent(); + i.setComponent(new ComponentName(labelp[0], labelp[1])); + i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); + return i; + } + return null; } // common utility - return intent to launch reader by reader name and full @@ -558,8 +528,7 @@ public Intent launchReader(String name, String file) { if (re.length == 2 && re[0].equals("Intent")) { Intent i = new Intent(); i.setAction(Intent.ACTION_VIEW); - i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK - | Intent.FLAG_ACTIVITY_CLEAR_TOP); + i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); i.setDataAndType(Uri.parse("file:///" + Uri.encode(file.substring(1))), re[1]); addToList("lastOpened", file, false); saveList("lastOpened"); @@ -572,19 +541,15 @@ public Intent launchReader(String name, String file) { Intent i = getIntentByLabel(name); if (i == null) // "Activity \"" + name + "\" not found!" - Toast.makeText( - this, - getResources().getString(R.string.jv_rla_activity) + Toast.makeText(this,getResources().getString(R.string.jv_rla_activity) + " \"" + name + "\" " - + getResources().getString( - R.string.jv_rla_not_found), + + getResources().getString(R.string.jv_rla_not_found), Toast.LENGTH_SHORT).show(); else { i.setAction(Intent.ACTION_VIEW); - i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK - | Intent.FLAG_ACTIVITY_CLEAR_TOP); + i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); // i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - ALREADY DONE! in // getIntentByLabel i.setData(Uri.parse("file:///" + Uri.encode(file.substring(1)))); @@ -600,24 +565,8 @@ public Intent launchReader(String name, String file) { return null; } - // compare by second element of String[] - public class o1Comparator implements java.util.Comparator { - public int compare(String[] o1, String[] o2) { - int rc = o1[1].compareTo(o2[1]); - if (rc == 0) - return o1[0].compareTo(o2[0]); - else - return rc; - } - } - - public o1Comparator getO1Comparator() { - return new o1Comparator(); - } - // FILTER - public boolean filterFile1(String dname, String fname, Integer method, - String value) { + public boolean filterFile1(String dname, String fname, Integer method, String value) { if (method == FLT_STARTS) return fname.startsWith(value); else if (method == FLT_ENDS) @@ -646,6 +595,7 @@ public boolean filterFile(String dname, String fname) { try { filtMethod = Integer.parseInt(f[0]); } catch (NumberFormatException e) { + //emply } if (filters_and) { // AND all filters @@ -657,7 +607,7 @@ public boolean filterFile(String dname, String fname) { return true; } } - return filters_and ? true : false; + return filters_and; } else return true; } @@ -674,10 +624,8 @@ public boolean specialAction(Activity a, String s) { if (s.endsWith(".apk")) { // Install application Intent intent = new Intent(Intent.ACTION_VIEW); - intent.setDataAndType(Uri.parse("file://" + s), - "application/vnd.android.package-archive"); - intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK - | Intent.FLAG_ACTIVITY_CLEAR_TOP); + intent.setDataAndType(Uri.parse("file://" + s), "application/vnd.android.package-archive"); + intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); a.startActivity(intent); return true; } @@ -695,6 +643,7 @@ public void About(final Activity a) { try { vers = getPackageManager().getPackageInfo(getPackageName(), 0).versionName; } catch (Exception e) { + //emply } AlertDialog.Builder builder = new AlertDialog.Builder(a); WebView wv = new WebView(a); @@ -710,7 +659,7 @@ public void About(final Activity a) { wv.loadDataWithBaseURL(null, str, "text/html", "utf-8", null); builder.setView(wv); // "Ok" - builder.setPositiveButton(getResources().getString(R.string.jv_rla_ok), + builder.setPositiveButton(getResources().getString(R.string.app_ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); @@ -721,24 +670,20 @@ public void onClick(DialogInterface dialog, int whichButton) { getResources().getString(R.string.jv_rla_see_changelog), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { - AlertDialog.Builder builder1 = new AlertDialog.Builder( - a); + AlertDialog.Builder builder1 = new AlertDialog.Builder(a); WebView wv = new WebView(a); wv.loadDataWithBaseURL( null, getResources().getString(R.string.about_help) - + getResources().getString( - R.string.about_appr) - + getResources().getString( - R.string.whats_new), + + getResources().getString(R.string.about_appr) + + getResources().getString(R.string.whats_new), "text/html", "utf-8", null); // "What's new" - builder1.setTitle(getResources().getString( - R.string.jv_rla_whats_new_title)); + builder1.setTitle(getResources().getString(R.string.jv_rla_whats_new_title)); builder1.setView(wv); // "Ok" builder1.setPositiveButton( - getResources().getString(R.string.jv_rla_ok), + getResources().getString(R.string.app_ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -754,12 +699,11 @@ public void onClick(DialogInterface dialog, public void setFullScreenIfNecessary(Activity a) { if (fullScreen) { a.requestWindowFeature(Window.FEATURE_NO_TITLE); - a.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, - WindowManager.LayoutParams.FLAG_FULLSCREEN); + a.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } } - public void generalOnResume(String name, Activity a) { + public void generalOnResume(String name) { Log.d(TAG, "--- onResume(" + name + ")"); } @@ -787,24 +731,17 @@ public boolean copyPrefs(String from, String to) { } String src = fromDir.getAbsolutePath() + "/shared_prefs/com.harasoft.relaunch_preferences.xml"; String dst = toDir.getAbsolutePath() + "/shared_prefs/com.harasoft.relaunch_preferences.xml"; -// boolean ret = copyFile(src, dst, true); - if (!copyFile(src, dst, true)) - return false; - return true; - } + return copyFile(src, dst, true); + } public boolean isStartDir(String dir) { - SharedPreferences prefs = PreferenceManager - .getDefaultSharedPreferences(getBaseContext()); + SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); String startDirs = prefs.getString("startDir", "/sdcard,/media/My Files"); - if (startDirs.contains(dir)) - return true; - return false; - } + return startDirs.contains(dir); + } public void setStartDir(String dir) { - SharedPreferences prefs = PreferenceManager - .getDefaultSharedPreferences(getBaseContext()); + SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); SharedPreferences.Editor editor = prefs.edit(); editor.putString("startDir", dir); editor.putBoolean("showAddStartDir", false); @@ -812,12 +749,52 @@ public void setStartDir(String dir) { } public void addStartDir(String dir) { - SharedPreferences prefs = PreferenceManager - .getDefaultSharedPreferences(getBaseContext()); + SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); SharedPreferences.Editor editor = prefs.edit(); String oldStart = prefs.getString("startDir", "/sdcard,/media/My Files"); editor.putString("startDir", oldStart + "," + dir); editor.commit(); } - + public void showToast(String msg) { + Toast error = Toast.makeText(this, msg, Toast.LENGTH_LONG); + error.show(); + } + // автоматический подбор числа колонок + public int getAutoColsNum(List> itemsArray, String polName, String columnsAlgIntensity) { + // implementation - via percentiles len + int auto_cols_num = 1; + ArrayList tmp = new ArrayList(); + + if (itemsArray.size() > 0) { + int factor ; + for (HashMap anItemsArray : itemsArray) { + tmp.add(anItemsArray.get(polName).length()); + } + String[] spat = columnsAlgIntensity.split("[\\s\\:]+"); + int quantile = Integer.parseInt(spat[0]); + factor = Percentile(tmp, quantile); + for (int i = 1; i < spat.length; i = i + 2) { + try { + double fval = Double.parseDouble(spat[i]); + int cval = Integer.parseInt(spat[i + 1]); + if (factor <= fval) { + auto_cols_num = cval; + break; + } + } catch (Exception e) { + // emply + } + } + } + if (auto_cols_num > itemsArray.size()) + auto_cols_num = itemsArray.size(); + return auto_cols_num; + } + private int Percentile(ArrayList values, int Quantile) + // not fully "mathematical proof", but not too difficult and working + { + Collections.sort(values); + int index = (values.size() * Quantile) / 100; + return values.get(index); + } } diff --git a/src/com/harasoft/relaunch/ResultsActivity.java b/src/com/harasoft/relaunch/ResultsActivity.java index 51d314a..c1790b1 100644 --- a/src/com/harasoft/relaunch/ResultsActivity.java +++ b/src/com/harasoft/relaunch/ResultsActivity.java @@ -1,25 +1,11 @@ package com.harasoft.relaunch; -import java.io.File; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.regex.Pattern; - -import ebook.EBook; -import ebook.parser.InstantParser; -import ebook.parser.Parser; - import android.app.Activity; import android.app.AlertDialog; -import android.content.ActivityNotFoundException; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.content.SharedPreferences; +import android.content.*; +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Typeface; @@ -30,33 +16,22 @@ import android.preference.PreferenceManager; import android.text.SpannableString; import android.text.style.StyleSpan; + +import android.util.Log; import android.util.TypedValue; -import android.view.ContextMenu; -import android.view.GestureDetector; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.MenuItem; -import android.view.MotionEvent; -import android.view.View; -import android.view.View.MeasureSpec; -import android.view.View.OnTouchListener; -import android.view.ViewGroup; +import android.view.*; import android.view.ContextMenu.ContextMenuInfo; import android.view.GestureDetector.SimpleOnGestureListener; -import android.widget.AbsListView; -import android.widget.AdapterView; -import android.widget.ArrayAdapter; -import android.widget.Button; -import android.widget.GridView; -import android.widget.ImageButton; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.ListView; -import android.widget.TextView; -import android.widget.Toast; +import android.view.View.MeasureSpec; +import android.view.View.OnTouchListener; +import android.widget.*; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; +import ebook.EBook; + +import java.io.File; +import java.util.*; +import java.util.regex.Pattern; public class ResultsActivity extends Activity { final String TAG = "Results"; @@ -69,53 +44,43 @@ public class ResultsActivity extends Activity { final int CNTXT_MENU_MARK_READING = 7; final int CNTXT_MENU_MARK_FORGET = 8; final int CNTXT_MENU_RMDIR = 9; + final int CNTXT_MENU_OPEN_DIR = 10; + final int CNTXT_MENU_ADD_OPDS = 11; + final int CNTXT_MENU_EDIT_OPDS = 12; + final int CNTXT_MENU_DEL_OPDS = 13; + final int CNTXT_MENU_CLEAN_OPDS = 14; ReLaunchApp app; HashMap icons; String listName; + static String listNameSecond; String title; Boolean rereadOnStart = true; SharedPreferences prefs; FLSimpleAdapter adapter; - ListView lv; - Integer currentColsNum = -1; + Integer currentColsNum = -1; List> itemsArray = new ArrayList>(); Integer currentPosition = -1; boolean addSView = true; boolean oldHome; Pattern purgeBracketsPattern; - - - private void setEinkController() { - if (prefs != null) { - Integer einkUpdateMode = 1; - try { - einkUpdateMode = Integer.parseInt(prefs.getString( - "einkUpdateMode", "1")); - } catch (Exception e) { - einkUpdateMode = 1; - } - if (einkUpdateMode < -1 || einkUpdateMode > 2) - einkUpdateMode = 1; - if (einkUpdateMode >= 0) { - EinkScreen.UpdateMode = einkUpdateMode; - - Integer einkUpdateInterval = 10; - try { - einkUpdateInterval = Integer.parseInt(prefs.getString( - "einkUpdateInterval", "10")); - } catch (Exception e) { - einkUpdateInterval = 10; - } - if (einkUpdateInterval < 0 || einkUpdateInterval > 100) - einkUpdateInterval = 10; - EinkScreen.UpdateModeInterval = einkUpdateInterval; - - EinkScreen.PrepareController(null, false); - } - } - } - - static class ViewHolder { + ArrayList arrIcon = new ArrayList(); + DBHelper dbHelper; + public static SQLiteDatabase db; + int total; + // переменные из настроек=============================================== + static boolean hideKnownExts = false; + static int firstLineFontSizePx = 20; + static int secondLineFontSizePx = 16; + static boolean showNew = false; + static boolean hideKnownDirs = false; + static int firstLineIconSizePx = 48; + static boolean filterResults = false; + static boolean showBookTitles = false; + + static LayoutInflater vi; + + + static class ViewHolder { TextView tv1; TextView tv2; LinearLayout tvHolder; @@ -124,13 +89,11 @@ static class ViewHolder { private Bitmap scaleDrawableById(int id, int size) { return Bitmap.createScaledBitmap( - BitmapFactory.decodeResource(getResources(), id), size, size, - true); + BitmapFactory.decodeResource(getResources(), id), size, size,true); } private Bitmap scaleDrawable(Drawable d, int size) { - return Bitmap.createScaledBitmap(((BitmapDrawable) d).getBitmap(), - size, size, true); + return Bitmap.createScaledBitmap(((BitmapDrawable) d).getBitmap(),size, size, true); } class FLSimpleAdapter extends ArrayAdapter> { @@ -148,71 +111,30 @@ public int getCount() { public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; View v = convertView; + HashMap item = itemsArray.get(position); if (v == null) { - LayoutInflater vi = (LayoutInflater) getApplicationContext() - .getSystemService(Context.LAYOUT_INFLATER_SERVICE); + //LayoutInflater v = vi.inflate(R.layout.results_item, null); holder = new ViewHolder(); - holder.tv1 = (TextView) v.findViewById(R.id.res_dname); - holder.tv2 = (TextView) v.findViewById(R.id.res_fname); - holder.tvHolder = (LinearLayout) v - .findViewById(R.id.res_holder); + if (v == null) { + return null; + } + holder.tv1 = (TextView) v.findViewById(R.id.res_dname); + holder.tv2 = (TextView) v.findViewById(R.id.res_fname); + holder.tvHolder = (LinearLayout) v.findViewById(R.id.res_holder); holder.iv = (ImageView) v.findViewById(R.id.res_icon); v.setTag(holder); - } else + } else{ holder = (ViewHolder) v.getTag(); - - // exts dirs sorter - final class ExtsComparator implements java.util.Comparator { - public int compare(String a, String b) { - if (a == null && b == null) - return 0; - if (a == null && b != null) - return 1; - if (a != null && b == null) - return -1; - if (a.length() < b.length()) - return 1; - if (a.length() > b.length()) - return -1; - return a.compareTo(b); - } - } - // known extensions - List> rc; - ArrayList exts = new ArrayList(); - if (prefs.getBoolean("hideKnownExts", false)) { - rc = app.getReaders(); - Set tkeys = new HashSet(); - for (int i = 0; i < rc.size(); i++) { - Object[] keys = rc.get(i).keySet().toArray(); - for (int j = 0; j < keys.length; j++) { - tkeys.add(keys[j].toString()); - } - } - exts = new ArrayList(tkeys); - Collections.sort(exts, new ExtsComparator()); - } - // known dirs - ArrayList dirs = new ArrayList(); - if (prefs.getBoolean("hideKnownDirs", false)) { - String[] home_dirs = prefs.getString("startDir", - "/sdcard,/media/My Files").split("\\,"); - for (int i = 0; i < home_dirs.length; i++) - dirs.add(home_dirs[i]); - Collections.sort(dirs, new ExtsComparator()); - } + } TextView tv1 = holder.tv1; TextView tv2 = holder.tv2; + LinearLayout tvHolder = holder.tvHolder; + ImageView iv = holder.iv; - tv2.setTextSize(TypedValue.COMPLEX_UNIT_PX, Integer.parseInt(prefs - .getString("firstLineFontSizePx", "20"))); - tv1.setTextSize(TypedValue.COMPLEX_UNIT_PX, Integer.parseInt(prefs - .getString("secondLineFontSizePx", "16"))); - - LinearLayout tvHolder = holder.tvHolder; - ImageView iv = holder.iv; + tv2.setTextSize(TypedValue.COMPLEX_UNIT_PX, firstLineFontSizePx); + tv1.setTextSize(TypedValue.COMPLEX_UNIT_PX, secondLineFontSizePx); if (position >= itemsArray.size()) { v.setVisibility(View.INVISIBLE); @@ -221,7 +143,7 @@ public int compare(String a, String b) { iv.setVisibility(View.INVISIBLE); return v; } - HashMap item = itemsArray.get(position); + if (item != null) { String fname = item.get("fname"); String sname = item.get("sname"); @@ -229,233 +151,114 @@ public int compare(String a, String b) { String sdname = item.get("dname"); String fullName = dname + "/" + fname; boolean setBold = false; - boolean useFaces = prefs.getBoolean("showNew", true); - - // clean extension, if needed - if (prefs.getBoolean("hideKnownExts", false)) { - for (int i = 0; i < exts.size(); i++) { - if (sname.endsWith(exts.get(i))) { - sname = sname.substring(0, sname.length() - - exts.get(i).length()); - } - } - } - // clean start prefixes, if need - if (prefs.getBoolean("hideKnownDirs", false)) { - for (int i = 0; i < dirs.size(); i++) { - if (sdname.startsWith(dirs.get(i))) { - sdname = "~" - + sdname.substring(dirs.get(i).length()); - } - } - } - - if (useFaces) { - if (app.history.containsKey(fullName)) { - if (app.history.get(fullName) == app.READING) { - tvHolder.setBackgroundColor(getResources() - .getColor(R.color.file_reading_bg)); - tv1.setTextColor(getResources().getColor( - R.color.file_reading_fg)); - tv2.setTextColor(getResources().getColor( - R.color.file_reading_fg)); - } else if (app.history.get(fullName) == app.FINISHED) { - tvHolder.setBackgroundColor(getResources() - .getColor(R.color.file_finished_bg)); - tv1.setTextColor(getResources().getColor( - R.color.file_finished_fg)); - tv2.setTextColor(getResources().getColor( - R.color.file_finished_fg)); - } else { - tvHolder.setBackgroundColor(getResources() - .getColor(R.color.file_unknown_bg)); - tv1.setTextColor(getResources().getColor( - R.color.file_unknown_fg)); - tv2.setTextColor(getResources().getColor( - R.color.file_unknown_fg)); - } - } else { - tvHolder.setBackgroundColor(getResources().getColor( - R.color.file_new_bg)); - tv1.setTextColor(getResources().getColor( - R.color.file_new_fg)); - tv2.setTextColor(getResources().getColor( - R.color.file_new_fg)); - if (getResources().getBoolean(R.bool.show_new_as_bold)) - setBold = true; - } - } // setup icon - if (prefs.getString("firstLineIconSizePx", "48").equals("0")) { - iv.setVisibility(View.GONE); - } else { - Drawable d = app.specialIcon(fullName, item.get("type") - .equals("dir")); - if (d != null) - iv.setImageBitmap(scaleDrawable(d, Integer - .parseInt(prefs.getString( - "firstLineIconSizePx", "48")))); - else { - String rdrName = app.readerName(fname); - if (rdrName.equals("Nope")) { - File f = new File(fullName); - if (f.length() > app.viewerMax) - iv.setImageBitmap(scaleDrawableById( - R.drawable.file_notok, Integer - .parseInt(prefs.getString( - "firstLineIconSizePx", - "48")))); - else - iv.setImageBitmap(scaleDrawableById( - R.drawable.file_ok, Integer - .parseInt(prefs.getString( - "firstLineIconSizePx", - "48")))); - } else if (rdrName.startsWith("Intent:")) - iv.setImageBitmap(scaleDrawableById( - R.drawable.icon, Integer.parseInt(prefs - .getString("firstLineIconSizePx", - "48")))); - else { - if (icons.containsKey(rdrName)) - iv.setImageBitmap(scaleDrawable(icons - .get(rdrName), - Integer.parseInt(prefs.getString( - "firstLineIconSizePx", "48")))); - else - iv.setImageBitmap(scaleDrawableById( - R.drawable.file_ok, Integer - .parseInt(prefs.getString( - "firstLineIconSizePx", - "48")))); - } - } - } + if (firstLineIconSizePx == 0) { // если отключены картинки + iv.setVisibility(View.GONE); // скрываем поле с ними + }else { + String temp_nameIcon = item.get("nameIcon"); + for (imageIcon anArrIcon : arrIcon) { + if (anArrIcon.nameIcon.equals(temp_nameIcon)) { + iv.setImageBitmap(anArrIcon.icon); + break; + } + } + } // special cases in dname & fname // dname empty - in root dir // fname empty with dname empty - root dir as is if (dname.equals("")) { - dname = "/"; + //dname = "/"; sdname = "/"; if (fname.equals("")) { - fname = "/"; + //fname = "/"; sname = "/"; - dname = ""; + //dname = ""; sdname = ""; } } - if (useFaces) { - SpannableString s = new SpannableString(sname); - s.setSpan(new StyleSpan(setBold ? Typeface.BOLD - : Typeface.NORMAL), 0, sname.length(), 0); - tv1.setText(sdname); - tv2.setText(s); - } else { - tvHolder.setBackgroundColor(getResources().getColor( - R.color.normal_bg)); - tv1.setTextColor(getResources().getColor(R.color.normal_fg)); - tv2.setTextColor(getResources().getColor(R.color.normal_fg)); - tv1.setText(sdname); - tv2.setText(sname); - } + + if (showNew) { + int color_txt; + if (app.history.containsKey(fullName)) { + int baseHistory = app.history.get(fullName); + if (baseHistory == app.READING) { + color_txt = getResources().getColor(R.color.file_reading_fg); + tvHolder.setBackgroundColor(getResources() .getColor(R.color.file_reading_bg)); + } else if (baseHistory == app.FINISHED) { + color_txt = getResources().getColor(R.color.file_finished_fg); + tvHolder.setBackgroundColor(getResources().getColor(R.color.file_finished_bg)); + } else { + color_txt = getResources().getColor(R.color.file_unknown_fg); + tvHolder.setBackgroundColor(getResources().getColor(R.color.file_unknown_bg)); + } + } else { + color_txt = getResources().getColor(R.color.file_new_fg); + tvHolder.setBackgroundColor(getResources().getColor(R.color.file_new_bg)); + if (getResources().getBoolean(R.bool.show_new_as_bold)) + setBold = true; + } + tv1.setTextColor(color_txt); + tv2.setTextColor(color_txt); + + SpannableString s = new SpannableString(sname); + s.setSpan(new StyleSpan(setBold ? Typeface.BOLD : Typeface.NORMAL), 0, sname.length(), 0); + tv1.setText(sdname); + tv2.setText(s); + }else { + tvHolder.setBackgroundColor(getResources().getColor(R.color.normal_bg)); + int color_txt = getResources().getColor(R.color.normal_fg); + tv1.setTextColor(color_txt); + tv2.setTextColor(color_txt); + tv1.setText(sdname); + tv2.setText(sname); + } + } // fixes on rows height in grid - if (currentColsNum != 1) { - GridView pgv = (GridView) parent; - Integer gcols = currentColsNum; - Integer between_columns = 0; // configure ??? - Integer after_row_space = 0; // configure ??? - Integer colw = (pgv.getWidth() - (gcols - 1) * between_columns) - / gcols; - Integer recalc_num = position; - Integer recalc_height = 0; - while (recalc_num % gcols != 0) { - recalc_num = recalc_num - 1; - View temp_v = getView(recalc_num, null, parent); - temp_v.measure(MeasureSpec.EXACTLY | colw, - MeasureSpec.UNSPECIFIED); - Integer p_height = temp_v.getMeasuredHeight(); - if (p_height > recalc_height) - recalc_height = p_height; - } - if (recalc_height > 0) { - v.setMinimumHeight(recalc_height + after_row_space); - } - } + // если у грида не одна колонка, то выравниваем ячейки по высоте в одной строке + if (currentColsNum != 1) { + GridView pgv = (GridView) parent; + int colw = (pgv.getWidth()) / currentColsNum; // получаем ширину колонки + int recalc_num = position; // номер позиции + int recalc_height = 0; + while (recalc_num % currentColsNum != 0) { // находим последний элемент в строке + recalc_num = recalc_num - 1; + View temp_v = getView(recalc_num, null, parent); + if (temp_v != null) { + temp_v.measure(MeasureSpec.EXACTLY | colw, MeasureSpec.UNSPECIFIED); + int p_height = temp_v.getMeasuredHeight(); + if (p_height > 0) + recalc_height = p_height; + } + + } + if (recalc_height > 0) { + v.setMinimumHeight(recalc_height); + } + } return v; } } - private Integer Percentile(ArrayList values, Integer Quantile) - // not fully "mathematical proof", but not too difficult and working - { - Collections.sort(values); - Integer index = (values.size() * Quantile) / 100; - return values.get(index); - } - - private Integer getAutoColsNum() { - // implementation - via percentiles len - Integer auto_cols_num = 1; - ArrayList tmp = new ArrayList(); - if (itemsArray.size() > 0) { - Integer factor = 0; - for (Integer i = 0; i < itemsArray.size(); i++) { - tmp.add(itemsArray.get(i).get("fname").length()); - } - String pattern = prefs.getString("columnsAlgIntensity", - "70 3:5 7:4 15:3 48:2"); // default - medium - String[] spat = pattern.split("[\\s\\:]+"); - Integer quantile = Integer.parseInt(spat[0]); - factor = Percentile(tmp, quantile); - for (Integer i = 1; i < spat.length; i = i + 2) { - try { - double fval = Double.parseDouble(spat[i]); - int cval = Integer.parseInt(spat[i + 1]); - if (factor <= fval) { - auto_cols_num = cval; - break; - } - } catch (Exception e) { - } - } - } - if (auto_cols_num > itemsArray.size()) - auto_cols_num = itemsArray.size(); - return auto_cols_num; - } private void redrawList() { - setEinkController(); - if (prefs.getBoolean("filterResults", false)) { + EinkScreen.PrepareController(null, false); + if (filterResults) { List> newItemsArray = new ArrayList>(); for (HashMap item : itemsArray) { - if (app.filterFile(item.get("dname"), item.get("fname")) - || item.get("type").equals("dir")) + if (app.filterFile(item.get("dname"), item.get("fname")) || item.get("type").equals("dir")) newItemsArray.add(item); } itemsArray = newItemsArray; } - Integer colsNum = -1; - if (listName.equals("homeList")) { - colsNum = Integer - .parseInt(prefs.getString("columnsHomeList", "-1")); - } - if (listName.equals("favorites")) { - colsNum = Integer.parseInt(prefs.getString("columnsFAV", "-1")); - } - if (listName.equals("lastOpened")) { - colsNum = Integer.parseInt(prefs.getString("columnsLRU", "-1")); - } - if (listName.equals("searchResults")) { - colsNum = Integer.parseInt(prefs.getString("columnsSearch", "-1")); - } + + Integer colsNum = Integer.parseInt(prefs.getString(listNameSecond, "-1")); // override auto (not working fine in adnroid) if (colsNum == -1) { - colsNum = getAutoColsNum(); + colsNum = app.getAutoColsNum(itemsArray, "fname", ReLaunch.columnsAlgIntensity); } currentColsNum = colsNum; final GridView gv = (GridView) findViewById(R.id.results_list); @@ -480,34 +283,115 @@ private void start(Intent i) { private void createItemsArray() { itemsArray = new ArrayList>(); - for (String[] n : app.getList(listName)) { - if (!prefs.getBoolean("filterResults", false) - || (prefs.getBoolean("filterResults", false) && app - .filterFile(n[0], n[1])) - || (n[1].equals(app.DIR_TAG))) { - HashMap item = new HashMap(); - item.put("dname", n[0]); - item.put("fname", n[1]); - item.put("sname", n[1]); - if (n[1].equals(app.DIR_TAG)) { - int ind = n[0].lastIndexOf('/'); - if (ind == -1) { - item.put("fname", ""); - item.put("sname", ""); - } else { - item.put("fname", n[0].substring(ind + 1)); - item.put("sname", n[0].substring(ind + 1)); - item.put("dname", n[0].substring(0, ind)); - } - item.put("type", "dir"); - } else { - item.put("type", "file"); - if (prefs.getBoolean("showBookTitles", false)) - item.put("sname", getEbookName(n[0], n[1])); - } - itemsArray.add(item); - } - } + // вычищаем иконки из массива. оставляем только стандартные + for(int i = 5, j = arrIcon.size(); i< j; j--){ + arrIcon.remove(j-1); + } + if(listName.equals("opdslist")){ + dbOPDS(); + }else { + + Button rt = (Button) findViewById(R.id.results_title); + if (total == -1){ + rt.setText(title + " (" + app.getList(listName).size() + ")"); + }else{ + rt.setText(title + " (" + app.getList(listName).size() + "/"+ total + ")"); + } + for (String[] n : app.getList(listName)) { + if (!filterResults || (filterResults && app.filterFile(n[0], n[1])) || (n[1].equals(app.DIR_TAG))) { + HashMap item = new HashMap(); + item.put("dname", n[0]); + item.put("fname", n[1]); + + if (n[1].equals(app.DIR_TAG)) { + int ind = n[0].lastIndexOf('/'); + if (ind == -1) { + item.put("fname", ""); + item.put("sname", ""); + } else { + String sname = n[0].substring(ind + 1); + item.put("fname", sname); + // clean start prefixes, if need + if (hideKnownDirs) { + for (int i = 0, j = ReLaunch.startDir.length; i < j; i++) { + if (sname.startsWith(ReLaunch.startDir[i])) { + sname = "~" + sname.substring(ReLaunch.startDir[i].length()); + } + } + } + item.put("sname", sname); + item.put("dname", n[0].substring(0, ind)); + } + //item.put("type", "dir"); + + // получение иконки========= + if (firstLineIconSizePx != 0) { + item.put("nameIcon", "dir_ok"); + } + //===================== + } else { + String fname = n[1]; + if (showBookTitles) { + item.put("sname", getEbookName(n[0], n[1])); + } else { + if (hideKnownExts) {// clean extension, if needed + for (int i = 0, j = ReLaunch.exts.size(); i < j; i++) { + if (fname.endsWith(ReLaunch.exts.get(i))) { + fname = fname.substring(0, fname.length() - ReLaunch.exts.get(i).length()); + //break; + } + } + } + item.put("sname", fname); + } + + //item.put("type", "file"); + // получение иконки============================== + if (firstLineIconSizePx != 0) { + String nameIcon; + + Drawable d = app.specialIcon(n[1], false); // получаем иконку + if (d != null) { // если удалось + imageIcon temp_icon = new imageIcon(); + temp_icon.nameIcon = n[1]; + temp_icon.icon = scaleDrawable(d, firstLineIconSizePx); + arrIcon.add(temp_icon); + nameIcon = n[1]; + } else { // иначе + String rdrName = app.readerName(n[1]); // в поле реадера читаем обработчик + + if (rdrName.startsWith("Intent:")) { // если ответ начинается с ... + nameIcon = "icon"; + } else if (rdrName.equals("Nope")) { // если не известен + File fil = new File(n[1]); // получаем файл + if (fil.length() > app.viewerMax * 1024) { // больше определенного размера + nameIcon = "file_notok"; + } else { // иначе + nameIcon = "file_ok"; + } + } else { // во всех остальных случаях + + if (app.getIcons().containsKey(rdrName)) { // у программы есть иконка? + imageIcon temp_icon = new imageIcon(); + temp_icon.nameIcon = rdrName; + temp_icon.icon = scaleDrawable(app.getIcons().get(rdrName), firstLineIconSizePx); + arrIcon.add(temp_icon); + nameIcon = rdrName; + } else { + nameIcon = "file_notok"; + } + } + } + + item.put("nameIcon", nameIcon); // тип - файл + } + //============================================= + } + itemsArray.add(item); + } + } + } + adapter.notifyDataSetChanged(); } @Override @@ -516,19 +400,34 @@ protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); - - setEinkController(); + hideKnownExts = prefs.getBoolean("hideKnownExts", false); + firstLineFontSizePx = Integer.parseInt(prefs.getString("firstLineFontSizePx", "20")); + secondLineFontSizePx = Integer.parseInt(prefs.getString("secondLineFontSizePx", "16")); + showNew = prefs.getBoolean("showNew", true); + hideKnownDirs = prefs.getBoolean("hideKnownDirs", false); + firstLineIconSizePx = Integer.parseInt(prefs.getString("firstLineIconSizePx", "48")); + filterResults = prefs.getBoolean("filterResults", false); + showBookTitles = prefs.getBoolean("showBookTitles", false); + // ------ загружаем стандартные иконки для отображения в менеджере ---------- + loadStandartIcons(); + + EinkScreen.setEinkController(prefs); app = ((ReLaunchApp) getApplicationContext()); - app.setFullScreenIfNecessary(this); - setContentView(R.layout.results_layout); + if (app != null) { + app.setFullScreenIfNecessary(this); + } + setContentView(R.layout.results_layout); + vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); icons = app.getIcons(); - if (app.dataBase == null) + if (app.dataBase == null){ app.dataBase = new BooksBase(this); - if (!app.dataBase.db.isOpen()) + } + if (!BooksBase.db.isOpen()){ app.dataBase = new BooksBase(this); + } purgeBracketsPattern = Pattern.compile("\\[[\\s\\.\\-_]*\\]"); // Recreate readers list @@ -540,10 +439,9 @@ protected void onCreate(Bundle savedInstanceState) { listName = data.getExtras().getString("list"); title = data.getExtras().getString("title"); rereadOnStart = data.getExtras().getBoolean("rereadOnStart"); - int total = data.getExtras().getInt("total", -1); + total = data.getExtras().getInt("total", -1); - ((ImageButton) findViewById(R.id.results_btn)) - .setOnClickListener(new View.OnClickListener() { + (findViewById(R.id.results_btn)).setOnClickListener(new View.OnClickListener() { public void onClick(View v) { finish(); } @@ -552,21 +450,34 @@ public void onClick(View v) { // set results icon ImageView results_icon = (ImageView) findViewById(R.id.results_icon); if (listName.equals("homeList")) { - results_icon.setImageDrawable(getResources().getDrawable( - R.drawable.ci_home)); + listNameSecond = "columnsHomeList"; + results_icon.setImageDrawable(getResources().getDrawable(R.drawable.ci_home)); } if (listName.equals("favorites")) { - results_icon.setImageDrawable(getResources().getDrawable( - R.drawable.ci_fav)); + listNameSecond = "columnsFAV"; + results_icon.setImageDrawable(getResources().getDrawable(R.drawable.ci_fav)); } if (listName.equals("lastOpened")) { - results_icon.setImageDrawable(getResources().getDrawable( - R.drawable.ci_lre)); + listNameSecond = "columnsLRU"; + results_icon.setImageDrawable(getResources().getDrawable(R.drawable.ci_lre)); } if (listName.equals("searchResults")) { - results_icon.setImageDrawable(getResources().getDrawable( - R.drawable.ci_search)); + listNameSecond = "columnsSearch"; + results_icon.setImageDrawable(getResources().getDrawable(R.drawable.ci_search)); } + if (listName.equals("opdslist")) { + listNameSecond = "opdslist"; + results_icon.setImageDrawable(getResources().getDrawable(R.drawable.ci_books)); + dbHelper = new DBHelper(this); + db = dbHelper.getReadableDatabase(); + Cursor c = db.query("OPDS1", null, null, null, null, null, null); + + if(c.getCount()== 0){ + addDbOPDS("Либрусек", "http://lib.rus.ec/opds", false, null, null); + } + c.close(); + db.close(); + } // may be "dead end" of code now(?) now UP functionality in this // screens? // so force to DISABLED @@ -582,20 +493,8 @@ public boolean onSingleTapConfirmed(MotionEvent e) { startActivity(i); return true; } - - @Override - public boolean onDoubleTap(MotionEvent e) { - return true; - } - - @Override - public void onLongPress(MotionEvent e) { - if (adv.hasWindowFocus()) { - - } - } } - ; + advSimpleOnGestureListener adv_gl = new advSimpleOnGestureListener(); final GestureDetector adv_gd = new GestureDetector(adv_gl); adv.setOnTouchListener(new OnTouchListener() { @@ -610,126 +509,41 @@ public boolean onTouch(View v, MotionEvent event) { final GridView gv = (GridView) findViewById(R.id.results_list); gv.setHorizontalSpacing(0); Button rt = (Button) findViewById(R.id.results_title); - if (total == -1) - rt.setText(title + " (" + app.getList(listName).size() + ")"); - else - rt.setText(title + " (" + app.getList(listName).size() + "/" - + total + ")"); rt.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { - final String[] columns = getResources().getStringArray( - R.array.output_columns_names); + final String[] columns = getResources().getStringArray(R.array.output_columns_names); final CharSequence[] columnsmode = new CharSequence[columns.length]; - for (int i = 0; i < columns.length; i++) { - columnsmode[i] = columns[i]; - } - boolean show_select = false; - Integer checked = -1; - if (listName.equals("homeList")) { - checked = Integer.parseInt(prefs.getString( - "columnsHomeList", "-1")); - if (checked == -1) - checked = 0; - show_select = true; - } - if (listName.equals("favorites")) { - checked = Integer.parseInt(prefs.getString("columnsFAV", - "-1")); - if (checked == -1) - checked = 0; - show_select = true; - } - if (listName.equals("lastOpened")) { - checked = Integer.parseInt(prefs.getString("columnsLRU", - "-1")); - if (checked == -1) - checked = 0; - show_select = true; - } - if (listName.equals("searchResults")) { - checked = Integer.parseInt(prefs.getString("columnsSearch", - "-1")); - if (checked == -1) - checked = 0; - show_select = true; - } + System.arraycopy(columns, 0, columnsmode, 0, columns.length); + Integer checked = Integer.parseInt(prefs.getString(listNameSecond, "-1")); + if (checked == -1){ + checked = 0; + } // get checked AlertDialog.Builder builder = new AlertDialog.Builder( ResultsActivity.this); // "Select application" - builder.setTitle(getResources().getString( - R.string.jv_relaunch_select_columns)); + builder.setTitle(getResources().getString(R.string.jv_relaunch_select_columns)); builder.setSingleChoiceItems(columnsmode, checked, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int i) { + SharedPreferences.Editor editor = prefs.edit(); if (i == 0) { - if (listName.equals("homeList")) { - SharedPreferences.Editor editor = prefs - .edit(); - editor.putString("columnsHomeList", - "-1"); - editor.commit(); - } - if (listName.equals("favorites")) { - SharedPreferences.Editor editor = prefs - .edit(); - editor.putString("columnsFAV", "-1"); - editor.commit(); - } - if (listName.equals("lastOpened")) { - SharedPreferences.Editor editor = prefs - .edit(); - editor.putString("columnsLRU", "-1"); - editor.commit(); - } - if (listName.equals("searchResults")) { - SharedPreferences.Editor editor = prefs - .edit(); - editor.putString("columnsSearch", "-1"); - editor.commit(); - } + editor.putString(listNameSecond,"-1"); } else { - if (listName.equals("homeList")) { - SharedPreferences.Editor editor = prefs - .edit(); - editor.putString("columnsHomeList", - Integer.toString(i)); - editor.commit(); - } - if (listName.equals("favorites")) { - SharedPreferences.Editor editor = prefs - .edit(); - editor.putString("columnsFAV", - Integer.toString(i)); - editor.commit(); - } - if (listName.equals("lastOpened")) { - SharedPreferences.Editor editor = prefs - .edit(); - editor.putString("columnsLRU", - Integer.toString(i)); - editor.commit(); - } - if (listName.equals("searchResults")) { - SharedPreferences.Editor editor = prefs - .edit(); - editor.putString("columnsSearch", - Integer.toString(i)); - editor.commit(); - } + editor.putString(listNameSecond,Integer.toString(i)); } + editor.commit(); redrawList(); dialog.dismiss(); } }); - if (show_select) { - AlertDialog alert = builder.create(); - alert.show(); - } + AlertDialog alert = builder.create(); + alert.show(); + } }); - createItemsArray(); + //createItemsArray(); adapter = new FLSimpleAdapter(this, R.layout.results_item, itemsArray); gv.setAdapter(adapter); registerForContextMenu(gv); @@ -737,8 +551,7 @@ public void onClick(DialogInterface dialog, int i) { if (addSView) { int scrollW; try { - scrollW = Integer.parseInt(prefs.getString("scrollWidth", - "25")); + scrollW = Integer.parseInt(prefs.getString("scrollWidth","25")); } catch (NumberFormatException e) { scrollW = 25; } @@ -756,8 +569,8 @@ public void onScroll(AbsListView view, sv.total = totalItemCount; sv.count = visibleItemCount; sv.first = firstVisibleItem; - setEinkController(); - sv.invalidate(); + EinkScreen.PrepareController(null, false); + sv.invalidate(); } public void onScrollStateChanged(AbsListView view, @@ -770,7 +583,7 @@ public void onScrollStateChanged(AbsListView view, gv.setOnScrollListener(new AbsListView.OnScrollListener() { public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { - setEinkController(); + EinkScreen.PrepareController(null, false); } public void onScrollStateChanged(AbsListView view, @@ -779,22 +592,25 @@ public void onScrollStateChanged(AbsListView view, }); } gv.setOnItemClickListener(new OnItemClickListener() { + public void onItemClick(AdapterView parent, View view, int position, long id) { HashMap item = itemsArray.get(position); - String fullName = item.get("dname") + "/" + item.get("fname"); + currentPosition = parent.getFirstVisiblePosition(); - if (item.get("type").equals("dir")) { - Intent intent = new Intent(ResultsActivity.this, - ReLaunch.class); - intent.putExtra("dirviewer", false); + if(listName.equals("opdslist")){ + Intent intent = new Intent(ResultsActivity.this, OPDSActivity.class); + intent.putExtra("opdscat", item.get("dname")); + intent.putExtra("login", item.get("login")); + intent.putExtra("password", item.get("password")); + startActivity(intent); + }else if (item.get("type").equals("dir")) { + Intent intent = new Intent(ResultsActivity.this,ReLaunch.class); intent.putExtra("start_dir", fullName); intent.putExtra("home", ReLaunch.useHome); intent.putExtra("home1", ReLaunch.useHome1); - intent.putExtra("shop", ReLaunch.useShop); - intent.putExtra("library", ReLaunch.useLibrary); oldHome = ReLaunch.useHome; startActivityForResult(intent, ReLaunch.DIR_ACT); } else { @@ -805,44 +621,31 @@ public void onItemClick(AdapterView parent, View view, else { // Launch reader if (app.askIfAmbiguous) { - List rdrs = app.readerNames(item - .get("fname")); + List rdrs = app.readerNames(item.get("fname")); if (rdrs.size() < 1) return; else if (rdrs.size() == 1) - start(app.launchReader(rdrs.get(0), - fullName)); + start(app.launchReader(rdrs.get(0),fullName)); else { - final CharSequence[] applications = rdrs - .toArray(new CharSequence[rdrs - .size()]); - CharSequence[] happlications = app - .getApps().toArray( - new CharSequence[app - .getApps().size()]); + final CharSequence[] applications = rdrs.toArray(new CharSequence[rdrs.size()]); + CharSequence[] happlications = app.getApps().toArray( + new CharSequence[app.getApps().size()]); for (int j = 0; j < happlications.length; j++) { String happ = (String) happlications[j]; String[] happp = happ.split("\\%"); happlications[j] = happp[2]; } final String rdr1 = fullName; - AlertDialog.Builder builder = new AlertDialog.Builder( - ResultsActivity.this); + AlertDialog.Builder builder = new AlertDialog.Builder(ResultsActivity.this); // "Select application" - builder.setTitle(getResources() - .getString( - R.string.jv_results_select_application)); + builder.setTitle(getResources().getString(R.string.jv_results_select_application)); builder.setSingleChoiceItems( - happlications, - -1, + happlications,-1, new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int i) { - start(app - .launchReader( - (String) applications[i], - rdr1)); + start(app.launchReader((String) applications[i],rdr1)); dialog.dismiss(); } }); @@ -850,8 +653,7 @@ public void onClick( alert.show(); } } else - start(app.launchReader( - app.readerName(fileName), fullName)); + start(app.launchReader(app.readerName(fileName), fullName)); } } // close in needed @@ -862,7 +664,7 @@ public void onClick( }); final Button upScroll = (Button) findViewById(R.id.upscroll_btn); - if (prefs.getBoolean("disableScrollJump", true) == false) { + if (!ReLaunch.disableScrollJump) { upScroll.setText(app.scrollStep + "%"); } else { upScroll.setText(getResources() @@ -871,22 +673,28 @@ public void onClick( class upScrlSimpleOnGestureListener extends SimpleOnGestureListener { @Override public boolean onSingleTapConfirmed(MotionEvent e) { - if (DeviceInfo.EINK_NOOK) { // nook + if (N2DeviceInfo.EINK_NOOK) { // nook MotionEvent ev; ev = MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 200, 100, 0); - gv.dispatchTouchEvent(ev); - ev = MotionEvent.obtain(SystemClock.uptimeMillis(), + if (ev != null) { + gv.dispatchTouchEvent(ev); + } + ev = MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis() + 100, MotionEvent.ACTION_MOVE, 200, 200, 0); - gv.dispatchTouchEvent(ev); - SystemClock.sleep(100); + if (ev != null) { + gv.dispatchTouchEvent(ev); + } + SystemClock.sleep(100); ev = MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, 200, 200, 0); - gv.dispatchTouchEvent(ev); - } else { // other devices + if (ev != null) { + gv.dispatchTouchEvent(ev); + } + } else { // other devices int first = gv.getFirstVisiblePosition(); int visible = gv.getLastVisiblePosition() - gv.getFirstVisiblePosition() + 1; @@ -906,7 +714,7 @@ public boolean onSingleTapConfirmed(MotionEvent e) { @Override public boolean onDoubleTap(MotionEvent e) { - if (prefs.getBoolean("disableScrollJump", true) == false) { + if (!ReLaunch.disableScrollJump) { int first = gv.getFirstVisiblePosition(); int total = itemsArray.size(); first -= (total * app.scrollStep) / 100; @@ -925,10 +733,9 @@ public boolean onDoubleTap(MotionEvent e) { @Override public void onLongPress(MotionEvent e) { if (upScroll.hasWindowFocus()) { - if (prefs.getBoolean("disableScrollJump", true) == false) { - int first = gv.getFirstVisiblePosition(); + if (!ReLaunch.disableScrollJump) { + int first = 0;// = gv.getFirstVisiblePosition(); int total = itemsArray.size(); - first = 0; gv.setSelection(first); // some hack workaround against not scrolling in some // cases @@ -940,7 +747,7 @@ public void onLongPress(MotionEvent e) { } } } - ; + upScrlSimpleOnGestureListener upscrl_gl = new upScrlSimpleOnGestureListener(); final GestureDetector upscrl_gd = new GestureDetector(upscrl_gl); upScroll.setOnTouchListener(new OnTouchListener() { @@ -979,7 +786,7 @@ public void run() { } final Button downScroll = (Button) findViewById(R.id.downscroll_btn); - if (prefs.getBoolean("disableScrollJump", true) == false) { + if (!ReLaunch.disableScrollJump) { downScroll.setText(app.scrollStep + "%"); } else { downScroll.setText(getResources().getString( @@ -988,22 +795,28 @@ public void run() { class dnScrlSimpleOnGestureListener extends SimpleOnGestureListener { @Override public boolean onSingleTapConfirmed(MotionEvent e) { - if (DeviceInfo.EINK_NOOK) { // nook special + if (N2DeviceInfo.EINK_NOOK) { // nook special MotionEvent ev; ev = MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 200, 200, 0); - gv.dispatchTouchEvent(ev); - ev = MotionEvent.obtain(SystemClock.uptimeMillis(), + if (ev != null) { + gv.dispatchTouchEvent(ev); + } + ev = MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis() + 100, MotionEvent.ACTION_MOVE, 200, 100, 0); - gv.dispatchTouchEvent(ev); - SystemClock.sleep(100); + if (ev != null) { + gv.dispatchTouchEvent(ev); + } + SystemClock.sleep(100); ev = MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, 200, 100, 0); - gv.dispatchTouchEvent(ev); - } else { // other devices + if (ev != null) { + gv.dispatchTouchEvent(ev); + } + } else { // other devices int first = gv.getFirstVisiblePosition(); int total = itemsArray.size(); int last = gv.getLastVisiblePosition(); @@ -1020,7 +833,7 @@ public boolean onSingleTapConfirmed(MotionEvent e) { @Override public boolean onDoubleTap(MotionEvent e) { - if (prefs.getBoolean("disableScrollJump", true) == false) { + if (!ReLaunch.disableScrollJump) { int first = gv.getFirstVisiblePosition(); int total = itemsArray.size(); int last = gv.getLastVisiblePosition(); @@ -1041,7 +854,7 @@ public boolean onDoubleTap(MotionEvent e) { @Override public void onLongPress(MotionEvent e) { if (downScroll.hasWindowFocus()) { - if (prefs.getBoolean("disableScrollJump", true) == false) { + if (!ReLaunch.disableScrollJump) { int first = gv.getFirstVisiblePosition(); int total = itemsArray.size(); int last = gv.getLastVisiblePosition(); @@ -1059,7 +872,7 @@ public void onLongPress(MotionEvent e) { } } } - ; + dnScrlSimpleOnGestureListener dnscrl_gl = new dnScrlSimpleOnGestureListener(); final GestureDetector dnscrl_gd = new GestureDetector(dnscrl_gl); downScroll.setOnTouchListener(new OnTouchListener() { @@ -1078,10 +891,16 @@ protected void onStart() { redrawList(); super.onStart(); } + @Override + protected void onStop() { + if (listName.equals("opdslist")) { + dbHelper.close(); + } + super.onStop(); + } @Override public boolean onCreateOptionsMenu(Menu menu) { - ; MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.resultsmenu, menu); return true; @@ -1091,16 +910,14 @@ public boolean onCreateOptionsMenu(Menu menu) { public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.mime_types: - Intent intent1 = new Intent(ResultsActivity.this, - TypesActivity.class); + Intent intent1 = new Intent(ResultsActivity.this, TypesActivity.class); startActivityForResult(intent1, ReLaunch.TYPES_ACT); return true; case R.id.about: app.About(this); return true; case R.id.setting: - Intent intent3 = new Intent(ResultsActivity.this, - PrefsActivity.class); + Intent intent3 = new Intent(ResultsActivity.this, PrefsActivity.class); startActivity(intent3); return true; default: @@ -1127,13 +944,12 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) { ReLaunch.useHome = oldHome; break; default: - return; + //return; } } @Override - public void onCreateContextMenu(ContextMenu menu, View v, - ContextMenuInfo menuInfo) { + public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; int pos = info.position; HashMap i = itemsArray.get(pos); @@ -1143,15 +959,23 @@ public void onCreateContextMenu(ContextMenu menu, View v, if (listName.equals("homeList")) { return; - } else if (i.get("type").equals("dir")) { + } else if (listNameSecond.equals("opdslist")) { + // "Add opds catalog" + menu.add(Menu.NONE, CNTXT_MENU_ADD_OPDS, Menu.NONE, getResources().getString(R.string.jv_results_add_opds)); + // "Remove from list" + menu.add(Menu.NONE, CNTXT_MENU_DEL_OPDS, Menu.NONE, getResources().getString(R.string.jv_relaunch_delete)); + // "Rename" + menu.add(Menu.NONE, CNTXT_MENU_EDIT_OPDS, Menu.NONE, getResources().getString(R.string.jv_relaunch_edit)); + // "Rename" + menu.add(Menu.NONE, CNTXT_MENU_CLEAN_OPDS, Menu.NONE, getResources().getString(R.string.jv_relaunch_clean)); + + } else if (i.get("type").equals("dir")) { if (pos > 0) // "Move one position up" - menu.add(Menu.NONE, CNTXT_MENU_MOVEUP, Menu.NONE, - getResources().getString(R.string.jv_results_move_up)); + menu.add(Menu.NONE, CNTXT_MENU_MOVEUP, Menu.NONE,getResources().getString(R.string.jv_results_move_up)); if (pos < (itemsArray.size() - 1)) // "Move one position down" - menu.add(Menu.NONE, CNTXT_MENU_MOVEDOWN, Menu.NONE, - getResources().getString(R.string.jv_results_move_down)); + menu.add(Menu.NONE, CNTXT_MENU_MOVEDOWN, Menu.NONE,getResources().getString(R.string.jv_results_move_down)); // "Remove from favorites" menu.add(Menu.NONE, CNTXT_MENU_RMFAV, Menu.NONE, getResources() .getString(R.string.jv_results_remove)); @@ -1159,18 +983,13 @@ public void onCreateContextMenu(ContextMenu menu, View v, if (prefs.getBoolean("useFileManagerFunctions", true)) menu.add(Menu.NONE, CNTXT_MENU_RMDIR, Menu.NONE, getResources() .getString(R.string.jv_results_delete_dir)); - // "Cancel" - menu.add(Menu.NONE, CNTXT_MENU_CANCEL, Menu.NONE, getResources() - .getString(R.string.jv_results_cancel)); } else if (listName.equals("favorites")) { if (pos > 0) // "Move one position up" - menu.add(Menu.NONE, CNTXT_MENU_MOVEUP, Menu.NONE, - getResources().getString(R.string.jv_results_move_up)); + menu.add(Menu.NONE, CNTXT_MENU_MOVEUP, Menu.NONE,getResources().getString(R.string.jv_results_move_up)); if (pos < (itemsArray.size() - 1)) // "Move one position down" - menu.add(Menu.NONE, CNTXT_MENU_MOVEDOWN, Menu.NONE, - getResources().getString(R.string.jv_results_move_down)); + menu.add(Menu.NONE, CNTXT_MENU_MOVEDOWN, Menu.NONE,getResources().getString(R.string.jv_results_move_down)); // "Remove from favorites" menu.add(Menu.NONE, CNTXT_MENU_RMFAV, Menu.NONE, getResources() .getString(R.string.jv_results_remove)); @@ -1182,28 +1001,21 @@ public void onCreateContextMenu(ContextMenu menu, View v, Menu.NONE, getResources().getString( R.string.jv_results_delete_file)); - // "Cancel" - menu.add(Menu.NONE, CNTXT_MENU_CANCEL, Menu.NONE, getResources() - .getString(R.string.jv_results_cancel)); } else if (listName.equals("lastOpened")) { if (app.history.containsKey(fullName)) { if (app.history.get(fullName) == app.READING) // "Mark as read" - menu.add(Menu.NONE, CNTXT_MENU_MARK_FINISHED, Menu.NONE, - getResources().getString(R.string.jv_results_mark)); + menu.add(Menu.NONE, CNTXT_MENU_MARK_FINISHED, Menu.NONE,getResources().getString(R.string.jv_results_mark)); else if (app.history.get(fullName) == app.FINISHED) // "Remove \"read\" mark" - menu.add(Menu.NONE, CNTXT_MENU_MARK_READING, Menu.NONE, - getResources() + menu.add(Menu.NONE, CNTXT_MENU_MARK_READING, Menu.NONE,getResources() .getString(R.string.jv_results_unmark)); // "Forget all marks" - menu.add(Menu.NONE, CNTXT_MENU_MARK_FORGET, Menu.NONE, - getResources() + menu.add(Menu.NONE, CNTXT_MENU_MARK_FORGET, Menu.NONE,getResources() .getString(R.string.jv_results_unmark_all)); } else // "Mark as read" - menu.add(Menu.NONE, CNTXT_MENU_MARK_FINISHED, Menu.NONE, - getResources().getString(R.string.jv_results_mark)); + menu.add(Menu.NONE, CNTXT_MENU_MARK_FINISHED, Menu.NONE,getResources().getString(R.string.jv_results_mark)); // "Delete file" if (prefs.getBoolean("useFileManagerFunctions", true)) menu.add( @@ -1212,36 +1024,31 @@ else if (app.history.get(fullName) == app.FINISHED) Menu.NONE, getResources().getString( R.string.jv_results_delete_file)); - // "Cancel" - menu.add(Menu.NONE, CNTXT_MENU_CANCEL, Menu.NONE, getResources() - .getString(R.string.jv_results_cancel)); + + // "Open dir" + menu.add(Menu.NONE, CNTXT_MENU_OPEN_DIR, Menu.NONE, getResources().getString(R.string.jv_open_dir)); } else if (listName.equals("searchResults")) { - if (pos > 0) + if (pos > 0){ // "Move one position up" - menu.add(Menu.NONE, CNTXT_MENU_MOVEUP, Menu.NONE, - getResources().getString(R.string.jv_results_move_up)); + menu.add(Menu.NONE, CNTXT_MENU_MOVEUP, Menu.NONE,getResources().getString(R.string.jv_results_move_up)); + } if (pos < (itemsArray.size() - 1)) // "Move one position down" - menu.add(Menu.NONE, CNTXT_MENU_MOVEDOWN, Menu.NONE, - getResources().getString(R.string.jv_results_move_down)); + menu.add(Menu.NONE, CNTXT_MENU_MOVEDOWN, Menu.NONE,getResources().getString(R.string.jv_results_move_down)); if (app.history.containsKey(fullName)) { if (app.history.get(fullName) == app.READING) // "Mark as read" - menu.add(Menu.NONE, CNTXT_MENU_MARK_FINISHED, Menu.NONE, - getResources().getString(R.string.jv_results_mark)); + menu.add(Menu.NONE, CNTXT_MENU_MARK_FINISHED, Menu.NONE,getResources().getString(R.string.jv_results_mark)); else if (app.history.get(fullName) == app.FINISHED) // "Remove \"read\" mark" - menu.add(Menu.NONE, CNTXT_MENU_MARK_READING, Menu.NONE, - getResources() + menu.add(Menu.NONE, CNTXT_MENU_MARK_READING, Menu.NONE,getResources() .getString(R.string.jv_results_unmark)); // "Forget all marks" - menu.add(Menu.NONE, CNTXT_MENU_MARK_FORGET, Menu.NONE, - getResources() + menu.add(Menu.NONE, CNTXT_MENU_MARK_FORGET, Menu.NONE,getResources() .getString(R.string.jv_results_unmark_all)); } else // "Mark as read" - menu.add(Menu.NONE, CNTXT_MENU_MARK_FINISHED, Menu.NONE, - getResources().getString(R.string.jv_results_mark)); + menu.add(Menu.NONE, CNTXT_MENU_MARK_FINISHED, Menu.NONE,getResources().getString(R.string.jv_results_mark)); // "Delete file" if (prefs.getBoolean("useFileManagerFunctions", true)) menu.add( @@ -1250,10 +1057,10 @@ else if (app.history.get(fullName) == app.FINISHED) Menu.NONE, getResources().getString( R.string.jv_results_delete_file)); - // "Cancel" - menu.add(Menu.NONE, CNTXT_MENU_CANCEL, Menu.NONE, getResources() - .getString(R.string.jv_results_cancel)); + } + // "Cancel" + menu.add(Menu.NONE, CNTXT_MENU_CANCEL, Menu.NONE, getResources().getString(R.string.app_cancel)); } @Override @@ -1261,8 +1068,10 @@ public boolean onContextItemSelected(MenuItem item) { if (item.getItemId() == CNTXT_MENU_CANCEL) return true; - AdapterContextMenuInfo info = (AdapterContextMenuInfo) item - .getMenuInfo(); + AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); + if(info == null){ + return false; + } final int pos = info.position; HashMap i = itemsArray.get(pos); final String dname = i.get("dname"); @@ -1346,7 +1155,7 @@ public boolean onContextItemSelected(MenuItem item) { R.string.jv_results_delete_file_text2)); // "Yes" builder.setPositiveButton( - getResources().getString(R.string.jv_results_yes), + getResources().getString(R.string.app_yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -1359,7 +1168,7 @@ public void onClick(DialogInterface dialog, }); // "No" builder.setNegativeButton( - getResources().getString(R.string.jv_results_no), + getResources().getString(R.string.app_no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -1392,7 +1201,7 @@ public void onClick(DialogInterface dialog, R.string.jv_results_delete_em_dir_text2)); // "Yes" builder.setPositiveButton( - getResources().getString(R.string.jv_results_yes), + getResources().getString(R.string.app_yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -1405,7 +1214,7 @@ public void onClick(DialogInterface dialog, }); // "No" builder.setNegativeButton( - getResources().getString(R.string.jv_results_no), + getResources().getString(R.string.app_no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -1434,7 +1243,7 @@ public void onClick(DialogInterface dialog, R.string.jv_results_delete_ne_dir_text2)); // "Yes" builder.setPositiveButton( - getResources().getString(R.string.jv_results_yes), + getResources().getString(R.string.app_yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -1447,7 +1256,7 @@ public void onClick(DialogInterface dialog, }); // "No" builder.setNegativeButton( - getResources().getString(R.string.jv_results_no), + getResources().getString(R.string.app_no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -1461,23 +1270,236 @@ public void onClick(DialogInterface dialog, } } break; + case CNTXT_MENU_OPEN_DIR: + Intent intent = new Intent(ResultsActivity.this,ReLaunch.class); + intent.putExtra("start_dir", dname); + intent.putExtra("home", ReLaunch.useHome); + intent.putExtra("home1", ReLaunch.useHome1); + oldHome = ReLaunch.useHome; + startActivityForResult(intent, ReLaunch.DIR_ACT); + break; + case CNTXT_MENU_ADD_OPDS: + AlertDialog.Builder builder = new AlertDialog.Builder(this); + builder.setTitle(getResources().getString(R.string.jv_results_add_opds)); + + // редактируемые поля + final EditText inputName = new EditText(this); // Имя. Уникальное + final EditText inputAddress = new EditText(this); // Адрес + final EditText inputLogin = new EditText(this); // Имя пользователя для доступа + final EditText inputPassword = new EditText(this); // Пароль + final CheckBox checkBox = new CheckBox(this); + checkBox.setText(getResources().getString(R.string.jv_results_checkbox_opds)); + + // Заголовки полей + TextView tAddress = new TextView(this); + TextView tName = new TextView(this); + final TextView tLogin = new TextView(this); + final TextView tPassword = new TextView(this); + // Заполняем заголовки + tAddress.setText(getResources().getString(R.string.jv_results_addres_opds)); + tName.setText(getResources().getString(R.string.jv_results_name_opds)); + tLogin.setText(getResources().getString(R.string.jv_results_login_opds)); + tPassword.setText(getResources().getString(R.string.jv_results_pass_opds)); + // предварительно отключаем поля + tLogin.setEnabled(false); + tPassword.setEnabled(false); + inputLogin.setEnabled(false); + inputPassword.setEnabled(false); + // при клике на чекбоксе изменяем доступность полей + checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { + @Override + public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) { + if(checkBox.isChecked()){ + tLogin.setEnabled(true); + tPassword.setEnabled(true); + inputLogin.setEnabled(true); + inputPassword.setEnabled(true); + }else{ + tLogin.setEnabled(false); + tPassword.setEnabled(false); + inputLogin.setEnabled(false); + inputPassword.setEnabled(false); + } + } + }); + // начинаем заполнять форму + LinearLayout ll=new LinearLayout(this); + ll.setOrientation(LinearLayout.VERTICAL);// вертивальное расположение элементов + // имя + ll.addView(tName); + ll.addView(inputName); + // адрес + ll.addView(tAddress); + ll.addView(inputAddress); + // чекбокс + ll.addView(checkBox); + // имя пользователя + ll.addView(tLogin); + + ll.addView(inputLogin); + // пароль + ll.addView(tPassword); + ll.addView(inputPassword); + builder.setView(ll); + + // "Yes" + builder.setPositiveButton(getResources().getString(R.string.app_yes), + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int whichButton) { + // добавление в базу данных + addDbOPDS(String.valueOf(inputName.getText()), + String.valueOf(inputAddress.getText()), + checkBox.isChecked(), + String.valueOf(inputLogin.getText()), + String.valueOf(inputPassword.getText())); + createItemsArray(); + } + }); + // "No" + builder.setNegativeButton( + getResources().getString(R.string.app_no), + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, + int whichButton) { + dialog.dismiss(); + } + }); + builder.show(); + break; + case CNTXT_MENU_EDIT_OPDS: + AlertDialog.Builder builder2 = new AlertDialog.Builder(this); + builder2.setTitle(getResources().getString(R.string.jv_results_add_opds)); + + // редактируемые поля + final EditText inputName2 = new EditText(this); // Имя. Уникальное + final EditText inputAddress2 = new EditText(this); // Адрес + final EditText inputLogin2 = new EditText(this); // Имя пользователя для доступа + final EditText inputPassword2 = new EditText(this); // Пароль + final CheckBox checkBox2 = new CheckBox(this); + checkBox2.setText(getResources().getString(R.string.jv_results_checkbox_opds)); + // Заголовки полей + TextView tAddress2 = new TextView(this); + TextView tName2 = new TextView(this); + final TextView tLogin2 = new TextView(this); + final TextView tPassword2 = new TextView(this); + // Заполняем заголовки + tAddress2.setText(getResources().getString(R.string.jv_results_addres_opds)); + tName2.setText(getResources().getString(R.string.jv_results_name_opds)); + tLogin2.setText(getResources().getString(R.string.jv_results_login_opds)); + tPassword2.setText(getResources().getString(R.string.jv_results_pass_opds)); + // заполняем поля из базы + inputAddress2.setText(dname); + inputName2.setText(fname); + if(i.get("check").equals("1")){ + checkBox2.setChecked(true); + inputLogin2.setText(i.get("login")); + inputPassword2.setText(i.get("password")); + tLogin2.setEnabled(true); + tPassword2.setEnabled(true); + inputLogin2.setEnabled(true); + inputPassword2.setEnabled(true); + }else{ + checkBox2.setChecked(false); + tLogin2.setEnabled(false); + tPassword2.setEnabled(false); + inputLogin2.setEnabled(false); + inputPassword2.setEnabled(false); + } + + // при клике на чекбоксе изменяем доступность полей + checkBox2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { + @Override + public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) { + if(checkBox2.isChecked()){ + tLogin2.setEnabled(true); + tPassword2.setEnabled(true); + inputLogin2.setEnabled(true); + inputPassword2.setEnabled(true); + }else{ + tLogin2.setEnabled(false); + tPassword2.setEnabled(false); + inputLogin2.setText(""); + inputLogin2.setEnabled(false); + inputPassword2.setText(""); + inputPassword2.setEnabled(false); + } + } + }); + // начинаем заполнять форму + LinearLayout ll2=new LinearLayout(this); + ll2.setOrientation(LinearLayout.VERTICAL);// вертивальное расположение элементов + // имя + ll2.addView(tName2); + ll2.addView(inputName2); + // адрес + ll2.addView(tAddress2); + ll2.addView(inputAddress2); + // чекбокс + ll2.addView(checkBox2); + // имя пользователя + ll2.addView(tLogin2); + + ll2.addView(inputLogin2); + // пароль + ll2.addView(tPassword2); + ll2.addView(inputPassword2); + // отрисовываем + builder2.setView(ll2); + + // "Yes" + builder2.setPositiveButton(getResources().getString(R.string.app_yes), + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int whichButton) { + // обновление базы + updateDbOPDS(fname, + String.valueOf(inputName2.getText()), + String.valueOf(inputAddress2.getText()), + checkBox2.isChecked(), + String.valueOf(inputLogin2.getText()), + String.valueOf(inputPassword2.getText())); + createItemsArray(); + } + }); + // "No" + builder2.setNegativeButton( + getResources().getString(R.string.app_no), + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, + int whichButton) { + dialog.dismiss(); + } + }); + builder2.show(); + break; + case CNTXT_MENU_DEL_OPDS: + // удаление из базы + delDbOPDS(fname); + createItemsArray(); + break; + case CNTXT_MENU_CLEAN_OPDS: + // очистка базы + db = dbHelper.getWritableDatabase(); + db.execSQL("delete from OPDS1"); + db.execSQL("reindex INDEXopds"); + db.close(); + createItemsArray(); + break; } return true; } @Override protected void onResume() { - setEinkController(); + EinkScreen.setEinkController(prefs); super.onResume(); - app.generalOnResume(TAG, this); + app.generalOnResume(TAG); } private String getEbookName(String dir, String file) { EBook eBook; if ((!file.endsWith("fb2")) && (!file.endsWith("fb2.zip")) &&(!file.endsWith("epub"))) return file; - String fileName = dir + "/" + file; - eBook = app.dataBase.getBookByFileName(dir + "/" + file); + eBook = app.dataBase.getBookByFileName(dir + "/" + file); if (eBook.isOk) { String output = prefs.getString("bookTitleFormat", "[%a. ]%t"); if (eBook.authors.size() > 0) { @@ -1505,4 +1527,155 @@ private String getEbookName(String dir, String file) { } else return file; } + + private class imageIcon { + String nameIcon; + Bitmap icon; + } + + private void loadStandartIcons() { + // иконки для файлов заранее заносим в массив======================== + imageIcon temp_icon = new imageIcon(); + temp_icon.icon = scaleDrawableById(R.drawable.dir_ok, firstLineIconSizePx); + temp_icon.nameIcon = "dir_ok"; + arrIcon.add(temp_icon); + temp_icon = new imageIcon(); + temp_icon.icon = scaleDrawableById(R.drawable.file_ok, firstLineIconSizePx); + temp_icon.nameIcon = "file_ok"; + arrIcon.add(temp_icon); + temp_icon = new imageIcon(); + temp_icon.icon = scaleDrawableById(R.drawable.file_notok, firstLineIconSizePx); + temp_icon.nameIcon = "file_notok"; + arrIcon.add(temp_icon); + temp_icon = new imageIcon(); + temp_icon.icon = scaleDrawableById(R.drawable.icon, firstLineIconSizePx); + temp_icon.nameIcon = "icon"; + arrIcon.add(temp_icon); + temp_icon = new imageIcon(); + temp_icon.nameIcon = "opdslist"; + temp_icon.icon = scaleDrawableById(R.drawable.ci_books, firstLineIconSizePx); + arrIcon.add(temp_icon); + } + + private void dbOPDS(){ + db = dbHelper.getReadableDatabase(); + + // делаем запрос данных из таблицы , получаем Cursor + Cursor c = db.query("OPDS1", null, null, null, null, null, null); + Button rt = (Button) findViewById(R.id.results_title); + if (total == -1){ + rt.setText(title + " (" + c.getCount() + ")"); + }else{ + rt.setText(title + " (" + c.getCount() + "/"+ total + ")"); + } + // ставим позицию курсора на первую строку выборки + // если в выборке нет строк, вернется false + if (c.moveToFirst()) { + // определяем номера столбцов по имени в выборке + int titleColIndex = c.getColumnIndex("TITLE"); + int ureColIndex = c.getColumnIndex("URE"); + int loginColIndex = c.getColumnIndex("LOGIN"); + int passColIndex = c.getColumnIndex("PASSWORD"); + int checkColIndex = c.getColumnIndex("EN_PASS"); + + do { + HashMap item = new HashMap(); + item.put("dname", c.getString(ureColIndex)); + item.put("fname", c.getString(titleColIndex)); + item.put("sname", c.getString(titleColIndex)); + item.put("login", c.getString(loginColIndex)); + item.put("password", c.getString(passColIndex)); + item.put("check", String.valueOf(c.getInt(checkColIndex))); + item.put("nameIcon", "opdslist"); // тип - файл + itemsArray.add(item); + // переход на следующую строку + // а если следующей нет (текущая - последняя), то false - выходим из цикла + } while (c.moveToNext()); + } + c.close(); + db.close(); + } + + private void addDbOPDS(String titleColIndex, String ureColIndex, Boolean en_passColIndex, String loginColIndex, String passwordColIndex){ + // создаем объект для данных + ContentValues cv = new ContentValues(); + + // подключаемся к БД + db = dbHelper.getWritableDatabase(); + + cv.put("TITLE", titleColIndex); + cv.put("URE", ureColIndex); + cv.put("EN_PASS", en_passColIndex); + if(en_passColIndex){ + cv.put("LOGIN", loginColIndex); + cv.put("PASSWORD", passwordColIndex); + }else{ + cv.put("LOGIN", " "); + cv.put("PASSWORD", " "); + } + + // вставляем запись и получаем ее ID + db.insert("OPDS1", null, cv); + + db.close(); + } + private void updateDbOPDS(String oldtitleColIndex, String titleColIndex, String ureColIndex, Boolean en_passColIndex, String loginColIndex, String passwordColIndex){ + // создаем объект для данных + ContentValues cv = new ContentValues(); + + // подключаемся к БД + db = dbHelper.getWritableDatabase(); + + cv.put("TITLE", titleColIndex); + cv.put("URE", ureColIndex); + cv.put("EN_PASS", en_passColIndex); + if(en_passColIndex){ + cv.put("LOGIN", loginColIndex); + cv.put("PASSWORD", passwordColIndex); + }else{ + cv.put("LOGIN", ""); + cv.put("PASSWORD", ""); + } + + // вставляем запись и получаем ее ID + db.update("OPDS1", cv, "TITLE = ?", new String[]{oldtitleColIndex}); + + db.close(); + } + + private void delDbOPDS(String titleColIndex){ + // подключаемся к БД + db = dbHelper.getWritableDatabase(); + db.delete("OPDS1", "TITLE = ?" ,new String[]{titleColIndex}); + + db.close(); + } + + public class DBHelper extends SQLiteOpenHelper { + private static final String DATABASE_NAME = "opde_database.db"; + private static final int DATABASE_VERSION = 1; + public DBHelper(Context context) { + // конструктор суперкласса + super(context, DATABASE_NAME, null, DATABASE_VERSION); + } + + @Override + public void onCreate(SQLiteDatabase db) { + Log.d(TAG, "--- onCreate database ---"); + // создаем таблицу с полями + db.execSQL("create table if not exists OPDS1 (" + + "ID integer primary key autoincrement, " + + "TITLE text unique, " + + "URE text default '', " + + "EN_PASS boolean default 'false', " + + "LOGIN text default '', " + + "PASSWORD text default '') "); + db.execSQL("create index if not exists INDEXopds on OPDS1(TITLE)"); + } + + @Override + public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { + + } + } } diff --git a/src/com/harasoft/relaunch/SearchActivity.java b/src/com/harasoft/relaunch/SearchActivity.java index d687c4b..c39eb8f 100644 --- a/src/com/harasoft/relaunch/SearchActivity.java +++ b/src/com/harasoft/relaunch/SearchActivity.java @@ -66,7 +66,7 @@ private void resetSearch() { pd.setCancelable(true); // "Cancel" pd.setButton(ProgressDialog.BUTTON_NEGATIVE, - getResources().getString(R.string.jv_search_cancel), + getResources().getString(R.string.app_cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { stop_search = true; @@ -268,12 +268,10 @@ public int compare(String[] o1, String[] o2) { Collections.sort(searchResults, o1c); } app.setList("searchResults", searchResults); - Intent intent = new Intent(SearchActivity.this, - ResultsActivity.class); + Intent intent = new Intent(SearchActivity.this,ResultsActivity.class); intent.putExtra("list", "searchResults"); // "Search results" - intent.putExtra("title", - getResources().getString(R.string.jv_search_results)); + intent.putExtra("title",getResources().getString(R.string.jv_search_results)); intent.putExtra("rereadOnStart", false); intent.putExtra("total", filesCount); startActivity(intent); @@ -399,7 +397,7 @@ protected void onResume() { super.onResume(); searchAs.setSelection(prefs.getInt("searchAs", 0), false); searchIn.setSelection(prefs.getInt("searchIn", 0), false); - app.generalOnResume(TAG, this); + app.generalOnResume(TAG); } @Override diff --git a/src/com/harasoft/relaunch/Shop.java b/src/com/harasoft/relaunch/Shop.java deleted file mode 100644 index 246226c..0000000 --- a/src/com/harasoft/relaunch/Shop.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.harasoft.relaunch; - -import android.app.Activity; -import android.app.PendingIntent; -import android.content.Intent; -import android.os.Bundle; - -public class Shop extends Activity { - final String TAG = "Shop"; - ReLaunchApp app; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - app = ((ReLaunchApp) getApplicationContext()); - app.RestartIntent = PendingIntent.getActivity(this, 0, getIntent(), - getIntent().getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK); - - Intent intent = new Intent(Shop.this, ReLaunch.class); - intent.putExtra("home", false); - intent.putExtra("home1", false); - intent.putExtra("shop", true); - intent.putExtra("library", false); - intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); - startActivityForResult(intent, 0); - } - - @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) { - finish(); - } -} diff --git a/src/com/harasoft/relaunch/TaskManager.java b/src/com/harasoft/relaunch/TaskManager.java index 9c77156..3f26545 100644 --- a/src/com/harasoft/relaunch/TaskManager.java +++ b/src/com/harasoft/relaunch/TaskManager.java @@ -1,14 +1,5 @@ package com.harasoft.relaunch; -import java.io.BufferedReader; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; import android.app.Activity; import android.app.ActivityManager; import android.app.Dialog; @@ -28,18 +19,16 @@ import android.text.style.StyleSpan; import android.view.LayoutInflater; import android.view.View; +import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.WindowManager; -import android.view.View.OnClickListener; -import android.widget.AbsListView; -import android.widget.ArrayAdapter; -import android.widget.Button; -import android.widget.EditText; -import android.widget.ImageButton; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.ListView; -import android.widget.TextView; +import android.widget.*; + +import java.io.BufferedReader; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.*; public class TaskManager extends Activity { final String TAG = "TaskManager"; @@ -136,37 +125,8 @@ static class PInfo { List newServ; HashMap newPinfo; - private void setEinkController() { - if (prefs != null) { - Integer einkUpdateMode = 1; - try { - einkUpdateMode = Integer.parseInt(prefs.getString( - "einkUpdateMode", "1")); - } catch (Exception e) { - einkUpdateMode = 1; - } - if (einkUpdateMode < -1 || einkUpdateMode > 2) - einkUpdateMode = 1; - if (einkUpdateMode >= 0) { - EinkScreen.UpdateMode = einkUpdateMode; - - Integer einkUpdateInterval = 10; - try { - einkUpdateInterval = Integer.parseInt(prefs.getString( - "einkUpdateInterval", "10")); - } catch (Exception e) { - einkUpdateInterval = 10; - } - if (einkUpdateInterval < 0 || einkUpdateInterval > 100) - einkUpdateInterval = 10; - EinkScreen.UpdateModeInterval = einkUpdateInterval; - EinkScreen.PrepareController(null, false); - } - } - } - - public class cpuComparator implements java.util.Comparator { + public class cpuComparator implements Comparator { public int compare(Integer o1, Integer o2) { PInfo p1 = pinfo.get(o1); PInfo p2 = pinfo.get(o2); @@ -186,7 +146,7 @@ public int compare(Integer o1, Integer o2) { } } - public class sizeComparator implements java.util.Comparator { + public class sizeComparator implements Comparator { public int compare(Integer o1, Integer o2) { PInfo p1 = pinfo.get(o1); PInfo p2 = pinfo.get(o2); @@ -202,7 +162,7 @@ public int compare(Integer o1, Integer o2) { } } - public class abcComparator implements java.util.Comparator { + public class abcComparator implements Comparator { public int compare(Integer o1, Integer o2) { PInfo p1 = pinfo.get(o1); PInfo p2 = pinfo.get(o2); @@ -525,7 +485,7 @@ protected void onPostExecute(String result) { taskPids = newTask; servPids = newServ; sortLists(); - setEinkController(); + EinkScreen.PrepareController(null, false); adapter_t.notifyDataSetChanged(); adapter_s.notifyDataSetChanged(); @@ -656,13 +616,13 @@ public View getView(int position, View convertView, ViewGroup parent) { ((TextView) dialog.findViewById(R.id.tm1_name)).setText(p.name); ((TextView) dialog.findViewById(R.id.tm1_extra)).setText(p.extra); ((Button) dialog.findViewById(R.id.tm1_ok)) - .setOnClickListener(new View.OnClickListener() { + .setOnClickListener(new OnClickListener() { public void onClick(View v) { dialog.dismiss(); } }); Button killBtn = (Button) dialog.findViewById(R.id.tm1_kill); - killBtn.setOnClickListener(new View.OnClickListener() { + killBtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { try { ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE); @@ -727,13 +687,13 @@ private void showServiceDetails(Integer pid) { .setText(p.clientLabel); ((TextView) dialog.findViewById(R.id.tm2_clientd)).setText(p.descr); ((Button) dialog.findViewById(R.id.tm2_ok)) - .setOnClickListener(new View.OnClickListener() { + .setOnClickListener(new OnClickListener() { public void onClick(View v) { dialog.dismiss(); } }); Button killBtn = (Button) dialog.findViewById(R.id.tm2_kill); - killBtn.setOnClickListener(new View.OnClickListener() { + killBtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { try { ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE); @@ -1005,7 +965,7 @@ protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); - setEinkController(); + EinkScreen.setEinkController(prefs); app = ((ReLaunchApp) getApplicationContext()); app.setFullScreenIfNecessary(this); @@ -1052,8 +1012,8 @@ public void onScroll(AbsListView view, sv.total = totalItemCount; sv.count = visibleItemCount; sv.first = firstVisibleItem; - setEinkController(); - sv.invalidate(); + EinkScreen.PrepareController(null, false); + sv.invalidate(); } public void onScrollStateChanged(AbsListView view, @@ -1077,8 +1037,12 @@ public void onScroll(AbsListView view, sv.total = totalItemCount; sv.count = visibleItemCount; sv.first = firstVisibleItem; - setEinkController(); - sv.invalidate(); + if(N2DeviceInfo.EINK_ONYX){ + EinkScreen.PrepareController(sv, false); + }else{ + EinkScreen.PrepareController(null, false); + sv.invalidate(); + } } public void onScrollStateChanged(AbsListView view, @@ -1091,7 +1055,7 @@ public void onScrollStateChanged(AbsListView view, lv_t.setOnScrollListener(new AbsListView.OnScrollListener() { public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { - setEinkController(); + EinkScreen.PrepareController(null, false); } public void onScrollStateChanged(AbsListView view, @@ -1101,7 +1065,7 @@ public void onScrollStateChanged(AbsListView view, lv_s.setOnScrollListener(new AbsListView.OnScrollListener() { public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { - setEinkController(); + EinkScreen.PrepareController(null, false); } public void onScrollStateChanged(AbsListView view, @@ -1128,25 +1092,25 @@ public void onScrollStateChanged(AbsListView view, tasks_title = (TextView) findViewById(R.id.tm_tasks_title); serv_title = (TextView) findViewById(R.id.tm_services_title); ((ImageButton) findViewById(R.id.tm_back)) - .setOnClickListener(new View.OnClickListener() { + .setOnClickListener(new OnClickListener() { public void onClick(View v) { finish(); } }); sortSizeBtn = (Button) findViewById(R.id.sort_size); - sortSizeBtn.setOnClickListener(new View.OnClickListener() { + sortSizeBtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { setSorting(sortSize); } }); sortCpuBtn = (Button) findViewById(R.id.sort_cpu); - sortCpuBtn.setOnClickListener(new View.OnClickListener() { + sortCpuBtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { setSorting(sortCpu); } }); sortAbcBtn = (Button) findViewById(R.id.sort_abc); - sortAbcBtn.setOnClickListener(new View.OnClickListener() { + sortAbcBtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { setSorting(sortAbc); } @@ -1168,25 +1132,19 @@ protected void onPause() { stopCPUUpdate(); } - @Override - protected void onRestart() { - super.onRestart(); - setEinkController(); - startCPUUpdate(); - } @Override protected void onResume() { super.onResume(); - setEinkController(); + EinkScreen.setEinkController(prefs); startCPUUpdate(); - app.generalOnResume(TAG, this); + app.generalOnResume(TAG); } @Override protected void onStart() { super.onStart(); - setEinkController(); + EinkScreen.setEinkController(prefs); startCPUUpdate(); } diff --git a/src/com/harasoft/relaunch/TypesActivity.java b/src/com/harasoft/relaunch/TypesActivity.java index f24b806..b0eaa53 100644 --- a/src/com/harasoft/relaunch/TypesActivity.java +++ b/src/com/harasoft/relaunch/TypesActivity.java @@ -9,7 +9,6 @@ import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; -import android.content.pm.PackageManager; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.preference.PreferenceManager; @@ -29,7 +28,7 @@ public class TypesActivity extends Activity { final String TAG = "Types"; final String INTENT_PREFIX = "Intent:"; HashMap icons; - PackageManager pm; + List applicationsArray; CharSequence[] applications; CharSequence[] happlications; @@ -57,12 +56,10 @@ public long getItemId(int position) { return 0; } - public View getView(final int position, View convertView, - ViewGroup parent) { + public View getView(final int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { - LayoutInflater vi = (LayoutInflater) getApplicationContext() - .getSystemService(Context.LAYOUT_INFLATER_SERVICE); + LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.types_layout, null); } final HashMap item = itemsArray.get(position); @@ -72,12 +69,10 @@ public View getView(final int position, View convertView, // Setting up button ImageButton upBtn = (ImageButton) v.findViewById(R.id.types_up); if (position == 0) { - upBtn.setImageDrawable(getResources().getDrawable( - android.R.drawable.checkbox_off_background)); + upBtn.setImageDrawable(getResources().getDrawable(android.R.drawable.checkbox_off_background)); upBtn.setEnabled(false); } else { - upBtn.setImageDrawable(getResources().getDrawable( - R.drawable.ci_arrowup)); + upBtn.setImageDrawable(getResources().getDrawable(R.drawable.ci_arrowup)); upBtn.setEnabled(true); } upBtn.setOnClickListener(new View.OnClickListener() { @@ -90,15 +85,12 @@ public void onClick(View v) { }); // Setting down button - ImageButton downBtn = (ImageButton) v - .findViewById(R.id.types_down); + ImageButton downBtn = (ImageButton) v.findViewById(R.id.types_down); if (position == (itemsArray.size() - 1)) { - downBtn.setImageDrawable(getResources().getDrawable( - android.R.drawable.checkbox_off_background)); + downBtn.setImageDrawable(getResources().getDrawable(android.R.drawable.checkbox_off_background)); downBtn.setEnabled(false); } else { - downBtn.setImageDrawable(getResources().getDrawable( - R.drawable.ci_arrowdown)); + downBtn.setImageDrawable(getResources().getDrawable(R.drawable.ci_arrowdown)); downBtn.setEnabled(true); } downBtn.setOnClickListener(new View.OnClickListener() { @@ -111,8 +103,7 @@ public void onClick(View v) { }); // Setting remove button - ImageButton rmBtn = (ImageButton) v - .findViewById(R.id.types_delete); + ImageButton rmBtn = (ImageButton) v.findViewById(R.id.types_delete); rmBtn.setEnabled(itemsArray.size() > 1); rmBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { @@ -122,8 +113,7 @@ public void onClick(View v) { }); // Setting extension title - TextView ext_title = (TextView) v - .findViewById(R.id.types_ext_title); + TextView ext_title = (TextView) v.findViewById(R.id.types_ext_title); // "Suffix (" + (position+1) + "/" + (itemsArray.size()) + ")" ext_title.setText(getResources().getString( R.string.jv_types_suffix) @@ -150,12 +140,11 @@ public void onClick(View v) { // "Ok" builder.setPositiveButton( - getResources().getString(R.string.jv_types_ok), + getResources().getString(R.string.app_ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { - String value = input.getText() - .toString(); + String value = String.valueOf(input.getText()); if (value.equals("")) // "Can't be empty!" Toast.makeText( @@ -176,7 +165,7 @@ public void onClick(DialogInterface dialog, // "Cancel" builder.setNegativeButton( getResources().getString( - R.string.jv_types_cancel), + R.string.app_cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -197,12 +186,11 @@ public void onClick(DialogInterface dialog, } else { appName.setText(app); } - if (icons.containsKey(app)) - iv.setImageDrawable(icons.get(app)); - else - iv.setImageDrawable(getResources().getDrawable( - R.drawable.icon)); - + if (icons.containsKey(app)) { + iv.setImageDrawable(icons.get(app)); + }else { + iv.setImageDrawable(getResources().getDrawable(R.drawable.icon)); + } appName.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { @@ -261,12 +249,10 @@ public void onClick(DialogInterface dialog, builder3.setTitle(getResources() .getString( R.string.jv_types_intent_type)); - final EditText input = new EditText( - cntx); + final EditText input = new EditText(cntx); String v = item.get("rdr"); if (v.startsWith(INTENT_PREFIX)) - v = v.substring(INTENT_PREFIX - .length()); + v = v.substring(INTENT_PREFIX.length()); else v = "application/"; input.setText(v); @@ -274,14 +260,12 @@ public void onClick(DialogInterface dialog, // "Ok" builder3.setPositiveButton( getResources().getString( - R.string.jv_types_ok), + R.string.app_ok), new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int whichButton) { - String value = input - .getText() - .toString(); + String value = String.valueOf(input.getText()); if (value.equals("")) // "Can't be empty!" Toast.makeText( @@ -304,10 +288,7 @@ public void onClick( }); // "Cancel" - builder3.setNegativeButton( - getResources() - .getString( - R.string.jv_types_cancel), + builder3.setNegativeButton(getResources().getString(R.string.app_cancel), new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, @@ -321,16 +302,12 @@ public void onClick( }); // "Cancel" - builder1.setNegativeButton( - getResources().getString( - R.string.jv_types_cancel), + builder1.setNegativeButton(getResources().getString(R.string.app_cancel), new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, - int which) { + public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); - builder1.show(); } }); @@ -429,6 +406,6 @@ public void onClick(View v) { @Override protected void onResume() { super.onResume(); - app.generalOnResume(TAG, this); + app.generalOnResume(TAG); } } diff --git a/src/com/harasoft/relaunch/Viewer.java b/src/com/harasoft/relaunch/Viewer.java index d28e990..efc358e 100644 --- a/src/com/harasoft/relaunch/Viewer.java +++ b/src/com/harasoft/relaunch/Viewer.java @@ -53,6 +53,7 @@ private boolean rereadFile(String fname, EditText editTxt) { try { br.close(); } catch (IOException e) { + // } // Set text @@ -111,7 +112,7 @@ protected void onCreate(Bundle savedInstanceState) { + getResources().getString(R.string.jv_viewer_bytes)); // "OK" builder.setPositiveButton( - getResources().getString(R.string.jv_viewer_ok), + getResources().getString(R.string.app_ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -155,7 +156,7 @@ public void onClick(View v) { R.string.jv_editor_bytes)); // "OK" builder.setPositiveButton( - getResources().getString(R.string.jv_viewer_ok), + getResources().getString(R.string.app_ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -198,14 +199,12 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) { case EDITOR_ACT: rereadFile(fileName, editTxt); break; - default: - return; } } @Override protected void onResume() { super.onResume(); - app.generalOnResume(TAG, this); + app.generalOnResume(TAG); } } diff --git a/src/ebook/EBook.java b/src/ebook/EBook.java new file mode 100644 index 0000000..d9a896f --- /dev/null +++ b/src/ebook/EBook.java @@ -0,0 +1,100 @@ +/* + * Copyright (C) 2011 Andrew Mochalov + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ +package ebook; + +import java.util.ArrayList; +import java.util.List; + +/** + * EBook - class that contains fields describing the parameters and + * properties of the e-book + */ +public class EBook { + /** + * True, if the processing of the e-book was successful. + * False if the e-book could not be processed. + */ + public boolean isOk; + /** + * The name of the file containing the processing e-book + */ + public String fileName; + /** + * The name of the internal format of the e-book + */ + public EBookFormat format; + /** + * List of authors of the e-book + */ + public ArrayList authors; + /** + * Title of the-ebook + */ + public String title; + /** + * Genre of the book according to fb2 format + */ + public List fb2Genres; + /** + * Genre of the book according to ePub format + */ + public List epubGenres; + /** + * the language in which the e-book was published + */ + public String language; + /** + * the language of the e-book source + */ + public String srcLanguage; + /** + * List of translators of the e-book + */ + public ArrayList translators; + /** + * The name of the series, which includes the e-book + */ + public String sequenceName; + /** + * Serial number of the e-book in the series + */ + public String sequenceNumber; + /** + * Charset of the e-book text + */ + public String encoding; + /** + * Brief summary of the e-book + */ + public String annotation; + /** + * Picture of e-book cover + */ + public byte[] cover; + public boolean doExtractCover; + /** + * The class constructor, fills the fields with null values + */ + public EBook() { + this.authors = new ArrayList(3); + this.fb2Genres = new ArrayList(2); + this.epubGenres = new ArrayList(2); + this.translators = new ArrayList(2); + this.isOk = false; + } +} diff --git a/src/ebook/EBookFormat.java b/src/ebook/EBookFormat.java new file mode 100644 index 0000000..4ce8b8a --- /dev/null +++ b/src/ebook/EBookFormat.java @@ -0,0 +1,38 @@ +/* + * Copyright (C) 2011 Andrew Mochalov + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ +package ebook; + +/** + * EBookFormat - Enumerations that contains a description of the format + * structure of the e-book + */ +public enum EBookFormat { + /** + * The format of the e-book is not supported in current version + */ + UNSUPPORTED, + /** + * Electronic publication - is a free and open e-book standard by + * the International Digital Publishing Forum (IDPF) + */ + EPUB, + /** + * FictionBook is an open XML-based e-book format. + */ + FB2 +} diff --git a/src/ebook/ParsingType.java b/src/ebook/ParsingType.java new file mode 100644 index 0000000..86e4ffd --- /dev/null +++ b/src/ebook/ParsingType.java @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2011 Andrew Mochalov + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ +package ebook; + +/** + *ParsingType - Enumeration, that contains kinds of processing of e-books + */ +public enum ParsingType { + /** + * Very fast processing is implemented on the use of regexp's + */ + INSTANT, + /** + * Not yet implemented + */ + FAST, + /** + * Not yet implemented + */ + FULL +} diff --git a/src/ebook/Person.java b/src/ebook/Person.java new file mode 100644 index 0000000..e66c9ca --- /dev/null +++ b/src/ebook/Person.java @@ -0,0 +1,71 @@ +/* + * Copyright (C) 2011 Andrew Mochalov + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ +package ebook; + +/** + * Class containing the data of the person, the author or translator + */ +public class Person { + /** + * Last name of the person + */ + public String lastName; + /** + * First name of the person + */ + public String firstName; + /** + * Middle name of the person + */ + public String middleName; + /** + * Nick name of the person + */ + public String nickName; + + /** + * The class constructor, fills the fields with null values. + */ + public Person() { + lastName = firstName = middleName = nickName= null; + } + + /** + * The class constructor, fills the fields from parsing person + * full name + * @param name - The person full name + */ + public Person(String name) { + name.trim(); + String[] nameParts = name.split("[\\s]+"); + int count = nameParts.length; + if (count > 2) { + this.firstName = nameParts[0]; + this.lastName = nameParts[count - 1]; + this.middleName = ""; + for (int index = 1; index < count - 1; index++) { + this.middleName += nameParts[index]; + } + } else if (count == 2) { + this.firstName = nameParts[0]; + this.lastName = nameParts[count - 1]; + } else if (count == 1) { + this.lastName = nameParts[0]; + } + } +} diff --git a/src/ebook/parser/Base64Decoder.java b/src/ebook/parser/Base64Decoder.java new file mode 100644 index 0000000..4351b43 --- /dev/null +++ b/src/ebook/parser/Base64Decoder.java @@ -0,0 +1,113 @@ +package ebook.parser; +/* + * Copyright (C) 2012 Andrew Mochalov + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ +/** + * Base64Decoder + */ +class Base64Decoder { + private static byte[] charTable = new byte[256]; + private static boolean[] isValidSymbol = new boolean[256]; + + static { + for (int index = 0; index < 256; index++) { + charTable[index] = -1; + isValidSymbol[index] = false; + } + for (int index = 'A'; index <= 'Z'; index++) { + charTable[index] = (byte) (index - 'A'); + isValidSymbol[index] = true; + } + for (int index = 'a'; index <= 'z'; index++) { + charTable[index] = (byte) (index - 'a' + 26); + isValidSymbol[index] = true; + } + for (int index = '0'; index <= '9'; index++) { + charTable[index] = (byte) (index - '0' + 52); + isValidSymbol[index] = true; + } + charTable['+'] = 62; + isValidSymbol['+'] = true; + charTable['/'] = 63; + isValidSymbol['/'] = true; + isValidSymbol['='] = true; + } + + public static byte[] decode(byte[] input) { + byte[] data = purgeNonBase64(input); + if (data.length == 0) + return null; + int numberQuadruple = data.length / 4; + byte output[] = null; + byte b1 = 0, b2 = 0, b3 = 0, b4 = 0, marker0 = 0, marker1 = 0; + + int outIndex = 0; + int inIndex = 0; + { + int lastData = data.length; + while (data[lastData - 1] == '=') { + if (--lastData == 0) { + return new byte[0]; + } + } + output = new byte[lastData - numberQuadruple]; + } + + for (int i = 0; i < numberQuadruple; i++) { + inIndex = i * 4; + marker0 = data[inIndex + 2]; + marker1 = data[inIndex + 3]; + + b1 = charTable[data[inIndex]]; + b2 = charTable[data[inIndex + 1]]; + + if (marker0 != '=' && marker1 != '=') { + //No PAD e.g 3cQl + b3 = charTable[marker0]; + b4 = charTable[marker1]; + + output[outIndex] = (byte) (b1 << 2 | b2 >> 4); + output[outIndex + 1] = + (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); + output[outIndex + 2] = (byte) (b3 << 6 | b4); + } else if (marker0 == '=') { + output[outIndex] = (byte) (b1 << 2 | b2 >> 4); + } else if (marker1 == '=') { + b3 = charTable[marker0]; + + output[outIndex] = (byte) (b1 << 2 | b2 >> 4); + output[outIndex + 1] = + (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); + } + outIndex += 3; + } + return output; + } + + private static byte[] purgeNonBase64(byte[] input) { + byte clean[] = new byte[input.length]; + int counter = 0; + for (int i = 0; i < input.length; i++) { + if (isValidSymbol[input[i]]) { + clean[counter++] = input[i]; + } + } + byte output[] = new byte[counter]; + System.arraycopy(clean, 0, output, 0, counter); + return output; + } +} diff --git a/src/ebook/parser/EpubInstantParser.java b/src/ebook/parser/EpubInstantParser.java new file mode 100644 index 0000000..c73211a --- /dev/null +++ b/src/ebook/parser/EpubInstantParser.java @@ -0,0 +1,168 @@ +/* + * Copyright (C) 2011 Andrew Mochalov + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ +package ebook.parser; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Enumeration; +import java.util.regex.Matcher; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +import android.util.Log; +import ebook.EBook; +import ebook.Person; + +/** + * EpubInstantParser + */ +class EpubInstantParser { + private final int MAX_EPUBINFO_SIZE = 4096; + private final int MAX_XMLINFO_SIZE = 80; + private EBook eBook; + private String source; + private ZipFile zipFile; + private Enumeration zipEntries; + + EpubInstantParser(EBook eBook) throws IOException { + this.eBook = eBook; + this.source = this.createSource(); + } + + private String createSource() throws IOException { + ZipEntry entry = null; + zipFile = new ZipFile(this.eBook.fileName); + zipEntries = zipFile.entries(); + while (zipEntries.hasMoreElements()) { + entry = zipEntries.nextElement(); + if (entry.getName().matches("(?i).*\\.opf$")) + break; + } + InputStream inputStream = zipFile.getInputStream(entry); + byte[] buffer = readInputStream(inputStream); + String encoding = getXmlEncoding(buffer); + String preparedInput = new String(buffer, encoding); + Matcher matcher = SOP.epubDescription.matcher(preparedInput); + if (matcher.find()) { + this.eBook.annotation = matcher.group(1); + preparedInput = matcher.replaceFirst(""); + } + return preparedInput; + } + + private byte[] readInputStream(InputStream input) throws IOException { + byte[] buffer = new byte[MAX_EPUBINFO_SIZE]; + int counter = 0; + int amount = 0; + int stopCounter = 0; + boolean stop = false; + while (!stop & (amount < MAX_EPUBINFO_SIZE) && (counter != -1)) { + counter = input.read(buffer, amount, MAX_EPUBINFO_SIZE - amount); + amount += counter; + while (stopCounter < amount) { + if (buffer[stopCounter] == '>') + if (buffer[stopCounter - 1] == 'a') + if (buffer[stopCounter - 10] == '<') + if (buffer[stopCounter - 9] == '/') { + stop = true; + break; + } + stopCounter++; + } + } + if (amount <= 0) + throw new IOException("Epmty input stream"); + byte[] output = new byte[stopCounter]; + System.arraycopy(buffer, 0, output, 0, stopCounter); + return output; + } + + private String getXmlEncoding(byte[] input) throws IOException { + String encoding; + String xmlHeader = new String(input, 0, MAX_XMLINFO_SIZE, "ISO-8859-1"); + Matcher matcher = SOP.xmlEncoding.matcher(xmlHeader.toString()); + if (matcher.find()) + encoding = matcher.group(1); + else + throw new IOException("Unknown encoding"); + return encoding; + } + + protected void parse() throws IOException { + Matcher matcher; + matcher = SOP.epubTitle.matcher(this.source); + if (matcher.find()) + this.eBook.title = matcher.group(1); + matcher = SOP.epubAuthor.matcher(this.source); + while (matcher.find()) { + this.eBook.authors.add(new Person(matcher.group(1))); + } + matcher = SOP.epubLanguage.matcher(this.source); + if (matcher.find()) + this.eBook.language = matcher.group(1); + this.eBook.isOk = true; + matcher = SOP.epubGenre.matcher(this.source); + while (matcher.find()) + this.eBook.epubGenres.add(matcher.group(1)); + if (this.eBook.doExtractCover) { + matcher = SOP.epubCover.matcher(this.source); + if (matcher.find()) + this.eBook.cover = getCover(matcher.group(1)); + } + matcher = SOP.epubMeta.matcher(this.source); + while (matcher.find()){ + String strMeta = matcher.group(1); + Matcher temp_matcher; + temp_matcher = SOP.epubSequenceName.matcher(strMeta); + if(temp_matcher.find()){ + temp_matcher = SOP.epubSequenceContent.matcher(strMeta); + if(temp_matcher.find()) { + this.eBook.sequenceName = temp_matcher.group(1); + } + } + temp_matcher = SOP.epubSequenceNumber.matcher(strMeta); + if(temp_matcher.find()){ + temp_matcher = SOP.epubSequenceContent.matcher(strMeta); + if(temp_matcher.find()){ + this.eBook.sequenceNumber = temp_matcher.group(1); + } + } + } + this.eBook.isOk = true; + } + + private byte[] getCover(String fileName) throws IOException { + ZipEntry entry = null; + zipEntries = zipFile.entries(); + while (zipEntries.hasMoreElements()) { + entry = zipEntries.nextElement(); + if (entry.getName().matches("(?i).*" + fileName)) + break; + } + int fileLength = (int) entry.getSize(); + InputStream inputStream = zipFile.getInputStream(entry); + byte[] output = new byte[fileLength]; + int counter; + int amount = 0; + while (amount < fileLength) { + counter = inputStream.read(output, amount, fileLength - amount); + amount += counter; + } + return output; + } +} diff --git a/src/ebook/parser/Fb2InstantParser.java b/src/ebook/parser/Fb2InstantParser.java new file mode 100644 index 0000000..5565fdc --- /dev/null +++ b/src/ebook/parser/Fb2InstantParser.java @@ -0,0 +1,202 @@ +/* + * Copyright (C) 2011 Andrew Mochalov + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ +package ebook.parser; + +import java.io.IOException; +import java.io.InputStream; +import java.util.regex.*; + +import ebook.EBook; +import ebook.Person; + +/** + * FB2InstantParser + */ +class Fb2InstantParser { + private final int MAX_FB2INFO_SIZE = 4096; + private final int MAX_XMLINFO_SIZE = 80; + private final int MAX_FB2_SIZE = 2097152; + private EBook eBook; + private String source; + private InputStream input; + + Fb2InstantParser(EBook eBook, InputStream input) throws IOException { + this.eBook = eBook; + this.source = this.createSource(input); + this.input = input; + } + + private String createSource(InputStream stream) throws IOException, + NullPointerException { + byte[] buffer = readInputStream(stream); + this.eBook.encoding = this.getXmlEncoding(buffer); + String preparedInput = new String(buffer, this.eBook.encoding); + Matcher matcher = SOP.fb2Annotation.matcher(preparedInput); + if (matcher.find()) { + this.eBook.annotation = matcher.group(1); + preparedInput = matcher.replaceFirst(""); + } + return preparedInput; + } + + private byte[] readInputStream(InputStream input) throws IOException { + byte[] buffer = new byte[MAX_FB2INFO_SIZE]; + int counter = 0; + int amount = 0; + int stopCounter = 0; + boolean stop = false; + while (!stop & (amount < MAX_FB2INFO_SIZE) && (counter != -1)) { + counter = input.read(buffer, amount, MAX_FB2INFO_SIZE - amount); + amount += counter; + while (stopCounter < amount) { + if (buffer[stopCounter] == '>') + if (buffer[stopCounter - 1] == 'o') + if (buffer[stopCounter - 12] == '<') + if (buffer[stopCounter - 10] == 't') { + stop = true; + break; + } + stopCounter++; + } + } + if (amount <= 0) + throw new IOException("Epmty input stream"); + byte[] output = new byte[stopCounter]; + System.arraycopy(buffer, 0, output, 0, stopCounter); + return output; + } + + private String getXmlEncoding(byte[] input) throws IOException { + String encoding = null; + String xmlHeader = new String(input, 0, MAX_XMLINFO_SIZE, "ISO-8859-1"); + Matcher matcher = SOP.xmlEncoding.matcher(xmlHeader.toString()); + if (matcher.find()) + encoding = matcher.group(1); + else + throw new IOException("Unknown encoding"); + return encoding; + } + + private Person extractPerson(String input) { + Matcher matcher; + Person person = new Person(); + matcher = SOP.fb2FirstName.matcher(input); + if (matcher.find()) + person.firstName = matcher.group(1).trim(); + matcher = SOP.fb2MiddleName.matcher(input); + if (matcher.find()) + person.middleName = matcher.group(1).trim(); + matcher = SOP.fb2LastName.matcher(input); + if (matcher.find()) + person.lastName = matcher.group(1).trim(); + return person; + } + + protected void parse() { + Matcher matcher; + matcher = SOP.fb2Author.matcher(source); + while (matcher.find()) + this.eBook.authors.add(extractPerson(matcher.group(1))); + matcher = SOP.fb2Title.matcher(source); + if (matcher.find()) + this.eBook.title = matcher.group(1); + matcher = SOP.fb2genre.matcher(source); + while (matcher.find()) + this.eBook.fb2Genres.add(matcher.group(1)); + matcher = SOP.fb2Language.matcher(source); + if (matcher.find()) + this.eBook.language = matcher.group(1); + matcher = SOP.fb2Sequence.matcher(source); + if (matcher.find()) { + String sequence = matcher.group(1); + matcher = SOP.fb2SequenceName.matcher(sequence); + if (matcher.find()) + this.eBook.sequenceName = matcher.group(1); + matcher = SOP.fb2SequenceNumber.matcher(sequence); + if (matcher.find()) + this.eBook.sequenceNumber = matcher.group(1); + } + if (eBook.doExtractCover) { + matcher = SOP.fb2CoverName.matcher(source); + if (matcher.find()) { + matcher.group(1); + this.eBook.cover = getCover(); + } + } + this.eBook.isOk = true; + } + + private byte[] getCover() { + // int q = this.input.available(); + byte[] buffer = new byte[MAX_FB2_SIZE]; + byte[] cover64; + int amount = 0; + int count = 0; + try { + while ((amount < MAX_FB2_SIZE) && (count != -1)) { + count = this.input.read(buffer, amount, MAX_FB2_SIZE - amount); + if (count != -1) + amount += count; + } + } catch (IOException e) { + } + if (amount == MAX_FB2_SIZE) { + return null; + } else { + int stop = -1; + int start = -1; + int counter = amount - 1; + while (counter >= 0) { + if (buffer[counter] == '<') + if (buffer[counter + 1] == '/') + if (buffer[counter + 2] == 'b') + if (buffer[counter + 7] == 'y') + if (buffer[counter + 8] == '>') { + stop = counter - 1; + break; + } + counter--; + } + while (counter >= 0) { + if (buffer[counter] == '<') + if (buffer[counter + 1] == 'b') + if (buffer[counter + 3] == 'n') + if (buffer[counter + 5] == 'r') + if (buffer[counter + 6] == 'y') { + start = counter; + break; + } + counter--; + } + if ((start == -1) || (stop == -1)) { + return null; + } + while (counter < stop) { + if (buffer[counter] == '>') { + start = counter + 1; + break; + } + counter++; + } + int newSize = stop - start + 1; + cover64 = new byte[newSize]; + System.arraycopy(buffer, start, cover64, 0, newSize); + } + return Base64Decoder.decode(cover64); + } +} diff --git a/src/ebook/parser/InstantParser.java b/src/ebook/parser/InstantParser.java new file mode 100644 index 0000000..86857ba --- /dev/null +++ b/src/ebook/parser/InstantParser.java @@ -0,0 +1,88 @@ +/* + * Copyright (C) 2011 Andrew Mochalov + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ +package ebook.parser; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +import ebook.EBookFormat; + +/** + * InstantParser - very fast, instant handler of the information contained + * in the files of e-books + */ +public class InstantParser extends ebook.parser.Parser { + protected void parseFile() { + if (SOP.fb2File.matcher(this.eBook.fileName).matches()) { + this.eBook.format = EBookFormat.FB2; + this.parseFb2(); + } + if (SOP.fb2zipFile.matcher(this.eBook.fileName).matches()) { + this.eBook.format = EBookFormat.FB2; + this.parseFb2Zip(); + } + if (SOP.epubFile.matcher(this.eBook.fileName).matches()) { + this.eBook.format = EBookFormat.EPUB; + this.parseEpub(); + } else { + this.eBook.format = EBookFormat.UNSUPPORTED; + } + } + + private void parseFb2() { + try { + InputStream inputStream = new FileInputStream(this.eBook.fileName); + Fb2InstantParser parser = new Fb2InstantParser(this.eBook, + inputStream); + parser.parse(); + inputStream.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + private void parseFb2Zip() { + try { + ZipFile zipFile = new ZipFile(this.eBook.fileName); + ZipEntry entry = zipFile.entries().nextElement(); + InputStream inputStream = zipFile.getInputStream(entry); + Fb2InstantParser parser = new Fb2InstantParser(this.eBook, + inputStream); + parser.parse(); + inputStream.close(); + zipFile.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + private void parseEpub() { + try { + EpubInstantParser parser = new EpubInstantParser(this.eBook); + parser.parse(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } +} diff --git a/src/ebook/parser/Parser.java b/src/ebook/parser/Parser.java new file mode 100644 index 0000000..bc2541f --- /dev/null +++ b/src/ebook/parser/Parser.java @@ -0,0 +1,63 @@ +/* + * Copyright (C) 2011 Andrew Mochalov + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ +package ebook.parser; + +import ebook.EBook; + +/** + * Parser - abstract class from which the e-books handlers are created + */ +abstract public class Parser { + protected EBook eBook; + + /** + * Handles the e-book extracts contained therein meta-information + * @param fileName - the name of the file to be processed + * @return - instance of the class EBook with the fields filled with + * e-book meta-information + */ + public EBook parse(String fileName) { + return this.parse(fileName, false); + } + + /** + * @param fileName + * @param extractCover + * @return + */ + public EBook parse(String fileName, boolean extractCover) { + this.eBook = new EBook(); + this.eBook.fileName = fileName; + this.eBook.doExtractCover = extractCover; + this.eBook.isOk = false; + this.parseFile(); + return this.eBook; + } + + + abstract protected void parseFile(); + + /** + * Returns instance of the class EBook with the fields filled with + * e-book meta-information + * @return - instance of the class EBook + */ + public EBook getEBoook() { + return this.eBook; + } +} diff --git a/src/ebook/parser/SOP.java b/src/ebook/parser/SOP.java new file mode 100644 index 0000000..672ee30 --- /dev/null +++ b/src/ebook/parser/SOP.java @@ -0,0 +1,97 @@ +/* + * Copyright (C) 2011 Andrew Mochalov + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ +package ebook.parser; + +import java.util.regex.Pattern; + +/** + * Store of Patterns + */ +class SOP { + protected static Pattern fb2File; + protected static Pattern fb2zipFile; + protected static Pattern epubFile; + protected static Pattern opfFile; + protected static Pattern xmlEncoding; + protected static Pattern fb2FirstName; + protected static Pattern fb2MiddleName; + protected static Pattern fb2LastName; + protected static Pattern fb2Author; + protected static Pattern fb2Title; + protected static Pattern fb2genre; + protected static Pattern fb2Language; + protected static Pattern fb2Sequence; + protected static Pattern fb2SequenceName; + protected static Pattern fb2SequenceNumber; + protected static Pattern fb2Annotation; + protected static Pattern fb2CoverName; + protected static Pattern epubDescription; + protected static Pattern epubTitle; + protected static Pattern epubAuthor; + protected static Pattern epubLanguage; + protected static Pattern epubGenre; + protected static Pattern epubCover; + protected static Pattern epubMeta; + protected static Pattern epubSequenceName; + protected static Pattern epubSequenceNumber; + protected static Pattern epubSequenceContent; + + static { + fb2File = Pattern.compile("(?i).*fb2$"); + fb2zipFile = Pattern.compile("(?i).*fb2\\.zip$"); + epubFile = Pattern.compile("(?i).*epub$"); + opfFile = Pattern.compile("(?i).*opf$"); + xmlEncoding = Pattern.compile("(?i).*encoding=[\"'](.*?)[\"'].*"); + fb2FirstName = Pattern.compile("(?s)(.*)"); + fb2MiddleName = Pattern + .compile("(?s)(.*)"); + fb2LastName = Pattern.compile("(?s)(.*)"); + fb2Author = Pattern.compile("(?s)(.*?)"); + fb2Title = Pattern.compile("(?s)(.*?)"); + fb2genre = Pattern.compile("(?s)(.*?)"); + fb2Language = Pattern.compile("(?s)(.*?)"); + fb2Sequence = Pattern.compile("(?s)"); + fb2SequenceName = Pattern.compile("name=\"(.*?)\""); + fb2SequenceNumber = Pattern.compile("number=\"(.*?)\""); + + fb2Annotation = Pattern + .compile("(?s)(.*?)"); + fb2CoverName = Pattern + .compile("(?s).*href=\"#(.*?)\".*"); + epubDescription = Pattern + .compile("(?s)(.*?)"); + epubTitle = Pattern + .compile("(?s)(.*?)"); + epubAuthor = Pattern + .compile("(?s)(.*?)"); + epubLanguage = Pattern + .compile("(?s)(.*?)"); + epubGenre = Pattern + .compile("(?s)(.*?)"); + epubCover = Pattern + .compile("(?s)(.*?)"); + epubMeta = Pattern + .compile("(?s)"); + epubSequenceName = Pattern + .compile("name=\"calibre:series\""); + epubSequenceNumber = Pattern + .compile("name=\"calibre:series_index\""); + epubSequenceContent = Pattern + .compile("content=\"(.*?)\""); + } +}