TBL editor working, saves to txt file, DB, TBL, works in game

This commit is contained in:
Hash Borgir 2023-06-14 02:40:21 -06:00
parent 29621fa46c
commit 9ed54b5d33
4 changed files with 466 additions and 63 deletions

View File

@ -24,43 +24,72 @@ try {
$cmd = $_REQUEST['cmd'];
$tableName = $_REQUEST['tableName'];
function dumpAndProcessTable($tableName) {
// Set the path to the SQLite3 executable
$sqlitePath = "bin\sqlite3.exe";
// Dump the SQLite table to a TSV file
$tsvFile = $tableName . ".txt";
$dumpCommand = "bin\sqlite3.exe {$_SESSION['modname']}.db \"SELECT * FROM string\" -separator \"\t\" -cmd \".mode tabs\" -cmd \".headers off\" > \"{$_SESSION['tbl']}{$tsvFile}\"";
shell_exec($dumpCommand);
// Run the executable with the TSV file as input
$executablePath = "bin\EnquettarM.exe";
$processCommand = "{$executablePath} -i \"{$_SESSION['tbl']}{$tsvFile}\"";
$etxt = 'ModString.txt';
$etbl = 'ModString.tbl';
shell_exec($processCommand);
// now file is generated in rootdir, etbl, which we need to move to session tbl
rename($etbl, "{$_SESSION['tbl']}/$tableName.tbl");
// Remove the generated ModString.tbl
//unlink($etbl);
}
//function dumpAndProcessTable($tableName) {
// // Set the path to the SQLite3 executable
// $sqlitePath = "bin\sqlite3.exe";
//
// // Dump the SQLite table to a TSV file
// $tsvFile = $tableName . ".txt";
// $dumpCommand = "bin\sqlite3.exe {$_SESSION['modname']}.db \"SELECT * FROM string\" -separator \"\t\" -cmd \".mode tabs\" -cmd \".headers off\" > \"{$_SESSION['tbl']}{$tsvFile}\"";
// shell_exec($dumpCommand);
//
// die();
//
// // Convert TSV to TBL
// // Run the executable with the TSV file as input
// $executablePath = "bin\EnquettarM.exe";
// $processCommand = "{$executablePath} -i \"{$_SESSION['tbl']}{$tsvFile}\"";
//
// // will be saved into ModString.tbl
//
// $etxt = 'ModString.txt';
// $etbl = 'ModString.tbl';
//
// shell_exec($processCommand);
//
// // now file is generated in rootdir, etbl, which we need to move to session tbl
// rename($etbl, "{$_SESSION['tbl']}/$tableName.tbl");
//
// // Remove the generated ModString.tbl
// //unlink($etbl);
//}
if ($cmd == "getTable") {
$query = "SELECT ROWID,* FROM $tableName";
$rows = PDO_Execute($query);
$filePath = "{$_SESSION['tbl']}/$tableName.tbl";
$executablePath = getcwd() . "\bin\EnquettarM.exe";
$processCommand = "{$executablePath} -e \"$filePath\"";
shell_exec($processCommand);
rename(getcwd() . "\ModString.txt", "{$_SESSION['tbl']}/$tableName.txt");
$filePath = "{$_SESSION['tbl']}/$tableName.txt";
$fileLines = file($filePath);
$rows = [];
$rowid = 1; // Starting rowid value
foreach ($fileLines as $line) {
$row = explode("\t", $line);
$key = $row[0];
$string = $row[1];
$rowData = [
'rowid' => $rowid,
'Key' => $key,
'String' => $string
];
$rows[] = $rowData;
$rowid++;
}
// Start the table with Bootstrap classes
$tableMarkup = '';
// Iterate over the rows
foreach ($rows as $row) {
$string = str_replace('\n', "
", $row['String']);
$tableMarkup .= "<tr class='row-{$row['rowid']}'>";
$tableMarkup .= "<td style='width: 64px;'>{$row['rowid']}</td>";
@ -69,7 +98,7 @@ if ($cmd == "getTable") {
$tableMarkup .= "<td style='width: 20%;'><input type='text' value='{$row['Key']}' class='form-control'><span style='visibility: hidden;'>{$row['Key']}</span></td>";
// Display the String column as a textarea with Bootstrap form-control class
$tableMarkup .= "<td><textarea class='form-control'>{$string}</textarea></td>";
$tableMarkup .= "<td><textarea class='form-control'>{$row['String']}</textarea></td>";
// Add the Update and Delete links within a single td element
$tableMarkup .= "<td style='width: 100px;'><div>";
@ -78,7 +107,7 @@ if ($cmd == "getTable") {
$tableMarkup .= "<a href='#' class='update-link btn btn-primary' data-rowid='{$row['rowid']}'>Update</a>";
// Add the Delete link with Bootstrap btn and btn-danger classes
$tableMarkup .= "<a style='float:right' href='#' class='delete-link btn btn-danger' data-rowid='{$row['rowid']}'>Delete</a>";
$tableMarkup .= "<a style='' href='#' class='delete-link btn btn-danger' data-rowid='{$row['rowid']}'>Delete</a>";
$tableMarkup .= "</div></td>";
@ -91,16 +120,71 @@ if ($cmd == "getTable") {
if ($cmd == "update") {
$query = "UPDATE $tableName SET Key = ?, String = ? WHERE ROWID = ?";
PDO_Execute($query, [$_REQUEST['key'], $_REQUEST['string'], $_REQUEST['rowid']]);
dumpAndProcessTable($tableName);
echo $_REQUEST['key'] . " updated";
$query = "UPDATE $tableName SET Key = ?, String = ? WHERE Key = ?";
PDO_Execute($query, [$_REQUEST['key'], $_REQUEST['string'], $_REQUEST['key']]);
// Update the corresponding row in the text file
$filePath = "{$_SESSION['tbl']}/$tableName.txt";
$fileLines = file($filePath);
// Calculate the line number to update based on the rowid
$lineNumber = $_REQUEST['rowid'];
// Update the line in the file with the new key and string values
$fileLines[$lineNumber - 1] = "{$_REQUEST['key']}\t{$_REQUEST['string']}\n";
// Save the updated content back to the text file
file_put_contents($filePath, implode("", array_filter($fileLines)));
// Convert TXT to TBL
$executablePath = "bin\EnquettarM.exe";
$processCommand = "{$executablePath} -i \"{$_SESSION['tbl']}/$tableName.txt\"";
shell_exec($processCommand);
rename(getcwd() . "\ModString.tbl", "{$_SESSION['tbl']}/$tableName.tbl");
// Remove empty lines from end of file
// Read the file contents into an array of lines
$lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
// Trim empty lines from the end of the array
while (!empty($lines) && trim(end($lines)) === '') {
array_pop($lines);
}
// Write the updated content back to the file
file_put_contents($filePath, implode(PHP_EOL, $lines));
}
if ($cmd == "delete") {
$query = "DELETE FROM $tableName WHERE ROWID = ?";
PDO_Execute($query, [$_REQUEST['rowid']]);
dumpAndProcessTable($tableName);
$query = "DELETE FROM $tableName WHERE Key = ?";
PDO_Execute($query, [$_REQUEST['key']]);
$rowid = $_REQUEST['rowid'];
$filePath = "{$_SESSION['tbl']}/$tableName.txt";
// Calculate the line number to delete based on the rowid
$lineNumber = $rowid - 1; // Assuming zero-indexed line numbers
// Read the lines of the text file into an array
$fileLines = file($filePath, FILE_IGNORE_NEW_LINES);
// Remove the line at the specified line number
if (isset($fileLines[$lineNumber])) {
unset($fileLines[$lineNumber]);
}
// Save the updated content back to the text file
file_put_contents($filePath, implode("\n", $fileLines));
// Convert TXT to TBL
$executablePath = "bin\EnquettarM.exe";
$processCommand = "{$executablePath} -i \"{$_SESSION['tbl']}/$tableName.txt\"";
shell_exec($processCommand);
rename(getcwd() . "\ModString.tbl", "{$_SESSION['tbl']}/$tableName.tbl");
echo $_REQUEST['rowid'] . " deleted";
}
@ -119,7 +203,15 @@ if ($cmd == "add") {
// Retrieve the last inserted rowid from the table
$query = "SELECT last_insert_rowid() AS rowid";
$result = PDO_FetchOne($query);
// Append the new row to the text file
$newLine = "{$key}\t{$string}";
file_put_contents($filePath, $newLine . PHP_EOL, FILE_APPEND);
echo $result;
dumpAndProcessTable($tableName);
}

286
TblEditorGUI_TAB.php Normal file
View File

@ -0,0 +1,286 @@
<?php
session_start();
ob_start();
require_once './config.php';
require_once './_pdo.php';
require_once './src/D2Functions.php';
require_once './src/D2Crud.php';
error_reporting(E_ERROR | E_PARSE);
set_time_limit(-1);
ini_set('max_input_time', '-1');
ini_set('max_execution_time', '0');
define('DB_FILE', $_SESSION['modname'] . ".db");
try {
PDO_Connect("sqlite:" . DB_FILE);
} catch (Exception $e) {
echo "Connection error: " . $e->getMessage();
}
$tbl = $_SESSION['tbl'];
$tableNames = [];
foreach (glob($tbl . "*.tbl") as $filename) {
$tableInfo = pathinfo($filename);
$tableNames[] = $tableInfo['filename'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- CSS -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.11.4/css/jquery.dataTables.min.css">
<!-- JS -->
<!-- <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>-->
<script src="https://cdn.datatables.net/1.11.4/js/jquery.dataTables.min.js"></script>
<!-- Bootstrap CSS (if not already included) -->
<!-- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css">-->
<!-- Bootstrap DataTables CSS -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.11.4/css/dataTables.bootstrap4.min.css">
<!-- Bootstrap JS (if not already included) -->
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.min.js"></script>-->
<!-- Bootstrap DataTables JS -->
<script src="https://cdn.datatables.net/1.11.4/js/dataTables.bootstrap4.min.js"></script>
<title>Editable Tables</title>
<!--<link rel="stylesheet" href="https://bootswatch.com/4/lumen/bootstrap.min.css">-->
<!-- <link rel="stylesheet" type="text/css" href="res/95assets/win95.css">-->
</head>
<body>
<div style="padding:10px; border: 1px solid #eee;">
<div class="container">
<div class="row">
<div class="col-md-6">
<select name="tableName" id="tableName" class="form-control">
<option value="" disabled selected>_______________SELECT TBL FILE_______________</option>
<?php foreach ($tableNames as $tableName): ?>
<option value="<?php echo $tableName; ?>" <?php echo ($tableName == "") ? "selected" : ""; ?>><?php echo $tableName; ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="col-md-6">
<button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapseForm" aria-expanded="false" aria-controls="collapseForm">
Add new String Key
</button>
</div>
</div>
<div class="collapse" id="collapseForm">
<div class="form-group">
<label for="inputKey">Key</label>
<input type="text" class="form-control" id="inputKey" placeholder="Enter Key">
</div>
<div class="form-group">
<label for="inputString">String</label>
<textarea class="form-control" id="inputString" placeholder="Enter String"></textarea>
</div>
<button type="button" class="btn btn-primary" id="addLink">Add</button>
</div>
</div>
<br>
<hr>
<div class="tablediv">
<table class="table">
<thead>
<tr>
<th style="width: 64px;">ID</th>
<th style='width: 20%;'>Key</th>
<th>String</th>
<th style="width: 100px;"></th>
</tr>
</thead>
<tbody>
<!-- Additional rows -->
</tbody>
</table>
</div>
</div>
<script>
function resizeTextarea() {
this.style.height = 'auto';
this.style.height = (this.scrollHeight) + 'px';
}
$(document).ready(function () {
// Function to resize textarea based on content
function resizeTextarea() {
this.style.height = 'auto';
this.style.height = (this.scrollHeight) + 'px';
}
// Select element change event handler
$('#tableName').change(function () {
$('.table').DataTable().destroy();
$('.table tbody').html('');
var selectedTable = $(this).val();
if (selectedTable !== '') {
// Send GET request to TblEditor.php?getTable with selected table name
var request = $.get('TblEditor.php', {cmd: 'getTable', tableName: selectedTable});
request.done(function (response) {
// Handle the response here
$('.tablediv tbody').html(response).promise().done(function () {
// Callback function after HTML content is loaded
// Initialize DataTables on the table
$('.table').DataTable();
// Resize textareas on page load
$('textarea').each(resizeTextarea);
// Resize textareas on input
$('textarea').on('input', resizeTextarea);
// Resize textareas on custom select change
$('.custom-select').change(function () {
$('textarea').each(resizeTextarea);
});
$('.page-link').click(function () {
$('textarea').each(resizeTextarea);
});
});
});
}
});
// Delete link click event handler
$(document).on('click', '.delete-link', function (event) {
event.preventDefault();
var selectedTable = $('select[name="tableName"]').val();
// Get the rowid from the custom attribute data-rowid
var rowid = $(this).data('rowid');
// Remove the deleted row from the table
$('.row-' + rowid).remove();
// Send GET request to TblEditor.php?cmd=delete&rowid={rowid}
$.get('TblEditor.php', {cmd: 'delete', tableName: selectedTable, rowid: rowid}, function (response) {
// Handle the response here
// Wait until the response is loaded, then remove the row
$(response).ready(function () {
// Update DataTable
});
});
});
// Update link click event handler
$(document).on('click', '.update-link', function (event) {
event.preventDefault();
var selectedTable = $('select[name="tableName"]').val();
// Get the rowid from the custom attribute data-rowid
var rowid = $(this).data('rowid');
// Get the updated values from the corresponding input and textarea
var key = $('.row-' + rowid + ' input').val();
var string = $('.row-' + rowid + ' textarea').val();
string = string.replace(/&#13;/g, '\\n');
string = string.replace(/\n/g, '\\n');
// Send POST request to TblEditor.php with the updated values
$.post('TblEditor.php', {cmd: 'update', tableName: selectedTable, rowid: rowid, key: key, string: string}, function (response) {
// Handle the response here
// Optional: Update any UI elements if needed
});
});
// Add link click event handler
$('#addLink').click(function () {
var selectedTable = $('#tableName').val();
var key = $('#inputKey').val();
var string = $('#inputString').val();
// Send POST request to TblEditor.php with parameters
$.post('TblEditor.php', {cmd: 'add', tableName: selectedTable, Key: key, String: string}, function (response) {
// Handle the response here
rowid = response;
// Create the HTML markup for the new row
var newRow = '<tr class="row-' + rowid + '">' +
'<td>' + rowid + '</td>' +
'<td><input type="text" value="' + key + '" class="form-control"></td>' +
'<td><textarea class="form-control">' + string + '</textarea></td>' +
'<td><div>' +
'<a href="#" class="update-link btn btn-primary" data-rowid="' + rowid + '">Update</a>' +
'<a style="float:right" href="#" class="delete-link btn btn-danger" data-rowid="' + rowid + '">Delete</a>' +
'</div></td>' +
'</tr>';
;
// Append the new row to the table
$('.table').DataTable().destroy();
$('.table tbody').append(newRow);
// Initialize DataTables on the table
var table = $('.table').DataTable();
// Go to the last page after loading the table
table.page('last').draw('page');
});
});
});
$(document).ready(function () {
$('textarea').each(function () {
this.style.height = 'auto';
this.style.height = (this.scrollHeight) + 'px';
});
setInterval(function () {
$('textarea').each(resizeTextarea);
}, 4000);
});
</script>
<style>
body {
background: #f8f8f8;
margin: 10px;
border: 1px solid #eee;
border-radius: 5px;
}
div.dataTables_wrapper div.dataTables_length select {
width: 75px !important;
}
textarea {
overflow: hidden;
resize: none;
scrollbar-width: none; /* For Firefox */
-ms-overflow-style: none; /* For Internet Explorer and Edge */
}
</style>
</body>
</html>

View File

@ -1,18 +1,17 @@
<?php
class D2Tbl
{
class D2Tbl {
/**
* Get strings from tbl file, based on "credits/EnquettarM.pl" script (more info can be found there).
* Credits to Ondo and Mephansteras.
*
* @param mixed $filePath
* @param mixed $replaceSpecialCharacters
*/
public static function getStrings($filePath, $replaceSpecialCharacters = true)
{
* Get strings from tbl file, based on "credits/EnquettarM.pl" script (more info can be found there).
* Credits to Ondo and Mephansteras.
*
* @param mixed $filePath
* @param mixed $replaceSpecialCharacters
*/
public static function getStrings_backup($filePath, $replaceSpecialCharacters = true) {
// Check file
if(!file_exists($filePath) || !is_readable($filePath)) {
if (!file_exists($filePath) || !is_readable($filePath)) {
return false;
}
@ -20,17 +19,15 @@ class D2Tbl
$fileData = file_get_contents($filePath);
// Skip: 0 - 1
// Get elements number
$unpack = unpack('S', substr($fileData, 2, 2));
$elementsNumber = $unpack[1];
// Skip: 4 - 20
// Get offsets
$offset = 21;
$offsets = array();
for($i = 0; $i < $elementsNumber; $i++) {
for ($i = 0; $i < $elementsNumber; $i++) {
$unpack = unpack('S', substr($fileData, $offset, 2));
$offsets[] = $unpack[1];
$offset += 2;
@ -40,7 +37,7 @@ class D2Tbl
$strings = array();
// Read elements
for($i = 0; $i < $elementsNumber; $i++) {
for ($i = 0; $i < $elementsNumber; $i++) {
$currentOffset = ($offset + ($offsets[$i] * 17));
// Skip 7 bytes
@ -70,7 +67,7 @@ class D2Tbl
$string = trim(substr($fileData, $stringOffset, $stringLength));
// Replace special characters
if($replaceSpecialCharacters) {
if ($replaceSpecialCharacters) {
$key = self::replaceSpecialCharacters($key);
$string = self::replaceSpecialCharacters($string);
}
@ -82,13 +79,36 @@ class D2Tbl
return $strings;
}
public static function getStrings($filePath) {
$executablePath = getcwd() . "\bin\EnquettarM.exe";
$processCommand = "{$executablePath} -e \"$filePath\"";
shell_exec($processCommand);
$filePath = "ModString.txt";
$fileLines = file($filePath);
$rows = [];
$strings = [];
foreach ($fileLines as $line) {
$row = explode("\t", $line);
$key = $row[0];
$string = $row[1];
$strings[$key] = $string;
}
return $strings;
}
/**
* Replace some special characters (\n, \t).
*
* @param mixed $text
*/
public static function replaceSpecialCharacters($text)
{
* Replace some special characters (\n, \t).
*
* @param mixed $text
*/
public static function replaceSpecialCharacters($text) {
return str_replace(array("\n", "\t"), array("\\n", "\\t"), $text);
}
}
}

View File

@ -79,7 +79,9 @@
<li class="nav-item" role="presentation">
<a class="nav-link" id="Chars-tab" data-toggle="tab" href="#Chars" role="tab" aria-controls="Chars" aria-selected="false">Character Editor</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="tbl-tab" data-toggle="tab" href="#Tbl" role="tab" aria-controls="Tbl" aria-selected="false">TBL Editor</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="Doc-tab" data-toggle="tab" href="#Doc" role="tab" aria-controls="Doc" aria-selected="false">Documentation Generator</a>
</li>
@ -116,6 +118,9 @@
<div class="tab-pane fade" id="Chars" role="tabpanel" aria-labelledby="Chars-tab">
<?php require_once 'tabs/Chars.php'; ?>
</div>
<div class="tab-pane fade" id="Tbl" role="tabpanel" aria-labelledby="Tbl-tab">
<?php require_once 'tabs/Tbl.php'; ?>
</div>
<div class="tab-pane fade" id="Debug" role="tabpanel" aria-labelledby="Debug-tab">
<?php require_once 'tabs/Debug.php'; ?>
</div>