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

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