### Launch File Selection in MainActivity Source: https://context7.com/gkalab/cb2pgn/llms.txt This snippet demonstrates how the MainActivity initiates the file selection process by launching a custom activity and handling the result via onActivityResult to trigger the conversion flow. ```java public class MainActivity extends Activity { private static final int CONVERT_RESULT = 0; private static final int RESULT_GET_FILENAME = 1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = new Intent(this, SelectFileActivity.class); intent.setAction("cbh"); startActivityForResult(intent, RESULT_GET_FILENAME); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (data != null && requestCode == RESULT_GET_FILENAME) { if (resultCode == RESULT_OK) { String fileName = data.getAction(); Intent intent = new Intent(this, ConvertActivity.class); intent.setAction(fileName); startActivityForResult(intent, CONVERT_RESULT); } } } } ``` -------------------------------- ### Orchestrate Conversion in ConvertActivity Source: https://context7.com/gkalab/cb2pgn/llms.txt This snippet manages the conversion lifecycle, including validating the presence of required ChessBase companion files and executing the conversion task asynchronously to prevent UI blocking. ```java public class ConvertActivity extends Activity implements IConversionCallback { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String fileName = getIntent().getAction(); List missing = getMissingFiles(fileName); if (missing.size() == 0) { File pgnDir = new File(Environment.getExternalStorageDirectory() + File.separator + "pgn"); if (!pgnDir.exists()) { pgnDir.mkdirs(); } new Cbh2PgnTask(this).execute(fileName, pgnDir.getAbsolutePath()); } else { showError("Missing required files: " + missing); } } private List getMissingFiles(String fileName) { List result = new ArrayList(); String[] extensions = new String[] { "g", "a", "p", "t", "c", "s" }; for (String extension : extensions) { String name = fileName.substring(0, fileName.length() - 1) + extension; if (!new File(name).exists()) { result.add(name); } } return result; } @Override public void success(int numGames, String fileName) { Intent intent = new Intent(); intent.putExtra("numGames", numGames); this.setResult(RESULT_OK, intent.setAction(fileName)); finish(); } } ``` -------------------------------- ### IConversionCallback: Interface for Conversion Result Handling Source: https://context7.com/gkalab/cb2pgn/llms.txt Defines a callback interface for receiving asynchronous conversion results. It includes methods for handling successful conversions, providing the number of games and output file path, and for handling failures. ```java public interface IConversionCallback { /** * Called when conversion completes successfully * @param numGames Number of games converted * @param fileName Path to output PGN file */ void success(int numGames, String fileName); /** * Called when conversion fails */ void failure(); } ``` -------------------------------- ### Java Asynchronous Task for CBH to PGN Conversion Source: https://context7.com/gkalab/cb2pgn/llms.txt The Cbh2PgnTask extends Android's AsyncTask to perform file conversion in a background thread. It loads necessary native libraries, displays a progress dialog, and uses callbacks to report success or failure. The task takes the input ChessBase file path and output directory as parameters. ```java public class Cbh2PgnTask extends AsyncTask { // Load required native libraries for conversion static { System.loadLibrary("zlib"); // Compression System.loadLibrary("minizip"); // ZIP handling System.loadLibrary("mstl"); // Standard library utilities System.loadLibrary("universalchardet"); // Character encoding detection System.loadLibrary("zzip"); // ZIP file access System.loadLibrary("util"); // Utility functions System.loadLibrary("db"); // Database operations System.loadLibrary("nativecb"); // ChessBase conversion core } // Native method for CBH to PGN conversion private final native int convertToPgn(String fileName, String outputDir); @Override protected void onPreExecute() { // Show progress dialog with horizontal progress bar progressDlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDlg.setMessage("Converting..."); progressDlg.setCancelable(false); progressDlg.show(); } @Override protected Integer doInBackground(String... params) { String fileName = params[0]; String outputDir = params[1]; // Call native conversion (returns number of games converted) return this.convertToPgn(fileName, outputDir); } @Override protected void onPostExecute(Integer result) { progressDlg.dismiss(); if (result > 0) { ((IConversionCallback) activity).success(result, pgnFileName); } else { ((IConversionCallback) activity).failure(); } } } ``` -------------------------------- ### SelectFileActivity - File Browser Source: https://context7.com/gkalab/cb2pgn/llms.txt Handles the file system navigation and filtering logic for selecting .cbh files within the application. ```APIDOC ## GET /SelectFileActivity ### Description Provides a native file browser UI for navigating the device filesystem and filtering files by specific extensions. ### Method GET ### Endpoint SelectFileActivity ### Parameters #### Query Parameters - **action** (String) - Optional - The file extension filter (e.g., "cbh"). ### Response #### Success Response (200) - **List** (Array) - A list of directories and files matching the extension filter. ``` -------------------------------- ### Tools - Preferences Utility Source: https://context7.com/gkalab/cb2pgn/llms.txt Utility class for managing persistent navigation history using SharedPreferences and JSON serialization. ```APIDOC ## UTILITY Tools ### Description Provides helper methods to store and retrieve navigation path stacks as JSON strings within SharedPreferences. ### Methods - **getStringStackPref(Context context, String key, Stack defaultValues)**: Retrieves a stored path stack. - **setStringStackPref(Context context, String key, Stack values)**: Serializes and saves a path stack to preferences. ``` -------------------------------- ### Tools: Android SharedPreferences Utility for Path History Source: https://context7.com/gkalab/cb2pgn/llms.txt Provides utility methods for managing navigation path history using Android's SharedPreferences. It supports storing and retrieving stacks of strings, serialized as JSON, to persist user navigation data. ```java public class Tools { // Retrieve stored path stack from preferences public static Stack getStringStackPref(Context context, String key, Stack defaultValues) { SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(context); String json = prefs.getString(key, null); Stack result = new Stack(); if (json != null) { JSONArray a = new JSONArray(json); for (int i = 0; i < a.length(); i++) { result.add(a.optString(i)); } } else if (defaultValues != null) { result = defaultValues; } return result; } // Store path stack to preferences as JSON public static void setStringStackPref(Context context, String key, Stack values) { SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(context); SharedPreferences.Editor editor = prefs.edit(); JSONArray a = new JSONArray(); for (int i = 0; i < values.size(); i++) { a.put(values.get(i)); } editor.putString(key, values.isEmpty() ? null : a.toString()); editor.commit(); } } ``` -------------------------------- ### C++ Native JNI Implementation for CBH to PGN Conversion Source: https://context7.com/gkalab/cb2pgn/llms.txt This C++ code implements the JNI interface for converting ChessBase files to PGN. It initializes necessary database components, opens the ChessBase file with auto character encoding detection, creates a PGN output stream, and exports all games using a PgnWriter with specified flags for comprehensive data inclusion. ```cpp // nativecb.cpp - Native JNI conversion implementation #include "db_database.h" #include "db_pgn_writer.h" // Writer flags for full game data export static unsigned const g_Flags = Writer::Flag_Include_Variations | Writer::Flag_Include_Comments | Writer::Flag_Include_Annotation | Writer::Flag_Include_Marks | Writer::Flag_Include_Termination_Tag | Writer::Flag_Include_Mode_Tag | Writer::Flag_Include_Setup_Tag | Writer::Flag_Include_Variant_Tag | Writer::Flag_Include_Time_Mode_Tag | Writer::Flag_Exclude_Extra_Tags | Writer::Flag_Symbolic_Annotation_Style; // JNI entry point for conversion extern "C" JNIEXPORT jint JNICALL Java_org_chess_cb_Cbh2PgnTask_convertToPgn( JNIEnv* env, jobject obj, jstring fileName, jstring outputDir) { const char* sourceFileName = env->GetStringUTFChars(fileName, NULL); const char* outDir = env->GetStringUTFChars(outputDir, NULL); // Initialize chess database components db::tag::initialize(); db::castling::initialize(); db::Board::initialize(); db::HomePawns::initialize(); db::Signature::initialize(); // Open ChessBase database with auto character encoding detection mstl::string convertto("utf-8"); mstl::string convertfrom("auto"); Progress progress; Database src(cbhPath, convertfrom, Database::ReadOnly, progress); // Create PGN output stream mstl::string fullPgnPath = outDir + "/" + pgnFileName; util::ZStream strm(fullPgnPath, util::ZStream::Text, mstl::ios_base::out | mstl::ios_base::app); PgnWriter writer(format::Pgn, strm, convertto, g_Flags); // Export all games unsigned numGames = exportGames(env, obj, progressMid, src, writer, progress); src.close(); return numGames; } ``` -------------------------------- ### SelectFileActivity: Android File Browser with Extension Filtering Source: https://context7.com/gkalab/cb2pgn/llms.txt Implements a native Android file browser for selecting .cbh files. It supports directory navigation with breadcrumbs and filters files based on a specified extension. Dependencies include Android SDK components like ListActivity, Bundle, and FileFilter. ```java public class SelectFileActivity extends ListActivity { public static final String PARENT_FOLDER = ".. (parent folder)"; private static Stack path = new Stack(); private String extension; // File extension filter (e.g., "cbh") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.filelist); // Get file extension filter from intent String extension = getIntent().getAction(); this.extension = (extension != null) ? extension : "*"; // Initialize path to external storage root String lastPathKey = "lastPath" + extension; path = Tools.getStringStackPref(this, lastPathKey, defaultPath); showList(lastPathKey); } // Find files matching extension in directory private List findFilesInDirectory(String dirName, final String extension) { File dir = new File(dirName); // Filter files by extension File[] files = dir.listFiles(new FileFilter() { public boolean accept(File pathname) { return pathname.isFile() && (pathname.getName().toLowerCase().endsWith(extension.toLowerCase()) || extension.equals("*")); } }); // Get directories for navigation File[] dirs = dir.listFiles(new FileFilter() { public boolean accept(File pathname) { return pathname.isDirectory(); } }); // Sort and combine results (directories first) Arrays.sort(dirNames, String.CASE_INSENSITIVE_ORDER); Arrays.sort(fileNames, String.CASE_INSENSITIVE_ORDER); List resultList = new ArrayList(Arrays.asList(dirNames)); resultList.addAll(Arrays.asList(fileNames)); return resultList; } } ``` -------------------------------- ### IConversionCallback - Conversion Result Interface Source: https://context7.com/gkalab/cb2pgn/llms.txt Defines the contract for handling the outcome of asynchronous file conversion tasks. ```APIDOC ## CALLBACK IConversionCallback ### Description Interface used to receive results from the background conversion process. ### Methods - **success(int numGames, String fileName)**: Triggered when conversion completes successfully. - **failure()**: Triggered when the conversion process encounters an error. ``` -------------------------------- ### Keep JavaScript Interface Classes for WebView Source: https://github.com/gkalab/cb2pgn/blob/master/proguard-project.txt This configuration snippet is used to keep specific classes that serve as JavaScript interfaces for Android's WebView. Uncomment and modify the `-keepclassmembers` directive to specify the fully qualified class name of your JavaScript interface. ```proguard # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.