char * strAppend (char * target, const char * s1, const char * s2) { target = strAppend (target, s1); target = strAppend (target, s2); return target; }
int sendCGIHTTPResponseHeader(http_cgi_response *header) { int i_index = 0; int i_success = 0; char* cp_cgi_http_response_header = NULL; if(header == NULL) return EXIT_FAILURE; strAppend(&cp_cgi_http_response_header, "HTTP/1.1 "); strAppend(&cp_cgi_http_response_header, header->status); strAppend(&cp_cgi_http_response_header, "\n"); for(i_index = 0; i_index < header->i_num_fields; i_index++) { strAppend(&cp_cgi_http_response_header, header->cpp_header_field_name[i_index]); strAppend(&cp_cgi_http_response_header, ": "); strAppend(&cp_cgi_http_response_header, header->cpp_header_field_body[i_index]); strAppend(&cp_cgi_http_response_header, "\n"); } strAppend(&cp_cgi_http_response_header, "\n"); i_success = writeStringToFile(STDOUT_FILENO, cp_cgi_http_response_header); return i_success; }
void backupEeprom() { char filename[60]; uint8_t buffer[1024]; FIL file; lcd_clear(); displayProgressBar(STR_WRITING); // reset unexpectedShutdown to prevent warning when user restores EEPROM backup g_eeGeneral.unexpectedShutdown = 0; eeDirty(EE_GENERAL); eeCheck(true); // create the directory if needed... DIR folder; FRESULT result = f_opendir(&folder, EEPROMS_PATH); if (result != FR_OK) { if (result == FR_NO_PATH) result = f_mkdir(EEPROMS_PATH); if (result != FR_OK) { POPUP_WARNING(SDCARD_ERROR(result)); return; } } // prepare the filename... char * tmp = strAppend(filename, EEPROMS_PATH "/eeprom"); tmp = strAppendDate(tmp, true); strAppend(tmp, EEPROM_EXT); // open the file for writing... f_open(&file, filename, FA_WRITE | FA_CREATE_ALWAYS); for (int i=0; i<EESIZE; i+=1024) { UINT count; eepromReadBlock(buffer, i, 1024); f_write(&file, buffer, 1024, &count); updateProgressBar(i, EESIZE); SIMU_SLEEP(100/*ms*/); } f_close(&file); //set back unexpectedShutdown g_eeGeneral.unexpectedShutdown = 1; eeDirty(EE_GENERAL); eeCheck(true); }
/**************************************************************** * @brief copy file * @param *filename: //! * @param *srcDir: //! * @param *destDir: //! ****************************************************************/ const char *fileCopy(const char *filename, const char *srcDir, const char *destDir) { FIL srcFile; FIL dstFile; char buf[256]; UINT read = sizeof(buf); UINT written = sizeof(buf); char path[2*CLIPBOARD_PATH_LEN+1]; char *tmp = strAppend(path, srcDir, CLIPBOARD_PATH_LEN); *tmp++ = '/'; strAppend(tmp, filename, CLIPBOARD_PATH_LEN); FRESULT result = f_open(&srcFile, path, FA_OPEN_EXISTING | FA_READ); if(result != FR_OK) { return SDCARD_ERROR(result); } tmp = strAppend(path, destDir, CLIPBOARD_PATH_LEN); *tmp++ = '/'; strAppend(tmp, filename, CLIPBOARD_PATH_LEN); result = f_open(&dstFile, path, FA_CREATE_ALWAYS | FA_WRITE); if(result != FR_OK) { f_close(&srcFile); return SDCARD_ERROR(result); } while(result==FR_OK && read==sizeof(buf) && written==sizeof(buf)) { result = f_read(&srcFile, buf, sizeof(buf), &read); if(result == FR_OK) { result = f_write(&dstFile, buf, read, &written); } } f_close(&dstFile); f_close(&srcFile); if(result != FR_OK) { return SDCARD_ERROR(result); } return NULL; }
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // renameFile(): // Renames the file from oldName to newName with the same suffix. // Returns OK if successfull, ERROR_FileMode otherwise. errorT renameFile (const char * oldName, const char * newName, const char * suffix) { fileNameT fnameOld, fnameNew; strCopy (fnameOld, oldName); strAppend (fnameOld, suffix); strCopy (fnameNew, newName); strAppend (fnameNew, suffix); if (rename (fnameOld, fnameNew) != 0) { return ERROR_FileMode; } return OK; }
END_TEST START_TEST(test_strAppend) { char *string; string = strCreate(); strCopy(string, "foo"); strAppend(string, "bar"); fail_unless(strEquals(string, "foobar"), NULL); strAppend(string, ""); fail_unless(strEquals(string, "foobar"), NULL); strAppend(string, "foo"); fail_unless(strEquals(string, "foobarfoo"), NULL); }
char * strAppend (char * target, uint u) { char temp [20]; sprintf (temp, "%u", u); return strAppend (target, temp); }
FRESULT readBinDir(DIR *dj, FILINFO *fno) { FRESULT fr; uint32_t loop; do { loop = 0; fr = f_readdir(dj, fno); // First entry if (fr != FR_OK || fno->fname[0] == 0) { break; } if (*fno->lfname == 0) { strAppend(fno->lfname, fno->fname); // Copy 8.3 name } int32_t len = strlen(fno->lfname) - 4; if (len < 0) { loop = 1; } if (fno->lfname[len] != '.') { loop = 1; } if ((fno->lfname[len + 1] != 'b') && (fno->lfname[len + 1] != 'B')) { loop = 1; } if ((fno->lfname[len + 2] != 'i') && (fno->lfname[len + 2] != 'I')) { loop = 1; } if ((fno->lfname[len + 3] != 'n') && (fno->lfname[len + 3] != 'N')) { loop = 1; } } while (loop); return fr; }
char * strAppend (char * target, int i) { char temp [20]; sprintf (temp, "%d", i); return strAppend (target, temp); }
int sendHTTPErrorMessage(int i_status) { char* cp_body = NULL; int i_success = 0; if(i_status > STATUS_OK && i_status <= STATUS_HTTP_VERSION_NOT_SUPPORTED) { strAppend(&cp_body, "<html><body>"); strAppend(&cp_body, getStatusCode(i_status)); strAppend(&cp_body, "</body></html>"); i_success = sendHTTPResponse(i_status, TEXT_HTML, cp_body); return i_success; } return EXIT_FAILURE; }
/** * @brief Transform a C string to a string. * @param from C string to be transformed * @param to string where the final data will be stored * @return Returns E_INTERNAL on memory allocation failure, * @return E_SUCCESS otherwise. */ int strCopyC(char *from, string *to) { to->len = 0; for (int i = 0; from[i] != '\0'; i++) if (strAppend(to, from[i]) != E_SUCCESS) return E_INTERNAL; return E_SUCCESS; }
/* * Format and return "timestamp" */ char* format_timestamp(char* timestamp) { char* month = (char*)malloc(sizeof(char*)*100); int monthNum; while(timestamp[0] != ' ') { charAppend(month, timestamp[0]); timestamp++; } timestamp++; char* monthAbrv = (char*)malloc(sizeof(char*)*100); monthNum = atoi(month); switch(monthNum) { case 1: monthAbrv = monthSet.jan; break; case 2: monthAbrv = monthSet.feb; break; case 3: monthAbrv = monthSet.mar; break; case 4: monthAbrv = monthSet.apr; break; case 5: monthAbrv = monthSet.may; break; case 6: monthAbrv = monthSet.jun; break; case 7: monthAbrv = monthSet.jul; break; case 8: monthAbrv = monthSet.aug; break; case 9: monthAbrv = monthSet.sep; break; case 10: monthAbrv = monthSet.oct; break; case 11: monthAbrv = monthSet.nov; break; case 12: monthAbrv = monthSet.dec; break; } timestamp = strAppend(monthAbrv, timestamp); return timestamp; }
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // createFile(): // Creates (and immediately closes) an empty file. // Returns OK if successfull, ERROR_FileOpen otherwise. errorT createFile (const char * name, const char * suffix) { fileNameT fname; strCopy (fname, name); strAppend (fname, suffix); FILE * fp = fopen (fname, "w"); if (!fp) { return ERROR_FileOpen; } fclose (fp); return OK; }
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // fileSize(): // Computes the plain (uncompressed) size of the named file, // using one of the other FileSize functions here. uint fileSize (const char * name, const char * suffix) { fileNameT fname; strCopy (fname, name); strAppend (fname, suffix); const char * lastSuffix = strFileSuffix (fname); if (lastSuffix != NULL && strEqual (lastSuffix, GZIP_SUFFIX)) { return gzipFileSize (fname); } return rawFileSize (fname); }
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // fileExists(): // Returns true if the file exists, false otherwise. bool fileExists (const char * name, const char * suffix) { struct stat statBuf; // Defined in <sys/stat.h> fileNameT fname; strCopy (fname, name); strAppend (fname, suffix); if (stat (fname, &statBuf) != 0) { return false; } return true; }
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // removeFile(): // Removes the file given the filename and suffix. // Returns OK if successfull, ERROR_FileMode otherwise. errorT removeFile (const char * name, const char * suffix) { fileNameT fname; strCopy (fname, name); strAppend (fname, suffix); if (remove (fname) != 0) { return ERROR_FileMode; } return OK; }
FRESULT openBinaryFile(uint32_t index) { TCHAR filename[60]; FRESULT fr; memset(Block_buffer, 0, sizeof(Block_buffer)); strAppend(strAppend(strAppend(filename, getBinaryPath()), "/"), Filenames[index]); if ((fr = f_open(&FlashFile, filename, FA_READ)) != FR_OK) { return fr; } if (memoryType == MEM_FLASH) { if ((fr = f_lseek(&FlashFile, BOOTLOADER_SIZE)) != FR_OK) { return fr; } } fr = f_read(&FlashFile, (BYTE *)Block_buffer, BLOCK_LEN, &BlockCount); if (BlockCount == BLOCK_LEN) return fr; else return FR_INVALID_OBJECT; }
string substr(string s, int i, int n) { string temp; if (strInit(&temp) != E_SUCCESS) return temp; for (int j = i; j < n; j++) if (strAppend(&temp, s.str[j]) != E_SUCCESS) return temp; return temp; }
int sendHTTPAuthorizationResponse(const char* ccp_realm, const char* ccp_nonce) { int i_success = 0; char* cp_http_auth_response = NULL; char* cp_body = "<html><body>Access Denied!</body></html>"; if(ccp_realm == NULL || ccp_nonce == NULL) return EXIT_FAILURE; cp_http_auth_response = secPrint2String("HTTP/1.1 %s\n", getStatusCode(STATUS_UNAUTHORIZED)); strAppend(&cp_http_auth_response, "Server: tiniweb/1.0\n"); strAppend(&cp_http_auth_response, "Connection: close\n"); strAppendFormatString(&cp_http_auth_response, "WWW-Authenticate: Digest realm=\"%s\", nonce=\"%s\"\n", ccp_realm, ccp_nonce); strAppendFormatString(&cp_http_auth_response, "Content-Type: %s\n", getContentType(TEXT_HTML)); strAppendFormatString(&cp_http_auth_response, "Content-Length: %d\n\n", strlen(cp_body)); strAppendFormatString(&cp_http_auth_response, "%s", cp_body); i_success = writeStringToFile(STDOUT_FILENO, cp_http_auth_response); return i_success; }
int sendHTTPResponseHeader(int i_status, int i_content_type, int i_content_length) { int i_success = 0; char* cp_http_response_header = NULL; cp_http_response_header = secPrint2String("HTTP/1.1 %s\n", getStatusCode(i_status)); strAppend(&cp_http_response_header, "Server: tiniweb/1.0\n"); strAppend(&cp_http_response_header, "Connection: close\n"); strAppendFormatString(&cp_http_response_header, "Content-Type: %s\n", getContentType(i_content_type)); if(i_content_length >= 0) { strAppendFormatString(&cp_http_response_header, "Content-Length: %i\n", i_content_length); } strAppend(&cp_http_response_header, "\n"); i_success = writeStringToFile(STDOUT_FILENO, cp_http_response_header); return i_success; }
string concat(string s1, string s2) { string temp; if (strInit(&temp) != E_SUCCESS) return temp; if (strCopy(&s1, &temp) != E_SUCCESS) return temp; for (int i = 0, j = length(temp); i < length(s2); i++, j++) if (strAppend(&temp, s2.str[j]) != E_SUCCESS) return temp; return temp; }
int sendHTTPResponseHeaderExplicit(const char* ccp_status, const char* ccp_content_type, int i_content_length) { int i_success = 0; char* cp_http_response_header = NULL; if(ccp_content_type == NULL || ccp_status == NULL) return EXIT_FAILURE; cp_http_response_header = secPrint2String("HTTP/1.1 %s\n", ccp_status); strAppend(&cp_http_response_header, "Server: tiniweb/1.0\n"); strAppend(&cp_http_response_header, "Connection: close\n"); strAppendFormatString(&cp_http_response_header, "Content-Type: %s\n", ccp_content_type); if(i_content_length >= 0) { strAppendFormatString(&cp_http_response_header, "Content-Length: %i\n", i_content_length); } strAppend(&cp_http_response_header, "\n"); i_success = writeStringToFile(STDOUT_FILENO, cp_http_response_header); return i_success; }
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // PBook::StripOpcode: // Strips the specified opcode from every position in the book. // Only the first occurrence of an opcode is removed for any position, // but opcodes are not supposed to occur more than once anyway. // Returns the number of positions where an opcode was removed. uint PBook::StripOpcode (const char * opcode) { char * searchCode = new char [strLength(opcode) + 2]; strCopy (searchCode, opcode); strAppend (searchCode, " "); DString dstr; uint countFound = 0; for (uint i=0; i < NodeListCount; i++) { bookNodeT * node = NodeList[i]; if (node == NULL) { continue; } const char * s = node->data.comment; int startIndex = -1; int index = 0; // Look for a line with a matching opcode: while (*s != 0) { while (*s == '\n' || *s == ' ') { s++; index++; } if (strIsPrefix (searchCode, s)) { startIndex = index; countFound++; break; } while (*s != 0 && *s != '\n') { s++; index++; } } if (startIndex > -1) { s = node->data.comment; index = 0; // Add all characters before the line to be stripped: dstr.Clear(); while (index < startIndex) { dstr.AddChar (s[index]); index++; } // Now find the end of this line: s = &(s[startIndex + 1]); while (*s != 0 && *s != '\n') { s++; } if (*s == '\n') { s++; } while (*s != 0) { dstr.AddChar (*s); s++; } delete[] node->data.comment; node->data.comment = strDuplicate (dstr.Data()); } } delete[] searchCode; return countFound; }
bool testPathAppend(TCHAR *path, TCHAR *append) { TCHAR cPath[MAX_PATH]; generic_string strPath(path); generic_string strAppend(append); _tcscpy_s(cPath, MAX_PATH, path); BOOL strRet = PathAppend(strPath, strAppend); BOOL charRet = PathAppend(cPath, append); if (strRet != charRet || strPath != cPath) { _tprintf(_T("Testing |%s| append |%s| String (ours) |%s| returned %d Char (system) |%s| returned %d\r\n"), path, append, strPath.c_str(), strRet, cPath, charRet); } return ((strRet == charRet) && (strPath == cPath)); }
int main(){ str_t *s = strNew("Testing"); str_t *s2 = strNew(" this thing \n"); str_t *s3 = strNew(NULL); strCat(s, s2); strCpy(s3, s); strAppend(s3, "aaaaa"); printf("%lu, %lu, %lu %s\n", s->len, s->size, strlen(s->str), s->str); printf("%lu, %lu, %lu %s\n", s3->len, s3->size, strlen(s3->str), s3->str); str_t *c = strNew("testing"); strCpy(s, c); // strCpy(s2, c); printf("compare: %d\n", strCmp(s, s2)); strDel(s); strDel(s2); strDel(s3); return 0; }
int main (int argc, char * argv[]) { setbuf(stdout, NULL); // Make stdout unbuffered. gameNumberT gNumber; bool option_ForceReplace = false; bool option_PreGameComments = true; uint pgnFileSize = 0; char *progname = argv[0]; fileNameT fname; fileNameT baseName; uint argsleft = argc - 1; char ** nextArg = argv + 1; // Parse command-line argments: while (argsleft > 0 && nextArg[0][0] == '-') { if (! strCompare (*nextArg, "-f")) { option_ForceReplace = true; } else if (! strCompare (*nextArg, "-x")) { option_PreGameComments = false; } else { usage (progname); } argsleft--; nextArg++; } if (argsleft != 1 && argsleft != 2) { usage (progname); } char * pgnName = *nextArg; MFile pgnFile; pgnFileSize = fileSize (pgnName, ""); // Ensure positive file size counter to avoid division by zero: if (pgnFileSize < 1) { pgnFileSize = 1; } // Make baseName from pgnName if baseName is not provided: if (argsleft == 1) { strCopy (baseName, pgnName); // If a gzip file, remove two suffixes, the first being ".gz": const char * lastSuffix = strFileSuffix (baseName); if (lastSuffix != NULL && strEqual (lastSuffix, GZIP_SUFFIX)) { strTrimFileSuffix (baseName); } // Trim the ".pgn" suffix: strTrimFileSuffix (baseName); } else { strCopy (baseName, nextArg[1]); } // Check for existing database, avoid overwriting it: if (! option_ForceReplace) { if (fileSize (baseName, INDEX_SUFFIX) > 0) { // Scid index file already exists: fprintf (stderr, "%s: database already exists: %s\n", progname, baseName); fprintf (stderr, "You can use: %s -f %s to overwrite" " the existing database.\n", progname, pgnName); exit(1); } } if (pgnFile.Open (pgnName, FMODE_ReadOnly) != OK) { fprintf (stderr, "%s: could not open file %s\n", progname, pgnName); exit(1); } // Try opening the log file: strCopy (fname, baseName); strAppend (fname, ".err"); FILE * logFile = fopen (fname, "w"); if (logFile == NULL) { fprintf (stderr, "%s: could not open log file: %s\n", progname, fname); exit(1); } printf ("Converting file %s to Scid database %s:\n", pgnName, baseName); printf ("Errors/warnings will be written to %s.\n\n", fname); scid_Init(); GFile * gameFile = new GFile; if ((gameFile->Create (baseName, FMODE_WriteOnly)) != OK) { fprintf (stderr, "%s: could not create the file %s%s\n", progname, baseName, GFILE_SUFFIX); fprintf (stderr, "The file may already exist and be read-only, or\n"); fprintf (stderr, "you may not have permission to create this file.\n"); exit(1); } NameBase * nb = new NameBase; Index * idx = new Index; IndexEntry * ie = new IndexEntry; idx->SetFileName (baseName); idx->CreateIndexFile (FMODE_WriteOnly); Game * game = new Game; ProgBar progBar(stdout); progBar.Start(); ByteBuffer *bbuf = new ByteBuffer; bbuf->SetBufferSize (BBUF_SIZE); // 32768 PgnParser pgnParser (&pgnFile); pgnParser.SetErrorFile (logFile); pgnParser.SetPreGameText (option_PreGameComments); // TODO: Add command line option for ignored tags, rather than // just hardcoding PlyCount as the only ignored tag. pgnParser.AddIgnoredTag ("PlyCount"); // Add each game found to the database: while (pgnParser.ParseGame(game) != ERROR_NotFound) { ie->Init(); if (idx->AddGame (&gNumber, ie) != OK) { fprintf (stderr, "\nLimit of %d games reached!\n", MAX_GAMES); exit(1); } // Add the names to the namebase: idNumberT id = 0; if (nb->AddName (NAME_PLAYER, game->GetWhiteStr(), &id) != OK) { fatalNameError (NAME_PLAYER); } nb->IncFrequency (NAME_PLAYER, id, 1); ie->SetWhite (id); if (nb->AddName (NAME_PLAYER, game->GetBlackStr(), &id) != OK) { fatalNameError (NAME_PLAYER); } nb->IncFrequency (NAME_PLAYER, id, 1); ie->SetBlack (id); if (nb->AddName (NAME_EVENT, game->GetEventStr(), &id) != OK) { fatalNameError (NAME_EVENT); } nb->IncFrequency (NAME_EVENT, id, 1); ie->SetEvent (id); if (nb->AddName (NAME_SITE, game->GetSiteStr(), &id) != OK) { fatalNameError (NAME_SITE); } nb->IncFrequency (NAME_SITE, id, 1); ie->SetSite (id); if (nb->AddName (NAME_ROUND, game->GetRoundStr(), &id) != OK) { fatalNameError (NAME_ROUND); } nb->IncFrequency (NAME_ROUND, id, 1); ie->SetRound (id); bbuf->Empty(); if (game->Encode (bbuf, ie) != OK) { fprintf (stderr, "Fatal error encoding game!\n"); abort(); } uint offset = 0; if (gameFile->AddGame (bbuf, &offset) != OK) { fprintf (stderr, "Fatal error writing game file!\n"); abort(); } ie->SetOffset (offset); ie->SetLength (bbuf->GetByteCount()); idx->WriteEntries (ie, gNumber, 1); // Update the progress bar: if (! (gNumber % 100)) { int bytesSeen = pgnParser.BytesUsed(); int percentDone = 1 + ((bytesSeen) * 100 / pgnFileSize); progBar.Update (percentDone); } } uint t = 0; // = time(0); nb->SetTimeStamp(t); nb->SetFileName (baseName); if (nb->WriteNameFile() != OK) { fprintf (stderr, "Fatal error writing name file!\n"); exit(1); } progBar.Finish(); printf ("\nDatabase `%s': %d games, %d players, %d events, %d sites.\n", baseName, idx->GetNumGames(), nb->GetNumNames (NAME_PLAYER), nb->GetNumNames (NAME_EVENT), nb->GetNumNames (NAME_SITE)); fclose (logFile); if (pgnParser.ErrorCount() > 0) { printf ("There were %u errors or warnings; ", pgnParser.ErrorCount()); printf ("examine the file \"%s.err\"\n", baseName); } else { printf ("There were no warnings or errors.\n"); removeFile (baseName, ".err"); } gameFile->Close(); idx->CloseIndexFile(); // If there is a tree cache file for this database, it is out of date: removeFile (baseName, TREEFILE_SUFFIX); #ifdef ASSERTIONS printf("%d asserts were tested\n", numAsserts); #endif return 0; }
void menuGeneralSdManager(uint8_t _event) { if (s_warning_result) { s_warning_result = 0; displayPopup(STR_FORMATTING); closeLogs(); audioQueue.stopSD(); if (f_mkfs(0, 1, 0) == FR_OK) { f_chdir("/"); REFRESH_FILES(); } else { POPUP_WARNING(STR_SDCARD_ERROR); } } int lastPos = m_posVert; uint8_t event = (EVT_KEY_MASK(_event) == KEY_ENTER ? 0 : _event); SIMPLE_MENU(SD_IS_HC() ? STR_SDHC_CARD : STR_SD_CARD, menuTabGeneral, e_Sd, reusableBuffer.sdmanager.count); int index = m_posVert-s_pgOfs; switch(_event) { case EVT_ENTRY: f_chdir(ROOT_PATH); REFRESH_FILES(); lastPos = -1; break; case EVT_KEY_LONG(KEY_MENU): if (!READ_ONLY() && s_editMode == 0) { killEvents(_event); MENU_ADD_ITEM(STR_SD_INFO); MENU_ADD_ITEM(STR_SD_FORMAT); menuHandler = onSdManagerMenu; } break; case EVT_KEY_BREAK(KEY_EXIT): REFRESH_FILES(); break; case EVT_KEY_BREAK(KEY_ENTER): if (s_editMode > 0) { break; } else { if (!reusableBuffer.sdmanager.lines[index][SD_SCREEN_FILE_LENGTH+1]) { f_chdir(reusableBuffer.sdmanager.lines[index]); s_pgOfs = 0; m_posVert = 1; index = 1; REFRESH_FILES(); killEvents(_event); return; } } // no break case EVT_KEY_LONG(KEY_ENTER): if (s_editMode == 0) { killEvents(_event); char *line = reusableBuffer.sdmanager.lines[index]; char *ext = getFileExtension(line, SD_SCREEN_FILE_LENGTH+1); if (ext) { if (!strcasecmp(ext, SOUNDS_EXT)) { MENU_ADD_ITEM(STR_PLAY_FILE); } else if (!strcasecmp(ext, BITMAPS_EXT)) { if (!READ_ONLY() && (ext-line) <= (int)sizeof(g_model.header.bitmap)) { MENU_ADD_ITEM(STR_ASSIGN_BITMAP); } } else if (!strcasecmp(ext, TEXT_EXT)) { MENU_ADD_ITEM(STR_VIEW_TEXT); } #if defined(LUA) else if (!strcasecmp(ext, SCRIPTS_EXT)) { MENU_ADD_ITEM(STR_EXECUTE_FILE); } #endif else if (!READ_ONLY() && !strcasecmp(ext, FIRMWARE_EXT)) { TCHAR lfn[_MAX_LFN + 1]; getSelectionFullPath(lfn); if (isBootloader(lfn)) { MENU_ADD_ITEM(STR_FLASH_BOOTLOADER); } } else if (!READ_ONLY() && !strcasecmp(ext, SPORT_FIRMWARE_EXT)) { MENU_ADD_ITEM(STR_FLASH_EXTERNAL_DEVICE); MENU_ADD_ITEM(STR_FLASH_INTERNAL_MODULE); } } if (!READ_ONLY()) { if (line[SD_SCREEN_FILE_LENGTH+1]) // it's a file MENU_ADD_ITEM(STR_COPY_FILE); if (clipboard.type == CLIPBOARD_TYPE_SD_FILE) MENU_ADD_ITEM(STR_PASTE); MENU_ADD_ITEM(STR_RENAME_FILE); MENU_ADD_ITEM(STR_DELETE_FILE); } menuHandler = onSdManagerMenu; } break; } if (reusableBuffer.sdmanager.offset != s_pgOfs) { FILINFO fno; DIR dir; char *fn; /* This function is assuming non-Unicode cfg. */ TCHAR lfn[_MAX_LFN + 1]; fno.lfname = lfn; fno.lfsize = sizeof(lfn); if (s_pgOfs == 0) { reusableBuffer.sdmanager.offset = 0; memset(reusableBuffer.sdmanager.lines, 0, sizeof(reusableBuffer.sdmanager.lines)); } else if (s_pgOfs == reusableBuffer.sdmanager.count-7) { reusableBuffer.sdmanager.offset = s_pgOfs; memset(reusableBuffer.sdmanager.lines, 0, sizeof(reusableBuffer.sdmanager.lines)); } else if (s_pgOfs > reusableBuffer.sdmanager.offset) { memmove(reusableBuffer.sdmanager.lines[0], reusableBuffer.sdmanager.lines[1], 6*sizeof(reusableBuffer.sdmanager.lines[0])); memset(reusableBuffer.sdmanager.lines[6], 0xff, SD_SCREEN_FILE_LENGTH); reusableBuffer.sdmanager.lines[6][SD_SCREEN_FILE_LENGTH+1] = 1; } else { memmove(reusableBuffer.sdmanager.lines[1], reusableBuffer.sdmanager.lines[0], 6*sizeof(reusableBuffer.sdmanager.lines[0])); memset(reusableBuffer.sdmanager.lines[0], 0, sizeof(reusableBuffer.sdmanager.lines[0])); } reusableBuffer.sdmanager.count = 0; FRESULT res = f_opendir(&dir, "."); /* Open the directory */ if (res == FR_OK) { for (;;) { res = f_readdir(&dir, &fno); /* Read a directory item */ if (res != FR_OK || fno.fname[0] == 0) break; /* Break on error or end of dir */ if (fno.fname[0] == '.' && fno.fname[1] == '\0') continue; /* Ignore dot entry */ #if _USE_LFN fn = *fno.lfname ? fno.lfname : fno.fname; #else fn = fno.fname; #endif if (strlen(fn) > SD_SCREEN_FILE_LENGTH) continue; reusableBuffer.sdmanager.count++; bool isfile = !(fno.fattrib & AM_DIR); if (s_pgOfs == 0) { for (int i=0; i<NUM_BODY_LINES; i++) { char *line = reusableBuffer.sdmanager.lines[i]; if (line[0] == '\0' || isFilenameLower(isfile, fn, line)) { if (i < 6) memmove(reusableBuffer.sdmanager.lines[i+1], line, sizeof(reusableBuffer.sdmanager.lines[i]) * (6-i)); memset(line, 0, sizeof(reusableBuffer.sdmanager.lines[i])); strcpy(line, fn); line[SD_SCREEN_FILE_LENGTH+1] = isfile; break; } } } else if (reusableBuffer.sdmanager.offset == s_pgOfs) { for (int8_t i=6; i>=0; i--) { char *line = reusableBuffer.sdmanager.lines[i]; if (line[0] == '\0' || isFilenameGreater(isfile, fn, line)) { if (i > 0) memmove(reusableBuffer.sdmanager.lines[0], reusableBuffer.sdmanager.lines[1], sizeof(reusableBuffer.sdmanager.lines[0]) * i); memset(line, 0, sizeof(reusableBuffer.sdmanager.lines[i])); strcpy(line, fn); line[SD_SCREEN_FILE_LENGTH+1] = isfile; break; } } } else if (s_pgOfs > reusableBuffer.sdmanager.offset) { if (isFilenameGreater(isfile, fn, reusableBuffer.sdmanager.lines[5]) && isFilenameLower(isfile, fn, reusableBuffer.sdmanager.lines[6])) { memset(reusableBuffer.sdmanager.lines[6], 0, sizeof(reusableBuffer.sdmanager.lines[0])); strcpy(reusableBuffer.sdmanager.lines[6], fn); reusableBuffer.sdmanager.lines[6][SD_SCREEN_FILE_LENGTH+1] = isfile; } } else { if (isFilenameLower(isfile, fn, reusableBuffer.sdmanager.lines[1]) && isFilenameGreater(isfile, fn, reusableBuffer.sdmanager.lines[0])) { memset(reusableBuffer.sdmanager.lines[0], 0, sizeof(reusableBuffer.sdmanager.lines[0])); strcpy(reusableBuffer.sdmanager.lines[0], fn); reusableBuffer.sdmanager.lines[0][SD_SCREEN_FILE_LENGTH+1] = isfile; } } } } } reusableBuffer.sdmanager.offset = s_pgOfs; for (int i=0; i<NUM_BODY_LINES; i++) { coord_t y = MENU_HEADER_HEIGHT + 1 + i*FH; lcdNextPos = 0; LcdFlags attr = (index == i ? BSS|INVERS : BSS); if (reusableBuffer.sdmanager.lines[i][0]) { if (!reusableBuffer.sdmanager.lines[i][SD_SCREEN_FILE_LENGTH+1]) { lcd_putcAtt(0, y, '[', s_editMode == EDIT_MODIFY_STRING ? 0 : attr); } if (s_editMode == EDIT_MODIFY_STRING && attr) { editName(lcdNextPos, y, reusableBuffer.sdmanager.lines[i], SD_SCREEN_FILE_LENGTH-4, _event, attr, 0); if (s_editMode == 0) { unsigned int len = effectiveLen(reusableBuffer.sdmanager.lines[i], SD_SCREEN_FILE_LENGTH-LEN_FILE_EXTENSION); char * ext = getFileExtension(reusableBuffer.sdmanager.originalName, sizeof(reusableBuffer.sdmanager.originalName)); if (ext) { strAppend(&reusableBuffer.sdmanager.lines[i][len], ext); } f_rename(reusableBuffer.sdmanager.originalName, reusableBuffer.sdmanager.lines[i]); REFRESH_FILES(); } } else { lcd_putsAtt(lcdNextPos, y, reusableBuffer.sdmanager.lines[i], attr); } if (!reusableBuffer.sdmanager.lines[i][SD_SCREEN_FILE_LENGTH+1]) { lcd_putcAtt(lcdNextPos, y, ']', s_editMode == EDIT_MODIFY_STRING ? 0 : attr); } } } char *ext = getFileExtension(reusableBuffer.sdmanager.lines[index], SD_SCREEN_FILE_LENGTH+1); if (ext && !strcasecmp(ext, BITMAPS_EXT)) { if (lastPos != m_posVert) { if (bmpLoad(modelBitmap, reusableBuffer.sdmanager.lines[index], MODEL_BITMAP_WIDTH, MODEL_BITMAP_HEIGHT)) { memcpy(modelBitmap, logo_taranis, MODEL_BITMAP_SIZE); } } lcd_bmp(22*FW+2, 2*FH+FH/2, modelBitmap); } }
errorT TreeCache::ReadFile (const char * fname) { // Only read the file if the cache is empty: if (NumInUse > 0) { return OK; } #ifdef WINCE /*FILE * */Tcl_Channel fp; fileNameT fullname; strCopy (fullname, fname); strAppend (fullname, TREEFILE_SUFFIX); //fp = fopen (fullname, "rb"); fp = mySilent_Tcl_OpenFileChannel(NULL, fullname, "r", 0666); if (fp == NULL) { return ERROR_FileOpen; } my_Tcl_SetChannelOption(NULL, fp, "-encoding", "binary"); my_Tcl_SetChannelOption(NULL, fp, "-translation", "binary"); uint magic = readFourBytes (fp); if (magic != TREEFILE_MAGIC) { //fclose (fp); my_Tcl_Close(NULL, fp); #else FILE * fp; fileNameT fullname; strCopy (fullname, fname); strAppend (fullname, TREEFILE_SUFFIX); fp = fopen (fullname, "rb"); if (fp == NULL) { return ERROR_FileOpen; } uint magic = readFourBytes (fp); if (magic != TREEFILE_MAGIC) { fclose (fp); #endif return ERROR_Corrupt; } readTwoBytes (fp); // Scid Version; unused uint cacheSize = readFourBytes (fp); SetCacheSize (cacheSize); NumInUse = readFourBytes (fp); LowestTotal = readFourBytes (fp); LowestTotalIndex = readFourBytes(fp); for (uint count=0; count < NumInUse; count++) { cachedTreeT * ctree = &(Cache[count]); ctree->toMove = readOneByte (fp); for (squareT sq=0; sq < 64; sq++) { ctree->board[sq] = readOneByte (fp); } // Read the moves: ctree->tree.moveCount = readFourBytes (fp); ctree->tree.totalCount = readFourBytes (fp); uint numMoves = ctree->tree.moveCount; for (uint i=0; i < numMoves; i++) { // Read this move node: treeNodeT * tnode = &(ctree->tree.node[i]); readSimpleMove (fp, &(tnode->sm)); readString (fp, tnode->san, 8); for (uint res = 0; res < 4; res++) { tnode->freq[res] = readFourBytes (fp); } tnode->total = readFourBytes (fp); tnode->score = readFourBytes (fp); tnode->ecoCode = readTwoBytes (fp); tnode->eloCount = readFourBytes (fp); tnode->eloSum = readFourBytes (fp); tnode->perfCount = readFourBytes (fp); tnode->perfSum = readFourBytes (fp); tnode->yearCount = readFourBytes (fp); tnode->yearSum = readFourBytes (fp); } // Read the compressed filter: ctree->cfilter = new CompressedFilter; ctree->cfilter->ReadFromFile (fp); } #ifdef WINCE my_Tcl_Close(NULL, fp); #else fclose (fp); #endif return OK; }
errorT TreeCache::WriteFile (const char * fname) { #ifdef WINCE /*FILE **/Tcl_Channel fp; fileNameT fullname; strCopy (fullname, fname); strAppend (fullname, TREEFILE_SUFFIX); // fp = fopen (fullname, "wb"); fp = my_Tcl_OpenFileChannel(NULL, fullname, "w", 0666); if (fp == NULL) { return ERROR_FileOpen; } my_Tcl_SetChannelOption(NULL, fp, "-encoding", "binary"); my_Tcl_SetChannelOption(NULL, fp, "-translation", "binary"); #else FILE * fp; fileNameT fullname; strCopy (fullname, fname); strAppend (fullname, TREEFILE_SUFFIX); fp = fopen (fullname, "wb"); if (fp == NULL) { return ERROR_FileOpen; } #endif writeFourBytes (fp, TREEFILE_MAGIC); writeTwoBytes (fp, SCID_VERSION); writeFourBytes (fp, CacheSize); writeFourBytes (fp, NumInUse); writeFourBytes (fp, LowestTotal); writeFourBytes (fp, LowestTotalIndex); for (uint count = 0; count < NumInUse; count++) { // Write this cached position: cachedTreeT * ctree = &(Cache[count]); writeOneByte (fp, ctree->toMove); for (squareT sq=0; sq < 64; sq++) { writeOneByte (fp, ctree->board[sq]); } // Write the moves: writeFourBytes (fp, ctree->tree.moveCount); writeFourBytes (fp, ctree->tree.totalCount); uint numMoves = ctree->tree.moveCount; for (uint i=0; i < numMoves; i++) { // Write this move node: treeNodeT * tnode = &(ctree->tree.node[i]); writeSimpleMove (fp, &(tnode->sm)); writeString (fp, tnode->san, 8); for (uint res = 0; res < 4; res++) { writeFourBytes (fp, tnode->freq[res]); } writeFourBytes (fp, tnode->total); writeFourBytes (fp, tnode->score); writeTwoBytes (fp, tnode->ecoCode); writeFourBytes (fp, tnode->eloCount); writeFourBytes (fp, tnode->eloSum); writeFourBytes (fp, tnode->perfCount); writeFourBytes (fp, tnode->perfSum); writeFourBytes (fp, tnode->yearCount); writeFourBytes (fp, tnode->yearSum); } // Write the compressed filter: ctree->cfilter->WriteToFile (fp); } #ifdef WINCE my_Tcl_Close(NULL, fp); #else fclose (fp); #endif return OK; }