My Marlin configs for Fabrikator Mini and CTC i3 Pro B
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

cardreader.cpp 38KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
  4. *
  5. * Based on Sprinter and grbl.
  6. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. *
  21. */
  22. #include "../inc/MarlinConfig.h"
  23. #if ENABLED(SDSUPPORT)
  24. //#define DEBUG_CARDREADER
  25. #include "cardreader.h"
  26. #include "../MarlinCore.h"
  27. #include "../lcd/marlinui.h"
  28. #if ENABLED(DWIN_CREALITY_LCD)
  29. #include "../lcd/e3v2/creality/dwin.h"
  30. #elif ENABLED(DWIN_CREALITY_LCD_ENHANCED)
  31. #include "../lcd/e3v2/enhanced/dwin.h"
  32. #endif
  33. #include "../module/planner.h" // for synchronize
  34. #include "../module/printcounter.h"
  35. #include "../gcode/queue.h"
  36. #include "../module/settings.h"
  37. #include "../module/stepper/indirection.h"
  38. #if ENABLED(EMERGENCY_PARSER)
  39. #include "../feature/e_parser.h"
  40. #endif
  41. #if ENABLED(POWER_LOSS_RECOVERY)
  42. #include "../feature/powerloss.h"
  43. #endif
  44. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  45. #include "../feature/pause.h"
  46. #endif
  47. #define DEBUG_OUT EITHER(DEBUG_CARDREADER, MARLIN_DEV_MODE)
  48. #include "../core/debug_out.h"
  49. #include "../libs/hex_print.h"
  50. // extern
  51. PGMSTR(M21_STR, "M21");
  52. PGMSTR(M23_STR, "M23 %s");
  53. PGMSTR(M24_STR, "M24");
  54. // public:
  55. card_flags_t CardReader::flag;
  56. char CardReader::filename[FILENAME_LENGTH], CardReader::longFilename[LONG_FILENAME_LENGTH];
  57. IF_DISABLED(NO_SD_AUTOSTART, uint8_t CardReader::autofile_index); // = 0
  58. #if ENABLED(BINARY_FILE_TRANSFER)
  59. serial_index_t IF_DISABLED(HAS_MULTI_SERIAL, constexpr) CardReader::transfer_port_index;
  60. #endif
  61. // private:
  62. SdFile CardReader::root, CardReader::workDir, CardReader::workDirParents[MAX_DIR_DEPTH];
  63. uint8_t CardReader::workDirDepth;
  64. #if ENABLED(SDCARD_SORT_ALPHA)
  65. uint16_t CardReader::sort_count;
  66. #if ENABLED(SDSORT_GCODE)
  67. bool CardReader::sort_alpha;
  68. int CardReader::sort_folders;
  69. //bool CardReader::sort_reverse;
  70. #endif
  71. #if ENABLED(SDSORT_DYNAMIC_RAM)
  72. uint8_t *CardReader::sort_order;
  73. #else
  74. uint8_t CardReader::sort_order[SDSORT_LIMIT];
  75. #endif
  76. #if ENABLED(SDSORT_USES_RAM)
  77. #if ENABLED(SDSORT_CACHE_NAMES)
  78. uint16_t CardReader::nrFiles; // Cached total file count
  79. #if ENABLED(SDSORT_DYNAMIC_RAM)
  80. char **CardReader::sortshort, **CardReader::sortnames;
  81. #else
  82. char CardReader::sortshort[SDSORT_LIMIT][FILENAME_LENGTH];
  83. char CardReader::sortnames[SDSORT_LIMIT][SORTED_LONGNAME_STORAGE];
  84. #endif
  85. #elif DISABLED(SDSORT_USES_STACK)
  86. char CardReader::sortnames[SDSORT_LIMIT][SORTED_LONGNAME_STORAGE];
  87. #endif
  88. #if HAS_FOLDER_SORTING
  89. #if ENABLED(SDSORT_DYNAMIC_RAM)
  90. uint8_t *CardReader::isDir;
  91. #elif ENABLED(SDSORT_CACHE_NAMES) || DISABLED(SDSORT_USES_STACK)
  92. uint8_t CardReader::isDir[(SDSORT_LIMIT+7)>>3];
  93. #endif
  94. #define IS_DIR(n) TEST(isDir[(n) >> 3], (n) & 0x07)
  95. #endif
  96. #endif // SDSORT_USES_RAM
  97. #endif // SDCARD_SORT_ALPHA
  98. #if HAS_USB_FLASH_DRIVE
  99. DiskIODriver_USBFlash CardReader::media_driver_usbFlash;
  100. #endif
  101. #if NEED_SD2CARD_SDIO || NEED_SD2CARD_SPI
  102. CardReader::sdcard_driver_t CardReader::media_driver_sdcard;
  103. #endif
  104. DiskIODriver* CardReader::driver = nullptr;
  105. SdVolume CardReader::volume;
  106. SdFile CardReader::file;
  107. #if HAS_MEDIA_SUBCALLS
  108. uint8_t CardReader::file_subcall_ctr;
  109. uint32_t CardReader::filespos[SD_PROCEDURE_DEPTH];
  110. char CardReader::proc_filenames[SD_PROCEDURE_DEPTH][MAXPATHNAMELENGTH];
  111. #endif
  112. uint32_t CardReader::filesize, CardReader::sdpos;
  113. CardReader::CardReader() {
  114. changeMedia(&
  115. #if HAS_USB_FLASH_DRIVE && !SHARED_VOLUME_IS(SD_ONBOARD)
  116. media_driver_usbFlash
  117. #else
  118. media_driver_sdcard
  119. #endif
  120. );
  121. #if ENABLED(SDCARD_SORT_ALPHA)
  122. sort_count = 0;
  123. #if ENABLED(SDSORT_GCODE)
  124. sort_alpha = true;
  125. sort_folders = FOLDER_SORTING;
  126. //sort_reverse = false;
  127. #endif
  128. #endif
  129. flag.sdprinting = flag.sdprintdone = flag.mounted = flag.saving = flag.logging = false;
  130. filesize = sdpos = 0;
  131. TERN_(HAS_MEDIA_SUBCALLS, file_subcall_ctr = 0);
  132. IF_DISABLED(NO_SD_AUTOSTART, autofile_cancel());
  133. workDirDepth = 0;
  134. ZERO(workDirParents);
  135. #if ENABLED(SDSUPPORT) && PIN_EXISTS(SD_DETECT)
  136. SET_INPUT_PULLUP(SD_DETECT_PIN);
  137. #endif
  138. #if PIN_EXISTS(SDPOWER)
  139. OUT_WRITE(SDPOWER_PIN, HIGH); // Power the SD reader
  140. #endif
  141. }
  142. //
  143. // Get a DOS 8.3 filename in its useful form
  144. //
  145. char *createFilename(char * const buffer, const dir_t &p) {
  146. char *pos = buffer;
  147. LOOP_L_N(i, 11) {
  148. if (p.name[i] == ' ') continue;
  149. if (i == 8) *pos++ = '.';
  150. *pos++ = p.name[i];
  151. }
  152. *pos++ = 0;
  153. return buffer;
  154. }
  155. //
  156. // Return 'true' if the item is a folder or G-code file
  157. //
  158. bool CardReader::is_dir_or_gcode(const dir_t &p) {
  159. //uint8_t pn0 = p.name[0];
  160. if ( (p.attributes & DIR_ATT_HIDDEN) // Hidden by attribute
  161. // When readDir() > 0 these must be false:
  162. //|| pn0 == DIR_NAME_FREE || pn0 == DIR_NAME_DELETED // Clear or Deleted entry
  163. //|| pn0 == '.' || longFilename[0] == '.' // Hidden file
  164. //|| !DIR_IS_FILE_OR_SUBDIR(&p) // Not a File or Directory
  165. ) return false;
  166. flag.filenameIsDir = DIR_IS_SUBDIR(&p); // We know it's a File or Folder
  167. return (
  168. flag.filenameIsDir // All Directories are ok
  169. || (p.name[8] == 'G' && p.name[9] != '~') // Non-backup *.G* files are accepted
  170. );
  171. }
  172. //
  173. // Get the number of (compliant) items in the folder
  174. //
  175. int CardReader::countItems(SdFile dir) {
  176. dir_t p;
  177. int c = 0;
  178. while (dir.readDir(&p, longFilename) > 0)
  179. c += is_dir_or_gcode(p);
  180. #if ALL(SDCARD_SORT_ALPHA, SDSORT_USES_RAM, SDSORT_CACHE_NAMES)
  181. nrFiles = c;
  182. #endif
  183. return c;
  184. }
  185. //
  186. // Get file/folder info for an item by index
  187. //
  188. void CardReader::selectByIndex(SdFile dir, const uint8_t index) {
  189. dir_t p;
  190. for (uint8_t cnt = 0; dir.readDir(&p, longFilename) > 0;) {
  191. if (is_dir_or_gcode(p)) {
  192. if (cnt == index) {
  193. createFilename(filename, p);
  194. return; // 0 based index
  195. }
  196. cnt++;
  197. }
  198. }
  199. }
  200. //
  201. // Get file/folder info for an item by name
  202. //
  203. void CardReader::selectByName(SdFile dir, const char * const match) {
  204. dir_t p;
  205. for (uint8_t cnt = 0; dir.readDir(&p, longFilename) > 0; cnt++) {
  206. if (is_dir_or_gcode(p)) {
  207. createFilename(filename, p);
  208. if (strcasecmp(match, filename) == 0) return;
  209. }
  210. }
  211. }
  212. /**
  213. * Recursive method to print all files within a folder in flat
  214. * DOS 8.3 format. This style of listing is the most compatible
  215. * with legacy hosts.
  216. *
  217. * This method recurses to unlimited depth and lists all G-code
  218. * files within the given parent. If the hierarchy is very deep
  219. * this can blow up the stack, so a 'depth' parameter would be a
  220. * good addition.
  221. */
  222. void CardReader::printListing(
  223. SdFile parent, const char * const prepend
  224. OPTARG(LONG_FILENAME_HOST_SUPPORT, const bool includeLongNames/*=false*/)
  225. OPTARG(LONG_FILENAME_HOST_SUPPORT, const char * const prependLong/*=nullptr*/)
  226. ) {
  227. dir_t p;
  228. while (parent.readDir(&p, longFilename) > 0) {
  229. if (DIR_IS_SUBDIR(&p)) {
  230. size_t lenPrepend = prepend ? strlen(prepend) + 1 : 0;
  231. // Allocate enough stack space for the full path including / separator
  232. char path[lenPrepend + FILENAME_LENGTH];
  233. if (prepend) { strcpy(path, prepend); path[lenPrepend - 1] = '/'; }
  234. char* dosFilename = path + lenPrepend;
  235. createFilename(dosFilename, p);
  236. // Get a new directory object using the full path
  237. // and dive recursively into it.
  238. SdFile child; // child.close() in destructor
  239. if (child.open(&parent, dosFilename, O_READ)) {
  240. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  241. if (includeLongNames) {
  242. size_t lenPrependLong = prependLong ? strlen(prependLong) + 1 : 0;
  243. // Allocate enough stack space for the full long path including / separator
  244. char pathLong[lenPrependLong + strlen(longFilename) + 1];
  245. if (prependLong) { strcpy(pathLong, prependLong); pathLong[lenPrependLong - 1] = '/'; }
  246. strcpy(pathLong + lenPrependLong, longFilename);
  247. printListing(child, path, true, pathLong);
  248. }
  249. else
  250. printListing(child, path);
  251. #else
  252. printListing(child, path);
  253. #endif
  254. }
  255. else {
  256. SERIAL_ECHO_MSG(STR_SD_CANT_OPEN_SUBDIR, dosFilename);
  257. return;
  258. }
  259. }
  260. else if (is_dir_or_gcode(p)) {
  261. if (prepend) { SERIAL_ECHO(prepend); SERIAL_CHAR('/'); }
  262. SERIAL_ECHO(createFilename(filename, p));
  263. SERIAL_CHAR(' ');
  264. SERIAL_ECHO(p.fileSize);
  265. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  266. if (includeLongNames) {
  267. SERIAL_CHAR(' ');
  268. if (prependLong) { SERIAL_ECHO(prependLong); SERIAL_CHAR('/'); }
  269. SERIAL_ECHO(longFilename[0] ? longFilename : "???");
  270. }
  271. #endif
  272. SERIAL_EOL();
  273. }
  274. }
  275. }
  276. //
  277. // List all files on the SD card
  278. //
  279. void CardReader::ls(TERN_(LONG_FILENAME_HOST_SUPPORT, bool includeLongNames/*=false*/)) {
  280. if (flag.mounted) {
  281. root.rewind();
  282. printListing(root, nullptr OPTARG(LONG_FILENAME_HOST_SUPPORT, includeLongNames));
  283. }
  284. }
  285. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  286. //
  287. // Get a long pretty path based on a DOS 8.3 path
  288. //
  289. void CardReader::printLongPath(char * const path) {
  290. int i, pathLen = path ? strlen(path) : 0;
  291. // SERIAL_ECHOPGM("Full Path: "); SERIAL_ECHOLN(path);
  292. // Zero out slashes to make segments
  293. for (i = 0; i < pathLen; i++) if (path[i] == '/') path[i] = '\0';
  294. SdFile diveDir = root; // start from the root for segment 1
  295. for (i = 0; i < pathLen;) {
  296. if (path[i] == '\0') i++; // move past a single nul
  297. char *segment = &path[i]; // The segment after most slashes
  298. // If a segment is empty (extra-slash) then exit
  299. if (!*segment) break;
  300. // Go to the next segment
  301. while (path[++i]) { }
  302. //SERIAL_ECHOLNPGM("Looking for segment: ", segment);
  303. // Find the item, setting the long filename
  304. diveDir.rewind();
  305. selectByName(diveDir, segment);
  306. // Print /LongNamePart to serial output
  307. SERIAL_CHAR('/');
  308. SERIAL_ECHO(longFilename[0] ? longFilename : "???");
  309. // If the filename was printed then that's it
  310. if (!flag.filenameIsDir) break;
  311. // SERIAL_ECHOPGM("Opening dir: "); SERIAL_ECHOLN(segment);
  312. // Open the sub-item as the new dive parent
  313. SdFile dir;
  314. if (!dir.open(&diveDir, segment, O_READ)) {
  315. SERIAL_EOL();
  316. SERIAL_ECHO_START();
  317. SERIAL_ECHOPGM(STR_SD_CANT_OPEN_SUBDIR, segment);
  318. break;
  319. }
  320. diveDir.close();
  321. diveDir = dir;
  322. } // while i<pathLen
  323. SERIAL_EOL();
  324. }
  325. #endif // LONG_FILENAME_HOST_SUPPORT
  326. //
  327. // Echo the DOS 8.3 filename (and long filename, if any)
  328. //
  329. void CardReader::printSelectedFilename() {
  330. if (file.isOpen()) {
  331. char dosFilename[FILENAME_LENGTH];
  332. file.getDosName(dosFilename);
  333. SERIAL_ECHO(dosFilename);
  334. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  335. selectFileByName(dosFilename);
  336. if (longFilename[0]) {
  337. SERIAL_CHAR(' ');
  338. SERIAL_ECHO(longFilename);
  339. }
  340. #endif
  341. }
  342. else
  343. SERIAL_ECHOPGM("(no file)");
  344. SERIAL_EOL();
  345. }
  346. void CardReader::mount() {
  347. flag.mounted = false;
  348. if (root.isOpen()) root.close();
  349. if (!driver->init(SD_SPI_SPEED, SDSS)
  350. #if defined(LCD_SDSS) && (LCD_SDSS != SDSS)
  351. && !driver->init(SD_SPI_SPEED, LCD_SDSS)
  352. #endif
  353. ) SERIAL_ECHO_MSG(STR_SD_INIT_FAIL);
  354. else if (!volume.init(driver))
  355. SERIAL_ERROR_MSG(STR_SD_VOL_INIT_FAIL);
  356. else if (!root.openRoot(&volume))
  357. SERIAL_ERROR_MSG(STR_SD_OPENROOT_FAIL);
  358. else {
  359. flag.mounted = true;
  360. SERIAL_ECHO_MSG(STR_SD_CARD_OK);
  361. }
  362. if (flag.mounted)
  363. cdroot();
  364. #if ENABLED(USB_FLASH_DRIVE_SUPPORT) || PIN_EXISTS(SD_DETECT)
  365. else if (marlin_state != MF_INITIALIZING)
  366. ui.set_status(GET_TEXT_F(MSG_MEDIA_INIT_FAIL), -1);
  367. #endif
  368. ui.refresh();
  369. }
  370. /**
  371. * Handle SD card events
  372. */
  373. #if MB(FYSETC_CHEETAH, FYSETC_AIO_II)
  374. #include "../module/stepper.h"
  375. #endif
  376. void CardReader::manage_media() {
  377. static uint8_t prev_stat = 2; // First call, no prior state
  378. uint8_t stat = uint8_t(IS_SD_INSERTED());
  379. if (stat == prev_stat) return;
  380. DEBUG_ECHOLNPGM("SD: Status changed from ", prev_stat, " to ", stat);
  381. flag.workDirIsRoot = true; // Return to root on mount/release
  382. if (ui.detected()) {
  383. uint8_t old_stat = prev_stat;
  384. prev_stat = stat; // Change now to prevent re-entry
  385. if (stat) { // Media Inserted
  386. safe_delay(500); // Some boards need a delay to get settled
  387. if (TERN1(SD_IGNORE_AT_STARTUP, old_stat != 2))
  388. mount(); // Try to mount the media
  389. #if MB(FYSETC_CHEETAH, FYSETC_CHEETAH_V12, FYSETC_AIO_II)
  390. reset_stepper_drivers(); // Workaround for Cheetah bug
  391. #endif
  392. if (!isMounted()) stat = 0; // Not mounted?
  393. }
  394. else {
  395. #if PIN_EXISTS(SD_DETECT)
  396. release(); // Card is released
  397. #endif
  398. }
  399. ui.media_changed(old_stat, stat); // Update the UI
  400. if (stat) {
  401. TERN_(SDCARD_EEPROM_EMULATION, settings.first_load());
  402. if (old_stat == 2) { // First mount?
  403. DEBUG_ECHOLNPGM("First mount.");
  404. #if ENABLED(POWER_LOSS_RECOVERY)
  405. recovery.check(); // Check for PLR file. (If not there then call autofile_begin)
  406. #elif DISABLED(NO_SD_AUTOSTART)
  407. autofile_begin(); // Look for auto0.g on the next loop
  408. #endif
  409. }
  410. }
  411. }
  412. else
  413. DEBUG_ECHOLNPGM("SD: No UI Detected.");
  414. }
  415. /**
  416. * "Release" the media by clearing the 'mounted' flag.
  417. * Used by M22, "Release Media", manage_media.
  418. */
  419. void CardReader::release() {
  420. // Card removed while printing? Abort!
  421. if (IS_SD_PRINTING())
  422. abortFilePrintSoon();
  423. else
  424. endFilePrintNow();
  425. flag.mounted = false;
  426. flag.workDirIsRoot = true;
  427. #if ALL(SDCARD_SORT_ALPHA, SDSORT_USES_RAM, SDSORT_CACHE_NAMES)
  428. nrFiles = 0;
  429. #endif
  430. }
  431. /**
  432. * Open a G-code file and set Marlin to start processing it.
  433. * Enqueues M23 and M24 commands to initiate a media print.
  434. */
  435. void CardReader::openAndPrintFile(const char *name) {
  436. char cmd[4 + strlen(name) + 1 + 3 + 1]; // Room for "M23 ", filename, "\n", "M24", and null
  437. sprintf_P(cmd, M23_STR, name);
  438. for (char *c = &cmd[4]; *c; c++) *c = tolower(*c);
  439. strcat_P(cmd, PSTR("\nM24"));
  440. queue.inject(cmd);
  441. }
  442. /**
  443. * Start or resume a media print by setting the sdprinting flag.
  444. * The file browser pre-sort is also purged to free up memory,
  445. * since you cannot browse files during active printing.
  446. * Used by M24 and anywhere Start / Resume applies.
  447. */
  448. void CardReader::startOrResumeFilePrinting() {
  449. if (isMounted()) {
  450. flag.sdprinting = true;
  451. flag.sdprintdone = false;
  452. TERN_(SD_RESORT, flush_presort());
  453. }
  454. }
  455. //
  456. // Run tasks upon finishing or aborting a file print.
  457. //
  458. void CardReader::endFilePrintNow(TERN_(SD_RESORT, const bool re_sort/*=false*/)) {
  459. TERN_(ADVANCED_PAUSE_FEATURE, did_pause_print = 0);
  460. TERN_(HAS_DWIN_E3V2_BASIC, HMI_flag.print_finish = flag.sdprinting);
  461. flag.abort_sd_printing = false;
  462. if (isFileOpen()) file.close();
  463. TERN_(SD_RESORT, if (re_sort) presort());
  464. }
  465. void CardReader::abortFilePrintNow(TERN_(SD_RESORT, const bool re_sort/*=false*/)) {
  466. flag.sdprinting = flag.sdprintdone = false;
  467. endFilePrintNow(TERN_(SD_RESORT, re_sort));
  468. }
  469. void CardReader::openLogFile(const char * const path) {
  470. flag.logging = DISABLED(SDCARD_READONLY);
  471. IF_DISABLED(SDCARD_READONLY, openFileWrite(path));
  472. }
  473. //
  474. // Get the root-relative DOS path of the selected file
  475. //
  476. void CardReader::getAbsFilenameInCWD(char *dst) {
  477. *dst++ = '/';
  478. uint8_t cnt = 1;
  479. auto appendAtom = [&](SdFile &file) {
  480. file.getDosName(dst);
  481. while (*dst && cnt < MAXPATHNAMELENGTH) { dst++; cnt++; }
  482. if (cnt < MAXPATHNAMELENGTH) { *dst = '/'; dst++; cnt++; }
  483. };
  484. LOOP_L_N(i, workDirDepth) // Loop down to current work dir
  485. appendAtom(workDirParents[i]);
  486. if (cnt < MAXPATHNAMELENGTH - (FILENAME_LENGTH) - 1) { // Leave room for filename and nul
  487. appendAtom(file);
  488. --dst;
  489. }
  490. *dst = '\0';
  491. }
  492. void openFailed(const char * const fname) {
  493. SERIAL_ECHOLNPGM(STR_SD_OPEN_FILE_FAIL, fname, ".");
  494. }
  495. void announceOpen(const uint8_t doing, const char * const path) {
  496. if (doing) {
  497. PORT_REDIRECT(SerialMask::All);
  498. SERIAL_ECHO_START();
  499. SERIAL_ECHOPGM("Now ");
  500. SERIAL_ECHOF(doing == 1 ? F("doing") : F("fresh"));
  501. SERIAL_ECHOLNPGM(" file: ", path);
  502. }
  503. }
  504. //
  505. // Open a file by DOS path for read
  506. // The 'subcall_type' flag indicates...
  507. // - 0 : Standard open from host or user interface.
  508. // - 1 : (file open) Opening a new sub-procedure.
  509. // - 1 : (no file open) Opening a macro (M98).
  510. // - 2 : Resuming from a sub-procedure
  511. //
  512. void CardReader::openFileRead(const char * const path, const uint8_t subcall_type/*=0*/) {
  513. if (!isMounted()) return;
  514. switch (subcall_type) {
  515. case 0: // Starting a new print. "Now fresh file: ..."
  516. announceOpen(2, path);
  517. TERN_(HAS_MEDIA_SUBCALLS, file_subcall_ctr = 0);
  518. break;
  519. #if HAS_MEDIA_SUBCALLS
  520. case 1: // Starting a sub-procedure
  521. // With no file is open it's a simple macro. "Now doing file: ..."
  522. if (!isFileOpen()) { announceOpen(1, path); break; }
  523. // Too deep? The firmware has to bail.
  524. if (file_subcall_ctr > SD_PROCEDURE_DEPTH - 1) {
  525. SERIAL_ERROR_MSG("Exceeded max SUBROUTINE depth:", SD_PROCEDURE_DEPTH);
  526. kill(GET_TEXT_F(MSG_KILL_SUBCALL_OVERFLOW));
  527. return;
  528. }
  529. // Store current filename (based on workDirParents) and position
  530. getAbsFilenameInCWD(proc_filenames[file_subcall_ctr]);
  531. filespos[file_subcall_ctr] = sdpos;
  532. // For sub-procedures say 'SUBROUTINE CALL target: "..." parent: "..." pos12345'
  533. SERIAL_ECHO_MSG("SUBROUTINE CALL target:\"", path, "\" parent:\"", proc_filenames[file_subcall_ctr], "\" pos", sdpos);
  534. file_subcall_ctr++;
  535. break;
  536. case 2: // Resuming previous file after sub-procedure
  537. SERIAL_ECHO_MSG("END SUBROUTINE");
  538. break;
  539. #endif
  540. }
  541. abortFilePrintNow();
  542. SdFile *diveDir;
  543. const char * const fname = diveToFile(true, diveDir, path);
  544. if (!fname) return;
  545. if (file.open(diveDir, fname, O_READ)) {
  546. filesize = file.fileSize();
  547. sdpos = 0;
  548. { // Don't remove this block, as the PORT_REDIRECT is a RAII
  549. PORT_REDIRECT(SerialMask::All);
  550. SERIAL_ECHOLNPGM(STR_SD_FILE_OPENED, fname, STR_SD_SIZE, filesize);
  551. SERIAL_ECHOLNPGM(STR_SD_FILE_SELECTED);
  552. }
  553. selectFileByName(fname);
  554. ui.set_status(longFilename[0] ? longFilename : fname);
  555. }
  556. else
  557. openFailed(fname);
  558. }
  559. inline void echo_write_to_file(const char * const fname) {
  560. SERIAL_ECHOLNPGM(STR_SD_WRITE_TO_FILE, fname);
  561. }
  562. //
  563. // Open a file by DOS path for write
  564. //
  565. void CardReader::openFileWrite(const char * const path) {
  566. if (!isMounted()) return;
  567. announceOpen(2, path);
  568. TERN_(HAS_MEDIA_SUBCALLS, file_subcall_ctr = 0);
  569. abortFilePrintNow();
  570. SdFile *diveDir;
  571. const char * const fname = diveToFile(false, diveDir, path);
  572. if (!fname) return;
  573. #if ENABLED(SDCARD_READONLY)
  574. openFailed(fname);
  575. #else
  576. if (file.open(diveDir, fname, O_CREAT | O_APPEND | O_WRITE | O_TRUNC)) {
  577. flag.saving = true;
  578. selectFileByName(fname);
  579. TERN_(EMERGENCY_PARSER, emergency_parser.disable());
  580. echo_write_to_file(fname);
  581. ui.set_status(fname);
  582. }
  583. else
  584. openFailed(fname);
  585. #endif
  586. }
  587. //
  588. // Check if a file exists by absolute or workDir-relative path
  589. // If the file exists, the long name can also be fetched.
  590. //
  591. bool CardReader::fileExists(const char * const path) {
  592. if (!isMounted()) return false;
  593. DEBUG_ECHOLNPGM("fileExists: ", path);
  594. // Dive to the file's directory and get the base name
  595. SdFile *diveDir = nullptr;
  596. const char * const fname = diveToFile(false, diveDir, path);
  597. if (!fname) return false;
  598. // Get the longname of the checked file
  599. //diveDir->rewind();
  600. //selectByName(*diveDir, fname);
  601. //diveDir->close();
  602. // Try to open the file and return the result
  603. SdFile tmpFile;
  604. const bool success = tmpFile.open(diveDir, fname, O_READ);
  605. if (success) tmpFile.close();
  606. return success;
  607. }
  608. //
  609. // Delete a file by name in the working directory
  610. //
  611. void CardReader::removeFile(const char * const name) {
  612. if (!isMounted()) return;
  613. //abortFilePrintNow();
  614. SdFile *itsDirPtr;
  615. const char * const fname = diveToFile(false, itsDirPtr, name);
  616. if (!fname) return;
  617. #if ENABLED(SDCARD_READONLY)
  618. SERIAL_ECHOLNPGM("Deletion failed (read-only), File: ", fname, ".");
  619. #else
  620. if (file.remove(itsDirPtr, fname)) {
  621. SERIAL_ECHOLNPGM("File deleted:", fname);
  622. sdpos = 0;
  623. TERN_(SDCARD_SORT_ALPHA, presort());
  624. }
  625. else
  626. SERIAL_ECHOLNPGM("Deletion failed, File: ", fname, ".");
  627. #endif
  628. }
  629. void CardReader::report_status() {
  630. if (isPrinting()) {
  631. SERIAL_ECHOPGM(STR_SD_PRINTING_BYTE, sdpos);
  632. SERIAL_CHAR('/');
  633. SERIAL_ECHOLN(filesize);
  634. }
  635. else
  636. SERIAL_ECHOLNPGM(STR_SD_NOT_PRINTING);
  637. }
  638. void CardReader::write_command(char * const buf) {
  639. char *begin = buf,
  640. *npos = nullptr,
  641. *end = buf + strlen(buf) - 1;
  642. file.writeError = false;
  643. if ((npos = strchr(buf, 'N'))) {
  644. begin = strchr(npos, ' ') + 1;
  645. end = strchr(npos, '*') - 1;
  646. }
  647. end[1] = '\r';
  648. end[2] = '\n';
  649. end[3] = '\0';
  650. file.write(begin);
  651. if (file.writeError) SERIAL_ERROR_MSG(STR_SD_ERR_WRITE_TO_FILE);
  652. }
  653. #if DISABLED(NO_SD_AUTOSTART)
  654. /**
  655. * Run all the auto#.g files. Called:
  656. * - On boot after successful card init.
  657. * - From the LCD command to Run Auto Files
  658. */
  659. void CardReader::autofile_begin() {
  660. autofile_index = 1;
  661. (void)autofile_check();
  662. }
  663. /**
  664. * Run the next auto#.g file. Called:
  665. * - On boot after successful card init
  666. * - After finishing the previous auto#.g file
  667. * - From the LCD command to begin the auto#.g files
  668. *
  669. * Return 'true' if an auto file was started
  670. */
  671. bool CardReader::autofile_check() {
  672. if (!autofile_index) return false;
  673. if (!isMounted())
  674. mount();
  675. else if (ENABLED(SDCARD_EEPROM_EMULATION))
  676. settings.first_load();
  677. // Don't run auto#.g when a PLR file exists
  678. if (isMounted() && TERN1(POWER_LOSS_RECOVERY, !recovery.valid())) {
  679. char autoname[10];
  680. sprintf_P(autoname, PSTR("/auto%c.g"), '0' + autofile_index - 1);
  681. if (fileExists(autoname)) {
  682. cdroot();
  683. openAndPrintFile(autoname);
  684. autofile_index++;
  685. return true;
  686. }
  687. }
  688. autofile_cancel();
  689. return false;
  690. }
  691. #endif
  692. void CardReader::closefile(const bool store_location/*=false*/) {
  693. file.sync();
  694. file.close();
  695. flag.saving = flag.logging = false;
  696. sdpos = 0;
  697. TERN_(EMERGENCY_PARSER, emergency_parser.enable());
  698. if (store_location) {
  699. //future: store printer state, filename and position for continuing a stopped print
  700. // so one can unplug the printer and continue printing the next day.
  701. }
  702. }
  703. //
  704. // Get info for a file in the working directory by index
  705. //
  706. void CardReader::selectFileByIndex(const uint16_t nr) {
  707. #if ENABLED(SDSORT_CACHE_NAMES)
  708. if (nr < sort_count) {
  709. strcpy(filename, sortshort[nr]);
  710. strcpy(longFilename, sortnames[nr]);
  711. flag.filenameIsDir = IS_DIR(nr);
  712. return;
  713. }
  714. #endif
  715. workDir.rewind();
  716. selectByIndex(workDir, nr);
  717. }
  718. //
  719. // Get info for a file in the working directory by DOS name
  720. //
  721. void CardReader::selectFileByName(const char * const match) {
  722. #if ENABLED(SDSORT_CACHE_NAMES)
  723. for (uint16_t nr = 0; nr < sort_count; nr++)
  724. if (strcasecmp(match, sortshort[nr]) == 0) {
  725. strcpy(filename, sortshort[nr]);
  726. strcpy(longFilename, sortnames[nr]);
  727. flag.filenameIsDir = IS_DIR(nr);
  728. return;
  729. }
  730. #endif
  731. workDir.rewind();
  732. selectByName(workDir, match);
  733. }
  734. uint16_t CardReader::countFilesInWorkDir() {
  735. workDir.rewind();
  736. return countItems(workDir);
  737. }
  738. /**
  739. * Dive to the given DOS 8.3 file path, with optional echo of the dive paths.
  740. *
  741. * On entry:
  742. * - The workDir points to the last-set navigation target by cd, cdup, cdroot, or diveToFile(true, ...)
  743. *
  744. * On exit:
  745. * - Your curDir pointer contains an SdFile reference to the file's directory.
  746. * - If update_cwd was 'true' the workDir now points to the file's directory.
  747. *
  748. * Returns a pointer to the last segment (filename) of the given DOS 8.3 path.
  749. * On exit, inDirPtr contains an SdFile reference to the file's directory.
  750. *
  751. * A nullptr result indicates an unrecoverable error.
  752. *
  753. * NOTE: End the path with a slash to dive to a folder. In this case the
  754. * returned filename will be blank (points to the end of the path).
  755. */
  756. const char* CardReader::diveToFile(const bool update_cwd, SdFile* &inDirPtr, const char * const path, const bool echo/*=false*/) {
  757. DEBUG_SECTION(est, "diveToFile", true);
  758. // Track both parent and subfolder
  759. static SdFile newDir1, newDir2;
  760. SdFile *sub = &newDir1, *startDirPtr;
  761. // Parsing the path string
  762. const char *atom_ptr = path;
  763. DEBUG_ECHOLNPGM(" path = '", path, "'");
  764. if (path[0] == '/') { // Starting at the root directory?
  765. inDirPtr = &root;
  766. atom_ptr++;
  767. DEBUG_ECHOLNPGM(" CWD to root: ", hex_address((void*)inDirPtr));
  768. if (update_cwd) workDirDepth = 0; // The cwd can be updated for the benefit of sub-programs
  769. }
  770. else
  771. inDirPtr = &workDir; // Dive from workDir (as set by the UI)
  772. startDirPtr = inDirPtr;
  773. DEBUG_ECHOLNPGM(" startDirPtr = ", hex_address((void*)startDirPtr));
  774. while (atom_ptr) {
  775. // Find next subdirectory delimiter
  776. const char * const name_end = strchr(atom_ptr, '/');
  777. // Last atom in the path? Item found.
  778. if (name_end <= atom_ptr) break;
  779. // Isolate the next subitem name
  780. const uint8_t len = name_end - atom_ptr;
  781. char dosSubdirname[len + 1];
  782. strncpy(dosSubdirname, atom_ptr, len);
  783. dosSubdirname[len] = 0;
  784. if (echo) SERIAL_ECHOLN(dosSubdirname);
  785. DEBUG_ECHOLNPGM(" sub = ", hex_address((void*)sub));
  786. // Open inDirPtr (closing first)
  787. sub->close();
  788. if (!sub->open(inDirPtr, dosSubdirname, O_READ)) {
  789. openFailed(dosSubdirname);
  790. atom_ptr = nullptr;
  791. break;
  792. }
  793. // Close inDirPtr if not at starting-point
  794. if (inDirPtr != startDirPtr) {
  795. DEBUG_ECHOLNPGM(" closing inDirPtr: ", hex_address((void*)inDirPtr));
  796. inDirPtr->close();
  797. }
  798. // inDirPtr now subDir
  799. inDirPtr = sub;
  800. DEBUG_ECHOLNPGM(" inDirPtr = sub: ", hex_address((void*)inDirPtr));
  801. // Update workDirParents and workDirDepth
  802. if (update_cwd) {
  803. DEBUG_ECHOLNPGM(" update_cwd");
  804. if (workDirDepth < MAX_DIR_DEPTH)
  805. workDirParents[workDirDepth++] = *inDirPtr;
  806. }
  807. // Point sub at the other scratch object
  808. sub = (inDirPtr != &newDir1) ? &newDir1 : &newDir2;
  809. DEBUG_ECHOLNPGM(" swapping sub = ", hex_address((void*)sub));
  810. // Next path atom address
  811. atom_ptr = name_end + 1;
  812. }
  813. if (update_cwd) {
  814. workDir = *inDirPtr;
  815. DEBUG_ECHOLNPGM(" final workDir = ", hex_address((void*)inDirPtr));
  816. flag.workDirIsRoot = (workDirDepth == 0);
  817. TERN_(SDCARD_SORT_ALPHA, presort());
  818. }
  819. DEBUG_ECHOLNPGM(" returning string ", atom_ptr ?: "nullptr");
  820. return atom_ptr;
  821. }
  822. void CardReader::cd(const char * relpath) {
  823. SdFile newDir, *parent = &getWorkDir();
  824. if (newDir.open(parent, relpath, O_READ)) {
  825. workDir = newDir;
  826. flag.workDirIsRoot = false;
  827. if (workDirDepth < MAX_DIR_DEPTH)
  828. workDirParents[workDirDepth++] = workDir;
  829. TERN_(SDCARD_SORT_ALPHA, presort());
  830. }
  831. else
  832. SERIAL_ECHO_MSG(STR_SD_CANT_ENTER_SUBDIR, relpath);
  833. }
  834. int8_t CardReader::cdup() {
  835. if (workDirDepth > 0) { // At least 1 dir has been saved
  836. workDir = --workDirDepth ? workDirParents[workDirDepth - 1] : root; // Use parent, or root if none
  837. TERN_(SDCARD_SORT_ALPHA, presort());
  838. }
  839. if (!workDirDepth) flag.workDirIsRoot = true;
  840. return workDirDepth;
  841. }
  842. void CardReader::cdroot() {
  843. workDir = root;
  844. flag.workDirIsRoot = true;
  845. workDirDepth = 0;
  846. TERN_(SDCARD_SORT_ALPHA, presort());
  847. }
  848. #if ENABLED(SDCARD_SORT_ALPHA)
  849. /**
  850. * Get the name of a file in the working directory by sort-index
  851. */
  852. void CardReader::getfilename_sorted(const uint16_t nr) {
  853. selectFileByIndex(TERN1(SDSORT_GCODE, sort_alpha) && (nr < sort_count)
  854. ? sort_order[nr] : nr);
  855. }
  856. #if ENABLED(SDSORT_USES_RAM)
  857. #if ENABLED(SDSORT_DYNAMIC_RAM)
  858. // Use dynamic method to copy long filename
  859. #define SET_SORTNAME(I) (sortnames[I] = strdup(longest_filename()))
  860. #if ENABLED(SDSORT_CACHE_NAMES)
  861. // When caching also store the short name, since
  862. // we're replacing the selectFileByIndex() behavior.
  863. #define SET_SORTSHORT(I) (sortshort[I] = strdup(filename))
  864. #else
  865. #define SET_SORTSHORT(I) NOOP
  866. #endif
  867. #else
  868. // Copy filenames into the static array
  869. #define _SET_SORTNAME(I) strncpy(sortnames[I], longest_filename(), SORTED_LONGNAME_MAXLEN)
  870. #if SORTED_LONGNAME_MAXLEN == LONG_FILENAME_LENGTH
  871. // Short name sorting always use LONG_FILENAME_LENGTH with no trailing nul
  872. #define SET_SORTNAME(I) _SET_SORTNAME(I)
  873. #else
  874. // Copy multiple name blocks. Add a nul for the longest case.
  875. #define SET_SORTNAME(I) do{ _SET_SORTNAME(I); sortnames[I][SORTED_LONGNAME_MAXLEN] = '\0'; }while(0)
  876. #endif
  877. #if ENABLED(SDSORT_CACHE_NAMES)
  878. #define SET_SORTSHORT(I) strcpy(sortshort[I], filename)
  879. #else
  880. #define SET_SORTSHORT(I) NOOP
  881. #endif
  882. #endif
  883. #endif
  884. /**
  885. * Read all the files and produce a sort key
  886. *
  887. * We can do this in 3 ways...
  888. * - Minimal RAM: Read two filenames at a time sorting along...
  889. * - Some RAM: Buffer the directory just for this sort
  890. * - Most RAM: Buffer the directory and return filenames from RAM
  891. */
  892. void CardReader::presort() {
  893. // Throw away old sort index
  894. flush_presort();
  895. // Sorting may be turned off
  896. if (TERN0(SDSORT_GCODE, !sort_alpha)) return;
  897. // If there are files, sort up to the limit
  898. uint16_t fileCnt = countFilesInWorkDir();
  899. if (fileCnt > 0) {
  900. // Never sort more than the max allowed
  901. // If you use folders to organize, 20 may be enough
  902. NOMORE(fileCnt, uint16_t(SDSORT_LIMIT));
  903. // Sort order is always needed. May be static or dynamic.
  904. TERN_(SDSORT_DYNAMIC_RAM, sort_order = new uint8_t[fileCnt]);
  905. // Use RAM to store the entire directory during pre-sort.
  906. // SDSORT_LIMIT should be set to prevent over-allocation.
  907. #if ENABLED(SDSORT_USES_RAM)
  908. // If using dynamic ram for names, allocate on the heap.
  909. #if ENABLED(SDSORT_CACHE_NAMES)
  910. #if ENABLED(SDSORT_DYNAMIC_RAM)
  911. sortshort = new char*[fileCnt];
  912. sortnames = new char*[fileCnt];
  913. #endif
  914. #elif ENABLED(SDSORT_USES_STACK)
  915. char sortnames[fileCnt][SORTED_LONGNAME_STORAGE];
  916. #endif
  917. // Folder sorting needs 1 bit per entry for flags.
  918. #if HAS_FOLDER_SORTING
  919. #if ENABLED(SDSORT_DYNAMIC_RAM)
  920. isDir = new uint8_t[(fileCnt + 7) >> 3];
  921. #elif ENABLED(SDSORT_USES_STACK)
  922. uint8_t isDir[(fileCnt + 7) >> 3];
  923. #endif
  924. #endif
  925. #else // !SDSORT_USES_RAM
  926. // By default re-read the names from SD for every compare
  927. // retaining only two filenames at a time. This is very
  928. // slow but is safest and uses minimal RAM.
  929. char name1[LONG_FILENAME_LENGTH];
  930. #endif
  931. if (fileCnt > 1) {
  932. // Init sort order.
  933. for (uint16_t i = 0; i < fileCnt; i++) {
  934. sort_order[i] = i;
  935. // If using RAM then read all filenames now.
  936. #if ENABLED(SDSORT_USES_RAM)
  937. selectFileByIndex(i);
  938. SET_SORTNAME(i);
  939. SET_SORTSHORT(i);
  940. //char out[30];
  941. //sprintf_P(out, PSTR("---- %i %s %s"), i, flag.filenameIsDir ? "D" : " ", sortnames[i]);
  942. //SERIAL_ECHOLN(out);
  943. #if HAS_FOLDER_SORTING
  944. const uint16_t bit = i & 0x07, ind = i >> 3;
  945. if (bit == 0) isDir[ind] = 0x00;
  946. if (flag.filenameIsDir) SBI(isDir[ind], bit);
  947. #endif
  948. #endif
  949. }
  950. // Bubble Sort
  951. for (uint16_t i = fileCnt; --i;) {
  952. bool didSwap = false;
  953. uint8_t o1 = sort_order[0];
  954. #if DISABLED(SDSORT_USES_RAM)
  955. selectFileByIndex(o1); // Pre-fetch the first entry and save it
  956. strcpy(name1, longest_filename()); // so the loop only needs one fetch
  957. #if HAS_FOLDER_SORTING
  958. bool dir1 = flag.filenameIsDir;
  959. #endif
  960. #endif
  961. for (uint16_t j = 0; j < i; ++j) {
  962. const uint16_t o2 = sort_order[j + 1];
  963. // Compare names from the array or just the two buffered names
  964. #if ENABLED(SDSORT_USES_RAM)
  965. #define _SORT_CMP_NODIR() (strcasecmp(sortnames[o1], sortnames[o2]) > 0)
  966. #else
  967. #define _SORT_CMP_NODIR() (strcasecmp(name1, name2) > 0)
  968. #endif
  969. #if HAS_FOLDER_SORTING
  970. #if ENABLED(SDSORT_USES_RAM)
  971. // Folder sorting needs an index and bit to test for folder-ness.
  972. #define _SORT_CMP_DIR(fs) (IS_DIR(o1) == IS_DIR(o2) ? _SORT_CMP_NODIR() : IS_DIR(fs > 0 ? o1 : o2))
  973. #else
  974. #define _SORT_CMP_DIR(fs) ((dir1 == flag.filenameIsDir) ? _SORT_CMP_NODIR() : (fs > 0 ? dir1 : !dir1))
  975. #endif
  976. #endif
  977. // The most economical method reads names as-needed
  978. // throughout the loop. Slow if there are many.
  979. #if DISABLED(SDSORT_USES_RAM)
  980. selectFileByIndex(o2);
  981. const bool dir2 = flag.filenameIsDir;
  982. char * const name2 = longest_filename(); // use the string in-place
  983. #endif // !SDSORT_USES_RAM
  984. // Sort the current pair according to settings.
  985. if (
  986. #if HAS_FOLDER_SORTING
  987. #if ENABLED(SDSORT_GCODE)
  988. sort_folders ? _SORT_CMP_DIR(sort_folders) : _SORT_CMP_NODIR()
  989. #else
  990. _SORT_CMP_DIR(FOLDER_SORTING)
  991. #endif
  992. #else
  993. _SORT_CMP_NODIR()
  994. #endif
  995. ) {
  996. // Reorder the index, indicate that sorting happened
  997. // Note that the next o1 will be the current o1. No new fetch needed.
  998. sort_order[j] = o2;
  999. sort_order[j + 1] = o1;
  1000. didSwap = true;
  1001. }
  1002. else {
  1003. // The next o1 is the current o2. No new fetch needed.
  1004. o1 = o2;
  1005. #if DISABLED(SDSORT_USES_RAM)
  1006. TERN_(HAS_FOLDER_SORTING, dir1 = dir2);
  1007. strcpy(name1, name2);
  1008. #endif
  1009. }
  1010. }
  1011. if (!didSwap) break;
  1012. }
  1013. // Using RAM but not keeping names around
  1014. #if ENABLED(SDSORT_USES_RAM) && DISABLED(SDSORT_CACHE_NAMES)
  1015. #if ENABLED(SDSORT_DYNAMIC_RAM)
  1016. for (uint16_t i = 0; i < fileCnt; ++i) free(sortnames[i]);
  1017. TERN_(HAS_FOLDER_SORTING, delete [] isDir);
  1018. #endif
  1019. #endif
  1020. }
  1021. else {
  1022. sort_order[0] = 0;
  1023. #if BOTH(SDSORT_USES_RAM, SDSORT_CACHE_NAMES)
  1024. #if ENABLED(SDSORT_DYNAMIC_RAM)
  1025. sortnames = new char*[1];
  1026. sortshort = new char*[1];
  1027. isDir = new uint8_t[1];
  1028. #endif
  1029. selectFileByIndex(0);
  1030. SET_SORTNAME(0);
  1031. SET_SORTSHORT(0);
  1032. isDir[0] = flag.filenameIsDir;
  1033. #endif
  1034. }
  1035. sort_count = fileCnt;
  1036. }
  1037. }
  1038. void CardReader::flush_presort() {
  1039. if (sort_count > 0) {
  1040. #if ENABLED(SDSORT_DYNAMIC_RAM)
  1041. delete [] sort_order;
  1042. #if ENABLED(SDSORT_CACHE_NAMES)
  1043. LOOP_L_N(i, sort_count) {
  1044. free(sortshort[i]); // strdup
  1045. free(sortnames[i]); // strdup
  1046. }
  1047. delete [] sortshort;
  1048. delete [] sortnames;
  1049. #endif
  1050. #endif
  1051. sort_count = 0;
  1052. }
  1053. }
  1054. #endif // SDCARD_SORT_ALPHA
  1055. uint16_t CardReader::get_num_Files() {
  1056. if (!isMounted()) return 0;
  1057. return (
  1058. #if ALL(SDCARD_SORT_ALPHA, SDSORT_USES_RAM, SDSORT_CACHE_NAMES)
  1059. nrFiles // no need to access the SD card for filenames
  1060. #else
  1061. countFilesInWorkDir()
  1062. #endif
  1063. );
  1064. }
  1065. //
  1066. // Return from procedure or close out the Print Job
  1067. //
  1068. void CardReader::fileHasFinished() {
  1069. file.close();
  1070. #if HAS_MEDIA_SUBCALLS
  1071. if (file_subcall_ctr > 0) { // Resume calling file after closing procedure
  1072. file_subcall_ctr--;
  1073. openFileRead(proc_filenames[file_subcall_ctr], 2); // 2 = Returning from sub-procedure
  1074. setIndex(filespos[file_subcall_ctr]);
  1075. startOrResumeFilePrinting();
  1076. return;
  1077. }
  1078. #endif
  1079. endFilePrintNow(TERN_(SD_RESORT, true));
  1080. flag.sdprintdone = true; // Stop getting bytes from the SD card
  1081. marlin_state = MF_SD_COMPLETE; // Tell Marlin to enqueue M1001 soon
  1082. }
  1083. #if ENABLED(AUTO_REPORT_SD_STATUS)
  1084. AutoReporter<CardReader::AutoReportSD> CardReader::auto_reporter;
  1085. #endif
  1086. #if ENABLED(POWER_LOSS_RECOVERY)
  1087. bool CardReader::jobRecoverFileExists() {
  1088. const bool exists = recovery.file.open(&root, recovery.filename, O_READ);
  1089. if (exists) recovery.file.close();
  1090. return exists;
  1091. }
  1092. void CardReader::openJobRecoveryFile(const bool read) {
  1093. if (!isMounted()) return;
  1094. if (recovery.file.isOpen()) return;
  1095. if (!recovery.file.open(&root, recovery.filename, read ? O_READ : O_CREAT | O_WRITE | O_TRUNC | O_SYNC))
  1096. openFailed(recovery.filename);
  1097. else if (!read)
  1098. echo_write_to_file(recovery.filename);
  1099. }
  1100. // Removing the job recovery file currently requires closing
  1101. // the file being printed, so during SD printing the file should
  1102. // be zeroed and written instead of deleted.
  1103. void CardReader::removeJobRecoveryFile() {
  1104. if (jobRecoverFileExists()) {
  1105. recovery.init();
  1106. removeFile(recovery.filename);
  1107. #if ENABLED(DEBUG_POWER_LOSS_RECOVERY)
  1108. SERIAL_ECHOPGM("Power-loss file delete");
  1109. SERIAL_ECHOF(jobRecoverFileExists() ? F(" failed.\n") : F("d.\n"));
  1110. #endif
  1111. }
  1112. }
  1113. #endif // POWER_LOSS_RECOVERY
  1114. #endif // SDSUPPORT