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 39KB

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