My Marlin configs for Fabrikator Mini and CTC i3 Pro B
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

cardreader.cpp 38KB

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