python_code
stringlengths
0
1.8M
repo_name
stringclasses
7 values
file_path
stringlengths
5
99
/* buffer.c * * Buffer management. * Some of the functions are internal, * and some are actually attached to user * keys. Like everyone else, they set hints * for the display system * * modified by Petri Kutvonen */ #include <stdio.h> #include "estruct.h" #include "edef.h" #include "efunc.h" #include "line.h" /* * Attach a buffer to a window. The * values of dot and mark come from the buffer * if the use count is 0. Otherwise, they come * from some other window. */ int usebuffer(int f, int n) { struct buffer *bp; int s; char bufn[NBUFN]; if ((s = mlreply("Use buffer: ", bufn, NBUFN)) != TRUE) return s; if ((bp = bfind(bufn, TRUE, 0)) == NULL) return FALSE; return swbuffer(bp); } /* * switch to the next buffer in the buffer list * * int f, n; default flag, numeric argument */ int nextbuffer(int f, int n) { struct buffer *bp = NULL; /* eligable buffer to switch to */ struct buffer *bbp; /* eligable buffer to switch to */ /* make sure the arg is legit */ if (f == FALSE) n = 1; if (n < 1) return FALSE; bbp = curbp; while (n-- > 0) { /* advance to the next buffer */ bp = bbp->b_bufp; /* cycle through the buffers to find an eligable one */ while (bp == NULL || bp->b_flag & BFINVS) { if (bp == NULL) bp = bheadp; else bp = bp->b_bufp; /* don't get caught in an infinite loop! */ if (bp == bbp) return FALSE; } bbp = bp; } return swbuffer(bp); } /* * make buffer BP current */ int swbuffer(struct buffer *bp) { struct window *wp; if (--curbp->b_nwnd == 0) { /* Last use. */ curbp->b_dotp = curwp->w_dotp; curbp->b_doto = curwp->w_doto; curbp->b_markp = curwp->w_markp; curbp->b_marko = curwp->w_marko; } curbp = bp; /* Switch. */ if (curbp->b_active != TRUE) { /* buffer not active yet */ /* read it in and activate it */ readin(curbp->b_fname, TRUE); curbp->b_dotp = lforw(curbp->b_linep); curbp->b_doto = 0; curbp->b_active = TRUE; curbp->b_mode |= gmode; /* P.K. */ } curwp->w_bufp = bp; curwp->w_linep = bp->b_linep; /* For macros, ignored. */ curwp->w_flag |= WFMODE | WFFORCE | WFHARD; /* Quite nasty. */ if (bp->b_nwnd++ == 0) { /* First use. */ curwp->w_dotp = bp->b_dotp; curwp->w_doto = bp->b_doto; curwp->w_markp = bp->b_markp; curwp->w_marko = bp->b_marko; cknewwindow(); return TRUE; } wp = wheadp; /* Look for old. */ while (wp != NULL) { if (wp != curwp && wp->w_bufp == bp) { curwp->w_dotp = wp->w_dotp; curwp->w_doto = wp->w_doto; curwp->w_markp = wp->w_markp; curwp->w_marko = wp->w_marko; break; } wp = wp->w_wndp; } cknewwindow(); return TRUE; } /* * Dispose of a buffer, by name. * Ask for the name. Look it up (don't get too * upset if it isn't there at all!). Get quite upset * if the buffer is being displayed. Clear the buffer (ask * if the buffer has been changed). Then free the header * line and the buffer header. Bound to "C-X K". */ int killbuffer(int f, int n) { struct buffer *bp; int s; char bufn[NBUFN]; if ((s = mlreply("Kill buffer: ", bufn, NBUFN)) != TRUE) return s; if ((bp = bfind(bufn, FALSE, 0)) == NULL) /* Easy if unknown. */ return TRUE; if (bp->b_flag & BFINVS) /* Deal with special buffers */ return TRUE; /* by doing nothing. */ return zotbuf(bp); } /* * kill the buffer pointed to by bp */ int zotbuf(struct buffer *bp) { struct buffer *bp1; struct buffer *bp2; int s; if (bp->b_nwnd != 0) { /* Error if on screen. */ mlwrite("Buffer is being displayed"); return FALSE; } if ((s = bclear(bp)) != TRUE) /* Blow text away. */ return s; free((char *) bp->b_linep); /* Release header line. */ bp1 = NULL; /* Find the header. */ bp2 = bheadp; while (bp2 != bp) { bp1 = bp2; bp2 = bp2->b_bufp; } bp2 = bp2->b_bufp; /* Next one in chain. */ if (bp1 == NULL) /* Unlink it. */ bheadp = bp2; else bp1->b_bufp = bp2; free((char *) bp); /* Release buffer block */ return TRUE; } /* * Rename the current buffer * * int f, n; default Flag & Numeric arg */ int namebuffer(int f, int n) { struct buffer *bp; /* pointer to scan through all buffers */ char bufn[NBUFN]; /* buffer to hold buffer name */ /* prompt for and get the new buffer name */ ask:if (mlreply("Change buffer name to: ", bufn, NBUFN) != TRUE) return FALSE; /* and check for duplicates */ bp = bheadp; while (bp != NULL) { if (bp != curbp) { /* if the names the same */ if (strcmp(bufn, bp->b_bname) == 0) goto ask; /* try again */ } bp = bp->b_bufp; /* onward */ } strcpy(curbp->b_bname, bufn); /* copy buffer name to structure */ curwp->w_flag |= WFMODE; /* make mode line replot */ mlerase(); return TRUE; } /* * List all of the active buffers. First update the special * buffer that holds the list. Next make sure at least 1 * window is displaying the buffer list, splitting the screen * if this is what it takes. Lastly, repaint all of the * windows that are displaying the list. Bound to "C-X C-B". * * A numeric argument forces it to list invisible buffers as * well. */ int listbuffers(int f, int n) { struct window *wp; struct buffer *bp; int s; if ((s = makelist(f)) != TRUE) return s; if (blistp->b_nwnd == 0) { /* Not on screen yet. */ if ((wp = wpopup()) == NULL) return FALSE; bp = wp->w_bufp; if (--bp->b_nwnd == 0) { bp->b_dotp = wp->w_dotp; bp->b_doto = wp->w_doto; bp->b_markp = wp->w_markp; bp->b_marko = wp->w_marko; } wp->w_bufp = blistp; ++blistp->b_nwnd; } wp = wheadp; while (wp != NULL) { if (wp->w_bufp == blistp) { wp->w_linep = lforw(blistp->b_linep); wp->w_dotp = lforw(blistp->b_linep); wp->w_doto = 0; wp->w_markp = NULL; wp->w_marko = 0; wp->w_flag |= WFMODE | WFHARD; } wp = wp->w_wndp; } return TRUE; } /* * This routine rebuilds the * text in the special secret buffer * that holds the buffer list. It is called * by the list buffers command. Return TRUE * if everything works. Return FALSE if there * is an error (if there is no memory). Iflag * indicates wether to list hidden buffers. * * int iflag; list hidden buffer flag */ #define MAXLINE MAXCOL int makelist(int iflag) { char *cp1; char *cp2; int c; struct buffer *bp; struct line *lp; int s; int i; long nbytes; /* # of bytes in current buffer */ char b[7 + 1]; char line[MAXLINE]; blistp->b_flag &= ~BFCHG; /* Don't complain! */ if ((s = bclear(blistp)) != TRUE) /* Blow old text away */ return s; strcpy(blistp->b_fname, ""); if (addline("ACT MODES Size Buffer File") == FALSE || addline("--- ----- ---- ------ ----") == FALSE) return FALSE; bp = bheadp; /* For all buffers */ /* build line to report global mode settings */ cp1 = &line[0]; *cp1++ = ' '; *cp1++ = ' '; *cp1++ = ' '; *cp1++ = ' '; /* output the mode codes */ for (i = 0; i < NUMMODES; i++) if (gmode & (1 << i)) *cp1++ = modecode[i]; else *cp1++ = '.'; strcpy(cp1, " Global Modes"); if (addline(line) == FALSE) return FALSE; /* output the list of buffers */ while (bp != NULL) { /* skip invisable buffers if iflag is false */ if (((bp->b_flag & BFINVS) != 0) && (iflag != TRUE)) { bp = bp->b_bufp; continue; } cp1 = &line[0]; /* Start at left edge */ /* output status of ACTIVE flag (has the file been read in? */ if (bp->b_active == TRUE) /* "@" if activated */ *cp1++ = '@'; else *cp1++ = ' '; /* output status of changed flag */ if ((bp->b_flag & BFCHG) != 0) /* "*" if changed */ *cp1++ = '*'; else *cp1++ = ' '; /* report if the file is truncated */ if ((bp->b_flag & BFTRUNC) != 0) *cp1++ = '#'; else *cp1++ = ' '; *cp1++ = ' '; /* space */ /* output the mode codes */ for (i = 0; i < NUMMODES; i++) { if (bp->b_mode & (1 << i)) *cp1++ = modecode[i]; else *cp1++ = '.'; } *cp1++ = ' '; /* Gap. */ nbytes = 0L; /* Count bytes in buf. */ lp = lforw(bp->b_linep); while (lp != bp->b_linep) { nbytes += (long) llength(lp) + 1L; lp = lforw(lp); } ltoa(b, 7, nbytes); /* 6 digit buffer size. */ cp2 = &b[0]; while ((c = *cp2++) != 0) *cp1++ = c; *cp1++ = ' '; /* Gap. */ cp2 = &bp->b_bname[0]; /* Buffer name */ while ((c = *cp2++) != 0) *cp1++ = c; cp2 = &bp->b_fname[0]; /* File name */ if (*cp2 != 0) { while (cp1 < &line[3 + 1 + 5 + 1 + 6 + 4 + NBUFN]) *cp1++ = ' '; while ((c = *cp2++) != 0) { if (cp1 < &line[MAXLINE - 1]) *cp1++ = c; } } *cp1 = 0; /* Add to the buffer. */ if (addline(line) == FALSE) return FALSE; bp = bp->b_bufp; } return TRUE; /* All done */ } void ltoa(char *buf, int width, long num) { buf[width] = 0; /* End of string. */ while (num >= 10) { /* Conditional digits. */ buf[--width] = (int) (num % 10L) + '0'; num /= 10L; } buf[--width] = (int) num + '0'; /* Always 1 digit. */ while (width != 0) /* Pad with blanks. */ buf[--width] = ' '; } /* * The argument "text" points to * a string. Append this line to the * buffer list buffer. Handcraft the EOL * on the end. Return TRUE if it worked and * FALSE if you ran out of room. */ int addline(char *text) { struct line *lp; int i; int ntext; ntext = strlen(text); if ((lp = lalloc(ntext)) == NULL) return FALSE; for (i = 0; i < ntext; ++i) lputc(lp, i, text[i]); blistp->b_linep->l_bp->l_fp = lp; /* Hook onto the end */ lp->l_bp = blistp->b_linep->l_bp; blistp->b_linep->l_bp = lp; lp->l_fp = blistp->b_linep; if (blistp->b_dotp == blistp->b_linep) /* If "." is at the end */ blistp->b_dotp = lp; /* move it to new line */ return TRUE; } /* * Look through the list of * buffers. Return TRUE if there * are any changed buffers. Buffers * that hold magic internal stuff are * not considered; who cares if the * list of buffer names is hacked. * Return FALSE if no buffers * have been changed. */ int anycb(void) { struct buffer *bp; bp = bheadp; while (bp != NULL) { if ((bp->b_flag & BFINVS) == 0 && (bp->b_flag & BFCHG) != 0) return TRUE; bp = bp->b_bufp; } return FALSE; } /* * Find a buffer, by name. Return a pointer * to the buffer structure associated with it. * If the buffer is not found * and the "cflag" is TRUE, create it. The "bflag" is * the settings for the flags in in buffer. */ struct buffer *bfind(char *bname, int cflag, int bflag) { struct buffer *bp; struct buffer *sb; /* buffer to insert after */ struct line *lp; bp = bheadp; while (bp != NULL) { if (strcmp(bname, bp->b_bname) == 0) return bp; bp = bp->b_bufp; } if (cflag != FALSE) { if ((bp = (struct buffer *)malloc(sizeof(struct buffer))) == NULL) return NULL; if ((lp = lalloc(0)) == NULL) { free((char *) bp); return NULL; } /* find the place in the list to insert this buffer */ if (bheadp == NULL || strcmp(bheadp->b_bname, bname) > 0) { /* insert at the beginning */ bp->b_bufp = bheadp; bheadp = bp; } else { sb = bheadp; while (sb->b_bufp != NULL) { if (strcmp(sb->b_bufp->b_bname, bname) > 0) break; sb = sb->b_bufp; } /* and insert it */ bp->b_bufp = sb->b_bufp; sb->b_bufp = bp; } /* and set up the other buffer fields */ bp->b_active = TRUE; bp->b_dotp = lp; bp->b_doto = 0; bp->b_markp = NULL; bp->b_marko = 0; bp->b_flag = bflag; bp->b_mode = gmode; bp->b_nwnd = 0; bp->b_linep = lp; strcpy(bp->b_fname, ""); strcpy(bp->b_bname, bname); #if CRYPT bp->b_key[0] = 0; #endif lp->l_fp = lp; lp->l_bp = lp; } return bp; } /* * This routine blows away all of the text * in a buffer. If the buffer is marked as changed * then we ask if it is ok to blow it away; this is * to save the user the grief of losing text. The * window chain is nearly always wrong if this gets * called; the caller must arrange for the updates * that are required. Return TRUE if everything * looks good. */ int bclear(struct buffer *bp) { struct line *lp; int s; if ((bp->b_flag & BFINVS) == 0 /* Not scratch buffer. */ && (bp->b_flag & BFCHG) != 0 /* Something changed */ && (s = mlyesno("Discard changes")) != TRUE) return s; bp->b_flag &= ~BFCHG; /* Not changed */ while ((lp = lforw(bp->b_linep)) != bp->b_linep) lfree(lp); bp->b_dotp = bp->b_linep; /* Fix "." */ bp->b_doto = 0; bp->b_markp = NULL; /* Invalidate "mark" */ bp->b_marko = 0; return TRUE; } /* * unmark the current buffers change flag * * int f, n; unused command arguments */ int unmark(int f, int n) { curbp->b_flag &= ~BFCHG; curwp->w_flag |= WFMODE; return TRUE; }
uemacs-master
buffer.c
/* display.c * * The functions in this file handle redisplay. There are two halves, the * ones that update the virtual display screen, and the ones that make the * physical display screen the same as the virtual display screen. These * functions use hints that are left in the windows by the commands. * * Modified by Petri Kutvonen */ #include <errno.h> #include <stdio.h> #include <stdarg.h> #include <unistd.h> #include "estruct.h" #include "edef.h" #include "efunc.h" #include "line.h" #include "version.h" #include "wrapper.h" #include "utf8.h" struct video { int v_flag; /* Flags */ #if COLOR int v_fcolor; /* current forground color */ int v_bcolor; /* current background color */ int v_rfcolor; /* requested forground color */ int v_rbcolor; /* requested background color */ #endif unicode_t v_text[1]; /* Screen data. */ }; #define VFCHG 0x0001 /* Changed flag */ #define VFEXT 0x0002 /* extended (beyond column 80) */ #define VFREV 0x0004 /* reverse video status */ #define VFREQ 0x0008 /* reverse video request */ #define VFCOL 0x0010 /* color change requested */ static struct video **vscreen; /* Virtual screen. */ #if MEMMAP == 0 || SCROLLCODE static struct video **pscreen; /* Physical screen. */ #endif static int displaying = TRUE; #if UNIX #include <signal.h> #endif #ifdef SIGWINCH #include <sys/ioctl.h> /* for window size changes */ int chg_width, chg_height; #endif static int reframe(struct window *wp); static void updone(struct window *wp); static void updall(struct window *wp); static int scrolls(int inserts); static void scrscroll(int from, int to, int count); static int texttest(int vrow, int prow); static int endofline(unicode_t *s, int n); static void updext(void); static int updateline(int row, struct video *vp1, struct video *vp2); static void modeline(struct window *wp); static void mlputi(int i, int r); static void mlputli(long l, int r); static void mlputf(int s); static int newscreensize(int h, int w); #if RAINBOW static void putline(int row, int col, char *buf); #endif /* * Initialize the data structures used by the display code. The edge vectors * used to access the screens are set up. The operating system's terminal I/O * channel is set up. All the other things get initialized at compile time. * The original window has "WFCHG" set, so that it will get completely * redrawn on the first call to "update". */ void vtinit(void) { int i; struct video *vp; TTopen(); /* open the screen */ TTkopen(); /* open the keyboard */ TTrev(FALSE); vscreen = xmalloc(term.t_mrow * sizeof(struct video *)); #if MEMMAP == 0 || SCROLLCODE pscreen = xmalloc(term.t_mrow * sizeof(struct video *)); #endif for (i = 0; i < term.t_mrow; ++i) { vp = xmalloc(sizeof(struct video) + term.t_mcol*4); vp->v_flag = 0; #if COLOR vp->v_rfcolor = 7; vp->v_rbcolor = 0; #endif vscreen[i] = vp; #if MEMMAP == 0 || SCROLLCODE vp = xmalloc(sizeof(struct video) + term.t_mcol*4); vp->v_flag = 0; pscreen[i] = vp; #endif } } #if CLEAN /* free up all the dynamically allocated video structures */ void vtfree(void) { int i; for (i = 0; i < term.t_mrow; ++i) { free(vscreen[i]); #if MEMMAP == 0 || SCROLLCODE free(pscreen[i]); #endif } free(vscreen); #if MEMMAP == 0 || SCROLLCODE free(pscreen); #endif } #endif /* * Clean up the virtual terminal system, in anticipation for a return to the * operating system. Move down to the last line and clear it out (the next * system prompt will be written in the line). Shut down the channel to the * terminal. */ void vttidy(void) { mlerase(); movecursor(term.t_nrow, 0); TTflush(); TTclose(); TTkclose(); #ifdef PKCODE write(1, "\r", 1); #endif } /* * Set the virtual cursor to the specified row and column on the virtual * screen. There is no checking for nonsense values; this might be a good * idea during the early stages. */ void vtmove(int row, int col) { vtrow = row; vtcol = col; } /* * Write a character to the virtual screen. The virtual row and * column are updated. If we are not yet on left edge, don't print * it yet. If the line is too long put a "$" in the last column. * * This routine only puts printing characters into the virtual * terminal buffers. Only column overflow is checked. */ static void vtputc(int c) { struct video *vp; /* ptr to line being updated */ /* In case somebody passes us a signed char.. */ if (c < 0) { c += 256; if (c < 0) return; } vp = vscreen[vtrow]; if (vtcol >= term.t_ncol) { ++vtcol; vp->v_text[term.t_ncol - 1] = '$'; return; } if (c == '\t') { do { vtputc(' '); } while (((vtcol + taboff) & tabmask) != 0); return; } if (c < 0x20) { vtputc('^'); vtputc(c ^ 0x40); return; } if (c == 0x7f) { vtputc('^'); vtputc('?'); return; } if (c >= 0x80 && c <= 0xA0) { static const char hex[] = "0123456789abcdef"; vtputc('\\'); vtputc(hex[c >> 4]); vtputc(hex[c & 15]); return; } if (vtcol >= 0) vp->v_text[vtcol] = c; ++vtcol; } /* * Erase from the end of the software cursor to the end of the line on which * the software cursor is located. */ static void vteeol(void) { /* struct video *vp; */ unicode_t *vcp = vscreen[vtrow]->v_text; /* vp = vscreen[vtrow]; */ while (vtcol < term.t_ncol) /* vp->v_text[vtcol++] = ' '; */ vcp[vtcol++] = ' '; } /* * upscreen: * user routine to force a screen update * always finishes complete update */ int upscreen(int f, int n) { update(TRUE); return TRUE; } #if SCROLLCODE static int scrflags; #endif /* * Make sure that the display is right. This is a three part process. First, * scan through all of the windows looking for dirty ones. Check the framing, * and refresh the screen. Second, make sure that "currow" and "curcol" are * correct for the current window. Third, make the virtual and physical * screens the same. * * int force; force update past type ahead? */ int update(int force) { struct window *wp; #if TYPEAH && ! PKCODE if (force == FALSE && typahead()) return TRUE; #endif #if VISMAC == 0 if (force == FALSE && kbdmode == PLAY) return TRUE; #endif displaying = TRUE; #if SCROLLCODE /* first, propagate mode line changes to all instances of a buffer displayed in more than one window */ wp = wheadp; while (wp != NULL) { if (wp->w_flag & WFMODE) { if (wp->w_bufp->b_nwnd > 1) { /* make sure all previous windows have this */ struct window *owp; owp = wheadp; while (owp != NULL) { if (owp->w_bufp == wp->w_bufp) owp->w_flag |= WFMODE; owp = owp->w_wndp; } } } wp = wp->w_wndp; } #endif /* update any windows that need refreshing */ wp = wheadp; while (wp != NULL) { if (wp->w_flag) { /* if the window has changed, service it */ reframe(wp); /* check the framing */ #if SCROLLCODE if (wp->w_flag & (WFKILLS | WFINS)) { scrflags |= (wp->w_flag & (WFINS | WFKILLS)); wp->w_flag &= ~(WFKILLS | WFINS); } #endif if ((wp->w_flag & ~WFMODE) == WFEDIT) updone(wp); /* update EDITed line */ else if (wp->w_flag & ~WFMOVE) updall(wp); /* update all lines */ #if SCROLLCODE if (scrflags || (wp->w_flag & WFMODE)) #else if (wp->w_flag & WFMODE) #endif modeline(wp); /* update modeline */ wp->w_flag = 0; wp->w_force = 0; } /* on to the next window */ wp = wp->w_wndp; } /* recalc the current hardware cursor location */ updpos(); #if MEMMAP && ! SCROLLCODE /* update the cursor and flush the buffers */ movecursor(currow, curcol - lbound); #endif /* check for lines to de-extend */ upddex(); /* if screen is garbage, re-plot it */ if (sgarbf != FALSE) updgar(); /* update the virtual screen to the physical screen */ updupd(force); /* update the cursor and flush the buffers */ movecursor(currow, curcol - lbound); TTflush(); displaying = FALSE; #if SIGWINCH while (chg_width || chg_height) newscreensize(chg_height, chg_width); #endif return TRUE; } /* * reframe: * check to see if the cursor is on in the window * and re-frame it if needed or wanted */ static int reframe(struct window *wp) { struct line *lp, *lp0; int i = 0; /* if not a requested reframe, check for a needed one */ if ((wp->w_flag & WFFORCE) == 0) { #if SCROLLCODE /* loop from one line above the window to one line after */ lp = wp->w_linep; lp0 = lback(lp); if (lp0 == wp->w_bufp->b_linep) i = 0; else { i = -1; lp = lp0; } for (; i <= (int) (wp->w_ntrows); i++) #else lp = wp->w_linep; for (i = 0; i < wp->w_ntrows; i++) #endif { /* if the line is in the window, no reframe */ if (lp == wp->w_dotp) { #if SCROLLCODE /* if not _quite_ in, we'll reframe gently */ if (i < 0 || i == wp->w_ntrows) { /* if the terminal can't help, then we're simply outside */ if (term.t_scroll == NULL) i = wp->w_force; break; } #endif return TRUE; } /* if we are at the end of the file, reframe */ if (lp == wp->w_bufp->b_linep) break; /* on to the next line */ lp = lforw(lp); } } #if SCROLLCODE if (i == -1) { /* we're just above the window */ i = scrollcount; /* put dot at first line */ scrflags |= WFINS; } else if (i == wp->w_ntrows) { /* we're just below the window */ i = -scrollcount; /* put dot at last line */ scrflags |= WFKILLS; } else /* put dot where requested */ #endif i = wp->w_force; /* (is 0, unless reposition() was called) */ wp->w_flag |= WFMODE; /* how far back to reframe? */ if (i > 0) { /* only one screen worth of lines max */ if (--i >= wp->w_ntrows) i = wp->w_ntrows - 1; } else if (i < 0) { /* negative update???? */ i += wp->w_ntrows; if (i < 0) i = 0; } else i = wp->w_ntrows / 2; /* backup to new line at top of window */ lp = wp->w_dotp; while (i != 0 && lback(lp) != wp->w_bufp->b_linep) { --i; lp = lback(lp); } /* and reset the current line at top of window */ wp->w_linep = lp; wp->w_flag |= WFHARD; wp->w_flag &= ~WFFORCE; return TRUE; } static void show_line(struct line *lp) { int i = 0, len = llength(lp); while (i < len) { unicode_t c; i += utf8_to_unicode(lp->l_text, i, len, &c); vtputc(c); } } /* * updone: * update the current line to the virtual screen * * struct window *wp; window to update current line in */ static void updone(struct window *wp) { struct line *lp; /* line to update */ int sline; /* physical screen line to update */ /* search down the line we want */ lp = wp->w_linep; sline = wp->w_toprow; while (lp != wp->w_dotp) { ++sline; lp = lforw(lp); } /* and update the virtual line */ vscreen[sline]->v_flag |= VFCHG; vscreen[sline]->v_flag &= ~VFREQ; vtmove(sline, 0); show_line(lp); #if COLOR vscreen[sline]->v_rfcolor = wp->w_fcolor; vscreen[sline]->v_rbcolor = wp->w_bcolor; #endif vteeol(); } /* * updall: * update all the lines in a window on the virtual screen * * struct window *wp; window to update lines in */ static void updall(struct window *wp) { struct line *lp; /* line to update */ int sline; /* physical screen line to update */ /* search down the lines, updating them */ lp = wp->w_linep; sline = wp->w_toprow; while (sline < wp->w_toprow + wp->w_ntrows) { /* and update the virtual line */ vscreen[sline]->v_flag |= VFCHG; vscreen[sline]->v_flag &= ~VFREQ; vtmove(sline, 0); if (lp != wp->w_bufp->b_linep) { /* if we are not at the end */ show_line(lp); lp = lforw(lp); } /* on to the next one */ #if COLOR vscreen[sline]->v_rfcolor = wp->w_fcolor; vscreen[sline]->v_rbcolor = wp->w_bcolor; #endif vteeol(); ++sline; } } /* * updpos: * update the position of the hardware cursor and handle extended * lines. This is the only update for simple moves. */ void updpos(void) { struct line *lp; int i; /* find the current row */ lp = curwp->w_linep; currow = curwp->w_toprow; while (lp != curwp->w_dotp) { ++currow; lp = lforw(lp); } /* find the current column */ curcol = 0; i = 0; while (i < curwp->w_doto) { unicode_t c; int bytes; bytes = utf8_to_unicode(lp->l_text, i, curwp->w_doto, &c); i += bytes; if (c == '\t') curcol |= tabmask; ++curcol; } /* if extended, flag so and update the virtual line image */ if (curcol >= term.t_ncol - 1) { vscreen[currow]->v_flag |= (VFEXT | VFCHG); updext(); } else lbound = 0; } /* * upddex: * de-extend any line that derserves it */ void upddex(void) { struct window *wp; struct line *lp; int i; wp = wheadp; while (wp != NULL) { lp = wp->w_linep; i = wp->w_toprow; while (i < wp->w_toprow + wp->w_ntrows) { if (vscreen[i]->v_flag & VFEXT) { if ((wp != curwp) || (lp != wp->w_dotp) || (curcol < term.t_ncol - 1)) { vtmove(i, 0); show_line(lp); vteeol(); /* this line no longer is extended */ vscreen[i]->v_flag &= ~VFEXT; vscreen[i]->v_flag |= VFCHG; } } lp = lforw(lp); ++i; } /* and onward to the next window */ wp = wp->w_wndp; } } /* * updgar: * if the screen is garbage, clear the physical screen and * the virtual screen and force a full update */ void updgar(void) { unicode_t *txt; int i, j; for (i = 0; i < term.t_nrow; ++i) { vscreen[i]->v_flag |= VFCHG; #if REVSTA vscreen[i]->v_flag &= ~VFREV; #endif #if COLOR vscreen[i]->v_fcolor = gfcolor; vscreen[i]->v_bcolor = gbcolor; #endif #if MEMMAP == 0 || SCROLLCODE txt = pscreen[i]->v_text; for (j = 0; j < term.t_ncol; ++j) txt[j] = ' '; #endif } movecursor(0, 0); /* Erase the screen. */ (*term.t_eeop) (); sgarbf = FALSE; /* Erase-page clears */ mpresf = FALSE; /* the message area. */ #if COLOR mlerase(); /* needs to be cleared if colored */ #endif } /* * updupd: * update the physical screen from the virtual screen * * int force; forced update flag */ int updupd(int force) { struct video *vp1; int i; #if SCROLLCODE if (scrflags & WFKILLS) scrolls(FALSE); if (scrflags & WFINS) scrolls(TRUE); scrflags = 0; #endif for (i = 0; i < term.t_nrow; ++i) { vp1 = vscreen[i]; /* for each line that needs to be updated */ if ((vp1->v_flag & VFCHG) != 0) { #if TYPEAH && ! PKCODE if (force == FALSE && typahead()) return TRUE; #endif #if MEMMAP && ! SCROLLCODE updateline(i, vp1); #else updateline(i, vp1, pscreen[i]); #endif } } return TRUE; } #if SCROLLCODE /* * optimize out scrolls (line breaks, and newlines) * arg. chooses between looking for inserts or deletes */ static int scrolls(int inserts) { /* returns true if it does something */ struct video *vpv; /* virtual screen image */ struct video *vpp; /* physical screen image */ int i, j, k; int rows, cols; int first, match, count, target, end; int longmatch, longcount; int from, to; if (!term.t_scroll) /* no way to scroll */ return FALSE; rows = term.t_nrow; cols = term.t_ncol; first = -1; for (i = 0; i < rows; i++) { /* find first wrong line */ if (!texttest(i, i)) { first = i; break; } } if (first < 0) return FALSE; /* no text changes */ vpv = vscreen[first]; vpp = pscreen[first]; if (inserts) { /* determine types of potential scrolls */ end = endofline(vpv->v_text, cols); if (end == 0) target = first; /* newlines */ else if (memcmp(vpp->v_text, vpv->v_text, 4*end) == 0) target = first + 1; /* broken line newlines */ else target = first; } else { target = first + 1; } /* find the matching shifted area */ match = -1; longmatch = -1; longcount = 0; from = target; for (i = from + 1; i < rows - longcount /* P.K. */ ; i++) { if (inserts ? texttest(i, from) : texttest(from, i)) { match = i; count = 1; for (j = match + 1, k = from + 1; j < rows && k < rows; j++, k++) { if (inserts ? texttest(j, k) : texttest(k, j)) count++; else break; } if (longcount < count) { longcount = count; longmatch = match; } } } match = longmatch; count = longcount; if (!inserts) { /* full kill case? */ if (match > 0 && texttest(first, match - 1)) { target--; match--; count++; } } /* do the scroll */ if (match > 0 && count > 2) { /* got a scroll */ /* move the count lines starting at target to match */ if (inserts) { from = target; to = match; } else { from = match; to = target; } if (2 * count < abs(from - to)) return FALSE; scrscroll(from, to, count); for (i = 0; i < count; i++) { vpp = pscreen[to + i]; vpv = vscreen[to + i]; memcpy(vpp->v_text, vpv->v_text, 4*cols); vpp->v_flag = vpv->v_flag; /* XXX */ if (vpp->v_flag & VFREV) { vpp->v_flag &= ~VFREV; vpp->v_flag |= ~VFREQ; } #if MEMMAP vscreen[to + i]->v_flag &= ~VFCHG; #endif } if (inserts) { from = target; to = match; } else { from = target + count; to = match + count; } #if MEMMAP == 0 for (i = from; i < to; i++) { unicode_t *txt; txt = pscreen[i]->v_text; for (j = 0; j < term.t_ncol; ++j) txt[j] = ' '; vscreen[i]->v_flag |= VFCHG; } #endif return TRUE; } return FALSE; } /* move the "count" lines starting at "from" to "to" */ static void scrscroll(int from, int to, int count) { ttrow = ttcol = -1; (*term.t_scroll) (from, to, count); } /* * return TRUE on text match * * int vrow, prow; virtual, physical rows */ static int texttest(int vrow, int prow) { struct video *vpv = vscreen[vrow]; /* virtual screen image */ struct video *vpp = pscreen[prow]; /* physical screen image */ return !memcmp(vpv->v_text, vpp->v_text, 4*term.t_ncol); } /* * return the index of the first blank of trailing whitespace */ static int endofline(unicode_t *s, int n) { int i; for (i = n - 1; i >= 0; i--) if (s[i] != ' ') return i + 1; return 0; } #endif /* SCROLLCODE */ /* * updext: * update the extended line which the cursor is currently * on at a column greater than the terminal width. The line * will be scrolled right or left to let the user see where * the cursor is */ static void updext(void) { int rcursor; /* real cursor location */ struct line *lp; /* pointer to current line */ /* calculate what column the real cursor will end up in */ rcursor = ((curcol - term.t_ncol) % term.t_scrsiz) + term.t_margin; taboff = lbound = curcol - rcursor + 1; /* scan through the line outputing characters to the virtual screen */ /* once we reach the left edge */ vtmove(currow, -lbound); /* start scanning offscreen */ lp = curwp->w_dotp; /* line to output */ show_line(lp); /* truncate the virtual line, restore tab offset */ vteeol(); taboff = 0; /* and put a '$' in column 1 */ vscreen[currow]->v_text[0] = '$'; } /* * Update a single line. This does not know how to use insert or delete * character sequences; we are using VT52 functionality. Update the physical * row and column variables. It does try an exploit erase to end of line. The * RAINBOW version of this routine uses fast video. */ #if MEMMAP /* UPDATELINE specific code for the IBM-PC and other compatables */ static int updateline(int row, struct video *vp1, struct video *vp2) { #if SCROLLCODE unicode_t *cp1; unicode_t *cp2; int nch; cp1 = &vp1->v_text[0]; cp2 = &vp2->v_text[0]; nch = term.t_ncol; do { *cp2 = *cp1; ++cp2; ++cp1; } while (--nch); #endif #if COLOR scwrite(row, vp1->v_text, vp1->v_rfcolor, vp1->v_rbcolor); vp1->v_fcolor = vp1->v_rfcolor; vp1->v_bcolor = vp1->v_rbcolor; #else if (vp1->v_flag & VFREQ) scwrite(row, vp1->v_text, 0, 7); else scwrite(row, vp1->v_text, 7, 0); #endif vp1->v_flag &= ~(VFCHG | VFCOL); /* flag this line as changed */ } #else /* * updateline() * * int row; row of screen to update * struct video *vp1; virtual screen image * struct video *vp2; physical screen image */ static int updateline(int row, struct video *vp1, struct video *vp2) { #if RAINBOW /* UPDATELINE specific code for the DEC rainbow 100 micro */ unicode_t *cp1; unicode_t *cp2; int nch; /* since we don't know how to make the rainbow do this, turn it off */ flags &= (~VFREV & ~VFREQ); cp1 = &vp1->v_text[0]; /* Use fast video. */ cp2 = &vp2->v_text[0]; putline(row + 1, 1, cp1); nch = term.t_ncol; do { *cp2 = *cp1; ++cp2; ++cp1; } while (--nch); *flags &= ~VFCHG; #else /* UPDATELINE code for all other versions */ unicode_t *cp1; unicode_t *cp2; unicode_t *cp3; unicode_t *cp4; unicode_t *cp5; int nbflag; /* non-blanks to the right flag? */ int rev; /* reverse video flag */ int req; /* reverse video request flag */ /* set up pointers to virtual and physical lines */ cp1 = &vp1->v_text[0]; cp2 = &vp2->v_text[0]; #if COLOR TTforg(vp1->v_rfcolor); TTbacg(vp1->v_rbcolor); #endif #if REVSTA | COLOR /* if we need to change the reverse video status of the current line, we need to re-write the entire line */ rev = (vp1->v_flag & VFREV) == VFREV; req = (vp1->v_flag & VFREQ) == VFREQ; if ((rev != req) #if COLOR || (vp1->v_fcolor != vp1->v_rfcolor) || (vp1->v_bcolor != vp1->v_rbcolor) #endif ) { movecursor(row, 0); /* Go to start of line. */ /* set rev video if needed */ if (rev != req) (*term.t_rev) (req); /* scan through the line and dump it to the screen and the virtual screen array */ cp3 = &vp1->v_text[term.t_ncol]; while (cp1 < cp3) { TTputc(*cp1); ++ttcol; *cp2++ = *cp1++; } /* turn rev video off */ if (rev != req) (*term.t_rev) (FALSE); /* update the needed flags */ vp1->v_flag &= ~VFCHG; if (req) vp1->v_flag |= VFREV; else vp1->v_flag &= ~VFREV; #if COLOR vp1->v_fcolor = vp1->v_rfcolor; vp1->v_bcolor = vp1->v_rbcolor; #endif return TRUE; } #endif /* advance past any common chars at the left */ while (cp1 != &vp1->v_text[term.t_ncol] && cp1[0] == cp2[0]) { ++cp1; ++cp2; } /* This can still happen, even though we only call this routine on changed * lines. A hard update is always done when a line splits, a massive * change is done, or a buffer is displayed twice. This optimizes out most * of the excess updating. A lot of computes are used, but these tend to * be hard operations that do a lot of update, so I don't really care. */ /* if both lines are the same, no update needs to be done */ if (cp1 == &vp1->v_text[term.t_ncol]) { vp1->v_flag &= ~VFCHG; /* flag this line is changed */ return TRUE; } /* find out if there is a match on the right */ nbflag = FALSE; cp3 = &vp1->v_text[term.t_ncol]; cp4 = &vp2->v_text[term.t_ncol]; while (cp3[-1] == cp4[-1]) { --cp3; --cp4; if (cp3[0] != ' ') /* Note if any nonblank */ nbflag = TRUE; /* in right match. */ } cp5 = cp3; /* Erase to EOL ? */ if (nbflag == FALSE && eolexist == TRUE && (req != TRUE)) { while (cp5 != cp1 && cp5[-1] == ' ') --cp5; if (cp3 - cp5 <= 3) /* Use only if erase is */ cp5 = cp3; /* fewer characters. */ } movecursor(row, cp1 - &vp1->v_text[0]); /* Go to start of line. */ #if REVSTA TTrev(rev); #endif while (cp1 != cp5) { /* Ordinary. */ TTputc(*cp1); ++ttcol; *cp2++ = *cp1++; } if (cp5 != cp3) { /* Erase. */ TTeeol(); while (cp1 != cp3) *cp2++ = *cp1++; } #if REVSTA TTrev(FALSE); #endif vp1->v_flag &= ~VFCHG; /* flag this line as updated */ return TRUE; #endif } #endif /* * Redisplay the mode line for the window pointed to by the "wp". This is the * only routine that has any idea of how the modeline is formatted. You can * change the modeline format by hacking at this routine. Called by "update" * any time there is a dirty window. */ static void modeline(struct window *wp) { char *cp; int c; int n; /* cursor position count */ struct buffer *bp; int i; /* loop index */ int lchar; /* character to draw line in buffer with */ int firstm; /* is this the first mode? */ char tline[NLINE]; /* buffer for part of mode line */ n = wp->w_toprow + wp->w_ntrows; /* Location. */ vscreen[n]->v_flag |= VFCHG | VFREQ | VFCOL; /* Redraw next time. */ #if COLOR vscreen[n]->v_rfcolor = 0; /* black on */ vscreen[n]->v_rbcolor = 7; /* white..... */ #endif vtmove(n, 0); /* Seek to right line. */ if (wp == curwp) /* mark the current buffer */ #if PKCODE lchar = '-'; #else lchar = '='; #endif else #if REVSTA if (revexist) lchar = ' '; else #endif lchar = '-'; bp = wp->w_bufp; #if PKCODE == 0 if ((bp->b_flag & BFTRUNC) != 0) vtputc('#'); else #endif vtputc(lchar); if ((bp->b_flag & BFCHG) != 0) /* "*" if changed. */ vtputc('*'); else vtputc(lchar); n = 2; strcpy(tline, " "); strcat(tline, PROGRAM_NAME_LONG); strcat(tline, " "); strcat(tline, VERSION); strcat(tline, ": "); cp = &tline[0]; while ((c = *cp++) != 0) { vtputc(c); ++n; } cp = &bp->b_bname[0]; while ((c = *cp++) != 0) { vtputc(c); ++n; } strcpy(tline, " ("); /* display the modes */ firstm = TRUE; if ((bp->b_flag & BFTRUNC) != 0) { firstm = FALSE; strcat(tline, "Truncated"); } for (i = 0; i < NUMMODES; i++) /* add in the mode flags */ if (wp->w_bufp->b_mode & (1 << i)) { if (firstm != TRUE) strcat(tline, " "); firstm = FALSE; strcat(tline, mode2name[i]); } strcat(tline, ") "); cp = &tline[0]; while ((c = *cp++) != 0) { vtputc(c); ++n; } #if PKCODE if (bp->b_fname[0] != 0 && strcmp(bp->b_bname, bp->b_fname) != 0) #else if (bp->b_fname[0] != 0) /* File name. */ #endif { #if PKCODE == 0 cp = "File: "; while ((c = *cp++) != 0) { vtputc(c); ++n; } #endif cp = &bp->b_fname[0]; while ((c = *cp++) != 0) { vtputc(c); ++n; } vtputc(' '); ++n; } while (n < term.t_ncol) { /* Pad to full width. */ vtputc(lchar); ++n; } { /* determine if top line, bottom line, or both are visible */ struct line *lp = wp->w_linep; int rows = wp->w_ntrows; char *msg = NULL; vtcol = n - 7; /* strlen(" top ") plus a couple */ while (rows--) { lp = lforw(lp); if (lp == wp->w_bufp->b_linep) { msg = " Bot "; break; } } if (lback(wp->w_linep) == wp->w_bufp->b_linep) { if (msg) { if (wp->w_linep == wp->w_bufp->b_linep) msg = " Emp "; else msg = " All "; } else { msg = " Top "; } } if (!msg) { struct line *lp; int numlines, predlines, ratio; lp = lforw(bp->b_linep); numlines = 0; predlines = 0; while (lp != bp->b_linep) { if (lp == wp->w_linep) { predlines = numlines; } ++numlines; lp = lforw(lp); } if (wp->w_dotp == bp->b_linep) { msg = " Bot "; } else { ratio = 0; if (numlines != 0) ratio = (100L * predlines) / numlines; if (ratio > 99) ratio = 99; sprintf(tline, " %2d%% ", ratio); msg = tline; } } cp = msg; while ((c = *cp++) != 0) { vtputc(c); ++n; } } } void upmode(void) { /* update all the mode lines */ struct window *wp; wp = wheadp; while (wp != NULL) { wp->w_flag |= WFMODE; wp = wp->w_wndp; } } /* * Send a command to the terminal to move the hardware cursor to row "row" * and column "col". The row and column arguments are origin 0. Optimize out * random calls. Update "ttrow" and "ttcol". */ void movecursor(int row, int col) { if (row != ttrow || col != ttcol) { ttrow = row; ttcol = col; TTmove(row, col); } } /* * Erase the message line. This is a special routine because the message line * is not considered to be part of the virtual screen. It always works * immediately; the terminal buffer is flushed via a call to the flusher. */ void mlerase(void) { int i; movecursor(term.t_nrow, 0); if (discmd == FALSE) return; #if COLOR TTforg(7); TTbacg(0); #endif if (eolexist == TRUE) TTeeol(); else { for (i = 0; i < term.t_ncol - 1; i++) TTputc(' '); movecursor(term.t_nrow, 1); /* force the move! */ movecursor(term.t_nrow, 0); } TTflush(); mpresf = FALSE; } /* * Write a message into the message line. Keep track of the physical cursor * position. A small class of printf like format items is handled. Assumes the * stack grows down; this assumption is made by the "++" in the argument scan * loop. Set the "message line" flag TRUE. * * char *fmt; format string for output * char *arg; pointer to first argument to print */ void mlwrite(const char *fmt, ...) { int c; /* current char in format string */ va_list ap; /* if we are not currently echoing on the command line, abort this */ if (discmd == FALSE) { movecursor(term.t_nrow, 0); return; } #if COLOR /* set up the proper colors for the command line */ TTforg(7); TTbacg(0); #endif /* if we can not erase to end-of-line, do it manually */ if (eolexist == FALSE) { mlerase(); TTflush(); } movecursor(term.t_nrow, 0); va_start(ap, fmt); while ((c = *fmt++) != 0) { if (c != '%') { TTputc(c); ++ttcol; } else { c = *fmt++; switch (c) { case 'd': mlputi(va_arg(ap, int), 10); break; case 'o': mlputi(va_arg(ap, int), 8); break; case 'x': mlputi(va_arg(ap, int), 16); break; case 'D': mlputli(va_arg(ap, long), 10); break; case 's': mlputs(va_arg(ap, char *)); break; case 'f': mlputf(va_arg(ap, int)); break; default: TTputc(c); ++ttcol; } } } va_end(ap); /* if we can, erase to the end of screen */ if (eolexist == TRUE) TTeeol(); TTflush(); mpresf = TRUE; } /* * Force a string out to the message line regardless of the * current $discmd setting. This is needed when $debug is TRUE * and for the write-message and clear-message-line commands * * char *s; string to force out */ void mlforce(char *s) { int oldcmd; /* original command display flag */ oldcmd = discmd; /* save the discmd value */ discmd = TRUE; /* and turn display on */ mlwrite(s); /* write the string out */ discmd = oldcmd; /* and restore the original setting */ } /* * Write out a string. Update the physical cursor position. This assumes that * the characters in the string all have width "1"; if this is not the case * things will get screwed up a little. */ void mlputs(char *s) { int c; while ((c = *s++) != 0) { TTputc(c); ++ttcol; } } /* * Write out an integer, in the specified radix. Update the physical cursor * position. */ static void mlputi(int i, int r) { int q; static char hexdigits[] = "0123456789ABCDEF"; if (i < 0) { i = -i; TTputc('-'); } q = i / r; if (q != 0) mlputi(q, r); TTputc(hexdigits[i % r]); ++ttcol; } /* * do the same except as a long integer. */ static void mlputli(long l, int r) { long q; if (l < 0) { l = -l; TTputc('-'); } q = l / r; if (q != 0) mlputli(q, r); TTputc((int) (l % r) + '0'); ++ttcol; } /* * write out a scaled integer with two decimal places * * int s; scaled integer to output */ static void mlputf(int s) { int i; /* integer portion of number */ int f; /* fractional portion of number */ /* break it up */ i = s / 100; f = s % 100; /* send out the integer portion */ mlputi(i, 10); TTputc('.'); TTputc((f / 10) + '0'); TTputc((f % 10) + '0'); ttcol += 3; } #if RAINBOW static void putline(int row, int col, char *buf) { int n; n = strlen(buf); if (col + n - 1 > term.t_ncol) n = term.t_ncol - col + 1; Put_Data(row, col, n, buf); } #endif /* Get terminal size from system. Store number of lines into *heightp and width into *widthp. If zero or a negative number is stored, the value is not valid. */ void getscreensize(int *widthp, int *heightp) { #ifdef TIOCGWINSZ struct winsize size; *widthp = 0; *heightp = 0; if (ioctl(0, TIOCGWINSZ, &size) < 0) return; *widthp = size.ws_col; *heightp = size.ws_row; #else *widthp = 0; *heightp = 0; #endif } #ifdef SIGWINCH void sizesignal(int signr) { int w, h; int old_errno = errno; getscreensize(&w, &h); if (h && w && (h - 1 != term.t_nrow || w != term.t_ncol)) newscreensize(h, w); signal(SIGWINCH, sizesignal); errno = old_errno; } static int newscreensize(int h, int w) { /* do the change later */ if (displaying) { chg_width = w; chg_height = h; return FALSE; } chg_width = chg_height = 0; if (h - 1 < term.t_mrow) newsize(TRUE, h); if (w < term.t_mcol) newwidth(TRUE, w); update(TRUE); return TRUE; } #endif
uemacs-master
display.c
/* basic.c * * The routines in this file move the cursor around on the screen. They * compute a new value for the cursor, then adjust ".". The display code * always updates the cursor location, so only moves between lines, or * functions that adjust the top line in the window and invalidate the * framing, are hard. * * modified by Petri Kutvonen */ #include <stdio.h> #include "estruct.h" #include "edef.h" #include "efunc.h" #include "line.h" #include "utf8.h" /* * This routine, given a pointer to a struct line, and the current cursor goal * column, return the best choice for the offset. The offset is returned. * Used by "C-N" and "C-P". */ static int getgoal(struct line *dlp) { int col; int newcol; int dbo; int len = llength(dlp); col = 0; dbo = 0; while (dbo != len) { unicode_t c; int width = utf8_to_unicode(dlp->l_text, dbo, len, &c); newcol = col; /* Take tabs, ^X and \xx hex characters into account */ if (c == '\t') newcol |= tabmask; else if (c < 0x20 || c == 0x7F) ++newcol; else if (c >= 0x80 && c <= 0xa0) newcol += 2; ++newcol; if (newcol > curgoal) break; col = newcol; dbo += width; } return dbo; } /* * Move the cursor to the beginning of the current line. */ int gotobol(int f, int n) { curwp->w_doto = 0; return TRUE; } /* * Move the cursor backwards by "n" characters. If "n" is less than zero call * "forwchar" to actually do the move. Otherwise compute the new cursor * location. Error if you try and move out of the buffer. Set the flag if the * line pointer for dot changes. */ int backchar(int f, int n) { struct line *lp; if (n < 0) return forwchar(f, -n); while (n--) { if (curwp->w_doto == 0) { if ((lp = lback(curwp->w_dotp)) == curbp->b_linep) return FALSE; curwp->w_dotp = lp; curwp->w_doto = llength(lp); curwp->w_flag |= WFMOVE; } else { do { unsigned char c; curwp->w_doto--; c = lgetc(curwp->w_dotp, curwp->w_doto); if (is_beginning_utf8(c)) break; } while (curwp->w_doto); } } return TRUE; } /* * Move the cursor to the end of the current line. Trivial. No errors. */ int gotoeol(int f, int n) { curwp->w_doto = llength(curwp->w_dotp); return TRUE; } /* * Move the cursor forwards by "n" characters. If "n" is less than zero call * "backchar" to actually do the move. Otherwise compute the new cursor * location, and move ".". Error if you try and move off the end of the * buffer. Set the flag if the line pointer for dot changes. */ int forwchar(int f, int n) { if (n < 0) return backchar(f, -n); while (n--) { int len = llength(curwp->w_dotp); if (curwp->w_doto == len) { if (curwp->w_dotp == curbp->b_linep) return FALSE; curwp->w_dotp = lforw(curwp->w_dotp); curwp->w_doto = 0; curwp->w_flag |= WFMOVE; } else { do { unsigned char c; curwp->w_doto++; c = lgetc(curwp->w_dotp, curwp->w_doto); if (is_beginning_utf8(c)) break; } while (curwp->w_doto < len); } } return TRUE; } /* * Move to a particular line. * * @n: The specified line position at the current buffer. */ int gotoline(int f, int n) { int status; char arg[NSTRING]; /* Buffer to hold argument. */ /* Get an argument if one doesnt exist. */ if (f == FALSE) { if ((status = mlreply("Line to GOTO: ", arg, NSTRING)) != TRUE) { mlwrite("(Aborted)"); return status; } n = atoi(arg); } /* Handle the case where the user may be passed something like this: * em filename + * In this case we just go to the end of the buffer. */ if (n == 0) return gotoeob(f, n); /* If a bogus argument was passed, then returns false. */ if (n < 0) return FALSE; /* First, we go to the begin of the buffer. */ gotobob(f, n); return forwline(f, n - 1); } /* * Goto the beginning of the buffer. Massive adjustment of dot. This is * considered to be hard motion; it really isn't if the original value of dot * is the same as the new value of dot. Normally bound to "M-<". */ int gotobob(int f, int n) { curwp->w_dotp = lforw(curbp->b_linep); curwp->w_doto = 0; curwp->w_flag |= WFHARD; return TRUE; } /* * Move to the end of the buffer. Dot is always put at the end of the file * (ZJ). The standard screen code does most of the hard parts of update. * Bound to "M->". */ int gotoeob(int f, int n) { curwp->w_dotp = curbp->b_linep; curwp->w_doto = 0; curwp->w_flag |= WFHARD; return TRUE; } /* * Move forward by full lines. If the number of lines to move is less than * zero, call the backward line function to actually do it. The last command * controls how the goal column is set. Bound to "C-N". No errors are * possible. */ int forwline(int f, int n) { struct line *dlp; if (n < 0) return backline(f, -n); /* if we are on the last line as we start....fail the command */ if (curwp->w_dotp == curbp->b_linep) return FALSE; /* if the last command was not note a line move, reset the goal column */ if ((lastflag & CFCPCN) == 0) curgoal = getccol(FALSE); /* flag this command as a line move */ thisflag |= CFCPCN; /* and move the point down */ dlp = curwp->w_dotp; while (n-- && dlp != curbp->b_linep) dlp = lforw(dlp); /* reseting the current position */ curwp->w_dotp = dlp; curwp->w_doto = getgoal(dlp); curwp->w_flag |= WFMOVE; return TRUE; } /* * This function is like "forwline", but goes backwards. The scheme is exactly * the same. Check for arguments that are less than zero and call your * alternate. Figure out the new line and call "movedot" to perform the * motion. No errors are possible. Bound to "C-P". */ int backline(int f, int n) { struct line *dlp; if (n < 0) return forwline(f, -n); /* if we are on the last line as we start....fail the command */ if (lback(curwp->w_dotp) == curbp->b_linep) return FALSE; /* if the last command was not note a line move, reset the goal column */ if ((lastflag & CFCPCN) == 0) curgoal = getccol(FALSE); /* flag this command as a line move */ thisflag |= CFCPCN; /* and move the point up */ dlp = curwp->w_dotp; while (n-- && lback(dlp) != curbp->b_linep) dlp = lback(dlp); /* reseting the current position */ curwp->w_dotp = dlp; curwp->w_doto = getgoal(dlp); curwp->w_flag |= WFMOVE; return TRUE; } #if WORDPRO static int is_new_para(void) { int i, len; len = llength(curwp->w_dotp); for (i = 0; i < len; i++) { int c = lgetc(curwp->w_dotp, i); if (c == ' ' || c == TAB) { #if PKCODE if (justflag) continue; #endif return 1; } if (!isletter(c)) return 1; return 0; } return 1; } /* * go back to the beginning of the current paragraph * here we look for a <NL><NL> or <NL><TAB> or <NL><SPACE> * combination to delimit the beginning of a paragraph * * int f, n; default Flag & Numeric argument */ int gotobop(int f, int n) { int suc; /* success of last backchar */ if (n < 0) /* the other way... */ return gotoeop(f, -n); while (n-- > 0) { /* for each one asked for */ /* first scan back until we are in a word */ suc = backchar(FALSE, 1); while (!inword() && suc) suc = backchar(FALSE, 1); curwp->w_doto = 0; /* and go to the B-O-Line */ /* and scan back until we hit a <NL><NL> or <NL><TAB> or a <NL><SPACE> */ while (lback(curwp->w_dotp) != curbp->b_linep) { if (is_new_para()) break; curwp->w_dotp = lback(curwp->w_dotp); } /* and then forward until we are in a word */ suc = forwchar(FALSE, 1); while (suc && !inword()) suc = forwchar(FALSE, 1); } curwp->w_flag |= WFMOVE; /* force screen update */ return TRUE; } /* * Go forword to the end of the current paragraph * here we look for a <NL><NL> or <NL><TAB> or <NL><SPACE> * combination to delimit the beginning of a paragraph * * int f, n; default Flag & Numeric argument */ int gotoeop(int f, int n) { int suc; /* success of last backchar */ if (n < 0) /* the other way... */ return gotobop(f, -n); while (n-- > 0) { /* for each one asked for */ /* first scan forward until we are in a word */ suc = forwchar(FALSE, 1); while (!inword() && suc) suc = forwchar(FALSE, 1); curwp->w_doto = 0; /* and go to the B-O-Line */ if (suc) /* of next line if not at EOF */ curwp->w_dotp = lforw(curwp->w_dotp); /* and scan forword until we hit a <NL><NL> or <NL><TAB> or a <NL><SPACE> */ while (curwp->w_dotp != curbp->b_linep) { if (is_new_para()) break; curwp->w_dotp = lforw(curwp->w_dotp); } /* and then backward until we are in a word */ suc = backchar(FALSE, 1); while (suc && !inword()) { suc = backchar(FALSE, 1); } curwp->w_doto = llength(curwp->w_dotp); /* and to the EOL */ } curwp->w_flag |= WFMOVE; /* force screen update */ return TRUE; } #endif /* * Scroll forward by a specified number of lines, or by a full page if no * argument. Bound to "C-V". The "2" in the arithmetic on the window size is * the overlap; this value is the default overlap value in ITS EMACS. Because * this zaps the top line in the display window, we have to do a hard update. */ int forwpage(int f, int n) { struct line *lp; if (f == FALSE) { #if SCROLLCODE if (term.t_scroll != NULL) if (overlap == 0) n = curwp->w_ntrows / 3 * 2; else n = curwp->w_ntrows - overlap; else #endif n = curwp->w_ntrows - 2; /* Default scroll. */ if (n <= 0) /* Forget the overlap. */ n = 1; /* If tiny window. */ } else if (n < 0) return backpage(f, -n); #if CVMVAS else /* Convert from pages. */ n *= curwp->w_ntrows; /* To lines. */ #endif lp = curwp->w_linep; while (n-- && lp != curbp->b_linep) lp = lforw(lp); curwp->w_linep = lp; curwp->w_dotp = lp; curwp->w_doto = 0; #if SCROLLCODE curwp->w_flag |= WFHARD | WFKILLS; #else curwp->w_flag |= WFHARD; #endif return TRUE; } /* * This command is like "forwpage", but it goes backwards. The "2", like * above, is the overlap between the two windows. The value is from the ITS * EMACS manual. Bound to "M-V". We do a hard update for exactly the same * reason. */ int backpage(int f, int n) { struct line *lp; if (f == FALSE) { #if SCROLLCODE if (term.t_scroll != NULL) if (overlap == 0) n = curwp->w_ntrows / 3 * 2; else n = curwp->w_ntrows - overlap; else #endif n = curwp->w_ntrows - 2; /* Default scroll. */ if (n <= 0) /* Don't blow up if the. */ n = 1; /* Window is tiny. */ } else if (n < 0) return forwpage(f, -n); #if CVMVAS else /* Convert from pages. */ n *= curwp->w_ntrows; /* To lines. */ #endif lp = curwp->w_linep; while (n-- && lback(lp) != curbp->b_linep) lp = lback(lp); curwp->w_linep = lp; curwp->w_dotp = lp; curwp->w_doto = 0; #if SCROLLCODE curwp->w_flag |= WFHARD | WFINS; #else curwp->w_flag |= WFHARD; #endif return TRUE; } /* * Set the mark in the current window to the value of "." in the window. No * errors are possible. Bound to "M-.". */ int setmark(int f, int n) { curwp->w_markp = curwp->w_dotp; curwp->w_marko = curwp->w_doto; mlwrite("(Mark set)"); return TRUE; } /* * Swap the values of "." and "mark" in the current window. This is pretty * easy, bacause all of the hard work gets done by the standard routine * that moves the mark about. The only possible error is "no mark". Bound to * "C-X C-X". */ int swapmark(int f, int n) { struct line *odotp; int odoto; if (curwp->w_markp == NULL) { mlwrite("No mark in this window"); return FALSE; } odotp = curwp->w_dotp; odoto = curwp->w_doto; curwp->w_dotp = curwp->w_markp; curwp->w_doto = curwp->w_marko; curwp->w_markp = odotp; curwp->w_marko = odoto; curwp->w_flag |= WFMOVE; return TRUE; }
uemacs-master
basic.c
/* FILEIO.C * * The routines in this file read and write ASCII files from the disk. All of * the knowledge about files are here. * * modified by Petri Kutvonen */ #include <stdio.h> #include "estruct.h" #include "edef.h" #include "efunc.h" static FILE *ffp; /* File pointer, all functions. */ static int eofflag; /* end-of-file flag */ /* * Open a file for reading. */ int ffropen(char *fn) { if ((ffp = fopen(fn, "r")) == NULL) return FIOFNF; eofflag = FALSE; return FIOSUC; } /* * Open a file for writing. Return TRUE if all is well, and FALSE on error * (cannot create). */ int ffwopen(char *fn) { #if VMS int fd; if ((fd = creat(fn, 0666, "rfm=var", "rat=cr")) < 0 || (ffp = fdopen(fd, "w")) == NULL) { #else if ((ffp = fopen(fn, "w")) == NULL) { #endif mlwrite("Cannot open file for writing"); return FIOERR; } return FIOSUC; } /* * Close a file. Should look at the status in all systems. */ int ffclose(void) { /* free this since we do not need it anymore */ if (fline) { free(fline); fline = NULL; } eofflag = FALSE; #if MSDOS & CTRLZ fputc(26, ffp); /* add a ^Z at the end of the file */ #endif #if V7 | USG | BSD | (MSDOS & (MSC | TURBO)) if (fclose(ffp) != FALSE) { mlwrite("Error closing file"); return FIOERR; } return FIOSUC; #else fclose(ffp); return FIOSUC; #endif } /* * Write a line to the already opened file. The "buf" points to the buffer, * and the "nbuf" is its length, less the free newline. Return the status. * Check only at the newline. */ int ffputline(char *buf, int nbuf) { int i; #if CRYPT char c; /* character to translate */ if (cryptflag) { for (i = 0; i < nbuf; ++i) { c = buf[i] & 0xff; myencrypt(&c, 1); fputc(c, ffp); } } else for (i = 0; i < nbuf; ++i) fputc(buf[i] & 0xFF, ffp); #else for (i = 0; i < nbuf; ++i) fputc(buf[i] & 0xFF, ffp); #endif fputc('\n', ffp); if (ferror(ffp)) { mlwrite("Write I/O error"); return FIOERR; } return FIOSUC; } /* * Read a line from a file, and store the bytes in the supplied buffer. The * "nbuf" is the length of the buffer. Complain about long lines and lines * at the end of the file that don't have a newline present. Check for I/O * errors too. Return status. */ int ffgetline(void) { int c; /* current character read */ int i; /* current index into fline */ char *tmpline; /* temp storage for expanding line */ /* if we are at the end...return it */ if (eofflag) return FIOEOF; /* dump fline if it ended up too big */ if (flen > NSTRING) { free(fline); fline = NULL; } /* if we don't have an fline, allocate one */ if (fline == NULL) if ((fline = malloc(flen = NSTRING)) == NULL) return FIOMEM; /* read the line in */ #if PKCODE if (!nullflag) { if (fgets(fline, NSTRING, ffp) == (char *) NULL) { /* EOF ? */ i = 0; c = EOF; } else { i = strlen(fline); c = 0; if (i > 0) { c = fline[i - 1]; i--; } } } else { i = 0; c = fgetc(ffp); } while (c != EOF && c != '\n') { #else i = 0; while ((c = fgetc(ffp)) != EOF && c != '\n') { #endif #if PKCODE if (c) { #endif fline[i++] = c; /* if it's longer, get more room */ if (i >= flen) { if ((tmpline = malloc(flen + NSTRING)) == NULL) return FIOMEM; strncpy(tmpline, fline, flen); flen += NSTRING; free(fline); fline = tmpline; } #if PKCODE } c = fgetc(ffp); #endif } /* test for any errors that may have occured */ if (c == EOF) { if (ferror(ffp)) { mlwrite("File read error"); return FIOERR; } if (i != 0) eofflag = TRUE; else return FIOEOF; } /* terminate and decrypt the string */ fline[i] = 0; #if CRYPT if (cryptflag) myencrypt(fline, strlen(fline)); #endif return FIOSUC; } /* * does <fname> exist on disk? * * char *fname; file to check for existance */ int fexist(char *fname) { FILE *fp; /* try to open the file for reading */ fp = fopen(fname, "r"); /* if it fails, just return false! */ if (fp == NULL) return FALSE; /* otherwise, close it and report true */ fclose(fp); return TRUE; }
uemacs-master
fileio.c
#include "util.h" /* Safe zeroing, no complaining about overlap */ void mystrscpy(char *dst, const char *src, int size) { if (!size) return; while (--size) { char c = *src++; if (!c) break; *dst++ = c; } *dst = 0; }
uemacs-master
util.c
/* exec.c * * This file is for functions dealing with execution of * commands, command lines, buffers, files and startup files. * * written 1986 by Daniel Lawrence * modified by Petri Kutvonen */ #include <stdio.h> #include "estruct.h" #include "edef.h" #include "efunc.h" #include "line.h" /* * Execute a named command even if it is not bound. */ int namedcmd(int f, int n) { fn_t kfunc; /* ptr to the requexted function to bind to */ /* prompt the user to type a named command */ mlwrite(": "); /* and now get the function name to execute */ kfunc = getname(); if (kfunc == NULL) { mlwrite("(No such function)"); return FALSE; } /* and then execute the command */ return kfunc(f, n); } /* * execcmd: * Execute a command line command to be typed in * by the user * * int f, n; default Flag and Numeric argument */ int execcmd(int f, int n) { int status; /* status return */ char cmdstr[NSTRING]; /* string holding command to execute */ /* get the line wanted */ if ((status = mlreply(": ", cmdstr, NSTRING)) != TRUE) return status; execlevel = 0; return docmd(cmdstr); } /* * docmd: * take a passed string as a command line and translate * it to be executed as a command. This function will be * used by execute-command-line and by all source and * startup files. Lastflag/thisflag is also updated. * * format of the command line is: * * {# arg} <command-name> {<argument string(s)>} * * char *cline; command line to execute */ int docmd(char *cline) { int f; /* default argument flag */ int n; /* numeric repeat value */ fn_t fnc; /* function to execute */ int status; /* return status of function */ int oldcle; /* old contents of clexec flag */ char *oldestr; /* original exec string */ char tkn[NSTRING]; /* next token off of command line */ /* if we are scanning and not executing..go back here */ if (execlevel) return TRUE; oldestr = execstr; /* save last ptr to string to execute */ execstr = cline; /* and set this one as current */ /* first set up the default command values */ f = FALSE; n = 1; lastflag = thisflag; thisflag = 0; if ((status = macarg(tkn)) != TRUE) { /* and grab the first token */ execstr = oldestr; return status; } /* process leadin argument */ if (gettyp(tkn) != TKCMD) { f = TRUE; getval(tkn, tkn, sizeof(tkn)); n = atoi(tkn); /* and now get the command to execute */ if ((status = macarg(tkn)) != TRUE) { execstr = oldestr; return status; } } /* and match the token to see if it exists */ if ((fnc = fncmatch(tkn)) == NULL) { mlwrite("(No such Function)"); execstr = oldestr; return FALSE; } /* save the arguments and go execute the command */ oldcle = clexec; /* save old clexec flag */ clexec = TRUE; /* in cline execution */ status = (*fnc) (f, n); /* call the function */ cmdstatus = status; /* save the status */ clexec = oldcle; /* restore clexec flag */ execstr = oldestr; return status; } /* * token: * chop a token off a string * return a pointer past the token * * char *src, *tok; source string, destination token string * int size; maximum size of token */ char *token(char *src, char *tok, int size) { int quotef; /* is the current string quoted? */ char c; /* temporary character */ /* first scan past any whitespace in the source string */ while (*src == ' ' || *src == '\t') ++src; /* scan through the source string */ quotef = FALSE; while (*src) { /* process special characters */ if (*src == '~') { ++src; if (*src == 0) break; switch (*src++) { case 'r': c = 13; break; case 'n': c = 10; break; case 't': c = 9; break; case 'b': c = 8; break; case 'f': c = 12; break; default: c = *(src - 1); } if (--size > 0) { *tok++ = c; } } else { /* check for the end of the token */ if (quotef) { if (*src == '"') break; } else { if (*src == ' ' || *src == '\t') break; } /* set quote mode if quote found */ if (*src == '"') quotef = TRUE; /* record the character */ c = *src++; if (--size > 0) *tok++ = c; } } /* terminate the token and exit */ if (*src) ++src; *tok = 0; return src; } /* * get a macro line argument * * char *tok; buffer to place argument */ int macarg(char *tok) { int savcle; /* buffer to store original clexec */ int status; savcle = clexec; /* save execution mode */ clexec = TRUE; /* get the argument */ status = nextarg("", tok, NSTRING, ctoec('\n')); clexec = savcle; /* restore execution mode */ return status; } /* * nextarg: * get the next argument * * char *prompt; prompt to use if we must be interactive * char *buffer; buffer to put token into * int size; size of the buffer * int terminator; terminating char to be used on interactive fetch */ int nextarg(char *prompt, char *buffer, int size, int terminator) { /* if we are interactive, go get it! */ if (clexec == FALSE) return getstring(prompt, buffer, size, terminator); /* grab token and advance past */ execstr = token(execstr, buffer, size); /* evaluate it */ getval(buffer, buffer, size); return TRUE; } /* * storemac: * Set up a macro buffer and flag to store all * executed command lines there * * int f; default flag * int n; macro number to use */ int storemac(int f, int n) { struct buffer *bp; /* pointer to macro buffer */ char bname[NBUFN]; /* name of buffer to use */ /* must have a numeric argument to this function */ if (f == FALSE) { mlwrite("No macro specified"); return FALSE; } /* range check the macro number */ if (n < 1 || n > 40) { mlwrite("Macro number out of range"); return FALSE; } /* construct the macro buffer name */ strcpy(bname, "*Macro xx*"); bname[7] = '0' + (n / 10); bname[8] = '0' + (n % 10); /* set up the new macro buffer */ if ((bp = bfind(bname, TRUE, BFINVS)) == NULL) { mlwrite("Can not create macro"); return FALSE; } /* and make sure it is empty */ bclear(bp); /* and set the macro store pointers to it */ mstore = TRUE; bstore = bp; return TRUE; } #if PROC /* * storeproc: * Set up a procedure buffer and flag to store all * executed command lines there * * int f; default flag * int n; macro number to use */ int storeproc(int f, int n) { struct buffer *bp; /* pointer to macro buffer */ int status; /* return status */ char bname[NBUFN]; /* name of buffer to use */ /* a numeric argument means its a numbered macro */ if (f == TRUE) return storemac(f, n); /* get the name of the procedure */ if ((status = mlreply("Procedure name: ", &bname[1], NBUFN - 2)) != TRUE) return status; /* construct the macro buffer name */ bname[0] = '*'; strcat(bname, "*"); /* set up the new macro buffer */ if ((bp = bfind(bname, TRUE, BFINVS)) == NULL) { mlwrite("Can not create macro"); return FALSE; } /* and make sure it is empty */ bclear(bp); /* and set the macro store pointers to it */ mstore = TRUE; bstore = bp; return TRUE; } /* * execproc: * Execute a procedure * * int f, n; default flag and numeric arg */ int execproc(int f, int n) { struct buffer *bp; /* ptr to buffer to execute */ int status; /* status return */ char bufn[NBUFN + 2]; /* name of buffer to execute */ /* find out what buffer the user wants to execute */ if ((status = mlreply("Execute procedure: ", &bufn[1], NBUFN)) != TRUE) return status; /* construct the buffer name */ bufn[0] = '*'; strcat(bufn, "*"); /* find the pointer to that buffer */ if ((bp = bfind(bufn, FALSE, 0)) == NULL) { mlwrite("No such procedure"); return FALSE; } /* and now execute it as asked */ while (n-- > 0) if ((status = dobuf(bp)) != TRUE) return status; return TRUE; } #endif /* * execbuf: * Execute the contents of a buffer of commands * * int f, n; default flag and numeric arg */ int execbuf(int f, int n) { struct buffer *bp; /* ptr to buffer to execute */ int status; /* status return */ char bufn[NSTRING]; /* name of buffer to execute */ /* find out what buffer the user wants to execute */ if ((status = mlreply("Execute buffer: ", bufn, NBUFN)) != TRUE) return status; /* find the pointer to that buffer */ if ((bp = bfind(bufn, FALSE, 0)) == NULL) { mlwrite("No such buffer"); return FALSE; } /* and now execute it as asked */ while (n-- > 0) if ((status = dobuf(bp)) != TRUE) return status; return TRUE; } /* * dobuf: * execute the contents of the buffer pointed to * by the passed BP * * Directives start with a "!" and include: * * !endm End a macro * !if (cond) conditional execution * !else * !endif * !return Return (terminating current macro) * !goto <label> Jump to a label in the current macro * !force Force macro to continue...even if command fails * !while (cond) Execute a loop if the condition is true * !endwhile * * Line Labels begin with a "*" as the first nonblank char, like: * * *LBL01 * * struct buffer *bp; buffer to execute */ int dobuf(struct buffer *bp) { int status; /* status return */ struct line *lp; /* pointer to line to execute */ struct line *hlp; /* pointer to line header */ struct line *glp; /* line to goto */ struct line *mp; /* Macro line storage temp */ int dirnum; /* directive index */ int linlen; /* length of line to execute */ int i; /* index */ int c; /* temp character */ int force; /* force TRUE result? */ struct window *wp; /* ptr to windows to scan */ struct while_block *whlist; /* ptr to !WHILE list */ struct while_block *scanner; /* ptr during scan */ struct while_block *whtemp; /* temporary ptr to a struct while_block */ char *einit; /* initial value of eline */ char *eline; /* text of line to execute */ char tkn[NSTRING]; /* buffer to evaluate an expresion in */ #if DEBUGM char *sp; /* temp for building debug string */ char *ep; /* ptr to end of outline */ #endif /* clear IF level flags/while ptr */ execlevel = 0; whlist = NULL; scanner = NULL; /* scan the buffer to execute, building WHILE header blocks */ hlp = bp->b_linep; lp = hlp->l_fp; while (lp != hlp) { /* scan the current line */ eline = lp->l_text; i = lp->l_used; /* trim leading whitespace */ while (i-- > 0 && (*eline == ' ' || *eline == '\t')) ++eline; /* if theres nothing here, don't bother */ if (i <= 0) goto nxtscan; /* if is a while directive, make a block... */ if (eline[0] == '!' && eline[1] == 'w' && eline[2] == 'h') { whtemp = (struct while_block *)malloc(sizeof(struct while_block)); if (whtemp == NULL) { noram:mlwrite ("%%Out of memory during while scan"); failexit:freewhile (scanner); freewhile(whlist); return FALSE; } whtemp->w_begin = lp; whtemp->w_type = BTWHILE; whtemp->w_next = scanner; scanner = whtemp; } /* if is a BREAK directive, make a block... */ if (eline[0] == '!' && eline[1] == 'b' && eline[2] == 'r') { if (scanner == NULL) { mlwrite ("%%!BREAK outside of any !WHILE loop"); goto failexit; } whtemp = (struct while_block *)malloc(sizeof(struct while_block)); if (whtemp == NULL) goto noram; whtemp->w_begin = lp; whtemp->w_type = BTBREAK; whtemp->w_next = scanner; scanner = whtemp; } /* if it is an endwhile directive, record the spot... */ if (eline[0] == '!' && strncmp(&eline[1], "endw", 4) == 0) { if (scanner == NULL) { mlwrite ("%%!ENDWHILE with no preceding !WHILE in '%s'", bp->b_bname); goto failexit; } /* move top records from the scanner list to the whlist until we have moved all BREAK records and one WHILE record */ do { scanner->w_end = lp; whtemp = whlist; whlist = scanner; scanner = scanner->w_next; whlist->w_next = whtemp; } while (whlist->w_type == BTBREAK); } nxtscan: /* on to the next line */ lp = lp->l_fp; } /* while and endwhile should match! */ if (scanner != NULL) { mlwrite("%%!WHILE with no matching !ENDWHILE in '%s'", bp->b_bname); goto failexit; } /* let the first command inherit the flags from the last one.. */ thisflag = lastflag; /* starting at the beginning of the buffer */ hlp = bp->b_linep; lp = hlp->l_fp; while (lp != hlp) { /* allocate eline and copy macro line to it */ linlen = lp->l_used; if ((einit = eline = malloc(linlen + 1)) == NULL) { mlwrite("%%Out of Memory during macro execution"); freewhile(whlist); return FALSE; } strncpy(eline, lp->l_text, linlen); eline[linlen] = 0; /* make sure it ends */ /* trim leading whitespace */ while (*eline == ' ' || *eline == '\t') ++eline; /* dump comments and blank lines */ if (*eline == ';' || *eline == 0) goto onward; #if DEBUGM /* if $debug == TRUE, every line to execute gets echoed and a key needs to be pressed to continue ^G will abort the command */ if (macbug) { strcpy(outline, "<<<"); /* debug macro name */ strcat(outline, bp->b_bname); strcat(outline, ":"); /* debug if levels */ strcat(outline, itoa(execlevel)); strcat(outline, ":"); /* and lastly the line */ strcat(outline, eline); strcat(outline, ">>>"); /* change all '%' to ':' so mlwrite won't expect arguments */ sp = outline; while (*sp) if (*sp++ == '%') { /* advance to the end */ ep = --sp; while (*ep++); /* null terminate the string one out */ *(ep + 1) = 0; /* copy backwards */ while (ep-- > sp) *(ep + 1) = *ep; /* and advance sp past the new % */ sp += 2; } /* write out the debug line */ mlforce(outline); update(TRUE); /* and get the keystroke */ if ((c = get1key()) == abortc) { mlforce("(Macro aborted)"); freewhile(whlist); return FALSE; } if (c == metac) macbug = FALSE; } #endif /* Parse directives here.... */ dirnum = -1; if (*eline == '!') { /* Find out which directive this is */ ++eline; for (dirnum = 0; dirnum < NUMDIRS; dirnum++) if (strncmp(eline, dname[dirnum], strlen(dname[dirnum])) == 0) break; /* and bitch if it's illegal */ if (dirnum == NUMDIRS) { mlwrite("%%Unknown Directive"); freewhile(whlist); return FALSE; } /* service only the !ENDM macro here */ if (dirnum == DENDM) { mstore = FALSE; bstore = NULL; goto onward; } /* restore the original eline.... */ --eline; } /* if macro store is on, just salt this away */ if (mstore) { /* allocate the space for the line */ linlen = strlen(eline); if ((mp = lalloc(linlen)) == NULL) { mlwrite ("Out of memory while storing macro"); return FALSE; } /* copy the text into the new line */ for (i = 0; i < linlen; ++i) lputc(mp, i, eline[i]); /* attach the line to the end of the buffer */ bstore->b_linep->l_bp->l_fp = mp; mp->l_bp = bstore->b_linep->l_bp; bstore->b_linep->l_bp = mp; mp->l_fp = bstore->b_linep; goto onward; } force = FALSE; /* dump comments */ if (*eline == '*') goto onward; /* now, execute directives */ if (dirnum != -1) { /* skip past the directive */ while (*eline && *eline != ' ' && *eline != '\t') ++eline; execstr = eline; switch (dirnum) { case DIF: /* IF directive */ /* grab the value of the logical exp */ if (execlevel == 0) { if (macarg(tkn) != TRUE) goto eexec; if (stol(tkn) == FALSE) ++execlevel; } else ++execlevel; goto onward; case DWHILE: /* WHILE directive */ /* grab the value of the logical exp */ if (execlevel == 0) { if (macarg(tkn) != TRUE) goto eexec; if (stol(tkn) == TRUE) goto onward; } /* drop down and act just like !BREAK */ case DBREAK: /* BREAK directive */ if (dirnum == DBREAK && execlevel) goto onward; /* jump down to the endwhile */ /* find the right while loop */ whtemp = whlist; while (whtemp) { if (whtemp->w_begin == lp) break; whtemp = whtemp->w_next; } if (whtemp == NULL) { mlwrite ("%%Internal While loop error"); freewhile(whlist); return FALSE; } /* reset the line pointer back.. */ lp = whtemp->w_end; goto onward; case DELSE: /* ELSE directive */ if (execlevel == 1) --execlevel; else if (execlevel == 0) ++execlevel; goto onward; case DENDIF: /* ENDIF directive */ if (execlevel) --execlevel; goto onward; case DGOTO: /* GOTO directive */ /* .....only if we are currently executing */ if (execlevel == 0) { /* grab label to jump to */ eline = token(eline, golabel, NPAT); linlen = strlen(golabel); glp = hlp->l_fp; while (glp != hlp) { if (*glp->l_text == '*' && (strncmp (&glp->l_text[1], golabel, linlen) == 0)) { lp = glp; goto onward; } glp = glp->l_fp; } mlwrite("%%No such label"); freewhile(whlist); return FALSE; } goto onward; case DRETURN: /* RETURN directive */ if (execlevel == 0) goto eexec; goto onward; case DENDWHILE: /* ENDWHILE directive */ if (execlevel) { --execlevel; goto onward; } else { /* find the right while loop */ whtemp = whlist; while (whtemp) { if (whtemp->w_type == BTWHILE && whtemp->w_end == lp) break; whtemp = whtemp->w_next; } if (whtemp == NULL) { mlwrite ("%%Internal While loop error"); freewhile(whlist); return FALSE; } /* reset the line pointer back.. */ lp = whtemp->w_begin->l_bp; goto onward; } case DFORCE: /* FORCE directive */ force = TRUE; } } /* execute the statement */ status = docmd(eline); if (force) /* force the status */ status = TRUE; /* check for a command error */ if (status != TRUE) { /* look if buffer is showing */ wp = wheadp; while (wp != NULL) { if (wp->w_bufp == bp) { /* and point it */ wp->w_dotp = lp; wp->w_doto = 0; wp->w_flag |= WFHARD; } wp = wp->w_wndp; } /* in any case set the buffer . */ bp->b_dotp = lp; bp->b_doto = 0; free(einit); execlevel = 0; freewhile(whlist); return status; } onward: /* on to the next line */ free(einit); lp = lp->l_fp; } eexec: /* exit the current function */ execlevel = 0; freewhile(whlist); return TRUE; } /* * free a list of while block pointers * * struct while_block *wp; head of structure to free */ void freewhile(struct while_block *wp) { if (wp == NULL) return; if (wp->w_next) freewhile(wp->w_next); free(wp); } /* * execute a series of commands in a file * * int f, n; default flag and numeric arg to pass on to file */ int execfile(int f, int n) { int status; /* return status of name query */ char fname[NSTRING]; /* name of file to execute */ char *fspec; /* full file spec */ if ((status = mlreply("File to execute: ", fname, NSTRING - 1)) != TRUE) return status; #if 1 /* look up the path for the file */ fspec = flook(fname, FALSE); /* used to by TRUE, P.K. */ /* if it isn't around */ if (fspec == NULL) return FALSE; #endif /* otherwise, execute it */ while (n-- > 0) if ((status = dofile(fspec)) != TRUE) return status; return TRUE; } /* * dofile: * yank a file into a buffer and execute it * if there are no errors, delete the buffer on exit * * char *fname; file name to execute */ int dofile(char *fname) { struct buffer *bp; /* buffer to place file to exeute */ struct buffer *cb; /* temp to hold current buf while we read */ int status; /* results of various calls */ char bname[NBUFN]; /* name of buffer */ makename(bname, fname); /* derive the name of the buffer */ unqname(bname); /* make sure we don't stomp things */ if ((bp = bfind(bname, TRUE, 0)) == NULL) /* get the needed buffer */ return FALSE; bp->b_mode = MDVIEW; /* mark the buffer as read only */ cb = curbp; /* save the old buffer */ curbp = bp; /* make this one current */ /* and try to read in the file to execute */ if ((status = readin(fname, FALSE)) != TRUE) { curbp = cb; /* restore the current buffer */ return status; } /* go execute it! */ curbp = cb; /* restore the current buffer */ if ((status = dobuf(bp)) != TRUE) return status; /* if not displayed, remove the now unneeded buffer and exit */ if (bp->b_nwnd == 0) zotbuf(bp); return TRUE; } /* * cbuf: * Execute the contents of a numbered buffer * * int f, n; default flag and numeric arg * int bufnum; number of buffer to execute */ int cbuf(int f, int n, int bufnum) { struct buffer *bp; /* ptr to buffer to execute */ int status; /* status return */ static char bufname[] = "*Macro xx*"; /* make the buffer name */ bufname[7] = '0' + (bufnum / 10); bufname[8] = '0' + (bufnum % 10); /* find the pointer to that buffer */ if ((bp = bfind(bufname, FALSE, 0)) == NULL) { mlwrite("Macro not defined"); return FALSE; } /* and now execute it as asked */ while (n-- > 0) if ((status = dobuf(bp)) != TRUE) return status; return TRUE; } int cbuf1(int f, int n) { return cbuf(f, n, 1); } int cbuf2(int f, int n) { return cbuf(f, n, 2); } int cbuf3(int f, int n) { return cbuf(f, n, 3); } int cbuf4(int f, int n) { return cbuf(f, n, 4); } int cbuf5(int f, int n) { return cbuf(f, n, 5); } int cbuf6(int f, int n) { return cbuf(f, n, 6); } int cbuf7(int f, int n) { return cbuf(f, n, 7); } int cbuf8(int f, int n) { return cbuf(f, n, 8); } int cbuf9(int f, int n) { return cbuf(f, n, 9); } int cbuf10(int f, int n) { return cbuf(f, n, 10); } int cbuf11(int f, int n) { return cbuf(f, n, 11); } int cbuf12(int f, int n) { return cbuf(f, n, 12); } int cbuf13(int f, int n) { return cbuf(f, n, 13); } int cbuf14(int f, int n) { return cbuf(f, n, 14); } int cbuf15(int f, int n) { return cbuf(f, n, 15); } int cbuf16(int f, int n) { return cbuf(f, n, 16); } int cbuf17(int f, int n) { return cbuf(f, n, 17); } int cbuf18(int f, int n) { return cbuf(f, n, 18); } int cbuf19(int f, int n) { return cbuf(f, n, 19); } int cbuf20(int f, int n) { return cbuf(f, n, 20); } int cbuf21(int f, int n) { return cbuf(f, n, 21); } int cbuf22(int f, int n) { return cbuf(f, n, 22); } int cbuf23(int f, int n) { return cbuf(f, n, 23); } int cbuf24(int f, int n) { return cbuf(f, n, 24); } int cbuf25(int f, int n) { return cbuf(f, n, 25); } int cbuf26(int f, int n) { return cbuf(f, n, 26); } int cbuf27(int f, int n) { return cbuf(f, n, 27); } int cbuf28(int f, int n) { return cbuf(f, n, 28); } int cbuf29(int f, int n) { return cbuf(f, n, 29); } int cbuf30(int f, int n) { return cbuf(f, n, 30); } int cbuf31(int f, int n) { return cbuf(f, n, 31); } int cbuf32(int f, int n) { return cbuf(f, n, 32); } int cbuf33(int f, int n) { return cbuf(f, n, 33); } int cbuf34(int f, int n) { return cbuf(f, n, 34); } int cbuf35(int f, int n) { return cbuf(f, n, 35); } int cbuf36(int f, int n) { return cbuf(f, n, 36); } int cbuf37(int f, int n) { return cbuf(f, n, 37); } int cbuf38(int f, int n) { return cbuf(f, n, 38); } int cbuf39(int f, int n) { return cbuf(f, n, 39); } int cbuf40(int f, int n) { return cbuf(f, n, 40); }
uemacs-master
exec.c
/* posix.c * * The functions in this file negotiate with the operating system for * characters, and write characters in a barely buffered fashion on the * display. All operating systems. * * modified by Petri Kutvonen * * based on termio.c, with all the old cruft removed, and * fixed for termios rather than the old termio.. Linus Torvalds */ #ifdef POSIX #include <errno.h> #include <fcntl.h> #include <signal.h> #include <stdio.h> #include <termios.h> #include <unistd.h> #include "estruct.h" #include "edef.h" #include "efunc.h" #include "utf8.h" /* Since Mac OS X's termios.h doesn't have the following 2 macros, define them. */ #if defined(SYSV) && (defined(_DARWIN_C_SOURCE) || defined(_FREEBSD_C_SOURCE)) #define OLCUC 0000002 #define XCASE 0000004 #endif static int kbdflgs; /* saved keyboard fd flags */ static int kbdpoll; /* in O_NDELAY mode */ static struct termios otermios; /* original terminal characteristics */ static struct termios ntermios; /* charactoristics to use inside */ #define TBUFSIZ 128 static char tobuf[TBUFSIZ]; /* terminal output buffer */ /* * This function is called once to set up the terminal device streams. * On VMS, it translates TT until it finds the terminal, then assigns * a channel to it and sets it raw. On CPM it is a no-op. */ void ttopen(void) { tcgetattr(0, &otermios); /* save old settings */ /* * base new settings on old ones - don't change things * we don't know about */ ntermios = otermios; /* raw CR/NL etc input handling, but keep ISTRIP if we're on a 7-bit line */ ntermios.c_iflag &= ~(IGNBRK | BRKINT | IGNPAR | PARMRK | INPCK | INLCR | IGNCR | ICRNL); /* raw CR/NR etc output handling */ ntermios.c_oflag &= ~(OPOST | ONLCR | OLCUC | OCRNL | ONOCR | ONLRET); /* No signal handling, no echo etc */ ntermios.c_lflag &= ~(ISIG | ICANON | XCASE | ECHO | ECHOE | ECHOK | ECHONL | NOFLSH | TOSTOP | ECHOCTL | ECHOPRT | ECHOKE | FLUSHO | PENDIN | IEXTEN); /* one character, no timeout */ ntermios.c_cc[VMIN] = 1; ntermios.c_cc[VTIME] = 0; tcsetattr(0, TCSADRAIN, &ntermios); /* and activate them */ /* * provide a smaller terminal output buffer so that * the type ahead detection works better (more often) */ setbuffer(stdout, &tobuf[0], TBUFSIZ); kbdflgs = fcntl(0, F_GETFL, 0); kbdpoll = FALSE; /* on all screens we are not sure of the initial position of the cursor */ ttrow = 999; ttcol = 999; } /* * This function gets called just before we go back home to the command * interpreter. On VMS it puts the terminal back in a reasonable state. * Another no-operation on CPM. */ void ttclose(void) { tcsetattr(0, TCSADRAIN, &otermios); /* restore terminal settings */ } /* * Write a character to the display. On VMS, terminal output is buffered, and * we just put the characters in the big array, after checking for overflow. * On CPM terminal I/O unbuffered, so we just write the byte out. Ditto on * MS-DOS (use the very very raw console output routine). */ int ttputc(int c) { char utf8[6]; int bytes; bytes = unicode_to_utf8(c, utf8); fwrite(utf8, 1, bytes, stdout); return 0; } /* * Flush terminal buffer. Does real work where the terminal output is buffered * up. A no-operation on systems where byte at a time terminal I/O is done. */ void ttflush(void) { /* * Add some terminal output success checking, sometimes an orphaned * process may be left looping on SunOS 4.1. * * How to recover here, or is it best just to exit and lose * everything? * * jph, 8-Oct-1993 * Jani Jaakkola suggested using select after EAGAIN but let's just wait a bit * */ int status; status = fflush(stdout); while (status < 0 && errno == EAGAIN) { sleep(1); status = fflush(stdout); } if (status < 0) exit(15); } /* * Read a character from the terminal, performing no editing and doing no echo * at all. More complex in VMS that almost anyplace else, which figures. Very * simple on CPM, because the system can do exactly what you want. */ int ttgetc(void) { static char buffer[32]; static int pending; unicode_t c; int count, bytes = 1, expected; count = pending; if (!count) { count = read(0, buffer, sizeof(buffer)); if (count <= 0) return 0; pending = count; } c = (unsigned char) buffer[0]; if (c >= 32 && c < 128) goto done; /* * Lazy. We don't bother calculating the exact * expected length. We want at least two characters * for the special character case (ESC+[) and for * the normal short UTF8 sequence that starts with * the 110xxxxx pattern. * * But if we have any of the other patterns, just * try to get more characters. At worst, that will * just result in a barely perceptible 0.1 second * delay for some *very* unusual utf8 character * input. */ expected = 2; if ((c & 0xe0) == 0xe0) expected = 6; /* Special character - try to fill buffer */ if (count < expected) { int n; ntermios.c_cc[VMIN] = 0; ntermios.c_cc[VTIME] = 1; /* A .1 second lag */ tcsetattr(0, TCSANOW, &ntermios); n = read(0, buffer + count, sizeof(buffer) - count); /* Undo timeout */ ntermios.c_cc[VMIN] = 1; ntermios.c_cc[VTIME] = 0; tcsetattr(0, TCSANOW, &ntermios); if (n > 0) pending += n; } if (pending > 1) { unsigned char second = buffer[1]; /* Turn ESC+'[' into CSI */ if (c == 27 && second == '[') { bytes = 2; c = 128+27; goto done; } } bytes = utf8_to_unicode(buffer, 0, pending, &c); /* Hackety hack! Turn no-break space into regular space */ if (c == 0xa0) c = ' '; done: pending -= bytes; memmove(buffer, buffer+bytes, pending); return c; } /* typahead: Check to see if any characters are already in the keyboard buffer */ int typahead(void) { int x; /* holds # of pending chars */ #ifdef FIONREAD if (ioctl(0, FIONREAD, &x) < 0) x = 0; #else x = 0; #endif return x; } #endif /* POSIX */
uemacs-master
posix.c
/* TERMIO.C * * The functions in this file negotiate with the operating system for * characters, and write characters in a barely buffered fashion on the display. * All operating systems. * * modified by Petri Kutvonen */ #ifndef POSIX #include <stdio.h> #include "estruct.h" #include "edef.h" #if VMS #include <stsdef.h> #include <ssdef.h> #include <descrip.h> #include <iodef.h> #include <ttdef.h> #include <tt2def.h> #define NIBUF 128 /* Input buffer size */ #define NOBUF 1024 /* MM says bug buffers win! */ #define EFN 0 /* Event flag */ char obuf[NOBUF]; /* Output buffer */ int nobuf; /* # of bytes in above */ char ibuf[NIBUF]; /* Input buffer */ int nibuf; /* # of bytes in above */ int ibufi; /* Read index */ int oldmode[3]; /* Old TTY mode bits */ int newmode[3]; /* New TTY mode bits */ short iochan; /* TTY I/O channel */ #endif #if MSDOS & (MSC | TURBO) union REGS rg; /* cpu register for use of DOS calls */ int nxtchar = -1; /* character held from type ahead */ #endif #if USG /* System V */ #include <signal.h> #include <termio.h> #include <fcntl.h> int kbdflgs; /* saved keyboard fd flags */ int kbdpoll; /* in O_NDELAY mode */ int kbdqp; /* there is a char in kbdq */ char kbdq; /* char we've already read */ struct termio otermio; /* original terminal characteristics */ struct termio ntermio; /* charactoristics to use inside */ #if XONXOFF #define XXMASK 0016000 #endif #endif #if V7 | BSD #include <sgtty.h> /* for stty/gtty functions */ #include <signal.h> struct sgttyb ostate; /* saved tty state */ struct sgttyb nstate; /* values for editor mode */ struct tchars otchars; /* Saved terminal special character set */ #if XONXOFF struct tchars ntchars = { 0xff, 0xff, 0x11, 0x13, 0xff, 0xff }; /* A lot of nothing and XON/XOFF */ #else struct tchars ntchars = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; /* A lot of nothing */ #endif #if BSD & PKCODE struct ltchars oltchars; /* Saved terminal local special character set */ struct ltchars nltchars = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; /* A lot of nothing */ #endif #if BSD #include <sys/ioctl.h> /* to get at the typeahead */ extern int rtfrmshell(); /* return from suspended shell */ #define TBUFSIZ 128 char tobuf[TBUFSIZ]; /* terminal output buffer */ #endif #endif #if __hpux | SVR4 extern int rtfrmshell(); /* return from suspended shell */ #define TBUFSIZ 128 char tobuf[TBUFSIZ]; /* terminal output buffer */ #endif /* * This function is called once to set up the terminal device streams. * On VMS, it translates TT until it finds the terminal, then assigns * a channel to it and sets it raw. On CPM it is a no-op. */ void ttopen(void) { #if VMS struct dsc$descriptor idsc; struct dsc$descriptor odsc; char oname[40]; int iosb[2]; int status; odsc.dsc$a_pointer = "TT"; odsc.dsc$w_length = strlen(odsc.dsc$a_pointer); odsc.dsc$b_dtype = DSC$K_DTYPE_T; odsc.dsc$b_class = DSC$K_CLASS_S; idsc.dsc$b_dtype = DSC$K_DTYPE_T; idsc.dsc$b_class = DSC$K_CLASS_S; do { idsc.dsc$a_pointer = odsc.dsc$a_pointer; idsc.dsc$w_length = odsc.dsc$w_length; odsc.dsc$a_pointer = &oname[0]; odsc.dsc$w_length = sizeof(oname); status = LIB$SYS_TRNLOG(&idsc, &odsc.dsc$w_length, &odsc); if (status != SS$_NORMAL && status != SS$_NOTRAN) exit(status); if (oname[0] == 0x1B) { odsc.dsc$a_pointer += 4; odsc.dsc$w_length -= 4; } } while (status == SS$_NORMAL); status = SYS$ASSIGN(&odsc, &iochan, 0, 0); if (status != SS$_NORMAL) exit(status); status = SYS$QIOW(EFN, iochan, IO$_SENSEMODE, iosb, 0, 0, oldmode, sizeof(oldmode), 0, 0, 0, 0); if (status != SS$_NORMAL || (iosb[0] & 0xFFFF) != SS$_NORMAL) exit(status); newmode[0] = oldmode[0]; newmode[1] = oldmode[1] | TT$M_NOECHO; #if XONXOFF #else newmode[1] &= ~(TT$M_TTSYNC | TT$M_HOSTSYNC); #endif newmode[2] = oldmode[2] | TT2$M_PASTHRU; status = SYS$QIOW(EFN, iochan, IO$_SETMODE, iosb, 0, 0, newmode, sizeof(newmode), 0, 0, 0, 0); if (status != SS$_NORMAL || (iosb[0] & 0xFFFF) != SS$_NORMAL) exit(status); term.t_nrow = (newmode[1] >> 24) - 1; term.t_ncol = newmode[0] >> 16; #endif #if MSDOS & (TURBO | (PKCODE & MSC)) /* kill the CONTROL-break interupt */ rg.h.ah = 0x33; /* control-break check dos call */ rg.h.al = 1; /* set the current state */ rg.h.dl = 0; /* set it OFF */ intdos(&rg, &rg); /* go for it! */ #endif #if USG ioctl(0, TCGETA, &otermio); /* save old settings */ ntermio.c_iflag = 0; /* setup new settings */ #if XONXOFF ntermio.c_iflag = otermio.c_iflag & XXMASK; /* save XON/XOFF P.K. */ #endif ntermio.c_oflag = 0; ntermio.c_cflag = otermio.c_cflag; ntermio.c_lflag = 0; ntermio.c_line = otermio.c_line; ntermio.c_cc[VMIN] = 1; ntermio.c_cc[VTIME] = 0; #if PKCODE ioctl(0, TCSETAW, &ntermio); /* and activate them */ #else ioctl(0, TCSETA, &ntermio); /* and activate them */ #endif kbdflgs = fcntl(0, F_GETFL, 0); kbdpoll = FALSE; #endif #if V7 | BSD gtty(0, &ostate); /* save old state */ gtty(0, &nstate); /* get base of new state */ #if XONXOFF nstate.sg_flags |= (CBREAK | TANDEM); #else nstate.sg_flags |= RAW; #endif nstate.sg_flags &= ~(ECHO | CRMOD); /* no echo for now... */ stty(0, &nstate); /* set mode */ ioctl(0, TIOCGETC, &otchars); /* Save old characters */ ioctl(0, TIOCSETC, &ntchars); /* Place new character into K */ #if BSD & PKCODE ioctl(0, TIOCGLTC, &oltchars); /* Save old local characters */ ioctl(0, TIOCSLTC, &nltchars); /* New local characters */ #endif #if BSD /* provide a smaller terminal output buffer so that the type ahead detection works better (more often) */ setbuffer(stdout, &tobuf[0], TBUFSIZ); signal(SIGTSTP, SIG_DFL); /* set signals so that we can */ signal(SIGCONT, rtfrmshell); /* suspend & restart emacs */ #endif #endif #if __hpux | SVR4 /* provide a smaller terminal output buffer so that the type ahead detection works better (more often) */ setvbuf(stdout, &tobuf[0], _IOFBF, TBUFSIZ); signal(SIGTSTP, SIG_DFL); /* set signals so that we can */ signal(SIGCONT, rtfrmshell); /* suspend & restart emacs */ TTflush(); #endif /* __hpux */ /* on all screens we are not sure of the initial position of the cursor */ ttrow = 999; ttcol = 999; } /* * This function gets called just before we go back home to the command * interpreter. On VMS it puts the terminal back in a reasonable state. * Another no-operation on CPM. */ void ttclose(void) { #if VMS int status; int iosb[1]; ttflush(); status = SYS$QIOW(EFN, iochan, IO$_SETMODE, iosb, 0, 0, oldmode, sizeof(oldmode), 0, 0, 0, 0); if (status != SS$_NORMAL || (iosb[0] & 0xFFFF) != SS$_NORMAL) exit(status); status = SYS$DASSGN(iochan); if (status != SS$_NORMAL) exit(status); #endif #if MSDOS & (TURBO | (PKCODE & MSC)) /* restore the CONTROL-break interupt */ rg.h.ah = 0x33; /* control-break check dos call */ rg.h.al = 1; /* set the current state */ rg.h.dl = 1; /* set it ON */ intdos(&rg, &rg); /* go for it! */ #endif #if USG #if PKCODE ioctl(0, TCSETAW, &otermio); /* restore terminal settings */ #else ioctl(0, TCSETA, &otermio); /* restore terminal settings */ #endif fcntl(0, F_SETFL, kbdflgs); #endif #if V7 | BSD stty(0, &ostate); ioctl(0, TIOCSETC, &otchars); /* Place old character into K */ #if BSD & PKCODE ioctl(0, TIOCSLTC, &oltchars); /* Place old local character into K */ #endif #endif } /* * Write a character to the display. On VMS, terminal output is buffered, and * we just put the characters in the big array, after checking for overflow. * On CPM terminal I/O unbuffered, so we just write the byte out. Ditto on * MS-DOS (use the very very raw console output routine). */ void ttputc(c) { #if VMS if (nobuf >= NOBUF) ttflush(); obuf[nobuf++] = c; #endif #if MSDOS & ~IBMPC bdos(6, c, 0); #endif #if V7 | USG | BSD fputc(c, stdout); #endif } /* * Flush terminal buffer. Does real work where the terminal output is buffered * up. A no-operation on systems where byte at a time terminal I/O is done. */ int ttflush(void) { #if VMS int status; int iosb[2]; status = SS$_NORMAL; if (nobuf != 0) { status = SYS$QIOW(EFN, iochan, IO$_WRITELBLK | IO$M_NOFORMAT, iosb, 0, 0, obuf, nobuf, 0, 0, 0, 0); if (status == SS$_NORMAL) status = iosb[0] & 0xFFFF; nobuf = 0; } return status; #endif #if MSDOS #endif #if V7 | USG | BSD /* * Add some terminal output success checking, sometimes an orphaned * process may be left looping on SunOS 4.1. * * How to recover here, or is it best just to exit and lose * everything? * * jph, 8-Oct-1993 */ #include <errno.h> int status; status = fflush(stdout); if (status != 0 && errno != EAGAIN) { exit(errno); } #endif } /* * Read a character from the terminal, performing no editing and doing no echo * at all. More complex in VMS that almost anyplace else, which figures. Very * simple on CPM, because the system can do exactly what you want. */ ttgetc() { #if VMS int status; int iosb[2]; int term[2]; while (ibufi >= nibuf) { ibufi = 0; term[0] = 0; term[1] = 0; status = SYS$QIOW(EFN, iochan, IO$_READLBLK | IO$M_TIMED, iosb, 0, 0, ibuf, NIBUF, 0, term, 0, 0); if (status != SS$_NORMAL) exit(status); status = iosb[0] & 0xFFFF; if (status != SS$_NORMAL && status != SS$_TIMEOUT && status != SS$_DATAOVERUN) exit(status); nibuf = (iosb[0] >> 16) + (iosb[1] >> 16); if (nibuf == 0) { status = SYS$QIOW(EFN, iochan, IO$_READLBLK, iosb, 0, 0, ibuf, 1, 0, term, 0, 0); if (status != SS$_NORMAL || (status = (iosb[0] & 0xFFFF)) != SS$_NORMAL) if (status != SS$_DATAOVERUN) exit(status); nibuf = (iosb[0] >> 16) + (iosb[1] >> 16); } } return ibuf[ibufi++] & 0xFF; /* Allow multinational */ #endif #if MSDOS & (MSC | TURBO) int c; /* character read */ /* if a char already is ready, return it */ if (nxtchar >= 0) { c = nxtchar; nxtchar = -1; return c; } /* call the dos to get a char */ rg.h.ah = 7; /* dos Direct Console Input call */ intdos(&rg, &rg); c = rg.h.al; /* grab the char */ return c & 255; #endif #if V7 | BSD return 255 & fgetc(stdin); /* 8BIT P.K. */ #endif #if USG if (kbdqp) kbdqp = FALSE; else { if (kbdpoll && fcntl(0, F_SETFL, kbdflgs) < 0) return FALSE; kbdpoll = FALSE; while (read(0, &kbdq, 1) != 1); } return kbdq & 255; #endif } #if TYPEAH /* typahead: Check to see if any characters are already in the keyboard buffer */ typahead() { #if MSDOS & (MSC | TURBO) if (kbhit() != 0) return TRUE; else return FALSE; #endif #if BSD int x; /* holds # of pending chars */ return (ioctl(0, FIONREAD, &x) < 0) ? 0 : x; #endif #if PKCODE & VMS return ibufi < nibuf; #endif #if USG if (!kbdqp) { if (!kbdpoll && fcntl(0, F_SETFL, kbdflgs | O_NDELAY) < 0) return FALSE; #if PKCODE kbdpoll = 1; #endif kbdqp = (1 == read(0, &kbdq, 1)); } return kbdqp; #endif #if !UNIX & !VMS & !MSDOS return FALSE; #endif } #endif #endif /* not POSIX */
uemacs-master
termio.c
/* bind.c * * This file is for functions having to do with key bindings, * descriptions, help commands and startup file. * * Written 11-feb-86 by Daniel Lawrence * Modified by Petri Kutvonen */ #include <stdio.h> #include "estruct.h" #include "edef.h" #include "efunc.h" #include "epath.h" #include "line.h" #include "util.h" int help(int f, int n) { /* give me some help!!!! bring up a fake buffer and read the help file into it with view mode */ struct window *wp; /* scaning pointer to windows */ struct buffer *bp; /* buffer pointer to help */ char *fname = NULL; /* ptr to file returned by flook() */ /* first check if we are already here */ bp = bfind("emacs.hlp", FALSE, BFINVS); if (bp == NULL) { fname = flook(pathname[1], FALSE); if (fname == NULL) { mlwrite("(Help file is not online)"); return FALSE; } } /* split the current window to make room for the help stuff */ if (splitwind(FALSE, 1) == FALSE) return FALSE; if (bp == NULL) { /* and read the stuff in */ if (getfile(fname, FALSE) == FALSE) return FALSE; } else swbuffer(bp); /* make this window in VIEW mode, update all mode lines */ curwp->w_bufp->b_mode |= MDVIEW; curwp->w_bufp->b_flag |= BFINVS; wp = wheadp; while (wp != NULL) { wp->w_flag |= WFMODE; wp = wp->w_wndp; } return TRUE; } int deskey(int f, int n) { /* describe the command for a certain key */ int c; /* key to describe */ char *ptr; /* string pointer to scan output strings */ char outseq[NSTRING]; /* output buffer for command sequence */ /* prompt the user to type us a key to describe */ mlwrite(": describe-key "); /* get the command sequence to describe change it to something we can print as well */ cmdstr(c = getckey(FALSE), &outseq[0]); /* and dump it out */ ostring(outseq); ostring(" "); /* find the right ->function */ if ((ptr = getfname(getbind(c))) == NULL) ptr = "Not Bound"; /* output the command sequence */ ostring(ptr); return TRUE; } /* * bindtokey: * add a new key to the key binding table * * int f, n; command arguments [IGNORED] */ int bindtokey(int f, int n) { unsigned int c; /* command key to bind */ fn_t kfunc; /* ptr to the requested function to bind to */ struct key_tab *ktp; /* pointer into the command table */ int found; /* matched command flag */ char outseq[80]; /* output buffer for keystroke sequence */ /* prompt the user to type in a key to bind */ mlwrite(": bind-to-key "); /* get the function name to bind it to */ kfunc = getname(); if (kfunc == NULL) { mlwrite("(No such function)"); return FALSE; } ostring(" "); /* get the command sequence to bind */ c = getckey((kfunc == metafn) || (kfunc == cex) || (kfunc == unarg) || (kfunc == ctrlg)); /* change it to something we can print as well */ cmdstr(c, &outseq[0]); /* and dump it out */ ostring(outseq); /* if the function is a prefix key */ if (kfunc == metafn || kfunc == cex || kfunc == unarg || kfunc == ctrlg) { /* search for an existing binding for the prefix key */ ktp = &keytab[0]; found = FALSE; while (ktp->k_fp != NULL) { if (ktp->k_fp == kfunc) unbindchar(ktp->k_code); ++ktp; } /* reset the appropriate global prefix variable */ if (kfunc == metafn) metac = c; if (kfunc == cex) ctlxc = c; if (kfunc == unarg) reptc = c; if (kfunc == ctrlg) abortc = c; } /* search the table to see if it exists */ ktp = &keytab[0]; found = FALSE; while (ktp->k_fp != NULL) { if (ktp->k_code == c) { found = TRUE; break; } ++ktp; } if (found) { /* it exists, just change it then */ ktp->k_fp = kfunc; } else { /* otherwise we need to add it to the end */ /* if we run out of binding room, bitch */ if (ktp >= &keytab[NBINDS]) { mlwrite("Binding table FULL!"); return FALSE; } ktp->k_code = c; /* add keycode */ ktp->k_fp = kfunc; /* and the function pointer */ ++ktp; /* and make sure the next is null */ ktp->k_code = 0; ktp->k_fp = NULL; } return TRUE; } /* * unbindkey: * delete a key from the key binding table * * int f, n; command arguments [IGNORED] */ int unbindkey(int f, int n) { int c; /* command key to unbind */ char outseq[80]; /* output buffer for keystroke sequence */ /* prompt the user to type in a key to unbind */ mlwrite(": unbind-key "); /* get the command sequence to unbind */ c = getckey(FALSE); /* get a command sequence */ /* change it to something we can print as well */ cmdstr(c, &outseq[0]); /* and dump it out */ ostring(outseq); /* if it isn't bound, bitch */ if (unbindchar(c) == FALSE) { mlwrite("(Key not bound)"); return FALSE; } return TRUE; } /* * unbindchar() * * int c; command key to unbind */ int unbindchar(int c) { struct key_tab *ktp; /* pointer into the command table */ struct key_tab *sktp; /* saved pointer into the command table */ int found; /* matched command flag */ /* search the table to see if the key exists */ ktp = &keytab[0]; found = FALSE; while (ktp->k_fp != NULL) { if (ktp->k_code == c) { found = TRUE; break; } ++ktp; } /* if it isn't bound, bitch */ if (!found) return FALSE; /* save the pointer and scan to the end of the table */ sktp = ktp; while (ktp->k_fp != NULL) ++ktp; --ktp; /* backup to the last legit entry */ /* copy the last entry to the current one */ sktp->k_code = ktp->k_code; sktp->k_fp = ktp->k_fp; /* null out the last one */ ktp->k_code = 0; ktp->k_fp = NULL; return TRUE; } /* describe bindings * bring up a fake buffer and list the key bindings * into it with view mode */ int desbind(int f, int n) #if APROP { buildlist(TRUE, ""); return TRUE; } int apro(int f, int n) { /* Apropos (List functions that match a substring) */ char mstring[NSTRING]; /* string to match cmd names to */ int status; /* status return */ status = mlreply("Apropos string: ", mstring, NSTRING - 1); if (status != TRUE) return status; return buildlist(FALSE, mstring); } /* * build a binding list (limited or full) * * int type; true = full list, false = partial list * char *mstring; match string if a partial list */ int buildlist(int type, char *mstring) #endif { struct window *wp; /* scanning pointer to windows */ struct key_tab *ktp; /* pointer into the command table */ struct name_bind *nptr; /* pointer into the name binding table */ struct buffer *bp; /* buffer to put binding list into */ int cpos; /* current position to use in outseq */ char outseq[80]; /* output buffer for keystroke sequence */ /* split the current window to make room for the binding list */ if (splitwind(FALSE, 1) == FALSE) return FALSE; /* and get a buffer for it */ bp = bfind("*Binding list*", TRUE, 0); if (bp == NULL || bclear(bp) == FALSE) { mlwrite("Can not display binding list"); return FALSE; } /* let us know this is in progress */ mlwrite("(Building binding list)"); /* disconect the current buffer */ if (--curbp->b_nwnd == 0) { /* Last use. */ curbp->b_dotp = curwp->w_dotp; curbp->b_doto = curwp->w_doto; curbp->b_markp = curwp->w_markp; curbp->b_marko = curwp->w_marko; } /* connect the current window to this buffer */ curbp = bp; /* make this buffer current in current window */ bp->b_mode = 0; /* no modes active in binding list */ bp->b_nwnd++; /* mark us as more in use */ wp = curwp; wp->w_bufp = bp; wp->w_linep = bp->b_linep; wp->w_flag = WFHARD | WFFORCE; wp->w_dotp = bp->b_dotp; wp->w_doto = bp->b_doto; wp->w_markp = NULL; wp->w_marko = 0; /* build the contents of this window, inserting it line by line */ nptr = &names[0]; while (nptr->n_func != NULL) { /* add in the command name */ strcpy(outseq, nptr->n_name); cpos = strlen(outseq); #if APROP /* if we are executing an apropos command..... */ if (type == FALSE && /* and current string doesn't include the search string */ strinc(outseq, mstring) == FALSE) goto fail; #endif /* search down any keys bound to this */ ktp = &keytab[0]; while (ktp->k_fp != NULL) { if (ktp->k_fp == nptr->n_func) { /* padd out some spaces */ while (cpos < 28) outseq[cpos++] = ' '; /* add in the command sequence */ cmdstr(ktp->k_code, &outseq[cpos]); strcat(outseq, "\n"); /* and add it as a line into the buffer */ if (linstr(outseq) != TRUE) return FALSE; cpos = 0; /* and clear the line */ } ++ktp; } /* if no key was bound, we need to dump it anyway */ if (cpos > 0) { outseq[cpos++] = '\n'; outseq[cpos] = 0; if (linstr(outseq) != TRUE) return FALSE; } fail: /* and on to the next name */ ++nptr; } curwp->w_bufp->b_mode |= MDVIEW; /* put this buffer view mode */ curbp->b_flag &= ~BFCHG; /* don't flag this as a change */ wp->w_dotp = lforw(bp->b_linep); /* back to the beginning */ wp->w_doto = 0; wp = wheadp; /* and update ALL mode lines */ while (wp != NULL) { wp->w_flag |= WFMODE; wp = wp->w_wndp; } mlwrite(""); /* clear the mode line */ return TRUE; } #if APROP /* * does source include sub? * * char *source; string to search in * char *sub; substring to look for */ int strinc(char *source, char *sub) { char *sp; /* ptr into source */ char *nxtsp; /* next ptr into source */ char *tp; /* ptr into substring */ /* for each character in the source string */ sp = source; while (*sp) { tp = sub; nxtsp = sp; /* is the substring here? */ while (*tp) { if (*nxtsp++ != *tp) break; else tp++; } /* yes, return a success */ if (*tp == 0) return TRUE; /* no, onward */ sp++; } return FALSE; } #endif /* * get a command key sequence from the keyboard * * int mflag; going for a meta sequence? */ unsigned int getckey(int mflag) { unsigned int c; /* character fetched */ char tok[NSTRING]; /* command incoming */ /* check to see if we are executing a command line */ if (clexec) { macarg(tok); /* get the next token */ return stock(tok); } /* or the normal way */ if (mflag) c = get1key(); else c = getcmd(); return c; } /* * execute the startup file * * char *sfname; name of startup file (null if default) */ int startup(char *sfname) { char *fname; /* resulting file name to execute */ /* look up the startup file */ if (*sfname != 0) fname = flook(sfname, TRUE); else fname = flook(pathname[0], TRUE); /* if it isn't around, don't sweat it */ if (fname == NULL) return TRUE; /* otherwise, execute the sucker */ return dofile(fname); } /* * Look up the existance of a file along the normal or PATH * environment variable. Look first in the HOME directory if * asked and possible * * char *fname; base file name to search for * int hflag; Look in the HOME environment variable first? */ char *flook(char *fname, int hflag) { char *home; /* path to home directory */ char *path; /* environmental PATH variable */ char *sp; /* pointer into path spec */ int i; /* index */ static char fspec[NSTRING]; /* full path spec to search */ #if ENVFUNC if (hflag) { home = getenv("HOME"); if (home != NULL) { /* build home dir file spec */ strcpy(fspec, home); strcat(fspec, "/"); strcat(fspec, fname); /* and try it out */ if (ffropen(fspec) == FIOSUC) { ffclose(); return fspec; } } } #endif /* always try the current directory first */ if (ffropen(fname) == FIOSUC) { ffclose(); return fname; } #if ENVFUNC /* get the PATH variable */ path = getenv("PATH"); if (path != NULL) while (*path) { /* build next possible file spec */ sp = fspec; while (*path && (*path != PATHCHR)) *sp++ = *path++; /* add a terminating dir separator if we need it */ if (sp != fspec) *sp++ = '/'; *sp = 0; strcat(fspec, fname); /* and try it out */ if (ffropen(fspec) == FIOSUC) { ffclose(); return fspec; } if (*path == PATHCHR) ++path; } #endif /* look it up via the old table method */ for (i = 2; i < ARRAY_SIZE(pathname); i++) { strcpy(fspec, pathname[i]); strcat(fspec, fname); /* and try it out */ if (ffropen(fspec) == FIOSUC) { ffclose(); return fspec; } } return NULL; /* no such luck */ } /* * change a key command to a string we can print out * * int c; sequence to translate * char *seq; destination string for sequence */ void cmdstr(int c, char *seq) { char *ptr; /* pointer into current position in sequence */ ptr = seq; /* apply meta sequence if needed */ if (c & META) { *ptr++ = 'M'; *ptr++ = '-'; } /* apply ^X sequence if needed */ if (c & CTLX) { *ptr++ = '^'; *ptr++ = 'X'; } /* apply SPEC sequence if needed */ if (c & SPEC) { *ptr++ = 'F'; *ptr++ = 'N'; } /* apply control sequence if needed */ if (c & CONTROL) { *ptr++ = '^'; } /* and output the final sequence */ *ptr++ = c & 255; /* strip the prefixes */ *ptr = 0; /* terminate the string */ } /* * This function looks a key binding up in the binding table * * int c; key to find what is bound to it */ int (*getbind(int c))(int, int) { struct key_tab *ktp; ktp = &keytab[0]; /* Look in key table. */ while (ktp->k_fp != NULL) { if (ktp->k_code == c) return ktp->k_fp; ++ktp; } /* no such binding */ return NULL; } /* * getfname: * This function takes a ptr to function and gets the name * associated with it. */ char *getfname(fn_t func) { struct name_bind *nptr; /* pointer into the name binding table */ /* skim through the table, looking for a match */ nptr = &names[0]; while (nptr->n_func != NULL) { if (nptr->n_func == func) return nptr->n_name; ++nptr; } return NULL; } /* * match fname to a function in the names table * and return any match or NULL if none * * char *fname; name to attempt to match */ int (*fncmatch(char *fname)) (int, int) { struct name_bind *ffp; /* pointer to entry in name binding table */ /* scan through the table, returning any match */ ffp = &names[0]; while (ffp->n_func != NULL) { if (strcmp(fname, ffp->n_name) == 0) return ffp->n_func; ++ffp; } return NULL; } /* * stock: * String key name TO Command Key * * char *keyname; name of key to translate to Command key form */ unsigned int stock(char *keyname) { unsigned int c; /* key sequence to return */ /* parse it up */ c = 0; /* first, the META prefix */ if (*keyname == 'M' && *(keyname + 1) == '-') { c = META; keyname += 2; } /* next the function prefix */ if (*keyname == 'F' && *(keyname + 1) == 'N') { c |= SPEC; keyname += 2; } /* control-x as well... (but not with FN) */ if (*keyname == '^' && *(keyname + 1) == 'X' && !(c & SPEC)) { c |= CTLX; keyname += 2; } /* a control char? */ if (*keyname == '^' && *(keyname + 1) != 0) { c |= CONTROL; ++keyname; } if (*keyname < 32) { c |= CONTROL; *keyname += 'A'; } /* make sure we are not lower case (not with function keys) */ if (*keyname >= 'a' && *keyname <= 'z' && !(c & SPEC)) *keyname -= 32; /* the final sequence... */ c |= *keyname; return c; } /* * string key name to binding name.... * * char *skey; name of keey to get binding for */ char *transbind(char *skey) { char *bindname; bindname = getfname(getbind(stock(skey))); if (bindname == NULL) bindname = "ERROR"; return bindname; }
uemacs-master
bind.c
/* region.c * * The routines in this file deal with the region, that magic space * between "." and mark. Some functions are commands. Some functions are * just for internal use. * * Modified by Petri Kutvonen */ #include <stdio.h> #include "estruct.h" #include "edef.h" #include "efunc.h" #include "line.h" /* * Kill the region. Ask "getregion" * to figure out the bounds of the region. * Move "." to the start, and kill the characters. * Bound to "C-W". */ int killregion(int f, int n) { int s; struct region region; if (curbp->b_mode & MDVIEW) /* don't allow this command if */ return rdonly(); /* we are in read only mode */ if ((s = getregion(&region)) != TRUE) return s; if ((lastflag & CFKILL) == 0) /* This is a kill type */ kdelete(); /* command, so do magic */ thisflag |= CFKILL; /* kill buffer stuff. */ curwp->w_dotp = region.r_linep; curwp->w_doto = region.r_offset; return ldelete(region.r_size, TRUE); } /* * Copy all of the characters in the * region to the kill buffer. Don't move dot * at all. This is a bit like a kill region followed * by a yank. Bound to "M-W". */ int copyregion(int f, int n) { struct line *linep; int loffs; int s; struct region region; if ((s = getregion(&region)) != TRUE) return s; if ((lastflag & CFKILL) == 0) /* Kill type command. */ kdelete(); thisflag |= CFKILL; linep = region.r_linep; /* Current line. */ loffs = region.r_offset; /* Current offset. */ while (region.r_size--) { if (loffs == llength(linep)) { /* End of line. */ if ((s = kinsert('\n')) != TRUE) return s; linep = lforw(linep); loffs = 0; } else { /* Middle of line. */ if ((s = kinsert(lgetc(linep, loffs))) != TRUE) return s; ++loffs; } } mlwrite("(region copied)"); return TRUE; } /* * Lower case region. Zap all of the upper * case characters in the region to lower case. Use * the region code to set the limits. Scan the buffer, * doing the changes. Call "lchange" to ensure that * redisplay is done in all buffers. Bound to * "C-X C-L". */ int lowerregion(int f, int n) { struct line *linep; int loffs; int c; int s; struct region region; if (curbp->b_mode & MDVIEW) /* don't allow this command if */ return rdonly(); /* we are in read only mode */ if ((s = getregion(&region)) != TRUE) return s; lchange(WFHARD); linep = region.r_linep; loffs = region.r_offset; while (region.r_size--) { if (loffs == llength(linep)) { linep = lforw(linep); loffs = 0; } else { c = lgetc(linep, loffs); if (c >= 'A' && c <= 'Z') lputc(linep, loffs, c + 'a' - 'A'); ++loffs; } } return TRUE; } /* * Upper case region. Zap all of the lower * case characters in the region to upper case. Use * the region code to set the limits. Scan the buffer, * doing the changes. Call "lchange" to ensure that * redisplay is done in all buffers. Bound to * "C-X C-L". */ int upperregion(int f, int n) { struct line *linep; int loffs; int c; int s; struct region region; if (curbp->b_mode & MDVIEW) /* don't allow this command if */ return rdonly(); /* we are in read only mode */ if ((s = getregion(&region)) != TRUE) return s; lchange(WFHARD); linep = region.r_linep; loffs = region.r_offset; while (region.r_size--) { if (loffs == llength(linep)) { linep = lforw(linep); loffs = 0; } else { c = lgetc(linep, loffs); if (c >= 'a' && c <= 'z') lputc(linep, loffs, c - 'a' + 'A'); ++loffs; } } return TRUE; } /* * This routine figures out the * bounds of the region in the current window, and * fills in the fields of the "struct region" structure pointed * to by "rp". Because the dot and mark are usually very * close together, we scan outward from dot looking for * mark. This should save time. Return a standard code. * Callers of this routine should be prepared to get * an "ABORT" status; we might make this have the * conform thing later. */ int getregion(struct region *rp) { struct line *flp; struct line *blp; long fsize; long bsize; if (curwp->w_markp == NULL) { mlwrite("No mark set in this window"); return FALSE; } if (curwp->w_dotp == curwp->w_markp) { rp->r_linep = curwp->w_dotp; if (curwp->w_doto < curwp->w_marko) { rp->r_offset = curwp->w_doto; rp->r_size = (long) (curwp->w_marko - curwp->w_doto); } else { rp->r_offset = curwp->w_marko; rp->r_size = (long) (curwp->w_doto - curwp->w_marko); } return TRUE; } blp = curwp->w_dotp; bsize = (long) curwp->w_doto; flp = curwp->w_dotp; fsize = (long) (llength(flp) - curwp->w_doto + 1); while (flp != curbp->b_linep || lback(blp) != curbp->b_linep) { if (flp != curbp->b_linep) { flp = lforw(flp); if (flp == curwp->w_markp) { rp->r_linep = curwp->w_dotp; rp->r_offset = curwp->w_doto; rp->r_size = fsize + curwp->w_marko; return TRUE; } fsize += llength(flp) + 1; } if (lback(blp) != curbp->b_linep) { blp = lback(blp); bsize += llength(blp) + 1; if (blp == curwp->w_markp) { rp->r_linep = blp; rp->r_offset = curwp->w_marko; rp->r_size = bsize - curwp->w_marko; return TRUE; } } } mlwrite("Bug: lost mark"); return FALSE; }
uemacs-master
region.c
/* line.c * * The functions in this file are a general set of line management utilities. * They are the only routines that touch the text. They also touch the buffer * and window structures, to make sure that the necessary updating gets done. * There are routines in this file that handle the kill buffer too. It isn't * here for any good reason. * * Note that this code only updates the dot and mark values in the window list. * Since all the code acts on the current window, the buffer that we are * editing must be being displayed, which means that "b_nwnd" is non zero, * which means that the dot and mark values in the buffer headers are nonsense. * */ #include "line.h" #include <stdio.h> #include "estruct.h" #include "edef.h" #include "efunc.h" #include "utf8.h" #define BLOCK_SIZE 16 /* Line block chunk size. */ /* * This routine allocates a block of memory large enough to hold a struct line * containing "used" characters. The block is always rounded up a bit. Return * a pointer to the new block, or NULL if there isn't any memory left. Print a * message in the message line if no space. */ struct line *lalloc(int used) { struct line *lp; int size; size = (used + BLOCK_SIZE - 1) & ~(BLOCK_SIZE - 1); if (size == 0) /* Assume that is an empty. */ size = BLOCK_SIZE; /* Line is for type-in. */ if ((lp = (struct line *)malloc(sizeof(struct line) + size)) == NULL) { mlwrite("(OUT OF MEMORY)"); return NULL; } lp->l_size = size; lp->l_used = used; return lp; } /* * Delete line "lp". Fix all of the links that might point at it (they are * moved to offset 0 of the next line. Unlink the line from whatever buffer it * might be in. Release the memory. The buffers are updated too; the magic * conditions described in the above comments don't hold here. */ void lfree(struct line *lp) { struct buffer *bp; struct window *wp; wp = wheadp; while (wp != NULL) { if (wp->w_linep == lp) wp->w_linep = lp->l_fp; if (wp->w_dotp == lp) { wp->w_dotp = lp->l_fp; wp->w_doto = 0; } if (wp->w_markp == lp) { wp->w_markp = lp->l_fp; wp->w_marko = 0; } wp = wp->w_wndp; } bp = bheadp; while (bp != NULL) { if (bp->b_nwnd == 0) { if (bp->b_dotp == lp) { bp->b_dotp = lp->l_fp; bp->b_doto = 0; } if (bp->b_markp == lp) { bp->b_markp = lp->l_fp; bp->b_marko = 0; } } bp = bp->b_bufp; } lp->l_bp->l_fp = lp->l_fp; lp->l_fp->l_bp = lp->l_bp; free((char *) lp); } /* * This routine gets called when a character is changed in place in the current * buffer. It updates all of the required flags in the buffer and window * system. The flag used is passed as an argument; if the buffer is being * displayed in more than 1 window we change EDIT t HARD. Set MODE if the * mode line needs to be updated (the "*" has to be set). */ void lchange(int flag) { struct window *wp; if (curbp->b_nwnd != 1) /* Ensure hard. */ flag = WFHARD; if ((curbp->b_flag & BFCHG) == 0) { /* First change, so */ flag |= WFMODE; /* update mode lines. */ curbp->b_flag |= BFCHG; } wp = wheadp; while (wp != NULL) { if (wp->w_bufp == curbp) wp->w_flag |= flag; wp = wp->w_wndp; } } /* * insert spaces forward into text * * int f, n; default flag and numeric argument */ int insspace(int f, int n) { linsert(n, ' '); backchar(f, n); return TRUE; } /* * linstr -- Insert a string at the current point */ int linstr(char *instr) { int status = TRUE; char tmpc; if (instr != NULL) while ((tmpc = *instr) && status == TRUE) { status = (tmpc == '\n' ? lnewline() : linsert(1, tmpc)); /* Insertion error? */ if (status != TRUE) { mlwrite("%%Out of memory while inserting"); break; } instr++; } return status; } /* * Insert "n" copies of the character "c" at the current location of dot. In * the easy case all that happens is the text is stored in the line. In the * hard case, the line has to be reallocated. When the window list is updated, * take special care; I screwed it up once. You always update dot in the * current window. You update mark, and a dot in another window, if it is * greater than the place where you did the insert. Return TRUE if all is * well, and FALSE on errors. */ static int linsert_byte(int n, int c) { char *cp1; char *cp2; struct line *lp1; struct line *lp2; struct line *lp3; int doto; int i; struct window *wp; if (curbp->b_mode & MDVIEW) /* don't allow this command if */ return rdonly(); /* we are in read only mode */ lchange(WFEDIT); lp1 = curwp->w_dotp; /* Current line */ if (lp1 == curbp->b_linep) { /* At the end: special */ if (curwp->w_doto != 0) { mlwrite("bug: linsert"); return FALSE; } if ((lp2 = lalloc(n)) == NULL) /* Allocate new line */ return FALSE; lp3 = lp1->l_bp; /* Previous line */ lp3->l_fp = lp2; /* Link in */ lp2->l_fp = lp1; lp1->l_bp = lp2; lp2->l_bp = lp3; for (i = 0; i < n; ++i) lp2->l_text[i] = c; curwp->w_dotp = lp2; curwp->w_doto = n; return TRUE; } doto = curwp->w_doto; /* Save for later. */ if (lp1->l_used + n > lp1->l_size) { /* Hard: reallocate */ if ((lp2 = lalloc(lp1->l_used + n)) == NULL) return FALSE; cp1 = &lp1->l_text[0]; cp2 = &lp2->l_text[0]; while (cp1 != &lp1->l_text[doto]) *cp2++ = *cp1++; cp2 += n; while (cp1 != &lp1->l_text[lp1->l_used]) *cp2++ = *cp1++; lp1->l_bp->l_fp = lp2; lp2->l_fp = lp1->l_fp; lp1->l_fp->l_bp = lp2; lp2->l_bp = lp1->l_bp; free((char *) lp1); } else { /* Easy: in place */ lp2 = lp1; /* Pretend new line */ lp2->l_used += n; cp2 = &lp1->l_text[lp1->l_used]; cp1 = cp2 - n; while (cp1 != &lp1->l_text[doto]) *--cp2 = *--cp1; } for (i = 0; i < n; ++i) /* Add the characters */ lp2->l_text[doto + i] = c; wp = wheadp; /* Update windows */ while (wp != NULL) { if (wp->w_linep == lp1) wp->w_linep = lp2; if (wp->w_dotp == lp1) { wp->w_dotp = lp2; if (wp == curwp || wp->w_doto > doto) wp->w_doto += n; } if (wp->w_markp == lp1) { wp->w_markp = lp2; if (wp->w_marko > doto) wp->w_marko += n; } wp = wp->w_wndp; } return TRUE; } int linsert(int n, int c) { char utf8[6]; int bytes = unicode_to_utf8(c, utf8), i; if (bytes == 1) return linsert_byte(n, (unsigned char) utf8[0]); for (i = 0; i < n; i++) { int j; for (j = 0; j < bytes; j++) { unsigned char c = utf8[j]; if (!linsert_byte(1, c)) return FALSE; } } return TRUE; } /* * Overwrite a character into the current line at the current position * * int c; character to overwrite on current position */ int lowrite(int c) { if (curwp->w_doto < curwp->w_dotp->l_used && (lgetc(curwp->w_dotp, curwp->w_doto) != '\t' || ((curwp->w_doto) & tabmask) == tabmask)) ldelchar(1, FALSE); return linsert(1, c); } /* * lover -- Overwrite a string at the current point */ int lover(char *ostr) { int status = TRUE; char tmpc; if (ostr != NULL) while ((tmpc = *ostr) && status == TRUE) { status = (tmpc == '\n' ? lnewline() : lowrite(tmpc)); /* Insertion error? */ if (status != TRUE) { mlwrite ("%%Out of memory while overwriting"); break; } ostr++; } return status; } /* * Insert a newline into the buffer at the current location of dot in the * current window. The funny ass-backwards way it does things is not a botch; * it just makes the last line in the file not a special case. Return TRUE if * everything works out and FALSE on error (memory allocation failure). The * update of dot and mark is a bit easier then in the above case, because the * split forces more updating. */ int lnewline(void) { char *cp1; char *cp2; struct line *lp1; struct line *lp2; int doto; struct window *wp; if (curbp->b_mode & MDVIEW) /* don't allow this command if */ return rdonly(); /* we are in read only mode */ #if SCROLLCODE lchange(WFHARD | WFINS); #else lchange(WFHARD); #endif lp1 = curwp->w_dotp; /* Get the address and */ doto = curwp->w_doto; /* offset of "." */ if ((lp2 = lalloc(doto)) == NULL) /* New first half line */ return FALSE; cp1 = &lp1->l_text[0]; /* Shuffle text around */ cp2 = &lp2->l_text[0]; while (cp1 != &lp1->l_text[doto]) *cp2++ = *cp1++; cp2 = &lp1->l_text[0]; while (cp1 != &lp1->l_text[lp1->l_used]) *cp2++ = *cp1++; lp1->l_used -= doto; lp2->l_bp = lp1->l_bp; lp1->l_bp = lp2; lp2->l_bp->l_fp = lp2; lp2->l_fp = lp1; wp = wheadp; /* Windows */ while (wp != NULL) { if (wp->w_linep == lp1) wp->w_linep = lp2; if (wp->w_dotp == lp1) { if (wp->w_doto < doto) wp->w_dotp = lp2; else wp->w_doto -= doto; } if (wp->w_markp == lp1) { if (wp->w_marko < doto) wp->w_markp = lp2; else wp->w_marko -= doto; } wp = wp->w_wndp; } return TRUE; } int lgetchar(unicode_t *c) { int len = llength(curwp->w_dotp); char *buf = curwp->w_dotp->l_text; return utf8_to_unicode(buf, curwp->w_doto, len, c); } /* * ldelete() really fundamentally works on bytes, not characters. * It is used for things like "scan 5 words forwards, and remove * the bytes we scanned". * * If you want to delete characters, use ldelchar(). */ int ldelchar(long n, int kflag) { while (n-- > 0) { unicode_t c; if (!ldelete(lgetchar(&c), kflag)) return FALSE; } return TRUE; } /* * This function deletes "n" bytes, starting at dot. It understands how do deal * with end of lines, etc. It returns TRUE if all of the characters were * deleted, and FALSE if they were not (because dot ran into the end of the * buffer. The "kflag" is TRUE if the text should be put in the kill buffer. * * long n; # of chars to delete * int kflag; put killed text in kill buffer flag */ int ldelete(long n, int kflag) { char *cp1; char *cp2; struct line *dotp; int doto; int chunk; struct window *wp; if (curbp->b_mode & MDVIEW) /* don't allow this command if */ return rdonly(); /* we are in read only mode */ while (n != 0) { dotp = curwp->w_dotp; doto = curwp->w_doto; if (dotp == curbp->b_linep) /* Hit end of buffer. */ return FALSE; chunk = dotp->l_used - doto; /* Size of chunk. */ if (chunk > n) chunk = n; if (chunk == 0) { /* End of line, merge. */ #if SCROLLCODE lchange(WFHARD | WFKILLS); #else lchange(WFHARD); #endif if (ldelnewline() == FALSE || (kflag != FALSE && kinsert('\n') == FALSE)) return FALSE; --n; continue; } lchange(WFEDIT); cp1 = &dotp->l_text[doto]; /* Scrunch text. */ cp2 = cp1 + chunk; if (kflag != FALSE) { /* Kill? */ while (cp1 != cp2) { if (kinsert(*cp1) == FALSE) return FALSE; ++cp1; } cp1 = &dotp->l_text[doto]; } while (cp2 != &dotp->l_text[dotp->l_used]) *cp1++ = *cp2++; dotp->l_used -= chunk; wp = wheadp; /* Fix windows */ while (wp != NULL) { if (wp->w_dotp == dotp && wp->w_doto >= doto) { wp->w_doto -= chunk; if (wp->w_doto < doto) wp->w_doto = doto; } if (wp->w_markp == dotp && wp->w_marko >= doto) { wp->w_marko -= chunk; if (wp->w_marko < doto) wp->w_marko = doto; } wp = wp->w_wndp; } n -= chunk; } return TRUE; } /* * getctext: grab and return a string with the text of * the current line */ char *getctext(void) { struct line *lp; /* line to copy */ int size; /* length of line to return */ char *sp; /* string pointer into line */ char *dp; /* string pointer into returned line */ static char rline[NSTRING]; /* line to return */ /* find the contents of the current line and its length */ lp = curwp->w_dotp; sp = lp->l_text; size = lp->l_used; if (size >= NSTRING) size = NSTRING - 1; /* copy it across */ dp = rline; while (size--) *dp++ = *sp++; *dp = 0; return rline; } /* * putctext: * replace the current line with the passed in text * * char *iline; contents of new line */ int putctext(char *iline) { int status; /* delete the current line */ curwp->w_doto = 0; /* starting at the beginning of the line */ if ((status = killtext(TRUE, 1)) != TRUE) return status; /* insert the new line */ if ((status = linstr(iline)) != TRUE) return status; status = lnewline(); backline(TRUE, 1); return status; } /* * Delete a newline. Join the current line with the next line. If the next line * is the magic header line always return TRUE; merging the last line with the * header line can be thought of as always being a successful operation, even * if nothing is done, and this makes the kill buffer work "right". Easy cases * can be done by shuffling data around. Hard cases require that lines be moved * about in memory. Return FALSE on error and TRUE if all looks ok. Called by * "ldelete" only. */ int ldelnewline(void) { char *cp1; char *cp2; struct line *lp1; struct line *lp2; struct line *lp3; struct window *wp; if (curbp->b_mode & MDVIEW) /* don't allow this command if */ return rdonly(); /* we are in read only mode */ lp1 = curwp->w_dotp; lp2 = lp1->l_fp; if (lp2 == curbp->b_linep) { /* At the buffer end. */ if (lp1->l_used == 0) /* Blank line. */ lfree(lp1); return TRUE; } if (lp2->l_used <= lp1->l_size - lp1->l_used) { cp1 = &lp1->l_text[lp1->l_used]; cp2 = &lp2->l_text[0]; while (cp2 != &lp2->l_text[lp2->l_used]) *cp1++ = *cp2++; wp = wheadp; while (wp != NULL) { if (wp->w_linep == lp2) wp->w_linep = lp1; if (wp->w_dotp == lp2) { wp->w_dotp = lp1; wp->w_doto += lp1->l_used; } if (wp->w_markp == lp2) { wp->w_markp = lp1; wp->w_marko += lp1->l_used; } wp = wp->w_wndp; } lp1->l_used += lp2->l_used; lp1->l_fp = lp2->l_fp; lp2->l_fp->l_bp = lp1; free((char *) lp2); return TRUE; } if ((lp3 = lalloc(lp1->l_used + lp2->l_used)) == NULL) return FALSE; cp1 = &lp1->l_text[0]; cp2 = &lp3->l_text[0]; while (cp1 != &lp1->l_text[lp1->l_used]) *cp2++ = *cp1++; cp1 = &lp2->l_text[0]; while (cp1 != &lp2->l_text[lp2->l_used]) *cp2++ = *cp1++; lp1->l_bp->l_fp = lp3; lp3->l_fp = lp2->l_fp; lp2->l_fp->l_bp = lp3; lp3->l_bp = lp1->l_bp; wp = wheadp; while (wp != NULL) { if (wp->w_linep == lp1 || wp->w_linep == lp2) wp->w_linep = lp3; if (wp->w_dotp == lp1) wp->w_dotp = lp3; else if (wp->w_dotp == lp2) { wp->w_dotp = lp3; wp->w_doto += lp1->l_used; } if (wp->w_markp == lp1) wp->w_markp = lp3; else if (wp->w_markp == lp2) { wp->w_markp = lp3; wp->w_marko += lp1->l_used; } wp = wp->w_wndp; } free((char *) lp1); free((char *) lp2); return TRUE; } /* * Delete all of the text saved in the kill buffer. Called by commands when a * new kill context is being created. The kill buffer array is released, just * in case the buffer has grown to immense size. No errors. */ void kdelete(void) { struct kill *kp; /* ptr to scan kill buffer chunk list */ if (kbufh != NULL) { /* first, delete all the chunks */ kbufp = kbufh; while (kbufp != NULL) { kp = kbufp->d_next; free(kbufp); kbufp = kp; } /* and reset all the kill buffer pointers */ kbufh = kbufp = NULL; kused = KBLOCK; } } /* * Insert a character to the kill buffer, allocating new chunks as needed. * Return TRUE if all is well, and FALSE on errors. * * int c; character to insert in the kill buffer */ int kinsert(int c) { struct kill *nchunk; /* ptr to newly malloced chunk */ /* check to see if we need a new chunk */ if (kused >= KBLOCK) { if ((nchunk = (struct kill *)malloc(sizeof(struct kill))) == NULL) return FALSE; if (kbufh == NULL) /* set head ptr if first time */ kbufh = nchunk; if (kbufp != NULL) /* point the current to this new one */ kbufp->d_next = nchunk; kbufp = nchunk; kbufp->d_next = NULL; kused = 0; } /* and now insert the character */ kbufp->d_chunk[kused++] = c; return TRUE; } /* * Yank text back from the kill buffer. This is really easy. All of the work * is done by the standard insert routines. All you do is run the loop, and * check for errors. Bound to "C-Y". */ int yank(int f, int n) { int c; int i; char *sp; /* pointer into string to insert */ struct kill *kp; /* pointer into kill buffer */ if (curbp->b_mode & MDVIEW) /* don't allow this command if */ return rdonly(); /* we are in read only mode */ if (n < 0) return FALSE; /* make sure there is something to yank */ if (kbufh == NULL) return TRUE; /* not an error, just nothing */ /* for each time.... */ while (n--) { kp = kbufh; while (kp != NULL) { if (kp->d_next == NULL) i = kused; else i = KBLOCK; sp = kp->d_chunk; while (i--) { if ((c = *sp++) == '\n') { if (lnewline() == FALSE) return FALSE; } else { if (linsert_byte(1, c) == FALSE) return FALSE; } } kp = kp->d_next; } } return TRUE; }
uemacs-master
line.c
/* random.c * * This file contains the command processing functions for a number of * random commands. There is no functional grouping here, for sure. * * Modified by Petri Kutvonen */ #include <stdio.h> #include "estruct.h" #include "edef.h" #include "efunc.h" #include "line.h" int tabsize; /* Tab size (0: use real tabs) */ /* * Set fill column to n. */ int setfillcol(int f, int n) { fillcol = n; mlwrite("(Fill column is %d)", n); return TRUE; } /* * Display the current position of the cursor, in origin 1 X-Y coordinates, * the character that is under the cursor (in hex), and the fraction of the * text that is before the cursor. The displayed column is not the current * column, but the column that would be used on an infinite width display. * Normally this is bound to "C-X =". */ int showcpos(int f, int n) { struct line *lp; /* current line */ long numchars; /* # of chars in file */ int numlines; /* # of lines in file */ long predchars; /* # chars preceding point */ int predlines; /* # lines preceding point */ int curchar; /* character under cursor */ int ratio; int col; int savepos; /* temp save for current offset */ int ecol; /* column pos/end of current line */ /* starting at the beginning of the buffer */ lp = lforw(curbp->b_linep); /* start counting chars and lines */ numchars = 0; numlines = 0; predchars = 0; predlines = 0; curchar = 0; while (lp != curbp->b_linep) { /* if we are on the current line, record it */ if (lp == curwp->w_dotp) { predlines = numlines; predchars = numchars + curwp->w_doto; if ((curwp->w_doto) == llength(lp)) curchar = '\n'; else curchar = lgetc(lp, curwp->w_doto); } /* on to the next line */ ++numlines; numchars += llength(lp) + 1; lp = lforw(lp); } /* if at end of file, record it */ if (curwp->w_dotp == curbp->b_linep) { predlines = numlines; predchars = numchars; #if PKCODE curchar = 0; #endif } /* Get real column and end-of-line column. */ col = getccol(FALSE); savepos = curwp->w_doto; curwp->w_doto = llength(curwp->w_dotp); ecol = getccol(FALSE); curwp->w_doto = savepos; ratio = 0; /* Ratio before dot. */ if (numchars != 0) ratio = (100L * predchars) / numchars; /* summarize and report the info */ mlwrite("Line %d/%d Col %d/%d Char %D/%D (%d%%) char = 0x%x", predlines + 1, numlines + 1, col, ecol, predchars, numchars, ratio, curchar); return TRUE; } int getcline(void) { /* get the current line number */ struct line *lp; /* current line */ int numlines; /* # of lines before point */ /* starting at the beginning of the buffer */ lp = lforw(curbp->b_linep); /* start counting lines */ numlines = 0; while (lp != curbp->b_linep) { /* if we are on the current line, record it */ if (lp == curwp->w_dotp) break; ++numlines; lp = lforw(lp); } /* and return the resulting count */ return numlines + 1; } /* * Return current column. Stop at first non-blank given TRUE argument. */ int getccol(int bflg) { int i, col; struct line *dlp = curwp->w_dotp; int byte_offset = curwp->w_doto; int len = llength(dlp); col = i = 0; while (i < byte_offset) { unicode_t c; i += utf8_to_unicode(dlp->l_text, i, len, &c); if (c != ' ' && c != '\t' && bflg) break; if (c == '\t') col |= tabmask; else if (c < 0x20 || c == 0x7F) ++col; else if (c >= 0xc0 && c <= 0xa0) col += 2; ++col; } return col; } /* * Set current column. * * int pos; position to set cursor */ int setccol(int pos) { int c; /* character being scanned */ int i; /* index into current line */ int col; /* current cursor column */ int llen; /* length of line in bytes */ col = 0; llen = llength(curwp->w_dotp); /* scan the line until we are at or past the target column */ for (i = 0; i < llen; ++i) { /* upon reaching the target, drop out */ if (col >= pos) break; /* advance one character */ c = lgetc(curwp->w_dotp, i); if (c == '\t') col |= tabmask; else if (c < 0x20 || c == 0x7F) ++col; ++col; } /* set us at the new position */ curwp->w_doto = i; /* and tell weather we made it */ return col >= pos; } /* * Twiddle the two characters on either side of dot. If dot is at the end of * the line twiddle the two characters before it. Return with an error if dot * is at the beginning of line; it seems to be a bit pointless to make this * work. This fixes up a very common typo with a single stroke. Normally bound * to "C-T". This always works within a line, so "WFEDIT" is good enough. */ int twiddle(int f, int n) { struct line *dotp; int doto; int cl; int cr; if (curbp->b_mode & MDVIEW) /* don't allow this command if */ return rdonly(); /* we are in read only mode */ dotp = curwp->w_dotp; doto = curwp->w_doto; if (doto == llength(dotp) && --doto < 0) return FALSE; cr = lgetc(dotp, doto); if (--doto < 0) return FALSE; cl = lgetc(dotp, doto); lputc(dotp, doto + 0, cr); lputc(dotp, doto + 1, cl); lchange(WFEDIT); return TRUE; } /* * Quote the next character, and insert it into the buffer. All the characters * are taken literally, with the exception of the newline, which always has * its line splitting meaning. The character is always read, even if it is * inserted 0 times, for regularity. Bound to "C-Q" */ int quote(int f, int n) { int s; int c; if (curbp->b_mode & MDVIEW) /* don't allow this command if */ return rdonly(); /* we are in read only mode */ c = tgetc(); if (n < 0) return FALSE; if (n == 0) return TRUE; if (c == '\n') { do { s = lnewline(); } while (s == TRUE && --n); return s; } return linsert(n, c); } /* * Set tab size if given non-default argument (n <> 1). Otherwise, insert a * tab into file. If given argument, n, of zero, change to true tabs. * If n > 1, simulate tab stop every n-characters using spaces. This has to be * done in this slightly funny way because the tab (in ASCII) has been turned * into "C-I" (in 10 bit code) already. Bound to "C-I". */ int insert_tab(int f, int n) { if (n < 0) return FALSE; if (n == 0 || n > 1) { tabsize = n; return TRUE; } if (!tabsize) return linsert(1, '\t'); return linsert(tabsize - (getccol(FALSE) % tabsize), ' '); } #if AEDIT /* * change tabs to spaces * * int f, n; default flag and numeric repeat count */ int detab(int f, int n) { int inc; /* increment to next line [sgn(n)] */ if (curbp->b_mode & MDVIEW) /* don't allow this command if */ return rdonly(); /* we are in read only mode */ if (f == FALSE) n = 1; /* loop thru detabbing n lines */ inc = ((n > 0) ? 1 : -1); while (n) { curwp->w_doto = 0; /* start at the beginning */ /* detab the entire current line */ while (curwp->w_doto < llength(curwp->w_dotp)) { /* if we have a tab */ if (lgetc(curwp->w_dotp, curwp->w_doto) == '\t') { ldelchar(1, FALSE); insspace(TRUE, (tabmask + 1) - (curwp->w_doto & tabmask)); } forwchar(FALSE, 1); } /* advance/or back to the next line */ forwline(TRUE, inc); n -= inc; } curwp->w_doto = 0; /* to the begining of the line */ thisflag &= ~CFCPCN; /* flag that this resets the goal column */ lchange(WFEDIT); /* yes, we have made at least an edit */ return TRUE; } /* * change spaces to tabs where posible * * int f, n; default flag and numeric repeat count */ int entab(int f, int n) { int inc; /* increment to next line [sgn(n)] */ int fspace; /* pointer to first space if in a run */ int ccol; /* current cursor column */ char cchar; /* current character */ if (curbp->b_mode & MDVIEW) /* don't allow this command if */ return rdonly(); /* we are in read only mode */ if (f == FALSE) n = 1; /* loop thru entabbing n lines */ inc = ((n > 0) ? 1 : -1); while (n) { curwp->w_doto = 0; /* start at the beginning */ /* entab the entire current line */ fspace = -1; ccol = 0; while (curwp->w_doto < llength(curwp->w_dotp)) { /* see if it is time to compress */ if ((fspace >= 0) && (nextab(fspace) <= ccol)) { if (ccol - fspace < 2) fspace = -1; else { /* there is a bug here dealing with mixed space/tabed lines.......it will get fixed */ backchar(TRUE, ccol - fspace); ldelete((long) (ccol - fspace), FALSE); linsert(1, '\t'); fspace = -1; } } /* get the current character */ cchar = lgetc(curwp->w_dotp, curwp->w_doto); switch (cchar) { case '\t': /* a tab...count em up */ ccol = nextab(ccol); break; case ' ': /* a space...compress? */ if (fspace == -1) fspace = ccol; ccol++; break; default: /* any other char...just count */ ccol++; fspace = -1; break; } forwchar(FALSE, 1); } /* advance/or back to the next line */ forwline(TRUE, inc); n -= inc; } curwp->w_doto = 0; /* to the begining of the line */ thisflag &= ~CFCPCN; /* flag that this resets the goal column */ lchange(WFEDIT); /* yes, we have made at least an edit */ return TRUE; } /* * trim trailing whitespace from the point to eol * * int f, n; default flag and numeric repeat count */ int trim(int f, int n) { struct line *lp; /* current line pointer */ int offset; /* original line offset position */ int length; /* current length */ int inc; /* increment to next line [sgn(n)] */ if (curbp->b_mode & MDVIEW) /* don't allow this command if */ return rdonly(); /* we are in read only mode */ if (f == FALSE) n = 1; /* loop thru trimming n lines */ inc = ((n > 0) ? 1 : -1); while (n) { lp = curwp->w_dotp; /* find current line text */ offset = curwp->w_doto; /* save original offset */ length = lp->l_used; /* find current length */ /* trim the current line */ while (length > offset) { if (lgetc(lp, length - 1) != ' ' && lgetc(lp, length - 1) != '\t') break; length--; } lp->l_used = length; /* advance/or back to the next line */ forwline(TRUE, inc); n -= inc; } lchange(WFEDIT); thisflag &= ~CFCPCN; /* flag that this resets the goal column */ return TRUE; } #endif /* * Open up some blank space. The basic plan is to insert a bunch of newlines, * and then back up over them. Everything is done by the subcommand * procerssors. They even handle the looping. Normally this is bound to "C-O". */ int openline(int f, int n) { int i; int s; if (curbp->b_mode & MDVIEW) /* don't allow this command if */ return rdonly(); /* we are in read only mode */ if (n < 0) return FALSE; if (n == 0) return TRUE; i = n; /* Insert newlines. */ do { s = lnewline(); } while (s == TRUE && --i); if (s == TRUE) /* Then back up overtop */ s = backchar(f, n); /* of them all. */ return s; } /* * Insert a newline. Bound to "C-M". If we are in CMODE, do automatic * indentation as specified. */ int insert_newline(int f, int n) { int s; if (curbp->b_mode & MDVIEW) /* don't allow this command if */ return rdonly(); /* we are in read only mode */ if (n < 0) return FALSE; /* if we are in C mode and this is a default <NL> */ if (n == 1 && (curbp->b_mode & MDCMOD) && curwp->w_dotp != curbp->b_linep) return cinsert(); /* * If a newline was typed, fill column is defined, the argument is non- * negative, wrap mode is enabled, and we are now past fill column, * and we are not read-only, perform word wrap. */ if ((curwp->w_bufp->b_mode & MDWRAP) && fillcol > 0 && getccol(FALSE) > fillcol && (curwp->w_bufp->b_mode & MDVIEW) == FALSE) execute(META | SPEC | 'W', FALSE, 1); /* insert some lines */ while (n--) { if ((s = lnewline()) != TRUE) return s; #if SCROLLCODE curwp->w_flag |= WFINS; #endif } return TRUE; } int cinsert(void) { /* insert a newline and indentation for C */ char *cptr; /* string pointer into text to copy */ int tptr; /* index to scan into line */ int bracef; /* was there a brace at the end of line? */ int i; char ichar[NSTRING]; /* buffer to hold indent of last line */ /* grab a pointer to text to copy indentation from */ cptr = &curwp->w_dotp->l_text[0]; /* check for a brace */ tptr = curwp->w_doto - 1; bracef = (cptr[tptr] == '{'); /* save the indent of the previous line */ i = 0; while ((i < tptr) && (cptr[i] == ' ' || cptr[i] == '\t') && (i < NSTRING - 1)) { ichar[i] = cptr[i]; ++i; } ichar[i] = 0; /* terminate it */ /* put in the newline */ if (lnewline() == FALSE) return FALSE; /* and the saved indentation */ linstr(ichar); /* and one more tab for a brace */ if (bracef) insert_tab(FALSE, 1); #if SCROLLCODE curwp->w_flag |= WFINS; #endif return TRUE; } #if NBRACE /* * insert a brace into the text here...we are in CMODE * * int n; repeat count * int c; brace to insert (always } for now) */ int insbrace(int n, int c) { int ch; /* last character before input */ int oc; /* caractere oppose a c */ int i, count; int target; /* column brace should go after */ struct line *oldlp; int oldoff; /* if we aren't at the beginning of the line... */ if (curwp->w_doto != 0) /* scan to see if all space before this is white space */ for (i = curwp->w_doto - 1; i >= 0; --i) { ch = lgetc(curwp->w_dotp, i); if (ch != ' ' && ch != '\t') return linsert(n, c); } /* chercher le caractere oppose correspondant */ switch (c) { case '}': oc = '{'; break; case ']': oc = '['; break; case ')': oc = '('; break; default: return FALSE; } oldlp = curwp->w_dotp; oldoff = curwp->w_doto; count = 1; backchar(FALSE, 1); while (count > 0) { if (curwp->w_doto == llength(curwp->w_dotp)) ch = '\n'; else ch = lgetc(curwp->w_dotp, curwp->w_doto); if (ch == c) ++count; if (ch == oc) --count; backchar(FALSE, 1); if (boundry(curwp->w_dotp, curwp->w_doto, REVERSE)) break; } if (count != 0) { /* no match */ curwp->w_dotp = oldlp; curwp->w_doto = oldoff; return linsert(n, c); } curwp->w_doto = 0; /* debut de ligne */ /* aller au debut de la ligne apres la tabulation */ while ((ch = lgetc(curwp->w_dotp, curwp->w_doto)) == ' ' || ch == '\t') forwchar(FALSE, 1); /* delete back first */ target = getccol(FALSE); /* c'est l'indent que l'on doit avoir */ curwp->w_dotp = oldlp; curwp->w_doto = oldoff; while (target != getccol(FALSE)) { if (target < getccol(FALSE)) /* on doit detruire des caracteres */ while (getccol(FALSE) > target) backdel(FALSE, 1); else { /* on doit en inserer */ while (target - getccol(FALSE) >= 8) linsert(1, '\t'); linsert(target - getccol(FALSE), ' '); } } /* and insert the required brace(s) */ return linsert(n, c); } #else /* * insert a brace into the text here...we are in CMODE * * int n; repeat count * int c; brace to insert (always { for now) */ int insbrace(int n, int c) { int ch; /* last character before input */ int i; int target; /* column brace should go after */ /* if we are at the beginning of the line, no go */ if (curwp->w_doto == 0) return linsert(n, c); /* scan to see if all space before this is white space */ for (i = curwp->w_doto - 1; i >= 0; --i) { ch = lgetc(curwp->w_dotp, i); if (ch != ' ' && ch != '\t') return linsert(n, c); } /* delete back first */ target = getccol(FALSE); /* calc where we will delete to */ target -= 1; target -= target % (tabsize == 0 ? 8 : tabsize); while (getccol(FALSE) > target) backdel(FALSE, 1); /* and insert the required brace(s) */ return linsert(n, c); } #endif int inspound(void) { /* insert a # into the text here...we are in CMODE */ int ch; /* last character before input */ int i; /* if we are at the beginning of the line, no go */ if (curwp->w_doto == 0) return linsert(1, '#'); /* scan to see if all space before this is white space */ for (i = curwp->w_doto - 1; i >= 0; --i) { ch = lgetc(curwp->w_dotp, i); if (ch != ' ' && ch != '\t') return linsert(1, '#'); } /* delete back first */ while (getccol(FALSE) >= 1) backdel(FALSE, 1); /* and insert the required pound */ return linsert(1, '#'); } /* * Delete blank lines around dot. What this command does depends if dot is * sitting on a blank line. If dot is sitting on a blank line, this command * deletes all the blank lines above and below the current line. If it is * sitting on a non blank line then it deletes all of the blank lines after * the line. Normally this command is bound to "C-X C-O". Any argument is * ignored. */ int deblank(int f, int n) { struct line *lp1; struct line *lp2; long nld; if (curbp->b_mode & MDVIEW) /* don't allow this command if */ return rdonly(); /* we are in read only mode */ lp1 = curwp->w_dotp; while (llength(lp1) == 0 && (lp2 = lback(lp1)) != curbp->b_linep) lp1 = lp2; lp2 = lp1; nld = 0; while ((lp2 = lforw(lp2)) != curbp->b_linep && llength(lp2) == 0) ++nld; if (nld == 0) return TRUE; curwp->w_dotp = lforw(lp1); curwp->w_doto = 0; return ldelete(nld, FALSE); } /* * Insert a newline, then enough tabs and spaces to duplicate the indentation * of the previous line. Assumes tabs are every eight characters. Quite simple. * Figure out the indentation of the current line. Insert a newline by calling * the standard routine. Insert the indentation by inserting the right number * of tabs and spaces. Return TRUE if all ok. Return FALSE if one of the * subcomands failed. Normally bound to "C-J". */ int indent(int f, int n) { int nicol; int c; int i; if (curbp->b_mode & MDVIEW) /* don't allow this command if */ return rdonly(); /* we are in read only mode */ if (n < 0) return FALSE; while (n--) { nicol = 0; for (i = 0; i < llength(curwp->w_dotp); ++i) { c = lgetc(curwp->w_dotp, i); if (c != ' ' && c != '\t') break; if (c == '\t') nicol |= tabmask; ++nicol; } if (lnewline() == FALSE || ((i = nicol / 8) != 0 && linsert(i, '\t') == FALSE) || ((i = nicol % 8) != 0 && linsert(i, ' ') == FALSE)) return FALSE; } return TRUE; } /* * Delete forward. This is real easy, because the basic delete routine does * all of the work. Watches for negative arguments, and does the right thing. * If any argument is present, it kills rather than deletes, to prevent loss * of text if typed with a big argument. Normally bound to "C-D". */ int forwdel(int f, int n) { if (curbp->b_mode & MDVIEW) /* don't allow this command if */ return rdonly(); /* we are in read only mode */ if (n < 0) return backdel(f, -n); if (f != FALSE) { /* Really a kill. */ if ((lastflag & CFKILL) == 0) kdelete(); thisflag |= CFKILL; } return ldelchar((long) n, f); } /* * Delete backwards. This is quite easy too, because it's all done with other * functions. Just move the cursor back, and delete forwards. Like delete * forward, this actually does a kill if presented with an argument. Bound to * both "RUBOUT" and "C-H". */ int backdel(int f, int n) { int s; if (curbp->b_mode & MDVIEW) /* don't allow this command if */ return rdonly(); /* we are in read only mode */ if (n < 0) return forwdel(f, -n); if (f != FALSE) { /* Really a kill. */ if ((lastflag & CFKILL) == 0) kdelete(); thisflag |= CFKILL; } if ((s = backchar(f, n)) == TRUE) s = ldelchar(n, f); return s; } /* * Kill text. If called without an argument, it kills from dot to the end of * the line, unless it is at the end of the line, when it kills the newline. * If called with an argument of 0, it kills from the start of the line to dot. * If called with a positive argument, it kills from dot forward over that * number of newlines. If called with a negative argument it kills backwards * that number of newlines. Normally bound to "C-K". */ int killtext(int f, int n) { struct line *nextp; long chunk; if (curbp->b_mode & MDVIEW) /* don't allow this command if */ return rdonly(); /* we are in read only mode */ if ((lastflag & CFKILL) == 0) /* Clear kill buffer if */ kdelete(); /* last wasn't a kill. */ thisflag |= CFKILL; if (f == FALSE) { chunk = llength(curwp->w_dotp) - curwp->w_doto; if (chunk == 0) chunk = 1; } else if (n == 0) { chunk = curwp->w_doto; curwp->w_doto = 0; } else if (n > 0) { chunk = llength(curwp->w_dotp) - curwp->w_doto + 1; nextp = lforw(curwp->w_dotp); while (--n) { if (nextp == curbp->b_linep) return FALSE; chunk += llength(nextp) + 1; nextp = lforw(nextp); } } else { mlwrite("neg kill"); return FALSE; } return ldelete(chunk, TRUE); } /* * prompt and set an editor mode * * int f, n; default and argument */ int setemode(int f, int n) { #if PKCODE return adjustmode(TRUE, FALSE); #else adjustmode(TRUE, FALSE); #endif } /* * prompt and delete an editor mode * * int f, n; default and argument */ int delmode(int f, int n) { #if PKCODE return adjustmode(FALSE, FALSE); #else adjustmode(FALSE, FALSE); #endif } /* * prompt and set a global editor mode * * int f, n; default and argument */ int setgmode(int f, int n) { #if PKCODE return adjustmode(TRUE, TRUE); #else adjustmode(TRUE, TRUE); #endif } /* * prompt and delete a global editor mode * * int f, n; default and argument */ int delgmode(int f, int n) { #if PKCODE return adjustmode(FALSE, TRUE); #else adjustmode(FALSE, TRUE); #endif } /* * change the editor mode status * * int kind; true = set, false = delete * int global; true = global flag, false = current buffer flag */ int adjustmode(int kind, int global) { char *scan; /* scanning pointer to convert prompt */ int i; /* loop index */ int status; /* error return on input */ #if COLOR int uflag; /* was modename uppercase? */ #endif char prompt[50]; /* string to prompt user with */ char cbuf[NPAT]; /* buffer to recieve mode name into */ /* build the proper prompt string */ if (global) strcpy(prompt, "Global mode to "); else strcpy(prompt, "Mode to "); if (kind == TRUE) strcat(prompt, "add: "); else strcat(prompt, "delete: "); /* prompt the user and get an answer */ status = mlreply(prompt, cbuf, NPAT - 1); if (status != TRUE) return status; /* make it uppercase */ scan = cbuf; #if COLOR uflag = (*scan >= 'A' && *scan <= 'Z'); #endif while (*scan != 0) { if (*scan >= 'a' && *scan <= 'z') *scan = *scan - 32; scan++; } /* test it first against the colors we know */ #if PKCODE & IBMPC for (i = 0; i <= NCOLORS; i++) { #else for (i = 0; i < NCOLORS; i++) { #endif if (strcmp(cbuf, cname[i]) == 0) { /* finding the match, we set the color */ #if COLOR if (uflag) { if (global) gfcolor = i; #if PKCODE == 0 else #endif curwp->w_fcolor = i; } else { if (global) gbcolor = i; #if PKCODE == 0 else #endif curwp->w_bcolor = i; } curwp->w_flag |= WFCOLR; #endif mlerase(); return TRUE; } } /* test it against the modes we know */ for (i = 0; i < NUMMODES; i++) { if (strcmp(cbuf, modename[i]) == 0) { /* finding a match, we process it */ if (kind == TRUE) if (global) gmode |= (1 << i); else curbp->b_mode |= (1 << i); else if (global) gmode &= ~(1 << i); else curbp->b_mode &= ~(1 << i); /* display new mode line */ if (global == 0) upmode(); mlerase(); /* erase the junk */ return TRUE; } } mlwrite("No such mode!"); return FALSE; } /* * This function simply clears the message line, * mainly for macro usage * * int f, n; arguments ignored */ int clrmes(int f, int n) { mlforce(""); return TRUE; } /* * This function writes a string on the message line * mainly for macro usage * * int f, n; arguments ignored */ int writemsg(int f, int n) { char *sp; /* pointer into buf to expand %s */ char *np; /* ptr into nbuf */ int status; char buf[NPAT]; /* buffer to recieve message into */ char nbuf[NPAT * 2]; /* buffer to expand string into */ if ((status = mlreply("Message to write: ", buf, NPAT - 1)) != TRUE) return status; /* expand all '%' to "%%" so mlwrite won't expect arguments */ sp = buf; np = nbuf; while (*sp) { *np++ = *sp; if (*sp++ == '%') *np++ = '%'; } *np = '\0'; /* write the message out */ mlforce(nbuf); return TRUE; } #if CFENCE /* * the cursor is moved to a matching fence * * int f, n; not used */ int getfence(int f, int n) { struct line *oldlp; /* original line pointer */ int oldoff; /* and offset */ int sdir; /* direction of search (1/-1) */ int count; /* current fence level count */ char ch; /* fence type to match against */ char ofence; /* open fence */ char c; /* current character in scan */ /* save the original cursor position */ oldlp = curwp->w_dotp; oldoff = curwp->w_doto; /* get the current character */ if (oldoff == llength(oldlp)) ch = '\n'; else ch = lgetc(oldlp, oldoff); /* setup proper matching fence */ switch (ch) { case '(': ofence = ')'; sdir = FORWARD; break; case '{': ofence = '}'; sdir = FORWARD; break; case '[': ofence = ']'; sdir = FORWARD; break; case ')': ofence = '('; sdir = REVERSE; break; case '}': ofence = '{'; sdir = REVERSE; break; case ']': ofence = '['; sdir = REVERSE; break; default: TTbeep(); return FALSE; } /* set up for scan */ count = 1; if (sdir == REVERSE) backchar(FALSE, 1); else forwchar(FALSE, 1); /* scan until we find it, or reach the end of file */ while (count > 0) { if (curwp->w_doto == llength(curwp->w_dotp)) c = '\n'; else c = lgetc(curwp->w_dotp, curwp->w_doto); if (c == ch) ++count; if (c == ofence) --count; if (sdir == FORWARD) forwchar(FALSE, 1); else backchar(FALSE, 1); if (boundry(curwp->w_dotp, curwp->w_doto, sdir)) break; } /* if count is zero, we have a match, move the sucker */ if (count == 0) { if (sdir == FORWARD) backchar(FALSE, 1); else forwchar(FALSE, 1); curwp->w_flag |= WFMOVE; return TRUE; } /* restore the current position */ curwp->w_dotp = oldlp; curwp->w_doto = oldoff; TTbeep(); return FALSE; } #endif /* * Close fences are matched against their partners, and if * on screen the cursor briefly lights there * * char ch; fence type to match against */ int fmatch(int ch) { struct line *oldlp; /* original line pointer */ int oldoff; /* and offset */ struct line *toplp; /* top line in current window */ int count; /* current fence level count */ char opench; /* open fence */ char c; /* current character in scan */ int i; /* first get the display update out there */ update(FALSE); /* save the original cursor position */ oldlp = curwp->w_dotp; oldoff = curwp->w_doto; /* setup proper open fence for passed close fence */ if (ch == ')') opench = '('; else if (ch == '}') opench = '{'; else opench = '['; /* find the top line and set up for scan */ toplp = curwp->w_linep->l_bp; count = 1; backchar(FALSE, 2); /* scan back until we find it, or reach past the top of the window */ while (count > 0 && curwp->w_dotp != toplp) { if (curwp->w_doto == llength(curwp->w_dotp)) c = '\n'; else c = lgetc(curwp->w_dotp, curwp->w_doto); if (c == ch) ++count; if (c == opench) --count; backchar(FALSE, 1); if (curwp->w_dotp == curwp->w_bufp->b_linep->l_fp && curwp->w_doto == 0) break; } /* if count is zero, we have a match, display the sucker */ /* there is a real machine dependant timing problem here we have yet to solve......... */ if (count == 0) { forwchar(FALSE, 1); for (i = 0; i < term.t_pause; i++) update(FALSE); } /* restore the current position */ curwp->w_dotp = oldlp; curwp->w_doto = oldoff; return TRUE; } /* * ask for and insert a string into the current * buffer at the current point * * int f, n; ignored arguments */ int istring(int f, int n) { int status; /* status return code */ char tstring[NPAT + 1]; /* string to add */ /* ask for string to insert */ status = mlreplyt("String to insert<META>: ", tstring, NPAT, metac); if (status != TRUE) return status; if (f == FALSE) n = 1; if (n < 0) n = -n; /* insert it */ while (n-- && (status = linstr(tstring))); return status; } /* * ask for and overwite a string into the current * buffer at the current point * * int f, n; ignored arguments */ int ovstring(int f, int n) { int status; /* status return code */ char tstring[NPAT + 1]; /* string to add */ /* ask for string to insert */ status = mlreplyt("String to overwrite<META>: ", tstring, NPAT, metac); if (status != TRUE) return status; if (f == FALSE) n = 1; if (n < 0) n = -n; /* insert it */ while (n-- && (status = lover(tstring))); return status; }
uemacs-master
random.c
#include "utf8.h" /* * utf8_to_unicode() * * Convert a UTF-8 sequence to its unicode value, and return the length of * the sequence in bytes. * * NOTE! Invalid UTF-8 will be converted to a one-byte sequence, so you can * either use it as-is (ie as Latin1) or you can check for invalid UTF-8 * by checking for a length of 1 and a result > 127. * * NOTE 2! This does *not* verify things like minimality. So overlong forms * are happily accepted and decoded, as are the various "invalid values". */ unsigned utf8_to_unicode(char *line, unsigned index, unsigned len, unicode_t *res) { unsigned value; unsigned char c = line[index]; unsigned bytes, mask, i; *res = c; line += index; len -= index; /* * 0xxxxxxx is valid utf8 * 10xxxxxx is invalid UTF-8, we assume it is Latin1 */ if (c < 0xc0) return 1; /* Ok, it's 11xxxxxx, do a stupid decode */ mask = 0x20; bytes = 2; while (c & mask) { bytes++; mask >>= 1; } /* Invalid? Do it as a single byte Latin1 */ if (bytes > 6) return 1; if (bytes > len) return 1; value = c & (mask-1); /* Ok, do the bytes */ for (i = 1; i < bytes; i++) { c = line[i]; if ((c & 0xc0) != 0x80) return 1; value = (value << 6) | (c & 0x3f); } *res = value; return bytes; } static void reverse_string(char *begin, char *end) { do { char a = *begin, b = *end; *end = a; *begin = b; begin++; end--; } while (begin < end); } /* * unicode_to_utf8() * * Convert a unicode value to its canonical utf-8 sequence. * * NOTE! This does not check for - or care about - the "invalid" unicode * values. Also, converting a utf-8 sequence to unicode and back does * *not* guarantee the same sequence, since this generates the shortest * possible sequence, while utf8_to_unicode() accepts both Latin1 and * overlong utf-8 sequences. */ unsigned unicode_to_utf8(unsigned int c, char *utf8) { int bytes = 1; *utf8 = c; if (c > 0x7f) { int prefix = 0x40; char *p = utf8; do { *p++ = 0x80 + (c & 0x3f); bytes++; prefix >>= 1; c >>= 6; } while (c > prefix); *p = c - 2*prefix; reverse_string(utf8, p); } return bytes; }
uemacs-master
utf8.c
/* word.c * * The routines in this file implement commands that work word or a * paragraph at a time. There are all sorts of word mode commands. If I * do any sentence mode commands, they are likely to be put in this file. * * Modified by Petri Kutvonen */ #include <stdio.h> #include "estruct.h" #include "edef.h" #include "efunc.h" #include "line.h" /* Word wrap on n-spaces. Back-over whatever precedes the point on the current * line and stop on the first word-break or the beginning of the line. If we * reach the beginning of the line, jump back to the end of the word and start * a new line. Otherwise, break the line at the word-break, eat it, and jump * back to the end of the word. * Returns TRUE on success, FALSE on errors. * * @f: default flag. * @n: numeric argument. */ int wrapword(int f, int n) { int cnt; /* size of word wrapped to next line */ int c; /* charector temporary */ /* backup from the <NL> 1 char */ if (!backchar(0, 1)) return FALSE; /* back up until we aren't in a word, make sure there is a break in the line */ cnt = 0; while (((c = lgetc(curwp->w_dotp, curwp->w_doto)) != ' ') && (c != '\t')) { cnt++; if (!backchar(0, 1)) return FALSE; /* if we make it to the beginning, start a new line */ if (curwp->w_doto == 0) { gotoeol(FALSE, 0); return lnewline(); } } /* delete the forward white space */ if (!forwdel(0, 1)) return FALSE; /* put in a end of line */ if (!lnewline()) return FALSE; /* and past the first word */ while (cnt-- > 0) { if (forwchar(FALSE, 1) == FALSE) return FALSE; } return TRUE; } /* * Move the cursor backward by "n" words. All of the details of motion are * performed by the "backchar" and "forwchar" routines. Error if you try to * move beyond the buffers. */ int backword(int f, int n) { if (n < 0) return forwword(f, -n); if (backchar(FALSE, 1) == FALSE) return FALSE; while (n--) { while (inword() == FALSE) { if (backchar(FALSE, 1) == FALSE) return FALSE; } while (inword() != FALSE) { if (backchar(FALSE, 1) == FALSE) return FALSE; } } return forwchar(FALSE, 1); } /* * Move the cursor forward by the specified number of words. All of the motion * is done by "forwchar". Error if you try and move beyond the buffer's end. */ int forwword(int f, int n) { if (n < 0) return backword(f, -n); while (n--) { while (inword() == TRUE) { if (forwchar(FALSE, 1) == FALSE) return FALSE; } while (inword() == FALSE) { if (forwchar(FALSE, 1) == FALSE) return FALSE; } } return TRUE; } /* * Move the cursor forward by the specified number of words. As you move, * convert any characters to upper case. Error if you try and move beyond the * end of the buffer. Bound to "M-U". */ int upperword(int f, int n) { int c; if (curbp->b_mode & MDVIEW) /* don't allow this command if */ return rdonly(); /* we are in read only mode */ if (n < 0) return FALSE; while (n--) { while (inword() == FALSE) { if (forwchar(FALSE, 1) == FALSE) return FALSE; } while (inword() != FALSE) { c = lgetc(curwp->w_dotp, curwp->w_doto); #if PKCODE if (islower(c)) { #else if (c >= 'a' && c <= 'z') { #endif c -= 'a' - 'A'; lputc(curwp->w_dotp, curwp->w_doto, c); lchange(WFHARD); } if (forwchar(FALSE, 1) == FALSE) return FALSE; } } return TRUE; } /* * Move the cursor forward by the specified number of words. As you move * convert characters to lower case. Error if you try and move over the end of * the buffer. Bound to "M-L". */ int lowerword(int f, int n) { int c; if (curbp->b_mode & MDVIEW) /* don't allow this command if */ return rdonly(); /* we are in read only mode */ if (n < 0) return FALSE; while (n--) { while (inword() == FALSE) { if (forwchar(FALSE, 1) == FALSE) return FALSE; } while (inword() != FALSE) { c = lgetc(curwp->w_dotp, curwp->w_doto); #if PKCODE if (isupper(c)) { #else if (c >= 'A' && c <= 'Z') { #endif c += 'a' - 'A'; lputc(curwp->w_dotp, curwp->w_doto, c); lchange(WFHARD); } if (forwchar(FALSE, 1) == FALSE) return FALSE; } } return TRUE; } /* * Move the cursor forward by the specified number of words. As you move * convert the first character of the word to upper case, and subsequent * characters to lower case. Error if you try and move past the end of the * buffer. Bound to "M-C". */ int capword(int f, int n) { int c; if (curbp->b_mode & MDVIEW) /* don't allow this command if */ return rdonly(); /* we are in read only mode */ if (n < 0) return FALSE; while (n--) { while (inword() == FALSE) { if (forwchar(FALSE, 1) == FALSE) return FALSE; } if (inword() != FALSE) { c = lgetc(curwp->w_dotp, curwp->w_doto); #if PKCODE if (islower(c)) { #else if (c >= 'a' && c <= 'z') { #endif c -= 'a' - 'A'; lputc(curwp->w_dotp, curwp->w_doto, c); lchange(WFHARD); } if (forwchar(FALSE, 1) == FALSE) return FALSE; while (inword() != FALSE) { c = lgetc(curwp->w_dotp, curwp->w_doto); #if PKCODE if (isupper(c)) { #else if (c >= 'A' && c <= 'Z') { #endif c += 'a' - 'A'; lputc(curwp->w_dotp, curwp->w_doto, c); lchange(WFHARD); } if (forwchar(FALSE, 1) == FALSE) return FALSE; } } } return TRUE; } /* * Kill forward by "n" words. Remember the location of dot. Move forward by * the right number of words. Put dot back where it was and issue the kill * command for the right number of characters. With a zero argument, just * kill one word and no whitespace. Bound to "M-D". */ int delfword(int f, int n) { struct line *dotp; /* original cursor line */ int doto; /* and row */ int c; /* temp char */ long size; /* # of chars to delete */ /* don't allow this command if we are in read only mode */ if (curbp->b_mode & MDVIEW) return rdonly(); /* ignore the command if there is a negative argument */ if (n < 0) return FALSE; /* Clear the kill buffer if last command wasn't a kill */ if ((lastflag & CFKILL) == 0) kdelete(); thisflag |= CFKILL; /* this command is a kill */ /* save the current cursor position */ dotp = curwp->w_dotp; doto = curwp->w_doto; /* figure out how many characters to give the axe */ size = 0; /* get us into a word.... */ while (inword() == FALSE) { if (forwchar(FALSE, 1) == FALSE) return FALSE; ++size; } if (n == 0) { /* skip one word, no whitespace! */ while (inword() == TRUE) { if (forwchar(FALSE, 1) == FALSE) return FALSE; ++size; } } else { /* skip n words.... */ while (n--) { /* if we are at EOL; skip to the beginning of the next */ while (curwp->w_doto == llength(curwp->w_dotp)) { if (forwchar(FALSE, 1) == FALSE) return FALSE; ++size; } /* move forward till we are at the end of the word */ while (inword() == TRUE) { if (forwchar(FALSE, 1) == FALSE) return FALSE; ++size; } /* if there are more words, skip the interword stuff */ if (n != 0) while (inword() == FALSE) { if (forwchar(FALSE, 1) == FALSE) return FALSE; ++size; } } /* skip whitespace and newlines */ while ((curwp->w_doto == llength(curwp->w_dotp)) || ((c = lgetc(curwp->w_dotp, curwp->w_doto)) == ' ') || (c == '\t')) { if (forwchar(FALSE, 1) == FALSE) break; ++size; } } /* restore the original position and delete the words */ curwp->w_dotp = dotp; curwp->w_doto = doto; return ldelete(size, TRUE); } /* * Kill backwards by "n" words. Move backwards by the desired number of words, * counting the characters. When dot is finally moved to its resting place, * fire off the kill command. Bound to "M-Rubout" and to "M-Backspace". */ int delbword(int f, int n) { long size; /* don't allow this command if we are in read only mode */ if (curbp->b_mode & MDVIEW) return rdonly(); /* ignore the command if there is a nonpositive argument */ if (n <= 0) return FALSE; /* Clear the kill buffer if last command wasn't a kill */ if ((lastflag & CFKILL) == 0) kdelete(); thisflag |= CFKILL; /* this command is a kill */ if (backchar(FALSE, 1) == FALSE) return FALSE; size = 0; while (n--) { while (inword() == FALSE) { if (backchar(FALSE, 1) == FALSE) return FALSE; ++size; } while (inword() != FALSE) { ++size; if (backchar(FALSE, 1) == FALSE) goto bckdel; } } if (forwchar(FALSE, 1) == FALSE) return FALSE; bckdel:return ldelchar(size, TRUE); } /* * Return TRUE if the character at dot is a character that is considered to be * part of a word. The word character list is hard coded. Should be setable. */ int inword(void) { int c; if (curwp->w_doto == llength(curwp->w_dotp)) return FALSE; c = lgetc(curwp->w_dotp, curwp->w_doto); #if PKCODE if (isletter(c)) #else if (c >= 'a' && c <= 'z') return TRUE; if (c >= 'A' && c <= 'Z') #endif return TRUE; if (c >= '0' && c <= '9') return TRUE; return FALSE; } #if WORDPRO /* * Fill the current paragraph according to the current * fill column * * f and n - deFault flag and Numeric argument */ int fillpara(int f, int n) { unicode_t c; /* current char during scan */ unicode_t wbuf[NSTRING];/* buffer for current word */ int wordlen; /* length of current word */ int clength; /* position on line during fill */ int i; /* index during word copy */ int newlength; /* tentative new line length */ int eopflag; /* Are we at the End-Of-Paragraph? */ int firstflag; /* first word? (needs no space) */ struct line *eopline; /* pointer to line just past EOP */ int dotflag; /* was the last char a period? */ if (curbp->b_mode & MDVIEW) /* don't allow this command if */ return rdonly(); /* we are in read only mode */ if (fillcol == 0) { /* no fill column set */ mlwrite("No fill column set"); return FALSE; } #if PKCODE justflag = FALSE; #endif /* record the pointer to the line just past the EOP */ gotoeop(FALSE, 1); eopline = lforw(curwp->w_dotp); /* and back top the beginning of the paragraph */ gotobop(FALSE, 1); /* initialize various info */ clength = curwp->w_doto; if (clength && curwp->w_dotp->l_text[0] == TAB) clength = 8; wordlen = 0; dotflag = FALSE; /* scan through lines, filling words */ firstflag = TRUE; eopflag = FALSE; while (!eopflag) { int bytes = 1; /* get the next character in the paragraph */ if (curwp->w_doto == llength(curwp->w_dotp)) { c = ' '; if (lforw(curwp->w_dotp) == eopline) eopflag = TRUE; } else bytes = lgetchar(&c); /* and then delete it */ ldelete(bytes, FALSE); /* if not a separator, just add it in */ if (c != ' ' && c != '\t') { dotflag = (c == '.'); /* was it a dot */ if (wordlen < NSTRING - 1) wbuf[wordlen++] = c; } else if (wordlen) { /* at a word break with a word waiting */ /* calculate tentitive new length with word added */ newlength = clength + 1 + wordlen; if (newlength <= fillcol) { /* add word to current line */ if (!firstflag) { linsert(1, ' '); /* the space */ ++clength; } firstflag = FALSE; } else { /* start a new line */ lnewline(); clength = 0; } /* and add the word in in either case */ for (i = 0; i < wordlen; i++) { linsert(1, wbuf[i]); ++clength; } if (dotflag) { linsert(1, ' '); ++clength; } wordlen = 0; } } /* and add a last newline for the end of our new paragraph */ lnewline(); return TRUE; } #if PKCODE /* Fill the current paragraph according to the current * fill column and cursor position * * int f, n; deFault flag and Numeric argument */ int justpara(int f, int n) { unicode_t c; /* current char durring scan */ unicode_t wbuf[NSTRING];/* buffer for current word */ int wordlen; /* length of current word */ int clength; /* position on line during fill */ int i; /* index during word copy */ int newlength; /* tentative new line length */ int eopflag; /* Are we at the End-Of-Paragraph? */ int firstflag; /* first word? (needs no space) */ struct line *eopline; /* pointer to line just past EOP */ int leftmarg; /* left marginal */ if (curbp->b_mode & MDVIEW) /* don't allow this command if */ return rdonly(); /* we are in read only mode */ if (fillcol == 0) { /* no fill column set */ mlwrite("No fill column set"); return FALSE; } justflag = TRUE; leftmarg = curwp->w_doto; if (leftmarg + 10 > fillcol) { leftmarg = 0; mlwrite("Column too narrow"); return FALSE; } /* record the pointer to the line just past the EOP */ gotoeop(FALSE, 1); eopline = lforw(curwp->w_dotp); /* and back top the beginning of the paragraph */ gotobop(FALSE, 1); /* initialize various info */ if (leftmarg < llength(curwp->w_dotp)) curwp->w_doto = leftmarg; clength = curwp->w_doto; if (clength && curwp->w_dotp->l_text[0] == TAB) clength = 8; wordlen = 0; /* scan through lines, filling words */ firstflag = TRUE; eopflag = FALSE; while (!eopflag) { int bytes = 1; /* get the next character in the paragraph */ if (curwp->w_doto == llength(curwp->w_dotp)) { c = ' '; if (lforw(curwp->w_dotp) == eopline) eopflag = TRUE; } else bytes = lgetchar(&c); /* and then delete it */ ldelete(bytes, FALSE); /* if not a separator, just add it in */ if (c != ' ' && c != '\t') { if (wordlen < NSTRING - 1) wbuf[wordlen++] = c; } else if (wordlen) { /* at a word break with a word waiting */ /* calculate tentitive new length with word added */ newlength = clength + 1 + wordlen; if (newlength <= fillcol) { /* add word to current line */ if (!firstflag) { linsert(1, ' '); /* the space */ ++clength; } firstflag = FALSE; } else { /* start a new line */ lnewline(); for (i = 0; i < leftmarg; i++) linsert(1, ' '); clength = leftmarg; } /* and add the word in in either case */ for (i = 0; i < wordlen; i++) { linsert(1, wbuf[i]); ++clength; } wordlen = 0; } } /* and add a last newline for the end of our new paragraph */ lnewline(); forwword(FALSE, 1); if (llength(curwp->w_dotp) > leftmarg) curwp->w_doto = leftmarg; else curwp->w_doto = llength(curwp->w_dotp); justflag = FALSE; return TRUE; } #endif /* * delete n paragraphs starting with the current one * * int f default flag * int n # of paras to delete */ int killpara(int f, int n) { int status; /* returned status of functions */ while (n--) { /* for each paragraph to delete */ /* mark out the end and beginning of the para to delete */ gotoeop(FALSE, 1); /* set the mark here */ curwp->w_markp = curwp->w_dotp; curwp->w_marko = curwp->w_doto; /* go to the beginning of the paragraph */ gotobop(FALSE, 1); curwp->w_doto = 0; /* force us to the beginning of line */ /* and delete it */ if ((status = killregion(FALSE, 1)) != TRUE) return status; /* and clean up the 2 extra lines */ ldelete(2L, TRUE); } return TRUE; } /* * wordcount: count the # of words in the marked region, * along with average word sizes, # of chars, etc, * and report on them. * * int f, n; ignored numeric arguments */ int wordcount(int f, int n) { struct line *lp; /* current line to scan */ int offset; /* current char to scan */ long size; /* size of region left to count */ int ch; /* current character to scan */ int wordflag; /* are we in a word now? */ int lastword; /* were we just in a word? */ long nwords; /* total # of words */ long nchars; /* total number of chars */ int nlines; /* total number of lines in region */ int avgch; /* average number of chars/word */ int status; /* status return code */ struct region region; /* region to look at */ /* make sure we have a region to count */ if ((status = getregion(&region)) != TRUE) return status; lp = region.r_linep; offset = region.r_offset; size = region.r_size; /* count up things */ lastword = FALSE; nchars = 0L; nwords = 0L; nlines = 0; while (size--) { /* get the current character */ if (offset == llength(lp)) { /* end of line */ ch = '\n'; lp = lforw(lp); offset = 0; ++nlines; } else { ch = lgetc(lp, offset); ++offset; } /* and tabulate it */ wordflag = ( #if PKCODE (isletter(ch)) || #else (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || #endif (ch >= '0' && ch <= '9')); if (wordflag == TRUE && lastword == FALSE) ++nwords; lastword = wordflag; ++nchars; } /* and report on the info */ if (nwords > 0L) avgch = (int) ((100L * nchars) / nwords); else avgch = 0; mlwrite("Words %D Chars %D Lines %d Avg chars/word %f", nwords, nchars, nlines + 1, avgch); return TRUE; } #endif
uemacs-master
word.c
#include "usage.h" #include <stdarg.h> #include <stdio.h> #include <stdlib.h> static void report(const char* prefix, const char *err, va_list params) { char msg[4096]; vsnprintf(msg, sizeof(msg), err, params); fprintf(stderr, "%s%s\n", prefix, msg); } void die(const char* err, ...) { va_list params; va_start(params, err); report("fatal: ", err, params); va_end(params); exit(128); }
uemacs-master
usage.c
/* search.c * * The functions in this file implement commands that search in the forward * and backward directions. There are no special characters in the search * strings. Probably should have a regular expression search, or something * like that. * * Aug. 1986 John M. Gamble: * Made forward and reverse search use the same scan routine. * * Added a limited number of regular expressions - 'any', * 'character class', 'closure', 'beginning of line', and * 'end of line'. * * Replacement metacharacters will have to wait for a re-write of * the replaces function, and a new variation of ldelete(). * * For those curious as to my references, i made use of * Kernighan & Plauger's "Software Tools." * I deliberately did not look at any published grep or editor * source (aside from this one) for inspiration. I did make use of * Allen Hollub's bitmap routines as published in Doctor Dobb's Journal, * June, 1985 and modified them for the limited needs of character class * matching. Any inefficiences, bugs, stupid coding examples, etc., * are therefore my own responsibility. * * April 1987: John M. Gamble * Deleted the "if (n == 0) n = 1;" statements in front of the * search/hunt routines. Since we now use a do loop, these * checks are unnecessary. Consolidated common code into the * function delins(). Renamed global mclen matchlen, * and added the globals matchline, matchoff, patmatch, and * mlenold. * This gave us the ability to unreplace regular expression searches, * and to put the matched string into an evironment variable. * SOON TO COME: Meta-replacement characters! * * 25-apr-87 DML * - cleaned up an unneccessary if/else in forwsearch() and * backsearch() * - savematch() failed to malloc room for the terminating byte * of the match string (stomp...stomp...). It does now. Also * it now returns gracefully if malloc fails * * July 1987: John M. Gamble * Set the variables matchlen and matchoff in the 'unreplace' * section of replaces(). The function savematch() would * get confused if you replaced, unreplaced, then replaced * again (serves you right for being so wishy-washy...) * * August 1987: John M. Gamble * Put in new function rmcstr() to create the replacement * meta-character array. Modified delins() so that it knows * whether or not to make use of the array. And, put in the * appropriate new structures and variables. * * Modified by Petri Kutvonen */ #include <stdio.h> #include "estruct.h" #include "edef.h" #include "efunc.h" #include "line.h" #if defined(MAGIC) /* * The variables magical and rmagical determine if there * were actual metacharacters in the search and replace strings - * if not, then we don't have to use the slower MAGIC mode * search functions. */ static short int magical; static short int rmagical; static struct magic mcpat[NPAT]; /* The magic pattern. */ static struct magic tapcm[NPAT]; /* The reversed magic patterni. */ static struct magic_replacement rmcpat[NPAT]; /* The replacement magic array. */ #endif static int amatch(struct magic *mcptr, int direct, struct line **pcwline, int *pcwoff); static int readpattern(char *prompt, char *apat, int srch); static int replaces(int kind, int f, int n); static int nextch(struct line **pcurline, int *pcuroff, int dir); static int mcstr(void); static int rmcstr(void); static int mceq(int bc, struct magic *mt); static int cclmake(char **ppatptr, struct magic *mcptr); static int biteq(int bc, char *cclmap); static char *clearbits(void); static void setbit(int bc, char *cclmap); /* * forwsearch -- Search forward. Get a search string from the user, and * search for the string. If found, reset the "." to be just after * the match string, and (perhaps) repaint the display. * * int f, n; default flag / numeric argument */ int forwsearch(int f, int n) { int status = TRUE; /* If n is negative, search backwards. * Otherwise proceed by asking for the search string. */ if (n < 0) return backsearch(f, -n); /* Ask the user for the text of a pattern. If the * response is TRUE (responses other than FALSE are * possible), search for the pattern for as long as * n is positive (n == 0 will go through once, which * is just fine). */ if ((status = readpattern("Search", &pat[0], TRUE)) == TRUE) { do { #if MAGIC if ((magical && curwp->w_bufp->b_mode & MDMAGIC) != 0) status = mcscanner(&mcpat[0], FORWARD, PTEND); else #endif status = scanner(&pat[0], FORWARD, PTEND); } while ((--n > 0) && status); /* Save away the match, or complain * if not there. */ if (status == TRUE) savematch(); else mlwrite("Not found"); } return status; } /* * forwhunt -- Search forward for a previously acquired search string. * If found, reset the "." to be just after the match string, * and (perhaps) repaint the display. * * int f, n; default flag / numeric argument */ int forwhunt(int f, int n) { int status = TRUE; if (n < 0) /* search backwards */ return backhunt(f, -n); /* Make sure a pattern exists, or that we didn't switch * into MAGIC mode until after we entered the pattern. */ if (pat[0] == '\0') { mlwrite("No pattern set"); return FALSE; } #if MAGIC if ((curwp->w_bufp->b_mode & MDMAGIC) != 0 && mcpat[0].mc_type == MCNIL) { if (!mcstr()) return FALSE; } #endif /* Search for the pattern for as long as * n is positive (n == 0 will go through once, which * is just fine). */ do { #if MAGIC if ((magical && curwp->w_bufp->b_mode & MDMAGIC) != 0) status = mcscanner(&mcpat[0], FORWARD, PTEND); else #endif status = scanner(&pat[0], FORWARD, PTEND); } while ((--n > 0) && status); /* Save away the match, or complain * if not there. */ if (status == TRUE) savematch(); else mlwrite("Not found"); return status; } /* * backsearch -- Reverse search. Get a search string from the user, and * search, starting at "." and proceeding toward the front of the buffer. * If found "." is left pointing at the first character of the pattern * (the last character that was matched). * * int f, n; default flag / numeric argument */ int backsearch(int f, int n) { int status = TRUE; /* If n is negative, search forwards. * Otherwise proceed by asking for the search string. */ if (n < 0) return forwsearch(f, -n); /* Ask the user for the text of a pattern. If the * response is TRUE (responses other than FALSE are * possible), search for the pattern for as long as * n is positive (n == 0 will go through once, which * is just fine). */ if ((status = readpattern("Reverse search", &pat[0], TRUE)) == TRUE) { do { #if MAGIC if ((magical && curwp->w_bufp->b_mode & MDMAGIC) != 0) status = mcscanner(&tapcm[0], REVERSE, PTBEG); else #endif status = scanner(&tap[0], REVERSE, PTBEG); } while ((--n > 0) && status); /* Save away the match, or complain * if not there. */ if (status == TRUE) savematch(); else mlwrite("Not found"); } return status; } /* * backhunt -- Reverse search for a previously acquired search string, * starting at "." and proceeding toward the front of the buffer. * If found "." is left pointing at the first character of the pattern * (the last character that was matched). * * int f, n; default flag / numeric argument */ int backhunt(int f, int n) { int status = TRUE; if (n < 0) return forwhunt(f, -n); /* Make sure a pattern exists, or that we didn't switch * into MAGIC mode until after we entered the pattern. */ if (tap[0] == '\0') { mlwrite("No pattern set"); return FALSE; } #if MAGIC if ((curwp->w_bufp->b_mode & MDMAGIC) != 0 && tapcm[0].mc_type == MCNIL) { if (!mcstr()) return FALSE; } #endif /* Go search for it for as long as * n is positive (n == 0 will go through once, which * is just fine). */ do { #if MAGIC if ((magical && curwp->w_bufp->b_mode & MDMAGIC) != 0) status = mcscanner(&tapcm[0], REVERSE, PTBEG); else #endif status = scanner(&tap[0], REVERSE, PTBEG); } while ((--n > 0) && status); /* Save away the match, or complain * if not there. */ if (status == TRUE) savematch(); else mlwrite("Not found"); return status; } #if MAGIC /* * mcscanner -- Search for a meta-pattern in either direction. If found, * reset the "." to be at the start or just after the match string, * and (perhaps) repaint the display. * * struct magic *mcpatrn; pointer into pattern * int direct; which way to go. * int beg_or_end; put point at beginning or end of pattern. */ int mcscanner(struct magic *mcpatrn, int direct, int beg_or_end) { struct line *curline; /* current line during scan */ int curoff; /* position within current line */ /* If we are going in reverse, then the 'end' is actually * the beginning of the pattern. Toggle it. */ beg_or_end ^= direct; /* * Save the old matchlen length, in case it is * very different (closure) from the old length. * This is important for query-replace undo * command. */ mlenold = matchlen; /* Setup local scan pointers to global ".". */ curline = curwp->w_dotp; curoff = curwp->w_doto; /* Scan each character until we hit the head link record. */ while (!boundry(curline, curoff, direct)) { /* Save the current position in case we need to * restore it on a match, and initialize matchlen to * zero in case we are doing a search for replacement. */ matchline = curline; matchoff = curoff; matchlen = 0; if (amatch(mcpatrn, direct, &curline, &curoff)) { /* A SUCCESSFULL MATCH!!! * reset the global "." pointers. */ if (beg_or_end == PTEND) { /* at end of string */ curwp->w_dotp = curline; curwp->w_doto = curoff; } else { /* at beginning of string */ curwp->w_dotp = matchline; curwp->w_doto = matchoff; } curwp->w_flag |= WFMOVE; /* flag that we have moved */ return TRUE; } /* Advance the cursor. */ nextch(&curline, &curoff, direct); } return FALSE; /* We could not find a match. */ } /* * amatch -- Search for a meta-pattern in either direction. Based on the * recursive routine amatch() (for "anchored match") in * Kernighan & Plauger's "Software Tools". * * struct magic *mcptr; string to scan for * int direct; which way to go. * struct line **pcwline; current line during scan * int *pcwoff; position within current line */ static int amatch(struct magic *mcptr, int direct, struct line **pcwline, int *pcwoff) { int c; /* character at current position */ struct line *curline; /* current line during scan */ int curoff; /* position within current line */ int nchars; /* Set up local scan pointers to ".", and get * the current character. Then loop around * the pattern pointer until success or failure. */ curline = *pcwline; curoff = *pcwoff; /* The beginning-of-line and end-of-line metacharacters * do not compare against characters, they compare * against positions. * BOL is guaranteed to be at the start of the pattern * for forward searches, and at the end of the pattern * for reverse searches. The reverse is true for EOL. * So, for a start, we check for them on entry. */ if (mcptr->mc_type == BOL) { if (curoff != 0) return FALSE; mcptr++; } if (mcptr->mc_type == EOL) { if (curoff != llength(curline)) return FALSE; mcptr++; } while (mcptr->mc_type != MCNIL) { c = nextch(&curline, &curoff, direct); if (mcptr->mc_type & CLOSURE) { /* Try to match as many characters as possible * against the current meta-character. A * newline never matches a closure. */ nchars = 0; while (c != '\n' && mceq(c, mcptr)) { c = nextch(&curline, &curoff, direct); nchars++; } /* We are now at the character that made us * fail. Try to match the rest of the pattern. * Shrink the closure by one for each failure. * Since closure matches *zero* or more occurences * of a pattern, a match may start even if the * previous loop matched no characters. */ mcptr++; for (;;) { c = nextch(&curline, &curoff, direct ^ REVERSE); if (amatch (mcptr, direct, &curline, &curoff)) { matchlen += nchars; goto success; } if (nchars-- == 0) return FALSE; } } else { /* Not closure. */ /* The only way we'd get a BOL metacharacter * at this point is at the end of the reversed pattern. * The only way we'd get an EOL metacharacter * here is at the end of a regular pattern. * So if we match one or the other, and are at * the appropriate position, we are guaranteed success * (since the next pattern character has to be MCNIL). * Before we report success, however, we back up by * one character, so as to leave the cursor in the * correct position. For example, a search for ")$" * will leave the cursor at the end of the line, while * a search for ")<NL>" will leave the cursor at the * beginning of the next line. This follows the * notion that the meta-character '$' (and likewise * '^') match positions, not characters. */ if (mcptr->mc_type == BOL) { if (curoff == llength(curline)) { c = nextch(&curline, &curoff, direct ^ REVERSE); goto success; } else return FALSE; } if (mcptr->mc_type == EOL) { if (curoff == 0) { c = nextch(&curline, &curoff, direct ^ REVERSE); goto success; } else return FALSE; } /* Neither BOL nor EOL, so go through * the meta-character equal function. */ if (!mceq(c, mcptr)) return FALSE; } /* Increment the length counter and * advance the pattern pointer. */ matchlen++; mcptr++; } /* End of mcptr loop. */ /* A SUCCESSFULL MATCH!!! * Reset the "." pointers. */ success: *pcwline = curline; *pcwoff = curoff; return TRUE; } #endif /* * scanner -- Search for a pattern in either direction. If found, * reset the "." to be at the start or just after the match string, * and (perhaps) repaint the display. * * unsigned char *patrn; string to scan for * int direct; which way to go. * int beg_or_end; put point at beginning or end of pattern. */ int scanner(const char *patrn, int direct, int beg_or_end) { int c; /* character at current position */ const char *patptr; /* pointer into pattern */ struct line *curline; /* current line during scan */ int curoff; /* position within current line */ struct line *scanline; /* current line during scanning */ int scanoff; /* position in scanned line */ /* If we are going in reverse, then the 'end' is actually * the beginning of the pattern. Toggle it. */ beg_or_end ^= direct; /* Set up local pointers to global ".". */ curline = curwp->w_dotp; curoff = curwp->w_doto; /* Scan each character until we hit the head link record. */ while (!boundry(curline, curoff, direct)) { /* Save the current position in case we match * the search string at this point. */ matchline = curline; matchoff = curoff; /* Get the character resolving newlines, and * test it against first char in pattern. */ c = nextch(&curline, &curoff, direct); if (eq(c, patrn[0])) { /* if we find it.. */ /* Setup scanning pointers. */ scanline = curline; scanoff = curoff; patptr = &patrn[0]; /* Scan through the pattern for a match. */ while (*++patptr != '\0') { c = nextch(&scanline, &scanoff, direct); if (!eq(c, *patptr)) goto fail; } /* A SUCCESSFULL MATCH!!! * reset the global "." pointers */ if (beg_or_end == PTEND) { /* at end of string */ curwp->w_dotp = scanline; curwp->w_doto = scanoff; } else { /* at beginning of string */ curwp->w_dotp = matchline; curwp->w_doto = matchoff; } curwp->w_flag |= WFMOVE; /* Flag that we have moved. */ return TRUE; } fail:; /* continue to search */ } return FALSE; /* We could not find a match */ } /* * eq -- Compare two characters. The "bc" comes from the buffer, "pc" * from the pattern. If we are not in EXACT mode, fold out the case. */ int eq(unsigned char bc, unsigned char pc) { if ((curwp->w_bufp->b_mode & MDEXACT) == 0) { if (islower(bc)) bc ^= DIFCASE; if (islower(pc)) pc ^= DIFCASE; } return bc == pc; } /* * readpattern -- Read a pattern. Stash it in apat. If it is the * search string, create the reverse pattern and the magic * pattern, assuming we are in MAGIC mode (and defined that way). * Apat is not updated if the user types in an empty line. If * the user typed an empty line, and there is no old pattern, it is * an error. Display the old pattern, in the style of Jeff Lomicka. * There is some do-it-yourself control expansion. Change to using * <META> to delimit the end-of-pattern to allow <NL>s in the search * string. */ static int readpattern(char *prompt, char *apat, int srch) { int status; char tpat[NPAT + 20]; strcpy(tpat, prompt); /* copy prompt to output string */ strcat(tpat, " ("); /* build new prompt string */ expandp(&apat[0], &tpat[strlen(tpat)], NPAT / 2); /* add old pattern */ strcat(tpat, ")<Meta>: "); /* Read a pattern. Either we get one, * or we just get the META charater, and use the previous pattern. * Then, if it's the search string, make a reversed pattern. * *Then*, make the meta-pattern, if we are defined that way. */ if ((status = mlreplyt(tpat, tpat, NPAT, metac)) == TRUE) { strcpy(apat, tpat); if (srch) { /* If we are doing the search string. */ /* Reverse string copy, and remember * the length for substitution purposes. */ rvstrcpy(tap, apat); mlenold = matchlen = strlen(apat); } #if MAGIC /* Only make the meta-pattern if in magic mode, * since the pattern in question might have an * invalid meta combination. */ if ((curwp->w_bufp->b_mode & MDMAGIC) == 0) { mcclear(); rmcclear(); } else status = srch ? mcstr() : rmcstr(); #endif } else if (status == FALSE && apat[0] != 0) /* Old one */ status = TRUE; return status; } /* * savematch -- We found the pattern? Let's save it away. */ void savematch(void) { char *ptr; /* pointer to last match string */ int j; struct line *curline; /* line of last match */ int curoff; /* offset " " */ /* Free any existing match string, then * attempt to allocate a new one. */ if (patmatch != NULL) free(patmatch); ptr = patmatch = malloc(matchlen + 1); if (ptr != NULL) { curoff = matchoff; curline = matchline; for (j = 0; j < matchlen; j++) *ptr++ = nextch(&curline, &curoff, FORWARD); *ptr = '\0'; } } /* * rvstrcpy -- Reverse string copy. */ void rvstrcpy(char *rvstr, char *str) { int i; str += (i = strlen(str)); while (i-- > 0) *rvstr++ = *--str; *rvstr = '\0'; } /* * sreplace -- Search and replace. * * int f; default flag * int n; # of repetitions wanted */ int sreplace(int f, int n) { return replaces(FALSE, f, n); } /* * qreplace -- search and replace with query. * * int f; default flag * int n; # of repetitions wanted */ int qreplace(int f, int n) { return replaces(TRUE, f, n); } /* * replaces -- Search for a string and replace it with another * string. Query might be enabled (according to kind). * * int kind; Query enabled flag * int f; default flag * int n; # of repetitions wanted */ static int replaces(int kind, int f, int n) { int status; /* success flag on pattern inputs */ int rlength; /* length of replacement string */ int numsub; /* number of substitutions */ int nummatch; /* number of found matches */ int nlflag; /* last char of search string a <NL>? */ int nlrepl; /* was a replace done on the last line? */ char c; /* input char for query */ char tpat[NPAT]; /* temporary to hold search pattern */ struct line *origline; /* original "." position */ int origoff; /* and offset (for . query option) */ struct line *lastline; /* position of last replace and */ int lastoff; /* offset (for 'u' query option) */ if (curbp->b_mode & MDVIEW) /* don't allow this command if */ return rdonly(); /* we are in read only mode */ /* Check for negative repetitions. */ if (f && n < 0) return FALSE; /* Ask the user for the text of a pattern. */ if ((status = readpattern((kind == FALSE ? "Replace" : "Query replace"), &pat[0], TRUE)) != TRUE) return status; /* Ask for the replacement string. */ if ((status = readpattern("with", &rpat[0], FALSE)) == ABORT) return status; /* Find the length of the replacement string. */ rlength = strlen(&rpat[0]); /* Set up flags so we can make sure not to do a recursive * replace on the last line. */ nlflag = (pat[matchlen - 1] == '\n'); nlrepl = FALSE; if (kind) { /* Build query replace question string. */ strcpy(tpat, "Replace '"); expandp(&pat[0], &tpat[strlen(tpat)], NPAT / 3); strcat(tpat, "' with '"); expandp(&rpat[0], &tpat[strlen(tpat)], NPAT / 3); strcat(tpat, "'? "); /* Initialize last replaced pointers. */ lastline = NULL; lastoff = 0; } /* Save original . position, init the number of matches and * substitutions, and scan through the file. */ origline = curwp->w_dotp; origoff = curwp->w_doto; numsub = 0; nummatch = 0; while ((f == FALSE || n > nummatch) && (nlflag == FALSE || nlrepl == FALSE)) { /* Search for the pattern. * If we search with a regular expression, * matchlen is reset to the true length of * the matched string. */ #if MAGIC if ((magical && curwp->w_bufp->b_mode & MDMAGIC) != 0) { if (!mcscanner(&mcpat[0], FORWARD, PTBEG)) break; } else #endif if (!scanner(&pat[0], FORWARD, PTBEG)) break; /* all done */ ++nummatch; /* Increment # of matches */ /* Check if we are on the last line. */ nlrepl = (lforw(curwp->w_dotp) == curwp->w_bufp->b_linep); /* Check for query. */ if (kind) { /* Get the query. */ pprompt:mlwrite(&tpat[0], &pat[0], &rpat[0]); qprompt: update(TRUE); /* show the proposed place to change */ c = tgetc(); /* and input */ mlwrite(""); /* and clear it */ /* And respond appropriately. */ switch (c) { #if PKCODE case 'Y': #endif case 'y': /* yes, substitute */ case ' ': savematch(); break; #if PKCODE case 'N': #endif case 'n': /* no, onword */ forwchar(FALSE, 1); continue; case '!': /* yes/stop asking */ kind = FALSE; break; #if PKCODE case 'U': #endif case 'u': /* undo last and re-prompt */ /* Restore old position. */ if (lastline == NULL) { /* There is nothing to undo. */ TTbeep(); goto pprompt; } curwp->w_dotp = lastline; curwp->w_doto = lastoff; lastline = NULL; lastoff = 0; /* Delete the new string. */ backchar(FALSE, rlength); #if PKCODE matchline = curwp->w_dotp; matchoff = curwp->w_doto; #endif status = delins(rlength, patmatch, FALSE); if (status != TRUE) return status; /* Record one less substitution, * backup, save our place, and * reprompt. */ --numsub; backchar(FALSE, mlenold); matchline = curwp->w_dotp; matchoff = curwp->w_doto; goto pprompt; case '.': /* abort! and return */ /* restore old position */ curwp->w_dotp = origline; curwp->w_doto = origoff; curwp->w_flag |= WFMOVE; case BELL: /* abort! and stay */ mlwrite("Aborted!"); return FALSE; default: /* bitch and beep */ TTbeep(); case '?': /* help me */ mlwrite ("(Y)es, (N)o, (!)Do rest, (U)ndo last, (^G)Abort, (.)Abort back, (?)Help: "); goto qprompt; } /* end of switch */ } /* end of "if kind" */ /* * Delete the sucker, and insert its * replacement. */ status = delins(matchlen, &rpat[0], TRUE); if (status != TRUE) return status; /* Save our position, since we may * undo this. */ if (kind) { lastline = curwp->w_dotp; lastoff = curwp->w_doto; } numsub++; /* increment # of substitutions */ } /* And report the results. */ mlwrite("%d substitutions", numsub); return TRUE; } /* * delins -- Delete a specified length from the current point * then either insert the string directly, or make use of * replacement meta-array. */ int delins(int dlength, char *instr, int use_meta) { int status; #if MAGIC struct magic_replacement *rmcptr; #endif /* Zap what we gotta, * and insert its replacement. */ if ((status = ldelete((long) dlength, FALSE)) != TRUE) mlwrite("%%ERROR while deleting"); else #if MAGIC if ((rmagical && use_meta) && (curwp->w_bufp->b_mode & MDMAGIC) != 0) { rmcptr = &rmcpat[0]; while (rmcptr->mc_type != MCNIL && status == TRUE) { if (rmcptr->mc_type == LITCHAR) status = linstr(rmcptr->rstr); else status = linstr(patmatch); rmcptr++; } } else #endif status = linstr(instr); return status; } /* * expandp -- Expand control key sequences for output. * * char *srcstr; string to expand * char *deststr; destination of expanded string * int maxlength; maximum chars in destination */ int expandp(char *srcstr, char *deststr, int maxlength) { unsigned char c; /* current char to translate */ /* Scan through the string. */ while ((c = *srcstr++) != 0) { if (c == '\n') { /* it's a newline */ *deststr++ = '<'; *deststr++ = 'N'; *deststr++ = 'L'; *deststr++ = '>'; maxlength -= 4; } #if PKCODE else if ((c > 0 && c < 0x20) || c == 0x7f) /* control character */ #else else if (c < 0x20 || c == 0x7f) /* control character */ #endif { *deststr++ = '^'; *deststr++ = c ^ 0x40; maxlength -= 2; } else if (c == '%') { *deststr++ = '%'; *deststr++ = '%'; maxlength -= 2; } else { /* any other character */ *deststr++ = c; maxlength--; } /* check for maxlength */ if (maxlength < 4) { *deststr++ = '$'; *deststr = '\0'; return FALSE; } } *deststr = '\0'; return TRUE; } /* * boundry -- Return information depending on whether we may search no * further. Beginning of file and end of file are the obvious * cases, but we may want to add further optional boundry restrictions * in future, a' la VMS EDT. At the moment, just return TRUE or * FALSE depending on if a boundry is hit (ouch). */ int boundry(struct line *curline, int curoff, int dir) { int border; if (dir == FORWARD) { border = (curoff == llength(curline)) && (lforw(curline) == curbp->b_linep); } else { border = (curoff == 0) && (lback(curline) == curbp->b_linep); } return border; } /* * nextch -- retrieve the next/previous character in the buffer, * and advance/retreat the point. * The order in which this is done is significant, and depends * upon the direction of the search. Forward searches look at * the current character and move, reverse searches move and * look at the character. */ static int nextch(struct line **pcurline, int *pcuroff, int dir) { struct line *curline; int curoff; int c; curline = *pcurline; curoff = *pcuroff; if (dir == FORWARD) { if (curoff == llength(curline)) { /* if at EOL */ curline = lforw(curline); /* skip to next line */ curoff = 0; c = '\n'; /* and return a <NL> */ } else c = lgetc(curline, curoff++); /* get the char */ } else { /* Reverse. */ if (curoff == 0) { curline = lback(curline); curoff = llength(curline); c = '\n'; } else c = lgetc(curline, --curoff); } *pcurline = curline; *pcuroff = curoff; return c; } #if MAGIC /* * mcstr -- Set up the 'magic' array. The closure symbol is taken as * a literal character when (1) it is the first character in the * pattern, and (2) when preceded by a symbol that does not allow * closure, such as a newline, beginning of line symbol, or another * closure symbol. * * Coding comment (jmg): yes, i know i have gotos that are, strictly * speaking, unnecessary. But right now we are so cramped for * code space that i will grab what i can in order to remain * within the 64K limit. C compilers actually do very little * in the way of optimizing - they expect you to do that. */ static int mcstr(void) { struct magic *mcptr, *rtpcm; char *patptr; int mj; int pchr; int status = TRUE; int does_closure = FALSE; /* If we had metacharacters in the struct magic array previously, * free up any bitmaps that may have been allocated. */ if (magical) mcclear(); magical = FALSE; mj = 0; mcptr = &mcpat[0]; patptr = &pat[0]; while ((pchr = *patptr) && status) { switch (pchr) { case MC_CCL: status = cclmake(&patptr, mcptr); magical = TRUE; does_closure = TRUE; break; case MC_BOL: if (mj != 0) goto litcase; mcptr->mc_type = BOL; magical = TRUE; does_closure = FALSE; break; case MC_EOL: if (*(patptr + 1) != '\0') goto litcase; mcptr->mc_type = EOL; magical = TRUE; does_closure = FALSE; break; case MC_ANY: mcptr->mc_type = ANY; magical = TRUE; does_closure = TRUE; break; case MC_CLOSURE: /* Does the closure symbol mean closure here? * If so, back up to the previous element * and indicate it is enclosed. */ if (!does_closure) goto litcase; mj--; mcptr--; mcptr->mc_type |= CLOSURE; magical = TRUE; does_closure = FALSE; break; /* Note: no break between MC_ESC case and the default. */ case MC_ESC: if (*(patptr + 1) != '\0') { pchr = *++patptr; magical = TRUE; } default: litcase:mcptr->mc_type = LITCHAR; mcptr->u.lchar = pchr; does_closure = (pchr != '\n'); break; } /* End of switch. */ mcptr++; patptr++; mj++; } /* End of while. */ /* Close off the meta-string. */ mcptr->mc_type = MCNIL; /* Set up the reverse array, if the status is good. Please note the * structure assignment - your compiler may not like that. * If the status is not good, nil out the meta-pattern. * The only way the status would be bad is from the cclmake() * routine, and the bitmap for that member is guarenteed to be * freed. So we stomp a MCNIL value there, and call mcclear() * to free any other bitmaps. */ if (status) { rtpcm = &tapcm[0]; while (--mj >= 0) { #if MSC | TURBO | VMS | USG | BSD | V7 *rtpcm++ = *--mcptr; #endif } rtpcm->mc_type = MCNIL; } else { (--mcptr)->mc_type = MCNIL; mcclear(); } return status; } /* * rmcstr -- Set up the replacement 'magic' array. Note that if there * are no meta-characters encountered in the replacement string, * the array is never actually created - we will just use the * character array rpat[] as the replacement string. */ static int rmcstr(void) { struct magic_replacement *rmcptr; char *patptr; int status = TRUE; int mj; patptr = &rpat[0]; rmcptr = &rmcpat[0]; mj = 0; rmagical = FALSE; while (*patptr && status == TRUE) { switch (*patptr) { case MC_DITTO: /* If there were non-magical characters * in the string before reaching this * character, plunk it in the replacement * array before processing the current * meta-character. */ if (mj != 0) { rmcptr->mc_type = LITCHAR; if ((rmcptr->rstr = malloc(mj + 1)) == NULL) { mlwrite("%%Out of memory"); status = FALSE; break; } strncpy(rmcptr->rstr, patptr - mj, mj); rmcptr++; mj = 0; } rmcptr->mc_type = DITTO; rmcptr++; rmagical = TRUE; break; case MC_ESC: rmcptr->mc_type = LITCHAR; /* We malloc mj plus two here, instead * of one, because we have to count the * current character. */ if ((rmcptr->rstr = malloc(mj + 2)) == NULL) { mlwrite("%%Out of memory"); status = FALSE; break; } strncpy(rmcptr->rstr, patptr - mj, mj + 1); /* If MC_ESC is not the last character * in the string, find out what it is * escaping, and overwrite the last * character with it. */ if (*(patptr + 1) != '\0') *((rmcptr->rstr) + mj) = *++patptr; rmcptr++; mj = 0; rmagical = TRUE; break; default: mj++; } patptr++; } if (rmagical && mj > 0) { rmcptr->mc_type = LITCHAR; if ((rmcptr->rstr = malloc(mj + 1)) == NULL) { mlwrite("%%Out of memory."); status = FALSE; } strncpy(rmcptr->rstr, patptr - mj, mj); rmcptr++; } rmcptr->mc_type = MCNIL; return status; } /* * mcclear -- Free up any CCL bitmaps, and MCNIL the struct magic search arrays. */ void mcclear(void) { struct magic *mcptr; mcptr = &mcpat[0]; while (mcptr->mc_type != MCNIL) { if ((mcptr->mc_type & MASKCL) == CCL || (mcptr->mc_type & MASKCL) == NCCL) free(mcptr->u.cclmap); mcptr++; } mcpat[0].mc_type = tapcm[0].mc_type = MCNIL; } /* * rmcclear -- Free up any strings, and MCNIL the struct magic_replacement array. */ void rmcclear(void) { struct magic_replacement *rmcptr; rmcptr = &rmcpat[0]; while (rmcptr->mc_type != MCNIL) { if (rmcptr->mc_type == LITCHAR) free(rmcptr->rstr); rmcptr++; } rmcpat[0].mc_type = MCNIL; } /* * mceq -- meta-character equality with a character. In Kernighan & Plauger's * Software Tools, this is the function omatch(), but i felt there * were too many functions with the 'match' name already. */ static int mceq(int bc, struct magic *mt) { int result; #if PKCODE bc = bc & 0xFF; #endif switch (mt->mc_type & MASKCL) { case LITCHAR: result = eq(bc, mt->u.lchar); break; case ANY: result = (bc != '\n'); break; case CCL: if (!(result = biteq(bc, mt->u.cclmap))) { if ((curwp->w_bufp->b_mode & MDEXACT) == 0 && (isletter(bc))) { result = biteq(CHCASE(bc), mt->u.cclmap); } } break; case NCCL: result = !biteq(bc, mt->u.cclmap); if ((curwp->w_bufp->b_mode & MDEXACT) == 0 && (isletter(bc))) { result &= !biteq(CHCASE(bc), mt->u.cclmap); } break; default: mlwrite("mceq: what is %d?", mt->mc_type); result = FALSE; break; } /* End of switch. */ return result; } extern char *clearbits(void); /* * cclmake -- create the bitmap for the character class. * ppatptr is left pointing to the end-of-character-class character, * so that a loop may automatically increment with safety. */ static int cclmake(char **ppatptr, struct magic *mcptr) { char *bmap; char *patptr; int pchr, ochr; if ((bmap = clearbits()) == NULL) { mlwrite("%%Out of memory"); return FALSE; } mcptr->u.cclmap = bmap; patptr = *ppatptr; /* * Test the initial character(s) in ccl for * special cases - negate ccl, or an end ccl * character as a first character. Anything * else gets set in the bitmap. */ if (*++patptr == MC_NCCL) { patptr++; mcptr->mc_type = NCCL; } else mcptr->mc_type = CCL; if ((ochr = *patptr) == MC_ECCL) { mlwrite("%%No characters in character class"); return FALSE; } else { if (ochr == MC_ESC) ochr = *++patptr; setbit(ochr, bmap); patptr++; } while (ochr != '\0' && (pchr = *patptr) != MC_ECCL) { switch (pchr) { /* Range character loses its meaning * if it is the last character in * the class. */ case MC_RCCL: if (*(patptr + 1) == MC_ECCL) setbit(pchr, bmap); else { pchr = *++patptr; while (++ochr <= pchr) setbit(ochr, bmap); } break; /* Note: no break between case MC_ESC and the default. */ case MC_ESC: pchr = *++patptr; default: setbit(pchr, bmap); break; } patptr++; ochr = pchr; } *ppatptr = patptr; if (ochr == '\0') { mlwrite("%%Character class not ended"); free(bmap); return FALSE; } return TRUE; } /* * biteq -- is the character in the bitmap? */ static int biteq(int bc, char *cclmap) { #if PKCODE bc = bc & 0xFF; #endif if (bc >= HICHAR) return FALSE; return (*(cclmap + (bc >> 3)) & BIT(bc & 7)) ? TRUE : FALSE; } /* * clearbits -- Allocate and zero out a CCL bitmap. */ static char *clearbits(void) { char *cclstart; char *cclmap; int i; if ((cclmap = cclstart = (char *)malloc(HIBYTE)) != NULL) { for (i = 0; i < HIBYTE; i++) *cclmap++ = 0; } return cclstart; } /* * setbit -- Set a bit (ON only) in the bitmap. */ static void setbit(int bc, char *cclmap) { #if PKCODE bc = bc & 0xFF; #endif if (bc < HICHAR) *(cclmap + (bc >> 3)) |= BIT(bc & 7); } #endif
uemacs-master
search.c
#include "usage.h" #include <stdlib.h> /* Function copyright: git */ int xmkstemp(char *template) { int fd; fd = mkstemp(template); if (fd < 0) die("Unable to create temporary file"); return fd; } void *xmalloc(size_t size) { void *ret = malloc(size); if (!ret) die("Out of memory"); return ret; }
uemacs-master
wrapper.c
/* PKLOCK.C * * locking routines as modified by Petri Kutvonen */ #include "estruct.h" #include "edef.h" #include "efunc.h" #if (FILOCK && BSD) || SVR4 #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <stdio.h> #include <fcntl.h> #ifdef SVR4 #include <string.h> #else #include <strings.h> #endif #include <errno.h> #define MAXLOCK 512 #define MAXNAME 128 #if defined(SVR4) && ! defined(__linux__) #include <sys/systeminfo.h> int gethostname(char *name, int namelen) { return sysinfo(SI_HOSTNAME, name, namelen); } #endif /********************** * * if successful, returns NULL * if file locked, returns username of person locking the file * if other error, returns "LOCK ERROR: explanation" * *********************/ char *dolock(char *fname) { int fd, n; static char lname[MAXLOCK], locker[MAXNAME + 1]; int mask; struct stat sbuf; strcat(strcpy(lname, fname), ".lock~"); /* check that we are not being cheated, qname must point to */ /* a regular file - even this code leaves a small window of */ /* vulnerability but it is rather hard to exploit it */ #if defined(S_IFLNK) if (lstat(lname, &sbuf) == 0) #else if (stat(lname, &sbuf) == 0) #endif #if defined(S_ISREG) if (!S_ISREG(sbuf.st_mode)) #else if (!(((sbuf.st_mode) & 070000) == 0)) /* SysV R2 */ #endif return "LOCK ERROR: not a regular file"; mask = umask(0); fd = open(lname, O_RDWR | O_CREAT, 0666); umask(mask); if (fd < 0) { if (errno == EACCES) return NULL; #ifdef EROFS if (errno == EROFS) return NULL; #endif return "LOCK ERROR: cannot access lock file"; } if ((n = read(fd, locker, MAXNAME)) < 1) { lseek(fd, 0, SEEK_SET); /* strcpy(locker, getlogin()); */ cuserid(locker); strcat(locker + strlen(locker), "@"); gethostname(locker + strlen(locker), 64); write(fd, locker, strlen(locker)); close(fd); return NULL; } locker[n > MAXNAME ? MAXNAME : n] = 0; return locker; } /********************* * * undolock -- unlock the file fname * * if successful, returns NULL * if other error, returns "LOCK ERROR: explanation" * *********************/ char *undolock(char *fname) { static char lname[MAXLOCK]; strcat(strcpy(lname, fname), ".lock~"); if (unlink(lname) != 0) { if (errno == EACCES || errno == ENOENT) return NULL; #ifdef EROFS if (errno == EROFS) return NULL; #endif return "LOCK ERROR: cannot remove lock file"; } return NULL; } #endif
uemacs-master
pklock.c
/* vt52.c * * The routines in this file * provide support for VT52 style terminals * over a serial line. The serial I/O services are * provided by routines in "termio.c". It compiles * into nothing if not a VT52 style device. The * bell on the VT52 is terrible, so the "beep" * routine is conditionalized on defining BEL. * * modified by Petri Kutvonen */ #define termdef 1 /* don't define "term" external */ #include <stdio.h> #include "estruct.h" #include "edef.h" #if VT52 #define NROW 24 /* Screen size. */ #define NCOL 80 /* Edit if you want to. */ #define MARGIN 8 /* size of minimim margin and */ #define SCRSIZ 64 /* scroll size for extended lines */ #define NPAUSE 100 /* # times thru update to pause */ #define BIAS 0x20 /* Origin 0 coordinate bias. */ #define ESC 0x1B /* ESC character. */ #define BEL 0x07 /* ascii bell character */ extern int ttopen(); /* Forward references. */ extern int ttgetc(); extern int ttputc(); extern int ttflush(); extern int ttclose(); extern int vt52move(); extern int vt52eeol(); extern int vt52eeop(); extern int vt52beep(); extern int vt52open(); extern int vt52rev(); extern int vt52cres(); extern int vt52kopen(); extern int vt52kclose(); #if COLOR extern int vt52fcol(); extern int vt52bcol(); #endif /* * Dispatch table. * All the hard fields just point into the terminal I/O code. */ struct terminal term = { NROW - 1, NROW - 1, NCOL, NCOL, MARGIN, SCRSIZ, NPAUSE, &vt52open, &ttclose, &vt52kopen, &vt52kclose, &ttgetc, &ttputc, &ttflush, &vt52move, &vt52eeol, &vt52eeop, &vt52beep, &vt52rev, &vt52cres #if COLOR , &vt52fcol, &vt52bcol #endif #if SCROLLCODE , NULL #endif }; vt52move(row, col) { ttputc(ESC); ttputc('Y'); ttputc(row + BIAS); ttputc(col + BIAS); } vt52eeol() { ttputc(ESC); ttputc('K'); } vt52eeop() { ttputc(ESC); ttputc('J'); } vt52rev(status) /* set the reverse video state */ int status; /* TRUE = reverse video, FALSE = normal video */ { /* can't do this here, so we won't */ } vt52cres() { /* change screen resolution - (not here though) */ return TRUE; } #if COLOR vt52fcol() { /* set the forground color [NOT IMPLIMENTED] */ } vt52bcol() { /* set the background color [NOT IMPLIMENTED] */ } #endif vt52beep() { #ifdef BEL ttputc(BEL); ttflush(); #endif } vt52open() { #if V7 | BSD char *cp; char *getenv(); if ((cp = getenv("TERM")) == NULL) { puts("Shell variable TERM not defined!"); exit(1); } if (strcmp(cp, "vt52") != 0 && strcmp(cp, "z19") != 0) { puts("Terminal type not 'vt52'or 'z19' !"); exit(1); } #endif ttopen(); } vt52kopen() { } vt52kclose() { } #endif
uemacs-master
vt52.c
/* input.c * * Various input routines * * written by Daniel Lawrence 5/9/86 * modified by Petri Kutvonen */ #include <stdio.h> #include <unistd.h> #include "estruct.h" #include "edef.h" #include "efunc.h" #include "wrapper.h" #if PKCODE #if MSDOS && TURBO #include <dir.h> #endif #endif #if PKCODE && (UNIX || (MSDOS && TURBO)) #define COMPLC 1 #else #define COMPLC 0 #endif /* * Ask a yes or no question in the message line. Return either TRUE, FALSE, or * ABORT. The ABORT status is returned if the user bumps out of the question * with a ^G. Used any time a confirmation is required. */ int mlyesno(char *prompt) { char c; /* input character */ char buf[NPAT]; /* prompt to user */ for (;;) { /* build and prompt the user */ strcpy(buf, prompt); strcat(buf, " (y/n)? "); mlwrite(buf); /* get the responce */ c = tgetc(); if (c == ectoc(abortc)) /* Bail out! */ return ABORT; if (c == 'y' || c == 'Y') return TRUE; if (c == 'n' || c == 'N') return FALSE; } } /* * Write a prompt into the message line, then read back a response. Keep * track of the physical position of the cursor. If we are in a keyboard * macro throw the prompt away, and return the remembered response. This * lets macros run at full speed. The reply is always terminated by a carriage * return. Handle erase, kill, and abort keys. */ int mlreply(char *prompt, char *buf, int nbuf) { return nextarg(prompt, buf, nbuf, ctoec('\n')); } int mlreplyt(char *prompt, char *buf, int nbuf, int eolchar) { return nextarg(prompt, buf, nbuf, eolchar); } /* * ectoc: * expanded character to character * collapse the CONTROL and SPEC flags back into an ascii code */ int ectoc(int c) { if (c & CONTROL) c = c & ~(CONTROL | 0x40); if (c & SPEC) c = c & 255; return c; } /* * ctoec: * character to extended character * pull out the CONTROL and SPEC prefixes (if possible) */ int ctoec(int c) { if (c >= 0x00 && c <= 0x1F) c = CONTROL | (c + '@'); return c; } /* * get a command name from the command line. Command completion means * that pressing a <SPACE> will attempt to complete an unfinished command * name if it is unique. */ fn_t getname(void) { int cpos; /* current column on screen output */ int c; char *sp; /* pointer to string for output */ struct name_bind *ffp; /* first ptr to entry in name binding table */ struct name_bind *cffp; /* current ptr to entry in name binding table */ struct name_bind *lffp; /* last ptr to entry in name binding table */ char buf[NSTRING]; /* buffer to hold tentative command name */ /* starting at the beginning of the string buffer */ cpos = 0; /* if we are executing a command line get the next arg and match it */ if (clexec) { if (macarg(buf) != TRUE) return NULL; return fncmatch(&buf[0]); } /* build a name string from the keyboard */ while (TRUE) { c = tgetc(); /* if we are at the end, just match it */ if (c == 0x0d) { buf[cpos] = 0; /* and match it off */ return fncmatch(&buf[0]); } else if (c == ectoc(abortc)) { /* Bell, abort */ ctrlg(FALSE, 0); TTflush(); return NULL; } else if (c == 0x7F || c == 0x08) { /* rubout/erase */ if (cpos != 0) { TTputc('\b'); TTputc(' '); TTputc('\b'); --ttcol; --cpos; TTflush(); } } else if (c == 0x15) { /* C-U, kill */ while (cpos != 0) { TTputc('\b'); TTputc(' '); TTputc('\b'); --cpos; --ttcol; } TTflush(); } else if (c == ' ' || c == 0x1b || c == 0x09) { /* <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< */ /* attempt a completion */ buf[cpos] = 0; /* terminate it for us */ ffp = &names[0]; /* scan for matches */ while (ffp->n_func != NULL) { if (strncmp(buf, ffp->n_name, strlen(buf)) == 0) { /* a possible match! More than one? */ if ((ffp + 1)->n_func == NULL || (strncmp (buf, (ffp + 1)->n_name, strlen(buf)) != 0)) { /* no...we match, print it */ sp = ffp->n_name + cpos; while (*sp) TTputc(*sp++); TTflush(); return ffp->n_func; } else { /* << << << << << << << << << << << << << << << << << */ /* try for a partial match against the list */ /* first scan down until we no longer match the current input */ lffp = (ffp + 1); while ((lffp + 1)->n_func != NULL) { if (strncmp (buf, (lffp + 1)->n_name, strlen(buf)) != 0) break; ++lffp; } /* and now, attempt to partial complete the string, char at a time */ while (TRUE) { /* add the next char in */ buf[cpos] = ffp-> n_name[cpos]; /* scan through the candidates */ cffp = ffp + 1; while (cffp <= lffp) { if (cffp-> n_name [cpos] != buf [cpos]) goto onward; ++cffp; } /* add the character */ TTputc(buf [cpos++]); } /* << << << << << << << << << << << << << << << << << */ } } ++ffp; } /* no match.....beep and onward */ TTbeep(); onward:; TTflush(); /* <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< */ } else { if (cpos < NSTRING - 1 && c > ' ') { buf[cpos++] = c; TTputc(c); } ++ttcol; TTflush(); } } } /* tgetc: Get a key from the terminal driver, resolve any keyboard macro action */ int tgetc(void) { int c; /* fetched character */ /* if we are playing a keyboard macro back, */ if (kbdmode == PLAY) { /* if there is some left... */ if (kbdptr < kbdend) return (int) *kbdptr++; /* at the end of last repitition? */ if (--kbdrep < 1) { kbdmode = STOP; #if VISMAC == 0 /* force a screen update after all is done */ update(FALSE); #endif } else { /* reset the macro to the begining for the next rep */ kbdptr = &kbdm[0]; return (int) *kbdptr++; } } /* fetch a character from the terminal driver */ c = TTgetc(); /* record it for $lastkey */ lastkey = c; /* save it if we need to */ if (kbdmode == RECORD) { *kbdptr++ = c; kbdend = kbdptr; /* don't overrun the buffer */ if (kbdptr == &kbdm[NKBDM - 1]) { kbdmode = STOP; TTbeep(); } } /* and finally give the char back */ return c; } /* GET1KEY: Get one keystroke. The only prefixs legal here are the SPEC and CONTROL prefixes. */ int get1key(void) { int c; /* get a keystroke */ c = tgetc(); #if MSDOS if (c == 0) { /* Apply SPEC prefix */ c = tgetc(); if (c >= 0x00 && c <= 0x1F) /* control key? */ c = CONTROL | (c + '@'); return SPEC | c; } #endif if (c >= 0x00 && c <= 0x1F) /* C0 control -> C- */ c = CONTROL | (c + '@'); return c; } /* GETCMD: Get a command from the keyboard. Process all applicable prefix keys */ int getcmd(void) { int c; /* fetched keystroke */ #if VT220 int d; /* second character P.K. */ int cmask = 0; #endif /* get initial character */ c = get1key(); #if VT220 proc_metac: #endif if (c == 128+27) /* CSI */ goto handle_CSI; /* process META prefix */ if (c == (CONTROL | '[')) { c = get1key(); #if VT220 if (c == '[' || c == 'O') { /* CSI P.K. */ handle_CSI: c = get1key(); if (c >= 'A' && c <= 'D') return SPEC | c | cmask; if (c >= 'E' && c <= 'z' && c != 'i' && c != 'c') return SPEC | c | cmask; d = get1key(); if (d == '~') /* ESC [ n ~ P.K. */ return SPEC | c | cmask; switch (c) { /* ESC [ n n ~ P.K. */ case '1': c = d + 32; break; case '2': c = d + 48; break; case '3': c = d + 64; break; default: c = '?'; break; } if (d != '~') /* eat tilde P.K. */ get1key(); if (c == 'i') { /* DO key P.K. */ c = ctlxc; goto proc_ctlxc; } else if (c == 'c') /* ESC key P.K. */ c = get1key(); else return SPEC | c | cmask; } #endif #if VT220 if (c == (CONTROL | '[')) { cmask = META; goto proc_metac; } #endif if (islower(c)) /* Force to upper */ c ^= DIFCASE; if (c >= 0x00 && c <= 0x1F) /* control key */ c = CONTROL | (c + '@'); return META | c; } #if PKCODE else if (c == metac) { c = get1key(); #if VT220 if (c == (CONTROL | '[')) { cmask = META; goto proc_metac; } #endif if (islower(c)) /* Force to upper */ c ^= DIFCASE; if (c >= 0x00 && c <= 0x1F) /* control key */ c = CONTROL | (c + '@'); return META | c; } #endif #if VT220 proc_ctlxc: #endif /* process CTLX prefix */ if (c == ctlxc) { c = get1key(); #if VT220 if (c == (CONTROL | '[')) { cmask = CTLX; goto proc_metac; } #endif if (c >= 'a' && c <= 'z') /* Force to upper */ c -= 0x20; if (c >= 0x00 && c <= 0x1F) /* control key */ c = CONTROL | (c + '@'); return CTLX | c; } /* otherwise, just return it */ return c; } /* A more generalized prompt/reply function allowing the caller to specify the proper terminator. If the terminator is not a return ('\n') it will echo as "<NL>" */ int getstring(char *prompt, char *buf, int nbuf, int eolchar) { int cpos; /* current character position in string */ int c; int quotef; /* are we quoting the next char? */ #if COMPLC int ffile, ocpos, nskip = 0, didtry = 0; #if MSDOS struct ffblk ffblk; char *fcp; #endif #if UNIX static char tmp[] = "/tmp/meXXXXXX"; FILE *tmpf = NULL; #endif ffile = (strcmp(prompt, "Find file: ") == 0 || strcmp(prompt, "View file: ") == 0 || strcmp(prompt, "Insert file: ") == 0 || strcmp(prompt, "Write file: ") == 0 || strcmp(prompt, "Read file: ") == 0 || strcmp(prompt, "File to execute: ") == 0); #endif cpos = 0; quotef = FALSE; /* prompt the user for the input string */ mlwrite(prompt); for (;;) { #if COMPLC if (!didtry) nskip = -1; didtry = 0; #endif /* get a character from the user */ c = get1key(); /* If it is a <ret>, change it to a <NL> */ #if PKCODE if (c == (CONTROL | 0x4d) && !quotef) #else if (c == (CONTROL | 0x4d)) #endif c = CONTROL | 0x40 | '\n'; /* if they hit the line terminate, wrap it up */ if (c == eolchar && quotef == FALSE) { buf[cpos++] = 0; /* clear the message line */ mlwrite(""); TTflush(); /* if we default the buffer, return FALSE */ if (buf[0] == 0) return FALSE; return TRUE; } /* change from command form back to character form */ c = ectoc(c); if (c == ectoc(abortc) && quotef == FALSE) { /* Abort the input? */ ctrlg(FALSE, 0); TTflush(); return ABORT; } else if ((c == 0x7F || c == 0x08) && quotef == FALSE) { /* rubout/erase */ if (cpos != 0) { outstring("\b \b"); --ttcol; if (buf[--cpos] < 0x20) { outstring("\b \b"); --ttcol; } if (buf[cpos] == '\n') { outstring("\b\b \b\b"); ttcol -= 2; } TTflush(); } } else if (c == 0x15 && quotef == FALSE) { /* C-U, kill */ while (cpos != 0) { outstring("\b \b"); --ttcol; if (buf[--cpos] < 0x20) { outstring("\b \b"); --ttcol; } if (buf[cpos] == '\n') { outstring("\b\b \b\b"); ttcol -= 2; } } TTflush(); #if COMPLC } else if ((c == 0x09 || c == ' ') && quotef == FALSE && ffile) { /* TAB, complete file name */ char ffbuf[255]; #if MSDOS char sffbuf[128]; int lsav = -1; #endif int n, iswild = 0; didtry = 1; ocpos = cpos; while (cpos != 0) { outstring("\b \b"); --ttcol; if (buf[--cpos] < 0x20) { outstring("\b \b"); --ttcol; } if (buf[cpos] == '\n') { outstring("\b\b \b\b"); ttcol -= 2; } if (buf[cpos] == '*' || buf[cpos] == '?') iswild = 1; #if MSDOS if (lsav < 0 && (buf[cpos] == '\\' || buf[cpos] == '/' || buf[cpos] == ':' && cpos == 1)) lsav = cpos; #endif } TTflush(); if (nskip < 0) { buf[ocpos] = 0; #if UNIX if (tmpf != NULL) fclose(tmpf); strcpy(tmp, "/tmp/meXXXXXX"); strcpy(ffbuf, "echo "); strcat(ffbuf, buf); if (!iswild) strcat(ffbuf, "*"); strcat(ffbuf, " >"); xmkstemp(tmp); strcat(ffbuf, tmp); strcat(ffbuf, " 2>&1"); system(ffbuf); tmpf = fopen(tmp, "r"); #endif #if MSDOS strcpy(sffbuf, buf); if (!iswild) strcat(sffbuf, "*.*"); #endif nskip = 0; } #if UNIX c = ' '; for (n = nskip; n > 0; n--) while ((c = getc(tmpf)) != EOF && c != ' '); #endif #if MSDOS if (nskip == 0) { strcpy(ffbuf, sffbuf); c = findfirst(ffbuf, &ffblk, FA_DIREC) ? '*' : ' '; } else if (nskip > 0) c = findnext(&ffblk) ? 0 : ' '; #endif nskip++; if (c != ' ') { TTbeep(); nskip = 0; } #if UNIX while ((c = getc(tmpf)) != EOF && c != '\n' && c != ' ' && c != '*') #endif #if MSDOS if (c == '*') fcp = sffbuf; else { strncpy(buf, sffbuf, lsav + 1); cpos = lsav + 1; fcp = ffblk.ff_name; } while (c != 0 && (c = *fcp++) != 0 && c != '*') #endif { if (cpos < nbuf - 1) buf[cpos++] = c; } #if UNIX if (c == '*') TTbeep(); #endif for (n = 0; n < cpos; n++) { c = buf[n]; if ((c < ' ') && (c != '\n')) { outstring("^"); ++ttcol; c ^= 0x40; } if (c != '\n') { if (disinp) TTputc(c); } else { /* put out <NL> for <ret> */ outstring("<NL>"); ttcol += 3; } ++ttcol; } TTflush(); #if UNIX rewind(tmpf); unlink(tmp); #endif #endif } else if ((c == quotec || c == 0x16) && quotef == FALSE) { quotef = TRUE; } else { quotef = FALSE; if (cpos < nbuf - 1) { buf[cpos++] = c; if ((c < ' ') && (c != '\n')) { outstring("^"); ++ttcol; c ^= 0x40; } if (c != '\n') { if (disinp) TTputc(c); } else { /* put out <NL> for <ret> */ outstring("<NL>"); ttcol += 3; } ++ttcol; TTflush(); } } } } /* * output a string of characters * * char *s; string to output */ void outstring(char *s) { if (disinp) while (*s) TTputc(*s++); } /* * output a string of output characters * * char *s; string to output */ void ostring(char *s) { if (discmd) while (*s) TTputc(*s++); }
uemacs-master
input.c
/* * main.c * uEmacs/PK 4.0 * * Based on: * * MicroEMACS 3.9 * Written by Dave G. Conroy. * Substantially modified by Daniel M. Lawrence * Modified by Petri Kutvonen * * MicroEMACS 3.9 (c) Copyright 1987 by Daniel M. Lawrence * * Original statement of copying policy: * * MicroEMACS 3.9 can be copied and distributed freely for any * non-commercial purposes. MicroEMACS 3.9 can only be incorporated * into commercial software with the permission of the current author. * * No copyright claimed for modifications made by Petri Kutvonen. * * This file contains the main driving routine, and some keyboard * processing code. * * REVISION HISTORY: * * 1.0 Steve Wilhite, 30-Nov-85 * * 2.0 George Jones, 12-Dec-85 * * 3.0 Daniel Lawrence, 29-Dec-85 * * 3.2-3.6 Daniel Lawrence, Feb...Apr-86 * * 3.7 Daniel Lawrence, 14-May-86 * * 3.8 Daniel Lawrence, 18-Jan-87 * * 3.9 Daniel Lawrence, 16-Jul-87 * * 3.9e Daniel Lawrence, 16-Nov-87 * * After that versions 3.X and Daniel Lawrence went their own ways. * A modified 3.9e/PK was heavily used at the University of Helsinki * for several years on different UNIX, VMS, and MSDOS platforms. * * This modified version is now called eEmacs/PK. * * 4.0 Petri Kutvonen, 1-Sep-91 * */ #include <stdio.h> /* Make global definitions not external. */ #define maindef #include "estruct.h" /* Global structures and defines. */ #include "edef.h" /* Global definitions. */ #include "efunc.h" /* Function declarations and name table. */ #include "ebind.h" /* Default key bindings. */ #include "version.h" /* For MSDOS, increase the default stack space. */ #if MSDOS & TURBO #if PKCODE extern unsigned _stklen = 20000; #else extern unsigned _stklen = 32766; #endif #endif #if VMS #include <ssdef.h> #define GOOD (SS$_NORMAL) #endif #ifndef GOOD #define GOOD 0 #endif #if UNIX #include <signal.h> static void emergencyexit(int); #ifdef SIGWINCH extern void sizesignal(int); #endif #endif void usage(int status) { printf("Usage: %s filename\n", PROGRAM_NAME); printf(" or: %s [options]\n\n", PROGRAM_NAME); fputs(" + start at the end of file\n", stdout); fputs(" +<n> start at line <n>\n", stdout); fputs(" -g[G]<n> go to line <n>\n", stdout); fputs(" --help display this help and exit\n", stdout); fputs(" --version output version information and exit\n", stdout); exit(status); } int main(int argc, char **argv) { int c = -1; /* command character */ int f; /* default flag */ int n; /* numeric repeat count */ int mflag; /* negative flag on repeat */ struct buffer *bp; /* temp buffer pointer */ int firstfile; /* first file flag */ int carg; /* current arg to scan */ int startflag; /* startup executed flag */ struct buffer *firstbp = NULL; /* ptr to first buffer in cmd line */ int basec; /* c stripped of meta character */ int viewflag; /* are we starting in view mode? */ int gotoflag; /* do we need to goto a line at start? */ int gline = 0; /* if so, what line? */ int searchflag; /* Do we need to search at start? */ int saveflag; /* temp store for lastflag */ int errflag; /* C error processing? */ char bname[NBUFN]; /* buffer name of file to read */ #if CRYPT int cryptflag; /* encrypting on the way in? */ char ekey[NPAT]; /* startup encryption key */ #endif int newc; #if PKCODE & VMS (void) umask(-1); /* Use old protection (this is at wrong place). */ #endif #if PKCODE & BSD sleep(1); /* Time for window manager. */ #endif #if UNIX #ifdef SIGWINCH signal(SIGWINCH, sizesignal); #endif #endif if (argc == 2) { if (strcmp(argv[1], "--help") == 0) { usage(EXIT_FAILURE); } if (strcmp(argv[1], "--version") == 0) { version(); exit(EXIT_SUCCESS); } } /* Initialize the editor. */ vtinit(); /* Display */ edinit("main"); /* Buffers, windows */ varinit(); /* user variables */ viewflag = FALSE; /* view mode defaults off in command line */ gotoflag = FALSE; /* set to off to begin with */ searchflag = FALSE; /* set to off to begin with */ firstfile = TRUE; /* no file to edit yet */ startflag = FALSE; /* startup file not executed yet */ errflag = FALSE; /* not doing C error parsing */ #if CRYPT cryptflag = FALSE; /* no encryption by default */ #endif /* Parse the command line */ for (carg = 1; carg < argc; ++carg) { /* Process Switches */ #if PKCODE if (argv[carg][0] == '+') { gotoflag = TRUE; gline = atoi(&argv[carg][1]); } else #endif if (argv[carg][0] == '-') { switch (argv[carg][1]) { /* Process Startup macroes */ case 'a': /* process error file */ case 'A': errflag = TRUE; break; case 'e': /* -e for Edit file */ case 'E': viewflag = FALSE; break; case 'g': /* -g for initial goto */ case 'G': gotoflag = TRUE; gline = atoi(&argv[carg][2]); break; #if CRYPT case 'k': /* -k<key> for code key */ case 'K': cryptflag = TRUE; strcpy(ekey, &argv[carg][2]); break; #endif #if PKCODE case 'n': /* -n accept null chars */ case 'N': nullflag = TRUE; break; #endif case 'r': /* -r restrictive use */ case 'R': restflag = TRUE; break; case 's': /* -s for initial search string */ case 'S': searchflag = TRUE; strncpy(pat, &argv[carg][2], NPAT); break; case 'v': /* -v for View File */ case 'V': viewflag = TRUE; break; default: /* unknown switch */ /* ignore this for now */ break; } } else if (argv[carg][0] == '@') { /* Process Startup macroes */ if (startup(&argv[carg][1]) == TRUE) /* don't execute emacs.rc */ startflag = TRUE; } else { /* Process an input file */ /* set up a buffer for this file */ makename(bname, argv[carg]); unqname(bname); /* set this to inactive */ bp = bfind(bname, TRUE, 0); strcpy(bp->b_fname, argv[carg]); bp->b_active = FALSE; if (firstfile) { firstbp = bp; firstfile = FALSE; } /* set the modes appropriatly */ if (viewflag) bp->b_mode |= MDVIEW; #if CRYPT if (cryptflag) { bp->b_mode |= MDCRYPT; myencrypt((char *) NULL, 0); myencrypt(ekey, strlen(ekey)); strncpy(bp->b_key, ekey, NPAT); } #endif } } #if UNIX signal(SIGHUP, emergencyexit); signal(SIGTERM, emergencyexit); #endif /* if we are C error parsing... run it! */ if (errflag) { if (startup("error.cmd") == TRUE) startflag = TRUE; } /* if invoked with no other startup files, run the system startup file here */ if (startflag == FALSE) { startup(""); startflag = TRUE; } discmd = TRUE; /* P.K. */ /* if there are any files to read, read the first one! */ bp = bfind("main", FALSE, 0); if (firstfile == FALSE && (gflags & GFREAD)) { swbuffer(firstbp); zotbuf(bp); } else bp->b_mode |= gmode; /* Deal with startup gotos and searches */ if (gotoflag && searchflag) { update(FALSE); mlwrite("(Can not search and goto at the same time!)"); } else if (gotoflag) { if (gotoline(TRUE, gline) == FALSE) { update(FALSE); mlwrite("(Bogus goto argument)"); } } else if (searchflag) { if (forwhunt(FALSE, 0) == FALSE) update(FALSE); } /* Setup to process commands. */ lastflag = 0; /* Fake last flags. */ loop: /* Execute the "command" macro...normally null. */ saveflag = lastflag; /* Preserve lastflag through this. */ execute(META | SPEC | 'C', FALSE, 1); lastflag = saveflag; #if TYPEAH && PKCODE if (typahead()) { newc = getcmd(); update(FALSE); do { fn_t execfunc; if (c == newc && (execfunc = getbind(c)) != NULL && execfunc != insert_newline && execfunc != insert_tab) newc = getcmd(); else break; } while (typahead()); c = newc; } else { update(FALSE); c = getcmd(); } #else /* Fix up the screen */ update(FALSE); /* get the next command from the keyboard */ c = getcmd(); #endif /* if there is something on the command line, clear it */ if (mpresf != FALSE) { mlerase(); update(FALSE); #if CLRMSG if (c == ' ') /* ITS EMACS does this */ goto loop; #endif } f = FALSE; n = 1; /* do META-# processing if needed */ basec = c & ~META; /* strip meta char off if there */ if ((c & META) && ((basec >= '0' && basec <= '9') || basec == '-')) { f = TRUE; /* there is a # arg */ n = 0; /* start with a zero default */ mflag = 1; /* current minus flag */ c = basec; /* strip the META */ while ((c >= '0' && c <= '9') || (c == '-')) { if (c == '-') { /* already hit a minus or digit? */ if ((mflag == -1) || (n != 0)) break; mflag = -1; } else { n = n * 10 + (c - '0'); } if ((n == 0) && (mflag == -1)) /* lonely - */ mlwrite("Arg:"); else mlwrite("Arg: %d", n * mflag); c = getcmd(); /* get the next key */ } n = n * mflag; /* figure in the sign */ } /* do ^U repeat argument processing */ if (c == reptc) { /* ^U, start argument */ f = TRUE; n = 4; /* with argument of 4 */ mflag = 0; /* that can be discarded. */ mlwrite("Arg: 4"); while (((c = getcmd()) >= '0' && c <= '9') || c == reptc || c == '-') { if (c == reptc) if ((n > 0) == ((n * 4) > 0)) n = n * 4; else n = 1; /* * If dash, and start of argument string, set arg. * to -1. Otherwise, insert it. */ else if (c == '-') { if (mflag) break; n = 0; mflag = -1; } /* * If first digit entered, replace previous argument * with digit and set sign. Otherwise, append to arg. */ else { if (!mflag) { n = 0; mflag = 1; } n = 10 * n + c - '0'; } mlwrite("Arg: %d", (mflag >= 0) ? n : (n ? -n : -1)); } /* * Make arguments preceded by a minus sign negative and change * the special argument "^U -" to an effective "^U -1". */ if (mflag == -1) { if (n == 0) n++; n = -n; } } /* and execute the command */ execute(c, f, n); goto loop; } /* * Initialize all of the buffers and windows. The buffer name is passed down * as an argument, because the main routine may have been told to read in a * file by default, and we want the buffer name to be right. */ void edinit(char *bname) { struct buffer *bp; struct window *wp; bp = bfind(bname, TRUE, 0); /* First buffer */ blistp = bfind("*List*", TRUE, BFINVS); /* Buffer list buffer */ wp = (struct window *)malloc(sizeof(struct window)); /* First window */ if (bp == NULL || wp == NULL || blistp == NULL) exit(1); curbp = bp; /* Make this current */ wheadp = wp; curwp = wp; wp->w_wndp = NULL; /* Initialize window */ wp->w_bufp = bp; bp->b_nwnd = 1; /* Displayed. */ wp->w_linep = bp->b_linep; wp->w_dotp = bp->b_linep; wp->w_doto = 0; wp->w_markp = NULL; wp->w_marko = 0; wp->w_toprow = 0; #if COLOR /* initalize colors to global defaults */ wp->w_fcolor = gfcolor; wp->w_bcolor = gbcolor; #endif wp->w_ntrows = term.t_nrow - 1; /* "-1" for mode line. */ wp->w_force = 0; wp->w_flag = WFMODE | WFHARD; /* Full. */ } /* * This is the general command execution routine. It handles the fake binding * of all the keys to "self-insert". It also clears out the "thisflag" word, * and arranges to move it to the "lastflag", so that the next command can * look at it. Return the status of command. */ int execute(int c, int f, int n) { int status; fn_t execfunc; /* if the keystroke is a bound function...do it */ execfunc = getbind(c); if (execfunc != NULL) { thisflag = 0; status = (*execfunc) (f, n); lastflag = thisflag; return status; } /* * If a space was typed, fill column is defined, the argument is non- * negative, wrap mode is enabled, and we are now past fill column, * and we are not read-only, perform word wrap. */ if (c == ' ' && (curwp->w_bufp->b_mode & MDWRAP) && fillcol > 0 && n >= 0 && getccol(FALSE) > fillcol && (curwp->w_bufp->b_mode & MDVIEW) == FALSE) execute(META | SPEC | 'W', FALSE, 1); #if PKCODE if ((c >= 0x20 && c <= 0x7E) /* Self inserting. */ #if IBMPC || (c >= 0x80 && c <= 0xFE)) { #else #if VMS || BSD || USG /* 8BIT P.K. */ || (c >= 0xA0 && c <= 0x10FFFF)) { #else ) { #endif #endif #else if ((c >= 0x20 && c <= 0xFF)) { /* Self inserting. */ #endif if (n <= 0) { /* Fenceposts. */ lastflag = 0; return n < 0 ? FALSE : TRUE; } thisflag = 0; /* For the future. */ /* if we are in overwrite mode, not at eol, and next char is not a tab or we are at a tab stop, delete a char forword */ if (curwp->w_bufp->b_mode & MDOVER && curwp->w_doto < curwp->w_dotp->l_used && (lgetc(curwp->w_dotp, curwp->w_doto) != '\t' || (curwp->w_doto) % 8 == 7)) ldelchar(1, FALSE); /* do the appropriate insertion */ if (c == '}' && (curbp->b_mode & MDCMOD) != 0) status = insbrace(n, c); else if (c == '#' && (curbp->b_mode & MDCMOD) != 0) status = inspound(); else status = linsert(n, c); #if CFENCE /* check for CMODE fence matching */ if ((c == '}' || c == ')' || c == ']') && (curbp->b_mode & MDCMOD) != 0) fmatch(c); #endif /* check auto-save mode */ if (curbp->b_mode & MDASAVE) if (--gacount == 0) { /* and save the file if needed */ upscreen(FALSE, 0); filesave(FALSE, 0); gacount = gasave; } lastflag = thisflag; return status; } TTbeep(); mlwrite("(Key not bound)"); /* complain */ lastflag = 0; /* Fake last flags. */ return FALSE; } /* * Fancy quit command, as implemented by Norm. If the any buffer has * changed do a write on that buffer and exit emacs, otherwise simply exit. */ int quickexit(int f, int n) { struct buffer *bp; /* scanning pointer to buffers */ struct buffer *oldcb; /* original current buffer */ int status; oldcb = curbp; /* save in case we fail */ bp = bheadp; while (bp != NULL) { if ((bp->b_flag & BFCHG) != 0 /* Changed. */ && (bp->b_flag & BFTRUNC) == 0 /* Not truncated P.K. */ && (bp->b_flag & BFINVS) == 0) { /* Real. */ curbp = bp; /* make that buffer cur */ mlwrite("(Saving %s)", bp->b_fname); #if PKCODE #else mlwrite("\n"); #endif if ((status = filesave(f, n)) != TRUE) { curbp = oldcb; /* restore curbp */ return status; } } bp = bp->b_bufp; /* on to the next buffer */ } quit(f, n); /* conditionally quit */ return TRUE; } static void emergencyexit(int signr) { quickexit(FALSE, 0); quit(TRUE, 0); } /* * Quit command. If an argument, always quit. Otherwise confirm if a buffer * has been changed and not written out. Normally bound to "C-X C-C". */ int quit(int f, int n) { int s; if (f != FALSE /* Argument forces it. */ || anycb() == FALSE /* All buffers clean. */ /* User says it's OK. */ || (s = mlyesno("Modified buffers exist. Leave anyway")) == TRUE) { #if (FILOCK && BSD) || SVR4 if (lockrel() != TRUE) { TTputc('\n'); TTputc('\r'); TTclose(); TTkclose(); exit(1); } #endif vttidy(); if (f) exit(n); else exit(GOOD); } mlwrite(""); return s; } /* * Begin a keyboard macro. * Error if not at the top level in keyboard processing. Set up variables and * return. */ int ctlxlp(int f, int n) { if (kbdmode != STOP) { mlwrite("%%Macro already active"); return FALSE; } mlwrite("(Start macro)"); kbdptr = &kbdm[0]; kbdend = kbdptr; kbdmode = RECORD; return TRUE; } /* * End keyboard macro. Check for the same limit conditions as the above * routine. Set up the variables and return to the caller. */ int ctlxrp(int f, int n) { if (kbdmode == STOP) { mlwrite("%%Macro not active"); return FALSE; } if (kbdmode == RECORD) { mlwrite("(End macro)"); kbdmode = STOP; } return TRUE; } /* * Execute a macro. * The command argument is the number of times to loop. Quit as soon as a * command gets an error. Return TRUE if all ok, else FALSE. */ int ctlxe(int f, int n) { if (kbdmode != STOP) { mlwrite("%%Macro already active"); return FALSE; } if (n <= 0) return TRUE; kbdrep = n; /* remember how many times to execute */ kbdmode = PLAY; /* start us in play mode */ kbdptr = &kbdm[0]; /* at the beginning */ return TRUE; } /* * Abort. * Beep the beeper. Kill off any keyboard macro, etc., that is in progress. * Sometimes called as a routine, to do general aborting of stuff. */ int ctrlg(int f, int n) { TTbeep(); kbdmode = STOP; mlwrite("(Aborted)"); return ABORT; } /* * tell the user that this command is illegal while we are in * VIEW (read-only) mode */ int rdonly(void) { TTbeep(); mlwrite("(Key illegal in VIEW mode)"); return FALSE; } int resterr(void) { TTbeep(); mlwrite("(That command is RESTRICTED)"); return FALSE; } /* user function that does NOTHING */ int nullproc(int f, int n) { return TRUE; } /* dummy function for binding to meta prefix */ int metafn(int f, int n) { return TRUE; } /* dummy function for binding to control-x prefix */ int cex(int f, int n) { return TRUE; } /* dummy function for binding to universal-argument */ int unarg(int f, int n) { return TRUE; } /***** Compiler specific Library functions ****/ #if RAMSIZE /* These routines will allow me to track memory usage by placing a layer on top of the standard system malloc() and free() calls. with this code defined, the environment variable, $RAM, will report on the number of bytes allocated via malloc. with SHOWRAM defined, the number is also posted on the end of the bottom mode line and is updated whenever it is changed. */ #undef malloc #undef free char *allocate(nbytes) /* allocate nbytes and track */ unsigned nbytes; /* # of bytes to allocate */ { char *mp; /* ptr returned from malloc */ char *malloc(); mp = malloc(nbytes); if (mp) { envram += nbytes; #if RAMSHOW dspram(); #endif } return mp; } release(mp) /* release malloced memory and track */ char *mp; /* chunk of RAM to release */ { unsigned *lp; /* ptr to the long containing the block size */ if (mp) { /* update amount of ram currently malloced */ lp = ((unsigned *) mp) - 1; envram -= (long) *lp - 2; free(mp); #if RAMSHOW dspram(); #endif } } #if RAMSHOW dspram() { /* display the amount of RAM currently malloced */ char mbuf[20]; char *sp; TTmove(term.t_nrow - 1, 70); #if COLOR TTforg(7); TTbacg(0); #endif sprintf(mbuf, "[%lu]", envram); sp = &mbuf[0]; while (*sp) TTputc(*sp++); TTmove(term.t_nrow, 0); movecursor(term.t_nrow, 0); } #endif #endif /* On some primitave operation systems, and when emacs is used as a subprogram to a larger project, emacs needs to de-alloc its own used memory */ #if CLEAN /* * cexit() * * int status; return status of emacs */ int cexit(int status) { struct buffer *bp; /* buffer list pointer */ struct window *wp; /* window list pointer */ struct window *tp; /* temporary window pointer */ /* first clean up the windows */ wp = wheadp; while (wp) { tp = wp->w_wndp; free(wp); wp = tp; } wheadp = NULL; /* then the buffers */ bp = bheadp; while (bp) { bp->b_nwnd = 0; bp->b_flag = 0; /* don't say anything about a changed buffer! */ zotbuf(bp); bp = bheadp; } /* and the kill buffer */ kdelete(); /* and the video buffers */ vtfree(); #undef exit exit(status); } #endif
uemacs-master
main.c
/* ibmpc.c * * The routines in this file provide support for the IBM-PC and other * compatible terminals. It goes directly to the graphics RAM to do * screen output. It compiles into nothing if not an IBM-PC driver * Supported monitor cards include CGA, MONO and EGA. * * modified by Petri Kutvonen */ #define termdef 1 /* don't define "term" external */ #include <stdio.h> #include "estruct.h" #include "edef.h" #if IBMPC #if PKCODE #define NROW 50 #else #define NROW 43 /* Max Screen size. */ #endif #define NCOL 80 /* Edit if you want to. */ #define MARGIN 8 /* size of minimim margin and */ #define SCRSIZ 64 /* scroll size for extended lines */ #define NPAUSE 200 /* # times thru update to pause */ #define BEL 0x07 /* BEL character. */ #define ESC 0x1B /* ESC character. */ #define SPACE 32 /* space character */ #define SCADC 0xb8000000L /* CGA address of screen RAM */ #define SCADM 0xb0000000L /* MONO address of screen RAM */ #define SCADE 0xb8000000L /* EGA address of screen RAM */ #define MONOCRSR 0x0B0D /* monochrome cursor */ #define CGACRSR 0x0607 /* CGA cursor */ #define EGACRSR 0x0709 /* EGA cursor */ #define CDCGA 0 /* color graphics card */ #define CDMONO 1 /* monochrome text card */ #define CDEGA 2 /* EGA color adapter */ #if PKCODE #define CDVGA 3 #endif #define CDSENSE 9 /* detect the card type */ #if PKCODE #define NDRIVE 4 #else #define NDRIVE 3 /* number of screen drivers */ #endif int dtype = -1; /* current display type */ char drvname[][8] = { /* screen resolution names */ "CGA", "MONO", "EGA" #if PKCODE , "VGA" #endif }; long scadd; /* address of screen ram */ int *scptr[NROW]; /* pointer to screen lines */ unsigned int sline[NCOL]; /* screen line image */ int egaexist = FALSE; /* is an EGA card available? */ extern union REGS rg; /* cpu register for use of DOS calls */ extern int ttopen(); /* Forward references. */ extern int ttgetc(); extern int ttputc(); extern int ttflush(); extern int ttclose(); extern int ibmmove(); extern int ibmeeol(); extern int ibmeeop(); extern int ibmbeep(); extern int ibmopen(); extern int ibmrev(); extern int ibmcres(); extern int ibmclose(); extern int ibmputc(); extern int ibmkopen(); extern int ibmkclose(); #if COLOR extern int ibmfcol(); extern int ibmbcol(); extern int ibmscroll_reg(); int cfcolor = -1; /* current forground color */ int cbcolor = -1; /* current background color */ int ctrans[] = /* ansi to ibm color translation table */ #if PKCODE { 0, 4, 2, 6, 1, 5, 3, 7, 15 }; #else { 0, 4, 2, 6, 1, 5, 3, 7 }; #endif #endif /* * Standard terminal interface dispatch table. Most of the fields point into * "termio" code. */ struct terminal term = { NROW - 1, NROW - 1, NCOL, NCOL, MARGIN, SCRSIZ, NPAUSE, ibmopen, ibmclose, ibmkopen, ibmkclose, ttgetc, ibmputc, ttflush, ibmmove, ibmeeol, ibmeeop, ibmbeep, ibmrev, ibmcres #if COLOR , ibmfcol, ibmbcol #endif #if SCROLLCODE , ibmscroll_reg #endif }; #if COLOR /* Set the current output color. * * @color: color to set. */ void ibmfcol(int color) { cfcolor = ctrans[color]; } /* Set the current background color. * * @color: color to set. */ void ibmbcol(int color) { cbcolor = ctrans[color]; } #endif void ibmmove(int row, int col) { rg.h.ah = 2; /* set cursor position function code */ rg.h.dl = col; rg.h.dh = row; rg.h.bh = 0; /* set screen page number */ int86(0x10, &rg, &rg); } void ibmeeol(void) { /* erase to the end of the line */ unsigned int attr; /* attribute byte mask to place in RAM */ unsigned int *lnptr; /* pointer to the destination line */ int i; int ccol; /* current column cursor lives */ int crow; /* row */ /* find the current cursor position */ rg.h.ah = 3; /* read cursor position function code */ rg.h.bh = 0; /* current video page */ int86(0x10, &rg, &rg); ccol = rg.h.dl; /* record current column */ crow = rg.h.dh; /* and row */ /* build the attribute byte and setup the screen pointer */ #if COLOR if (dtype != CDMONO) attr = (((cbcolor & 15) << 4) | (cfcolor & 15)) << 8; else attr = 0x0700; #else attr = 0x0700; #endif lnptr = &sline[0]; for (i = 0; i < term.t_ncol; i++) *lnptr++ = SPACE | attr; if (flickcode && (dtype == CDCGA)) { /* wait for vertical retrace to be off */ while ((inp(0x3da) & 8)); /* and to be back on */ while ((inp(0x3da) & 8) == 0); } /* and send the string out */ movmem(&sline[0], scptr[crow] + ccol, (term.t_ncol - ccol) * 2); } /* Put a character at the current position in the current colors */ void ibmputc(int ch) { rg.h.ah = 14; /* write char to screen with current attrs */ rg.h.al = ch; #if COLOR if (dtype != CDMONO) rg.h.bl = cfcolor; else rg.h.bl = 0x07; #else rg.h.bl = 0x07; #endif int86(0x10, &rg, &rg); } void ibmeeop(void) { int attr; /* attribute to fill screen with */ rg.h.ah = 6; /* scroll page up function code */ rg.h.al = 0; /* # lines to scroll (clear it) */ rg.x.cx = 0; /* upper left corner of scroll */ rg.x.dx = (term.t_nrow << 8) | (term.t_ncol - 1); /* lower right corner of scroll */ #if COLOR if (dtype != CDMONO) attr = ((ctrans[gbcolor] & 15) << 4) | (ctrans[gfcolor] & 15); else attr = 0; #else attr = 0; #endif rg.h.bh = attr; int86(0x10, &rg, &rg); } /* Change reverse video state. * * @state: TRUE = reverse, FALSE = normal. */ void ibmrev(int state) { /* This never gets used under the IBM-PC driver */ } /* Change screen resolution. * * @res: resolution to change to. */ void ibmcres(char *res) { int i; for (i = 0; i < NDRIVE; i++) { if (strcmp(res, drvname[i]) == 0) { scinit(i); return TRUE; } } return FALSE; } #if SCROLLCODE /* Move howmany lines starting at from to to. */ void ibmscroll_reg(from, to, howmany) { int i; if (to < from) { for (i = 0; i < howmany; i++) { movmem(scptr[from + i], scptr[to + i], term.t_ncol * 2); } } else if (to > from) { for (i = howmany - 1; i >= 0; i--) { movmem(scptr[from + i], scptr[to + i], term.t_ncol * 2); } } } #endif void ibmbeep(void) { bdos(6, BEL, 0); } void ibmopen(void) { scinit(CDSENSE); revexist = TRUE; ttopen(); } void ibmclose(void) { #if COLOR ibmfcol(7); ibmbcol(0); #endif /* if we had the EGA open... close it */ if (dtype == CDEGA) egaclose(); #if PKCODE if (dtype == CDVGA) egaclose(); #endif ttclose(); } /* Open the keyboard. */ void ibmkopen(void) { } /* Close the keyboard. */ void ibmkclose(void) { } /* Initialize the screen head pointers. * * @type: type of adapter to init for. */ static int scinit(int type) { union { long laddr; /* long form of address */ int *paddr; /* pointer form of address */ } addr; int i; /* if asked...find out what display is connected */ if (type == CDSENSE) type = getboard(); /* if we have nothing to do....don't do it */ if (dtype == type) return TRUE; /* if we try to switch to EGA and there is none, don't */ if (type == CDEGA && egaexist != TRUE) return FALSE; /* if we had the EGA open... close it */ if (dtype == CDEGA) egaclose(); #if PKCODE if (dtype == CDVGA) egaclose(); #endif /* and set up the various parameters as needed */ switch (type) { case CDMONO: /* Monochrome adapter */ scadd = SCADM; newsize(TRUE, 25); break; case CDCGA: /* Color graphics adapter */ scadd = SCADC; newsize(TRUE, 25); break; case CDEGA: /* Enhanced graphics adapter */ scadd = SCADE; egaopen(); newsize(TRUE, 43); break; case CDVGA: /* Enhanced graphics adapter */ scadd = SCADE; egaopen(); newsize(TRUE, 50); break; } /* reset the $sres environment variable */ strcpy(sres, drvname[type]); dtype = type; /* initialize the screen pointer array */ for (i = 0; i < NROW; i++) { addr.laddr = scadd + (long) (NCOL * i * 2); scptr[i] = addr.paddr; } return TRUE; } /* getboard: Determine which type of display board is attached. Current known types include: CDMONO Monochrome graphics adapter CDCGA Color Graphics Adapter CDEGA Extended graphics Adapter */ /* getboard: Detect the current display adapter if MONO set to MONO CGA set to CGA EGAexist = FALSE EGA set to CGA EGAexist = TRUE */ int getboard(void) { int type; /* board type to return */ type = CDCGA; int86(0x11, &rg, &rg); if ((((rg.x.ax >> 4) & 3) == 3)) type = CDMONO; /* test if EGA present */ rg.x.ax = 0x1200; rg.x.bx = 0xff10; int86(0x10, &rg, &rg); /* If EGA, bh=0-1 and bl=0-3 */ egaexist = !(rg.x.bx & 0xfefc); /* Yes, it's EGA */ return type; } /* init the computer to work with the EGA */ void egaopen(void) { /* put the beast into EGA 43 row mode */ rg.x.ax = 3; int86(16, &rg, &rg); rg.h.ah = 17; /* set char. generator function code */ rg.h.al = 18; /* to 8 by 8 double dot ROM */ rg.h.bl = 0; /* block 0 */ int86(16, &rg, &rg); rg.h.ah = 18; /* alternate select function code */ rg.h.al = 0; /* clear AL for no good reason */ rg.h.bl = 32; /* alt. print screen routine */ int86(16, &rg, &rg); rg.h.ah = 1; /* set cursor size function code */ rg.x.cx = 0x0607; /* turn cursor on code */ int86(0x10, &rg, &rg); outp(0x3d4, 10); /* video bios bug patch */ outp(0x3d5, 6); } void egaclose(void) { /* put the beast into 80 column mode */ rg.x.ax = 3; int86(16, &rg, &rg); } /* Write a line out. * * @row: row of screen to place outstr on. * @outstr: string to write out (must be term.t_ncol long). * @forg: forground color of string to write. * @bacg: background color. */ void scwrite(int row, char *outstr, int forg, int bacg) { unsigned int attr; /* attribute byte mask to place in RAM */ unsigned int *lnptr; /* pointer to the destination line */ int i; /* build the attribute byte and setup the screen pointer */ #if COLOR if (dtype != CDMONO) attr = (((ctrans[bacg] & 15) << 4) | (ctrans[forg] & 15)) << 8; else attr = (((bacg & 15) << 4) | (forg & 15)) << 8; #else attr = (((bacg & 15) << 4) | (forg & 15)) << 8; #endif lnptr = &sline[0]; for (i = 0; i < term.t_ncol; i++) *lnptr++ = (outstr[i] & 255) | attr; if (flickcode && (dtype == CDCGA)) { /* wait for vertical retrace to be off */ while ((inp(0x3da) & 8)); /* and to be back on */ while ((inp(0x3da) & 8) == 0); } /* and send the string out */ movmem(&sline[0], scptr[row], term.t_ncol * 2); } #endif
uemacs-master
ibmpc.c
/* tcap.c * * Unix V7 SysV and BS4 Termcap video driver * * modified by Petri Kutvonen */ /* * Defining this to 1 breaks tcapopen() - it doesn't check if the * sceen size has changed. * -lbt */ #define USE_BROKEN_OPTIMIZATION 0 #define termdef 1 /* Don't define "term" external. */ #include <curses.h> #include <stdio.h> #include <term.h> #include "estruct.h" #include "edef.h" #include "efunc.h" #if TERMCAP #if UNIX #include <signal.h> #endif #define MARGIN 8 #define SCRSIZ 64 #define NPAUSE 10 /* # times thru update to pause. */ #define BEL 0x07 #define ESC 0x1B static void tcapkopen(void); static void tcapkclose(void); static void tcapmove(int, int); static void tcapeeol(void); static void tcapeeop(void); static void tcapbeep(void); static void tcaprev(int); static int tcapcres(char *); static void tcapscrollregion(int top, int bot); static void putpad(char *str); static void tcapopen(void); #if PKCODE static void tcapclose(void); #endif #if COLOR static void tcapfcol(void); static void tcapbcol(void); #endif #if SCROLLCODE static void tcapscroll_reg(int from, int to, int linestoscroll); static void tcapscroll_delins(int from, int to, int linestoscroll); #endif #define TCAPSLEN 315 static char tcapbuf[TCAPSLEN]; static char *UP, PC, *CM, *CE, *CL, *SO, *SE; #if PKCODE static char *TI, *TE; #if USE_BROKEN_OPTIMIZATION static int term_init_ok = 0; #endif #endif #if SCROLLCODE static char *CS, *DL, *AL, *SF, *SR; #endif struct terminal term = { 0, /* These four values are set dynamically at open time. */ 0, 0, 0, MARGIN, SCRSIZ, NPAUSE, tcapopen, #if PKCODE tcapclose, #else ttclose, #endif tcapkopen, tcapkclose, ttgetc, ttputc, ttflush, tcapmove, tcapeeol, tcapeeop, tcapbeep, tcaprev, tcapcres #if COLOR , tcapfcol, tcapbcol #endif #if SCROLLCODE , NULL /* set dynamically at open time */ #endif }; static void tcapopen(void) { char *t, *p; char tcbuf[1024]; char *tv_stype; char err_str[72]; int int_col, int_row; #if PKCODE && USE_BROKEN_OPTIMIZATION if (!term_init_ok) { #endif if ((tv_stype = getenv("TERM")) == NULL) { puts("Environment variable TERM not defined!"); exit(1); } if ((tgetent(tcbuf, tv_stype)) != 1) { sprintf(err_str, "Unknown terminal type %s!", tv_stype); puts(err_str); exit(1); } /* Get screen size from system, or else from termcap. */ getscreensize(&int_col, &int_row); term.t_nrow = int_row - 1; term.t_ncol = int_col; if ((term.t_nrow <= 0) && (term.t_nrow = (short) tgetnum("li") - 1) == -1) { puts("termcap entry incomplete (lines)"); exit(1); } if ((term.t_ncol <= 0) && (term.t_ncol = (short) tgetnum("co")) == -1) { puts("Termcap entry incomplete (columns)"); exit(1); } #ifdef SIGWINCH term.t_mrow = MAXROW; term.t_mcol = MAXCOL; #else term.t_mrow = term.t_nrow > MAXROW ? MAXROW : term.t_nrow; term.t_mcol = term.t_ncol > MAXCOL ? MAXCOL : term.t_ncol; #endif p = tcapbuf; t = tgetstr("pc", &p); if (t) PC = *t; else PC = 0; CL = tgetstr("cl", &p); CM = tgetstr("cm", &p); CE = tgetstr("ce", &p); UP = tgetstr("up", &p); SE = tgetstr("se", &p); SO = tgetstr("so", &p); if (SO != NULL) revexist = TRUE; #if PKCODE if (tgetnum("sg") > 0) { /* can reverse be used? P.K. */ revexist = FALSE; SE = NULL; SO = NULL; } TI = tgetstr("ti", &p); /* terminal init and exit */ TE = tgetstr("te", &p); #endif if (CL == NULL || CM == NULL || UP == NULL) { puts("Incomplete termcap entry\n"); exit(1); } if (CE == NULL) /* will we be able to use clear to EOL? */ eolexist = FALSE; #if SCROLLCODE CS = tgetstr("cs", &p); SF = tgetstr("sf", &p); SR = tgetstr("sr", &p); DL = tgetstr("dl", &p); AL = tgetstr("al", &p); if (CS && SR) { if (SF == NULL) /* assume '\n' scrolls forward */ SF = "\n"; term.t_scroll = tcapscroll_reg; } else if (DL && AL) { term.t_scroll = tcapscroll_delins; } else { term.t_scroll = NULL; } #endif if (p >= &tcapbuf[TCAPSLEN]) { puts("Terminal description too big!\n"); exit(1); } #if PKCODE && USE_BROKEN_OPTIMIZATION term_init_ok = 1; } #endif ttopen(); } #if PKCODE static void tcapclose(void) { putpad(tgoto(CM, 0, term.t_nrow)); putpad(TE); ttflush(); ttclose(); } #endif static void tcapkopen(void) { #if PKCODE putpad(TI); ttflush(); ttrow = 999; ttcol = 999; sgarbf = TRUE; #endif strcpy(sres, "NORMAL"); } static void tcapkclose(void) { #if PKCODE putpad(TE); ttflush(); #endif } static void tcapmove(int row, int col) { putpad(tgoto(CM, col, row)); } static void tcapeeol(void) { putpad(CE); } static void tcapeeop(void) { putpad(CL); } /* * Change reverse video status * * @state: FALSE = normal video, TRUE = reverse video. */ static void tcaprev(int state) { if (state) { if (SO != NULL) putpad(SO); } else if (SE != NULL) putpad(SE); } /* Change screen resolution. */ static int tcapcres(char *res) { return TRUE; } #if SCROLLCODE /* move howmanylines lines starting at from to to */ static void tcapscroll_reg(int from, int to, int howmanylines) { int i; if (to == from) return; if (to < from) { tcapscrollregion(to, from + howmanylines - 1); tcapmove(from + howmanylines - 1, 0); for (i = from - to; i > 0; i--) putpad(SF); } else { /* from < to */ tcapscrollregion(from, to + howmanylines - 1); tcapmove(from, 0); for (i = to - from; i > 0; i--) putpad(SR); } tcapscrollregion(0, term.t_nrow); } /* move howmanylines lines starting at from to to */ static void tcapscroll_delins(int from, int to, int howmanylines) { int i; if (to == from) return; if (to < from) { tcapmove(to, 0); for (i = from - to; i > 0; i--) putpad(DL); tcapmove(to + howmanylines, 0); for (i = from - to; i > 0; i--) putpad(AL); } else { tcapmove(from + howmanylines, 0); for (i = to - from; i > 0; i--) putpad(DL); tcapmove(from, 0); for (i = to - from; i > 0; i--) putpad(AL); } } /* cs is set up just like cm, so we use tgoto... */ static void tcapscrollregion(int top, int bot) { ttputc(PC); putpad(tgoto(CS, bot, top)); } #endif #if COLOR /* No colors here, ignore this. */ static void tcapfcol(void) { } /* No colors here, ignore this. */ static void tcapbcol(void) { } #endif static void tcapbeep(void) { ttputc(BEL); } static void putpad(char *str) { tputs(str, 1, ttputc); } #endif /* TERMCAP */
uemacs-master
tcap.c
/* VMSVT.C * * Advanced VMS terminal driver * * Knows about any terminal defined in SMGTERMS.TXT and TERMTABLE.TXT * located in SYS$SYSTEM. * * Author: Curtis Smith * modified by Petri Kutvonen */ #include <stdio.h> /* Standard I/O package */ #include "estruct.h" /* Emacs' structures */ #include "edef.h" /* Emacs' definitions */ #if VMSVT #include <descrip.h> /* Descriptor definitions */ /* These would normally come from iodef.h and ttdef.h */ #define IO$_SENSEMODE 0x27 /* Sense mode of terminal */ #define TT$_UNKNOWN 0x00 /* Unknown terminal */ #define TT$_VT100 96 /** Forward references **/ int vmsopen(), ttclose(), vmskopen(), vmskclose(), ttgetc(), ttputc(); int ttflush(), vmsmove(), vmseeol(), vmseeop(), vmsbeep(), vmsrev(); int vmscres(); extern int eolexist, revexist; extern char sres[]; #if COLOR int vmsfcol(), vmsbcol(); #endif /** SMG stuff **/ static char *begin_reverse, *end_reverse, *erase_to_end_line; static char *erase_whole_display; static int termtype; #define SMG$K_BEGIN_REVERSE 0x1bf #define SMG$K_END_REVERSE 0x1d6 #define SMG$K_SET_CURSOR_ABS 0x23a #define SMG$K_ERASE_WHOLE_DISPLAY 0x1da #define SMG$K_ERASE_TO_END_LINE 0x1d9 #if SCROLLCODE #define SMG$K_SCROLL_FORWARD 561 /* from sys$library:smgtrmptr.h */ #define SMG$K_SCROLL_REVERSE 562 #define SMG$K_SET_SCROLL_REGION 572 static char *scroll_forward, *scroll_reverse; #endif /* Dispatch table. All hard fields just point into the terminal I/O code. */ struct terminal term = { #if PKCODE MAXROW, #else 24 - 1, /* Max number of rows allowable */ #endif /* Filled in */ -1, /* Current number of rows used */ MAXCOL, /* Max number of columns */ /* Filled in */ 0, /* Current number of columns */ 64, /* Min margin for extended lines */ 8, /* Size of scroll region */ 100, /* # times thru update to pause */ vmsopen, /* Open terminal at the start */ ttclose, /* Close terminal at end */ vmskopen, /* Open keyboard */ vmskclose, /* Close keyboard */ ttgetc, /* Get character from keyboard */ ttputc, /* Put character to display */ ttflush, /* Flush output buffers */ vmsmove, /* Move cursor, origin 0 */ vmseeol, /* Erase to end of line */ vmseeop, /* Erase to end of page */ vmsbeep, /* Beep */ vmsrev, /* Set reverse video state */ vmscres /* Change screen resolution */ #if COLOR , vmsfcol, /* Set forground color */ vmsbcol /* Set background color */ #endif #if SCROLLCODE , NULL #endif }; /*** * ttputs - Send a string to ttputc * * Nothing returned ***/ ttputs(string) char *string; /* String to write */ { if (string) while (*string != '\0') ttputc(*string++); } /*** * vmsmove - Move the cursor (0 origin) * * Nothing returned ***/ vmsmove(row, col) int row; /* Row position */ int col; /* Column position */ { char buffer[32]; int ret_length; static int request_code = SMG$K_SET_CURSOR_ABS; static int max_buffer_length = sizeof(buffer); static int arg_list[3] = { 2 }; char *cp; int i; /* Set the arguments into the arg_list array * SMG assumes the row/column positions are 1 based (boo!) */ arg_list[1] = row + 1; arg_list[2] = col + 1; if ((smg$get_term_data( /* Get terminal data */ &termtype, /* Terminal table address */ &request_code, /* Request code */ &max_buffer_length, /* Maximum buffer length */ &ret_length, /* Return length */ buffer, /* Capability data buffer */ arg_list) /* Argument list array */ /* We'll know soon enough if this doesn't work */ &1) == 0) { ttputs("OOPS"); return; } /* Send out resulting sequence */ i = ret_length; cp = buffer; while (i-- > 0) ttputc(*cp++); } #if SCROLLCODE vmsscroll_reg(from, to, howmany) { int i; if (to == from) return; if (to < from) { vmsscrollregion(to, from + howmany - 1); vmsmove(from + howmany - 1, 0); for (i = from - to; i > 0; i--) ttputs(scroll_forward); } else { /* from < to */ vmsscrollregion(from, to + howmany - 1); vmsmove(from, 0); for (i = to - from; i > 0; i--) ttputs(scroll_reverse); } vmsscrollregion(-1, -1); } vmsscrollregion(top, bot) int top; /* Top position */ int bot; /* Bottom position */ { char buffer[32]; int ret_length; static int request_code = SMG$K_SET_SCROLL_REGION; static int max_buffer_length = sizeof(buffer); static int arg_list[3] = { 2 }; char *cp; int i; /* Set the arguments into the arg_list array * SMG assumes the row/column positions are 1 based (boo!) */ arg_list[1] = top + 1; arg_list[2] = bot + 1; if ((smg$get_term_data( /* Get terminal data */ &termtype, /* Terminal table address */ &request_code, /* Request code */ &max_buffer_length, /* Maximum buffer length */ &ret_length, /* Return length */ buffer, /* Capability data buffer */ arg_list) /* Argument list array */ /* We'll know soon enough if this doesn't work */ &1) == 0) { ttputs("OOPS"); return; } ttputc(0); /* Send out resulting sequence */ i = ret_length; cp = buffer; while (i-- > 0) ttputc(*cp++); } #endif /*** * vmsrev - Set the reverse video status * * Nothing returned ***/ vmsrev(status) int status; /* TRUE if setting reverse */ { if (status) ttputs(begin_reverse); else ttputs(end_reverse); } /*** * vmscres - Change screen resolution (which it doesn't) * * Nothing returned ***/ vmscres() { /* But it could. For vt100/vt200s, one could switch from 80 and 132 columns modes */ } #if COLOR /*** * vmsfcol - Set the forground color (not implimented) * * Nothing returned ***/ vmsfcol() { } /*** * vmsbcol - Set the background color (not implimented) * * Nothing returned ***/ vmsbcol() { } #endif /*** * vmseeol - Erase to end of line * * Nothing returned ***/ vmseeol() { ttputs(erase_to_end_line); } /*** * vmseeop - Erase to end of page (clear screen) * * Nothing returned ***/ vmseeop() { ttputs(erase_whole_display); } /*** * vmsbeep - Ring the bell * * Nothing returned ***/ vmsbeep() { ttputc('\007'); } /*** * vmsgetstr - Get an SMG string capability by name * * Returns: Escape sequence * NULL No escape sequence available ***/ char *vmsgetstr(request_code) int request_code; /* Request code */ { char *result; static char seq_storage[1024]; static char *buffer = seq_storage; static int arg_list[2] = { 1, 1 }; int max_buffer_length, ret_length; /* Precompute buffer length */ max_buffer_length = (seq_storage + sizeof(seq_storage)) - buffer; /* Get terminal commands sequence from master table */ if ((smg$get_term_data( /* Get terminal data */ &termtype, /* Terminal table address */ &request_code, /* Request code */ &max_buffer_length, /* Maximum buffer length */ &ret_length, /* Return length */ buffer, /* Capability data buffer */ arg_list) /* Argument list array */ /* If this doesn't work, try again with no arguments */ &1) == 0 && (smg$get_term_data( /* Get terminal data */ &termtype, /* Terminal table address */ &request_code, /* Request code */ &max_buffer_length, /* Maximum buffer length */ &ret_length, /* Return length */ buffer) /* Capability data buffer */ /* Return NULL pointer if capability is not available */ &1) == 0) return NULL; /* Check for empty result */ if (ret_length == 0) return NULL; /* Save current position so we can return it to caller */ result = buffer; /* NIL terminate the sequence for return */ buffer[ret_length] = 0; /* Advance buffer */ buffer += ret_length + 1; /* Return capability to user */ return result; } /** I/O information block definitions **/ struct iosb { /* I/O status block */ short i_cond; /* Condition value */ short i_xfer; /* Transfer count */ long i_info; /* Device information */ }; struct termchar { /* Terminal characteristics */ char t_class; /* Terminal class */ char t_type; /* Terminal type */ short t_width; /* Terminal width in characters */ long t_mandl; /* Terminal's mode and length */ long t_extend; /* Extended terminal characteristics */ }; static struct termchar tc; /* Terminal characteristics */ /*** * vmsgtty - Get terminal type from system control block * * Nothing returned ***/ vmsgtty() { short fd; int status; struct iosb iostatus; $DESCRIPTOR(devnam, "SYS$INPUT"); /* Assign input to a channel */ status = sys$assign(&devnam, &fd, 0, 0); if ((status & 1) == 0) exit(status); /* Get terminal characteristics */ status = sys$qiow( /* Queue and wait */ 0, /* Wait on event flag zero */ fd, /* Channel to input terminal */ IO$_SENSEMODE, /* Get current characteristic */ &iostatus, /* Status after operation */ 0, 0, /* No AST service */ &tc, /* Terminal characteristics buf */ sizeof(tc), /* Size of the buffer */ 0, 0, 0, 0); /* P3-P6 unused */ /* De-assign the input device */ if ((sys$dassgn(fd) & 1) == 0) exit(status); /* Jump out if bad status */ if ((status & 1) == 0) exit(status); if ((iostatus.i_cond & 1) == 0) exit(iostatus.i_cond); } /*** * vmsopen - Get terminal type and open terminal * * Nothing returned ***/ vmsopen() { /* Get terminal type */ vmsgtty(); if (tc.t_type == TT$_UNKNOWN) { printf("Terminal type is unknown!\n"); printf ("Try set your terminal type with SET TERMINAL/INQUIRE\n"); printf("Or get help on SET TERMINAL/DEVICE_TYPE\n"); exit(3); } /* Access the system terminal definition table for the */ /* information of the terminal type returned by IO$_SENSEMODE */ if ((smg$init_term_table_by_type(&tc.t_type, &termtype) & 1) == 0) return -1; /* Set sizes */ term.t_nrow = ((unsigned int) tc.t_mandl >> 24) - 1; term.t_ncol = tc.t_width; /* Get some capabilities */ begin_reverse = vmsgetstr(SMG$K_BEGIN_REVERSE); end_reverse = vmsgetstr(SMG$K_END_REVERSE); revexist = begin_reverse != NULL && end_reverse != NULL; erase_to_end_line = vmsgetstr(SMG$K_ERASE_TO_END_LINE); eolexist = erase_to_end_line != NULL; erase_whole_display = vmsgetstr(SMG$K_ERASE_WHOLE_DISPLAY); #if SCROLLCODE scroll_forward = vmsgetstr(SMG$K_SCROLL_FORWARD); scroll_reverse = vmsgetstr(SMG$K_SCROLL_REVERSE); if (tc.t_type < TT$_VT100 || scroll_reverse == NULL || scroll_forward == NULL) term.t_scroll = NULL; else term.t_scroll = vmsscroll_reg; #endif /* Set resolution */ strcpy(sres, "NORMAL"); /* Open terminal I/O drivers */ ttopen(); } /*** * vmskopen - Open keyboard (not used) * * Nothing returned ***/ vmskopen() { } /*** * vmskclose - Close keyboard (not used) * * Nothing returned ***/ vmskclose() { } #endif
uemacs-master
vmsvt.c
/* isearch.c * * The functions in this file implement commands that perform incremental * searches in the forward and backward directions. This "ISearch" command * is intended to emulate the same command from the original EMACS * implementation (ITS). Contains references to routines internal to * SEARCH.C. * * REVISION HISTORY: * * D. R. Banks 9-May-86 * - added ITS EMACSlike ISearch * * John M. Gamble 5-Oct-86 * - Made iterative search use search.c's scanner() routine. * This allowed the elimination of bakscan(). * - Put isearch constants into estruct.h * - Eliminated the passing of 'status' to scanmore() and * checknext(), since there were no circumstances where * it ever equalled FALSE. * * Modified by Petri Kutvonen */ #include <stdio.h> #include "estruct.h" #include "edef.h" #include "efunc.h" #include "line.h" #if ISRCH static int echo_char(int c, int col); /* A couple of "own" variables for re-eat */ static int (*saved_get_char) (void); /* Get character routine */ static int eaten_char = -1; /* Re-eaten char */ /* A couple more "own" variables for the command string */ static int cmd_buff[CMDBUFLEN]; /* Save the command args here */ static int cmd_offset; /* Current offset into command buff */ static int cmd_reexecute = -1; /* > 0 if re-executing command */ /* * Subroutine to do incremental reverse search. It actually uses the * same code as the normal incremental search, as both can go both ways. */ int risearch(int f, int n) { struct line *curline; /* Current line on entry */ int curoff; /* Current offset on entry */ /* remember the initial . on entry: */ curline = curwp->w_dotp; /* Save the current line pointer */ curoff = curwp->w_doto; /* Save the current offset */ /* Make sure the search doesn't match where we already are: */ backchar(TRUE, 1); /* Back up a character */ if (!(isearch(f, -n))) { /* Call ISearch backwards *//* If error in search: */ curwp->w_dotp = curline; /* Reset the line pointer */ curwp->w_doto = curoff; /* and the offset to original value */ curwp->w_flag |= WFMOVE; /* Say we've moved */ update(FALSE); /* And force an update */ mlwrite("(search failed)"); /* Say we died */ #if PKCODE matchlen = strlen(pat); #endif } else mlerase(); /* If happy, just erase the cmd line */ #if PKCODE matchlen = strlen(pat); #endif return TRUE; } /* * Again, but for the forward direction */ int fisearch(int f, int n) { struct line *curline; /* Current line on entry */ int curoff; /* Current offset on entry */ /* remember the initial . on entry: */ curline = curwp->w_dotp; /* Save the current line pointer */ curoff = curwp->w_doto; /* Save the current offset */ /* do the search */ if (!(isearch(f, n))) { /* Call ISearch forwards *//* If error in search: */ curwp->w_dotp = curline; /* Reset the line pointer */ curwp->w_doto = curoff; /* and the offset to original value */ curwp->w_flag |= WFMOVE; /* Say we've moved */ update(FALSE); /* And force an update */ mlwrite("(search failed)"); /* Say we died */ #if PKCODE matchlen = strlen(pat); #endif } else mlerase(); /* If happy, just erase the cmd line */ #if PKCODE matchlen = strlen(pat); #endif return TRUE; } /* * Subroutine to do an incremental search. In general, this works similarly * to the older micro-emacs search function, except that the search happens * as each character is typed, with the screen and cursor updated with each * new search character. * * While searching forward, each successive character will leave the cursor * at the end of the entire matched string. Typing a Control-S or Control-X * will cause the next occurrence of the string to be searched for (where the * next occurrence does NOT overlap the current occurrence). A Control-R will * change to a backwards search, META will terminate the search and Control-G * will abort the search. Rubout will back up to the previous match of the * string, or if the starting point is reached first, it will delete the * last character from the search string. * * While searching backward, each successive character will leave the cursor * at the beginning of the matched string. Typing a Control-R will search * backward for the next occurrence of the string. Control-S or Control-X * will revert the search to the forward direction. In general, the reverse * incremental search is just like the forward incremental search inverted. * * In all cases, if the search fails, the user will be feeped, and the search * will stall until the pattern string is edited back into something that * exists (or until the search is aborted). */ int isearch(int f, int n) { int status; /* Search status */ int col; /* prompt column */ int cpos; /* character number in search string */ int c; /* current input character */ int expc; /* function expanded input char */ char pat_save[NPAT]; /* Saved copy of the old pattern str */ struct line *curline; /* Current line on entry */ int curoff; /* Current offset on entry */ int init_direction; /* The initial search direction */ /* Initialize starting conditions */ cmd_reexecute = -1; /* We're not re-executing (yet?) */ cmd_offset = 0; /* Start at the beginning of the buff */ cmd_buff[0] = '\0'; /* Init the command buffer */ strncpy(pat_save, pat, NPAT); /* Save the old pattern string */ curline = curwp->w_dotp; /* Save the current line pointer */ curoff = curwp->w_doto; /* Save the current offset */ init_direction = n; /* Save the initial search direction */ /* This is a good place to start a re-execution: */ start_over: /* ask the user for the text of a pattern */ col = promptpattern("ISearch: "); /* Prompt, remember the col */ cpos = 0; /* Start afresh */ status = TRUE; /* Assume everything's cool */ /* Get the first character in the pattern. If we get an initial Control-S or Control-R, re-use the old search string and find the first occurrence */ c = ectoc(expc = get_char()); /* Get the first character */ if ((c == IS_FORWARD) || (c == IS_REVERSE) || (c == IS_VMSFORW)) { /* Reuse old search string? */ for (cpos = 0; pat[cpos] != 0; cpos++) /* Yup, find the length */ col = echo_char(pat[cpos], col); /* and re-echo the string */ if (c == IS_REVERSE) { /* forward search? */ n = -1; /* No, search in reverse */ backchar(TRUE, 1); /* Be defensive about EOB */ } else n = 1; /* Yes, search forward */ status = scanmore(pat, n); /* Do the search */ c = ectoc(expc = get_char()); /* Get another character */ } /* Top of the per character loop */ for (;;) { /* ISearch per character loop */ /* Check for special characters first: */ /* Most cases here change the search */ if (expc == metac) /* Want to quit searching? */ return TRUE; /* Quit searching now */ switch (c) { /* dispatch on the input char */ case IS_ABORT: /* If abort search request */ return FALSE; /* Quit searching again */ case IS_REVERSE: /* If backward search */ case IS_FORWARD: /* If forward search */ case IS_VMSFORW: /* of either flavor */ if (c == IS_REVERSE) /* If reverse search */ n = -1; /* Set the reverse direction */ else /* Otherwise, */ n = 1; /* go forward */ status = scanmore(pat, n); /* Start the search again */ c = ectoc(expc = get_char()); /* Get the next char */ continue; /* Go continue with the search */ case IS_NEWLINE: /* Carriage return */ c = '\n'; /* Make it a new line */ break; /* Make sure we use it */ case IS_QUOTE: /* Quote character */ case IS_VMSQUOTE: /* of either variety */ c = ectoc(expc = get_char()); /* Get the next char */ case IS_TAB: /* Generically allowed */ case '\n': /* controlled characters */ break; /* Make sure we use it */ case IS_BACKSP: /* If a backspace: */ case IS_RUBOUT: /* or if a Rubout: */ if (cmd_offset <= 1) /* Anything to delete? */ return TRUE; /* No, just exit */ --cmd_offset; /* Back up over the Rubout */ cmd_buff[--cmd_offset] = '\0'; /* Yes, delete last char */ curwp->w_dotp = curline; /* Reset the line pointer */ curwp->w_doto = curoff; /* and the offset */ n = init_direction; /* Reset the search direction */ strncpy(pat, pat_save, NPAT); /* Restore the old search str */ cmd_reexecute = 0; /* Start the whole mess over */ goto start_over; /* Let it take care of itself */ /* Presumably a quasi-normal character comes here */ default: /* All other chars */ if (c < ' ') { /* Is it printable? *//* Nope. */ reeat(c); /* Re-eat the char */ return TRUE; /* And return the last status */ } } /* Switch */ /* I guess we got something to search for, so search for it */ pat[cpos++] = c; /* put the char in the buffer */ if (cpos >= NPAT) { /* too many chars in string? *//* Yup. Complain about it */ mlwrite("? Search string too long"); return TRUE; /* Return an error */ } pat[cpos] = 0; /* null terminate the buffer */ col = echo_char(c, col); /* Echo the character */ if (!status) { /* If we lost last time */ TTputc(BELL); /* Feep again */ TTflush(); /* see that the feep feeps */ } else /* Otherwise, we must have won */ if (!(status = checknext(c, pat, n))) /* See if match */ status = scanmore(pat, n); /* or find the next match */ c = ectoc(expc = get_char()); /* Get the next char */ } /* for {;;} */ } /* * Trivial routine to insure that the next character in the search string is * still true to whatever we're pointing to in the buffer. This routine will * not attempt to move the "point" if the match fails, although it will * implicitly move the "point" if we're forward searching, and find a match, * since that's the way forward isearch works. * * If the compare fails, we return FALSE and assume the caller will call * scanmore or something. * * char chr; Next char to look for * char *patrn; The entire search string (incl chr) * int dir; Search direction */ int checknext(char chr, char *patrn, int dir) /* Check next character in search string */ { struct line *curline; /* current line during scan */ int curoff; /* position within current line */ int buffchar; /* character at current position */ int status; /* how well things go */ /* setup the local scan pointer to current "." */ curline = curwp->w_dotp; /* Get the current line structure */ curoff = curwp->w_doto; /* Get the offset within that line */ if (dir > 0) { /* If searching forward */ if (curoff == llength(curline)) { /* If at end of line */ curline = lforw(curline); /* Skip to the next line */ if (curline == curbp->b_linep) return FALSE; /* Abort if at end of buffer */ curoff = 0; /* Start at the beginning of the line */ buffchar = '\n'; /* And say the next char is NL */ } else buffchar = lgetc(curline, curoff++); /* Get the next char */ if ((status = eq(buffchar, chr)) != 0) { /* Is it what we're looking for? */ curwp->w_dotp = curline; /* Yes, set the buffer's point */ curwp->w_doto = curoff; /* to the matched character */ curwp->w_flag |= WFMOVE; /* Say that we've moved */ } return status; /* And return the status */ } else /* Else, if reverse search: */ return match_pat(patrn); /* See if we're in the right place */ } /* * This hack will search for the next occurrence of <pat> in the buffer, either * forward or backward. It is called with the status of the prior search * attempt, so that it knows not to bother if it didn't work last time. If * we can't find any more matches, "point" is left where it was before. If * we do find a match, "point" will be at the end of the matched string for * forward searches and at the beginning of the matched string for reverse * searches. * * char *patrn; string to scan for * int dir; direction to search */ int scanmore(char *patrn, int dir) /* search forward or back for a pattern */ { int sts; /* search status */ if (dir < 0) { /* reverse search? */ rvstrcpy(tap, patrn); /* Put reversed string in tap */ sts = scanner(tap, REVERSE, PTBEG); } else sts = scanner(patrn, FORWARD, PTEND); /* Nope. Go forward */ if (!sts) { TTputc(BELL); /* Feep if search fails */ TTflush(); /* see that the feep feeps */ } return sts; /* else, don't even try */ } /* * The following is a worker subroutine used by the reverse search. It * compares the pattern string with the characters at "." for equality. If * any characters mismatch, it will return FALSE. * * This isn't used for forward searches, because forward searches leave "." * at the end of the search string (instead of in front), so all that needs to * be done is match the last char input. * * char *patrn; String to match to buffer */ int match_pat(char *patrn) /* See if the pattern string matches string at "." */ { int i; /* Generic loop index/offset */ int buffchar; /* character at current position */ struct line *curline; /* current line during scan */ int curoff; /* position within current line */ /* setup the local scan pointer to current "." */ curline = curwp->w_dotp; /* Get the current line structure */ curoff = curwp->w_doto; /* Get the offset within that line */ /* top of per character compare loop: */ for (i = 0; i < strlen(patrn); i++) { /* Loop for all characters in patrn */ if (curoff == llength(curline)) { /* If at end of line */ curline = lforw(curline); /* Skip to the next line */ curoff = 0; /* Start at the beginning of the line */ if (curline == curbp->b_linep) return FALSE; /* Abort if at end of buffer */ buffchar = '\n'; /* And say the next char is NL */ } else buffchar = lgetc(curline, curoff++); /* Get the next char */ if (!eq(buffchar, patrn[i])) /* Is it what we're looking for? */ return FALSE; /* Nope, just punt it then */ } return TRUE; /* Everything matched? Let's celebrate */ } /* * Routine to prompt for I-Search string. */ int promptpattern(char *prompt) { char tpat[NPAT + 20]; strcpy(tpat, prompt); /* copy prompt to output string */ strcat(tpat, " ("); /* build new prompt string */ expandp(pat, &tpat[strlen(tpat)], NPAT / 2); /* add old pattern */ strcat(tpat, ")<Meta>: "); /* check to see if we are executing a command line */ if (!clexec) { mlwrite(tpat); } return strlen(tpat); } /* * routine to echo i-search characters * * int c; character to be echoed * int col; column to be echoed in */ static int echo_char(int c, int col) { movecursor(term.t_nrow, col); /* Position the cursor */ if ((c < ' ') || (c == 0x7F)) { /* Control character? */ switch (c) { /* Yes, dispatch special cases */ case '\n': /* Newline */ TTputc('<'); TTputc('N'); TTputc('L'); TTputc('>'); col += 3; break; case '\t': /* Tab */ TTputc('<'); TTputc('T'); TTputc('A'); TTputc('B'); TTputc('>'); col += 4; break; case 0x7F: /* Rubout: */ TTputc('^'); /* Output a funny looking */ TTputc('?'); /* indication of Rubout */ col++; /* Count the extra char */ break; default: /* Vanilla control char */ TTputc('^'); /* Yes, output prefix */ TTputc(c + 0x40); /* Make it "^X" */ col++; /* Count this char */ } } else TTputc(c); /* Otherwise, output raw char */ TTflush(); /* Flush the output */ return ++col; /* return the new column no */ } /* * Routine to get the next character from the input stream. If we're reading * from the real terminal, force a screen update before we get the char. * Otherwise, we must be re-executing the command string, so just return the * next character. */ int get_char(void) { int c; /* A place to get a character */ /* See if we're re-executing: */ if (cmd_reexecute >= 0) /* Is there an offset? */ if ((c = cmd_buff[cmd_reexecute++]) != 0) return c; /* Yes, return any character */ /* We're not re-executing (or aren't any more). Try for a real char */ cmd_reexecute = -1; /* Say we're in real mode again */ update(FALSE); /* Pretty up the screen */ if (cmd_offset >= CMDBUFLEN - 1) { /* If we're getting too big ... */ mlwrite("? command too long"); /* Complain loudly and bitterly */ return metac; /* And force a quit */ } c = get1key(); /* Get the next character */ cmd_buff[cmd_offset++] = c; /* Save the char for next time */ cmd_buff[cmd_offset] = '\0'; /* And terminate the buffer */ return c; /* Return the character */ } /* * Hacky routine to re-eat a character. This will save the character to be * re-eaten by redirecting the input call to a routine here. Hack, etc. */ /* Come here on the next term.t_getchar call: */ int uneat(void) { int c; term.t_getchar = saved_get_char; /* restore the routine address */ c = eaten_char; /* Get the re-eaten char */ eaten_char = -1; /* Clear the old char */ return c; /* and return the last char */ } void reeat(int c) { if (eaten_char != -1) /* If we've already been here */ return /*(NULL) */ ; /* Don't do it again */ eaten_char = c; /* Else, save the char for later */ saved_get_char = term.t_getchar; /* Save the char get routine */ term.t_getchar = uneat; /* Replace it with ours */ } #else int isearch(int f, int n) { } #endif
uemacs-master
isearch.c
#include <stdio.h> #include "version.h" void version(void) { printf("%s version %s\n", PROGRAM_NAME_LONG, VERSION); }
uemacs-master
version.c
/* file.c * * The routines in this file handle the reading, writing * and lookup of disk files. All of details about the * reading and writing of the disk are in "fileio.c". * * modified by Petri Kutvonen */ #include <stdio.h> #include <unistd.h> #include "estruct.h" #include "edef.h" #include "efunc.h" #include "line.h" #include "util.h" #if defined(PKCODE) /* Max number of lines from one file. */ #define MAXNLINE 10000000 #endif /* * Read a file into the current * buffer. This is really easy; all you do it * find the name of the file, and call the standard * "read a file into the current buffer" code. * Bound to "C-X C-R". */ int fileread(int f, int n) { int s; char fname[NFILEN]; if (restflag) /* don't allow this command if restricted */ return resterr(); if ((s = mlreply("Read file: ", fname, NFILEN)) != TRUE) return s; return readin(fname, TRUE); } /* * Insert a file into the current * buffer. This is really easy; all you do it * find the name of the file, and call the standard * "insert a file into the current buffer" code. * Bound to "C-X C-I". */ int insfile(int f, int n) { int s; char fname[NFILEN]; if (restflag) /* don't allow this command if restricted */ return resterr(); if (curbp->b_mode & MDVIEW) /* don't allow this command if */ return rdonly(); /* we are in read only mode */ if ((s = mlreply("Insert file: ", fname, NFILEN)) != TRUE) return s; if ((s = ifile(fname)) != TRUE) return s; return reposition(TRUE, -1); } /* * Select a file for editing. * Look around to see if you can find the * fine in another buffer; if you can find it * just switch to the buffer. If you cannot find * the file, create a new buffer, read in the * text, and switch to the new buffer. * Bound to C-X C-F. */ int filefind(int f, int n) { char fname[NFILEN]; /* file user wishes to find */ int s; /* status return */ if (restflag) /* don't allow this command if restricted */ return resterr(); if ((s = mlreply("Find file: ", fname, NFILEN)) != TRUE) return s; return getfile(fname, TRUE); } int viewfile(int f, int n) { /* visit a file in VIEW mode */ char fname[NFILEN]; /* file user wishes to find */ int s; /* status return */ struct window *wp; /* scan for windows that need updating */ if (restflag) /* don't allow this command if restricted */ return resterr(); if ((s = mlreply("View file: ", fname, NFILEN)) != TRUE) return s; s = getfile(fname, FALSE); if (s) { /* if we succeed, put it in view mode */ curwp->w_bufp->b_mode |= MDVIEW; /* scan through and update mode lines of all windows */ wp = wheadp; while (wp != NULL) { wp->w_flag |= WFMODE; wp = wp->w_wndp; } } return s; } #if CRYPT static int resetkey(void) { /* reset the encryption key if needed */ int s; /* return status */ /* turn off the encryption flag */ cryptflag = FALSE; /* if we are in crypt mode */ if (curbp->b_mode & MDCRYPT) { if (curbp->b_key[0] == 0) { s = set_encryption_key(FALSE, 0); if (s != TRUE) return s; } /* let others know... */ cryptflag = TRUE; /* and set up the key to be used! */ /* de-encrypt it */ myencrypt((char *) NULL, 0); myencrypt(curbp->b_key, strlen(curbp->b_key)); /* re-encrypt it...seeding it to start */ myencrypt((char *) NULL, 0); myencrypt(curbp->b_key, strlen(curbp->b_key)); } return TRUE; } #endif /* * getfile() * * char fname[]; file name to find * int lockfl; check the file for locks? */ int getfile(char *fname, int lockfl) { struct buffer *bp; struct line *lp; int i; int s; char bname[NBUFN]; /* buffer name to put file */ #if MSDOS mklower(fname); /* msdos isn't case sensitive */ #endif for (bp = bheadp; bp != NULL; bp = bp->b_bufp) { if ((bp->b_flag & BFINVS) == 0 && strcmp(bp->b_fname, fname) == 0) { swbuffer(bp); lp = curwp->w_dotp; i = curwp->w_ntrows / 2; while (i-- && lback(lp) != curbp->b_linep) lp = lback(lp); curwp->w_linep = lp; curwp->w_flag |= WFMODE | WFHARD; cknewwindow(); mlwrite("(Old buffer)"); return TRUE; } } makename(bname, fname); /* New buffer name. */ while ((bp = bfind(bname, FALSE, 0)) != NULL) { /* old buffer name conflict code */ s = mlreply("Buffer name: ", bname, NBUFN); if (s == ABORT) /* ^G to just quit */ return s; if (s == FALSE) { /* CR to clobber it */ makename(bname, fname); break; } } if (bp == NULL && (bp = bfind(bname, TRUE, 0)) == NULL) { mlwrite("Cannot create buffer"); return FALSE; } if (--curbp->b_nwnd == 0) { /* Undisplay. */ curbp->b_dotp = curwp->w_dotp; curbp->b_doto = curwp->w_doto; curbp->b_markp = curwp->w_markp; curbp->b_marko = curwp->w_marko; } curbp = bp; /* Switch to it. */ curwp->w_bufp = bp; curbp->b_nwnd++; s = readin(fname, lockfl); /* Read it in. */ cknewwindow(); return s; } /* * Read file "fname" into the current buffer, blowing away any text * found there. Called by both the read and find commands. Return * the final status of the read. Also called by the mainline, to * read in a file specified on the command line as an argument. * The command bound to M-FNR is called after the buffer is set up * and before it is read. * * char fname[]; name of file to read * int lockfl; check for file locks? */ int readin(char *fname, int lockfl) { struct line *lp1; struct line *lp2; int i; struct window *wp; struct buffer *bp; int s; int nbytes; int nline; char mesg[NSTRING]; #if (FILOCK && BSD) || SVR4 if (lockfl && lockchk(fname) == ABORT) #if PKCODE { s = FIOFNF; bp = curbp; strcpy(bp->b_fname, ""); goto out; } #else return ABORT; #endif #endif #if CRYPT s = resetkey(); if (s != TRUE) return s; #endif bp = curbp; /* Cheap. */ if ((s = bclear(bp)) != TRUE) /* Might be old. */ return s; bp->b_flag &= ~(BFINVS | BFCHG); mystrscpy(bp->b_fname, fname, NFILEN); /* let a user macro get hold of things...if he wants */ execute(META | SPEC | 'R', FALSE, 1); if ((s = ffropen(fname)) == FIOERR) /* Hard file open. */ goto out; if (s == FIOFNF) { /* File not found. */ mlwrite("(New file)"); goto out; } /* read the file in */ mlwrite("(Reading file)"); nline = 0; while ((s = ffgetline()) == FIOSUC) { nbytes = strlen(fline); if ((lp1 = lalloc(nbytes)) == NULL) { s = FIOMEM; /* Keep message on the */ break; /* display. */ } #if PKCODE if (nline > MAXNLINE) { s = FIOMEM; break; } #endif lp2 = lback(curbp->b_linep); lp2->l_fp = lp1; lp1->l_fp = curbp->b_linep; lp1->l_bp = lp2; curbp->b_linep->l_bp = lp1; for (i = 0; i < nbytes; ++i) lputc(lp1, i, fline[i]); ++nline; } ffclose(); /* Ignore errors. */ strcpy(mesg, "("); if (s == FIOERR) { strcat(mesg, "I/O ERROR, "); curbp->b_flag |= BFTRUNC; } if (s == FIOMEM) { strcat(mesg, "OUT OF MEMORY, "); curbp->b_flag |= BFTRUNC; } sprintf(&mesg[strlen(mesg)], "Read %d line", nline); if (nline != 1) strcat(mesg, "s"); strcat(mesg, ")"); mlwrite(mesg); out: for (wp = wheadp; wp != NULL; wp = wp->w_wndp) { if (wp->w_bufp == curbp) { wp->w_linep = lforw(curbp->b_linep); wp->w_dotp = lforw(curbp->b_linep); wp->w_doto = 0; wp->w_markp = NULL; wp->w_marko = 0; wp->w_flag |= WFMODE | WFHARD; } } if (s == FIOERR || s == FIOFNF) /* False if error. */ return FALSE; return TRUE; } /* * Take a file name, and from it * fabricate a buffer name. This routine knows * about the syntax of file names on the target system. * I suppose that this information could be put in * a better place than a line of code. */ void makename(char *bname, char *fname) { char *cp1; char *cp2; cp1 = &fname[0]; while (*cp1 != 0) ++cp1; #if VMS #if PKCODE while (cp1 != &fname[0] && cp1[-1] != ':' && cp1[-1] != ']' && cp1[-1] != '>') #else while (cp1 != &fname[0] && cp1[-1] != ':' && cp1[-1] != ']') #endif --cp1; #endif #if MSDOS while (cp1 != &fname[0] && cp1[-1] != ':' && cp1[-1] != '\\' && cp1[-1] != '/') --cp1; #endif #if V7 | USG | BSD while (cp1 != &fname[0] && cp1[-1] != '/') --cp1; #endif cp2 = &bname[0]; while (cp2 != &bname[NBUFN - 1] && *cp1 != 0 && *cp1 != ';') *cp2++ = *cp1++; *cp2 = 0; } /* * make sure a buffer name is unique * * char *name; name to check on */ void unqname(char *name) { char *sp; /* check to see if it is in the buffer list */ while (bfind(name, 0, FALSE) != NULL) { /* go to the end of the name */ sp = name; while (*sp) ++sp; if (sp == name || (*(sp - 1) < '0' || *(sp - 1) > '8')) { *sp++ = '0'; *sp = 0; } else *(--sp) += 1; } } /* * Ask for a file name, and write the * contents of the current buffer to that file. * Update the remembered file name and clear the * buffer changed flag. This handling of file names * is different from the earlier versions, and * is more compatable with Gosling EMACS than * with ITS EMACS. Bound to "C-X C-W". */ int filewrite(int f, int n) { struct window *wp; int s; char fname[NFILEN]; if (restflag) /* don't allow this command if restricted */ return resterr(); if ((s = mlreply("Write file: ", fname, NFILEN)) != TRUE) return s; if ((s = writeout(fname)) == TRUE) { strcpy(curbp->b_fname, fname); curbp->b_flag &= ~BFCHG; wp = wheadp; /* Update mode lines. */ while (wp != NULL) { if (wp->w_bufp == curbp) wp->w_flag |= WFMODE; wp = wp->w_wndp; } } return s; } /* * Save the contents of the current * buffer in its associatd file. No nothing * if nothing has changed (this may be a bug, not a * feature). Error if there is no remembered file * name for the buffer. Bound to "C-X C-S". May * get called by "C-Z". */ int filesave(int f, int n) { struct window *wp; int s; if (curbp->b_mode & MDVIEW) /* don't allow this command if */ return rdonly(); /* we are in read only mode */ if ((curbp->b_flag & BFCHG) == 0) /* Return, no changes. */ return TRUE; if (curbp->b_fname[0] == 0) { /* Must have a name. */ mlwrite("No file name"); return FALSE; } /* complain about truncated files */ if ((curbp->b_flag & BFTRUNC) != 0) { if (mlyesno("Truncated file ... write it out") == FALSE) { mlwrite("(Aborted)"); return FALSE; } } if ((s = writeout(curbp->b_fname)) == TRUE) { curbp->b_flag &= ~BFCHG; wp = wheadp; /* Update mode lines. */ while (wp != NULL) { if (wp->w_bufp == curbp) wp->w_flag |= WFMODE; wp = wp->w_wndp; } } return s; } /* * This function performs the details of file * writing. Uses the file management routines in the * "fileio.c" package. The number of lines written is * displayed. Sadly, it looks inside a struct line; provide * a macro for this. Most of the grief is error * checking of some sort. */ int writeout(char *fn) { int s; struct line *lp; int nline; #if CRYPT s = resetkey(); if (s != TRUE) return s; #endif if ((s = ffwopen(fn)) != FIOSUC) { /* Open writes message. */ return FALSE; } mlwrite("(Writing...)"); /* tell us were writing */ lp = lforw(curbp->b_linep); /* First line. */ nline = 0; /* Number of lines. */ while (lp != curbp->b_linep) { if ((s = ffputline(&lp->l_text[0], llength(lp))) != FIOSUC) break; ++nline; lp = lforw(lp); } if (s == FIOSUC) { /* No write error. */ s = ffclose(); if (s == FIOSUC) { /* No close error. */ if (nline == 1) mlwrite("(Wrote 1 line)"); else mlwrite("(Wrote %d lines)", nline); } } else /* Ignore close error */ ffclose(); /* if a write error. */ if (s != FIOSUC) /* Some sort of error. */ return FALSE; return TRUE; } /* * The command allows the user * to modify the file name associated with * the current buffer. It is like the "f" command * in UNIX "ed". The operation is simple; just zap * the name in the buffer structure, and mark the windows * as needing an update. You can type a blank line at the * prompt if you wish. */ int filename(int f, int n) { struct window *wp; int s; char fname[NFILEN]; if (restflag) /* don't allow this command if restricted */ return resterr(); if ((s = mlreply("Name: ", fname, NFILEN)) == ABORT) return s; if (s == FALSE) strcpy(curbp->b_fname, ""); else strcpy(curbp->b_fname, fname); wp = wheadp; /* Update mode lines. */ while (wp != NULL) { if (wp->w_bufp == curbp) wp->w_flag |= WFMODE; wp = wp->w_wndp; } curbp->b_mode &= ~MDVIEW; /* no longer read only mode */ return TRUE; } /* * Insert file "fname" into the current * buffer, Called by insert file command. Return the final * status of the read. */ int ifile(char *fname) { struct line *lp0; struct line *lp1; struct line *lp2; int i; struct buffer *bp; int s; int nbytes; int nline; char mesg[NSTRING]; bp = curbp; /* Cheap. */ bp->b_flag |= BFCHG; /* we have changed */ bp->b_flag &= ~BFINVS; /* and are not temporary */ if ((s = ffropen(fname)) == FIOERR) /* Hard file open. */ goto out; if (s == FIOFNF) { /* File not found. */ mlwrite("(No such file)"); return FALSE; } mlwrite("(Inserting file)"); #if CRYPT s = resetkey(); if (s != TRUE) return s; #endif /* back up a line and save the mark here */ curwp->w_dotp = lback(curwp->w_dotp); curwp->w_doto = 0; curwp->w_markp = curwp->w_dotp; curwp->w_marko = 0; nline = 0; while ((s = ffgetline()) == FIOSUC) { nbytes = strlen(fline); if ((lp1 = lalloc(nbytes)) == NULL) { s = FIOMEM; /* Keep message on the */ break; /* display. */ } lp0 = curwp->w_dotp; /* line previous to insert */ lp2 = lp0->l_fp; /* line after insert */ /* re-link new line between lp0 and lp2 */ lp2->l_bp = lp1; lp0->l_fp = lp1; lp1->l_bp = lp0; lp1->l_fp = lp2; /* and advance and write out the current line */ curwp->w_dotp = lp1; for (i = 0; i < nbytes; ++i) lputc(lp1, i, fline[i]); ++nline; } ffclose(); /* Ignore errors. */ curwp->w_markp = lforw(curwp->w_markp); strcpy(mesg, "("); if (s == FIOERR) { strcat(mesg, "I/O ERROR, "); curbp->b_flag |= BFTRUNC; } if (s == FIOMEM) { strcat(mesg, "OUT OF MEMORY, "); curbp->b_flag |= BFTRUNC; } sprintf(&mesg[strlen(mesg)], "Inserted %d line", nline); if (nline > 1) strcat(mesg, "s"); strcat(mesg, ")"); mlwrite(mesg); out: /* advance to the next line and mark the window for changes */ curwp->w_dotp = lforw(curwp->w_dotp); curwp->w_flag |= WFHARD | WFMODE; /* copy window parameters back to the buffer structure */ curbp->b_dotp = curwp->w_dotp; curbp->b_doto = curwp->w_doto; curbp->b_markp = curwp->w_markp; curbp->b_marko = curwp->w_marko; if (s == FIOERR) /* False if error. */ return FALSE; return TRUE; }
uemacs-master
file.c
/* LOCK.C * * File locking command routines * * written by Daniel Lawrence */ #include <stdio.h> #include "estruct.h" #include "edef.h" #include "efunc.h" #if BSD | SVR4 #include <sys/errno.h> static char *lname[NLOCKS]; /* names of all locked files */ static int numlocks; /* # of current locks active */ /* * lockchk: * check a file for locking and add it to the list * * char *fname; file to check for a lock */ int lockchk(char *fname) { int i; /* loop indexes */ int status; /* return status */ /* check to see if that file is already locked here */ if (numlocks > 0) for (i = 0; i < numlocks; ++i) if (strcmp(fname, lname[i]) == 0) return TRUE; /* if we have a full locking table, bitch and leave */ if (numlocks == NLOCKS) { mlwrite("LOCK ERROR: Lock table full"); return ABORT; } /* next, try to lock it */ status = lock(fname); if (status == ABORT) /* file is locked, no override */ return ABORT; if (status == FALSE) /* locked, overriden, dont add to table */ return TRUE; /* we have now locked it, add it to our table */ lname[++numlocks - 1] = (char *) malloc(strlen(fname) + 1); if (lname[numlocks - 1] == NULL) { /* malloc failure */ undolock(fname); /* free the lock */ mlwrite("Cannot lock, out of memory"); --numlocks; return ABORT; } /* everthing is cool, add it to the table */ strcpy(lname[numlocks - 1], fname); return TRUE; } /* * lockrel: * release all the file locks so others may edit */ int lockrel(void) { int i; /* loop index */ int status; /* status of locks */ int s; /* status of one unlock */ status = TRUE; if (numlocks > 0) for (i = 0; i < numlocks; ++i) { if ((s = unlock(lname[i])) != TRUE) status = s; free(lname[i]); } numlocks = 0; return status; } /* * lock: * Check and lock a file from access by others * returns TRUE = files was not locked and now is * FALSE = file was locked and overridden * ABORT = file was locked, abort command * * char *fname; file name to lock */ int lock(char *fname) { char *locker; /* lock error message */ int status; /* return status */ char msg[NSTRING]; /* message string */ /* attempt to lock the file */ locker = dolock(fname); if (locker == NULL) /* we win */ return TRUE; /* file failed...abort */ if (strncmp(locker, "LOCK", 4) == 0) { lckerror(locker); return ABORT; } /* someone else has it....override? */ strcpy(msg, "File in use by "); strcat(msg, locker); strcat(msg, ", override?"); status = mlyesno(msg); /* ask them */ if (status == TRUE) return FALSE; else return ABORT; } /* * unlock: * Unlock a file * this only warns the user if it fails * * char *fname; file to unlock */ int unlock(char *fname) { char *locker; /* undolock return string */ /* unclock and return */ locker = undolock(fname); if (locker == NULL) return TRUE; /* report the error and come back */ lckerror(locker); return FALSE; } /* * report a lock error * * char *errstr; lock error string to print out */ void lckerror(char *errstr) { char obuf[NSTRING]; /* output buffer for error message */ strcpy(obuf, errstr); strcat(obuf, " - "); strcat(obuf, strerror(errno)); mlwrite(obuf); } #endif
uemacs-master
lock.c
/* ANSI.C * * The routines in this file provide support for ANSI style terminals * over a serial line. The serial I/O services are provided by routines in * "termio.c". It compiles into nothing if not an ANSI device. * * modified by Petri Kutvonen */ #define termdef 1 /* don't define "term" external */ #include <stdio.h> #include "estruct.h" #include "edef.h" #if ANSI #define NROW 25 /* Screen size. */ #define NCOL 80 /* Edit if you want to. */ #if PKCODE #define MROW 64 #endif #define NPAUSE 100 /* # times thru update to pause */ #define MARGIN 8 /* size of minimim margin and */ #define SCRSIZ 64 /* scroll size for extended lines */ #define BEL 0x07 /* BEL character. */ #define ESC 0x1B /* ESC character. */ extern int ttopen(); /* Forward references. */ extern int ttgetc(); extern int ttputc(); extern int ttflush(); extern int ttclose(); extern int ansimove(); extern int ansieeol(); extern int ansieeop(); extern int ansibeep(); extern int ansiopen(); extern int ansirev(); extern int ansiclose(); extern int ansikopen(); extern int ansikclose(); extern int ansicres(); #if COLOR extern int ansifcol(); extern int ansibcol(); int cfcolor = -1; /* current forground color */ int cbcolor = -1; /* current background color */ #endif /* * Standard terminal interface dispatch table. Most of the fields point into * "termio" code. */ struct terminal term = { #if PKCODE MROW - 1, #else NROW - 1, #endif NROW - 1, NCOL, NCOL, MARGIN, SCRSIZ, NPAUSE, ansiopen, ansiclose, ansikopen, ansikclose, ttgetc, ttputc, ttflush, ansimove, ansieeol, ansieeop, ansibeep, ansirev, ansicres #if COLOR , ansifcol, ansibcol #endif #if SCROLLCODE , NULL #endif }; #if COLOR ansifcol(color) /* set the current output color */ int color; /* color to set */ { if (color == cfcolor) return; ttputc(ESC); ttputc('['); ansiparm(color + 30); ttputc('m'); cfcolor = color; } /* Set the current background color. * color: color to set. */ void ansibcol(int color) { if (color == cbcolor) return; ttputc(ESC); ttputc('['); ansiparm(color + 40); ttputc('m'); cbcolor = color; } #endif ansimove(row, col) { ttputc(ESC); ttputc('['); ansiparm(row + 1); ttputc(';'); ansiparm(col + 1); ttputc('H'); } void ansieeol(void) { ttputc(ESC); ttputc('['); ttputc('K'); } void ansieeop(void) { #if COLOR ansifcol(gfcolor); ansibcol(gbcolor); #endif ttputc(ESC); ttputc('['); ttputc('J'); } /* Change reverse video state. * state: TRUE = reverse, FALSE = normal */ void ansirev(int state) { #if COLOR int ftmp, btmp; /* temporaries for colors */ #endif ttputc(ESC); ttputc('['); ttputc(state ? '7' : '0'); ttputc('m'); #if COLOR if (state == FALSE) { ftmp = cfcolor; btmp = cbcolor; cfcolor = -1; cbcolor = -1; ansifcol(ftmp); ansibcol(btmp); } #endif } /* Change screen resolution. */ int ansicres() { return TRUE; } void ansibeep(void) { ttputc(BEL); ttflush(); } void ansiparm(int n) { int q, r; q = n / 10; if (q != 0) { r = q / 10; if (r != 0) { ttputc((r % 10) + '0'); } ttputc((q % 10) + '0'); } ttputc((n % 10) + '0'); } void ansiopen(void) { #if V7 | USG | BSD char *cp; if ((cp = getenv("TERM")) == NULL) { puts("Shell variable TERM not defined!"); exit(1); } if (strcmp(cp, "vt100") != 0) { puts("Terminal type not 'vt100'!"); exit(1); } #endif strcpy(sres, "NORMAL"); revexist = TRUE; ttopen(); } void ansiclose(void) { #if COLOR ansifcol(7); ansibcol(0); #endif ttclose(); } /* Open the keyboard (a noop here). */ void ansikopen(void) { } /* Close the keyboard (a noop here). */ void ansikclose(void) { } #endif
uemacs-master
ansi.c
#include "estruct.h" #include "edef.h" /* initialized global definitions */ int fillcol = 72; /* Current fill column */ int kbdm[NKBDM]; /* Macro */ char *execstr = NULL; /* pointer to string to execute */ char golabel[NPAT] = ""; /* current line to go to */ int execlevel = 0; /* execution IF level */ int eolexist = TRUE; /* does clear to EOL exist */ int revexist = FALSE; /* does reverse video exist? */ int flickcode = FALSE; /* do flicker supression? */ char *modename[] = { /* name of modes */ "WRAP", "CMODE", "SPELL", "EXACT", "VIEW", "OVER", "MAGIC", "CRYPT", "ASAVE", "UTF-8" }; char *mode2name[] = { /* name of modes */ "Wrap", "Cmode", "Spell", "Exact", "View", "Over", "Magic", "Crypt", "Asave", "utf-8" }; char modecode[] = "WCSEVOMYAU"; /* letters to represent modes */ int gmode = 0; /* global editor mode */ int gflags = GFREAD; /* global control flag */ #if PKCODE & IBMPC int gfcolor = 8; /* global forgrnd color (white) */ #else int gfcolor = 7; /* global forgrnd color (white) */ #endif int gbcolor = 0; /* global backgrnd color (black) */ int gasave = 256; /* global ASAVE size */ int gacount = 256; /* count until next ASAVE */ int sgarbf = TRUE; /* TRUE if screen is garbage */ int mpresf = FALSE; /* TRUE if message in last line */ int clexec = FALSE; /* command line execution flag */ int mstore = FALSE; /* storing text to macro flag */ int discmd = TRUE; /* display command flag */ int disinp = TRUE; /* display input characters */ struct buffer *bstore = NULL; /* buffer to store macro text to */ int vtrow = 0; /* Row location of SW cursor */ int vtcol = 0; /* Column location of SW cursor */ int ttrow = HUGE; /* Row location of HW cursor */ int ttcol = HUGE; /* Column location of HW cursor */ int lbound = 0; /* leftmost column of current line being displayed */ int taboff = 0; /* tab offset for display */ int metac = CONTROL | '['; /* current meta character */ int ctlxc = CONTROL | 'X'; /* current control X prefix char */ int reptc = CONTROL | 'U'; /* current universal repeat char */ int abortc = CONTROL | 'G'; /* current abort command char */ int quotec = 0x11; /* quote char during mlreply() */ int tabmask = 0x07; /* tabulator mask */ char *cname[] = { /* names of colors */ "BLACK", "RED", "GREEN", "YELLOW", "BLUE", "MAGENTA", "CYAN", "WHITE" #if PKCODE & IBMPC , "HIGH" #endif }; struct kill *kbufp = NULL; /* current kill buffer chunk pointer */ struct kill *kbufh = NULL; /* kill buffer header pointer */ int kused = KBLOCK; /* # of bytes used in kill buffer */ struct window *swindow = NULL; /* saved window pointer */ int cryptflag = FALSE; /* currently encrypting? */ int *kbdptr; /* current position in keyboard buf */ int *kbdend = &kbdm[0]; /* ptr to end of the keyboard */ int kbdmode = STOP; /* current keyboard macro mode */ int kbdrep = 0; /* number of repetitions */ int restflag = FALSE; /* restricted use? */ int lastkey = 0; /* last keystoke */ int seed = 0; /* random number seed */ long envram = 0l; /* # of bytes current in use by malloc */ int macbug = FALSE; /* macro debuging flag */ char errorm[] = "ERROR"; /* error literal */ char truem[] = "TRUE"; /* true literal */ char falsem[] = "FALSE"; /* false litereal */ int cmdstatus = TRUE; /* last command status */ char palstr[49] = ""; /* palette string */ int saveflag = 0; /* Flags, saved with the $target var */ char *fline = NULL; /* dynamic return line */ int flen = 0; /* current length of fline */ int rval = 0; /* return value of a subprocess */ #if PKCODE int nullflag = FALSE; /* accept null characters */ int justflag = FALSE; /* justify, don't fill */ #endif int overlap = 0; /* line overlap in forw/back page */ int scrollcount = 1; /* number of lines to scroll */ /* uninitialized global definitions */ int currow; /* Cursor row */ int curcol; /* Cursor column */ int thisflag; /* Flags, this command */ int lastflag; /* Flags, last command */ int curgoal; /* Goal for C-P, C-N */ struct window *curwp; /* Current window */ struct buffer *curbp; /* Current buffer */ struct window *wheadp; /* Head of list of windows */ struct buffer *bheadp; /* Head of list of buffers */ struct buffer *blistp; /* Buffer for C-X C-B */ char sres[NBUFN]; /* current screen resolution */ char pat[NPAT]; /* Search pattern */ char tap[NPAT]; /* Reversed pattern array. */ char rpat[NPAT]; /* replacement pattern */ /* The variable matchlen holds the length of the matched * string - used by the replace functions. * The variable patmatch holds the string that satisfies * the search command. * The variables matchline and matchoff hold the line and * offset position of the *start* of match. */ unsigned int matchlen = 0; unsigned int mlenold = 0; char *patmatch = NULL; struct line *matchline = NULL; int matchoff = 0; /* directive name table: This holds the names of all the directives.... */ char *dname[] = { "if", "else", "endif", "goto", "return", "endm", "while", "endwhile", "break", "force" }; #if DEBUGM /* vars needed for macro debugging output */ char outline[NSTRING]; /* global string to hold debug line text */ #endif
uemacs-master
globals.c
/* spaw.c * * Various operating system access commands. * * <odified by Petri Kutvonen */ #include <stdio.h> #include <unistd.h> #include "estruct.h" #include "edef.h" #include "efunc.h" #if VMS #define EFN 0 /* Event flag. */ #include <ssdef.h> /* Random headers. */ #include <stsdef.h> #include <descrip.h> #include <iodef.h> extern int oldmode[3]; /* In "termio.c" */ extern int newmode[3]; /* In "termio.c" */ extern short iochan; /* In "termio.c" */ #endif #if V7 | USG | BSD #include <signal.h> #ifdef SIGWINCH extern int chg_width, chg_height; extern void sizesignal(int); #endif #endif #if MSDOS & (MSC | TURBO) #include <process.h> #endif /* * Create a subjob with a copy of the command intrepreter in it. When the * command interpreter exits, mark the screen as garbage so that you do a full * repaint. Bound to "^X C". The message at the start in VMS puts out a newline. * Under some (unknown) condition, you don't get one free when DCL starts up. */ int spawncli(int f, int n) { #if V7 | USG | BSD char *cp; #endif /* don't allow this command if restricted */ if (restflag) return resterr(); #if VMS movecursor(term.t_nrow, 0); /* In last line. */ mlputs("(Starting DCL)\r\n"); TTflush(); /* Ignore "ttcol". */ sgarbf = TRUE; sys(NULL); sleep(1); mlputs("\r\n(Returning from DCL)\r\n"); TTflush(); sleep(1); return TRUE; #endif #if MSDOS & (MSC | TURBO) movecursor(term.t_nrow, 0); /* Seek to last line. */ TTflush(); TTkclose(); shellprog(""); TTkopen(); sgarbf = TRUE; return TRUE; #endif #if V7 | USG | BSD movecursor(term.t_nrow, 0); /* Seek to last line. */ TTflush(); TTclose(); /* stty to old settings */ TTkclose(); /* Close "keyboard" */ if ((cp = getenv("SHELL")) != NULL && *cp != '\0') system(cp); else #if BSD system("exec /bin/csh"); #else system("exec /bin/sh"); #endif sgarbf = TRUE; sleep(2); TTopen(); TTkopen(); #ifdef SIGWINCH /* * This fools the update routines to force a full * redraw with complete window size checking. * -lbt */ chg_width = term.t_ncol; chg_height = term.t_nrow + 1; term.t_nrow = term.t_ncol = 0; #endif return TRUE; #endif } #if BSD | __hpux | SVR4 int bktoshell(int f, int n) { /* suspend MicroEMACS and wait to wake up */ vttidy(); /****************************** int pid; pid = getpid(); kill(pid,SIGTSTP); ******************************/ kill(0, SIGTSTP); return TRUE; } void rtfrmshell(void) { TTopen(); curwp->w_flag = WFHARD; sgarbf = TRUE; } #endif /* * Run a one-liner in a subjob. When the command returns, wait for a single * character to be typed, then mark the screen as garbage so a full repaint is * done. Bound to "C-X !". */ int spawn(int f, int n) { int s; char line[NLINE]; /* don't allow this command if restricted */ if (restflag) return resterr(); #if VMS if ((s = mlreply("!", line, NLINE)) != TRUE) return s; movecursor(term.t_nrow, 0); TTflush(); s = sys(line); /* Run the command. */ if (clexec == FALSE) { mlputs("\r\n\n(End)"); /* Pause. */ TTflush(); tgetc(); } sgarbf = TRUE; return s; #endif #if MSDOS if ((s = mlreply("!", line, NLINE)) != TRUE) return s; movecursor(term.t_nrow, 0); TTkclose(); shellprog(line); TTkopen(); /* if we are interactive, pause here */ if (clexec == FALSE) { mlputs("\r\n(End)"); tgetc(); } sgarbf = TRUE; return TRUE; #endif #if V7 | USG | BSD if ((s = mlreply("!", line, NLINE)) != TRUE) return s; TTflush(); TTclose(); /* stty to old modes */ TTkclose(); system(line); fflush(stdout); /* to be sure P.K. */ TTopen(); if (clexec == FALSE) { mlputs("(End)"); /* Pause. */ TTflush(); while ((s = tgetc()) != '\r' && s != ' '); mlputs("\r\n"); } TTkopen(); sgarbf = TRUE; return TRUE; #endif } /* * Run an external program with arguments. When it returns, wait for a single * character to be typed, then mark the screen as garbage so a full repaint is * done. Bound to "C-X $". */ int execprg(int f, int n) { int s; char line[NLINE]; /* don't allow this command if restricted */ if (restflag) return resterr(); #if VMS if ((s = mlreply("!", line, NLINE)) != TRUE) return s; TTflush(); s = sys(line); /* Run the command. */ mlputs("\r\n\n(End)"); /* Pause. */ TTflush(); tgetc(); sgarbf = TRUE; return s; #endif #if MSDOS if ((s = mlreply("$", line, NLINE)) != TRUE) return s; movecursor(term.t_nrow, 0); TTkclose(); execprog(line); TTkopen(); /* if we are interactive, pause here */ if (clexec == FALSE) { mlputs("\r\n(End)"); tgetc(); } sgarbf = TRUE; return TRUE; #endif #if V7 | USG | BSD if ((s = mlreply("!", line, NLINE)) != TRUE) return s; TTputc('\n'); /* Already have '\r' */ TTflush(); TTclose(); /* stty to old modes */ TTkclose(); system(line); fflush(stdout); /* to be sure P.K. */ TTopen(); mlputs("(End)"); /* Pause. */ TTflush(); while ((s = tgetc()) != '\r' && s != ' '); sgarbf = TRUE; return TRUE; #endif } /* * Pipe a one line command into a window * Bound to ^X @ */ int pipecmd(int f, int n) { int s; /* return status from CLI */ struct window *wp; /* pointer to new window */ struct buffer *bp; /* pointer to buffer to zot */ char line[NLINE]; /* command line send to shell */ static char bname[] = "command"; static char filnam[NSTRING] = "command"; #if MSDOS char *tmp; FILE *fp; int len; #endif /* don't allow this command if restricted */ if (restflag) return resterr(); #if MSDOS if ((tmp = getenv("TMP")) == NULL && (tmp = getenv("TEMP")) == NULL) strcpy(filnam, "command"); else { strcpy(filnam, tmp); len = strlen(tmp); if (len <= 0 || filnam[len - 1] != '\\' && filnam[len - 1] != '/') strcat(filnam, "\\"); strcat(filnam, "command"); } #endif #if VMS mlwrite("Not available under VMS"); return FALSE; #endif /* get the command to pipe in */ if ((s = mlreply("@", line, NLINE)) != TRUE) return s; /* get rid of the command output buffer if it exists */ if ((bp = bfind(bname, FALSE, 0)) != FALSE) { /* try to make sure we are off screen */ wp = wheadp; while (wp != NULL) { if (wp->w_bufp == bp) { #if PKCODE if (wp == curwp) delwind(FALSE, 1); else onlywind(FALSE, 1); break; #else onlywind(FALSE, 1); break; #endif } wp = wp->w_wndp; } if (zotbuf(bp) != TRUE) return FALSE; } #if MSDOS strcat(line, " >>"); strcat(line, filnam); movecursor(term.t_nrow, 0); TTkclose(); shellprog(line); TTkopen(); sgarbf = TRUE; if ((fp = fopen(filnam, "r")) == NULL) { s = FALSE; } else { fclose(fp); s = TRUE; } #endif #if V7 | USG | BSD TTflush(); TTclose(); /* stty to old modes */ TTkclose(); strcat(line, ">"); strcat(line, filnam); system(line); TTopen(); TTkopen(); TTflush(); sgarbf = TRUE; s = TRUE; #endif if (s != TRUE) return s; /* split the current window to make room for the command output */ if (splitwind(FALSE, 1) == FALSE) return FALSE; /* and read the stuff in */ if (getfile(filnam, FALSE) == FALSE) return FALSE; /* make this window in VIEW mode, update all mode lines */ curwp->w_bufp->b_mode |= MDVIEW; wp = wheadp; while (wp != NULL) { wp->w_flag |= WFMODE; wp = wp->w_wndp; } /* and get rid of the temporary file */ unlink(filnam); return TRUE; } /* * filter a buffer through an external DOS program * Bound to ^X # */ int filter_buffer(int f, int n) { int s; /* return status from CLI */ struct buffer *bp; /* pointer to buffer to zot */ char line[NLINE]; /* command line send to shell */ char tmpnam[NFILEN]; /* place to store real file name */ static char bname1[] = "fltinp"; static char filnam1[] = "fltinp"; static char filnam2[] = "fltout"; /* don't allow this command if restricted */ if (restflag) return resterr(); if (curbp->b_mode & MDVIEW) /* don't allow this command if */ return rdonly(); /* we are in read only mode */ #if VMS mlwrite("Not available under VMS"); return FALSE; #endif /* get the filter name and its args */ if ((s = mlreply("#", line, NLINE)) != TRUE) return s; /* setup the proper file names */ bp = curbp; strcpy(tmpnam, bp->b_fname); /* save the original name */ strcpy(bp->b_fname, bname1); /* set it to our new one */ /* write it out, checking for errors */ if (writeout(filnam1) != TRUE) { mlwrite("(Cannot write filter file)"); strcpy(bp->b_fname, tmpnam); return FALSE; } #if MSDOS strcat(line, " <fltinp >fltout"); movecursor(term.t_nrow - 1, 0); TTkclose(); shellprog(line); TTkopen(); sgarbf = TRUE; s = TRUE; #endif #if V7 | USG | BSD TTputc('\n'); /* Already have '\r' */ TTflush(); TTclose(); /* stty to old modes */ TTkclose(); strcat(line, " <fltinp >fltout"); system(line); TTopen(); TTkopen(); TTflush(); sgarbf = TRUE; s = TRUE; #endif /* on failure, escape gracefully */ if (s != TRUE || (readin(filnam2, FALSE) == FALSE)) { mlwrite("(Execution failed)"); strcpy(bp->b_fname, tmpnam); unlink(filnam1); unlink(filnam2); return s; } /* reset file name */ strcpy(bp->b_fname, tmpnam); /* restore name */ bp->b_flag |= BFCHG; /* flag it as changed */ /* and get rid of the temporary file */ unlink(filnam1); unlink(filnam2); return TRUE; } #if VMS /* * Run a command. The "cmd" is a pointer to a command string, or NULL if you * want to run a copy of DCL in the subjob (this is how the standard routine * LIB$SPAWN works. You have to do wierd stuff with the terminal on the way in * and the way out, because DCL does not want the channel to be in raw mode. */ int sys(char *cmd) { struct dsc$descriptor cdsc; struct dsc$descriptor *cdscp; long status; long substatus; long iosb[2]; status = SYS$QIOW(EFN, iochan, IO$_SETMODE, iosb, 0, 0, oldmode, sizeof(oldmode), 0, 0, 0, 0); if (status != SS$_NORMAL || (iosb[0] & 0xFFFF) != SS$_NORMAL) return FALSE; cdscp = NULL; /* Assume DCL. */ if (cmd != NULL) { /* Build descriptor. */ cdsc.dsc$a_pointer = cmd; cdsc.dsc$w_length = strlen(cmd); cdsc.dsc$b_dtype = DSC$K_DTYPE_T; cdsc.dsc$b_class = DSC$K_CLASS_S; cdscp = &cdsc; } status = LIB$SPAWN(cdscp, 0, 0, 0, 0, 0, &substatus, 0, 0, 0); if (status != SS$_NORMAL) substatus = status; status = SYS$QIOW(EFN, iochan, IO$_SETMODE, iosb, 0, 0, newmode, sizeof(newmode), 0, 0, 0, 0); if (status != SS$_NORMAL || (iosb[0] & 0xFFFF) != SS$_NORMAL) return FALSE; if ((substatus & STS$M_SUCCESS) == 0) /* Command failed. */ return FALSE; return TRUE; } #endif #if MSDOS & (TURBO | MSC) /* * SHELLPROG: Execute a command in a subshell * * char *cmd; Incoming command line to execute */ int shellprog(char *cmd) { char *shell; /* Name of system command processor */ char *p; /* Temporary pointer */ char swchar; /* switch character to use */ union REGS regs; /* parameters for dos call */ char comline[NSTRING]; /* constructed command line */ /* detect current switch character and set us up to use it */ regs.h.ah = 0x37; /* get setting data */ regs.h.al = 0x00; /* get switch character */ intdos(&regs, &regs); swchar = (char) regs.h.dl; /* get name of system shell */ if ((shell = getenv("COMSPEC")) == NULL) { return FALSE; /* No shell located */ } /* trim leading whitespace off the command */ while (*cmd == ' ' || *cmd == '\t') /* find out if null command */ cmd++; /** If the command line is not empty, bring up the shell **/ /** and execute the command. Otherwise, bring up the **/ /** shell in interactive mode. **/ if (*cmd) { strcpy(comline, shell); strcat(comline, " "); comline[strlen(comline) + 1] = 0; comline[strlen(comline)] = swchar; strcat(comline, "c "); strcat(comline, cmd); return execprog(comline); } else return execprog(shell); } /* * EXECPROG: * A function to execute a named program * with arguments * * char *cmd; Incoming command line to execute */ int execprog(char *cmd) { char *sp; /* temporary string pointer */ char f1[38]; /* FCB1 area (not initialized */ char f2[38]; /* FCB2 area (not initialized */ char prog[NSTRING]; /* program filespec */ char tail[NSTRING]; /* command tail with length byte */ union REGS regs; /* parameters for dos call */ struct SREGS segreg; /* segment registers for dis call */ struct pblock { /* EXEC parameter block */ short envptr; /* 2 byte pointer to environment string */ char *cline; /* 4 byte pointer to command line */ char *fcb1; /* 4 byte pointer to FCB at PSP+5Ch */ char *fcb2; /* 4 byte pointer to FCB at PSP+6Ch */ } pblock; char *flook(); /* parse the command name from the command line */ sp = prog; while (*cmd && (*cmd != ' ') && (*cmd != '\t')) *sp++ = *cmd++; *sp = 0; /* and parse out the command tail */ while (*cmd && ((*cmd == ' ') || (*cmd == '\t'))) ++cmd; *tail = (char) (strlen(cmd)); /* record the byte length */ strcpy(&tail[1], cmd); strcat(&tail[1], "\r"); /* look up the program on the path trying various extentions */ if ((sp = flook(prog, TRUE)) == NULL) if ((sp = flook(strcat(prog, ".exe"), TRUE)) == NULL) { strcpy(&prog[strlen(prog) - 4], ".com"); if ((sp = flook(prog, TRUE)) == NULL) return FALSE; } strcpy(prog, sp); /* get a pointer to this PSPs environment segment number */ segread(&segreg); /* set up the EXEC parameter block */ pblock.envptr = 0; /* make the child inherit the parents env */ pblock.fcb1 = f1; /* point to a blank FCB */ pblock.fcb2 = f2; /* point to a blank FCB */ pblock.cline = tail; /* parameter line pointer */ /* and make the call */ regs.h.ah = 0x4b; /* EXEC Load or Execute a Program */ regs.h.al = 0x00; /* load end execute function subcode */ segreg.ds = ((unsigned long) (prog) >> 16); /* program name ptr */ regs.x.dx = (unsigned int) (prog); segreg.es = ((unsigned long) (&pblock) >> 16); /* set up param block ptr */ regs.x.bx = (unsigned int) (&pblock); #if TURBO | MSC intdosx(&regs, &regs, &segreg); if (regs.x.cflag == 0) { regs.h.ah = 0x4d; /* get child process return code */ intdos(&regs, &regs); /* go do it */ rval = regs.x.ax; /* save child's return code */ } else #if MSC rval = -1; #else rval = -_doserrno; /* failed child call */ #endif #endif return (rval < 0) ? FALSE : TRUE; } #endif
uemacs-master
spawn.c
/* window.c * * Window management. Some of the functions are internal, and some are * attached to keys that the user actually types. * */ #include <stdio.h> #include "estruct.h" #include "edef.h" #include "efunc.h" #include "line.h" #include "wrapper.h" /* * Reposition dot in the current window to line "n". If the argument is * positive, it is that line. If it is negative it is that line from the * bottom. If it is 0 the window is centered (this is what the standard * redisplay code does). With no argument it defaults to 0. Bound to M-!. */ int reposition(int f, int n) { if (f == FALSE) /* default to 0 to center screen */ n = 0; curwp->w_force = n; curwp->w_flag |= WFFORCE; return TRUE; } /* * Refresh the screen. With no argument, it just does the refresh. With an * argument it recenters "." in the current window. Bound to "C-L". */ int redraw(int f, int n) { if (f == FALSE) sgarbf = TRUE; else { curwp->w_force = 0; /* Center dot. */ curwp->w_flag |= WFFORCE; } return TRUE; } /* * The command make the next window (next => down the screen) the current * window. There are no real errors, although the command does nothing if * there is only 1 window on the screen. Bound to "C-X C-N". * * with an argument this command finds the <n>th window from the top * * int f, n; default flag and numeric argument * */ int nextwind(int f, int n) { struct window *wp; int nwindows; /* total number of windows */ if (f) { /* first count the # of windows */ wp = wheadp; nwindows = 1; while (wp->w_wndp != NULL) { nwindows++; wp = wp->w_wndp; } /* if the argument is negative, it is the nth window from the bottom of the screen */ if (n < 0) n = nwindows + n + 1; /* if an argument, give them that window from the top */ if (n > 0 && n <= nwindows) { wp = wheadp; while (--n) wp = wp->w_wndp; } else { mlwrite("Window number out of range"); return FALSE; } } else if ((wp = curwp->w_wndp) == NULL) wp = wheadp; curwp = wp; curbp = wp->w_bufp; cknewwindow(); upmode(); return TRUE; } /* * This command makes the previous window (previous => up the screen) the * current window. There arn't any errors, although the command does not do a * lot if there is 1 window. */ int prevwind(int f, int n) { struct window *wp1; struct window *wp2; /* if we have an argument, we mean the nth window from the bottom */ if (f) return nextwind(f, -n); wp1 = wheadp; wp2 = curwp; if (wp1 == wp2) wp2 = NULL; while (wp1->w_wndp != wp2) wp1 = wp1->w_wndp; curwp = wp1; curbp = wp1->w_bufp; cknewwindow(); upmode(); return TRUE; } /* * This command moves the current window down by "arg" lines. Recompute the * top line in the window. The move up and move down code is almost completely * the same; most of the work has to do with reframing the window, and picking * a new dot. We share the code by having "move down" just be an interface to * "move up". Magic. Bound to "C-X C-N". */ int mvdnwind(int f, int n) { return mvupwind(f, -n); } /* * Move the current window up by "arg" lines. Recompute the new top line of * the window. Look to see if "." is still on the screen. If it is, you win. * If it isn't, then move "." to center it in the new framing of the window * (this command does not really move "."; it moves the frame). Bound to * "C-X C-P". */ int mvupwind(int f, int n) { struct line *lp; int i; lp = curwp->w_linep; if (n < 0) { while (n++ && lp != curbp->b_linep) lp = lforw(lp); } else { while (n-- && lback(lp) != curbp->b_linep) lp = lback(lp); } curwp->w_linep = lp; curwp->w_flag |= WFHARD; /* Mode line is OK. */ for (i = 0; i < curwp->w_ntrows; ++i) { if (lp == curwp->w_dotp) return TRUE; if (lp == curbp->b_linep) break; lp = lforw(lp); } lp = curwp->w_linep; i = curwp->w_ntrows / 2; while (i-- && lp != curbp->b_linep) lp = lforw(lp); curwp->w_dotp = lp; curwp->w_doto = 0; return TRUE; } /* * This command makes the current window the only window on the screen. Bound * to "C-X 1". Try to set the framing so that "." does not have to move on the * display. Some care has to be taken to keep the values of dot and mark in * the buffer structures right if the distruction of a window makes a buffer * become undisplayed. */ int onlywind(int f, int n) { struct window *wp; struct line *lp; int i; while (wheadp != curwp) { wp = wheadp; wheadp = wp->w_wndp; if (--wp->w_bufp->b_nwnd == 0) { wp->w_bufp->b_dotp = wp->w_dotp; wp->w_bufp->b_doto = wp->w_doto; wp->w_bufp->b_markp = wp->w_markp; wp->w_bufp->b_marko = wp->w_marko; } free((char *) wp); } while (curwp->w_wndp != NULL) { wp = curwp->w_wndp; curwp->w_wndp = wp->w_wndp; if (--wp->w_bufp->b_nwnd == 0) { wp->w_bufp->b_dotp = wp->w_dotp; wp->w_bufp->b_doto = wp->w_doto; wp->w_bufp->b_markp = wp->w_markp; wp->w_bufp->b_marko = wp->w_marko; } free((char *) wp); } lp = curwp->w_linep; i = curwp->w_toprow; while (i != 0 && lback(lp) != curbp->b_linep) { --i; lp = lback(lp); } curwp->w_toprow = 0; curwp->w_ntrows = term.t_nrow - 1; curwp->w_linep = lp; curwp->w_flag |= WFMODE | WFHARD; return TRUE; } /* * Delete the current window, placing its space in the window above, * or, if it is the top window, the window below. Bound to C-X 0. * * int f, n; arguments are ignored for this command */ int delwind(int f, int n) { struct window *wp; /* window to recieve deleted space */ struct window *lwp; /* ptr window before curwp */ int target; /* target line to search for */ /* if there is only one window, don't delete it */ if (wheadp->w_wndp == NULL) { mlwrite("Can not delete this window"); return FALSE; } /* find window before curwp in linked list */ wp = wheadp; lwp = NULL; while (wp != NULL) { if (wp == curwp) break; lwp = wp; wp = wp->w_wndp; } /* find recieving window and give up our space */ wp = wheadp; if (curwp->w_toprow == 0) { /* find the next window down */ target = curwp->w_ntrows + 1; while (wp != NULL) { if (wp->w_toprow == target) break; wp = wp->w_wndp; } if (wp == NULL) return FALSE; wp->w_toprow = 0; wp->w_ntrows += target; } else { /* find the next window up */ target = curwp->w_toprow - 1; while (wp != NULL) { if ((wp->w_toprow + wp->w_ntrows) == target) break; wp = wp->w_wndp; } if (wp == NULL) return FALSE; wp->w_ntrows += 1 + curwp->w_ntrows; } /* get rid of the current window */ if (--curwp->w_bufp->b_nwnd == 0) { curwp->w_bufp->b_dotp = curwp->w_dotp; curwp->w_bufp->b_doto = curwp->w_doto; curwp->w_bufp->b_markp = curwp->w_markp; curwp->w_bufp->b_marko = curwp->w_marko; } if (lwp == NULL) wheadp = curwp->w_wndp; else lwp->w_wndp = curwp->w_wndp; free((char *) curwp); curwp = wp; wp->w_flag |= WFHARD; curbp = wp->w_bufp; cknewwindow(); upmode(); return TRUE; } /* * Split the current window. A window smaller than 3 lines cannot be * split. An argument of 1 forces the cursor into the upper window, an * argument of two forces the cursor to the lower window. The only * other error that is possible is a "malloc" failure allocating the * structure for the new window. Bound to "C-X 2". * * int f, n; default flag and numeric argument */ int splitwind(int f, int n) { struct window *wp; struct line *lp; int ntru; int ntrl; int ntrd; struct window *wp1; struct window *wp2; if (curwp->w_ntrows < 3) { mlwrite("Cannot split a %d line window", curwp->w_ntrows); return FALSE; } wp = xmalloc(sizeof(struct window)); ++curbp->b_nwnd; /* Displayed twice. */ wp->w_bufp = curbp; wp->w_dotp = curwp->w_dotp; wp->w_doto = curwp->w_doto; wp->w_markp = curwp->w_markp; wp->w_marko = curwp->w_marko; wp->w_flag = 0; wp->w_force = 0; #if COLOR /* set the colors of the new window */ wp->w_fcolor = gfcolor; wp->w_bcolor = gbcolor; #endif ntru = (curwp->w_ntrows - 1) / 2; /* Upper size */ ntrl = (curwp->w_ntrows - 1) - ntru; /* Lower size */ lp = curwp->w_linep; ntrd = 0; while (lp != curwp->w_dotp) { ++ntrd; lp = lforw(lp); } lp = curwp->w_linep; if (((f == FALSE) && (ntrd <= ntru)) || ((f == TRUE) && (n == 1))) { /* Old is upper window. */ if (ntrd == ntru) /* Hit mode line. */ lp = lforw(lp); curwp->w_ntrows = ntru; wp->w_wndp = curwp->w_wndp; curwp->w_wndp = wp; wp->w_toprow = curwp->w_toprow + ntru + 1; wp->w_ntrows = ntrl; } else { /* Old is lower window */ wp1 = NULL; wp2 = wheadp; while (wp2 != curwp) { wp1 = wp2; wp2 = wp2->w_wndp; } if (wp1 == NULL) wheadp = wp; else wp1->w_wndp = wp; wp->w_wndp = curwp; wp->w_toprow = curwp->w_toprow; wp->w_ntrows = ntru; ++ntru; /* Mode line. */ curwp->w_toprow += ntru; curwp->w_ntrows = ntrl; while (ntru--) lp = lforw(lp); } curwp->w_linep = lp; /* Adjust the top lines */ wp->w_linep = lp; /* if necessary. */ curwp->w_flag |= WFMODE | WFHARD; wp->w_flag |= WFMODE | WFHARD; return TRUE; } /* * Enlarge the current window. Find the window that loses space. Make sure it * is big enough. If so, hack the window descriptions, and ask redisplay to do * all the hard work. You don't just set "force reframe" because dot would * move. Bound to "C-X Z". */ int enlargewind(int f, int n) { struct window *adjwp; struct line *lp; int i; if (n < 0) return shrinkwind(f, -n); if (wheadp->w_wndp == NULL) { mlwrite("Only one window"); return FALSE; } if ((adjwp = curwp->w_wndp) == NULL) { adjwp = wheadp; while (adjwp->w_wndp != curwp) adjwp = adjwp->w_wndp; } if (adjwp->w_ntrows <= n) { mlwrite("Impossible change"); return FALSE; } if (curwp->w_wndp == adjwp) { /* Shrink below. */ lp = adjwp->w_linep; for (i = 0; i < n && lp != adjwp->w_bufp->b_linep; ++i) lp = lforw(lp); adjwp->w_linep = lp; adjwp->w_toprow += n; } else { /* Shrink above. */ lp = curwp->w_linep; for (i = 0; i < n && lback(lp) != curbp->b_linep; ++i) lp = lback(lp); curwp->w_linep = lp; curwp->w_toprow -= n; } curwp->w_ntrows += n; adjwp->w_ntrows -= n; #if SCROLLCODE curwp->w_flag |= WFMODE | WFHARD | WFINS; adjwp->w_flag |= WFMODE | WFHARD | WFKILLS; #else curwp->w_flag |= WFMODE | WFHARD; adjwp->w_flag |= WFMODE | WFHARD; #endif return TRUE; } /* * Shrink the current window. Find the window that gains space. Hack at the * window descriptions. Ask the redisplay to do all the hard work. Bound to * "C-X C-Z". */ int shrinkwind(int f, int n) { struct window *adjwp; struct line *lp; int i; if (n < 0) return enlargewind(f, -n); if (wheadp->w_wndp == NULL) { mlwrite("Only one window"); return FALSE; } if ((adjwp = curwp->w_wndp) == NULL) { adjwp = wheadp; while (adjwp->w_wndp != curwp) adjwp = adjwp->w_wndp; } if (curwp->w_ntrows <= n) { mlwrite("Impossible change"); return FALSE; } if (curwp->w_wndp == adjwp) { /* Grow below. */ lp = adjwp->w_linep; for (i = 0; i < n && lback(lp) != adjwp->w_bufp->b_linep; ++i) lp = lback(lp); adjwp->w_linep = lp; adjwp->w_toprow -= n; } else { /* Grow above. */ lp = curwp->w_linep; for (i = 0; i < n && lp != curbp->b_linep; ++i) lp = lforw(lp); curwp->w_linep = lp; curwp->w_toprow += n; } curwp->w_ntrows -= n; adjwp->w_ntrows += n; #if SCROLLCODE curwp->w_flag |= WFMODE | WFHARD | WFKILLS; adjwp->w_flag |= WFMODE | WFHARD | WFINS; #else curwp->w_flag |= WFMODE | WFHARD; adjwp->w_flag |= WFMODE | WFHARD; #endif return TRUE; } /* * Resize the current window to the requested size * * int f, n; default flag and numeric argument */ int resize(int f, int n) { int clines; /* current # of lines in window */ /* must have a non-default argument, else ignore call */ if (f == FALSE) return TRUE; /* find out what to do */ clines = curwp->w_ntrows; /* already the right size? */ if (clines == n) return TRUE; return enlargewind(TRUE, n - clines); } /* * Pick a window for a pop-up. Split the screen if there is only one window. * Pick the uppermost window that isn't the current window. An LRU algorithm * might be better. Return a pointer, or NULL on error. */ struct window *wpopup(void) { struct window *wp; if (wheadp->w_wndp == NULL /* Only 1 window */ && splitwind(FALSE, 0) == FALSE) /* and it won't split */ return NULL; wp = wheadp; /* Find window to use */ while (wp != NULL && wp == curwp) wp = wp->w_wndp; return wp; } int scrnextup(int f, int n) { /* scroll the next window up (back) a page */ nextwind(FALSE, 1); backpage(f, n); prevwind(FALSE, 1); return TRUE; } int scrnextdw(int f, int n) { /* scroll the next window down (forward) a page */ nextwind(FALSE, 1); forwpage(f, n); prevwind(FALSE, 1); return TRUE; } int savewnd(int f, int n) { /* save ptr to current window */ swindow = curwp; return TRUE; } int restwnd(int f, int n) { /* restore the saved screen */ struct window *wp; /* find the window */ wp = wheadp; while (wp != NULL) { if (wp == swindow) { curwp = wp; curbp = wp->w_bufp; upmode(); return TRUE; } wp = wp->w_wndp; } mlwrite("(No such window exists)"); return FALSE; } /* * resize the screen, re-writing the screen * * int f; default flag * int n; numeric argument */ int newsize(int f, int n) { struct window *wp; /* current window being examined */ struct window *nextwp; /* next window to scan */ struct window *lastwp; /* last window scanned */ int lastline; /* screen line of last line of current window */ /* if the command defaults, assume the largest */ if (f == FALSE) n = term.t_mrow + 1; /* make sure it's in range */ if (n < 3 || n > term.t_mrow + 1) { mlwrite("%%Screen size out of range"); return FALSE; } if (term.t_nrow == n - 1) return TRUE; else if (term.t_nrow < n - 1) { /* go to the last window */ wp = wheadp; while (wp->w_wndp != NULL) wp = wp->w_wndp; /* and enlarge it as needed */ wp->w_ntrows = n - wp->w_toprow - 2; wp->w_flag |= WFHARD | WFMODE; } else { /* rebuild the window structure */ nextwp = wheadp; wp = NULL; lastwp = NULL; while (nextwp != NULL) { wp = nextwp; nextwp = wp->w_wndp; /* get rid of it if it is too low */ if (wp->w_toprow > n - 2) { /* save the point/mark if needed */ if (--wp->w_bufp->b_nwnd == 0) { wp->w_bufp->b_dotp = wp->w_dotp; wp->w_bufp->b_doto = wp->w_doto; wp->w_bufp->b_markp = wp->w_markp; wp->w_bufp->b_marko = wp->w_marko; } /* update curwp and lastwp if needed */ if (wp == curwp) curwp = wheadp; curbp = curwp->w_bufp; if (lastwp != NULL) lastwp->w_wndp = NULL; /* free the structure */ free((char *) wp); wp = NULL; } else { /* need to change this window size? */ lastline = wp->w_toprow + wp->w_ntrows - 1; if (lastline >= n - 2) { wp->w_ntrows = n - wp->w_toprow - 2; wp->w_flag |= WFHARD | WFMODE; } } lastwp = wp; } } /* screen is garbage */ term.t_nrow = n - 1; sgarbf = TRUE; return TRUE; } /* * resize the screen, re-writing the screen * * int f; default flag * int n; numeric argument */ int newwidth(int f, int n) { struct window *wp; /* if the command defaults, assume the largest */ if (f == FALSE) n = term.t_mcol; /* make sure it's in range */ if (n < 10 || n > term.t_mcol) { mlwrite("%%Screen width out of range"); return FALSE; } /* otherwise, just re-width it (no big deal) */ term.t_ncol = n; term.t_margin = n / 10; term.t_scrsiz = n - (term.t_margin * 2); /* florce all windows to redraw */ wp = wheadp; while (wp) { wp->w_flag |= WFHARD | WFMOVE | WFMODE; wp = wp->w_wndp; } sgarbf = TRUE; return TRUE; } int getwpos(void) { /* get screen offset of current line in current window */ int sline; /* screen line from top of window */ struct line *lp; /* scannile line pointer */ /* search down the line we want */ lp = curwp->w_linep; sline = 1; while (lp != curwp->w_dotp) { ++sline; lp = lforw(lp); } /* and return the value */ return sline; } void cknewwindow(void) { execute(META | SPEC | 'X', FALSE, 1); }
uemacs-master
window.c
/* * PES file parsing. * * All format credit goes to Robert Heel and * * https://bugs.launchpad.net/inkscape/+bug/247463 * * which has a php script to do so. He in turn seems to have * gotten it from NJ Crawford's C# PES viewer. I just turned * it into C. */ #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <string.h> #include "pes.h" static struct color color_def[256] = { { NULL, 0, 0, 0 }, { "Color1", 14, 31, 124 }, { "Color2", 10, 85, 163 }, { "Color3", 48, 135, 119 }, { "Color4", 75, 107, 175 }, { "Color5", 237, 23, 31 }, { "Color6", 209, 92, 0 }, { "Color7", 145, 54, 151 }, { "Color8", 228, 154, 203 }, { "Color9", 145, 95, 172 }, { "Color10", 157, 214, 125 }, { "Color11", 232, 169, 0 }, { "Color12", 254, 186, 53 }, { "Color13", 255, 255, 0 }, { "Color14", 112, 188, 31 }, { "Color15", 192, 148, 0 }, { "Color16", 168, 168, 168 }, { "Color17", 123, 111, 0 }, { "Color18", 255, 255, 179 }, { "Color19", 79, 85, 86 }, { "Black", 0, 0, 0 }, { "Color21", 11, 61, 145 }, { "Color22", 119, 1, 118 }, { "Color23", 41, 49, 51 }, { "Color24", 42, 19, 1 }, { "Color25", 246, 74, 138 }, { "Color26", 178, 118, 36 }, { "Color27", 252, 187, 196 }, { "Color28", 254, 55, 15 }, { "White", 240, 240, 240 }, { "Color30", 106, 28, 138 }, { "Color31", 168, 221, 196 }, { "Color32", 37, 132, 187 }, { "Color33", 254, 179, 67 }, { "Color34", 255, 240, 141 }, { "Color35", 208, 166, 96 }, { "Color36", 209, 84, 0 }, { "Color37", 102, 186, 73 }, { "Color38", 19, 74, 70 }, { "Color39", 135, 135, 135 }, { "Color40", 216, 202, 198 }, { "Color41", 67, 86, 7 }, { "Color42", 254, 227, 197 }, { "Color43", 249, 147, 188 }, { "Color44", 0, 56, 34 }, { "Color45", 178, 175, 212 }, { "Color46", 104, 106, 176 }, { "Color47", 239, 227, 185 }, { "Color48", 247, 56, 102 }, { "Color49", 181, 76, 100 }, { "Color50", 19, 43, 26 }, { "Color51", 199, 1, 85 }, { "Color52", 254, 158, 50 }, { "Color53", 168, 222, 235 }, { "Color54", 0, 103, 26 }, { "Color55", 78, 41, 144 }, { "Color56", 47, 126, 32 }, { "Color57", 253, 217, 222 }, { "Color58", 255, 217, 17 }, { "Color59", 9, 91, 166 }, { "Color60", 240, 249, 112 }, { "Color61", 227, 243, 91 }, { "Color62", 255, 200, 100 }, { "Color63", 255, 200, 150 }, { "Color64", 255, 200, 200 }, }; static struct color *my_colors[256]; #define CHUNKSIZE (8192) int read_file(int fd, struct region *region) { int len = 0, done = 0; char *buf = NULL; for (;;) { int space = len - done, ret; if (!space) { space = CHUNKSIZE; len += space; buf = realloc(buf, len); } ret = read(fd, buf + done, space); if (ret > 0) { done += ret; continue; } if (!ret) break; if (errno == EINTR || errno == EAGAIN) continue; free(buf); return -1; } /* "len+8" guarantees that there is some slop at the end */ region->ptr = realloc(buf, len+8); region->size = len; return 0; } int read_path(const char *path, struct region *region) { if (path) { int fd = open(path, O_RDONLY); if (fd > 0) { int ret = read_file(fd, region); int saved_errno = errno; close(fd); errno = saved_errno; return ret; } return fd; } return read_file(0, region); } #define get_u8(buf, offset) (*(unsigned char *)((offset)+(const char *)(buf))) #define get_le32(buf, offset) (*(unsigned int *)((offset)+(const char *)(buf))) static int parse_pes_colors(struct region *region, unsigned int pec) { const void *buf = region->ptr; int nr_colors = get_u8(buf, pec+48) + 1; int i; for (i = 0; i < nr_colors; i++) { struct color *color; color = color_def + get_u8(buf, pec+49+i); my_colors[i] = color; } return 0; } static struct pes_block *new_block(struct pes *pes) { struct pes_block *block = calloc(1, sizeof(*block)); if (block) { unsigned color = pes->nr_colors++; if (color >= sizeof(my_colors) / sizeof(my_colors[0])) { free(block); return NULL; } block->color = my_colors[color]; if (!block->color) { free(block); return NULL; } struct pes_block **pp = pes->last ? &pes->last->next : &pes->blocks; *pp = block; pes->last = block; } return block; } static int add_stitch(struct pes *pes, int x, int y, int jumpstitch) { struct pes_block *block = pes->last; struct stitch *stitch = block->stitch; int nr_stitches = block->nr_stitches; if (x < pes->min_x) pes->min_x = x; if (x > pes->max_x) pes->max_x = x; if (y < pes->min_y) pes->min_y = y; if (y > pes->max_y) pes->max_y = y; if (block->max_stitches == nr_stitches) { int new_stitches = (nr_stitches * 3) / 2 + 64; int size = new_stitches*sizeof(struct stitch); stitch = realloc(stitch, size); if (!stitch) return -1; block->max_stitches = new_stitches; block->stitch = stitch; } stitch[nr_stitches].x = x; stitch[nr_stitches].y = y; stitch[nr_stitches].jumpstitch = jumpstitch; block->nr_stitches = nr_stitches+1; return 0; } static int parse_pes_stitches(struct region *region, unsigned int pec, struct pes *pes) { int oldx, oldy; const unsigned char *buf = region->ptr, *p, *end; struct pes_block *block; p = buf + pec + 532; end = buf + region->size; oldx = oldy = 0; block = new_block(pes); if (!block) return -1; while (p < end) { int val1 = p[0], val2 = p[1], jumpstitch = 0; p += 2; if (val1 == 255 && !val2) return 0; if (val1 == 254 && val2 == 176) { if (block->nr_stitches) { block = new_block(pes); if (!block) return -1; } p++; /* Skip byte */ continue; } /* High bit set means 12-bit offset, otherwise 7-bit signed delta */ if (val1 & 0x80) { val1 = ((val1 & 15) << 8) + val2; /* Signed 12-bit arithmetic */ if (val1 & 2048) val1 -= 4096; val2 = *p++; jumpstitch = 1; } else { if (val1 & 64) val1 -= 128; } if (val2 & 0x80) { val2 = ((val2 & 15) << 8) + *p++; /* Signed 12-bit arithmetic */ if (val2 & 2048) val2 -= 4096; jumpstitch = 1; } else { if (val2 & 64) val2 -= 128; } val1 += oldx; val2 += oldy; oldx = val1; oldy = val2; if (add_stitch(pes, val1, val2, jumpstitch)) return -1; } return 0; } int parse_pes(struct region *region, struct pes *pes) { const void *buf = region->ptr; unsigned int size = region->size; unsigned int pec; if (size < 48) return -1; if (memcmp(buf, "#PES", 4)) return -1; pec = get_le32(buf, 8); if (pec > region->size) return -1; if (pec + 532 >= size) return -1; if (parse_pes_colors(region, pec) < 0) return -1; return parse_pes_stitches(region, pec, pes); }
pesconvert-master
pes.c
#include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <errno.h> #include <string.h> #include "pes.h" static void report(const char *fmt, va_list params) { vfprintf(stderr, fmt, params); } static void die(const char *fmt, ...) { va_list params; va_start(params, fmt); report(fmt, params); va_end(params); exit(1); } int main(int argc, char **argv) { double density = 1.0; int i, outputsize = -1; const char *output = NULL; struct region region; struct pes pes = { .min_x = 65535, .max_x = -65535, .min_y = 65535, .max_y = -65535, .blocks = NULL, .last = NULL, }; for (i = 1; i < argc; i++) { const char *arg = argv[i]; if (*arg == '-') { switch (arg[1]) { case 's': outputsize = atoi(argv[i+1]); i++; continue; case 'd': density = atof(argv[i+1]); i++; continue; } die("Unknown argument '%s'\n", arg); } if (!pes.blocks) { if (read_path(arg, &region)) die("Unable to read file %s (%s)\n", arg, strerror(errno)); if (parse_pes(&region, &pes) < 0) die("Unable to parse PES file\n"); continue; } if (!output) { output = arg; continue; } die("Too many arguments (%s)\n", arg); } if (!pes.blocks) die("Need an input PES file\n"); if (!output) die("Need a png output file name\n"); output_cairo(&pes, output, outputsize, density); return 0; }
pesconvert-master
main.c
#include <cairo/cairo.h> #include "pes.h" #define X(stitch) (((stitch)->x - pes->min_x) * scale) #define Y(stitch) (((stitch)->y - pes->min_y) * scale) void output_cairo(struct pes *pes, const char *filename, int size, double density) { int width = pes->max_x - pes->min_x, outw; int height = pes->max_y - pes->min_y, outh; double scale = 1.0; cairo_surface_t *surface; cairo_t *cr; if (size > 0) { int maxd = width > height ? width : height; scale = (double) size / maxd; } outw = width * scale; outh = height * scale; surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, outw+1, outh+1); cr = cairo_create (surface); for (struct pes_block *block = pes->blocks; block; block = block->next) { struct color *c = block->color; struct stitch *stitch = block->stitch; int i; if (!block->nr_stitches) continue; cairo_set_source_rgb(cr, c->r / 255.0, c->g / 255.0, c->b / 255.0); cairo_move_to(cr, X(stitch), Y(stitch)); for (i = 1; i < block->nr_stitches; i++) { ++stitch; if(!stitch->jumpstitch) cairo_line_to(cr, X(stitch), Y(stitch)); else cairo_move_to(cr, X(stitch), Y(stitch)); } cairo_set_line_width(cr, scale * density); cairo_set_line_cap(cr, CAIRO_LINE_CAP_ROUND); cairo_set_line_join(cr, CAIRO_LINE_JOIN_ROUND); cairo_stroke(cr); } cairo_surface_write_to_png(surface, filename); }
pesconvert-master
cairo.c
#include <stdio.h> #include <stdlib.h> #include <png.h> #include "pes.h" void output_png(struct pes *pes) { int i; int width = pes->max_x - pes->min_x + 1; int height = pes->max_y - pes->min_y + 1; int outw = 128, outh = 128; png_byte **rows; struct pes_block *block; png_structp png_ptr; png_infop info_ptr; rows = calloc(sizeof(*rows), outh); for (i = 0; i < outh; i++) rows[i] = calloc(sizeof(png_byte)*4, outw); block = pes->blocks; while (block) { struct color *c = block->color; struct stitch *stitch = block->stitch; int i; for (i = 0; i < block->nr_stitches; i++, stitch++) { int x = (stitch->x - pes->min_x) * outw / width; int y = (stitch->y - pes->min_y) * outh / height; png_byte *ptr = rows[y] + x*4; ptr[0] = c->r; ptr[1] = c->g; ptr[2] = c->b; ptr[3] = 255; } block = block->next; } png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); info_ptr = png_create_info_struct(png_ptr); png_init_io(png_ptr, stdout); png_set_IHDR(png_ptr, info_ptr, outw, outh, 8, PNG_COLOR_TYPE_RGBA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_write_info(png_ptr, info_ptr); png_write_image(png_ptr, rows); png_write_end(png_ptr, NULL); }
pesconvert-master
png.c
#include <stdio.h> #include "pes.h" void output_svg(struct pes *pes) { printf("<?xml version=\"1.0\"?>\n"); printf("<svg xmlns=\"http://www.w3.org/2000/svg\" " "xlink=\"http://www.w3.org/1999/xlink\" " "ev=\"http://www.w3.org/2001/xml-events\" " "version=\"1.1\" " "baseProfile=\"full\" " "width=\"%d\" height=\"%d\">", pes->max_x - pes->min_x, pes->max_y - pes->min_y); for (struct pes_block *block = pes->blocks; block; block = block->next) { if (!block->nr_stitches) continue; int i; printf("<path stroke=\"#%02x%02x%02x\" fill=\"none\" d=\"M %d %d", block->color->r, block->color->g, block->color->b, block->stitch[0].x - pes->min_x, block->stitch[0].y - pes->min_y); for (i = 1; i < block->nr_stitches; i++) printf(" L %d %d", block->stitch[i].x - pes->min_x, block->stitch[i].y - pes->min_y); printf("\"/>"); } printf("</svg>\n"); }
pesconvert-master
svg.c
// SPDX-License-Identifier: GPL-2.0 #include "trip.h" #include "dive.h" #include "subsurface-time.h" #include "subsurface-string.h" #include "selection.h" #include "table.h" #include "core/qthelper.h" struct trip_table trip_table; #ifdef DEBUG_TRIP void dump_trip_list(void) { dive_trip_t *trip; int i = 0; timestamp_t last_time = 0; for (i = 0; i < trip_table.nr; ++i) { struct tm tm; trip = trip_table.trips[i]; utc_mkdate(trip_date(trip), &tm); if (trip_date(trip) < last_time) printf("\n\ntrip_table OUT OF ORDER!!!\n\n\n"); printf("%s trip %d to \"%s\" on %04u-%02u-%02u %02u:%02u:%02u (%d dives - %p)\n", trip->autogen ? "autogen " : "", i + 1, trip->location, tm.tm_year, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, trip->dives.nr, trip); last_time = trip_date(trip); } printf("-----\n"); } #endif /* free resources associated with a trip structure */ void free_trip(dive_trip_t *trip) { if (trip) { free(trip->location); free(trip->notes); free(trip->dives.dives); free(trip); } } /* Trip table functions */ static MAKE_GET_IDX(trip_table, struct dive_trip *, trips) static MAKE_GROW_TABLE(trip_table, struct dive_trip *, trips) static MAKE_GET_INSERTION_INDEX(trip_table, struct dive_trip *, trips, trip_less_than) static MAKE_ADD_TO(trip_table, struct dive_trip *, trips) static MAKE_REMOVE_FROM(trip_table, trips) MAKE_SORT(trip_table, struct dive_trip *, trips, comp_trips) MAKE_REMOVE(trip_table, struct dive_trip *, trip) MAKE_CLEAR_TABLE(trip_table, trips, trip) timestamp_t trip_date(const struct dive_trip *trip) { if (!trip || trip->dives.nr == 0) return 0; return trip->dives.dives[0]->when; } timestamp_t trip_enddate(const struct dive_trip *trip) { if (!trip || trip->dives.nr == 0) return 0; return dive_endtime(trip->dives.dives[trip->dives.nr - 1]); } /* check if we have a trip right before / after this dive */ bool is_trip_before_after(const struct dive *dive, bool before) { int idx = get_idx_by_uniq_id(dive->id); if (before) { const struct dive *d = get_dive(idx - 1); if (d && d->divetrip) return true; } else { const struct dive *d = get_dive(idx + 1); if (d && d->divetrip) return true; } return false; } /* Add dive to a trip. Caller is responsible for removing dive * from trip beforehand. */ void add_dive_to_trip(struct dive *dive, dive_trip_t *trip) { if (dive->divetrip == trip) return; if (dive->divetrip) SSRF_INFO("Warning: adding dive to trip that has trip set\n"); insert_dive(&trip->dives, dive); dive->divetrip = trip; } /* remove a dive from the trip it's associated to, but don't delete the * trip if this was the last dive in the trip. the caller is responsible * for removing the trip, if the trip->dives.nr went to 0. */ struct dive_trip *unregister_dive_from_trip(struct dive *dive) { dive_trip_t *trip = dive->divetrip; if (!trip) return NULL; remove_dive(dive, &trip->dives); dive->divetrip = NULL; return trip; } static void delete_trip(dive_trip_t *trip, struct trip_table *trip_table_arg) { remove_trip(trip, trip_table_arg); free_trip(trip); } void remove_dive_from_trip(struct dive *dive, struct trip_table *trip_table_arg) { struct dive_trip *trip = unregister_dive_from_trip(dive); if (trip && trip->dives.nr == 0) delete_trip(trip, trip_table_arg); } dive_trip_t *alloc_trip(void) { dive_trip_t *res = calloc(1, sizeof(dive_trip_t)); res->id = dive_getUniqID(); return res; } /* insert the trip into the trip table */ void insert_trip(dive_trip_t *dive_trip, struct trip_table *trip_table_arg) { int idx = trip_table_get_insertion_index(trip_table_arg, dive_trip); add_to_trip_table(trip_table_arg, idx, dive_trip); #ifdef DEBUG_TRIP dump_trip_list(); #endif } dive_trip_t *create_trip_from_dive(struct dive *dive) { dive_trip_t *trip; trip = alloc_trip(); trip->location = copy_string(get_dive_location(dive)); return trip; } dive_trip_t *create_and_hookup_trip_from_dive(struct dive *dive, struct trip_table *trip_table_arg) { dive_trip_t *dive_trip; dive_trip = create_trip_from_dive(dive); add_dive_to_trip(dive, dive_trip); insert_trip(dive_trip, trip_table_arg); return dive_trip; } /* random threshold: three days without diving -> new trip * this works very well for people who usually dive as part of a trip and don't * regularly dive at a local facility; this is why trips are an optional feature */ #define TRIP_THRESHOLD 3600 * 24 * 3 /* * Find a trip a new dive should be autogrouped with. If no such trips * exist, allocate a new trip. The bool "*allocated" is set to true * if a new trip was allocated. */ dive_trip_t *get_trip_for_new_dive(struct dive *new_dive, bool *allocated) { struct dive *d; dive_trip_t *trip; int i; /* Find dive that is within TRIP_THRESHOLD of current dive */ for_each_dive(i, d) { /* Check if we're past the range of possible dives */ if (d->when >= new_dive->when + TRIP_THRESHOLD) break; if (d->when + TRIP_THRESHOLD >= new_dive->when && d->divetrip) { /* Found a dive with trip in the range */ *allocated = false; return d->divetrip; } } /* Didn't find a trip -> allocate a new one */ trip = create_trip_from_dive(new_dive); trip->autogen = true; *allocated = true; return trip; } /* lookup of trip in main trip_table based on its id */ dive_trip_t *get_trip_by_uniq_id(int tripId) { for (int i = 0; i < trip_table.nr; i++) { if (trip_table.trips[i]->id == tripId) return trip_table.trips[i]; } return NULL; } /* Check if two trips overlap time-wise up to trip threshold. */ bool trips_overlap(const struct dive_trip *t1, const struct dive_trip *t2) { /* First, handle the empty-trip cases. */ if (t1->dives.nr == 0 || t2->dives.nr == 0) return 0; if (trip_date(t1) < trip_date(t2)) return trip_enddate(t1) + TRIP_THRESHOLD >= trip_date(t2); else return trip_enddate(t2) + TRIP_THRESHOLD >= trip_date(t1); } /* * Collect dives for auto-grouping. Pass in first dive which should be checked. * Returns range of dives that should be autogrouped and trip it should be * associated to. If the returned trip was newly allocated, the last bool * is set to true. Caller still has to register it in the system. Note * whereas this looks complicated - it is needed by the undo-system, which * manually injects the new trips. If there are no dives to be autogrouped, * return NULL. */ dive_trip_t *get_dives_to_autogroup(struct dive_table *table, int start, int *from, int *to, bool *allocated) { int i; struct dive *lastdive = NULL; /* Find first dive that should be merged and remember any previous * dive that could be merged into. */ for (i = start; i < table->nr; i++) { struct dive *dive = table->dives[i]; dive_trip_t *trip; if (dive->divetrip) { lastdive = dive; continue; } /* Only consider dives that have not been explicitly removed from * a dive trip by the user. */ if (dive->notrip) { lastdive = NULL; continue; } /* We found a dive, let's see if we have to allocate a new trip */ if (!lastdive || dive->when >= lastdive->when + TRIP_THRESHOLD) { /* allocate new trip */ trip = create_trip_from_dive(dive); trip->autogen = true; *allocated = true; } else { /* use trip of previous dive */ trip = lastdive->divetrip; *allocated = false; } // Now, find all dives that will be added to this trip lastdive = dive; *from = i; for (*to = *from + 1; *to < table->nr; (*to)++) { dive = table->dives[*to]; if (dive->divetrip || dive->notrip || dive->when >= lastdive->when + TRIP_THRESHOLD) break; if (get_dive_location(dive) && !trip->location) trip->location = copy_string(get_dive_location(dive)); lastdive = dive; } return trip; } /* Did not find anyhting - mark as end */ return NULL; } void deselect_dives_in_trip(struct dive_trip *trip) { if (!trip) return; for (int i = 0; i < trip->dives.nr; ++i) deselect_dive(trip->dives.dives[i]); } void select_dives_in_trip(struct dive_trip *trip) { struct dive *dive; if (!trip) return; for (int i = 0; i < trip->dives.nr; ++i) { dive = trip->dives.dives[i]; if (!dive->hidden_by_filter) select_dive(dive); } } /* Out of two strings, copy the string that is not empty (if any). */ static char *copy_non_empty_string(const char *a, const char *b) { return copy_string(empty_string(b) ? a : b); } /* This combines the information of two trips, generating a * new trip. To support undo, we have to preserve the old trips. */ dive_trip_t *combine_trips(struct dive_trip *trip_a, struct dive_trip *trip_b) { dive_trip_t *trip; trip = alloc_trip(); trip->location = copy_non_empty_string(trip_a->location, trip_b->location); trip->notes = copy_non_empty_string(trip_a->notes, trip_b->notes); return trip; } /* Trips are compared according to the first dive in the trip. */ int comp_trips(const struct dive_trip *a, const struct dive_trip *b) { /* This should never happen, nevertheless don't crash on trips * with no (or worse a negative number of) dives. */ if (a->dives.nr <= 0) return b->dives.nr <= 0 ? 0 : -1; if (b->dives.nr <= 0) return 1; return comp_dives(a->dives.dives[0], b->dives.dives[0]); } bool trip_less_than(const struct dive_trip *a, const struct dive_trip *b) { return comp_trips(a, b) < 0; } static bool is_same_day(timestamp_t trip_when, timestamp_t dive_when) { static timestamp_t twhen = (timestamp_t) 0; static struct tm tmt; struct tm tmd; utc_mkdate(dive_when, &tmd); if (twhen != trip_when) { twhen = trip_when; utc_mkdate(twhen, &tmt); } return (tmd.tm_mday == tmt.tm_mday) && (tmd.tm_mon == tmt.tm_mon) && (tmd.tm_year == tmt.tm_year); } bool trip_is_single_day(const struct dive_trip *trip) { if (trip->dives.nr <= 1) return true; return is_same_day(trip->dives.dives[0]->when, trip->dives.dives[trip->dives.nr - 1]->when); } int trip_shown_dives(const struct dive_trip *trip) { int res = 0; for (int i = 0; i < trip->dives.nr; ++i) { if (!trip->dives.dives[i]->hidden_by_filter) res++; } return res; }
subsurface-for-dirk-master
core/trip.c
// SPDX-License-Identifier: GPL-2.0 #ifdef __clang__ // Clang has a bug on zero-initialization of C structs. #pragma clang diagnostic ignored "-Wmissing-field-initializers" #endif #include "ssrf.h" #include "dive.h" #include "sample.h" #include "subsurface-string.h" #include "parse.h" #include "divelist.h" #include "device.h" #include "membuffer.h" #include "gettext.h" #include <stdlib.h> static int shearwater_cylinders(void *param, int columns, char **data, char **column) { UNUSED(columns); UNUSED(column); struct parser_state *state = (struct parser_state *)param; cylinder_t *cyl; int o2 = lrint(strtod_flags(data[0], NULL, 0) * 1000); int he = lrint(strtod_flags(data[1], NULL, 0) * 1000); /* Shearwater allows entering only 99%, not 100% * so assume 99% to be pure oxygen */ if (o2 == 990 && he == 0) o2 = 1000; cyl = cylinder_start(state); cyl->gasmix.o2.permille = o2; cyl->gasmix.he.permille = he; cylinder_end(state); return 0; } static int shearwater_changes(void *param, int columns, char **data, char **column) { UNUSED(columns); UNUSED(column); struct parser_state *state = (struct parser_state *)param; cylinder_t *cyl; if (columns != 3) { return 1; } if (!data[0] || !data[1] || !data[2]) { return 2; } int o2 = lrint(strtod_flags(data[1], NULL, 0) * 1000); int he = lrint(strtod_flags(data[2], NULL, 0) * 1000); /* Shearwater allows entering only 99%, not 100% * so assume 99% to be pure oxygen */ if (o2 == 990 && he == 0) o2 = 1000; // Find the cylinder index int index; bool found = false; for (index = 0; index < state->cur_dive->cylinders.nr; ++index) { const cylinder_t *cyl = get_cylinder(state->cur_dive, index); if (cyl->gasmix.o2.permille == o2 && cyl->gasmix.he.permille == he) { found = true; break; } } if (!found) { // Cylinder not found, creating a new one cyl = cylinder_start(state); cyl->gasmix.o2.permille = o2; cyl->gasmix.he.permille = he; cylinder_end(state); } add_gas_switch_event(state->cur_dive, get_dc(state), state->sample_rate ? atoi(data[0]) / state->sample_rate * 10 : atoi(data[0]), index); return 0; } static int shearwater_profile_sample(void *param, int columns, char **data, char **column) { UNUSED(columns); UNUSED(column); struct parser_state *state = (struct parser_state *)param; int d6, d7; sample_start(state); /* * If we have sample_rate, we use self calculated sample number * to count the sample time. * If we do not have sample_rate, we try to use the sample time * provided by Shearwater as is. */ if (data[9] && state->sample_rate) state->cur_sample->time.seconds = atoi(data[9]) * state->sample_rate; else if (data[0]) state->cur_sample->time.seconds = atoi(data[0]); if (data[1]) state->cur_sample->depth.mm = state->metric ? lrint(strtod_flags(data[1], NULL, 0) * 1000) : feet_to_mm(strtod_flags(data[1], NULL, 0)); if (data[2]) state->cur_sample->temperature.mkelvin = state->metric ? C_to_mkelvin(strtod_flags(data[2], NULL, 0)) : F_to_mkelvin(strtod_flags(data[2], NULL, 0)); if (data[3]) { state->cur_sample->setpoint.mbar = lrint(strtod_flags(data[3], NULL, 0) * 1000); } if (data[4]) state->cur_sample->ndl.seconds = atoi(data[4]) * 60; if (data[5]) state->cur_sample->cns = atoi(data[5]); if (data[6]) { d6 = atoi(data[6]); if (d6 > 0) { state->cur_sample->stopdepth.mm = state->metric ? d6 * 1000 : feet_to_mm(d6); state->cur_sample->in_deco = 1; } else if (data[7]) { d7 = atoi(data[7]); if (d7 > 0) { state->cur_sample->stopdepth.mm = state->metric ? d7 * 1000 : feet_to_mm(d7); if (data[8]) state->cur_sample->stoptime.seconds = atoi(data[8]) * 60; state->cur_sample->in_deco = 1; } else { state->cur_sample->in_deco = 0; } } else { state->cur_sample->in_deco = 0; } } /* We don't actually have data[3], but it should appear in the * SQL query at some point. if (data[3]) state->cur_sample->pressure[0].mbar = state->metric ? atoi(data[3]) * 1000 : psi_to_mbar(atoi(data[3])); */ sample_end(state); return 0; } static int shearwater_ai_profile_sample(void *param, int columns, char **data, char **column) { UNUSED(columns); UNUSED(column); struct parser_state *state = (struct parser_state *)param; int d6, d9; sample_start(state); /* * If we have sample_rate, we use self calculated sample number * to count the sample time. * If we do not have sample_rate, we try to use the sample time * provided by Shearwater as is. */ if (data[11] && state->sample_rate) state->cur_sample->time.seconds = atoi(data[11]) * state->sample_rate; else if (data[0]) state->cur_sample->time.seconds = atoi(data[0]); if (data[1]) state->cur_sample->depth.mm = state->metric ? lrint(strtod_flags(data[1], NULL, 0) * 1000) : feet_to_mm(strtod_flags(data[1], NULL, 0)); if (data[2]) state->cur_sample->temperature.mkelvin = state->metric ? C_to_mkelvin(strtod_flags(data[2], NULL, 0)) : F_to_mkelvin(strtod_flags(data[2], NULL, 0)); if (data[3]) { state->cur_sample->setpoint.mbar = lrint(strtod_flags(data[3], NULL, 0) * 1000); } if (data[4]) state->cur_sample->ndl.seconds = atoi(data[4]) * 60; if (data[5]) state->cur_sample->cns = atoi(data[5]); if (data[6]) { d6 = atoi(data[6]); if (d6 > 0) { state->cur_sample->stopdepth.mm = state->metric ? d6 * 1000 : feet_to_mm(d6); state->cur_sample->in_deco = 1; } else if (data[9]) { d9 = atoi(data[9]); if (d9 > 0) { state->cur_sample->stopdepth.mm = state->metric ? d9 * 1000 : feet_to_mm(d9); if (data[10]) state->cur_sample->stoptime.seconds = atoi(data[10]) * 60; state->cur_sample->in_deco = 1; } else { state->cur_sample->in_deco = 0; } } else { state->cur_sample->in_deco = 0; } } /* * I have seen sample log where the sample pressure had to be multiplied by 2. However, * currently this seems to be corrected in ShearWater, so we are no longer taking this into * account. * * Also, missing values might be nowadays 8184, even though an old log I have received has * 8190. Thus discarding values over 8180 here. */ if (data[7] && atoi(data[7]) < 8180) { state->cur_sample->pressure[0].mbar = psi_to_mbar(atoi(data[7])); } if (data[8] && atoi(data[8]) < 8180) state->cur_sample->pressure[1].mbar = psi_to_mbar(atoi(data[8])); sample_end(state); return 0; } static int shearwater_mode(void *param, int columns, char **data, char **column) { UNUSED(columns); UNUSED(column); struct parser_state *state = (struct parser_state *)param; if (data[0]) state->cur_dive->dc.divemode = atoi(data[0]) == 0 ? CCR : OC; return 0; } static int shearwater_dive(void *param, int columns, char **data, char **column) { UNUSED(columns); UNUSED(column); int retval = 0; struct parser_state *state = (struct parser_state *)param; sqlite3 *handle = state->sql_handle; char get_profile_template[] = "select currentTime,currentDepth,waterTemp,averagePPO2,currentNdl,CNSPercent,decoCeiling,firstStopDepth,firstStopTime from dive_log_records where diveLogId=%ld"; char get_profile_template_ai[] = "select currentTime,currentDepth,waterTemp,averagePPO2,currentNdl,CNSPercent,decoCeiling,aiSensor0_PressurePSI,aiSensor1_PressurePSI,firstStopDepth,firstStopTime from dive_log_records where diveLogId = %ld"; char get_cylinder_template[] = "select fractionO2,fractionHe from dive_log_records where diveLogId = %ld group by fractionO2,fractionHe"; char get_changes_template[] = "select a.currentTime,a.fractionO2,a.fractionHe from dive_log_records as a,dive_log_records as b where (a.id - 1) = b.id and (a.fractionO2 != b.fractionO2 or a.fractionHe != b.fractionHe) and a.diveLogId=b.divelogId and a.diveLogId = %ld"; char get_mode_template[] = "select distinct currentCircuitSetting from dive_log_records where diveLogId = %ld"; char get_buffer[1024]; dive_start(state); state->cur_dive->number = atoi(data[0]); state->cur_dive->when = (time_t)(atol(data[1])); long int dive_id = atol(data[11]); if (data[2]) add_dive_site(data[2], state->cur_dive, state); if (data[3]) utf8_string(data[3], &state->cur_dive->buddy); if (data[4]) utf8_string(data[4], &state->cur_dive->notes); state->metric = atoi(data[5]) == 1 ? 0 : 1; /* TODO: verify that metric calculation is correct */ if (data[6]) state->cur_dive->dc.maxdepth.mm = state->metric ? lrint(strtod_flags(data[6], NULL, 0) * 1000) : feet_to_mm(strtod_flags(data[6], NULL, 0)); if (data[7]) state->cur_dive->dc.duration.seconds = atoi(data[7]) * 60; if (data[8]) state->cur_dive->dc.surface_pressure.mbar = atoi(data[8]); /* * TODO: the deviceid hash should be calculated here. */ settings_start(state); dc_settings_start(state); if (data[9]) utf8_string(data[9], &state->cur_settings.dc.serial_nr); if (data[10]) { switch (atoi(data[10])) { case 2: state->cur_settings.dc.model = strdup("Shearwater Petrel/Perdix"); break; case 4: state->cur_settings.dc.model = strdup("Shearwater Predator"); break; default: state->cur_settings.dc.model = strdup("Shearwater import"); break; } } state->cur_settings.dc.deviceid = atoi(data[9]); dc_settings_end(state); settings_end(state); if (data[10]) { switch (atoi(data[10])) { case 2: state->cur_dive->dc.model = strdup("Shearwater Petrel/Perdix"); break; case 4: state->cur_dive->dc.model = strdup("Shearwater Predator"); break; default: state->cur_dive->dc.model = strdup("Shearwater import"); break; } } if (data[11]) { snprintf(get_buffer, sizeof(get_buffer) - 1, get_mode_template, dive_id); retval = sqlite3_exec(handle, get_buffer, &shearwater_mode, state, NULL); if (retval != SQLITE_OK) { fprintf(stderr, "%s", "Database query shearwater_mode failed.\n"); return 1; } } snprintf(get_buffer, sizeof(get_buffer) - 1, get_cylinder_template, dive_id); retval = sqlite3_exec(handle, get_buffer, &shearwater_cylinders, state, NULL); if (retval != SQLITE_OK) { fprintf(stderr, "%s", "Database query shearwater_cylinders failed.\n"); return 1; } snprintf(get_buffer, sizeof(get_buffer) - 1, get_changes_template, dive_id); retval = sqlite3_exec(handle, get_buffer, &shearwater_changes, state, NULL); if (retval != SQLITE_OK) { fprintf(stderr, "%s", "Database query shearwater_changes failed.\n"); return 1; } snprintf(get_buffer, sizeof(get_buffer) - 1, get_profile_template_ai, dive_id); retval = sqlite3_exec(handle, get_buffer, &shearwater_ai_profile_sample, state, NULL); if (retval != SQLITE_OK) { snprintf(get_buffer, sizeof(get_buffer) - 1, get_profile_template, dive_id); retval = sqlite3_exec(handle, get_buffer, &shearwater_profile_sample, state, NULL); if (retval != SQLITE_OK) { fprintf(stderr, "%s", "Database query shearwater_profile_sample failed.\n"); return 1; } } dive_end(state); return SQLITE_OK; } static int shearwater_cloud_dive(void *param, int columns, char **data, char **column) { UNUSED(columns); UNUSED(column); int retval = 0; struct parser_state *state = (struct parser_state *)param; sqlite3 *handle = state->sql_handle; /* * Since Shearwater reported sample time can be totally bogus, * we need to calculate the sample number by ourselves. The * calculated sample number is multiplied by sample interval * giving us correct sample time. */ char get_profile_template[] = "select currentTime,currentDepth,waterTemp,averagePPO2,currentNdl,CNSPercent,decoCeiling,firstStopDepth,firstStopTime,(select count(0) from dive_log_records r where r.id < d.id and r.diveLogId = %ld and r.currentTime > 0) as row from dive_log_records d where d.diveLogId=%ld and d.currentTime > 0"; char get_profile_template_ai[] = "select currentTime,currentDepth,waterTemp,averagePPO2,currentNdl,CNSPercent,decoCeiling,aiSensor0_PressurePSI,aiSensor1_PressurePSI,firstStopDepth,firstStopTime,(select count(0) from dive_log_records r where r.id < d.id and r.diveLogId = %ld and r.currentTime > 0) as row from dive_log_records d where d.diveLogId = %ld and d.currentTime > 0"; char get_cylinder_template[] = "select fractionO2 / 100,fractionHe / 100 from dive_log_records where diveLogId = %ld group by fractionO2,fractionHe"; char get_first_gas_template[] = "select currentTime, fractionO2 / 100, fractionHe / 100 from dive_log_records where diveLogId = %ld limit 1"; char get_changes_template[] = "select a.currentTime,a.fractionO2 / 100,a.fractionHe /100 from dive_log_records as a,dive_log_records as b where (a.id - 1) = b.id and (a.fractionO2 != b.fractionO2 or a.fractionHe != b.fractionHe) and a.diveLogId=b.divelogId and a.diveLogId = %ld and a.fractionO2 > 0 and b.fractionO2 > 0"; char get_mode_template[] = "select distinct currentCircuitSetting from dive_log_records where diveLogId = %ld"; char get_buffer[1024]; dive_start(state); state->cur_dive->number = atoi(data[0]); state->cur_dive->when = (time_t)(atol(data[1])); long int dive_id = atol(data[11]); if (data[12]) state->sample_rate = atoi(data[12]); else state->sample_rate = 0; if (data[2]) add_dive_site(data[2], state->cur_dive, state); if (data[3]) utf8_string(data[3], &state->cur_dive->buddy); if (data[4]) utf8_string(data[4], &state->cur_dive->notes); state->metric = atoi(data[5]) == 1 ? 0 : 1; /* TODO: verify that metric calculation is correct */ if (data[6]) state->cur_dive->dc.maxdepth.mm = state->metric ? lrint(strtod_flags(data[6], NULL, 0) * 1000) : feet_to_mm(strtod_flags(data[6], NULL, 0)); if (data[7]) state->cur_dive->dc.duration.seconds = atoi(data[7]); if (data[8]) state->cur_dive->dc.surface_pressure.mbar = atoi(data[8]); /* * TODO: the deviceid hash should be calculated here. */ settings_start(state); dc_settings_start(state); if (data[9]) utf8_string(data[9], &state->cur_settings.dc.serial_nr); if (data[10]) { switch (atoi(data[10])) { case 2: state->cur_settings.dc.model = strdup("Shearwater Petrel/Perdix"); break; case 4: state->cur_settings.dc.model = strdup("Shearwater Predator"); break; default: state->cur_settings.dc.model = strdup("Shearwater import"); break; } } state->cur_settings.dc.deviceid = atoi(data[9]); dc_settings_end(state); settings_end(state); if (data[10]) { switch (atoi(data[10])) { case 2: state->cur_dive->dc.model = strdup("Shearwater Petrel/Perdix"); break; case 4: state->cur_dive->dc.model = strdup("Shearwater Predator"); break; default: state->cur_dive->dc.model = strdup("Shearwater import"); break; } } if (data[11]) { snprintf(get_buffer, sizeof(get_buffer) - 1, get_mode_template, dive_id); retval = sqlite3_exec(handle, get_buffer, &shearwater_mode, state, NULL); if (retval != SQLITE_OK) { fprintf(stderr, "%s", "Database query shearwater_mode failed.\n"); return 1; } } snprintf(get_buffer, sizeof(get_buffer) - 1, get_cylinder_template, dive_id); retval = sqlite3_exec(handle, get_buffer, &shearwater_cylinders, state, NULL); if (retval != SQLITE_OK) { fprintf(stderr, "%s", "Database query shearwater_cylinders failed.\n"); return 1; } snprintf(get_buffer, sizeof(get_buffer) - 1, get_first_gas_template, dive_id); retval = sqlite3_exec(handle, get_buffer, &shearwater_changes, state, NULL); if (retval != SQLITE_OK) { fprintf(stderr, "%s", "Database query shearwater_changes failed.\n"); return 1; } snprintf(get_buffer, sizeof(get_buffer) - 1, get_changes_template, dive_id); retval = sqlite3_exec(handle, get_buffer, &shearwater_changes, state, NULL); if (retval != SQLITE_OK) { fprintf(stderr, "%s", "Database query shearwater_changes failed.\n"); return 1; } snprintf(get_buffer, sizeof(get_buffer) - 1, get_profile_template_ai, dive_id, dive_id); retval = sqlite3_exec(handle, get_buffer, &shearwater_ai_profile_sample, state, NULL); if (retval != SQLITE_OK) { snprintf(get_buffer, sizeof(get_buffer) - 1, get_profile_template, dive_id, dive_id); retval = sqlite3_exec(handle, get_buffer, &shearwater_profile_sample, state, NULL); if (retval != SQLITE_OK) { fprintf(stderr, "%s", "Database query shearwater_profile_sample failed.\n"); return 1; } } dive_end(state); return SQLITE_OK; } int parse_shearwater_buffer(sqlite3 *handle, const char *url, const char *buffer, int size, struct dive_table *table, struct trip_table *trips, struct dive_site_table *sites, struct device_table *devices) { UNUSED(buffer); UNUSED(size); int retval; struct parser_state state; init_parser_state(&state); state.target_table = table; state.trips = trips; state.sites = sites; state.devices = devices; state.sql_handle = handle; // So far have not seen any sample rate in Shearwater Desktop state.sample_rate = 0; char get_dives[] = "select l.number,timestamp,location||' / '||site,buddy,notes,imperialUnits,maxDepth,maxTime,startSurfacePressure,computerSerial,computerModel,i.diveId FROM dive_info AS i JOIN dive_logs AS l ON i.diveId=l.diveId"; retval = sqlite3_exec(handle, get_dives, &shearwater_dive, &state, NULL); free_parser_state(&state); if (retval != SQLITE_OK) { fprintf(stderr, "Database query failed '%s'.\n", url); return 1; } return 0; } int parse_shearwater_cloud_buffer(sqlite3 *handle, const char *url, const char *buffer, int size, struct dive_table *table, struct trip_table *trips, struct dive_site_table *sites, struct device_table *devices) { UNUSED(buffer); UNUSED(size); int retval; struct parser_state state; init_parser_state(&state); state.target_table = table; state.trips = trips; state.sites = sites; state.devices = devices; state.sql_handle = handle; char get_dives[] = "select l.number,strftime('%s', DiveDate),location||' / '||site,buddy,notes,imperialUnits,maxDepth,DiveLengthTime,startSurfacePressure,computerSerial,computerModel,d.diveId,l.sampleRateMs / 1000 FROM dive_details AS d JOIN dive_logs AS l ON d.diveId=l.diveId"; retval = sqlite3_exec(handle, get_dives, &shearwater_cloud_dive, &state, NULL); free_parser_state(&state); if (retval != SQLITE_OK) { fprintf(stderr, "Database query failed '%s'.\n", url); return 1; } return 0; }
subsurface-for-dirk-master
core/import-shearwater.c
#include <unistd.h> #include <stdlib.h> #include <errno.h> #include <libdivecomputer/parser.h> #include "dive.h" #include "errorhelper.h" #include "ssrf.h" #include "subsurface-string.h" #include "divelist.h" #include "file.h" #include "parse.h" #include "sample.h" #include "divelist.h" #include "gettext.h" #include "import-csv.h" #include "qthelper.h" #include "xmlparams.h" #define MATCH(buffer, pattern) \ memcmp(buffer, pattern, strlen(pattern)) static timestamp_t parse_date(const char *date) { int hour, min, sec; struct tm tm; char *p; memset(&tm, 0, sizeof(tm)); tm.tm_mday = strtol(date, &p, 10); if (tm.tm_mday < 1 || tm.tm_mday > 31) return 0; for (tm.tm_mon = 0; tm.tm_mon < 12; tm.tm_mon++) { if (!memcmp(p, monthname(tm.tm_mon), 3)) break; } if (tm.tm_mon > 11) return 0; date = p + 3; tm.tm_year = strtol(date, &p, 10); if (date == p) return 0; if (tm.tm_year < 70) tm.tm_year += 2000; if (tm.tm_year < 100) tm.tm_year += 1900; if (sscanf(p, "%d:%d:%d", &hour, &min, &sec) != 3) return 0; tm.tm_hour = hour; tm.tm_min = min; tm.tm_sec = sec; return utc_mktime(&tm); } static void add_sample_data(struct sample *sample, enum csv_format type, double val) { switch (type) { case CSV_DEPTH: sample->depth.mm = feet_to_mm(val); break; case CSV_TEMP: sample->temperature.mkelvin = F_to_mkelvin(val); break; case CSV_PRESSURE: sample->pressure[0].mbar = psi_to_mbar(val * 4); break; case POSEIDON_DEPTH: sample->depth.mm = lrint(val * 0.5 * 1000); break; case POSEIDON_TEMP: sample->temperature.mkelvin = C_to_mkelvin(val * 0.2); break; case POSEIDON_SETPOINT: sample->setpoint.mbar = lrint(val * 10); break; case POSEIDON_SENSOR1: sample->o2sensor[0].mbar = lrint(val * 10); break; case POSEIDON_SENSOR2: sample->o2sensor[1].mbar = lrint(val * 10); break; case POSEIDON_NDL: sample->ndl.seconds = lrint(val * 60); break; case POSEIDON_CEILING: sample->stopdepth.mm = lrint(val * 1000); break; } } static char *parse_dan_new_line(char *buf, const char *NL) { char *iter = buf; if (!iter) return NULL; iter = strstr(iter, NL); if (iter) { iter += strlen(NL); } else { fprintf(stderr, "DEBUG: No new line found\n"); return NULL; } return iter; } static int try_to_xslt_open_csv(const char *filename, struct memblock *mem, const char *tag); static int parse_dan_format(const char *filename, struct xml_params *params, struct dive_table *table, struct trip_table *trips, struct dive_site_table *sites, struct device_table *devices, struct filter_preset_table *filter_presets) { int ret = 0, i; size_t end_ptr = 0; struct memblock mem, mem_csv; char tmpbuf[MAXCOLDIGITS]; int params_orig_size = xml_params_count(params); char *ptr = NULL; const char *NL = NULL; char *iter = NULL; if (readfile(filename, &mem) < 0) return report_error(translate("gettextFromC", "Failed to read '%s'"), filename); /* Determine NL (new line) character and the start of CSV data */ if ((ptr = strstr(mem.buffer, "\r\n")) != NULL) { NL = "\r\n"; } else if ((ptr = strstr(mem.buffer, "\n")) != NULL) { NL = "\n"; } else { fprintf(stderr, "DEBUG: failed to detect NL\n"); return -1; } while ((end_ptr < mem.size) && (ptr = strstr(mem.buffer + end_ptr, "ZDH"))) { xml_params_resize(params, params_orig_size); // restart with original parameter block char *iter_end = NULL; mem_csv.buffer = malloc(mem.size + 1); mem_csv.size = mem.size; iter = ptr + 4; iter = strchr(iter, '|'); if (iter) { memcpy(tmpbuf, ptr + 4, iter - ptr - 4); tmpbuf[iter - ptr - 4] = 0; xml_params_add(params, "diveNro", tmpbuf); } //fprintf(stderr, "DEBUG: BEGIN end_ptr %d round %d <%s>\n", end_ptr, j++, ptr); iter = ptr + 1; for (i = 0; i <= 4 && iter; ++i) { iter = strchr(iter, '|'); if (iter) ++iter; } if (!iter) { fprintf(stderr, "DEBUG: Data corrupt"); return -1; } /* Setting date */ memcpy(tmpbuf, iter, 8); tmpbuf[8] = 0; xml_params_add(params, "date", tmpbuf); /* Setting time, gotta prepend it with 1 to * avoid octal parsing (this is stripped out in * XSLT */ tmpbuf[0] = '1'; memcpy(tmpbuf + 1, iter + 8, 6); tmpbuf[7] = 0; xml_params_add(params, "time", tmpbuf); /* Air temperature */ memset(tmpbuf, 0, sizeof(tmpbuf)); iter = strchr(iter, '|'); if (iter && iter[1]) { iter = iter + 1; iter_end = strchr(iter, '|'); if (iter_end) { memcpy(tmpbuf, iter, iter_end - iter); xml_params_add(params, "airTemp", tmpbuf); } } /* Search for the next line */ if (iter) iter = parse_dan_new_line(iter, NL); if (!iter) return -1; /* We got a trailer, no samples on this dive */ if (strncmp(iter, "ZDT", 3) == 0) { end_ptr = iter - (char *)mem.buffer; /* Water temperature */ memset(tmpbuf, 0, sizeof(tmpbuf)); for (i = 0; i < 5 && iter; ++i) iter = strchr(iter + 1, '|'); if (iter && iter + 1) { iter = iter + 1; iter_end = strchr(iter, '|'); if (iter_end) { memcpy(tmpbuf, iter, iter_end - iter); xml_params_add(params, "waterTemp", tmpbuf); } } ret |= parse_xml_buffer(filename, "<csv></csv>", 11, table, trips, sites, devices, filter_presets, params); continue; } /* After ZDH we should get either ZDT (above) or ZDP */ if (strncmp(iter, "ZDP{", 4) != 0) { fprintf(stderr, "DEBUG: Input appears to violate DL7 specification\n"); end_ptr = iter - (char *)mem.buffer; continue; } if (ptr && ptr[4] == '}') { end_ptr += ptr - (char *)mem_csv.buffer; return report_error(translate("gettextFromC", "No dive profile found from '%s'"), filename); } if (ptr) ptr = parse_dan_new_line(ptr, NL); if (!ptr) return -1; end_ptr = ptr - (char *)mem.buffer; /* Copy the current dive data to start of mem_csv buffer */ memcpy(mem_csv.buffer, ptr, mem.size - (ptr - (char *)mem.buffer)); ptr = strstr(mem_csv.buffer, "ZDP}"); if (ptr) { *ptr = 0; } else { fprintf(stderr, "DEBUG: failed to find end ZDP\n"); return -1; } mem_csv.size = ptr - (char*)mem_csv.buffer; end_ptr += ptr - (char *)mem_csv.buffer; iter = parse_dan_new_line(ptr + 1, NL); if (iter && strncmp(iter, "ZDT", 3) == 0) { /* Water temperature */ memset(tmpbuf, 0, sizeof(tmpbuf)); for (i = 0; i < 5 && iter; ++i) iter = strchr(iter + 1, '|'); if (iter && iter + 1) { iter = iter + 1; iter_end = strchr(iter, '|'); if (iter_end) { memcpy(tmpbuf, iter, iter_end - iter); xml_params_add(params, "waterTemp", tmpbuf); } } } if (try_to_xslt_open_csv(filename, &mem_csv, "csv")) return -1; ret |= parse_xml_buffer(filename, mem_csv.buffer, mem_csv.size, table, trips, sites, devices, filter_presets, params); free(mem_csv.buffer); } free(mem.buffer); return ret; } int parse_csv_file(const char *filename, struct xml_params *params, const char *csvtemplate, struct dive_table *table, struct trip_table *trips, struct dive_site_table *sites, struct device_table *devices, struct filter_preset_table *filter_presets) { int ret; struct memblock mem; time_t now; struct tm *timep = NULL; char tmpbuf[MAXCOLDIGITS]; /* Increase the limits for recursion and variables on XSLT * parsing */ xsltMaxDepth = 30000; #if LIBXSLT_VERSION > 10126 xsltMaxVars = 150000; #endif if (filename == NULL) return report_error("No CSV filename"); mem.size = 0; if (!strcmp("DL7", csvtemplate)) { return parse_dan_format(filename, params, table, trips, sites, devices, filter_presets); } else if (strcmp(xml_params_get_key(params, 0), "date")) { time(&now); timep = localtime(&now); strftime(tmpbuf, MAXCOLDIGITS, "%Y%m%d", timep); xml_params_add(params, "date", tmpbuf); /* As the parameter is numeric, we need to ensure that the leading zero * is not discarded during the transform, thus prepend time with 1 */ strftime(tmpbuf, MAXCOLDIGITS, "1%H%M", timep); xml_params_add(params, "time", tmpbuf); } if (try_to_xslt_open_csv(filename, &mem, csvtemplate)) return -1; /* * Lets print command line for manual testing with xsltproc if * verbosity level is high enough. The printed line needs the * input file added as last parameter. */ #ifndef SUBSURFACE_MOBILE if (verbose >= 2) { fprintf(stderr, "(echo '<csv>'; cat %s;echo '</csv>') | xsltproc ", filename); for (int i = 0; i < xml_params_count(params); i++) fprintf(stderr, "--stringparam %s %s ", xml_params_get_key(params, i), xml_params_get_value(params, i)); fprintf(stderr, "%s/xslt/%s -\n", SUBSURFACE_SOURCE, csvtemplate); } #endif ret = parse_xml_buffer(filename, mem.buffer, mem.size, table, trips, sites, devices, filter_presets, params); free(mem.buffer); return ret; } static int try_to_xslt_open_csv(const char *filename, struct memblock *mem, const char *tag) { char *buf; size_t i, amp = 0, rest = 0; if (mem->size == 0 && readfile(filename, mem) < 0) return report_error(translate("gettextFromC", "Failed to read '%s'"), filename); /* Count ampersand characters */ for (i = 0; i < mem->size; ++i) { if (((char *)mem->buffer)[i] == '&') { ++amp; } } /* Surround the CSV file content with XML tags to enable XSLT * parsing * * Tag markers take: strlen("<></>") = 5 * Reserve also room for encoding ampersands "&" => "&amp;" */ buf = realloc(mem->buffer, mem->size + 7 + strlen(tag) * 2 + amp * 4); if (buf != NULL) { char *starttag = NULL; char *endtag = NULL; starttag = malloc(3 + strlen(tag)); endtag = malloc(5 + strlen(tag)); if (starttag == NULL || endtag == NULL) { /* this is fairly silly - so the malloc fails, but we strdup the error? * let's complete the silliness by freeing the two pointers in case one malloc succeeded * and the other one failed - this will make static analysis tools happy */ free(starttag); free(endtag); free(buf); return report_error("Memory allocation failed in %s", __func__); } sprintf(starttag, "<%s>", tag); sprintf(endtag, "\n</%s>", tag); memmove(buf + 2 + strlen(tag), buf, mem->size); memcpy(buf, starttag, 2 + strlen(tag)); memcpy(buf + mem->size + 2 + strlen(tag), endtag, 5 + strlen(tag)); mem->size += (6 + 2 * strlen(tag)); mem->buffer = buf; free(starttag); free(endtag); /* Expand ampersands to encoded version */ for (i = mem->size, rest = 0; i > 0; --i, ++rest) { if (((char *)mem->buffer)[i] == '&') { memmove(((char *)mem->buffer) + i + 4 + 1, ((char *)mem->buffer) + i + 1, rest); memcpy(((char *)mem->buffer) + i + 1, "amp;", 4); rest += 4; mem->size += 4; } } } else { free(mem->buffer); return report_error("realloc failed in %s", __func__); } return 0; } int try_to_open_csv(struct memblock *mem, enum csv_format type, struct dive_table *table, struct trip_table *trips, struct dive_site_table *sites) { UNUSED(sites); char *p = mem->buffer; char *header[8]; int i, time; timestamp_t date; struct dive *dive; struct divecomputer *dc; for (i = 0; i < 8; i++) { header[i] = p; p = strchr(p, ','); if (!p) return 0; p++; } date = parse_date(header[2]); if (!date) return 0; dive = alloc_dive(); dive->when = date; dive->number = atoi(header[1]); dc = &dive->dc; time = 0; for (;;) { char *end; double val; struct sample *sample; errno = 0; val = strtod(p, &end); // FIXME == localization issue if (end == p) break; if (errno) break; sample = prepare_sample(dc); sample->time.seconds = time; add_sample_data(sample, type, val); finish_sample(dc); time++; dc->duration.seconds = time; if (*end != ',') break; p = end + 1; } record_dive_to_table(dive, table); return 1; } static char *parse_mkvi_value(const char *haystack, const char *needle) { char *lineptr, *valueptr, *endptr, *ret = NULL; if ((lineptr = strstr(haystack, needle)) != NULL) { if ((valueptr = strstr(lineptr, ": ")) != NULL) { valueptr += 2; } if ((endptr = strstr(lineptr, "\n")) != NULL) { char terminator = '\n'; if (*(endptr - 1) == '\r') { --endptr; terminator = '\r'; } *endptr = 0; ret = copy_string(valueptr); *endptr = terminator; } } return ret; } static char *next_mkvi_key(const char *haystack) { char *valueptr, *endptr, *ret = NULL; if ((valueptr = strstr(haystack, "\n")) != NULL) { valueptr += 1; if ((endptr = strstr(valueptr, ": ")) != NULL) { *endptr = 0; ret = strdup(valueptr); *endptr = ':'; } } return ret; } int parse_txt_file(const char *filename, const char *csv, struct dive_table *table, struct trip_table *trips, struct dive_site_table *sites, struct device_table *devices) { UNUSED(sites); struct memblock memtxt, memcsv; if (readfile(filename, &memtxt) < 0) { return report_error(translate("gettextFromC", "Failed to read '%s'"), filename); } /* * MkVI stores some information in .txt file but the whole profile and events are stored in .csv file. First * make sure the input .txt looks like proper MkVI file, then start parsing the .csv. */ if (MATCH(memtxt.buffer, "MkVI_Config") == 0) { int d, m, y, he; int hh = 0, mm = 0, ss = 0; int prev_depth = 0, cur_sampletime = 0, prev_setpoint = -1, prev_ndl = -1; bool has_depth = false, has_setpoint = false, has_ndl = false; char *lineptr, *key, *value; int prev_time = 0; cylinder_t cyl = empty_cylinder; struct dive *dive; struct divecomputer *dc; struct tm cur_tm; value = parse_mkvi_value(memtxt.buffer, "Dive started at"); if (sscanf(value, "%d-%d-%d %d:%d:%d", &y, &m, &d, &hh, &mm, &ss) != 6) { free(value); return -1; } free(value); cur_tm.tm_year = y; cur_tm.tm_mon = m - 1; cur_tm.tm_mday = d; cur_tm.tm_hour = hh; cur_tm.tm_min = mm; cur_tm.tm_sec = ss; dive = alloc_dive(); dive->when = utc_mktime(&cur_tm);; dive->dc.model = strdup("Poseidon MkVI Discovery"); value = parse_mkvi_value(memtxt.buffer, "Rig Serial number"); dive->dc.deviceid = atoi(value); free(value); dive->dc.divemode = CCR; dive->dc.no_o2sensors = 2; cyl.cylinder_use = OXYGEN; cyl.type.size.mliter = 3000; cyl.type.workingpressure.mbar = 200000; cyl.type.description = "3l Mk6"; cyl.gasmix.o2.permille = 1000; cyl.manually_added = true; cyl.bestmix_o2 = 0; cyl.bestmix_he = 0; add_cloned_cylinder(&dive->cylinders, cyl); cyl.cylinder_use = DILUENT; cyl.type.size.mliter = 3000; cyl.type.workingpressure.mbar = 200000; cyl.type.description = "3l Mk6"; value = parse_mkvi_value(memtxt.buffer, "Helium percentage"); he = atoi(value); free(value); value = parse_mkvi_value(memtxt.buffer, "Nitrogen percentage"); cyl.gasmix.o2.permille = (100 - atoi(value) - he) * 10; free(value); cyl.gasmix.he.permille = he * 10; add_cloned_cylinder(&dive->cylinders, cyl); lineptr = strstr(memtxt.buffer, "Dive started at"); while (!empty_string(lineptr) && (lineptr = strchr(lineptr, '\n'))) { ++lineptr; // Skip over '\n' key = next_mkvi_key(lineptr); if (!key) break; value = parse_mkvi_value(lineptr, key); if (!value) { free(key); break; } add_extra_data(&dive->dc, key, value); free(key); free(value); } dc = &dive->dc; /* * Read samples from the CSV file. A sample contains all the lines with same timestamp. The CSV file has * the following format: * * timestamp, type, value * * And following fields are of interest to us: * * 6 sensor1 * 7 sensor2 * 8 depth * 13 o2 tank pressure * 14 diluent tank pressure * 20 o2 setpoint * 39 water temp */ if (readfile(csv, &memcsv) < 0) { free_dive(dive); return report_error(translate("gettextFromC", "Poseidon import failed: unable to read '%s'"), csv); } lineptr = memcsv.buffer; for (;;) { struct sample *sample; int type; int value; int sampletime; int gaschange = 0; /* Collect all the information for one sample */ sscanf(lineptr, "%d,%d,%d", &cur_sampletime, &type, &value); has_depth = false; has_setpoint = false; has_ndl = false; sample = prepare_sample(dc); /* * There was a bug in MKVI download tool that resulted in erroneous sample * times. This fix should work similarly as the vendor's own. */ sample->time.seconds = cur_sampletime < 0xFFFF * 3 / 4 ? cur_sampletime : prev_time; prev_time = sample->time.seconds; do { int i = sscanf(lineptr, "%d,%d,%d", &sampletime, &type, &value); switch (i) { case 3: switch (type) { case 0: //Mouth piece position event: 0=OC, 1=CC, 2=UN, 3=NC switch (value) { case 0: add_event(dc, cur_sampletime, 0, 0, 0, QT_TRANSLATE_NOOP("gettextFromC", "Mouth piece position OC")); break; case 1: add_event(dc, cur_sampletime, 0, 0, 0, QT_TRANSLATE_NOOP("gettextFromC", "Mouth piece position CC")); break; case 2: add_event(dc, cur_sampletime, 0, 0, 0, QT_TRANSLATE_NOOP("gettextFromC", "Mouth piece position unknown")); break; case 3: add_event(dc, cur_sampletime, 0, 0, 0, QT_TRANSLATE_NOOP("gettextFromC", "Mouth piece position not connected")); break; } break; case 3: //Power Off event add_event(dc, cur_sampletime, 0, 0, 0, QT_TRANSLATE_NOOP("gettextFromC", "Power off")); break; case 4: //Battery State of Charge in % #ifdef SAMPLE_EVENT_BATTERY add_event(dc, cur_sampletime, SAMPLE_EVENT_BATTERY, 0, value, QT_TRANSLATE_NOOP("gettextFromC", "battery")); #endif break; case 6: //PO2 Cell 1 Average add_sample_data(sample, POSEIDON_SENSOR1, value); break; case 7: //PO2 Cell 2 Average add_sample_data(sample, POSEIDON_SENSOR2, value); break; case 8: //Depth * 2 has_depth = true; prev_depth = value; add_sample_data(sample, POSEIDON_DEPTH, value); break; //9 Max Depth * 2 //10 Ascent/Descent Rate * 2 case 11: //Ascent Rate Alert >10 m/s add_event(dc, cur_sampletime, SAMPLE_EVENT_ASCENT, 0, 0, QT_TRANSLATE_NOOP("gettextFromC", "ascent")); break; case 13: //O2 Tank Pressure add_sample_pressure(sample, 0, lrint(value * 1000)); break; case 14: //Diluent Tank Pressure add_sample_pressure(sample, 1, lrint(value * 1000)); break; //16 Remaining dive time #1? //17 related to O2 injection case 20: //PO2 Setpoint has_setpoint = true; prev_setpoint = value; add_sample_data(sample, POSEIDON_SETPOINT, value); break; case 22: //End of O2 calibration Event: 0 = OK, 2 = Failed, rest of dive setpoint 1.0 if (value == 2) add_event(dc, cur_sampletime, 0, SAMPLE_FLAGS_END, 0, QT_TRANSLATE_NOOP("gettextFromC", "O₂ calibration failed")); add_event(dc, cur_sampletime, 0, SAMPLE_FLAGS_END, 0, QT_TRANSLATE_NOOP("gettextFromC", "O₂ calibration")); break; case 25: //25 Max Ascent depth add_sample_data(sample, POSEIDON_CEILING, value); break; case 31: //Start of O2 calibration Event add_event(dc, cur_sampletime, 0, SAMPLE_FLAGS_BEGIN, 0, QT_TRANSLATE_NOOP("gettextFromC", "O₂ calibration")); break; case 37: //Remaining dive time #2? has_ndl = true; prev_ndl = value; add_sample_data(sample, POSEIDON_NDL, value); break; case 39: // Water Temperature in Celsius add_sample_data(sample, POSEIDON_TEMP, value); break; case 85: //He diluent part in % gaschange += value << 16; break; case 86: //O2 diluent part in % gaschange += value; break; //239 Unknown, maybe PO2 at sensor validation? //240 Unknown, maybe PO2 at sensor validation? //247 Unknown, maybe PO2 Cell 1 during pressure test //248 Unknown, maybe PO2 Cell 2 during pressure test //250 PO2 Cell 1 //251 PO2 Cell 2 default: break; } /* sample types */ break; case EOF: break; default: printf("Unable to parse input: %s\n", lineptr); break; } lineptr = strchr(lineptr, '\n'); if (!lineptr || !*lineptr) break; lineptr++; /* Grabbing next sample time */ sscanf(lineptr, "%d,%d,%d", &cur_sampletime, &type, &value); } while (sampletime == cur_sampletime); if (gaschange) add_event(dc, cur_sampletime, SAMPLE_EVENT_GASCHANGE2, 0, gaschange, QT_TRANSLATE_NOOP("gettextFromC", "gaschange")); if (!has_depth) add_sample_data(sample, POSEIDON_DEPTH, prev_depth); if (!has_setpoint && prev_setpoint >= 0) add_sample_data(sample, POSEIDON_SETPOINT, prev_setpoint); if (!has_ndl && prev_ndl >= 0) add_sample_data(sample, POSEIDON_NDL, prev_ndl); finish_sample(dc); if (!lineptr || !*lineptr) break; } record_dive_to_table(dive, table); return 1; } else { return 0; } return 0; } #define DATESTR 9 #define TIMESTR 6 #define SBPARAMS 40 static int parse_seabear_csv_file(const char *filename, struct xml_params *params, const char *csvtemplate, struct dive_table *table, struct trip_table *trips, struct dive_site_table *sites, struct device_table *devices, struct filter_preset_table *filter_presets); int parse_seabear_log(const char *filename, struct dive_table *table, struct trip_table *trips, struct dive_site_table *sites, struct device_table *devices, struct filter_preset_table *filter_presets) { struct xml_params *params = alloc_xml_params(); int ret; parse_seabear_header(filename, params); ret = parse_seabear_csv_file(filename, params, "csv", table, trips, sites, devices, filter_presets) < 0 ? -1 : 0; free_xml_params(params); return ret; } static int parse_seabear_csv_file(const char *filename, struct xml_params *params, const char *csvtemplate, struct dive_table *table, struct trip_table *trips, struct dive_site_table *sites, struct device_table *devices, struct filter_preset_table *filter_presets) { int ret, i; struct memblock mem; time_t now; struct tm *timep = NULL; char *ptr, *ptr_old = NULL; char *NL = NULL; char tmpbuf[MAXCOLDIGITS]; /* Increase the limits for recursion and variables on XSLT * parsing */ xsltMaxDepth = 30000; #if LIBXSLT_VERSION > 10126 xsltMaxVars = 150000; #endif time(&now); timep = localtime(&now); strftime(tmpbuf, MAXCOLDIGITS, "%Y%m%d", timep); xml_params_add(params, "date", tmpbuf); /* As the parameter is numeric, we need to ensure that the leading zero * is not discarded during the transform, thus prepend time with 1 */ strftime(tmpbuf, MAXCOLDIGITS, "1%H%M", timep); xml_params_add(params, "time", tmpbuf); if (filename == NULL) return report_error("No CSV filename"); if (readfile(filename, &mem) < 0) return report_error(translate("gettextFromC", "Failed to read '%s'"), filename); /* Determine NL (new line) character and the start of CSV data */ ptr = mem.buffer; while ((ptr = strstr(ptr, "\r\n\r\n")) != NULL) { ptr_old = ptr; ptr += 1; NL = "\r\n"; } if (!ptr_old) { ptr = mem.buffer; while ((ptr = strstr(ptr, "\n\n")) != NULL) { ptr_old = ptr; ptr += 1; NL = "\n"; } ptr_old += 2; } else { ptr_old += 4; } /* * If file does not contain empty lines, it is not a valid * Seabear CSV file. */ if (NL == NULL) return -1; /* * On my current sample of Seabear DC log file, the date is * without any identifier. Thus we must search for the previous * line and step through from there. That is the line after * Serial number. */ ptr = strstr(mem.buffer, "Serial number:"); if (ptr) ptr = strstr(ptr, NL); /* * Write date and time values to params array, if available in * the CSV header */ if (ptr) { /* * The two last entries should be date and time. * Here we overwrite them with the data from the * CSV header. */ char buf[10]; ptr += strlen(NL) + 2; memcpy(buf, ptr, 4); memcpy(buf + 4, ptr + 5, 2); memcpy(buf + 6, ptr + 8, 2); buf[8] = 0; xml_params_set_value(params, xml_params_count(params) - 2, buf); buf[0] = xml_params_get_value(params, xml_params_count(params) - 1)[0]; memcpy(buf + 1, ptr + 11, 2); memcpy(buf + 3, ptr + 14, 2); buf[5] = 0; xml_params_set_value(params, xml_params_count(params) - 1, buf); } /* Move the CSV data to the start of mem buffer */ memmove(mem.buffer, ptr_old, mem.size - (ptr_old - (char*)mem.buffer)); mem.size = (int)mem.size - (ptr_old - (char*)mem.buffer); if (try_to_xslt_open_csv(filename, &mem, csvtemplate)) return -1; /* * Lets print command line for manual testing with xsltproc if * verbosity level is high enough. The printed line needs the * input file added as last parameter. */ if (verbose >= 2) { fprintf(stderr, "xsltproc "); for (i = 0; i < xml_params_count(params); i++) fprintf(stderr, "--stringparam %s %s ", xml_params_get_key(params, i), xml_params_get_value(params, i)); fprintf(stderr, "xslt/csv2xml.xslt\n"); } ret = parse_xml_buffer(filename, mem.buffer, mem.size, table, trips, sites, devices, filter_presets, params); free(mem.buffer); return ret; } int parse_manual_file(const char *filename, struct xml_params *params, struct dive_table *table, struct trip_table *trips, struct dive_site_table *sites, struct device_table *devices, struct filter_preset_table *filter_presets) { struct memblock mem; time_t now; struct tm *timep; char curdate[9]; char curtime[6]; int ret; time(&now); timep = localtime(&now); strftime(curdate, DATESTR, "%Y%m%d", timep); /* As the parameter is numeric, we need to ensure that the leading zero * is not discarded during the transform, thus prepend time with 1 */ strftime(curtime, TIMESTR, "1%H%M", timep); xml_params_add(params, "date", curdate); xml_params_add(params, "time", curtime); if (filename == NULL) return report_error("No manual CSV filename"); mem.size = 0; if (try_to_xslt_open_csv(filename, &mem, "manualCSV")) return -1; #ifndef SUBSURFACE_MOBILE if (verbose >= 2) { fprintf(stderr, "(echo '<manualCSV>'; cat %s;echo '</manualCSV>') | xsltproc ", filename); for (int i = 0; i < xml_params_count(params); i++) fprintf(stderr, "--stringparam %s %s ", xml_params_get_key(params, i), xml_params_get_value(params, i)); fprintf(stderr, "%s/xslt/manualcsv2xml.xslt -\n", SUBSURFACE_SOURCE); } #endif ret = parse_xml_buffer(filename, mem.buffer, mem.size, table, trips, sites, devices, filter_presets, params); free(mem.buffer); return ret; }
subsurface-for-dirk-master
core/import-csv.c
// SPDX-License-Identifier: GPL-2.0 #ifdef __clang__ // Clang has a bug on zero-initialization of C structs. #pragma clang diagnostic ignored "-Wmissing-field-initializers" #endif #include "ssrf.h" #include <stdio.h> #include <ctype.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <git2.h> #include "dive.h" #include "divesite.h" #include "filterconstraint.h" #include "filterpreset.h" #include "sample.h" #include "subsurface-string.h" #include "trip.h" #include "device.h" #include "errorhelper.h" #include "event.h" #include "extradata.h" #include "membuffer.h" #include "git-access.h" #include "version.h" #include "picture.h" #include "qthelper.h" #include "gettext.h" #include "tag.h" #include "subsurface-time.h" #define VA_BUF(b, fmt) do { va_list args; va_start(args, fmt); put_vformat(b, fmt, args); va_end(args); } while (0) static void cond_put_format(int cond, struct membuffer *b, const char *fmt, ...) { if (cond) { VA_BUF(b, fmt); } } #define SAVE(str, x) cond_put_format(dive->x, b, str " %d\n", dive->x) static void quote(struct membuffer *b, const char *text) { const char *p = text; for (;;) { const char *escape; switch (*p++) { default: continue; case 0: escape = NULL; break; case 1 ... 8: case 11: case 12: case 14 ... 31: escape = "?"; break; case '\\': escape = "\\\\"; break; case '"': escape = "\\\""; break; case '\n': escape = "\n\t"; if (*p == '\n') escape = "\n"; break; } put_bytes(b, text, (p - text - 1)); if (!escape) break; put_string(b, escape); text = p; } } static void show_utf8(struct membuffer *b, const char *prefix, const char *value, const char *postfix) { if (value) { put_format(b, "%s\"", prefix); quote(b, value); put_format(b, "\"%s", postfix); } } static void save_overview(struct membuffer *b, struct dive *dive) { show_utf8(b, "divemaster ", dive->diveguide, "\n"); show_utf8(b, "buddy ", dive->buddy, "\n"); show_utf8(b, "suit ", dive->suit, "\n"); show_utf8(b, "notes ", dive->notes, "\n"); } static void save_tags(struct membuffer *b, struct tag_entry *tags) { const char *sep = " "; if (!tags) return; put_string(b, "tags"); while (tags) { show_utf8(b, sep, tags->tag->source ? : tags->tag->name, ""); sep = ", "; tags = tags->next; } put_string(b, "\n"); } static void save_extra_data(struct membuffer *b, struct extra_data *ed) { while (ed) { if (ed->key && ed->value) put_format(b, "keyvalue \"%s\" \"%s\"\n", ed->key ? : "", ed->value ? : ""); ed = ed->next; } } static void put_gasmix(struct membuffer *b, struct gasmix mix) { int o2 = mix.o2.permille; int he = mix.he.permille; if (o2) { put_format(b, " o2=%u.%u%%", FRACTION(o2, 10)); if (he) put_format(b, " he=%u.%u%%", FRACTION(he, 10)); } } static void save_cylinder_info(struct membuffer *b, struct dive *dive) { int i, nr; nr = nr_cylinders(dive); for (i = 0; i < nr; i++) { cylinder_t *cylinder = get_cylinder(dive, i); int volume = cylinder->type.size.mliter; const char *description = cylinder->type.description; int use = cylinder->cylinder_use; put_string(b, "cylinder"); if (volume) put_milli(b, " vol=", volume, "l"); put_pressure(b, cylinder->type.workingpressure, " workpressure=", "bar"); show_utf8(b, " description=", description, ""); strip_mb(b); put_gasmix(b, cylinder->gasmix); put_pressure(b, cylinder->start, " start=", "bar"); put_pressure(b, cylinder->end, " end=", "bar"); if (use > OC_GAS && use < NUM_GAS_USE) show_utf8(b, " use=", cylinderuse_text[use], ""); if (cylinder->depth.mm != 0) put_milli(b, " depth=", cylinder->depth.mm, "m"); put_string(b, "\n"); } } static void save_weightsystem_info(struct membuffer *b, struct dive *dive) { int i, nr; nr = nr_weightsystems(dive); for (i = 0; i < nr; i++) { weightsystem_t ws = dive->weightsystems.weightsystems[i]; int grams = ws.weight.grams; const char *description = ws.description; put_string(b, "weightsystem"); put_milli(b, " weight=", grams, "kg"); show_utf8(b, " description=", description, ""); put_string(b, "\n"); } } static void save_dive_temperature(struct membuffer *b, struct dive *dive) { if (dive->airtemp.mkelvin != dc_airtemp(&dive->dc)) put_temperature(b, dive->airtemp, "airtemp ", "°C\n"); if (dive->watertemp.mkelvin != dc_watertemp(&dive->dc)) put_temperature(b, dive->watertemp, "watertemp ", "°C\n"); } static void save_depths(struct membuffer *b, struct divecomputer *dc) { put_depth(b, dc->maxdepth, "maxdepth ", "m\n"); put_depth(b, dc->meandepth, "meandepth ", "m\n"); } static void save_temperatures(struct membuffer *b, struct divecomputer *dc) { put_temperature(b, dc->airtemp, "airtemp ", "°C\n"); put_temperature(b, dc->watertemp, "watertemp ", "°C\n"); } static void save_airpressure(struct membuffer *b, struct divecomputer *dc) { put_pressure(b, dc->surface_pressure, "surfacepressure ", "bar\n"); } static void save_salinity(struct membuffer *b, struct divecomputer *dc) { /* only save if we have a value that isn't the default of sea water */ if (!dc->salinity || dc->salinity == SEAWATER_SALINITY) return; put_salinity(b, dc->salinity, "salinity ", "g/l\n"); } static void show_date(struct membuffer *b, timestamp_t when) { struct tm tm; utc_mkdate(when, &tm); put_format(b, "date %04u-%02u-%02u\n", tm.tm_year, tm.tm_mon + 1, tm.tm_mday); put_format(b, "time %02u:%02u:%02u\n", tm.tm_hour, tm.tm_min, tm.tm_sec); } static void show_integer(struct membuffer *b, int value, const char *pre, const char *post) { put_format(b, " %s%d%s", pre, value, post); } static void show_index(struct membuffer *b, int value, const char *pre, const char *post) { if (value) show_integer(b, value, pre, post); } /* * Samples are saved as densely as possible while still being readable, * since they are the bulk of the data. * * For parsing, look at the units to figure out what the numbers are. */ static void save_sample(struct membuffer *b, struct sample *sample, struct sample *old, int o2sensor) { int idx; put_format(b, "%3u:%02u", FRACTION(sample->time.seconds, 60)); put_milli(b, " ", sample->depth.mm, "m"); put_temperature(b, sample->temperature, " ", "°C"); for (idx = 0; idx < MAX_SENSORS; idx++) { pressure_t p = sample->pressure[idx]; int sensor = sample->sensor[idx]; if (sensor == NO_SENSOR) continue; if (!p.mbar) continue; /* Old-style "o2sensor" syntax for CCR dives? */ if (o2sensor >= 0) { if (sensor == o2sensor) { put_pressure(b, sample->pressure[1]," o2pressure=","bar"); continue; } put_pressure(b, p, " ", "bar"); /* * Note: regardless of which index we used for the non-O2 * sensor, we know there is only one non-O2 sensor in legacy * mode, and "old->sensor[0]" contains that index. */ if (sensor != old->sensor[0]) { put_format(b, " sensor=%d", sensor); old->sensor[0] = sensor; } continue; } /* The new-style format is much simpler: the sensor is always encoded */ put_pressure(b, p, " ", "bar"); put_format(b, ":%d", sensor); } /* the deco/ndl values are stored whenever they change */ if (sample->ndl.seconds != old->ndl.seconds) { put_format(b, " ndl=%u:%02u", FRACTION(sample->ndl.seconds, 60)); old->ndl = sample->ndl; } if (sample->tts.seconds != old->tts.seconds) { put_format(b, " tts=%u:%02u", FRACTION(sample->tts.seconds, 60)); old->tts = sample->tts; } if (sample->in_deco != old->in_deco) { put_format(b, " in_deco=%d", sample->in_deco ? 1 : 0); old->in_deco = sample->in_deco; } if (sample->stoptime.seconds != old->stoptime.seconds) { put_format(b, " stoptime=%u:%02u", FRACTION(sample->stoptime.seconds, 60)); old->stoptime = sample->stoptime; } if (sample->stopdepth.mm != old->stopdepth.mm) { put_milli(b, " stopdepth=", sample->stopdepth.mm, "m"); old->stopdepth = sample->stopdepth; } if (sample->cns != old->cns) { put_format(b, " cns=%u%%", sample->cns); old->cns = sample->cns; } if (sample->rbt.seconds != old->rbt.seconds) { put_format(b, " rbt=%u:%02u", FRACTION(sample->rbt.seconds, 60)); old->rbt.seconds = sample->rbt.seconds; } if (sample->o2sensor[0].mbar != old->o2sensor[0].mbar) { put_milli(b, " sensor1=", sample->o2sensor[0].mbar, "bar"); old->o2sensor[0] = sample->o2sensor[0]; } if ((sample->o2sensor[1].mbar) && (sample->o2sensor[1].mbar != old->o2sensor[1].mbar)) { put_milli(b, " sensor2=", sample->o2sensor[1].mbar, "bar"); old->o2sensor[1] = sample->o2sensor[1]; } if ((sample->o2sensor[2].mbar) && (sample->o2sensor[2].mbar != old->o2sensor[2].mbar)) { put_milli(b, " sensor3=", sample->o2sensor[2].mbar, "bar"); old->o2sensor[2] = sample->o2sensor[2]; } if (sample->setpoint.mbar != old->setpoint.mbar) { put_milli(b, " po2=", sample->setpoint.mbar, "bar"); old->setpoint = sample->setpoint; } if (sample->heartbeat != old->heartbeat) { show_index(b, sample->heartbeat, "heartbeat=", ""); old->heartbeat = sample->heartbeat; } if (sample->bearing.degrees != old->bearing.degrees) { show_index(b, sample->bearing.degrees, "bearing=", "°"); old->bearing.degrees = sample->bearing.degrees; } put_format(b, "\n"); } static void save_samples(struct membuffer *b, struct dive *dive, struct divecomputer *dc) { int nr; int o2sensor; struct sample *s; struct sample dummy = { .bearing.degrees = -1, .ndl.seconds = -1 }; /* Is this a CCR dive with the old-style "o2pressure" sensor? */ o2sensor = legacy_format_o2pressures(dive, dc); if (o2sensor >= 0) { dummy.sensor[0] = !o2sensor; dummy.sensor[1] = o2sensor; } s = dc->sample; nr = dc->samples; while (--nr >= 0) { save_sample(b, s, &dummy, o2sensor); s++; } } static void save_one_event(struct membuffer *b, struct dive *dive, struct event *ev) { put_format(b, "event %d:%02d", FRACTION(ev->time.seconds, 60)); show_index(b, ev->type, "type=", ""); show_index(b, ev->flags, "flags=", ""); if (!strcmp(ev->name,"modechange")) show_utf8(b, " divemode=", divemode_text[ev->value], ""); else show_index(b, ev->value, "value=", ""); show_utf8(b, " name=", ev->name, ""); if (event_is_gaschange(ev)) { struct gasmix mix = get_gasmix_from_event(dive, ev); if (ev->gas.index >= 0) show_integer(b, ev->gas.index, "cylinder=", ""); put_gasmix(b, mix); } put_string(b, "\n"); } static void save_events(struct membuffer *b, struct dive *dive, struct event *ev) { while (ev) { save_one_event(b, dive, ev); ev = ev->next; } } static void save_dc(struct membuffer *b, struct dive *dive, struct divecomputer *dc) { show_utf8(b, "model ", dc->model, "\n"); if (dc->last_manual_time.seconds) put_duration(b, dc->last_manual_time, "lastmanualtime ", "min\n"); if (dc->deviceid) put_format(b, "deviceid %08x\n", dc->deviceid); if (dc->diveid) put_format(b, "diveid %08x\n", dc->diveid); if (dc->when && dc->when != dive->when) show_date(b, dc->when); if (dc->duration.seconds && dc->duration.seconds != dive->dc.duration.seconds) put_duration(b, dc->duration, "duration ", "min\n"); if (dc->divemode != OC) { put_format(b, "dctype %s\n", divemode_text[dc->divemode]); put_format(b, "numberofoxygensensors %d\n",dc->no_o2sensors); } save_depths(b, dc); save_temperatures(b, dc); save_airpressure(b, dc); save_salinity(b, dc); put_duration(b, dc->surfacetime, "surfacetime ", "min\n"); save_extra_data(b, dc->extra_data); save_events(b, dive, dc->events); save_samples(b, dive, dc); } /* * Note that we don't save the date and time or dive * number: they are encoded in the filename. */ static void create_dive_buffer(struct dive *dive, struct membuffer *b) { pressure_t surface_pressure = un_fixup_surface_pressure(dive); if (dive->dc.duration.seconds > 0) put_format(b, "duration %u:%02u min\n", FRACTION(dive->dc.duration.seconds, 60)); SAVE("rating", rating); SAVE("visibility", visibility); SAVE("wavesize", wavesize); SAVE("current", current); SAVE("surge", surge); SAVE("chill", chill); if (dive->user_salinity) put_format(b, "watersalinity %d g/l\n", (int)(dive->user_salinity/10)); if (surface_pressure.mbar) SAVE("airpressure", surface_pressure.mbar); cond_put_format(dive->notrip, b, "notrip\n"); cond_put_format(dive->invalid, b, "invalid\n"); save_tags(b, dive->tag_list); if (dive->dive_site) put_format(b, "divesiteid %08x\n", dive->dive_site->uuid); if (verbose && dive->dive_site) SSRF_INFO("removed reference to non-existant dive site with uuid %08x\n", dive->dive_site->uuid); save_overview(b, dive); save_cylinder_info(b, dive); save_weightsystem_info(b, dive); save_dive_temperature(b, dive); } /* * libgit2 has a "git_treebuilder" concept, but it's broken, and can not * be used to do a flat tree (like the git "index") nor a recursive tree. * Stupid. * * So we have to do that "keep track of recursive treebuilder entries" * ourselves. We use 'git_treebuilder' for any regular files, and our own * data structures for recursive trees. * * When finally writing it out, we traverse the subdirectories depth- * first, writing them out, and then adding the written-out trees to * the git_treebuilder they existed in. */ struct dir { git_treebuilder *files; struct dir *subdirs, *sibling; char unique, name[1]; }; static int tree_insert(git_treebuilder *dir, const char *name, int mkunique, git_oid *id, unsigned mode) { int ret; struct membuffer uniquename = { 0 }; if (mkunique && git_treebuilder_get(dir, name)) { char hex[8]; git_oid_nfmt(hex, 7, id); hex[7] = 0; put_format(&uniquename, "%s~%s", name, hex); name = mb_cstring(&uniquename); } ret = git_treebuilder_insert(NULL, dir, name, id, mode); free_buffer(&uniquename); if (ret) { const git_error *gerr = giterr_last(); if (gerr) { SSRF_INFO("tree_insert failed with return %d error %s\n", ret, gerr->message); } } return ret; } /* * This does *not* make sure the new subdirectory doesn't * alias some existing name. That is actually useful: you * can create multiple directories with the same name, and * set the "unique" flag, which will then append the SHA1 * of the directory to the name when it is written. */ static struct dir *new_directory(git_repository *repo, struct dir *parent, struct membuffer *namebuf) { struct dir *subdir; const char *name = mb_cstring(namebuf); int len = namebuf->len; subdir = malloc(sizeof(*subdir)+len); /* * It starts out empty: no subdirectories of its own, * and an empty treebuilder list of files. */ subdir->subdirs = NULL; git_treebuilder_new(&subdir->files, repo, NULL); memcpy(subdir->name, name, len); subdir->unique = 0; subdir->name[len] = 0; /* Add it to the list of subdirs of the parent */ subdir->sibling = parent->subdirs; parent->subdirs = subdir; return subdir; } static struct dir *mktree(git_repository *repo, struct dir *dir, const char *fmt, ...) { struct membuffer buf = { 0 }; struct dir *subdir; VA_BUF(&buf, fmt); for (subdir = dir->subdirs; subdir; subdir = subdir->sibling) { if (subdir->unique) continue; if (strncmp(subdir->name, buf.buffer, buf.len)) continue; if (!subdir->name[buf.len]) break; } if (!subdir) subdir = new_directory(repo, dir, &buf); free_buffer(&buf); return subdir; } /* * The name of a dive is the date and the dive number (and possibly * the uniqueness suffix). * * Note that the time of the dive may not be the same as the * time of the directory structure it is created in: the dive * might be part of a trip that straddles a month (or even a * year). * * We do *not* want to use localized weekdays and cause peoples save * formats to depend on their locale. */ static void create_dive_name(struct dive *dive, struct membuffer *name, struct tm *dirtm) { struct tm tm; static const char weekday[7][4] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; utc_mkdate(dive->when, &tm); if (tm.tm_year != dirtm->tm_year) put_format(name, "%04u-", tm.tm_year); if (tm.tm_mon != dirtm->tm_mon) put_format(name, "%02u-", tm.tm_mon+1); /* a colon is an illegal char in a file name on Windows - use an '=' instead */ put_format(name, "%02u-%s-%02u=%02u=%02u", tm.tm_mday, weekday[tm.tm_wday], tm.tm_hour, tm.tm_min, tm.tm_sec); } /* * Write a membuffer to the git repo, and free it */ static int blob_insert(git_repository *repo, struct dir *tree, struct membuffer *b, const char *fmt, ...) { int ret; git_oid blob_id; struct membuffer name = { 0 }; ret = git_blob_create_frombuffer(&blob_id, repo, b->buffer, b->len); free_buffer(b); if (ret) return ret; VA_BUF(&name, fmt); ret = tree_insert(tree->files, mb_cstring(&name), 1, &blob_id, GIT_FILEMODE_BLOB); free_buffer(&name); return ret; } static int save_one_divecomputer(git_repository *repo, struct dir *tree, struct dive *dive, struct divecomputer *dc, int idx) { int ret; struct membuffer buf = { 0 }; save_dc(&buf, dive, dc); ret = blob_insert(repo, tree, &buf, "Divecomputer%c%03u", idx ? '-' : 0, idx); if (ret) report_error("divecomputer tree insert failed"); return ret; } static int save_one_picture(git_repository *repo, struct dir *dir, struct picture *pic) { int offset = pic->offset.seconds; struct membuffer buf = { 0 }; char sign = '+'; unsigned h; show_utf8(&buf, "filename ", pic->filename, "\n"); put_location(&buf, &pic->location, "gps ", "\n"); /* Picture loading will load even negative offsets.. */ if (offset < 0) { offset = -offset; sign = '-'; } /* Use full hh:mm:ss format to make it all sort nicely */ h = offset / 3600; offset -= h *3600; return blob_insert(repo, dir, &buf, "%c%02u=%02u=%02u", sign, h, FRACTION(offset, 60)); } static int save_pictures(git_repository *repo, struct dir *dir, struct dive *dive) { if (dive->pictures.nr > 0) { dir = mktree(repo, dir, "Pictures"); FOR_EACH_PICTURE(dive) { save_one_picture(repo, dir, picture); } } return 0; } static int save_one_dive(git_repository *repo, struct dir *tree, struct dive *dive, struct tm *tm, bool cached_ok) { struct divecomputer *dc; struct membuffer buf = { 0 }, name = { 0 }; struct dir *subdir; int ret, nr; /* Create dive directory */ create_dive_name(dive, &name, tm); /* * If the dive git ID is valid, we just create the whole directory * with that ID */ if (cached_ok && dive_cache_is_valid(dive)) { git_oid oid; git_oid_fromraw(&oid, dive->git_id); ret = tree_insert(tree->files, mb_cstring(&name), 1, &oid, GIT_FILEMODE_TREE); free_buffer(&name); if (ret) return report_error("cached dive tree insert failed"); return 0; } subdir = new_directory(repo, tree, &name); subdir->unique = 1; free_buffer(&name); create_dive_buffer(dive, &buf); nr = dive->number; ret = blob_insert(repo, subdir, &buf, "Dive%c%d", nr ? '-' : 0, nr); if (ret) return report_error("dive save-file tree insert failed"); /* * Save the dive computer data. If there is only one dive * computer, use index 0 for that (which disables the index * generation when naming it). */ dc = &dive->dc; nr = dc->next ? 1 : 0; do { save_one_divecomputer(repo, subdir, dive, dc, nr++); dc = dc->next; } while (dc); /* Save the picture data, if any */ save_pictures(repo, subdir, dive); return 0; } /* * We'll mark the trip directories unique, so this does not * need to be unique per se. It could be just "trip". But * to make things a bit more user-friendly, we try to take * the trip location into account. * * But no special characters, and no numbers (numbers in the * name could be construed as a date). * * So we might end up with "02-Maui", and then the unique * flag will make us write it out as "02-Maui~54b4" or * similar. */ #define MAXTRIPNAME 15 static void create_trip_name(dive_trip_t *trip, struct membuffer *name, struct tm *tm) { put_format(name, "%02u-", tm->tm_mday); if (trip->location) { char ascii_loc[MAXTRIPNAME+1], *p = trip->location; int i; for (i = 0; i < MAXTRIPNAME; ) { char c = *p++; switch (c) { case 0: case ',': case '.': break; case 'a' ... 'z': case 'A' ... 'Z': ascii_loc[i++] = c; continue; default: continue; } break; } if (i > 1) { put_bytes(name, ascii_loc, i); return; } } /* No useful name? */ put_string(name, "trip"); } static int save_trip_description(git_repository *repo, struct dir *dir, dive_trip_t *trip, struct tm *tm) { int ret; git_oid blob_id; struct membuffer desc = { 0 }; put_format(&desc, "date %04u-%02u-%02u\n", tm->tm_year, tm->tm_mon + 1, tm->tm_mday); put_format(&desc, "time %02u:%02u:%02u\n", tm->tm_hour, tm->tm_min, tm->tm_sec); show_utf8(&desc, "location ", trip->location, "\n"); show_utf8(&desc, "notes ", trip->notes, "\n"); ret = git_blob_create_frombuffer(&blob_id, repo, desc.buffer, desc.len); free_buffer(&desc); if (ret) return report_error("trip blob creation failed"); ret = tree_insert(dir->files, "00-Trip", 0, &blob_id, GIT_FILEMODE_BLOB); if (ret) return report_error("trip description tree insert failed"); return 0; } static void verify_shared_date(timestamp_t when, struct tm *tm) { struct tm tmp_tm; utc_mkdate(when, &tmp_tm); if (tmp_tm.tm_year != tm->tm_year) { tm->tm_year = -1; tm->tm_mon = -1; } if (tmp_tm.tm_mon != tm->tm_mon) tm->tm_mon = -1; } #define MIN_TIMESTAMP (0) #define MAX_TIMESTAMP (0x7fffffffffffffff) static int save_one_trip(git_repository *repo, struct dir *tree, dive_trip_t *trip, struct tm *tm, bool cached_ok) { int i; struct dive *dive; struct dir *subdir; struct membuffer name = { 0 }; timestamp_t first, last; /* Create trip directory */ create_trip_name(trip, &name, tm); subdir = new_directory(repo, tree, &name); subdir->unique = 1; free_buffer(&name); /* Trip description file */ save_trip_description(repo, subdir, trip, tm); /* Make sure we write out the dates to the dives consistently */ first = MAX_TIMESTAMP; last = MIN_TIMESTAMP; for_each_dive(i, dive) { if (dive->divetrip != trip) continue; if (dive->when < first) first = dive->when; if (dive->when > last) last = dive->when; } verify_shared_date(first, tm); verify_shared_date(last, tm); /* Save each dive in the directory */ for_each_dive(i, dive) { if (dive->divetrip == trip) save_one_dive(repo, subdir, dive, tm, cached_ok); } return 0; } static void save_units(void *_b) { struct membuffer *b =_b; if (prefs.unit_system == METRIC) put_string(b, "units METRIC\n"); else if (prefs.unit_system == IMPERIAL) put_string(b, "units IMPERIAL\n"); else put_format(b, "units PERSONALIZE %s %s %s %s %s %s\n", prefs.units.length == METERS ? "METERS" : "FEET", prefs.units.volume == LITER ? "LITER" : "CUFT", prefs.units.pressure == BAR ? "BAR" : "PSI", prefs.units.temperature == CELSIUS ? "CELSIUS" : prefs.units.temperature == FAHRENHEIT ? "FAHRENHEIT" : "KELVIN", prefs.units.weight == KG ? "KG" : "LBS", prefs.units.vertical_speed_time == SECONDS ? "SECONDS" : "MINUTES"); } static void save_one_device(struct membuffer *b, const struct device *d) { const char *model = device_get_model(d); const char *nickname = device_get_nickname(d); const char *serial = device_get_serial(d); if (empty_string(serial)) serial = NULL; if (empty_string(nickname)) nickname = NULL; if (!nickname || !serial) return; show_utf8(b, "divecomputerid ", model, ""); put_format(b, " deviceid=%08x", calculate_string_hash(serial)); show_utf8(b, " serial=", serial, ""); show_utf8(b, " nickname=", nickname, ""); put_string(b, "\n"); } static void save_one_fingerprint(struct membuffer *b, unsigned int i) { put_format(b, "fingerprint model=%08x serial=%08x deviceid=%08x diveid=%08x data=\"%s\"\n", fp_get_model(&fingerprint_table, i), fp_get_serial(&fingerprint_table, i), fp_get_deviceid(&fingerprint_table, i), fp_get_diveid(&fingerprint_table, i), fp_get_data(&fingerprint_table, i)); } static void save_settings(git_repository *repo, struct dir *tree) { struct membuffer b = { 0 }; put_format(&b, "version %d\n", DATAFORMAT_VERSION); for (int i = 0; i < nr_devices(&device_table); i++) save_one_device(&b, get_device(&device_table, i)); /* save the fingerprint data */ for (unsigned int i = 0; i < nr_fingerprints(&fingerprint_table); i++) save_one_fingerprint(&b, i); cond_put_format(autogroup, &b, "autogroup\n"); save_units(&b); if (prefs.tankbar) put_string(&b, "prefs TANKBAR\n"); if (prefs.dcceiling) put_string(&b, "prefs DCCEILING\n"); if (prefs.show_ccr_setpoint) put_string(&b, "prefs SHOW_SETPOINT\n"); if (prefs.show_ccr_sensors) put_string(&b, "prefs SHOW_SENSORS\n"); if (prefs.pp_graphs.po2) put_string(&b, "prefs PO2_GRAPH\n"); blob_insert(repo, tree, &b, "00-Subsurface"); } static void save_divesites(git_repository *repo, struct dir *tree) { struct dir *subdir; struct membuffer dirname = { 0 }; put_format(&dirname, "01-Divesites"); subdir = new_directory(repo, tree, &dirname); free_buffer(&dirname); purge_empty_dive_sites(&dive_site_table); for (int i = 0; i < dive_site_table.nr; i++) { struct membuffer b = { 0 }; struct dive_site *ds = get_dive_site(i, &dive_site_table); struct membuffer site_file_name = { 0 }; put_format(&site_file_name, "Site-%08x", ds->uuid); show_utf8(&b, "name ", ds->name, "\n"); show_utf8(&b, "description ", ds->description, "\n"); show_utf8(&b, "notes ", ds->notes, "\n"); put_location(&b, &ds->location, "gps ", "\n"); for (int j = 0; j < ds->taxonomy.nr; j++) { struct taxonomy *t = &ds->taxonomy.category[j]; if (t->category != TC_NONE && t->value) { put_format(&b, "geo cat %d origin %d ", t->category, t->origin); show_utf8(&b, "", t->value, "\n" ); } } blob_insert(repo, subdir, &b, mb_cstring(&site_file_name)); free_buffer(&site_file_name); } } /* * Format a filter constraint line to the membuffer b. * The format is * constraint type "type of the constraint" [stringmode "string mode"] [rangemode "rangemode"] [negate] data "data of the constraint". * where brackets indicate optional blocks. * For possible types and how data is interpreted see core/filterconstraint.[c|h] * Whether stringmode or rangemode exist depends on the type of the constraint. * Any constraint can be negated. */ static void format_one_filter_constraint(int preset_id, int constraint_id, struct membuffer *b) { const struct filter_constraint *constraint = filter_preset_constraint(preset_id, constraint_id); const char *type = filter_constraint_type_to_string(constraint->type); char *data; show_utf8(b, "constraint type=", type, ""); if (filter_constraint_has_string_mode(constraint->type)) { const char *mode = filter_constraint_string_mode_to_string(constraint->string_mode); show_utf8(b, " stringmode=", mode, ""); } if (filter_constraint_has_range_mode(constraint->type)) { const char *mode = filter_constraint_range_mode_to_string(constraint->range_mode); show_utf8(b, " rangemode=", mode, ""); } if (constraint->negate) put_format(b, " negate"); data = filter_constraint_data_to_string(constraint); show_utf8(b, " data=", data, "\n"); free(data); } /* * Write a filter constraint to the membuffer b. * Each line starts with a type, which is either "name", "fulltext" or "constraint". * There must be one "name" entry, zero or one "fulltext" entries and an arbitrary number of "contraint" entries. * The "name" entry gives the name of the filter constraint. * The "fulltext" entry has the format * fulltext mode "fulltext mode" query "the query as entered by the user" * The format of the "constraint" entry is described in the format_one_filter_constraint() function. */ static void format_one_filter_preset(int preset_id, struct membuffer *b) { char *name, *fulltext; name = filter_preset_name(preset_id); show_utf8(b, "name ", name, "\n"); free(name); fulltext = filter_preset_fulltext_query(preset_id); if (!empty_string(fulltext)) { show_utf8(b, "fulltext mode=", filter_preset_fulltext_mode(preset_id), ""); show_utf8(b, " query=", fulltext, "\n"); } free(fulltext); for (int i = 0; i < filter_preset_constraint_count(preset_id); i++) format_one_filter_constraint(preset_id, i, b); } static void save_filter_presets(git_repository *repo, struct dir *tree) { struct membuffer dirname = { 0 }; struct dir *filter_dir; put_format(&dirname, "02-Filterpresets"); filter_dir = new_directory(repo, tree, &dirname); free_buffer(&dirname); for (int i = 0; i < filter_presets_count(); i++) { struct membuffer preset_name = { 0 }; struct membuffer preset_buffer = { 0 }; put_format(&preset_name, "Preset-%03d", i); format_one_filter_preset(i, &preset_buffer); blob_insert(repo, filter_dir, &preset_buffer, mb_cstring(&preset_name)); free_buffer(&preset_name); free_buffer(&preset_buffer); } } static int create_git_tree(git_repository *repo, struct dir *root, bool select_only, bool cached_ok) { int i; struct dive *dive; dive_trip_t *trip; git_storage_update_progress(translate("gettextFromC", "Start saving data")); save_settings(repo, root); save_divesites(repo, root); save_filter_presets(repo, root); for (i = 0; i < trip_table.nr; ++i) trip_table.trips[i]->saved = 0; /* save the dives */ git_storage_update_progress(translate("gettextFromC", "Start saving dives")); for_each_dive(i, dive) { struct tm tm; struct dir *tree; trip = dive->divetrip; if (select_only) { if (!dive->selected) continue; /* We don't save trips when doing selected dive saves */ trip = NULL; } /* Create the date-based hierarchy */ utc_mkdate(trip ? trip_date(trip) : dive->when, &tm); tree = mktree(repo, root, "%04d", tm.tm_year); tree = mktree(repo, tree, "%02d", tm.tm_mon + 1); if (trip) { /* Did we already save this trip? */ if (trip->saved) continue; trip->saved = 1; /* Pass that new subdirectory in for save-trip */ save_one_trip(repo, tree, trip, &tm, cached_ok); continue; } save_one_dive(repo, tree, dive, &tm, cached_ok); } git_storage_update_progress(translate("gettextFromC", "Done creating local cache")); return 0; } /* * See if we can find the parent ID that the git data came from */ static git_object *try_to_find_parent(const char *hex_id, git_repository *repo) { git_oid object_id; git_commit *commit; if (!hex_id) return NULL; if (git_oid_fromstr(&object_id, hex_id)) return NULL; if (git_commit_lookup(&commit, repo, &object_id)) return NULL; return (git_object *)commit; } static int notify_cb(git_checkout_notify_t why, const char *path, const git_diff_file *baseline, const git_diff_file *target, const git_diff_file *workdir, void *payload) { UNUSED(baseline); UNUSED(target); UNUSED(workdir); UNUSED(payload); UNUSED(why); report_error("File '%s' does not match in working tree", path); return 0; /* Continue with checkout */ } static git_tree *get_git_tree(git_repository *repo, git_object *parent) { git_tree *tree; if (!parent) return NULL; if (git_tree_lookup(&tree, repo, git_commit_tree_id((const git_commit *) parent))) return NULL; return tree; } int update_git_checkout(git_repository *repo, git_object *parent, git_tree *tree) { git_checkout_options opts = GIT_CHECKOUT_OPTIONS_INIT; opts.checkout_strategy = GIT_CHECKOUT_SAFE; opts.notify_flags = GIT_CHECKOUT_NOTIFY_CONFLICT | GIT_CHECKOUT_NOTIFY_DIRTY; opts.notify_cb = notify_cb; opts.baseline = get_git_tree(repo, parent); return git_checkout_tree(repo, (git_object *) tree, &opts); } int get_authorship(git_repository *repo, git_signature **authorp) { if (git_signature_default(authorp, repo) == 0) return 0; #ifdef SUBSURFACE_MOBILE #define APPNAME "Subsurface-mobile" #else #define APPNAME "Subsurface" #endif return git_signature_now(authorp, APPNAME, "subsurface-app-account@subsurface-divelog.org"); #undef APPNAME } static void create_commit_message(struct membuffer *msg, bool create_empty) { int nr = dive_table.nr; struct dive *dive = get_dive(nr-1); char* changes_made = get_changes_made(); if (create_empty) { put_string(msg, "Initial commit to create empty repo.\n\n"); } else if (!empty_string(changes_made)) { put_format(msg, "Changes made: \n\n%s\n", changes_made); } else if (dive) { dive_trip_t *trip = dive->divetrip; const char *location = get_dive_location(dive) ? : "no location"; struct divecomputer *dc = &dive->dc; const char *sep = "\n"; if (dive->number) nr = dive->number; put_format(msg, "dive %d: %s", nr, location); if (trip && !empty_string(trip->location) && strcmp(trip->location, location)) put_format(msg, " (%s)", trip->location); put_format(msg, "\n"); do { if (!empty_string(dc->model)) { put_format(msg, "%s%s", sep, dc->model); sep = ", "; } } while ((dc = dc->next) != NULL); put_format(msg, "\n"); } const char *user_agent = subsurface_user_agent(); put_format(msg, "Created by %s\n", user_agent); free((void *)user_agent); free(changes_made); if (verbose) SSRF_INFO("Commit message:\n\n%s\n", mb_cstring(msg)); } static int create_new_commit(struct git_info *info, git_oid *tree_id, bool create_empty) { int ret; git_reference *ref; git_object *parent; git_oid commit_id; git_signature *author; git_commit *commit; git_tree *tree; ret = git_branch_lookup(&ref, info->repo, info->branch, GIT_BRANCH_LOCAL); switch (ret) { default: return report_error("Bad branch '%s' (%s)", info->branch, strerror(errno)); case GIT_EINVALIDSPEC: return report_error("Invalid branch name '%s'", info->branch); case GIT_ENOTFOUND: /* We'll happily create it */ ref = NULL; parent = try_to_find_parent(saved_git_id, info->repo); break; case 0: if (git_reference_peel(&parent, ref, GIT_OBJ_COMMIT)) return report_error("Unable to look up parent in branch '%s'", info->branch); if (saved_git_id) { if (existing_filename && verbose) SSRF_INFO("existing filename %s\n", existing_filename); const git_oid *id = git_commit_id((const git_commit *) parent); /* if we are saving to the same git tree we got this from, let's make * sure there is no confusion */ if (same_string(existing_filename, info->url) && git_oid_strcmp(id, saved_git_id)) return report_error("The git branch does not match the git parent of the source"); } /* all good */ break; } if (git_tree_lookup(&tree, info->repo, tree_id)) return report_error("Could not look up newly created tree"); if (get_authorship(info->repo, &author)) return report_error("No user name configuration in git repo"); /* If the parent commit has the same tree ID, do not create a new commit */ if (parent && git_oid_equal(tree_id, git_commit_tree_id((const git_commit *) parent))) { /* If the parent already came from the ref, the commit is already there */ if (ref) { git_signature_free(author); return 0; } /* Else we do want to create the new branch, but with the old commit */ commit = (git_commit *) parent; } else { struct membuffer commit_msg = { 0 }; create_commit_message(&commit_msg, create_empty); if (git_commit_create_v(&commit_id, info->repo, NULL, author, author, NULL, mb_cstring(&commit_msg), tree, parent != NULL, parent)) { git_signature_free(author); return report_error("Git commit create failed (%s)", strerror(errno)); } free_buffer(&commit_msg); if (git_commit_lookup(&commit, info->repo, &commit_id)) { git_signature_free(author); return report_error("Could not look up newly created commit"); } } git_signature_free(author); if (!ref) { if (git_branch_create(&ref, info->repo, info->branch, commit, 0)) return report_error("Failed to create branch '%s'", info->branch); } /* * If it's a checked-out branch, try to also update the working * tree and index. If that fails (dirty working tree or whatever), * this is not technically a save error (we did save things in * the object database), but it can cause extreme confusion, so * warn about it. */ if (git_branch_is_head(ref) && !git_repository_is_bare(info->repo)) { if (update_git_checkout(info->repo, parent, tree)) { const git_error *err = giterr_last(); const char *errstr = err ? err->message : strerror(errno); report_error("Git branch '%s' is checked out, but worktree is dirty (%s)", info->branch, errstr); } } if (git_reference_set_target(&ref, ref, &commit_id, "Subsurface save event")) return report_error("Failed to update branch '%s'", info->branch); /* * if this was the empty commit to initialize a new repo, don't remember the * commit_id, otherwise we'll think that the cache is valid and fail when building * the tree when we actually try to store the dive data */ if (! create_empty) set_git_id(&commit_id); return 0; } static int write_git_tree(git_repository *repo, struct dir *tree, git_oid *result) { int ret; struct dir *subdir; /* Write out our subdirectories, add them to the treebuilder, and free them */ while ((subdir = tree->subdirs) != NULL) { git_oid id; if (!write_git_tree(repo, subdir, &id)) tree_insert(tree->files, subdir->name, subdir->unique, &id, GIT_FILEMODE_TREE); tree->subdirs = subdir->sibling; free(subdir); }; /* .. write out the resulting treebuilder */ ret = git_treebuilder_write(result, tree->files); if (ret && verbose) { const git_error *gerr = giterr_last(); if (gerr) SSRF_INFO("tree_insert failed with return %d error %s\n", ret, gerr->message); } /* .. and free the now useless treebuilder */ git_treebuilder_free(tree->files); return ret; } int do_git_save(struct git_info *info, bool select_only, bool create_empty) { struct dir tree; git_oid id; bool cached_ok; if (!info->repo) return report_error("Unable to open git repository '%s[%s]'", info->url, info->branch); if (verbose) SSRF_INFO("git storage: do git save\n"); if (!create_empty) // so we are actually saving the dives git_storage_update_progress(translate("gettextFromC", "Preparing to save data")); /* * Check if we can do the cached writes - we need to * have the original git commit we loaded in the repo */ cached_ok = try_to_find_parent(saved_git_id, info->repo); /* Start with an empty tree: no subdirectories, no files */ tree.name[0] = 0; tree.subdirs = NULL; if (git_treebuilder_new(&tree.files, info->repo, NULL)) return report_error("git treebuilder failed"); if (!create_empty) /* Populate our tree data structure */ if (create_git_tree(info->repo, &tree, select_only, cached_ok)) return -1; if (verbose) SSRF_INFO("git storage, write git tree\n"); if (write_git_tree(info->repo, &tree, &id)) return report_error("git tree write failed"); /* And save the tree! */ if (create_new_commit(info, &id, create_empty)) return report_error("creating commit failed"); /* now sync the tree with the remote server */ if (info->url && !git_local_only) return sync_with_remote(info); return 0; } int git_save_dives(struct git_info *info, bool select_only) { /* * First, just try to open the local git repo without * doing any remote updates at all. If networking is * reliable, the remote has been updated at open time, * and we want to update *after* saving. * * And if networking isn't reliable, we want to save * first anyway. * * Note that 'do_git_save()' will try to sync with the * remote after saving (see sync_with_remote()), so we * will be doing the remote access at that point, but * at least the local state will be saved early in * case something goes wrong. */ if (!git_repository_open(&info->repo, info->localdir)) return do_git_save(info, select_only, false); /* * Ok, so there was something wrong with the local * repo (possibly it's just missing entirely). That * means we don't want to just save to it, we'll * need to try to load the remote state first. * * This shouldn't be the common case. */ if (!open_git_repository(info)) return report_error(translate("gettextFromC", "Failed to save dives to %s[%s] (%s)"), info->url, info->branch, strerror(errno)); return do_git_save(info, select_only, false); }
subsurface-for-dirk-master
core/save-git.c
// SPDX-License-Identifier: GPL-2.0 #include <string.h> #include "ssrf.h" #include "divesite.h" #include "dive.h" #include "file.h" #include "sample.h" #include "strndup.h" // Convert bytes into an INT #define array_uint16_le(p) ((unsigned int) (p)[0] \ + ((p)[1]<<8) ) #define array_uint32_le(p) ((unsigned int) (p)[0] \ + ((p)[1]<<8) + ((p)[2]<<16) \ + ((p)[3]<<24)) struct lv_event { uint32_t time; struct pressure { int sensor; int mbar; } pressure; }; // Liquivision supports the following sensor configurations: // Primary sensor only // Primary + Buddy sensor // Primary + Up to 4 additional sensors // Primary + Up to 9 addiitonal sensors struct lv_sensor_ids { uint16_t primary; uint16_t buddy; uint16_t group[9]; }; struct lv_sensor_ids sensor_ids; static int handle_event_ver2(int code, const unsigned char *ps, unsigned int ps_ptr, struct lv_event *event) { UNUSED(code); UNUSED(ps); UNUSED(ps_ptr); UNUSED(event); // Skip 4 bytes return 4; } static int handle_event_ver3(int code, const unsigned char *ps, unsigned int ps_ptr, struct lv_event *event) { int skip = 4; uint16_t current_sensor; switch (code) { case 0x0002: // Unknown case 0x0004: // Unknown skip = 4; break; case 0x0005: // Unknown skip = 6; break; case 0x0007: // Gas // 4 byte time // 1 byte O2, 1 bye He skip = 6; break; case 0x0008: // 4 byte time // 2 byte gas setpoint 2 skip = 6; break; case 0x000f: // Tank pressure event->time = array_uint32_le(ps + ps_ptr); current_sensor = array_uint16_le(ps + ps_ptr + 4); event->pressure.sensor = -1; event->pressure.mbar = array_uint16_le(ps + ps_ptr + 6) * 10; // cb->mb if (current_sensor == sensor_ids.primary) { event->pressure.sensor = 0; } else if (current_sensor == sensor_ids.buddy) { event->pressure.sensor = 1; } else { int i; for (i = 0; i < 9; ++i) { if (current_sensor == sensor_ids.group[i]) { event->pressure.sensor = i + 2; break; } } } // 1 byte PSR // 1 byte ST skip = 10; break; case 0x0010: // 4 byte time // 2 byte primary transmitter S/N // 2 byte buddy transmitter S/N // 2 byte group transmitter S/N (9x) // I don't think it's possible to change sensor IDs once a dive has started but disallow it here just in case if (sensor_ids.primary == 0) { sensor_ids.primary = array_uint16_le(ps + ps_ptr + 4); } if (sensor_ids.buddy == 0) { sensor_ids.buddy = array_uint16_le(ps + ps_ptr + 6); } int i; const unsigned char *group_ptr = ps + ps_ptr + 8; for (i = 0; i < 9; ++i, group_ptr += 2) { if (sensor_ids.group[i] == 0) { sensor_ids.group[i] = array_uint16_le(group_ptr); } } skip = 26; break; case 0x0015: // Unknown skip = 2; break; default: skip = 4; break; } return skip; } static void parse_dives(int log_version, const unsigned char *buf, unsigned int buf_size, struct dive_table *table, struct dive_site_table *sites) { unsigned int ptr = 0; unsigned char model; struct dive *dive; struct divecomputer *dc; struct sample *sample; while (ptr < buf_size) { int i; dive = alloc_dive(); memset(&sensor_ids, 0, sizeof(sensor_ids)); dc = &dive->dc; /* Just the main cylinder until we can handle the buddy cylinder porperly */ for (i = 0; i < 1; i++) { cylinder_t cyl = empty_cylinder; fill_default_cylinder(dive, &cyl); add_cylinder(&dive->cylinders, i, cyl); } // Model 0=Xen, 1,2=Xeo, 4=Lynx, other=Liquivision model = *(buf + ptr); switch (model) { case 0: dc->model = strdup("Xen"); break; case 1: case 2: dc->model = strdup("Xeo"); break; case 4: dc->model = strdup("Lynx"); break; default: dc->model = strdup("Liquivision"); break; } ptr++; // Dive location, assemble Location and Place unsigned int len, place_len; char *location; len = array_uint32_le(buf + ptr); ptr += 4; place_len = array_uint32_le(buf + ptr + len); if (len && place_len) { location = malloc(len + place_len + 4); memset(location, 0, len + place_len + 4); memcpy(location, buf + ptr, len); memcpy(location + len, ", ", 2); memcpy(location + len + 2, buf + ptr + len + 4, place_len); } else if (len) { location = strndup((char *)buf + ptr, len); } else if (place_len) { location = strndup((char *)buf + ptr + len + 4, place_len); } /* Store the location only if we have one */ if (len || place_len) { add_dive_to_dive_site(dive, find_or_create_dive_site_with_name(location, sites)); free(location); } ptr += len + 4 + place_len; // Dive comment len = array_uint32_le(buf + ptr); ptr += 4; // Blank notes are better than the default text if (len && strncmp((char *)buf + ptr, "Comment ...", 11)) { dive->notes = strndup((char *)buf + ptr, len); } ptr += len; dive->id = array_uint32_le(buf + ptr); ptr += 4; dive->number = array_uint16_le(buf + ptr) + 1; ptr += 2; dive->duration.seconds = array_uint32_le(buf + ptr); // seconds ptr += 4; dive->maxdepth.mm = array_uint16_le(buf + ptr) * 10; // cm->mm ptr += 2; dive->meandepth.mm = array_uint16_le(buf + ptr) * 10; // cm->mm ptr += 2; dive->when = array_uint32_le(buf + ptr); ptr += 4; //unsigned int end_time = array_uint32_le(buf + ptr); ptr += 4; //unsigned int sit = array_uint32_le(buf + ptr); ptr += 4; //if (sit == 0xffffffff) { //} dive->surface_pressure.mbar = array_uint16_le(buf + ptr); // ??? ptr += 2; //unsigned int rep_dive = array_uint16_le(buf + ptr); ptr += 2; dive->mintemp.mkelvin = C_to_mkelvin((float)array_uint16_le(buf + ptr)/10);// C->mK ptr += 2; dive->maxtemp.mkelvin = C_to_mkelvin((float)array_uint16_le(buf + ptr)/10);// C->mK ptr += 2; dive->salinity = *(buf + ptr); // ??? ptr += 1; unsigned int sample_count = array_uint32_le(buf + ptr); ptr += 4; // Sample interval unsigned char sample_interval; sample_interval = 1; unsigned char intervals[6] = {1,2,5,10,30,60}; if (*(buf + ptr) < 6) sample_interval = intervals[*(buf + ptr)]; ptr += 1; float start_cns = 0; unsigned char dive_mode = 0, algorithm = 0; if (array_uint32_le(buf + ptr) != sample_count) { // Xeo, with CNS and OTU start_cns = *(float *) (buf + ptr); ptr += 4; dive->cns = lrintf(*(float *) (buf + ptr)); // end cns ptr += 4; dive->otu = lrintf(*(float *) (buf + ptr)); ptr += 4; dive_mode = *(buf + ptr++); // 0=Deco, 1=Gauge, 2=None, 35=Rec algorithm = *(buf + ptr++); // 0=ZH-L16C+GF sample_count = array_uint32_le(buf + ptr); } if (sample_count == 0) { fprintf(stderr, "DEBUG: sample count 0 - terminating parser\n"); break; } if (ptr + sample_count * 4 + 4 > buf_size) { fprintf(stderr, "DEBUG: BOF - terminating parser\n"); break; } // we aren't using the start_cns, dive_mode, and algorithm, yet UNUSED(start_cns); UNUSED(dive_mode); UNUSED(algorithm); ptr += 4; // Parse dive samples const unsigned char *ds = buf + ptr; const unsigned char *ts = buf + ptr + sample_count * 2 + 4; const unsigned char *ps = buf + ptr + sample_count * 4 + 4; unsigned int ps_count = array_uint32_le(ps); ps += 4; // Bump ptr ptr += sample_count * 4 + 4; // Handle events unsigned int ps_ptr; ps_ptr = 0; unsigned int event_code, d = 0, e; struct lv_event event; memset(&event, 0, sizeof(event)); // Loop through events for (e = 0; e < ps_count; e++) { // Get event event_code = array_uint16_le(ps + ps_ptr); ps_ptr += 2; if (log_version == 3) { ps_ptr += handle_event_ver3(event_code, ps, ps_ptr, &event); if (event_code != 0xf) continue; // ignore all but pressure sensor event } else { // version 2 ps_ptr += handle_event_ver2(event_code, ps, ps_ptr, &event); continue; // ignore all events } uint32_t sample_time, last_time; int depth_mm, last_depth, temp_mk, last_temp; while (true) { sample = prepare_sample(dc); // Get sample times sample_time = d * sample_interval; depth_mm = array_uint16_le(ds + d * 2) * 10; // cm->mm temp_mk = C_to_mkelvin((float)array_uint16_le(ts + d * 2) / 10); // dC->mK last_time = (d ? (d - 1) * sample_interval : 0); if (d == sample_count) { // We still have events to record sample->time.seconds = event.time; sample->depth.mm = array_uint16_le(ds + (d - 1) * 2) * 10; // cm->mm sample->temperature.mkelvin = C_to_mkelvin((float) array_uint16_le(ts + (d - 1) * 2) / 10); // dC->mK add_sample_pressure(sample, event.pressure.sensor, event.pressure.mbar); finish_sample(dc); break; } else if (event.time > sample_time) { // Record sample and loop sample->time.seconds = sample_time; sample->depth.mm = depth_mm; sample->temperature.mkelvin = temp_mk; finish_sample(dc); d++; continue; } else if (event.time == sample_time) { sample->time.seconds = sample_time; sample->depth.mm = depth_mm; sample->temperature.mkelvin = temp_mk; add_sample_pressure(sample, event.pressure.sensor, event.pressure.mbar); finish_sample(dc); d++; break; } else { // Event is prior to sample sample->time.seconds = event.time; add_sample_pressure(sample, event.pressure.sensor, event.pressure.mbar); if (last_time == sample_time) { sample->depth.mm = depth_mm; sample->temperature.mkelvin = temp_mk; } else { // Extrapolate last_depth = array_uint16_le(ds + (d - 1) * 2) * 10; // cm->mm last_temp = C_to_mkelvin((float) array_uint16_le(ts + (d - 1) * 2) / 10); // dC->mK sample->depth.mm = last_depth + (depth_mm - last_depth) * ((int)event.time - (int)last_time) / sample_interval; sample->temperature.mkelvin = last_temp + (temp_mk - last_temp) * ((int)event.time - (int)last_time) / sample_interval; } finish_sample(dc); break; } } // while (true); } // for each event sample // record trailing depth samples for ( ;d < sample_count; d++) { sample = prepare_sample(dc); sample->time.seconds = d * sample_interval; sample->depth.mm = array_uint16_le(ds + d * 2) * 10; // cm->mm sample->temperature.mkelvin = C_to_mkelvin((float)array_uint16_le(ts + d * 2) / 10); finish_sample(dc); } if (log_version == 3 && model == 4) { // Advance to begin of next dive switch (array_uint16_le(ps + ps_ptr)) { case 0x0000: ps_ptr += 5; break; case 0x0100: ps_ptr += 7; break; case 0x0200: ps_ptr += 9; break; case 0x0300: ps_ptr += 11; break; case 0x0b0b: ps_ptr += 27; break; } while (((ptr + ps_ptr + 4) < buf_size) && (*(ps + ps_ptr) != 0x04)) ps_ptr++; } // End dive record_dive_to_table(dive, table); dive = NULL; // Advance ptr for next dive ptr += ps_ptr + 4; } // while //DEBUG save_dives("/tmp/test.xml"); // if we bailed out of the loop, the dive hasn't been recorded and dive hasn't been set to NULL free_dive(dive); } int try_to_open_liquivision(const char *filename, struct memblock *mem, struct dive_table *table, struct trip_table *trips, struct dive_site_table *sites) { UNUSED(filename); UNUSED(trips); const unsigned char *buf = mem->buffer; unsigned int buf_size = mem->size; unsigned int ptr; int log_version; // Get name length unsigned int len = array_uint32_le(buf); // Ignore length field and the name ptr = 4 + len; unsigned int dive_count = array_uint32_le(buf + ptr); if (dive_count == 0xffffffff) { // File version 3.0 log_version = 3; ptr += 6; dive_count = array_uint32_le(buf + ptr); } else { log_version = 2; } ptr += 4; parse_dives(log_version, buf + ptr, buf_size - ptr, table, sites); return 1; }
subsurface-for-dirk-master
core/liquivision.c
// SPDX-License-Identifier: MIT /* * uemis.c * * UEMIS SDA file importer * AUTHOR: Dirk Hohndel - Copyright 2011 * * Licensed under the MIT license. */ #include <stdio.h> #include <string.h> #include "gettext.h" #include "uemis.h" #include "divesite.h" #include "sample.h" #include <libdivecomputer/parser.h> #include <libdivecomputer/version.h> /* * following code is based on code found in at base64.sourceforge.net/b64.c * AUTHOR: Bob Trower 08/04/01 * COPYRIGHT: Copyright (c) Trantor Standard Systems Inc., 2001 * NOTE: This source code may be used as you wish, subject to * the MIT license. */ /* * Translation Table to decode (created by Bob Trower) */ static const char cd64[] = "|$$$}rstuvwxyz{$$$$$$$>?@ABCDEFGHIJKLMNOPQRSTUVW$$$$$$XYZ[\\]^_`abcdefghijklmnopq"; /* * decodeblock -- decode 4 '6-bit' characters into 3 8-bit binary bytes */ static void decodeblock(unsigned char in[4], unsigned char out[3]) { out[0] = (unsigned char)(in[0] << 2 | in[1] >> 4); out[1] = (unsigned char)(in[1] << 4 | in[2] >> 2); out[2] = (unsigned char)(((in[2] << 6) & 0xc0) | in[3]); } /* * decode a base64 encoded stream discarding padding, line breaks and noise */ static void decode(uint8_t *inbuf, uint8_t *outbuf, int inbuf_len) { uint8_t in[4], out[3], v; int i, len, indx_in = 0, indx_out = 0; while (indx_in < inbuf_len) { for (len = 0, i = 0; i < 4 && (indx_in < inbuf_len); i++) { v = 0; while ((indx_in < inbuf_len) && v == 0) { v = inbuf[indx_in++]; v = ((v < 43 || v > 122) ? 0 : cd64[v - 43]); if (v) v = ((v == '$') ? 0 : v - 61); } if (indx_in < inbuf_len) { len++; if (v) in[i] = (v - 1); } else in[i] = 0; } if (len) { decodeblock(in, out); for (i = 0; i < len - 1; i++) outbuf[indx_out++] = out[i]; } } } /* end code from Bob Trower */ /* * convert the base64 data blog */ static int uemis_convert_base64(char *base64, uint8_t **data) { int len, datalen; len = strlen(base64); datalen = (len / 4 + 1) * 3; if (datalen < 0x123 + 0x25) /* less than header + 1 sample??? */ fprintf(stderr, "suspiciously short data block %d\n", datalen); *data = malloc(datalen); if (!*data) { fprintf(stderr, "Out of memory\n"); return 0; } decode((unsigned char *)base64, *data, len); if (memcmp(*data, "Dive\01\00\00", 7)) fprintf(stderr, "Missing Dive100 header\n"); return datalen; } struct uemis_helper { uint32_t diveid; int lbs; int divespot; struct dive_site *dive_site; struct uemis_helper *next; }; static struct uemis_helper *uemis_helper = NULL; static struct uemis_helper *uemis_get_helper(uint32_t diveid) { struct uemis_helper **php = &uemis_helper; struct uemis_helper *hp = *php; while (hp) { if (hp->diveid == diveid) return hp; if (hp->next) { hp = hp->next; continue; } php = &hp->next; break; } hp = *php = calloc(1, sizeof(struct uemis_helper)); hp->diveid = diveid; hp->next = NULL; return hp; } static void uemis_weight_unit(int diveid, int lbs) { struct uemis_helper *hp = uemis_get_helper(diveid); if (hp) hp->lbs = lbs; } int uemis_get_weight_unit(uint32_t diveid) { struct uemis_helper *hp = uemis_helper; while (hp) { if (hp->diveid == diveid) return hp->lbs; hp = hp->next; } /* odd - we should have found this; default to kg */ return 0; } void uemis_mark_divelocation(int diveid, int divespot, struct dive_site *ds) { struct uemis_helper *hp = uemis_get_helper(diveid); hp->divespot = divespot; hp->dive_site = ds; } /* support finding a dive spot based on the diveid */ int uemis_get_divespot_id_by_diveid(uint32_t diveid) { struct uemis_helper *hp = uemis_helper; while (hp) { if (hp->diveid == diveid) return hp->divespot; hp = hp->next; } return -1; } void uemis_set_divelocation(int divespot, char *text, double longitude, double latitude) { struct uemis_helper *hp = uemis_helper; while (hp) { if (hp->divespot == divespot) { struct dive_site *ds = hp->dive_site; if (ds) { ds->name = strdup(text); ds->location = create_location(latitude, longitude); } } hp = hp->next; } } /* Create events from the flag bits and other data in the sample; * These bits basically represent what is displayed on screen at sample time. * Many of these 'warnings' are way hyper-active and seriously clutter the * profile plot - so these are disabled by default * * we mark all the strings for translation, but we store the untranslated * strings and only convert them when displaying them on screen - this way * when we write them to the XML file we'll always have the English strings, * regardless of locale */ static void uemis_event(struct dive *dive, struct divecomputer *dc, struct sample *sample, uemis_sample_t *u_sample) { uint8_t *flags = u_sample->flags; int stopdepth; static int lastndl; if (flags[1] & 0x01) add_event(dc, sample->time.seconds, 0, 0, 0, QT_TRANSLATE_NOOP("gettextFromC", "Safety stop violation")); if (flags[1] & 0x08) add_event(dc, sample->time.seconds, 0, 0, 0, QT_TRANSLATE_NOOP("gettextFromC", "Speed alarm")); #if WANT_CRAZY_WARNINGS if (flags[1] & 0x06) /* both bits 1 and 2 are a warning */ add_event(dc, sample->time.seconds, 0, 0, 0, QT_TRANSLATE_NOOP("gettextFromC", "Speed warning")); if (flags[1] & 0x10) add_event(dc, sample->time.seconds, 0, 0, 0, QT_TRANSLATE_NOOP("gettextFromC", "pO₂ green warning")); #endif if (flags[1] & 0x20) add_event(dc, sample->time.seconds, 0, 0, 0, QT_TRANSLATE_NOOP("gettextFromC", "pO₂ ascend warning")); if (flags[1] & 0x40) add_event(dc, sample->time.seconds, 0, 0, 0, QT_TRANSLATE_NOOP("gettextFromC", "pO₂ ascend alarm")); /* flags[2] reflects the deco / time bar * flags[3] reflects more display details on deco and pO2 */ if (flags[4] & 0x01) add_event(dc, sample->time.seconds, 0, 0, 0, QT_TRANSLATE_NOOP("gettextFromC", "Tank pressure info")); if (flags[4] & 0x04) add_event(dc, sample->time.seconds, 0, 0, 0, QT_TRANSLATE_NOOP("gettextFromC", "RGT warning")); if (flags[4] & 0x08) add_event(dc, sample->time.seconds, 0, 0, 0, QT_TRANSLATE_NOOP("gettextFromC", "RGT alert")); if (flags[4] & 0x40) add_event(dc, sample->time.seconds, 0, 0, 0, QT_TRANSLATE_NOOP("gettextFromC", "Tank change suggested")); if (flags[4] & 0x80) add_event(dc, sample->time.seconds, 0, 0, 0, QT_TRANSLATE_NOOP("gettextFromC", "Depth limit exceeded")); if (flags[5] & 0x01) add_event(dc, sample->time.seconds, 0, 0, 0, QT_TRANSLATE_NOOP("gettextFromC", "Max deco time warning")); if (flags[5] & 0x04) add_event(dc, sample->time.seconds, 0, 0, 0, QT_TRANSLATE_NOOP("gettextFromC", "Dive time info")); if (flags[5] & 0x08) add_event(dc, sample->time.seconds, 0, 0, 0, QT_TRANSLATE_NOOP("gettextFromC", "Dive time alert")); if (flags[5] & 0x10) add_event(dc, sample->time.seconds, 0, 0, 0, QT_TRANSLATE_NOOP("gettextFromC", "Marker")); if (flags[6] & 0x02) add_event(dc, sample->time.seconds, 0, 0, 0, QT_TRANSLATE_NOOP("gettextFromC", "No tank data")); if (flags[6] & 0x04) add_event(dc, sample->time.seconds, 0, 0, 0, QT_TRANSLATE_NOOP("gettextFromC", "Low battery warning")); if (flags[6] & 0x08) add_event(dc, sample->time.seconds, 0, 0, 0, QT_TRANSLATE_NOOP("gettextFromC", "Low battery alert")); /* flags[7] reflects the little on screen icons that remind of previous * warnings / alerts - not useful for events */ #if UEMIS_DEBUG & 32 int i, j; for (i = 0; i < 8; i++) { printf(" %d: ", 29 + i); for (j = 7; j >= 0; j--) printf("%c", flags[i] & 1 << j ? '1' : '0'); } printf("\n"); #endif /* now add deco / NDL * we don't use events but store this in the sample - that makes much more sense * for the way we display this information * What we know about the encoding so far: * flags[3].bit0 | flags[5].bit1 != 0 ==> in deco * flags[0].bit7 == 1 ==> Safety Stop * otherwise NDL */ stopdepth = rel_mbar_to_depth(u_sample->hold_depth, dive); if ((flags[3] & 1) | (flags[5] & 2)) { /* deco */ sample->in_deco = true; sample->stopdepth.mm = stopdepth; sample->stoptime.seconds = u_sample->hold_time * 60; sample->ndl.seconds = 0; } else if (flags[0] & 128) { /* safety stop - distinguished from deco stop by having * both ndl and stop information */ sample->in_deco = false; sample->stopdepth.mm = stopdepth; sample->stoptime.seconds = u_sample->hold_time * 60; sample->ndl.seconds = lastndl; } else { /* NDL */ sample->in_deco = false; lastndl = sample->ndl.seconds = u_sample->hold_time * 60; sample->stopdepth.mm = 0; sample->stoptime.seconds = 0; } #if UEMIS_DEBUG & 32 printf("%dm:%ds: p_amb_tol:%d surface:%d holdtime:%d holddepth:%d/%d ---> stopdepth:%d stoptime:%d ndl:%d\n", sample->time.seconds / 60, sample->time.seconds % 60, u_sample->p_amb_tol, dive->dc.surface_pressure.mbar, u_sample->hold_time, u_sample->hold_depth, stopdepth, sample->stopdepth.mm, sample->stoptime.seconds, sample->ndl.seconds); #endif } /* * parse uemis base64 data blob into struct dive */ void uemis_parse_divelog_binary(char *base64, void *datap) { int datalen; int i; uint8_t *data; struct sample *sample = NULL; uemis_sample_t *u_sample; struct dive *dive = datap; struct divecomputer *dc = &dive->dc; int template, gasoffset; uint8_t active = 0; datalen = uemis_convert_base64(base64, &data); dive->dc.airtemp.mkelvin = C_to_mkelvin((*(uint16_t *)(data + 45)) / 10.0); dive->dc.surface_pressure.mbar = *(uint16_t *)(data + 43); if (*(uint8_t *)(data + 19)) dive->dc.salinity = SEAWATER_SALINITY; /* avg grams per 10l sea water */ else dive->dc.salinity = FRESHWATER_SALINITY; /* grams per 10l fresh water */ /* this will allow us to find the last dive read so far from this computer */ dc->model = strdup("Uemis Zurich"); dc->deviceid = *(uint32_t *)(data + 9); dc->diveid = *(uint16_t *)(data + 7); /* remember the weight units used in this dive - we may need this later when * parsing the weight */ uemis_weight_unit(dc->diveid, *(uint8_t *)(data + 24)); /* dive template in use: 0 = air 1 = nitrox (B) 2 = nitrox (B+D) 3 = nitrox (B+T+D) uemis cylinder data is insane - it stores seven tank settings in a block and the template tells us which of the four groups of tanks we need to look at */ gasoffset = template = *(uint8_t *)(data + 115); if (template == 3) gasoffset = 4; if (template == 0) template = 1; for (i = 0; i < template; i++) { float volume = *(float *)(data + 116 + 25 * (gasoffset + i)) * 1000.0f; /* uemis always assumes a working pressure of 202.6bar (!?!?) - I first thought * it was 3000psi, but testing against all my dives gets me that strange number. * Still, that's of course completely bogus and shows they don't get how * cylinders are named in non-metric parts of the world... * we store the incorrect working pressure to get the SAC calculations "close" * but the user will have to correct this manually */ cylinder_t *cyl = get_or_create_cylinder(dive, i); cyl->type.size.mliter = lrintf(volume); cyl->type.workingpressure.mbar = 202600; cyl->gasmix.o2.permille = *(uint8_t *)(data + 120 + 25 * (gasoffset + i)) * 10; cyl->gasmix.he.permille = 0; } /* first byte of divelog data is at offset 0x123 */ i = 0x123; u_sample = (uemis_sample_t *)(data + i); while ((i <= datalen) && (data[i] != 0 || data[i + 1] != 0)) { if (u_sample->active_tank != active) { if (u_sample->active_tank >= dive->cylinders.nr) { fprintf(stderr, "got invalid sensor #%d was #%d\n", u_sample->active_tank, active); } else { active = u_sample->active_tank; add_gas_switch_event(dive, dc, u_sample->dive_time, active); } } sample = prepare_sample(dc); sample->time.seconds = u_sample->dive_time; sample->depth.mm = rel_mbar_to_depth(u_sample->water_pressure, dive); sample->temperature.mkelvin = C_to_mkelvin(u_sample->dive_temperature / 10.0); add_sample_pressure(sample, active, (u_sample->tank_pressure_high * 256 + u_sample->tank_pressure_low) * 10); sample->cns = u_sample->cns; uemis_event(dive, dc, sample, u_sample); finish_sample(dc); i += 0x25; u_sample++; } if (sample) dive->dc.duration.seconds = sample->time.seconds - 1; /* get data from the footer */ char buffer[24]; snprintf(buffer, sizeof(buffer), "%1u.%02u", data[18], data[17]); add_extra_data(dc, "FW Version", buffer); snprintf(buffer, sizeof(buffer), "%08x", *(uint32_t *)(data + 9)); add_extra_data(dc, "Serial", buffer); snprintf(buffer, sizeof(buffer), "%d", *(uint16_t *)(data + i + 35)); add_extra_data(dc, "main battery after dive", buffer); snprintf(buffer, sizeof(buffer), "%0u:%02u", FRACTION(*(uint16_t *)(data + i + 24), 60)); add_extra_data(dc, "no fly time", buffer); snprintf(buffer, sizeof(buffer), "%0u:%02u", FRACTION(*(uint16_t *)(data + i + 26), 60)); add_extra_data(dc, "no dive time", buffer); snprintf(buffer, sizeof(buffer), "%0u:%02u", FRACTION(*(uint16_t *)(data + i + 28), 60)); add_extra_data(dc, "desat time", buffer); snprintf(buffer, sizeof(buffer), "%u", *(uint16_t *)(data + i + 30)); add_extra_data(dc, "allowed altitude", buffer); return; }
subsurface-for-dirk-master
core/uemis.c
/* * libdivecomputer * * Copyright (C) 2018 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #ifdef _WIN32 #define NOGDI #include <windows.h> #else #include <time.h> #include <sys/time.h> #ifdef HAVE_MACH_MACH_TIME_H #include <mach/mach_time.h> #endif #endif #include "timer.h" struct dc_timer_t { #if defined (_WIN32) LARGE_INTEGER timestamp; LARGE_INTEGER frequency; #elif defined (HAVE_CLOCK_GETTIME) struct timespec timestamp; #elif defined (HAVE_MACH_ABSOLUTE_TIME) uint64_t timestamp; mach_timebase_info_data_t info; #else struct timeval timestamp; #endif }; dc_status_t dc_timer_new (dc_timer_t **out) { dc_timer_t *timer = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; timer = (dc_timer_t *) malloc (sizeof (dc_timer_t)); if (timer == NULL) { return DC_STATUS_NOMEMORY; } #if defined (_WIN32) if (!QueryPerformanceFrequency(&timer->frequency) || !QueryPerformanceCounter(&timer->timestamp)) { free(timer); return DC_STATUS_IO; } #elif defined (HAVE_CLOCK_GETTIME) if (clock_gettime(CLOCK_MONOTONIC, &timer->timestamp) != 0) { free(timer); return DC_STATUS_IO; } #elif defined (HAVE_MACH_ABSOLUTE_TIME) if (mach_timebase_info(&timer->info) != KERN_SUCCESS) { free(timer); return DC_STATUS_IO; } timer->timestamp = mach_absolute_time(); #else if (gettimeofday (&timer->timestamp, NULL) != 0) { free(timer); return DC_STATUS_IO; } #endif *out = timer; return DC_STATUS_SUCCESS; } dc_status_t dc_timer_now (dc_timer_t *timer, dc_usecs_t *usecs) { dc_status_t status = DC_STATUS_SUCCESS; dc_usecs_t value = 0; if (timer == NULL) { status = DC_STATUS_INVALIDARGS; goto out; } #if defined (_WIN32) LARGE_INTEGER now; if (!QueryPerformanceCounter(&now)) { status = DC_STATUS_IO; goto out; } value = (now.QuadPart - timer->timestamp.QuadPart) * 1000000 / timer->frequency.QuadPart; #elif defined (HAVE_CLOCK_GETTIME) struct timespec now, delta; if (clock_gettime(CLOCK_MONOTONIC, &now) != 0) { status = DC_STATUS_IO; goto out; } if (now.tv_nsec < timer->timestamp.tv_nsec) { delta.tv_nsec = 1000000000 + now.tv_nsec - timer->timestamp.tv_nsec; delta.tv_sec = now.tv_sec - timer->timestamp.tv_sec - 1; } else { delta.tv_nsec = now.tv_nsec - timer->timestamp.tv_nsec; delta.tv_sec = now.tv_sec - timer->timestamp.tv_sec; } value = (dc_usecs_t) delta.tv_sec * 1000000 + delta.tv_nsec / 1000; #elif defined (HAVE_MACH_ABSOLUTE_TIME) uint64_t now = mach_absolute_time(); value = (now - timer->timestamp) * timer->info.numer / (timer->info.denom * 1000); #else struct timeval now, delta; if (gettimeofday (&now, NULL) != 0) { status = DC_STATUS_IO; goto out; } timersub (&now, &timer->timestamp, &delta); value = (dc_usecs_t) delta.tv_sec * 1000000 + delta.tv_usec; #endif out: if (usecs) *usecs = value; return status; } dc_status_t dc_timer_free (dc_timer_t *timer) { free (timer); return DC_STATUS_SUCCESS; }
subsurface-for-dirk-master
core/timer.c
// SPDX-License-Identifier: GPL-2.0 #include "taxonomy.h" #include "gettext.h" #include "subsurface-string.h" #include <stdlib.h> #include <stdio.h> char *taxonomy_category_names[TC_NR_CATEGORIES] = { QT_TRANSLATE_NOOP("gettextFromC", "None"), QT_TRANSLATE_NOOP("gettextFromC", "Ocean"), QT_TRANSLATE_NOOP("gettextFromC", "Country"), QT_TRANSLATE_NOOP("gettextFromC", "State"), QT_TRANSLATE_NOOP("gettextFromC", "County"), QT_TRANSLATE_NOOP("gettextFromC", "Town"), QT_TRANSLATE_NOOP("gettextFromC", "City") }; // these are the names for geoname.org char *taxonomy_api_names[TC_NR_CATEGORIES] = { "none", "name", "countryName", "adminName1", "adminName2", "toponymName", "adminName3" }; static void alloc_taxonomy_table(struct taxonomy_data *t) { if (!t->category) t->category = calloc(TC_NR_CATEGORIES, sizeof(struct taxonomy)); } void free_taxonomy(struct taxonomy_data *t) { if (t) { for (int i = 0; i < t->nr; i++) free((void *)t->category[i].value); free(t->category); t->category = NULL; t->nr = 0; } } void copy_taxonomy(const struct taxonomy_data *orig, struct taxonomy_data *copy) { if (orig->category == NULL) { free_taxonomy(copy); } else { alloc_taxonomy_table(copy); for (int i = 0; i < TC_NR_CATEGORIES; i++) { if (i < copy->nr) { free((void *)copy->category[i].value); copy->category[i].value = NULL; } if (i < orig->nr) { copy->category[i] = orig->category[i]; copy->category[i].value = copy_string(orig->category[i].value); } } copy->nr = orig->nr; } } static int taxonomy_index_for_category(const struct taxonomy_data *t, enum taxonomy_category cat) { for (int i = 0; i < t->nr; i++) { if (t->category[i].category == cat) return i; } return -1; } const char *taxonomy_get_value(const struct taxonomy_data *t, enum taxonomy_category cat) { int idx = taxonomy_index_for_category(t, cat); return idx >= 0 ? t->category[idx].value : NULL; } const char *taxonomy_get_country(const struct taxonomy_data *t) { return taxonomy_get_value(t, TC_COUNTRY); } void taxonomy_set_category(struct taxonomy_data *t, enum taxonomy_category category, const char *value, enum taxonomy_origin origin) { int idx = taxonomy_index_for_category(t, category); if (idx < 0) { alloc_taxonomy_table(t); // make sure we have taxonomy data allocated if (t->nr == TC_NR_CATEGORIES - 1) { // can't add another one fprintf(stderr, "Error adding taxonomy category\n"); return; } idx = t->nr++; } else { free((void *)t->category[idx].value); t->category[idx].value = NULL; } t->category[idx].value = strdup(value); t->category[idx].origin = origin; t->category[idx].category = category; } void taxonomy_set_country(struct taxonomy_data *t, const char *country, enum taxonomy_origin origin) { fprintf(stderr, "%s: set the taxonomy country to %s\n", __func__, country); taxonomy_set_category(t, TC_COUNTRY, country, origin); }
subsurface-for-dirk-master
core/taxonomy.c
// SPDX-License-Identifier: GPL-2.0 #include "pref.h" #include "subsurface-string.h" #include "git-access.h" // for CLOUD_HOST struct preferences prefs, git_prefs; struct preferences default_prefs = { .cloud_base_url = "https://" CLOUD_HOST_EU "/", // if we don't know any better, use the European host .units = SI_UNITS, .unit_system = METRIC, .coordinates_traditional = true, .pp_graphs = { .po2 = false, .pn2 = false, .phe = false, .po2_threshold_min = 0.16, .po2_threshold_max = 1.6, .pn2_threshold = 4.0, .phe_threshold = 13.0, }, .mod = false, .modpO2 = 1.6, .ead = false, .hrgraph = false, .percentagegraph = false, .dcceiling = true, .redceiling = false, .calcceiling = false, .calcceiling3m = false, .calcndltts = false, .decoinfo = true, .gflow = 30, .gfhigh = 75, .animation_speed = 500, .gf_low_at_maxdepth = false, .show_ccr_setpoint = false, .show_ccr_sensors = false, .show_scr_ocpo2 = false, .font_size = -1, .mobile_scale = 1.0, .display_invalid_dives = false, .show_sac = false, .display_unused_tanks = false, .display_default_tank_infos = true, .show_average_depth = true, .show_icd = false, .ascrate75 = 9000 / 60, .ascrate50 = 9000 / 60, .ascratestops = 9000 / 60, .ascratelast6m = 9000 / 60, .descrate = 18000 / 60, .sacfactor = 400, .problemsolvingtime = 4, .bottompo2 = 1400, .decopo2 = 1600, .bestmixend.mm = 30000, .doo2breaks = false, .dobailout = false, .drop_stone_mode = false, .switch_at_req_stop = false, .min_switch_duration = 60, .surface_segment = 0, .last_stop = false, .verbatim_plan = false, .display_runtime = true, .display_duration = true, .display_transitions = true, .display_variations = false, .o2narcotic = true, .safetystop = true, .bottomsac = 20000, .decosac = 17000, .reserve_gas=40000, .o2consumption = 720, .pscr_ratio = 100, .show_pictures_in_profile = true, .tankbar = false, .defaultsetpoint = 1100, .geocoding = { .category = { 0 } }, .locale = { .use_system_language = true, }, .planner_deco_mode = BUEHLMANN, .vpmb_conservatism = 3, #if defined(SUBSURFACE_MOBILE) .cloud_timeout = 10, #else .cloud_timeout = 5, #endif .auto_recalculate_thumbnails = true, .extract_video_thumbnails = true, .extract_video_thumbnails_position = 20, // The first fifth seems like a reasonable place .three_m_based_grid = false, }; /* copy a preferences block, including making copies of all included strings */ void copy_prefs(struct preferences *src, struct preferences *dest) { *dest = *src; dest->divelist_font = copy_string(src->divelist_font); dest->default_filename = copy_string(src->default_filename); dest->default_cylinder = copy_string(src->default_cylinder); dest->cloud_base_url = copy_string(src->cloud_base_url); dest->proxy_host = copy_string(src->proxy_host); dest->proxy_user = copy_string(src->proxy_user); dest->proxy_pass = copy_string(src->proxy_pass); dest->time_format = copy_string(src->time_format); dest->date_format = copy_string(src->date_format); dest->date_format_short = copy_string(src->date_format_short); dest->cloud_storage_password = copy_string(src->cloud_storage_password); dest->cloud_storage_email = copy_string(src->cloud_storage_email); dest->cloud_storage_email_encoded = copy_string(src->cloud_storage_email_encoded); dest->ffmpeg_executable = copy_string(src->ffmpeg_executable); } /* * Free strduped prefs before exit. * * These are not real leaks but they plug the holes found by eg. * valgrind so you can find the real leaks. */ void free_prefs(void) { // nop }
subsurface-for-dirk-master
core/pref.c
// SPDX-License-Identifier: GPL-2.0 #include "gas.h" #include "pref.h" #include "gettext.h" #include <stdio.h> #include <string.h> /* Perform isobaric counterdiffusion calculations for gas changes in trimix dives. * Here we use the rule-of-fifths where, during a change involving trimix gas, the increase in nitrogen * should not exceed one fifth of the decrease in helium. * Parameters: 1) pointers to two gas mixes, the gas being switched from and the gas being switched to. * 2) a pointer to an icd_data structure. * Output: i) The icd_data stucture is filled with the delta_N2 and delta_He numbers (as permille). * ii) Function returns a boolean indicating an exceeding of the rule-of-fifths. False = no icd problem. */ bool isobaric_counterdiffusion(struct gasmix oldgasmix, struct gasmix newgasmix, struct icd_data *results) { if (!prefs.show_icd) return false; results->dN2 = get_n2(newgasmix) - get_n2(oldgasmix); results->dHe = get_he(newgasmix) - get_he(oldgasmix); return get_he(oldgasmix) > 0 && results->dN2 > 0 && results->dHe < 0 && get_he(oldgasmix) && results->dN2 > 0 && 5 * results->dN2 > -results->dHe; } bool gasmix_is_invalid(struct gasmix mix) { return mix.o2.permille < 0; } int same_gasmix(struct gasmix a, struct gasmix b) { if (gasmix_is_invalid(a) || gasmix_is_invalid(b)) return 0; if (gasmix_is_air(a) && gasmix_is_air(b)) return 1; return get_o2(a) == get_o2(b) && get_he(a) == get_he(b); } void sanitize_gasmix(struct gasmix *mix) { unsigned int o2, he; o2 = get_o2(*mix); he = get_he(*mix); /* Regular air: leave empty */ if (!he) { if (!o2) return; /* 20.8% to 21% O2 is just air */ if (gasmix_is_air(*mix)) { mix->o2.permille = 0; return; } } /* Sane mix? */ if (o2 <= 1000 && he <= 1000 && o2 + he <= 1000) return; fprintf(stderr, "Odd gasmix: %u O2 %u He\n", o2, he); memset(mix, 0, sizeof(*mix)); } int gasmix_distance(struct gasmix a, struct gasmix b) { int a_o2 = get_o2(a), b_o2 = get_o2(b); int a_he = get_he(a), b_he = get_he(b); int delta_o2 = a_o2 - b_o2, delta_he = a_he - b_he; delta_he = delta_he * delta_he; delta_o2 = delta_o2 * delta_o2; return delta_he + delta_o2; } bool gasmix_is_air(struct gasmix gasmix) { int o2 = get_o2(gasmix); int he = get_he(gasmix); return (he == 0) && (o2 == 0 || ((o2 >= O2_IN_AIR - 1) && (o2 <= O2_IN_AIR + 1))); } fraction_t make_fraction(int i) { fraction_t res; res.permille = i; return res; } fraction_t get_gas_component_fraction(struct gasmix mix, enum gas_component component) { switch (component) { case O2: return make_fraction(get_o2(mix)); case N2: return make_fraction(get_n2(mix)); case HE: return make_fraction(get_he(mix)); default: return make_fraction(0); } } // O2 pressure in mbar according to the steady state model for the PSCR // NB: Ambient pressure comes in bar! int pscr_o2(const double amb_pressure, struct gasmix mix) { int o2 = (int)(get_o2(mix) * amb_pressure - (1.0 - get_o2(mix) / 1000.0) * prefs.o2consumption / (prefs.bottomsac * prefs.pscr_ratio) * 1000000); if (o2 < 0.0) // He's dead, Jim. o2 = 0.0; return o2; } /* fill_pressures(): Compute partial gas pressures in bar from gasmix and ambient pressures, possibly for OC or CCR, to be * extended to PSCT. This function does the calculations of gas pressures applicable to a single point on the dive profile. * The structure "pressures" is used to return calculated gas pressures to the calling software. * Call parameters: po2 = po2 value applicable to the record in calling function * amb_pressure = ambient pressure applicable to the record in calling function * *pressures = structure for communicating o2 sensor values from and gas pressures to the calling function. * *mix = structure containing cylinder gas mixture information. * divemode = the dive mode pertaining to this point in the dive profile. * This function called by: calculate_gas_information_new() in profile.c; add_segment() in deco.c. */ void fill_pressures(struct gas_pressures *pressures, const double amb_pressure, struct gasmix mix, double po2, enum divemode_t divemode) { if ((divemode != OC) && po2) { // This is a rebreather dive where pressures->o2 is defined if (po2 >= amb_pressure) { pressures->o2 = amb_pressure; pressures->n2 = pressures->he = 0.0; } else { pressures->o2 = po2; if (get_o2(mix) == 1000) { pressures->he = pressures->n2 = 0; } else { pressures->he = (amb_pressure - pressures->o2) * (double)get_he(mix) / (1000 - get_o2(mix)); pressures->n2 = amb_pressure - pressures->o2 - pressures->he; } } } else { if (divemode == PSCR) { /* The steady state approximation should be good enough */ pressures->o2 = pscr_o2(amb_pressure, mix) / 1000.0; if (get_o2(mix) != 1000) { pressures->he = (amb_pressure - pressures->o2) * get_he(mix) / (1000.0 - get_o2(mix)); pressures->n2 = (amb_pressure - pressures->o2) * get_n2(mix) / (1000.0 - get_o2(mix)); } else { pressures->he = pressures->n2 = 0; } } else { // Open circuit dives: no gas pressure values available, they need to be calculated pressures->o2 = get_o2(mix) / 1000.0 * amb_pressure; // These calculations are also used if the CCR calculation above.. pressures->he = get_he(mix) / 1000.0 * amb_pressure; // ..returned a po2 of zero (i.e. o2 sensor data not resolvable) pressures->n2 = get_n2(mix) / 1000.0 * amb_pressure; } } } enum gastype gasmix_to_type(struct gasmix mix) { if (gasmix_is_air(mix)) return GASTYPE_AIR; if (get_o2(mix) >= 980) return GASTYPE_OXYGEN; if (get_he(mix) == 0) return get_o2(mix) >= 230 ? GASTYPE_NITROX : GASTYPE_AIR; if (get_o2(mix) <= 180) return GASTYPE_HYPOXIC_TRIMIX; return get_o2(mix) <= 230 ? GASTYPE_NORMOXIC_TRIMIX : GASTYPE_HYPEROXIC_TRIMIX; } static const char *gastype_names[] = { QT_TRANSLATE_NOOP("gettextFromC", "Air"), QT_TRANSLATE_NOOP("gettextFromC", "Nitrox"), QT_TRANSLATE_NOOP("gettextFromC", "Hypoxic Trimix"), QT_TRANSLATE_NOOP("gettextFromC", "Normoxic Trimix"), QT_TRANSLATE_NOOP("gettextFromC", "Hyperoxic Trimix"), QT_TRANSLATE_NOOP("gettextFromC", "Oxygen") }; const char *gastype_name(enum gastype type) { if (type < 0 || type >= GASTYPE_COUNT) return ""; return translate("gettextFromC", gastype_names[type]); }
subsurface-for-dirk-master
core/gas.c
#include "core/profile.h" #include "core/errorhelper.h" #include "core/file.h" #include "core/membuffer.h" #include "core/subsurface-string.h" #include "core/save-profiledata.h" #include "core/version.h" #include <errno.h> static void put_int(struct membuffer *b, int val) { put_format(b, "\"%d\", ", val); } static void put_int_with_nl(struct membuffer *b, int val) { put_format(b, "\"%d\"\n", val); } static void put_csv_string(struct membuffer *b, const char *val) { put_format(b, "\"%s\", ", val); } static void put_csv_string_with_nl(struct membuffer *b, const char *val) { put_format(b, "\"%s\"\n", val); } static void put_double(struct membuffer *b, double val) { put_format(b, "\"%f\", ", val); } static void put_video_time(struct membuffer *b, int secs) { int hours = secs / 3600; secs -= hours * 3600; int mins = secs / 60; secs -= mins * 60; put_format(b, "%d:%02d:%02d.000,", hours, mins, secs); } static void put_pd(struct membuffer *b, const struct plot_info *pi, int idx) { const struct plot_data *entry = pi->entry + idx; put_int(b, entry->in_deco); put_int(b, entry->sec); for (int c = 0; c < pi->nr_cylinders; c++) { put_int(b, get_plot_sensor_pressure(pi, idx, c)); put_int(b, get_plot_interpolated_pressure(pi, idx, c)); } put_int(b, entry->temperature); put_int(b, entry->depth); put_int(b, entry->ceiling); for (int i = 0; i < 16; i++) put_int(b, entry->ceilings[i]); for (int i = 0; i < 16; i++) put_int(b, entry->percentages[i]); put_int(b, entry->ndl); put_int(b, entry->tts); put_int(b, entry->rbt); put_int(b, entry->stoptime); put_int(b, entry->stopdepth); put_int(b, entry->cns); put_int(b, entry->smoothed); put_int(b, entry->sac); put_int(b, entry->running_sum); put_double(b, entry->pressures.o2); put_double(b, entry->pressures.n2); put_double(b, entry->pressures.he); put_int(b, entry->o2pressure.mbar); put_int(b, entry->o2sensor[0].mbar); put_int(b, entry->o2sensor[1].mbar); put_int(b, entry->o2sensor[2].mbar); put_int(b, entry->o2setpoint.mbar); put_int(b, entry->scr_OC_pO2.mbar); put_int(b, entry->mod); put_int(b, entry->ead); put_int(b, entry->end); put_int(b, entry->eadd); switch (entry->velocity) { case STABLE: put_csv_string(b, "STABLE"); break; case SLOW: put_csv_string(b, "SLOW"); break; case MODERATE: put_csv_string(b, "MODERATE"); break; case FAST: put_csv_string(b, "FAST"); break; case CRAZY: put_csv_string(b, "CRAZY"); break; } put_int(b, entry->speed); put_int(b, entry->in_deco_calc); put_int(b, entry->ndl_calc); put_int(b, entry->tts_calc); put_int(b, entry->stoptime_calc); put_int(b, entry->stopdepth_calc); put_int(b, entry->pressure_time); put_int(b, entry->heartbeat); put_int(b, entry->bearing); put_double(b, entry->ambpressure); put_double(b, entry->gfline); put_double(b, entry->surface_gf); put_double(b, entry->density); put_int_with_nl(b, entry->icd_warning ? 1 : 0); } static void put_headers(struct membuffer *b, int nr_cylinders) { put_csv_string(b, "in_deco"); put_csv_string(b, "sec"); for (int c = 0; c < nr_cylinders; c++) { put_format(b, "\"pressure_%d_cylinder\", ", c); put_format(b, "\"pressure_%d_interpolated\", ", c); } put_csv_string(b, "temperature"); put_csv_string(b, "depth"); put_csv_string(b, "ceiling"); for (int i = 0; i < 16; i++) put_format(b, "\"ceiling_%d\", ", i); for (int i = 0; i < 16; i++) put_format(b, "\"percentage_%d\", ", i); put_csv_string(b, "ndl"); put_csv_string(b, "tts"); put_csv_string(b, "rbt"); put_csv_string(b, "stoptime"); put_csv_string(b, "stopdepth"); put_csv_string(b, "cns"); put_csv_string(b, "smoothed"); put_csv_string(b, "sac"); put_csv_string(b, "running_sum"); put_csv_string(b, "pressureo2"); put_csv_string(b, "pressuren2"); put_csv_string(b, "pressurehe"); put_csv_string(b, "o2pressure"); put_csv_string(b, "o2sensor0"); put_csv_string(b, "o2sensor1"); put_csv_string(b, "o2sensor2"); put_csv_string(b, "o2setpoint"); put_csv_string(b, "scr_oc_po2"); put_csv_string(b, "mod"); put_csv_string(b, "ead"); put_csv_string(b, "end"); put_csv_string(b, "eadd"); put_csv_string(b, "velocity"); put_csv_string(b, "speed"); put_csv_string(b, "in_deco_calc"); put_csv_string(b, "ndl_calc"); put_csv_string(b, "tts_calc"); put_csv_string(b, "stoptime_calc"); put_csv_string(b, "stopdepth_calc"); put_csv_string(b, "pressure_time"); put_csv_string(b, "heartbeat"); put_csv_string(b, "bearing"); put_csv_string(b, "ambpressure"); put_csv_string(b, "gfline"); put_csv_string(b, "surface_gf"); put_csv_string(b, "density"); put_csv_string_with_nl(b, "icd_warning"); } static void put_st_event(struct membuffer *b, struct plot_data *entry, int offset, int length) { double value; int decimals; const char *unit; if (entry->sec < offset || entry->sec > offset + length) return; put_format(b, "Dialogue: 0,"); put_video_time(b, entry->sec - offset); put_video_time(b, (entry+1)->sec - offset < length ? (entry+1)->sec - offset : length); put_format(b, "Default,,0,0,0,,"); put_format(b, "%d:%02d ", FRACTION(entry->sec, 60)); value = get_depth_units(entry->depth, &decimals, &unit); put_format(b, "D=%02.2f %s ", value, unit); if (entry->temperature) { value = get_temp_units(entry->temperature, &unit); put_format(b, "T=%.1f%s ", value, unit); } // Only show NDL if it is not essentially infinite, show TTS for mandatory stops. if (entry->ndl_calc < 3600) { if (entry->ndl_calc > 0) put_format(b, "NDL=%d:%02d ", FRACTION(entry->ndl_calc, 60)); else if (entry->tts_calc > 0) put_format(b, "TTS=%d:%02d ", FRACTION(entry->tts_calc, 60)); } if (entry->surface_gf > 0.0) { put_format(b, "sGF=%.1f%% ", entry->surface_gf); } put_format(b, "\n"); } static void save_profiles_buffer(struct membuffer *b, bool select_only) { int i; struct dive *dive; struct plot_info pi; struct deco_state *planner_deco_state = NULL; init_plot_info(&pi); for_each_dive(i, dive) { if (select_only && !dive->selected) continue; create_plot_info_new(dive, &dive->dc, &pi, planner_deco_state); put_headers(b, pi.nr_cylinders); for (int i = 0; i < pi.nr; i++) put_pd(b, &pi, i); put_format(b, "\n"); free_plot_info_data(&pi); } } void save_subtitles_buffer(struct membuffer *b, struct dive *dive, int offset, int length) { struct plot_info pi; struct deco_state *planner_deco_state = NULL; init_plot_info(&pi); create_plot_info_new(dive, &dive->dc, &pi, planner_deco_state); put_format(b, "[Script Info]\n"); put_format(b, "; Script generated by Subsurface %s\n", subsurface_canonical_version()); put_format(b, "ScriptType: v4.00+\nPlayResX: 384\nPlayResY: 288\n\n"); put_format(b, "[V4+ Styles]\nFormat: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\n"); put_format(b, "Style: Default,Arial,12,&Hffffff,&Hffffff,&H0,&H0,0,0,0,0,100,100,0,0,1,1,0,7,10,10,10,0\n\n"); put_format(b, "[Events]\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n"); for (int i = 0; i < pi.nr; i++) { put_st_event(b, &pi.entry[i], offset, length); } put_format(b, "\n"); free_plot_info_data(&pi); } int save_profiledata(const char *filename, bool select_only) { struct membuffer buf = { 0 }; FILE *f; int error = 0; save_profiles_buffer(&buf, select_only); if (same_string(filename, "-")) { f = stdout; } else { error = -1; f = subsurface_fopen(filename, "w"); } if (f) { flush_buffer(&buf, f); error = fclose(f); } if (error) report_error("Save failed (%s)", strerror(errno)); free_buffer(&buf); return error; }
subsurface-for-dirk-master
core/save-profiledata.c
// SPDX-License-Identifier: GPL-2.0 /* statistics.c * * core logic for the Info & Stats page - * void calculate_stats_summary(struct stats_summary *out, bool selected_only); * void calculate_stats_selected(stats_t *stats_selection); */ #include "statistics.h" #include "dive.h" #include "event.h" #include "gettext.h" #include "sample.h" #include "subsurface-time.h" #include "trip.h" #include "units.h" #include <stdlib.h> #include <string.h> #include <ctype.h> static void process_temperatures(struct dive *dp, stats_t *stats) { temperature_t min_temp, mean_temp, max_temp = {.mkelvin = 0}; max_temp.mkelvin = dp->maxtemp.mkelvin; if (max_temp.mkelvin && (!stats->max_temp.mkelvin || max_temp.mkelvin > stats->max_temp.mkelvin)) stats->max_temp.mkelvin = max_temp.mkelvin; min_temp.mkelvin = dp->mintemp.mkelvin; if (min_temp.mkelvin && (!stats->min_temp.mkelvin || min_temp.mkelvin < stats->min_temp.mkelvin)) stats->min_temp.mkelvin = min_temp.mkelvin; if (min_temp.mkelvin || max_temp.mkelvin) { mean_temp.mkelvin = min_temp.mkelvin; if (mean_temp.mkelvin) mean_temp.mkelvin = (mean_temp.mkelvin + max_temp.mkelvin) / 2; else mean_temp.mkelvin = max_temp.mkelvin; stats->combined_temp.mkelvin += mean_temp.mkelvin; stats->combined_count++; } } static void process_dive(struct dive *dive, stats_t *stats) { int old_tadt, sac_time = 0; int32_t duration = dive->duration.seconds; old_tadt = stats->total_average_depth_time.seconds; stats->total_time.seconds += duration; if (duration > stats->longest_time.seconds) stats->longest_time.seconds = duration; if (stats->shortest_time.seconds == 0 || duration < stats->shortest_time.seconds) stats->shortest_time.seconds = duration; if (dive->maxdepth.mm > stats->max_depth.mm) stats->max_depth.mm = dive->maxdepth.mm; if (stats->min_depth.mm == 0 || dive->maxdepth.mm < stats->min_depth.mm) stats->min_depth.mm = dive->maxdepth.mm; stats->combined_max_depth.mm += dive->maxdepth.mm; process_temperatures(dive, stats); /* Maybe we should drop zero-duration dives */ if (!duration) return; if (dive->meandepth.mm) { stats->total_average_depth_time.seconds += duration; stats->avg_depth.mm = lrint((1.0 * old_tadt * stats->avg_depth.mm + duration * dive->meandepth.mm) / stats->total_average_depth_time.seconds); } if (dive->sac > 100) { /* less than .1 l/min is bogus, even with a pSCR */ sac_time = stats->total_sac_time.seconds + duration; stats->avg_sac.mliter = lrint((1.0 * stats->total_sac_time.seconds * stats->avg_sac.mliter + duration * dive->sac) / sac_time); if (dive->sac > stats->max_sac.mliter) stats->max_sac.mliter = dive->sac; if (stats->min_sac.mliter == 0 || dive->sac < stats->min_sac.mliter) stats->min_sac.mliter = dive->sac; stats->total_sac_time.seconds = sac_time; } } /* * Calculate a summary of the statistics and put in the stats_summary * structure provided in the first parameter. * Before first use, it should be initialized with init_stats_summary(). * After use, memory must be released with free_stats_summary(). */ void calculate_stats_summary(struct stats_summary *out, bool selected_only) { int idx; int t_idx, d_idx, r; struct dive *dp; struct tm tm; int current_year = 0; int current_month = 0; int year_iter = 0; int month_iter = 0; int prev_month = 0, prev_year = 0; int trip_iter = 0; dive_trip_t *trip_ptr = 0; size_t size, tsize, dsize, tmsize; stats_t stats = { 0 }; if (dive_table.nr > 0) { stats.shortest_time.seconds = dive_table.dives[0]->duration.seconds; stats.min_depth.mm = dive_table.dives[0]->maxdepth.mm; stats.selection_size = dive_table.nr; } /* allocate sufficient space to hold the worst * case (one dive per year or all dives during * one month) for yearly and monthly statistics*/ size = sizeof(stats_t) * (dive_table.nr + 1); tsize = sizeof(stats_t) * (NUM_DIVEMODE + 1); dsize = sizeof(stats_t) * ((STATS_MAX_DEPTH / STATS_DEPTH_BUCKET) + 1); tmsize = sizeof(stats_t) * ((STATS_MAX_TEMP / STATS_TEMP_BUCKET) + 1); free_stats_summary(out); out->stats_yearly = malloc(size); out->stats_monthly = malloc(size); out->stats_by_trip = malloc(size); out->stats_by_type = malloc(tsize); out->stats_by_depth = malloc(dsize); out->stats_by_temp = malloc(tmsize); if (!out->stats_yearly || !out->stats_monthly || !out->stats_by_trip || !out->stats_by_type || !out->stats_by_depth || !out->stats_by_temp) return; memset(out->stats_yearly, 0, size); memset(out->stats_monthly, 0, size); memset(out->stats_by_trip, 0, size); memset(out->stats_by_type, 0, tsize); memset(out->stats_by_depth, 0, dsize); memset(out->stats_by_temp, 0, tmsize); out->stats_yearly[0].is_year = true; /* Setting the is_trip to true to show the location as first * field in the statistics window */ out->stats_by_type[0].location = strdup(translate("gettextFromC", "All (by type stats)")); out->stats_by_type[0].is_trip = true; out->stats_by_type[1].location = strdup(translate("gettextFromC", divemode_text_ui[OC])); out->stats_by_type[1].is_trip = true; out->stats_by_type[2].location = strdup(translate("gettextFromC", divemode_text_ui[CCR])); out->stats_by_type[2].is_trip = true; out->stats_by_type[3].location = strdup(translate("gettextFromC", divemode_text_ui[PSCR])); out->stats_by_type[3].is_trip = true; out->stats_by_type[4].location = strdup(translate("gettextFromC", divemode_text_ui[FREEDIVE])); out->stats_by_type[4].is_trip = true; out->stats_by_depth[0].location = strdup(translate("gettextFromC", "All (by max depth stats)")); out->stats_by_depth[0].is_trip = true; out->stats_by_temp[0].location = strdup(translate("gettextFromC", "All (by min. temp stats)")); out->stats_by_temp[0].is_trip = true; /* this relies on the fact that the dives in the dive_table * are in chronological order */ for_each_dive (idx, dp) { if (selected_only && !dp->selected) continue; if (dp->invalid) continue; process_dive(dp, &stats); /* yearly statistics */ utc_mkdate(dp->when, &tm); if (current_year == 0) current_year = tm.tm_year; if (current_year != tm.tm_year) { current_year = tm.tm_year; process_dive(dp, &(out->stats_yearly[++year_iter])); out->stats_yearly[year_iter].is_year = true; } else { process_dive(dp, &(out->stats_yearly[year_iter])); } out->stats_yearly[year_iter].selection_size++; out->stats_yearly[year_iter].period = current_year; /* stats_by_type[0] is all the dives combined */ out->stats_by_type[0].selection_size++; process_dive(dp, &(out->stats_by_type[0])); process_dive(dp, &(out->stats_by_type[dp->dc.divemode + 1])); out->stats_by_type[dp->dc.divemode + 1].selection_size++; /* stats_by_depth[0] is all the dives combined */ out->stats_by_depth[0].selection_size++; process_dive(dp, &(out->stats_by_depth[0])); d_idx = dp->maxdepth.mm / (STATS_DEPTH_BUCKET * 1000); if (d_idx < 0) d_idx = 0; if (d_idx >= STATS_MAX_DEPTH / STATS_DEPTH_BUCKET) d_idx = STATS_MAX_DEPTH / STATS_DEPTH_BUCKET - 1; process_dive(dp, &(out->stats_by_depth[d_idx + 1])); out->stats_by_depth[d_idx + 1].selection_size++; /* stats_by_temp[0] is all the dives combined */ out->stats_by_temp[0].selection_size++; process_dive(dp, &(out->stats_by_temp[0])); t_idx = ((int)mkelvin_to_C(dp->mintemp.mkelvin)) / STATS_TEMP_BUCKET; if (t_idx < 0) t_idx = 0; if (t_idx >= STATS_MAX_TEMP / STATS_TEMP_BUCKET) t_idx = STATS_MAX_TEMP / STATS_TEMP_BUCKET - 1; process_dive(dp, &(out->stats_by_temp[t_idx + 1])); out->stats_by_temp[t_idx + 1].selection_size++; if (dp->divetrip != NULL) { if (trip_ptr != dp->divetrip) { trip_ptr = dp->divetrip; trip_iter++; } /* stats_by_trip[0] is all the dives combined */ out->stats_by_trip[0].selection_size++; process_dive(dp, &(out->stats_by_trip[0])); out->stats_by_trip[0].is_trip = true; out->stats_by_trip[0].location = strdup(translate("gettextFromC", "All (by trip stats)")); process_dive(dp, &(out->stats_by_trip[trip_iter])); out->stats_by_trip[trip_iter].selection_size++; out->stats_by_trip[trip_iter].is_trip = true; out->stats_by_trip[trip_iter].location = dp->divetrip->location; } /* monthly statistics */ if (current_month == 0) { current_month = tm.tm_mon + 1; } else { if (current_month != tm.tm_mon + 1) current_month = tm.tm_mon + 1; if (prev_month != current_month || prev_year != current_year) month_iter++; } process_dive(dp, &(out->stats_monthly[month_iter])); out->stats_monthly[month_iter].selection_size++; out->stats_monthly[month_iter].period = current_month; prev_month = current_month; prev_year = current_year; } /* add labels for depth ranges up to maximum depth seen */ if (out->stats_by_depth[0].selection_size) { d_idx = out->stats_by_depth[0].max_depth.mm; if (d_idx > STATS_MAX_DEPTH * 1000) d_idx = STATS_MAX_DEPTH * 1000; for (r = 0; r * (STATS_DEPTH_BUCKET * 1000) < d_idx; ++r) out->stats_by_depth[r+1].is_trip = true; } /* add labels for depth ranges up to maximum temperature seen */ if (out->stats_by_temp[0].selection_size) { t_idx = (int)mkelvin_to_C(out->stats_by_temp[0].max_temp.mkelvin); if (t_idx > STATS_MAX_TEMP) t_idx = STATS_MAX_TEMP; for (r = 0; r * STATS_TEMP_BUCKET < t_idx; ++r) out->stats_by_temp[r+1].is_trip = true; } } void free_stats_summary(struct stats_summary *stats) { free(stats->stats_yearly); free(stats->stats_monthly); free(stats->stats_by_trip); free(stats->stats_by_type); free(stats->stats_by_depth); free(stats->stats_by_temp); } void init_stats_summary(struct stats_summary *stats) { stats->stats_yearly = NULL; stats->stats_monthly = NULL; stats->stats_by_trip = NULL; stats->stats_by_type = NULL; stats->stats_by_depth = NULL; stats->stats_by_temp = NULL; } /* make sure we skip the selected summary entries */ void calculate_stats_selected(stats_t *stats_selection) { struct dive *dive; unsigned int i, nr; memset(stats_selection, 0, sizeof(*stats_selection)); nr = 0; for_each_dive(i, dive) { if (dive->selected && !dive->invalid) { process_dive(dive, stats_selection); nr++; } } stats_selection->selection_size = nr; } #define SOME_GAS 5000 // 5bar drop in cylinder pressure makes cylinder used bool has_gaschange_event(const struct dive *dive, const struct divecomputer *dc, int idx) { bool first_gas_explicit = false; const struct event *event = get_next_event(dc->events, "gaschange"); while (event) { if (dc->sample && (event->time.seconds == 0 || (dc->samples && dc->sample[0].time.seconds == event->time.seconds))) first_gas_explicit = true; if (get_cylinder_index(dive, event) == idx) return true; event = get_next_event(event->next, "gaschange"); } if (dc->divemode == CCR) { if (idx == get_cylinder_idx_by_use(dive, DILUENT)) return true; if (idx == get_cylinder_idx_by_use(dive, OXYGEN)) return true; } return !first_gas_explicit && idx == 0; } bool is_cylinder_used(const struct dive *dive, int idx) { const struct divecomputer *dc; cylinder_t *cyl; if (idx < 0 || idx >= dive->cylinders.nr) return false; cyl = get_cylinder(dive, idx); if ((cyl->start.mbar - cyl->end.mbar) > SOME_GAS) return true; if ((cyl->sample_start.mbar - cyl->sample_end.mbar) > SOME_GAS) return true; for_each_dc(dive, dc) { if (has_gaschange_event(dive, dc, idx)) return true; } return false; } bool is_cylinder_prot(const struct dive *dive, int idx) { const struct divecomputer *dc; if (idx < 0 || idx >= dive->cylinders.nr) return false; for_each_dc(dive, dc) { if (has_gaschange_event(dive, dc, idx)) return true; } return false; } /* Returns a dynamically allocated array with dive->cylinders.nr entries, * which has to be freed by the caller */ volume_t *get_gas_used(struct dive *dive) { int idx; volume_t *gases = malloc(dive->cylinders.nr * sizeof(volume_t)); for (idx = 0; idx < dive->cylinders.nr; idx++) { cylinder_t *cyl = get_cylinder(dive, idx); pressure_t start, end; start = cyl->start.mbar ? cyl->start : cyl->sample_start; end = cyl->end.mbar ? cyl->end : cyl->sample_end; if (end.mbar && start.mbar > end.mbar) gases[idx].mliter = gas_volume(cyl, start) - gas_volume(cyl, end); else gases[idx].mliter = 0; } return gases; } /* Quite crude reverse-blender-function, but it produces a approx result */ static void get_gas_parts(struct gasmix mix, volume_t vol, int o2_in_topup, volume_t *o2, volume_t *he) { volume_t air = {}; if (gasmix_is_air(mix)) { o2->mliter = 0; he->mliter = 0; return; } air.mliter = lrint(((double)vol.mliter * get_n2(mix)) / (1000 - o2_in_topup)); he->mliter = lrint(((double)vol.mliter * get_he(mix)) / 1000.0); o2->mliter += vol.mliter - he->mliter - air.mliter; } void selected_dives_gas_parts(volume_t *o2_tot, volume_t *he_tot) { int i, j; struct dive *d; for_each_dive (i, d) { if (!d->selected || d->invalid) continue; volume_t *diveGases = get_gas_used(d); for (j = 0; j < d->cylinders.nr; j++) { if (diveGases[j].mliter) { volume_t o2 = {}, he = {}; get_gas_parts(get_cylinder(d, j)->gasmix, diveGases[j], O2_IN_AIR, &o2, &he); o2_tot->mliter += o2.mliter; he_tot->mliter += he.mliter; } } free(diveGases); } }
subsurface-for-dirk-master
core/statistics.c
// SPDX-License-Identifier: GPL-2.0 #include "ssrf.h" #include <stdio.h> #include <ctype.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <git2.h> #include <libdivecomputer/parser.h> #include "gettext.h" #include "dive.h" #include "divesite.h" #include "event.h" #include "errorhelper.h" #include "sample.h" #include "subsurface-string.h" #include "trip.h" #include "device.h" #include "membuffer.h" #include "git-access.h" #include "picture.h" #include "qthelper.h" #include "tag.h" #include "subsurface-time.h" const char *saved_git_id = NULL; struct git_parser_state { git_repository *repo; struct divecomputer *active_dc; struct dive *active_dive; dive_trip_t *active_trip; char *fulltext_mode; char *fulltext_query; char *filter_constraint_type; char *filter_constraint_string_mode; char *filter_constraint_range_mode; bool filter_constraint_negate; char *filter_constraint_data; struct picture active_pic; struct dive_site *active_site; struct filter_preset *active_filter; struct dive_table *table; struct trip_table *trips; struct dive_site_table *sites; struct device_table *devices; struct filter_preset_table *filter_presets; int o2pressure_sensor; }; struct keyword_action { const char *keyword; void (*fn)(char *, struct membuffer *, struct git_parser_state *); }; static git_blob *git_tree_entry_blob(git_repository *repo, const git_tree_entry *entry); static temperature_t get_temperature(const char *line) { temperature_t t; t.mkelvin = C_to_mkelvin(ascii_strtod(line, NULL)); return t; } static depth_t get_depth(const char *line) { depth_t d; d.mm = lrint(1000 * ascii_strtod(line, NULL)); return d; } static volume_t get_volume(const char *line) { volume_t v; v.mliter = lrint(1000 * ascii_strtod(line, NULL)); return v; } static weight_t get_weight(const char *line) { weight_t w; w.grams = lrint(1000 * ascii_strtod(line, NULL)); return w; } static pressure_t get_airpressure(const char *line) { pressure_t p; p.mbar = lrint(ascii_strtod(line, NULL)); return p; } static pressure_t get_pressure(const char *line) { pressure_t p; p.mbar = lrint(1000 * ascii_strtod(line, NULL)); return p; } static int get_salinity(const char *line) { return lrint(10 * ascii_strtod(line, NULL)); } static fraction_t get_fraction(const char *line) { fraction_t f; f.permille = lrint(10 * ascii_strtod(line, NULL)); return f; } static void update_date(timestamp_t *when, const char *line) { unsigned yyyy, mm, dd; struct tm tm; if (sscanf(line, "%04u-%02u-%02u", &yyyy, &mm, &dd) != 3) return; utc_mkdate(*when, &tm); tm.tm_year = yyyy; tm.tm_mon = mm - 1; tm.tm_mday = dd; *when = utc_mktime(&tm); } static void update_time(timestamp_t *when, const char *line) { unsigned h, m, s = 0; struct tm tm; if (sscanf(line, "%02u:%02u:%02u", &h, &m, &s) < 2) return; utc_mkdate(*when, &tm); tm.tm_hour = h; tm.tm_min = m; tm.tm_sec = s; *when = utc_mktime(&tm); } static duration_t get_duration(const char *line) { int m = 0, s = 0; duration_t d; sscanf(line, "%d:%d", &m, &s); d.seconds = m * 60 + s; return d; } static enum divemode_t get_dctype(const char *line) { for (enum divemode_t i = 0; i < NUM_DIVEMODE; i++) { if (strcmp(line, divemode_text[i]) == 0) return i; } return 0; } static int get_index(const char *line) { return atoi(line); } static int get_hex(const char *line) { return strtoul(line, NULL, 16); } static void parse_dive_gps(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(str); location_t location; struct dive_site *ds = get_dive_site_for_dive(state->active_dive); parse_location(line, &location); if (!ds) { ds = get_dive_site_by_gps(&location, state->sites); if (!ds) ds = create_dive_site_with_gps("", &location, &dive_site_table); add_dive_to_dive_site(state->active_dive, ds); } else { if (dive_site_has_gps_location(ds) && !same_location(&ds->location, &location)) { char *coords = printGPSCoordsC(&location); // we have a dive site that already has GPS coordinates ds->notes = add_to_string(ds->notes, translate("gettextFromC", "multiple GPS locations for this dive site; also %s\n"), coords); free(coords); } ds->location = location; } } static void parse_dive_location(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(line); char *name = detach_cstring(str); struct dive_site *ds = get_dive_site_for_dive(state->active_dive); if (!ds) { ds = get_dive_site_by_name(name, &dive_site_table); if (!ds) ds = create_dive_site(name, &dive_site_table); add_dive_to_dive_site(state->active_dive, ds); } else { // we already had a dive site linked to the dive if (empty_string(ds->name)) { ds->name = strdup(name); } else { // and that dive site had a name. that's weird - if our name is different, add it to the notes if (!same_string(ds->name, name)) ds->notes = add_to_string(ds->notes, translate("gettextFromC", "additional name for site: %s\n"), name); } } free(name); } static void parse_dive_diveguide(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(line); state->active_dive->diveguide = detach_cstring(str); } static void parse_dive_buddy(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(line); state->active_dive->buddy = detach_cstring(str); } static void parse_dive_suit(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(line); state->active_dive->suit = detach_cstring(str); } static void parse_dive_notes(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(line); state->active_dive->notes = detach_cstring(str); } static void parse_dive_divesiteid(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(str); add_dive_to_dive_site(state->active_dive, get_dive_site_by_uuid(get_hex(line), &dive_site_table)); } /* * We can have multiple tags in the membuffer. They are separated by * NUL bytes. */ static void parse_dive_tags(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(line); const char *tag; int len = str->len; if (!len) return; /* Make sure there is a NUL at the end too */ tag = mb_cstring(str); for (;;) { int taglen = strlen(tag); if (taglen) taglist_add_tag(&state->active_dive->tag_list, tag); len -= taglen; if (!len) return; tag += taglen + 1; len--; } } static void parse_dive_airtemp(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(str); state->active_dive->airtemp = get_temperature(line); } static void parse_dive_watertemp(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(str); state->active_dive->watertemp = get_temperature(line); } static void parse_dive_airpressure(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(str); state->active_dive->surface_pressure = get_airpressure(line); } static void parse_dive_duration(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(str); state->active_dive->duration = get_duration(line); } static void parse_dive_rating(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(str); state->active_dive->rating = get_index(line); } static void parse_dive_visibility(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(str); state->active_dive->visibility = get_index(line); } static void parse_dive_wavesize(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(str); state->active_dive->wavesize = get_index(line); } static void parse_dive_current(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(str); state->active_dive->current = get_index(line); } static void parse_dive_surge(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(str); state->active_dive->surge = get_index(line); } static void parse_dive_chill(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(str); state->active_dive->chill = get_index(line); } static void parse_dive_watersalinity(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(str); state->active_dive->user_salinity = get_salinity(line); } static void parse_dive_notrip(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(str); UNUSED(line); state->active_dive->notrip = true; } static void parse_dive_invalid(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(str); UNUSED(line); state->active_dive->invalid = true; } static void parse_site_description(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(line); state->active_site->description = detach_cstring(str); } static void parse_site_name(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(line); state->active_site->name = detach_cstring(str); } static void parse_site_notes(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(line); state->active_site->notes = detach_cstring(str); } static void parse_site_gps(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(str); parse_location(line, &state->active_site->location); } static void parse_site_geo(char *line, struct membuffer *str, struct git_parser_state *state) { int origin; int category; sscanf(line, "cat %d origin %d \"", &category, &origin); taxonomy_set_category(&state->active_site->taxonomy , category, mb_cstring(str), origin); } static char *remove_from_front(struct membuffer *str, int len) { char *prefix; if (len >= str->len) return detach_cstring(str); /* memdup() - oh well */ prefix = malloc(len); if (!prefix) { report_error("git-load: out of memory"); return NULL; } memcpy(prefix, str->buffer, len); str->len -= len; memmove(str->buffer, str->buffer+len, str->len); return prefix; } static char *pop_cstring(struct membuffer *str, const char *err) { int len; if (!str) { report_error("git-load: string marker without any strings ('%s')", err); return strdup(""); } len = strlen(mb_cstring(str)) + 1; return remove_from_front(str, len); } /* Parse key=val parts of samples and cylinders etc */ static char *parse_keyvalue_entry(void (*fn)(void *, const char *, const char *), void *fndata, char *line, struct membuffer *str) { char *key = line, *val, c; while ((c = *line) != 0) { if (isspace(c) || c == '=') break; line++; } if (c == '=') *line++ = 0; val = line; /* Did we get a string? Take it from the list of strings */ if (*val == '"') val = pop_cstring(str, key); while ((c = *line) != 0) { if (isspace(c)) break; line++; } if (c) *line++ = 0; fn(fndata, key, val); return line; } static void parse_cylinder_keyvalue(void *_cylinder, const char *key, const char *value) { cylinder_t *cylinder = _cylinder; if (!strcmp(key, "vol")) { cylinder->type.size = get_volume(value); return; } if (!strcmp(key, "workpressure")) { cylinder->type.workingpressure = get_pressure(value); return; } if (!strcmp(key, "description")) { cylinder->type.description = value; return; } if (!strcmp(key, "o2")) { cylinder->gasmix.o2 = get_fraction(value); return; } if (!strcmp(key, "he")) { cylinder->gasmix.he = get_fraction(value); return; } if (!strcmp(key, "start")) { cylinder->start = get_pressure(value); return; } if (!strcmp(key, "end")) { cylinder->end = get_pressure(value); return; } if (!strcmp(key, "use")) { cylinder->cylinder_use = cylinderuse_from_text(value); return; } if (!strcmp(key, "depth")) { cylinder->depth = get_depth(value); return; } if ((*key == 'm') && strlen(value) == 0) { /* found a bogus key/value pair in the cylinder, consisting * of a lonely "m" or m<single quote> without value. This * is caused by commit 46004c39e26 and fixed in 48d9c8eb6eb0 and * b984fb98c38e4. See referenced commits for more info. * * Just ignore this key/value pair. No processing is broken * due to this, as the git storage stores only metric SI type data. * In fact, the m unit is superfluous anyway. */ return; } report_error("Unknown cylinder key/value pair (%s/%s)", key, value); } static void parse_dive_cylinder(char *line, struct membuffer *str, struct git_parser_state *state) { cylinder_t cylinder = empty_cylinder; for (;;) { char c; while (isspace(c = *line)) line++; if (!c) break; line = parse_keyvalue_entry(parse_cylinder_keyvalue, &cylinder, line, str); } if (cylinder.cylinder_use == OXYGEN) state->o2pressure_sensor = state->active_dive->cylinders.nr; add_cylinder(&state->active_dive->cylinders, state->active_dive->cylinders.nr, cylinder); } static void parse_weightsystem_keyvalue(void *_ws, const char *key, const char *value) { weightsystem_t *ws = _ws; if (!strcmp(key, "weight")) { ws->weight = get_weight(value); return; } if (!strcmp(key, "description")) { ws->description = value; return; } report_error("Unknown weightsystem key/value pair (%s/%s)", key, value); } static void parse_dive_weightsystem(char *line, struct membuffer *str, struct git_parser_state *state) { weightsystem_t ws = empty_weightsystem; for (;;) { char c; while (isspace(c = *line)) line++; if (!c) break; line = parse_keyvalue_entry(parse_weightsystem_keyvalue, &ws, line, str); } add_to_weightsystem_table(&state->active_dive->weightsystems, state->active_dive->weightsystems.nr, ws); } static int match_action(char *line, struct membuffer *str, void *data, struct keyword_action *action, unsigned nr_action) { char *p = line, c; unsigned low, high; while ((c = *p) >= 'a' && c <= 'z') // skip over 1st word p++; // Extract the second word from the line: if (p == line) return -1; switch (c) { case 0: // if 2nd word is C-terminated break; case ' ': // =end of 2nd word? *p++ = 0; // then C-terminate that word break; default: return -1; } /* Standard binary search in a table */ low = 0; high = nr_action; while (low < high) { unsigned mid = (low + high)/2; struct keyword_action *a = action + mid; int cmp = strcmp(line, a->keyword); if (!cmp) { // attribute found: a->fn(p, str, data); // Execute appropriate function, return 0; // .. passing 2n word from above } // (p) as a function argument. if (cmp < 0) high = mid; else low = mid + 1; } report_error("Unmatched action '%s'", line); return -1; } /* FIXME! We should do the array thing here too. */ static void parse_sample_keyvalue(void *_sample, const char *key, const char *value) { struct sample *sample = _sample; if (!strcmp(key, "sensor")) { sample->sensor[0] = atoi(value); return; } if (!strcmp(key, "ndl")) { sample->ndl = get_duration(value); return; } if (!strcmp(key, "tts")) { sample->tts = get_duration(value); return; } if (!strcmp(key, "in_deco")) { sample->in_deco = atoi(value); return; } if (!strcmp(key, "stoptime")) { sample->stoptime = get_duration(value); return; } if (!strcmp(key, "stopdepth")) { sample->stopdepth = get_depth(value); return; } if (!strcmp(key, "cns")) { sample->cns = atoi(value); return; } if (!strcmp(key, "rbt")) { sample->rbt = get_duration(value); return; } if (!strcmp(key, "po2")) { pressure_t p = get_pressure(value); sample->setpoint.mbar = p.mbar; return; } if (!strcmp(key, "sensor1")) { pressure_t p = get_pressure(value); sample->o2sensor[0].mbar = p.mbar; return; } if (!strcmp(key, "sensor2")) { pressure_t p = get_pressure(value); sample->o2sensor[1].mbar = p.mbar; return; } if (!strcmp(key, "sensor3")) { pressure_t p = get_pressure(value); sample->o2sensor[2].mbar = p.mbar; return; } if (!strcmp(key, "o2pressure")) { pressure_t p = get_pressure(value); sample->pressure[1].mbar = p.mbar; return; } if (!strcmp(key, "heartbeat")) { sample->heartbeat = atoi(value); return; } if (!strcmp(key, "bearing")) { sample->bearing.degrees = atoi(value); return; } report_error("Unexpected sample key/value pair (%s/%s)", key, value); } static char *parse_sample_unit(struct sample *sample, double val, char *unit) { unsigned int sensor; char *end = unit, c; /* Skip over the unit */ while ((c = *end) != 0) { if (isspace(c)) { *end++ = 0; break; } end++; } /* The units are "°C", "m" or "bar", so let's just look at the first character */ /* The cylinder pressure may also be of the form '123.0bar:4' to indicate sensor */ switch (*unit) { case 'm': sample->depth.mm = lrint(1000 * val); break; case 'b': sensor = sample->sensor[0]; if (end > unit + 4 && unit[3] == ':') sensor = atoi(unit + 4); add_sample_pressure(sample, sensor, lrint(1000 * val)); break; default: sample->temperature.mkelvin = C_to_mkelvin(val); break; } return end; } /* * If the given cylinder doesn't exist, return NO_SENSOR. */ static uint8_t sanitize_sensor_id(const struct dive *d, int nr) { return d && nr >= 0 && nr < d->cylinders.nr ? nr : NO_SENSOR; } /* * By default the sample data does not change unless the * save-file gives an explicit new value. So we copy the * data from the previous sample if one exists, and then * the parsing will update it as necessary. * * There are a few exceptions, like the sample pressure: * missing sample pressure doesn't mean "same as last * time", but "interpolate". We clear those ones * explicitly. * * NOTE! We default sensor use to 0, 1 respetively for * the two sensors, but for CCR dives with explicit * OXYGEN bottles we set the secondary sensor to that. * Then the primary sensor will be either the first * or the second cylinder depending on what isn't an * oxygen cylinder. */ static struct sample *new_sample(struct git_parser_state *state) { struct sample *sample = prepare_sample(state->active_dc); if (sample != state->active_dc->sample) { memcpy(sample, sample - 1, sizeof(struct sample)); sample->pressure[0].mbar = 0; sample->pressure[1].mbar = 0; } else { sample->sensor[0] = sanitize_sensor_id(state->active_dive, !state->o2pressure_sensor); sample->sensor[1] = sanitize_sensor_id(state->active_dive, state->o2pressure_sensor); } return sample; } static void sample_parser(char *line, struct git_parser_state *state) { int m, s = 0; struct sample *sample = new_sample(state); m = strtol(line, &line, 10); if (*line == ':') s = strtol(line + 1, &line, 10); sample->time.seconds = m * 60 + s; for (;;) { char c; while (isspace(c = *line)) line++; if (!c) break; /* Less common sample entries have a name */ if (c >= 'a' && c <= 'z') { line = parse_keyvalue_entry(parse_sample_keyvalue, sample, line, NULL); } else { const char *end; double val = ascii_strtod(line, &end); if (end == line) { report_error("Odd sample data: %s", line); break; } line = (char *)end; line = parse_sample_unit(sample, val, line); } } finish_sample(state->active_dc); } static void parse_dc_airtemp(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(str); state->active_dc->airtemp = get_temperature(line); } static void parse_dc_date(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(str); update_date(&state->active_dc->when, line); } static void parse_dc_deviceid(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(str); int id = get_hex(line); UNUSED(id); // legacy } static void parse_dc_diveid(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(str); state->active_dc->diveid = get_hex(line); } static void parse_dc_duration(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(str); state->active_dc->duration = get_duration(line); } static void parse_dc_dctype(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(str); state->active_dc->divemode = get_dctype(line); } static void parse_dc_lastmanualtime(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(str); state->active_dc->last_manual_time = get_duration(line); } static void parse_dc_maxdepth(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(str); state->active_dc->maxdepth = get_depth(line); } static void parse_dc_meandepth(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(str); state->active_dc->meandepth = get_depth(line); } static void parse_dc_model(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(line); state->active_dc->model = detach_cstring(str); } static void parse_dc_numberofoxygensensors(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(str); state->active_dc->no_o2sensors = get_index(line); } static void parse_dc_surfacepressure(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(str); state->active_dc->surface_pressure = get_pressure(line); } static void parse_dc_salinity(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(str); state->active_dc->salinity = get_salinity(line); } static void parse_dc_surfacetime(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(str); state->active_dc->surfacetime = get_duration(line); } static void parse_dc_time(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(str); update_time(&state->active_dc->when, line); } static void parse_dc_watertemp(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(str); state->active_dc->watertemp = get_temperature(line); } static int get_divemode(const char *divemodestring) { for (int i = 0; i < NUM_DIVEMODE; i++) { if (!strcmp(divemodestring, divemode_text[i])) return i; } return 0; } /* * A 'struct event' has a variable-sized name allocation at the * end. So when we parse the event data, we can't fill in the * event directly, because we don't know how to allocate one * before we have the size of the name. * * Thus this initial 'parse_event' with a separate name pointer. */ struct parse_event { const char *name; int has_divemode; struct event ev; }; static void parse_event_keyvalue(void *_parse, const char *key, const char *value) { struct parse_event *parse = _parse; int val = atoi(value); if (!strcmp(key, "type")) { parse->ev.type = val; } else if (!strcmp(key, "flags")) { parse->ev.flags = val; } else if (!strcmp(key, "value")) { parse->ev.value = val; } else if (!strcmp(key, "name")) { parse->name = value; } else if (!strcmp(key,"divemode")) { parse->ev.value = get_divemode(value); parse->has_divemode = 1; } else if (!strcmp(key, "cylinder")) { /* NOTE! We add one here as a marker that "yes, we got a cylinder index" */ parse->ev.gas.index = 1 + get_index(value); } else if (!strcmp(key, "o2")) { parse->ev.gas.mix.o2 = get_fraction(value); } else if (!strcmp(key, "he")) { parse->ev.gas.mix.he = get_fraction(value); } else report_error("Unexpected event key/value pair (%s/%s)", key, value); } /* keyvalue "key" "value" * so we have two strings (possibly empty) in the membuffer, separated by a '\0' */ static void parse_dc_keyvalue(char *line, struct membuffer *str, struct git_parser_state *state) { const char *key, *value; // Let's make sure we have two strings... int string_counter = 0; while(*line) { if (*line == '"') string_counter++; line++; } if (string_counter != 2) return; // stupidly the second string in the membuffer isn't NUL terminated; // asking for a cstring fixes that; interestingly enough, given that there are two // strings in the mb, the next command at the same time assigns a pointer to the // first string to 'key' and NUL terminates the second string (which then goes to 'value') key = mb_cstring(str); value = key + strlen(key) + 1; add_extra_data(state->active_dc, key, value); } static void parse_dc_event(char *line, struct membuffer *str, struct git_parser_state *state) { int m, s = 0; struct parse_event p = { NULL, }; struct event *ev; m = strtol(line, &line, 10); if (*line == ':') s = strtol(line + 1, &line, 10); p.ev.time.seconds = m * 60 + s; for (;;) { char c; while (isspace(c = *line)) line++; if (!c) break; line = parse_keyvalue_entry(parse_event_keyvalue, &p, line, str); } /* Only modechange events should have a divemode - fix up any corrupted names */ if (p.has_divemode && strcmp(p.name, "modechange")) p.name = "modechange"; ev = add_event(state->active_dc, p.ev.time.seconds, p.ev.type, p.ev.flags, p.ev.value, p.name); /* * Older logs might mark the dive to be CCR by having an "SP change" event at time 0:00. * Better to mark them being CCR on import so no need for special treatments elsewhere on * the code. */ if (ev && p.ev.time.seconds == 0 && p.ev.type == SAMPLE_EVENT_PO2 && p.ev.value && state->active_dc->divemode==OC) state->active_dc->divemode = CCR; if (ev && event_is_gaschange(ev)) { /* * We subtract one here because "0" is "no index", * and the parsing will add one for actual cylinder * index data (see parse_event_keyvalue) */ ev->gas.index = p.ev.gas.index-1; if (p.ev.gas.mix.o2.permille || p.ev.gas.mix.he.permille) ev->gas.mix = p.ev.gas.mix; } } /* Not needed anymore - trip date calculated implicitly from first dive */ static void parse_trip_date(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(line); UNUSED(str); UNUSED(state); } /* Not needed anymore - trip date calculated implicitly from first dive */ static void parse_trip_time(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(line); UNUSED(str); UNUSED(state); } static void parse_trip_location(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(line); state->active_trip->location = detach_cstring(str); } static void parse_trip_notes(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(line); state->active_trip->notes = detach_cstring(str); } static void parse_settings_autogroup(char *line, struct membuffer *str, struct git_parser_state *_unused) { UNUSED(line); UNUSED(str); UNUSED(_unused); set_autogroup(true); } static void parse_settings_units(char *line, struct membuffer *str, struct git_parser_state *unused) { UNUSED(str); UNUSED(unused); if (line) set_informational_units(line); } static void parse_settings_userid(char *line, struct membuffer *str, struct git_parser_state *_unused) /* Keep this despite removal of the webservice as there are legacy logbook around * that still have this defined. */ { UNUSED(str); UNUSED(_unused); UNUSED(line); } static void parse_settings_prefs(char *line, struct membuffer *str, struct git_parser_state *unused) { UNUSED(str); UNUSED(unused); if (line) set_git_prefs(line); } /* * Our versioning is a joke right now, but this is more of an example of what we * *can* do some day. And if we do change the version, this warning will show if * you read with a version of subsurface that doesn't know about it. * We MUST keep this in sync with the XML version (so we can report a consistent * minimum datafile version) */ static void parse_settings_version(char *line, struct membuffer *str, struct git_parser_state *_unused) { UNUSED(str); UNUSED(_unused); int version = atoi(line); report_datafile_version(version); if (version > DATAFORMAT_VERSION) report_error("Git save file version %d is newer than version %d I know about", version, DATAFORMAT_VERSION); } /* The string in the membuffer is the version string of subsurface that saved things, just FYI */ static void parse_settings_subsurface(char *line, struct membuffer *str, struct git_parser_state *_unused) { UNUSED(line); UNUSED(str); UNUSED(_unused); } struct divecomputerid { const char *model; const char *nickname; const char *firmware; const char *serial; unsigned int deviceid; }; static void parse_divecomputerid_keyvalue(void *_cid, const char *key, const char *value) { struct divecomputerid *cid = _cid; // Ignored legacy fields if (!strcmp(key, "firmware")) return; if (!strcmp(key, "deviceid")) return; // Serial number and nickname matter if (!strcmp(key, "serial")) { cid->serial = value; cid->deviceid = calculate_string_hash(value); return; } if (!strcmp(key, "nickname")) { cid->nickname = value; return; } report_error("Unknown divecomputerid key/value pair (%s/%s)", key, value); } /* * The 'divecomputerid' is a bit harder to parse than some other things, because * it can have multiple strings (but see the tag parsing for another example of * that) in addition to the non-string entries. */ static void parse_settings_divecomputerid(char *line, struct membuffer *str, struct git_parser_state *state) { struct divecomputerid id = { pop_cstring(str, line) }; /* Skip the '"' that stood for the model string */ line++; /* Parse the rest of the entries */ for (;;) { char c; while (isspace(c = *line)) line++; if (!c) break; line = parse_keyvalue_entry(parse_divecomputerid_keyvalue, &id, line, str); } create_device_node(state->devices, id.model, id.serial, id.nickname); } struct fingerprint_helper { uint32_t model; uint32_t serial; uint32_t fdeviceid; uint32_t fdiveid; const char *hex_data; }; static void parse_fingerprint_keyvalue(void *_fph, const char *key, const char *value) { struct fingerprint_helper *fph = _fph; if (!strcmp(key, "model")) { fph->model = get_hex(value); return; } if (!strcmp(key, "serial")) { fph->serial = get_hex(value); return; } if (!strcmp(key, "deviceid")) { fph->fdeviceid = get_hex(value); return; } if (!strcmp(key, "diveid")) { fph->fdiveid = get_hex(value); return; } if (!strcmp(key, "data")) { fph->hex_data = value; return; } report_error("Unknown fingerprint key/value pair (%s/%s)", key, value); } static void parse_settings_fingerprint(char *line, struct membuffer *str, struct git_parser_state *state) { struct fingerprint_helper fph = { 0, 0, 0, 0 }; for (;;) { char c; while (isspace(c = *line)) line++; if (!c) break; line = parse_keyvalue_entry(parse_fingerprint_keyvalue, &fph, line, str); } if (verbose > 1) SSRF_INFO("fingerprint %08x %08x %08x %08x %s\n", fph.model, fph.serial, fph.fdeviceid, fph.fdiveid, fph.hex_data); create_fingerprint_node_from_hex(&fingerprint_table, fph.model, fph.serial, fph.hex_data, fph.fdeviceid, fph.fdiveid); } static void parse_picture_filename(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(line); state->active_pic.filename = detach_cstring(str); } static void parse_picture_gps(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(str); parse_location(line, &state->active_pic.location); } static void parse_picture_hash(char *line, struct membuffer *str, struct git_parser_state *state) { // we no longer use hashes to identify pictures, but we shouldn't // remove this parser lest users get an ugly red warning when // opening old git repos UNUSED(line); UNUSED(state); UNUSED(str); } /* These need to be sorted! */ struct keyword_action dc_action[] = { #undef D #define D(x) { #x, parse_dc_ ## x } D(airtemp), D(date), D(dctype), D(deviceid), D(diveid), D(duration), D(event), D(keyvalue), D(lastmanualtime), D(maxdepth), D(meandepth), D(model), D(numberofoxygensensors), D(salinity), D(surfacepressure), D(surfacetime), D(time), D(watertemp) }; /* Sample lines start with a space or a number */ static void divecomputer_parser(char *line, struct membuffer *str, struct git_parser_state *state) { char c = *line; if (c < 'a' || c > 'z') sample_parser(line, state); match_action(line, str, state, dc_action, ARRAY_SIZE(dc_action)); } /* These need to be sorted! */ struct keyword_action dive_action[] = { #undef D #define D(x) { #x, parse_dive_ ## x } /* For historical reasons, we accept divemaster and diveguide */ D(airpressure), D(airtemp), D(buddy), D(chill), D(current), D(cylinder), D(diveguide), { "divemaster", parse_dive_diveguide }, D(divesiteid), D(duration), D(gps), D(invalid), D(location), D(notes), D(notrip), D(rating), D(suit), D(surge), D(tags), D(visibility), D(watersalinity), D(watertemp), D(wavesize), D(weightsystem) }; static void dive_parser(char *line, struct membuffer *str, struct git_parser_state *state) { match_action(line, str, state, dive_action, ARRAY_SIZE(dive_action)); } /* These need to be sorted! */ struct keyword_action site_action[] = { #undef D #define D(x) { #x, parse_site_ ## x } D(description), D(geo), D(gps), D(name), D(notes) }; static void site_parser(char *line, struct membuffer *str, struct git_parser_state *state) { match_action(line, str, state, site_action, ARRAY_SIZE(site_action)); } /* These need to be sorted! */ struct keyword_action trip_action[] = { #undef D #define D(x) { #x, parse_trip_ ## x } D(date), D(location), D(notes), D(time), }; static void trip_parser(char *line, struct membuffer *str, struct git_parser_state *state) { match_action(line, str, state, trip_action, ARRAY_SIZE(trip_action)); } /* These need to be sorted! */ static struct keyword_action settings_action[] = { #undef D #define D(x) { #x, parse_settings_ ## x } D(autogroup), D(divecomputerid), D(fingerprint), D(prefs), D(subsurface), D(units), D(userid), D(version) }; static void settings_parser(char *line, struct membuffer *str, struct git_parser_state *state) { match_action(line, str, state, settings_action, ARRAY_SIZE(settings_action)); } /* These need to be sorted! */ static struct keyword_action picture_action[] = { #undef D #define D(x) { #x, parse_picture_ ## x } D(filename), D(gps), D(hash) }; static void picture_parser(char *line, struct membuffer *str, struct git_parser_state *state) { match_action(line, str, state, picture_action, ARRAY_SIZE(picture_action)); } static void parse_filter_preset_constraint_keyvalue(void *_state, const char *key, const char *value) { struct git_parser_state *state = _state; if (!strcmp(key, "type")) { free(state->filter_constraint_type); state->filter_constraint_type = strdup(value); return; } if (!strcmp(key, "rangemode")) { free(state->filter_constraint_range_mode); state->filter_constraint_range_mode = strdup(value); return; } if (!strcmp(key, "stringmode")) { free(state->filter_constraint_string_mode); state->filter_constraint_string_mode = strdup(value); return; } if (!strcmp(key, "negate")) { state->filter_constraint_negate = true; return; } if (!strcmp(key, "data")) { free(state->filter_constraint_data); state->filter_constraint_data = strdup(value); return; } report_error("Unknown filter preset constraint key/value pair (%s/%s)", key, value); } static void parse_filter_preset_constraint(char *line, struct membuffer *str, struct git_parser_state *state) { for (;;) { char c; while (isspace(c = *line)) line++; if (!c) break; line = parse_keyvalue_entry(parse_filter_preset_constraint_keyvalue, state, line, str); } filter_preset_add_constraint(state->active_filter, state->filter_constraint_type, state->filter_constraint_string_mode, state->filter_constraint_range_mode, state->filter_constraint_negate, state->filter_constraint_data); free(state->filter_constraint_type); free(state->filter_constraint_string_mode); free(state->filter_constraint_range_mode); free(state->filter_constraint_data); state->filter_constraint_type = NULL; state->filter_constraint_string_mode = NULL; state->filter_constraint_range_mode = NULL; state->filter_constraint_negate = false; state->filter_constraint_data = NULL; } static void parse_filter_preset_fulltext_keyvalue(void *_state, const char *key, const char *value) { struct git_parser_state *state = _state; if (!strcmp(key, "mode")) { free(state->fulltext_mode); state->fulltext_mode = strdup(value); return; } if (!strcmp(key, "query")) { free(state->fulltext_query); state->fulltext_query = strdup(value); return; } report_error("Unknown filter preset fulltext key/value pair (%s/%s)", key, value); } static void parse_filter_preset_fulltext(char *line, struct membuffer *str, struct git_parser_state *state) { for (;;) { char c; while (isspace(c = *line)) line++; if (!c) break; line = parse_keyvalue_entry(parse_filter_preset_fulltext_keyvalue, state, line, str); } filter_preset_set_fulltext(state->active_filter, state->fulltext_query, state->fulltext_mode); free(state->fulltext_mode); free(state->fulltext_query); state->fulltext_mode = NULL; state->fulltext_query = NULL; } static void parse_filter_preset_name(char *line, struct membuffer *str, struct git_parser_state *state) { UNUSED(line); filter_preset_set_name(state->active_filter, detach_cstring(str)); } /* These need to be sorted! */ struct keyword_action filter_preset_action[] = { #undef D #define D(x) { #x, parse_filter_preset_ ## x } D(constraint), D(fulltext), D(name) }; static void filter_preset_parser(char *line, struct membuffer *str, struct git_parser_state *state) { match_action(line, str, state, filter_preset_action, ARRAY_SIZE(filter_preset_action)); } /* * We have a very simple line-based interface, with the small * complication that lines can have strings in the middle, and * a string can be multiple lines. * * The UTF-8 string escaping is *very* simple, though: * * - a string starts and ends with double quotes (") * * - inside the string we escape: * (a) double quotes with '\"' * (b) backslash (\) with '\\' * * - additionally, for human readability, we escape * newlines with '\n\t', with the exception that * consecutive newlines are left unescaped (so an * empty line doesn't become a line with just a tab * on it). * * Also, while the UTF-8 string can have arbitrarily * long lines, the non-string parts of the lines are * never long, so we can use a small temporary buffer * on stack for that part. * * Also, note that if a line has one or more strings * in it: * * - each string will be represented as a single '"' * character in the output. * * - all string will exist in the same 'membuffer', * separated by NUL characters (that cannot exist * in a string, not even quoted). */ static const char *parse_one_string(const char *buf, const char *end, struct membuffer *b) { const char *p = buf; /* * We turn multiple strings one one line (think dive tags) into one * membuffer that has NUL characters in between strings. */ if (b->len) put_bytes(b, "", 1); while (p < end) { char replace; switch (*p++) { default: continue; case '\n': if (p < end && *p == '\t') { replace = '\n'; break; } continue; case '\\': if (p < end) { replace = *p; break; } continue; case '"': replace = 0; break; } put_bytes(b, buf, p - buf - 1); if (!replace) break; put_bytes(b, &replace, 1); buf = ++p; } return p; } typedef void (line_fn_t)(char *, struct membuffer *, struct git_parser_state *); #define MAXLINE 500 static unsigned parse_one_line(const char *buf, unsigned size, line_fn_t *fn, struct git_parser_state *state, struct membuffer *b) { const char *end = buf + size; const char *p = buf; char line[MAXLINE + 1]; int off = 0; // Check the first character of a line: an empty line // or a line starting with a TAB is invalid, and likely // due to an early string end quote due to a merge // conflict. Ignore such a line. switch (*p) { case '\n': case '\t': do { if (*p++ == '\n') break; } while (p < end); SSRF_INFO("git storage: Ignoring line '%.*s'", (int)(p-buf-1), buf); return p - buf; default: break; } while (p < end) { char c = *p++; if (c == '\n') break; line[off] = c; off++; if (off > MAXLINE) off = MAXLINE; if (c == '"') p = parse_one_string(p, end, b); } line[off] = 0; fn(line, b, state); return p - buf; } /* * We keep on re-using the membuffer that we use for * strings, but the callback function can "steal" it by * saving its value and just clear the original. */ static void for_each_line(git_blob *blob, line_fn_t *fn, struct git_parser_state *state) { const char *content = git_blob_rawcontent(blob); unsigned int size = git_blob_rawsize(blob); struct membuffer str = { 0 }; while (size) { unsigned int n = parse_one_line(content, size, fn, state, &str); content += n; size -= n; /* Re-use the allocation, but forget the data */ str.len = 0; } free_buffer(&str); } #define GIT_WALK_OK 0 #define GIT_WALK_SKIP 1 static void finish_active_trip(struct git_parser_state *state) { dive_trip_t *trip = state->active_trip; if (trip) { state->active_trip = NULL; insert_trip(trip, state->trips); } } static void finish_active_dive(struct git_parser_state *state) { struct dive *dive = state->active_dive; if (dive) { state->active_dive = NULL; record_dive_to_table(dive, state->table); } } static void create_new_dive(timestamp_t when, struct git_parser_state *state) { state->active_dive = alloc_dive(); /* We'll fill in more data from the dive file */ state->active_dive->when = when; if (state->active_trip) add_dive_to_trip(state->active_dive, state->active_trip); } static bool validate_date(int yyyy, int mm, int dd) { return yyyy > 1930 && yyyy < 3000 && mm > 0 && mm < 13 && dd > 0 && dd < 32; } static bool validate_time(int h, int m, int s) { return h >= 0 && h < 24 && m >= 0 && m < 60 && s >=0 && s <= 60; } /* * Dive trip directory, name is 'nn-alphabetic[~hex]' */ static int dive_trip_directory(const char *root, const char *name, struct git_parser_state *state) { int yyyy = -1, mm = -1, dd = -1; if (sscanf(root, "%d/%d", &yyyy, &mm) != 2) return GIT_WALK_SKIP; dd = atoi(name); if (!validate_date(yyyy, mm, dd)) return GIT_WALK_SKIP; finish_active_trip(state); state->active_trip = alloc_trip(); return GIT_WALK_OK; } /* * Dive directory, name is [[yyyy-]mm-]nn-ddd-hh:mm:ss[~hex] in older git repositories * but [[yyyy-]mm-]nn-ddd-hh=mm=ss[~hex] in newer repos as ':' is an illegal character for Windows files * and 'timeoff' points to what should be the time part of * the name (the first digit of the hour). * * The root path will be of the form yyyy/mm[/tripdir], */ static int dive_directory(const char *root, const git_tree_entry *entry, const char *name, int timeoff, struct git_parser_state *state) { int yyyy = -1, mm = -1, dd = -1; int h, m, s; int mday_off, month_off, year_off; struct tm tm; /* Skip the '-' before the time */ mday_off = timeoff; if (!mday_off || name[--mday_off] != '-') return GIT_WALK_SKIP; /* Skip the day name */ while (mday_off > 0 && name[--mday_off] != '-') /* nothing */; mday_off = mday_off - 2; month_off = mday_off - 3; year_off = month_off - 5; if (mday_off < 0) return GIT_WALK_SKIP; /* Get the time of day -- parse both time formats so we can read old repos when not on Windows */ if (sscanf(name + timeoff, "%d:%d:%d", &h, &m, &s) != 3 && sscanf(name + timeoff, "%d=%d=%d", &h, &m, &s) != 3) return GIT_WALK_SKIP; if (!validate_time(h, m, s)) return GIT_WALK_SKIP; /* * Using the "git_tree_walk()" interface is simple, but * it kind of sucks as an interface because there is * no sane way to pass the hierarchy to the callbacks. * The "payload" is a fixed one-time thing: we'd like * the "current trip" to be passed down to the dives * that get parsed under that trip, but we can't. * * So "active_trip" is not the trip that is in the hierarchy * _above_ us, it's just the trip that was _before_ us. But * if a dive is not in a trip at all, we can't tell. * * We could just do a better walker that passes the * return value around, but we hack around this by * instead looking at the one hierarchical piece of * data we have: the pathname to the current entry. * * This is pretty hacky. The magic '8' is the length * of a pathname of the form 'yyyy/mm/'. */ if (strlen(root) == 8) finish_active_trip(state); /* * Get the date. The day of the month is in the dive directory * name, the year and month might be in the path leading up * to it. */ dd = atoi(name + mday_off); if (year_off < 0) { if (sscanf(root, "%d/%d", &yyyy, &mm) != 2) return GIT_WALK_SKIP; } else yyyy = atoi(name + year_off); if (month_off >= 0) mm = atoi(name + month_off); if (!validate_date(yyyy, mm, dd)) return GIT_WALK_SKIP; /* Ok, close enough. We've gotten sufficient information */ memset(&tm, 0, sizeof(tm)); tm.tm_hour = h; tm.tm_min = m; tm.tm_sec = s; tm.tm_year = yyyy; tm.tm_mon = mm-1; tm.tm_mday = dd; finish_active_dive(state); create_new_dive(utc_mktime(&tm), state); memcpy(state->active_dive->git_id, git_tree_entry_id(entry)->id, 20); return GIT_WALK_OK; } static int picture_directory(const char *root, const char *name, struct git_parser_state *state) { UNUSED(root); UNUSED(name); if (!state->active_dive) return GIT_WALK_SKIP; return GIT_WALK_OK; } /* * Return the length of the string without the unique part. */ static int nonunique_length(const char *str) { int len = 0; for (;;) { char c = *str++; if (!c || c == '~') return len; len++; } } /* * When hitting a directory node, we have a couple of cases: * * - It's just a date entry - all numeric (either year or month): * * [yyyy|mm] * * We don't do anything with these, we just traverse into them. * The numeric data will show up as part of the full path when * we hit more interesting entries. * * - It's a trip directory. The name will be of the form * * nn-alphabetic[~hex] * * where 'nn' is the day of the month (year and month will be * encoded in the path leading up to this). * * - It's a dive directory. The name will be of the form * * [[yyyy-]mm-]nn-ddd-hh=mm=ss[~hex] * * (older versions had this as [[yyyy-]mm-]nn-ddd-hh:mm:ss[~hex] * but that faile on Windows) * * which describes the date and time of a dive (yyyy and mm * are optional, and may be encoded in the path leading up to * the dive). * * - It is a per-dive picture directory ("Pictures") * * - It's some random non-dive-data directory. * * If it doesn't match the above patterns, we'll ignore them * for dive loading purposes, and not even recurse into them. */ static int walk_tree_directory(const char *root, const git_tree_entry *entry, struct git_parser_state *state) { const char *name = git_tree_entry_name(entry); int digits = 0, len; char c; if (!strcmp(name, "Pictures")) return picture_directory(root, name, state); if (!strcmp(name, "01-Divesites")) return GIT_WALK_OK; if (!strcmp(name, "02-Filterpresets")) return GIT_WALK_OK; while (isdigit(c = name[digits])) digits++; /* Doesn't start with two or four digits? Skip */ if (digits != 4 && digits != 2) return GIT_WALK_SKIP; /* Only digits? Do nothing, but recurse into it */ if (!c) return GIT_WALK_OK; /* All valid cases need to have a slash following */ if (c != '-') return GIT_WALK_SKIP; /* Do a quick check for a common dive case */ len = nonunique_length(name); /* * We know the len is at least 3, because we had at least * two digits and a dash */ if (name[len-3] == ':' || name[len-3] == '=') return dive_directory(root, entry, name, len-8, state); if (digits != 2) return GIT_WALK_SKIP; return dive_trip_directory(root, name, state); } static git_blob *git_tree_entry_blob(git_repository *repo, const git_tree_entry *entry) { const git_oid *id = git_tree_entry_id(entry); git_blob *blob; if (git_blob_lookup(&blob, repo, id)) return NULL; return blob; } static struct divecomputer *create_new_dc(struct dive *dive) { struct divecomputer *dc = &dive->dc; while (dc->next) dc = dc->next; /* Did we already fill that in? */ if (dc->samples || dc->model || dc->when) { struct divecomputer *newdc = calloc(1, sizeof(*newdc)); if (!newdc) return NULL; dc->next = newdc; dc = newdc; } dc->when = dive->when; dc->duration = dive->duration; return dc; } /* * We should *really* try to delay the dive computer data parsing * until necessary, in order to reduce load-time. The parsing is * cheap, but the loading of the git blob into memory can be pretty * costly. */ static int parse_divecomputer_entry(struct git_parser_state *state, const git_tree_entry *entry, const char *suffix) { UNUSED(suffix); git_blob *blob = git_tree_entry_blob(state->repo, entry); if (!blob) return report_error("Unable to read divecomputer file"); state->active_dc = create_new_dc(state->active_dive); for_each_line(blob, divecomputer_parser, state); git_blob_free(blob); state->active_dc = NULL; return 0; } /* * NOTE! The "git_id" for the dive is the hash for the whole dive directory. * As such, it covers not just the dive, but the divecomputers and the * pictures too. So if any of the dive computers change, the dive cache * has to be invalidated too. */ static int parse_dive_entry(struct git_parser_state *state, const git_tree_entry *entry, const char *suffix) { struct dive *dive = state->active_dive; git_blob *blob = git_tree_entry_blob(state->repo, entry); if (!blob) return report_error("Unable to read dive file"); if (*suffix) dive->number = atoi(suffix + 1); clear_weightsystem_table(&state->active_dive->weightsystems); state->o2pressure_sensor = 1; for_each_line(blob, dive_parser, state); git_blob_free(blob); return 0; } static int parse_site_entry(struct git_parser_state *state, const git_tree_entry *entry, const char *suffix) { if (*suffix == '\0') return report_error("Dive site without uuid"); uint32_t uuid = strtoul(suffix, NULL, 16); state->active_site = alloc_or_get_dive_site(uuid, &dive_site_table); git_blob *blob = git_tree_entry_blob(state->repo, entry); if (!blob) return report_error("Unable to read dive site file"); for_each_line(blob, site_parser, state); state->active_site = NULL; git_blob_free(blob); return 0; } static int parse_trip_entry(struct git_parser_state *state, const git_tree_entry *entry) { git_blob *blob = git_tree_entry_blob(state->repo, entry); if (!blob) return report_error("Unable to read trip file"); for_each_line(blob, trip_parser, state); git_blob_free(blob); return 0; } static int parse_settings_entry(struct git_parser_state *state, const git_tree_entry *entry) { git_blob *blob = git_tree_entry_blob(state->repo, entry); if (!blob) return report_error("Unable to read settings file"); for_each_line(blob, settings_parser, state); git_blob_free(blob); return 0; } static int parse_picture_entry(struct git_parser_state *state, const git_tree_entry *entry, const char *name) { git_blob *blob; int hh, mm, ss, offset; char sign; /* * The format of the picture name files is just the offset within * the dive in form [[+-]hh=mm=ss (previously [[+-]hh:mm:ss, but * that didn't work on Windows), possibly followed by a hash to * make the filename unique (which we can just ignore). */ if (sscanf(name, "%c%d:%d:%d", &sign, &hh, &mm, &ss) != 4 && sscanf(name, "%c%d=%d=%d", &sign, &hh, &mm, &ss) != 4) return report_error("Unknown file name %s", name); offset = ss + 60 * (mm + 60 * hh); if (sign == '-') offset = -offset; blob = git_tree_entry_blob(state->repo, entry); if (!blob) return report_error("Unable to read picture file"); state->active_pic.offset.seconds = offset; for_each_line(blob, picture_parser, state); add_picture(&state->active_dive->pictures, state->active_pic); git_blob_free(blob); /* add_picture took ownership of the data - * clear out our copy just to be sure. */ state->active_pic = empty_picture; return 0; } static int parse_filter_preset(struct git_parser_state *state, const git_tree_entry *entry) { git_blob *blob = git_tree_entry_blob(state->repo, entry); if (!blob) return report_error("Unable to read filter preset file"); state->active_filter = alloc_filter_preset(); for_each_line(blob, filter_preset_parser, state); git_blob_free(blob); add_filter_preset_to_table(state->active_filter, state->filter_presets); free_filter_preset(state->active_filter); state->active_filter = NULL; return 0; } static int walk_tree_file(const char *root, const git_tree_entry *entry, struct git_parser_state *state) { struct dive *dive = state->active_dive; dive_trip_t *trip = state->active_trip; const char *name = git_tree_entry_name(entry); if (verbose > 1) SSRF_INFO("git load handling file %s\n", name); switch (*name) { case '-': case '+': if (dive) return parse_picture_entry(state, entry, name); break; case 'D': if (dive && !strncmp(name, "Divecomputer", 12)) return parse_divecomputer_entry(state, entry, name + 12); if (dive && !strncmp(name, "Dive", 4)) return parse_dive_entry(state, entry, name + 4); break; case 'P': if (!strncmp(name, "Preset-", 7)) return parse_filter_preset(state, entry); break; case 'S': if (!strncmp(name, "Site", 4)) return parse_site_entry(state, entry, name + 5); break; case '0': if (trip && !strcmp(name, "00-Trip")) return parse_trip_entry(state, entry); if (!strcmp(name, "00-Subsurface")) return parse_settings_entry(state, entry); break; } report_error("Unknown file %s%s (%p %p)", root, name, dive, trip); return GIT_WALK_SKIP; } static int walk_tree_cb(const char *root, const git_tree_entry *entry, void *payload) { struct git_parser_state *state = payload; git_filemode_t mode = git_tree_entry_filemode(entry); if (mode == GIT_FILEMODE_TREE) return walk_tree_directory(root, entry, state); walk_tree_file(root, entry, state); /* Ignore failed blob loads */ return GIT_WALK_OK; } static int load_dives_from_tree(git_repository *repo, git_tree *tree, struct git_parser_state *state) { git_tree_walk(tree, GIT_TREEWALK_PRE, walk_tree_cb, state); return 0; } void clear_git_id(void) { free((void *)saved_git_id); saved_git_id = NULL; } void set_git_id(const struct git_oid *id) { char git_id_buffer[GIT_OID_HEXSZ + 1]; git_oid_tostr(git_id_buffer, sizeof(git_id_buffer), id); free((void *)saved_git_id); saved_git_id = strdup(git_id_buffer); } static int find_commit(git_repository *repo, const char *branch, git_commit **commit_p) { git_object *object; if (git_revparse_single(&object, repo, branch)) return report_error("Unable to look up revision '%s'", branch); if (git_object_peel((git_object **)commit_p, object, GIT_OBJ_COMMIT)) return report_error("Revision '%s' is not a valid commit", branch); return 0; } static int do_git_load(git_repository *repo, const char *branch, struct git_parser_state *state) { int ret; git_commit *commit; git_tree *tree; ret = find_commit(repo, branch, &commit); if (ret) return ret; if (git_commit_tree(&tree, commit)) return report_error("Could not look up tree of commit in branch '%s'", branch); git_storage_update_progress(translate("gettextFromC", "Load dives from local cache")); ret = load_dives_from_tree(repo, tree, state); if (!ret) { set_git_id(git_commit_id(commit)); git_storage_update_progress(translate("gettextFromC", "Successfully opened dive data")); } git_object_free((git_object *)tree); return ret; } const char *get_sha(git_repository *repo, const char *branch) { static char git_id_buffer[GIT_OID_HEXSZ + 1]; git_commit *commit; if (find_commit(repo, branch, &commit)) return NULL; git_oid_tostr(git_id_buffer, sizeof(git_id_buffer), (const git_oid *)commit); return git_id_buffer; } /* * Like git_save_dives(), this silently returns a negative * value if it's not a git repository at all (so that you * can try to load it some other way. * * If it is a git repository, we return zero for success, * or report an error and return 1 if the load failed. */ int git_load_dives(struct git_info *info, struct dive_table *table, struct trip_table *trips, struct dive_site_table *sites, struct device_table *devices, struct filter_preset_table *filter_presets) { int ret; struct git_parser_state state = { 0 }; state.repo = info->repo; state.table = table; state.trips = trips; state.sites = sites; state.devices = devices; state.filter_presets = filter_presets; if (!info->repo) return report_error("Unable to open git repository '%s[%s]'", info->url, info->branch); ret = do_git_load(info->repo, info->branch, &state); finish_active_dive(&state); finish_active_trip(&state); return ret; }
subsurface-for-dirk-master
core/load-git.c
// SPDX-License-Identifier: GPL-2.0 #ifdef __clang__ // Clang has a bug on zero-initialization of C structs. #pragma clang diagnostic ignored "-Wmissing-field-initializers" #endif #include "ssrf.h" #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "dive.h" #include "file.h" #include "sample.h" #include "subsurface-time.h" #include "units.h" #include "sha1.h" #include "gettext.h" #include "cochran.h" #include "divelist.h" #include <libdivecomputer/parser.h> #define POUND 0.45359237 #define FEET 0.3048 #define INCH 0.0254 #define GRAVITY 9.80665 #define ATM 101325.0 #define BAR 100000.0 #define FSW (ATM / 33.0) #define MSW (BAR / 10.0) #define PSI ((POUND * GRAVITY) / (INCH * INCH)) // Some say 0x4a14 and 0x4b14 are the right number for this offset // This works with CAN files from Analyst 4.01v and computers // such as Commander, Gemini, EMC-16, and EMC-20H #define LOG_ENTRY_OFFSET 0x4914 enum cochran_type { TYPE_GEMINI, TYPE_COMMANDER, TYPE_EMC }; struct config { enum cochran_type type; unsigned int logbook_size; unsigned int sample_size; } config; // Convert 4 bytes into an INT #define array_uint16_le(p) ((unsigned int) (p)[0] \ + ((p)[1]<<8) ) #define array_uint32_le(p) ((unsigned int) (p)[0] \ + ((p)[1]<<8) + ((p)[2]<<16) \ + ((p)[3]<<24)) /* * The Cochran file format is designed to be annoying to read. It's roughly: * * 0x00000: room for 65534 4-byte words, giving the starting offsets * of the dives themselves. * * 0x3fff8: the size of the file + 1 * 0x3ffff: 0 (high 32 bits of filesize? Bogus: the offsets into the file * are 32-bit, so it can't be a large file anyway) * * 0x40000: byte 0x46 * 0x40001: "block 0": 256 byte encryption key * 0x40101: the random modulus, or length of the key to use * 0x40102: block 1: Version and date of Analyst and a feature string identifying * the computer features and the features of the file * 0x40138: Computer configuration page 1, 512 bytes * 0x40338: Computer configuration page 2, 512 bytes * 0x40538: Misc data (tissues) 1500 bytes * 0x40b14: Ownership data 512 bytes ??? * * 0x4171c: Ownership data 512 bytes ??? <copy> * * 0x45415: Time stamp 17 bytes * 0x45426: Computer configuration page 1, 512 bytes <copy> * 0x45626: Computer configuration page 2, 512 bytes <copy> * */ static unsigned int partial_decode(unsigned int start, unsigned int end, const unsigned char *decode, unsigned offset, unsigned mod, const unsigned char *buf, unsigned int size, unsigned char *dst) { unsigned i, sum = 0; for (i = start; i < end; i++) { unsigned char d = decode[offset++]; if (i >= size) break; if (offset == mod) offset = 0; d += buf[i]; if (dst) dst[i] = d; sum += d; } return sum; } #ifdef COCHRAN_DEBUG #define hexchar(n) ("0123456789abcdef"[(n) & 15]) static int show_line(unsigned offset, const unsigned char *data, unsigned size, int show_empty) { unsigned char bits; int i, off; char buffer[120]; if (size > 16) size = 16; bits = 0; memset(buffer, ' ', sizeof(buffer)); off = sprintf(buffer, "%06x ", offset); for (i = 0; i < size; i++) { char *hex = buffer + off + 3 * i; char *asc = buffer + off + 50 + i; unsigned char byte = data[i]; hex[0] = hexchar(byte >> 4); hex[1] = hexchar(byte); bits |= byte; if (byte < 32 || byte > 126) byte = '.'; asc[0] = byte; asc[1] = 0; } if (bits) { puts(buffer); return 1; } if (show_empty) puts("..."); return 0; } static void cochran_debug_write(const unsigned char *data, unsigned size) { return; int show = 1, i; for (i = 0; i < size; i += 16) show = show_line(i, data + i, size - i, show); } static void cochran_debug_sample(const char *s, unsigned int sample_cnt) { switch (config.type) { case TYPE_GEMINI: switch (sample_cnt % 4) { case 0: printf("Hex: %02x %02x ", s[0], s[1]); break; case 1: printf("Hex: %02x %02x ", s[0], s[1]); break; case 2: printf("Hex: %02x %02x ", s[0], s[1]); break; case 3: printf("Hex: %02x %02x ", s[0], s[1]); break; } break; case TYPE_COMMANDER: switch (sample_cnt % 2) { case 0: printf("Hex: %02x %02x ", s[0], s[1]); break; case 1: printf("Hex: %02x %02x ", s[0], s[1]); break; } break; case TYPE_EMC: switch (sample_cnt % 2) { case 0: printf("Hex: %02x %02x %02x ", s[0], s[1], s[2]); break; case 1: printf("Hex: %02x %02x %02x ", s[0], s[1], s[2]); break; } break; } printf ("%02dh %02dm %02ds: Depth: %-5.2f, ", sample_cnt / 3660, (sample_cnt % 3660) / 60, sample_cnt % 60, depth); } #endif // COCHRAN_DEBUG static void cochran_parse_header(const unsigned char *decode, unsigned mod, const unsigned char *in, unsigned size) { unsigned char *buf = malloc(size); /* Do the "null decode" using a one-byte decode array of '\0' */ /* Copies in plaintext, will be overwritten later */ partial_decode(0, 0x0102, (const unsigned char *)"", 0, 1, in, size, buf); /* * The header scrambling is different form the dive * scrambling. Oh yay! */ partial_decode(0x0102, 0x010e, decode, 0, mod, in, size, buf); partial_decode(0x010e, 0x0b14, decode, 0, mod, in, size, buf); partial_decode(0x0b14, 0x1b14, decode, 0, mod, in, size, buf); partial_decode(0x1b14, 0x2b14, decode, 0, mod, in, size, buf); partial_decode(0x2b14, 0x3b14, decode, 0, mod, in, size, buf); partial_decode(0x3b14, 0x5414, decode, 0, mod, in, size, buf); partial_decode(0x5414, size, decode, 0, mod, in, size, buf); // Detect log type switch (buf[0x133]) { case '2': // Cochran Commander, version II log format config.logbook_size = 256; if (buf[0x132] == 0x10) { config.type = TYPE_GEMINI; config.sample_size = 2; // Gemini with tank PSI samples } else { config.type = TYPE_COMMANDER; config.sample_size = 2; // Commander } break; case '3': // Cochran EMC, version III log format config.type = TYPE_EMC; config.logbook_size = 512; config.sample_size = 3; break; default: printf ("Unknown log format v%c\n", buf[0x137]); free(buf); exit(1); break; } #ifdef COCHRAN_DEBUG puts("Header\n======\n\n"); cochran_debug_write(buf, size); #endif free(buf); } /* * Bytes expected after a pre-dive event code */ static int cochran_predive_event_bytes(unsigned char code) { int x = 0; int cmdr_event_bytes[15][2] = {{0x00, 16}, {0x01, 20}, {0x02, 17}, {0x03, 16}, {0x06, 18}, {0x07, 18}, {0x08, 18}, {0x09, 18}, {0x0a, 18}, {0x0b, 18}, {0x0c, 18}, {0x0d, 18}, {0x0e, 18}, {0x10, 20}, {-1, 0}}; int emc_event_bytes[15][2] = {{0x00, 18}, {0x01, 22}, {0x02, 19}, {0x03, 18}, {0x06, 20}, {0x07, 20}, {0x0a, 20}, {0x0b, 20}, {0x0f, 18}, {0x10, 20}, {-1, 0}}; switch (config.type) { case TYPE_GEMINI: case TYPE_COMMANDER: while (cmdr_event_bytes[x][0] != code && cmdr_event_bytes[x][0] != -1) x++; return cmdr_event_bytes[x][1]; break; case TYPE_EMC: while (emc_event_bytes[x][0] != code && emc_event_bytes[x][0] != -1) x++; return emc_event_bytes[x][1]; break; } return 0; } int cochran_dive_event_bytes(unsigned char event) { return (event == 0xAD || event == 0xAB) ? 4 : 0; } static void cochran_dive_event(struct divecomputer *dc, const unsigned char *s, unsigned int seconds, unsigned int *in_deco, unsigned int *deco_ceiling, unsigned int *deco_time) { switch (s[0]) { case 0xC5: // Deco obligation begins *in_deco = 1; add_event(dc, seconds, SAMPLE_EVENT_DECOSTOP, SAMPLE_FLAGS_BEGIN, 0, QT_TRANSLATE_NOOP("gettextFromC", "deco stop")); break; case 0xDB: // Deco obligation ends *in_deco = 0; add_event(dc, seconds, SAMPLE_EVENT_DECOSTOP, SAMPLE_FLAGS_END, 0, QT_TRANSLATE_NOOP("gettextFromC", "deco stop")); break; case 0xAD: // Raise deco ceiling 10 ft *deco_ceiling -= 10; // ft *deco_time = (array_uint16_le(s + 3) + 1) * 60; break; case 0xAB: // Lower deco ceiling 10 ft *deco_ceiling += 10; // ft *deco_time = (array_uint16_le(s + 3) + 1) * 60; break; case 0xA8: // Entered Post Dive interval mode (surfaced) break; case 0xA9: // Exited PDI mode (re-submierged) break; case 0xBD: // Switched to normal PO2 setting break; case 0xC0: // Switched to FO2 21% mode (generally upon surface) break; case 0xC1: // "Ascent rate alarm add_event(dc, seconds, SAMPLE_EVENT_ASCENT, SAMPLE_FLAGS_BEGIN, 0, QT_TRANSLATE_NOOP("gettextFromC", "ascent")); break; case 0xC2: // Low battery warning #ifdef SAMPLE_EVENT_BATTERY add_event(dc, seconds, SAMPLE_EVENT_BATTERY, SAMPLE_FLAGS_NONE, 0, QT_TRANSLATE_NOOP("gettextFromC", "battery")); #endif break; case 0xC3: // CNS warning add_event(dc, seconds, SAMPLE_EVENT_OLF, SAMPLE_FLAGS_BEGIN, 0, QT_TRANSLATE_NOOP("gettextFromC", "OLF")); break; case 0xC4: // Depth alarm begin add_event(dc, seconds, SAMPLE_EVENT_MAXDEPTH, SAMPLE_FLAGS_BEGIN, 0, QT_TRANSLATE_NOOP("gettextFromC", "maxdepth")); break; case 0xC8: // PPO2 alarm begin add_event(dc, seconds, SAMPLE_EVENT_PO2, SAMPLE_FLAGS_BEGIN, 0, QT_TRANSLATE_NOOP("gettextFromC", "pO₂")); break; case 0xCC: // Low cylinder 1 pressure"; break; case 0xCD: // Switch to deco blend setting add_event(dc, seconds, SAMPLE_EVENT_GASCHANGE, SAMPLE_FLAGS_NONE, 0, QT_TRANSLATE_NOOP("gettextFromC", "gaschange")); break; case 0xCE: // NDL alarm begin add_event(dc, seconds, SAMPLE_EVENT_RBT, SAMPLE_FLAGS_BEGIN, 0, QT_TRANSLATE_NOOP("gettextFromC", "rbt")); break; case 0xD0: // Breathing rate alarm begin break; case 0xD3: // Low gas 1 flow rate alarm begin"; break; case 0xD6: // Ceiling alarm begin add_event(dc, seconds, SAMPLE_EVENT_CEILING, SAMPLE_FLAGS_BEGIN, 0, QT_TRANSLATE_NOOP("gettextFromC", "ceiling")); break; case 0xD8: // End decompression mode *in_deco = 0; add_event(dc, seconds, SAMPLE_EVENT_DECOSTOP, SAMPLE_FLAGS_END, 0, QT_TRANSLATE_NOOP("gettextFromC", "deco stop")); break; case 0xE1: // Ascent alarm end add_event(dc, seconds, SAMPLE_EVENT_ASCENT, SAMPLE_FLAGS_END, 0, QT_TRANSLATE_NOOP("gettextFromC", "ascent")); break; case 0xE2: // Low transmitter battery alarm add_event(dc, seconds, SAMPLE_EVENT_TRANSMITTER, SAMPLE_FLAGS_BEGIN, 0, QT_TRANSLATE_NOOP("gettextFromC", "transmitter")); break; case 0xE3: // Switch to FO2 mode break; case 0xE5: // Switched to PO2 mode break; case 0xE8: // PO2 too low alarm add_event(dc, seconds, SAMPLE_EVENT_PO2, SAMPLE_FLAGS_BEGIN, 0, QT_TRANSLATE_NOOP("gettextFromC", "pO₂")); break; case 0xEE: // NDL alarm end add_event(dc, seconds, SAMPLE_EVENT_RBT, SAMPLE_FLAGS_END, 0, QT_TRANSLATE_NOOP("gettextFromC", "rbt")); break; case 0xEF: // Switch to blend 2 add_event(dc, seconds, SAMPLE_EVENT_GASCHANGE, SAMPLE_FLAGS_NONE, 0, QT_TRANSLATE_NOOP("gettextFromC", "gaschange")); break; case 0xF0: // Breathing rate alarm end break; case 0xF3: // Switch to blend 1 (often at dive start) add_event(dc, seconds, SAMPLE_EVENT_GASCHANGE, SAMPLE_FLAGS_NONE, 0, QT_TRANSLATE_NOOP("gettextFromC", "gaschange")); break; case 0xF6: // Ceiling alarm end add_event(dc, seconds, SAMPLE_EVENT_CEILING, SAMPLE_FLAGS_END, 0, QT_TRANSLATE_NOOP("gettextFromC", "ceiling")); break; default: break; } } /* * Parse sample data, extract events and build a dive */ static void cochran_parse_samples(struct dive *dive, const unsigned char *log, const unsigned char *samples, unsigned int size, unsigned int *duration, double *max_depth, double *avg_depth, double *min_temp) { const unsigned char *s; unsigned int offset = 0, profile_period = 1, sample_cnt = 0; double depth = 0, temp = 0, depth_sample = 0, psi = 0, sgc_rate = 0; int ascent_rate = 0; unsigned int ndl = 0; unsigned int in_deco = 0, deco_ceiling = 0, deco_time = 0; struct divecomputer *dc = &dive->dc; struct sample *sample; // Initialize stat variables *max_depth = 0, *avg_depth = 0, *min_temp = 0xFF; // Get starting depth and temp (tank PSI???) switch (config.type) { case TYPE_GEMINI: depth = (double) (log[CMD_START_DEPTH] + log[CMD_START_DEPTH + 1] * 256) / 4; temp = log[CMD_START_TEMP]; psi = log[CMD_START_PSI] + log[CMD_START_PSI + 1] * 256; sgc_rate = (double)(log[CMD_START_SGC] + log[CMD_START_SGC + 1] * 256) / 2; profile_period = log[CMD_PROFILE_PERIOD]; break; case TYPE_COMMANDER: depth = (double) (log[CMD_START_DEPTH] + log[CMD_START_DEPTH + 1] * 256) / 4; temp = log[CMD_START_TEMP]; profile_period = log[CMD_PROFILE_PERIOD]; break; case TYPE_EMC: depth = (double) log [EMC_START_DEPTH] / 256 + log[EMC_START_DEPTH + 1]; temp = log[EMC_START_TEMP]; profile_period = log[EMC_PROFILE_PERIOD]; break; } // Skip past pre-dive events unsigned int x = 0; unsigned int c; while (x < size && (samples[x] & 0x80) == 0 && samples[x] != 0x40) { c = cochran_predive_event_bytes(samples[x]) + 1; #ifdef COCHRAN_DEBUG printf("Predive event: "); for (unsigned int y = 0; y < c && x + y < size; y++) printf("%02x ", samples[x + y]); putchar('\n'); #endif x += c; } // Now process samples offset = x; while (offset + config.sample_size < size) { s = samples + offset; // Start with an empty sample sample = prepare_sample(dc); sample->time.seconds = sample_cnt * profile_period; // Check for event if (s[0] & 0x80) { cochran_dive_event(dc, s, sample_cnt * profile_period, &in_deco, &deco_ceiling, &deco_time); offset += cochran_dive_event_bytes(s[0]) + 1; continue; } // Depth is in every sample depth_sample = (double)(s[0] & 0x3F) / 4 * (s[0] & 0x40 ? -1 : 1); depth += depth_sample; #ifdef COCHRAN_DEBUG cochran_debug_sample(s, sample_cnt); #endif switch (config.type) { case TYPE_COMMANDER: switch (sample_cnt % 2) { case 0: // Ascent rate ascent_rate = (s[1] & 0x7f) * (s[1] & 0x80 ? 1: -1); break; case 1: // Temperature temp = s[1] / 2 + 20; break; } break; case TYPE_GEMINI: // Gemini with tank pressure and SAC rate. switch (sample_cnt % 4) { case 0: // Ascent rate ascent_rate = (s[1] & 0x7f) * (s[1] & 0x80 ? 1 : -1); break; case 2: // PSI change psi -= (double)(s[1] & 0x7f) * (s[1] & 0x80 ? 1 : -1) / 4; break; case 1: // SGC rate sgc_rate -= (double)(s[1] & 0x7f) * (s[1] & 0x80 ? 1 : -1) / 2; break; case 3: // Temperature temp = (double)s[1] / 2 + 20; break; } break; case TYPE_EMC: switch (sample_cnt % 2) { case 0: // Ascent rate ascent_rate = (s[1] & 0x7f) * (s[1] & 0x80 ? 1: -1); break; case 1: // Temperature temp = (double)s[1] / 2 + 20; break; } // Get NDL and deco information switch (sample_cnt % 24) { case 20: if (offset + 5 < size) { if (in_deco) { // Fist stop time //first_deco_time = (s[2] + s[5] * 256 + 1) * 60; // seconds ndl = 0; } else { // NDL ndl = (s[2] + s[5] * 256 + 1) * 60; // seconds deco_time = 0; } } break; case 22: if (offset + 5 < size) { if (in_deco) { // Total stop time deco_time = (s[2] + s[5] * 256 + 1) * 60; // seconds ndl = 0; } } break; } } // Track dive stats if (depth > *max_depth) *max_depth = depth; if (temp < *min_temp) *min_temp = temp; *avg_depth = (*avg_depth * sample_cnt + depth) / (sample_cnt + 1); sample->depth.mm = lrint(depth * FEET * 1000); sample->ndl.seconds = ndl; sample->in_deco = in_deco; sample->stoptime.seconds = deco_time; sample->stopdepth.mm = lrint(deco_ceiling * FEET * 1000); sample->temperature.mkelvin = F_to_mkelvin(temp); sample->sensor[0] = 0; sample->pressure[0].mbar = lrint(psi * PSI / 100); finish_sample(dc); offset += config.sample_size; sample_cnt++; } UNUSED(ascent_rate); // mark the variable as unused if (sample_cnt > 0) *duration = sample_cnt * profile_period - 1; } static void cochran_parse_dive(const unsigned char *decode, unsigned mod, const unsigned char *in, unsigned size, struct dive_table *table) { unsigned char *buf = malloc(size); struct dive *dive; struct divecomputer *dc; struct tm tm = {0}; uint32_t csum[5]; double max_depth, avg_depth, min_temp; unsigned int duration = 0, corrupt_dive = 0; /* * The scrambling has odd boundaries. I think the boundaries * match some data structure size, but I don't know. They were * discovered the same way we dynamically discover the decode * size: automatically looking for least random output. * * The boundaries are also this confused "off-by-one" thing, * the same way the file size is off by one. It's as if the * cochran software forgot to write one byte at the beginning. */ partial_decode(0, 0x0fff, decode, 1, mod, in, size, buf); partial_decode(0x0fff, 0x1fff, decode, 0, mod, in, size, buf); partial_decode(0x1fff, 0x2fff, decode, 0, mod, in, size, buf); partial_decode(0x2fff, 0x48ff, decode, 0, mod, in, size, buf); /* * This is not all the descrambling you need - the above are just * what appears to be the fixed-size blocks. The rest is also * scrambled, but there seems to be size differences in the data, * so this just descrambles part of it: */ if (size < 0x4914 + config.logbook_size) { // Analyst calls this a "Corrupt Beginning Summary" free(buf); return; } // Decode log entry (512 bytes + random prefix) partial_decode(0x48ff, 0x4914 + config.logbook_size, decode, 0, mod, in, size, buf); unsigned int sample_size = size - 0x4914 - config.logbook_size; int g; unsigned int sample_pre_offset = 0, sample_end_offset = 0; // Decode sample data partial_decode(0x4914 + config.logbook_size, size, decode, 0, mod, in, size, buf); #ifdef COCHRAN_DEBUG // Display pre-logbook data puts("\nPre Logbook Data\n"); cochran_debug_write(buf, 0x4914); // Display log book puts("\nLogbook Data\n"); cochran_debug_write(buf + 0x4914, config.logbook_size + 0x400); // Display sample data puts("\nSample Data\n"); #endif dive = alloc_dive(); dc = &dive->dc; unsigned char *log = (buf + 0x4914); switch (config.type) { case TYPE_GEMINI: case TYPE_COMMANDER: if (config.type == TYPE_GEMINI) { cylinder_t cyl = empty_cylinder; dc->model = "Gemini"; dc->deviceid = buf[0x18c] * 256 + buf[0x18d]; // serial no fill_default_cylinder(dive, &cyl); cyl.gasmix.o2.permille = (log[CMD_O2_PERCENT] / 256 + log[CMD_O2_PERCENT + 1]) * 10; cyl.gasmix.he.permille = 0; add_cylinder(&dive->cylinders, 0, cyl); } else { dc->model = "Commander"; dc->deviceid = array_uint32_le(buf + 0x31e); // serial no for (g = 0; g < 2; g++) { cylinder_t cyl = empty_cylinder; fill_default_cylinder(dive, &cyl); cyl.gasmix.o2.permille = (log[CMD_O2_PERCENT + g * 2] / 256 + log[CMD_O2_PERCENT + g * 2 + 1]) * 10; cyl.gasmix.he.permille = 0; add_cylinder(&dive->cylinders, g, cyl); } } tm.tm_year = log[CMD_YEAR]; tm.tm_mon = log[CMD_MON] - 1; tm.tm_mday = log[CMD_DAY]; tm.tm_hour = log[CMD_HOUR]; tm.tm_min = log[CMD_MIN]; tm.tm_sec = log[CMD_SEC]; tm.tm_isdst = -1; dive->when = dc->when = utc_mktime(&tm); dive->number = log[CMD_NUMBER] + log[CMD_NUMBER + 1] * 256 + 1; dc->duration.seconds = (log[CMD_BT] + log[CMD_BT + 1] * 256) * 60; dc->surfacetime.seconds = (log[CMD_SIT] + log[CMD_SIT + 1] * 256) * 60; dc->maxdepth.mm = lrint((log[CMD_MAX_DEPTH] + log[CMD_MAX_DEPTH + 1] * 256) / 4 * FEET * 1000); dc->meandepth.mm = lrint((log[CMD_AVG_DEPTH] + log[CMD_AVG_DEPTH + 1] * 256) / 4 * FEET * 1000); dc->watertemp.mkelvin = F_to_mkelvin(log[CMD_MIN_TEMP]); dc->surface_pressure.mbar = lrint(ATM / BAR * pow(1 - 0.0000225577 * (double) log[CMD_ALTITUDE] * 250 * FEET, 5.25588) * 1000); dc->salinity = 10000 + 150 * log[CMD_WATER_CONDUCTIVITY]; SHA1(log + CMD_NUMBER, 2, (unsigned char *)csum); dc->diveid = csum[0]; if (log[CMD_MAX_DEPTH] == 0xff && log[CMD_MAX_DEPTH + 1] == 0xff) corrupt_dive = 1; sample_pre_offset = array_uint32_le(log + CMD_PREDIVE_OFFSET); sample_end_offset = array_uint32_le(log + CMD_END_OFFSET); break; case TYPE_EMC: dc->model = "EMC"; dc->deviceid = array_uint32_le(buf + 0x31e); // serial no for (g = 0; g < 4; g++) { cylinder_t cyl = empty_cylinder; fill_default_cylinder(dive, &cyl); cyl.gasmix.o2.permille = (log[EMC_O2_PERCENT + g * 2] / 256 + log[EMC_O2_PERCENT + g * 2 + 1]) * 10; cyl.gasmix.he.permille = (log[EMC_HE_PERCENT + g * 2] / 256 + log[EMC_HE_PERCENT + g * 2 + 1]) * 10; add_cylinder(&dive->cylinders, g, cyl); } tm.tm_year = log[EMC_YEAR]; tm.tm_mon = log[EMC_MON] - 1; tm.tm_mday = log[EMC_DAY]; tm.tm_hour = log[EMC_HOUR]; tm.tm_min = log[EMC_MIN]; tm.tm_sec = log[EMC_SEC]; tm.tm_isdst = -1; dive->when = dc->when = utc_mktime(&tm); dive->number = log[EMC_NUMBER] + log[EMC_NUMBER + 1] * 256 + 1; dc->duration.seconds = (log[EMC_BT] + log[EMC_BT + 1] * 256) * 60; dc->surfacetime.seconds = (log[EMC_SIT] + log[EMC_SIT + 1] * 256) * 60; dc->maxdepth.mm = lrint((log[EMC_MAX_DEPTH] + log[EMC_MAX_DEPTH + 1] * 256) / 4 * FEET * 1000); dc->meandepth.mm = lrint((log[EMC_AVG_DEPTH] + log[EMC_AVG_DEPTH + 1] * 256) / 4 * FEET * 1000); dc->watertemp.mkelvin = F_to_mkelvin(log[EMC_MIN_TEMP]); dc->surface_pressure.mbar = lrint(ATM / BAR * pow(1 - 0.0000225577 * (double) log[EMC_ALTITUDE] * 250 * FEET, 5.25588) * 1000); dc->salinity = 10000 + 150 * (log[EMC_WATER_CONDUCTIVITY] & 0x3); SHA1(log + EMC_NUMBER, 2, (unsigned char *)csum); dc->diveid = csum[0]; if (log[EMC_MAX_DEPTH] == 0xff && log[EMC_MAX_DEPTH + 1] == 0xff) corrupt_dive = 1; sample_pre_offset = array_uint32_le(log + EMC_PREDIVE_OFFSET); sample_end_offset = array_uint32_le(log + EMC_END_OFFSET); break; } // Use the log information to determine actual profile sample size // Otherwise we will get surface time at end of dive. if (sample_pre_offset < sample_end_offset && sample_end_offset != 0xffffffff) sample_size = sample_end_offset - sample_pre_offset; cochran_parse_samples(dive, buf + 0x4914, buf + 0x4914 + config.logbook_size, sample_size, &duration, &max_depth, &avg_depth, &min_temp); // Check for corrupt dive if (corrupt_dive) { dc->maxdepth.mm = lrint(max_depth * FEET * 1000); dc->meandepth.mm = lrint(avg_depth * FEET * 1000); dc->watertemp.mkelvin = F_to_mkelvin(min_temp); dc->duration.seconds = duration; } record_dive_to_table(dive, table); free(buf); } int try_to_open_cochran(const char *filename, struct memblock *mem, struct dive_table *table, struct trip_table *trips, struct dive_site_table *sites) { UNUSED(filename); UNUSED(trips); UNUSED(sites); unsigned int i; unsigned int mod; unsigned int *offsets, dive1, dive2; unsigned char *decode = mem->buffer + 0x40001; if (mem->size < 0x40000) return 0; offsets = (unsigned int *) mem->buffer; dive1 = offsets[0]; dive2 = offsets[1]; if (dive1 < 0x40000 || dive2 < dive1 || dive2 > mem->size) return 0; mod = decode[0x100] + 1; cochran_parse_header(decode, mod, mem->buffer + 0x40000, dive1 - 0x40000); // Decode each dive for (i = 0; i < 65534; i++) { dive1 = offsets[i]; dive2 = offsets[i + 1]; if (dive2 < dive1) break; if (dive2 > mem->size) break; cochran_parse_dive(decode, mod, mem->buffer + dive1, dive2 - dive1, table); } return 1; // no further processing needed }
subsurface-for-dirk-master
core/cochran.c
// SPDX-License-Identifier: GPL-2.0 #ifdef __clang__ // Clang has a bug on zero-initialization of C structs. #pragma clang diagnostic ignored "-Wmissing-field-initializers" #endif #include "ssrf.h" #include <stdio.h> #include <unistd.h> #include <inttypes.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "gettext.h" #include "divesite.h" #include "sample.h" #include "subsurface-float.h" #include "subsurface-string.h" #include "device.h" #include "dive.h" #include "errorhelper.h" #include "event.h" #include "sha1.h" #include "subsurface-time.h" #include "timer.h" #include <libdivecomputer/version.h> #include <libdivecomputer/usbhid.h> #include <libdivecomputer/usb.h> #include <libdivecomputer/serial.h> #include <libdivecomputer/irda.h> #include <libdivecomputer/bluetooth.h> #include "libdivecomputer.h" #include "core/version.h" #include "core/qthelper.h" #include "core/membuffer.h" #include "core/file.h" #include <QtGlobal> char *dumpfile_name; char *logfile_name; const char *progress_bar_text = ""; void (*progress_callback)(const char *text) = NULL; double progress_bar_fraction = 0.0; static int stoptime, stopdepth, ndl, po2, cns, heartbeat, bearing; static bool in_deco, first_temp_is_air; static int current_gas_index; /* logging bits from libdivecomputer */ #ifndef __ANDROID__ #define INFO(context, fmt, ...) fprintf(stderr, "INFO: " fmt "\n", ##__VA_ARGS__) #define ERROR(context, fmt, ...) fprintf(stderr, "ERROR: " fmt "\n", ##__VA_ARGS__) #else #include <android/log.h> #define INFO(context, fmt, ...) __android_log_print(ANDROID_LOG_DEBUG, __FILE__, "INFO: " fmt "\n", ##__VA_ARGS__) #define ERROR(context, fmt, ...) __android_log_print(ANDROID_LOG_DEBUG, __FILE__, "ERROR: " fmt "\n", ##__VA_ARGS__) #endif /* * Directly taken from libdivecomputer's examples/common.c to improve * the error messages resulting from libdc's return codes */ const char *errmsg (dc_status_t rc) { switch (rc) { case DC_STATUS_SUCCESS: return "Success"; case DC_STATUS_UNSUPPORTED: return "Unsupported operation"; case DC_STATUS_INVALIDARGS: return "Invalid arguments"; case DC_STATUS_NOMEMORY: return "Out of memory"; case DC_STATUS_NODEVICE: return "No device found"; case DC_STATUS_NOACCESS: return "Access denied"; case DC_STATUS_IO: return "Input/output error"; case DC_STATUS_TIMEOUT: return "Timeout"; case DC_STATUS_PROTOCOL: return "Protocol error"; case DC_STATUS_DATAFORMAT: return "Data format error"; case DC_STATUS_CANCELLED: return "Cancelled"; default: return "Unknown error"; } } static dc_status_t create_parser(device_data_t *devdata, dc_parser_t **parser) { return dc_parser_new(parser, devdata->device); } static int parse_gasmixes(device_data_t *devdata, struct dive *dive, dc_parser_t *parser, unsigned int ngases) { static bool shown_warning = false; unsigned int i; int rc; unsigned int ntanks = 0; rc = dc_parser_get_field(parser, DC_FIELD_TANK_COUNT, 0, &ntanks); if (rc == DC_STATUS_SUCCESS) { if (ntanks && ntanks < ngases) { shown_warning = true; report_error("Warning: different number of gases (%d) and cylinders (%d)", ngases, ntanks); } else if (ntanks > ngases) { shown_warning = true; report_error("Warning: smaller number of gases (%d) than cylinders (%d). Assuming air.", ngases, ntanks); } } bool no_volume = true; clear_cylinder_table(&dive->cylinders); for (i = 0; i < ngases || i < ntanks; i++) { cylinder_t cyl = empty_cylinder; if (i < ngases) { dc_gasmix_t gasmix = { 0 }; int o2, he; rc = dc_parser_get_field(parser, DC_FIELD_GASMIX, i, &gasmix); if (rc != DC_STATUS_SUCCESS && rc != DC_STATUS_UNSUPPORTED) return rc; o2 = lrint(gasmix.oxygen * 1000); he = lrint(gasmix.helium * 1000); /* Ignore bogus data - libdivecomputer does some crazy stuff */ if (o2 + he <= O2_IN_AIR || o2 > 1000) { if (!shown_warning) { shown_warning = true; report_error("unlikely dive gas data from libdivecomputer: o2 = %d he = %d", o2, he); } o2 = 0; } if (he < 0 || o2 + he > 1000) { if (!shown_warning) { shown_warning = true; report_error("unlikely dive gas data from libdivecomputer: o2 = %d he = %d", o2, he); } he = 0; } cyl.gasmix.o2.permille = o2; cyl.gasmix.he.permille = he; } if (i < ntanks) { dc_tank_t tank = { 0 }; rc = dc_parser_get_field(parser, DC_FIELD_TANK, i, &tank); if (rc == DC_STATUS_SUCCESS) { cyl.type.size.mliter = lrint(tank.volume * 1000); cyl.type.workingpressure.mbar = lrint(tank.workpressure * 1000); cyl.cylinder_use = OC_GAS; if (tank.type & DC_TANKINFO_CC_O2) cyl.cylinder_use = OXYGEN; if (tank.type & DC_TANKINFO_CC_DILUENT) cyl.cylinder_use = DILUENT; if (tank.type & DC_TANKINFO_IMPERIAL) { if (same_string(devdata->model, "Suunto EON Steel")) { /* Suunto EON Steele gets this wrong. Badly. * but on the plus side it only supports a few imperial sizes, * so let's try and guess at least the most common ones. * First, the pressures are off by a constant factor. WTF? * Then we can round the wet sizes so we get to multiples of 10 * for cuft sizes (as that's all that you can enter) */ cyl.type.workingpressure.mbar = lrint( cyl.type.workingpressure.mbar * 206.843 / 206.7 ); char name_buffer[17]; int rounded_size = lrint(ml_to_cuft(gas_volume(&cyl, cyl.type.workingpressure))); rounded_size = (int)((rounded_size + 5) / 10) * 10; switch (cyl.type.workingpressure.mbar) { case 206843: snprintf(name_buffer, sizeof(name_buffer), "AL%d", rounded_size); break; case 234422: /* this is wrong - HP tanks tend to be 3440, but Suunto only allows 3400 */ snprintf(name_buffer, sizeof(name_buffer), "HP%d", rounded_size); break; case 179263: snprintf(name_buffer, sizeof(name_buffer), "LP+%d", rounded_size); break; case 165474: snprintf(name_buffer, sizeof(name_buffer), "LP%d", rounded_size); break; default: snprintf(name_buffer, sizeof(name_buffer), "%d cuft", rounded_size); break; } cyl.type.description = copy_string(name_buffer); cyl.type.size.mliter = lrint(cuft_to_l(rounded_size) * 1000 / mbar_to_atm(cyl.type.workingpressure.mbar)); } } if (tank.gasmix != DC_GASMIX_UNKNOWN && tank.gasmix != i) { // we don't handle this, yet shown_warning = true; report_error("gasmix %d for tank %d doesn't match", tank.gasmix, i); } } if (!nearly_0(tank.volume)) no_volume = false; // this new API also gives us the beginning and end pressure for the tank // normally 0 is not a valid pressure, but for some Uwatec dive computers we // don't get the actual start and end pressure, but instead a start pressure // that matches the consumption and an end pressure of always 0 // In order to make this work, we arbitrary shift this up by 30bar so the // rest of the code treats this as if they were valid values if (!nearly_0(tank.beginpressure)) { if (!nearly_0(tank.endpressure)) { cyl.start.mbar = lrint(tank.beginpressure * 1000); cyl.end.mbar = lrint(tank.endpressure * 1000); } else if (same_string(devdata->vendor, "Uwatec")) { cyl.start.mbar = lrint(tank.beginpressure * 1000 + 30000); cyl.end.mbar = 30000; } } } if (no_volume) { /* for the first tank, if there is no tanksize available from the * dive computer, fill in the default tank information (if set) */ fill_default_cylinder(dive, &cyl); } /* whatever happens, make sure there is a name for the cylinder */ if (empty_string(cyl.type.description)) cyl.type.description = strdup(translate("gettextFromC", "unknown")); add_cylinder(&dive->cylinders, dive->cylinders.nr, cyl); } return DC_STATUS_SUCCESS; } static void handle_event(struct divecomputer *dc, struct sample *sample, dc_sample_value_t value) { int type, time; struct event *ev; /* we mark these for translation here, but we store the untranslated strings * and only translate them when they are displayed on screen */ static const char *events[] = { [SAMPLE_EVENT_NONE] = QT_TRANSLATE_NOOP("gettextFromC", "none"), [SAMPLE_EVENT_DECOSTOP] = QT_TRANSLATE_NOOP("gettextFromC", "deco stop"), [SAMPLE_EVENT_RBT] = QT_TRANSLATE_NOOP("gettextFromC", "rbt"), [SAMPLE_EVENT_ASCENT] = QT_TRANSLATE_NOOP("gettextFromC", "ascent"), [SAMPLE_EVENT_CEILING] = QT_TRANSLATE_NOOP("gettextFromC", "ceiling"), [SAMPLE_EVENT_WORKLOAD] = QT_TRANSLATE_NOOP("gettextFromC", "workload"), [SAMPLE_EVENT_TRANSMITTER] = QT_TRANSLATE_NOOP("gettextFromC", "transmitter"), [SAMPLE_EVENT_VIOLATION] = QT_TRANSLATE_NOOP("gettextFromC", "violation"), [SAMPLE_EVENT_BOOKMARK] = QT_TRANSLATE_NOOP("gettextFromC", "bookmark"), [SAMPLE_EVENT_SURFACE] = QT_TRANSLATE_NOOP("gettextFromC", "surface"), [SAMPLE_EVENT_SAFETYSTOP] = QT_TRANSLATE_NOOP("gettextFromC", "safety stop"), [SAMPLE_EVENT_GASCHANGE] = QT_TRANSLATE_NOOP("gettextFromC", "gaschange"), [SAMPLE_EVENT_SAFETYSTOP_VOLUNTARY] = QT_TRANSLATE_NOOP("gettextFromC", "safety stop (voluntary)"), [SAMPLE_EVENT_SAFETYSTOP_MANDATORY] = QT_TRANSLATE_NOOP("gettextFromC", "safety stop (mandatory)"), [SAMPLE_EVENT_DEEPSTOP] = QT_TRANSLATE_NOOP("gettextFromC", "deepstop"), [SAMPLE_EVENT_CEILING_SAFETYSTOP] = QT_TRANSLATE_NOOP("gettextFromC", "ceiling (safety stop)"), [SAMPLE_EVENT_FLOOR] = QT_TRANSLATE_NOOP3("gettextFromC", "below floor", "event showing dive is below deco floor and adding deco time"), [SAMPLE_EVENT_DIVETIME] = QT_TRANSLATE_NOOP("gettextFromC", "divetime"), [SAMPLE_EVENT_MAXDEPTH] = QT_TRANSLATE_NOOP("gettextFromC", "maxdepth"), [SAMPLE_EVENT_OLF] = QT_TRANSLATE_NOOP("gettextFromC", "OLF"), [SAMPLE_EVENT_PO2] = QT_TRANSLATE_NOOP("gettextFromC", "pO₂"), [SAMPLE_EVENT_AIRTIME] = QT_TRANSLATE_NOOP("gettextFromC", "airtime"), [SAMPLE_EVENT_RGBM] = QT_TRANSLATE_NOOP("gettextFromC", "rgbm"), [SAMPLE_EVENT_HEADING] = QT_TRANSLATE_NOOP("gettextFromC", "heading"), [SAMPLE_EVENT_TISSUELEVEL] = QT_TRANSLATE_NOOP("gettextFromC", "tissue level warning"), [SAMPLE_EVENT_GASCHANGE2] = QT_TRANSLATE_NOOP("gettextFromC", "gaschange"), }; const int nr_events = sizeof(events) / sizeof(const char *); const char *name; /* * Other evens might be more interesting, but for now we just print them out. */ type = value.event.type; name = QT_TRANSLATE_NOOP("gettextFromC", "invalid event number"); if (type < nr_events && events[type]) name = events[type]; #ifdef SAMPLE_EVENT_STRING if (type == SAMPLE_EVENT_STRING) name = value.event.name; #endif time = value.event.time; if (sample) time += sample->time.seconds; ev = add_event(dc, time, type, value.event.flags, value.event.value, name); if (event_is_gaschange(ev) && ev->gas.index >= 0) current_gas_index = ev->gas.index; } static void handle_gasmix(struct divecomputer *dc, struct sample *sample, int idx) { /* TODO: Verify that index is not higher than the number of cylinders */ if (idx < 0) return; add_event(dc, sample->time.seconds, SAMPLE_EVENT_GASCHANGE2, idx+1, 0, "gaschange"); current_gas_index = idx; } void sample_cb(dc_sample_type_t type, dc_sample_value_t value, void *userdata) { static unsigned int nsensor = 0; struct divecomputer *dc = userdata; struct sample *sample; /* * We fill in the "previous" sample - except for DC_SAMPLE_TIME, * which creates a new one. */ sample = dc->samples ? dc->sample + dc->samples - 1 : NULL; /* * Ok, sanity check. * If first sample is not a DC_SAMPLE_TIME, Allocate a sample for us */ if (sample == NULL && type != DC_SAMPLE_TIME) sample = prepare_sample(dc); switch (type) { case DC_SAMPLE_TIME: nsensor = 0; // Create a new sample. // Mark depth as negative sample = prepare_sample(dc); sample->time.seconds = value.time; sample->depth.mm = -1; // The current sample gets some sticky values // that may have been around from before, these // values will be overwritten by new data if available sample->in_deco = in_deco; sample->ndl.seconds = ndl; sample->stoptime.seconds = stoptime; sample->stopdepth.mm = stopdepth; sample->setpoint.mbar = po2; sample->cns = cns; sample->heartbeat = heartbeat; sample->bearing.degrees = bearing; finish_sample(dc); break; case DC_SAMPLE_DEPTH: sample->depth.mm = lrint(value.depth * 1000); break; case DC_SAMPLE_PRESSURE: add_sample_pressure(sample, value.pressure.tank, lrint(value.pressure.value * 1000)); break; case DC_SAMPLE_GASMIX: handle_gasmix(dc, sample, value.gasmix); break; case DC_SAMPLE_TEMPERATURE: sample->temperature.mkelvin = C_to_mkelvin(value.temperature); break; case DC_SAMPLE_EVENT: handle_event(dc, sample, value); break; case DC_SAMPLE_RBT: sample->rbt.seconds = (!strncasecmp(dc->model, "suunto", 6)) ? value.rbt : value.rbt * 60; break; #ifdef DC_SAMPLE_TTS case DC_SAMPLE_TTS: sample->tts.seconds = value.time; break; #endif case DC_SAMPLE_HEARTBEAT: sample->heartbeat = heartbeat = value.heartbeat; break; case DC_SAMPLE_BEARING: sample->bearing.degrees = bearing = value.bearing; break; #ifdef DEBUG_DC_VENDOR case DC_SAMPLE_VENDOR: printf(" <vendor time='%u:%02u' type=\"%u\" size=\"%u\">", FRACTION(sample->time.seconds, 60), value.vendor.type, value.vendor.size); for (int i = 0; i < value.vendor.size; ++i) printf("%02X", ((unsigned char *)value.vendor.data)[i]); printf("</vendor>\n"); break; #endif case DC_SAMPLE_SETPOINT: /* for us a setpoint means constant pO2 from here */ sample->setpoint.mbar = po2 = lrint(value.setpoint * 1000); break; case DC_SAMPLE_PPO2: if (nsensor < 3) sample->o2sensor[nsensor].mbar = lrint(value.ppo2 * 1000); else report_error("%d is more o2 sensors than we can handle", nsensor); nsensor++; // Set the amount of detected o2 sensors if (nsensor > dc->no_o2sensors) dc->no_o2sensors = nsensor; break; case DC_SAMPLE_CNS: sample->cns = cns = lrint(value.cns * 100); break; case DC_SAMPLE_DECO: if (value.deco.type == DC_DECO_NDL) { sample->ndl.seconds = ndl = value.deco.time; sample->stopdepth.mm = stopdepth = lrint(value.deco.depth * 1000.0); sample->in_deco = in_deco = false; } else if (value.deco.type == DC_DECO_DECOSTOP || value.deco.type == DC_DECO_DEEPSTOP) { sample->stopdepth.mm = stopdepth = lrint(value.deco.depth * 1000.0); sample->stoptime.seconds = stoptime = value.deco.time; sample->in_deco = in_deco = stopdepth > 0; ndl = 0; } else if (value.deco.type == DC_DECO_SAFETYSTOP) { sample->in_deco = in_deco = false; sample->stopdepth.mm = stopdepth = lrint(value.deco.depth * 1000.0); sample->stoptime.seconds = stoptime = value.deco.time; } default: break; } } static void dev_info(device_data_t *devdata, const char *fmt, ...) { UNUSED(devdata); static char buffer[1024]; va_list ap; va_start(ap, fmt); vsnprintf(buffer, sizeof(buffer), fmt, ap); va_end(ap); progress_bar_text = buffer; if (verbose) INFO(0, "dev_info: %s\n", buffer); if (progress_callback) (*progress_callback)(buffer); } static int import_dive_number = 0; static void download_error(const char *fmt, ...) { static char buffer[1024]; va_list ap; va_start(ap, fmt); vsnprintf(buffer, sizeof(buffer), fmt, ap); va_end(ap); report_error("Dive %d: %s", import_dive_number, buffer); } static int parse_samples(device_data_t *devdata, struct divecomputer *dc, dc_parser_t *parser) { UNUSED(devdata); // Parse the sample data. return dc_parser_samples_foreach(parser, sample_cb, dc); } static int might_be_same_dc(struct divecomputer *a, struct divecomputer *b) { if (!a->model || !b->model) return 1; if (strcasecmp(a->model, b->model)) return 0; if (!a->deviceid || !b->deviceid) return 1; return a->deviceid == b->deviceid; } static int match_one_dive(struct divecomputer *a, struct dive *dive) { struct divecomputer *b = &dive->dc; /* * Walk the existing dive computer data, * see if we have a match (or an anti-match: * the same dive computer but a different * dive ID). */ do { int match = match_one_dc(a, b); if (match) return match > 0; b = b->next; } while (b); /* Ok, no exact dive computer match. Does the date match? */ b = &dive->dc; do { if (a->when == b->when && might_be_same_dc(a, b)) return 1; b = b->next; } while (b); return 0; } /* * Check if this dive already existed before the import */ static int find_dive(struct divecomputer *match) { int i; for (i = dive_table.nr - 1; i >= 0; i--) { struct dive *old = dive_table.dives[i]; if (match_one_dive(match, old)) return 1; } return 0; } /* * Like g_strdup_printf(), but without the stupid g_malloc/g_free confusion. * And we limit the string to some arbitrary size. */ static char *str_printf(const char *fmt, ...) { va_list args; char buf[1024]; va_start(args, fmt); vsnprintf(buf, sizeof(buf) - 1, fmt, args); va_end(args); buf[sizeof(buf) - 1] = 0; return strdup(buf); } /* * The dive ID for libdivecomputer dives is the first word of the * SHA1 of the fingerprint, if it exists. * * NOTE! This is byte-order dependent, and I don't care. */ static uint32_t calculate_diveid(const unsigned char *fingerprint, unsigned int fsize) { uint32_t csum[5]; if (!fingerprint || !fsize) return 0; SHA1(fingerprint, fsize, (unsigned char *)csum); return csum[0]; } uint32_t calculate_string_hash(const char *str) { return calculate_diveid((const unsigned char *)str, strlen(str)); } static void parse_string_field(device_data_t *devdata, struct dive *dive, dc_field_string_t *str) { // Our dive ID is the string hash of the "Dive ID" string if (!strcmp(str->desc, "Dive ID")) { if (!dive->dc.diveid) dive->dc.diveid = calculate_string_hash(str->value); return; } // This will pick up serial number and firmware data add_extra_data(&dive->dc, str->desc, str->value); /* GPS data? */ if (!strncmp(str->desc, "GPS", 3)) { char *line = (char *) str->value; location_t location; /* Do we already have a divesite? */ if (dive->dive_site) { /* * "GPS1" always takes precedence, anything else * we'll just pick the first "GPS*" that matches. */ if (strcmp(str->desc, "GPS1") != 0) return; } parse_location(line, &location); if (location.lat.udeg && location.lon.udeg) { unregister_dive_from_dive_site(dive); add_dive_to_dive_site(dive, create_dive_site_with_gps(str->value, &location, devdata->sites)); } } } static dc_status_t libdc_header_parser(dc_parser_t *parser, device_data_t *devdata, struct dive *dive) { dc_status_t rc = 0; dc_datetime_t dt = { 0 }; struct tm tm; rc = dc_parser_get_datetime(parser, &dt); if (rc != DC_STATUS_SUCCESS && rc != DC_STATUS_UNSUPPORTED) { download_error(translate("gettextFromC", "Error parsing the datetime")); return rc; } // Our deviceid is the hash of the serial number dive->dc.deviceid = 0; if (rc == DC_STATUS_SUCCESS) { tm.tm_year = dt.year; tm.tm_mon = dt.month - 1; tm.tm_mday = dt.day; tm.tm_hour = dt.hour; tm.tm_min = dt.minute; tm.tm_sec = dt.second; dive->when = dive->dc.when = utc_mktime(&tm); } // Parse the divetime. char *date_string = get_dive_date_c_string(dive->when); dev_info(devdata, translate("gettextFromC", "Dive %d: %s"), import_dive_number, date_string); free(date_string); unsigned int divetime = 0; rc = dc_parser_get_field(parser, DC_FIELD_DIVETIME, 0, &divetime); if (rc != DC_STATUS_SUCCESS && rc != DC_STATUS_UNSUPPORTED) { download_error(translate("gettextFromC", "Error parsing the divetime")); return rc; } if (rc == DC_STATUS_SUCCESS) dive->dc.duration.seconds = divetime; // Parse the maxdepth. double maxdepth = 0.0; rc = dc_parser_get_field(parser, DC_FIELD_MAXDEPTH, 0, &maxdepth); if (rc != DC_STATUS_SUCCESS && rc != DC_STATUS_UNSUPPORTED) { download_error(translate("gettextFromC", "Error parsing the maxdepth")); return rc; } if (rc == DC_STATUS_SUCCESS) dive->dc.maxdepth.mm = lrint(maxdepth * 1000); // Parse temperatures double temperature; dc_field_type_t temp_fields[] = {DC_FIELD_TEMPERATURE_SURFACE, DC_FIELD_TEMPERATURE_MAXIMUM, DC_FIELD_TEMPERATURE_MINIMUM}; for (int i = 0; i < 3; i++) { rc = dc_parser_get_field(parser, temp_fields[i], 0, &temperature); if (rc != DC_STATUS_SUCCESS && rc != DC_STATUS_UNSUPPORTED) { download_error(translate("gettextFromC", "Error parsing temperature")); return rc; } if (rc == DC_STATUS_SUCCESS) switch(i) { case 0: dive->dc.airtemp.mkelvin = C_to_mkelvin(temperature); break; case 1: // we don't distinguish min and max water temp here, so take min if given, max otherwise case 2: dive->dc.watertemp.mkelvin = C_to_mkelvin(temperature); break; } } // Parse the gas mixes. unsigned int ngases = 0; rc = dc_parser_get_field(parser, DC_FIELD_GASMIX_COUNT, 0, &ngases); if (rc != DC_STATUS_SUCCESS && rc != DC_STATUS_UNSUPPORTED) { download_error(translate("gettextFromC", "Error parsing the gas mix count")); return rc; } // Check if the libdivecomputer version already supports salinity & atmospheric dc_salinity_t salinity = { .type = DC_WATER_SALT, .density = SEAWATER_SALINITY / 10.0 }; rc = dc_parser_get_field(parser, DC_FIELD_SALINITY, 0, &salinity); if (rc != DC_STATUS_SUCCESS && rc != DC_STATUS_UNSUPPORTED) { download_error(translate("gettextFromC", "Error obtaining water salinity")); return rc; } if (rc == DC_STATUS_SUCCESS) { dive->dc.salinity = lrint(salinity.density * 10.0); if (dive->dc.salinity == 0) { // sometimes libdivecomputer gives us density values, sometimes just // a water type and a density of zero; let's make this work as best as we can switch (salinity.type) { case DC_WATER_FRESH: dive->dc.salinity = FRESHWATER_SALINITY; break; default: dive->dc.salinity = SEAWATER_SALINITY; break; } } } double surface_pressure = 0; rc = dc_parser_get_field(parser, DC_FIELD_ATMOSPHERIC, 0, &surface_pressure); if (rc != DC_STATUS_SUCCESS && rc != DC_STATUS_UNSUPPORTED) { download_error(translate("gettextFromC", "Error obtaining surface pressure")); return rc; } if (rc == DC_STATUS_SUCCESS) dive->dc.surface_pressure.mbar = lrint(surface_pressure * 1000.0); // The dive parsing may give us more device information int idx; for (idx = 0; idx < 100; idx++) { dc_field_string_t str = { NULL }; rc = dc_parser_get_field(parser, DC_FIELD_STRING, idx, &str); if (rc != DC_STATUS_SUCCESS) break; if (!str.desc || !str.value) break; parse_string_field(devdata, dive, &str); free((void *)str.value); // libdc gives us copies of the value-string. } dc_divemode_t divemode; rc = dc_parser_get_field(parser, DC_FIELD_DIVEMODE, 0, &divemode); if (rc != DC_STATUS_SUCCESS && rc != DC_STATUS_UNSUPPORTED) { download_error(translate("gettextFromC", "Error obtaining dive mode")); return rc; } if (rc == DC_STATUS_SUCCESS) switch(divemode) { case DC_DIVEMODE_FREEDIVE: dive->dc.divemode = FREEDIVE; break; case DC_DIVEMODE_GAUGE: case DC_DIVEMODE_OC: /* Open circuit */ dive->dc.divemode = OC; break; case DC_DIVEMODE_CCR: /* Closed circuit rebreather*/ dive->dc.divemode = CCR; break; case DC_DIVEMODE_SCR: /* Semi-closed circuit rebreather */ dive->dc.divemode = PSCR; break; } rc = parse_gasmixes(devdata, dive, parser, ngases); if (rc != DC_STATUS_SUCCESS && rc != DC_STATUS_UNSUPPORTED) { download_error(translate("gettextFromC", "Error parsing the gas mix")); return rc; } return DC_STATUS_SUCCESS; } /* returns true if we want libdivecomputer's dc_device_foreach() to continue, * false otherwise */ static int dive_cb(const unsigned char *data, unsigned int size, const unsigned char *fingerprint, unsigned int fsize, void *userdata) { int rc; dc_parser_t *parser = NULL; device_data_t *devdata = userdata; struct dive *dive = NULL; /* reset static data, that is only valid per dive */ stoptime = stopdepth = po2 = cns = heartbeat = 0; ndl = bearing = -1; in_deco = false; current_gas_index = -1; import_dive_number++; rc = create_parser(devdata, &parser); if (rc != DC_STATUS_SUCCESS) { download_error(translate("gettextFromC", "Unable to create parser for %s %s"), devdata->vendor, devdata->product); return true; } rc = dc_parser_set_data(parser, data, size); if (rc != DC_STATUS_SUCCESS) { download_error(translate("gettextFromC", "Error registering the data")); goto error_exit; } dive = alloc_dive(); // Fill in basic fields dive->dc.model = strdup(devdata->model); dive->dc.diveid = calculate_diveid(fingerprint, fsize); // Parse the dive's header data rc = libdc_header_parser (parser, devdata, dive); if (rc != DC_STATUS_SUCCESS) { download_error(translate("getextFromC", "Error parsing the header")); goto error_exit; } // Initialize the sample data. rc = parse_samples(devdata, &dive->dc, parser); if (rc != DC_STATUS_SUCCESS) { download_error(translate("gettextFromC", "Error parsing the samples")); goto error_exit; } dc_parser_destroy(parser); /* * Save off fingerprint data. * * NOTE! We do this after parsing the dive fully, so that * we have the final deviceid here. */ if (fingerprint && fsize && !devdata->fingerprint) { devdata->fingerprint = calloc(fsize, 1); if (devdata->fingerprint) { devdata->fsize = fsize; devdata->fdeviceid = dive->dc.deviceid; devdata->fdiveid = dive->dc.diveid; memcpy(devdata->fingerprint, fingerprint, fsize); } } /* If we already saw this dive, abort. */ if (!devdata->force_download && find_dive(&dive->dc)) { char *date_string = get_dive_date_c_string(dive->when); dev_info(devdata, translate("gettextFromC", "Already downloaded dive at %s"), date_string); free(date_string); free_dive(dive); return false; } /* Various libdivecomputer interface fixups */ if (dive->dc.airtemp.mkelvin == 0 && first_temp_is_air && dive->dc.samples) { dive->dc.airtemp = dive->dc.sample[0].temperature; dive->dc.sample[0].temperature.mkelvin = 0; } /* special case for bug in Tecdiving DiveComputer.eu * often the first sample has a water temperature of 0C, followed by the correct * temperature in the next sample */ if (same_string(dive->dc.model, "Tecdiving DiveComputer.eu") && dive->dc.sample[0].temperature.mkelvin == ZERO_C_IN_MKELVIN && dive->dc.sample[1].temperature.mkelvin > dive->dc.sample[0].temperature.mkelvin) dive->dc.sample[0].temperature.mkelvin = dive->dc.sample[1].temperature.mkelvin; record_dive_to_table(dive, devdata->download_table); return true; error_exit: dc_parser_destroy(parser); free_dive(dive); return true; } #ifndef O_BINARY #define O_BINARY 0 #endif static void do_save_fingerprint(device_data_t *devdata, const char *tmp, const char *final) { int fd, written = -1; fd = subsurface_open(tmp, O_WRONLY | O_BINARY | O_CREAT | O_TRUNC, 0666); if (fd < 0) return; if (verbose) dev_info(devdata, "Saving fingerprint for %08x:%08x to '%s'", devdata->fdeviceid, devdata->fdiveid, final); /* The fingerprint itself.. */ written = write(fd, devdata->fingerprint, devdata->fsize); /* ..followed by the device ID and dive ID of the fingerprinted dive */ if (write(fd, &devdata->fdeviceid, 4) != 4 || write(fd, &devdata->fdiveid, 4) != 4) written = -1; /* I'd like to do fsync() here too, but does Windows support it? */ if (close(fd) < 0) written = -1; if (written == devdata->fsize) { if (!subsurface_rename(tmp, final)) return; } unlink(tmp); } static char *fingerprint_file(device_data_t *devdata) { uint32_t model, serial; // Model hash and libdivecomputer 32-bit 'serial number' for the file name model = calculate_string_hash(devdata->model); serial = devdata->devinfo.serial; return format_string("%s/fingerprints/%04x.%u", system_default_directory(), model, serial); } /* * Save the fingerprint after a successful download * * NOTE! At this point, we have the final device ID for the divecomputer * we downloaded from. But that 'deviceid' is actually not useful, because * at the point where we want to _load_ this, we only have the libdivecomputer * DC_EVENT_DEVINFO state (devdata->devinfo). * * Now, we do have the devdata->devinfo at save time, but at load time we * need to verify not only that it's the proper fingerprint file: we also * need to check that we actually have the particular dive that was * associated with that fingerprint state. * * That means that the fingerprint save file needs to include not only the * fingerprint data itself, but also enough data to look up a dive unambiguously * when loading the fingerprint. And the fingerprint data needs to be looked * up using the DC_EVENT_DEVINFO data. * * End result: * * - fingerprint filename depends on the model name and 'devinfo.serial' * so that we can look it up at DC_EVENT_DEVINFO time before the full * info has been parsed. * * - the fingerprint file contains the 'diveid' of the fingerprinted dive, * which is just a hash of the fingerprint itself. * * - we also save the final 'deviceid' in the fingerprint file, so that * looking up the dive associated with the fingerprint is possible. */ static void save_fingerprint(device_data_t *devdata) { char *dir, *tmp, *final; // Don't try to save nonexistent fingerprint data if (!devdata->fingerprint || !devdata->fdiveid) return; // Make sure the fingerprints directory exists dir = format_string("%s/fingerprints", system_default_directory()); subsurface_mkdir(dir); final = fingerprint_file(devdata); tmp = format_string("%s.tmp", final); free(dir); do_save_fingerprint(devdata, tmp, final); free(tmp); free(final); } /* * The fingerprint cache files contain the actual libdivecomputer * fingerprint, followed by 8 bytes of (deviceid,diveid) data. * * Before we use the fingerprint data, verify that we actually * do have that fingerprinted dive. */ static void verify_fingerprint(dc_device_t *device, device_data_t *devdata, const unsigned char *buffer, size_t size) { uint32_t diveid, deviceid; if (size <= 8) return; size -= 8; /* Get the dive ID from the end of the fingerprint cache file.. */ memcpy(&deviceid, buffer + size, 4); memcpy(&diveid, buffer + size + 4, 4); if (verbose) dev_info(devdata, " ... fingerprinted dive %08x:%08x", deviceid, diveid); /* Only use it if we *have* that dive! */ if (!has_dive(deviceid, diveid)) { if (verbose) dev_info(devdata, " ... dive not found"); return; } dc_device_set_fingerprint(device, buffer, size); if (verbose) dev_info(devdata, " ... fingerprint of size %zu", size); } /* * Look up the fingerprint from the fingerprint caches, and * give it to libdivecomputer to avoid downloading already * downloaded dives. */ static void lookup_fingerprint(dc_device_t *device, device_data_t *devdata) { char *cachename; struct memblock mem; const unsigned char *raw_data; if (devdata->force_download) return; /* first try our in memory data - raw_data is owned by the table, the dc_device_set_fingerprint function copies the data */ int fsize = get_fingerprint_data(&fingerprint_table, calculate_string_hash(devdata->model), devdata->devinfo.serial, &raw_data); if (fsize) { if (verbose) dev_info(devdata, "... found fingerprint in dive table"); dc_device_set_fingerprint(device, raw_data, fsize); return; } /* now check if we have a fingerprint on disk */ cachename = fingerprint_file(devdata); if (verbose) dev_info(devdata, "Looking for fingerprint in '%s'", cachename); if (readfile(cachename, &mem) > 0) { if (verbose) dev_info(devdata, " ... got %zu bytes", mem.size); verify_fingerprint(device, devdata, mem.buffer, mem.size); free(mem.buffer); } free(cachename); } static void event_cb(dc_device_t *device, dc_event_type_t event, const void *data, void *userdata) { UNUSED(device); static unsigned int last = 0; const dc_event_progress_t *progress = data; const dc_event_devinfo_t *devinfo = data; const dc_event_clock_t *clock = data; const dc_event_vendor_t *vendor = data; device_data_t *devdata = userdata; switch (event) { case DC_EVENT_WAITING: dev_info(devdata, translate("gettextFromC", "Event: waiting for user action")); break; case DC_EVENT_PROGRESS: /* this seems really dumb... but having no idea what is happening on long * downloads makes people think that the app is hung; * since the progress is in bytes downloaded (usually), simply give updates in 10k increments */ if (progress->current < last) /* this is a new communication with the divecomputer */ last = progress->current; if (progress->current > last + 10240) { last = progress->current; dev_info(NULL, translate("gettextFromC", "read %dkb"), progress->current / 1024); } if (progress->maximum) progress_bar_fraction = (double)progress->current / (double)progress->maximum; break; case DC_EVENT_DEVINFO: if (dc_descriptor_get_model(devdata->descriptor) != devinfo->model) { dc_descriptor_t *better_descriptor = get_descriptor(dc_descriptor_get_type(devdata->descriptor), devinfo->model); if (better_descriptor != NULL) { fprintf(stderr, "EVENT_DEVINFO gave us a different detected product (model %d instead of %d), which we are using now.\n", devinfo->model, dc_descriptor_get_model(devdata->descriptor)); devdata->descriptor = better_descriptor; devdata->product = dc_descriptor_get_product(better_descriptor); devdata->vendor = dc_descriptor_get_vendor(better_descriptor); devdata->model = str_printf("%s %s", devdata->vendor, devdata->product); } else { fprintf(stderr, "EVENT_DEVINFO gave us a different detected product (model %d instead of %d), but that one is unknown.\n", devinfo->model, dc_descriptor_get_model(devdata->descriptor)); } } dev_info(devdata, translate("gettextFromC", "model=%s firmware=%u serial=%u"), devdata->product, devinfo->firmware, devinfo->serial); if (devdata->libdc_logfile) { fprintf(devdata->libdc_logfile, "Event: model=%u (0x%08x), firmware=%u (0x%08x), serial=%u (0x%08x)\n", devinfo->model, devinfo->model, devinfo->firmware, devinfo->firmware, devinfo->serial, devinfo->serial); } devdata->devinfo = *devinfo; lookup_fingerprint(device, devdata); break; case DC_EVENT_CLOCK: dev_info(devdata, translate("gettextFromC", "Event: systime=%" PRId64 ", devtime=%u\n"), (uint64_t)clock->systime, clock->devtime); if (devdata->libdc_logfile) { fprintf(devdata->libdc_logfile, "Event: systime=%" PRId64 ", devtime=%u\n", (uint64_t)clock->systime, clock->devtime); } break; case DC_EVENT_VENDOR: if (devdata->libdc_logfile) { fprintf(devdata->libdc_logfile, "Event: vendor="); for (unsigned int i = 0; i < vendor->size; ++i) fprintf(devdata->libdc_logfile, "%02X", vendor->data[i]); fprintf(devdata->libdc_logfile, "\n"); } break; default: break; } } int import_thread_cancelled; static int cancel_cb(void *userdata) { UNUSED(userdata); return import_thread_cancelled; } static const char *do_device_import(device_data_t *data) { dc_status_t rc; dc_device_t *device = data->device; data->model = str_printf("%s %s", data->vendor, data->product); // Register the event handler. int events = DC_EVENT_WAITING | DC_EVENT_PROGRESS | DC_EVENT_DEVINFO | DC_EVENT_CLOCK | DC_EVENT_VENDOR; rc = dc_device_set_events(device, events, event_cb, data); if (rc != DC_STATUS_SUCCESS) return translate("gettextFromC", "Error registering the event handler."); // Register the cancellation handler. rc = dc_device_set_cancel(device, cancel_cb, data); if (rc != DC_STATUS_SUCCESS) return translate("gettextFromC", "Error registering the cancellation handler."); if (data->libdc_dump) { dc_buffer_t *buffer = dc_buffer_new(0); rc = dc_device_dump(device, buffer); if (rc == DC_STATUS_SUCCESS && dumpfile_name) { FILE *fp = subsurface_fopen(dumpfile_name, "wb"); if (fp != NULL) { fwrite(dc_buffer_get_data(buffer), 1, dc_buffer_get_size(buffer), fp); fclose(fp); } } dc_buffer_free(buffer); } else { rc = dc_device_foreach(device, dive_cb, data); } if (rc != DC_STATUS_SUCCESS) { progress_bar_fraction = 0.0; return translate("gettextFromC", "Dive data import error"); } /* All good */ return NULL; } static dc_timer_t *logfunc_timer = NULL; void logfunc(dc_context_t *context, dc_loglevel_t loglevel, const char *file, unsigned int line, const char *function, const char *msg, void *userdata) { UNUSED(context); const char *loglevels[] = { "NONE", "ERROR", "WARNING", "INFO", "DEBUG", "ALL" }; if (logfunc_timer == NULL) dc_timer_new(&logfunc_timer); FILE *fp = (FILE *)userdata; dc_usecs_t now = 0; dc_timer_now(logfunc_timer, &now); unsigned long seconds = now / 1000000; unsigned long microseconds = now % 1000000; if (loglevel == DC_LOGLEVEL_ERROR || loglevel == DC_LOGLEVEL_WARNING) { fprintf(fp, "[%li.%06li] %s: %s [in %s:%d (%s)]\n", seconds, microseconds, loglevels[loglevel], msg, file, line, function); } else { fprintf(fp, "[%li.%06li] %s: %s\n", seconds, microseconds, loglevels[loglevel], msg); } } char *transport_string[] = { "SERIAL", "USB", "USBHID", "IRDA", "BT", "BLE" }; /* * Get the transports supported by us (as opposed to * the list of transports supported by a particular * dive computer). * * This could have various platform rules too.. */ unsigned int get_supported_transports(device_data_t *data) { #if defined(Q_OS_IOS) // BLE only - don't bother with being clever. return DC_TRANSPORT_BLE; #endif // start out with the list of transports that libdivecomputer claims to support // dc_context_get_transports ignores its context argument... unsigned int supported = dc_context_get_transports(NULL); // then add the ones that we have our own implementations for #if defined(BT_SUPPORT) supported |= DC_TRANSPORT_BLUETOOTH; #endif #if defined(BLE_SUPPORT) supported |= DC_TRANSPORT_BLE; #endif #if defined(Q_OS_ANDROID) // we cannot support transports that need libusb, hid, filesystem access, or IRDA on Android supported &= ~(DC_TRANSPORT_USB | DC_TRANSPORT_USBHID | DC_TRANSPORT_IRDA | DC_TRANSPORT_USBSTORAGE); #endif if (data) { /* * If we have device data available, we can refine this: * We don't support BT or BLE unless bluetooth_mode was set, * and if it was we won't try any of the other transports. */ if (data->bluetooth_mode) { supported &= (DC_TRANSPORT_BLUETOOTH | DC_TRANSPORT_BLE); if (!strncmp(data->devname, "LE:", 3)) supported &= DC_TRANSPORT_BLE; } else { supported &= ~(DC_TRANSPORT_BLUETOOTH | DC_TRANSPORT_BLE); } } return supported; } static dc_status_t usbhid_device_open(dc_iostream_t **iostream, dc_context_t *context, device_data_t *data) { dc_status_t rc; dc_iterator_t *iterator = NULL; dc_usbhid_device_t *device = NULL; // Discover the usbhid device. dc_usbhid_iterator_new (&iterator, context, data->descriptor); while (dc_iterator_next (iterator, &device) == DC_STATUS_SUCCESS) break; dc_iterator_free (iterator); if (!device) { ERROR(context, "didn't find HID device\n"); return DC_STATUS_NODEVICE; } dev_info(data, "Opening USB HID device for %04x:%04x", dc_usbhid_device_get_vid(device), dc_usbhid_device_get_pid(device)); rc = dc_usbhid_open(iostream, context, device); dc_usbhid_device_free(device); return rc; } static dc_status_t usb_device_open(dc_iostream_t **iostream, dc_context_t *context, device_data_t *data) { dc_status_t rc; dc_iterator_t *iterator = NULL; dc_usb_device_t *device = NULL; // Discover the usb device. dc_usb_iterator_new (&iterator, context, data->descriptor); while (dc_iterator_next (iterator, &device) == DC_STATUS_SUCCESS) break; dc_iterator_free (iterator); if (!device) return DC_STATUS_NODEVICE; dev_info(data, "Opening USB device for %04x:%04x", dc_usb_device_get_vid(device), dc_usb_device_get_pid(device)); rc = dc_usb_open(iostream, context, device); dc_usb_device_free(device); return rc; } static dc_status_t irda_device_open(dc_iostream_t **iostream, dc_context_t *context, device_data_t *data) { unsigned int address = 0; dc_iterator_t *iterator = NULL; dc_irda_device_t *device = NULL; // Try to find the IRDA address dc_irda_iterator_new (&iterator, context, data->descriptor); while (dc_iterator_next (iterator, &device) == DC_STATUS_SUCCESS) { address = dc_irda_device_get_address (device); dc_irda_device_free (device); break; } dc_iterator_free (iterator); // If that fails, use the device name. This will // use address 0 if it's not a number. if (!address) address = strtoul(data->devname, NULL, 0); dev_info(data, "Opening IRDA address %u", address); return dc_irda_open(&data->iostream, context, address, 1); } #if defined(BT_SUPPORT) && !defined(__ANDROID__) && !defined(__APPLE__) static dc_status_t bluetooth_device_open(dc_context_t *context, device_data_t *data) { dc_bluetooth_address_t address = 0; dc_iterator_t *iterator = NULL; dc_bluetooth_device_t *device = NULL; // Try to find the rfcomm device address dc_bluetooth_iterator_new (&iterator, context, data->descriptor); while (dc_iterator_next (iterator, &device) == DC_STATUS_SUCCESS) { address = dc_bluetooth_device_get_address (device); dc_bluetooth_device_free (device); break; } dc_iterator_free (iterator); if (!address) { report_error("No rfcomm device found"); return DC_STATUS_NODEVICE; } dev_info(data, "Opening rfcomm address %llu", address); return dc_bluetooth_open(&data->iostream, context, address, 0); } #endif dc_status_t divecomputer_device_open(device_data_t *data) { dc_status_t rc; dc_context_t *context = data->context; unsigned int transports, supported; transports = dc_descriptor_get_transports(data->descriptor); supported = get_supported_transports(data); transports &= supported; if (!transports) { report_error("Dive computer transport not supported"); return DC_STATUS_UNSUPPORTED; } #ifdef BT_SUPPORT if (transports & DC_TRANSPORT_BLUETOOTH) { dev_info(data, "Opening rfcomm stream %s", data->devname); #if defined(__ANDROID__) || defined(__APPLE__) // we don't have BT on iOS in the first place, so this is for Android and macOS rc = rfcomm_stream_open(&data->iostream, context, data->devname); #else rc = bluetooth_device_open(context, data); #endif if (rc == DC_STATUS_SUCCESS) return rc; } #endif #ifdef BLE_SUPPORT if (transports & DC_TRANSPORT_BLE) { dev_info(data, "Connecting to BLE device %s", data->devname); rc = ble_packet_open(&data->iostream, context, data->devname, data); if (rc == DC_STATUS_SUCCESS) return rc; } #endif if (transports & DC_TRANSPORT_USBHID) { dev_info(data, "Connecting to USB HID device"); rc = usbhid_device_open(&data->iostream, context, data); if (rc == DC_STATUS_SUCCESS) return rc; } if (transports & DC_TRANSPORT_USB) { dev_info(data, "Connecting to native USB device"); rc = usb_device_open(&data->iostream, context, data); if (rc == DC_STATUS_SUCCESS) return rc; } if (transports & DC_TRANSPORT_SERIAL) { dev_info(data, "Opening serial device %s", data->devname); #ifdef SERIAL_FTDI if (!strcasecmp(data->devname, "ftdi")) return ftdi_open(&data->iostream, context); #endif #ifdef __ANDROID__ if (data->androidUsbDeviceDescriptor) return serial_usb_android_open(&data->iostream, context, data->androidUsbDeviceDescriptor); #endif rc = dc_serial_open(&data->iostream, context, data->devname); if (rc == DC_STATUS_SUCCESS) return rc; } if (transports & DC_TRANSPORT_IRDA) { dev_info(data, "Connecting to IRDA device"); rc = irda_device_open(&data->iostream, context, data); if (rc == DC_STATUS_SUCCESS) return rc; } if (transports & DC_TRANSPORT_USBSTORAGE) { dev_info(data, "Opening USB storage at %s", data->devname); rc = dc_usb_storage_open(&data->iostream, context, data->devname); if (rc == DC_STATUS_SUCCESS) return rc; } return DC_STATUS_UNSUPPORTED; } const char *do_libdivecomputer_import(device_data_t *data) { dc_status_t rc; const char *err; FILE *fp = NULL; import_dive_number = 0; first_temp_is_air = 0; data->device = NULL; data->context = NULL; data->iostream = NULL; data->fingerprint = NULL; data->fsize = 0; if (data->libdc_log && logfile_name) fp = subsurface_fopen(logfile_name, "w"); data->libdc_logfile = fp; rc = dc_context_new(&data->context); if (rc != DC_STATUS_SUCCESS) return translate("gettextFromC", "Unable to create libdivecomputer context"); if (fp) { dc_context_set_loglevel(data->context, DC_LOGLEVEL_ALL); dc_context_set_logfunc(data->context, logfunc, fp); fprintf(data->libdc_logfile, "Subsurface: v%s, ", subsurface_git_version()); fprintf(data->libdc_logfile, "built with libdivecomputer v%s\n", dc_version(NULL)); } err = translate("gettextFromC", "Unable to open %s %s (%s)"); rc = divecomputer_device_open(data); if (rc != DC_STATUS_SUCCESS) { report_error(errmsg(rc)); } else { dev_info(data, "Connecting ..."); rc = dc_device_open(&data->device, data->context, data->descriptor, data->iostream); INFO(0, "dc_device_open error value of %d", rc); if (rc != DC_STATUS_SUCCESS && subsurface_access(data->devname, R_OK | W_OK) != 0) #if defined(SUBSURFACE_MOBILE) err = translate("gettextFromC", "Error opening the device %s %s (%s).\nIn most cases, in order to debug this issue, it is useful to send the developers the log files. You can copy them to the clipboard in the About dialog."); #else err = translate("gettextFromC", "Error opening the device %s %s (%s).\nIn most cases, in order to debug this issue, a libdivecomputer logfile will be useful.\nYou can create this logfile by selecting the corresponding checkbox in the download dialog."); #endif if (rc == DC_STATUS_SUCCESS) { dev_info(data, "Starting import ..."); err = do_device_import(data); /* TODO: Show the logfile to the user on error. */ dc_device_close(data->device); data->device = NULL; if (!data->download_table->nr) dev_info(data, translate("gettextFromC", "No new dives downloaded from dive computer")); } dc_iostream_close(data->iostream); data->iostream = NULL; } dc_context_free(data->context); data->context = NULL; if (fp) { fclose(fp); } /* * Note that we save the fingerprint unconditionally. * This is ok because we only have fingerprint data if * we got a dive header, and because we will use the * dive id to verify that we actually have the dive * it refers to before we use the fingerprint data. * * For now we save the fingerprint both to the local file system * and to the global fingerprint table (to be then saved out with * the dive log data). */ save_fingerprint(data); if (data->fingerprint && data->fdiveid) create_fingerprint_node(&fingerprint_table, calculate_string_hash(data->model), data->devinfo.serial, data->fingerprint, data->fsize, data->fdeviceid, data->fdiveid); free(data->fingerprint); data->fingerprint = NULL; return err; } /* * Parse data buffers instead of dc devices downloaded data. * Intended to be used to parse profile data from binary files during import tasks. * Actually included Uwatec families because of works on datatrak and smartrak logs * and OSTC families for OSTCTools logs import. * For others, simply include them in the switch (check parameters). * Note that dc_descriptor_t in data *must* have been filled using dc_descriptor_iterator() * calls. */ dc_status_t libdc_buffer_parser(struct dive *dive, device_data_t *data, unsigned char *buffer, int size) { dc_status_t rc; dc_parser_t *parser = NULL; switch (dc_descriptor_get_type(data->descriptor)) { case DC_FAMILY_UWATEC_ALADIN: case DC_FAMILY_UWATEC_MEMOMOUSE: case DC_FAMILY_UWATEC_SMART: case DC_FAMILY_UWATEC_MERIDIAN: case DC_FAMILY_HW_OSTC: case DC_FAMILY_HW_FROG: case DC_FAMILY_HW_OSTC3: rc = dc_parser_new2(&parser, data->context, data->descriptor, 0, 0); break; default: report_error("Device type not handled!"); return DC_STATUS_UNSUPPORTED; } if (rc != DC_STATUS_SUCCESS) { report_error("Error creating parser."); dc_parser_destroy (parser); return rc; } rc = dc_parser_set_data(parser, buffer, size); if (rc != DC_STATUS_SUCCESS) { report_error("Error registering the data."); dc_parser_destroy (parser); return rc; } // Do not parse Aladin/Memomouse headers as they are fakes // Do not return on error, we can still parse the samples if (dc_descriptor_get_type(data->descriptor) != DC_FAMILY_UWATEC_ALADIN && dc_descriptor_get_type(data->descriptor) != DC_FAMILY_UWATEC_MEMOMOUSE) { rc = libdc_header_parser (parser, data, dive); if (rc != DC_STATUS_SUCCESS) { report_error("Error parsing the dive header data. Dive # %d\nStatus = %s", dive->number, errmsg(rc)); } } rc = dc_parser_samples_foreach (parser, sample_cb, &dive->dc); if (rc != DC_STATUS_SUCCESS) { report_error("Error parsing the sample data. Dive # %d\nStatus = %s", dive->number, errmsg(rc)); dc_parser_destroy (parser); return rc; } dc_parser_destroy(parser); return DC_STATUS_SUCCESS; } /* * Returns a dc_descriptor_t structure based on dc model's number and family. * * That dc_descriptor_t needs to be freed with dc_descriptor_free by the reciver. */ dc_descriptor_t *get_descriptor(dc_family_t type, unsigned int model) { dc_descriptor_t *descriptor = NULL, *needle = NULL; dc_iterator_t *iterator = NULL; dc_status_t rc; rc = dc_descriptor_iterator(&iterator); if (rc != DC_STATUS_SUCCESS) { fprintf(stderr, "Error creating the device descriptor iterator.\n"); return NULL; } while ((dc_iterator_next(iterator, &descriptor)) == DC_STATUS_SUCCESS) { unsigned int desc_model = dc_descriptor_get_model(descriptor); dc_family_t desc_type = dc_descriptor_get_type(descriptor); if (model == desc_model && type == desc_type) { needle = descriptor; break; } dc_descriptor_free(descriptor); } dc_iterator_free(iterator); return needle; }
subsurface-for-dirk-master
core/libdivecomputer.c
// SPDX-License-Identifier: GPL-2.0 #ifdef __clang__ // Clang has a bug on zero-initialization of C structs. #pragma clang diagnostic ignored "-Wmissing-field-initializers" #endif #include "qthelper.h" #include "ssrf.h" #include "dive.h" #include "sample.h" #include "subsurface-string.h" #include "parse.h" #include "divelist.h" #include "device.h" #include "membuffer.h" #include "gettext.h" #include "tag.h" #include "errorhelper.h" #include <string.h> #include "divecomputer.h" /* Process gas change event for seac database. * Create gas change event at the time of the * current sample. */ static int seac_gaschange(void *param, sqlite3_stmt *sqlstmt) { struct parser_state *state = (struct parser_state *)param; event_start(state); state->cur_event.time.seconds = sqlite3_column_int(sqlstmt, 1); strcpy(state->cur_event.name, "gaschange"); state->cur_event.gas.mix.o2.permille = 10 * sqlite3_column_int(sqlstmt, 4); event_end(state); return 0; } /* Callback function to parse seac dives. Reads headers_dive table to read dive * information into divecomputer struct. */ static int seac_dive(void *param, int columns, char **data, char **column) { UNUSED(columns); UNUSED(column); int retval = 0, cylnum = 0; int year, month, day, hour, min, sec, tz; char isodatetime[30]; time_t divetime; struct gasmix lastgas, curgas; struct parser_state *state = (struct parser_state *)param; sqlite3 *handle = state->sql_handle; sqlite3_stmt *sqlstmt; const char *get_samples = "SELECT dive_number, runtime_s, depth_cm, temperature_mCx10, active_O2_fr, first_stop_depth_cm, first_stop_time_s, ndl_tts_s, cns, gf_l, gf_h FROM dive_data WHERE dive_number = ? AND dive_id = ? ORDER BY runtime_s ASC"; /* 0 = dive_number * 1 = runtime_s * 2 = depth_cm * 3 = temperature_mCx10 - eg dC * 4 = active_O2_fr * 5 = first_stop_depth_cm * 6 = first_stop_time_s * 7 = ndl_tts_s * 8 = cns * 9 = gf-l * 10 = gf-h */ dive_start(state); state->cur_dive->number = atoi(data[0]); // Create first cylinder cylinder_t *curcyl = get_or_create_cylinder(state->cur_dive, 0); // Get time and date sscanf(data[2], "%d/%d/%2d", &day, &month, &year); sscanf(data[4], "%2d:%2d:%2d", &hour, &min, &sec); year += 2000; tz = atoi(data[3]); // Timezone offset lookup array const char timezoneoffset[][7] = {"+12:00", // 0 "+11:00", // 1 "+10:00", // 2 "+09:30", // 3 "+09:00", // 4 "+08:00", // 5 "+07:00", // 6 "+06:00", // 7 "+05:00", // 8 "+04:30", // 9 "+04:00", // 10 "+03:30", // 11 "+03:00", // 12 "+02:00", // 13 "+01:00", // 14 "+00:00", // 15 "-01:00", // 16 "-02:00", // 17 "-03:00", // 18 "-03:30", // 19 "-04:00", // 20 "-04:30", // 21 "-05:00", // 22 "-05:30", // 23 "-05:45", // 24 "-06:00", // 25 "-06:30", // 26 "-07:00", // 27 "-08:00", // 28 "-08:45", // 29 "-09:00", // 30 "-09:30", // 31 "-09:45", // 32 "-10:00", // 33 "-10:30", // 34 "-11:00", // 35 "-11:30", // 36 "-12:00", // 37 "-12:45", // 38 "-13:00", // 39 "-13:45", // 40 "-14:00"}; // 41 sprintf(isodatetime, "%4i-%02i-%02iT%02i:%02i:%02i%6s", year, month, day, hour, min, sec, timezoneoffset[tz]); divetime = get_dive_datetime_from_isostring(isodatetime); state->cur_dive->when = divetime; // 6 = dive_type // Dive type 2? if (data[6]) { switch (atoi(data[6])) { case 1: state->cur_dive->dc.divemode = OC; break; // Gauge Mode case 2: state->cur_dive->dc.divemode = UNDEF_COMP_TYPE; break; case 3: state->cur_dive->dc.divemode = FREEDIVE; break; default: if (verbose) { fprintf(stderr, "Unknown divetype %i", atoi(data[6])); } } } // 9 = comments from seac app if (data[9]) { utf8_string(data[9], &state->cur_dive->notes); } // 10 = dive duration if (data[10]) { state->cur_dive->dc.duration.seconds = atoi(data[10]); } // 8 = water_type /* TODO: Seac only offers fresh / salt, and doesn't * seem to record correctly currently. I have both * fresh and saltwater dives and water type is reported * as 150 for both. */ if (data[8]) { switch (atoi(data[8])) { case 150: state->cur_dive->salinity = 0; break; case 100: state->cur_dive->salinity = 1; break; default: if (verbose) { fprintf(stderr, "Unknown salinity %i", atoi(data[8])); } } } if (data[11]) { state->cur_dive->dc.maxdepth.mm = 10 * atoi(data[11]); } // Create sql_stmt type to query DB retval = sqlite3_prepare_v2(handle, get_samples, -1, &sqlstmt, 0); if (retval != SQLITE_OK) { fprintf(stderr, "%s", "Preparing SQL object failed when getting SeacSync dives.\n"); return 1; } // Bind current dive number to sql statement sqlite3_bind_int(sqlstmt, 1, state->cur_dive->number); sqlite3_bind_int(sqlstmt, 2, atoi(data[13])); // Catch a bad query retval = sqlite3_step(sqlstmt); if (retval == SQLITE_ERROR) { fprintf(stderr, "%s", "Getting dive data from SeacSync DB failed.\n"); return 1; } settings_start(state); dc_settings_start(state); utf8_string(data[1], &state->cur_dive->dc.serial); utf8_string(data[12], &state->cur_dive->dc.fw_version); state->cur_dive->dc.model = strdup("Seac Action"); state->cur_dive->dc.deviceid = calculate_string_hash(data[1]); add_extra_data(&state->cur_dive->dc, "GF-Lo", (const char*)sqlite3_column_text(sqlstmt, 9)); add_extra_data(&state->cur_dive->dc, "GF-Hi", (const char*)sqlite3_column_text(sqlstmt, 10)); dc_settings_end(state); settings_end(state); if (data[11]) { state->cur_dive->dc.maxdepth.mm = 10 * atoi(data[11]); } curcyl->gasmix.o2.permille = 10 * sqlite3_column_int(sqlstmt, 4); // Track gasses to tell when switch occurs lastgas = curcyl->gasmix; curgas = curcyl->gasmix; // Read samples while (retval == SQLITE_ROW) { sample_start(state); state->cur_sample->time.seconds = sqlite3_column_int(sqlstmt, 1); state->cur_sample->depth.mm = 10 * sqlite3_column_int(sqlstmt, 2); state->cur_sample->temperature.mkelvin = cC_to_mkelvin(sqlite3_column_int(sqlstmt, 3)); curgas.o2.permille = 10 * sqlite3_column_int(sqlstmt, 4); if (!same_gasmix(lastgas, curgas)) { seac_gaschange(state, sqlstmt); lastgas = curgas; cylnum ^= 1; // Only need to toggle between two cylinders curcyl = get_or_create_cylinder(state->cur_dive, cylnum); curcyl->gasmix.o2.permille = 10 * sqlite3_column_int(sqlstmt, 4); } state->cur_sample->stopdepth.mm = 10 * sqlite3_column_int(sqlstmt, 5); state->cur_sample->stoptime.seconds = sqlite3_column_int(sqlstmt, 6); state->cur_sample->ndl.seconds = sqlite3_column_int(sqlstmt, 7); state->cur_sample->cns = sqlite3_column_int(sqlstmt, 8); sample_end(state); retval = sqlite3_step(sqlstmt); } sqlite3_finalize(sqlstmt); dive_end(state); return SQLITE_OK; } /** Read SeacSync divesDB.db sqlite3 database into dive and samples. * * Each row returned in the query of headers_dive creates a new dive. * The callback function performs another SQL query on the other * table, to read in the sample values. */ int parse_seac_buffer(sqlite3 *handle, const char *url, const char *buffer, int size, struct dive_table *table, struct trip_table *trips, struct dive_site_table *sites, struct device_table *devices) { UNUSED(buffer); UNUSED(size); int retval; char *err = NULL; struct parser_state state; init_parser_state(&state); state.target_table = table; state.trips = trips; state.sites = sites; state.devices = devices; state.sql_handle = handle; const char *get_dives = "SELECT dive_number, device_sn, date, timezone, time, elapsed_surface_time, dive_type, start_mode, water_type, comment, total_dive_time, max_depth, firmware_version, dive_id FROM headers_dive"; /* 0 = dive_number * 1 = device_sn * 2 = date * 3 = timezone * 4 = time * 5 = elapsed_surface_time * 6 = dive_type * 7 = start_mode * 8 = water_type * 9 = comment * 10 = total_dive_time * 11 = max_depth * 12 = firmware version * 13 = dive_id */ retval = sqlite3_exec(handle, get_dives, &seac_dive, &state, &err); free_parser_state(&state); if (retval != SQLITE_OK) { fprintf(stderr, "Database query failed '%s'.\n", url); return 1; } return 0; }
subsurface-for-dirk-master
core/import-seac.c
/* * SHA1 routine optimized to do word accesses rather than byte accesses, * and to avoid unnecessary copies into the context array. * * This was initially based on the Mozilla SHA1 implementation, although * none of the original Mozilla code remains. */ /* this is only to get definitions for memcpy(), ntohl() and htonl() */ #include <string.h> #include <stdint.h> #ifdef WIN32 #include <winsock2.h> #else #include <arpa/inet.h> #endif #include "sha1.h" #if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) /* * Force usage of rol or ror by selecting the one with the smaller constant. * It _can_ generate slightly smaller code (a constant of 1 is special), but * perhaps more importantly it's possibly faster on any uarch that does a * rotate with a loop. */ #define SHA_ASM(op, x, n) ({ unsigned int __res; __asm__(op " %1,%0":"=r" (__res):"i" (n), "0" (x)); __res; }) #define SHA_ROL(x, n) SHA_ASM("rol", x, n) #define SHA_ROR(x, n) SHA_ASM("ror", x, n) #else #define SHA_ROT(X, l, r) (((X) << (l)) | ((X) >> (r))) #define SHA_ROL(X, n) SHA_ROT(X, n, 32 - (n)) #define SHA_ROR(X, n) SHA_ROT(X, 32 - (n), n) #endif /* * If you have 32 registers or more, the compiler can (and should) * try to change the array[] accesses into registers. However, on * machines with less than ~25 registers, that won't really work, * and at least gcc will make an unholy mess of it. * * So to avoid that mess which just slows things down, we force * the stores to memory to actually happen (we might be better off * with a 'W(t)=(val);asm("":"+m" (W(t))' there instead, as * suggested by Artur Skawina - that will also make gcc unable to * try to do the silly "optimize away loads" part because it won't * see what the value will be). * * Ben Herrenschmidt reports that on PPC, the C version comes close * to the optimized asm with this (ie on PPC you don't want that * 'volatile', since there are lots of registers). * * On ARM we get the best code generation by forcing a full memory barrier * between each SHA_ROUND, otherwise gcc happily get wild with spilling and * the stack frame size simply explode and performance goes down the drain. */ #if defined(__i386__) || defined(__x86_64__) #define setW(x, val) (*(volatile unsigned int *)&W(x) = (val)) #elif defined(__GNUC__) && defined(__arm__) #define setW(x, val) \ do { \ W(x) = (val); \ __asm__("" :: : "memory"); \ } while (0) #else #define setW(x, val) (W(x) = (val)) #endif /* * Performance might be improved if the CPU architecture is OK with * unaligned 32-bit loads and a fast ntohl() is available. * Otherwise fall back to byte loads and shifts which is portable, * and is faster on architectures with memory alignment issues. */ #if defined(__i386__) || defined(__x86_64__) || \ defined(_M_IX86) || defined(_M_X64) || \ defined(__ppc__) || defined(__ppc64__) || \ defined(__powerpc__) || defined(__powerpc64__) || \ defined(__s390__) || defined(__s390x__) #define get_be32(p) ntohl(*(unsigned int *)(p)) #define put_be32(p, v) \ do { \ *(unsigned int *)(p) = htonl(v); \ } while (0) #else #define get_be32(p) ( \ (*((unsigned char *)(p) + 0) << 24) | \ (*((unsigned char *)(p) + 1) << 16) | \ (*((unsigned char *)(p) + 2) << 8) | \ (*((unsigned char *)(p) + 3) << 0)) #define put_be32(p, v) \ do { \ unsigned int __v = (v); \ *((unsigned char *)(p) + 0) = __v >> 24; \ *((unsigned char *)(p) + 1) = __v >> 16; \ *((unsigned char *)(p) + 2) = __v >> 8; \ *((unsigned char *)(p) + 3) = __v >> 0; \ } while (0) #endif /* This "rolls" over the 512-bit array */ #define W(x) (array[(x) & 15]) /* * Where do we get the source from? The first 16 iterations get it from * the input data, the next mix it from the 512-bit array. */ #define SHA_SRC(t) get_be32((unsigned char *)block + (t) * 4) #define SHA_MIX(t) SHA_ROL(W((t) + 13) ^ W((t) + 8) ^ W((t) + 2) ^ W(t), 1); #define SHA_ROUND(t, input, fn, constant, A, B, C, D, E) \ do { \ unsigned int TEMP = input(t); \ setW(t, TEMP); \ E += TEMP + SHA_ROL(A, 5) + (fn) + (constant); \ B = SHA_ROR(B, 2); \ } while (0) #define T_0_15(t, A, B, C, D, E) SHA_ROUND(t, SHA_SRC, (((C ^ D) & B) ^ D), 0x5a827999, A, B, C, D, E) #define T_16_19(t, A, B, C, D, E) SHA_ROUND(t, SHA_MIX, (((C ^ D) & B) ^ D), 0x5a827999, A, B, C, D, E) #define T_20_39(t, A, B, C, D, E) SHA_ROUND(t, SHA_MIX, (B ^ C ^ D), 0x6ed9eba1, A, B, C, D, E) #define T_40_59(t, A, B, C, D, E) SHA_ROUND(t, SHA_MIX, ((B &C) + (D &(B ^ C))), 0x8f1bbcdc, A, B, C, D, E) #define T_60_79(t, A, B, C, D, E) SHA_ROUND(t, SHA_MIX, (B ^ C ^ D), 0xca62c1d6, A, B, C, D, E) static void blk_SHA1_Block(blk_SHA_CTX *ctx, const void *block) { unsigned int A, B, C, D, E; unsigned int array[16]; A = ctx->H[0]; B = ctx->H[1]; C = ctx->H[2]; D = ctx->H[3]; E = ctx->H[4]; /* Round 1 - iterations 0-16 take their input from 'block' */ T_0_15(0, A, B, C, D, E); T_0_15(1, E, A, B, C, D); T_0_15(2, D, E, A, B, C); T_0_15(3, C, D, E, A, B); T_0_15(4, B, C, D, E, A); T_0_15(5, A, B, C, D, E); T_0_15(6, E, A, B, C, D); T_0_15(7, D, E, A, B, C); T_0_15(8, C, D, E, A, B); T_0_15(9, B, C, D, E, A); T_0_15(10, A, B, C, D, E); T_0_15(11, E, A, B, C, D); T_0_15(12, D, E, A, B, C); T_0_15(13, C, D, E, A, B); T_0_15(14, B, C, D, E, A); T_0_15(15, A, B, C, D, E); /* Round 1 - tail. Input from 512-bit mixing array */ T_16_19(16, E, A, B, C, D); T_16_19(17, D, E, A, B, C); T_16_19(18, C, D, E, A, B); T_16_19(19, B, C, D, E, A); /* Round 2 */ T_20_39(20, A, B, C, D, E); T_20_39(21, E, A, B, C, D); T_20_39(22, D, E, A, B, C); T_20_39(23, C, D, E, A, B); T_20_39(24, B, C, D, E, A); T_20_39(25, A, B, C, D, E); T_20_39(26, E, A, B, C, D); T_20_39(27, D, E, A, B, C); T_20_39(28, C, D, E, A, B); T_20_39(29, B, C, D, E, A); T_20_39(30, A, B, C, D, E); T_20_39(31, E, A, B, C, D); T_20_39(32, D, E, A, B, C); T_20_39(33, C, D, E, A, B); T_20_39(34, B, C, D, E, A); T_20_39(35, A, B, C, D, E); T_20_39(36, E, A, B, C, D); T_20_39(37, D, E, A, B, C); T_20_39(38, C, D, E, A, B); T_20_39(39, B, C, D, E, A); /* Round 3 */ T_40_59(40, A, B, C, D, E); T_40_59(41, E, A, B, C, D); T_40_59(42, D, E, A, B, C); T_40_59(43, C, D, E, A, B); T_40_59(44, B, C, D, E, A); T_40_59(45, A, B, C, D, E); T_40_59(46, E, A, B, C, D); T_40_59(47, D, E, A, B, C); T_40_59(48, C, D, E, A, B); T_40_59(49, B, C, D, E, A); T_40_59(50, A, B, C, D, E); T_40_59(51, E, A, B, C, D); T_40_59(52, D, E, A, B, C); T_40_59(53, C, D, E, A, B); T_40_59(54, B, C, D, E, A); T_40_59(55, A, B, C, D, E); T_40_59(56, E, A, B, C, D); T_40_59(57, D, E, A, B, C); T_40_59(58, C, D, E, A, B); T_40_59(59, B, C, D, E, A); /* Round 4 */ T_60_79(60, A, B, C, D, E); T_60_79(61, E, A, B, C, D); T_60_79(62, D, E, A, B, C); T_60_79(63, C, D, E, A, B); T_60_79(64, B, C, D, E, A); T_60_79(65, A, B, C, D, E); T_60_79(66, E, A, B, C, D); T_60_79(67, D, E, A, B, C); T_60_79(68, C, D, E, A, B); T_60_79(69, B, C, D, E, A); T_60_79(70, A, B, C, D, E); T_60_79(71, E, A, B, C, D); T_60_79(72, D, E, A, B, C); T_60_79(73, C, D, E, A, B); T_60_79(74, B, C, D, E, A); T_60_79(75, A, B, C, D, E); T_60_79(76, E, A, B, C, D); T_60_79(77, D, E, A, B, C); T_60_79(78, C, D, E, A, B); T_60_79(79, B, C, D, E, A); ctx->H[0] += A; ctx->H[1] += B; ctx->H[2] += C; ctx->H[3] += D; ctx->H[4] += E; } void blk_SHA1_Init(blk_SHA_CTX *ctx) { ctx->size = 0; /* Initialize H with the magic constants (see FIPS180 for constants) */ ctx->H[0] = 0x67452301; ctx->H[1] = 0xefcdab89; ctx->H[2] = 0x98badcfe; ctx->H[3] = 0x10325476; ctx->H[4] = 0xc3d2e1f0; } void blk_SHA1_Update(blk_SHA_CTX *ctx, const void *data, unsigned long len) { unsigned int lenW = ctx->size & 63; ctx->size += len; /* Read the data into W and process blocks as they get full */ if (lenW) { unsigned int left = 64 - lenW; if (len < left) left = len; memcpy(lenW + (char *)ctx->W, data, left); lenW = (lenW + left) & 63; len -= left; data = ((const char *)data + left); if (lenW) return; blk_SHA1_Block(ctx, ctx->W); } while (len >= 64) { blk_SHA1_Block(ctx, data); data = ((const char *)data + 64); len -= 64; } if (len) memcpy(ctx->W, data, len); } void blk_SHA1_Final(unsigned char hashout[20], blk_SHA_CTX *ctx) { static const unsigned char pad[64] = { 0x80 }; unsigned int padlen[2]; int i; /* Pad with a binary 1 (ie 0x80), then zeroes, then length */ padlen[0] = htonl((uint32_t)(ctx->size >> 29)); padlen[1] = htonl((uint32_t)(ctx->size << 3)); i = ctx->size & 63; blk_SHA1_Update(ctx, pad, 1 + (63 & (55 - i))); blk_SHA1_Update(ctx, padlen, 8); /* Output hash */ for (i = 0; i < 5; i++) put_be32(hashout + i * 4, ctx->H[i]); }
subsurface-for-dirk-master
core/sha1.c
// SPDX-License-Identifier: GPL-2.0 /* divelist.c */ #include "divelist.h" #include "subsurface-string.h" #include "deco.h" #include "device.h" #include "divesite.h" #include "dive.h" #include "event.h" #include "filterpreset.h" #include "fulltext.h" #include "interpolate.h" #include "planner.h" #include "qthelper.h" #include "gettext.h" #include "git-access.h" #include "selection.h" #include "sample.h" #include "table.h" #include "trip.h" bool autogroup = false; void set_autogroup(bool value) { /* if we keep the UI paradigm, this needs to toggle * the checkbox on the autogroup menu item */ autogroup = value; } /* * Get "maximal" dive gas for a dive. * Rules: * - Trimix trumps nitrox (highest He wins, O2 breaks ties) * - Nitrox trumps air (even if hypoxic) * These are the same rules as the inter-dive sorting rules. */ void get_dive_gas(const struct dive *dive, int *o2_p, int *he_p, int *o2max_p) { int i; int maxo2 = -1, maxhe = -1, mino2 = 1000; for (i = 0; i < dive->cylinders.nr; i++) { const cylinder_t *cyl = get_cylinder(dive, i); int o2 = get_o2(cyl->gasmix); int he = get_he(cyl->gasmix); if (!is_cylinder_used(dive, i)) continue; if (o2 > maxo2) maxo2 = o2; if (he > maxhe) goto newmax; if (he < maxhe) continue; if (o2 <= maxo2) continue; newmax: maxhe = he; mino2 = o2; } /* All air? Show/sort as "air"/zero */ if ((!maxhe && maxo2 == O2_IN_AIR && mino2 == maxo2) || (maxo2 == -1 && maxhe == -1 && mino2 == 1000)) maxo2 = mino2 = 0; *o2_p = mino2; *he_p = maxhe; *o2max_p = maxo2; } int total_weight(const struct dive *dive) { int i, total_grams = 0; if (dive) for (i = 0; i < dive->weightsystems.nr; i++) total_grams += dive->weightsystems.weightsystems[i].weight.grams; return total_grams; } static int active_o2(const struct dive *dive, const struct divecomputer *dc, duration_t time) { struct gasmix gas = get_gasmix_at_time(dive, dc, time); return get_o2(gas); } // Do not call on first sample as it acccesses the previous sample static int get_sample_o2(const struct dive *dive, const struct divecomputer *dc, const struct sample *sample) { int po2i, po2f, po2; const struct sample *psample = sample - 1; // Use sensor[0] if available if ((dc->divemode == CCR || dc->divemode == PSCR) && sample->o2sensor[0].mbar) { po2i = psample->o2sensor[0].mbar; po2f = sample->o2sensor[0].mbar; // then use data from the first o2 sensor po2 = (po2f + po2i) / 2; } else if (sample->setpoint.mbar > 0) { po2 = MIN((int) sample->setpoint.mbar, depth_to_mbar(sample->depth.mm, dive)); } else { double amb_presure = depth_to_bar(sample->depth.mm, dive); double pamb_pressure = depth_to_bar(psample->depth.mm , dive); if (dc->divemode == PSCR) { po2i = pscr_o2(pamb_pressure, get_gasmix_at_time(dive, dc, psample->time)); po2f = pscr_o2(amb_presure, get_gasmix_at_time(dive, dc, sample->time)); } else { int o2 = active_o2(dive, dc, psample->time); // ... calculate po2 from depth and FiO2. po2i = lrint(o2 * pamb_pressure); // (initial) po2 at start of segment po2f = lrint(o2 * amb_presure); // (final) po2 at end of segment } po2 = (po2i + po2f) / 2; } return po2; } /* Calculate OTU for a dive - this only takes the first divecomputer into account. Implement the protocol in Erik Baker's document "Oxygen Toxicity Calculations". This code implements a third-order continuous approximation of Baker's Eq. 2 and enables OTU calculation for rebreathers. Baker obtained his information from: Comroe Jr. JH et al. (1945) Oxygen toxicity. J. Am. Med. Assoc. 128,710-717 Clark JM & CJ Lambertsen (1970) Pulmonary oxygen tolerance in man and derivation of pulmonary oxygen tolerance curves. Inst. env. Med. Report 1-70, University of Pennsylvania, Philadelphia, USA. */ static int calculate_otu(const struct dive *dive) { int i; double otu = 0.0; const struct divecomputer *dc = &dive->dc; for (i = 1; i < dc->samples; i++) { int t; int po2i, po2f; double pm; struct sample *sample = dc->sample + i; struct sample *psample = sample - 1; t = sample->time.seconds - psample->time.seconds; // if there is sensor data use sensor[0] if ((dc->divemode == CCR || dc->divemode == PSCR) && sample->o2sensor[0].mbar) { po2i = psample->o2sensor[0].mbar; po2f = sample->o2sensor[0].mbar; // ... use data from the first o2 sensor } else { if (sample->setpoint.mbar > 0) { po2f = MIN((int) sample->setpoint.mbar, depth_to_mbar(sample->depth.mm, dive)); if (psample->setpoint.mbar > 0) po2i = MIN((int) psample->setpoint.mbar, depth_to_mbar(psample->depth.mm, dive)); else po2i = po2f; } else { // For OC and rebreather without o2 sensor/setpoint double amb_presure = depth_to_bar(sample->depth.mm, dive); double pamb_pressure = depth_to_bar(psample->depth.mm , dive); if (dc->divemode == PSCR) { po2i = pscr_o2(pamb_pressure, get_gasmix_at_time(dive, dc, psample->time)); po2f = pscr_o2(amb_presure, get_gasmix_at_time(dive, dc, sample->time)); } else { int o2 = active_o2(dive, dc, psample->time); // ... calculate po2 from depth and FiO2. po2i = lrint(o2 * pamb_pressure); // (initial) po2 at start of segment po2f = lrint(o2 * amb_presure); // (final) po2 at end of segment } } } if ((po2i > 500) || (po2f > 500)) { // If PO2 in segment is above 500 mbar then calculate otu if (po2i <= 500) { // For descent segment with po2i <= 500 mbar .. t = t * (po2f - 500) / (po2f - po2i); // .. only consider part with PO2 > 500 mbar po2i = 501; // Mostly important for the dive planner with long segments } else { if (po2f <= 500){ t = t * (po2i - 500) / (po2i - po2f); // For ascent segment with po2f <= 500 mbar .. po2f = 501; // .. only consider part with PO2 > 500 mbar } } pm = (po2f + po2i)/1000.0 - 1.0; // This is a 3rd order continuous approximation of Baker's eq. 2, therefore Baker's eq. 1 is not used: otu += t / 60.0 * pow(pm, 5.0/6.0) * (1.0 - 5.0 * (po2f - po2i) * (po2f - po2i) / 216000000.0 / (pm * pm)); } } return lrint(otu); } /* Calculate the CNS for a single dive - this only takes the first divecomputer into account. The CNS contributions are summed for dive segments defined by samples. The maximum O2 exposure duration for each segment is calculated based on the mean depth of the two samples (start & end) that define each segment. The CNS contribution of each segment is found by dividing the time duration of the segment by its maximum exposure duration. The contributions of all segments of the dive are summed to get the total CNS% value. This is a partial implementation of the proposals in Erik Baker's document "Oxygen Toxicity Calculations" using fixed-depth calculations for the mean po2 for each segment. Empirical testing showed that, for large changes in depth, the cns calculation for the mean po2 value is extremely close, if not identical to the additive calculations for 0.1 bar increments in po2 from the start to the end of the segment, assuming a constant rate of change in po2 (i.e. depth) with time. */ static double calculate_cns_dive(const struct dive *dive) { int n; const struct divecomputer *dc = &dive->dc; double cns = 0.0; double rate; /* Calculate the CNS for each sample in this dive and sum them */ for (n = 1; n < dc->samples; n++) { int t; int po2; struct sample *sample = dc->sample + n; struct sample *psample = sample - 1; t = sample->time.seconds - psample->time.seconds; po2 = get_sample_o2(dive, dc, sample); /* Don't increase CNS when po2 below 500 matm */ if (po2 <= 500) continue; // This formula is the result of fitting two lines to the Log of the NOAA CNS table rate = po2 <= 1500 ? exp(-11.7853 + 0.00193873 * po2) : exp(-23.6349 + 0.00980829 * po2); cns += (double) t * rate * 100.0; } return cns; } /* this only gets called if dive->maxcns == 0 which means we know that * none of the divecomputers has tracked any CNS for us * so we calculated it "by hand" */ static int calculate_cns(struct dive *dive) { int i, divenr; double cns = 0.0; timestamp_t last_starttime, last_endtime = 0; /* shortcut */ if (dive->cns) return dive->cns; divenr = get_divenr(dive); i = divenr >= 0 ? divenr : dive_table.nr; #if DECO_CALC_DEBUG & 2 if (i >= 0 && i < dive_table.nr) printf("\n\n*** CNS for dive #%d %d\n", i, get_dive(i)->number); else printf("\n\n*** CNS for dive #%d\n", i); #endif /* Look at next dive in dive list table and correct i when needed */ while (i < dive_table.nr - 1) { struct dive *pdive = get_dive(i); if (!pdive || pdive->when > dive->when) break; i++; } /* Look at previous dive in dive list table and correct i when needed */ while (i > 0) { struct dive *pdive = get_dive(i - 1); if (!pdive || pdive->when < dive->when) break; i--; } #if DECO_CALC_DEBUG & 2 printf("Dive number corrected to #%d\n", i); #endif last_starttime = dive->when; /* Walk backwards to check previous dives - how far do we need to go back? */ while (i--) { if (i == divenr && i > 0) i--; #if DECO_CALC_DEBUG & 2 printf("Check if dive #%d %d has to be considered as prev dive: ", i, get_dive(i)->number); #endif struct dive *pdive = get_dive(i); /* we don't want to mix dives from different trips as we keep looking * for how far back we need to go */ if (dive->divetrip && pdive->divetrip != dive->divetrip) { #if DECO_CALC_DEBUG & 2 printf("No - other dive trip\n"); #endif continue; } if (!pdive || pdive->when >= dive->when || dive_endtime(pdive) + 12 * 60 * 60 < last_starttime) { #if DECO_CALC_DEBUG & 2 printf("No\n"); #endif break; } last_starttime = pdive->when; #if DECO_CALC_DEBUG & 2 printf("Yes\n"); #endif } /* Walk forward and add dives and surface intervals to CNS */ while (++i < dive_table.nr) { #if DECO_CALC_DEBUG & 2 printf("Check if dive #%d %d will be really added to CNS calc: ", i, get_dive(i)->number); #endif struct dive *pdive = get_dive(i); /* again skip dives from different trips */ if (dive->divetrip && dive->divetrip != pdive->divetrip) { #if DECO_CALC_DEBUG & 2 printf("No - other dive trip\n"); #endif continue; } /* Don't add future dives */ if (pdive->when >= dive->when) { #if DECO_CALC_DEBUG & 2 printf("No - future or same dive\n"); #endif break; } /* Don't add the copy of the dive itself */ if (i == divenr) { #if DECO_CALC_DEBUG & 2 printf("No - copy of dive\n"); #endif continue; } #if DECO_CALC_DEBUG & 2 printf("Yes\n"); #endif /* CNS reduced with 90min halftime during surface interval */ if (last_endtime) cns /= pow(2, (pdive->when - last_endtime) / (90.0 * 60.0)); #if DECO_CALC_DEBUG & 2 printf("CNS after surface interval: %f\n", cns); #endif cns += calculate_cns_dive(pdive); #if DECO_CALC_DEBUG & 2 printf("CNS after previous dive: %f\n", cns); #endif last_starttime = pdive->when; last_endtime = dive_endtime(pdive); } /* CNS reduced with 90min halftime during surface interval */ if (last_endtime) cns /= pow(2, (dive->when - last_endtime) / (90.0 * 60.0)); #if DECO_CALC_DEBUG & 2 printf("CNS after last surface interval: %f\n", cns); #endif cns += calculate_cns_dive(dive); #if DECO_CALC_DEBUG & 2 printf("CNS after dive: %f\n", cns); #endif /* save calculated cns in dive struct */ dive->cns = lrint(cns); return dive->cns; } /* * Return air usage (in liters). */ static double calculate_airuse(const struct dive *dive) { int airuse = 0; int i; // SAC for a CCR dive does not make sense. if (dive->dc.divemode == CCR) return 0.0; for (i = 0; i < dive->cylinders.nr; i++) { pressure_t start, end; const cylinder_t *cyl = get_cylinder(dive, i); start = cyl->start.mbar ? cyl->start : cyl->sample_start; end = cyl->end.mbar ? cyl->end : cyl->sample_end; if (!end.mbar || start.mbar <= end.mbar) { // If a cylinder is used but we do not have info on amout of gas used // better not pretend we know the total gas use. // Eventually, logic should be fixed to compute average depth and total time // for those segments where cylinders with known pressure drop are breathed from. if (is_cylinder_used(dive, i)) return 0.0; else continue; } airuse += gas_volume(cyl, start) - gas_volume(cyl, end); } return airuse / 1000.0; } /* this only uses the first divecomputer to calculate the SAC rate */ static int calculate_sac(const struct dive *dive) { const struct divecomputer *dc = &dive->dc; double airuse, pressure, sac; int duration, meandepth; airuse = calculate_airuse(dive); if (!airuse) return 0; duration = dc->duration.seconds; if (!duration) return 0; meandepth = dc->meandepth.mm; if (!meandepth) return 0; /* Mean pressure in ATM (SAC calculations are in atm*l/min) */ pressure = depth_to_atm(meandepth, dive); sac = airuse / pressure * 60 / duration; /* milliliters per minute.. */ return lrint(sac * 1000); } /* for now we do this based on the first divecomputer */ static void add_dive_to_deco(struct deco_state *ds, struct dive *dive, bool in_planner) { struct divecomputer *dc = &dive->dc; struct gasmix gasmix = gasmix_air; int i; const struct event *ev = NULL, *evd = NULL; enum divemode_t current_divemode = UNDEF_COMP_TYPE; if (!dc) return; for (i = 1; i < dc->samples; i++) { struct sample *psample = dc->sample + i - 1; struct sample *sample = dc->sample + i; int t0 = psample->time.seconds; int t1 = sample->time.seconds; int j; for (j = t0; j < t1; j++) { int depth = interpolate(psample->depth.mm, sample->depth.mm, j - t0, t1 - t0); gasmix = get_gasmix(dive, dc, j, &ev, gasmix); add_segment(ds, depth_to_bar(depth, dive), gasmix, 1, sample->setpoint.mbar, get_current_divemode(&dive->dc, j, &evd, &current_divemode), dive->sac, in_planner); } } } int get_divenr(const struct dive *dive) { int i; const struct dive *d; // tempting as it may be, don't die when called with dive=NULL if (dive) for_each_dive(i, d) { if (d->id == dive->id) // don't compare pointers, we could be passing in a copy of the dive return i; } return -1; } static struct gasmix air = { .o2.permille = O2_IN_AIR, .he.permille = 0 }; /* take into account previous dives until there is a 48h gap between dives */ /* return last surface time before this dive or dummy value of 48h */ /* return negative surface time if dives are overlapping */ /* The place you call this function is likely the place where you want * to create the deco_state */ int init_decompression(struct deco_state *ds, const struct dive *dive, bool in_planner) { int i, divenr = -1; int surface_time = 48 * 60 * 60; timestamp_t last_endtime = 0, last_starttime = 0; bool deco_init = false; double surface_pressure; if (!dive) return false; divenr = get_divenr(dive); i = divenr >= 0 ? divenr : dive_table.nr; #if DECO_CALC_DEBUG & 2 if (i >= 0 && i < dive_table.nr) printf("\n\n*** Init deco for dive #%d %d\n", i, get_dive(i)->number); else printf("\n\n*** Init deco for dive #%d\n", i); #endif /* Look at next dive in dive list table and correct i when needed */ while (i < dive_table.nr - 1) { struct dive *pdive = get_dive(i); if (!pdive || pdive->when > dive->when) break; i++; } /* Look at previous dive in dive list table and correct i when needed */ while (i > 0) { struct dive *pdive = get_dive(i - 1); if (!pdive || pdive->when < dive->when) break; i--; } #if DECO_CALC_DEBUG & 2 printf("Dive number corrected to #%d\n", i); #endif last_starttime = dive->when; /* Walk backwards to check previous dives - how far do we need to go back? */ while (i--) { if (i == divenr && i > 0) i--; #if DECO_CALC_DEBUG & 2 printf("Check if dive #%d %d has to be considered as prev dive: ", i, get_dive(i)->number); #endif struct dive *pdive = get_dive(i); /* we don't want to mix dives from different trips as we keep looking * for how far back we need to go */ if (dive->divetrip && pdive->divetrip != dive->divetrip) { #if DECO_CALC_DEBUG & 2 printf("No - other dive trip\n"); #endif continue; } if (!pdive || pdive->when >= dive->when || dive_endtime(pdive) + 48 * 60 * 60 < last_starttime) { #if DECO_CALC_DEBUG & 2 printf("No\n"); #endif break; } last_starttime = pdive->when; #if DECO_CALC_DEBUG & 2 printf("Yes\n"); #endif } /* Walk forward an add dives and surface intervals to deco */ while (++i < dive_table.nr) { #if DECO_CALC_DEBUG & 2 printf("Check if dive #%d %d will be really added to deco calc: ", i, get_dive(i)->number); #endif struct dive *pdive = get_dive(i); /* again skip dives from different trips */ if (dive->divetrip && dive->divetrip != pdive->divetrip) { #if DECO_CALC_DEBUG & 2 printf("No - other dive trip\n"); #endif continue; } /* Don't add future dives */ if (pdive->when >= dive->when) { #if DECO_CALC_DEBUG & 2 printf("No - future or same dive\n"); #endif break; } /* Don't add the copy of the dive itself */ if (i == divenr) { #if DECO_CALC_DEBUG & 2 printf("No - copy of dive\n"); #endif continue; } #if DECO_CALC_DEBUG & 2 printf("Yes\n"); #endif surface_pressure = get_surface_pressure_in_mbar(pdive, true) / 1000.0; /* Is it the first dive we add? */ if (!deco_init) { #if DECO_CALC_DEBUG & 2 printf("Init deco\n"); #endif clear_deco(ds, surface_pressure, in_planner); deco_init = true; #if DECO_CALC_DEBUG & 2 printf("Tissues after init:\n"); dump_tissues(ds); #endif } else { surface_time = pdive->when - last_endtime; if (surface_time < 0) { #if DECO_CALC_DEBUG & 2 printf("Exit because surface intervall is %d\n", surface_time); #endif return surface_time; } add_segment(ds, surface_pressure, air, surface_time, 0, dive->dc.divemode, prefs.decosac, in_planner); #if DECO_CALC_DEBUG & 2 printf("Tissues after surface intervall of %d:%02u:\n", FRACTION(surface_time, 60)); dump_tissues(ds); #endif } add_dive_to_deco(ds, pdive, in_planner); last_starttime = pdive->when; last_endtime = dive_endtime(pdive); clear_vpmb_state(ds); #if DECO_CALC_DEBUG & 2 printf("Tissues after added dive #%d:\n", pdive->number); dump_tissues(ds); #endif } surface_pressure = get_surface_pressure_in_mbar(dive, true) / 1000.0; /* We don't have had a previous dive at all? */ if (!deco_init) { #if DECO_CALC_DEBUG & 2 printf("Init deco\n"); #endif clear_deco(ds, surface_pressure, in_planner); #if DECO_CALC_DEBUG & 2 printf("Tissues after no previous dive, surface time set to 48h:\n"); dump_tissues(ds); #endif } else { surface_time = dive->when - last_endtime; if (surface_time < 0) { #if DECO_CALC_DEBUG & 2 printf("Exit because surface intervall is %d\n", surface_time); #endif return surface_time; } add_segment(ds, surface_pressure, air, surface_time, 0, dive->dc.divemode, prefs.decosac, in_planner); #if DECO_CALC_DEBUG & 2 printf("Tissues after surface intervall of %d:%02u:\n", FRACTION(surface_time, 60)); dump_tissues(ds); #endif } // I do not dare to remove this call. We don't need the result but it might have side effects. Bummer. tissue_tolerance_calc(ds, dive, surface_pressure, in_planner); return surface_time; } void update_cylinder_related_info(struct dive *dive) { if (dive != NULL) { dive->sac = calculate_sac(dive); dive->otu = calculate_otu(dive); if (dive->maxcns == 0) dive->maxcns = calculate_cns(dive); } } #define MAX_GAS_STRING 80 /* callers needs to free the string */ char *get_dive_gas_string(const struct dive *dive) { int o2, he, o2max; char *buffer = malloc(MAX_GAS_STRING); if (buffer) { get_dive_gas(dive, &o2, &he, &o2max); o2 = (o2 + 5) / 10; he = (he + 5) / 10; o2max = (o2max + 5) / 10; if (he) if (o2 == o2max) snprintf(buffer, MAX_GAS_STRING, "%d/%d", o2, he); else snprintf(buffer, MAX_GAS_STRING, "%d/%d…%d%%", o2, he, o2max); else if (o2) if (o2 == o2max) snprintf(buffer, MAX_GAS_STRING, "%d%%", o2); else snprintf(buffer, MAX_GAS_STRING, "%d…%d%%", o2, o2max); else strcpy(buffer, translate("gettextFromC", "air")); } return buffer; } /* Like strcmp(), but don't crash on null-pointers */ static int safe_strcmp(const char *s1, const char *s2) { return strcmp(s1 ? s1 : "", s2 ? s2 : ""); } /* Compare a list of dive computers by model name */ static int comp_dc(const struct divecomputer *dc1, const struct divecomputer *dc2) { int cmp; while (dc1 || dc2) { if (!dc1) return -1; if (!dc2) return 1; if ((cmp = safe_strcmp(dc1->model, dc2->model)) != 0) return cmp; dc1 = dc1->next; dc2 = dc2->next; } return 0; } /* This function defines the sort ordering of dives. The core * and the UI models should use the same sort function, which * should be stable. This is not crucial at the moment, as the * indices in core and UI are independent, but ultimately we * probably want to unify the models. * After editing a key used in this sort-function, the order of * the dives must be re-astablished. * Currently, this does a lexicographic sort on the * (start-time, trip-time, number, id) tuple. * trip-time is defined such that dives that do not belong to * a trip are sorted *after* dives that do. Thus, in the default * chronologically-descending sort order, they are shown *before*. * "id" is a stable, strictly increasing unique number, that * is handed out when a dive is added to the system. * We might also consider sorting by end-time and other criteria, * but see the caveat above (editing means rearrangement of the dives). */ int comp_dives(const struct dive *a, const struct dive *b) { int cmp; if (a->when < b->when) return -1; if (a->when > b->when) return 1; if (a->divetrip != b->divetrip) { if (!b->divetrip) return -1; if (!a->divetrip) return 1; if (trip_date(a->divetrip) < trip_date(b->divetrip)) return -1; if (trip_date(a->divetrip) > trip_date(b->divetrip)) return 1; } if (a->number < b->number) return -1; if (a->number > b->number) return 1; if ((cmp = comp_dc(&a->dc, &b->dc)) != 0) return cmp; if (a->id < b->id) return -1; if (a->id > b->id) return 1; return 0; /* this should not happen for a != b */ } /* Dive table functions */ static MAKE_GROW_TABLE(dive_table, struct dive *, dives) MAKE_GET_INSERTION_INDEX(dive_table, struct dive *, dives, dive_less_than) MAKE_ADD_TO(dive_table, struct dive *, dives) static MAKE_REMOVE_FROM(dive_table, dives) static MAKE_GET_IDX(dive_table, struct dive *, dives) MAKE_SORT(dive_table, struct dive *, dives, comp_dives) MAKE_REMOVE(dive_table, struct dive *, dive) MAKE_CLEAR_TABLE(dive_table, dives, dive) MAKE_MOVE_TABLE(dive_table, dives) void insert_dive(struct dive_table *table, struct dive *d) { int idx = dive_table_get_insertion_index(table, d); add_to_dive_table(table, idx, d); } /* * Walk the dives from the oldest dive in the given table, and see if we * can autogroup them. But only do this when the user selected autogrouping. */ static void autogroup_dives(struct dive_table *table, struct trip_table *trip_table_arg) { int from, to; dive_trip_t *trip; int i, j; bool alloc; if (!autogroup) return; for (i = 0; (trip = get_dives_to_autogroup(table, i, &from, &to, &alloc)) != NULL; i = to) { for (j = from; j < to; ++j) add_dive_to_trip(table->dives[j], trip); /* If this was newly allocated, add trip to list */ if (alloc) insert_trip(trip, trip_table_arg); } sort_trip_table(trip_table_arg); #ifdef DEBUG_TRIP dump_trip_list(); #endif } /* Remove a dive from a dive table. This assumes that the * dive was already removed from any trip and deselected. * It simply shrinks the table and frees the trip */ void delete_dive_from_table(struct dive_table *table, int idx) { free_dive(table->dives[idx]); remove_from_dive_table(table, idx); } struct dive *get_dive_from_table(int nr, const struct dive_table *dt) { if (nr >= dt->nr || nr < 0) return NULL; return dt->dives[nr]; } /* This removes a dive from the global dive table but doesn't free the * resources associated with the dive. The caller must removed the dive * from the trip-list. Returns a pointer to the unregistered dive. * The unregistered dive has the selection- and hidden-flags cleared. */ struct dive *unregister_dive(int idx) { struct dive *dive = get_dive(idx); if (!dive) return NULL; /* this should never happen */ /* When removing a dive from the global dive table, * we also have to unregister its fulltext cache. */ fulltext_unregister(dive); remove_from_dive_table(&dive_table, idx); if (dive->selected) amount_selected--; dive->selected = false; return dive; } /* this implements the mechanics of removing the dive from the global * dive table and the trip, but doesn't deal with updating dive trips, etc */ void delete_single_dive(int idx) { struct dive *dive = get_dive(idx); if (!dive) return; /* this should never happen */ if (dive->selected) deselect_dive(dive); remove_dive_from_trip(dive, &trip_table); unregister_dive_from_dive_site(dive); delete_dive_from_table(&dive_table, idx); } void process_loaded_dives() { sort_dive_table(&dive_table); sort_trip_table(&trip_table); /* Autogroup dives if desired by user. */ autogroup_dives(&dive_table, &trip_table); fulltext_populate(); /* Inform frontend of reset data. This should reset all the models. */ emit_reset_signal(); /* Now that everything is settled, select the newest dive. */ select_newest_visible_dive(); } /* * Merge subsequent dives in a table, if mergeable. This assumes * that the dives are neither selected, not part of a trip, as * is the case of freshly imported dives. */ static void merge_imported_dives(struct dive_table *table) { int i; for (i = 1; i < table->nr; i++) { struct dive *prev = table->dives[i - 1]; struct dive *dive = table->dives[i]; struct dive *merged; struct dive_site *ds; /* only try to merge overlapping dives - or if one of the dives has * zero duration (that might be a gps marker from the webservice) */ if (prev->duration.seconds && dive->duration.seconds && dive_endtime(prev) < dive->when) continue; merged = try_to_merge(prev, dive, false); if (!merged) continue; /* Add dive to dive site; try_to_merge() does not do that! */ ds = merged->dive_site; if (ds) { merged->dive_site = NULL; add_dive_to_dive_site(merged, ds); } unregister_dive_from_dive_site(prev); unregister_dive_from_dive_site(dive); unregister_dive_from_trip(prev); unregister_dive_from_trip(dive); /* Overwrite the first of the two dives and remove the second */ free_dive(prev); table->dives[i - 1] = merged; delete_dive_from_table(table, i); /* Redo the new 'i'th dive */ i--; } } /* * Try to merge a new dive into the dive at position idx. Return * true on success. On success, the old dive will be added to the * dives_to_remove table and the merged dive to the dives_to_add * table. On failure everything stays unchanged. * If "prefer_imported" is true, use data of the new dive. */ static bool try_to_merge_into(struct dive *dive_to_add, int idx, struct dive_table *table, bool prefer_imported, /* output parameters: */ struct dive_table *dives_to_add, struct dive_table *dives_to_remove) { struct dive *old_dive = table->dives[idx]; struct dive *merged = try_to_merge(old_dive, dive_to_add, prefer_imported); if (!merged) return false; merged->divetrip = old_dive->divetrip; insert_dive(dives_to_remove, old_dive); insert_dive(dives_to_add, merged); return true; } /* Check if a dive is ranked after the last dive of the global dive list */ static bool dive_is_after_last(struct dive *d) { if (dive_table.nr == 0) return true; return dive_less_than(dive_table.dives[dive_table.nr - 1], d); } /* Merge dives from "dives_from" into "dives_to". Overlapping dives will be merged, * non-overlapping dives will be moved. The results will be added to the "dives_to_add" * table. Dives that were merged are added to the "dives_to_remove" table. * Any newly added (not merged) dive will be assigned to the trip of the "trip" * paremeter. If "delete_from" is non-null dives will be removed from this table. * This function supposes that all input tables are sorted. * Returns true if any dive was added (not merged) that is not past the * last dive of the global dive list (i.e. the sequence will change). * The integer pointed to by "num_merged" will be increased for every * merged dive that is added to "dives_to_add" */ static bool merge_dive_tables(struct dive_table *dives_from, struct dive_table *delete_from, struct dive_table *dives_to, bool prefer_imported, struct dive_trip *trip, /* output parameters: */ struct dive_table *dives_to_add, struct dive_table *dives_to_remove, int *num_merged) { int i, j; int last_merged_into = -1; bool sequence_changed = false; /* Merge newly imported dives into the dive table. * Since both lists (old and new) are sorted, we can step * through them concurrently and locate the insertions points. * Once found, check if the new dive can be merged in the * previous or next dive. * Note that this doesn't consider pathological cases such as: * - New dive "connects" two old dives (turn three into one). * - New dive can not be merged into adjacent but some further dive. */ j = 0; /* Index in dives_to */ for (i = 0; i < dives_from->nr; i++) { struct dive *dive_to_add = dives_from->dives[i]; if (delete_from) remove_dive(dive_to_add, delete_from); /* Find insertion point. */ while (j < dives_to->nr && dive_less_than(dives_to->dives[j], dive_to_add)) j++; /* Try to merge into previous dive. * We are extra-careful to not merge into the same dive twice, as that * would put the merged-into dive twice onto the dives-to-delete list. * In principle that shouldn't happen as all dives that compare equal * by is_same_dive() were already merged, and is_same_dive() should be * transitive. But let's just go *completely* sure for the odd corner-case. */ if (j > 0 && j - 1 > last_merged_into && dive_endtime(dives_to->dives[j - 1]) > dive_to_add->when) { if (try_to_merge_into(dive_to_add, j - 1, dives_to, prefer_imported, dives_to_add, dives_to_remove)) { free_dive(dive_to_add); last_merged_into = j - 1; (*num_merged)++; continue; } } /* That didn't merge into the previous dive. * Try to merge into next dive. */ if (j < dives_to->nr && j > last_merged_into && dive_endtime(dive_to_add) > dives_to->dives[j]->when) { if (try_to_merge_into(dive_to_add, j, dives_to, prefer_imported, dives_to_add, dives_to_remove)) { free_dive(dive_to_add); last_merged_into = j; (*num_merged)++; continue; } } /* We couldnt merge dives, simply add to list of dives to-be-added. */ insert_dive(dives_to_add, dive_to_add); sequence_changed |= !dive_is_after_last(dive_to_add); dive_to_add->divetrip = trip; } /* we took care of all dives, clean up the import table */ dives_from->nr = 0; return sequence_changed; } /* Merge the dives of the trip "from" and the dive_table "dives_from" into the trip "to" * and dive_table "dives_to". If "prefer_imported" is true, dive data of "from" takes * precedence */ void add_imported_dives(struct dive_table *import_table, struct trip_table *import_trip_table, struct dive_site_table *import_sites_table, struct device_table *import_device_table, int flags) { int i, idx; struct dive_table dives_to_add = empty_dive_table; struct dive_table dives_to_remove = empty_dive_table; struct trip_table trips_to_add = empty_trip_table; struct dive_site_table dive_sites_to_add = empty_dive_site_table; struct device_table *devices_to_add = alloc_device_table(); /* Process imported dives and generate lists of dives * to-be-added and to-be-removed */ process_imported_dives(import_table, import_trip_table, import_sites_table, import_device_table, flags, &dives_to_add, &dives_to_remove, &trips_to_add, &dive_sites_to_add, devices_to_add); /* Add new dives to trip and site to get reference count correct. */ for (i = 0; i < dives_to_add.nr; i++) { struct dive *d = dives_to_add.dives[i]; struct dive_trip *trip = d->divetrip; struct dive_site *site = d->dive_site; d->divetrip = NULL; d->dive_site = NULL; add_dive_to_trip(d, trip); add_dive_to_dive_site(d, site); } /* Remove old dives */ for (i = 0; i < dives_to_remove.nr; i++) { idx = get_divenr(dives_to_remove.dives[i]); delete_single_dive(idx); } dives_to_remove.nr = 0; /* Add new dives */ for (i = 0; i < dives_to_add.nr; i++) insert_dive(&dive_table, dives_to_add.dives[i]); dives_to_add.nr = 0; /* Add new trips */ for (i = 0; i < trips_to_add.nr; i++) insert_trip(trips_to_add.trips[i], &trip_table); trips_to_add.nr = 0; /* Add new dive sites */ for (i = 0; i < dive_sites_to_add.nr; i++) register_dive_site(dive_sites_to_add.dive_sites[i]); dive_sites_to_add.nr = 0; /* Add new devices */ for (i = 0; i < nr_devices(devices_to_add); i++) { const struct device *dev = get_device(devices_to_add, i); add_to_device_table(&device_table, dev); } /* We might have deleted the old selected dive. * Choose the newest dive as selected (if any) */ current_dive = dive_table.nr > 0 ? dive_table.dives[dive_table.nr - 1] : NULL; free_device_table(devices_to_add); /* Inform frontend of reset data. This should reset all the models. */ emit_reset_signal(); } /* Helper function for process_imported_dives(): * Try to merge a trip into one of the existing trips. * The bool pointed to by "sequence_changed" is set to true, if the sequence of * the existing dives changes. * The int pointed to by "start_renumbering_at" keeps track of the first dive * to be renumbered in the dives_to_add table. * For other parameters see process_imported_dives() * Returns true if trip was merged. In this case, the trip will be * freed. */ bool try_to_merge_trip(struct dive_trip *trip_import, struct dive_table *import_table, bool prefer_imported, /* output parameters: */ struct dive_table *dives_to_add, struct dive_table *dives_to_remove, bool *sequence_changed, int *start_renumbering_at) { int i; struct dive_trip *trip_old; for (i = 0; i < trip_table.nr; i++) { trip_old = trip_table.trips[i]; if (trips_overlap(trip_import, trip_old)) { *sequence_changed |= merge_dive_tables(&trip_import->dives, import_table, &trip_old->dives, prefer_imported, trip_old, dives_to_add, dives_to_remove, start_renumbering_at); free_trip(trip_import); /* All dives in trip have been consumed -> free */ return true; } } return false; } /* Process imported dives: take a table of dives to be imported and * generate five lists: * 1) Dives to be added * 2) Dives to be removed * 3) Trips to be added * 4) Dive sites to be added * 5) Devices to be added * The dives to be added are owning (i.e. the caller is responsible * for freeing them). * The dives, trips and sites in "import_table", "import_trip_table" * and "import_sites_table" are consumed. On return, the tables have * size 0. "import_trip_table" may be NULL if all dives are not associated * with a trip. * The output tables should be empty - if not, their content * will be cleared! * * Note: The new dives will have their divetrip- and divesites-fields * set, but will *not* be part of the trip and site. The caller has to * add them to the trip and site. * * The lists are generated by merging dives if possible. This is * performed trip-wise. Finer control on merging is provided by * the "flags" parameter: * - If IMPORT_PREFER_IMPORTED is set, data of the new dives are * prioritized on merging. * - If IMPORT_MERGE_ALL_TRIPS is set, all overlapping trips will * be merged, not only non-autogenerated trips. * - If IMPORT_IS_DOWNLOADED is true, only the divecomputer of the * first dive will be considered, as it is assumed that all dives * come from the same computer. * - If IMPORT_ADD_TO_NEW_TRIP is true, dives that are not assigned * to a trip will be added to a newly generated trip. */ void process_imported_dives(struct dive_table *import_table, struct trip_table *import_trip_table, struct dive_site_table *import_sites_table, struct device_table *import_device_table, int flags, /* output parameters: */ struct dive_table *dives_to_add, struct dive_table *dives_to_remove, struct trip_table *trips_to_add, struct dive_site_table *sites_to_add, struct device_table *devices_to_add) { int i, j, nr, start_renumbering_at = 0; struct dive_trip *trip_import, *new_trip; bool sequence_changed = false; bool new_dive_has_number = false; bool last_old_dive_is_numbered; /* If the caller didn't pass an import_trip_table because all * dives are tripless, provide a local table. This may be * necessary if the trips are autogrouped */ struct trip_table local_trip_table = empty_trip_table; if (!import_trip_table) import_trip_table = &local_trip_table; /* Make sure that output parameters don't contain garbage */ clear_dive_table(dives_to_add); clear_dive_table(dives_to_remove); clear_trip_table(trips_to_add); clear_dive_site_table(sites_to_add); clear_device_table(devices_to_add); /* Check if any of the new dives has a number. This will be * important later to decide if we want to renumber the added * dives */ for (int i = 0; i < import_table->nr; i++) { if (import_table->dives[i]->number > 0) { new_dive_has_number = true; break; } } /* If no dives were imported, don't bother doing anything */ if (!import_table->nr) return; /* Add only the devices that we don't know about yet. */ for (i = 0; i < nr_devices(import_device_table); i++) { const struct device *dev = get_device(import_device_table, i); if (!device_exists(&device_table, dev)) add_to_device_table(devices_to_add, dev); } /* Sort the table of dives to be imported and combine mergable dives */ sort_dive_table(import_table); merge_imported_dives(import_table); /* Autogroup tripless dives if desired by user. But don't autogroup * if tripless dives should be added to a new trip. */ if (!(flags & IMPORT_ADD_TO_NEW_TRIP)) autogroup_dives(import_table, import_trip_table); /* If dive sites already exist, use the existing versions. */ for (i = 0; i < import_sites_table->nr; i++) { struct dive_site *new_ds = import_sites_table->dive_sites[i]; struct dive_site *old_ds = get_same_dive_site(new_ds); /* Check if it dive site is actually used by new dives. */ for (j = 0; j < import_table->nr; j++) { if (import_table->dives[j]->dive_site == new_ds) break; } if (j == import_table->nr) { /* Dive site not even used - free it and go to next. */ free_dive_site(new_ds); continue; } if (!old_ds) { /* Dive site doesn't exist. Add it to list of dive sites to be added. */ new_ds->dives.nr = 0; /* Caller is responsible for adding dives to site */ add_dive_site_to_table(new_ds, sites_to_add); continue; } /* Dive site already exists - use the old and free the new. */ for (j = 0; j < import_table->nr; j++) { if (import_table->dives[j]->dive_site == new_ds) import_table->dives[j]->dive_site = old_ds; } free_dive_site(new_ds); } import_sites_table->nr = 0; /* All dive sites were consumed */ /* Merge overlapping trips. Since both trip tables are sorted, we * could be smarter here, but realistically not a whole lot of trips * will be imported so do a simple n*m loop until someone complains. */ for (i = 0; i < import_trip_table->nr; i++) { trip_import = import_trip_table->trips[i]; if ((flags & IMPORT_MERGE_ALL_TRIPS) || trip_import->autogen) { if (try_to_merge_trip(trip_import, import_table, flags & IMPORT_PREFER_IMPORTED, dives_to_add, dives_to_remove, &sequence_changed, &start_renumbering_at)) continue; } /* If no trip to merge-into was found, add trip as-is. * First, add dives to list of dives to add */ for (j = 0; j < trip_import->dives.nr; j++) { struct dive *d = trip_import->dives.dives[j]; /* Add dive to list of dives to-be-added. */ insert_dive(dives_to_add, d); sequence_changed |= !dive_is_after_last(d); remove_dive(d, import_table); } /* Then, add trip to list of trips to add */ insert_trip(trip_import, trips_to_add); trip_import->dives.nr = 0; /* Caller is responsible for adding dives to trip */ } import_trip_table->nr = 0; /* All trips were consumed */ if ((flags & IMPORT_ADD_TO_NEW_TRIP) && import_table->nr > 0) { /* Create a new trip for unassigned dives, if desired. */ new_trip = create_trip_from_dive(import_table->dives[0]); insert_trip(new_trip, trips_to_add); /* Add all remaining dives to this trip */ for (i = 0; i < import_table->nr; i++) { struct dive *d = import_table->dives[i]; d->divetrip = new_trip; insert_dive(dives_to_add, d); sequence_changed |= !dive_is_after_last(d); } import_table->nr = 0; /* All dives were consumed */ } else if (import_table->nr > 0) { /* The remaining dives in import_table are those that don't belong to * a trip and the caller does not want them to be associated to a * new trip. Merge them into the global table. */ sequence_changed |= merge_dive_tables(import_table, NULL, &dive_table, flags & IMPORT_PREFER_IMPORTED, NULL, dives_to_add, dives_to_remove, &start_renumbering_at); } /* If new dives were only added at the end, renumber the added dives. * But only if * - The last dive in the old dive table had a number itself (if there is a last dive). * - None of the new dives has a number. */ last_old_dive_is_numbered = dive_table.nr == 0 || dive_table.dives[dive_table.nr - 1]->number > 0; /* We counted the number of merged dives that were added to dives_to_add. * Skip those. Since sequence_changed is false all added dives are *after* * all merged dives. */ if (!sequence_changed && last_old_dive_is_numbered && !new_dive_has_number) { nr = dive_table.nr > 0 ? dive_table.dives[dive_table.nr - 1]->number : 0; for (i = start_renumbering_at; i < dives_to_add->nr; i++) dives_to_add->dives[i]->number = ++nr; } } static struct dive *get_last_valid_dive() { int i; for (i = dive_table.nr - 1; i >= 0; i--) { if (!dive_table.dives[i]->invalid) return dive_table.dives[i]; } return NULL; } /* return the number a dive gets when inserted at the given index. * this function is supposed to be called *before* a dive was added. * this returns: * - 1 for an empty log * - last_nr+1 for addition at end of log (if last dive had a number) * - 0 for all other cases */ int get_dive_nr_at_idx(int idx) { if (idx < dive_table.nr) return 0; struct dive *last_dive = get_last_valid_dive(); if (!last_dive) return 1; return last_dive->number ? last_dive->number + 1 : 0; } static int min_datafile_version; int get_min_datafile_version() { return min_datafile_version; } void reset_min_datafile_version() { min_datafile_version = 0; } void report_datafile_version(int version) { if (min_datafile_version == 0 || min_datafile_version > version) min_datafile_version = version; } int get_dive_id_closest_to(timestamp_t when) { int i; int nr = dive_table.nr; // deal with pathological cases if (nr == 0) return 0; else if (nr == 1) return dive_table.dives[0]->id; for (i = 0; i < nr && dive_table.dives[i]->when <= when; i++) ; // nothing // again, capture the two edge cases first if (i == nr) return dive_table.dives[i - 1]->id; else if (i == 0) return dive_table.dives[0]->id; if (when - dive_table.dives[i - 1]->when < dive_table.dives[i]->when - when) return dive_table.dives[i - 1]->id; else return dive_table.dives[i]->id; } void clear_dive_file_data() { fulltext_unregister_all(); select_single_dive(NULL); // This is propagate up to the UI and clears all the information. while (dive_table.nr) delete_single_dive(0); current_dive = NULL; while (dive_site_table.nr) delete_dive_site(get_dive_site(0, &dive_site_table), &dive_site_table); if (trip_table.nr != 0) { fprintf(stderr, "Warning: trip table not empty in clear_dive_file_data()!\n"); trip_table.nr = 0; } clear_dive(&displayed_dive); clear_device_table(&device_table); clear_events(); clear_filter_presets(); reset_min_datafile_version(); clear_git_id(); reset_tank_info_table(&tank_info_table); /* Inform frontend of reset data. This should reset all the models. */ emit_reset_signal(); } bool dive_less_than(const struct dive *a, const struct dive *b) { return comp_dives(a, b) < 0; } /* When comparing a dive to a trip, use the first dive of the trip. */ static int comp_dive_to_trip(struct dive *a, struct dive_trip *b) { /* This should never happen, nevertheless don't crash on trips * with no (or worse a negative number of) dives. */ if (!b || b->dives.nr <= 0) return -1; return comp_dives(a, b->dives.dives[0]); } static int comp_dive_or_trip(struct dive_or_trip a, struct dive_or_trip b) { /* we should only be called with both a and b having exactly one of * dive or trip not NULL. But in an abundance of caution, make sure * we still give a consistent answer even when called with invalid * arguments, as otherwise we might be hunting down crashes at a later * time... */ if (!a.dive && !a.trip && !b.dive && !b.trip) return 0; if (!a.dive && !a.trip) return -1; if (!b.dive && !b.trip) return 1; if (a.dive && b.dive) return comp_dives(a.dive, b.dive); if (a.trip && b.trip) return comp_trips(a.trip, b.trip); if (a.dive) return comp_dive_to_trip(a.dive, b.trip); else return -comp_dive_to_trip(b.dive, a.trip); } bool dive_or_trip_less_than(struct dive_or_trip a, struct dive_or_trip b) { return comp_dive_or_trip(a, b) < 0; } /* * Calculate surface interval for dive starting at "when". Currently, we * might display dives which are not yet in the divelist, therefore the * input parameter is a timestamp. * If the given dive starts during a different dive, the surface interval * is 0. If we can't determine a surface interval (first dive), <0 is * returned. This does *not* consider pathological cases such as dives * that happened inside other dives. The interval will always be calculated * with respect to the dive that started previously. */ timestamp_t get_surface_interval(timestamp_t when) { int i; timestamp_t prev_end; /* find previous dive. might want to use a binary search. */ for (i = dive_table.nr - 1; i >= 0; --i) { if (dive_table.dives[i]->when < when) break; } if (i < 0) return -1; prev_end = dive_endtime(dive_table.dives[i]); if (prev_end > when) return 0; return when - prev_end; } /* Find visible dive close to given date. First search towards older, * then newer dives. */ struct dive *find_next_visible_dive(timestamp_t when) { int i, j; if (!dive_table.nr) return NULL; /* we might want to use binary search here */ for (i = 0; i < dive_table.nr; i++) { if (when <= get_dive(i)->when) break; } for (j = i - 1; j > 0; j--) { if (!get_dive(j)->hidden_by_filter) return get_dive(j); } for (j = i; j < dive_table.nr; j++) { if (!get_dive(j)->hidden_by_filter) return get_dive(j); } return NULL; } bool has_dive(unsigned int deviceid, unsigned int diveid) { int i; struct dive *dive; for_each_dive (i, dive) { struct divecomputer *dc; for_each_dc (dive, dc) { if (dc->deviceid != deviceid) continue; if (dc->diveid != diveid) continue; return 1; } } return 0; }
subsurface-for-dirk-master
core/divelist.c
// SPDX-License-Identifier: GPL-2.0 /* unix.c */ /* implements UNIX specific functions */ #include "ssrf.h" #include "dive.h" #include "file.h" #include "subsurface-string.h" #include "device.h" #include "libdivecomputer.h" #include "membuffer.h" #include <stdlib.h> #include <sys/types.h> #include <dirent.h> #include <fnmatch.h> #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <pwd.h> #include <zip.h> // the DE should provide us with a default font and font size... const char unix_system_divelist_default_font[] = "Sans"; const char *system_divelist_default_font = unix_system_divelist_default_font; double system_divelist_default_font_size = -1.0; void subsurface_OS_pref_setup(void) { // nothing } bool subsurface_ignore_font(const char *font) { // there are no old default fonts to ignore UNUSED(font); return false; } static const char *system_default_path_append(const char *append) { const char *home = getenv("HOME"); if (!home) home = "~"; const char *path = "/.subsurface"; int len = strlen(home) + strlen(path) + 1; if (append) len += strlen(append) + 1; char *buffer = (char *)malloc(len); memset(buffer, 0, len); strcat(buffer, home); strcat(buffer, path); if (append) { strcat(buffer, "/"); strcat(buffer, append); } return buffer; } const char *system_default_directory(void) { static const char *path = NULL; if (!path) path = system_default_path_append(NULL); return path; } const char *system_default_filename(void) { static const char *path = NULL; if (!path) { const char *user = getenv("LOGNAME"); if (empty_string(user)) user = "username"; char *filename = calloc(strlen(user) + 5, 1); strcat(filename, user); strcat(filename, ".xml"); path = system_default_path_append(filename); free(filename); } return path; } int enumerate_devices(device_callback_t callback, void *userdata, unsigned int transport) { int index = -1, entries = 0; DIR *dp = NULL; struct dirent *ep = NULL; size_t i; FILE *file; char *line = NULL; char *fname; size_t len; if (transport & DC_TRANSPORT_SERIAL) { const char *dirname = "/dev"; #ifdef __OpenBSD__ const char *patterns[] = { "ttyU*", "ttyC*", NULL }; #else const char *patterns[] = { "ttyUSB*", "ttyS*", "ttyACM*", "rfcomm*", NULL }; #endif dp = opendir(dirname); if (dp == NULL) { return -1; } while ((ep = readdir(dp)) != NULL) { for (i = 0; patterns[i] != NULL; ++i) { if (fnmatch(patterns[i], ep->d_name, 0) == 0) { char filename[1024]; int n = snprintf(filename, sizeof(filename), "%s/%s", dirname, ep->d_name); if (n >= (int)sizeof(filename)) { closedir(dp); return -1; } callback(filename, userdata); if (is_default_dive_computer_device(filename)) index = entries; entries++; break; } } } closedir(dp); } #ifdef __linux__ if (transport & DC_TRANSPORT_USBSTORAGE) { int num_uemis = 0; file = fopen("/proc/mounts", "r"); if (file == NULL) return index; while ((getline(&line, &len, file)) != -1) { char *ptr = strstr(line, "UEMISSDA"); if (!ptr) ptr = strstr(line, "GARMIN"); if (ptr) { char *end = ptr, *start = ptr; while (start > line && *start != ' ') start--; if (*start == ' ') start++; while (*end != ' ' && *end != '\0') end++; *end = '\0'; fname = strdup(start); callback(fname, userdata); if (is_default_dive_computer_device(fname)) index = entries; entries++; num_uemis++; free((void *)fname); } } free(line); fclose(file); if (num_uemis == 1 && entries == 1) /* if we found only one and it's a mounted Uemis, pick it */ index = 0; } #endif return index; } /* NOP wrappers to comform with windows.c */ int subsurface_rename(const char *path, const char *newpath) { return rename(path, newpath); } int subsurface_open(const char *path, int oflags, mode_t mode) { return open(path, oflags, mode); } FILE *subsurface_fopen(const char *path, const char *mode) { return fopen(path, mode); } void *subsurface_opendir(const char *path) { return (void *)opendir(path); } int subsurface_access(const char *path, int mode) { return access(path, mode); } int subsurface_stat(const char* path, struct stat* buf) { return stat(path, buf); } struct zip *subsurface_zip_open_readonly(const char *path, int flags, int *errorp) { return zip_open(path, flags, errorp); } int subsurface_zip_close(struct zip *zip) { return zip_close(zip); } /* win32 console */ void subsurface_console_init(void) { /* NOP */ } void subsurface_console_exit(void) { /* NOP */ } bool subsurface_user_is_root() { return geteuid() == 0; }
subsurface-for-dirk-master
core/unix.c
// SPDX-License-Identifier: GPL-2.0 #include "units.h" #include "gettext.h" #include "pref.h" int get_pressure_units(int mb, const char **units) { int pressure; const char *unit; const struct units *units_p = get_units(); switch (units_p->pressure) { case BAR: default: pressure = (mb + 500) / 1000; unit = translate("gettextFromC", "bar"); break; case PSI: pressure = (int)lrint(mbar_to_PSI(mb)); unit = translate("gettextFromC", "psi"); break; } if (units) *units = unit; return pressure; } double get_temp_units(unsigned int mk, const char **units) { double deg; const char *unit; const struct units *units_p = get_units(); if (units_p->temperature == FAHRENHEIT) { deg = mkelvin_to_F(mk); unit = "°F"; } else { deg = mkelvin_to_C(mk); unit = "°C"; } if (units) *units = unit; return deg; } double get_volume_units(unsigned int ml, int *frac, const char **units) { int decimals; double vol; const char *unit; const struct units *units_p = get_units(); switch (units_p->volume) { case LITER: default: vol = ml / 1000.0; unit = translate("gettextFromC", "ℓ"); decimals = 1; break; case CUFT: vol = ml_to_cuft(ml); unit = translate("gettextFromC", "cuft"); decimals = 2; break; } if (frac) *frac = decimals; if (units) *units = unit; return vol; } int units_to_sac(double volume) { if (get_units()->volume == CUFT) return lrint(cuft_to_l(volume) * 1000.0); else return lrint(volume * 1000); } depth_t units_to_depth(double depth) { depth_t internaldepth; if (get_units()->length == METERS) { internaldepth.mm = lrint(depth * 1000); } else { internaldepth.mm = feet_to_mm(depth); } return internaldepth; } double get_depth_units(int mm, int *frac, const char **units) { int decimals; double d; const char *unit; const struct units *units_p = get_units(); switch (units_p->length) { case METERS: default: d = mm / 1000.0; unit = translate("gettextFromC", "m"); decimals = d < 20; break; case FEET: d = mm_to_feet(mm); unit = translate("gettextFromC", "ft"); decimals = 0; break; } if (frac) *frac = decimals; if (units) *units = unit; return d; } double get_vertical_speed_units(unsigned int mms, int *frac, const char **units) { double d; const char *unit; const struct units *units_p = get_units(); const double time_factor = units_p->vertical_speed_time == MINUTES ? 60.0 : 1.0; switch (units_p->length) { case METERS: default: d = mms / 1000.0 * time_factor; if (units_p->vertical_speed_time == MINUTES) unit = translate("gettextFromC", "m/min"); else unit = translate("gettextFromC", "m/s"); break; case FEET: d = mm_to_feet(mms) * time_factor; if (units_p->vertical_speed_time == MINUTES) unit = translate("gettextFromC", "ft/min"); else unit = translate("gettextFromC", "ft/s"); break; } if (frac) *frac = d < 10; if (units) *units = unit; return d; } double get_weight_units(unsigned int grams, int *frac, const char **units) { int decimals; double value; const char *unit; const struct units *units_p = get_units(); if (units_p->weight == LBS) { value = grams_to_lbs(grams); unit = translate("gettextFromC", "lbs"); decimals = 0; } else { value = grams / 1000.0; unit = translate("gettextFromC", "kg"); decimals = 1; } if (frac) *frac = decimals; if (units) *units = unit; return value; } const struct units *get_units() { return &prefs.units; }
subsurface-for-dirk-master
core/units.c
// SPDX-License-Identifier: GPL-2.0 #include "sample.h" /* * Adding a cylinder pressure sample field is not quite as trivial as it * perhaps should be. * * We try to keep the same sensor index for the same sensor, so that even * if the dive computer doesn't give pressure information for every sample, * we don't move pressure information around between the different sensor * indices. * * The "prepare_sample()" function will always copy the sensor indices * from the previous sample, so the indices are pre-populated (but the * pressures obviously are not) */ void add_sample_pressure(struct sample *sample, int sensor, int mbar) { int idx; if (!mbar) return; /* Do we already have a slot for this sensor */ for (idx = 0; idx < MAX_SENSORS; idx++) { if (sensor != sample->sensor[idx]) continue; sample->pressure[idx].mbar = mbar; return; } /* Pick the first unused index if we couldn't reuse one */ for (idx = 0; idx < MAX_SENSORS; idx++) { if (sample->pressure[idx].mbar) continue; sample->sensor[idx] = sensor; sample->pressure[idx].mbar = mbar; return; } /* We do not have enough slots for the pressure samples. */ /* Should we warn the user about dropping pressure data? */ }
subsurface-for-dirk-master
core/sample.c
// SPDX-License-Identifier: GPL-2.0 /* gas-model.c */ /* gas compressibility model */ #include <stdio.h> #include <stdlib.h> #include "dive.h" /* "Virial minus one" - the virial cubic form without the initial 1.0 */ static double virial_m1(const double coeff[], double x) { return x*coeff[0] + x*x*coeff[1] + x*x*x*coeff[2]; } /* * Z = pV/nRT * * Cubic virial least-square coefficients for O2/N2/He based on data from * * PERRY’S CHEMICAL ENGINEERS’ HANDBOOK SEVENTH EDITION * * with the lookup and curve fitting by Lubomir. * * The "virial" form of the compression factor polynomial is * * Z = 1.0 + C[0]*P + C[1]*P^2 + C[2]*P^3 ... * * and these tables do not contain the initial 1.0 term. * * NOTE! Helium coefficients are a linear mix operation between the * 323K and one for 273K isotherms, to make everything be at 300K. */ double gas_compressibility_factor(struct gasmix gas, double bar) { static const double o2_coefficients[3] = { -7.18092073703e-04, +2.81852572808e-06, -1.50290620492e-09 }; static const double n2_coefficients[3] = { -2.19260353292e-04, +2.92844845532e-06, -2.07613482075e-09 }; static const double he_coefficients[3] = { +4.87320026468e-04, -8.83632921053e-08, +5.33304543646e-11 }; int o2, he; double Z; /* * The curve fitting range is only [0,500] bar. * Anything else is way out of range for cylinder * pressures. */ if (bar < 0) bar = 0; if (bar > 500) bar = 500; o2 = get_o2(gas); he = get_he(gas); Z = virial_m1(o2_coefficients, bar) * o2 + virial_m1(he_coefficients, bar) * he + virial_m1(n2_coefficients, bar) * (1000 - o2 - he); /* * We add the 1.0 at the very end - the linear mixing of the * three 1.0 terms is still 1.0 regardless of the gas mix. * * The * 0.001 is because we did the linear mixing using the * raw permille gas values. */ return Z * 0.001 + 1.0; } /* Compute the new pressure when compressing (expanding) volome v1 at pressure p1 bar to volume v2 * taking into account the compressebility (to first order) */ double isothermal_pressure(struct gasmix gas, double p1, int volume1, int volume2) { double p_ideal = p1 * volume1 / volume2 / gas_compressibility_factor(gas, p1); return p_ideal * gas_compressibility_factor(gas, p_ideal); } double gas_density(struct gasmix gas, int pressure) { int fo2 = get_o2(gas); int fhe = get_he(gas); int density = fhe * HE_DENSITY + fo2 * O2_DENSITY + (1000 - fhe - fo2) * N2_DENSITY; return density * (double) pressure / gas_compressibility_factor(gas, pressure / 1000.0) / SURFACE_PRESSURE / 1000000.0; }
subsurface-for-dirk-master
core/gas-model.c
// SPDX-License-Identifier: GPL-2.0 #ifdef __clang__ // Clang has a bug on zero-initialization of C structs. #pragma clang diagnostic ignored "-Wmissing-field-initializers" #endif #include "ssrf.h" #include "dive.h" #include "divesite.h" #include "gas.h" #include "parse.h" #include "sample.h" #include "subsurface-string.h" #include "divelist.h" #include "device.h" #include "membuffer.h" #include "gettext.h" static int cobalt_profile_sample(void *param, int columns, char **data, char **column) { UNUSED(columns); UNUSED(column); struct parser_state *state = (struct parser_state *)param; sample_start(state); if (data[0]) state->cur_sample->time.seconds = atoi(data[0]); if (data[1]) state->cur_sample->depth.mm = atoi(data[1]); if (data[2]) state->cur_sample->temperature.mkelvin = state->metric ? C_to_mkelvin(strtod_flags(data[2], NULL, 0)) : F_to_mkelvin(strtod_flags(data[2], NULL, 0)); sample_end(state); return 0; } static int cobalt_cylinders(void *param, int columns, char **data, char **column) { UNUSED(columns); UNUSED(column); struct parser_state *state = (struct parser_state *)param; cylinder_t *cyl; cyl = cylinder_start(state); if (data[0]) cyl->gasmix.o2.permille = atoi(data[0]) * 10; if (data[1]) cyl->gasmix.he.permille = atoi(data[1]) * 10; if (data[2]) cyl->start.mbar = psi_to_mbar(atoi(data[2])); if (data[3]) cyl->end.mbar = psi_to_mbar(atoi(data[3])); if (data[4]) cyl->type.size.mliter = atoi(data[4]) * 100; if (data[5]) cyl->gas_used.mliter = atoi(data[5]) * 1000; cylinder_end(state); return 0; } static int cobalt_buddies(void *param, int columns, char **data, char **column) { UNUSED(columns); UNUSED(column); struct parser_state *state = (struct parser_state *)param; if (data[0]) utf8_string(data[0], &state->cur_dive->buddy); return 0; } /* * We still need to figure out how to map free text visibility to * Subsurface star rating. */ static int cobalt_visibility(void *param, int columns, char **data, char **column) { UNUSED(param); UNUSED(columns); UNUSED(column); UNUSED(data); return 0; } static int cobalt_location(void *param, int columns, char **data, char **column) { UNUSED(columns); UNUSED(column); char **location = (char **)param; *location = data[0] ? strdup(data[0]) : NULL; return 0; } static int cobalt_dive(void *param, int columns, char **data, char **column) { UNUSED(columns); UNUSED(column); int retval = 0; struct parser_state *state = (struct parser_state *)param; sqlite3 *handle = state->sql_handle; char *location, *location_site; char get_profile_template[] = "select runtime*60,(DepthPressure*10000/SurfacePressure)-10000,p.Temperature from Dive AS d JOIN TrackPoints AS p ON d.Id=p.DiveId where d.Id=%d"; char get_cylinder_template[] = "select FO2,FHe,StartingPressure,EndingPressure,TankSize,TankPressure,TotalConsumption from GasMixes where DiveID=%d and StartingPressure>0 and EndingPressure > 0 group by FO2,FHe"; char get_buddy_template[] = "select l.Data from Items AS i, List AS l ON i.Value1=l.Id where i.DiveId=%d and l.Type=4"; char get_visibility_template[] = "select l.Data from Items AS i, List AS l ON i.Value1=l.Id where i.DiveId=%d and l.Type=3"; char get_location_template[] = "select l.Data from Items AS i, List AS l ON i.Value1=l.Id where i.DiveId=%d and l.Type=0"; char get_site_template[] = "select l.Data from Items AS i, List AS l ON i.Value1=l.Id where i.DiveId=%d and l.Type=1"; char get_buffer[1024]; dive_start(state); state->cur_dive->number = atoi(data[0]); state->cur_dive->when = (time_t)(atol(data[1])); if (data[4]) utf8_string(data[4], &state->cur_dive->notes); /* data[5] should have information on Units used, but I cannot * parse it at all based on the sample log I have received. The * temperatures in the samples are all Imperial, so let's go by * that. */ state->metric = 0; /* Cobalt stores the pressures, not the depth */ if (data[6]) state->cur_dive->dc.maxdepth.mm = atoi(data[6]); if (data[7]) state->cur_dive->dc.duration.seconds = atoi(data[7]); if (data[8]) state->cur_dive->dc.surface_pressure.mbar = atoi(data[8]); /* * TODO: the deviceid hash should be calculated here. */ settings_start(state); dc_settings_start(state); if (data[9]) { utf8_string(data[9], &state->cur_settings.dc.serial_nr); state->cur_settings.dc.deviceid = atoi(data[9]); state->cur_settings.dc.model = strdup("Cobalt import"); } dc_settings_end(state); settings_end(state); if (data[9]) { state->cur_dive->dc.deviceid = atoi(data[9]); state->cur_dive->dc.model = strdup("Cobalt import"); } snprintf(get_buffer, sizeof(get_buffer) - 1, get_cylinder_template, state->cur_dive->number); retval = sqlite3_exec(handle, get_buffer, &cobalt_cylinders, state, NULL); if (retval != SQLITE_OK) { fprintf(stderr, "%s", "Database query cobalt_cylinders failed.\n"); return 1; } snprintf(get_buffer, sizeof(get_buffer) - 1, get_buddy_template, state->cur_dive->number); retval = sqlite3_exec(handle, get_buffer, &cobalt_buddies, state, NULL); if (retval != SQLITE_OK) { fprintf(stderr, "%s", "Database query cobalt_buddies failed.\n"); return 1; } snprintf(get_buffer, sizeof(get_buffer) - 1, get_visibility_template, state->cur_dive->number); retval = sqlite3_exec(handle, get_buffer, &cobalt_visibility, state, NULL); if (retval != SQLITE_OK) { fprintf(stderr, "%s", "Database query cobalt_visibility failed.\n"); return 1; } snprintf(get_buffer, sizeof(get_buffer) - 1, get_location_template, state->cur_dive->number); retval = sqlite3_exec(handle, get_buffer, &cobalt_location, &location, NULL); if (retval != SQLITE_OK) { fprintf(stderr, "%s", "Database query cobalt_location failed.\n"); return 1; } snprintf(get_buffer, sizeof(get_buffer) - 1, get_site_template, state->cur_dive->number); retval = sqlite3_exec(handle, get_buffer, &cobalt_location, &location_site, NULL); if (retval != SQLITE_OK) { fprintf(stderr, "%s", "Database query cobalt_location (site) failed.\n"); return 1; } if (location && location_site) { char *tmp = malloc(strlen(location) + strlen(location_site) + 4); if (!tmp) { free(location); free(location_site); return 1; } sprintf(tmp, "%s / %s", location, location_site); add_dive_to_dive_site(state->cur_dive, find_or_create_dive_site_with_name(tmp, state->sites)); free(tmp); } free(location); free(location_site); snprintf(get_buffer, sizeof(get_buffer) - 1, get_profile_template, state->cur_dive->number); retval = sqlite3_exec(handle, get_buffer, &cobalt_profile_sample, state, NULL); if (retval != SQLITE_OK) { fprintf(stderr, "%s", "Database query cobalt_profile_sample failed.\n"); return 1; } dive_end(state); return SQLITE_OK; } int parse_cobalt_buffer(sqlite3 *handle, const char *url, const char *buffer, int size, struct dive_table *table, struct trip_table *trips, struct dive_site_table *sites, struct device_table *devices) { UNUSED(buffer); UNUSED(size); int retval; struct parser_state state; init_parser_state(&state); state.target_table = table; state.trips = trips; state.sites = sites; state.devices = devices; state.sql_handle = handle; char get_dives[] = "select Id,strftime('%s',DiveStartTime),LocationId,'buddy','notes',Units,(MaxDepthPressure*10000/SurfacePressure)-10000,DiveMinutes,SurfacePressure,SerialNumber,'model' from Dive where IsViewDeleted = 0"; retval = sqlite3_exec(handle, get_dives, &cobalt_dive, &state, NULL); free_parser_state(&state); if (retval != SQLITE_OK) { fprintf(stderr, "Database query failed '%s'.\n", url); return 1; } return 0; }
subsurface-for-dirk-master
core/import-cobalt.c
// SPDX-License-Identifier: GPL-2.0 #ifdef __clang__ // Clang has a bug on zero-initialization of C structs. #pragma clang diagnostic ignored "-Wmissing-field-initializers" #endif #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include "dive.h" #include "membuffer.h" #include "divesite.h" #include "errorhelper.h" #include "file.h" #include "save-html.h" #include "worldmap-save.h" #include "worldmap-options.h" #include "gettext.h" char *getGoogleApi() { /* google maps api auth*/ return "https://maps.googleapis.com/maps/api/js?"; } void writeMarkers(struct membuffer *b, bool selected_only) { int i, dive_no = 0; struct dive *dive; char pre[1000], post[1000]; for_each_dive (i, dive) { if (selected_only) { if (!dive->selected) continue; } struct dive_site *ds = get_dive_site_for_dive(dive); if (!dive_site_has_gps_location(ds)) continue; put_degrees(b, ds->location.lat, "temp = new google.maps.Marker({position: new google.maps.LatLng(", ""); put_degrees(b, ds->location.lon, ",", ")});\n"); put_string(b, "markers.push(temp);\ntempinfowindow = new google.maps.InfoWindow({content: '<div id=\"content\">'+'<div id=\"siteNotice\">'+'</div>'+'<div id=\"bodyContent\">"); snprintf(pre, sizeof(pre), "<p>%s ", translate("gettextFromC", "Date:")); put_HTML_date(b, dive, pre, "</p>"); snprintf(pre, sizeof(pre), "<p>%s ", translate("gettextFromC", "Time:")); put_HTML_time(b, dive, pre, "</p>"); snprintf(pre, sizeof(pre), "<p>%s ", translate("gettextFromC", "Duration:")); snprintf(post, sizeof(post), " %s</p>", translate("gettextFromC", "min")); put_duration(b, dive->duration, pre, post); put_string(b, "<p> "); put_HTML_quoted(b, translate("gettextFromC", "Max. depth:")); put_HTML_depth(b, dive, " ", "</p>"); put_string(b, "<p> "); put_HTML_quoted(b, translate("gettextFromC", "Air temp.:")); put_HTML_airtemp(b, dive, " ", "</p>"); put_string(b, "<p> "); put_HTML_quoted(b, translate("gettextFromC", "Water temp.:")); put_HTML_watertemp(b, dive, " ", "</p>"); snprintf(pre, sizeof(pre), "<p>%s <b>", translate("gettextFromC", "Location:")); put_string(b, pre); put_HTML_quoted(b, get_dive_location(dive)); put_string(b, "</b></p>"); snprintf(pre, sizeof(pre), "<p> %s ", translate("gettextFromC", "Notes:")); put_HTML_notes(b, dive, pre, " </p>"); put_string(b, "</p>'+'</div>'+'</div>'});\ninfowindows.push(tempinfowindow);\n"); put_format(b, "google.maps.event.addListener(markers[%d], 'mouseover', function() {\ninfowindows[%d].open(map,markers[%d]);}", dive_no, dive_no, dive_no); put_format(b, ");google.maps.event.addListener(markers[%d], 'mouseout', function() {\ninfowindows[%d].close();});\n", dive_no, dive_no); dive_no++; } } void insert_html_header(struct membuffer *b) { put_string(b, "<!DOCTYPE html>\n<html>\n<head>\n"); put_string(b, "<meta name=\"viewport\" content=\"initial-scale=1.0, user-scalable=no\" />\n<title>World Map</title>\n"); put_string(b, "<meta charset=\"UTF-8\">"); } void insert_css(struct membuffer *b) { put_format(b, "<style type=\"text/css\">%s</style>\n", css); } void insert_javascript(struct membuffer *b, const bool selected_only) { put_string(b, "<script type=\"text/javascript\" src=\""); put_string(b, getGoogleApi()); put_string(b, "&amp;sensor=false\">\n</script>\n<script type=\"text/javascript\">\nvar map;\n"); put_format(b, "function initialize() {\nvar mapOptions = {\n\t%s,", map_options); put_string(b, "rotateControl: false,\n\tstreetViewControl: false,\n\tmapTypeControl: false\n};\n"); put_string(b, "map = new google.maps.Map(document.getElementById(\"map-canvas\"),mapOptions);\nvar markers = new Array();"); put_string(b, "\nvar infowindows = new Array();\nvar temp;\nvar tempinfowindow;\n"); writeMarkers(b, selected_only); put_string(b, "\nfor(var i=0;i<markers.length;i++)\n\tmarkers[i].setMap(map);\n}\n"); put_string(b, "google.maps.event.addDomListener(window, 'load', initialize);</script>\n"); } void export(struct membuffer *b, const bool selected_only) { insert_html_header(b); insert_css(b); insert_javascript(b, selected_only); put_string(b, "\t</head>\n<body>\n<div id=\"map-canvas\"></div>\n</body>\n</html>"); } void export_worldmap_HTML(const char *file_name, const bool selected_only) { FILE *f; struct membuffer buf = { 0 }; export(&buf, selected_only); f = subsurface_fopen(file_name, "w+"); if (!f) { report_error(translate("gettextFromC", "Can't open file %s"), file_name); } else { flush_buffer(&buf, f); /*check for writing errors? */ fclose(f); } free_buffer(&buf); }
subsurface-for-dirk-master
core/worldmap-save.c
// SPDX-License-Identifier: GPL-2.0 /* calculate deco values * based on Bühlmann ZHL-16b * based on an implemention by heinrichs weikamp for the DR5 * the original file was given to Subsurface under the GPLv2 * by Matthias Heinrichs * * The implementation below is a fairly complete rewrite since then * (C) Robert C. Helling 2013 and released under the GPLv2 * * add_segment() - add <seconds> at the given pressure, breathing gasmix * deco_allowed_depth() - ceiling based on lead tissue, surface pressure, 3m increments or smooth * set_gf() - set Buehlmann gradient factors * set_vpmb_conservatism() - set VPM-B conservatism value * clear_deco() * cache_deco_state() * restore_deco_state() * dump_tissues() */ #include <math.h> #include <string.h> #include <assert.h> #include "deco.h" #include "ssrf.h" #include "dive.h" #include "gas.h" #include "subsurface-string.h" #include "errorhelper.h" #include "planner.h" #include "qthelper.h" #define cube(x) (x * x * x) // Subsurface until v4.6.2 appeared to produce marginally less conservative plans than our benchmarks. // This factor was used to correct this. Since a fix for the saturation and desaturation rates // was introduced in v4.6.3 this can be set to a value of 1.0 which means no correction. #define subsurface_conservatism_factor 1.0 //! Option structure for Buehlmann decompression. struct buehlmann_config { double satmult; //! safety at inert gas accumulation as percentage of effect (more than 100). double desatmult; //! safety at inert gas depletion as percentage of effect (less than 100). int last_deco_stop_in_mtr; //! depth of last_deco_stop. double gf_high; //! gradient factor high (at surface). double gf_low; //! gradient factor low (at bottom/start of deco calculation). double gf_low_position_min; //! gf_low_position below surface_min_shallow. }; struct buehlmann_config buehlmann_config = { .satmult = 1.0, .desatmult = 1.0, .last_deco_stop_in_mtr = 0, .gf_high = 0.75, .gf_low = 0.35, .gf_low_position_min = 1.0, }; //! Option structure for VPM-B decompression. struct vpmb_config { double crit_radius_N2; //! Critical radius of N2 nucleon (microns). double crit_radius_He; //! Critical radius of He nucleon (microns). double crit_volume_lambda; //! Constant corresponding to critical gas volume (bar * min). double gradient_of_imperm; //! Gradient after which bubbles become impermeable (bar). double surface_tension_gamma; //! Nucleons surface tension constant (N / bar = m2). double skin_compression_gammaC; //! Skin compression gammaC (N / bar = m2). double regeneration_time; //! Time needed for the bubble to regenerate to the start radius (min). double other_gases_pressure; //! Always present pressure of other gasses in tissues (bar). short conservatism; //! VPM-B conservatism level (0-4) }; static struct vpmb_config vpmb_config = { .crit_radius_N2 = 0.55, .crit_radius_He = 0.45, .crit_volume_lambda = 199.58, .gradient_of_imperm = 8.30865, // = 8.2 atm .surface_tension_gamma = 0.18137175, // = 0.0179 N/msw .skin_compression_gammaC = 2.6040525, // = 0.257 N/msw .regeneration_time = 20160.0, .other_gases_pressure = 0.1359888, .conservatism = 3 }; static const double buehlmann_N2_a[] = { 1.1696, 1.0, 0.8618, 0.7562, 0.62, 0.5043, 0.441, 0.4, 0.375, 0.35, 0.3295, 0.3065, 0.2835, 0.261, 0.248, 0.2327 }; static const double buehlmann_N2_b[] = { 0.5578, 0.6514, 0.7222, 0.7825, 0.8126, 0.8434, 0.8693, 0.8910, 0.9092, 0.9222, 0.9319, 0.9403, 0.9477, 0.9544, 0.9602, 0.9653 }; const double buehlmann_N2_t_halflife[] = { 5.0, 8.0, 12.5, 18.5, 27.0, 38.3, 54.3, 77.0, 109.0, 146.0, 187.0, 239.0, 305.0, 390.0, 498.0, 635.0 }; // 1 - exp(-1 / (halflife * 60) * ln(2)) static const double buehlmann_N2_factor_expositon_one_second[] = { 2.30782347297664E-003, 1.44301447809736E-003, 9.23769302935806E-004, 6.24261986779007E-004, 4.27777107246730E-004, 3.01585140931371E-004, 2.12729727268379E-004, 1.50020603047807E-004, 1.05980191127841E-004, 7.91232600646508E-005, 6.17759153688224E-005, 4.83354552742732E-005, 3.78761777920511E-005, 2.96212356654113E-005, 2.31974277413727E-005, 1.81926738960225E-005 }; static const double buehlmann_He_a[] = { 1.6189, 1.383, 1.1919, 1.0458, 0.922, 0.8205, 0.7305, 0.6502, 0.595, 0.5545, 0.5333, 0.5189, 0.5181, 0.5176, 0.5172, 0.5119 }; static const double buehlmann_He_b[] = { 0.4770, 0.5747, 0.6527, 0.7223, 0.7582, 0.7957, 0.8279, 0.8553, 0.8757, 0.8903, 0.8997, 0.9073, 0.9122, 0.9171, 0.9217, 0.9267 }; static const double buehlmann_He_t_halflife[] = { 1.88, 3.02, 4.72, 6.99, 10.21, 14.48, 20.53, 29.11, 41.20, 55.19, 70.69, 90.34, 115.29, 147.42, 188.24, 240.03 }; static const double buehlmann_He_factor_expositon_one_second[] = { 6.12608039419837E-003, 3.81800836683133E-003, 2.44456078654209E-003, 1.65134647076792E-003, 1.13084424730725E-003, 7.97503165599123E-004, 5.62552521860549E-004, 3.96776399429366E-004, 2.80360036664540E-004, 2.09299583354805E-004, 1.63410794820518E-004, 1.27869320250551E-004, 1.00198406028040E-004, 7.83611475491108E-005, 6.13689891868496E-005, 4.81280465299827E-005 }; static const double vpmb_conservatism_lvls[] = { 1.0, 1.05, 1.12, 1.22, 1.35 }; /* Inspired gas loading equations depend on the partial pressure of inert gas in the alveolar. * P_alv = (P_amb - P_H2O + (1 - Rq) / Rq * P_CO2) * f * where: * P_alv alveolar partial pressure of inert gas * P_amb ambient pressure * P_H2O water vapour partial pressure = ~0.0627 bar * P_CO2 carbon dioxide partial pressure = ~0.0534 bar * Rq respiratory quotient (O2 consumption / CO2 production) * f fraction of inert gas * * In our calculations, we simplify this to use an effective water vapour pressure * WV = P_H20 - (1 - Rq) / Rq * P_CO2 * * Buhlmann ignored the contribution of CO2 (i.e. Rq = 1.0), whereas Schreiner adopted Rq = 0.8. * WV_Buhlmann = PP_H2O = 0.0627 bar * WV_Schreiner = 0.0627 - (1 - 0.8) / Rq * 0.0534 = 0.0493 bar * Buhlmann calculations use the Buhlmann value, VPM-B calculations use the Schreiner value. */ #define WV_PRESSURE 0.0627 // water vapor pressure in bar, based on respiratory quotient Rq = 1.0 (Buhlmann value) #define WV_PRESSURE_SCHREINER 0.0493 // water vapor pressure in bar, based on respiratory quotient Rq = 0.8 (Schreiner value) #define DECO_STOPS_MULTIPLIER_MM 3000.0 #define NITROGEN_FRACTION 0.79 #define TISSUE_ARRAY_SZ sizeof(ds->tissue_n2_sat) static double get_crit_radius_He() { if (vpmb_config.conservatism <= 4) return vpmb_config.crit_radius_He * vpmb_conservatism_lvls[vpmb_config.conservatism] * subsurface_conservatism_factor; return vpmb_config.crit_radius_He; } static double get_crit_radius_N2() { if (vpmb_config.conservatism <= 4) return vpmb_config.crit_radius_N2 * vpmb_conservatism_lvls[vpmb_config.conservatism] * subsurface_conservatism_factor; return vpmb_config.crit_radius_N2; } // Solve another cubic equation, this time // x^3 - B x - C == 0 // Use trigonometric formula for negative discriminants (see Wikipedia for details) static double solve_cubic2(double B, double C) { double discriminant = 27 * C * C - 4 * cube(B); if (discriminant < 0.0) { return 2.0 * sqrt(B / 3.0) * cos(acos(3.0 * C * sqrt(3.0 / B) / (2.0 * B)) / 3.0); } double denominator = pow(9 * C + sqrt(3 * discriminant), 1 / 3.0); return pow(2.0 / 3.0, 1.0 / 3.0) * B / denominator + denominator / pow(18.0, 1.0 / 3.0); } // This is a simplified formula avoiding radii. It uses the fact that Boyle's law says // pV = (G + P_amb) / G^3 is constant to solve for the new gradient G. static double update_gradient(struct deco_state *ds, double next_stop_pressure, double first_gradient) { double B = cube(first_gradient) / (ds->first_ceiling_pressure.mbar / 1000.0 + first_gradient); double C = next_stop_pressure * B; double new_gradient = solve_cubic2(B, C); if (new_gradient < 0.0) report_error("Negative gradient encountered!"); return new_gradient; } static double vpmb_tolerated_ambient_pressure(struct deco_state *ds, double reference_pressure, int ci) { double n2_gradient, he_gradient, total_gradient; if (reference_pressure >= ds->first_ceiling_pressure.mbar / 1000.0 || !ds->first_ceiling_pressure.mbar) { n2_gradient = ds->bottom_n2_gradient[ci]; he_gradient = ds->bottom_he_gradient[ci]; } else { n2_gradient = update_gradient(ds, reference_pressure, ds->bottom_n2_gradient[ci]); he_gradient = update_gradient(ds, reference_pressure, ds->bottom_he_gradient[ci]); } total_gradient = ((n2_gradient * ds->tissue_n2_sat[ci]) + (he_gradient * ds->tissue_he_sat[ci])) / (ds->tissue_n2_sat[ci] + ds->tissue_he_sat[ci]); return ds->tissue_n2_sat[ci] + ds->tissue_he_sat[ci] + vpmb_config.other_gases_pressure - total_gradient; } double tissue_tolerance_calc(struct deco_state *ds, const struct dive *dive, double pressure, bool in_planner) { int ci = -1; double ret_tolerance_limit_ambient_pressure = 0.0; double gf_high = buehlmann_config.gf_high; double gf_low = buehlmann_config.gf_low; double surface = get_surface_pressure_in_mbar(dive, true) / 1000.0; double lowest_ceiling = 0.0; double tissue_lowest_ceiling[16]; for (ci = 0; ci < 16; ci++) { ds->buehlmann_inertgas_a[ci] = ((buehlmann_N2_a[ci] * ds->tissue_n2_sat[ci]) + (buehlmann_He_a[ci] * ds->tissue_he_sat[ci])) / ds->tissue_inertgas_saturation[ci]; ds->buehlmann_inertgas_b[ci] = ((buehlmann_N2_b[ci] * ds->tissue_n2_sat[ci]) + (buehlmann_He_b[ci] * ds->tissue_he_sat[ci])) / ds->tissue_inertgas_saturation[ci]; } if (decoMode(in_planner) != VPMB) { for (ci = 0; ci < 16; ci++) { /* tolerated = (tissue_inertgas_saturation - buehlmann_inertgas_a) * buehlmann_inertgas_b; */ tissue_lowest_ceiling[ci] = (ds->buehlmann_inertgas_b[ci] * ds->tissue_inertgas_saturation[ci] - gf_low * ds->buehlmann_inertgas_a[ci] * ds->buehlmann_inertgas_b[ci]) / ((1.0 - ds->buehlmann_inertgas_b[ci]) * gf_low + ds->buehlmann_inertgas_b[ci]); if (tissue_lowest_ceiling[ci] > lowest_ceiling) lowest_ceiling = tissue_lowest_ceiling[ci]; if (lowest_ceiling > ds->gf_low_pressure_this_dive) ds->gf_low_pressure_this_dive = lowest_ceiling; } for (ci = 0; ci < 16; ci++) { double tolerated; if ((surface / ds->buehlmann_inertgas_b[ci] + ds->buehlmann_inertgas_a[ci] - surface) * gf_high + surface < (ds->gf_low_pressure_this_dive / ds->buehlmann_inertgas_b[ci] + ds->buehlmann_inertgas_a[ci] - ds->gf_low_pressure_this_dive) * gf_low + ds->gf_low_pressure_this_dive) tolerated = (-ds->buehlmann_inertgas_a[ci] * ds->buehlmann_inertgas_b[ci] * (gf_high * ds->gf_low_pressure_this_dive - gf_low * surface) - (1.0 - ds->buehlmann_inertgas_b[ci]) * (gf_high - gf_low) * ds->gf_low_pressure_this_dive * surface + ds->buehlmann_inertgas_b[ci] * (ds->gf_low_pressure_this_dive - surface) * ds->tissue_inertgas_saturation[ci]) / (-ds->buehlmann_inertgas_a[ci] * ds->buehlmann_inertgas_b[ci] * (gf_high - gf_low) + (1.0 - ds->buehlmann_inertgas_b[ci]) * (gf_low * ds->gf_low_pressure_this_dive - gf_high * surface) + ds->buehlmann_inertgas_b[ci] * (ds->gf_low_pressure_this_dive - surface)); else tolerated = ret_tolerance_limit_ambient_pressure; ds->tolerated_by_tissue[ci] = tolerated; if (tolerated >= ret_tolerance_limit_ambient_pressure) { ds->ci_pointing_to_guiding_tissue = ci; ret_tolerance_limit_ambient_pressure = tolerated; } } } else { // VPM-B ceiling double reference_pressure; ret_tolerance_limit_ambient_pressure = pressure; // The Boyle compensated gradient depends on ambient pressure. For the ceiling, this should set the ambient pressure. do { reference_pressure = ret_tolerance_limit_ambient_pressure; ret_tolerance_limit_ambient_pressure = 0.0; for (ci = 0; ci < 16; ci++) { double tolerated = vpmb_tolerated_ambient_pressure(ds, reference_pressure, ci); if (tolerated >= ret_tolerance_limit_ambient_pressure) { ds->ci_pointing_to_guiding_tissue = ci; ret_tolerance_limit_ambient_pressure = tolerated; } ds->tolerated_by_tissue[ci] = tolerated; } // We are doing ok if the gradient was computed within ten centimeters of the ceiling. } while (fabs(ret_tolerance_limit_ambient_pressure - reference_pressure) > 0.01); } return ret_tolerance_limit_ambient_pressure; } /* * Return Buehlmann factor for a particular period and tissue index. */ static double factor(int period_in_seconds, int ci, enum gas_component gas) { if (period_in_seconds == 1) { if (gas == N2) return buehlmann_N2_factor_expositon_one_second[ci]; else return buehlmann_He_factor_expositon_one_second[ci]; } // ln(2)/60 = 1.155245301e-02 if (gas == N2) return 1.0 - exp(-period_in_seconds * 1.155245301e-02 / buehlmann_N2_t_halflife[ci]); else return 1.0 - exp(-period_in_seconds * 1.155245301e-02 / buehlmann_He_t_halflife[ci]); } static double calc_surface_phase(double surface_pressure, double he_pressure, double n2_pressure, double he_time_constant, double n2_time_constant, bool in_planner) { double inspired_n2 = (surface_pressure - ((in_planner && (decoMode(true) == VPMB)) ? WV_PRESSURE_SCHREINER : WV_PRESSURE)) * NITROGEN_FRACTION; if (n2_pressure > inspired_n2) return (he_pressure / he_time_constant + (n2_pressure - inspired_n2) / n2_time_constant) / (he_pressure + n2_pressure - inspired_n2); if (he_pressure + n2_pressure >= inspired_n2){ double gradient_decay_time = 1.0 / (n2_time_constant - he_time_constant) * log ((inspired_n2 - n2_pressure) / he_pressure); double gradients_integral = he_pressure / he_time_constant * (1.0 - exp(-he_time_constant * gradient_decay_time)) + (n2_pressure - inspired_n2) / n2_time_constant * (1.0 - exp(-n2_time_constant * gradient_decay_time)); return gradients_integral / (he_pressure + n2_pressure - inspired_n2); } return 0; } void vpmb_start_gradient(struct deco_state *ds) { int ci; for (ci = 0; ci < 16; ++ci) { ds->initial_n2_gradient[ci] = ds->bottom_n2_gradient[ci] = 2.0 * (vpmb_config.surface_tension_gamma / vpmb_config.skin_compression_gammaC) * ((vpmb_config.skin_compression_gammaC - vpmb_config.surface_tension_gamma) / ds->n2_regen_radius[ci]); ds->initial_he_gradient[ci] = ds->bottom_he_gradient[ci] = 2.0 * (vpmb_config.surface_tension_gamma / vpmb_config.skin_compression_gammaC) * ((vpmb_config.skin_compression_gammaC - vpmb_config.surface_tension_gamma) / ds->he_regen_radius[ci]); } } void vpmb_next_gradient(struct deco_state *ds, double deco_time, double surface_pressure, bool in_planner) { int ci; double n2_b, n2_c; double he_b, he_c; double desat_time; deco_time /= 60.0; for (ci = 0; ci < 16; ++ci) { desat_time = deco_time + calc_surface_phase(surface_pressure, ds->tissue_he_sat[ci], ds->tissue_n2_sat[ci], log(2.0) / buehlmann_He_t_halflife[ci], log(2.0) / buehlmann_N2_t_halflife[ci], in_planner); n2_b = ds->initial_n2_gradient[ci] + (vpmb_config.crit_volume_lambda * vpmb_config.surface_tension_gamma) / (vpmb_config.skin_compression_gammaC * desat_time); he_b = ds->initial_he_gradient[ci] + (vpmb_config.crit_volume_lambda * vpmb_config.surface_tension_gamma) / (vpmb_config.skin_compression_gammaC * desat_time); n2_c = vpmb_config.surface_tension_gamma * vpmb_config.surface_tension_gamma * vpmb_config.crit_volume_lambda * ds->max_n2_crushing_pressure[ci]; n2_c = n2_c / (vpmb_config.skin_compression_gammaC * vpmb_config.skin_compression_gammaC * desat_time); he_c = vpmb_config.surface_tension_gamma * vpmb_config.surface_tension_gamma * vpmb_config.crit_volume_lambda * ds->max_he_crushing_pressure[ci]; he_c = he_c / (vpmb_config.skin_compression_gammaC * vpmb_config.skin_compression_gammaC * desat_time); ds->bottom_n2_gradient[ci] = 0.5 * ( n2_b + sqrt(n2_b * n2_b - 4.0 * n2_c)); ds->bottom_he_gradient[ci] = 0.5 * ( he_b + sqrt(he_b * he_b - 4.0 * he_c)); } } // A*r^3 - B*r^2 - C == 0 // Solved with the help of mathematica static double solve_cubic(double A, double B, double C) { double BA = B/A; double CA = C/A; double discriminant = CA * (4 * cube(BA) + 27 * CA); // Let's make sure we have a real solution: if (discriminant < 0.0) { // This should better not happen report_error("Complex solution for inner pressure encountered!\n A=%f\tB=%f\tC=%f\n", A, B, C); return 0.0; } double denominator = pow(cube(BA) + 1.5 * (9 * CA + sqrt(3.0) * sqrt(discriminant)), 1/3.0); return (BA + BA * BA / denominator + denominator) / 3.0; } void nuclear_regeneration(struct deco_state *ds, double time) { time /= 60.0; int ci; double crushing_radius_N2, crushing_radius_He; for (ci = 0; ci < 16; ++ci) { //rm crushing_radius_N2 = 1.0 / (ds->max_n2_crushing_pressure[ci] / (2.0 * (vpmb_config.skin_compression_gammaC - vpmb_config.surface_tension_gamma)) + 1.0 / get_crit_radius_N2()); crushing_radius_He = 1.0 / (ds->max_he_crushing_pressure[ci] / (2.0 * (vpmb_config.skin_compression_gammaC - vpmb_config.surface_tension_gamma)) + 1.0 / get_crit_radius_He()); //rs ds->n2_regen_radius[ci] = crushing_radius_N2 + (get_crit_radius_N2() - crushing_radius_N2) * (1.0 - exp (-time / vpmb_config.regeneration_time)); ds->he_regen_radius[ci] = crushing_radius_He + (get_crit_radius_He() - crushing_radius_He) * (1.0 - exp (-time / vpmb_config.regeneration_time)); } } // Calculates the nucleons inner pressure during the impermeable period static double calc_inner_pressure(double crit_radius, double onset_tension, double current_ambient_pressure) { double onset_radius = 1.0 / (vpmb_config.gradient_of_imperm / (2.0 * (vpmb_config.skin_compression_gammaC - vpmb_config.surface_tension_gamma)) + 1.0 / crit_radius); double A = current_ambient_pressure - vpmb_config.gradient_of_imperm + (2.0 * (vpmb_config.skin_compression_gammaC - vpmb_config.surface_tension_gamma)) / onset_radius; double B = 2.0 * (vpmb_config.skin_compression_gammaC - vpmb_config.surface_tension_gamma); double C = onset_tension * pow(onset_radius, 3); double current_radius = solve_cubic(A, B, C); return onset_tension * onset_radius * onset_radius * onset_radius / (current_radius * current_radius * current_radius); } // Calculates the crushing pressure in the given moment. Updates crushing_onset_tension and critical radius if needed void calc_crushing_pressure(struct deco_state *ds, double pressure) { int ci; double gradient; double gas_tension; double n2_crushing_pressure, he_crushing_pressure; double n2_inner_pressure, he_inner_pressure; for (ci = 0; ci < 16; ++ci) { gas_tension = ds->tissue_n2_sat[ci] + ds->tissue_he_sat[ci] + vpmb_config.other_gases_pressure; gradient = pressure - gas_tension; if (gradient <= vpmb_config.gradient_of_imperm) { // permeable situation n2_crushing_pressure = he_crushing_pressure = gradient; ds->crushing_onset_tension[ci] = gas_tension; } else { // impermeable if (ds->max_ambient_pressure >= pressure) return; n2_inner_pressure = calc_inner_pressure(get_crit_radius_N2(), ds->crushing_onset_tension[ci], pressure); he_inner_pressure = calc_inner_pressure(get_crit_radius_He(), ds->crushing_onset_tension[ci], pressure); n2_crushing_pressure = pressure - n2_inner_pressure; he_crushing_pressure = pressure - he_inner_pressure; } ds->max_n2_crushing_pressure[ci] = MAX(ds->max_n2_crushing_pressure[ci], n2_crushing_pressure); ds->max_he_crushing_pressure[ci] = MAX(ds->max_he_crushing_pressure[ci], he_crushing_pressure); } ds->max_ambient_pressure = MAX(pressure, ds->max_ambient_pressure); } /* add period_in_seconds at the given pressure and gas to the deco calculation */ void add_segment(struct deco_state *ds, double pressure, struct gasmix gasmix, int period_in_seconds, int ccpo2, enum divemode_t divemode, int sac, bool in_planner) { UNUSED(sac); int ci; struct gas_pressures pressures; bool icd = false; fill_pressures(&pressures, pressure - ((in_planner && (decoMode(true) == VPMB)) ? WV_PRESSURE_SCHREINER : WV_PRESSURE), gasmix, (double) ccpo2 / 1000.0, divemode); for (ci = 0; ci < 16; ci++) { double pn2_oversat = pressures.n2 - ds->tissue_n2_sat[ci]; double phe_oversat = pressures.he - ds->tissue_he_sat[ci]; double n2_f = factor(period_in_seconds, ci, N2); double he_f = factor(period_in_seconds, ci, HE); double n2_satmult = pn2_oversat > 0 ? buehlmann_config.satmult : buehlmann_config.desatmult; double he_satmult = phe_oversat > 0 ? buehlmann_config.satmult : buehlmann_config.desatmult; // Report ICD if N2 is more on-gasing than He off-gasing in leading tissue if (ci == ds->ci_pointing_to_guiding_tissue && pn2_oversat > 0.0 && phe_oversat < 0.0 && pn2_oversat * n2_satmult * n2_f + phe_oversat * he_satmult * he_f > 0) icd = true; ds->tissue_n2_sat[ci] += n2_satmult * pn2_oversat * n2_f; ds->tissue_he_sat[ci] += he_satmult * phe_oversat * he_f; ds->tissue_inertgas_saturation[ci] = ds->tissue_n2_sat[ci] + ds->tissue_he_sat[ci]; } if (decoMode(in_planner) == VPMB) calc_crushing_pressure(ds, pressure); ds->icd_warning = icd; return; } #if DECO_CALC_DEBUG void dump_tissues(struct deco_state *ds) { int ci; printf("N2 tissues:"); for (ci = 0; ci < 16; ci++) printf(" %6.3e", ds->tissue_n2_sat[ci]); printf("\nHe tissues:"); for (ci = 0; ci < 16; ci++) printf(" %6.3e", ds->tissue_he_sat[ci]); printf("\n"); } #endif void clear_vpmb_state(struct deco_state *ds) { int ci; for (ci = 0; ci < 16; ci++) { ds->max_n2_crushing_pressure[ci] = 0.0; ds->max_he_crushing_pressure[ci] = 0.0; } ds->max_ambient_pressure = 0; ds->first_ceiling_pressure.mbar = 0; ds->max_bottom_ceiling_pressure.mbar = 0; } void clear_deco(struct deco_state *ds, double surface_pressure, bool in_planner) { int ci; memset(ds, 0, sizeof(*ds)); clear_vpmb_state(ds); for (ci = 0; ci < 16; ci++) { ds->tissue_n2_sat[ci] = (surface_pressure - ((in_planner && (decoMode(true) == VPMB)) ? WV_PRESSURE_SCHREINER : WV_PRESSURE)) * N2_IN_AIR / 1000; ds->tissue_he_sat[ci] = 0.0; ds->max_n2_crushing_pressure[ci] = 0.0; ds->max_he_crushing_pressure[ci] = 0.0; ds->n2_regen_radius[ci] = get_crit_radius_N2(); ds->he_regen_radius[ci] = get_crit_radius_He(); } ds->gf_low_pressure_this_dive = surface_pressure + buehlmann_config.gf_low_position_min; ds->max_ambient_pressure = 0.0; ds->ci_pointing_to_guiding_tissue = -1; } void cache_deco_state(struct deco_state *src, struct deco_state **cached_datap) { struct deco_state *data = *cached_datap; if (!data) { data = malloc(sizeof(struct deco_state)); *cached_datap = data; } *data = *src; } void restore_deco_state(struct deco_state *data, struct deco_state *target, bool keep_vpmb_state) { if (keep_vpmb_state) { int ci; for (ci = 0; ci < 16; ci++) { data->bottom_n2_gradient[ci] = target->bottom_n2_gradient[ci]; data->bottom_he_gradient[ci] = target->bottom_he_gradient[ci]; data->initial_n2_gradient[ci] = target->initial_n2_gradient[ci]; data->initial_he_gradient[ci] = target->initial_he_gradient[ci]; } data->first_ceiling_pressure = target->first_ceiling_pressure; data->max_bottom_ceiling_pressure = target->max_bottom_ceiling_pressure; } *target = *data; } int deco_allowed_depth(double tissues_tolerance, double surface_pressure, const struct dive *dive, bool smooth) { int depth; double pressure_delta; /* Avoid negative depths */ pressure_delta = tissues_tolerance > surface_pressure ? tissues_tolerance - surface_pressure : 0.0; depth = rel_mbar_to_depth(lrint(pressure_delta * 1000), dive); if (!smooth) depth = lrint(ceil(depth / DECO_STOPS_MULTIPLIER_MM) * DECO_STOPS_MULTIPLIER_MM); if (depth > 0 && depth < buehlmann_config.last_deco_stop_in_mtr * 1000) depth = buehlmann_config.last_deco_stop_in_mtr * 1000; return depth; } void set_gf(short gflow, short gfhigh) { if (gflow != -1) buehlmann_config.gf_low = (double)gflow / 100.0; if (gfhigh != -1) buehlmann_config.gf_high = (double)gfhigh / 100.0; } void set_vpmb_conservatism(short conservatism) { if (conservatism < 0) vpmb_config.conservatism = 0; else if (conservatism > 4) vpmb_config.conservatism = 4; else vpmb_config.conservatism = conservatism; } double get_gf(struct deco_state *ds, double ambpressure_bar, const struct dive *dive) { double surface_pressure_bar = get_surface_pressure_in_mbar(dive, true) / 1000.0; double gf_low = buehlmann_config.gf_low; double gf_high = buehlmann_config.gf_high; double gf; if (ds->gf_low_pressure_this_dive > surface_pressure_bar) gf = MAX((double)gf_low, (ambpressure_bar - surface_pressure_bar) / (ds->gf_low_pressure_this_dive - surface_pressure_bar) * (gf_low - gf_high) + gf_high); else gf = gf_low; return gf; } double regressiona(const struct deco_state *ds) { if (ds->sum1 > 1) { double avxy = ds->sumxy / ds->sum1; double avx = (double)ds->sumx / ds->sum1; double avy = ds->sumy / ds->sum1; double avxx = (double) ds->sumxx / ds->sum1; return (avxy - avx * avy) / (avxx - avx*avx); } else return 0.0; } double regressionb(const struct deco_state *ds) { if (ds->sum1) return ds->sumy / ds->sum1 - ds->sumx * regressiona(ds) / ds->sum1; else return 0.0; } void reset_regression(struct deco_state *ds) { ds->sum1 = 0; ds->sumxx = ds->sumx = 0L; ds->sumy = ds->sumxy = 0.0; } void update_regression(struct deco_state *ds, const struct dive *dive) { if (!ds->plot_depth) return; ds->sum1 += 1; ds->sumx += ds->plot_depth; ds->sumxx += (long)ds->plot_depth * ds->plot_depth; double n2_gradient, he_gradient, total_gradient; n2_gradient = update_gradient(ds, depth_to_bar(ds->plot_depth, dive), ds->bottom_n2_gradient[ds->ci_pointing_to_guiding_tissue]); he_gradient = update_gradient(ds, depth_to_bar(ds->plot_depth, dive), ds->bottom_he_gradient[ds->ci_pointing_to_guiding_tissue]); total_gradient = ((n2_gradient * ds->tissue_n2_sat[ds->ci_pointing_to_guiding_tissue]) + (he_gradient * ds->tissue_he_sat[ds->ci_pointing_to_guiding_tissue])) / (ds->tissue_n2_sat[ds->ci_pointing_to_guiding_tissue] + ds->tissue_he_sat[ds->ci_pointing_to_guiding_tissue]); double buehlmann_gradient = (1.0 / ds->buehlmann_inertgas_b[ds->ci_pointing_to_guiding_tissue] - 1.0) * depth_to_bar(ds->plot_depth, dive) + ds->buehlmann_inertgas_a[ds->ci_pointing_to_guiding_tissue]; double gf = (total_gradient - vpmb_config.other_gases_pressure) / buehlmann_gradient; ds->sumxy += gf * ds->plot_depth; ds->sumy += gf; ds->plot_depth = 0; }
subsurface-for-dirk-master
core/deco.c
// SPDX-License-Identifier: GPL-2.0 #include "picture.h" #include "dive.h" #if !defined(SUBSURFACE_MOBILE) #include "metadata.h" #endif #include "subsurface-string.h" #include "table.h" #include <stdlib.h> #include <string.h> static void free_picture(struct picture picture) { free(picture.filename); picture.filename = NULL; } static int comp_pictures(struct picture a, struct picture b) { if (a.offset.seconds < b.offset.seconds) return -1; if (a.offset.seconds > b.offset.seconds) return 1; return strcmp(a.filename ?: "", b.filename ?: ""); } static bool picture_less_than(struct picture a, struct picture b) { return comp_pictures(a, b) < 0; } /* picture table functions */ //static MAKE_GET_IDX(picture_table, struct picture, pictures) static MAKE_GROW_TABLE(picture_table, struct picture, pictures) static MAKE_GET_INSERTION_INDEX(picture_table, struct picture, pictures, picture_less_than) MAKE_ADD_TO(picture_table, struct picture, pictures) MAKE_REMOVE_FROM(picture_table, pictures) MAKE_SORT(picture_table, struct picture, pictures, comp_pictures) //MAKE_REMOVE(picture_table, struct picture, picture) MAKE_CLEAR_TABLE(picture_table, pictures, picture) /* Add a clone of a picture to the end of a picture table. * Cloned means that the filename-string is copied. */ static void add_cloned_picture(struct picture_table *t, struct picture pic) { pic.filename = copy_string(pic.filename); int idx = picture_table_get_insertion_index(t, pic); add_to_picture_table(t, idx, pic); } void copy_pictures(const struct picture_table *s, struct picture_table *d) { int i; clear_picture_table(d); for (i = 0; i < s->nr; i++) add_cloned_picture(d, s->pictures[i]); } void add_picture(struct picture_table *t, struct picture newpic) { int idx = picture_table_get_insertion_index(t, newpic); add_to_picture_table(t, idx, newpic); } int get_picture_idx(const struct picture_table *t, const char *filename) { for (int i = 0; i < t->nr; ++i) { if (same_string(t->pictures[i].filename, filename)) return i; } return -1; } /* Return distance of timestamp to time of dive. Result is always positive, 0 means during dive. */ static timestamp_t time_from_dive(const struct dive *d, timestamp_t timestamp) { timestamp_t end_time = dive_endtime(d); if (timestamp < d->when) return d->when - timestamp; else if (timestamp > end_time) return timestamp - end_time; else return 0; } /* Return dive closest selected dive to given timestamp or NULL if no dives are selected. */ static struct dive *nearest_selected_dive(timestamp_t timestamp) { struct dive *d, *res = NULL; int i; timestamp_t offset, min = 0; for_each_dive(i, d) { if (!d->selected) continue; offset = time_from_dive(d, timestamp); if (!res || offset < min) { res = d; min = offset; } /* We suppose that dives are sorted chronologically. Thus * if the offset starts to increase, we can end. This ignores * pathological cases such as overlapping dives. In such a * case the user will have to add pictures manually. */ if (offset == 0 || offset > min) break; } return res; } // only add pictures that have timestamps between 30 minutes before the dive and // 30 minutes after the dive ends #define D30MIN (30 * 60) static bool dive_check_picture_time(const struct dive *d, timestamp_t timestamp) { return time_from_dive(d, timestamp) < D30MIN; } #if !defined(SUBSURFACE_MOBILE) /* Creates a picture and indicates the dive to which this picture should be added. * The caller is responsible for actually adding the picture to the dive. * If no appropriate dive was found, no picture is created and NULL is returned. */ struct picture *create_picture(const char *filename, int shift_time, bool match_all, struct dive **dive) { struct metadata metadata; timestamp_t timestamp; get_metadata(filename, &metadata); timestamp = metadata.timestamp + shift_time; *dive = nearest_selected_dive(timestamp); if (!*dive) return NULL; if (get_picture_idx(&(*dive)->pictures, filename) >= 0) return NULL; if (!match_all && !dive_check_picture_time(*dive, timestamp)) return NULL; struct picture *picture = malloc(sizeof(struct picture)); picture->filename = strdup(filename); picture->offset.seconds = metadata.timestamp - (*dive)->when + shift_time; picture->location = metadata.location; return picture; } bool picture_check_valid_time(timestamp_t timestamp, int shift_time) { int i; struct dive *dive; for_each_dive (i, dive) if (dive->selected && dive_check_picture_time(dive, timestamp + shift_time)) return true; return false; } #endif
subsurface-for-dirk-master
core/picture.c
// SPDX-License-Identifier: GPL-2.0 #include "subsurface-time.h" #include "subsurface-string.h" #include "gettext.h" #include <string.h> #include <stdio.h> #include <stdlib.h> /* * The date handling internally works in seconds since * Jan 1, 1900. That avoids negative numbers which avoids * some silly problems. * * But we then use the same base epoch base (Jan 1, 1970) * that POSIX uses, so that we can use the normal date * handling functions for getting current time etc. * * There's 25567 dats from Jan 1, 1900 to Jan 1, 1970. * * NOTE! The SEC_PER_DAY is not so much because the * number is complicated, as to make sure we always * expand the type to "timestamp_t" in the arithmetic. */ #define SEC_PER_DAY ((timestamp_t) 24*60*60) #define EPOCH_OFFSET (25567 * SEC_PER_DAY) /* * Convert 64-bit timestamp to 'struct tm' in UTC. * * On 32-bit machines, only do 64-bit arithmetic for the seconds * part, after that we do everything in 'long'. 64-bit divides * are unnecessary once you're counting minutes (32-bit minutes: * 8000+ years). */ void utc_mkdate(timestamp_t timestamp, struct tm *tm) { static const unsigned int mdays[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, }; static const unsigned int mdays_leap[] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, }; unsigned long val; unsigned int leapyears; int m; const unsigned int *mp; memset(tm, 0, sizeof(*tm)); // Midnight at Jan 1, 1970 means "no date" if (!timestamp) return; /* Convert to seconds since 1900 */ timestamp += EPOCH_OFFSET; /* minutes since 1900 */ tm->tm_sec = timestamp % 60; val = timestamp / 60; /* Do the simple stuff */ tm->tm_min = val % 60; val /= 60; tm->tm_hour = val % 24; val /= 24; /* Jan 1, 1900 was a Monday (tm_wday=1) */ tm->tm_wday = (val + 1) % 7; /* * Now we're in "days since Jan 1, 1900". To make things easier, * let's make it "days since Jan 1, 1904", since that's a leap-year. * 1900 itself was not. The following logic will get 1900-1903 * wrong. If you were diving back then, you're kind of screwed. */ val -= 365*4; /* This only works up until 2099 (2100 isn't a leap-year) */ leapyears = val / (365 * 4 + 1); val %= (365 * 4 + 1); tm->tm_year = 1904 + leapyears * 4; /* Handle the leap-year itself */ mp = mdays_leap; if (val > 365) { tm->tm_year++; val -= 366; tm->tm_year += val / 365; val %= 365; mp = mdays; } for (m = 0; m < 12; m++) { if (val < *mp) break; val -= *mp++; } tm->tm_mday = val + 1; tm->tm_mon = m; } timestamp_t utc_mktime(const struct tm *tm) { static const int mdays[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; int year = tm->tm_year; int month = tm->tm_mon; int day = tm->tm_mday; int days_since_1900; timestamp_t when; /* First normalize relative to 1900 */ if (year < 50) year += 100; else if (year >= 1900) year -= 1900; if (year < 0 || year > 129) /* algo only works for 1900-2099 */ return 0; if (month < 0 || month > 11) /* array bounds */ return 0; if (month < 2 || (year && year % 4)) day--; if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_sec < 0) return 0; /* This works until 2099 */ days_since_1900 = year * 365 + (year - 1) / 4; /* Note the 'day' fixup for non-leapyears above */ days_since_1900 += mdays[month] + day; /* Now add it all up, making sure to do this part in "timestamp_t" */ when = days_since_1900 * SEC_PER_DAY; when += tm->tm_hour * 60 * 60 + tm->tm_min * 60 + tm->tm_sec; return when - EPOCH_OFFSET; } /* * Extract year from 64-bit timestamp. * * This looks inefficient, since it breaks down into a full * struct tm. However, modern compilers are effective at throwing * out unused calculations. If it turns out to be a bottle neck * we will have to cache a struct tm per dive. */ int utc_year(timestamp_t timestamp) { struct tm tm; utc_mkdate(timestamp, &tm); return tm.tm_year; } /* * Extract day of week from 64-bit timestamp. * Returns 0-6, whereby 0 is Sunday and 6 is Saturday. * * Same comment as for utc_year(): Modern compilers are good * at throwing out unused calculations, so this is more efficient * than it looks. */ int utc_weekday(timestamp_t timestamp) { struct tm tm; utc_mkdate(timestamp, &tm); return tm.tm_wday; } /* * Try to parse datetime of the form "YYYY-MM-DD hh:mm:ss" or as * an 64-bit decimal and return 64-bit timestamp. On failure or * if passed an empty string, return 0. */ extern timestamp_t parse_datetime(const char *s) { int y, m, d; int hr, min, sec; struct tm tm; if (empty_string(s)) return 0; if (sscanf(s, "%d-%d-%d %d:%d:%d", &y, &m, &d, &hr, &min, &sec) != 6) { char *endptr; timestamp_t res = strtoull(s, &endptr, 10); return *endptr == '\0' ? res : 0; } tm.tm_year = y; tm.tm_mon = m - 1; tm.tm_mday = d; tm.tm_hour = hr; tm.tm_min = min; tm.tm_sec = sec; return utc_mktime(&tm); } /* * Format 64-bit timestamp in the form "YYYY-MM-DD hh:mm:ss". * Returns the empty string for timestamp = 0 */ extern char *format_datetime(timestamp_t timestamp) { char buf[32]; struct tm tm; if (!timestamp) return strdup(""); utc_mkdate(timestamp, &tm); snprintf(buf, sizeof(buf), "%04u-%02u-%02u %02u:%02u:%02u", tm.tm_year, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); return strdup(buf); } /* Turn month (0-12) into three-character short name */ const char *monthname(int mon) { static const char month_array[12][4] = { QT_TRANSLATE_NOOP("gettextFromC", "Jan"), QT_TRANSLATE_NOOP("gettextFromC", "Feb"), QT_TRANSLATE_NOOP("gettextFromC", "Mar"), QT_TRANSLATE_NOOP("gettextFromC", "Apr"), QT_TRANSLATE_NOOP("gettextFromC", "May"), QT_TRANSLATE_NOOP("gettextFromC", "Jun"), QT_TRANSLATE_NOOP("gettextFromC", "Jul"), QT_TRANSLATE_NOOP("gettextFromC", "Aug"), QT_TRANSLATE_NOOP("gettextFromC", "Sep"), QT_TRANSLATE_NOOP("gettextFromC", "Oct"), QT_TRANSLATE_NOOP("gettextFromC", "Nov"), QT_TRANSLATE_NOOP("gettextFromC", "Dec"), }; return translate("gettextFromC", month_array[mon]); }
subsurface-for-dirk-master
core/time.c
// SPDX-License-Identifier: GPL-2.0 #include "subsurfacestartup.h" #include "subsurface-string.h" #include "version.h" #include "errorhelper.h" #include "gettext.h" #include "qthelper.h" #include "git-access.h" #include "pref.h" #include "libdivecomputer/version.h" #include <stdbool.h> #include <string.h> extern void show_computer_list(); int quit, force_root, ignore_bt; #ifdef SUBSURFACE_MOBILE_DESKTOP char *testqml = NULL; #endif /* * track whether we switched to importing dives */ bool imported = false; void print_version() { static bool version_printed = false; if (version_printed) return; #if defined(SUBSURFACE_DOWNLOADER) printf("Subsurface-downloader v%s,\n", subsurface_git_version()); #else printf("Subsurface v%s,\n", subsurface_git_version()); #endif printf("built with libdivecomputer v%s\n", dc_version(NULL)); print_qt_versions(); int git_maj, git_min, git_rev; git_libgit2_version(&git_maj, &git_min, &git_rev); printf("built with libgit2 %d.%d.%d\n", git_maj, git_min, git_rev); version_printed = true; } void print_files() { struct git_info info = { }; const char *filename; printf("\nFile locations:\n\n"); printf("Cloud email:%s\n", prefs.cloud_storage_email); if (!empty_string(prefs.cloud_storage_email) && !empty_string(prefs.cloud_storage_password)) { filename = cloud_url(); is_git_repository(filename, &info); } else { /* strdup so the free below works in either case */ filename = strdup("No valid cloud credentials set.\n"); } if (info.localdir) { printf("Local git storage: %s\n", info.localdir); } else { printf("Unable to get local git directory\n"); } cleanup_git_info(&info); printf("Cloud URL: %s\n", filename); free((void *)filename); char *tmp = hashfile_name_string(); printf("Image filename table: %s\n", tmp); free(tmp); tmp = picturedir_string(); printf("Local picture directory: %s\n\n", tmp); free(tmp); } static void print_help() { print_version(); printf("\nUsage: subsurface [options] [logfile ...] [--import logfile ...]"); printf("\n\noptions include:"); printf("\n --help|-h This help text"); printf("\n --ignore-bt Don't enable Bluetooth support"); printf("\n --import logfile ... Logs before this option is treated as base, everything after is imported"); printf("\n --verbose|-v Verbose debug (repeat to increase verbosity)"); printf("\n --version Prints current version"); printf("\n --user=<test> Choose configuration space for user <test>"); #ifdef SUBSURFACE_MOBILE_DESKTOP printf("\n --testqml=<dir> Use QML files from <dir> instead of QML resources"); #elif SUBSURFACE_DOWNLOADER printf("\n --dc-vendor=vendor Set the dive computer to download from"); printf("\n --dc-product=product Set the dive computer to download from"); printf("\n --device=device Set the device to download from"); #endif printf("\n --cloud-timeout=<nr> Set timeout for cloud connection (0 < timeout < 60)\n\n"); } void parse_argument(const char *arg) { const char *p = arg + 1; do { switch (*p) { case 'h': print_help(); exit(0); case 'v': print_version(); verbose++; continue; case 'q': quit++; continue; case '-': /* long options with -- */ /* first test for --user=bla which allows the use of user specific settings */ if (strncmp(arg, "--user=", sizeof("--user=") - 1) == 0) { settings_suffix = strdup(arg + sizeof("--user=") - 1); return; } if (strncmp(arg, "--cloud-timeout=", sizeof("--cloud-timeout=") - 1) == 0) { const char *timeout = arg + sizeof("--cloud-timeout=") - 1; int to = strtol(timeout, NULL, 10); if (0 < to && to < 60) default_prefs.cloud_timeout = to; return; } if (strcmp(arg, "--help") == 0) { print_help(); exit(0); } if (strcmp(arg, "--ignore-bt") == 0) { ignore_bt = true; return; } if (strcmp(arg, "--import") == 0) { imported = true; /* mark the dives so far as the base, * everything after is imported */ return; } if (strcmp(arg, "--verbose") == 0) { print_version(); verbose++; return; } if (strcmp(arg, "--version") == 0) { print_version(); exit(0); } if (strcmp(arg, "--allow_run_as_root") == 0) { ++force_root; return; } #if SUBSURFACE_DOWNLOADER if (strncmp(arg, "--dc-vendor=", sizeof("--dc-vendor=") - 1) == 0) { prefs.dive_computer.vendor = strdup(arg + sizeof("--dc-vendor=") - 1); return; } if (strncmp(arg, "--dc-product=", sizeof("--dc-product=") - 1) == 0) { prefs.dive_computer.product = strdup(arg + sizeof("--dc-product=") - 1); return; } if (strncmp(arg, "--device=", sizeof("--device=") - 1) == 0) { prefs.dive_computer.device = strdup(arg + sizeof("--device=") - 1); return; } if (strncmp(arg, "--list-dc", sizeof("--list-dc") - 1) == 0) { show_computer_list(); exit(0); } #elif SUBSURFACE_MOBILE_DESKTOP if (strncmp(arg, "--testqml=", sizeof("--testqml=") - 1) == 0) { testqml = malloc(strlen(arg) - sizeof("--testqml=") + 1); strcpy(testqml, arg + sizeof("--testqml=") - 1); return; } #endif /* fallthrough */ case 'p': /* ignore process serial number argument when run as native macosx app */ if (strncmp(arg, "-psQT_TR_NOOP(", 5) == 0) { return; } /* fallthrough */ default: fprintf(stderr, "Bad argument '%s'\n", arg); exit(1); } } while (*++p); } /* * Under a POSIX setup, the locale string should have a format * like [language[_territory][.codeset][@modifier]]. * * So search for the underscore, and see if the "territory" is * US, and turn on imperial units by default. * * I guess Burma and Liberia should trigger this too. I'm too * lazy to look up the territory names, though. */ void setup_system_prefs(void) { const char *env; subsurface_OS_pref_setup(); default_prefs.divelist_font = strdup(system_divelist_default_font); default_prefs.font_size = system_divelist_default_font_size; default_prefs.ffmpeg_executable = strdup("ffmpeg"); #if !defined(SUBSURFACE_MOBILE) default_prefs.default_filename = copy_string(system_default_filename()); #endif env = getenv("LC_MEASUREMENT"); if (!env) env = getenv("LC_ALL"); if (!env) env = getenv("LANG"); if (!env) return; env = strchr(env, '_'); if (!env) return; env++; if (strncmp(env, "US", 2)) return; default_prefs.units = IMPERIAL_units; }
subsurface-for-dirk-master
core/subsurfacestartup.c
// SPDX-License-Identifier: GPL-2.0 #include "event.h" #include "subsurface-string.h" #include <string.h> #include <stdlib.h> int event_is_gaschange(const struct event *ev) { return ev->type == SAMPLE_EVENT_GASCHANGE || ev->type == SAMPLE_EVENT_GASCHANGE2; } bool event_is_divemodechange(const struct event *ev) { return same_string(ev->name, "modechange"); } struct event *clone_event(const struct event *src_ev) { struct event *ev; if (!src_ev) return NULL; size_t size = sizeof(*src_ev) + strlen(src_ev->name) + 1; ev = (struct event*) malloc(size); if (!ev) exit(1); memcpy(ev, src_ev, size); ev->next = NULL; return ev; } void free_events(struct event *ev) { while (ev) { struct event *next = ev->next; free(ev); ev = next; } } struct event *create_event(unsigned int time, int type, int flags, int value, const char *name) { int gas_index = -1; struct event *ev; unsigned int size, len = strlen(name); size = sizeof(*ev) + len + 1; ev = malloc(size); if (!ev) return NULL; memset(ev, 0, size); memcpy(ev->name, name, len); ev->time.seconds = time; ev->type = type; ev->flags = flags; ev->value = value; /* * Expand the events into a sane format. Currently * just gas switches */ switch (type) { case SAMPLE_EVENT_GASCHANGE2: /* High 16 bits are He percentage */ ev->gas.mix.he.permille = (value >> 16) * 10; /* Extension to the GASCHANGE2 format: cylinder index in 'flags' */ /* TODO: verify that gas_index < num_cylinders. */ if (flags > 0) gas_index = flags-1; /* Fallthrough */ case SAMPLE_EVENT_GASCHANGE: /* Low 16 bits are O2 percentage */ ev->gas.mix.o2.permille = (value & 0xffff) * 10; ev->gas.index = gas_index; break; } return ev; } struct event *clone_event_rename(const struct event *ev, const char *name) { return create_event(ev->time.seconds, ev->type, ev->flags, ev->value, name); } bool same_event(const struct event *a, const struct event *b) { if (a->time.seconds != b->time.seconds) return 0; if (a->type != b->type) return 0; if (a->flags != b->flags) return 0; if (a->value != b->value) return 0; return !strcmp(a->name, b->name); } /* collect all event names and whether we display them */ struct ev_select *ev_namelist = NULL; int evn_used = 0; static int evn_allocated = 0; void clear_events(void) { for (int i = 0; i < evn_used; i++) free(ev_namelist[i].ev_name); evn_used = 0; } void remember_event(const char *eventname) { int i = 0, len; if (!eventname || (len = strlen(eventname)) == 0) return; while (i < evn_used) { if (!strncmp(eventname, ev_namelist[i].ev_name, len)) return; i++; } if (evn_used == evn_allocated) { evn_allocated += 10; ev_namelist = realloc(ev_namelist, evn_allocated * sizeof(struct ev_select)); if (!ev_namelist) /* we are screwed, but let's just bail out */ return; } ev_namelist[evn_used].ev_name = strdup(eventname); ev_namelist[evn_used].plot_ev = true; evn_used++; }
subsurface-for-dirk-master
core/event.c
// SPDX-License-Identifier: GPL-2.0 #include "divecomputer.h" #include "event.h" #include "extradata.h" #include "pref.h" #include "sample.h" #include "structured_list.h" #include "subsurface-string.h" #include <string.h> #include <stdlib.h> /* * Good fake dive profiles are hard. * * "depthtime" is the integral of the dive depth over * time ("area" of the dive profile). We want that * area to match the average depth (avg_d*max_t). * * To do that, we generate a 6-point profile: * * (0, 0) * (t1, max_d) * (t2, max_d) * (t3, d) * (t4, d) * (max_t, 0) * * with the same ascent/descent rates between the * different depths. * * NOTE: avg_d, max_d and max_t are given constants. * The rest we can/should play around with to get a * good-looking profile. * * That six-point profile gives a total area of: * * (max_d*max_t) - (max_d*t1) - (max_d-d)*(t4-t3) * * And the "same ascent/descent rates" requirement * gives us (time per depth must be same): * * t1 / max_d = (t3-t2) / (max_d-d) * t1 / max_d = (max_t-t4) / d * * We also obviously require: * * 0 <= t1 <= t2 <= t3 <= t4 <= max_t * * Let us call 'd_frac = d / max_d', and we get: * * Total area must match average depth-time: * * (max_d*max_t) - (max_d*t1) - (max_d-d)*(t4-t3) = avg_d*max_t * max_d*(max_t-t1-(1-d_frac)*(t4-t3)) = avg_d*max_t * max_t-t1-(1-d_frac)*(t4-t3) = avg_d*max_t/max_d * t1+(1-d_frac)*(t4-t3) = max_t*(1-avg_d/max_d) * * and descent slope must match ascent slopes: * * t1 / max_d = (t3-t2) / (max_d*(1-d_frac)) * t1 = (t3-t2)/(1-d_frac) * * and * * t1 / max_d = (max_t-t4) / (max_d*d_frac) * t1 = (max_t-t4)/d_frac * * In general, we have more free variables than we have constraints, * but we can aim for certain basics, like a good ascent slope. */ static int fill_samples(struct sample *s, int max_d, int avg_d, int max_t, double slope, double d_frac) { double t_frac = max_t * (1 - avg_d / (double)max_d); int t1 = lrint(max_d / slope); int t4 = lrint(max_t - t1 * d_frac); int t3 = lrint(t4 - (t_frac - t1) / (1 - d_frac)); int t2 = lrint(t3 - t1 * (1 - d_frac)); if (t1 < 0 || t1 > t2 || t2 > t3 || t3 > t4 || t4 > max_t) return 0; s[1].time.seconds = t1; s[1].depth.mm = max_d; s[2].time.seconds = t2; s[2].depth.mm = max_d; s[3].time.seconds = t3; s[3].depth.mm = lrint(max_d * d_frac); s[4].time.seconds = t4; s[4].depth.mm = lrint(max_d * d_frac); return 1; } /* we have no average depth; instead of making up a random average depth * we should assume either a PADI rectangular profile (for short and/or * shallow dives) or more reasonably a six point profile with a 3 minute * safety stop at 5m */ static void fill_samples_no_avg(struct sample *s, int max_d, int max_t, double slope) { // shallow or short dives are just trapecoids based on the given slope if (max_d < 10000 || max_t < 600) { s[1].time.seconds = lrint(max_d / slope); s[1].depth.mm = max_d; s[2].time.seconds = max_t - lrint(max_d / slope); s[2].depth.mm = max_d; } else { s[1].time.seconds = lrint(max_d / slope); s[1].depth.mm = max_d; s[2].time.seconds = max_t - lrint(max_d / slope) - 180; s[2].depth.mm = max_d; s[3].time.seconds = max_t - lrint(5000 / slope) - 180; s[3].depth.mm = 5000; s[4].time.seconds = max_t - lrint(5000 / slope); s[4].depth.mm = 5000; } } void fake_dc(struct divecomputer *dc) { alloc_samples(dc, 6); struct sample *fake = dc->sample; int i; dc->samples = 6; /* The dive has no samples, so create a few fake ones */ int max_t = dc->duration.seconds; int max_d = dc->maxdepth.mm; int avg_d = dc->meandepth.mm; memset(fake, 0, 6 * sizeof(struct sample)); fake[5].time.seconds = max_t; for (i = 0; i < 6; i++) { fake[i].bearing.degrees = -1; fake[i].ndl.seconds = -1; } if (!max_t || !max_d) { dc->samples = 0; return; } /* Set last manually entered time to the total dive length */ dc->last_manual_time = dc->duration; /* * We want to fake the profile so that the average * depth ends up correct. However, in the absence of * a reasonable average, let's just make something * up. Note that 'avg_d == max_d' is _not_ a reasonable * average. * We explicitly treat avg_d == 0 differently */ if (avg_d == 0) { /* we try for a sane slope, but bow to the insanity of * the user supplied data */ fill_samples_no_avg(fake, max_d, max_t, MAX(2.0 * max_d / max_t, (double)prefs.ascratelast6m)); if (fake[3].time.seconds == 0) { // just a 4 point profile dc->samples = 4; fake[3].time.seconds = max_t; } return; } if (avg_d < max_d / 10 || avg_d >= max_d) { avg_d = (max_d + 10000) / 3; if (avg_d > max_d) avg_d = max_d * 2 / 3; } if (!avg_d) avg_d = 1; /* * Ok, first we try a basic profile with a specific ascent * rate (5 meters per minute) and d_frac (1/3). */ if (fill_samples(fake, max_d, avg_d, max_t, (double)prefs.ascratelast6m, 0.33)) return; /* * Ok, assume that didn't work because we cannot make the * average come out right because it was a quick deep dive * followed by a much shallower region */ if (fill_samples(fake, max_d, avg_d, max_t, 10000.0 / 60, 0.10)) return; /* * Uhhuh. That didn't work. We'd need to find a good combination that * satisfies our constraints. Currently, we don't, we just give insane * slopes. */ if (fill_samples(fake, max_d, avg_d, max_t, 10000.0, 0.01)) return; /* Even that didn't work? Give up, there's something wrong */ } /* Find the divemode at time 'time' (in seconds) into the dive. Sequentially step through the divemode-change events, * saving the dive mode for each event. When the events occur AFTER 'time' seconds, the last stored divemode * is returned. This function is self-tracking, relying on setting the event pointer 'evp' so that, in each iteration * that calls this function, the search does not have to begin at the first event of the dive */ enum divemode_t get_current_divemode(const struct divecomputer *dc, int time, const struct event **evp, enum divemode_t *divemode) { const struct event *ev = *evp; if (dc) { if (*divemode == UNDEF_COMP_TYPE) { *divemode = dc->divemode; ev = get_next_event(dc->events, "modechange"); } } else { ev = NULL; } while (ev && ev->time.seconds < time) { *divemode = (enum divemode_t) ev->value; ev = get_next_event(ev->next, "modechange"); } *evp = ev; return *divemode; } /* helper function to make it easier to work with our structures * we don't interpolate here, just use the value from the last sample up to that time */ int get_depth_at_time(const struct divecomputer *dc, unsigned int time) { int depth = 0; if (dc && dc->sample) for (int i = 0; i < dc->samples; i++) { if (dc->sample[i].time.seconds > time) break; depth = dc->sample[i].depth.mm; } return depth; } /* The first divecomputer is embedded in the dive structure. Free its data but not * the structure itself. For all remainding dcs in the list, free data *and* structures. */ void free_dive_dcs(struct divecomputer *dc) { free_dc_contents(dc); STRUCTURED_LIST_FREE(struct divecomputer, dc->next, free_dc); } /* make room for num samples; if not enough space is available, the sample * array is reallocated and the existing samples are copied. */ void alloc_samples(struct divecomputer *dc, int num) { if (num > dc->alloc_samples) { dc->alloc_samples = (num * 3) / 2 + 10; dc->sample = realloc(dc->sample, dc->alloc_samples * sizeof(struct sample)); if (!dc->sample) dc->samples = dc->alloc_samples = 0; } } void free_samples(struct divecomputer *dc) { if (dc) { free(dc->sample); dc->sample = 0; dc->samples = 0; dc->alloc_samples = 0; } } struct sample *prepare_sample(struct divecomputer *dc) { if (dc) { int nr = dc->samples; struct sample *sample; alloc_samples(dc, nr + 1); if (!dc->sample) return NULL; sample = dc->sample + nr; memset(sample, 0, sizeof(*sample)); // Copy the sensor numbers - but not the pressure values // from the previous sample if any. if (nr) { for (int idx = 0; idx < MAX_SENSORS; idx++) sample->sensor[idx] = sample[-1].sensor[idx]; } // Init some values with -1 sample->bearing.degrees = -1; sample->ndl.seconds = -1; return sample; } return NULL; } void finish_sample(struct divecomputer *dc) { dc->samples++; } struct sample *add_sample(const struct sample *sample, int time, struct divecomputer *dc) { struct sample *p = prepare_sample(dc); if (p) { *p = *sample; p->time.seconds = time; finish_sample(dc); } return p; } /* * Calculate how long we were actually under water, and the average * depth while under water. * * This ignores any surface time in the middle of the dive. */ void fixup_dc_duration(struct divecomputer *dc) { int duration, i; int lasttime, lastdepth, depthtime; duration = 0; lasttime = 0; lastdepth = 0; depthtime = 0; for (i = 0; i < dc->samples; i++) { struct sample *sample = dc->sample + i; int time = sample->time.seconds; int depth = sample->depth.mm; /* We ignore segments at the surface */ if (depth > SURFACE_THRESHOLD || lastdepth > SURFACE_THRESHOLD) { duration += time - lasttime; depthtime += (time - lasttime) * (depth + lastdepth) / 2; } lastdepth = depth; lasttime = time; } if (duration) { dc->duration.seconds = duration; dc->meandepth.mm = (depthtime + duration / 2) / duration; } } /* * What do the dive computers say the water temperature is? * (not in the samples, but as dc property for dcs that support that) */ unsigned int dc_watertemp(const struct divecomputer *dc) { int sum = 0, nr = 0; do { if (dc->watertemp.mkelvin) { sum += dc->watertemp.mkelvin; nr++; } } while ((dc = dc->next) != NULL); if (!nr) return 0; return (sum + nr / 2) / nr; } /* * What do the dive computers say the air temperature is? */ unsigned int dc_airtemp(const struct divecomputer *dc) { int sum = 0, nr = 0; do { if (dc->airtemp.mkelvin) { sum += dc->airtemp.mkelvin; nr++; } } while ((dc = dc->next) != NULL); if (!nr) return 0; return (sum + nr / 2) / nr; } /* copies all events in this dive computer */ void copy_events(const struct divecomputer *s, struct divecomputer *d) { const struct event *ev; struct event **pev; if (!s || !d) return; ev = s->events; pev = &d->events; while (ev != NULL) { struct event *new_ev = clone_event(ev); *pev = new_ev; pev = &new_ev->next; ev = ev->next; } *pev = NULL; } void copy_samples(const struct divecomputer *s, struct divecomputer *d) { /* instead of carefully copying them one by one and calling add_sample * over and over again, let's just copy the whole blob */ if (!s || !d) return; int nr = s->samples; d->samples = nr; d->alloc_samples = nr; // We expect to be able to read the memory in the other end of the pointer // if its a valid pointer, so don't expect malloc() to return NULL for // zero-sized malloc, do it ourselves. d->sample = NULL; if(!nr) return; d->sample = malloc(nr * sizeof(struct sample)); if (d->sample) memcpy(d->sample, s->sample, nr * sizeof(struct sample)); } void add_event_to_dc(struct divecomputer *dc, struct event *ev) { struct event **p; p = &dc->events; /* insert in the sorted list of events */ while (*p && (*p)->time.seconds <= ev->time.seconds) p = &(*p)->next; ev->next = *p; *p = ev; } struct event *add_event(struct divecomputer *dc, unsigned int time, int type, int flags, int value, const char *name) { struct event *ev = create_event(time, type, flags, value, name); if (!ev) return NULL; add_event_to_dc(dc, ev); remember_event(name); return ev; } /* Substitutes an event in a divecomputer for another. No reordering is performed! */ void swap_event(struct divecomputer *dc, struct event *from, struct event *to) { for (struct event **ep = &dc->events; *ep; ep = &(*ep)->next) { if (*ep == from) { to->next = from->next; *ep = to; from->next = NULL; // For good measure. break; } } } /* Remove given event from dive computer. Does *not* free the event. */ void remove_event_from_dc(struct divecomputer *dc, struct event *event) { for (struct event **ep = &dc->events; *ep; ep = &(*ep)->next) { if (*ep == event) { *ep = event->next; event->next = NULL; // For good measure. break; } } } void add_extra_data(struct divecomputer *dc, const char *key, const char *value) { struct extra_data **ed = &dc->extra_data; if (!strcasecmp(key, "Serial")) { dc->deviceid = calculate_string_hash(value); dc->serial = strdup(value); } if (!strcmp(key, "FW Version")) { dc->fw_version = strdup(value); } while (*ed) ed = &(*ed)->next; *ed = malloc(sizeof(struct extra_data)); if (*ed) { (*ed)->key = strdup(key); (*ed)->value = strdup(value); (*ed)->next = NULL; } } bool is_dc_planner(const struct divecomputer *dc) { return same_string(dc->model, "planned dive"); } /* * Match two dive computer entries against each other, and * tell if it's the same dive. Return 0 if "don't know", * positive for "same dive" and negative for "definitely * not the same dive" */ int match_one_dc(const struct divecomputer *a, const struct divecomputer *b) { /* Not same model? Don't know if matching.. */ if (!a->model || !b->model) return 0; if (strcasecmp(a->model, b->model)) return 0; /* Different device ID's? Don't know */ if (a->deviceid != b->deviceid) return 0; /* Do we have dive IDs? */ if (!a->diveid || !b->diveid) return 0; /* * If they have different dive ID's on the same * dive computer, that's a definite "same or not" */ return a->diveid == b->diveid && a->when == b->when ? 1 : -1; } static void free_extra_data(struct extra_data *ed) { free((void *)ed->key); free((void *)ed->value); } void free_dc_contents(struct divecomputer *dc) { free(dc->sample); free((void *)dc->model); free((void *)dc->serial); free((void *)dc->fw_version); free_events(dc->events); STRUCTURED_LIST_FREE(struct extra_data, dc->extra_data, free_extra_data); } void free_dc(struct divecomputer *dc) { free_dc_contents(dc); free(dc); }
subsurface-for-dirk-master
core/divecomputer.c
// SPDX-License-Identifier: GPL-2.0 #ifdef __clang__ // Clang has a bug on zero-initialization of C structs. #pragma clang diagnostic ignored "-Wmissing-field-initializers" #endif #include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include <string.h> #include <time.h> #include "gettext.h" #include "datatrak.h" #include "subsurface-string.h" #include "units.h" #include "device.h" #include "file.h" #include "divesite.h" #include "dive.h" #include "errorhelper.h" #include "ssrf.h" #include "tag.h" static unsigned int two_bytes_to_int(unsigned char x, unsigned char y) { return (x << 8) + y; } static unsigned long four_bytes_to_long(unsigned char x, unsigned char y, unsigned char z, unsigned char t) { return ((long)x << 24) + ((long)y << 16) + ((long)z << 8) + (long)t; } static bool bit_set(unsigned char byte, int bit) { return byte & (1 << bit); } /* * Datatrak stores the date in days since 01-01-1600, while Subsurface uses * time_t (seconds since 00:00 01-01-1970). Function subtracts * (1970 - 1600) * 365,2425 = 135139,725 to our date variable, getting the * days since Epoch. */ static time_t date_time_to_ssrfc(unsigned long date, int time) { time_t tmp; tmp = (date - 135140) * 86400 + time * 60; return tmp; } static unsigned char to_8859(unsigned char char_cp850) { static const unsigned char char_8859[46] = { 0xc7, 0xfc, 0xe9, 0xe2, 0xe4, 0xe0, 0xe5, 0xe7, 0xea, 0xeb, 0xe8, 0xef, 0xee, 0xec, 0xc4, 0xc5, 0xc9, 0xe6, 0xc6, 0xf4, 0xf6, 0xf2, 0xfb, 0xf9, 0xff, 0xd6, 0xdc, 0xf8, 0xa3, 0xd8, 0xd7, 0x66, 0xe1, 0xed, 0xf3, 0xfa, 0xf1, 0xd1, 0xaa, 0xba, 0xbf, 0xae, 0xac, 0xbd, 0xbc, 0xa1 }; return char_8859[char_cp850 - 0x80]; } static char *to_utf8(unsigned char *in_string) { int outlen, inlen, i = 0, j = 0; inlen = strlen((char *)in_string); outlen = inlen * 2 + 1; char *out_string = calloc(outlen, 1); for (i = 0; i < inlen; i++) { if (in_string[i] < 127) { out_string[j] = in_string[i]; } else { if (in_string[i] > 127 && in_string[i] <= 173) in_string[i] = to_8859(in_string[i]); out_string[j] = (in_string[i] >> 6) | 0xC0; j++; out_string[j] = (in_string[i] & 0x3F) | 0x80; } j++; } out_string[j + 1] = '\0'; return out_string; } /* * Reads the header of a datatrak buffer and returns the number of * dives; zero on error (meaning this isn't a datatrak file). * All other info in the header is useless for Subsurface. */ static int read_file_header(unsigned char *buffer) { int n = 0; if (two_bytes_to_int(buffer[0], buffer[1]) == 0xA100) n = two_bytes_to_int(buffer[7], buffer[6]); return n; } /* * Fills a device_data_t structure based on the info from g_models table, using * the dc's model number as start point. * Returns libdc's equivalent model number (also from g_models) or zero if * this a manual dive. */ static int dtrak_prepare_data(int model, device_data_t *dev_data) { dc_descriptor_t *d = NULL; int i = 0; while (model != g_models[i].model_num && g_models[i].model_num != 0xEE) i++; dev_data->model = copy_string(g_models[i].name); dev_data->vendor = (const char *)malloc(strlen(g_models[i].name) + 1); sscanf(g_models[i].name, "%[A-Za-z] ", (char *)dev_data->vendor); dev_data->product = copy_string(strchr(g_models[i].name, ' ') + 1); d = get_descriptor(g_models[i].type, g_models[i].libdc_num); if (d) dev_data->descriptor = d; else return 0; return g_models[i].libdc_num; } /* * Return a default name for a tank based on it's size. * Just get the first in the user's list for given size. * Reaching the end of the list means there is no tank of this size. */ static const char *cyl_type_by_size(int size) { for (int i = 0; i < tank_info_table.nr; ++i) { const struct tank_info *ti = &tank_info_table.infos[i]; if (ti->ml == size) return ti->name; } return ""; } /* * Reads the size of a datatrak profile from actual position in buffer *ptr, * zero padds it with a faked header and inserts the model number for * libdivecomputer parsing. Puts the completed buffer in a pre-allocated * compl_buffer, and returns status. */ static dc_status_t dt_libdc_buffer(unsigned char *ptr, int prf_length, int dc_model, unsigned char *compl_buffer) { if (compl_buffer == NULL) return DC_STATUS_NOMEMORY; compl_buffer[3] = (unsigned char) dc_model; memcpy(compl_buffer + 18, ptr, prf_length); return DC_STATUS_SUCCESS; } /* * Parses a mem buffer extracting its data and filling a subsurface's dive structure. * Returns a pointer to last position in buffer, or NULL on failure. */ static unsigned char *dt_dive_parser(unsigned char *runner, struct dive *dt_dive, struct dive_site_table *sites, struct device_table *devices, long maxbuf) { int rc, profile_length, libdc_model; char *tmp_notes_str = NULL; unsigned char *tmp_string1 = NULL, *locality = NULL, *dive_point = NULL, *compl_buffer, *membuf = runner; char buffer[1024]; unsigned char tmp_1byte; unsigned int tmp_2bytes; unsigned long tmp_4bytes; struct dive_site *ds; char is_nitrox = 0, is_O2 = 0, is_SCR = 0; device_data_t *devdata = calloc(1, sizeof(device_data_t)); devdata->sites = sites; devdata->devices = devices; /* * Parse byte to byte till next dive entry */ while (membuf[0] != 0xA0 || membuf[1] != 0x00) { JUMP(membuf, 1); } JUMP(membuf, 2); /* * Begin parsing * First, Date of dive, 4 bytes */ read_bytes(4); /* * Next, Time in minutes since 00:00 */ read_bytes(2); dt_dive->dc.when = dt_dive->when = (timestamp_t)date_time_to_ssrfc(tmp_4bytes, tmp_2bytes); /* * Now, Locality, 1st byte is long of string, rest is string */ read_bytes(1); read_string(locality); /* * Next, Dive point, defined as Locality */ read_bytes(1); read_string(dive_point); /* * Subsurface only have a location variable, so we have to merge DTrak's * Locality and Dive points. */ snprintf(buffer, sizeof(buffer), "%s, %s", locality, dive_point); ds = get_dive_site_by_name(buffer, sites); if (!ds) ds = create_dive_site(buffer, sites); add_dive_to_dive_site(dt_dive, ds); free(locality); locality = NULL; free(dive_point); /* * Altitude. Don't exist in Subsurface, the equivalent would be * surface air pressure which can, be calculated from altitude. * As dtrak registers altitude intervals, we, arbitrarily, choose * the lower altitude/pressure equivalence for each segment. So * * Datatrak table * Conversion formula: * * * byte = 1 0 - 700 m * P = P0 * exp(-(g * M * h ) / (R * T0)) * byte = 2 700 - 1700m * P0 = sealevel pressure = 101325 Pa * byte = 3 1700 - 2700 m * g = grav. acceleration = 9,80665 m/s² * byte = 4 2700 - * m * M = molar mass (dry air) = 0,0289644 Kg/mol * * h = altitude over sea level (m) * * R = Universal gas constant = 8,31447 J/(mol*K) * * T0 = sea level standard temperature = 288,15 K */ read_bytes(1); switch (tmp_1byte) { case 1: dt_dive->dc.surface_pressure.mbar = 1013; break; case 2: dt_dive->dc.surface_pressure.mbar = 932; break; case 3: dt_dive->dc.surface_pressure.mbar = 828; break; case 4: dt_dive->dc.surface_pressure.mbar = 735; break; default: dt_dive->dc.surface_pressure.mbar = 1013; } /* * Interval (minutes) */ read_bytes(2); if (tmp_2bytes != 0x7FFF) dt_dive->dc.surfacetime.seconds = (uint32_t) tmp_2bytes * 60; /* * Weather, values table, 0 to 6 * Subsurface don't have this record but we can use tags */ dt_dive->tag_list = NULL; read_bytes(1); switch (tmp_1byte) { case 1: taglist_add_tag(&dt_dive->tag_list, strdup(QT_TRANSLATE_NOOP("gettextFromC", "clear"))); break; case 2: taglist_add_tag(&dt_dive->tag_list, strdup(QT_TRANSLATE_NOOP("gettextFromC", "misty"))); break; case 3: taglist_add_tag(&dt_dive->tag_list, strdup(QT_TRANSLATE_NOOP("gettextFromC", "fog"))); break; case 4: taglist_add_tag(&dt_dive->tag_list, strdup(QT_TRANSLATE_NOOP("gettextFromC", "rain"))); break; case 5: taglist_add_tag(&dt_dive->tag_list, strdup(QT_TRANSLATE_NOOP("gettextFromC", "storm"))); break; case 6: taglist_add_tag(&dt_dive->tag_list, strdup(QT_TRANSLATE_NOOP("gettextFromC", "snow"))); break; default: // unknown, do nothing break; } /* * Air Temperature */ read_bytes(2); if (tmp_2bytes != 0x7FFF) dt_dive->dc.airtemp.mkelvin = C_to_mkelvin((double)(tmp_2bytes / 100)); /* * Dive suit, values table, 0 to 6 */ read_bytes(1); switch (tmp_1byte) { case 1: dt_dive->suit = strdup(QT_TRANSLATE_NOOP("gettextFromC", "No suit")); break; case 2: dt_dive->suit = strdup(QT_TRANSLATE_NOOP("gettextFromC", "Shorty")); break; case 3: dt_dive->suit = strdup(QT_TRANSLATE_NOOP("gettextFromC", "Combi")); break; case 4: dt_dive->suit = strdup(QT_TRANSLATE_NOOP("gettextFromC", "Wet suit")); break; case 5: dt_dive->suit = strdup(QT_TRANSLATE_NOOP("gettextFromC", "Semidry suit")); break; case 6: dt_dive->suit = strdup(QT_TRANSLATE_NOOP("gettextFromC", "Dry suit")); break; default: // unknown, do nothing break; } /* * Tank, volume size in liter*100. And initialize gasmix to air (default). * Dtrak doesn't record init and end pressures, but consumed bar, so let's * init a default pressure of 200 bar. */ read_bytes(2); if (tmp_2bytes != 0x7FFF) { cylinder_t cyl = empty_cylinder; cyl.type.size.mliter = tmp_2bytes * 10; cyl.type.description = cyl_type_by_size(tmp_2bytes * 10); cyl.start.mbar = 200000; cyl.gasmix.he.permille = 0; cyl.gasmix.o2.permille = 210; cyl.manually_added = true; add_cloned_cylinder(&dt_dive->cylinders, cyl); } /* * Maximum depth, in cm. */ read_bytes(2); if (tmp_2bytes != 0x7FFF) dt_dive->maxdepth.mm = dt_dive->dc.maxdepth.mm = (int32_t)tmp_2bytes * 10; /* * Dive time in minutes. */ read_bytes(2); if (tmp_2bytes != 0x7FFF) dt_dive->duration.seconds = dt_dive->dc.duration.seconds = (uint32_t)tmp_2bytes * 60; /* * Minimum water temperature in C*100. If unknown, set it to 0K which * is subsurface's value for "unknown" */ read_bytes(2); if (tmp_2bytes != 0x7fff) dt_dive->watertemp.mkelvin = dt_dive->dc.watertemp.mkelvin = C_to_mkelvin((double)(tmp_2bytes / 100)); else dt_dive->watertemp.mkelvin = 0; /* * Air used in bar*100. */ read_bytes(2); if (tmp_2bytes != 0x7FFF && dt_dive->cylinders.nr > 0) get_cylinder(dt_dive, 0)->gas_used.mliter = lrint(get_cylinder(dt_dive, 0)->type.size.mliter * (tmp_2bytes / 100.0)); /* * Dive Type 1 - Bit table. Subsurface don't have this record, but * will use tags. Bits 0 and 1 are not used. Reuse coincident tags. */ read_bytes(1); if (bit_set(tmp_1byte, 2)) taglist_add_tag(&dt_dive->tag_list, strdup(QT_TRANSLATE_NOOP("gettextFromC", "no stop"))); if (bit_set(tmp_1byte, 3)) taglist_add_tag(&dt_dive->tag_list, strdup(QT_TRANSLATE_NOOP("gettextFromC", "deco"))); if (bit_set(tmp_1byte, 4)) taglist_add_tag(&dt_dive->tag_list, strdup(QT_TRANSLATE_NOOP("gettextFromC", "single ascent"))); if (bit_set(tmp_1byte, 5)) taglist_add_tag(&dt_dive->tag_list, strdup(QT_TRANSLATE_NOOP("gettextFromC", "multiple ascent"))); if (bit_set(tmp_1byte, 6)) taglist_add_tag(&dt_dive->tag_list, strdup(QT_TRANSLATE_NOOP("gettextFromC", "fresh water"))); if (bit_set(tmp_1byte, 7)) taglist_add_tag(&dt_dive->tag_list, strdup(QT_TRANSLATE_NOOP("gettextFromC", "salt water"))); /* * Dive Type 2 - Bit table, use tags again */ read_bytes(1); if (bit_set(tmp_1byte, 0)) { taglist_add_tag(&dt_dive->tag_list, strdup("nitrox")); is_nitrox = 1; } if (bit_set(tmp_1byte, 1)) { taglist_add_tag(&dt_dive->tag_list, strdup("rebreather")); is_SCR = 1; dt_dive->dc.divemode = PSCR; } /* * Dive Activity 1 - Bit table, use tags again */ read_bytes(1); if (bit_set(tmp_1byte, 0)) taglist_add_tag(&dt_dive->tag_list, strdup(QT_TRANSLATE_NOOP("gettextFromC", "sight seeing"))); if (bit_set(tmp_1byte, 1)) taglist_add_tag(&dt_dive->tag_list, strdup(QT_TRANSLATE_NOOP("gettextFromC", "club dive"))); if (bit_set(tmp_1byte, 2)) taglist_add_tag(&dt_dive->tag_list, strdup(QT_TRANSLATE_NOOP("gettextFromC", "instructor"))); if (bit_set(tmp_1byte, 3)) taglist_add_tag(&dt_dive->tag_list, strdup(QT_TRANSLATE_NOOP("gettextFromC", "instruction"))); if (bit_set(tmp_1byte, 4)) taglist_add_tag(&dt_dive->tag_list, strdup(QT_TRANSLATE_NOOP("gettextFromC", "night"))); if (bit_set(tmp_1byte, 5)) taglist_add_tag(&dt_dive->tag_list, strdup(QT_TRANSLATE_NOOP("gettextFromC", "cave"))); if (bit_set(tmp_1byte, 6)) taglist_add_tag(&dt_dive->tag_list, strdup(QT_TRANSLATE_NOOP("gettextFromC", "ice"))); if (bit_set(tmp_1byte, 7)) taglist_add_tag(&dt_dive->tag_list, strdup(QT_TRANSLATE_NOOP("gettextFromC", "search"))); /* * Dive Activity 2 - Bit table, use tags again */ read_bytes(1); if (bit_set(tmp_1byte, 0)) taglist_add_tag(&dt_dive->tag_list, strdup(QT_TRANSLATE_NOOP("gettextFromC", "wreck"))); if (bit_set(tmp_1byte, 1)) taglist_add_tag(&dt_dive->tag_list, strdup(QT_TRANSLATE_NOOP("gettextFromC", "river"))); if (bit_set(tmp_1byte, 2)) taglist_add_tag(&dt_dive->tag_list, strdup(QT_TRANSLATE_NOOP("gettextFromC", "drift"))); if (bit_set(tmp_1byte, 3)) taglist_add_tag(&dt_dive->tag_list, strdup(QT_TRANSLATE_NOOP("gettextFromC", "photo"))); if (bit_set(tmp_1byte, 4)) taglist_add_tag(&dt_dive->tag_list, strdup(QT_TRANSLATE_NOOP("gettextFromC", "other"))); /* * Other activities - String 1st byte = long * Will put this in dive notes before the true notes */ read_bytes(1); if (tmp_1byte != 0) { read_string(tmp_string1); snprintf(buffer, sizeof(buffer), "%s: %s\n", QT_TRANSLATE_NOOP("gettextFromC", "Other activities"), tmp_string1); tmp_notes_str = strdup(buffer); free(tmp_string1); } /* * Dive buddies */ read_bytes(1); if (tmp_1byte != 0) { read_string(tmp_string1); dt_dive->buddy = strdup((char *)tmp_string1); free(tmp_string1); } /* * Dive notes */ read_bytes(1); if (tmp_1byte != 0) { read_string(tmp_string1); int len = snprintf(buffer, sizeof(buffer), "%s%s:\n%s", tmp_notes_str ? tmp_notes_str : "", QT_TRANSLATE_NOOP("gettextFromC", "Datatrak/Wlog notes"), tmp_string1); dt_dive->notes = calloc((len +1), 1); dt_dive->notes = memcpy(dt_dive->notes, buffer, len); free(tmp_string1); } free(tmp_notes_str); /* * Alarms 1 and Alarms2 - Bit tables - Not in Subsurface, we use the profile */ JUMP(membuf, 2); /* * Dive number (in datatrak, after import user has to renumber) */ read_bytes(2); dt_dive->number = tmp_2bytes; /* * Computer timestamp - Useless for Subsurface */ JUMP(membuf, 4); /* * Model number to check against equivalence with libdivecomputer table. * The number also defines if the model is nitrox or O2 capable. */ read_bytes(1); switch (tmp_1byte & 0xF0) { case 0xF0: is_nitrox = 1; break; case 0xA0: is_O2 = 1; break; default: is_nitrox = 0; is_O2 = 0; break; } libdc_model = dtrak_prepare_data(tmp_1byte, devdata); if (!libdc_model) report_error(translate("gettextFromC", "[Warning] Manual dive # %d\n"), dt_dive->number); dt_dive->dc.model = copy_string(devdata->model); /* * Air usage, unknown use. Probably allows or deny manually entering gas * comsumption based on dc model - Useless for Subsurface * And 6 bytes without known use. */ JUMP(membuf, 7); /* * Profile data length */ read_bytes(2); profile_length = tmp_2bytes; /* * Profile parsing, only if we have a profile and a dc model. * If just a profile, skip parsing and seek the buffer to the end of dive. */ if (profile_length != 0 && libdc_model != 0) { compl_buffer = (unsigned char *) calloc(18 + profile_length, 1); rc = dt_libdc_buffer(membuf, profile_length, libdc_model, compl_buffer); if (rc == DC_STATUS_SUCCESS) { libdc_buffer_parser(dt_dive, devdata, compl_buffer, profile_length + 18); } else { report_error(translate("gettextFromC", "[Error] Out of memory for dive %d. Abort parsing."), dt_dive->number); free(compl_buffer); goto bail; } if (is_nitrox && dt_dive->cylinders.nr > 0) get_cylinder(dt_dive, 0)->gasmix.o2.permille = lrint(membuf[23] & 0x0F ? 20.0 + 2 * (membuf[23] & 0x0F) : 21.0) * 10; if (is_O2 && dt_dive->cylinders.nr > 0) get_cylinder(dt_dive, 0)->gasmix.o2.permille = membuf[23] * 10; free(compl_buffer); } JUMP(membuf, profile_length); /* * Initialize some dive data not supported by Datatrak/WLog */ if (!libdc_model) dt_dive->dc.deviceid = 0; else dt_dive->dc.deviceid = 0xffffffff; dt_dive->dc.next = NULL; if (!is_SCR && dt_dive->cylinders.nr > 0) { get_cylinder(dt_dive, 0)->end.mbar = get_cylinder(dt_dive, 0)->start.mbar - ((get_cylinder(dt_dive, 0)->gas_used.mliter / get_cylinder(dt_dive, 0)->type.size.mliter) * 1000); } free(devdata); return membuf; bail: free(locality); free(devdata); return NULL; } /* * Parses the header of the .add file, returns the number of dives in * the archive (must be the same than number of dives in .log file). */ static int wlog_header_parser (struct memblock *mem) { int tmp; unsigned char *runner = (unsigned char *) mem->buffer; if (!runner) return -1; if (!memcmp(runner, "\x52\x02", 2)) { runner += 8; tmp = (int) two_bytes_to_int(runner[1], runner[0]); return tmp; } else { fprintf(stderr, "Error, not a Wlog .add file\n"); return -1; } } #define NOTES_LENGTH 256 #define SUIT_LENGTH 26 static void wlog_compl_parser(struct memblock *wl_mem, struct dive *dt_dive, int dcount) { int tmp = 0, offset = 12 + (dcount * 850), pos_weight = offset + 256, pos_viz = offset + 258, pos_tank_init = offset + 266, pos_suit = offset + 268; char *wlog_notes = NULL, *wlog_suit = NULL, *buffer = NULL; unsigned char *runner = (unsigned char *) wl_mem->buffer; /* * Extended notes string. Fixed length 256 bytes. 0 padded if not complete */ if (*(runner + offset)) { char wlog_notes_temp[NOTES_LENGTH + 1]; wlog_notes_temp[NOTES_LENGTH] = 0; (void)memcpy(wlog_notes_temp, runner + offset, NOTES_LENGTH); wlog_notes = to_utf8((unsigned char *) wlog_notes_temp); } if (dt_dive->notes && wlog_notes) { buffer = calloc (strlen(dt_dive->notes) + strlen(wlog_notes) + 1, 1); sprintf(buffer, "%s%s", dt_dive->notes, wlog_notes); free(dt_dive->notes); dt_dive->notes = copy_string(buffer); } else if (wlog_notes) { dt_dive->notes = copy_string(wlog_notes); } free(buffer); free(wlog_notes); /* * Weight in Kg * 100 */ tmp = (int) two_bytes_to_int(runner[pos_weight + 1], runner[pos_weight]); if (tmp != 0x7fff) { weightsystem_t ws = { {lrint(tmp * 10)}, QT_TRANSLATE_NOOP("gettextFromC", "unknown"), false }; add_cloned_weightsystem(&dt_dive->weightsystems, ws); } /* * Visibility in m * 100. Arbitrarily choosed to be 5 stars if >= 25m and * then assign a star for each 5 meters, resulting 0 stars if < 5 m */ tmp = (int) two_bytes_to_int(runner[pos_viz + 1], runner[pos_viz]); if (tmp != 0x7fff) { tmp = tmp > 2500 ? 2500 / 100 : tmp / 100; dt_dive->visibility = (int) floor(tmp / 5); } /* * Tank initial pressure in bar * 100 * If we know initial pressure, rework end pressure. */ tmp = (int) two_bytes_to_int(runner[pos_tank_init + 1], runner[pos_tank_init]); if (tmp != 0x7fff) { get_cylinder(dt_dive, 0)->start.mbar = tmp * 10; get_cylinder(dt_dive, 0)->end.mbar = get_cylinder(dt_dive, 0)->start.mbar - lrint(get_cylinder(dt_dive, 0)->gas_used.mliter / get_cylinder(dt_dive, 0)->type.size.mliter) * 1000; } /* * Dive suit, fixed length of 26 bytes, zero padded if shorter. * Expected to be preferred by the user if he did the work of setting it. */ if (*(runner + pos_suit)) { char wlog_suit_temp[SUIT_LENGTH + 1]; wlog_suit_temp[SUIT_LENGTH] = 0; (void)memcpy(wlog_suit_temp, runner + pos_suit, SUIT_LENGTH); wlog_suit = to_utf8((unsigned char *) wlog_suit_temp); } if (wlog_suit) dt_dive->suit = copy_string(wlog_suit); free(wlog_suit); } /* * Main function call from file.c memblock is allocated (and freed) there. * If parsing is aborted due to errors, stores correctly parsed dives. */ int datatrak_import(struct memblock *mem, struct memblock *wl_mem, struct dive_table *table, struct trip_table *trips, struct dive_site_table *sites, struct device_table *devices) { UNUSED(trips); unsigned char *runner; int i = 0, numdives = 0, rc = 0; long maxbuf = (long) mem->buffer + mem->size; // Verify fileheader, get number of dives in datatrak divelog, zero on error numdives = read_file_header((unsigned char *)mem->buffer); if (!numdives) { report_error(translate("gettextFromC", "[Error] File is not a DataTrak file. Aborted")); goto bail; } // Verify WLog .add file, Beginning sequence and Nº dives if(wl_mem) { int compl_dives_n = wlog_header_parser(wl_mem); if (compl_dives_n != numdives) { report_error("ERROR: Not the same number of dives in .log %d and .add file %d.\nWill not parse .add file", numdives , compl_dives_n); free(wl_mem->buffer); wl_mem->buffer = NULL; wl_mem = NULL; } } // Point to the expected begining of 1st. dive data runner = (unsigned char *)mem->buffer; JUMP(runner, 12); // Secuential parsing. Abort if received NULL from dt_dive_parser. while ((i < numdives) && ((long) runner < maxbuf)) { struct dive *ptdive = alloc_dive(); runner = dt_dive_parser(runner, ptdive, sites, devices, maxbuf); if (wl_mem) wlog_compl_parser(wl_mem, ptdive, i); if (runner == NULL) { report_error(translate("gettextFromC", "Error: no dive")); free(ptdive); rc = 1; goto out; } else { record_dive_to_table(ptdive, table); } i++; } out: taglist_cleanup(&g_tag_list); sort_dive_table(table); return rc; bail: return 1; }
subsurface-for-dirk-master
core/datatrak.c
// SPDX-License-Identifier: GPL-2.0 #include "tag.h" #include "structured_list.h" #include "subsurface-string.h" #include "membuffer.h" #include "gettext.h" #include <stdlib.h> struct tag_entry *g_tag_list = NULL; static const char *default_tags[] = { QT_TRANSLATE_NOOP("gettextFromC", "boat"), QT_TRANSLATE_NOOP("gettextFromC", "shore"), QT_TRANSLATE_NOOP("gettextFromC", "drift"), QT_TRANSLATE_NOOP("gettextFromC", "deep"), QT_TRANSLATE_NOOP("gettextFromC", "cavern"), QT_TRANSLATE_NOOP("gettextFromC", "ice"), QT_TRANSLATE_NOOP("gettextFromC", "wreck"), QT_TRANSLATE_NOOP("gettextFromC", "cave"), QT_TRANSLATE_NOOP("gettextFromC", "altitude"), QT_TRANSLATE_NOOP("gettextFromC", "pool"), QT_TRANSLATE_NOOP("gettextFromC", "lake"), QT_TRANSLATE_NOOP("gettextFromC", "river"), QT_TRANSLATE_NOOP("gettextFromC", "night"), QT_TRANSLATE_NOOP("gettextFromC", "fresh"), QT_TRANSLATE_NOOP("gettextFromC", "student"), QT_TRANSLATE_NOOP("gettextFromC", "instructor"), QT_TRANSLATE_NOOP("gettextFromC", "photo"), QT_TRANSLATE_NOOP("gettextFromC", "video"), QT_TRANSLATE_NOOP("gettextFromC", "deco") }; /* copy an element in a list of tags */ static void copy_tl(struct tag_entry *st, struct tag_entry *dt) { dt->tag = malloc(sizeof(struct divetag)); dt->tag->name = copy_string(st->tag->name); dt->tag->source = copy_string(st->tag->source); } static bool tag_seen_before(struct tag_entry *start, struct tag_entry *before) { while (start && start != before) { if (same_string(start->tag->name, before->tag->name)) return true; start = start->next; } return false; } /* remove duplicates and empty nodes */ void taglist_cleanup(struct tag_entry **tag_list) { struct tag_entry **tl = tag_list; while (*tl) { /* skip tags that are empty or that we have seen before */ if (empty_string((*tl)->tag->name) || tag_seen_before(*tag_list, *tl)) { *tl = (*tl)->next; continue; } tl = &(*tl)->next; } } char *taglist_get_tagstring(struct tag_entry *tag_list) { bool first_tag = true; struct membuffer b = { 0 }; struct tag_entry *tmp = tag_list; while (tmp != NULL) { if (!empty_string(tmp->tag->name)) { if (first_tag) { put_format(&b, "%s", tmp->tag->name); first_tag = false; } else { put_format(&b, ", %s", tmp->tag->name); } } tmp = tmp->next; } /* Ensures we do return null terminated empty string for: * - empty tag list * - tag list with empty tag only */ return detach_cstring(&b); } static inline void taglist_free_divetag(struct divetag *tag) { if (tag->name != NULL) free(tag->name); if (tag->source != NULL) free(tag->source); free(tag); } /* Add a tag to the tag_list, keep the list sorted */ static struct divetag *taglist_add_divetag(struct tag_entry **tag_list, struct divetag *tag) { struct tag_entry *next, *entry; while ((next = *tag_list) != NULL) { int cmp = strcmp(next->tag->name, tag->name); /* Already have it? */ if (!cmp) return next->tag; /* Is the entry larger? If so, insert here */ if (cmp > 0) break; /* Continue traversing the list */ tag_list = &next->next; } /* Insert in front of it */ entry = malloc(sizeof(struct tag_entry)); entry->next = next; entry->tag = tag; *tag_list = entry; return tag; } struct divetag *taglist_add_tag(struct tag_entry **tag_list, const char *tag) { size_t i = 0; int is_default_tag = 0; struct divetag *ret_tag, *new_tag; const char *translation; new_tag = malloc(sizeof(struct divetag)); for (i = 0; i < sizeof(default_tags) / sizeof(char *); i++) { if (strcmp(default_tags[i], tag) == 0) { is_default_tag = 1; break; } } /* Only translate default tags */ if (is_default_tag) { translation = translate("gettextFromC", tag); new_tag->name = malloc(strlen(translation) + 1); memcpy(new_tag->name, translation, strlen(translation) + 1); new_tag->source = malloc(strlen(tag) + 1); memcpy(new_tag->source, tag, strlen(tag) + 1); } else { new_tag->source = NULL; new_tag->name = malloc(strlen(tag) + 1); memcpy(new_tag->name, tag, strlen(tag) + 1); } /* Try to insert new_tag into g_tag_list if we are not operating on it */ if (tag_list != &g_tag_list) { ret_tag = taglist_add_divetag(&g_tag_list, new_tag); /* g_tag_list already contains new_tag, free the duplicate */ if (ret_tag != new_tag) taglist_free_divetag(new_tag); ret_tag = taglist_add_divetag(tag_list, ret_tag); } else { ret_tag = taglist_add_divetag(tag_list, new_tag); if (ret_tag != new_tag) taglist_free_divetag(new_tag); } return ret_tag; } void taglist_free(struct tag_entry *entry) { STRUCTURED_LIST_FREE(struct tag_entry, entry, free) } struct tag_entry *taglist_copy(struct tag_entry *s) { struct tag_entry *res; STRUCTURED_LIST_COPY(struct tag_entry, s, res, copy_tl); return res; } /* Merge src1 and src2, write to *dst */ void taglist_merge(struct tag_entry **dst, struct tag_entry *src1, struct tag_entry *src2) { struct tag_entry *entry; for (entry = src1; entry; entry = entry->next) taglist_add_divetag(dst, entry->tag); for (entry = src2; entry; entry = entry->next) taglist_add_divetag(dst, entry->tag); } void taglist_init_global() { size_t i; for (i = 0; i < sizeof(default_tags) / sizeof(char *); i++) taglist_add_tag(&g_tag_list, default_tags[i]); } bool taglist_contains(struct tag_entry *tag_list, const char *tag) { while (tag_list) { if (same_string(tag_list->tag->name, tag)) return true; tag_list = tag_list->next; } return false; } struct tag_entry *taglist_added(struct tag_entry *original_list, struct tag_entry *new_list) { struct tag_entry *added_list = NULL; while (new_list) { if (!taglist_contains(original_list, new_list->tag->name)) taglist_add_tag(&added_list, new_list->tag->name); new_list = new_list->next; } return added_list; }
subsurface-for-dirk-master
core/tag.c
// SPDX-License-Identifier: GPL-2.0 #ifdef __clang__ // Clang has a bug on zero-initialization of C structs. #pragma clang diagnostic ignored "-Wmissing-field-initializers" #endif #include "ssrf.h" #include <stdio.h> #include <ctype.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include <assert.h> #define __USE_XOPEN #include <libxml/parser.h> #include <libxml/parserInternals.h> #include <libxml/tree.h> #include <libxslt/transform.h> #include <libdivecomputer/parser.h> #include "gettext.h" #include "dive.h" #include "divesite.h" #include "errorhelper.h" #include "parse.h" #include "subsurface-float.h" #include "subsurface-string.h" #include "subsurface-time.h" #include "trip.h" #include "device.h" #include "membuffer.h" #include "picture.h" #include "qthelper.h" #include "sample.h" #include "tag.h" #include "xmlparams.h" int last_xml_version = -1; static xmlDoc *test_xslt_transforms(xmlDoc *doc, const struct xml_params *params); const struct units SI_units = SI_UNITS; const struct units IMPERIAL_units = IMPERIAL_UNITS; static void divedate(const char *buffer, timestamp_t *when, struct parser_state *state) { int d, m, y; int hh, mm, ss; hh = 0; mm = 0; ss = 0; if (sscanf(buffer, "%d.%d.%d %d:%d:%d", &d, &m, &y, &hh, &mm, &ss) >= 3) { /* This is ok, and we got at least the date */ } else if (sscanf(buffer, "%d-%d-%d %d:%d:%d", &y, &m, &d, &hh, &mm, &ss) >= 3) { /* This is also ok */ } else { fprintf(stderr, "Unable to parse date '%s'\n", buffer); return; } state->cur_tm.tm_year = y; state->cur_tm.tm_mon = m - 1; state->cur_tm.tm_mday = d; state->cur_tm.tm_hour = hh; state->cur_tm.tm_min = mm; state->cur_tm.tm_sec = ss; *when = utc_mktime(&state->cur_tm); } static void divetime(const char *buffer, timestamp_t *when, struct parser_state *state) { int h, m, s = 0; if (sscanf(buffer, "%d:%d:%d", &h, &m, &s) >= 2) { state->cur_tm.tm_hour = h; state->cur_tm.tm_min = m; state->cur_tm.tm_sec = s; *when = utc_mktime(&state->cur_tm); } } /* Libdivecomputer: "2011-03-20 10:22:38" */ static void divedatetime(char *buffer, timestamp_t *when, struct parser_state *state) { int y, m, d; int hr, min, sec; if (sscanf(buffer, "%d-%d-%d %d:%d:%d", &y, &m, &d, &hr, &min, &sec) == 6) { state->cur_tm.tm_year = y; state->cur_tm.tm_mon = m - 1; state->cur_tm.tm_mday = d; state->cur_tm.tm_hour = hr; state->cur_tm.tm_min = min; state->cur_tm.tm_sec = sec; *when = utc_mktime(&state->cur_tm); } } enum ParseState { FINDSTART, FINDEND }; static void divetags(char *buffer, struct tag_entry **tags) { int i = 0, start = 0, end = 0; enum ParseState state = FINDEND; int len = buffer ? strlen(buffer) : 0; while (i < len) { if (buffer[i] == ',') { if (state == FINDSTART) { /* Detect empty tags */ } else if (state == FINDEND) { /* Found end of tag */ if (i > 0 && buffer[i - 1] != '\\') { buffer[i] = '\0'; state = FINDSTART; taglist_add_tag(tags, buffer + start); } else { state = FINDSTART; } } } else if (buffer[i] == ' ') { /* Handled */ } else { /* Found start of tag */ if (state == FINDSTART) { state = FINDEND; start = i; } else if (state == FINDEND) { end = i; } } i++; } if (state == FINDEND) { if (end < start) end = len - 1; if (len > 0) { buffer[end + 1] = '\0'; taglist_add_tag(tags, buffer + start); } } } enum number_type { NEITHER, FLOATVAL }; static enum number_type parse_float(const char *buffer, double *res, const char **endp) { double val; static bool first_time = true; errno = 0; val = ascii_strtod(buffer, endp); if (errno || *endp == buffer) return NEITHER; if (**endp == ',') { if (nearly_equal(val, rint(val))) { /* we really want to send an error if this is a Subsurface native file * as this is likely indication of a bug - but right now we don't have * that information available */ if (first_time) { fprintf(stderr, "Floating point value with decimal comma (%s)?\n", buffer); first_time = false; } /* Try again in permissive mode*/ val = strtod_flags(buffer, endp, 0); } } *res = val; return FLOATVAL; } union int_or_float { double fp; }; static enum number_type integer_or_float(char *buffer, union int_or_float *res) { const char *end; return parse_float(buffer, &res->fp, &end); } static void pressure(char *buffer, pressure_t *pressure, struct parser_state *state) { double mbar = 0.0; union int_or_float val; switch (integer_or_float(buffer, &val)) { case FLOATVAL: /* Just ignore zero values */ if (!val.fp) break; switch (state->xml_parsing_units.pressure) { case PASCALS: mbar = val.fp / 100; break; case BAR: /* Assume mbar, but if it's really small, it's bar */ mbar = val.fp; if (fabs(mbar) < 5000) mbar = mbar * 1000; break; case PSI: mbar = psi_to_mbar(val.fp); break; } if (fabs(mbar) > 5 && fabs(mbar) < 5000000) { pressure->mbar = lrint(mbar); break; } /* fallthrough */ default: printf("Strange pressure reading %s\n", buffer); } } static void cylinder_use(char *buffer, enum cylinderuse *cyl_use, struct parser_state *state) { if (trimspace(buffer)) { int use = cylinderuse_from_text(buffer); *cyl_use = use; if (use == OXYGEN) state->o2pressure_sensor = state->cur_dive->cylinders.nr - 1; } } static void salinity(char *buffer, int *salinity) { union int_or_float val; switch (integer_or_float(buffer, &val)) { case FLOATVAL: *salinity = lrint(val.fp * 10.0); break; default: printf("Strange salinity reading %s\n", buffer); } } static void depth(char *buffer, depth_t *depth, struct parser_state *state) { union int_or_float val; switch (integer_or_float(buffer, &val)) { case FLOATVAL: switch (state->xml_parsing_units.length) { case METERS: depth->mm = lrint(val.fp * 1000); break; case FEET: depth->mm = feet_to_mm(val.fp); break; } break; default: printf("Strange depth reading %s\n", buffer); } } static void extra_data_start(struct parser_state *state) { memset(&state->cur_extra_data, 0, sizeof(struct extra_data)); } static void extra_data_end(struct parser_state *state) { // don't save partial structures - we must have both key and value if (state->cur_extra_data.key && state->cur_extra_data.value) add_extra_data(get_dc(state), state->cur_extra_data.key, state->cur_extra_data.value); free((void *)state->cur_extra_data.key); free((void *)state->cur_extra_data.value); state->cur_extra_data.key = state->cur_extra_data.value = NULL; } static void weight(char *buffer, weight_t *weight, struct parser_state *state) { union int_or_float val; switch (integer_or_float(buffer, &val)) { case FLOATVAL: switch (state->xml_parsing_units.weight) { case KG: weight->grams = lrint(val.fp * 1000); break; case LBS: weight->grams = lbs_to_grams(val.fp); break; } break; default: printf("Strange weight reading %s\n", buffer); } } static void temperature(char *buffer, temperature_t *temperature, struct parser_state *state) { union int_or_float val; switch (integer_or_float(buffer, &val)) { case FLOATVAL: switch (state->xml_parsing_units.temperature) { case KELVIN: temperature->mkelvin = lrint(val.fp * 1000); break; case CELSIUS: temperature->mkelvin = C_to_mkelvin(val.fp); break; case FAHRENHEIT: temperature->mkelvin = F_to_mkelvin(val.fp); break; } break; default: printf("Strange temperature reading %s\n", buffer); } /* temperatures outside -40C .. +70C should be ignored */ if (temperature->mkelvin < ZERO_C_IN_MKELVIN - 40000 || temperature->mkelvin > ZERO_C_IN_MKELVIN + 70000) temperature->mkelvin = 0; } static void sampletime(char *buffer, duration_t *time) { int i; int hr, min, sec; i = sscanf(buffer, "%d:%d:%d", &hr, &min, &sec); switch (i) { case 1: min = hr; hr = 0; /* fallthrough */ case 2: sec = min; min = hr; hr = 0; /* fallthrough */ case 3: time->seconds = (hr * 60 + min) * 60 + sec; break; default: time->seconds = 0; printf("Strange sample time reading %s\n", buffer); } } static void offsettime(char *buffer, offset_t *time) { duration_t uoffset; int sign = 1; if (*buffer == '-') { sign = -1; buffer++; } /* yes, this could indeed fail if we have an offset > 34yrs * - too bad */ sampletime(buffer, &uoffset); time->seconds = sign * uoffset.seconds; } static void duration(char *buffer, duration_t *time) { /* DivingLog 5.08 (and maybe other versions) appear to sometimes * store the dive time as 44.00 instead of 44:00; * This attempts to parse this in a fairly robust way */ if (!strchr(buffer, ':') && strchr(buffer, '.')) { char *mybuffer = strdup(buffer); char *dot = strchr(mybuffer, '.'); *dot = ':'; sampletime(mybuffer, time); free(mybuffer); } else { sampletime(buffer, time); } } static void percent(char *buffer, fraction_t *fraction) { double val; const char *end; switch (parse_float(buffer, &val, &end)) { case FLOATVAL: /* Turn fractions into percent unless explicit.. */ if (val <= 1.0) { while (isspace(*end)) end++; if (*end != '%') val *= 100; } /* Then turn percent into our integer permille format */ if (val >= 0 && val <= 100.0) { fraction->permille = lrint(val * 10); break; } default: printf(translate("gettextFromC", "Strange percentage reading %s\n"), buffer); break; } } static void gasmix(char *buffer, fraction_t *fraction, struct parser_state *state) { /* libdivecomputer does negative percentages. */ if (*buffer == '-') return; percent(buffer, fraction); } static void gasmix_nitrogen(char *buffer, struct gasmix *gasmix) { UNUSED(buffer); UNUSED(gasmix); /* Ignore n2 percentages. There's no value in them. */ } static void cylindersize(char *buffer, volume_t *volume) { union int_or_float val; switch (integer_or_float(buffer, &val)) { case FLOATVAL: volume->mliter = lrint(val.fp * 1000); break; default: printf("Strange volume reading %s\n", buffer); break; } } static void event_name(char *buffer, char *name) { int size = trimspace(buffer); if (size >= MAX_EVENT_NAME) size = MAX_EVENT_NAME - 1; memcpy(name, buffer, size); name[size] = 0; } // We don't use gauge as a mode, and pscr doesn't exist as a libdc divemode const char *libdc_divemode_text[] = { "oc", "cc", "pscr", "freedive", "gauge"}; /* Extract the dive computer type from the xml text buffer */ static void get_dc_type(char *buffer, enum divemode_t *dct) { if (trimspace(buffer)) { for (enum divemode_t i = 0; i < NUM_DIVEMODE; i++) { if (strcmp(buffer, divemode_text[i]) == 0) *dct = i; else if (strcmp(buffer, libdc_divemode_text[i]) == 0) *dct = i; } } } /* For divemode_text[] (defined in dive.h) determine the index of * the string contained in the xml divemode attribute and passed * in buffer, below. Typical xml input would be: * <event name='modechange' divemode='OC' /> */ static void event_divemode(char *buffer, int *value) { int size = trimspace(buffer); if (size >= MAX_EVENT_NAME) size = MAX_EVENT_NAME - 1; buffer[size] = 0x0; for (int i = 0; i < NUM_DIVEMODE; i++) { if (!strcmp(buffer,divemode_text[i])) { *value = i; break; } } } /* Compare a pattern with a name, whereby the name may end in '\0' or '.'. */ static int match_name(const char *pattern, const char *name) { while (*pattern == *name && *pattern) { pattern++; name++; } return *pattern == '\0' && (*name == '\0' || *name == '.'); } typedef void (*matchfn_t)(char *buffer, void *); static int match(const char *pattern, const char *name, matchfn_t fn, char *buf, void *data) { if (!match_name(pattern, name)) return 0; fn(buf, data); return 1; } typedef void (*matchfn_state_t)(char *buffer, void *, struct parser_state *state); static int match_state(const char *pattern, const char *name, matchfn_state_t fn, char *buf, void *data, struct parser_state *state) { if (!match_name(pattern, name)) return 0; fn(buf, data, state); return 1; } #define MATCH(pattern, fn, dest) ({ \ /* Silly type compatibility test */ \ if (0) (fn)("test", dest); \ match(pattern, name, (matchfn_t) (fn), buf, dest); }) #define MATCH_STATE(pattern, fn, dest) ({ \ /* Silly type compatibility test */ \ if (0) (fn)("test", dest, state); \ match_state(pattern, name, (matchfn_state_t) (fn), buf, dest, state); }) static void get_index(char *buffer, int *i) { *i = atoi(buffer); } static void get_bool(char *buffer, bool *i) { *i = atoi(buffer); } static void get_uint8(char *buffer, uint8_t *i) { *i = atoi(buffer); } static void get_uint16(char *buffer, uint16_t *i) { *i = atoi(buffer); } static void get_bearing(char *buffer, bearing_t *bearing) { bearing->degrees = atoi(buffer); } static void get_rating(char *buffer, int *i) { int j = atoi(buffer); if (j >= 0 && j <= 5) { *i = j; } } static void double_to_o2pressure(char *buffer, o2pressure_t *i) { i->mbar = lrint(ascii_strtod(buffer, NULL) * 1000.0); } static void hex_value(char *buffer, uint32_t *i) { *i = strtoul(buffer, NULL, 16); } static void dive_site(char *buffer, struct dive *d, struct parser_state *state) { uint32_t uuid; hex_value(buffer, &uuid); add_dive_to_dive_site(d, get_dive_site_by_uuid(uuid, state->sites)); } static void get_notrip(char *buffer, bool *notrip) { *notrip = !strcmp(buffer, "NOTRIP"); } /* * Divinglog is crazy. The temperatures are in celsius. EXCEPT * for the sample temperatures, that are in Fahrenheit. * WTF? * * Oh, and I think Diving Log *internally* probably kept them * in celsius, because I'm seeing entries like * * <Temp>32.0</Temp> * * in there. Which is freezing, aka 0 degC. I bet the "0" is * what Diving Log uses for "no temperature". * * So throw away crap like that. * * It gets worse. Sometimes the sample temperatures are in * Celsius, which apparently happens if you are in a SI * locale. So we now do: * * - temperatures < 32.0 == Celsius * - temperature == 32.0 -> garbage, it's a missing temperature (zero converted from C to F) * - temperatures > 32.0 == Fahrenheit */ static void fahrenheit(char *buffer, temperature_t *temperature) { union int_or_float val; switch (integer_or_float(buffer, &val)) { case FLOATVAL: if (nearly_equal(val.fp, 32.0)) break; if (val.fp < 32.0) temperature->mkelvin = C_to_mkelvin(val.fp); else temperature->mkelvin = F_to_mkelvin(val.fp); break; default: fprintf(stderr, "Crazy Diving Log temperature reading %s\n", buffer); } } /* * Did I mention how bat-shit crazy divinglog is? The sample * pressures are in PSI. But the tank working pressure is in * bar. WTF^2? * * Crazy stuff like this is why subsurface has everything in * these inconvenient typed structures, and you have to say * "pressure->mbar" to get the actual value. Exactly so that * you can never have unit confusion. * * It gets worse: sometimes apparently the pressures are in * bar, sometimes in psi. Dirk suspects that this may be a * DivingLog Uemis importer bug, and that they are always * supposed to be in bar, but that the importer got the * sample importing wrong. * * Sadly, there's no way to really tell. So I think we just * have to have some arbitrary cut-off point where we assume * that smaller values mean bar.. Not good. */ static void psi_or_bar(char *buffer, pressure_t *pressure) { union int_or_float val; switch (integer_or_float(buffer, &val)) { case FLOATVAL: if (val.fp > 400) pressure->mbar = psi_to_mbar(val.fp); else pressure->mbar = lrint(val.fp * 1000); break; default: fprintf(stderr, "Crazy Diving Log PSI reading %s\n", buffer); } } static int divinglog_fill_sample(struct sample *sample, const char *name, char *buf, struct parser_state *state) { return MATCH("time.p", sampletime, &sample->time) || MATCH_STATE("depth.p", depth, &sample->depth) || MATCH("temp.p", fahrenheit, &sample->temperature) || MATCH("press1.p", psi_or_bar, &sample->pressure[0]) || 0; } static void uddf_gasswitch(char *buffer, struct sample *sample, struct parser_state *state) { int idx = atoi(buffer); int seconds = sample->time.seconds; struct dive *dive = state->cur_dive; struct divecomputer *dc = get_dc(state); add_gas_switch_event(dive, dc, seconds, idx); } static int uddf_fill_sample(struct sample *sample, const char *name, char *buf, struct parser_state *state) { return MATCH("divetime", sampletime, &sample->time) || MATCH_STATE("depth", depth, &sample->depth) || MATCH_STATE("temperature", temperature, &sample->temperature) || MATCH_STATE("tankpressure", pressure, &sample->pressure[0]) || MATCH_STATE("ref.switchmix", uddf_gasswitch, sample) || 0; } static void eventtime(char *buffer, duration_t *duration, struct parser_state *state) { sampletime(buffer, duration); if (state->cur_sample) duration->seconds += state->cur_sample->time.seconds; } static void try_to_match_autogroup(const char *name, char *buf) { bool autogroupvalue; start_match("autogroup", name, buf); if (MATCH("state.autogroup", get_bool, &autogroupvalue)) { set_autogroup(autogroupvalue); return; } nonmatch("autogroup", name, buf); } static void get_cylinderindex(char *buffer, int16_t *i, struct parser_state *state) { *i = atoi(buffer); if (state->lastcylinderindex != *i) { add_gas_switch_event(state->cur_dive, get_dc(state), state->cur_sample->time.seconds, *i); state->lastcylinderindex = *i; } } static void get_sensor(char *buffer, int16_t *i) { *i = atoi(buffer); } static void parse_libdc_deco(char *buffer, struct sample *s) { if (strcmp(buffer, "deco") == 0) { s->in_deco = true; } else if (strcmp(buffer, "ndl") == 0) { s->in_deco = false; // The time wasn't stoptime, it was ndl s->ndl = s->stoptime; s->stoptime.seconds = 0; } } static void try_to_fill_dc_settings(const char *name, char *buf, struct parser_state *state) { start_match("divecomputerid", name, buf); if (MATCH("model.divecomputerid", utf8_string, &state->cur_settings.dc.model)) return; if (MATCH("deviceid.divecomputerid", hex_value, &state->cur_settings.dc.deviceid)) return; if (MATCH("nickname.divecomputerid", utf8_string, &state->cur_settings.dc.nickname)) return; if (MATCH("serial.divecomputerid", utf8_string, &state->cur_settings.dc.serial_nr)) return; if (MATCH("firmware.divecomputerid", utf8_string, &state->cur_settings.dc.firmware)) return; nonmatch("divecomputerid", name, buf); } static void try_to_fill_fingerprint(const char *name, char *buf, struct parser_state *state) { start_match("fingerprint", name, buf); if (MATCH("model.fingerprint", hex_value, &state->cur_settings.fingerprint.model)) return; if (MATCH("serial.fingerprint", hex_value, &state->cur_settings.fingerprint.serial)) return; if (MATCH("deviceid.fingerprint", hex_value, &state->cur_settings.fingerprint.fdeviceid)) return; if (MATCH("diveid.fingerprint", hex_value, &state->cur_settings.fingerprint.fdiveid)) return; if (MATCH("data.fingerprint", utf8_string, &state->cur_settings.fingerprint.data)) return; nonmatch("fingerprint", name, buf); } static void try_to_fill_event(const char *name, char *buf, struct parser_state *state) { start_match("event", name, buf); if (MATCH("event", event_name, state->cur_event.name)) return; if (MATCH("name", event_name, state->cur_event.name)) return; if (MATCH_STATE("time", eventtime, &state->cur_event.time)) return; if (MATCH("type", get_index, &state->cur_event.type)) return; if (MATCH("flags", get_index, &state->cur_event.flags)) return; if (MATCH("value", get_index, &state->cur_event.value)) return; if (MATCH("divemode", event_divemode, &state->cur_event.value)) return; if (MATCH("cylinder", get_index, &state->cur_event.gas.index)) { /* We add one to indicate that we got an actual cylinder index value */ state->cur_event.gas.index++; return; } if (MATCH("o2", percent, &state->cur_event.gas.mix.o2)) return; if (MATCH("he", percent, &state->cur_event.gas.mix.he)) return; nonmatch("event", name, buf); } static int match_dc_data_fields(struct divecomputer *dc, const char *name, char *buf, struct parser_state *state) { if (MATCH_STATE("maxdepth", depth, &dc->maxdepth)) return 1; if (MATCH_STATE("meandepth", depth, &dc->meandepth)) return 1; if (MATCH_STATE("max.depth", depth, &dc->maxdepth)) return 1; if (MATCH_STATE("mean.depth", depth, &dc->meandepth)) return 1; if (MATCH("duration", duration, &dc->duration)) return 1; if (MATCH("divetime", duration, &dc->duration)) return 1; if (MATCH("divetimesec", duration, &dc->duration)) return 1; if (MATCH("last-manual-time", duration, &dc->last_manual_time)) return 1; if (MATCH("surfacetime", duration, &dc->surfacetime)) return 1; if (MATCH_STATE("airtemp", temperature, &dc->airtemp)) return 1; if (MATCH_STATE("watertemp", temperature, &dc->watertemp)) return 1; if (MATCH_STATE("air.temperature", temperature, &dc->airtemp)) return 1; if (MATCH_STATE("water.temperature", temperature, &dc->watertemp)) return 1; if (MATCH_STATE("pressure.surface", pressure, &dc->surface_pressure)) return 1; if (MATCH("salinity.water", salinity, &dc->salinity)) return 1; if (MATCH("key.extradata", utf8_string, &state->cur_extra_data.key)) return 1; if (MATCH("value.extradata", utf8_string, &state->cur_extra_data.value)) return 1; if (MATCH("divemode", get_dc_type, &dc->divemode)) return 1; if (MATCH("salinity", salinity, &dc->salinity)) return 1; if (MATCH_STATE("atmospheric", pressure, &dc->surface_pressure)) return 1; return 0; } /* We're in the top-level dive xml. Try to convert whatever value to a dive value */ static void try_to_fill_dc(struct divecomputer *dc, const char *name, char *buf, struct parser_state *state) { unsigned int deviceid; start_match("divecomputer", name, buf); if (MATCH_STATE("date", divedate, &dc->when)) return; if (MATCH_STATE("time", divetime, &dc->when)) return; if (MATCH("model", utf8_string, &dc->model)) return; if (MATCH("deviceid", hex_value, &deviceid)) return; if (MATCH("diveid", hex_value, &dc->diveid)) return; if (MATCH("dctype", get_dc_type, &dc->divemode)) return; if (MATCH("no_o2sensors", get_uint8, &dc->no_o2sensors)) return; if (match_dc_data_fields(dc, name, buf, state)) return; nonmatch("divecomputer", name, buf); } /* We're in samples - try to convert the random xml value to something useful */ static void try_to_fill_sample(struct sample *sample, const char *name, char *buf, struct parser_state *state) { int in_deco; pressure_t p; start_match("sample", name, buf); if (MATCH_STATE("pressure.sample", pressure, &sample->pressure[0])) return; if (MATCH_STATE("cylpress.sample", pressure, &sample->pressure[0])) return; if (MATCH_STATE("pdiluent.sample", pressure, &sample->pressure[0])) return; if (MATCH_STATE("o2pressure.sample", pressure, &sample->pressure[1])) return; /* Christ, this is ugly */ if (MATCH_STATE("pressure0.sample", pressure, &p)) { add_sample_pressure(sample, 0, p.mbar); return; } if (MATCH_STATE("pressure1.sample", pressure, &p)) { add_sample_pressure(sample, 1, p.mbar); return; } if (MATCH_STATE("pressure2.sample", pressure, &p)) { add_sample_pressure(sample, 2, p.mbar); return; } if (MATCH_STATE("pressure3.sample", pressure, &p)) { add_sample_pressure(sample, 3, p.mbar); return; } if (MATCH_STATE("pressure4.sample", pressure, &p)) { add_sample_pressure(sample, 4, p.mbar); return; } if (MATCH_STATE("cylinderindex.sample", get_cylinderindex, &sample->sensor[0])) return; if (MATCH("sensor.sample", get_sensor, &sample->sensor[0])) return; if (MATCH_STATE("depth.sample", depth, &sample->depth)) return; if (MATCH_STATE("temp.sample", temperature, &sample->temperature)) return; if (MATCH_STATE("temperature.sample", temperature, &sample->temperature)) return; if (MATCH("sampletime.sample", sampletime, &sample->time)) return; if (MATCH("time.sample", sampletime, &sample->time)) return; if (MATCH("ndl.sample", sampletime, &sample->ndl)) return; if (MATCH("tts.sample", sampletime, &sample->tts)) return; if (MATCH("in_deco.sample", get_index, &in_deco)) { sample->in_deco = (in_deco == 1); return; } if (MATCH("stoptime.sample", sampletime, &sample->stoptime)) return; if (MATCH_STATE("stopdepth.sample", depth, &sample->stopdepth)) return; if (MATCH("cns.sample", get_uint16, &sample->cns)) return; if (MATCH("rbt.sample", sampletime, &sample->rbt)) return; if (MATCH("sensor1.sample", double_to_o2pressure, &sample->o2sensor[0])) // CCR O2 sensor data return; if (MATCH("sensor2.sample", double_to_o2pressure, &sample->o2sensor[1])) return; if (MATCH("sensor3.sample", double_to_o2pressure, &sample->o2sensor[2])) // up to 3 CCR sensors return; if (MATCH("po2.sample", double_to_o2pressure, &sample->setpoint)) return; if (MATCH("heartbeat", get_uint8, &sample->heartbeat)) return; if (MATCH("bearing", get_bearing, &sample->bearing)) return; if (MATCH("setpoint.sample", double_to_o2pressure, &sample->setpoint)) return; if (MATCH("ppo2.sample", double_to_o2pressure, &sample->o2sensor[state->next_o2_sensor])) { state->next_o2_sensor++; return; } if (MATCH("deco.sample", parse_libdc_deco, sample)) return; if (MATCH("time.deco", sampletime, &sample->stoptime)) return; if (MATCH_STATE("depth.deco", depth, &sample->stopdepth)) return; switch (state->import_source) { case DIVINGLOG: if (divinglog_fill_sample(sample, name, buf, state)) return; break; case UDDF: if (uddf_fill_sample(sample, name, buf, state)) return; break; default: break; } nonmatch("sample", name, buf); } static void divinglog_place(char *place, struct dive *d, struct parser_state *state) { char buffer[1024]; struct dive_site *ds; snprintf(buffer, sizeof(buffer), "%s%s%s%s%s", place, state->city ? ", " : "", state->city ? state->city : "", state->country ? ", " : "", state->country ? state->country : ""); ds = get_dive_site_by_name(buffer, state->sites); if (!ds) ds = create_dive_site(buffer, state->sites); add_dive_to_dive_site(d, ds); // TODO: capture the country / city info in the taxonomy instead free(state->city); free(state->country); state->city = NULL; state->country = NULL; } static int divinglog_dive_match(struct dive *dive, const char *name, char *buf, struct parser_state *state) { /* For cylinder related fields, we might have to create a cylinder first. */ cylinder_t cyl = empty_cylinder; if (MATCH("tanktype", utf8_string, &cyl.type.description)) { cylinder_t *cyl0 = get_or_create_cylinder(dive, 0); free((void *)cyl0->type.description); cyl0->type.description = cyl.type.description; return 1; } if (MATCH("tanksize", cylindersize, &cyl.type.size)) { get_or_create_cylinder(dive, 0)->type.size = cyl.type.size; return 1; } if (MATCH_STATE("presw", pressure, &cyl.type.workingpressure)) { get_or_create_cylinder(dive, 0)->type.workingpressure = cyl.type.workingpressure; return 1; } if (MATCH_STATE("press", pressure, &cyl.start)) { get_or_create_cylinder(dive, 0)->start = cyl.start; return 1; } if (MATCH_STATE("prese", pressure, &cyl.end)) { get_or_create_cylinder(dive, 0)->end = cyl.end; return 1; } return MATCH_STATE("divedate", divedate, &dive->when) || MATCH_STATE("entrytime", divetime, &dive->when) || MATCH("divetime", duration, &dive->dc.duration) || MATCH_STATE("depth", depth, &dive->dc.maxdepth) || MATCH_STATE("depthavg", depth, &dive->dc.meandepth) || MATCH("comments", utf8_string, &dive->notes) || MATCH("names.buddy", utf8_string, &dive->buddy) || MATCH("name.country", utf8_string, &state->country) || MATCH("name.city", utf8_string, &state->city) || MATCH_STATE("name.place", divinglog_place, dive) || 0; } /* * Uddf specifies ISO 8601 time format. * * There are many variations on that. This handles the useful cases. */ static void uddf_datetime(char *buffer, timestamp_t *when, struct parser_state *state) { char c; int y, m, d, hh, mm, ss; struct tm tm = { 0 }; int i; i = sscanf(buffer, "%d-%d-%d%c%d:%d:%d", &y, &m, &d, &c, &hh, &mm, &ss); if (i == 7) goto success; ss = 0; if (i == 6) goto success; i = sscanf(buffer, "%04d%02d%02d%c%02d%02d%02d", &y, &m, &d, &c, &hh, &mm, &ss); if (i == 7) goto success; ss = 0; if (i == 6) goto success; bad_date: printf("Bad date time %s\n", buffer); return; success: if (c != 'T' && c != ' ') goto bad_date; tm.tm_year = y; tm.tm_mon = m - 1; tm.tm_mday = d; tm.tm_hour = hh; tm.tm_min = mm; tm.tm_sec = ss; *when = utc_mktime(&tm); } #define uddf_datedata(name, offset) \ static void uddf_##name(char *buffer, timestamp_t *when, struct parser_state *state) \ { \ state->cur_tm.tm_##name = atoi(buffer) + offset; \ *when = utc_mktime(&state->cur_tm); \ } uddf_datedata(year, 0) uddf_datedata(mon, -1) uddf_datedata(mday, 0) uddf_datedata(hour, 0) uddf_datedata(min, 0) static int uddf_dive_match(struct dive *dive, const char *name, char *buf, struct parser_state *state) { return MATCH_STATE("datetime", uddf_datetime, &dive->when) || MATCH("diveduration", duration, &dive->dc.duration) || MATCH_STATE("greatestdepth", depth, &dive->dc.maxdepth) || MATCH_STATE("year.date", uddf_year, &dive->when) || MATCH_STATE("month.date", uddf_mon, &dive->when) || MATCH_STATE("day.date", uddf_mday, &dive->when) || MATCH_STATE("hour.time", uddf_hour, &dive->when) || MATCH_STATE("minute.time", uddf_min, &dive->when) || 0; } /* * This parses "floating point" into micro-degrees. * We don't do exponentials etc, if somebody does * GPS locations in that format, they are insane. */ static degrees_t parse_degrees(const char *buf, const char **end) { int sign = 1, decimals = 6, value = 0; degrees_t ret; while (isspace(*buf)) buf++; switch (*buf) { case '-': sign = -1; /* fallthrough */ case '+': buf++; } while (isdigit(*buf)) { value = 10 * value + *buf - '0'; buf++; } /* Get the first six decimals if they exist */ if (*buf == '.') buf++; do { value *= 10; if (isdigit(*buf)) { value += *buf - '0'; buf++; } } while (--decimals); /* Rounding */ switch (*buf) { case '5' ... '9': value++; } while (isdigit(*buf)) buf++; *end = buf; ret.udeg = value * sign; return ret; } static void gps_lat(char *buffer, struct dive *dive, struct parser_state *state) { const char *end; location_t location = { }; struct dive_site *ds = get_dive_site_for_dive(dive); location.lat = parse_degrees(buffer, &end); if (!ds) { add_dive_to_dive_site(dive, create_dive_site_with_gps(NULL, &location, state->sites)); } else { if (ds->location.lat.udeg && ds->location.lat.udeg != location.lat.udeg) fprintf(stderr, "Oops, changing the latitude of existing dive site id %8x name %s; not good\n", ds->uuid, ds->name ?: "(unknown)"); ds->location.lat = location.lat; } } static void gps_long(char *buffer, struct dive *dive, struct parser_state *state) { const char *end; location_t location = { }; struct dive_site *ds = get_dive_site_for_dive(dive); location.lon = parse_degrees(buffer, &end); if (!ds) { add_dive_to_dive_site(dive, create_dive_site_with_gps(NULL, &location, state->sites)); } else { if (ds->location.lon.udeg && ds->location.lon.udeg != location.lon.udeg) fprintf(stderr, "Oops, changing the longitude of existing dive site id %8x name %s; not good\n", ds->uuid, ds->name ?: "(unknown)"); ds->location.lon = location.lon; } } /* We allow either spaces or a comma between the decimal degrees */ void parse_location(const char *buffer, location_t *loc) { const char *end; loc->lat = parse_degrees(buffer, &end); if (*end == ',') end++; loc->lon = parse_degrees(end, &end); } static void gps_location(char *buffer, struct dive_site *ds) { parse_location(buffer, &ds->location); } static void gps_in_dive(char *buffer, struct dive *dive, struct parser_state *state) { struct dive_site *ds = dive->dive_site; location_t location; parse_location(buffer, &location); if (!ds) { // check if we have a dive site within 20 meters of that gps fix ds = get_dive_site_by_gps_proximity(&location, 20, state->sites); if (ds) { // found a site nearby; in case it turns out this one had a different name let's // remember the original coordinates so we can create the correct dive site later state->cur_location = location; } else { ds = create_dive_site_with_gps("", &location, state->sites); } add_dive_to_dive_site(dive, ds); } else { if (dive_site_has_gps_location(ds) && has_location(&location) && !same_location(&ds->location, &location)) { // Houston, we have a problem fprintf(stderr, "dive site uuid in dive, but gps location (%10.6f/%10.6f) different from dive location (%10.6f/%10.6f)\n", ds->location.lat.udeg / 1000000.0, ds->location.lon.udeg / 1000000.0, location.lat.udeg / 1000000.0, location.lon.udeg / 1000000.0); char *coords = printGPSCoordsC(&location); ds->notes = add_to_string(ds->notes, translate("gettextFromC", "multiple GPS locations for this dive site; also %s\n"), coords); free(coords); } else { ds->location = location; } } } static void gps_picture_location(char *buffer, struct picture *pic) { parse_location(buffer, &pic->location); } /* We're in the top-level dive xml. Try to convert whatever value to a dive value */ static void try_to_fill_dive(struct dive *dive, const char *name, char *buf, struct parser_state *state) { char *hash = NULL; cylinder_t *cyl = dive->cylinders.nr > 0 ? get_cylinder(dive, dive->cylinders.nr - 1) : NULL; weightsystem_t *ws = dive->weightsystems.nr > 0 ? &dive->weightsystems.weightsystems[dive->weightsystems.nr - 1] : NULL; pressure_t p; weight_t w; start_match("dive", name, buf); switch (state->import_source) { case DIVINGLOG: if (divinglog_dive_match(dive, name, buf, state)) return; break; case UDDF: if (uddf_dive_match(dive, name, buf, state)) return; break; default: break; } if (MATCH_STATE("divesiteid", dive_site, dive)) return; if (MATCH("number", get_index, &dive->number)) return; if (MATCH("tags", divetags, &dive->tag_list)) return; if (MATCH("tripflag", get_notrip, &dive->notrip)) return; if (MATCH_STATE("date", divedate, &dive->when)) return; if (MATCH_STATE("time", divetime, &dive->when)) return; if (MATCH_STATE("datetime", divedatetime, &dive->when)) return; /* * Legacy format note: per-dive depths and duration get saved * in the first dive computer entry */ if (match_dc_data_fields(&dive->dc, name, buf, state)) return; if (MATCH("filename.picture", utf8_string, &state->cur_picture.filename)) return; if (MATCH("offset.picture", offsettime, &state->cur_picture.offset)) return; if (MATCH("gps.picture", gps_picture_location, &state->cur_picture)) return; if (MATCH("hash.picture", utf8_string, &hash)) { /* Legacy -> ignore. */ free(hash); return; } if (MATCH_STATE("cylinderstartpressure", pressure, &p)) { get_or_create_cylinder(dive, 0)->start = p; return; } if (MATCH_STATE("cylinderendpressure", pressure, &p)) { get_or_create_cylinder(dive, 0)->end = p; return; } if (MATCH_STATE("gps", gps_in_dive, dive)) return; if (MATCH_STATE("Place", gps_in_dive, dive)) return; if (MATCH_STATE("latitude", gps_lat, dive)) return; if (MATCH_STATE("sitelat", gps_lat, dive)) return; if (MATCH_STATE("lat", gps_lat, dive)) return; if (MATCH_STATE("longitude", gps_long, dive)) return; if (MATCH_STATE("sitelon", gps_long, dive)) return; if (MATCH_STATE("lon", gps_long, dive)) return; if (MATCH_STATE("location", add_dive_site, dive)) return; if (MATCH_STATE("name.dive", add_dive_site, dive)) return; if (MATCH("suit", utf8_string, &dive->suit)) return; if (MATCH("divesuit", utf8_string, &dive->suit)) return; if (MATCH("notes", utf8_string, &dive->notes)) return; // For historic reasons, we accept dive guide as well as dive master if (MATCH("diveguide", utf8_string, &dive->diveguide)) return; if (MATCH("divemaster", utf8_string, &dive->diveguide)) return; if (MATCH("buddy", utf8_string, &dive->buddy)) return; if (MATCH("watersalinity", salinity, &dive->user_salinity)) return; if (MATCH("rating.dive", get_rating, &dive->rating)) return; if (MATCH("visibility.dive", get_rating, &dive->visibility)) return; if (MATCH("wavesize.dive", get_rating, &dive->wavesize)) return; if (MATCH("current.dive", get_rating, &dive->current)) return; if (MATCH("surge.dive", get_rating, &dive->surge)) return; if (MATCH("chill.dive", get_rating, &dive->chill)) return; if (MATCH_STATE("airpressure.dive", pressure, &dive->surface_pressure)) return; if (ws) { if (MATCH("description.weightsystem", utf8_string, &ws->description)) return; if (MATCH_STATE("weight.weightsystem", weight, &ws->weight)) return; } if (MATCH_STATE("weight", weight, &w)) { weightsystem_t ws = empty_weightsystem; ws.weight = w; add_cloned_weightsystem(&dive->weightsystems, ws); return; } if (cyl) { if (MATCH("size.cylinder", cylindersize, &cyl->type.size)) return; if (MATCH_STATE("workpressure.cylinder", pressure, &cyl->type.workingpressure)) return; if (MATCH("description.cylinder", utf8_string, &cyl->type.description)) return; if (MATCH_STATE("start.cylinder", pressure, &cyl->start)) return; if (MATCH_STATE("end.cylinder", pressure, &cyl->end)) return; if (MATCH_STATE("use.cylinder", cylinder_use, &cyl->cylinder_use)) return; if (MATCH_STATE("depth.cylinder", depth, &cyl->depth)) return; if (MATCH_STATE("o2", gasmix, &cyl->gasmix.o2)) return; if (MATCH_STATE("o2percent", gasmix, &cyl->gasmix.o2)) return; if (MATCH("n2", gasmix_nitrogen, &cyl->gasmix)) return; if (MATCH_STATE("he", gasmix, &cyl->gasmix.he)) return; } if (MATCH_STATE("air.divetemperature", temperature, &dive->airtemp)) return; if (MATCH_STATE("water.divetemperature", temperature, &dive->watertemp)) return; if (MATCH("invalid", get_bool, &dive->invalid)) return; nonmatch("dive", name, buf); } /* We're in the top-level trip xml. Try to convert whatever value to a trip value */ static void try_to_fill_trip(dive_trip_t *dive_trip, const char *name, char *buf, struct parser_state *state) { start_match("trip", name, buf); if (MATCH("location", utf8_string, &dive_trip->location)) return; if (MATCH("notes", utf8_string, &dive_trip->notes)) return; nonmatch("trip", name, buf); } /* We're processing a divesite entry - try to fill the components */ static void try_to_fill_dive_site(struct parser_state *state, const char *name, char *buf) { struct dive_site *ds = state->cur_dive_site; char *taxonomy_value = NULL; start_match("divesite", name, buf); if (MATCH("uuid", hex_value, &ds->uuid)) return; if (MATCH("name", utf8_string, &ds->name)) return; if (MATCH("description", utf8_string, &ds->description)) return; if (MATCH("notes", utf8_string, &ds->notes)) return; if (MATCH("gps", gps_location, ds)) return; if (MATCH("cat.geo", get_index, &state->taxonomy_category)) return; if (MATCH("origin.geo", get_index, &state->taxonomy_origin)) return; if (MATCH("value.geo", utf8_string, &taxonomy_value)) { /* The code assumes that "value.geo" comes last, which is against * the expectations of an XML file. Let's at least make sure that * cat and origin have been set! */ if (state->taxonomy_category < 0 || state->taxonomy_origin < 0) { report_error("Warning: taxonomy value without origin or category"); } else { taxonomy_set_category(&ds->taxonomy, state->taxonomy_category, taxonomy_value, state->taxonomy_origin); } state->taxonomy_category = state->taxonomy_origin = -1; free(taxonomy_value); return; } nonmatch("divesite", name, buf); } static void try_to_fill_filter(struct filter_preset *filter, const char *name, char *buf) { start_match("filterpreset", name, buf); char *s = NULL; if (MATCH("name", utf8_string, &s)) { filter_preset_set_name(filter, s); free(s); return; } nonmatch("filterpreset", name, buf); } static void try_to_fill_fulltext(const char *name, char *buf, struct parser_state *state) { start_match("fulltext", name, buf); if (MATCH("mode", utf8_string, &state->fulltext_string_mode)) return; if (MATCH("fulltext", utf8_string, &state->fulltext)) return; nonmatch("fulltext", name, buf); } static void try_to_fill_filter_constraint(const char *name, char *buf, struct parser_state *state) { start_match("fulltext", name, buf); if (MATCH("type", utf8_string, &state->filter_constraint_type)) return; if (MATCH("string_mode", utf8_string, &state->filter_constraint_string_mode)) return; if (MATCH("range_mode", utf8_string, &state->filter_constraint_range_mode)) return; if (MATCH("negate", get_bool, &state->filter_constraint_negate)) return; if (MATCH("constraint", utf8_string, &state->filter_constraint)) return; nonmatch("fulltext", name, buf); } static bool entry(const char *name, char *buf, struct parser_state *state) { if (!strncmp(name, "version.program", sizeof("version.program") - 1) || !strncmp(name, "version.divelog", sizeof("version.divelog") - 1)) { last_xml_version = atoi(buf); report_datafile_version(last_xml_version); } if (state->in_userid) { return true; } if (state->in_settings) { try_to_fill_fingerprint(name, buf, state); try_to_fill_dc_settings(name, buf, state); try_to_match_autogroup(name, buf); return true; } if (state->cur_dive_site) { try_to_fill_dive_site(state, name, buf); return true; } if (state->in_filter_constraint) { try_to_fill_filter_constraint(name, buf, state); return true; } if (state->in_fulltext) { try_to_fill_fulltext(name, buf, state); return true; } if (state->cur_filter) { try_to_fill_filter(state->cur_filter, name, buf); return true; } if (!state->cur_event.deleted) { try_to_fill_event(name, buf, state); return true; } if (state->cur_sample) { try_to_fill_sample(state->cur_sample, name, buf, state); return true; } if (state->cur_dc) { try_to_fill_dc(state->cur_dc, name, buf, state); return true; } if (state->cur_dive) { try_to_fill_dive(state->cur_dive, name, buf, state); return true; } if (state->cur_trip) { try_to_fill_trip(state->cur_trip, name, buf, state); return true; } return true; } static const char *nodename(xmlNode *node, char *buf, int len) { int levels = 2; char *p = buf; if (!node || (node->type != XML_CDATA_SECTION_NODE && !node->name)) { return "root"; } if (node->type == XML_CDATA_SECTION_NODE || (node->parent && !strcmp((const char *)node->name, "text"))) node = node->parent; /* Make sure it's always NUL-terminated */ p[--len] = 0; for (;;) { const char *name = (const char *)node->name; char c; while ((c = *name++) != 0) { /* Cheaper 'tolower()' for ASCII */ c = (c >= 'A' && c <= 'Z') ? c - 'A' + 'a' : c; *p++ = c; if (!--len) return buf; } *p = 0; node = node->parent; if (!node || !node->name) return buf; *p++ = '.'; if (!--len) return buf; if (!--levels) return buf; } } #define MAXNAME 32 static bool visit_one_node(xmlNode *node, struct parser_state *state) { xmlChar *content; char buffer[MAXNAME]; const char *name; content = node->content; if (!content || xmlIsBlankNode(node)) return true; name = nodename(node, buffer, sizeof(buffer)); return entry(name, (char *)content, state); } static bool traverse(xmlNode *root, struct parser_state *state); static bool traverse_properties(xmlNode *node, struct parser_state *state) { xmlAttr *p; bool ret = true; for (p = node->properties; p; p = p->next) if ((ret = traverse(p->children, state)) == false) break; return ret; } static bool visit(xmlNode *n, struct parser_state *state) { return visit_one_node(n, state) && traverse_properties(n, state) && traverse(n->children, state); } static void DivingLog_importer(struct parser_state *state) { state->import_source = DIVINGLOG; /* * Diving Log units are really strange. * * Temperatures are in C, except in samples, * when they are in Fahrenheit. Depths are in * meters, an dpressure is in PSI in the samples, * but in bar when it comes to working pressure. * * Crazy f*%^ morons. */ state->xml_parsing_units = SI_units; } static void uddf_importer(struct parser_state *state) { state->import_source = UDDF; state->xml_parsing_units = SI_units; state->xml_parsing_units.pressure = PASCALS; state->xml_parsing_units.temperature = KELVIN; } typedef void (*parser_func)(struct parser_state *); /* * I'm sure this could be done as some fancy DTD rules. * It's just not worth the headache. */ static struct nesting { const char *name; parser_func start, end; } nesting[] = { { "fingerprint", fingerprint_settings_start, fingerprint_settings_end }, { "divecomputerid", dc_settings_start, dc_settings_end }, { "settings", settings_start, settings_end }, { "site", dive_site_start, dive_site_end }, { "filterpreset", filter_preset_start, filter_preset_end }, { "fulltext", fulltext_start, fulltext_end }, { "constraint", filter_constraint_start, filter_constraint_end }, { "dive", dive_start, dive_end }, { "Dive", dive_start, dive_end }, { "trip", trip_start, trip_end }, { "sample", sample_start, sample_end }, { "waypoint", sample_start, sample_end }, { "SAMPLE", sample_start, sample_end }, { "reading", sample_start, sample_end }, { "event", event_start, event_end }, { "mix", (parser_func)cylinder_start, (parser_func)cylinder_end }, { "gasmix", (parser_func)cylinder_start, (parser_func)cylinder_end }, { "cylinder", (parser_func)cylinder_start, (parser_func)cylinder_end }, { "weightsystem", ws_start, ws_end }, { "divecomputer", divecomputer_start, divecomputer_end }, { "P", sample_start, sample_end }, { "userid", userid_start, userid_stop}, { "picture", picture_start, picture_end }, { "extradata", extra_data_start, extra_data_end }, /* Import type recognition */ { "Divinglog", DivingLog_importer }, { "uddf", uddf_importer }, { NULL, } }; static bool traverse(xmlNode *root, struct parser_state *state) { xmlNode *n; bool ret = true; for (n = root; n; n = n->next) { struct nesting *rule = nesting; if (!n->name) { if ((ret = visit(n, state)) == false) break; continue; } do { if (!strcmp(rule->name, (const char *)n->name)) break; rule++; } while (rule->name); if (rule->start) rule->start(state); if ((ret = visit(n, state)) == false) break; if (rule->end) rule->end(state); } return ret; } /* Per-file reset */ static void reset_all(struct parser_state *state) { /* * We reset the units for each file. You'd think it was * a per-dive property, but I'm not going to trust people * to do per-dive setup. If the xml does have per-dive * data within one file, we might have to reset it per * dive for that format. */ state->xml_parsing_units = SI_units; state->import_source = UNKNOWN; } /* divelog.de sends us xml files that claim to be iso-8859-1 * but once we decode the HTML encoded characters they turn * into UTF-8 instead. So skip the incorrect encoding * declaration and decode the HTML encoded characters */ static const char *preprocess_divelog_de(const char *buffer) { char *ret = strstr(buffer, "<DIVELOGSDATA>"); if (ret) { xmlParserCtxtPtr ctx; char buf[] = ""; size_t i; for (i = 0; i < strlen(ret); ++i) if (!isascii(ret[i])) return buffer; ctx = xmlCreateMemoryParserCtxt(buf, sizeof(buf)); ret = (char *)xmlStringLenDecodeEntities(ctx, (xmlChar *)ret, strlen(ret), XML_SUBSTITUTE_REF, 0, 0, 0); return ret; } return buffer; } int parse_xml_buffer(const char *url, const char *buffer, int size, struct dive_table *table, struct trip_table *trips, struct dive_site_table *sites, struct device_table *devices, struct filter_preset_table *filter_presets, const struct xml_params *params) { UNUSED(size); xmlDoc *doc; const char *res = preprocess_divelog_de(buffer); int ret = 0; struct parser_state state; init_parser_state(&state); state.target_table = table; state.trips = trips; state.sites = sites; state.devices = devices; state.fingerprints = &fingerprint_table; // simply use the global table for now state.filter_presets = filter_presets; doc = xmlReadMemory(res, strlen(res), url, NULL, XML_PARSE_HUGE | XML_PARSE_RECOVER); if (!doc) doc = xmlReadMemory(res, strlen(res), url, "latin1", XML_PARSE_HUGE | XML_PARSE_RECOVER); if (res != buffer) free((char *)res); if (!doc) return report_error(translate("gettextFromC", "Failed to parse '%s'"), url); reset_all(&state); dive_start(&state); doc = test_xslt_transforms(doc, params); if (!traverse(xmlDocGetRootElement(doc), &state)) { // we decided to give up on parsing... why? ret = -1; } dive_end(&state); free_parser_state(&state); xmlFreeDoc(doc); return ret; } /* * Parse a unsigned 32-bit integer in little-endian mode, * that is seconds since Jan 1, 2000. */ static timestamp_t parse_dlf_timestamp(unsigned char *buffer) { timestamp_t offset; offset = buffer[3]; offset = (offset << 8) + buffer[2]; offset = (offset << 8) + buffer[1]; offset = (offset << 8) + buffer[0]; // Jan 1, 2000 is 946684800 seconds after Jan 1, 1970, which is // the Unix epoch date that "timestamp_t" uses. return offset + 946684800; } int parse_dlf_buffer(unsigned char *buffer, size_t size, struct dive_table *table, struct trip_table *trips, struct dive_site_table *sites, struct device_table *devices) { unsigned char *ptr = buffer; unsigned char event; bool found; unsigned int time = 0; int i; char serial[6]; struct battery_status { uint16_t volt1; uint8_t percent1; uint16_t volt2; uint8_t percent2; }; struct battery_status battery_start = {0, 0, 0, 0}; struct battery_status battery_end = {0, 0, 0, 0}; uint16_t o2_sensor_calibration_values[4] = {0}; cylinder_t *cyl; struct parser_state state; init_parser_state(&state); state.target_table = table; state.trips = trips; state.sites = sites; state.devices = devices; // Check for the correct file magic if (ptr[0] != 'D' || ptr[1] != 'i' || ptr[2] != 'v' || ptr[3] != 'E') return -1; dive_start(&state); divecomputer_start(&state); state.cur_dc->model = strdup("DLF import"); // (ptr[7] << 8) + ptr[6] Is "Serial" snprintf(serial, sizeof(serial), "%d", (ptr[7] << 8) + ptr[6]); state.cur_dc->serial = strdup(serial); state.cur_dc->when = parse_dlf_timestamp(ptr + 8); state.cur_dive->when = state.cur_dc->when; state.cur_dc->duration.seconds = ((ptr[14] & 0xFE) << 16) + (ptr[13] << 8) + ptr[12]; // ptr[14] >> 1 is scrubber used in % // 3 bit dive type switch((ptr[15] & 0x38) >> 3) { case 0: // unknown case 1: state.cur_dc->divemode = OC; break; case 2: state.cur_dc->divemode = CCR; break; case 3: state.cur_dc->divemode = CCR; // mCCR break; case 4: state.cur_dc->divemode = FREEDIVE; break; case 5: state.cur_dc->divemode = OC; // Gauge break; case 6: state.cur_dc->divemode = PSCR; // ASCR break; case 7: state.cur_dc->divemode = PSCR; break; } state.cur_dc->maxdepth.mm = ((ptr[21] << 8) + ptr[20]) * 10; state.cur_dc->surface_pressure.mbar = ((ptr[25] << 8) + ptr[24]) / 10; // Declare initial mix as first cylinder cyl = get_or_create_cylinder(state.cur_dive, 0); cyl->gasmix.o2.permille = ptr[26] * 10; cyl->gasmix.he.permille = ptr[27] * 10; /* Done with parsing what we know about the dive header */ ptr += 32; // We're going to interpret ppO2 saved as a sensor value in these modes. if (state.cur_dc->divemode == CCR || state.cur_dc->divemode == PSCR) state.cur_dc->no_o2sensors = 1; for (; ptr < buffer + size; ptr += 16) { time = ((ptr[0] >> 4) & 0x0f) + ((ptr[1] << 4) & 0xff0) + ((ptr[2] << 12) & 0x1f000); event = ptr[0] & 0x0f; switch (event) { case 0: /* Regular sample */ sample_start(&state); state.cur_sample->time.seconds = time; state.cur_sample->depth.mm = ((ptr[5] << 8) + ptr[4]) * 10; // Crazy precision on these stored values... // Only store value if we're in CCR/PSCR mode, // because we rather calculate ppo2 our selfs. if (state.cur_dc->divemode == CCR || state.cur_dc->divemode == PSCR) state.cur_sample->o2sensor[0].mbar = ((ptr[7] << 8) + ptr[6]) / 10; // In some test files, ndl / tts / temp is bogus if this bits are 1 // flag bits in ptr[11] & 0xF0 is probably involved to, if ((ptr[2] >> 5) != 1) { // NDL in minutes, 10 bit state.cur_sample->ndl.seconds = (((ptr[9] & 0x03) << 8) + ptr[8]) * 60; // TTS in minutes, 10 bit state.cur_sample->tts.seconds = (((ptr[10] & 0x0F) << 6) + (ptr[9] >> 2)) * 60; // Temperature in 1/10 C, 10 bit signed state.cur_sample->temperature.mkelvin = ((ptr[11] & 0x20) ? -1 : 1) * (((ptr[11] & 0x1F) << 4) + (ptr[10] >> 4)) * 100 + ZERO_C_IN_MKELVIN; } state.cur_sample->stopdepth.mm = ((ptr[13] << 8) + ptr[12]) * 10; if (state.cur_sample->stopdepth.mm) state.cur_sample->in_deco = true; //ptr[14] is helium content, always zero? //ptr[15] is setpoint, what the computer thinks you should aim for? sample_end(&state); break; case 1: /* dive event */ case 2: /* automatic parameter change */ case 3: /* diver error */ case 4: /* internal error */ case 5: /* device activity log */ //Event 18 is a button press. Lets ingore that event. if (ptr[4] == 18) continue; event_start(&state); state.cur_event.time.seconds = time; switch (ptr[4]) { case 1: strcpy(state.cur_event.name, "Setpoint Manual"); state.cur_event.value = ptr[6]; sample_start(&state); state.cur_sample->setpoint.mbar = ptr[6] * 10; sample_end(&state); break; case 2: strcpy(state.cur_event.name, "Setpoint Auto"); state.cur_event.value = ptr[6]; sample_start(&state); state.cur_sample->setpoint.mbar = ptr[6] * 10; sample_end(&state); switch (ptr[7]) { case 0: strcat(state.cur_event.name, " Manual"); break; case 1: strcat(state.cur_event.name, " Auto Start"); break; case 2: strcat(state.cur_event.name, " Auto Hypox"); break; case 3: strcat(state.cur_event.name, " Auto Timeout"); break; case 4: strcat(state.cur_event.name, " Auto Ascent"); break; case 5: strcat(state.cur_event.name, " Auto Stall"); break; case 6: strcat(state.cur_event.name, " Auto SP Low"); break; default: break; } break; case 3: // obsolete strcpy(state.cur_event.name, "OC"); break; case 4: // obsolete strcpy(state.cur_event.name, "CCR"); break; case 5: strcpy(state.cur_event.name, "gaschange"); state.cur_event.type = SAMPLE_EVENT_GASCHANGE2; state.cur_event.value = ptr[7] << 8 ^ ptr[6]; found = false; for (i = 0; i < state.cur_dive->cylinders.nr; ++i) { const cylinder_t *cyl = get_cylinder(state.cur_dive, i); if (cyl->gasmix.o2.permille == ptr[6] * 10 && cyl->gasmix.he.permille == ptr[7] * 10) { found = true; break; } } if (!found) { cyl = cylinder_start(&state); cyl->gasmix.o2.permille = ptr[6] * 10; cyl->gasmix.he.permille = ptr[7] * 10; cylinder_end(&state); state.cur_event.gas.index = state.cur_dive->cylinders.nr - 1; } else { state.cur_event.gas.index = i; } break; case 6: strcpy(state.cur_event.name, "Start"); break; case 7: strcpy(state.cur_event.name, "Too Fast"); break; case 8: strcpy(state.cur_event.name, "Above Ceiling"); break; case 9: strcpy(state.cur_event.name, "Toxic"); break; case 10: strcpy(state.cur_event.name, "Hypox"); break; case 11: strcpy(state.cur_event.name, "Critical"); break; case 12: strcpy(state.cur_event.name, "Sensor Disabled"); break; case 13: strcpy(state.cur_event.name, "Sensor Enabled"); break; case 14: strcpy(state.cur_event.name, "O2 Backup"); break; case 15: strcpy(state.cur_event.name, "Peer Down"); break; case 16: strcpy(state.cur_event.name, "HS Down"); break; case 17: strcpy(state.cur_event.name, "Inconsistent"); break; case 18: // key pressed - It should never get in here // as we ingored it at the parent 'case 5'. break; case 19: // obsolete strcpy(state.cur_event.name, "SCR"); break; case 20: strcpy(state.cur_event.name, "Above Stop"); break; case 21: strcpy(state.cur_event.name, "Safety Miss"); break; case 22: strcpy(state.cur_event.name, "Fatal"); break; case 23: strcpy(state.cur_event.name, "gaschange"); state.cur_event.type = SAMPLE_EVENT_GASCHANGE2; state.cur_event.value = ptr[7] << 8 ^ ptr[6]; event_end(&state); break; case 24: strcpy(state.cur_event.name, "gaschange"); state.cur_event.type = SAMPLE_EVENT_GASCHANGE2; state.cur_event.value = ptr[7] << 8 ^ ptr[6]; event_end(&state); // This is both a mode change and a gas change event // so we encode it as two separate events. event_start(&state); strcpy(state.cur_event.name, "Change Mode"); switch (ptr[8]) { case 1: strcat(state.cur_event.name, ": OC"); break; case 2: strcat(state.cur_event.name, ": CCR"); break; case 3: strcat(state.cur_event.name, ": mCCR"); break; case 4: strcat(state.cur_event.name, ": Free"); break; case 5: strcat(state.cur_event.name, ": Gauge"); break; case 6: strcat(state.cur_event.name, ": ASCR"); break; case 7: strcat(state.cur_event.name, ": PSCR"); break; default: break; } event_end(&state); break; case 25: // uint16_t solenoid_bitmap = (ptr[7] << 8) + (ptr[6] << 0); // uint32_t time = (ptr[11] << 24) + (ptr[10] << 16) + (ptr[9] << 8) + (ptr[8] << 0); snprintf(state.cur_event.name, MAX_EVENT_NAME, "CCR O2 solenoid %s", ptr[12] ? "opened": "closed"); break; case 26: strcpy(state.cur_event.name, "User mark"); break; case 27: snprintf(state.cur_event.name, MAX_EVENT_NAME, "%sGF Switch (%d/%d)", ptr[6] ? "Bailout, ": "", ptr[7], ptr[8]); break; case 28: strcpy(state.cur_event.name, "Peer Up"); break; case 29: strcpy(state.cur_event.name, "HS Up"); break; case 30: snprintf(state.cur_event.name, MAX_EVENT_NAME, "CNS %d%%", ptr[6]); break; default: // No values above 30 had any description break; } event_end(&state); break; case 6: /* device configuration */ switch (((ptr[3] & 0x7f) << 3) + ((ptr[2] & 0xe0) >> 5)) { // Buffer to print extra string into char config_buf[256]; // Local variables to temporary decode into struct tm tm; char *device; char *deep_stops; case 0: // TEST_CCR_FULL_1 utc_mkdate(parse_dlf_timestamp(ptr + 12), &tm); snprintf(config_buf, sizeof(config_buf), "START=%04u-%02u-%02u %02u:%02u:%02u,TEST=%02X%02X%02X%02X,RESULT=%02X%02X%02X%02X", tm.tm_year, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, ptr[7], ptr[6], ptr[5], ptr[4], ptr[11], ptr[10], ptr[9], ptr[8]); add_extra_data(state.cur_dc, "TEST_CCR_FULL_1", config_buf); break; case 1: // TEST_CCR_PARTIAL_1 utc_mkdate(parse_dlf_timestamp(ptr + 12), &tm); snprintf(config_buf, sizeof(config_buf), "START=%04u-%02u-%02u %02u:%02u:%02u,TEST=%02X%02X%02X%02X,RESULT=%02X%02X%02X%02X", tm.tm_year, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, ptr[7], ptr[6], ptr[5], ptr[4], ptr[11], ptr[10], ptr[9], ptr[8]); add_extra_data(state.cur_dc, "TEST_CCR_PARTIAL_1", config_buf); break; case 2: // CFG_OXYGEN_CALIBRATION utc_mkdate(parse_dlf_timestamp(ptr + 12), &tm); o2_sensor_calibration_values[0] = (ptr[5] << 8) + ptr[4]; o2_sensor_calibration_values[1] = (ptr[7] << 8) + ptr[6]; o2_sensor_calibration_values[2] = (ptr[9] << 8) + ptr[8]; o2_sensor_calibration_values[3] = (ptr[11] << 8) + ptr[10]; snprintf(config_buf, sizeof(config_buf), "%04u,%04u,%04u,%04u,TIME=%04u-%02u-%02u %02u:%02u:%02u", o2_sensor_calibration_values[0], o2_sensor_calibration_values[1], o2_sensor_calibration_values[2], o2_sensor_calibration_values[3], tm.tm_year, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); add_extra_data(state.cur_dc, "CFG_OXYGEN_CALIBRATION", config_buf); break; case 3: // CFG_SERIAL snprintf(config_buf, sizeof(config_buf), "PRODUCT=%c%c%c%c,SERIAL=%c%c%c%c%c%c%c%c", ptr[4], ptr[5], ptr[6], ptr[7], ptr[8], ptr[9], ptr[10], ptr[11], ptr[12], ptr[13], ptr[14], ptr[15]); add_extra_data(state.cur_dc, "CFG_SERIAL", config_buf); break; case 4: // CFG_CONFIG_DECO switch ((ptr[5] & 0xC0) >> 6) { case 0: deep_stops = "none"; break; case 1: deep_stops = "Pyle"; break; case 2: deep_stops = "Sladek"; break; default: deep_stops = "unknown"; break; } snprintf(config_buf, sizeof(config_buf), "%s,%s,%s,safety stop required=%s,last_stop=%s,deco_algorithm=%s,stop_rounding=%u,deep_stops=%s", (ptr[4] & 0x80) ? "imperial" : "metric", (ptr[4] & 0x40) ? "sea" : "fresh", (ptr[4] & 0x30) ? "stops" : "ceiling", (ptr[4] & 0x10) ? "yes" : "no", (ptr[4] & 0x08) ? "6m" : "3m", (ptr[4] & 0x04) ? "VPM" : "Buhlmann+GF", (ptr[4] & 0x03) ? (ptr[4] & 0x03) * 30 : 1, deep_stops); add_extra_data(state.cur_dc, "CFG_CONFIG_DECO part 1", config_buf); snprintf(config_buf, sizeof(config_buf), "deep_stop_len=%u min,gas_switch_len=%u min,gf_low=%u,gf_high=%u,gf_low_bailout=%u,gf_high_bailout=%u,ppO2_low=%4.2f,ppO2_high=%4.2f", (ptr[5] & 0x38) >> 3, ptr[5] & 0x07, ptr[6], ptr[7], ptr[8], ptr[9], ptr[10] / 100.0f, ptr[11] / 100.0f); add_extra_data(state.cur_dc, "CFG_CONFIG_DECO part 2", config_buf); snprintf(config_buf, sizeof(config_buf), "alarm_global=%u,alarm_cns=%u,alarm_ppO2=%u,alarm_ceiling=%u,alarm_stop_miss=%u,alarm_decentrate=%u,alarm_ascentrate=%u", (ptr[12] & 0x80) >> 7, (ptr[12] & 0x40) >> 6, (ptr[12] & 0x20) >> 5, (ptr[12] & 0x10) >> 4, (ptr[12] & 0x08) >> 3, (ptr[12] & 0x04) >> 2, (ptr[12] & 0x02) >> 1); add_extra_data(state.cur_dc, "CFG_CONFIG_DECO part 3", config_buf); break; case 5: // CFG_VERSION switch (ptr[4]) { case 0: device = "FREEDOM"; break; case 1: device = "LIBERTY_CU"; break; case 2: device = "LIBERTY_HS"; break; default: device = "UNKNOWN"; break; } snprintf(config_buf, sizeof(config_buf), "DEVICE=%s,HW=%d.%d,FW=%d.%d.%d.%d,FLAGS=%04X", device, ptr[5], ptr[6], ptr[7], ptr[8], ptr[9], (ptr[15] << 24) + (ptr[14] << 16) + (ptr[13] << 8) + (ptr[12]), (ptr[11] << 8) + ptr[10]); add_extra_data(state.cur_dc, "CFG_VERSION", config_buf); break; } break; case 7: /* measure record */ switch (ptr[2] >> 5) { case 1: /* Record starting battery level */ if (!battery_start.volt1 && !battery_start.volt2) { battery_start.volt1 = (ptr[5] << 8) + ptr[4]; battery_start.percent1 = ptr[6]; battery_start.volt2 = (ptr[9] << 8) + ptr[8]; battery_start.percent2 = ptr[10]; } /* Measure Battery, recording the last reading only */ battery_end.volt1 = (ptr[5] << 8) + ptr[4]; battery_end.percent1 = ptr[6]; battery_end.volt2 = (ptr[9] << 8) + ptr[8]; battery_end.percent2 = ptr[10]; break; case 2: /* Measure He */ //printf("%ds he2 cells(0.01 mV): %d %d\n", time, (ptr[5] << 8) + ptr[4], (ptr[9] << 8) + ptr[8]); break; case 3: /* Measure Oxygen */ //printf("%d s: o2 cells(0.01 mV): %d %d %d %d\n", time, (ptr[5] << 8) + ptr[4], (ptr[7] << 8) + ptr[6], (ptr[9] << 8) + ptr[8], (ptr[11] << 8) + ptr[10]); // [Pa/mV] coeficient O2 // 100 Pa == 1 mbar sample_start(&state); state.cur_sample->time.seconds = time; state.cur_sample->o2sensor[0].mbar = ( ((ptr[5] << 8) + ptr[4]) * o2_sensor_calibration_values[0]) / 10000; state.cur_sample->o2sensor[1].mbar = ( ((ptr[7] << 8) + ptr[6]) * o2_sensor_calibration_values[1]) / 10000; state.cur_sample->o2sensor[2].mbar = ( ((ptr[9] << 8) + ptr[8]) * o2_sensor_calibration_values[2]) / 10000; // Subsurface only handles 3 o2 sensors. //state.cur_sample->o2sensor[3].mbar = ( ((ptr[11] << 8) + ptr[10]) * o2_sensor_calibration_values[3]) / 10000; sample_end(&state); break; case 4: /* Measure GPS */ state.cur_location.lat.udeg = (int)((ptr[7] << 24) + (ptr[6] << 16) + (ptr[5] << 8) + (ptr[4] << 0)); state.cur_location.lon.udeg = (int)((ptr[11] << 24) + (ptr[10] << 16) + (ptr[9] << 8) + (ptr[8] << 0)); add_dive_to_dive_site(state.cur_dive, create_dive_site_with_gps("DLF imported", &state.cur_location, state.sites)); break; default: break; } break; case 8: /* Deco event */ break; default: /* Unknown... */ break; } } /* Recording the starting battery status to extra data */ if (battery_start.volt1) { size_t stringsize = snprintf(NULL, 0, "%dmV (%d%%)", battery_start.volt1, battery_start.percent1) + 1; char *ptr = malloc(size); if (ptr) { snprintf(ptr, stringsize, "%dmV (%d%%)", battery_start.volt1, battery_start.percent1); add_extra_data(state.cur_dc, "Battery 1 (start)", ptr); free(ptr); } stringsize = snprintf(NULL, 0, "%dmV (%d%%)", battery_start.volt2, battery_start.percent2) + 1; ptr = malloc(stringsize); if (ptr) { snprintf(ptr, stringsize, "%dmV (%d%%)", battery_start.volt2, battery_start.percent2); add_extra_data(state.cur_dc, "Battery 2 (start)", ptr); free(ptr); } } /* Recording the ending battery status to extra data */ if (battery_end.volt1) { size_t stringsize = snprintf(NULL, 0, "%dmV (%d%%)", battery_end.volt1, battery_end.percent1) + 1; char *ptr = malloc(stringsize); if (ptr) { snprintf(ptr, stringsize, "%dmV (%d%%)", battery_end.volt1, battery_end.percent1); add_extra_data(state.cur_dc, "Battery 1 (end)", ptr); free(ptr); } stringsize = snprintf(NULL, 0, "%dmV (%d%%)", battery_end.volt2, battery_end.percent2) + 1; ptr = malloc(stringsize); if (ptr) { snprintf(ptr, stringsize, "%dmV (%d%%)", battery_end.volt2, battery_end.percent2); add_extra_data(state.cur_dc, "Battery 2 (end)", ptr); free(ptr); } } divecomputer_end(&state); dive_end(&state); free_parser_state(&state); return 0; } void parse_xml_init(void) { LIBXML_TEST_VERSION } void parse_xml_exit(void) { xmlCleanupParser(); } static struct xslt_files { const char *root; const char *file; const char *attribute; } xslt_files[] = { { "SUUNTO", "SuuntoSDM.xslt", NULL }, { "Dive", "SuuntoDM4.xslt", "xmlns" }, { "Dive", "shearwater.xslt", "version" }, { "JDiveLog", "jdivelog2subsurface.xslt", NULL }, { "dives", "MacDive.xslt", NULL }, { "DIVELOGSDATA", "divelogs.xslt", NULL }, { "uddf", "uddf.xslt", NULL }, { "UDDF", "uddf.xslt", NULL }, { "profile", "udcf.xslt", NULL }, { "Divinglog", "DivingLog.xslt", NULL }, { "csv", "csv2xml.xslt", NULL }, { "sensuscsv", "sensuscsv.xslt", NULL }, { "SubsurfaceCSV", "subsurfacecsv.xslt", NULL }, { "manualcsv", "manualcsv2xml.xslt", NULL }, { "logbook", "DiveLog.xslt", NULL }, { "AV1", "av1.xslt", NULL }, { "exportTrak", "Mares.xslt", NULL }, { NULL, } }; static xmlDoc *test_xslt_transforms(xmlDoc *doc, const struct xml_params *params) { struct xslt_files *info = xslt_files; xmlDoc *transformed; xsltStylesheetPtr xslt = NULL; xmlNode *root_element = xmlDocGetRootElement(doc); char *attribute; while (info->root) { if ((strcasecmp((const char *)root_element->name, info->root) == 0)) { if (info->attribute == NULL) break; else if (xmlGetProp(root_element, (const xmlChar *)info->attribute) != NULL) break; } info++; } if (info->root) { attribute = (char *)xmlGetProp(xmlFirstElementChild(root_element), (const xmlChar *)"name"); if (attribute) { if (strcasecmp(attribute, "subsurface") == 0) { free((void *)attribute); return doc; } free((void *)attribute); } xmlSubstituteEntitiesDefault(1); xslt = get_stylesheet(info->file); if (xslt == NULL) { report_error(translate("gettextFromC", "Can't open stylesheet %s"), info->file); return doc; } transformed = xsltApplyStylesheet(xslt, doc, xml_params_get(params)); xmlFreeDoc(doc); xsltFreeStylesheet(xslt); return transformed; } return doc; }
subsurface-for-dirk-master
core/parse-xml.c
// SPDX-License-Identifier: GPL-2.0 /* profile.c */ /* creates all the necessary data for drawing the dive profile */ #include "ssrf.h" #include "gettext.h" #include <limits.h> #include <string.h> #include <assert.h> #include "dive.h" #include "divelist.h" #include "event.h" #include "interpolate.h" #include "sample.h" #include "subsurface-string.h" #include "profile.h" #include "gaspressures.h" #include "deco.h" #include "libdivecomputer/parser.h" #include "libdivecomputer/version.h" #include "membuffer.h" #include "qthelper.h" #include "format.h" //#define DEBUG_GAS 1 #define MAX_PROFILE_DECO 7200 extern int ascent_velocity(int depth, int avg_depth, int bottom_time); struct dive *current_dive = NULL; unsigned int dc_number = 0; #ifdef DEBUG_PI /* debugging tool - not normally used */ static void dump_pi(struct plot_info *pi) { int i; printf("pi:{nr:%d maxtime:%d meandepth:%d maxdepth:%d \n" " maxpressure:%d mintemp:%d maxtemp:%d\n", pi->nr, pi->maxtime, pi->meandepth, pi->maxdepth, pi->maxpressure, pi->mintemp, pi->maxtemp); for (i = 0; i < pi->nr; i++) { struct plot_data *entry = &pi->entry[i]; printf(" entry[%d]:{cylinderindex:%d sec:%d pressure:{%d,%d}\n" " time:%d:%02d temperature:%d depth:%d stopdepth:%d stoptime:%d ndl:%d smoothed:%d po2:%lf phe:%lf pn2:%lf sum-pp %lf}\n", i, entry->sensor[0], entry->sec, entry->pressure[0], entry->pressure[1], entry->sec / 60, entry->sec % 60, entry->temperature, entry->depth, entry->stopdepth, entry->stoptime, entry->ndl, entry->smoothed, entry->pressures.o2, entry->pressures.he, entry->pressures.n2, entry->pressures.o2 + entry->pressures.he + entry->pressures.n2); } printf(" }\n"); } #endif #define ROUND_UP(x, y) ((((x) + (y) - 1) / (y)) * (y)) #define DIV_UP(x, y) (((x) + (y) - 1) / (y)) /* * When showing dive profiles, we scale things to the * current dive. However, we don't scale past less than * 30 minutes or 90 ft, just so that small dives show * up as such unless zoom is enabled. */ int get_maxtime(const struct plot_info *pi) { int seconds = pi->maxtime; int min = prefs.zoomed_plot ? 30 : 30 * 60; return MAX(min, seconds); } /* get the maximum depth to which we want to plot */ int get_maxdepth(const struct plot_info *pi) { /* 3m to spare */ int mm = pi->maxdepth + 3000; return prefs.zoomed_plot ? mm : MAX(30000, mm); } /* UNUSED! */ static int get_local_sac(struct plot_info *pi, int idx1, int idx2, struct dive *dive) __attribute__((unused)); /* Get local sac-rate (in ml/min) between entry1 and entry2 */ static int get_local_sac(struct plot_info *pi, int idx1, int idx2, struct dive *dive) { int index = 0; cylinder_t *cyl; struct plot_data *entry1 = pi->entry + idx1; struct plot_data *entry2 = pi->entry + idx2; int duration = entry2->sec - entry1->sec; int depth, airuse; pressure_t a, b; double atm; if (duration <= 0) return 0; a.mbar = get_plot_pressure(pi, idx1, 0); b.mbar = get_plot_pressure(pi, idx2, 0); if (!b.mbar || a.mbar <= b.mbar) return 0; /* Mean pressure in ATM */ depth = (entry1->depth + entry2->depth) / 2; atm = depth_to_atm(depth, dive); cyl = get_cylinder(dive, index); airuse = gas_volume(cyl, a) - gas_volume(cyl, b); /* milliliters per minute */ return lrint(airuse / atm * 60 / duration); } static velocity_t velocity(int speed) { velocity_t v; if (speed < -304) /* ascent faster than -60ft/min */ v = CRAZY; else if (speed < -152) /* above -30ft/min */ v = FAST; else if (speed < -76) /* -15ft/min */ v = MODERATE; else if (speed < -25) /* -5ft/min */ v = SLOW; else if (speed < 25) /* very hard to find data, but it appears that the recommendations for descent are usually about 2x ascent rate; still, we want stable to mean stable */ v = STABLE; else if (speed < 152) /* between 5 and 30ft/min is considered slow */ v = SLOW; else if (speed < 304) /* up to 60ft/min is moderate */ v = MODERATE; else if (speed < 507) /* up to 100ft/min is fast */ v = FAST; else /* more than that is just crazy - you'll blow your ears out */ v = CRAZY; return v; } static void analyze_plot_info(struct plot_info *pi) { int i; int nr = pi->nr; /* Smoothing function: 5-point triangular smooth */ for (i = 2; i < nr; i++) { struct plot_data *entry = pi->entry + i; int depth; if (i < nr - 2) { depth = entry[-2].depth + 2 * entry[-1].depth + 3 * entry[0].depth + 2 * entry[1].depth + entry[2].depth; entry->smoothed = (depth + 4) / 9; } /* vertical velocity in mm/sec */ /* Linus wants to smooth this - let's at least look at the samples that aren't FAST or CRAZY */ if (entry[0].sec - entry[-1].sec) { entry->speed = (entry[0].depth - entry[-1].depth) / (entry[0].sec - entry[-1].sec); entry->velocity = velocity(entry->speed); /* if our samples are short and we aren't too FAST*/ if (entry[0].sec - entry[-1].sec < 15 && entry->velocity < FAST) { int past = -2; while (i + past > 0 && entry[0].sec - entry[past].sec < 15) past--; entry->velocity = velocity((entry[0].depth - entry[past].depth) / (entry[0].sec - entry[past].sec)); } } else { entry->velocity = STABLE; entry->speed = 0; } } } /* * If the event has an explicit cylinder index, * we return that. If it doesn't, we return the best * match based on the gasmix. * * Some dive computers give cylinder indices, some * give just the gas mix. */ int get_cylinder_index(const struct dive *dive, const struct event *ev) { int best; struct gasmix mix; if (ev->gas.index >= 0) return ev->gas.index; /* * This should no longer happen! * * We now match up gas change events with their cylinders at dive * event fixup time. */ SSRF_INFO("Still looking up cylinder based on gas mix in get_cylinder_index()!\n"); mix = get_gasmix_from_event(dive, ev); best = find_best_gasmix_match(mix, &dive->cylinders); return best < 0 ? 0 : best; } struct event *get_next_event_mutable(struct event *event, const char *name) { if (!name || !*name) return NULL; while (event) { if (same_string(event->name, name)) return event; event = event->next; } return event; } const struct event *get_next_event(const struct event *event, const char *name) { return get_next_event_mutable((struct event *)event, name); } static int count_events(const struct divecomputer *dc) { int result = 0; struct event *ev = dc->events; while (ev != NULL) { result++; ev = ev->next; } return result; } static int set_setpoint(struct plot_info *pi, int i, int setpoint, int end) { while (i < pi->nr) { struct plot_data *entry = pi->entry + i; if (entry->sec > end) break; entry->o2pressure.mbar = setpoint; i++; } return i; } static void check_setpoint_events(const struct dive *dive, const struct divecomputer *dc, struct plot_info *pi) { UNUSED(dive); int i = 0; pressure_t setpoint; setpoint.mbar = 0; const struct event *ev = get_next_event(dc->events, "SP change"); if (!ev) return; do { i = set_setpoint(pi, i, setpoint.mbar, ev->time.seconds); setpoint.mbar = ev->value; ev = get_next_event(ev->next, "SP change"); } while (ev); set_setpoint(pi, i, setpoint.mbar, INT_MAX); } static void calculate_max_limits_new(const struct dive *dive, const struct divecomputer *given_dc, struct plot_info *pi, bool in_planner) { const struct divecomputer *dc = &(dive->dc); bool seen = false; bool found_sample_beyond_last_event = false; int maxdepth = dive->maxdepth.mm; int maxtime = 0; int maxpressure = 0, minpressure = INT_MAX; int maxhr = 0, minhr = INT_MAX; int mintemp = dive->mintemp.mkelvin; int maxtemp = dive->maxtemp.mkelvin; int cyl; /* Get the per-cylinder maximum pressure if they are manual */ for (cyl = 0; cyl < dive->cylinders.nr; cyl++) { int mbar_start = get_cylinder(dive, cyl)->start.mbar; int mbar_end = get_cylinder(dive, cyl)->end.mbar; if (mbar_start > maxpressure) maxpressure = mbar_start; if (mbar_end < minpressure) minpressure = mbar_end; } /* Then do all the samples from all the dive computers */ do { if (dc == given_dc) seen = true; int i = dc->samples; int lastdepth = 0; struct sample *s = dc->sample; struct event *ev; /* Make sure we can fit all events */ ev = dc->events; while (ev) { if (ev->time.seconds > maxtime) maxtime = ev->time.seconds; ev = ev->next; } while (--i >= 0) { int depth = s->depth.mm; int pressure = s->pressure[0].mbar; int temperature = s->temperature.mkelvin; int heartbeat = s->heartbeat; if (!mintemp && temperature < mintemp) mintemp = temperature; if (temperature > maxtemp) maxtemp = temperature; if (pressure && pressure < minpressure) minpressure = pressure; if (pressure > maxpressure) maxpressure = pressure; if (heartbeat > maxhr) maxhr = heartbeat; if (heartbeat && heartbeat < minhr) minhr = heartbeat; if (depth > maxdepth) maxdepth = s->depth.mm; /* Make sure that we get the first sample beyond the last event. * If maxtime is somewhere in the middle of the last segment, * populate_plot_entries() gets confused leading to display artifacts. */ if ((depth > SURFACE_THRESHOLD || lastdepth > SURFACE_THRESHOLD || in_planner || !found_sample_beyond_last_event) && s->time.seconds > maxtime) { found_sample_beyond_last_event = true; maxtime = s->time.seconds; } lastdepth = depth; s++; } dc = dc->next; if (dc == NULL && !seen) { dc = given_dc; seen = true; } } while (dc != NULL); if (minpressure > maxpressure) minpressure = 0; if (minhr > maxhr) minhr = maxhr; memset(pi, 0, sizeof(*pi)); pi->maxdepth = maxdepth; pi->maxtime = maxtime; pi->maxpressure = maxpressure; pi->minpressure = minpressure; pi->minhr = minhr; pi->maxhr = maxhr; pi->mintemp = mintemp; pi->maxtemp = maxtemp; } /* copy the previous entry (we know this exists), update time and depth * and zero out the sensor pressure (since this is a synthetic entry) * increment the entry pointer and the count of synthetic entries. */ static void insert_entry(struct plot_info *pi, int idx, int time, int depth, int sac) { struct plot_data *entry = pi->entry + idx; struct plot_data *prev = pi->entry + idx - 1; *entry = *prev; entry->sec = time; entry->depth = depth; entry->running_sum = prev->running_sum + (time - prev->sec) * (depth + prev->depth) / 2; entry->sac = sac; entry->ndl = -1; entry->bearing = -1; } void free_plot_info_data(struct plot_info *pi) { free(pi->entry); free(pi->pressures); memset(pi, 0, sizeof(*pi)); } static void populate_plot_entries(const struct dive *dive, const struct divecomputer *dc, struct plot_info *pi) { UNUSED(dive); int idx, maxtime, nr, i; int lastdepth, lasttime, lasttemp = 0; struct plot_data *plot_data; struct event *ev = dc->events; maxtime = pi->maxtime; /* * We want to have a plot_info event at least every 10s (so "maxtime/10+1"), * but samples could be more dense than that (so add in dc->samples). We also * need to have one for every event (so count events and add that) and * additionally we want two surface events around the whole thing (thus the * additional 4). There is also one extra space for a final entry * that has time > maxtime (because there can be surface samples * past "maxtime" in the original sample data) */ nr = dc->samples + 6 + maxtime / 10 + count_events(dc); plot_data = calloc(nr, sizeof(struct plot_data)); pi->entry = plot_data; pi->nr_cylinders = dive->cylinders.nr; pi->pressures = calloc(nr * (size_t)pi->nr_cylinders, sizeof(struct plot_pressure_data)); if (!plot_data) return; pi->nr = nr; idx = 2; /* the two extra events at the start */ lastdepth = 0; lasttime = 0; /* skip events at time = 0 */ while (ev && ev->time.seconds == 0) ev = ev->next; for (i = 0; i < dc->samples; i++) { struct plot_data *entry = plot_data + idx; struct sample *sample = dc->sample + i; int time = sample->time.seconds; int offset, delta; int depth = sample->depth.mm; int sac = sample->sac.mliter; /* Add intermediate plot entries if required */ delta = time - lasttime; if (delta <= 0) { time = lasttime; delta = 1; // avoid divide by 0 } for (offset = 10; offset < delta; offset += 10) { if (lasttime + offset > maxtime) break; /* Add events if they are between plot entries */ while (ev && (int)ev->time.seconds < lasttime + offset) { insert_entry(pi, idx, ev->time.seconds, interpolate(lastdepth, depth, ev->time.seconds - lasttime, delta), sac); entry++; idx++; ev = ev->next; } /* now insert the time interpolated entry */ insert_entry(pi, idx, lasttime + offset, interpolate(lastdepth, depth, offset, delta), sac); entry++; idx++; /* skip events that happened at this time */ while (ev && (int)ev->time.seconds == lasttime + offset) ev = ev->next; } /* Add events if they are between plot entries */ while (ev && (int)ev->time.seconds < time) { insert_entry(pi, idx, ev->time.seconds, interpolate(lastdepth, depth, ev->time.seconds - lasttime, delta), sac); entry++; idx++; ev = ev->next; } entry->sec = time; entry->depth = depth; entry->running_sum = (entry - 1)->running_sum + (time - (entry - 1)->sec) * (depth + (entry - 1)->depth) / 2; entry->stopdepth = sample->stopdepth.mm; entry->stoptime = sample->stoptime.seconds; entry->ndl = sample->ndl.seconds; entry->tts = sample->tts.seconds; entry->in_deco = sample->in_deco; entry->cns = sample->cns; if (dc->divemode == CCR || (dc->divemode == PSCR && dc->no_o2sensors)) { entry->o2pressure.mbar = entry->o2setpoint.mbar = sample->setpoint.mbar; // for rebreathers entry->o2sensor[0].mbar = sample->o2sensor[0].mbar; // for up to three rebreather O2 sensors entry->o2sensor[1].mbar = sample->o2sensor[1].mbar; entry->o2sensor[2].mbar = sample->o2sensor[2].mbar; } else { entry->pressures.o2 = sample->setpoint.mbar / 1000.0; } if (sample->pressure[0].mbar && sample->sensor[0] != NO_SENSOR) set_plot_pressure_data(pi, idx, SENSOR_PR, sample->sensor[0], sample->pressure[0].mbar); if (sample->pressure[1].mbar && sample->sensor[1] != NO_SENSOR) set_plot_pressure_data(pi, idx, SENSOR_PR, sample->sensor[1], sample->pressure[1].mbar); if (sample->temperature.mkelvin) entry->temperature = lasttemp = sample->temperature.mkelvin; else entry->temperature = lasttemp; entry->heartbeat = sample->heartbeat; entry->bearing = sample->bearing.degrees; entry->sac = sample->sac.mliter; if (sample->rbt.seconds) entry->rbt = sample->rbt.seconds; /* skip events that happened at this time */ while (ev && (int)ev->time.seconds == time) ev = ev->next; lasttime = time; lastdepth = depth; idx++; if (time > maxtime) break; } /* Add any remaining events */ while (ev) { struct plot_data *entry = plot_data + idx; int time = ev->time.seconds; if (time > lasttime) { insert_entry(pi, idx, ev->time.seconds, 0, 0); lasttime = time; idx++; entry++; } ev = ev->next; } /* Add two final surface events */ plot_data[idx++].sec = lasttime + 1; plot_data[idx++].sec = lasttime + 2; pi->nr = idx; } /* * Calculate the sac rate between the two plot entries 'first' and 'last'. * * Everything in between has a cylinder pressure for at least some of the cylinders. */ static int sac_between(const struct dive *dive, struct plot_info *pi, int first, int last, const bool gases[]) { int i, airuse; double pressuretime; if (first == last) return 0; /* Get airuse for the set of cylinders over the range */ airuse = 0; for (i = 0; i < pi->nr_cylinders; i++) { pressure_t a, b; cylinder_t *cyl; int cyluse; if (!gases[i]) continue; a.mbar = get_plot_pressure(pi, first, i); b.mbar = get_plot_pressure(pi, last, i); cyl = get_cylinder(dive, i); cyluse = gas_volume(cyl, a) - gas_volume(cyl, b); if (cyluse > 0) airuse += cyluse; } if (!airuse) return 0; /* Calculate depthpressure integrated over time */ pressuretime = 0.0; do { struct plot_data *entry = pi->entry + first; struct plot_data *next = entry + 1; int depth = (entry->depth + next->depth) / 2; int time = next->sec - entry->sec; double atm = depth_to_atm(depth, dive); pressuretime += atm * time; } while (++first < last); /* Turn "atmseconds" into "atmminutes" */ pressuretime /= 60; /* SAC = mliter per minute */ return lrint(airuse / pressuretime); } /* Is there pressure data for all gases? */ static bool all_pressures(struct plot_info *pi, int idx, const bool gases[]) { int i; for (i = 0; i < pi->nr_cylinders; i++) { if (gases[i] && !get_plot_pressure(pi, idx, i)) return false; } return true; } /* Which of the set of gases have pressure data? Returns false if none of them. */ static bool filter_pressures(struct plot_info *pi, int idx, const bool gases_in[], bool gases_out[]) { int i; bool has_pressure = false; for (i = 0; i < pi->nr_cylinders; i++) { gases_out[i] = gases_in[i] && get_plot_pressure(pi, idx, i); has_pressure |= gases_out[i]; } return has_pressure; } /* * Try to do the momentary sac rate for this entry, averaging over one * minute. This is premature optimization, but instead of allocating * an array of gases, the caller passes in scratch memory in the last * argument. */ static void fill_sac(const struct dive *dive, struct plot_info *pi, int idx, const bool gases_in[], bool gases[]) { struct plot_data *entry = pi->entry + idx; int first, last; int time; if (entry->sac) return; /* * We may not have pressure data for all the cylinders, * but we'll calculate the SAC for the ones we do have. */ if (!filter_pressures(pi, idx, gases_in, gases)) return; /* * Try to go back 30 seconds to get 'first'. * Stop if the cylinder pressure data set changes. */ first = idx; time = entry->sec - 30; while (idx > 0) { struct plot_data *entry = pi->entry + idx; struct plot_data *prev = pi->entry + idx - 1; if (prev->depth < SURFACE_THRESHOLD && entry->depth < SURFACE_THRESHOLD) break; if (prev->sec < time) break; if (!all_pressures(pi, idx - 1, gases)) break; idx--; first = idx; } /* Now find an entry a minute after the first one */ last = first; time = pi->entry[first].sec + 60; while (++idx < pi->nr) { struct plot_data *entry = pi->entry + last; struct plot_data *next = pi->entry + last + 1; if (next->depth < SURFACE_THRESHOLD && entry->depth < SURFACE_THRESHOLD) break; if (next->sec > time) break; if (!all_pressures(pi, idx + 1, gases)) break; last = idx; } /* Ok, now calculate the SAC between 'first' and 'last' */ entry->sac = sac_between(dive, pi, first, last, gases); } /* * Create a bitmap of cylinders that match our current gasmix */ static void matching_gases(const struct dive *dive, struct gasmix gasmix, bool gases[]) { int i; for (i = 0; i < dive->cylinders.nr; i++) gases[i] = same_gasmix(gasmix, get_cylinder(dive, i)->gasmix); } static void calculate_sac(const struct dive *dive, const struct divecomputer *dc, struct plot_info *pi) { struct gasmix gasmix = gasmix_invalid; const struct event *ev = NULL; bool *gases, *gases_scratch; gases = calloc(pi->nr_cylinders, sizeof(*gases)); /* This might be premature optimization, but let's allocate the gas array for * the fill_sac function only once an not once per sample */ gases_scratch = malloc(pi->nr_cylinders * sizeof(*gases)); for (int i = 0; i < pi->nr; i++) { struct plot_data *entry = pi->entry + i; struct gasmix newmix = get_gasmix(dive, dc, entry->sec, &ev, gasmix); if (!same_gasmix(newmix, gasmix)) { gasmix = newmix; matching_gases(dive, newmix, gases); } fill_sac(dive, pi, i, gases, gases_scratch); } free(gases); free(gases_scratch); } static void populate_secondary_sensor_data(const struct divecomputer *dc, struct plot_info *pi) { int *seen = calloc(pi->nr_cylinders, sizeof(*seen)); for (int idx = 0; idx < pi->nr; ++idx) for (int c = 0; c < pi->nr_cylinders; ++c) if (get_plot_pressure_data(pi, idx, SENSOR_PR, c)) ++seen[c]; // Count instances so we can differentiate a real sensor from just start and end pressure int idx = 0; /* We should try to see if it has interesting pressure data here */ for (int i = 0; i < dc->samples && idx < pi->nr; i++) { struct sample *sample = dc->sample + i; for (; idx < pi->nr; ++idx) { if (idx == pi->nr - 1 || pi->entry[idx].sec >= sample->time.seconds) // We've either found the entry at or just after the sample's time, // or this is the last entry so use for the last sensor readings if there are any. break; } for (int s = 0; s < MAX_SENSORS; ++s) // Copy sensor data if available, but don't add if this dc already has sensor data if (sample->sensor[s] != NO_SENSOR && seen[sample->sensor[s]] < 3 && sample->pressure[s].mbar) set_plot_pressure_data(pi, idx, SENSOR_PR, sample->sensor[s], sample->pressure[s].mbar); } free(seen); } /* * This adds a pressure entry to the plot_info based on the gas change * information and the manually filled in pressures. */ static void add_plot_pressure(struct plot_info *pi, int time, int cyl, pressure_t p) { for (int i = 0; i < pi->nr; i++) { if (i == pi->nr - 1 || pi->entry[i].sec >= time) { set_plot_pressure_data(pi, i, SENSOR_PR, cyl, p.mbar); return; } } } static void setup_gas_sensor_pressure(const struct dive *dive, const struct divecomputer *dc, struct plot_info *pi) { int prev, i; const struct event *ev; if (pi->nr_cylinders == 0) return; int *seen = malloc(pi->nr_cylinders * sizeof(*seen)); int *first = malloc(pi->nr_cylinders * sizeof(*first)); int *last = malloc(pi->nr_cylinders * sizeof(*last)); const struct divecomputer *secondary; for (i = 0; i < pi->nr_cylinders; i++) { seen[i] = 0; first[i] = 0; last[i] = INT_MAX; } prev = explicit_first_cylinder(dive, dc); seen[prev] = 1; for (ev = get_next_event(dc->events, "gaschange"); ev != NULL; ev = get_next_event(ev->next, "gaschange")) { int cyl = ev->gas.index; int sec = ev->time.seconds; if (cyl < 0) continue; last[prev] = sec; prev = cyl; last[cyl] = sec; if (!seen[cyl]) { // The end time may be updated by a subsequent cylinder change first[cyl] = sec; seen[cyl] = 1; } } last[prev] = INT_MAX; // Fill in "seen[]" array - mark cylinders we're not interested // in as negative. for (i = 0; i < pi->nr_cylinders; i++) { const cylinder_t *cyl = get_cylinder(dive, i); int start = cyl->start.mbar; int end = cyl->end.mbar; /* * Fundamentally uninteresting? * * A dive computer with no pressure data isn't interesting * to plot pressures for even if we've seen it.. */ if (!start || !end || start == end) { seen[i] = -1; continue; } /* If we've seen it, we're definitely interested */ if (seen[i]) continue; /* If it's only mentioned by other dc's, ignore it */ for_each_dc(dive, secondary) { if (has_gaschange_event(dive, secondary, i)) { seen[i] = -1; break; } } } for (i = 0; i < pi->nr_cylinders; i++) { if (seen[i] >= 0) { const cylinder_t *cyl = get_cylinder(dive, i); add_plot_pressure(pi, first[i], i, cyl->start); add_plot_pressure(pi, last[i], i, cyl->end); } } /* * Here, we should try to walk through all the dive computers, * and try to see if they have sensor data different from the * current dive computer (dc). */ secondary = &dive->dc; do { if (secondary == dc) continue; populate_secondary_sensor_data(secondary, pi); } while ((secondary = secondary->next) != NULL); free(seen); free(first); free(last); } /* calculate DECO STOP / TTS / NDL */ static void calculate_ndl_tts(struct deco_state *ds, const struct dive *dive, struct plot_data *entry, struct gasmix gasmix, double surface_pressure, enum divemode_t divemode, bool in_planner) { /* should this be configurable? */ /* ascent speed up to first deco stop */ const int ascent_s_per_step = 1; const int ascent_s_per_deco_step = 1; /* how long time steps in deco calculations? */ const int time_stepsize = 60; const int deco_stepsize = M_OR_FT(3, 10); /* at what depth is the current deco-step? */ int next_stop = ROUND_UP(deco_allowed_depth( tissue_tolerance_calc(ds, dive, depth_to_bar(entry->depth, dive), in_planner), surface_pressure, dive, 1), deco_stepsize); int ascent_depth = entry->depth; /* at what time should we give up and say that we got enuff NDL? */ /* If iterating through a dive, entry->tts_calc needs to be reset */ entry->tts_calc = 0; /* If we don't have a ceiling yet, calculate ndl. Don't try to calculate * a ndl for lower values than 3m it would take forever */ if (next_stop == 0) { if (entry->depth < 3000) { entry->ndl = MAX_PROFILE_DECO; return; } /* stop if the ndl is above max_ndl seconds, and call it plenty of time */ while (entry->ndl_calc < MAX_PROFILE_DECO && deco_allowed_depth(tissue_tolerance_calc(ds, dive, depth_to_bar(entry->depth, dive), in_planner), surface_pressure, dive, 1) <= 0 ) { entry->ndl_calc += time_stepsize; add_segment(ds, depth_to_bar(entry->depth, dive), gasmix, time_stepsize, entry->o2pressure.mbar, divemode, prefs.bottomsac, in_planner); } /* we don't need to calculate anything else */ return; } /* We are in deco */ entry->in_deco_calc = true; /* Add segments for movement to stopdepth */ for (; ascent_depth > next_stop; ascent_depth -= ascent_s_per_step * ascent_velocity(ascent_depth, entry->running_sum / entry->sec, 0), entry->tts_calc += ascent_s_per_step) { add_segment(ds, depth_to_bar(ascent_depth, dive), gasmix, ascent_s_per_step, entry->o2pressure.mbar, divemode, prefs.decosac, in_planner); next_stop = ROUND_UP(deco_allowed_depth(tissue_tolerance_calc(ds, dive, depth_to_bar(ascent_depth, dive), in_planner), surface_pressure, dive, 1), deco_stepsize); } ascent_depth = next_stop; /* And how long is the current deco-step? */ entry->stoptime_calc = 0; entry->stopdepth_calc = next_stop; next_stop -= deco_stepsize; /* And how long is the total TTS */ while (next_stop >= 0) { /* save the time for the first stop to show in the graph */ if (ascent_depth == entry->stopdepth_calc) entry->stoptime_calc += time_stepsize; entry->tts_calc += time_stepsize; if (entry->tts_calc > MAX_PROFILE_DECO) break; add_segment(ds, depth_to_bar(ascent_depth, dive), gasmix, time_stepsize, entry->o2pressure.mbar, divemode, prefs.decosac, in_planner); if (deco_allowed_depth(tissue_tolerance_calc(ds, dive, depth_to_bar(ascent_depth,dive), in_planner), surface_pressure, dive, 1) <= next_stop) { /* move to the next stop and add the travel between stops */ for (; ascent_depth > next_stop; ascent_depth -= ascent_s_per_deco_step * ascent_velocity(ascent_depth, entry->running_sum / entry->sec, 0), entry->tts_calc += ascent_s_per_deco_step) add_segment(ds, depth_to_bar(ascent_depth, dive), gasmix, ascent_s_per_deco_step, entry->o2pressure.mbar, divemode, prefs.decosac, in_planner); ascent_depth = next_stop; next_stop -= deco_stepsize; } } } /* Let's try to do some deco calculations. */ static void calculate_deco_information(struct deco_state *ds, const struct deco_state *planner_ds, const struct dive *dive, const struct divecomputer *dc, struct plot_info *pi) { int i, count_iteration = 0; double surface_pressure = (dc->surface_pressure.mbar ? dc->surface_pressure.mbar : get_surface_pressure_in_mbar(dive, true)) / 1000.0; bool first_iteration = true; int prev_deco_time = 10000000, time_deep_ceiling = 0; bool in_planner = planner_ds != NULL; if (!in_planner) { ds->deco_time = 0; ds->first_ceiling_pressure.mbar = 0; } else { ds->deco_time = planner_ds->deco_time; ds->first_ceiling_pressure = planner_ds->first_ceiling_pressure; } struct deco_state *cache_data_initial = NULL; lock_planner(); /* For VPM-B outside the planner, cache the initial deco state for CVA iterations */ if (decoMode(in_planner) == VPMB) { cache_deco_state(ds, &cache_data_initial); } /* For VPM-B outside the planner, iterate until deco time converges (usually one or two iterations after the initial) * Set maximum number of iterations to 10 just in case */ while ((abs(prev_deco_time - ds->deco_time) >= 30) && (count_iteration < 10)) { int last_ndl_tts_calc_time = 0, first_ceiling = 0, current_ceiling, last_ceiling = 0, final_tts = 0 , time_clear_ceiling = 0; if (decoMode(in_planner) == VPMB) ds->first_ceiling_pressure.mbar = depth_to_mbar(first_ceiling, dive); struct gasmix gasmix = gasmix_invalid; const struct event *ev = NULL, *evd = NULL; enum divemode_t current_divemode = UNDEF_COMP_TYPE; for (i = 1; i < pi->nr; i++) { struct plot_data *entry = pi->entry + i; int j, t0 = (entry - 1)->sec, t1 = entry->sec; int time_stepsize = 20, max_ceiling = -1; current_divemode = get_current_divemode(dc, entry->sec, &evd, &current_divemode); gasmix = get_gasmix(dive, dc, t1, &ev, gasmix); entry->ambpressure = depth_to_bar(entry->depth, dive); entry->gfline = get_gf(ds, entry->ambpressure, dive) * (100.0 - AMB_PERCENTAGE) + AMB_PERCENTAGE; if (t0 > t1) { SSRF_INFO("non-monotonous dive stamps %d %d\n", t0, t1); int xchg = t1; t1 = t0; t0 = xchg; } if (t0 != t1 && t1 - t0 < time_stepsize) time_stepsize = t1 - t0; for (j = t0 + time_stepsize; j <= t1; j += time_stepsize) { int depth = interpolate(entry[-1].depth, entry[0].depth, j - t0, t1 - t0); add_segment(ds, depth_to_bar(depth, dive), gasmix, time_stepsize, entry->o2pressure.mbar, current_divemode, entry->sac, in_planner); entry->icd_warning = ds->icd_warning; if ((t1 - j < time_stepsize) && (j < t1)) time_stepsize = t1 - j; } if (t0 == t1) { entry->ceiling = (entry - 1)->ceiling; } else { /* Keep updating the VPM-B gradients until the start of the ascent phase of the dive. */ if (decoMode(in_planner) == VPMB && last_ceiling >= first_ceiling && first_iteration == true) { nuclear_regeneration(ds, t1); vpmb_start_gradient(ds); /* For CVA iterations, calculate next gradient */ if (!first_iteration || in_planner) vpmb_next_gradient(ds, ds->deco_time, surface_pressure / 1000.0, in_planner); } entry->ceiling = deco_allowed_depth(tissue_tolerance_calc(ds, dive, depth_to_bar(entry->depth, dive), in_planner), surface_pressure, dive, !prefs.calcceiling3m); if (prefs.calcceiling3m) current_ceiling = deco_allowed_depth(tissue_tolerance_calc(ds, dive, depth_to_bar(entry->depth, dive), in_planner), surface_pressure, dive, true); else current_ceiling = entry->ceiling; last_ceiling = current_ceiling; /* If using VPM-B, take first_ceiling_pressure as the deepest ceiling */ if (decoMode(in_planner) == VPMB) { if (current_ceiling >= first_ceiling || (time_deep_ceiling == t0 && entry->depth == (entry - 1)->depth)) { time_deep_ceiling = t1; first_ceiling = current_ceiling; ds->first_ceiling_pressure.mbar = depth_to_mbar(first_ceiling, dive); if (first_iteration) { nuclear_regeneration(ds, t1); vpmb_start_gradient(ds); /* For CVA calculations, deco time = dive time remaining is a good guess, but we want to over-estimate deco_time for the first iteration so it converges correctly, so add 30min*/ if (!in_planner) ds->deco_time = pi->maxtime - t1 + 1800; vpmb_next_gradient(ds, ds->deco_time, surface_pressure / 1000.0, in_planner); } } // Use the point where the ceiling clears as the end of deco phase for CVA calculations if (current_ceiling > 0) time_clear_ceiling = 0; else if (time_clear_ceiling == 0 && t1 > time_deep_ceiling) time_clear_ceiling = t1; } } entry->surface_gf = 0.0; entry->current_gf = 0.0; for (j = 0; j < 16; j++) { double m_value = ds->buehlmann_inertgas_a[j] + entry->ambpressure / ds->buehlmann_inertgas_b[j]; double surface_m_value = ds->buehlmann_inertgas_a[j] + surface_pressure / ds->buehlmann_inertgas_b[j]; entry->ceilings[j] = deco_allowed_depth(ds->tolerated_by_tissue[j], surface_pressure, dive, 1); if (entry->ceilings[j] > max_ceiling) max_ceiling = entry->ceilings[j]; double current_gf = (ds->tissue_inertgas_saturation[j] - entry->ambpressure) / (m_value - entry->ambpressure); entry->percentages[j] = ds->tissue_inertgas_saturation[j] < entry->ambpressure ? lrint(ds->tissue_inertgas_saturation[j] / entry->ambpressure * AMB_PERCENTAGE) : lrint(AMB_PERCENTAGE + current_gf * (100.0 - AMB_PERCENTAGE)); if (current_gf > entry->current_gf) entry->current_gf = current_gf; double surface_gf = 100.0 * (ds->tissue_inertgas_saturation[j] - surface_pressure) / (surface_m_value - surface_pressure); if (surface_gf > entry->surface_gf) entry->surface_gf = surface_gf; } // In the planner, if the ceiling is violated, add an event. // TODO: This *really* shouldn't be done here. This is a contract // between the planner and the profile that the planner uses a dive // that can be trampled upon. But ultimately, the ceiling-violation // marker should be handled differently! // Don't scream if we violate the ceiling by a few cm. if (in_planner && !pi->waypoint_above_ceiling && entry->depth < max_ceiling - 100 && entry->sec > 0) { struct dive *non_const_dive = (struct dive *)dive; // cast away const! add_event(&non_const_dive->dc, entry->sec, SAMPLE_EVENT_CEILING, -1, max_ceiling / 1000, translate("gettextFromC", "planned waypoint above ceiling")); pi->waypoint_above_ceiling = true; } /* should we do more calculations? * We don't for print-mode because this info doesn't show up there * If the ceiling hasn't cleared by the last data point, we need tts for VPM-B CVA calculation * It is not necessary to do these calculation on the first VPMB iteration, except for the last data point */ if ((prefs.calcndltts && (decoMode(in_planner) != VPMB || in_planner || !first_iteration)) || (decoMode(in_planner) == VPMB && !in_planner && i == pi->nr - 1)) { /* only calculate ndl/tts on every 30 seconds */ if ((entry->sec - last_ndl_tts_calc_time) < 30 && i != pi->nr - 1) { struct plot_data *prev_entry = (entry - 1); entry->stoptime_calc = prev_entry->stoptime_calc; entry->stopdepth_calc = prev_entry->stopdepth_calc; entry->tts_calc = prev_entry->tts_calc; entry->ndl_calc = prev_entry->ndl_calc; continue; } last_ndl_tts_calc_time = entry->sec; /* We are going to mess up deco state, so store it for later restore */ struct deco_state *cache_data = NULL; cache_deco_state(ds, &cache_data); calculate_ndl_tts(ds, dive, entry, gasmix, surface_pressure, current_divemode, in_planner); if (decoMode(in_planner) == VPMB && !in_planner && i == pi->nr - 1) final_tts = entry->tts_calc; /* Restore "real" deco state for next real time step */ restore_deco_state(cache_data, ds, decoMode(in_planner) == VPMB); free(cache_data); } } if (decoMode(in_planner) == VPMB && !in_planner) { int this_deco_time; prev_deco_time = ds->deco_time; // Do we need to update deco_time? if (final_tts > 0) ds->deco_time = last_ndl_tts_calc_time + final_tts - time_deep_ceiling; else if (time_clear_ceiling > 0) /* Consistent with planner, deco_time ends after ascending (20s @9m/min from 3m) * at end of whole minute after clearing ceiling. The deepest ceiling when planning a dive * comes typically 10-60s after the end of the bottom time, so add 20s to the calculated * deco time. */ ds->deco_time = ROUND_UP(time_clear_ceiling - time_deep_ceiling + 20, 60) + 20; vpmb_next_gradient(ds, ds->deco_time, surface_pressure / 1000.0, in_planner); final_tts = 0; last_ndl_tts_calc_time = 0; first_ceiling = 0; first_iteration = false; count_iteration ++; this_deco_time = ds->deco_time; restore_deco_state(cache_data_initial, ds, true); ds->deco_time = this_deco_time; } else { // With Buhlmann iterating isn't needed. This makes the while condition false. prev_deco_time = ds->deco_time = 0; } } free(cache_data_initial); #if DECO_CALC_DEBUG & 1 dump_tissues(ds); #endif unlock_planner(); } /* Function calculate_ccr_po2: This function takes information from one plot_data structure (i.e. one point on * the dive profile), containing the oxygen sensor values of a CCR system and, for that plot_data structure, * calculates the po2 value from the sensor data. Several rules are applied, depending on how many o2 sensors * there are and the differences among the readings from these sensors. */ static int calculate_ccr_po2(struct plot_data *entry, const struct divecomputer *dc) { int sump = 0, minp = 999999, maxp = -999999; int diff_limit = 100; // The limit beyond which O2 sensor differences are considered significant (default = 100 mbar) int i, np = 0; for (i = 0; i < dc->no_o2sensors; i++) if (entry->o2sensor[i].mbar) { // Valid reading ++np; sump += entry->o2sensor[i].mbar; minp = MIN(minp, entry->o2sensor[i].mbar); maxp = MAX(maxp, entry->o2sensor[i].mbar); } switch (np) { case 0: // Uhoh return entry->o2pressure.mbar; case 1: // Return what we have return sump; case 2: // Take the average return sump / 2; case 3: // Voting logic if (2 * maxp - sump + minp < diff_limit) { // Upper difference acceptable... if (2 * minp - sump + maxp) // ...and lower difference acceptable return sump / 3; else return (sump - minp) / 2; } else { if (2 * minp - sump + maxp) // ...but lower difference acceptable return (sump - maxp) / 2; else return sump / 3; } default: // This should not happen assert(np <= 3); return 0; } } static void calculate_gas_information_new(const struct dive *dive, const struct divecomputer *dc, struct plot_info *pi) { int i; double amb_pressure; struct gasmix gasmix = gasmix_invalid; const struct event *evg = NULL, *evd = NULL; enum divemode_t current_divemode = UNDEF_COMP_TYPE; for (i = 1; i < pi->nr; i++) { double fn2, fhe; struct plot_data *entry = pi->entry + i; gasmix = get_gasmix(dive, dc, entry->sec, &evg, gasmix); amb_pressure = depth_to_bar(entry->depth, dive); current_divemode = get_current_divemode(dc, entry->sec, &evd, &current_divemode); fill_pressures(&entry->pressures, amb_pressure, gasmix, (current_divemode == OC) ? 0.0 : entry->o2pressure.mbar / 1000.0, current_divemode); fn2 = 1000.0 * entry->pressures.n2 / amb_pressure; fhe = 1000.0 * entry->pressures.he / amb_pressure; if (dc->divemode == PSCR) { // OC pO2 is calulated for PSCR with or without external PO2 monitoring. struct gasmix gasmix2 = get_gasmix(dive, dc, entry->sec, &evg, gasmix); entry->scr_OC_pO2.mbar = (int) depth_to_mbar(entry->depth, dive) * get_o2(gasmix2) / 1000; } /* Calculate MOD, EAD, END and EADD based on partial pressures calculated before * so there is no difference in calculating between OC and CC * END takes O₂ + N₂ (air) into account ("Narcotic" for trimix dives) * EAD just uses N₂ ("Air" for nitrox dives) */ pressure_t modpO2 = { .mbar = (int)(prefs.modpO2 * 1000) }; entry->mod = gas_mod(gasmix, modpO2, dive, 1).mm; entry->end = mbar_to_depth(lrint(depth_to_mbarf(entry->depth, dive) * (1000 - fhe) / 1000.0), dive); entry->ead = mbar_to_depth(lrint(depth_to_mbarf(entry->depth, dive) * fn2 / (double)N2_IN_AIR), dive); entry->eadd = mbar_to_depth(lrint(depth_to_mbarf(entry->depth, dive) * (entry->pressures.o2 / amb_pressure * O2_DENSITY + entry->pressures.n2 / amb_pressure * N2_DENSITY + entry->pressures.he / amb_pressure * HE_DENSITY) / (O2_IN_AIR * O2_DENSITY + N2_IN_AIR * N2_DENSITY) * 1000), dive); entry->density = gas_density(gasmix, depth_to_mbar(entry->depth, dive)); if (entry->mod < 0) entry->mod = 0; if (entry->ead < 0) entry->ead = 0; if (entry->end < 0) entry->end = 0; if (entry->eadd < 0) entry->eadd = 0; } } static void fill_o2_values(const struct dive *dive, const struct divecomputer *dc, struct plot_info *pi) /* In the samples from each dive computer, there may be uninitialised oxygen * sensor or setpoint values, e.g. when events were inserted into the dive log * or if the dive computer does not report o2 values with every sample. But * for drawing the profile a complete series of valid o2 pressure values is * required. This function takes the oxygen sensor data and setpoint values * from the structures of plotinfo and replaces the zero values with their * last known values so that the oxygen sensor data are complete and ready * for plotting. This function called by: create_plot_info_new() */ { int i, j; pressure_t last_sensor[3], o2pressure; pressure_t amb_pressure; for (i = 0; i < pi->nr; i++) { struct plot_data *entry = pi->entry + i; if (dc->divemode == CCR || (dc->divemode == PSCR && dc->no_o2sensors)) { if (i == 0) { // For 1st iteration, initialise the last_sensor values for (j = 0; j < dc->no_o2sensors; j++) last_sensor[j].mbar = pi->entry->o2sensor[j].mbar; } else { // Now re-insert the missing oxygen pressure values for (j = 0; j < dc->no_o2sensors; j++) if (entry->o2sensor[j].mbar) last_sensor[j].mbar = entry->o2sensor[j].mbar; else entry->o2sensor[j].mbar = last_sensor[j].mbar; } // having initialised the empty o2 sensor values for this point on the profile, amb_pressure.mbar = depth_to_mbar(entry->depth, dive); o2pressure.mbar = calculate_ccr_po2(entry, dc); // ...calculate the po2 based on the sensor data entry->o2pressure.mbar = MIN(o2pressure.mbar, amb_pressure.mbar); } else { entry->o2pressure.mbar = 0; // initialise po2 to zero for dctype = OC } } } #ifdef DEBUG_GAS /* A CCR debug function that writes the cylinder pressure and the oxygen values to the file debug_print_profiledata.dat: * Called in create_plot_info_new() */ static void debug_print_profiledata(struct plot_info *pi) { FILE *f1; struct plot_data *entry; int i; if (!(f1 = fopen("debug_print_profiledata.dat", "w"))) { printf("File open error for: debug_print_profiledata.dat\n"); } else { fprintf(f1, "id t1 gas gasint t2 t3 dil dilint t4 t5 setpoint sensor1 sensor2 sensor3 t6 po2 fo2\n"); for (i = 0; i < pi->nr; i++) { entry = pi->entry + i; fprintf(f1, "%d gas=%8d %8d ; dil=%8d %8d ; o2_sp= %d %d %d %d PO2= %f\n", i, get_plot_sensor_pressure(pi, i), get_plot_interpolated_pressure(pi, i), O2CYLINDER_PRESSURE(entry), INTERPOLATED_O2CYLINDER_PRESSURE(entry), entry->o2pressure.mbar, entry->o2sensor[0].mbar, entry->o2sensor[1].mbar, entry->o2sensor[2].mbar, entry->pressures.o2); } fclose(f1); } } #endif /* * Initialize a plot_info structure to all-zeroes */ void init_plot_info(struct plot_info *pi) { memset(pi, 0, sizeof(*pi)); } /* * Create a plot-info with smoothing and ranged min/max * * This also makes sure that we have extra empty events on both * sides, so that you can do end-points without having to worry * about it. * * The old data will be freed. Before the first call, the plot * info must be initialized with init_plot_info(). */ void create_plot_info_new(const struct dive *dive, const struct divecomputer *dc, struct plot_info *pi, const struct deco_state *planner_ds) { int o2, he, o2max; struct deco_state plot_deco_state; bool in_planner = planner_ds != NULL; init_decompression(&plot_deco_state, dive, in_planner); free_plot_info_data(pi); calculate_max_limits_new(dive, dc, pi, in_planner); get_dive_gas(dive, &o2, &he, &o2max); if (dc->divemode == FREEDIVE){ pi->dive_type = FREEDIVE; } else if (he > 0) { pi->dive_type = TRIMIX; } else { if (o2) pi->dive_type = NITROX; else pi->dive_type = AIR; } populate_plot_entries(dive, dc, pi); check_setpoint_events(dive, dc, pi); /* Populate setpoints */ setup_gas_sensor_pressure(dive, dc, pi); /* Try to populate our gas pressure knowledge */ for (int cyl = 0; cyl < pi->nr_cylinders; cyl++) populate_pressure_information(dive, dc, pi, cyl); fill_o2_values(dive, dc, pi); /* .. and insert the O2 sensor data having 0 values. */ calculate_sac(dive, dc, pi); /* Calculate sac */ calculate_deco_information(&plot_deco_state, planner_ds, dive, dc, pi); /* and ceiling information, using gradient factor values in Preferences) */ calculate_gas_information_new(dive, dc, pi); /* Calculate gas partial pressures */ #ifdef DEBUG_GAS debug_print_profiledata(pi); #endif pi->meandepth = dive->dc.meandepth.mm; analyze_plot_info(pi); } static void plot_string(const struct dive *d, const struct plot_info *pi, int idx, struct membuffer *b) { int pressurevalue, mod, ead, end, eadd; const char *depth_unit, *pressure_unit, *temp_unit, *vertical_speed_unit; double depthvalue, tempvalue, speedvalue, sacvalue; int decimals, cyl; const char *unit; const struct plot_data *entry = pi->entry + idx; depthvalue = get_depth_units(entry->depth, NULL, &depth_unit); put_format_loc(b, translate("gettextFromC", "@: %d:%02d\nD: %.1f%s\n"), FRACTION(entry->sec, 60), depthvalue, depth_unit); for (cyl = 0; cyl < pi->nr_cylinders; cyl++) { int mbar = get_plot_pressure(pi, idx, cyl); if (!mbar) continue; struct gasmix mix = get_cylinder(d, cyl)->gasmix; pressurevalue = get_pressure_units(mbar, &pressure_unit); put_format_loc(b, translate("gettextFromC", "P: %d%s (%s)\n"), pressurevalue, pressure_unit, gasname(mix)); } if (entry->temperature) { tempvalue = get_temp_units(entry->temperature, &temp_unit); put_format_loc(b, translate("gettextFromC", "T: %.1f%s\n"), tempvalue, temp_unit); } speedvalue = get_vertical_speed_units(abs(entry->speed), NULL, &vertical_speed_unit); /* Ascending speeds are positive, descending are negative */ if (entry->speed > 0) speedvalue *= -1; put_format_loc(b, translate("gettextFromC", "V: %.1f%s\n"), speedvalue, vertical_speed_unit); sacvalue = get_volume_units(entry->sac, &decimals, &unit); if (entry->sac && prefs.show_sac) put_format_loc(b, translate("gettextFromC", "SAC: %.*f%s/min\n"), decimals, sacvalue, unit); if (entry->cns) put_format_loc(b, translate("gettextFromC", "CNS: %u%%\n"), entry->cns); if (prefs.pp_graphs.po2 && entry->pressures.o2 > 0) { put_format_loc(b, translate("gettextFromC", "pO₂: %.2fbar\n"), entry->pressures.o2); if (entry->scr_OC_pO2.mbar) put_format_loc(b, translate("gettextFromC", "SCR ΔpO₂: %.2fbar\n"), entry->scr_OC_pO2.mbar/1000.0 - entry->pressures.o2); } if (prefs.pp_graphs.pn2 && entry->pressures.n2 > 0) put_format_loc(b, translate("gettextFromC", "pN₂: %.2fbar\n"), entry->pressures.n2); if (prefs.pp_graphs.phe && entry->pressures.he > 0) put_format_loc(b, translate("gettextFromC", "pHe: %.2fbar\n"), entry->pressures.he); if (prefs.mod && entry->mod > 0) { mod = lrint(get_depth_units(entry->mod, NULL, &depth_unit)); put_format_loc(b, translate("gettextFromC", "MOD: %d%s\n"), mod, depth_unit); } eadd = lrint(get_depth_units(entry->eadd, NULL, &depth_unit)); if (prefs.ead) { switch (pi->dive_type) { case NITROX: if (entry->ead > 0) { ead = lrint(get_depth_units(entry->ead, NULL, &depth_unit)); put_format_loc(b, translate("gettextFromC", "EAD: %d%s\nEADD: %d%s / %.1fg/ℓ\n"), ead, depth_unit, eadd, depth_unit, entry->density); break; } case TRIMIX: if (entry->end > 0) { end = lrint(get_depth_units(entry->end, NULL, &depth_unit)); put_format_loc(b, translate("gettextFromC", "END: %d%s\nEADD: %d%s / %.1fg/ℓ\n"), end, depth_unit, eadd, depth_unit, entry->density); break; } case AIR: if (entry->density > 0) { put_format_loc(b, translate("gettextFromC", "Density: %.1fg/ℓ\n"), entry->density); } case FREEDIVING: /* nothing */ break; } } if (entry->stopdepth) { depthvalue = get_depth_units(entry->stopdepth, NULL, &depth_unit); if (entry->ndl > 0) { /* this is a safety stop as we still have ndl */ if (entry->stoptime) put_format_loc(b, translate("gettextFromC", "Safety stop: %umin @ %.0f%s\n"), DIV_UP(entry->stoptime, 60), depthvalue, depth_unit); else put_format_loc(b, translate("gettextFromC", "Safety stop: unknown time @ %.0f%s\n"), depthvalue, depth_unit); } else { /* actual deco stop */ if (entry->stoptime) put_format_loc(b, translate("gettextFromC", "Deco: %umin @ %.0f%s\n"), DIV_UP(entry->stoptime, 60), depthvalue, depth_unit); else put_format_loc(b, translate("gettextFromC", "Deco: unknown time @ %.0f%s\n"), depthvalue, depth_unit); } } else if (entry->in_deco) { put_string(b, translate("gettextFromC", "In deco\n")); } else if (entry->ndl >= 0) { put_format_loc(b, translate("gettextFromC", "NDL: %umin\n"), DIV_UP(entry->ndl, 60)); } if (entry->tts) put_format_loc(b, translate("gettextFromC", "TTS: %umin\n"), DIV_UP(entry->tts, 60)); if (entry->stopdepth_calc && entry->stoptime_calc) { depthvalue = get_depth_units(entry->stopdepth_calc, NULL, &depth_unit); put_format_loc(b, translate("gettextFromC", "Deco: %umin @ %.0f%s (calc)\n"), DIV_UP(entry->stoptime_calc, 60), depthvalue, depth_unit); } else if (entry->in_deco_calc) { /* This means that we have no NDL left, * and we have no deco stop, * so if we just accend to the surface slowly * (ascent_mm_per_step / ascent_s_per_step) * everything will be ok. */ put_string(b, translate("gettextFromC", "In deco (calc)\n")); } else if (prefs.calcndltts && entry->ndl_calc != 0) { if(entry->ndl_calc < MAX_PROFILE_DECO) put_format_loc(b, translate("gettextFromC", "NDL: %umin (calc)\n"), DIV_UP(entry->ndl_calc, 60)); else put_string(b, translate("gettextFromC", "NDL: >2h (calc)\n")); } if (entry->tts_calc) { if (entry->tts_calc < MAX_PROFILE_DECO) put_format_loc(b, translate("gettextFromC", "TTS: %umin (calc)\n"), DIV_UP(entry->tts_calc, 60)); else put_string(b, translate("gettextFromC", "TTS: >2h (calc)\n")); } if (entry->rbt) put_format_loc(b, translate("gettextFromC", "RBT: %umin\n"), DIV_UP(entry->rbt, 60)); if (prefs.decoinfo) { if (entry->current_gf > 0.0) put_format(b, translate("gettextFromC", "GF %d%%\n"), (int)(100.0 * entry->current_gf)); if (entry->surface_gf > 0.0) put_format(b, translate("gettextFromC", "Surface GF %.0f%%\n"), entry->surface_gf); if (entry->ceiling) { depthvalue = get_depth_units(entry->ceiling, NULL, &depth_unit); put_format_loc(b, translate("gettextFromC", "Calculated ceiling %.1f%s\n"), depthvalue, depth_unit); if (prefs.calcalltissues) { int k; for (k = 0; k < 16; k++) { if (entry->ceilings[k]) { depthvalue = get_depth_units(entry->ceilings[k], NULL, &depth_unit); put_format_loc(b, translate("gettextFromC", "Tissue %.0fmin: %.1f%s\n"), buehlmann_N2_t_halflife[k], depthvalue, depth_unit); } } } } } if (entry->icd_warning) put_format(b, "%s", translate("gettextFromC", "ICD in leading tissue\n")); if (entry->heartbeat && prefs.hrgraph) put_format_loc(b, translate("gettextFromC", "heart rate: %d\n"), entry->heartbeat); if (entry->bearing >= 0) put_format_loc(b, translate("gettextFromC", "bearing: %d\n"), entry->bearing); if (entry->running_sum) { depthvalue = get_depth_units(entry->running_sum / entry->sec, NULL, &depth_unit); put_format_loc(b, translate("gettextFromC", "mean depth to here %.1f%s\n"), depthvalue, depth_unit); } strip_mb(b); } int get_plot_details_new(const struct dive *d, const struct plot_info *pi, int time, struct membuffer *mb) { int i; /* The two first and the two last plot entries do not have useful data */ if (pi->nr <= 4) return 0; for (i = 2; i < pi->nr - 3; i++) { if (pi->entry[i].sec >= time) break; } plot_string(d, pi, i, mb); return i; } /* Compare two plot_data entries and writes the results into a string */ void compare_samples(const struct dive *d, const struct plot_info *pi, int idx1, int idx2, char *buf, int bufsize, bool sum) { struct plot_data *start, *stop, *data; const char *depth_unit, *pressure_unit, *vertical_speed_unit; char *buf2 = malloc(bufsize); int avg_speed, max_asc_speed, max_desc_speed; int delta_depth, avg_depth, max_depth, min_depth; int bar_used, last_pressure, next_pressure, pressurevalue; int last_sec, delta_time; bool crossed_tankchange = false; double depthvalue, speedvalue; if (bufsize > 0) buf[0] = '\0'; if (idx1 < 0 || idx2 < 0) { free(buf2); return; } if (pi->entry[idx1].sec > pi->entry[idx2].sec) { int tmp = idx2; idx2 = idx1; idx1 = tmp; } else if (pi->entry[idx1].sec == pi->entry[idx2].sec) { free(buf2); return; } start = pi->entry + idx1; stop = pi->entry + idx2; avg_speed = 0; max_asc_speed = 0; max_desc_speed = 0; delta_depth = abs(start->depth - stop->depth); delta_time = abs(start->sec - stop->sec); avg_depth = 0; max_depth = 0; min_depth = INT_MAX; bar_used = 0; last_sec = start->sec; last_pressure = get_plot_pressure(pi, idx1, 0); data = start; for (int i = idx1; i < idx2; ++i) { data = pi->entry + i; if (sum) avg_speed += abs(data->speed) * (data->sec - last_sec); else avg_speed += data->speed * (data->sec - last_sec); avg_depth += data->depth * (data->sec - last_sec); if (data->speed > max_desc_speed) max_desc_speed = data->speed; if (data->speed < max_asc_speed) max_asc_speed = data->speed; if (data->depth < min_depth) min_depth = data->depth; if (data->depth > max_depth) max_depth = data->depth; /* Try to detect gas changes - this hack might work for some side mount scenarios? */ next_pressure = get_plot_pressure(pi, i, 0); if (next_pressure < last_pressure + 2000) bar_used += last_pressure - next_pressure; last_sec = data->sec; last_pressure = next_pressure; } avg_depth /= stop->sec - start->sec; avg_speed /= stop->sec - start->sec; snprintf_loc(buf, bufsize, translate("gettextFromC", "ΔT:%d:%02dmin"), delta_time / 60, delta_time % 60); memcpy(buf2, buf, bufsize); depthvalue = get_depth_units(delta_depth, NULL, &depth_unit); snprintf_loc(buf, bufsize, translate("gettextFromC", "%s ΔD:%.1f%s"), buf2, depthvalue, depth_unit); memcpy(buf2, buf, bufsize); depthvalue = get_depth_units(min_depth, NULL, &depth_unit); snprintf_loc(buf, bufsize, translate("gettextFromC", "%s ↓D:%.1f%s"), buf2, depthvalue, depth_unit); memcpy(buf2, buf, bufsize); depthvalue = get_depth_units(max_depth, NULL, &depth_unit); snprintf_loc(buf, bufsize, translate("gettextFromC", "%s ↑D:%.1f%s"), buf2, depthvalue, depth_unit); memcpy(buf2, buf, bufsize); depthvalue = get_depth_units(avg_depth, NULL, &depth_unit); snprintf_loc(buf, bufsize, translate("gettextFromC", "%s øD:%.1f%s\n"), buf2, depthvalue, depth_unit); memcpy(buf2, buf, bufsize); speedvalue = get_vertical_speed_units(abs(max_desc_speed), NULL, &vertical_speed_unit); snprintf_loc(buf, bufsize, translate("gettextFromC", "%s ↓V:%.2f%s"), buf2, speedvalue, vertical_speed_unit); memcpy(buf2, buf, bufsize); speedvalue = get_vertical_speed_units(abs(max_asc_speed), NULL, &vertical_speed_unit); snprintf_loc(buf, bufsize, translate("gettextFromC", "%s ↑V:%.2f%s"), buf2, speedvalue, vertical_speed_unit); memcpy(buf2, buf, bufsize); speedvalue = get_vertical_speed_units(abs(avg_speed), NULL, &vertical_speed_unit); snprintf_loc(buf, bufsize, translate("gettextFromC", "%s øV:%.2f%s"), buf2, speedvalue, vertical_speed_unit); memcpy(buf2, buf, bufsize); /* Only print if gas has been used */ if (bar_used && d->cylinders.nr > 0) { pressurevalue = get_pressure_units(bar_used, &pressure_unit); memcpy(buf2, buf, bufsize); snprintf_loc(buf, bufsize, translate("gettextFromC", "%s ΔP:%d%s"), buf2, pressurevalue, pressure_unit); cylinder_t *cyl = get_cylinder(d, 0); /* if we didn't cross a tank change and know the cylidner size as well, show SAC rate */ if (!crossed_tankchange && cyl->type.size.mliter) { double volume_value; int volume_precision; const char *volume_unit; int first = idx1; int last = idx2; while (first < last && get_plot_pressure(pi, first, 0) == 0) first++; while (last > first && get_plot_pressure(pi, last, 0) == 0) last--; pressure_t first_pressure = { get_plot_pressure(pi, first, 0) }; pressure_t stop_pressure = { get_plot_pressure(pi, last, 0) }; int volume_used = gas_volume(cyl, first_pressure) - gas_volume(cyl, stop_pressure); /* Mean pressure in ATM */ double atm = depth_to_atm(avg_depth, d); /* milliliters per minute */ int sac = lrint(volume_used / atm * 60 / delta_time); memcpy(buf2, buf, bufsize); volume_value = get_volume_units(sac, &volume_precision, &volume_unit); snprintf_loc(buf, bufsize, translate("gettextFromC", "%s SAC:%.*f%s/min"), buf2, volume_precision, volume_value, volume_unit); } } free(buf2); }
subsurface-for-dirk-master
core/profile.c
// SPDX-License-Identifier: GPL-2.0 /* gaspressures.c * --------------- * This file contains the routines to calculate the gas pressures in the cylinders. * The functions below support the code in profile.c. * The high-level function is populate_pressure_information(), called by function * create_plot_info_new() in profile.c. The other functions below are, in turn, * called by populate_pressure_information(). The calling sequence is as follows: * * populate_pressure_information() -> calc_pressure_time() * -> fill_missing_tank_pressures() -> fill_missing_segment_pressures() * -> get_pr_interpolate_data() * * The pr_track_t related functions below implement a linked list that is used by * the majority of the functions below. The linked list covers a part of the dive profile * for which there are no cylinder pressure data. Each element in the linked list * represents a segment between two consecutive points on the dive profile. * pr_track_t is defined in gaspressures.h */ #include "ssrf.h" #include "dive.h" #include "event.h" #include "profile.h" #include "gaspressures.h" #include "pref.h" #include <stdlib.h> /* * simple structure to track the beginning and end tank pressure as * well as the integral of depth over time spent while we have no * pressure reading from the tank */ typedef struct pr_track_struct pr_track_t; struct pr_track_struct { int start; int end; int t_start; int t_end; int pressure_time; pr_track_t *next; }; typedef struct pr_interpolate_struct pr_interpolate_t; struct pr_interpolate_struct { int start; int end; int pressure_time; int acc_pressure_time; }; enum interpolation_strategy {SAC, TIME, CONSTANT}; static pr_track_t *pr_track_alloc(int start, int t_start) { pr_track_t *pt = malloc(sizeof(pr_track_t)); pt->start = start; pt->end = 0; pt->t_start = pt->t_end = t_start; pt->pressure_time = 0; pt->next = NULL; return pt; } /* poor man's linked list */ static pr_track_t *list_last(pr_track_t *list) { pr_track_t *tail = list; if (!tail) return NULL; while (tail->next) { tail = tail->next; } return tail; } static pr_track_t *list_add(pr_track_t *list, pr_track_t *element) { pr_track_t *tail = list_last(list); if (!tail) return element; tail->next = element; return list; } static void list_free(pr_track_t *list) { if (!list) return; list_free(list->next); free(list); } #ifdef DEBUG_PR_TRACK static void dump_pr_track(int cyl, pr_track_t *track_pr) { pr_track_t *list; printf("cyl%d:\n", cyl); list = track_pr; while (list) { printf(" start %f end %f t_start %d:%02d t_end %d:%02d pt %d\n", mbar_to_PSI(list->start), mbar_to_PSI(list->end), FRACTION(list->t_start, 60), FRACTION(list->t_end, 60), list->pressure_time); list = list->next; } } #endif /* * This looks at the pressures for one cylinder, and * calculates any missing beginning/end pressures for * each segment by taking the over-all SAC-rate into * account for that cylinder. * * NOTE! Many segments have full pressure information * (both beginning and ending pressure). But if we have * switched away from a cylinder, we will have the * beginning pressure for the first segment with a * missing end pressure. We may then have one or more * segments without beginning or end pressures, until * we finally have a segment with an end pressure. * * We want to spread out the pressure over these missing * segments according to how big of a time_pressure area * they have. */ static void fill_missing_segment_pressures(pr_track_t *list, enum interpolation_strategy strategy) { double magic; while (list) { int start = list->start, end; pr_track_t *tmp = list; int pt_sum = 0, pt = 0; for (;;) { pt_sum += tmp->pressure_time; end = tmp->end; if (end) break; end = start; if (!tmp->next) break; tmp = tmp->next; } if (!start) start = end; /* * Now 'start' and 'end' contain the pressure values * for the set of segments described by 'list'..'tmp'. * pt_sum is the sum of all the pressure-times of the * segments. * * Now dole out the pressures relative to pressure-time. */ list->start = start; tmp->end = end; switch (strategy) { case SAC: for (;;) { int pressure; pt += list->pressure_time; pressure = start; if (pt_sum) pressure -= lrint((start - end) * (double)pt / pt_sum); list->end = pressure; if (list == tmp) break; list = list->next; list->start = pressure; } break; case TIME: if (list->t_end && (tmp->t_start - tmp->t_end)) { magic = (list->t_start - tmp->t_end) / (tmp->t_start - tmp->t_end); list->end = lrint(start - (start - end) * magic); } else { list->end = start; } break; case CONSTANT: list->end = start; } /* Ok, we've done that set of segments */ list = list->next; } } #ifdef DEBUG_PR_INTERPOLATE void dump_pr_interpolate(int i, pr_interpolate_t interpolate_pr) { printf("Interpolate for entry %d: start %d - end %d - pt %d - acc_pt %d\n", i, interpolate_pr.start, interpolate_pr.end, interpolate_pr.pressure_time, interpolate_pr.acc_pressure_time); } #endif static struct pr_interpolate_struct get_pr_interpolate_data(pr_track_t *segment, struct plot_info *pi, int cur) { // cur = index to pi->entry corresponding to t_end of segment; struct pr_interpolate_struct interpolate; int i; struct plot_data *entry; interpolate.start = segment->start; interpolate.end = segment->end; interpolate.acc_pressure_time = 0; interpolate.pressure_time = 0; for (i = 0; i < pi->nr; i++) { entry = pi->entry + i; if (entry->sec < segment->t_start) continue; interpolate.pressure_time += entry->pressure_time; if (entry->sec >= segment->t_end) break; if (i <= cur) interpolate.acc_pressure_time += entry->pressure_time; } return interpolate; } static void fill_missing_tank_pressures(const struct dive *dive, struct plot_info *pi, pr_track_t *track_pr, int cyl) { int i; struct plot_data *entry; pr_interpolate_t interpolate = { 0, 0, 0, 0 }; pr_track_t *last_segment = NULL; int cur_pr; enum interpolation_strategy strategy; /* no segment where this cylinder is used */ if (!track_pr) return; if (get_cylinder(dive, cyl)->cylinder_use == OC_GAS) strategy = SAC; else strategy = TIME; fill_missing_segment_pressures(track_pr, strategy); // Interpolate the missing tank pressure values .. cur_pr = track_pr->start; // in the pr_track_t lists of structures // and keep the starting pressure for each cylinder. #ifdef DEBUG_PR_TRACK dump_pr_track(cyl, track_pr); #endif /* Transfer interpolated cylinder pressures from pr_track strucktures to plotdata * Go down the list of tank pressures in plot_info. Align them with the start & * end times of each profile segment represented by a pr_track_t structure. Get * the accumulated pressure_depths from the pr_track_t structures and then * interpolate the pressure where these do not exist in the plot_info pressure * variables. Pressure values are transferred from the pr_track_t structures * to the plot_info structure, allowing us to plot the tank pressure. * * The first two pi structures are "fillers", but in case we don't have a sample * at time 0 we need to process the second of them here, therefore i=1 */ for (i = 1; i < pi->nr; i++) { // For each point on the profile: double magic; pr_track_t *segment; int pressure; entry = pi->entry + i; pressure = get_plot_pressure(pi, i, cyl); if (pressure) { // If there is a valid pressure value, last_segment = NULL; // get rid of interpolation data, cur_pr = pressure; // set current pressure continue; // and skip to next point. } // If there is NO valid pressure value.. // Find the pressure segment corresponding to this entry.. segment = track_pr; while (segment && segment->t_end < entry->sec) // Find the track_pr with end time.. segment = segment->next; // ..that matches the plot_info time (entry->sec) // After last segment? All done. if (!segment) break; // Before first segment, or between segments.. Go on, no interpolation. if (segment->t_start > entry->sec) continue; if (!segment->pressure_time) { // Empty segment? set_plot_pressure_data(pi, i, SENSOR_PR, cyl, cur_pr); // Just use our current pressure continue; // and skip to next point. } // If there is a valid segment but no tank pressure .. if (segment == last_segment) { interpolate.acc_pressure_time += entry->pressure_time; } else { // Set up an interpolation structure interpolate = get_pr_interpolate_data(segment, pi, i); last_segment = segment; } if(get_cylinder(dive, cyl)->cylinder_use == OC_GAS) { /* if this segment has pressure_time, then calculate a new interpolated pressure */ if (interpolate.pressure_time) { /* Overall pressure change over total pressure-time for this segment*/ magic = (interpolate.end - interpolate.start) / (double)interpolate.pressure_time; /* Use that overall pressure change to update the current pressure */ cur_pr = lrint(interpolate.start + magic * interpolate.acc_pressure_time); } } else { magic = (interpolate.end - interpolate.start) / (segment->t_end - segment->t_start); cur_pr = lrint(segment->start + magic * (entry->sec - segment->t_start)); } set_plot_pressure_data(pi, i, INTERPOLATED_PR, cyl, cur_pr); // and store the interpolated data in plot_info } } /* * What's the pressure-time between two plot data entries? * We're calculating the integral of pressure over time by * adding these up. * * The units won't matter as long as everybody agrees about * them, since they'll cancel out - we use this to calculate * a constant SAC-rate-equivalent, but we only use it to * scale pressures, so it ends up being a unitless scaling * factor. */ static inline int calc_pressure_time(const struct dive *dive, struct plot_data *a, struct plot_data *b) { int time = b->sec - a->sec; int depth = (a->depth + b->depth) / 2; if (depth <= SURFACE_THRESHOLD) return 0; return depth_to_mbar(depth, dive) * time; } #ifdef PRINT_PRESSURES_DEBUG // A CCR debugging tool that prints the gas pressures in cylinder 0 and in the diluent cylinder, used in populate_pressure_information(): static void debug_print_pressures(struct plot_info *pi) { int i; for (i = 0; i < pi->nr; i++) printf("%5d |%9d | %9d |\n", i, get_plot_sensor_pressure(pi, i), get_plot_interpolated_pressure(pi, i)); } #endif /* This function goes through the list of tank pressures, of structure plot_info for the dive profile where each * item in the list corresponds to one point (node) of the profile. It finds values for which there are no tank * pressures (pressure==0). For each missing item (node) of tank pressure it creates a pr_track_alloc structure * that represents a segment on the dive profile and that contains tank pressures. There is a linked list of * pr_track_alloc structures for each cylinder. These pr_track_alloc structures ultimately allow for filling * the missing tank pressure values on the dive profile using the depth_pressure of the dive. To do this, it * calculates the summed pressure-time value for the duration of the dive and stores these * in the pr_track_alloc * structures. This function is called by create_plot_info_new() in profile.c */ void populate_pressure_information(const struct dive *dive, const struct divecomputer *dc, struct plot_info *pi, int sensor) { UNUSED(dc); int first, last, cyl; cylinder_t *cylinder = get_cylinder(dive, sensor); pr_track_t *track = NULL; pr_track_t *current = NULL; const struct event *ev, *b_ev; int missing_pr = 0, dense = 1; enum divemode_t dmode = dc->divemode; const double gasfactor[5] = {1.0, 0.0, prefs.pscr_ratio/1000.0, 1.0, 1.0 }; if (sensor < 0 || sensor >= dive->cylinders.nr) return; /* if we have no pressure data whatsoever, this is pointless, so let's just return */ if (!cylinder->start.mbar && !cylinder->end.mbar && !cylinder->sample_start.mbar && !cylinder->sample_end.mbar) return; /* Get a rough range of where we have any pressures at all */ first = last = -1; for (int i = 0; i < pi->nr; i++) { int pressure = get_plot_sensor_pressure(pi, i, sensor); if (!pressure) continue; if (first < 0) first = i; last = i; } /* No sensor data at all? */ if (first == last) return; /* * Split the range: * - missing pressure data * - gas change events to other cylinders * * Note that we only look at gas switches if this cylinder * itself has a gas change event. */ cyl = sensor; ev = NULL; if (has_gaschange_event(dive, dc, sensor)) ev = get_next_event(dc->events, "gaschange"); b_ev = get_next_event(dc->events, "modechange"); for (int i = first; i <= last; i++) { struct plot_data *entry = pi->entry + i; int pressure = get_plot_sensor_pressure(pi, i, sensor); int time = entry->sec; while (ev && ev->time.seconds <= time) { // Find 1st gaschange event after cyl = get_cylinder_index(dive, ev); // the current gas change. if (cyl < 0) cyl = sensor; ev = get_next_event(ev->next, "gaschange"); } while (b_ev && b_ev->time.seconds <= time) { // Keep existing divemode, then dmode = b_ev->value; // find 1st divemode change event after the current b_ev = get_next_event(b_ev->next, "modechange"); // divemode change. } if (current) { // calculate pressure-time, taking into account the dive mode for this specific segment. entry->pressure_time = (int)(calc_pressure_time(dive, entry - 1, entry) * gasfactor[dmode] + 0.5); current->pressure_time += entry->pressure_time; current->t_end = entry->sec; if (pressure) current->end = pressure; } // We have a final pressure for 'current' // If a gas switch has occurred, finish the // current pressure track entry and continue // until we get back to this cylinder. if (cyl != sensor) { current = NULL; set_plot_pressure_data(pi, i, SENSOR_PR, sensor, 0); continue; } // If we have no pressure information, we will need to // continue with or without a tracking entry. Mark any // existing tracking entry as non-dense, and remember // to fill in interpolated data. if (current && !pressure) { missing_pr = 1; dense = 0; continue; } // If we already have a pressure tracking entry, and // it has not had any missing samples, just continue // using it - there's nothing to interpolate yet. if (current && dense) continue; // We need to start a new tracking entry, either // because the previous was interrupted by a gas // switch event, or because the previous one has // missing entries that need to be interpolated. // Or maybe we didn't have a previous one at all, // and this is the first pressure entry. current = pr_track_alloc(pressure, entry->sec); track = list_add(track, current); dense = 1; } if (missing_pr) { fill_missing_tank_pressures(dive, pi, track, sensor); } #ifdef PRINT_PRESSURES_DEBUG debug_print_pressures(pi); #endif list_free(track); }
subsurface-for-dirk-master
core/gaspressures.c
// SPDX-License-Identifier: GPL-2.0 #include "ssrf-version.h" const char *subsurface_git_version(void) { return GIT_VERSION_STRING; } const char *subsurface_canonical_version(void) { return CANONICAL_VERSION_STRING; } #ifdef SUBSURFACE_MOBILE const char *subsurface_mobile_version(void) { return MOBILE_VERSION_STRING; } #endif
subsurface-for-dirk-master
core/version.c
// SPDX-License-Identifier: LGPL-2.1+ /* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * Copyright (C) 2014 Venkatesh Shukla * Copyright (C) 2015-2016 Anton Lundin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> // malloc, free #include <string.h> // strerror #include <errno.h> // errno #include <sys/time.h> // gettimeofday #include <stdio.h> #include <libusb.h> #include <ftdi.h> #ifdef _WIN32 #include <windows.h> // Sleep #else #include <time.h> // nanosleep #endif #ifndef __ANDROID__ #define INFO(context, fmt, ...) fprintf(stderr, "INFO: " fmt "\n", ##__VA_ARGS__) #define ERROR(context, fmt, ...) fprintf(stderr, "ERROR: " fmt "\n", ##__VA_ARGS__) #else #include <android/log.h> #define INFO(context, fmt, ...) __android_log_print(ANDROID_LOG_DEBUG, __FILE__, "INFO: " fmt "\n", ##__VA_ARGS__) #define ERROR(context, fmt, ...) __android_log_print(ANDROID_LOG_DEBUG, __FILE__, "ERROR: " fmt "\n", ##__VA_ARGS__) #endif //#define SYSERROR(context, errcode) ERROR(__FILE__ ":" __LINE__ ": %s", strerror(errcode)) #define SYSERROR(context, errcode) ; #include "libdivecomputer.h" #include <libdivecomputer/context.h> #include <libdivecomputer/custom.h> #define VID 0x0403 // Vendor ID of FTDI typedef struct ftdi_serial_t { /* Library context. */ dc_context_t *context; /* * The file descriptor corresponding to the serial port. * Also a libftdi_ftdi_ctx could be used? */ struct ftdi_context *ftdi_ctx; long timeout; /* * Serial port settings are saved into this variable immediately * after the port is opened. These settings are restored when the * serial port is closed. * Saving this using libftdi context or libusb. Search further. * Custom implementation using libftdi functions could be done. */ unsigned int baudrate; unsigned int nbits; unsigned int databits; unsigned int stopbits; unsigned int parity; } ftdi_serial_t; static dc_status_t serial_ftdi_get_available (void *io, size_t *value) { ftdi_serial_t *device = io; if (device == NULL) return DC_STATUS_INVALIDARGS; // Direct access is not encouraged. But function implementation // is not available. The return quantity might be anything. // Find out further about its possible values and correct way of // access. *value = device->ftdi_ctx->readbuffer_remaining; return DC_STATUS_SUCCESS; } static dc_status_t serial_ftdi_get_transmitted (ftdi_serial_t *device) { if (device == NULL) return DC_STATUS_INVALIDARGS; // This is not possible using libftdi. Look further into it. return DC_STATUS_UNSUPPORTED; } /* * Get an msec value on some random base */ static unsigned int serial_ftdi_get_msec(void) { #ifdef _WIN32 return GetTickCount(); #else struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec * 1000 + tv.tv_usec / 1000; #endif } static dc_status_t serial_ftdi_sleep (void *io, unsigned int timeout) { ftdi_serial_t *device = io; if (device == NULL) return DC_STATUS_INVALIDARGS; INFO (device->context, "Sleep: value=%u", timeout); #ifdef _WIN32 Sleep((DWORD)timeout); #else struct timespec ts; ts.tv_sec = (timeout / 1000); ts.tv_nsec = (timeout % 1000) * 1000000; while (nanosleep (&ts, &ts) != 0) { if (errno != EINTR ) { SYSERROR (device->context, errno); return DC_STATUS_IO; } } #endif return DC_STATUS_SUCCESS; } // Used internally for opening ftdi devices static int serial_ftdi_open_device (struct ftdi_context *ftdi_ctx) { INFO(0, "serial_ftdi_open_device called"); int accepted_pids[] = { 0x6001, 0x6010, 0x6011, // Suunto (Smart Interface), Heinrichs Weikamp 0x6015, // possibly Aqualung 0xF460, // Oceanic 0xF680, // Suunto 0x87D0, // Cressi (Leonardo) }; int num_accepted_pids = sizeof(accepted_pids) / sizeof(accepted_pids[0]); int i, pid, ret; for (i = 0; i < num_accepted_pids; i++) { pid = accepted_pids[i]; ret = ftdi_usb_open (ftdi_ctx, VID, pid); INFO(0, "FTDI tried VID %04x pid %04x ret %d\n", VID, pid, ret); if (ret == -3) // Device not found continue; else return ret; } // No supported devices are attached. return ret; } // // Open the serial port. // Initialise ftdi_context and use it to open the device static dc_status_t serial_ftdi_open (void **io, dc_context_t *context) { INFO(0, "serial_ftdi_open called"); // Allocate memory. ftdi_serial_t *device = (ftdi_serial_t *) malloc (sizeof (ftdi_serial_t)); if (device == NULL) { INFO(0, "couldn't allocate memory"); SYSERROR (context, errno); return DC_STATUS_NOMEMORY; } INFO(0, "setting up ftdi_ctx"); struct ftdi_context *ftdi_ctx = ftdi_new(); if (ftdi_ctx == NULL) { INFO(0, "failed ftdi_new()"); free(device); SYSERROR (context, errno); return DC_STATUS_NOMEMORY; } // Library context. //device->context = context; // Default to blocking reads. device->timeout = -1; // Default to full-duplex. device->baudrate = 0; device->nbits = 0; device->databits = 0; device->stopbits = 0; device->parity = 0; // Initialize device ftdi context INFO(0, "initialize ftdi_ctx"); ftdi_init(ftdi_ctx); if (ftdi_set_interface(ftdi_ctx,INTERFACE_ANY)) { free(device); ERROR (context, "%s", ftdi_get_error_string(ftdi_ctx)); return DC_STATUS_IO; } INFO(0, "call serial_ftdi_open_device"); if (serial_ftdi_open_device(ftdi_ctx) < 0) { free(device); ERROR (context, "%s", ftdi_get_error_string(ftdi_ctx)); return DC_STATUS_IO; } if (ftdi_usb_reset(ftdi_ctx)) { free(device); ERROR (context, "%s", ftdi_get_error_string(ftdi_ctx)); return DC_STATUS_IO; } if (ftdi_usb_purge_buffers(ftdi_ctx)) { free(device); ERROR (context, "%s", ftdi_get_error_string(ftdi_ctx)); return DC_STATUS_IO; } device->ftdi_ctx = ftdi_ctx; *io = device; return DC_STATUS_SUCCESS; } // // Close the serial port. // static dc_status_t serial_ftdi_close (void *io) { ftdi_serial_t *device = io; if (device == NULL) return DC_STATUS_SUCCESS; // Restore the initial terminal attributes. // See if it is possible using libusb or libftdi int ret = ftdi_usb_close(device->ftdi_ctx); if (ret < 0) { ERROR (device->context, "Unable to close the ftdi device : %d (%s)\n", ret, ftdi_get_error_string(device->ftdi_ctx)); return ret; } ftdi_free(device->ftdi_ctx); // Free memory. free (device); return DC_STATUS_SUCCESS; } // // Configure the serial port (baudrate, databits, parity, stopbits and flowcontrol). // static dc_status_t serial_ftdi_configure (void *io, unsigned int baudrate, unsigned int databits, dc_parity_t parity, dc_stopbits_t stopbits, dc_flowcontrol_t flowcontrol) { ftdi_serial_t *device = io; if (device == NULL) return DC_STATUS_INVALIDARGS; INFO (device->context, "Configure: baudrate=%i, databits=%i, parity=%i, stopbits=%i, flowcontrol=%i", baudrate, databits, parity, stopbits, flowcontrol); enum ftdi_bits_type ft_bits; enum ftdi_stopbits_type ft_stopbits; enum ftdi_parity_type ft_parity; if (ftdi_set_baudrate(device->ftdi_ctx, baudrate) < 0) { ERROR (device->context, "%s", ftdi_get_error_string(device->ftdi_ctx)); return DC_STATUS_IO; } // Set the character size. switch (databits) { case 7: ft_bits = BITS_7; break; case 8: ft_bits = BITS_8; break; default: return DC_STATUS_INVALIDARGS; } // Set the parity type. switch (parity) { case DC_PARITY_NONE: /**< No parity */ ft_parity = NONE; break; case DC_PARITY_EVEN: /**< Even parity */ ft_parity = EVEN; break; case DC_PARITY_ODD: /**< Odd parity */ ft_parity = ODD; break; case DC_PARITY_MARK: /**< Mark parity (always 1) */ case DC_PARITY_SPACE: /**< Space parity (alwasy 0) */ default: return DC_STATUS_INVALIDARGS; } // Set the number of stop bits. switch (stopbits) { case DC_STOPBITS_ONE: /**< 1 stop bit */ ft_stopbits = STOP_BIT_1; break; case DC_STOPBITS_TWO: /**< 2 stop bits */ ft_stopbits = STOP_BIT_2; break; case DC_STOPBITS_ONEPOINTFIVE: /**< 1.5 stop bits*/ default: return DC_STATUS_INVALIDARGS; } // Set the attributes if (ftdi_set_line_property(device->ftdi_ctx, ft_bits, ft_stopbits, ft_parity)) { ERROR (device->context, "%s", ftdi_get_error_string(device->ftdi_ctx)); return DC_STATUS_IO; } // Set the flow control. switch (flowcontrol) { case DC_FLOWCONTROL_NONE: /**< No flow control */ if (ftdi_setflowctrl(device->ftdi_ctx, SIO_DISABLE_FLOW_CTRL) < 0) { ERROR (device->context, "%s", ftdi_get_error_string(device->ftdi_ctx)); return DC_STATUS_IO; } break; case DC_FLOWCONTROL_HARDWARE: /**< Hardware (RTS/CTS) flow control */ if (ftdi_setflowctrl(device->ftdi_ctx, SIO_RTS_CTS_HS) < 0) { ERROR (device->context, "%s", ftdi_get_error_string(device->ftdi_ctx)); return DC_STATUS_IO; } break; case DC_FLOWCONTROL_SOFTWARE: /**< Software (XON/XOFF) flow control */ if (ftdi_setflowctrl(device->ftdi_ctx, SIO_XON_XOFF_HS) < 0) { ERROR (device->context, "%s", ftdi_get_error_string(device->ftdi_ctx)); return DC_STATUS_IO; } break; default: return DC_STATUS_INVALIDARGS; } device->baudrate = baudrate; device->nbits = 1 + databits + stopbits + (parity ? 1 : 0); device->databits = databits; device->stopbits = stopbits; device->parity = parity; return DC_STATUS_SUCCESS; } // // Configure the serial port (timeouts). // static dc_status_t serial_ftdi_set_timeout (void *io, int timeout) { ftdi_serial_t *device = io; if (device == NULL) return DC_STATUS_INVALIDARGS; INFO (device->context, "Timeout: value=%i", timeout); device->timeout = timeout; return DC_STATUS_SUCCESS; } static dc_status_t serial_ftdi_read (void *io, void *data, size_t size, size_t *actual) { ftdi_serial_t *device = io; if (device == NULL) return DC_STATUS_INVALIDARGS; // The total timeout. long timeout = device->timeout; // Simulate blocking read as 10s timeout if (timeout == -1) timeout = 10000; unsigned int start_time = serial_ftdi_get_msec(); unsigned int nbytes = 0; while (nbytes < size) { int n = ftdi_read_data (device->ftdi_ctx, (unsigned char *) data + nbytes, size - nbytes); if (n < 0) { if (n == LIBUSB_ERROR_INTERRUPTED) continue; //Retry. ERROR (device->context, "%s", ftdi_get_error_string(device->ftdi_ctx)); return DC_STATUS_IO; //Error during read call. } else if (n == 0) { if (serial_ftdi_get_msec() - start_time > timeout) { ERROR(device->context, "%s", "FTDI read timed out."); return DC_STATUS_TIMEOUT; } serial_ftdi_sleep (device, 1); } nbytes += n; } INFO (device->context, "Read %d bytes", nbytes); if (actual) *actual = nbytes; return DC_STATUS_SUCCESS; } static dc_status_t serial_ftdi_write (void *io, const void *data, size_t size, size_t *actual) { ftdi_serial_t *device = io; if (device == NULL) return DC_STATUS_INVALIDARGS; unsigned int nbytes = 0; while (nbytes < size) { int n = ftdi_write_data (device->ftdi_ctx, (unsigned char *) data + nbytes, size - nbytes); if (n < 0) { if (n == LIBUSB_ERROR_INTERRUPTED) continue; // Retry. ERROR (device->context, "%s", ftdi_get_error_string(device->ftdi_ctx)); return DC_STATUS_IO; // Error during write call. } else if (n == 0) { break; // EOF. } nbytes += n; } INFO (device->context, "Wrote %d bytes", nbytes); if (actual) *actual = nbytes; return DC_STATUS_SUCCESS; } static dc_status_t serial_ftdi_purge (void *io, dc_direction_t queue) { ftdi_serial_t *device = io; if (device == NULL) return DC_STATUS_INVALIDARGS; size_t input; serial_ftdi_get_available (io, &input); INFO (device->context, "Flush: queue=%u, input=%lu, output=%i", queue, input, serial_ftdi_get_transmitted (device)); switch (queue) { case DC_DIRECTION_INPUT: /**< Input direction */ if (ftdi_usb_purge_tx_buffer(device->ftdi_ctx)) { ERROR (device->context, "%s", ftdi_get_error_string(device->ftdi_ctx)); return DC_STATUS_IO; } break; case DC_DIRECTION_OUTPUT: /**< Output direction */ if (ftdi_usb_purge_rx_buffer(device->ftdi_ctx)) { ERROR (device->context, "%s", ftdi_get_error_string(device->ftdi_ctx)); return DC_STATUS_IO; } break; case DC_DIRECTION_ALL: /**< All directions */ default: if (ftdi_usb_reset(device->ftdi_ctx)) { ERROR (device->context, "%s", ftdi_get_error_string(device->ftdi_ctx)); return DC_STATUS_IO; } break; } return DC_STATUS_SUCCESS; } static dc_status_t serial_ftdi_set_break (void *io, unsigned int level) { ftdi_serial_t *device = io; if (device == NULL) return DC_STATUS_INVALIDARGS; INFO (device->context, "Break: value=%i", level); if (ftdi_set_line_property2(device->ftdi_ctx, device->databits, device->stopbits, device->parity, level)) { ERROR (device->context, "%s", ftdi_get_error_string(device->ftdi_ctx)); return DC_STATUS_IO; } return DC_STATUS_UNSUPPORTED; } static dc_status_t serial_ftdi_set_dtr (void *io, unsigned int value) { ftdi_serial_t *device = io; if (device == NULL) return DC_STATUS_INVALIDARGS; INFO (device->context, "DTR: value=%u", value); if (ftdi_setdtr(device->ftdi_ctx, value)) { ERROR (device->context, "%s", ftdi_get_error_string(device->ftdi_ctx)); return DC_STATUS_IO; } return DC_STATUS_SUCCESS; } static dc_status_t serial_ftdi_set_rts (void *io, unsigned int level) { ftdi_serial_t *device = io; if (device == NULL) return DC_STATUS_INVALIDARGS; INFO (device->context, "RTS: value=%u", level); if (ftdi_setrts(device->ftdi_ctx, level)) { ERROR (device->context, "%s", ftdi_get_error_string(device->ftdi_ctx)); return DC_STATUS_IO; } return DC_STATUS_SUCCESS; } dc_status_t ftdi_open(dc_iostream_t **iostream, dc_context_t *context) { dc_status_t rc = DC_STATUS_SUCCESS; void *io = NULL; static const dc_custom_cbs_t callbacks = { .set_timeout = serial_ftdi_set_timeout, .set_break = serial_ftdi_set_break, .set_dtr = serial_ftdi_set_dtr, .set_rts = serial_ftdi_set_rts, .get_available = serial_ftdi_get_available, .configure = serial_ftdi_configure, .read = serial_ftdi_read, .write = serial_ftdi_write, .purge = serial_ftdi_purge, .sleep = serial_ftdi_sleep, .close = serial_ftdi_close, }; INFO(device->contxt, "%s", "in ftdi_open"); rc = serial_ftdi_open(&io, context); if (rc != DC_STATUS_SUCCESS) { INFO(device->contxt, "%s", "serial_ftdi_open() failed"); return rc; } INFO(device->contxt, "%s", "calling dc_custom_open())"); return dc_custom_open(iostream, context, DC_TRANSPORT_SERIAL, &callbacks, io); }
subsurface-for-dirk-master
core/serial_ftdi.c
// SPDX-License-Identifier: GPL-2.0 /* divesite.c */ #include "divesite.h" #include "dive.h" #include "subsurface-string.h" #include "divelist.h" #include "membuffer.h" #include "table.h" #include "sha1.h" #include <math.h> struct dive_site_table dive_site_table; int get_divesite_idx(const struct dive_site *ds, struct dive_site_table *ds_table) { int i; const struct dive_site *d; // tempting as it may be, don't die when called with ds=NULL if (ds) for_each_dive_site(i, d, ds_table) { if (d == ds) return i; } return -1; } // TODO: keep table sorted by UUID and do a binary search? struct dive_site *get_dive_site_by_uuid(uint32_t uuid, struct dive_site_table *ds_table) { int i; struct dive_site *ds; for_each_dive_site (i, ds, ds_table) if (ds->uuid == uuid) return get_dive_site(i, ds_table); return NULL; } /* there could be multiple sites of the same name - return the first one */ struct dive_site *get_dive_site_by_name(const char *name, struct dive_site_table *ds_table) { int i; struct dive_site *ds; for_each_dive_site (i, ds, ds_table) { if (same_string(ds->name, name)) return ds; } return NULL; } /* there could be multiple sites at the same GPS fix - return the first one */ struct dive_site *get_dive_site_by_gps(const location_t *loc, struct dive_site_table *ds_table) { int i; struct dive_site *ds; for_each_dive_site (i, ds, ds_table) { if (same_location(loc, &ds->location)) return ds; } return NULL; } /* to avoid a bug where we have two dive sites with different name and the same GPS coordinates * and first get the gps coordinates (reading a V2 file) and happen to get back "the other" name, * this function allows us to verify if a very specific name/GPS combination already exists */ struct dive_site *get_dive_site_by_gps_and_name(char *name, const location_t *loc, struct dive_site_table *ds_table) { int i; struct dive_site *ds; for_each_dive_site (i, ds, ds_table) { if (same_location(loc, &ds->location) && same_string(ds->name, name)) return ds; } return NULL; } // Calculate the distance in meters between two coordinates. unsigned int get_distance(const location_t *loc1, const location_t *loc2) { double lat1_r = udeg_to_radians(loc1->lat.udeg); double lat2_r = udeg_to_radians(loc2->lat.udeg); double lat_d_r = udeg_to_radians(loc2->lat.udeg - loc1->lat.udeg); double lon_d_r = udeg_to_radians(loc2->lon.udeg - loc1->lon.udeg); double a = sin(lat_d_r/2) * sin(lat_d_r/2) + cos(lat1_r) * cos(lat2_r) * sin(lon_d_r/2) * sin(lon_d_r/2); if (a < 0.0) a = 0.0; if (a > 1.0) a = 1.0; double c = 2 * atan2(sqrt(a), sqrt(1.0 - a)); // Earth radius in metres return lrint(6371000 * c); } /* find the closest one, no more than distance meters away - if more than one at same distance, pick the first */ struct dive_site *get_dive_site_by_gps_proximity(const location_t *loc, int distance, struct dive_site_table *ds_table) { int i; struct dive_site *ds, *res = NULL; unsigned int cur_distance, min_distance = distance; for_each_dive_site (i, ds, ds_table) { if (dive_site_has_gps_location(ds) && (cur_distance = get_distance(&ds->location, loc)) < min_distance) { min_distance = cur_distance; res = ds; } } return res; } int register_dive_site(struct dive_site *ds) { return add_dive_site_to_table(ds, &dive_site_table); } static int compare_sites(const struct dive_site *a, const struct dive_site *b) { return a->uuid > b->uuid ? 1 : a->uuid == b->uuid ? 0 : -1; } static int site_less_than(const struct dive_site *a, const struct dive_site *b) { return compare_sites(a, b) < 0; } static MAKE_GROW_TABLE(dive_site_table, struct dive_site *, dive_sites) static MAKE_GET_INSERTION_INDEX(dive_site_table, struct dive_site *, dive_sites, site_less_than) static MAKE_ADD_TO(dive_site_table, struct dive_site *, dive_sites) static MAKE_REMOVE_FROM(dive_site_table, dive_sites) static MAKE_GET_IDX(dive_site_table, struct dive_site *, dive_sites) MAKE_SORT(dive_site_table, struct dive_site *, dive_sites, compare_sites) static MAKE_REMOVE(dive_site_table, struct dive_site *, dive_site) MAKE_CLEAR_TABLE(dive_site_table, dive_sites, dive_site) MAKE_MOVE_TABLE(dive_site_table, dive_sites) int add_dive_site_to_table(struct dive_site *ds, struct dive_site_table *ds_table) { /* If the site doesn't yet have an UUID, create a new one. * Make this deterministic for testing. */ if (!ds->uuid) { SHA_CTX ctx; uint32_t csum[5]; SHA1_Init(&ctx); if (ds->name) SHA1_Update(&ctx, ds->name, strlen(ds->name)); if (ds->description) SHA1_Update(&ctx, ds->description, strlen(ds->description)); if (ds->notes) SHA1_Update(&ctx, ds->notes, strlen(ds->notes)); SHA1_Final((unsigned char *)csum, &ctx); ds->uuid = csum[0]; } /* Take care to never have the same uuid twice. This could happen on * reimport of a log where the dive sites have diverged */ while (ds->uuid == 0 || get_dive_site_by_uuid(ds->uuid, ds_table) != NULL) ++ds->uuid; int idx = dive_site_table_get_insertion_index(ds_table, ds); add_to_dive_site_table(ds_table, idx, ds); return idx; } struct dive_site *alloc_dive_site() { struct dive_site *ds; ds = calloc(1, sizeof(*ds)); if (!ds) exit(1); return ds; } struct dive_site *alloc_dive_site_with_name(const char *name) { struct dive_site *ds = alloc_dive_site(); ds->name = copy_string(name); return ds; } struct dive_site *alloc_dive_site_with_gps(const char *name, const location_t *loc) { struct dive_site *ds = alloc_dive_site_with_name(name); ds->location = *loc; return ds; } /* when parsing, dive sites are identified by uuid */ struct dive_site *alloc_or_get_dive_site(uint32_t uuid, struct dive_site_table *ds_table) { struct dive_site *ds; if (uuid && (ds = get_dive_site_by_uuid(uuid, ds_table)) != NULL) return ds; ds = alloc_dive_site(); ds->uuid = uuid; add_dive_site_to_table(ds, ds_table); return ds; } int nr_of_dives_at_dive_site(struct dive_site *ds) { return ds->dives.nr; } bool is_dive_site_selected(struct dive_site *ds) { int i; for (i = 0; i < ds->dives.nr; i++) { if (ds->dives.dives[i]->selected) return true; } return false; } void free_dive_site(struct dive_site *ds) { if (ds) { free(ds->name); free(ds->notes); free(ds->description); free(ds->dives.dives); free_taxonomy(&ds->taxonomy); free(ds); } } int unregister_dive_site(struct dive_site *ds) { return remove_dive_site(ds, &dive_site_table); } void delete_dive_site(struct dive_site *ds, struct dive_site_table *ds_table) { if (!ds) return; remove_dive_site(ds, ds_table); free_dive_site(ds); } /* allocate a new site and add it to the table */ struct dive_site *create_dive_site(const char *name, struct dive_site_table *ds_table) { struct dive_site *ds = alloc_dive_site_with_name(name); add_dive_site_to_table(ds, ds_table); return ds; } /* same as before, but with GPS data */ struct dive_site *create_dive_site_with_gps(const char *name, const location_t *loc, struct dive_site_table *ds_table) { struct dive_site *ds = alloc_dive_site_with_gps(name, loc); add_dive_site_to_table(ds, ds_table); return ds; } /* if all fields are empty, the dive site is pointless */ bool dive_site_is_empty(struct dive_site *ds) { return !ds || (empty_string(ds->name) && empty_string(ds->description) && empty_string(ds->notes) && !has_location(&ds->location)); } void copy_dive_site(struct dive_site *orig, struct dive_site *copy) { free(copy->name); free(copy->notes); free(copy->description); copy->location = orig->location; copy->name = copy_string(orig->name); copy->notes = copy_string(orig->notes); copy->description = copy_string(orig->description); copy_taxonomy(&orig->taxonomy, &copy->taxonomy); } static void merge_string(char **a, char **b) { char *s1 = *a, *s2 = *b; if (!s2) return; if (same_string(s1, s2)) return; if (!s1) { *a = strdup(s2); return; } *a = format_string("(%s) or (%s)", s1, s2); free(s1); } /* Used to check on import if two dive sites are equivalent. * Since currently no merging is performed, be very conservative * and only consider equal dive sites that are exactly the same. * Taxonomy is not compared, as no taxonomy is generated on * import. */ static bool same_dive_site(const struct dive_site *a, const struct dive_site *b) { return same_string(a->name, b->name) && same_location(&a->location, &b->location) && same_string(a->description, b->description) && same_string(a->notes, b->notes); } struct dive_site *get_same_dive_site(const struct dive_site *site) { int i; struct dive_site *ds; for_each_dive_site (i, ds, &dive_site_table) if (same_dive_site(ds, site)) return ds; return NULL; } void merge_dive_site(struct dive_site *a, struct dive_site *b) { if (!has_location(&a->location)) a->location = b->location; merge_string(&a->name, &b->name); merge_string(&a->notes, &b->notes); merge_string(&a->description, &b->description); if (!a->taxonomy.category) { a->taxonomy = b->taxonomy; memset(&b->taxonomy, 0, sizeof(b->taxonomy)); } } struct dive_site *find_or_create_dive_site_with_name(const char *name, struct dive_site_table *ds_table) { int i; struct dive_site *ds; for_each_dive_site(i,ds, ds_table) { if (same_string(name, ds->name)) break; } if (ds) return ds; return create_dive_site(name, ds_table); } void purge_empty_dive_sites(struct dive_site_table *ds_table) { int i, j; struct dive *d; struct dive_site *ds; for (i = 0; i < ds_table->nr; i++) { ds = get_dive_site(i, ds_table); if (!dive_site_is_empty(ds)) continue; for_each_dive(j, d) { if (d->dive_site == ds) unregister_dive_from_dive_site(d); } } } void add_dive_to_dive_site(struct dive *d, struct dive_site *ds) { int idx; if (!d) { fprintf(stderr, "Warning: add_dive_to_dive_site called with NULL dive\n"); return; } if (!ds) { fprintf(stderr, "Warning: add_dive_to_dive_site called with NULL dive site\n"); return; } if (d->dive_site == ds) return; if (d->dive_site) { fprintf(stderr, "Warning: adding dive that already belongs to a dive site to a different site\n"); unregister_dive_from_dive_site(d); } idx = dive_table_get_insertion_index(&ds->dives, d); add_to_dive_table(&ds->dives, idx, d); d->dive_site = ds; } struct dive_site *unregister_dive_from_dive_site(struct dive *d) { struct dive_site *ds = d->dive_site; if (!ds) return NULL; remove_dive(d, &ds->dives); d->dive_site = NULL; return ds; }
subsurface-for-dirk-master
core/divesite.c
// SPDX-License-Identifier: GPL-2.0 #include <stdlib.h> #include <stdio.h> #include <string.h> #include "errorhelper.h" #include "ssrf.h" #include "subsurface-string.h" #include "gettext.h" #include "dive.h" #include "divelist.h" #include "extradata.h" #include "file.h" #include "libdivecomputer.h" /* * Fills a device_data_t structure with known dc data and a descriptor. */ static int ostc_prepare_data(int data_model, dc_family_t dc_fam, device_data_t *dev_data) { dc_descriptor_t *data_descriptor; dev_data->device = NULL; dev_data->context = NULL; data_descriptor = get_descriptor(dc_fam, data_model); if (data_descriptor) { dev_data->descriptor = data_descriptor; dev_data->vendor = copy_string(dc_descriptor_get_vendor(data_descriptor)); dev_data->model = copy_string(dc_descriptor_get_product(data_descriptor)); } else { return 0; } return 1; } /* * OSTCTools stores the raw dive data in heavily padded files, one dive * each file. So it's not necessary to iterate once and again on a parsing * function. Actually there's only one kind of archive for every DC model. */ void ostctools_import(const char *file, struct dive_table *divetable, struct trip_table *trips, struct dive_site_table *sites) { UNUSED(trips); UNUSED(sites); FILE *archive; device_data_t *devdata = calloc(1, sizeof(device_data_t)); dc_family_t dc_fam; unsigned char *buffer = calloc(65536, 1); unsigned char uc_tmp[2]; char *tmp; struct dive *ostcdive = alloc_dive(); dc_status_t rc = 0; int model, ret, i = 0, c; unsigned int serial; struct extra_data *ptr; const char *failed_to_read_msg = translate("gettextFromC", "Failed to read '%s'"); // Open the archive if ((archive = subsurface_fopen(file, "rb")) == NULL) { report_error(failed_to_read_msg, file); free_dive(ostcdive); goto out; } // Read dive number from the log if (fseek(archive, 258, 0) == -1) { report_error(failed_to_read_msg, file); free_dive(ostcdive); goto close_out; } if (fread(uc_tmp, 1, 2, archive) != 2) { report_error(failed_to_read_msg, file); free_dive(ostcdive); goto close_out; } ostcdive->number = uc_tmp[0] + (uc_tmp[1] << 8); // Read device's serial number if (fseek(archive, 265, 0) == -1) { report_error(failed_to_read_msg, file); free_dive(ostcdive); goto close_out; } if (fread(uc_tmp, 1, 2, archive) != 2) { report_error(failed_to_read_msg, file); free_dive(ostcdive); goto close_out; } serial = uc_tmp[0] + (uc_tmp[1] << 8); // Read dive's raw data, header + profile if (fseek(archive, 456, 0) == -1) { report_error(failed_to_read_msg, file); free_dive(ostcdive); goto close_out; } while ((c = getc(archive)) != EOF) { buffer[i] = c; if (buffer[i] == 0xFD && buffer[i - 1] == 0xFD) break; i++; } if (ferror(archive)) { report_error(failed_to_read_msg, file); free_dive(ostcdive); goto close_out; } // Try to determine the dc family based on the header type if (buffer[2] == 0x20 || buffer[2] == 0x21) { dc_fam = DC_FAMILY_HW_OSTC; } else { switch (buffer[8]) { case 0x22: dc_fam = DC_FAMILY_HW_FROG; break; case 0x23: case 0x24: dc_fam = DC_FAMILY_HW_OSTC3; break; default: report_error(translate("gettextFromC", "Unknown DC in dive %d"), ostcdive->number); free_dive(ostcdive); goto close_out; } } // Try to determine the model based on serial number switch (dc_fam) { case DC_FAMILY_HW_OSTC: if (serial > 7000) model = 3; //2C else if (serial > 2048) model = 2; //2N else if (serial > 300) model = 1; //MK2 else model = 0; //OSTC break; case DC_FAMILY_HW_FROG: model = 0; break; default: if (serial > 10000) model = 0x12; //Sport else model = 0x0A; //OSTC3 } // Prepare data to pass to libdivecomputer. ret = ostc_prepare_data(model, dc_fam, devdata); if (ret == 0) { report_error(translate("gettextFromC", "Unknown DC in dive %d"), ostcdive->number); free_dive(ostcdive); goto close_out; } tmp = calloc(strlen(devdata->vendor) + strlen(devdata->model) + 28, 1); sprintf(tmp, "%s %s (Imported from OSTCTools)", devdata->vendor, devdata->model); ostcdive->dc.model = copy_string(tmp); free(tmp); // Parse the dive data rc = libdc_buffer_parser(ostcdive, devdata, buffer, i + 1); if (rc != DC_STATUS_SUCCESS) report_error(translate("gettextFromC", "Error - %s - parsing dive %d"), errmsg(rc), ostcdive->number); // Serial number is not part of the header nor the profile, so libdc won't // catch it. If Serial is part of the extra_data, and set to zero, remove // it from the list and add again. tmp = calloc(12, 1); sprintf(tmp, "%d", serial); ostcdive->dc.serial = copy_string(tmp); free(tmp); if (ostcdive->dc.extra_data) { ptr = ostcdive->dc.extra_data; while (strcmp(ptr->key, "Serial")) ptr = ptr->next; if (!strcmp(ptr->value, "0")) { add_extra_data(&ostcdive->dc, "Serial", ostcdive->dc.serial); *ptr = *(ptr)->next; } } else { add_extra_data(&ostcdive->dc, "Serial", ostcdive->dc.serial); } record_dive_to_table(ostcdive, divetable); sort_dive_table(divetable); close_out: fclose(archive); out: free(devdata); free(buffer); }
subsurface-for-dirk-master
core/ostctools.c
// SPDX-License-Identifier: GPL-2.0 #ifdef __clang__ // Clang has a bug on zero-initialization of C structs. #pragma clang diagnostic ignored "-Wmissing-field-initializers" #endif /* equipment.c */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdarg.h> #include <time.h> #include <limits.h> #include "equipment.h" #include "gettext.h" #include "dive.h" #include "divelist.h" #include "pref.h" #include "subsurface-string.h" #include "table.h" /* Warning: this has strange semantics for C-code! Not the weightsystem object * is freed, but the data it references. The object itself is passed in by value. * This is due to the fact how the table macros work. */ void free_weightsystem(weightsystem_t ws) { free((void *)ws.description); ws.description = NULL; } void free_cylinder(cylinder_t c) { free((void *)c.type.description); c.type.description = NULL; } void copy_weights(const struct weightsystem_table *s, struct weightsystem_table *d) { clear_weightsystem_table(d); for (int i = 0; i < s->nr; i++) add_cloned_weightsystem(d, s->weightsystems[i]); } void copy_cylinders(const struct cylinder_table *s, struct cylinder_table *d) { int i; clear_cylinder_table(d); for (i = 0; i < s->nr; i++) add_cloned_cylinder(d, s->cylinders[i]); } static void free_tank_info(struct tank_info info) { free((void *)info.name); } /* weightsystem table functions */ //static MAKE_GET_IDX(weightsystem_table, weightsystem_t, weightsystems) static MAKE_GROW_TABLE(weightsystem_table, weightsystem_t, weightsystems) //static MAKE_GET_INSERTION_INDEX(weightsystem_table, weightsystem_t, weightsystems, weightsystem_less_than) MAKE_ADD_TO(weightsystem_table, weightsystem_t, weightsystems) static MAKE_REMOVE_FROM(weightsystem_table, weightsystems) //MAKE_SORT(weightsystem_table, weightsystem_t, weightsystems, comp_weightsystems) //MAKE_REMOVE(weightsystem_table, weightsystem_t, weightsystem) MAKE_CLEAR_TABLE(weightsystem_table, weightsystems, weightsystem) /* cylinder table functions */ //static MAKE_GET_IDX(cylinder_table, cylinder_t, cylinders) static MAKE_GROW_TABLE(cylinder_table, cylinder_t, cylinders) //static MAKE_GET_INSERTION_INDEX(cylinder_table, cylinder_t, cylinders, cylinder_less_than) static MAKE_ADD_TO(cylinder_table, cylinder_t, cylinders) static MAKE_REMOVE_FROM(cylinder_table, cylinders) //MAKE_SORT(cylinder_table, cylinder_t, cylinders, comp_cylinders) //MAKE_REMOVE(cylinder_table, cylinder_t, cylinder) MAKE_CLEAR_TABLE(cylinder_table, cylinders, cylinder) /* tank_info table functions */ static MAKE_GROW_TABLE(tank_info_table, tank_info_t, infos) static MAKE_ADD_TO(tank_info_table, tank_info_t, infos) //static MAKE_REMOVE_FROM(tank_info_table, infos) MAKE_CLEAR_TABLE(tank_info_table, infos, tank_info) const char *cylinderuse_text[NUM_GAS_USE] = { QT_TRANSLATE_NOOP("gettextFromC", "OC-gas"), QT_TRANSLATE_NOOP("gettextFromC", "diluent"), QT_TRANSLATE_NOOP("gettextFromC", "oxygen"), QT_TRANSLATE_NOOP("gettextFromC", "not used") }; int cylinderuse_from_text(const char *text) { for (enum cylinderuse i = 0; i < NUM_GAS_USE; i++) { if (same_string(text, cylinderuse_text[i]) || same_string(text, translate("gettextFromC", cylinderuse_text[i]))) return i; } return -1; } /* Add a metric or an imperial tank info structure. Copies the passed-in string. */ void add_tank_info_metric(struct tank_info_table *table, const char *name, int ml, int bar) { struct tank_info info = { strdup(name), .ml = ml, .bar = bar }; add_to_tank_info_table(table, table->nr, info); } void add_tank_info_imperial(struct tank_info_table *table, const char *name, int cuft, int psi) { struct tank_info info = { strdup(name), .cuft = cuft, .psi = psi }; add_to_tank_info_table(table, table->nr, info); } /* placeholders for a few functions that we need to redesign for the Qt UI */ void add_cylinder_description(const cylinder_type_t *type) { const char *desc = type->description; if (empty_string(desc)) return; for (int i = 0; i < tank_info_table.nr; i++) { if (strcmp(tank_info_table.infos[i].name, desc) == 0) return; } add_tank_info_metric(&tank_info_table, desc, type->size.mliter, type->workingpressure.mbar / 1000); } void add_weightsystem_description(const weightsystem_t *weightsystem) { const char *desc; int i; desc = weightsystem->description; if (!desc) return; for (i = 0; i < MAX_WS_INFO && ws_info[i].name != NULL; i++) { if (strcmp(ws_info[i].name, desc) == 0) { ws_info[i].grams = weightsystem->weight.grams; return; } } if (i < MAX_WS_INFO) { // FIXME: leaked on exit ws_info[i].name = strdup(desc); ws_info[i].grams = weightsystem->weight.grams; } } weightsystem_t clone_weightsystem(weightsystem_t ws) { weightsystem_t res = { ws.weight, copy_string(ws.description), ws.auto_filled }; return res; } /* Add a clone of a weightsystem to the end of a weightsystem table. * Cloned means that the description-string is copied. */ void add_cloned_weightsystem(struct weightsystem_table *t, weightsystem_t ws) { add_to_weightsystem_table(t, t->nr, clone_weightsystem(ws)); } /* Add a clone of a weightsystem to the end of a weightsystem table. * Cloned means that the description-string is copied. */ void add_cloned_weightsystem_at(struct weightsystem_table *t, weightsystem_t ws) { add_to_weightsystem_table(t, t->nr, clone_weightsystem(ws)); } cylinder_t clone_cylinder(cylinder_t cyl) { cylinder_t res = cyl; res.type.description = copy_string(res.type.description); return res; } void add_cylinder(struct cylinder_table *t, int idx, cylinder_t cyl) { add_to_cylinder_table(t, idx, cyl); /* FIXME: This is a horrible hack: we make sure that at the end of * every single cylinder table there is an empty cylinder that can * be used by the planner as "surface air" cylinder. Fix this. */ add_to_cylinder_table(t, t->nr, empty_cylinder); t->nr--; t->cylinders[t->nr].cylinder_use = NOT_USED; } /* Add a clone of a cylinder to the end of a cylinder table. * Cloned means that the description-string is copied. */ void add_cloned_cylinder(struct cylinder_table *t, cylinder_t cyl) { add_cylinder(t, t->nr, clone_cylinder(cyl)); } bool same_weightsystem(weightsystem_t w1, weightsystem_t w2) { return w1.weight.grams == w2.weight.grams && same_string(w1.description, w2.description); } void get_gas_string(struct gasmix gasmix, char *text, int len) { if (gasmix_is_air(gasmix)) snprintf(text, len, "%s", translate("gettextFromC", "air")); else if (get_he(gasmix) == 0 && get_o2(gasmix) < 1000) snprintf(text, len, translate("gettextFromC", "EAN%d"), (get_o2(gasmix) + 5) / 10); else if (get_he(gasmix) == 0 && get_o2(gasmix) == 1000) snprintf(text, len, "%s", translate("gettextFromC", "oxygen")); else snprintf(text, len, "(%d/%d)", (get_o2(gasmix) + 5) / 10, (get_he(gasmix) + 5) / 10); } /* Returns a static char buffer - only good for immediate use by printf etc */ const char *gasname(struct gasmix gasmix) { static char gas[64]; get_gas_string(gasmix, gas, sizeof(gas)); return gas; } int gas_volume(const cylinder_t *cyl, pressure_t p) { double bar = p.mbar / 1000.0; double z_factor = gas_compressibility_factor(cyl->gasmix, bar); return lrint(cyl->type.size.mliter * bar_to_atm(bar) / z_factor); } int find_best_gasmix_match(struct gasmix mix, const struct cylinder_table *cylinders) { int i; int best = -1, score = INT_MAX; for (i = 0; i < cylinders->nr; i++) { const cylinder_t *match; int distance; match = cylinders->cylinders + i; distance = gasmix_distance(mix, match->gasmix); if (distance >= score) continue; best = i; score = distance; } return best; } /* * We hardcode the most common standard cylinders, * we should pick up any other names from the dive * logs directly. */ static void add_default_tank_infos(struct tank_info_table *table) { /* Size-only metric cylinders */ add_tank_info_metric(table, "10.0ℓ", 10000, 0); add_tank_info_metric(table, "11.1ℓ", 11100, 0); /* Most common AL cylinders */ add_tank_info_imperial(table, "AL40", 40, 3000); add_tank_info_imperial(table, "AL50", 50, 3000); add_tank_info_imperial(table, "AL63", 63, 3000); add_tank_info_imperial(table, "AL72", 72, 3000); add_tank_info_imperial(table, "AL80", 80, 3000); add_tank_info_imperial(table, "AL100", 100, 3300); /* Metric AL cylinders */ add_tank_info_metric(table, "ALU7", 7000, 200); /* Somewhat common LP steel cylinders */ add_tank_info_imperial(table, "LP85", 85, 2640); add_tank_info_imperial(table, "LP95", 95, 2640); add_tank_info_imperial(table, "LP108", 108, 2640); add_tank_info_imperial(table, "LP121", 121, 2640); /* Somewhat common HP steel cylinders */ add_tank_info_imperial(table, "HP65", 65, 3442); add_tank_info_imperial(table, "HP80", 80, 3442); add_tank_info_imperial(table, "HP100", 100, 3442); add_tank_info_imperial(table, "HP117", 117, 3442); add_tank_info_imperial(table, "HP119", 119, 3442); add_tank_info_imperial(table, "HP130", 130, 3442); /* Common European steel cylinders */ add_tank_info_metric(table, "3ℓ 232 bar", 3000, 232); add_tank_info_metric(table, "3ℓ 300 bar", 3000, 300); add_tank_info_metric(table, "10ℓ 200 bar", 10000, 200); add_tank_info_metric(table, "10ℓ 232 bar", 10000, 232); add_tank_info_metric(table, "10ℓ 300 bar", 10000, 300); add_tank_info_metric(table, "12ℓ 200 bar", 12000, 200); add_tank_info_metric(table, "12ℓ 232 bar", 12000, 232); add_tank_info_metric(table, "12ℓ 300 bar", 12000, 300); add_tank_info_metric(table, "15ℓ 200 bar", 15000, 200); add_tank_info_metric(table, "15ℓ 232 bar", 15000, 232); add_tank_info_metric(table, "D7 300 bar", 14000, 300); add_tank_info_metric(table, "D8.5 232 bar", 17000, 232); add_tank_info_metric(table, "D12 232 bar", 24000, 232); add_tank_info_metric(table, "D13 232 bar", 26000, 232); add_tank_info_metric(table, "D15 232 bar", 30000, 232); add_tank_info_metric(table, "D16 232 bar", 32000, 232); add_tank_info_metric(table, "D18 232 bar", 36000, 232); add_tank_info_metric(table, "D20 232 bar", 40000, 232); } struct tank_info_table tank_info_table; void reset_tank_info_table(struct tank_info_table *table) { clear_tank_info_table(table); if (prefs.display_default_tank_infos) add_default_tank_infos(table); /* Add cylinders from dive list */ for (int i = 0; i < dive_table.nr; ++i) { const struct dive *dive = dive_table.dives[i]; for (int j = 0; j < dive->cylinders.nr; j++) { const cylinder_t *cyl = get_cylinder(dive, j); add_cylinder_description(&cyl->type); } } } /* * We hardcode the most common weight system types * This is a bit odd as the weight system types don't usually encode weight */ struct ws_info_t ws_info[MAX_WS_INFO] = { { QT_TRANSLATE_NOOP("gettextFromC", "integrated"), 0 }, { QT_TRANSLATE_NOOP("gettextFromC", "belt"), 0 }, { QT_TRANSLATE_NOOP("gettextFromC", "ankle"), 0 }, { QT_TRANSLATE_NOOP("gettextFromC", "backplate"), 0 }, { QT_TRANSLATE_NOOP("gettextFromC", "clip-on"), 0 }, }; void remove_cylinder(struct dive *dive, int idx) { remove_from_cylinder_table(&dive->cylinders, idx); } void remove_weightsystem(struct dive *dive, int idx) { remove_from_weightsystem_table(&dive->weightsystems, idx); } // ws is cloned. void set_weightsystem(struct dive *dive, int idx, weightsystem_t ws) { if (idx < 0 || idx >= dive->weightsystems.nr) return; free_weightsystem(dive->weightsystems.weightsystems[idx]); dive->weightsystems.weightsystems[idx] = clone_weightsystem(ws); } /* when planning a dive we need to make sure that all cylinders have a sane depth assigned * and if we are tracking gas consumption the pressures need to be reset to start = end = workingpressure */ void reset_cylinders(struct dive *dive, bool track_gas) { pressure_t decopo2 = {.mbar = prefs.decopo2}; for (int i = 0; i < dive->cylinders.nr; i++) { cylinder_t *cyl = get_cylinder(dive, i); if (cyl->depth.mm == 0) /* if the gas doesn't give a mod, calculate based on prefs */ cyl->depth = gas_mod(cyl->gasmix, decopo2, dive, M_OR_FT(3,10)); if (track_gas) cyl->start.mbar = cyl->end.mbar = cyl->type.workingpressure.mbar; cyl->gas_used.mliter = 0; cyl->deco_gas_used.mliter = 0; } } static void copy_cylinder_type(const cylinder_t *s, cylinder_t *d) { free_cylinder(*d); d->type = s->type; d->type.description = s->type.description ? strdup(s->type.description) : NULL; d->gasmix = s->gasmix; d->depth = s->depth; d->cylinder_use = s->cylinder_use; d->manually_added = true; } /* copy the equipment data part of the cylinders but keep pressures */ void copy_cylinder_types(const struct dive *s, struct dive *d) { int i; if (!s || !d) return; for (i = 0; i < s->cylinders.nr && i < d->cylinders.nr; i++) copy_cylinder_type(get_cylinder(s, i), get_cylinder(d, i)); for ( ; i < s->cylinders.nr; i++) add_cloned_cylinder(&d->cylinders, *get_cylinder(s, i)); } cylinder_t *add_empty_cylinder(struct cylinder_table *t) { cylinder_t cyl = empty_cylinder; cyl.type.description = strdup(""); add_cylinder(t, t->nr, cyl); return &t->cylinders[t->nr - 1]; } /* access to cylinders is controlled by two functions: * - get_cylinder() returns the cylinder of a dive and supposes that * the cylinder with the given index exists. If it doesn't, an error * message is printed and NULL returned. * - get_or_create_cylinder() creates an empty cylinder if it doesn't exist. * Multiple cylinders might be created if the index is bigger than the * number of existing cylinders */ cylinder_t *get_cylinder(const struct dive *d, int idx) { /* FIXME: The planner uses a dummy cylinder one past the official number of cylinders * in the table to mark no-cylinder surface interavals. This is horrendous. Fix ASAP. */ // if (idx < 0 || idx >= d->cylinders.nr) { if (idx < 0 || idx >= d->cylinders.nr + 1 || idx >= d->cylinders.allocated) { fprintf(stderr, "Warning: accessing invalid cylinder %d (%d existing)\n", idx, d->cylinders.nr); return NULL; } return &d->cylinders.cylinders[idx]; } cylinder_t *get_or_create_cylinder(struct dive *d, int idx) { if (idx < 0) { fprintf(stderr, "Warning: accessing invalid cylinder %d\n", idx); return NULL; } while (idx >= d->cylinders.nr) add_empty_cylinder(&d->cylinders); return &d->cylinders.cylinders[idx]; } /* if a default cylinder is set, use that */ void fill_default_cylinder(const struct dive *dive, cylinder_t *cyl) { const char *cyl_name = prefs.default_cylinder; pressure_t pO2 = {.mbar = lrint(prefs.modpO2 * 1000.0)}; if (!cyl_name) return; for (int i = 0; i < tank_info_table.nr; ++i) { struct tank_info *ti = &tank_info_table.infos[i]; if (strcmp(ti->name, cyl_name) == 0) { cyl->type.description = strdup(ti->name); if (ti->ml) { cyl->type.size.mliter = ti->ml; cyl->type.workingpressure.mbar = ti->bar * 1000; } else { cyl->type.workingpressure.mbar = psi_to_mbar(ti->psi); if (ti->psi) cyl->type.size.mliter = lrint(cuft_to_l(ti->cuft) * 1000 / bar_to_atm(psi_to_bar(ti->psi))); } // MOD of air cyl->depth = gas_mod(cyl->gasmix, pO2, dive, 1); return; } } } cylinder_t create_new_cylinder(const struct dive *d) { cylinder_t cyl = empty_cylinder; fill_default_cylinder(d, &cyl); cyl.start = cyl.type.workingpressure; cyl.manually_added = true; cyl.cylinder_use = OC_GAS; return cyl; } static bool show_cylinder(const struct dive *d, int i) { if (is_cylinder_used(d, i)) return true; const cylinder_t *cyl = &d->cylinders.cylinders[i]; if (cyl->start.mbar || cyl->sample_start.mbar || cyl->end.mbar || cyl->sample_end.mbar) return true; if (cyl->manually_added) return true; /* * The cylinder has some data, but none of it is very interesting, * it has no pressures and no gas switches. Do we want to show it? */ return false; } /* The unused cylinders at the end of the cylinder list are hidden. */ int first_hidden_cylinder(const struct dive *d) { int res = d->cylinders.nr; while (res > 0 && !show_cylinder(d, res - 1)) --res; return res; } #ifdef DEBUG_CYL void dump_cylinders(struct dive *dive, bool verbose) { printf("Cylinder list:\n"); for (int i = 0; i < dive->cylinders; i++) { cylinder_t *cyl = get_cylinder(dive, i); printf("%02d: Type %s, %3.1fl, %3.0fbar\n", i, cyl->type.description, cyl->type.size.mliter / 1000.0, cyl->type.workingpressure.mbar / 1000.0); printf(" Gasmix O2 %2.0f%% He %2.0f%%\n", cyl->gasmix.o2.permille / 10.0, cyl->gasmix.he.permille / 10.0); printf(" Pressure Start %3.0fbar End %3.0fbar Sample start %3.0fbar Sample end %3.0fbar\n", cyl->start.mbar / 1000.0, cyl->end.mbar / 1000.0, cyl->sample_start.mbar / 1000.0, cyl->sample_end.mbar / 1000.0); if (verbose) { printf(" Depth %3.0fm\n", cyl->depth.mm / 1000.0); printf(" Added %s\n", (cyl->manually_added ? "manually" : "")); printf(" Gas used Bottom %5.0fl Deco %5.0fl\n", cyl->gas_used.mliter / 1000.0, cyl->deco_gas_used.mliter / 1000.0); printf(" Use %d\n", cyl->cylinder_use); printf(" Bestmix %s %s\n", (cyl->bestmix_o2 ? "O2" : " "), (cyl->bestmix_he ? "He" : " ")); } } } #endif
subsurface-for-dirk-master
core/equipment.c
// SPDX-License-Identifier: GPL-2.0 #include "ssrf.h" #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include "gettext.h" #include <zip.h> #include <time.h> #include "dive.h" #include "subsurface-string.h" #include "errorhelper.h" #include "file.h" #include "git-access.h" #include "qthelper.h" #include "import-csv.h" #include "parse.h" /* For SAMPLE_* */ #include <libdivecomputer/parser.h> /* to check XSLT version number */ #include <libxslt/xsltconfig.h> /* Crazy windows sh*t */ #ifndef O_BINARY #define O_BINARY 0 #endif int readfile(const char *filename, struct memblock *mem) { int ret, fd; struct stat st; char *buf; mem->buffer = NULL; mem->size = 0; fd = subsurface_open(filename, O_RDONLY | O_BINARY, 0); if (fd < 0) return fd; ret = fstat(fd, &st); if (ret < 0) goto out; ret = -EINVAL; if (!S_ISREG(st.st_mode)) goto out; ret = 0; if (!st.st_size) goto out; buf = malloc(st.st_size + 1); ret = -1; errno = ENOMEM; if (!buf) goto out; mem->buffer = buf; mem->size = st.st_size; ret = read(fd, buf, mem->size); if (ret < 0) goto free; buf[ret] = 0; if (ret == (int)mem->size) // converting to int loses a bit but size will never be that big goto out; errno = EIO; ret = -1; free: free(mem->buffer); mem->buffer = NULL; mem->size = 0; out: close(fd); return ret; } static void zip_read(struct zip_file *file, const char *filename, struct dive_table *table, struct trip_table *trips, struct dive_site_table *sites, struct device_table *devices, struct filter_preset_table *filter_presets) { int size = 1024, n, read = 0; char *mem = malloc(size); while ((n = zip_fread(file, mem + read, size - read)) > 0) { read += n; size = read * 3 / 2; mem = realloc(mem, size); } mem[read] = 0; (void) parse_xml_buffer(filename, mem, read, table, trips, sites, devices, filter_presets, NULL); free(mem); } int try_to_open_zip(const char *filename, struct dive_table *table, struct trip_table *trips, struct dive_site_table *sites, struct device_table *devices, struct filter_preset_table *filter_presets) { int success = 0; /* Grr. libzip needs to re-open the file, it can't take a buffer */ struct zip *zip = subsurface_zip_open_readonly(filename, ZIP_CHECKCONS, NULL); if (zip) { int index; for (index = 0;; index++) { struct zip_file *file = zip_fopen_index(zip, index, 0); if (!file) break; /* skip parsing the divelogs.de pictures */ if (strstr(zip_get_name(zip, index, 0), "pictures/")) continue; zip_read(file, filename, table, trips, sites, devices, filter_presets); zip_fclose(file); success++; } subsurface_zip_close(zip); if (!success) return report_error(translate("gettextFromC", "No dives in the input file '%s'"), filename); } return success; } static int db_test_func(void *param, int columns, char **data, char **column) { UNUSED(param); UNUSED(columns); UNUSED(column); return *data[0] == '0'; } static int try_to_open_db(const char *filename, struct memblock *mem, struct dive_table *table, struct trip_table *trips, struct dive_site_table *sites, struct device_table *devices) { sqlite3 *handle; char dm4_test[] = "select count(*) from sqlite_master where type='table' and name='Dive' and sql like '%ProfileBlob%'"; char dm5_test[] = "select count(*) from sqlite_master where type='table' and name='Dive' and sql like '%SampleBlob%'"; char shearwater_test[] = "select count(*) from sqlite_master where type='table' and name='system' and sql like '%dbVersion%'"; char shearwater_cloud_test[] = "select count(*) from sqlite_master where type='table' and name='SyncV3MetadataDiveLog' and sql like '%CreatedDevice%'"; char cobalt_test[] = "select count(*) from sqlite_master where type='table' and name='TrackPoints' and sql like '%DepthPressure%'"; char divinglog_test[] = "select count(*) from sqlite_master where type='table' and name='DBInfo' and sql like '%PrgName%'"; char seacsync_test[] = "select count(*) from sqlite_master where type='table' and name='dive_data' and sql like '%ndl_tts_s%'"; int retval; retval = sqlite3_open(filename, &handle); if (retval) { fprintf(stderr, "Database connection failed '%s'.\n", filename); return 1; } /* Testing if DB schema resembles Suunto DM5 database format */ retval = sqlite3_exec(handle, dm5_test, &db_test_func, 0, NULL); if (!retval) { retval = parse_dm5_buffer(handle, filename, mem->buffer, mem->size, table, trips, sites, devices); sqlite3_close(handle); return retval; } /* Testing if DB schema resembles Suunto DM4 database format */ retval = sqlite3_exec(handle, dm4_test, &db_test_func, 0, NULL); if (!retval) { retval = parse_dm4_buffer(handle, filename, mem->buffer, mem->size, table, trips, sites, devices); sqlite3_close(handle); return retval; } /* Testing if DB schema resembles Shearwater database format */ retval = sqlite3_exec(handle, shearwater_test, &db_test_func, 0, NULL); if (!retval) { retval = parse_shearwater_buffer(handle, filename, mem->buffer, mem->size, table, trips, sites, devices); sqlite3_close(handle); return retval; } /* Testing if DB schema resembles Shearwater cloud database format */ retval = sqlite3_exec(handle, shearwater_cloud_test, &db_test_func, 0, NULL); if (!retval) { retval = parse_shearwater_cloud_buffer(handle, filename, mem->buffer, mem->size, table, trips, sites, devices); sqlite3_close(handle); return retval; } /* Testing if DB schema resembles Atomic Cobalt database format */ retval = sqlite3_exec(handle, cobalt_test, &db_test_func, 0, NULL); if (!retval) { retval = parse_cobalt_buffer(handle, filename, mem->buffer, mem->size, table, trips, sites, devices); sqlite3_close(handle); return retval; } /* Testing if DB schema resembles Divinglog database format */ retval = sqlite3_exec(handle, divinglog_test, &db_test_func, 0, NULL); if (!retval) { retval = parse_divinglog_buffer(handle, filename, mem->buffer, mem->size, table, trips, sites, devices); sqlite3_close(handle); return retval; } /* Testing if DB schema resembles Seac database format */ retval = sqlite3_exec(handle, seacsync_test, &db_test_func, 0, NULL); if (!retval) { retval = parse_seac_buffer(handle, filename, mem->buffer, mem->size, table, trips, sites, devices); sqlite3_close(handle); return retval; } sqlite3_close(handle); return retval; } /* * Cochran comma-separated values: depth in feet, temperature in F, pressure in psi. * * They start with eight comma-separated fields like: * * filename: {C:\Analyst4\can\T036785.can},{C:\Analyst4\can\K031892.can} * divenr: %d * datetime: {03Sep11 16:37:22},{15Dec11 18:27:02} * ??: 1 * serialnr??: {CCI134},{CCI207} * computer??: {GeminiII},{CommanderIII} * computer??: {GeminiII},{CommanderIII} * ??: 1 * * Followed by the data values (all comma-separated, all one long line). */ static int open_by_filename(const char *filename, const char *fmt, struct memblock *mem, struct dive_table *table, struct trip_table *trips, struct dive_site_table *sites, struct device_table *devices, struct filter_preset_table *filter_presets) { // hack to be able to provide a comment for the translated string static char *csv_warning = QT_TRANSLATE_NOOP3("gettextFromC", "Cannot open CSV file %s; please use Import log file dialog", "'Import log file' should be the same text as corresponding label in Import menu"); /* Suunto Dive Manager files: SDE, ZIP; divelogs.de files: DLD */ if (!strcasecmp(fmt, "SDE") || !strcasecmp(fmt, "ZIP") || !strcasecmp(fmt, "DLD")) return try_to_open_zip(filename, table, trips, sites, devices, filter_presets); /* CSV files */ if (!strcasecmp(fmt, "CSV")) return report_error(translate("gettextFromC", csv_warning), filename); /* Truly nasty intentionally obfuscated Cochran Anal software */ if (!strcasecmp(fmt, "CAN")) return try_to_open_cochran(filename, mem, table, trips, sites); /* Cochran export comma-separated-value files */ if (!strcasecmp(fmt, "DPT")) return try_to_open_csv(mem, CSV_DEPTH, table, trips, sites); if (!strcasecmp(fmt, "LVD")) return try_to_open_liquivision(filename, mem, table, trips, sites); if (!strcasecmp(fmt, "TMP")) return try_to_open_csv(mem, CSV_TEMP, table, trips, sites); if (!strcasecmp(fmt, "HP1")) return try_to_open_csv(mem, CSV_PRESSURE, table, trips, sites); return 0; } static int parse_file_buffer(const char *filename, struct memblock *mem, struct dive_table *table, struct trip_table *trips, struct dive_site_table *sites, struct device_table *devices, struct filter_preset_table *filter_presets) { int ret; char *fmt = strrchr(filename, '.'); if (fmt && (ret = open_by_filename(filename, fmt + 1, mem, table, trips, sites, devices, filter_presets)) != 0) return ret; if (!mem->size || !mem->buffer) return report_error("Out of memory parsing file %s\n", filename); return parse_xml_buffer(filename, mem->buffer, mem->size, table, trips, sites, devices, filter_presets, NULL); } bool remote_repo_uptodate(const char *filename, struct git_info *info) { char *current_sha = copy_string(saved_git_id); if (is_git_repository(filename, info) && open_git_repository(info)) { const char *sha = get_sha(info->repo, info->branch); if (!empty_string(sha) && same_string(sha, current_sha)) { fprintf(stderr, "already have loaded SHA %s - don't load again\n", sha); free(current_sha); return true; } } // Either the repository couldn't be opened, or the SHA couldn't // be found. free(current_sha); return false; } int parse_file(const char *filename, struct dive_table *table, struct trip_table *trips, struct dive_site_table *sites, struct device_table *devices, struct filter_preset_table *filter_presets) { struct git_info info; struct memblock mem; char *fmt; int ret; if (is_git_repository(filename, &info)) { if (!open_git_repository(&info)) { /* * Opening the cloud storage repository failed for some reason * give up here and don't send errors about git repositories */ if (info.is_subsurface_cloud) { cleanup_git_info(&info); return -1; } } ret = git_load_dives(&info, table, trips, sites, devices, filter_presets); cleanup_git_info(&info); return ret; } if ((ret = readfile(filename, &mem)) < 0) { /* we don't want to display an error if this was the default file */ if (same_string(filename, prefs.default_filename)) return 0; return report_error(translate("gettextFromC", "Failed to read '%s'"), filename); } else if (ret == 0) { return report_error(translate("gettextFromC", "Empty file '%s'"), filename); } fmt = strrchr(filename, '.'); if (fmt && (!strcasecmp(fmt + 1, "DB") || !strcasecmp(fmt + 1, "BAK") || !strcasecmp(fmt + 1, "SQL"))) { if (!try_to_open_db(filename, &mem, table, trips, sites, devices)) { free(mem.buffer); return 0; } } /* Divesoft Freedom */ if (fmt && (!strcasecmp(fmt + 1, "DLF"))) { ret = parse_dlf_buffer(mem.buffer, mem.size, table, trips, sites, devices); free(mem.buffer); return ret; } /* DataTrak/Wlog */ if (fmt && !strcasecmp(fmt + 1, "LOG")) { struct memblock wl_mem; const char *t = strrchr(filename, '.'); char *wl_name = memcpy(calloc(t - filename + 1, 1), filename, t - filename); wl_name = realloc(wl_name, strlen(wl_name) + 5); wl_name = strcat(wl_name, ".add"); if((ret = readfile(wl_name, &wl_mem)) < 0) { fprintf(stderr, "No file %s found. No WLog extensions.\n", wl_name); ret = datatrak_import(&mem, NULL, table, trips, sites, devices); } else { ret = datatrak_import(&mem, &wl_mem, table, trips, sites, devices); free(wl_mem.buffer); } free(mem.buffer); free(wl_name); return ret; } /* OSTCtools */ if (fmt && (!strcasecmp(fmt + 1, "DIVE"))) { free(mem.buffer); ostctools_import(filename, table, trips, sites); return 0; } ret = parse_file_buffer(filename, &mem, table, trips, sites, devices, filter_presets); free(mem.buffer); return ret; }
subsurface-for-dirk-master
core/file.c
// SPDX-License-Identifier: GPL-2.0 /* * Sane helper for 'strtod()'. * * Sad that we even need this, but the C library version has * insane locale behavior, and while the Qt "doDouble()" routines * are better in that regard, they don't have an end pointer * (having replaced it with the completely idiotic "ok" boolean * pointer instead). * * I wonder what drugs people are on sometimes. * * Right now we support the following flags to limit the * parsing some ways: * * STRTOD_NO_SIGN - don't accept signs * STRTOD_NO_DOT - no decimal dots, I'm European * STRTOD_NO_COMMA - no comma, please, I'm C locale * STRTOD_NO_EXPONENT - no exponent parsing, I'm human * * The "negative" flags are so that the common case can just * use a flag value of 0, and only if you have some special * requirements do you need to state those with explicit flags. * * So if you want the C locale kind of parsing, you'd use the * STRTOD_NO_COMMA flag to disallow a decimal comma. But if you * want a more relaxed "Hey, Europeans are people too, even if * they have locales with commas", just pass in a zero flag. */ #include <ctype.h> #include "subsurface-string.h" double strtod_flags(const char *str, const char **ptr, unsigned int flags) { char c; const char *p = str, *ep; double val = 0.0; double decimal = 1.0; int sign = 0, esign = 0; int numbers = 0, dot = 0; /* skip spaces */ while (isspace(c = *p++)) /* */; /* optional sign */ if (!(flags & STRTOD_NO_SIGN)) { switch (c) { case '-': sign = 1; /* fallthrough */ case '+': c = *p++; } } /* Mantissa */ for (;; c = *p++) { if ((c == '.' && !(flags & STRTOD_NO_DOT)) || (c == ',' && !(flags & STRTOD_NO_COMMA))) { if (dot) goto done; dot = 1; continue; } if (c >= '0' && c <= '9') { numbers++; val = (val * 10) + (c - '0'); if (dot) decimal *= 10; continue; } if (c != 'e' && c != 'E') goto done; if (flags & STRTOD_NO_EXPONENT) goto done; break; } if (!numbers) goto done; /* Exponent */ ep = p; c = *ep++; switch (c) { case '-': esign = 1; /* fallthrough */ case '+': c = *ep++; } if (c >= '0' && c <= '9') { p = ep; int exponent = c - '0'; for (;;) { c = *p++; if (c < '0' || c > '9') break; exponent *= 10; exponent += c - '0'; } /* We're not going to bother playing games */ if (exponent > 308) exponent = 308; while (exponent-- > 0) { if (esign) decimal *= 10; else decimal /= 10; } } done: if (!numbers) goto no_conversion; if (ptr) *ptr = p - 1; return (sign ? -val : val) / decimal; no_conversion: if (ptr) *ptr = str; return 0.0; }
subsurface-for-dirk-master
core/strtod.c
#include "ssrf.h" #include <stdio.h> #include <assert.h> #include <stdarg.h> #include "membuffer.h" #include <stdlib.h> #include <unistd.h> #include <libdivecomputer/parser.h> #include "parse.h" #include "dive.h" #include "divesite.h" #include "errorhelper.h" #include "sample.h" #include "subsurface-string.h" #include "picture.h" #include "trip.h" #include "device.h" #include "gettext.h" struct dive_table dive_table; void init_parser_state(struct parser_state *state) { memset(state, 0, sizeof(*state)); state->metric = true; state->cur_event.deleted = 1; state->sample_rate = 0; } void free_parser_state(struct parser_state *state) { free_dive(state->cur_dive); free_trip(state->cur_trip); free_dive_site(state->cur_dive_site); free_filter_preset(state->cur_filter); free((void *)state->cur_extra_data.key); free((void *)state->cur_extra_data.value); free((void *)state->cur_settings.dc.model); free((void *)state->cur_settings.dc.nickname); free((void *)state->cur_settings.dc.serial_nr); free((void *)state->cur_settings.dc.firmware); free(state->country); free(state->city); free(state->fulltext); free(state->fulltext_string_mode); free(state->filter_constraint_type); free(state->filter_constraint_string_mode); free(state->filter_constraint_range_mode); free(state->filter_constraint); } /* * If we don't have an explicit dive computer, * we use the implicit one that every dive has.. */ struct divecomputer *get_dc(struct parser_state *state) { return state->cur_dc ?: &state->cur_dive->dc; } /* Trim a character string by removing leading and trailing white space characters. * Parameter: a pointer to a null-terminated character string (buffer); * Return value: length of the trimmed string, excluding the terminal 0x0 byte * The original pointer (buffer) remains valid after this function has been called * and points to the trimmed string */ int trimspace(char *buffer) { int i, size, start, end; size = strlen(buffer); if (!size) return 0; for(start = 0; isspace(buffer[start]); start++) if (start >= size) return 0; // Find 1st character following leading whitespace for(end = size - 1; isspace(buffer[end]); end--) // Find last character before trailing whitespace if (end <= 0) return 0; for(i = start; i <= end; i++) // Move the nonspace characters to the start of the string buffer[i-start] = buffer[i]; size = end - start + 1; buffer[size] = 0x0; // then terminate the string return size; // return string length } /* * Add a dive into the dive_table array */ void record_dive_to_table(struct dive *dive, struct dive_table *table) { add_to_dive_table(table, table->nr, fixup_dive(dive)); } void start_match(const char *type, const char *name, char *buffer) { if (verbose > 2) printf("Matching %s '%s' (%s)\n", type, name, buffer); } void nonmatch(const char *type, const char *name, char *buffer) { if (verbose > 1) printf("Unable to match %s '%s' (%s)\n", type, name, buffer); } void event_start(struct parser_state *state) { memset(&state->cur_event, 0, sizeof(state->cur_event)); state->cur_event.deleted = 0; /* Active */ } void event_end(struct parser_state *state) { struct divecomputer *dc = get_dc(state); if (state->cur_event.type == 123) { struct picture pic = empty_picture; pic.filename = strdup(state->cur_event.name); /* theoretically this could fail - but we didn't support multi year offsets */ pic.offset.seconds = state->cur_event.time.seconds; add_picture(&state->cur_dive->pictures, pic); /* Takes ownership. */ } else { struct event *ev; /* At some point gas change events did not have any type. Thus we need to add * one on import, if we encounter the type one missing. */ if (state->cur_event.type == 0 && strcmp(state->cur_event.name, "gaschange") == 0) state->cur_event.type = state->cur_event.value >> 16 > 0 ? SAMPLE_EVENT_GASCHANGE2 : SAMPLE_EVENT_GASCHANGE; ev = add_event(dc, state->cur_event.time.seconds, state->cur_event.type, state->cur_event.flags, state->cur_event.value, state->cur_event.name); /* * Older logs might mark the dive to be CCR by having an "SP change" event at time 0:00. Better * to mark them being CCR on import so no need for special treatments elsewhere on the code. */ if (ev && state->cur_event.time.seconds == 0 && state->cur_event.type == SAMPLE_EVENT_PO2 && state->cur_event.value && dc->divemode==OC) { dc->divemode = CCR; } if (ev && event_is_gaschange(ev)) { /* See try_to_fill_event() on why the filled-in index is one too big */ ev->gas.index = state->cur_event.gas.index-1; if (state->cur_event.gas.mix.o2.permille || state->cur_event.gas.mix.he.permille) ev->gas.mix = state->cur_event.gas.mix; } } state->cur_event.deleted = 1; /* No longer active */ } /* * While in some formats file boundaries are dive boundaries, in many * others (as for example in our native format) there are * multiple dives per file, so there can be other events too that * trigger a "new dive" marker and you may get some nesting due * to that. Just ignore nesting levels. * On the flipside it is possible that we start an XML file that ends * up having no dives in it at all - don't create a bogus empty dive * for those. It's not entirely clear what is the minimum set of data * to make a dive valid, but if it has no location, no date and no * samples I'm pretty sure it's useless. */ bool is_dive(struct parser_state *state) { return state->cur_dive && (state->cur_dive->dive_site || state->cur_dive->when || state->cur_dive->dc.samples); } void reset_dc_info(struct divecomputer *dc, struct parser_state *state) { /* WARN: reset dc info does't touch the dc? */ UNUSED(dc); state->lastcylinderindex = 0; } void reset_dc_settings(struct parser_state *state) { free((void *)state->cur_settings.dc.model); free((void *)state->cur_settings.dc.nickname); free((void *)state->cur_settings.dc.serial_nr); free((void *)state->cur_settings.dc.firmware); state->cur_settings.dc.model = NULL; state->cur_settings.dc.nickname = NULL; state->cur_settings.dc.serial_nr = NULL; state->cur_settings.dc.firmware = NULL; state->cur_settings.dc.deviceid = 0; } void reset_fingerprint(struct parser_state *state) { free((void *)state->cur_settings.fingerprint.data); state->cur_settings.fingerprint.data = NULL; state->cur_settings.fingerprint.model = 0; state->cur_settings.fingerprint.serial = 0; state->cur_settings.fingerprint.fdeviceid = 0; state->cur_settings.fingerprint.fdiveid = 0; } void settings_start(struct parser_state *state) { state->in_settings = true; } void settings_end(struct parser_state *state) { state->in_settings = false; } void fingerprint_settings_start(struct parser_state *state) { reset_fingerprint(state); } void fingerprint_settings_end(struct parser_state *state) { create_fingerprint_node_from_hex(state->fingerprints, state->cur_settings.fingerprint.model, state->cur_settings.fingerprint.serial, state->cur_settings.fingerprint.data, state->cur_settings.fingerprint.fdeviceid, state->cur_settings.fingerprint.fdiveid); } void dc_settings_start(struct parser_state *state) { reset_dc_settings(state); } void dc_settings_end(struct parser_state *state) { create_device_node(state->devices, state->cur_settings.dc.model, state->cur_settings.dc.serial_nr, state->cur_settings.dc.nickname); reset_dc_settings(state); } void dive_site_start(struct parser_state *state) { if (state->cur_dive_site) return; state->taxonomy_category = -1; state->taxonomy_origin = -1; state->cur_dive_site = calloc(1, sizeof(struct dive_site)); } void dive_site_end(struct parser_state *state) { if (!state->cur_dive_site) return; struct dive_site *ds = alloc_or_get_dive_site(state->cur_dive_site->uuid, state->sites); merge_dive_site(ds, state->cur_dive_site); if (verbose > 3) printf("completed dive site uuid %x8 name {%s}\n", ds->uuid, ds->name); free_dive_site(state->cur_dive_site); state->cur_dive_site = NULL; } void filter_preset_start(struct parser_state *state) { if (state->cur_filter) return; state->cur_filter = alloc_filter_preset(); } void filter_preset_end(struct parser_state *state) { add_filter_preset_to_table(state->cur_filter, state->filter_presets); free_filter_preset(state->cur_filter); state->cur_filter = NULL; } void fulltext_start(struct parser_state *state) { if (!state->cur_filter) return; state->in_fulltext = true; } void fulltext_end(struct parser_state *state) { if (!state->in_fulltext) return; filter_preset_set_fulltext(state->cur_filter, state->fulltext, state->fulltext_string_mode); free(state->fulltext); free(state->fulltext_string_mode); state->fulltext = NULL; state->fulltext_string_mode = NULL; state->in_fulltext = false; } void filter_constraint_start(struct parser_state *state) { if (!state->cur_filter) return; state->in_filter_constraint = true; } void filter_constraint_end(struct parser_state *state) { if (!state->in_filter_constraint) return; filter_preset_add_constraint(state->cur_filter, state->filter_constraint_type, state->filter_constraint_string_mode, state->filter_constraint_range_mode, state->filter_constraint_negate, state->filter_constraint); free(state->filter_constraint_type); free(state->filter_constraint_string_mode); free(state->filter_constraint_range_mode); free(state->filter_constraint); state->filter_constraint_type = NULL; state->filter_constraint_string_mode = NULL; state->filter_constraint_range_mode = NULL; state->filter_constraint_negate = false; state->filter_constraint = NULL; state->in_filter_constraint = false; } void dive_start(struct parser_state *state) { if (state->cur_dive) return; state->cur_dive = alloc_dive(); reset_dc_info(&state->cur_dive->dc, state); memset(&state->cur_tm, 0, sizeof(state->cur_tm)); state->o2pressure_sensor = 1; } void dive_end(struct parser_state *state) { if (!state->cur_dive) return; if (!is_dive(state)) { free_dive(state->cur_dive); } else { record_dive_to_table(state->cur_dive, state->target_table); if (state->cur_trip) add_dive_to_trip(state->cur_dive, state->cur_trip); } state->cur_dive = NULL; state->cur_dc = NULL; state->cur_location.lat.udeg = 0; state->cur_location.lon.udeg = 0; } void trip_start(struct parser_state *state) { if (state->cur_trip) return; dive_end(state); state->cur_trip = alloc_trip(); memset(&state->cur_tm, 0, sizeof(state->cur_tm)); } void trip_end(struct parser_state *state) { if (!state->cur_trip) return; insert_trip(state->cur_trip, state->trips); state->cur_trip = NULL; } void picture_start(struct parser_state *state) { } void picture_end(struct parser_state *state) { add_picture(&state->cur_dive->pictures, state->cur_picture); /* dive_add_picture took ownership, we can just clear out copy of the data */ state->cur_picture = empty_picture; } cylinder_t *cylinder_start(struct parser_state *state) { return add_empty_cylinder(&state->cur_dive->cylinders); } void cylinder_end(struct parser_state *state) { } void ws_start(struct parser_state *state) { add_cloned_weightsystem(&state->cur_dive->weightsystems, empty_weightsystem); } void ws_end(struct parser_state *state) { } /* * If the given cylinder doesn't exist, return NO_SENSOR. */ static uint8_t sanitize_sensor_id(const struct dive *d, int nr) { return d && nr >= 0 && nr < d->cylinders.nr ? nr : NO_SENSOR; } /* * By default the sample data does not change unless the * save-file gives an explicit new value. So we copy the * data from the previous sample if one exists, and then * the parsing will update it as necessary. * * There are a few exceptions, like the sample pressure: * missing sample pressure doesn't mean "same as last * time", but "interpolate". We clear those ones * explicitly. * * NOTE! We default sensor use to 0, 1 respetively for * the two sensors, but for CCR dives with explicit * OXYGEN bottles we set the secondary sensor to that. * Then the primary sensor will be either the first * or the second cylinder depending on what isn't an * oxygen cylinder. */ void sample_start(struct parser_state *state) { struct divecomputer *dc = get_dc(state); struct sample *sample = prepare_sample(dc); if (sample != dc->sample) { memcpy(sample, sample-1, sizeof(struct sample)); sample->pressure[0].mbar = 0; sample->pressure[1].mbar = 0; } else { sample->sensor[0] = sanitize_sensor_id(state->cur_dive, !state->o2pressure_sensor); sample->sensor[1] = sanitize_sensor_id(state->cur_dive, state->o2pressure_sensor); } state->cur_sample = sample; state->next_o2_sensor = 0; } void sample_end(struct parser_state *state) { if (!state->cur_dive) return; finish_sample(get_dc(state)); state->cur_sample = NULL; } void divecomputer_start(struct parser_state *state) { struct divecomputer *dc; /* Start from the previous dive computer */ dc = &state->cur_dive->dc; while (dc->next) dc = dc->next; /* Did we already fill that in? */ if (dc->samples || dc->model || dc->when) { struct divecomputer *newdc = calloc(1, sizeof(*newdc)); if (newdc) { dc->next = newdc; dc = newdc; } } /* .. this is the one we'll use */ state->cur_dc = dc; reset_dc_info(dc, state); } void divecomputer_end(struct parser_state *state) { if (!state->cur_dc->when) state->cur_dc->when = state->cur_dive->when; state->cur_dc = NULL; } void userid_start(struct parser_state *state) { state->in_userid = true; } void userid_stop(struct parser_state *state) { state->in_userid = false; } /* * Copy whitespace-trimmed string. Warning: the passed in string will be freed, * therefore make sure to only pass in to NULL-initialized pointers or pointers * to owned strings */ void utf8_string(char *buffer, void *_res) { char **res = _res; int size; free(*res); size = trimspace(buffer); if(size) *res = strdup(buffer); } void add_dive_site(char *ds_name, struct dive *dive, struct parser_state *state) { char *buffer = ds_name; char *to_free = NULL; int size = trimspace(buffer); if (size) { struct dive_site *ds = dive->dive_site; if (!ds) { // if the dive doesn't have a dive site, check if there's already a dive site by this name ds = get_dive_site_by_name(buffer, state->sites); } if (ds) { // we have a dive site, let's hope there isn't a different name if (empty_string(ds->name)) { ds->name = copy_string(buffer); } else if (!same_string(ds->name, buffer)) { // if it's not the same name, it's not the same dive site // but wait, we could have gotten this one based on GPS coords and could // have had two different names for the same site... so let's search the other // way around struct dive_site *exact_match = get_dive_site_by_gps_and_name(buffer, &ds->location, state->sites); if (exact_match) { unregister_dive_from_dive_site(dive); add_dive_to_dive_site(dive, exact_match); } else { struct dive_site *newds = create_dive_site(buffer, state->sites); unregister_dive_from_dive_site(dive); add_dive_to_dive_site(dive, newds); if (has_location(&state->cur_location)) { // we started this uuid with GPS data, so lets use those newds->location = state->cur_location; } else { newds->location = ds->location; } newds->notes = add_to_string(newds->notes, translate("gettextFromC", "additional name for site: %s\n"), ds->name); } } else if (dive->dive_site != ds) { // add the existing dive site to the current dive unregister_dive_from_dive_site(dive); add_dive_to_dive_site(dive, ds); } } else { add_dive_to_dive_site(dive, create_dive_site(buffer, state->sites)); } } free(to_free); } int atoi_n(char *ptr, unsigned int len) { if (len < 10) { char buf[10]; memcpy(buf, ptr, len); buf[len] = 0; return atoi(buf); } return 0; }
subsurface-for-dirk-master
core/parse.c
// SPDX-License-Identifier: GPL-2.0 #ifdef __clang__ // Clang has a bug on zero-initialization of C structs. #pragma clang diagnostic ignored "-Wmissing-field-initializers" #endif #include "ssrf.h" #include "dive.h" #include "divesite.h" #include "sample.h" #include "subsurface-string.h" #include "parse.h" #include "divelist.h" #include "device.h" #include "membuffer.h" #include "gettext.h" static int divinglog_cylinder(void *param, int columns, char **data, char **column) { UNUSED(columns); UNUSED(column); struct parser_state *state = (struct parser_state *)param; cylinder_t *cyl; short dbl = 1; //char get_cylinder_template[] = "select TankID,TankSize,PresS,PresE,PresW,O2,He,DblTank from Tank where LogID = %d"; if (data[7] && atoi(data[7]) > 0) dbl = 2; cyl = cylinder_start(state); /* * Assuming that we have to double the cylinder size, if double * is set */ if (data[1] && atoi(data[1]) > 0) cyl->type.size.mliter = atol(data[1]) * 1000 * dbl; if (data[2] && atoi(data[2]) > 0) cyl->start.mbar = atol(data[2]) * 1000; if (data[3] && atoi(data[3]) > 0) cyl->end.mbar = atol(data[3]) * 1000; if (data[4] && atoi(data[4]) > 0) cyl->type.workingpressure.mbar = atol(data[4]) * 1000; if (data[5] && atoi(data[5]) > 0) cyl->gasmix.o2.permille = atol(data[5]) * 10; if (data[6] && atoi(data[6]) > 0) cyl->gasmix.he.permille = atol(data[6]) * 10; cylinder_end(state); return 0; } static int divinglog_profile(void *param, int columns, char **data, char **column) { UNUSED(columns); UNUSED(column); struct parser_state *state = (struct parser_state *)param; int sinterval = 0; unsigned long time; int len1, len2, len3, len4, len5; char *ptr1, *ptr2, *ptr3, *ptr4, *ptr5; short oldcyl = -1; /* We do not have samples */ if (!data[1]) return 0; if (data[0]) sinterval = atoi(data[0]); /* * Profile * * DDDDDCRASWEE * D: Depth (in meter with two decimals) * C: Deco (1 = yes, 0 = no) * R: RBT (Remaining Bottom Time warning) * A: Ascent warning * S: Decostop ignored * W: Work warning * E: Extra info (different for every computer) * * Example: 004500010000 * 4.5 m, no deco, no RBT warning, ascanding too fast, no decostop ignored, no work, no extra info * * * Profile2 * * TTTFFFFIRRR * * T: Temperature (in °C with one decimal) * F: Tank pressure 1 (in bar with one decimal) * I: Tank ID (0, 1, 2 ... 9) * R: RBT (in min) * * Example: 25518051099 * 25.5 °C, 180.5 bar, Tank 1, 99 min RBT * */ ptr1 = data[1]; ptr2 = data[2]; ptr3 = data[3]; ptr4 = data[4]; ptr5 = data[5]; len1 = strlen(ptr1); len2 = ptr2 ? strlen(ptr2) : 0; len3 = ptr3 ? strlen(ptr3) : 0; len4 = ptr4 ? strlen(ptr4) : 0; len5 = ptr5 ? strlen(ptr5) : 0; time = 0; while (len1 >= 12) { sample_start(state); state->cur_sample->time.seconds = time; state->cur_sample->in_deco = ptr1[5] - '0' ? true : false; state->cur_sample->depth.mm = atoi_n(ptr1, 5) * 10; if (len2 >= 11) { int temp = atoi_n(ptr2, 3); int pressure = atoi_n(ptr2+3, 4); int tank = atoi_n(ptr2+7, 1); int rbt = atoi_n(ptr2+8, 3) * 60; state->cur_sample->temperature.mkelvin = C_to_mkelvin(temp / 10.0f); state->cur_sample->pressure[0].mbar = pressure * 100; state->cur_sample->rbt.seconds = rbt; if (oldcyl != tank && tank >= 0 && tank < state->cur_dive->cylinders.nr) { struct gasmix mix = get_cylinder(state->cur_dive, tank)->gasmix; int o2 = get_o2(mix); int he = get_he(mix); event_start(state); state->cur_event.time.seconds = time; strcpy(state->cur_event.name, "gaschange"); o2 = (o2 + 5) / 10; he = (he + 5) / 10; state->cur_event.value = o2 + (he << 16); event_end(state); oldcyl = tank; } ptr2 += 11; len2 -= 11; } if (len3 >= 14) { state->cur_sample->heartbeat = atoi_n(ptr3+8, 3); ptr3 += 14; len3 -= 14; } if (len4 >= 9) { /* * Following value is NDL when not in deco, and * either 0 or TTS when in deco. */ int val = atoi_n(ptr4, 3); if (state->cur_sample->in_deco) { state->cur_sample->ndl.seconds = 0; if (val) state->cur_sample->tts.seconds = val * 60; } else { state->cur_sample->ndl.seconds = val * 60; } state->cur_sample->stoptime.seconds = atoi_n(ptr4+3, 3) * 60; state->cur_sample->stopdepth.mm = atoi_n(ptr4+6, 3) * 1000; ptr4 += 9; len4 -= 9; } /* * AAABBBCCCOOOONNNNSS * * A = ppO2 cell 1 (measured) * B = ppO2 cell 2 (measured) * C = ppO2 cell 3 (measured) * O = OTU * N = CNS * S = Setpoint * * Example: 1121131141548026411 * 1.12 bar, 1.13 bar, 1.14 bar, OTU = 154.8, CNS = 26.4, Setpoint = 1.1 */ if (len5 >= 19) { int ppo2_1 = atoi_n(ptr5 + 0, 3); int ppo2_2 = atoi_n(ptr5 + 3, 3); int ppo2_3 = atoi_n(ptr5 + 6, 3); int otu = atoi_n(ptr5 + 9, 4); UNUSED(otu); // we seem to not store this? Do we understand its format? int cns = atoi_n(ptr5 + 13, 4); int setpoint = atoi_n(ptr5 + 17, 2); if (ppo2_1 > 0) state->cur_sample->o2sensor[0].mbar = ppo2_1 * 100; if (ppo2_2 > 0) state->cur_sample->o2sensor[1].mbar = ppo2_2 * 100; if (ppo2_3 > 0) state->cur_sample->o2sensor[2].mbar = ppo2_3 * 100; if (cns > 0) state->cur_sample->cns = lrintf(cns / 10.0f); if (setpoint > 0) state->cur_sample->setpoint.mbar = setpoint * 100; ptr5 += 19; len5 -= 19; } /* * Count the number of o2 sensors */ if (!state->cur_dive->dc.no_o2sensors && (state->cur_sample->o2sensor[0].mbar || state->cur_sample->o2sensor[1].mbar || state->cur_sample->o2sensor[2].mbar)) { state->cur_dive->dc.no_o2sensors = state->cur_sample->o2sensor[0].mbar ? 1 : 0 + state->cur_sample->o2sensor[1].mbar ? 1 : 0 + state->cur_sample->o2sensor[2].mbar ? 1 : 0; } sample_end(state); /* Remaining bottom time warning */ if (ptr1[6] - '0') { event_start(state); state->cur_event.time.seconds = time; strcpy(state->cur_event.name, "rbt"); event_end(state); } /* Ascent warning */ if (ptr1[7] - '0') { event_start(state); state->cur_event.time.seconds = time; strcpy(state->cur_event.name, "ascent"); event_end(state); } /* Deco stop ignored */ if (ptr1[8] - '0') { event_start(state); state->cur_event.time.seconds = time; strcpy(state->cur_event.name, "violation"); event_end(state); } /* Workload warning */ if (ptr1[9] - '0') { event_start(state); state->cur_event.time.seconds = time; strcpy(state->cur_event.name, "workload"); event_end(state); } ptr1 += 12; len1 -= 12; time += sinterval; } return 0; } static int divinglog_dive(void *param, int columns, char **data, char **column) { UNUSED(columns); UNUSED(column); int retval = 0, diveid; struct parser_state *state = (struct parser_state *)param; sqlite3 *handle = state->sql_handle; char get_profile_template[] = "select ProfileInt,Profile,Profile2,Profile3,Profile4,Profile5 from Logbook where ID = %d"; char get_cylinder0_template[] = "select 0,TankSize,PresS,PresE,PresW,O2,He,DblTank from Logbook where ID = %d"; char get_cylinder_template[] = "select TankID,TankSize,PresS,PresE,PresW,O2,He,DblTank from Tank where LogID = %d order by TankID"; char get_buffer[1024]; dive_start(state); diveid = atoi(data[13]); state->cur_dive->number = atoi(data[0]); state->cur_dive->when = (time_t)(atol(data[1])); if (data[2]) add_dive_to_dive_site(state->cur_dive, find_or_create_dive_site_with_name(data[2], state->sites)); if (data[3]) utf8_string(data[3], &state->cur_dive->buddy); if (data[4]) utf8_string(data[4], &state->cur_dive->notes); if (data[5]) state->cur_dive->dc.maxdepth.mm = lrint(strtod_flags(data[5], NULL, 0) * 1000); if (data[6]) state->cur_dive->dc.duration.seconds = atoi(data[6]) * 60; if (data[7]) utf8_string(data[7], &state->cur_dive->diveguide); if (data[8]) state->cur_dive->airtemp.mkelvin = C_to_mkelvin(atol(data[8])); if (data[9]) state->cur_dive->watertemp.mkelvin = C_to_mkelvin(atol(data[9])); if (data[10]) { weightsystem_t ws = { { atol(data[10]) * 1000 }, translate("gettextFromC", "unknown"), false }; add_cloned_weightsystem(&state->cur_dive->weightsystems, ws); } if (data[11]) state->cur_dive->suit = strdup(data[11]); /* Divinglog has following visibility options: good, medium, bad */ if (data[14]) { switch(data[14][0]) { case '0': break; case '1': state->cur_dive->visibility = 5; break; case '2': state->cur_dive->visibility = 3; break; case '3': state->cur_dive->visibility = 1; break; default: break; } } settings_start(state); dc_settings_start(state); if (data[12]) { state->cur_dive->dc.model = strdup(data[12]); } else { state->cur_settings.dc.model = strdup("Divinglog import"); } snprintf(get_buffer, sizeof(get_buffer) - 1, get_cylinder0_template, diveid); retval = sqlite3_exec(handle, get_buffer, &divinglog_cylinder, state, NULL); if (retval != SQLITE_OK) { fprintf(stderr, "%s", "Database query divinglog_cylinder0 failed.\n"); return 1; } snprintf(get_buffer, sizeof(get_buffer) - 1, get_cylinder_template, diveid); retval = sqlite3_exec(handle, get_buffer, &divinglog_cylinder, state, NULL); if (retval != SQLITE_OK) { fprintf(stderr, "%s", "Database query divinglog_cylinder failed.\n"); return 1; } if (data[15]) { switch (data[15][0]) { /* OC */ case '0': break; case '1': state->cur_dive->dc.divemode = PSCR; break; case '2': state->cur_dive->dc.divemode = CCR; break; } } dc_settings_end(state); settings_end(state); if (data[12]) { state->cur_dive->dc.model = strdup(data[12]); } else { state->cur_dive->dc.model = strdup("Divinglog import"); } snprintf(get_buffer, sizeof(get_buffer) - 1, get_profile_template, diveid); retval = sqlite3_exec(handle, get_buffer, &divinglog_profile, state, NULL); if (retval != SQLITE_OK) { fprintf(stderr, "%s", "Database query divinglog_profile failed.\n"); return 1; } dive_end(state); return SQLITE_OK; } int parse_divinglog_buffer(sqlite3 *handle, const char *url, const char *buffer, int size, struct dive_table *table, struct trip_table *trips, struct dive_site_table *sites, struct device_table *devices) { UNUSED(buffer); UNUSED(size); int retval; struct parser_state state; init_parser_state(&state); state.target_table = table; state.trips = trips; state.sites = sites; state.devices = devices; state.sql_handle = handle; char get_dives[] = "select Number,strftime('%s',Divedate || ' ' || ifnull(Entrytime,'00:00')),Country || ' - ' || City || ' - ' || Place,Buddy,Comments,Depth,Divetime,Divemaster,Airtemp,Watertemp,Weight,Divesuit,Computer,ID,Visibility,SupplyType from Logbook where UUID not in (select UUID from DeletedRecords)"; retval = sqlite3_exec(handle, get_dives, &divinglog_dive, &state, NULL); free_parser_state(&state); if (retval != SQLITE_OK) { fprintf(stderr, "Database query failed '%s'.\n", url); return 1; } return 0; }
subsurface-for-dirk-master
core/import-divinglog.c
// SPDX-License-Identifier: GPL-2.0 #ifdef __clang__ // Clang has a bug on zero-initialization of C structs. #pragma clang diagnostic ignored "-Wmissing-field-initializers" #endif #include "ssrf.h" #include <stdio.h> #include <ctype.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <time.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <stdarg.h> #include <git2.h> #include "subsurface-string.h" #include "membuffer.h" #include "strndup.h" #include "qthelper.h" #include "file.h" #include "errorhelper.h" #include "git-access.h" #include "gettext.h" #include "sha1.h" // the mobile app assumes that it shouldn't talk to the cloud // the desktop app assumes that it should #if defined(SUBSURFACE_MOBILE) bool git_local_only = true; #else bool git_local_only = false; #endif bool git_remote_sync_successful = false; int (*update_progress_cb)(const char *) = NULL; static bool includes_string_caseinsensitive(const char *haystack, const char *needle) { if (!needle) return 1; /* every string includes the NULL string */ if (!haystack) return 0; /* nothing is included in the NULL string */ int len = strlen(needle); while (*haystack) { if (strncasecmp(haystack, needle, len)) return 1; haystack++; } return 0; } void set_git_update_cb(int(*cb)(const char *)) { update_progress_cb = cb; } // total overkill, but this allows us to get good timing in various scenarios; // the various parts of interacting with the local and remote git repositories send // us updates which indicate progress (and no, this is not smooth and definitely not // proportional - some parts are based on compute performance, some on network speed) // they also provide information where in the process we are so we can analyze the log // to understand which parts of the process take how much time. int git_storage_update_progress(const char *text) { int ret = 0; if (update_progress_cb) ret = (*update_progress_cb)(text); return ret; } // the checkout_progress_cb doesn't allow canceling of the operation // map the git progress to 20% of overall progress static void progress_cb(const char *path, size_t completed_steps, size_t total_steps, void *payload) { UNUSED(path); UNUSED(payload); char buf[80]; snprintf(buf, sizeof(buf), translate("gettextFromC", "Checkout from storage (%lu/%lu)"), completed_steps, total_steps); (void)git_storage_update_progress(buf); } // this randomly assumes that 80% of the time is spent on the objects and 20% on the deltas // map the git progress to 20% of overall progress // if the user cancels the dialog this is passed back to libgit2 static int transfer_progress_cb(const git_transfer_progress *stats, void *payload) { UNUSED(payload); static int last_done = -1; char buf[80]; int done = 0; int total = 0; if (stats->total_objects) { total = 60; done = 60 * stats->received_objects / stats->total_objects; } if (stats->total_deltas) { total += 20; done += 20 * stats->indexed_deltas / stats->total_deltas; } /* for debugging this is useful char buf[100]; snprintf(buf, 100, "transfer cb rec_obj %d tot_obj %d idx_delta %d total_delta %d local obj %d", stats->received_objects, stats->total_objects, stats->indexed_deltas, stats->total_deltas, stats->local_objects); return git_storage_update_progress(buf); */ if (done > last_done) { last_done = done; snprintf(buf, sizeof(buf), translate("gettextFromC", "Transfer from storage (%d/%d)"), done, total); return git_storage_update_progress(buf); } return 0; } // the initial push to sync the repos is mapped to 10% of overall progress static int push_transfer_progress_cb(unsigned int current, unsigned int total, size_t bytes, void *payload) { UNUSED(bytes); UNUSED(payload); char buf[80]; snprintf(buf, sizeof(buf), translate("gettextFromC", "Transfer to storage (%d/%d)"), current, total); return git_storage_update_progress(buf); } char *get_local_dir(const char *url, const char *branch) { SHA_CTX ctx; unsigned char hash[20]; // this optimization could in theory lead to odd things happening if the // cloud backend servers ever get out of sync - but when a user switches // between those servers (either because one is down, or because the algorithm // which server to pick changed, or because the user is on a different continent), // then the hash and therefore the local directory would change. To prevent that // from happening, normalize the cloud string to always use the old default name. // That's trivial with QString operations and painful to do right in plain C, so // let's be lazy and call a C++ helper function // just remember to free the string we get back const char *remote = normalize_cloud_name(url); // That zero-byte update is so that we don't get hash // collisions for "repo1 branch" vs "repo 1branch". SHA1_Init(&ctx); SHA1_Update(&ctx, remote, strlen(remote)); SHA1_Update(&ctx, "", 1); SHA1_Update(&ctx, branch, strlen(branch)); SHA1_Final(hash, &ctx); free((void *)remote); return format_string("%s/cloudstorage/%02x%02x%02x%02x%02x%02x%02x%02x", system_default_directory(), hash[0], hash[1], hash[2], hash[3], hash[4], hash[5], hash[6], hash[7]); } static char *move_local_cache(struct git_info *info) { char *old_path = get_local_dir(info->url, info->branch); return move_away(old_path); } static int check_clean(const char *path, unsigned int status, void *payload) { struct git_info *info = (struct git_info *)payload; status &= ~GIT_STATUS_CURRENT | GIT_STATUS_IGNORED; if (!status) return 0; SSRF_INFO("git storage: local cache dir %s modified, git status 0x%04x", path, status); if (info->is_subsurface_cloud) report_error(translate("gettextFromC", "Local cache directory %s corrupted - can't sync with Subsurface cloud storage"), path); else report_error("WARNING: Git cache directory modified (path %s) status 0x%04x", path, status); return 1; } /* * The remote is strictly newer than the local branch. */ static int reset_to_remote(struct git_info *info, git_reference *local, const git_oid *new_id) { git_checkout_options opts = GIT_CHECKOUT_OPTIONS_INIT; opts.progress_cb = &progress_cb; git_object *target; if (verbose) SSRF_INFO("git storage: reset to remote\n"); // If it's not checked out (bare or not HEAD), just update the reference */ if (git_repository_is_bare(info->repo) || git_branch_is_head(local) != 1) { git_reference *out; if (git_reference_set_target(&out, local, new_id, "Update to remote")) { SSRF_INFO("git storage: could not update local cache to newer remote data"); return report_error(translate("gettextFromC", "Could not update local cache to newer remote data")); } git_reference_free(out); #ifdef DEBUG // Not really an error, just informational report_error("Updated local branch from remote"); #endif return 0; } if (git_object_lookup(&target, info->repo, new_id, GIT_OBJ_COMMIT)) { SSRF_INFO("git storage: could not look up remote commit"); if (info->is_subsurface_cloud) return report_error(translate("gettextFromC", "Subsurface cloud storage corrupted")); else return report_error("Could not look up remote commit"); } opts.checkout_strategy = GIT_CHECKOUT_SAFE; if (git_reset(info->repo, target, GIT_RESET_HARD, &opts)) { SSRF_INFO("git storage: local head checkout failed after update"); if (info->is_subsurface_cloud) return report_error(translate("gettextFromC", "Could not update local cache to newer remote data")); else return report_error("Local head checkout failed after update"); } // Not really an error, just informational #ifdef DEBUG report_error("Updated local information from remote"); #endif return 0; } static int auth_attempt = 0; static const int max_auth_attempts = 2; static bool exceeded_auth_attempts() { if (auth_attempt++ > max_auth_attempts) { SSRF_INFO("git storage: authentication to cloud storage failed"); report_error("Authentication to cloud storage failed."); return true; } return false; } int credential_ssh_cb(git_cred **out, const char *url, const char *username_from_url, unsigned int allowed_types, void *payload) { UNUSED(url); UNUSED(payload); UNUSED(username_from_url); const char *username = prefs.cloud_storage_email_encoded; const char *passphrase = prefs.cloud_storage_password ? prefs.cloud_storage_password : ""; // TODO: We need a way to differentiate between password and private key authentication if (allowed_types & GIT_CREDTYPE_SSH_KEY) { char *priv_key = format_string("%s/%s", system_default_directory(), "ssrf_remote.key"); if (!access(priv_key, F_OK)) { if (exceeded_auth_attempts()) return GIT_EUSER; int ret = git_cred_ssh_key_new(out, username, NULL, priv_key, passphrase); free(priv_key); return ret; } free(priv_key); } if (allowed_types & GIT_CREDTYPE_USERPASS_PLAINTEXT) { if (exceeded_auth_attempts()) return GIT_EUSER; return git_cred_userpass_plaintext_new(out, username, passphrase); } if (allowed_types & GIT_CREDTYPE_USERNAME) return git_cred_username_new(out, username); report_error("No supported ssh authentication."); return GIT_EUSER; } int credential_https_cb(git_cred **out, const char *url, const char *username_from_url, unsigned int allowed_types, void *payload) { UNUSED(url); UNUSED(username_from_url); UNUSED(payload); UNUSED(allowed_types); if (exceeded_auth_attempts()) return GIT_EUSER; const char *username = prefs.cloud_storage_email_encoded; const char *password = prefs.cloud_storage_password ? prefs.cloud_storage_password : ""; return git_cred_userpass_plaintext_new(out, username, password); } int certificate_check_cb(git_cert *cert, int valid, const char *host, void *payload) { UNUSED(payload); if (verbose) SSRF_INFO("git storage: certificate callback for host %s with validity %d\n", host, valid); if ((same_string(host, CLOUD_HOST_GENERIC) || same_string(host, CLOUD_HOST_US) || same_string(host, CLOUD_HOST_EU)) && cert->cert_type == GIT_CERT_X509) { // for some reason the LetsEncrypt certificate makes libgit2 throw up on some // platforms but not on others // if we are connecting to the cloud server we alrady called 'canReachCloudServer()' // which will fail if the SSL certificate isn't valid, so let's simply always // tell the caller that this certificate is valid return 1; } return valid; } static int update_remote(struct git_info *info, git_remote *origin, git_reference *local, git_reference *remote) { UNUSED(remote); git_push_options opts = GIT_PUSH_OPTIONS_INIT; git_strarray refspec; const char *name = git_reference_name(local); if (verbose) SSRF_INFO("git storage: update remote\n"); refspec.count = 1; refspec.strings = (char **)&name; auth_attempt = 0; opts.callbacks.push_transfer_progress = &push_transfer_progress_cb; if (info->transport == RT_SSH) opts.callbacks.credentials = credential_ssh_cb; else if (info->transport == RT_HTTPS) opts.callbacks.credentials = credential_https_cb; opts.callbacks.certificate_check = certificate_check_cb; if (git_remote_push(origin, &refspec, &opts)) { const char *msg = giterr_last()->message; SSRF_INFO("git storage: unable to update remote with current local cache state, error: %s", msg); if (info->is_subsurface_cloud) return report_error(translate("gettextFromC", "Could not update Subsurface cloud storage, try again later")); else return report_error("Unable to update remote with current local cache state (%s)", msg); } return 0; } extern int update_git_checkout(git_repository *repo, git_object *parent, git_tree *tree); static int try_to_git_merge(struct git_info *info, git_reference **local_p, git_reference *remote, git_oid *base, const git_oid *local_id, const git_oid *remote_id) { UNUSED(remote); git_tree *local_tree, *remote_tree, *base_tree; git_commit *local_commit, *remote_commit, *base_commit; git_index *merged_index; git_merge_options merge_options; struct membuffer msg = { 0, 0, NULL}; if (verbose) { char outlocal[41], outremote[41]; outlocal[40] = outremote[40] = 0; git_oid_fmt(outlocal, local_id); git_oid_fmt(outremote, remote_id); SSRF_INFO("git storage: trying to merge local SHA %s remote SHA %s\n", outlocal, outremote); } git_merge_init_options(&merge_options, GIT_MERGE_OPTIONS_VERSION); merge_options.flags = GIT_MERGE_FIND_RENAMES; merge_options.file_favor = GIT_MERGE_FILE_FAVOR_UNION; merge_options.rename_threshold = 100; if (git_commit_lookup(&local_commit, info->repo, local_id)) { SSRF_INFO("git storage: remote storage and local data diverged. Error: can't get commit (%s)", giterr_last()->message); goto diverged_error; } if (git_commit_tree(&local_tree, local_commit)) { SSRF_INFO("git storage: remote storage and local data diverged. Error: failed local tree lookup (%s)", giterr_last()->message); goto diverged_error; } if (git_commit_lookup(&remote_commit, info->repo, remote_id)) { SSRF_INFO("git storage: remote storage and local data diverged. Error: can't get commit (%s)", giterr_last()->message); goto diverged_error; } if (git_commit_tree(&remote_tree, remote_commit)) { SSRF_INFO("git storage: remote storage and local data diverged. Error: failed local tree lookup (%s)", giterr_last()->message); goto diverged_error; } if (git_commit_lookup(&base_commit, info->repo, base)) { SSRF_INFO("git storage: remote storage and local data diverged. Error: can't get commit (%s)", giterr_last()->message); goto diverged_error; } if (git_commit_tree(&base_tree, base_commit)) { SSRF_INFO("git storage: remote storage and local data diverged. Error: failed base tree lookup (%s)", giterr_last()->message); goto diverged_error; } if (git_merge_trees(&merged_index, info->repo, base_tree, local_tree, remote_tree, &merge_options)) { SSRF_INFO("git storage: remote storage and local data diverged. Error: merge failed (%s)", giterr_last()->message); // this is the one where I want to report more detail to the user - can't quite explain why return report_error(translate("gettextFromC", "Remote storage and local data diverged. Error: merge failed (%s)"), giterr_last()->message); } if (git_index_has_conflicts(merged_index)) { int error; const git_index_entry *ancestor = NULL, *ours = NULL, *theirs = NULL; git_index_conflict_iterator *iter = NULL; error = git_index_conflict_iterator_new(&iter, merged_index); while (git_index_conflict_next(&ancestor, &ours, &theirs, iter) != GIT_ITEROVER) { /* Mark this conflict as resolved */ SSRF_INFO("git storage: conflict in %s / %s / %s -- ", ours ? ours->path : "-", theirs ? theirs->path : "-", ancestor ? ancestor->path : "-"); if ((!ours && theirs && ancestor) || (ours && !theirs && ancestor)) { // the file was removed on one side or the other - just remove it SSRF_INFO("git storage: looks like a delete on one side; removing the file from the index\n"); error = git_index_remove(merged_index, ours ? ours->path : theirs->path, GIT_INDEX_STAGE_ANY); } else if (ancestor) { error = git_index_conflict_remove(merged_index, ours ? ours->path : theirs ? theirs->path : ancestor->path); } if (error) { SSRF_INFO("git storage: error at conflict resolution (%s)", giterr_last()->message); } } git_index_conflict_cleanup(merged_index); git_index_conflict_iterator_free(iter); report_error(translate("gettextFromC", "Remote storage and local data diverged. Cannot combine local and remote changes")); } git_oid merge_oid, commit_oid; git_tree *merged_tree; git_signature *author; git_commit *commit; if (git_index_write_tree_to(&merge_oid, merged_index, info->repo)) goto write_error; if (git_tree_lookup(&merged_tree, info->repo, &merge_oid)) goto write_error; if (get_authorship(info->repo, &author) < 0) goto write_error; const char *user_agent = subsurface_user_agent(); put_format(&msg, "Automatic merge\n\nCreated by %s\n", user_agent); free((void *)user_agent); if (git_commit_create_v(&commit_oid, info->repo, NULL, author, author, NULL, mb_cstring(&msg), merged_tree, 2, local_commit, remote_commit)) goto write_error; if (git_commit_lookup(&commit, info->repo, &commit_oid)) goto write_error; if (git_branch_is_head(*local_p) && !git_repository_is_bare(info->repo)) { git_object *parent; git_reference_peel(&parent, *local_p, GIT_OBJ_COMMIT); if (update_git_checkout(info->repo, parent, merged_tree)) { goto write_error; } } if (git_reference_set_target(local_p, *local_p, &commit_oid, "Subsurface merge event")) goto write_error; set_git_id(&commit_oid); git_signature_free(author); if (verbose) SSRF_INFO("git storage: successfully merged repositories"); free_buffer(&msg); return 0; diverged_error: return report_error(translate("gettextFromC", "Remote storage and local data diverged")); write_error: free_buffer(&msg); return report_error(translate("gettextFromC", "Remote storage and local data diverged. Error: writing the data failed (%s)"), giterr_last()->message); } // if accessing the local cache of Subsurface cloud storage fails, we simplify things // for the user and simply move the cache away (in case they want to try and extract data) // and ask them to retry the operation (which will then refresh the data from the cloud server) static int cleanup_local_cache(struct git_info *info) { char *backup_path = move_local_cache(info); SSRF_INFO("git storage: problems with local cache, moved to %s", backup_path); report_error(translate("gettextFromC", "Problems with local cache of Subsurface cloud data")); report_error(translate("gettextFromC", "Moved cache data to %s. Please try the operation again."), backup_path); free(backup_path); return -1; } static int try_to_update(struct git_info *info, git_remote *origin, git_reference *local, git_reference *remote) { git_oid base; const git_oid *local_id, *remote_id; int ret = 0; if (verbose) SSRF_INFO("git storage: try to update\n"); if (!git_reference_cmp(local, remote)) return 0; // Dirty modified state in the working tree? We're not going // to update either way if (git_status_foreach(info->repo, check_clean, (void *)info)) { SSRF_INFO("git storage: local cache is dirty, skipping update"); if (info->is_subsurface_cloud) goto cloud_data_error; else return report_error("local cached copy is dirty, skipping update"); } local_id = git_reference_target(local); remote_id = git_reference_target(remote); if (!local_id || !remote_id) { if (!local_id) SSRF_INFO("git storage: unable to get local SHA"); if (!remote_id) SSRF_INFO("git storage: unable to get remote SHA"); if (info->is_subsurface_cloud) goto cloud_data_error; else return report_error("Unable to get local or remote SHA1"); } if (git_merge_base(&base, info->repo, local_id, remote_id)) { // TODO: // if they have no merge base, they actually are different repos // so instead merge this as merging a commit into a repo - git_merge() appears to do that // but needs testing and cleanup afterwards // SSRF_INFO("git storage: no common commit between local and remote branches"); if (info->is_subsurface_cloud) goto cloud_data_error; else return report_error("Unable to find common commit of local and remote branches"); } /* Is the remote strictly newer? Use it */ if (git_oid_equal(&base, local_id)) { if (verbose) SSRF_INFO("git storage: remote is newer than local, update local"); git_storage_update_progress(translate("gettextFromC", "Update local storage to match cloud storage")); return reset_to_remote(info, local, remote_id); } /* Is the local repo the more recent one? See if we can update upstream */ if (git_oid_equal(&base, remote_id)) { if (verbose) SSRF_INFO("git storage: local is newer than remote, update remote"); git_storage_update_progress(translate("gettextFromC", "Push local changes to cloud storage")); return update_remote(info, origin, local, remote); } /* Merging a bare repository always needs user action */ if (git_repository_is_bare(info->repo)) { SSRF_INFO("git storage: local is bare and has diverged from remote; user action needed"); if (info->is_subsurface_cloud) goto cloud_data_error; else return report_error("Local and remote have diverged, merge of bare branch needed"); } /* Merging will definitely need the head branch too */ if (git_branch_is_head(local) != 1) { SSRF_INFO("git storage: local branch is not HEAD, cannot merge"); if (info->is_subsurface_cloud) goto cloud_data_error; else return report_error("Local and remote do not match, local branch not HEAD - cannot update"); } /* Ok, let's try to merge these */ git_storage_update_progress(translate("gettextFromC", "Try to merge local changes into cloud storage")); ret = try_to_git_merge(info, &local, remote, &base, local_id, remote_id); if (ret == 0) return update_remote(info, origin, local, remote); else return ret; cloud_data_error: // since we are working with Subsurface cloud storage we want to make the user interaction // as painless as possible. So if something went wrong with the local cache, tell the user // about it an move it away return cleanup_local_cache(info); } static int check_remote_status(struct git_info *info, git_remote *origin) { int error = 0; git_reference *local_ref, *remote_ref; if (verbose) SSRF_INFO("git storage: check remote status\n"); if (git_branch_lookup(&local_ref, info->repo, info->branch, GIT_BRANCH_LOCAL)) { SSRF_INFO("git storage: branch %s is missing in local repo", info->branch); if (info->is_subsurface_cloud) return cleanup_local_cache(info); else return report_error("Git cache branch %s no longer exists", info->branch); } if (git_branch_upstream(&remote_ref, local_ref)) { /* so there is no upstream branch for our branch; that's a problem. * let's push our branch */ SSRF_INFO("git storage: branch %s is missing in remote, pushing branch", info->branch); git_strarray refspec; git_reference_list(&refspec, info->repo); git_push_options opts = GIT_PUSH_OPTIONS_INIT; opts.callbacks.transfer_progress = &transfer_progress_cb; auth_attempt = 0; if (info->transport == RT_SSH) opts.callbacks.credentials = credential_ssh_cb; else if (info->transport == RT_HTTPS) opts.callbacks.credentials = credential_https_cb; opts.callbacks.certificate_check = certificate_check_cb; git_storage_update_progress(translate("gettextFromC", "Store data into cloud storage")); error = git_remote_push(origin, &refspec, &opts); } else { error = try_to_update(info, origin, local_ref, remote_ref); git_reference_free(remote_ref); } git_reference_free(local_ref); git_remote_sync_successful = (error == 0); return error; } /* this is (so far) only used by the git storage tests to remove a remote branch * it will print out errors, but not return an error (as this isn't a function that * we test as part of the tests, it's a helper to not leave loads of dead branches on * the server) */ void delete_remote_branch(git_repository *repo, const char *remote, const char *branch) { int error; char *proxy_string; git_remote *origin; git_config *conf; /* set up the config and proxy information in order to connect to the server */ git_repository_config(&conf, repo); if (getProxyString(&proxy_string)) { git_config_set_string(conf, "http.proxy", proxy_string); free(proxy_string); } else { git_config_delete_entry(conf, "http.proxy"); } if (git_remote_lookup(&origin, repo, "origin")) { SSRF_INFO("git storage: repository '%s' origin lookup failed (%s)", remote, giterr_last() ? giterr_last()->message : "(unspecified)"); return; } /* fetch the remote state */ git_fetch_options f_opts = GIT_FETCH_OPTIONS_INIT; auth_attempt = 0; f_opts.callbacks.credentials = credential_https_cb; error = git_remote_fetch(origin, NULL, &f_opts, NULL); if (error) { SSRF_INFO("git storage: remote fetch failed (%s)\n", giterr_last() ? giterr_last()->message : "authentication failed"); return; } /* delete the remote branch by pushing to ":refs/heads/<branch>" */ git_strarray refspec; char *branch_ref = format_string(":refs/heads/%s", branch); refspec.count = 1; refspec.strings = &branch_ref; git_push_options p_opts = GIT_PUSH_OPTIONS_INIT; auth_attempt = 0; p_opts.callbacks.credentials = credential_https_cb; error = git_remote_push(origin, &refspec, &p_opts); free(branch_ref); if (error) { SSRF_INFO("git storage: unable to delete branch '%s'", branch); SSRF_INFO("git storage: error was (%s)\n", giterr_last() ? giterr_last()->message : "(unspecified)"); } git_remote_free(origin); return; } int sync_with_remote(struct git_info *info) { int error; git_remote *origin; char *proxy_string; git_config *conf; if (git_local_only) { if (verbose) SSRF_INFO("git storage: don't sync with remote - read from cache only\n"); return 0; } if (verbose) SSRF_INFO("git storage: sync with remote %s[%s]\n", info->url, info->branch); git_storage_update_progress(translate("gettextFromC", "Sync with cloud storage")); git_repository_config(&conf, info->repo); if (info->transport == RT_HTTPS && getProxyString(&proxy_string)) { if (verbose) SSRF_INFO("git storage: set proxy to \"%s\"\n", proxy_string); git_config_set_string(conf, "http.proxy", proxy_string); free(proxy_string); } else { if (verbose) SSRF_INFO("git storage: delete proxy setting\n"); git_config_delete_entry(conf, "http.proxy"); } /* * NOTE! Remote errors are reported, but are nonfatal: * we still successfully return the local repository. */ error = git_remote_lookup(&origin, info->repo, "origin"); if (error) { const char *msg = giterr_last()->message; SSRF_INFO("git storage: repo %s origin lookup failed with: %s", info->url, msg); if (!info->is_subsurface_cloud) report_error("Repository '%s' origin lookup failed (%s)", info->url, msg); return 0; } // we know that we already checked for the cloud server, but to give a decent warning message // here in case none of them are reachable, let's check one more time if (info->is_subsurface_cloud && !canReachCloudServer(info)) { // this is not an error, just a warning message, so return 0 SSRF_INFO("git storage: cannot connect to remote server"); report_error("Cannot connect to cloud server, working with local copy"); git_storage_update_progress(translate("gettextFromC", "Can't reach cloud server, working with local data")); return 0; } if (verbose) SSRF_INFO("git storage: fetch remote %s\n", git_remote_url(origin)); git_fetch_options opts = GIT_FETCH_OPTIONS_INIT; opts.callbacks.transfer_progress = &transfer_progress_cb; auth_attempt = 0; if (info->transport == RT_SSH) opts.callbacks.credentials = credential_ssh_cb; else if (info->transport == RT_HTTPS) opts.callbacks.credentials = credential_https_cb; opts.callbacks.certificate_check = certificate_check_cb; git_storage_update_progress(translate("gettextFromC", "Successful cloud connection, fetch remote")); error = git_remote_fetch(origin, NULL, &opts, NULL); // NOTE! A fetch error is not fatal, we just report it if (error) { if (info->is_subsurface_cloud) report_error("Cannot sync with cloud server, working with offline copy"); else report_error("Unable to fetch remote '%s'", info->url); // If we returned GIT_EUSER during authentication, giterr_last() returns NULL SSRF_INFO("git storage: remote fetch failed (%s)\n", giterr_last() ? giterr_last()->message : "authentication failed"); // Since we failed to sync with online repository, enter offline mode git_local_only = true; error = 0; } else { error = check_remote_status(info, origin); } git_remote_free(origin); git_storage_update_progress(translate("gettextFromC", "Done syncing with cloud storage")); return error; } static bool update_local_repo(struct git_info *info) { git_reference *head; /* Check the HEAD being the right branch */ if (!git_repository_head(&head, info->repo)) { const char *name; if (!git_branch_name(&name, head)) { if (strcmp(name, info->branch)) { char *branchref = format_string("refs/heads/%s", info->branch); SSRF_INFO("git storage: setting cache branch from '%s' to '%s'", name, info->branch); git_repository_set_head(info->repo, branchref); free(branchref); } } git_reference_free(head); } /* make sure we have the correct origin - the cloud server URL could have changed */ if (git_remote_set_url(info->repo, "origin", info->url)) { SSRF_INFO("git storage: failed to update origin to '%s'", info->url); return false; } if (!git_local_only) sync_with_remote(info); return true; } static int repository_create_cb(git_repository **out, const char *path, int bare, void *payload) { UNUSED(payload); char *proxy_string; git_config *conf; int ret = git_repository_init(out, path, bare); if (ret != 0) { if (verbose) SSRF_INFO("git storage: initializing git repository failed\n"); return ret; } git_repository_config(&conf, *out); if (getProxyString(&proxy_string)) { if (verbose) SSRF_INFO("git storage: set proxy to \"%s\"\n", proxy_string); git_config_set_string(conf, "http.proxy", proxy_string); free(proxy_string); } else { if (verbose) SSRF_INFO("git storage: delete proxy setting\n"); git_config_delete_entry(conf, "http.proxy"); } return ret; } /* this should correctly initialize both the local and remote * repository for the Subsurface cloud storage */ static bool create_and_push_remote(struct git_info *info) { git_config *conf; char *variable_name, *head; if (verbose) SSRF_INFO("git storage: create and push remote\n"); /* first make sure the directory for the local cache exists */ subsurface_mkdir(info->localdir); head = format_string("refs/heads/%s", info->branch); /* set up the origin to point to our remote */ git_repository_init_options init_opts = GIT_REPOSITORY_INIT_OPTIONS_INIT; init_opts.origin_url = info->url; init_opts.initial_head = head; /* now initialize the repository with */ git_repository_init_ext(&info->repo, info->localdir, &init_opts); /* create a config so we can set the remote tracking branch */ git_repository_config(&conf, info->repo); variable_name = format_string("branch.%s.remote", info->branch); git_config_set_string(conf, variable_name, "origin"); free(variable_name); variable_name = format_string("branch.%s.merge", info->branch); git_config_set_string(conf, variable_name, head); free(head); free(variable_name); /* finally create an empty commit and push it to the remote */ if (do_git_save(info, false, true)) return false; return true; } static bool create_local_repo(struct git_info *info) { int error; git_clone_options opts = GIT_CLONE_OPTIONS_INIT; if (verbose) SSRF_INFO("git storage: create_local_repo\n"); auth_attempt = 0; opts.fetch_opts.callbacks.transfer_progress = &transfer_progress_cb; if (info->transport == RT_SSH) opts.fetch_opts.callbacks.credentials = credential_ssh_cb; else if (info->transport == RT_HTTPS) opts.fetch_opts.callbacks.credentials = credential_https_cb; opts.repository_cb = repository_create_cb; opts.fetch_opts.callbacks.certificate_check = certificate_check_cb; opts.checkout_branch = info->branch; if (info->is_subsurface_cloud && !canReachCloudServer(info)) { SSRF_INFO("git storage: cannot reach remote server"); return false; } if (verbose > 1) SSRF_INFO("git storage: calling git_clone()\n"); error = git_clone(&info->repo, info->url, info->localdir, &opts); if (verbose > 1) SSRF_INFO("git storage: returned from git_clone() with return value %d\n", error); if (error) { SSRF_INFO("git storage: clone of %s failed", info->url); char *msg = ""; if (giterr_last()) { msg = giterr_last()->message; SSRF_INFO("git storage: error message was %s\n", msg); } char *pattern = format_string("reference 'refs/remotes/origin/%s' not found", info->branch); // it seems that we sometimes get 'Reference' and sometimes 'reference' if (includes_string_caseinsensitive(msg, pattern)) { /* we're trying to open the remote branch that corresponds * to our cloud storage and the branch doesn't exist. * So we need to create the branch and push it to the remote */ if (verbose) SSRF_INFO("git storage: remote repo didn't include our branch\n"); if (create_and_push_remote(info)) error = 0; #if !defined(DEBUG) && !defined(SUBSURFACE_MOBILE) } else if (info->is_subsurface_cloud) { report_error(translate("gettextFromC", "Error connecting to Subsurface cloud storage")); #endif } else { report_error(translate("gettextFromC", "git clone of %s failed (%s)"), info->url, msg); } free(pattern); } return !error; } static enum remote_transport url_to_remote_transport(const char *remote) { /* figure out the remote transport */ if (strncmp(remote, "ssh://", 6) == 0) return RT_SSH; else if (strncmp(remote, "https://", 8) == 0) return RT_HTTPS; else return RT_OTHER; } static bool get_remote_repo(struct git_info *info) { struct stat st; if (verbose > 1) { SSRF_INFO("git storage: accessing %s\n", info->url); } git_storage_update_progress(translate("gettextFromC", "Synchronising data file")); /* Do we already have a local cache? */ if (!subsurface_stat(info->localdir, &st)) { int error; if (verbose) SSRF_INFO("git storage: update local repo\n"); error = git_repository_open(&info->repo, info->localdir); if (error) { const char *msg = giterr_last()->message; SSRF_INFO("git storage: unable to open local cache at %s: %s", info->localdir, msg); if (info->is_subsurface_cloud) (void)cleanup_local_cache(info); else report_error("Unable to open git cache repository at %s: %s", info->localdir, msg); return false; } return update_local_repo(info); } else { /* We have no local cache yet. * Take us temporarly online to create a local and * remote cloud repo. */ bool ret; bool glo = git_local_only; git_local_only = false; ret = create_local_repo(info); git_local_only = glo; if (ret) git_remote_sync_successful = true; return ret; } /* all normal cases are handled above */ return false; } /* * Remove the user name from the url if it exists, and * save it in 'info->username'. */ static void extract_username(struct git_info *info, char *url) { char c; char *p = url; while ((c = *p++) >= 'a' && c <= 'z') /* nothing */; if (c != ':') return; if (*p++ != '/' || *p++ != '/') return; /* * Ok, we found "[a-z]*://" and we think we have a real * "remote git" format. The "file://" case was handled * in the calling function. */ info->transport = url_to_remote_transport(url); char *at = strchr(p, '@'); if (!at) return; /* was this the @ that denotes an account? that means it was before the * first '/' after the protocol:// - so let's find a '/' after that and compare */ char *slash = strchr(p, '/'); if (!slash || at > slash) return; /* grab the part between "protocol://" and "@" as encoded email address * (that's our username) and move the rest of the URL forward, remembering * to copy the closing NUL as well */ info->username = strndup(p, at - p); memmove(p, at + 1, strlen(at + 1) + 1); /* * Ugly, ugly. Parsing the remote repo user name also sets * it in the preferences. We should do this somewhere else! */ prefs.cloud_storage_email_encoded = strdup(info->username); } void cleanup_git_info(struct git_info *info) { if (info->repo) git_repository_free(info->repo); free((void *)info->url); free((void *)info->branch); free((void *)info->username); free((void *)info->localdir); memset(info, 0, sizeof(*info)); } /* * If it's not a git repo, return NULL. Be very conservative. * * The recognized formats are * git://host/repo[branch] * ssh://host/repo[branch] * http://host/repo[branch] * https://host/repo[branch] * file://repo[branch] */ bool is_git_repository(const char *filename, struct git_info *info) { int flen, blen; int offset = 1; char *url, *branch; /* we are looking at a new potential remote, but we haven't synced with it */ git_remote_sync_successful = false; memset(info, 0, sizeof(*info)); info->transport = RT_LOCAL; flen = strlen(filename); if (!flen || filename[--flen] != ']') return false; /* * Special-case "file://", and treat it as a local * repository since libgit2 is insanely slow for that. */ if (!strncmp(filename, "file://", 7)) { filename += 7; flen -= 7; } /* Find the matching '[' */ blen = 0; while (flen && filename[--flen] != '[') blen++; /* Ignore slashes at the end of the repo name */ while (flen && filename[flen-1] == '/') { flen--; offset++; } if (!flen) return false; /* * This is the "point of no return": the name matches * the git repository name rules, and we will no longer * return NULL. * * We will either return with NULL git repo and the * branch pointer will have the _whole_ filename in it, * or we will return a real git repository with the * branch pointer being filled in with just the branch * name. * * The actual git reading/writing routines can use this * to generate proper error messages. */ url = format_string("%.*s", flen, filename); branch = format_string("%.*s", blen, filename + flen + offset); /* Extract the username from the url string */ extract_username(info, url); info->url = url; info->branch = branch; /* * We now create the SHA1 hash of the whole thing, * including the branch name. That will be our unique * local repository name. * * NOTE! We will create a local repository per branch, * because * * (a) libgit2 remote tracking branch support seems to * be a bit lacking * (b) we'll actually check the branch out so that we * can do merges etc too. * * so even if you have a single remote git repo with * multiple branches for different people, the local * caches will sadly force that to split into multiple * individual repositories. */ switch (info->transport) { case RT_LOCAL: info->localdir = strdup(url); break; default: info->localdir = get_local_dir(info->url, info->branch); break; } /* * Remember if the current git storage we are working on is our * cloud storage. * * This is used to create more user friendly error message and warnings. */ info->is_subsurface_cloud = (strstr(info->url, prefs.cloud_base_url) != NULL); return true; } bool open_git_repository(struct git_info *info) { /* * If the repository is local, just open it. There's nothing * else to do. */ if (info->transport == RT_LOCAL) { const char *url = info->localdir; if (git_repository_open(&info->repo, url)) { if (verbose) SSRF_INFO("git storage: loc %s couldn't be opened (%s)\n", url, giterr_last()->message); return false; } return true; } /* if we are planning to access the server, make sure it's available and try to * pick one of the alternative servers if necessary */ if (info->is_subsurface_cloud && !git_local_only) { // since we know that this is Subsurface cloud storage, we don't have to // worry about the local directory name changing if we end up with a different // cloud_base_url... the algorithm normalizes those URLs (void)canReachCloudServer(info); } return get_remote_repo(info); } int git_create_local_repo(const char *filename) { git_repository *repo; char *path = strdup(filename); char *branch = strchr(path, '['); if (branch) *branch = '\0'; int ret = git_repository_init(&repo, path, false); free(path); if (ret != 0) (void)report_error("Create local repo failed with error code %d", ret); git_repository_free(repo); return ret; }
subsurface-for-dirk-master
core/git-access.c
// SPDX-License-Identifier: GPL-2.0 /* dive.c */ /* maintains the internal dive list structure */ #include <string.h> #include <stdio.h> #include <stdlib.h> #include <limits.h> #include "dive.h" #include "gettext.h" #include "subsurface-string.h" #include "libdivecomputer.h" #include "device.h" #include "divelist.h" #include "divesite.h" #include "errorhelper.h" #include "event.h" #include "extradata.h" #include "interpolate.h" #include "qthelper.h" #include "membuffer.h" #include "picture.h" #include "sample.h" #include "tag.h" #include "trip.h" #include "structured_list.h" #include "fulltext.h" /* one could argue about the best place to have this variable - * it's used in the UI, but it seems to make the most sense to have it * here */ struct dive displayed_dive; // For user visible text but still not translated const char *divemode_text_ui[] = { QT_TRANSLATE_NOOP("gettextFromC", "Open circuit"), QT_TRANSLATE_NOOP("gettextFromC", "CCR"), QT_TRANSLATE_NOOP("gettextFromC", "pSCR"), QT_TRANSLATE_NOOP("gettextFromC", "Freedive") }; // For writing/reading files. const char *divemode_text[] = {"OC", "CCR", "PSCR", "Freedive"}; static double calculate_depth_to_mbarf(int depth, pressure_t surface_pressure, int salinity); /* * The legacy format for sample pressures has a single pressure * for each sample that can have any sensor, plus a possible * "o2pressure" that is fixed to the Oxygen sensor for a CCR dive. * * For more complex pressure data, we have to use explicit * cylinder indices for each sample. * * This function returns a negative number for "no legacy mode", * or a non-negative number that indicates the o2 sensor index. */ int legacy_format_o2pressures(const struct dive *dive, const struct divecomputer *dc) { int i, o2sensor; o2sensor = (dc->divemode == CCR) ? get_cylinder_idx_by_use(dive, OXYGEN) : -1; for (i = 0; i < dc->samples; i++) { const struct sample *s = dc->sample + i; int seen_pressure = 0, idx; for (idx = 0; idx < MAX_SENSORS; idx++) { int sensor = s->sensor[idx]; pressure_t p = s->pressure[idx]; if (!p.mbar) continue; if (sensor == o2sensor) continue; if (seen_pressure) return -1; seen_pressure = 1; } } /* * Use legacy mode: if we have no O2 sensor we return a * positive sensor index that is guaranmteed to not match * any sensor (we encode it as 8 bits). */ return o2sensor < 0 ? 256 : o2sensor; } /* warning: does not test idx for validity */ struct event *create_gas_switch_event(struct dive *dive, struct divecomputer *dc, int seconds, int idx) { /* The gas switch event format is insane for historical reasons */ struct gasmix mix = get_cylinder(dive, idx)->gasmix; int o2 = get_o2(mix); int he = get_he(mix); struct event *ev; int value; o2 = (o2 + 5) / 10; he = (he + 5) / 10; value = o2 + (he << 16); ev = create_event(seconds, he ? SAMPLE_EVENT_GASCHANGE2 : SAMPLE_EVENT_GASCHANGE, 0, value, "gaschange"); ev->gas.index = idx; ev->gas.mix = mix; return ev; } void add_gas_switch_event(struct dive *dive, struct divecomputer *dc, int seconds, int idx) { /* sanity check so we don't crash */ /* FIXME: The planner uses a dummy cylinder one past the official number of cylinders * in the table to mark no-cylinder surface interavals. This is horrendous. Fix ASAP. */ //if (idx < 0 || idx >= dive->cylinders.nr) { if (idx < 0 || idx >= dive->cylinders.nr + 1 || idx >= dive->cylinders.allocated) { report_error("Unknown cylinder index: %d", idx); return; } struct event *ev = create_gas_switch_event(dive, dc, seconds, idx); add_event_to_dc(dc, ev); } /* since the name is an array as part of the structure (how silly is that?) we * have to actually remove the existing event and replace it with a new one. * WARNING, WARNING... this may end up freeing event in case that event is indeed * WARNING, WARNING... part of this divecomputer on this dive! */ void update_event_name(struct dive *d, int dc_number, struct event *event, const char *name) { if (!d || !event) return; struct divecomputer *dc = get_dive_dc(d, dc_number); if (!dc) return; struct event **removep = &dc->events; struct event *remove; while ((*removep)->next && !same_event(*removep, event)) removep = &(*removep)->next; if (!same_event(*removep, event)) return; remove = *removep; *removep = (*removep)->next; add_event(dc, event->time.seconds, event->type, event->flags, event->value, name); free(remove); invalidate_dive_cache(d); } struct gasmix get_gasmix_from_event(const struct dive *dive, const struct event *ev) { if (ev && event_is_gaschange(ev)) { int index = ev->gas.index; // FIXME: The planner uses one past cylinder-count to signify "surface air". Remove in due course. if (index == dive->cylinders.nr) return gasmix_air; if (index >= 0 && index < dive->cylinders.nr) return get_cylinder(dive, index)->gasmix; return ev->gas.mix; } return gasmix_air; } // we need this to be uniq. oh, and it has no meaning whatsoever // - that's why we have the silly initial number and increment by 3 :-) int dive_getUniqID() { static int maxId = 83529; maxId += 3; return maxId; } struct dive *alloc_dive(void) { struct dive *dive; dive = malloc(sizeof(*dive)); if (!dive) exit(1); memset(dive, 0, sizeof(*dive)); dive->id = dive_getUniqID(); return dive; } /* copy an element in a list of dive computer extra data */ static void copy_extra_data(struct extra_data *sed, struct extra_data *ded) { ded->key = copy_string(sed->key); ded->value = copy_string(sed->value); } /* this is very different from the copy_divecomputer later in this file; * this function actually makes full copies of the content */ static void copy_dc(const struct divecomputer *sdc, struct divecomputer *ddc) { *ddc = *sdc; ddc->model = copy_string(sdc->model); ddc->serial = copy_string(sdc->serial); ddc->fw_version = copy_string(sdc->fw_version); copy_samples(sdc, ddc); copy_events(sdc, ddc); STRUCTURED_LIST_COPY(struct extra_data, sdc->extra_data, ddc->extra_data, copy_extra_data); } static void dc_cylinder_renumber(struct dive *dive, struct divecomputer *dc, const int mapping[]); /* copy dive computer list and renumber the cylinders * space for the first divecomputer is provided by the * caller, the remainder is allocated */ static void copy_dc_renumber(struct dive *d, const struct divecomputer *sdc, struct divecomputer *ddc, const int cylinders_map[]) { for (;;) { copy_dc(sdc, ddc); dc_cylinder_renumber(d, ddc, cylinders_map); if (!sdc->next) break; sdc = sdc->next; ddc->next = calloc(1, sizeof(struct divecomputer)); ddc = ddc->next; } ddc->next = NULL; } static void free_dive_structures(struct dive *d) { if (!d) return; fulltext_unregister(d); /* free the strings */ free(d->buddy); free(d->diveguide); free(d->notes); free(d->suit); /* free tags, additional dive computers, and pictures */ taglist_free(d->tag_list); free_dive_dcs(&d->dc); clear_cylinder_table(&d->cylinders); free(d->cylinders.cylinders); clear_weightsystem_table(&d->weightsystems); free(d->weightsystems.weightsystems); clear_picture_table(&d->pictures); free(d->pictures.pictures); } void free_dive(struct dive *d) { free_dive_structures(d); free(d); } /* copy_dive makes duplicates of many components of a dive; * in order not to leak memory, we need to free those . * copy_dive doesn't play with the divetrip and forward/backward pointers * so we can ignore those */ void clear_dive(struct dive *d) { if (!d) return; free_dive_structures(d); memset(d, 0, sizeof(struct dive)); } /* make a true copy that is independent of the source dive; * all data structures are duplicated, so the copy can be modified without * any impact on the source */ static void copy_dive_nodc(const struct dive *s, struct dive *d) { clear_dive(d); /* simply copy things over, but then make actual copies of the * relevant components that are referenced through pointers, * so all the strings and the structured lists */ *d = *s; memset(&d->cylinders, 0, sizeof(d->cylinders)); memset(&d->weightsystems, 0, sizeof(d->weightsystems)); memset(&d->pictures, 0, sizeof(d->pictures)); d->full_text = NULL; invalidate_dive_cache(d); d->buddy = copy_string(s->buddy); d->diveguide = copy_string(s->diveguide); d->notes = copy_string(s->notes); d->suit = copy_string(s->suit); copy_cylinders(&s->cylinders, &d->cylinders); copy_weights(&s->weightsystems, &d->weightsystems); copy_pictures(&s->pictures, &d->pictures); d->tag_list = taglist_copy(s->tag_list); } void copy_dive(const struct dive *s, struct dive *d) { copy_dive_nodc(s, d); // Copy the first dc explicitly, then the list of subsequent dc's copy_dc(&s->dc, &d->dc); STRUCTURED_LIST_COPY(struct divecomputer, s->dc.next, d->dc.next, copy_dc); } static void copy_dive_onedc(const struct dive *s, const struct divecomputer *sdc, struct dive *d) { copy_dive_nodc(s, d); copy_dc(sdc, &d->dc); d->dc.next = NULL; } /* make a clone of the source dive and clean out the source dive; * this is specifically so we can create a dive in the displayed_dive and then * add it to the divelist. * Note the difference to copy_dive() / clean_dive() */ struct dive *move_dive(struct dive *s) { struct dive *dive = alloc_dive(); *dive = *s; // so all the pointers in dive point to the things s pointed to memset(s, 0, sizeof(struct dive)); // and now the pointers in s are gone return dive; } #define CONDITIONAL_COPY_STRING(_component) \ if (what._component) \ d->_component = copy_string(s->_component) // copy elements, depending on bits in what that are set void selective_copy_dive(const struct dive *s, struct dive *d, struct dive_components what, bool clear) { if (clear) clear_dive(d); CONDITIONAL_COPY_STRING(notes); CONDITIONAL_COPY_STRING(diveguide); CONDITIONAL_COPY_STRING(buddy); CONDITIONAL_COPY_STRING(suit); if (what.rating) d->rating = s->rating; if (what.visibility) d->visibility = s->visibility; if (what.divesite) { unregister_dive_from_dive_site(d); add_dive_to_dive_site(d, s->dive_site); } if (what.tags) d->tag_list = taglist_copy(s->tag_list); if (what.cylinders) copy_cylinder_types(s, d); if (what.weights) copy_weights(&s->weightsystems, &d->weightsystems); if (what.number) d->number = s->number; if (what.when) d->when = s->when; } #undef CONDITIONAL_COPY_STRING /* copies all events from all dive computers before a given time this is used when editing a dive in the planner to preserve the events of the old dive */ void copy_events_until(const struct dive *sd, struct dive *dd, int time) { if (!sd || !dd) return; const struct divecomputer *s = &sd->dc; struct divecomputer *d = &dd->dc; while (s && d) { const struct event *ev; ev = s->events; while (ev != NULL) { // Don't add events the planner knows about if (ev->time.seconds < time && !event_is_gaschange(ev) && !event_is_divemodechange(ev)) add_event(d, ev->time.seconds, ev->type, ev->flags, ev->value, ev->name); ev = ev->next; } s = s->next; d = d->next; } } int nr_cylinders(const struct dive *dive) { return dive->cylinders.nr; } int nr_weightsystems(const struct dive *dive) { return dive->weightsystems.nr; } void copy_used_cylinders(const struct dive *s, struct dive *d, bool used_only) { int i; if (!s || !d) return; clear_cylinder_table(&d->cylinders); for (i = 0; i < s->cylinders.nr; i++) { if (!used_only || is_cylinder_used(s, i) || get_cylinder(s, i)->cylinder_use == NOT_USED) add_cloned_cylinder(&d->cylinders, *get_cylinder(s, i)); } } /* * So when we re-calculate maxdepth and meandepth, we will * not override the old numbers if they are close to the * new ones. * * Why? Because a dive computer may well actually track the * max. depth and mean depth at finer granularity than the * samples it stores. So it's possible that the max and mean * have been reported more correctly originally. * * Only if the values calculated from the samples are clearly * different do we override the normal depth values. * * This considers 1m to be "clearly different". That's * a totally random number. */ static void update_depth(depth_t *depth, int new) { if (new) { int old = depth->mm; if (abs(old - new) > 1000) depth->mm = new; } } static void update_temperature(temperature_t *temperature, int new) { if (new) { int old = temperature->mkelvin; if (abs(old - new) > 1000) temperature->mkelvin = new; } } /* Which cylinders had gas used? */ #define SOME_GAS 5000 static bool cylinder_used(const cylinder_t *cyl) { int start_mbar, end_mbar; start_mbar = cyl->start.mbar ?: cyl->sample_start.mbar; end_mbar = cyl->end.mbar ?: cyl->sample_end.mbar; // More than 5 bar used? This matches statistics.c // heuristics return start_mbar > end_mbar + SOME_GAS; } /* Get list of used cylinders. Returns the number of used cylinders. */ static int get_cylinder_used(const struct dive *dive, bool used[]) { int i, num = 0; for (i = 0; i < dive->cylinders.nr; i++) { used[i] = cylinder_used(get_cylinder(dive, i)); if (used[i]) num++; } return num; } /* Are there any used cylinders which we do not know usage about? */ static bool has_unknown_used_cylinders(const struct dive *dive, const struct divecomputer *dc, const bool used_cylinders[], int num) { int idx; const struct event *ev; bool *used_and_unknown = malloc(dive->cylinders.nr * sizeof(bool)); memcpy(used_and_unknown, used_cylinders, dive->cylinders.nr * sizeof(bool)); /* We know about using the O2 cylinder in a CCR dive */ if (dc->divemode == CCR) { int o2_cyl = get_cylinder_idx_by_use(dive, OXYGEN); if (o2_cyl >= 0 && used_and_unknown[o2_cyl]) { used_and_unknown[o2_cyl] = false; num--; } } /* We know about the explicit first cylinder (or first) */ idx = explicit_first_cylinder(dive, dc); if (used_and_unknown[idx]) { used_and_unknown[idx] = false; num--; } /* And we have possible switches to other gases */ ev = get_next_event(dc->events, "gaschange"); while (ev && num > 0) { idx = get_cylinder_index(dive, ev); if (idx >= 0 && used_and_unknown[idx]) { used_and_unknown[idx] = false; num--; } ev = get_next_event(ev->next, "gaschange"); } free(used_and_unknown); return num > 0; } void per_cylinder_mean_depth(const struct dive *dive, struct divecomputer *dc, int *mean, int *duration) { int i; int *depthtime; uint32_t lasttime = 0; int lastdepth = 0; int idx = 0; bool *used_cylinders; int num_used_cylinders; if (dive->cylinders.nr <= 0) return; for (i = 0; i < dive->cylinders.nr; i++) mean[i] = duration[i] = 0; if (!dc) return; /* * There is no point in doing per-cylinder information * if we don't actually know about the usage of all the * used cylinders. */ used_cylinders = malloc(dive->cylinders.nr * sizeof(bool)); num_used_cylinders = get_cylinder_used(dive, used_cylinders); if (has_unknown_used_cylinders(dive, dc, used_cylinders, num_used_cylinders)) { /* * If we had more than one used cylinder, but * do not know usage of them, we simply cannot * account mean depth to them. */ if (num_used_cylinders > 1) { free(used_cylinders); return; } /* * For a single cylinder, use the overall mean * and duration */ for (i = 0; i < dive->cylinders.nr; i++) { if (used_cylinders[i]) { mean[i] = dc->meandepth.mm; duration[i] = dc->duration.seconds; } } free(used_cylinders); return; } free(used_cylinders); if (!dc->samples) fake_dc(dc); const struct event *ev = get_next_event(dc->events, "gaschange"); depthtime = malloc(dive->cylinders.nr * sizeof(*depthtime)); memset(depthtime, 0, dive->cylinders.nr * sizeof(*depthtime)); for (i = 0; i < dc->samples; i++) { struct sample *sample = dc->sample + i; uint32_t time = sample->time.seconds; int depth = sample->depth.mm; /* Make sure to move the event past 'lasttime' */ while (ev && lasttime >= ev->time.seconds) { idx = get_cylinder_index(dive, ev); ev = get_next_event(ev->next, "gaschange"); } /* Do we need to fake a midway sample at an event? */ if (ev && time > ev->time.seconds) { int newtime = ev->time.seconds; int newdepth = interpolate(lastdepth, depth, newtime - lasttime, time - lasttime); time = newtime; depth = newdepth; i--; } /* We ignore segments at the surface */ if (depth > SURFACE_THRESHOLD || lastdepth > SURFACE_THRESHOLD) { duration[idx] += time - lasttime; depthtime[idx] += (time - lasttime) * (depth + lastdepth) / 2; } lastdepth = depth; lasttime = time; } for (i = 0; i < dive->cylinders.nr; i++) { if (duration[i]) mean[i] = (depthtime[i] + duration[i] / 2) / duration[i]; } free(depthtime); } static void update_min_max_temperatures(struct dive *dive, temperature_t temperature) { if (temperature.mkelvin) { if (!dive->maxtemp.mkelvin || temperature.mkelvin > dive->maxtemp.mkelvin) dive->maxtemp = temperature; if (!dive->mintemp.mkelvin || temperature.mkelvin < dive->mintemp.mkelvin) dive->mintemp = temperature; } } /* * If the cylinder tank pressures are within half a bar * (about 8 PSI) of the sample pressures, we consider it * to be a rounding error, and throw them away as redundant. */ static int same_rounded_pressure(pressure_t a, pressure_t b) { return abs(a.mbar - b.mbar) <= 500; } /* Some dive computers (Cobalt) don't start the dive with cylinder 0 but explicitly * tell us what the first gas is with a gas change event in the first sample. * Sneakily we'll use a return value of 0 (or FALSE) when there is no explicit * first cylinder - in which case cylinder 0 is indeed the first cylinder. * We likewise return 0 if the event concerns a cylinder that doesn't exist. * If the dive has no cylinders, -1 is returned. */ int explicit_first_cylinder(const struct dive *dive, const struct divecomputer *dc) { int res = 0; if (!dive->cylinders.nr) return -1; if (dc) { const struct event *ev = get_next_event(dc->events, "gaschange"); if (ev && ((dc->sample && ev->time.seconds == dc->sample[0].time.seconds) || ev->time.seconds <= 1)) res = get_cylinder_index(dive, ev); else if (dc->divemode == CCR) res = MAX(get_cylinder_idx_by_use(dive, DILUENT), 0); } return res < dive->cylinders.nr ? res : 0; } /* this gets called when the dive mode has changed (so OC vs. CC) * there are two places we might have setpoints... events or in the samples */ void update_setpoint_events(const struct dive *dive, struct divecomputer *dc) { struct event *ev; int new_setpoint = 0; if (dc->divemode == CCR) new_setpoint = prefs.defaultsetpoint; if (dc->divemode == OC && (same_string(dc->model, "Shearwater Predator") || same_string(dc->model, "Shearwater Petrel") || same_string(dc->model, "Shearwater Nerd"))) { // make sure there's no setpoint in the samples // this is an irreversible change - so switching a dive to OC // by mistake when it's actually CCR is _bad_ // So we make sure, this comes from a Predator or Petrel and we only remove // pO2 values we would have computed anyway. const struct event *ev = get_next_event(dc->events, "gaschange"); struct gasmix gasmix = get_gasmix_from_event(dive, ev); const struct event *next = get_next_event(ev, "gaschange"); for (int i = 0; i < dc->samples; i++) { struct gas_pressures pressures; if (next && dc->sample[i].time.seconds >= next->time.seconds) { ev = next; gasmix = get_gasmix_from_event(dive, ev); next = get_next_event(ev, "gaschange"); } fill_pressures(&pressures, lrint(calculate_depth_to_mbarf(dc->sample[i].depth.mm, dc->surface_pressure, 0)), gasmix ,0, dc->divemode); if (abs(dc->sample[i].setpoint.mbar - (int)(1000 * pressures.o2)) <= 50) dc->sample[i].setpoint.mbar = 0; } } // an "SP change" event at t=0 is currently our marker for OC vs CCR // this will need to change to a saner setup, but for now we can just // check if such an event is there and adjust it, or add that event ev = get_next_event_mutable(dc->events, "SP change"); if (ev && ev->time.seconds == 0) { ev->value = new_setpoint; } else { if (!add_event(dc, 0, SAMPLE_EVENT_PO2, 0, new_setpoint, "SP change")) fprintf(stderr, "Could not add setpoint change event\n"); } } /* * See if the size/workingpressure looks like some standard cylinder * size, eg "AL80". * * NOTE! We don't take compressibility into account when naming * cylinders. That makes a certain amount of sense, since the * cylinder name is independent from the gasmix, and different * gasmixes have different compressibility. */ static void match_standard_cylinder(cylinder_type_t *type) { double cuft, bar; int psi, len; const char *fmt; char buffer[40], *p; /* Do we already have a cylinder description? */ if (type->description) return; bar = type->workingpressure.mbar / 1000.0; cuft = ml_to_cuft(type->size.mliter); cuft *= bar_to_atm(bar); psi = lrint(to_PSI(type->workingpressure)); switch (psi) { case 2300 ... 2500: /* 2400 psi: LP tank */ fmt = "LP%d"; break; case 2600 ... 2700: /* 2640 psi: LP+10% */ fmt = "LP%d"; break; case 2900 ... 3100: /* 3000 psi: ALx tank */ fmt = "AL%d"; break; case 3400 ... 3500: /* 3442 psi: HP tank */ fmt = "HP%d"; break; case 3700 ... 3850: /* HP+10% */ fmt = "HP%d+"; break; default: return; } len = snprintf(buffer, sizeof(buffer), fmt, (int)lrint(cuft)); p = malloc(len + 1); if (!p) return; memcpy(p, buffer, len + 1); type->description = p; } /* * There are two ways to give cylinder size information: * - total amount of gas in cuft (depends on working pressure and physical size) * - physical size * * where "physical size" is the one that actually matters and is sane. * * We internally use physical size only. But we save the workingpressure * so that we can do the conversion if required. */ static void sanitize_cylinder_type(cylinder_type_t *type) { /* If we have no working pressure, it had *better* be just a physical size! */ if (!type->workingpressure.mbar) return; /* No size either? Nothing to go on */ if (!type->size.mliter) return; /* Ok, we have both size and pressure: try to match a description */ match_standard_cylinder(type); } static void sanitize_cylinder_info(struct dive *dive) { int i; for (i = 0; i < dive->cylinders.nr; i++) { sanitize_gasmix(&get_cylinder(dive, i)->gasmix); sanitize_cylinder_type(&get_cylinder(dive, i)->type); } } /* some events should never be thrown away */ static bool is_potentially_redundant(const struct event *event) { if (!strcmp(event->name, "gaschange")) return false; if (!strcmp(event->name, "bookmark")) return false; if (!strcmp(event->name, "heading")) return false; return true; } /* match just by name - we compare the details in the code that uses this helper */ static struct event *find_previous_event(struct divecomputer *dc, struct event *event) { struct event *ev = dc->events; struct event *previous = NULL; if (empty_string(event->name)) return NULL; while (ev && ev != event) { if (same_string(ev->name, event->name)) previous = ev; ev = ev->next; } return previous; } pressure_t calculate_surface_pressure(const struct dive *dive) { const struct divecomputer *dc; pressure_t res; int sum = 0, nr = 0; for_each_relevant_dc(dive, dc) { if (dc->surface_pressure.mbar) { sum += dc->surface_pressure.mbar; nr++; } } res.mbar = nr ? (sum + nr / 2) / nr : 0; return res; } static void fixup_surface_pressure(struct dive *dive) { dive->surface_pressure = calculate_surface_pressure(dive); } /* if the surface pressure in the dive data is redundant to the calculated * value (i.e., it was added by running fixup on the dive) return 0, * otherwise return the surface pressure given in the dive */ pressure_t un_fixup_surface_pressure(const struct dive *d) { pressure_t res = d->surface_pressure; if (res.mbar && res.mbar == calculate_surface_pressure(d).mbar) res.mbar = 0; return res; } static void fixup_water_salinity(struct dive *dive) { struct divecomputer *dc; int sum = 0, nr = 0; for_each_relevant_dc (dive, dc) { if (dc->salinity) { if (dc->salinity < 500) dc->salinity += FRESHWATER_SALINITY; sum += dc->salinity; nr++; } } if (nr) dive->salinity = (sum + nr / 2) / nr; } int get_dive_salinity(const struct dive *dive) { return dive->user_salinity ? dive->user_salinity : dive->salinity; } static void fixup_meandepth(struct dive *dive) { struct divecomputer *dc; int sum = 0, nr = 0; for_each_relevant_dc (dive, dc) { if (dc->meandepth.mm) { sum += dc->meandepth.mm; nr++; } } if (nr) dive->meandepth.mm = (sum + nr / 2) / nr; } static void fixup_duration(struct dive *dive) { struct divecomputer *dc; duration_t duration = { }; for_each_relevant_dc (dive, dc) { duration.seconds = MAX(duration.seconds, dc->duration.seconds); } dive->duration.seconds = duration.seconds; } static void fixup_watertemp(struct dive *dive) { if (!dive->watertemp.mkelvin) dive->watertemp.mkelvin = dc_watertemp(&dive->dc); } static void fixup_airtemp(struct dive *dive) { if (!dive->airtemp.mkelvin) dive->airtemp.mkelvin = dc_airtemp(&dive->dc); } /* if the air temperature in the dive data is redundant to the one in its * first divecomputer (i.e., it was added by running fixup on the dive) * return 0, otherwise return the air temperature given in the dive */ static temperature_t un_fixup_airtemp(const struct dive *a) { temperature_t res = a->airtemp; if (a->airtemp.mkelvin && a->airtemp.mkelvin == dc_airtemp(&a->dc)) res.mkelvin = 0; return res; } /* * events are stored as a linked list, so the concept of * "consecutive, identical events" is somewhat hard to * implement correctly (especially given that on some dive * computers events are asynchronous, so they can come in * between what would be the non-constant sample rate). * * So what we do is that we throw away clearly redundant * events that are fewer than 61 seconds apart (assuming there * is no dive computer with a sample rate of more than 60 * seconds... that would be pretty pointless to plot the * profile with) * * We first only mark the events for deletion so that we * still know when the previous event happened. */ static void fixup_dc_events(struct divecomputer *dc) { struct event *event; event = dc->events; while (event) { struct event *prev; if (is_potentially_redundant(event)) { prev = find_previous_event(dc, event); if (prev && prev->value == event->value && prev->flags == event->flags && event->time.seconds - prev->time.seconds < 61) event->deleted = true; } event = event->next; } event = dc->events; while (event) { if (event->next && event->next->deleted) { struct event *nextnext = event->next->next; free(event->next); event->next = nextnext; } else { event = event->next; } } } static int interpolate_depth(struct divecomputer *dc, int idx, int lastdepth, int lasttime, int now) { int i; int nextdepth = lastdepth; int nexttime = now; for (i = idx+1; i < dc->samples; i++) { struct sample *sample = dc->sample + i; if (sample->depth.mm < 0) continue; nextdepth = sample->depth.mm; nexttime = sample->time.seconds; break; } return interpolate(lastdepth, nextdepth, now-lasttime, nexttime-lasttime); } static void fixup_dc_depths(struct dive *dive, struct divecomputer *dc) { int i; int maxdepth = dc->maxdepth.mm; int lasttime = 0, lastdepth = 0; for (i = 0; i < dc->samples; i++) { struct sample *sample = dc->sample + i; int time = sample->time.seconds; int depth = sample->depth.mm; if (depth < 0) { depth = interpolate_depth(dc, i, lastdepth, lasttime, time); sample->depth.mm = depth; } if (depth > SURFACE_THRESHOLD) { if (depth > maxdepth) maxdepth = depth; } lastdepth = depth; lasttime = time; if (sample->cns > dive->maxcns) dive->maxcns = sample->cns; } update_depth(&dc->maxdepth, maxdepth); if (!has_planned(dive, false) || !is_dc_planner(dc)) if (maxdepth > dive->maxdepth.mm) dive->maxdepth.mm = maxdepth; } static void fixup_dc_ndl(struct divecomputer *dc) { int i; for (i = 0; i < dc->samples; i++) { struct sample *sample = dc->sample + i; if (sample->ndl.seconds != 0) break; if (sample->ndl.seconds == 0) sample->ndl.seconds = -1; } } static void fixup_dc_temp(struct dive *dive, struct divecomputer *dc) { int i; int mintemp = 0, lasttemp = 0; for (i = 0; i < dc->samples; i++) { struct sample *sample = dc->sample + i; int temp = sample->temperature.mkelvin; if (temp) { /* * If we have consecutive identical * temperature readings, throw away * the redundant ones. */ if (lasttemp == temp) sample->temperature.mkelvin = 0; else lasttemp = temp; if (!mintemp || temp < mintemp) mintemp = temp; } update_min_max_temperatures(dive, sample->temperature); } update_temperature(&dc->watertemp, mintemp); update_min_max_temperatures(dive, dc->watertemp); } /* Remove redundant pressure information */ static void simplify_dc_pressures(struct divecomputer *dc) { int i; int lastindex[2] = { -1, -1 }; int lastpressure[2] = { 0 }; for (i = 0; i < dc->samples; i++) { int j; struct sample *sample = dc->sample + i; for (j = 0; j < MAX_SENSORS; j++) { int pressure = sample->pressure[j].mbar; int index = sample->sensor[j]; if (index == lastindex[j]) { /* Remove duplicate redundant pressure information */ if (pressure == lastpressure[j]) sample->pressure[j].mbar = 0; } lastindex[j] = index; lastpressure[j] = pressure; } } } /* Do we need a sensor -> cylinder mapping? */ static void fixup_start_pressure(struct dive *dive, int idx, pressure_t p) { if (idx >= 0 && idx < dive->cylinders.nr) { cylinder_t *cyl = get_cylinder(dive, idx); if (p.mbar && !cyl->sample_start.mbar) cyl->sample_start = p; } } static void fixup_end_pressure(struct dive *dive, int idx, pressure_t p) { if (idx >= 0 && idx < dive->cylinders.nr) { cylinder_t *cyl = get_cylinder(dive, idx); if (p.mbar && !cyl->sample_end.mbar) cyl->sample_end = p; } } /* * Check the cylinder pressure sample information and fill in the * overall cylinder pressures from those. * * We ignore surface samples for tank pressure information. * * At the beginning of the dive, let the cylinder cool down * if the diver starts off at the surface. And at the end * of the dive, there may be surface pressures where the * diver has already turned off the air supply (especially * for computers like the Uemis Zurich that end up saving * quite a bit of samples after the dive has ended). */ static void fixup_dive_pressures(struct dive *dive, struct divecomputer *dc) { int i; /* Walk the samples from the beginning to find starting pressures.. */ for (i = 0; i < dc->samples; i++) { int idx; struct sample *sample = dc->sample + i; if (sample->depth.mm < SURFACE_THRESHOLD) continue; for (idx = 0; idx < MAX_SENSORS; idx++) fixup_start_pressure(dive, sample->sensor[idx], sample->pressure[idx]); } /* ..and from the end for ending pressures */ for (i = dc->samples; --i >= 0; ) { int idx; struct sample *sample = dc->sample + i; if (sample->depth.mm < SURFACE_THRESHOLD) continue; for (idx = 0; idx < MAX_SENSORS; idx++) fixup_end_pressure(dive, sample->sensor[idx], sample->pressure[idx]); } simplify_dc_pressures(dc); } /* * Match a gas change event against the cylinders we have */ static bool validate_gaschange(struct dive *dive, struct event *event) { int index; int o2, he, value; /* We'll get rid of the per-event gasmix, but for now sanitize it */ if (gasmix_is_air(event->gas.mix)) event->gas.mix.o2.permille = 0; /* Do we already have a cylinder index for this gasmix? */ if (event->gas.index >= 0) return true; index = find_best_gasmix_match(event->gas.mix, &dive->cylinders); if (index < 0 || index >= dive->cylinders.nr) return false; /* Fix up the event to have the right information */ event->gas.index = index; event->gas.mix = get_cylinder(dive, index)->gasmix; /* Convert to odd libdivecomputer format */ o2 = get_o2(event->gas.mix); he = get_he(event->gas.mix); o2 = (o2 + 5) / 10; he = (he + 5) / 10; value = o2 + (he << 16); event->value = value; if (he) event->type = SAMPLE_EVENT_GASCHANGE2; return true; } /* Clean up event, return true if event is ok, false if it should be dropped as bogus */ static bool validate_event(struct dive *dive, struct event *event) { if (event_is_gaschange(event)) return validate_gaschange(dive, event); return true; } static void fixup_dc_gasswitch(struct dive *dive, struct divecomputer *dc) { struct event **evp, *event; evp = &dc->events; while ((event = *evp) != NULL) { if (validate_event(dive, event)) { evp = &event->next; continue; } /* Delete this event and try the next one */ *evp = event->next; } } static void fixup_no_o2sensors(struct divecomputer *dc) { // Its only relevant to look for sensor values on CCR and PSCR dives without any no_o2sensors recorded. if (dc->no_o2sensors != 0 || !(dc->divemode == CCR || dc->divemode == PSCR)) return; for (int i = 0; i < dc->samples; i++) { int nsensor = 0; struct sample *s = dc->sample + i; // How many o2 sensors can we find in this sample? if (s->o2sensor[0].mbar) nsensor++; if (s->o2sensor[1].mbar) nsensor++; if (s->o2sensor[2].mbar) nsensor++; // If we fond more than the previous found max, record it. if (nsensor > dc->no_o2sensors) dc->no_o2sensors = nsensor; // Already found the maximum posible amount. if (nsensor == 3) return; } } static void fixup_dc_sample_sensors(struct divecomputer *dc, int nr_cylinders) { int cyl; unsigned long sensor_mask = 0; unsigned int renumber[MAX_SENSORS]; for (int i = 0; i < dc->samples; i++) { struct sample *s = dc->sample + i; for (int j = 0; j < MAX_SENSORS; j++) { int sensor = s->sensor[j]; if (!s->pressure[j].mbar) continue; // No invalid sensor ID's, please if (sensor < 0 || sensor > MAX_SENSORS) { s->sensor[j] = NO_SENSOR; s->pressure[j].mbar = 0; continue; } sensor_mask |= 1ul << sensor; } } // No sensor data? if (!sensor_mask) return; // Sensor data proper subset of cylinders? if (sensor_mask < (1ul << nr_cylinders)) return; // We'll need to fix up sensor numbers.. cyl = 0; for (int i = 0; i < MAX_SENSORS; i++) { renumber[i] = cyl; cyl += sensor_mask & 1; sensor_mask >>= 1; } if (cyl > nr_cylinders) SSRF_INFO("fixup_dc_sample_sensors: more sensors than cylinders in dive!"); // Just rename all the sensors for this DC to the minimal ones for (int i = 0; i < dc->samples; i++) { struct sample *s = dc->sample + i; for (int j = 0; j < MAX_SENSORS; j++) { int sensor = s->sensor[j]; if (sensor < 0) continue; s->sensor[j] = renumber[sensor]; } } } static void fixup_dive_dc(struct dive *dive, struct divecomputer *dc) { /* Fixup duration and mean depth */ fixup_dc_duration(dc); /* Fix up sample depth data */ fixup_dc_depths(dive, dc); /* Fix up first sample ndl data */ fixup_dc_ndl(dc); /* Fix up dive temperatures based on dive computer samples */ fixup_dc_temp(dive, dc); /* Fix up gas switch events */ fixup_dc_gasswitch(dive, dc); /* Fix up cylinder ids in pressure sensors */ fixup_dc_sample_sensors(dc, dive->cylinders.nr); /* Fix up cylinder pressures based on DC info */ fixup_dive_pressures(dive, dc); fixup_dc_events(dc); /* Fixup CCR / PSCR dives with o2sensor values, but without no_o2sensors */ fixup_no_o2sensors(dc); /* If there are no samples, generate a fake profile based on depth and time */ if (!dc->samples) fake_dc(dc); } struct dive *fixup_dive(struct dive *dive) { int i; struct divecomputer *dc; sanitize_cylinder_info(dive); dive->maxcns = dive->cns; /* * Use the dive's temperatures for minimum and maximum in case * we do not have temperatures recorded by DC. */ update_min_max_temperatures(dive, dive->watertemp); for_each_dc (dive, dc) fixup_dive_dc(dive, dc); fixup_water_salinity(dive); if (!dive->surface_pressure.mbar) fixup_surface_pressure(dive); fixup_meandepth(dive); fixup_duration(dive); fixup_watertemp(dive); fixup_airtemp(dive); for (i = 0; i < dive->cylinders.nr; i++) { cylinder_t *cyl = get_cylinder(dive, i); add_cylinder_description(&cyl->type); if (same_rounded_pressure(cyl->sample_start, cyl->start)) cyl->start.mbar = 0; if (same_rounded_pressure(cyl->sample_end, cyl->end)) cyl->end.mbar = 0; } update_cylinder_related_info(dive); for (i = 0; i < dive->weightsystems.nr; i++) { weightsystem_t *ws = &dive->weightsystems.weightsystems[i]; add_weightsystem_description(ws); } /* we should always have a uniq ID as that gets assigned during alloc_dive(), * but we want to make sure... */ if (!dive->id) dive->id = dive_getUniqID(); return dive; } /* Don't pick a zero for MERGE_MIN() */ #define MERGE_MAX(res, a, b, n) res->n = MAX(a->n, b->n) #define MERGE_MIN(res, a, b, n) res->n = (a->n) ? (b->n) ? MIN(a->n, b->n) : (a->n) : (b->n) #define MERGE_TXT(res, a, b, n, sep) res->n = merge_text(a->n, b->n, sep) #define MERGE_NONZERO(res, a, b, n) res->n = a->n ? a->n : b->n /* * This is like add_sample(), but if the distance from the last sample * is excessive, we add two surface samples in between. * * This is so that if you merge two non-overlapping dives, we make sure * that the time in between the dives is at the surface, not some "last * sample that happened to be at a depth of 1.2m". */ static void merge_one_sample(const struct sample *sample, int time, struct divecomputer *dc) { int last = dc->samples - 1; if (last >= 0) { struct sample *prev = dc->sample + last; int last_time = prev->time.seconds; int last_depth = prev->depth.mm; /* * Only do surface events if the samples are more than * a minute apart, and shallower than 5m */ if (time > last_time + 60 && last_depth < 5000) { struct sample surface = { 0 }; /* Init a few values from prev sample to avoid useless info in XML */ surface.bearing.degrees = prev->bearing.degrees; surface.ndl.seconds = prev->ndl.seconds; add_sample(&surface, last_time + 20, dc); add_sample(&surface, time - 20, dc); } } add_sample(sample, time, dc); } static void renumber_last_sample(struct divecomputer *dc, const int mapping[]); static void sample_renumber(struct sample *s, int i, const int mapping[]); /* * Merge samples. Dive 'a' is "offset" seconds before Dive 'b' */ static void merge_samples(struct divecomputer *res, const struct divecomputer *a, const struct divecomputer *b, const int *cylinders_map_a, const int *cylinders_map_b, int offset) { int asamples = a->samples; int bsamples = b->samples; struct sample *as = a->sample; struct sample *bs = b->sample; /* * We want a positive sample offset, so that sample * times are always positive. So if the samples for * 'b' are before the samples for 'a' (so the offset * is negative), we switch a and b around, and use * the reverse offset. */ if (offset < 0) { const int *cylinders_map_tmp; offset = -offset; asamples = bsamples; bsamples = a->samples; as = bs; bs = a->sample; cylinders_map_tmp = cylinders_map_a; cylinders_map_a = cylinders_map_b; cylinders_map_b = cylinders_map_tmp; } for (;;) { int j; int at, bt; struct sample sample = { .bearing.degrees = -1, .ndl.seconds = -1 }; if (!res) return; at = asamples ? as->time.seconds : -1; bt = bsamples ? bs->time.seconds + offset : -1; /* No samples? All done! */ if (at < 0 && bt < 0) return; /* Only samples from a? */ if (bt < 0) { add_sample_a: merge_one_sample(as, at, res); renumber_last_sample(res, cylinders_map_a); as++; asamples--; continue; } /* Only samples from b? */ if (at < 0) { add_sample_b: merge_one_sample(bs, bt, res); renumber_last_sample(res, cylinders_map_b); bs++; bsamples--; continue; } if (at < bt) goto add_sample_a; if (at > bt) goto add_sample_b; /* same-time sample: add a merged sample. Take the non-zero ones */ sample = *bs; sample_renumber(&sample, 0, cylinders_map_b); if (as->depth.mm) sample.depth = as->depth; if (as->temperature.mkelvin) sample.temperature = as->temperature; for (j = 0; j < MAX_SENSORS; ++j) { int sensor_id; sensor_id = cylinders_map_a[as->sensor[j]]; if (sensor_id < 0) continue; if (as->pressure[j].mbar) sample.pressure[j] = as->pressure[j]; if (as->sensor[j]) sample.sensor[j] = sensor_id; } if (as->cns) sample.cns = as->cns; if (as->setpoint.mbar) sample.setpoint = as->setpoint; if (as->ndl.seconds) sample.ndl = as->ndl; if (as->stoptime.seconds) sample.stoptime = as->stoptime; if (as->stopdepth.mm) sample.stopdepth = as->stopdepth; if (as->in_deco) sample.in_deco = true; merge_one_sample(&sample, at, res); as++; bs++; asamples--; bsamples--; } } /* * Does the extradata key/value pair already exist in the * supplied dive computer data? * * This is not hugely efficient (with the whole "do this for * every value you merge" it's O(n**2)) but it's not like we * have very many extra_data entries per dive computer anyway. */ static bool extra_data_exists(const struct extra_data *ed, const struct divecomputer *dc) { const struct extra_data *p; for (p = dc->extra_data; p; p = p->next) { if (strcmp(p->key, ed->key)) continue; if (strcmp(p->value, ed->value)) continue; return true; } return false; } /* * Merge extra_data. * * The extra data from 'a' has already been copied into 'res'. So * we really should just copy over the data from 'b' too. */ static void merge_extra_data(struct divecomputer *res, const struct divecomputer *a, const struct divecomputer *b) { struct extra_data **ed, *src; // Find the place to add things in the result ed = &res->extra_data; while (*ed) ed = &(*ed)->next; for (src = b->extra_data; src; src = src->next) { if (extra_data_exists(src, a)) continue; *ed = malloc(sizeof(struct extra_data)); if (!*ed) break; copy_extra_data(src, *ed); ed = &(*ed)->next; } // Terminate the result list *ed = NULL; } static char *merge_text(const char *a, const char *b, const char *sep) { char *res; if (!a && !b) return NULL; if (!a || !*a) return copy_string(b); if (!b || !*b) return strdup(a); if (!strcmp(a, b)) return copy_string(a); res = malloc(strlen(a) + strlen(b) + 32); if (!res) return (char *)a; sprintf(res, "%s%s%s", a, sep, b); return res; } #define SORT(a, b) \ if (a != b) \ return a < b ? -1 : 1 #define SORT_FIELD(a, b, field) SORT(a->field, b->field) static int sort_event(const struct event *a, const struct event *b, int time_a, int time_b) { SORT(time_a, time_b); SORT_FIELD(a, b, type); SORT_FIELD(a, b, flags); SORT_FIELD(a, b, value); return strcmp(a->name, b->name); } static int same_gas(const struct event *a, const struct event *b) { if (a->type == b->type && a->flags == b->flags && a->value == b->value && !strcmp(a->name, b->name) && same_gasmix(a->gas.mix, b->gas.mix)) { return true; } return false; } static void event_renumber(struct event *ev, const int mapping[]); static void add_initial_gaschange(struct dive *dive, struct divecomputer *dc, int offset, int idx); static void merge_events(struct dive *d, struct divecomputer *res, const struct divecomputer *src1, const struct divecomputer *src2, const int *cylinders_map1, const int *cylinders_map2, int offset) { const struct event *a, *b; struct event **p = &res->events; const struct event *last_gas = NULL; /* Always use positive offsets */ if (offset < 0) { const struct divecomputer *tmp; const int *cylinders_map_tmp; offset = -offset; tmp = src1; src1 = src2; src2 = tmp; cylinders_map_tmp = cylinders_map1; cylinders_map1 = cylinders_map2; cylinders_map2 = cylinders_map_tmp; } a = src1->events; b = src2->events; while (a || b) { int s; const struct event *pick; const int *cylinders_map; int event_offset; if (!b) goto pick_a; if (!a) goto pick_b; s = sort_event(a, b, a->time.seconds, b->time.seconds + offset); /* Identical events? Just skip one of them (we skip a) */ if (!s) { a = a->next; continue; } /* Otherwise, pick the one that sorts first */ if (s < 0) { pick_a: pick = a; a = a->next; event_offset = 0; cylinders_map = cylinders_map1; } else { pick_b: pick = b; b = b->next; event_offset = offset; cylinders_map = cylinders_map2; } /* * If that's a gas-change that matches the previous * gas change, we'll just skip it */ if (event_is_gaschange(pick)) { if (last_gas && same_gas(pick, last_gas)) continue; last_gas = pick; } /* Add it to the target list */ *p = clone_event(pick); (*p)->time.seconds += event_offset; event_renumber(*p, cylinders_map); p = &(*p)->next; } /* If the initial cylinder of a divecomputer was remapped, add a gas change event to that cylinder */ if (cylinders_map1[0] > 0) add_initial_gaschange(d, res, 0, cylinders_map1[0]); if (cylinders_map2[0] > 0) add_initial_gaschange(d, res, offset, cylinders_map2[0]); } /* get_cylinder_idx_by_use(): Find the index of the first cylinder with a particular CCR use type. * The index returned corresponds to that of the first cylinder with a cylinder_use that * equals the appropriate enum value [oxygen, diluent, bailout] given by cylinder_use_type. * A negative number returned indicates that a match could not be found. * Call parameters: dive = the dive being processed * cylinder_use_type = an enum, one of {oxygen, diluent, bailout} */ extern int get_cylinder_idx_by_use(const struct dive *dive, enum cylinderuse cylinder_use_type) { int cylinder_index; for (cylinder_index = 0; cylinder_index < dive->cylinders.nr; cylinder_index++) { if (get_cylinder(dive, cylinder_index)->cylinder_use == cylinder_use_type) return cylinder_index; // return the index of the cylinder with that cylinder use type } return -1; // negative number means cylinder_use_type not found in list of cylinders } /* Force an initial gaschange event to the (old) gas #0 */ static void add_initial_gaschange(struct dive *dive, struct divecomputer *dc, int offset, int idx) { /* if there is a gaschange event up to 30 sec after the initial event, * refrain from adding the initial event */ const struct event *ev = dc->events; while(ev && (ev = get_next_event(ev, "gaschange")) != NULL) { if (ev->time.seconds > offset + 30) break; else if (ev->time.seconds > offset) return; ev = ev->next; } /* Old starting gas mix */ add_gas_switch_event(dive, dc, offset, idx); } static void sample_renumber(struct sample *s, int i, const int mapping[]) { int j; for (j = 0; j < MAX_SENSORS; j++) { int sensor = -1; if (s->sensor[j] != NO_SENSOR) sensor = mapping[s->sensor[j]]; if (sensor == -1) { // Remove sensor and gas pressure info if (i == 0) { s->sensor[j] = 0; s->pressure[j].mbar = 0; } else { s->sensor[j] = s[-1].sensor[j]; s->pressure[j].mbar = s[-1].pressure[j].mbar; } } else { s->sensor[j] = sensor; } } } static void renumber_last_sample(struct divecomputer *dc, const int mapping[]) { int idx; if (dc->samples <= 0) return; idx = dc->samples - 1; sample_renumber(dc->sample + idx, idx, mapping); } static void event_renumber(struct event *ev, const int mapping[]) { if (!event_is_gaschange(ev)) return; if (ev->gas.index < 0) return; ev->gas.index = mapping[ev->gas.index]; } static void dc_cylinder_renumber(struct dive *dive, struct divecomputer *dc, const int mapping[]) { int i; struct event *ev; /* Remap or delete the sensor indices */ for (i = 0; i < dc->samples; i++) sample_renumber(dc->sample + i, i, mapping); /* Remap the gas change indices */ for (ev = dc->events; ev; ev = ev->next) event_renumber(ev, mapping); /* If the initial cylinder of a dive was remapped, add a gas change event to that cylinder */ if (mapping[0] > 0) add_initial_gaschange(dive, dc, 0, mapping[0]); } /* * If the cylinder indices change (due to merging dives or deleting * cylinders in the middle), we need to change the indices in the * dive computer data for this dive. * * Also note that we assume that the initial cylinder is cylinder 0, * so if that got renamed, we need to create a fake gas change event */ void cylinder_renumber(struct dive *dive, int mapping[]) { struct divecomputer *dc; for_each_dc (dive, dc) dc_cylinder_renumber(dive, dc, mapping); } int same_gasmix_cylinder(const cylinder_t *cyl, int cylid, const struct dive *dive, bool check_unused) { struct gasmix mygas = cyl->gasmix; for (int i = 0; i < dive->cylinders.nr; i++) { if (i == cylid) continue; struct gasmix gas2 = get_cylinder(dive, i)->gasmix; if (gasmix_distance(mygas, gas2) == 0 && (is_cylinder_used(dive, i) || check_unused)) return i; } return -1; } static int pdiff(pressure_t a, pressure_t b) { return a.mbar && b.mbar && a.mbar != b.mbar; } static int different_manual_pressures(const cylinder_t *a, const cylinder_t *b) { return pdiff(a->start, b->start) || pdiff(a->end, b->end); } /* * Can we find an exact match for a cylinder in another dive? * Take the "already matched" map into account, so that we * don't match multiple similar cylinders to one target. * * To match, the cylinders have to have the same gasmix and the * same cylinder use (ie OC/Diluent/Oxygen), and if pressures * have been added manually they need to match. */ static int match_cylinder(const cylinder_t *cyl, const struct dive *dive, const bool *try_match) { int i; for (i = 0; i < dive->cylinders.nr; i++) { const cylinder_t *target; if (!try_match[i]) continue; target = get_cylinder(dive, i); if (!same_gasmix(cyl->gasmix, target->gasmix)) continue; if (cyl->cylinder_use != target->cylinder_use) continue; if (different_manual_pressures(cyl, target)) continue; /* open question: Should we check sizes too? */ return i; } return -1; } /* * Function used to merge manually set start or end pressures. This * is used to merge cylinders when merging dives. We store up to two * values for start _and_ end pressures: one derived from samples and * one entered manually, whereby the latter takes precedence. It may * happen that the user merges two dives where one has a manual, * the other only a sample-derived pressure. In such a case we want to * supplement the non-existing manual value by a sample derived one. * Otherwise, the merged dive would end up with incomplete pressure * information. * The last argument to the function specifies whether the larger * or smaller value of the two dives should be returned. Obviously, * for the starting pressure we want the larger and for the ending * pressure the smaller value. */ static pressure_t merge_pressures(pressure_t a, pressure_t sample_a, pressure_t b, pressure_t sample_b, bool take_min) { if (!a.mbar && !b.mbar) return a; if (!a.mbar) a = sample_a; if (!b.mbar) b = sample_b; if (!a.mbar) a = b; if (!b.mbar) b = a; if (take_min && a.mbar < b.mbar) return a; else return b; } /* * We matched things up so that they have the same gasmix and * use, but we might want to fill in any missing cylinder details * in 'a' if we had it from 'b'. */ static void merge_one_cylinder(cylinder_t *a, const cylinder_t *b) { if (!a->type.size.mliter) a->type.size.mliter = b->type.size.mliter; if (!a->type.workingpressure.mbar) a->type.workingpressure.mbar = b->type.workingpressure.mbar; if (empty_string(a->type.description)) a->type.description = copy_string(b->type.description); /* If either cylinder has manually entered pressures, try to merge them. * Use pressures from divecomputer samples if only one cylinder has such a value. * Yes, this is an actual use case we encountered. * Note that we don't merge the sample-derived pressure values, as this is * perfomed after merging in fixup_dive() */ a->start = merge_pressures(a->start, a->sample_start, b->start, b->sample_start, false); a->end = merge_pressures(a->end, a->sample_end, b->end, b->sample_end, true); /* Really? */ a->gas_used.mliter += b->gas_used.mliter; a->deco_gas_used.mliter += b->deco_gas_used.mliter; a->bestmix_o2 = a->bestmix_o2 && b->bestmix_o2; a->bestmix_he = a->bestmix_he && b->bestmix_he; } static bool cylinder_has_data(const cylinder_t *cyl) { return !cyl->type.size.mliter && !cyl->type.workingpressure.mbar && !cyl->type.description && !cyl->gasmix.o2.permille && !cyl->gasmix.he.permille && !cyl->start.mbar && !cyl->end.mbar && !cyl->sample_start.mbar && !cyl->sample_end.mbar && !cyl->gas_used.mliter && !cyl->deco_gas_used.mliter; } static bool cylinder_in_use(const struct dive *dive, int idx) { if (idx < 0 || idx >= dive->cylinders.nr) return false; /* This tests for gaschange events or pressure changes */ if (is_cylinder_used(dive, idx)) return true; /* This tests for typenames or gas contents */ return cylinder_has_data(get_cylinder(dive, idx)); } /* * Merging cylinder information is non-trivial, because the two dive computers * may have different ideas of what the different cylinder indexing is. * * Logic: take all the cylinder information from the preferred dive ('a'), and * then try to match each of the cylinders in the other dive by the gasmix that * is the best match and hasn't been used yet. * * For each dive, a cylinder-renumbering table is returned. */ static void merge_cylinders(struct dive *res, const struct dive *a, const struct dive *b, int mapping_a[], int mapping_b[]) { int i; int max_cylinders = a->cylinders.nr + b->cylinders.nr; bool *used_in_a = malloc(max_cylinders * sizeof(bool)); bool *used_in_b = malloc(max_cylinders * sizeof(bool)); bool *try_to_match = malloc(max_cylinders * sizeof(bool)); /* First, clear all cylinders in destination */ clear_cylinder_table(&res->cylinders); /* Clear all cylinder mappings */ for (i = 0; i < a->cylinders.nr; i++) mapping_a[i] = -1; for (i = 0; i < b->cylinders.nr; i++) mapping_b[i] = -1; /* Calculate usage map of cylinders, clear matching map */ for (i = 0; i < max_cylinders; i++) { used_in_a[i] = cylinder_in_use(a, i); used_in_b[i] = cylinder_in_use(b, i); try_to_match[i] = false; } /* * For each cylinder in 'a' that is used, copy it to 'res'. * These are also potential matches for 'b' to use. */ for (i = 0; i < max_cylinders; i++) { int res_nr = res->cylinders.nr; if (!used_in_a[i]) continue; mapping_a[i] = res_nr; try_to_match[res_nr] = true; add_cloned_cylinder(&res->cylinders, *get_cylinder(a, i)); } /* * For each cylinder in 'b' that is used, try to match it * with an existing cylinder in 'res' from 'a' */ for (i = 0; i < b->cylinders.nr; i++) { int j; if (!used_in_b[i]) continue; j = match_cylinder(get_cylinder(b, i), res, try_to_match); /* No match? Add it to the result */ if (j < 0) { int res_nr = res->cylinders.nr; mapping_b[i] = res_nr; add_cloned_cylinder(&res->cylinders, *get_cylinder(b, i)); continue; } /* Otherwise, merge the result to the one we found */ mapping_b[i] = j; merge_one_cylinder(get_cylinder(res,j), get_cylinder(b, i)); /* Don't match the same target more than once */ try_to_match[j] = false; } free(used_in_a); free(used_in_b); free(try_to_match); } /* Check whether a weightsystem table contains a given weightsystem */ static bool has_weightsystem(const struct weightsystem_table *t, const weightsystem_t w) { int i; for (i = 0; i < t->nr; i++) { if (same_weightsystem(w, t->weightsystems[i])) return true; } return false; } static void merge_equipment(struct dive *res, const struct dive *a, const struct dive *b) { int i; for (i = 0; i < a->weightsystems.nr; i++) { if (!has_weightsystem(&res->weightsystems, a->weightsystems.weightsystems[i])) add_cloned_weightsystem(&res->weightsystems, a->weightsystems.weightsystems[i]); } for (i = 0; i < b->weightsystems.nr; i++) { if (!has_weightsystem(&res->weightsystems, b->weightsystems.weightsystems[i])) add_cloned_weightsystem(&res->weightsystems, b->weightsystems.weightsystems[i]); } } static void merge_temperatures(struct dive *res, const struct dive *a, const struct dive *b) { temperature_t airtemp_a = un_fixup_airtemp(a); temperature_t airtemp_b = un_fixup_airtemp(b); res->airtemp = airtemp_a.mkelvin ? airtemp_a : airtemp_b; MERGE_NONZERO(res, a, b, watertemp.mkelvin); } /* * Pick a trip for a dive */ static struct dive_trip *get_preferred_trip(const struct dive *a, const struct dive *b) { dive_trip_t *atrip, *btrip; /* If only one dive has a trip, choose that */ atrip = a->divetrip; btrip = b->divetrip; if (!atrip) return btrip; if (!btrip) return atrip; /* Both dives have a trip - prefer the non-autogenerated one */ if (atrip->autogen && !btrip->autogen) return btrip; if (!atrip->autogen && btrip->autogen) return atrip; /* Otherwise, look at the trip data and pick the "better" one */ if (!atrip->location) return btrip; if (!btrip->location) return atrip; if (!atrip->notes) return btrip; if (!btrip->notes) return atrip; /* * Ok, so both have location and notes. * Pick the earlier one. */ if (a->when < b->when) return atrip; return btrip; } #if CURRENTLY_NOT_USED /* * Sample 's' is between samples 'a' and 'b'. It is 'offset' seconds before 'b'. * * If 's' and 'a' are at the same time, offset is 0, and b is NULL. */ static int compare_sample(struct sample *s, struct sample *a, struct sample *b, int offset) { unsigned int depth = a->depth.mm; int diff; if (offset) { unsigned int interval = b->time.seconds - a->time.seconds; unsigned int depth_a = a->depth.mm; unsigned int depth_b = b->depth.mm; if (offset > interval) return -1; /* pick the average depth, scaled by the offset from 'b' */ depth = (depth_a * offset) + (depth_b * (interval - offset)); depth /= interval; } diff = s->depth.mm - depth; if (diff < 0) diff = -diff; /* cut off at one meter difference */ if (diff > 1000) diff = 1000; return diff * diff; } /* * Calculate a "difference" in samples between the two dives, given * the offset in seconds between them. Use this to find the best * match of samples between two different dive computers. */ static unsigned long sample_difference(struct divecomputer *a, struct divecomputer *b, int offset) { int asamples = a->samples; int bsamples = b->samples; struct sample *as = a->sample; struct sample *bs = b->sample; unsigned long error = 0; int start = -1; if (!asamples || !bsamples) return 0; /* * skip the first sample - this way we know can always look at * as/bs[-1] to look at the samples around it in the loop. */ as++; bs++; asamples--; bsamples--; for (;;) { int at, bt, diff; /* If we run out of samples, punt */ if (!asamples) return INT_MAX; if (!bsamples) return INT_MAX; at = as->time.seconds; bt = bs->time.seconds + offset; /* b hasn't started yet? Ignore it */ if (bt < 0) { bs++; bsamples--; continue; } if (at < bt) { diff = compare_sample(as, bs - 1, bs, bt - at); as++; asamples--; } else if (at > bt) { diff = compare_sample(bs, as - 1, as, at - bt); bs++; bsamples--; } else { diff = compare_sample(as, bs, NULL, 0); as++; bs++; asamples--; bsamples--; } /* Invalid comparison point? */ if (diff < 0) continue; if (start < 0) start = at; error += diff; if (at - start > 120) break; } return error; } /* * Dive 'a' is 'offset' seconds before dive 'b' * * This is *not* because the dive computers clocks aren't in sync, * it is because the dive computers may "start" the dive at different * points in the dive, so the sample at time X in dive 'a' is the * same as the sample at time X+offset in dive 'b'. * * For example, some dive computers take longer to "wake up" when * they sense that you are under water (ie Uemis Zurich if it was off * when the dive started). And other dive computers have different * depths that they activate at, etc etc. * * If we cannot find a shared offset, don't try to merge. */ static int find_sample_offset(struct divecomputer *a, struct divecomputer *b) { int offset, best; unsigned long max; /* No samples? Merge at any time (0 offset) */ if (!a->samples) return 0; if (!b->samples) return 0; /* * Common special-case: merging a dive that came from * the same dive computer, so the samples are identical. * Check this first, without wasting time trying to find * some minimal offset case. */ best = 0; max = sample_difference(a, b, 0); if (!max) return 0; /* * Otherwise, look if we can find anything better within * a thirty second window.. */ for (offset = -30; offset <= 30; offset++) { unsigned long diff; diff = sample_difference(a, b, offset); if (diff > max) continue; best = offset; max = diff; } return best; } #endif /* * Are a and b "similar" values, when given a reasonable lower end expected * difference? * * So for example, we'd expect different dive computers to give different * max. depth readings. You might have them on different arms, and they * have different pressure sensors and possibly different ideas about * water salinity etc. * * So have an expected minimum difference, but also allow a larger relative * error value. */ static int similar(unsigned long a, unsigned long b, unsigned long expected) { if (!a && !b) return 1; if (a && b) { unsigned long min, max, diff; min = a; max = b; if (a > b) { min = b; max = a; } diff = max - min; /* Smaller than expected difference? */ if (diff < expected) return 1; /* Error less than 10% or the maximum */ if (diff * 10 < max) return 1; } return 0; } /* * Match every dive computer against each other to see if * we have a matching dive. * * Return values: * -1 for "is definitely *NOT* the same dive" * 0 for "don't know" * 1 for "is definitely the same dive" */ static int match_dc_dive(const struct divecomputer *a, const struct divecomputer *b) { do { const struct divecomputer *tmp = b; do { int match = match_one_dc(a, tmp); if (match) return match; tmp = tmp->next; } while (tmp); a = a->next; } while (a); return 0; } /* * Do we want to automatically try to merge two dives that * look like they are the same dive? * * This happens quite commonly because you download a dive * that you already had, or perhaps because you maintained * multiple dive logs and want to load them all together * (possibly one of them was imported from another dive log * application entirely). * * NOTE! We mainly look at the dive time, but it can differ * between two dives due to a few issues: * * - rounding the dive date to the nearest minute in other dive * applications * * - dive computers with "relative datestamps" (ie the dive * computer doesn't actually record an absolute date at all, * but instead at download-time synchronizes its internal * time with real-time on the downloading computer) * * - using multiple dive computers with different real time on * the same dive * * We do not merge dives that look radically different, and if * the dates are *too* far off the user will have to join two * dives together manually. But this tries to handle the sane * cases. */ static int likely_same_dive(const struct dive *a, const struct dive *b) { int match, fuzz = 20 * 60; /* don't merge manually added dives with anything */ if (same_string(a->dc.model, "manually added dive") || same_string(b->dc.model, "manually added dive")) return 0; /* * Do some basic sanity testing of the values we * have filled in during 'fixup_dive()' */ if (!similar(a->maxdepth.mm, b->maxdepth.mm, 1000) || (a->meandepth.mm && b->meandepth.mm && !similar(a->meandepth.mm, b->meandepth.mm, 1000)) || !a->duration.seconds || !b->duration.seconds || !similar(a->duration.seconds, b->duration.seconds, 5 * 60)) return 0; /* See if we can get an exact match on the dive computer */ match = match_dc_dive(&a->dc, &b->dc); if (match) return match > 0; /* * Allow a time difference due to dive computer time * setting etc. Check if they overlap. */ fuzz = MAX(a->duration.seconds, b->duration.seconds) / 2; if (fuzz < 60) fuzz = 60; return (a->when <= b->when + fuzz) && (a->when >= b->when - fuzz); } /* * This could do a lot more merging. Right now it really only * merges almost exact duplicates - something that happens easily * with overlapping dive downloads. * * If new dives are merged into the dive table, dive a is supposed to * be the old dive and dive b is supposed to be the newly imported * dive. If the flag "prefer_downloaded" is set, data of the latter * will take priority over the former. * * Attn: The dive_site parameter of the dive will be set, but the caller * still has to register the dive in the dive site! */ struct dive *try_to_merge(struct dive *a, struct dive *b, bool prefer_downloaded) { struct dive *res; struct dive_site *site; if (!likely_same_dive(a, b)) return NULL; res = merge_dives(a, b, 0, prefer_downloaded, NULL, &site); res->dive_site = site; /* Caller has to call add_dive_to_dive_site()! */ return res; } static int same_sample(struct sample *a, struct sample *b) { if (a->time.seconds != b->time.seconds) return 0; if (a->depth.mm != b->depth.mm) return 0; if (a->temperature.mkelvin != b->temperature.mkelvin) return 0; if (a->pressure[0].mbar != b->pressure[0].mbar) return 0; return a->sensor[0] == b->sensor[0]; } static int same_dc(struct divecomputer *a, struct divecomputer *b) { int i; const struct event *eva, *evb; i = match_one_dc(a, b); if (i) return i > 0; if (a->when && b->when && a->when != b->when) return 0; if (a->samples != b->samples) return 0; for (i = 0; i < a->samples; i++) if (!same_sample(a->sample + i, b->sample + i)) return 0; eva = a->events; evb = b->events; while (eva && evb) { if (!same_event(eva, evb)) return 0; eva = eva->next; evb = evb->next; } return eva == evb; } static int might_be_same_device(const struct divecomputer *a, const struct divecomputer *b) { /* No dive computer model? That matches anything */ if (!a->model || !b->model) return 1; /* Otherwise at least the model names have to match */ if (strcasecmp(a->model, b->model)) return 0; /* No device ID? Match */ if (!a->deviceid || !b->deviceid) return 1; return a->deviceid == b->deviceid; } static void remove_redundant_dc(struct divecomputer *dc, int prefer_downloaded) { do { struct divecomputer **p = &dc->next; /* Check this dc against all the following ones.. */ while (*p) { struct divecomputer *check = *p; if (same_dc(dc, check) || (prefer_downloaded && might_be_same_device(dc, check))) { *p = check->next; check->next = NULL; free_dc(check); continue; } p = &check->next; } /* .. and then continue down the chain, but we */ prefer_downloaded = 0; dc = dc->next; } while (dc); } static const struct divecomputer *find_matching_computer(const struct divecomputer *match, const struct divecomputer *list) { const struct divecomputer *p; while ((p = list) != NULL) { list = list->next; if (might_be_same_device(match, p)) break; } return p; } static void copy_dive_computer(struct divecomputer *res, const struct divecomputer *a) { *res = *a; res->model = copy_string(a->model); res->serial = copy_string(a->serial); res->fw_version = copy_string(a->fw_version); STRUCTURED_LIST_COPY(struct extra_data, a->extra_data, res->extra_data, copy_extra_data); res->samples = res->alloc_samples = 0; res->sample = NULL; res->events = NULL; res->next = NULL; } /* * Join dive computers with a specific time offset between * them. * * Use the dive computer ID's (or names, if ID's are missing) * to match them up. If we find a matching dive computer, we * merge them. If not, we just take the data from 'a'. */ static void interleave_dive_computers(struct dive *d, struct divecomputer *res, const struct divecomputer *a, const struct divecomputer *b, const int cylinders_map_a[], const int cylinders_map_b[], int offset) { do { const struct divecomputer *match; copy_dive_computer(res, a); match = find_matching_computer(a, b); if (match) { merge_events(d, res, a, match, cylinders_map_a, cylinders_map_b, offset); merge_samples(res, a, match, cylinders_map_a, cylinders_map_b, offset); merge_extra_data(res, a, match); /* Use the diveid of the later dive! */ if (offset > 0) res->diveid = match->diveid; } else { copy_dc_renumber(d, a, res, cylinders_map_a); } a = a->next; if (!a) break; res->next = calloc(1, sizeof(struct divecomputer)); res = res->next; } while (res); } /* * Join dive computer information. * * If we have old-style dive computer information (no model * name etc), we will prefer a new-style one and just throw * away the old. We're assuming it's a re-download. * * Otherwise, we'll just try to keep all the information, * unless the user has specified that they prefer the * downloaded computer, in which case we'll aggressively * try to throw out old information that *might* be from * that one. */ static void join_dive_computers(struct dive *d, struct divecomputer *res, const struct divecomputer *a, const struct divecomputer *b, const int cylinders_map_a[], const int cylinders_map_b[], int prefer_downloaded) { struct divecomputer *tmp; if (a->model && !b->model) { copy_dc_renumber(d, a, res, cylinders_map_a); return; } if (b->model && !a->model) { copy_dc_renumber(d, b, res, cylinders_map_b); return; } copy_dc_renumber(d, a, res, cylinders_map_a); tmp = res; while (tmp->next) tmp = tmp->next; tmp->next = calloc(1, sizeof(*tmp)); copy_dc_renumber(d, b, tmp->next, cylinders_map_b); remove_redundant_dc(res, prefer_downloaded); } // Does this dive have a dive computer for which is_dc_planner has value planned bool has_planned(const struct dive *dive, bool planned) { const struct divecomputer *dc = &dive->dc; while (dc) { if (is_dc_planner(&dive->dc) == planned) return true; dc = dc->next; } return false; } /* * Merging two dives can be subtle, because there's two different ways * of merging: * * (a) two distinctly _different_ dives that have the same dive computer * are merged into one longer dive, because the user asked for it * in the divelist. * * Because this case is with the same dive computer, we *know* the * two must have a different start time, and "offset" is the relative * time difference between the two. * * (b) two different dive computers that we might want to merge into * one single dive with multiple dive computers. * * This is the "try_to_merge()" case, which will have offset == 0, * even if the dive times might be different. * * If new dives are merged into the dive table, dive a is supposed to * be the old dive and dive b is supposed to be the newly imported * dive. If the flag "prefer_downloaded" is set, data of the latter * will take priority over the former. * * The trip the new dive should be associated with (if any) is returned * in the "trip" output parameter. * * The dive site the new dive should be added to (if any) is returned * in the "dive_site" output parameter. */ struct dive *merge_dives(const struct dive *a, const struct dive *b, int offset, bool prefer_downloaded, struct dive_trip **trip, struct dive_site **site) { struct dive *res = alloc_dive(); int *cylinders_map_a, *cylinders_map_b; if (offset) { /* * If "likely_same_dive()" returns true, that means that * it is *not* the same dive computer, and we do not want * to try to turn it into a single longer dive. So we'd * join them as two separate dive computers at zero offset. */ if (likely_same_dive(a, b)) offset = 0; } if (is_dc_planner(&a->dc)) { const struct dive *tmp = a; a = b; b = tmp; } res->when = prefer_downloaded ? b->when : a->when; res->selected = a->selected || b->selected; if (trip) *trip = get_preferred_trip(a, b); MERGE_TXT(res, a, b, notes, "\n--\n"); MERGE_TXT(res, a, b, buddy, ", "); MERGE_TXT(res, a, b, diveguide, ", "); MERGE_MAX(res, a, b, rating); MERGE_TXT(res, a, b, suit, ", "); MERGE_MAX(res, a, b, number); MERGE_NONZERO(res, a, b, visibility); MERGE_NONZERO(res, a, b, wavesize); MERGE_NONZERO(res, a, b, current); MERGE_NONZERO(res, a, b, surge); MERGE_NONZERO(res, a, b, chill); copy_pictures(a->pictures.nr ? &a->pictures : &b->pictures, &res->pictures); taglist_merge(&res->tag_list, a->tag_list, b->tag_list); /* if we get dives without any gas / cylinder information in an import, make sure * that there is at leatst one entry in the cylinder map for that dive */ cylinders_map_a = malloc(MAX(1, a->cylinders.nr) * sizeof(*cylinders_map_a)); cylinders_map_b = malloc(MAX(1, b->cylinders.nr) * sizeof(*cylinders_map_b)); merge_cylinders(res, a, b, cylinders_map_a, cylinders_map_b); merge_equipment(res, a, b); merge_temperatures(res, a, b); if (prefer_downloaded) { /* If we prefer downloaded, do those first, and get rid of "might be same" computers */ join_dive_computers(res, &res->dc, &b->dc, &a->dc, cylinders_map_b, cylinders_map_a, 1); } else if (offset && might_be_same_device(&a->dc, &b->dc)) interleave_dive_computers(res, &res->dc, &a->dc, &b->dc, cylinders_map_a, cylinders_map_b, offset); else join_dive_computers(res, &res->dc, &a->dc, &b->dc, cylinders_map_a, cylinders_map_b, 0); /* The CNS values will be recalculated from the sample in fixup_dive() */ res->cns = res->maxcns = 0; /* we take the first dive site, unless it's empty */ *site = a->dive_site && !dive_site_is_empty(a->dive_site) ? a->dive_site : b->dive_site; if (!dive_site_has_gps_location(*site) && dive_site_has_gps_location(b->dive_site)) { /* we picked the first dive site and that didn't have GPS data, but the new dive has * GPS data (that could be a download from a GPS enabled dive computer). * Keep the dive site, but add the GPS data */ (*site)->location = b->dive_site->location; } fixup_dive(res); free(cylinders_map_a); free(cylinders_map_b); return res; } // copy_dive(), but retaining the new ID for the copied dive static struct dive *create_new_copy(const struct dive *from) { struct dive *to = alloc_dive(); int id; // alloc_dive() gave us a new ID, we just need to // make sure it's not overwritten. id = to->id; copy_dive(from, to); to->id = id; return to; } struct start_end_pressure { pressure_t start; pressure_t end; }; static void force_fixup_dive(struct dive *d) { struct divecomputer *dc = &d->dc; int old_temp = dc->watertemp.mkelvin; int old_mintemp = d->mintemp.mkelvin; int old_maxtemp = d->maxtemp.mkelvin; duration_t old_duration = d->duration; struct start_end_pressure *old_pressures = malloc(d->cylinders.nr * sizeof(*old_pressures)); d->maxdepth.mm = 0; dc->maxdepth.mm = 0; d->watertemp.mkelvin = 0; dc->watertemp.mkelvin = 0; d->duration.seconds = 0; d->maxtemp.mkelvin = 0; d->mintemp.mkelvin = 0; for (int i = 0; i < d->cylinders.nr; i++) { cylinder_t *cyl = get_cylinder(d, i); old_pressures[i].start = cyl->start; old_pressures[i].end = cyl->end; cyl->start.mbar = 0; cyl->end.mbar = 0; } fixup_dive(d); if (!d->watertemp.mkelvin) d->watertemp.mkelvin = old_temp; if (!dc->watertemp.mkelvin) dc->watertemp.mkelvin = old_temp; if (!d->maxtemp.mkelvin) d->maxtemp.mkelvin = old_maxtemp; if (!d->mintemp.mkelvin) d->mintemp.mkelvin = old_mintemp; if (!d->duration.seconds) d->duration = old_duration; for (int i = 0; i < d->cylinders.nr; i++) { if (!get_cylinder(d, i)->start.mbar) get_cylinder(d, i)->start = old_pressures[i].start; if (!get_cylinder(d, i)->end.mbar) get_cylinder(d, i)->end = old_pressures[i].end; } free(old_pressures); } /* * Split a dive that has a surface interval from samples 'a' to 'b' * into two dives, but don't add them to the log yet. * Returns the nr of the old dive or <0 on failure. * Moreover, on failure both output dives are set to NULL. * On success, the newly allocated dives are returned in out1 and out2. */ static int split_dive_at(const struct dive *dive, int a, int b, struct dive **out1, struct dive **out2) { int i, nr; uint32_t t; struct dive *d1, *d2; struct divecomputer *dc1, *dc2; struct event *event, **evp; /* if we can't find the dive in the dive list, don't bother */ if ((nr = get_divenr(dive)) < 0) return -1; /* Splitting should leave at least 3 samples per dive */ if (a < 3 || b > dive->dc.samples - 4) return -1; /* We're not trying to be efficient here.. */ d1 = create_new_copy(dive); d2 = create_new_copy(dive); d1->divetrip = d2->divetrip = 0; /* now unselect the first first segment so we don't keep all * dives selected by mistake. But do keep the second one selected * so the algorithm keeps splitting the dive further */ d1->selected = false; dc1 = &d1->dc; dc2 = &d2->dc; /* * Cut off the samples of d1 at the beginning * of the interval. */ dc1->samples = a; /* And get rid of the 'b' first samples of d2 */ dc2->samples -= b; memmove(dc2->sample, dc2->sample+b, dc2->samples * sizeof(struct sample)); /* Now the secondary dive computers */ t = dc2->sample[0].time.seconds; while ((dc1 = dc1->next)) { i = 0; while (dc1->samples < i && dc1->sample[i].time.seconds <= t) ++i; dc1->samples = i; } while ((dc2 = dc2->next)) { i = 0; while (dc2->samples < i && dc2->sample[i].time.seconds < t) ++i; dc2->samples -= i; memmove(dc2->sample, dc2->sample + i, dc2->samples * sizeof(struct sample)); } dc1 = &d1->dc; dc2 = &d2->dc; /* * This is where we cut off events from d1, * and shift everything in d2 */ d2->when += t; while (dc1 && dc2) { dc2->when += t; for (i = 0; i < dc2->samples; i++) dc2->sample[i].time.seconds -= t; /* Remove the events past 't' from d1 */ evp = &dc1->events; while ((event = *evp) != NULL && event->time.seconds < t) evp = &event->next; *evp = NULL; while (event) { struct event *next = event->next; free(event); event = next; } /* Remove the events before 't' from d2, and shift the rest */ evp = &dc2->events; while ((event = *evp) != NULL) { if (event->time.seconds < t) { *evp = event->next; free(event); } else { event->time.seconds -= t; } } dc1 = dc1->next; dc2 = dc2->next; } force_fixup_dive(d1); force_fixup_dive(d2); /* * Was the dive numbered? If it was the last dive, then we'll * increment the dive number for the tail part that we split off. * Otherwise the tail is unnumbered. */ if (d2->number) { if (dive_table.nr == nr + 1) d2->number++; else d2->number = 0; } *out1 = d1; *out2 = d2; return nr; } /* in freedive mode we split for as little as 10 seconds on the surface, * otherwise we use a minute */ static bool should_split(const struct divecomputer *dc, int t1, int t2) { int threshold = dc->divemode == FREEDIVE ? 10 : 60; return t2 - t1 >= threshold; } /* * Try to split a dive into multiple dives at a surface interval point. * * NOTE! We will split when there is at least one surface event that has * non-surface events on both sides. * * The surface interval points are determined using the first dive computer. * * In other words, this is a (simplified) reversal of the dive merging. */ int split_dive(const struct dive *dive, struct dive **new1, struct dive **new2) { int i; int at_surface, surface_start; const struct divecomputer *dc; *new1 = *new2 = NULL; if (!dive) return -1; dc = &dive->dc; surface_start = 0; at_surface = 1; for (i = 1; i < dc->samples; i++) { struct sample *sample = dc->sample+i; int surface_sample = sample->depth.mm < SURFACE_THRESHOLD; /* * We care about the transition from and to depth 0, * not about the depth staying similar. */ if (at_surface == surface_sample) continue; at_surface = surface_sample; // Did it become surface after having been non-surface? We found the start if (at_surface) { surface_start = i; continue; } // Going down again? We want at least a minute from // the surface start. if (!surface_start) continue; if (!should_split(dc, dc->sample[surface_start].time.seconds, sample[-1].time.seconds)) continue; return split_dive_at(dive, surface_start, i-1, new1, new2); } return -1; } int split_dive_at_time(const struct dive *dive, duration_t time, struct dive **new1, struct dive **new2) { int i = 0; if (!dive) return -1; struct sample *sample = dive->dc.sample; *new1 = *new2 = NULL; while(sample->time.seconds < time.seconds) { ++sample; ++i; if (dive->dc.samples == i) return -1; } return split_dive_at(dive, i, i - 1, new1, new2); } /* * "dc_maxtime()" is how much total time this dive computer * has for this dive. Note that it can differ from "duration" * if there are surface events in the middle. * * Still, we do ignore all but the last surface samples from the * end, because some divecomputers just generate lots of them. */ static inline int dc_totaltime(const struct divecomputer *dc) { int time = dc->duration.seconds; int nr = dc->samples; while (nr--) { struct sample *s = dc->sample + nr; time = s->time.seconds; if (s->depth.mm >= SURFACE_THRESHOLD) break; } return time; } /* * The end of a dive is actually not trivial, because "duration" * is not the duration until the end, but the time we spend under * water, which can be very different if there are surface events * during the dive. * * So walk the dive computers, looking for the longest actual * time in the samples (and just default to the dive duration if * there are no samples). */ static inline int dive_totaltime(const struct dive *dive) { int time = dive->duration.seconds; const struct divecomputer *dc; for_each_relevant_dc(dive, dc) { int dc_time = dc_totaltime(dc); if (dc_time > time) time = dc_time; } return time; } timestamp_t dive_endtime(const struct dive *dive) { return dive->when + dive_totaltime(dive); } bool time_during_dive_with_offset(const struct dive *dive, timestamp_t when, timestamp_t offset) { timestamp_t start = dive->when; timestamp_t end = dive_endtime(dive); return start - offset <= when && when <= end + offset; } /* this sets a usually unused copy of the preferences with the units * that were active the last time the dive list was saved to git storage * (this isn't used in XML files); storing the unit preferences in the * data file is usually pointless (that's a setting of the software, * not a property of the data), but it's a great hint of what the user * might expect to see when creating a backend service that visualizes * the dive list without Subsurface running - so this is basically a * functionality for the core library that Subsurface itself doesn't * use but that another consumer of the library (like an HTML exporter) * will need */ void set_informational_units(const char *units) { if (strstr(units, "METRIC")) { git_prefs.unit_system = METRIC; } else if (strstr(units, "IMPERIAL")) { git_prefs.unit_system = IMPERIAL; } else if (strstr(units, "PERSONALIZE")) { git_prefs.unit_system = PERSONALIZE; if (strstr(units, "METERS")) git_prefs.units.length = METERS; if (strstr(units, "FEET")) git_prefs.units.length = FEET; if (strstr(units, "LITER")) git_prefs.units.volume = LITER; if (strstr(units, "CUFT")) git_prefs.units.volume = CUFT; if (strstr(units, "BAR")) git_prefs.units.pressure = BAR; if (strstr(units, "PSI")) git_prefs.units.pressure = PSI; if (strstr(units, "CELSIUS")) git_prefs.units.temperature = CELSIUS; if (strstr(units, "FAHRENHEIT")) git_prefs.units.temperature = FAHRENHEIT; if (strstr(units, "KG")) git_prefs.units.weight = KG; if (strstr(units, "LBS")) git_prefs.units.weight = LBS; if (strstr(units, "SECONDS")) git_prefs.units.vertical_speed_time = SECONDS; if (strstr(units, "MINUTES")) git_prefs.units.vertical_speed_time = MINUTES; } } void set_git_prefs(const char *prefs) { if (strstr(prefs, "TANKBAR")) git_prefs.tankbar = 1; if (strstr(prefs, "DCCEILING")) git_prefs.dcceiling = 1; if (strstr(prefs, "SHOW_SETPOINT")) git_prefs.show_ccr_setpoint = 1; if (strstr(prefs, "SHOW_SENSORS")) git_prefs.show_ccr_sensors = 1; if (strstr(prefs, "PO2_GRAPH")) git_prefs.pp_graphs.po2 = 1; } /* clones a dive and moves given dive computer to front */ struct dive *make_first_dc(const struct dive *d, int dc_number) { struct dive *res; struct divecomputer *dc, *newdc, *old_dc; /* copy the dive */ res = alloc_dive(); copy_dive(d, res); /* make a new unique id, since we still can't handle two equal ids */ res->id = dive_getUniqID(); if (dc_number == 0) return res; dc = &res->dc; newdc = malloc(sizeof(*newdc)); old_dc = get_dive_dc(res, dc_number); /* skip the current DC in the linked list */ for (dc = &res->dc; dc && dc->next != old_dc; dc = dc->next) ; if (!dc) { free(newdc); fprintf(stderr, "data inconsistent: can't find the current DC"); return res; } dc->next = old_dc->next; *newdc = res->dc; res->dc = *old_dc; res->dc.next = newdc; free(old_dc); return res; } static void delete_divecomputer(struct dive *d, int num) { int i; /* Refuse to delete the last dive computer */ if (!d->dc.next) return; if (num == 0) { /* remove the first one, so copy the second one in place of the first and free the second one * be careful about freeing the no longer needed structures - since we copy things around we can't use free_dc()*/ struct divecomputer *fdc = d->dc.next; free_dc_contents(&d->dc); memcpy(&d->dc, fdc, sizeof(struct divecomputer)); free(fdc); } else { struct divecomputer *pdc = &d->dc; for (i = 0; i < num - 1 && pdc; i++) pdc = pdc->next; if (pdc && pdc->next) { struct divecomputer *dc = pdc->next; pdc->next = dc->next; free_dc(dc); } } } /* Clone a dive and delete goven dive computer */ struct dive *clone_delete_divecomputer(const struct dive *d, int dc_number) { struct dive *res; /* copy the dive */ res = alloc_dive(); copy_dive(d, res); /* make a new unique id, since we still can't handle two equal ids */ res->id = dive_getUniqID(); delete_divecomputer(res, dc_number); force_fixup_dive(res); return res; } /* * This splits the dive src by dive computer. The first output dive has all * dive computers except num, the second only dive computer num. * The dives will not be associated with a trip. * On error, both output parameters are set to NULL. */ void split_divecomputer(const struct dive *src, int num, struct dive **out1, struct dive **out2) { const struct divecomputer *srcdc = get_dive_dc_const(src, num); if (src && srcdc) { // Copy the dive, but only using the selected dive computer *out2 = alloc_dive(); copy_dive_onedc(src, srcdc, *out2); // This will also make fixup_dive() to allocate a new dive id... (*out2)->id = 0; fixup_dive(*out2); // Copy the dive with all dive computers *out1 = create_new_copy(src); // .. and then delete the split-out dive computer delete_divecomputer(*out1, num); (*out1)->divetrip = (*out2)->divetrip = NULL; } else { *out1 = *out2 = NULL; } } //Calculate O2 in best mix fraction_t best_o2(depth_t depth, const struct dive *dive, bool in_planner) { fraction_t fo2; int po2 = in_planner ? prefs.bottompo2 : (int)(prefs.modpO2 * 1000.0); fo2.permille = (po2 * 100 / depth_to_mbar(depth.mm, dive)) * 10; //use integer arithmetic to round down to nearest percent // Don't permit >100% O2 if (fo2.permille > 1000) fo2.permille = 1000; return fo2; } //Calculate He in best mix. O2 is considered narcopic fraction_t best_he(depth_t depth, const struct dive *dive, bool o2narcotic, fraction_t fo2) { fraction_t fhe; int pnarcotic, ambient; pnarcotic = depth_to_mbar(prefs.bestmixend.mm, dive); ambient = depth_to_mbar(depth.mm, dive); if (o2narcotic) { fhe.permille = (100 - 100 * pnarcotic / ambient) * 10; //use integer arithmetic to round up to nearest percent } else { fhe.permille = 1000 - fo2.permille - N2_IN_AIR * pnarcotic / ambient; } if (fhe.permille < 0) fhe.permille = 0; return fhe; } void invalidate_dive_cache(struct dive *dive) { memset(dive->git_id, 0, 20); } bool dive_cache_is_valid(const struct dive *dive) { static const unsigned char null_id[20] = { 0, }; return !!memcmp(dive->git_id, null_id, 20); } int get_surface_pressure_in_mbar(const struct dive *dive, bool non_null) { int mbar = dive->surface_pressure.mbar; if (!mbar && non_null) mbar = SURFACE_PRESSURE; return mbar; } /* This returns the conversion factor that you need to multiply * a (relative) depth in mm to obtain a (relative) pressure in mbar. * As everywhere in Subsurface, the expected unit of a salinity is * g/10l such that sea water has a salinity of 10300 */ static double salinity_to_specific_weight(int salinity) { return salinity * 0.981 / 100000.0; } /* Pa = N/m^2 - so we determine the weight (in N) of the mass of 10m * of water (and use standard salt water at 1.03kg per liter if we don't know salinity) * and add that to the surface pressure (or to 1013 if that's unknown) */ static double calculate_depth_to_mbarf(int depth, pressure_t surface_pressure, int salinity) { double specific_weight; int mbar = surface_pressure.mbar; if (!mbar) mbar = SURFACE_PRESSURE; if (!salinity) salinity = SEAWATER_SALINITY; if (salinity < 500) salinity += FRESHWATER_SALINITY; specific_weight = salinity_to_specific_weight(salinity); return mbar + depth * specific_weight; } int depth_to_mbar(int depth, const struct dive *dive) { return lrint(calculate_depth_to_mbarf(depth, dive->surface_pressure, dive->salinity)); } double depth_to_mbarf(int depth, const struct dive *dive) { return calculate_depth_to_mbarf(depth, dive->surface_pressure, dive->salinity); } double depth_to_bar(int depth, const struct dive *dive) { return depth_to_mbar(depth, dive) / 1000.0; } double depth_to_atm(int depth, const struct dive *dive) { return mbar_to_atm(depth_to_mbar(depth, dive)); } /* for the inverse calculation we use just the relative pressure * (that's the one that some dive computers like the Uemis Zurich * provide - for the other models that do this libdivecomputer has to * take care of this, but the Uemis we support natively */ int rel_mbar_to_depth(int mbar, const struct dive *dive) { double specific_weight = salinity_to_specific_weight(SEAWATER_SALINITY); if (dive->dc.salinity) specific_weight = salinity_to_specific_weight(dive->dc.salinity); /* whole mbar gives us cm precision */ return (int)lrint(mbar / specific_weight); } int mbar_to_depth(int mbar, const struct dive *dive) { pressure_t surface_pressure; if (dive->surface_pressure.mbar) surface_pressure = dive->surface_pressure; else surface_pressure.mbar = SURFACE_PRESSURE; return rel_mbar_to_depth(mbar - surface_pressure.mbar, dive); } /* MOD rounded to multiples of roundto mm */ depth_t gas_mod(struct gasmix mix, pressure_t po2_limit, const struct dive *dive, int roundto) { depth_t rounded_depth; double depth = (double) mbar_to_depth(po2_limit.mbar * 1000 / get_o2(mix), dive); rounded_depth.mm = (int)lrint(depth / roundto) * roundto; return rounded_depth; } /* Maximum narcotic depth rounded to multiples of roundto mm */ depth_t gas_mnd(struct gasmix mix, depth_t end, const struct dive *dive, int roundto) { depth_t rounded_depth; pressure_t ppo2n2; ppo2n2.mbar = depth_to_mbar(end.mm, dive); int maxambient = prefs.o2narcotic ? (int)lrint(ppo2n2.mbar / (1 - get_he(mix) / 1000.0)) : get_n2(mix) > 0 ? (int)lrint(ppo2n2.mbar * N2_IN_AIR / get_n2(mix)) : // Actually: Infinity 1000000; rounded_depth.mm = (int)lrint(((double)mbar_to_depth(maxambient, dive)) / roundto) * roundto; return rounded_depth; } struct dive *get_dive(int nr) { if (nr >= dive_table.nr || nr < 0) return NULL; return dive_table.dives[nr]; } struct dive_site *get_dive_site_for_dive(const struct dive *dive) { return dive->dive_site; } const char *get_dive_country(const struct dive *dive) { struct dive_site *ds = dive->dive_site; return ds ? taxonomy_get_country(&ds->taxonomy) : NULL; } const char *get_dive_location(const struct dive *dive) { const struct dive_site *ds = dive->dive_site; if (ds && ds->name) return ds->name; return NULL; } unsigned int number_of_computers(const struct dive *dive) { unsigned int total_number = 0; const struct divecomputer *dc = &dive->dc; if (!dive) return 1; do { total_number++; dc = dc->next; } while (dc); return total_number; } struct divecomputer *get_dive_dc(struct dive *dive, int nr) { struct divecomputer *dc; if (!dive) return NULL; dc = &dive->dc; while (nr-- > 0) { dc = dc->next; if (!dc) return &dive->dc; } return dc; } const struct divecomputer *get_dive_dc_const(const struct dive *dive, int nr) { return get_dive_dc((struct dive *)dive, nr); } struct dive *get_dive_by_uniq_id(int id) { int i; struct dive *dive = NULL; for_each_dive (i, dive) { if (dive->id == id) break; } #ifdef DEBUG if (dive == NULL) { fprintf(stderr, "Invalid id %x passed to get_dive_by_diveid, try to fix the code\n", id); exit(1); } #endif return dive; } int get_idx_by_uniq_id(int id) { int i; struct dive *dive = NULL; for_each_dive (i, dive) { if (dive->id == id) break; } #ifdef DEBUG if (dive == NULL) { fprintf(stderr, "Invalid id %x passed to get_dive_by_diveid, try to fix the code\n", id); exit(1); } #endif return i; } bool dive_site_has_gps_location(const struct dive_site *ds) { return ds && has_location(&ds->location); } int dive_has_gps_location(const struct dive *dive) { if (!dive) return false; return dive_site_has_gps_location(dive->dive_site); } /* Extract GPS location of a dive computer stored in the GPS1 * or GPS2 extra data fields */ static location_t dc_get_gps_location(const struct divecomputer *dc) { location_t res = { }; for (struct extra_data *data = dc->extra_data; data; data = data->next) { if (!strcmp(data->key, "GPS1")) { parse_location(data->value, &res); /* If we found a valid GPS1 field exit early since * it has priority over GPS2 */ if (has_location(&res)) break; } else if (!strcmp(data->key, "GPS2")) { /* For GPS2 fields continue searching, as we might * still find a GPS1 field */ parse_location(data->value, &res); } } return res; } /* Get GPS location for a dive. Highest priority is given to the GPS1 * extra data written by libdivecomputer, as this comes from a real GPS * device. If that doesn't exits, use the currently set dive site. * This function is potentially slow, therefore only call sparingly * and remember the result. */ location_t dive_get_gps_location(const struct dive *d) { location_t res = { }; for (const struct divecomputer *dc = &d->dc; dc; dc = dc->next) { res = dc_get_gps_location(dc); if (has_location(&res)) return res; } /* No libdivecomputer generated GPS data found. * Let's use the location of the current dive site. */ if (d->dive_site) res = d->dive_site->location; return res; } /* When evaluated at the time of a gasswitch, this returns the new gas */ struct gasmix get_gasmix(const struct dive *dive, const struct divecomputer *dc, int time, const struct event **evp, struct gasmix gasmix) { const struct event *ev = *evp; struct gasmix res; /* if there is no cylinder, return air */ if (dive->cylinders.nr <= 0) return gasmix_air; if (!ev) { /* on first invocation, get initial gas mix and first event (if any) */ int cyl = explicit_first_cylinder(dive, dc); res = get_cylinder(dive, cyl)->gasmix; ev = dc ? get_next_event(dc->events, "gaschange") : NULL; } else { res = gasmix; } while (ev && ev->time.seconds <= time) { res = get_gasmix_from_event(dive, ev); ev = get_next_event(ev->next, "gaschange"); } *evp = ev; return res; } /* get the gas at a certain time during the dive */ /* If there is a gasswitch at that time, it returns the new gasmix */ struct gasmix get_gasmix_at_time(const struct dive *d, const struct divecomputer *dc, duration_t time) { const struct event *ev = NULL; struct gasmix gasmix = gasmix_air; return get_gasmix(d, dc, time.seconds, &ev, gasmix); } /* Does that cylinder have any pressure readings? */ extern bool cylinder_with_sensor_sample(const struct dive *dive, int cylinder_id) { for (const struct divecomputer *dc = &dive->dc; dc; dc = dc->next) { for (int i = 0; i < dc->samples; ++i) { struct sample *sample = dc->sample + i; for (int j = 0; j < MAX_SENSORS; ++j) { if (!sample->pressure[j].mbar) continue; if (sample->sensor[j] == cylinder_id) return true; } } } return false; }
subsurface-for-dirk-master
core/dive.c
// SPDX-License-Identifier: GPL-2.0 /* planner.c * * code that allows us to plan future dives * * (c) Dirk Hohndel 2013 */ #include <assert.h> #include <unistd.h> #include <ctype.h> #include <string.h> #include "dive.h" #include "deco.h" #include "units.h" #include "divelist.h" #include "planner.h" #include "gettext.h" #include "libdivecomputer/parser.h" #include "qthelper.h" #include "format.h" #include "version.h" #include "membuffer.h" static int diveplan_duration(struct diveplan *diveplan) { struct divedatapoint *dp = diveplan->dp; int duration = 0; int lastdepth = 0; while(dp) { if (dp->time > duration && (dp->depth.mm > SURFACE_THRESHOLD || lastdepth > SURFACE_THRESHOLD)) { duration = dp->time; lastdepth = dp->depth.mm; } dp = dp->next; } return (duration + 30) / 60; } /* Add the icd results of one trimix gas change to the dive plan html buffer. Two rows are added to the table, one * indicating fractions of gas, the other indication partial pressures of gas. This function makes use of the * icd_data structure that was filled with information by the function isobaric_counterdiffusion(). * Parameters: 1) Pointer to the output buffer position at which writing should start. * 2) The size of the part of the unused output buffer that remains unused. * 3) The data structure containing icd calculation results: icdvalues. * 4) A boolean value indicating whether a table header should be written before the data. Only during 1st call. * 5) Pointers to gas mixes in the gas change: gas-from and gas-to. * Returns: The size of the output buffer that has been used after the new results have been added. */ static void add_icd_entry(struct membuffer *b, struct icd_data *icdvalues, bool printheader, int time_seconds, int ambientpressure_mbar, struct gasmix gas_from, struct gasmix gas_to) { if (printheader) { // Create a table description and a table header if no icd data have been written yet. put_format(b, "<div>%s:", translate("gettextFromC","Isobaric counterdiffusion information")); put_format(b, "<table><tr><td align='left'><b>%s</b></td>", translate("gettextFromC", "runtime")); put_format(b, "<td align='center'><b>%s</b></td>", translate("gettextFromC", "gaschange")); put_format(b, "<td style='padding-left: 15px;'><b>%s</b></td>", translate("gettextFromC", "&#916;He")); put_format(b, "<td style='padding-left: 20px;'><b>%s</b></td>", translate("gettextFromC", "&#916;N&#8322;")); put_format(b, "<td style='padding-left: 10px;'><b>%s</b></td></tr>", translate("gettextFromC", "max &#916;N&#8322;")); } // Add one entry to the icd table: put_format_loc(b, "<tr><td rowspan='2' style= 'vertical-align:top;'>%3d%s</td>" "<td rowspan=2 style= 'vertical-align:top;'>%s&#10137;", (time_seconds + 30) / 60, translate("gettextFromC", "min"), gasname(gas_from)); put_format_loc(b, "%s</td><td style='padding-left: 10px;'>%+5.1f%%</td>" "<td style= 'padding-left: 15px; color:%s;'>%+5.1f%%</td>" "<td style='padding-left: 15px;'>%+5.1f%%</td></tr>" "<tr><td style='padding-left: 10px;'>%+5.2f%s</td>" "<td style='padding-left: 15px; color:%s;'>%+5.2f%s</td>" "<td style='padding-left: 15px;'>%+5.2f%s</td></tr>", gasname(gas_to), icdvalues->dHe / 10.0, ((5 * icdvalues->dN2) > -icdvalues->dHe) ? "red" : "#383838", icdvalues->dN2 / 10.0 , 0.2 * (-icdvalues->dHe / 10.0), ambientpressure_mbar * icdvalues->dHe / 1e6f, translate("gettextFromC", "bar"), ((5 * icdvalues->dN2) > -icdvalues->dHe) ? "red" : "#383838", ambientpressure_mbar * icdvalues->dN2 / 1e6f, translate("gettextFromC", "bar"), ambientpressure_mbar * -icdvalues->dHe / 5e6f, translate("gettextFromC", "bar")); } const char *get_planner_disclaimer() { return translate("gettextFromC", "DISCLAIMER / WARNING: THIS IMPLEMENTATION OF THE %s " "ALGORITHM AND A DIVE PLANNER IMPLEMENTATION BASED ON THAT HAS " "RECEIVED ONLY A LIMITED AMOUNT OF TESTING. WE STRONGLY RECOMMEND NOT TO " "PLAN DIVES SIMPLY BASED ON THE RESULTS GIVEN HERE."); } /* Returns newly allocated buffer. Must be freed by caller */ char *get_planner_disclaimer_formatted() { struct membuffer buf = { 0 }; const char *deco = decoMode(true) == VPMB ? translate("gettextFromC", "VPM-B") : translate("gettextFromC", "BUHLMANN"); put_format(&buf, get_planner_disclaimer(), deco); return detach_cstring(&buf); } void add_plan_to_notes(struct diveplan *diveplan, struct dive *dive, bool show_disclaimer, int error) { struct membuffer buf = { 0 }; struct membuffer icdbuf = { 0 }; const char *segmentsymbol; int lastdepth = 0, lasttime = 0, lastsetpoint = -1, newdepth = 0, lastprintdepth = 0, lastprintsetpoint = -1; struct gasmix lastprintgasmix = gasmix_invalid; struct divedatapoint *dp = diveplan->dp; bool plan_verbatim = prefs.verbatim_plan; bool plan_display_runtime = prefs.display_runtime; bool plan_display_duration = prefs.display_duration; bool plan_display_transitions = prefs.display_transitions; bool gaschange_after = !plan_verbatim; bool gaschange_before; bool rebreatherchange_after = !plan_verbatim; bool rebreatherchange_before; enum divemode_t lastdivemode = UNDEF_COMP_TYPE; bool lastentered = true; bool icdwarning = false, icdtableheader = true; struct divedatapoint *nextdp = NULL; struct divedatapoint *lastbottomdp = NULL; struct icd_data icdvalues; char *temp; if (!dp) return; if (error) { put_format(&buf, "<span style='color: red;'>%s </span> %s<br/>", translate("gettextFromC", "Warning:"), translate("gettextFromC", "Decompression calculation aborted due to excessive time")); goto finished; } if (show_disclaimer) { char *disclaimer = get_planner_disclaimer_formatted(); put_string(&buf, "<div><b>"); put_string(&buf, disclaimer); put_string(&buf, "</b><br/>\n</div>\n"); free(disclaimer); } put_string(&buf, "<div>\n<b>"); if (diveplan->surface_interval < 0) { put_format(&buf, "%s (%s) %s", translate("gettextFromC", "Subsurface"), subsurface_canonical_version(), translate("gettextFromC", "dive plan</b> (overlapping dives detected)")); goto finished; } else if (diveplan->surface_interval >= 48 * 60 *60) { char *current_date = get_current_date(); put_format(&buf, "%s (%s) %s %s", translate("gettextFromC", "Subsurface"), subsurface_canonical_version(), translate("gettextFromC", "dive plan</b> created on"), current_date); free(current_date); } else { char *current_date = get_current_date(); put_format_loc(&buf, "%s (%s) %s %d:%02d) %s %s", translate("gettextFromC", "Subsurface"), subsurface_canonical_version(), translate("gettextFromC", "dive plan</b> (surface interval "), FRACTION(diveplan->surface_interval / 60, 60), translate("gettextFromC", "created on"), current_date); free(current_date); } put_string(&buf, "<br/>\n"); if (prefs.display_variations && decoMode(true) != RECREATIONAL) put_format_loc(&buf, translate("gettextFromC", "Runtime: %dmin%s"), diveplan_duration(diveplan), "VARIATIONS"); else put_format_loc(&buf, translate("gettextFromC", "Runtime: %dmin%s"), diveplan_duration(diveplan), ""); put_string(&buf, "<br/>\n</div>\n"); if (!plan_verbatim) { put_format(&buf, "<table>\n<thead>\n<tr><th></th><th>%s</th>", translate("gettextFromC", "depth")); if (plan_display_duration) put_format(&buf, "<th style='padding-left: 10px;'>%s</th>", translate("gettextFromC", "duration")); if (plan_display_runtime) put_format(&buf, "<th style='padding-left: 10px;'>%s</th>", translate("gettextFromC", "runtime")); put_format(&buf, "<th style='padding-left: 10px; float: left;'>%s</th></tr>\n</thead>\n<tbody style='float: left;'>\n", translate("gettextFromC", "gas")); } do { struct gasmix gasmix, newgasmix = {}; const char *depth_unit; double depthvalue; int decimals; bool isascent = (dp->depth.mm < lastdepth); nextdp = dp->next; if (dp->time == 0) continue; gasmix = get_cylinder(dive, dp->cylinderid)->gasmix; depthvalue = get_depth_units(dp->depth.mm, &decimals, &depth_unit); /* analyze the dive points ahead */ while (nextdp && nextdp->time == 0) nextdp = nextdp->next; if (nextdp) newgasmix = get_cylinder(dive, nextdp->cylinderid)->gasmix; gaschange_after = (nextdp && (gasmix_distance(gasmix, newgasmix))); gaschange_before = (gasmix_distance(lastprintgasmix, gasmix)); rebreatherchange_after = (nextdp && (dp->setpoint != nextdp->setpoint || dp->divemode != nextdp->divemode)); rebreatherchange_before = lastprintsetpoint != dp->setpoint || lastdivemode != dp->divemode; /* do we want to skip this leg as it is devoid of anything useful? */ if (!dp->entered && nextdp && dp->depth.mm != lastdepth && nextdp->depth.mm != dp->depth.mm && !gaschange_before && !gaschange_after && !rebreatherchange_before && !rebreatherchange_after) continue; // Ignore final surface segment for notes if (lastdepth == 0 && dp->depth.mm == 0 && !dp->next) continue; if ((dp->time - lasttime < 10 && lastdepth == dp->depth.mm) && !(gaschange_after && dp->next && dp->depth.mm != dp->next->depth.mm)) continue; /* Store pointer to last entered datapoint for minimum gas calculation */ if (dp->entered && !nextdp->entered) lastbottomdp = dp; if (plan_verbatim) { /* When displaying a verbatim plan, we output a waypoint for every gas change. * Therefore, we do not need to test for difficult cases that mean we need to * print a segment just so we don't miss a gas change. This makes the logic * to determine whether or not to print a segment much simpler than with the * non-verbatim plan. */ if (dp->depth.mm != lastprintdepth) { if (plan_display_transitions || dp->entered || !dp->next || (gaschange_after && dp->next && dp->depth.mm != nextdp->depth.mm)) { if (dp->setpoint) { put_format_loc(&buf, translate("gettextFromC", "%s to %.*f %s in %d:%02d min - runtime %d:%02u on %s (SP = %.1fbar)"), dp->depth.mm < lastprintdepth ? translate("gettextFromC", "Ascend") : translate("gettextFromC", "Descend"), decimals, depthvalue, depth_unit, FRACTION(dp->time - lasttime, 60), FRACTION(dp->time, 60), gasname(gasmix), (double) dp->setpoint / 1000.0); } else { put_format_loc(&buf, translate("gettextFromC", "%s to %.*f %s in %d:%02d min - runtime %d:%02u on %s"), dp->depth.mm < lastprintdepth ? translate("gettextFromC", "Ascend") : translate("gettextFromC", "Descend"), decimals, depthvalue, depth_unit, FRACTION(dp->time - lasttime, 60), FRACTION(dp->time, 60), gasname(gasmix)); } put_string(&buf, "<br/>\n"); } newdepth = dp->depth.mm; lasttime = dp->time; } else { if ((nextdp && dp->depth.mm != nextdp->depth.mm) || gaschange_after) { if (dp->setpoint) { put_format_loc(&buf, translate("gettextFromC", "Stay at %.*f %s for %d:%02d min - runtime %d:%02u on %s (SP = %.1fbar CCR)"), decimals, depthvalue, depth_unit, FRACTION(dp->time - lasttime, 60), FRACTION(dp->time, 60), gasname(gasmix), (double) dp->setpoint / 1000.0); } else { put_format_loc(&buf, translate("gettextFromC", "Stay at %.*f %s for %d:%02d min - runtime %d:%02u on %s %s"), decimals, depthvalue, depth_unit, FRACTION(dp->time - lasttime, 60), FRACTION(dp->time, 60), gasname(gasmix), translate("gettextFromC", divemode_text_ui[dp->divemode])); } put_string(&buf, "<br/>\n"); newdepth = dp->depth.mm; lasttime = dp->time; } } } else { /* When not displaying the verbatim dive plan, we typically ignore ascents between deco stops, * unless the display transitions option has been selected. We output a segment if any of the * following conditions are met. * 1) Display transitions is selected * 2) The segment was manually entered * 3) It is the last segment of the dive * 4) The segment is not an ascent, there was a gas change at the start of the segment and the next segment * is a change in depth (typical deco stop) * 5) There is a gas change at the end of the segment and the last segment was entered (first calculated * segment if it ends in a gas change) * 6) There is a gaschange after but no ascent. This should only occur when backgas breaks option is selected * 7) It is an ascent ending with a gas change, but is not followed by a stop. As case 5 already matches * the first calculated ascent if it ends with a gas change, this should only occur if a travel gas is * used for a calculated ascent, there is a subsequent gas change before the first deco stop, and zero * time has been allowed for a gas switch. */ if (plan_display_transitions || dp->entered || !dp->next || (nextdp && dp->depth.mm != nextdp->depth.mm) || (!isascent && (gaschange_before || rebreatherchange_before) && nextdp && dp->depth.mm != nextdp->depth.mm) || ((gaschange_after || rebreatherchange_after) && lastentered) || ((gaschange_after || rebreatherchange_after)&& !isascent) || (isascent && (gaschange_after || rebreatherchange_after) && nextdp && dp->depth.mm != nextdp->depth.mm ) || (lastentered && !dp->entered && dp->next->depth.mm == dp->depth.mm)) { // Print a symbol to indicate whether segment is an ascent, descent, constant depth (user entered) or deco stop if (isascent) segmentsymbol = "&#10138;"; // up-right arrow for ascent else if (dp->depth.mm > lastdepth) segmentsymbol = "&#10136;"; // down-right arrow for descent else if (dp->entered) segmentsymbol = "&#10137;"; // right arrow for entered entered segment at constant depth else segmentsymbol = "-"; // minus sign (a.k.a. horizontal line) for deco stop put_format(&buf, "<tr><td style='padding-left: 10px; float: right;'>%s</td>", segmentsymbol); asprintf_loc(&temp, translate("gettextFromC", "%3.0f%s"), depthvalue, depth_unit); put_format(&buf, "<td style='padding-left: 10px; float: right;'>%s</td>", temp); free(temp); if (plan_display_duration) { asprintf_loc(&temp, translate("gettextFromC", "%3dmin"), (dp->time - lasttime + 30) / 60); put_format(&buf, "<td style='padding-left: 10px; float: right;'>%s</td>", temp); free(temp); } if (plan_display_runtime) { asprintf_loc(&temp, translate("gettextFromC", "%3dmin"), (dp->time + 30) / 60); put_format(&buf, "<td style='padding-left: 10px; float: right;'>%s</td>", temp); free(temp); } /* Normally a gas change is displayed on the stopping segment, so only display a gas change at the end of * an ascent segment if it is not followed by a stop */ if ((isascent || dp->entered) && gaschange_after && dp->next && nextdp && (dp->depth.mm != nextdp->depth.mm || nextdp->entered)) { if (dp->setpoint) { asprintf_loc(&temp, translate("gettextFromC", "(SP = %.1fbar CCR)"), dp->setpoint / 1000.0); put_format(&buf, "<td style='padding-left: 10px; color: red; float: left;'><b>%s %s</b></td>", gasname(newgasmix), temp); free(temp); } else { put_format(&buf, "<td style='padding-left: 10px; color: red; float: left;'><b>%s %s</b></td>", gasname(newgasmix), lastdivemode == UNDEF_COMP_TYPE || lastdivemode == dp->divemode ? "" : translate("gettextFromC", divemode_text_ui[dp->divemode])); if (isascent && (get_he(lastprintgasmix) > 0)) { // For a trimix gas change on ascent, save ICD info if previous cylinder had helium if (isobaric_counterdiffusion(lastprintgasmix, newgasmix, &icdvalues)) // Do icd calulations icdwarning = true; if (icdvalues.dN2 > 0) { // If the gas change involved helium as well as an increase in nitrogen.. add_icd_entry(&icdbuf, &icdvalues, icdtableheader, dp->time, depth_to_mbar(dp->depth.mm, dive), lastprintgasmix, newgasmix); // .. then print calculations to buffer. icdtableheader = false; } } } lastprintsetpoint = dp->setpoint; lastprintgasmix = newgasmix; lastdivemode = dp->divemode; gaschange_after = false; } else if (gaschange_before || rebreatherchange_before) { // If a new gas has been used for this segment, now is the time to show it if (dp->setpoint) { asprintf_loc(&temp, translate("gettextFromC", "(SP = %.1fbar CCR)"), (double) dp->setpoint / 1000.0); put_format(&buf, "<td style='padding-left: 10px; color: red; float: left;'><b>%s %s</b></td>", gasname(gasmix), temp); free(temp); } else { put_format(&buf, "<td style='padding-left: 10px; color: red; float: left;'><b>%s %s</b></td>", gasname(gasmix), lastdivemode == UNDEF_COMP_TYPE || lastdivemode == dp->divemode ? "" : translate("gettextFromC", divemode_text_ui[dp->divemode])); if (get_he(lastprintgasmix) > 0) { // For a trimix gas change, save ICD info if previous cylinder had helium if (isobaric_counterdiffusion(lastprintgasmix, gasmix, &icdvalues)) // Do icd calculations icdwarning = true; if (icdvalues.dN2 > 0) { // If the gas change involved helium as well as an increase in nitrogen.. add_icd_entry(&icdbuf, &icdvalues, icdtableheader, lasttime, depth_to_mbar(dp->depth.mm, dive), lastprintgasmix, gasmix); // .. then print data to buffer. icdtableheader = false; } } } // Set variables so subsequent iterations can test against the last gas printed lastprintsetpoint = dp->setpoint; lastprintgasmix = gasmix; lastdivemode = dp->divemode; gaschange_after = false; } else { put_string(&buf, "<td>&nbsp;</td>"); } put_string(&buf, "</tr>\n"); newdepth = dp->depth.mm; // Only add the time we actually displayed so rounding errors dont accumulate lasttime += ((dp->time - lasttime + 30) / 60) * 60; } } if (gaschange_after || gaschange_before) { // gas switch at this waypoint for verbatim if (plan_verbatim) { if (lastsetpoint >= 0) { if (nextdp && nextdp->setpoint) { put_format_loc(&buf, translate("gettextFromC", "Switch gas to %s (SP = %.1fbar)"), gasname(newgasmix), (double) nextdp->setpoint / 1000.0); } else { put_format(&buf, translate("gettextFromC", "Switch gas to %s"), gasname(newgasmix)); if ((isascent) && (get_he(lastprintgasmix) > 0)) { // For a trimix gas change on ascent: if (isobaric_counterdiffusion(lastprintgasmix, newgasmix, &icdvalues)) // Do icd calculations icdwarning = true; if (icdvalues.dN2 > 0) { // If the gas change involved helium as well as an increase in nitrogen.. add_icd_entry(&icdbuf, &icdvalues, icdtableheader, dp->time, depth_to_mbar(dp->depth.mm, dive), lastprintgasmix, newgasmix); // ... then print data to buffer. icdtableheader = false; } } } put_string(&buf, "<br/>\n"); } lastprintgasmix = newgasmix; gaschange_after = false; gasmix = newgasmix; } } lastprintdepth = newdepth; lastdepth = dp->depth.mm; lastsetpoint = dp->setpoint; lastentered = dp->entered; } while ((dp = nextdp) != NULL); if (!plan_verbatim) put_string(&buf, "</tbody>\n</table>\n<br/>\n"); /* Print the CNS and OTU next.*/ dive->cns = 0; dive->maxcns = 0; update_cylinder_related_info(dive); put_format_loc(&buf, "<div>\n%s: %i%%", translate("gettextFromC", "CNS"), dive->cns); put_format_loc(&buf, "<br/>\n%s: %i<br/>\n</div>\n", translate("gettextFromC", "OTU"), dive->otu); /* Print the settings for the diveplan next. */ put_string(&buf, "<div>\n"); if (decoMode(true) == BUEHLMANN) { put_format_loc(&buf, translate("gettextFromC", "Deco model: Bühlmann ZHL-16C with GFLow = %d%% and GFHigh = %d%%"), diveplan->gflow, diveplan->gfhigh); } else if (decoMode(true) == VPMB) { if (diveplan->vpmb_conservatism == 0) put_string(&buf, translate("gettextFromC", "Deco model: VPM-B at nominal conservatism")); else put_format_loc(&buf, translate("gettextFromC", "Deco model: VPM-B at +%d conservatism"), diveplan->vpmb_conservatism); if (diveplan->eff_gflow) put_format_loc(&buf, translate("gettextFromC", ", effective GF=%d/%d"), diveplan->eff_gflow, diveplan->eff_gfhigh); } else if (decoMode(true) == RECREATIONAL) { put_format_loc(&buf, translate("gettextFromC", "Deco model: Recreational mode based on Bühlmann ZHL-16B with GFLow = %d%% and GFHigh = %d%%"), diveplan->gflow, diveplan->gfhigh); } put_string(&buf, "<br/>\n"); const char *depth_unit; int altitude = (int) get_depth_units((int) (pressure_to_altitude(diveplan->surface_pressure)), NULL, &depth_unit); put_format_loc(&buf, translate("gettextFromC", "ATM pressure: %dmbar (%d%s)<br/>\n</div>\n"), diveplan->surface_pressure, altitude, depth_unit); /* Get SAC values and units for printing it in gas consumption */ double bottomsacvalue, decosacvalue; int sacdecimals; const char* sacunit; bottomsacvalue = get_volume_units(prefs.bottomsac, &sacdecimals, &sacunit); decosacvalue = get_volume_units(prefs.decosac, NULL, NULL); /* Reduce number of decimals from 1 to 0 for bar/min, keep 2 for cuft/min */ if (sacdecimals==1) sacdecimals--; /* Print the gas consumption next.*/ if (dive->dc.divemode == CCR) temp = strdup(translate("gettextFromC", "Gas consumption (CCR legs excluded):")); else asprintf_loc(&temp, "%s %.*f|%.*f%s/min):", translate("gettextFromC", "Gas consumption (based on SAC"), sacdecimals, bottomsacvalue, sacdecimals, decosacvalue, sacunit); put_format(&buf, "<div>\n%s<br/>\n", temp); free(temp); /* Print gas consumption: This loop covers all cylinders */ for (int gasidx = 0; gasidx < dive->cylinders.nr; gasidx++) { double volume, pressure, deco_volume, deco_pressure, mingas_volume, mingas_pressure, mingas_d_pressure, mingas_depth; const char *unit, *pressure_unit, *depth_unit; char warning[1000] = ""; char mingas[1000] = ""; cylinder_t *cyl = get_cylinder(dive, gasidx); if (cyl->cylinder_use == NOT_USED) continue; volume = get_volume_units(cyl->gas_used.mliter, NULL, &unit); deco_volume = get_volume_units(cyl->deco_gas_used.mliter, NULL, &unit); if (cyl->type.size.mliter) { int remaining_gas = lrint((double)cyl->end.mbar * cyl->type.size.mliter / 1000.0 / gas_compressibility_factor(cyl->gasmix, cyl->end.mbar / 1000.0)); double deco_pressure_mbar = isothermal_pressure(cyl->gasmix, 1.0, remaining_gas + cyl->deco_gas_used.mliter, cyl->type.size.mliter) * 1000 - cyl->end.mbar; deco_pressure = get_pressure_units(lrint(deco_pressure_mbar), &pressure_unit); pressure = get_pressure_units(cyl->start.mbar - cyl->end.mbar, &pressure_unit); /* Warn if the plan uses more gas than is available in a cylinder * This only works if we have working pressure for the cylinder * 10bar is a made up number - but it seemed silly to pretend you could breathe cylinder down to 0 */ if (cyl->end.mbar < 10000) snprintf(warning, sizeof(warning), "<br/>\n&nbsp;&mdash; <span style='color: red;'>%s </span> %s", translate("gettextFromC", "Warning:"), translate("gettextFromC", "this is more gas than available in the specified cylinder!")); else if (cyl->end.mbar / 1000.0 * cyl->type.size.mliter / gas_compressibility_factor(cyl->gasmix, cyl->end.mbar / 1000.0) < cyl->deco_gas_used.mliter) snprintf(warning, sizeof(warning), "<br/>\n&nbsp;&mdash; <span style='color: red;'>%s </span> %s", translate("gettextFromC", "Warning:"), translate("gettextFromC", "not enough reserve for gas sharing on ascent!")); /* Do and print minimum gas calculation for last bottom gas, but only for OC mode, */ /* not for recreational mode and if no other warning was set before. */ else if (lastbottomdp && gasidx == lastbottomdp->cylinderid && dive->dc.divemode == OC && decoMode(true) != RECREATIONAL) { /* Calculate minimum gas volume. */ volume_t mingasv; mingasv.mliter = lrint(prefs.sacfactor / 100.0 * prefs.problemsolvingtime * prefs.bottomsac * depth_to_bar(lastbottomdp->depth.mm, dive) + prefs.sacfactor / 100.0 * cyl->deco_gas_used.mliter); /* Calculate minimum gas pressure for cyclinder. */ lastbottomdp->minimum_gas.mbar = lrint(isothermal_pressure(cyl->gasmix, 1.0, mingasv.mliter, cyl->type.size.mliter) * 1000); /* Translate all results into correct units */ mingas_volume = get_volume_units(mingasv.mliter, NULL, &unit); mingas_pressure = get_pressure_units(lastbottomdp->minimum_gas.mbar, &pressure_unit); mingas_d_pressure = get_pressure_units(lrint((double)cyl->end.mbar + deco_pressure_mbar - lastbottomdp->minimum_gas.mbar), &pressure_unit); mingas_depth = get_depth_units(lastbottomdp->depth.mm, NULL, &depth_unit); /* Print it to results */ if (cyl->start.mbar > lastbottomdp->minimum_gas.mbar) { snprintf_loc(mingas, sizeof(mingas), "<br/>\n&nbsp;&mdash; <span style='color: %s;'>%s</span> (%s %.1fx%s/+%d%s@%.0f%s): " "%.0f%s/%.0f%s<span style='color: %s;'>/&Delta;:%+.0f%s</span>", mingas_d_pressure > 0 ? "green" :"red", translate("gettextFromC", "Minimum gas"), translate("gettextFromC", "based on"), prefs.sacfactor / 100.0, translate("gettextFromC", "SAC"), prefs.problemsolvingtime, translate("gettextFromC", "min"), mingas_depth, depth_unit, mingas_volume, unit, mingas_pressure, pressure_unit, mingas_d_pressure > 0 ? "grey" :"indianred", mingas_d_pressure, pressure_unit); } else { snprintf(warning, sizeof(warning), "<br/>\n&nbsp;&mdash; <span style='color: red;'>%s </span> %s", translate("gettextFromC", "Warning:"), translate("gettextFromC", "required minimum gas for ascent already exceeding start pressure of cylinder!")); } } /* Print the gas consumption for every cylinder here to temp buffer. */ if (lrint(volume) > 0) { asprintf_loc(&temp, translate("gettextFromC", "%.0f%s/%.0f%s of <span style='color: red;'><b>%s</b></span> (%.0f%s/%.0f%s in planned ascent)"), volume, unit, pressure, pressure_unit, gasname(cyl->gasmix), deco_volume, unit, deco_pressure, pressure_unit); } else { asprintf_loc(&temp, translate("gettextFromC", "%.0f%s/%.0f%s of <span style='color: red;'><b>%s</b></span>"), volume, unit, pressure, pressure_unit, gasname(cyl->gasmix)); } } else { if (lrint(volume) > 0) { asprintf_loc(&temp, translate("gettextFromC", "%.0f%s of <span style='color: red;'><b>%s</b></span> (%.0f%s during planned ascent)"), volume, unit, gasname(cyl->gasmix), deco_volume, unit); } else { asprintf_loc(&temp, translate("gettextFromC", "%.0f%s of <span style='color: red;'><b>%s</b></span>"), volume, unit, gasname(cyl->gasmix)); } } /* Gas consumption: Now finally print all strings to output */ put_format(&buf, "%s%s%s<br/>\n", temp, warning, mingas); free(temp); } put_format(&buf, "</div>\n"); /* For trimix OC dives, if an icd table header and icd data were printed to buffer, then add the ICD table here */ if (!icdtableheader && prefs.show_icd) { put_string(&icdbuf, "</tbody></table>\n"); // End the ICD table mb_cstring(&icdbuf); put_string(&buf, icdbuf.buffer); // ..and add it to the html buffer if (icdwarning) { // If necessary, add warning put_format(&buf, "<span style='color: red;'>%s</span> %s", translate("gettextFromC", "Warning:"), translate("gettextFromC", "Isobaric counterdiffusion conditions exceeded")); } put_string(&buf, "<br/></div>\n"); } free_buffer(&icdbuf); /* Print warnings for pO2 */ dp = diveplan->dp; bool o2warning_exist = false; enum divemode_t current_divemode; double amb; const struct event *evd = NULL; current_divemode = UNDEF_COMP_TYPE; if (dive->dc.divemode != CCR) { while (dp) { if (dp->time != 0) { struct gas_pressures pressures; struct gasmix gasmix = get_cylinder(dive, dp->cylinderid)->gasmix; current_divemode = get_current_divemode(&dive->dc, dp->time, &evd, &current_divemode); amb = depth_to_atm(dp->depth.mm, dive); fill_pressures(&pressures, amb, gasmix, (current_divemode == OC) ? 0.0 : amb * gasmix.o2.permille / 1000.0, current_divemode); if (pressures.o2 > (dp->entered ? prefs.bottompo2 : prefs.decopo2) / 1000.0) { const char *depth_unit; int decimals; double depth_value = get_depth_units(dp->depth.mm, &decimals, &depth_unit); if (!o2warning_exist) put_string(&buf, "<div>\n"); o2warning_exist = true; asprintf_loc(&temp, translate("gettextFromC", "high pO₂ value %.2f at %d:%02u with gas %s at depth %.*f %s"), pressures.o2, FRACTION(dp->time, 60), gasname(gasmix), decimals, depth_value, depth_unit); put_format(&buf, "<span style='color: red;'>%s </span> %s<br/>\n", translate("gettextFromC", "Warning:"), temp); free(temp); } else if (pressures.o2 < 0.16) { const char *depth_unit; int decimals; double depth_value = get_depth_units(dp->depth.mm, &decimals, &depth_unit); if (!o2warning_exist) put_string(&buf, "<div>"); o2warning_exist = true; asprintf_loc(&temp, translate("gettextFromC", "low pO₂ value %.2f at %d:%02u with gas %s at depth %.*f %s"), pressures.o2, FRACTION(dp->time, 60), gasname(gasmix), decimals, depth_value, depth_unit); put_format(&buf, "<span style='color: red;'>%s </span> %s<br/>\n", translate("gettextFromC", "Warning:"), temp); free(temp); } } dp = dp->next; } } if (o2warning_exist) put_string(&buf, "</div>\n"); finished: free(dive->notes); dive->notes = detach_cstring(&buf); #ifdef DEBUG_PLANNER_NOTES printf("<!DOCTYPE html>\n<html>\n\t<head><title>plannernotes</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/></head>\n\t<body>\n%s\t</body>\n</html>\n", dive->notes); #endif }
subsurface-for-dirk-master
core/plannernotes.c
// SPDX-License-Identifier: GPL-2.0 /* macos.c */ /* implements Mac OS X specific functions */ #include "ssrf.h" #include <stdlib.h> #include <dirent.h> #include <fnmatch.h> #include "dive.h" #include "subsurface-string.h" #include "device.h" #include "libdivecomputer.h" #include <CoreFoundation/CoreFoundation.h> #if !defined(__IPHONE_5_0) #include <CoreServices/CoreServices.h> #endif #include <mach-o/dyld.h> #include <sys/syslimits.h> #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <zip.h> #include <sys/stat.h> /* macos defines CFSTR to create a CFString object from a constant, * but no similar macros if a C string variable is supposed to be * the argument. We add this here (hardcoding the default allocator * and MacRoman encoding */ #define CFSTR_VAR(_var) CFStringCreateWithCStringNoCopy(kCFAllocatorDefault, \ (_var), kCFStringEncodingMacRoman, \ kCFAllocatorNull) #define SUBSURFACE_PREFERENCES CFSTR("org.hohndel.subsurface") #define ICON_NAME "Subsurface.icns" #define UI_FONT "Arial 12" const char mac_system_divelist_default_font[] = "Arial"; const char *system_divelist_default_font = mac_system_divelist_default_font; double system_divelist_default_font_size = -1.0; void subsurface_OS_pref_setup(void) { // nothing } bool subsurface_ignore_font(const char *font) { UNUSED(font); // there are no old default fonts to ignore return false; } static const char *system_default_path_append(const char *append) { const char *home = getenv("HOME"); const char *path = "/Library/Application Support/Subsurface"; int len = strlen(home) + strlen(path) + 1; if (append) len += strlen(append) + 1; char *buffer = (char *)malloc(len); memset(buffer, 0, len); strcat(buffer, home); strcat(buffer, path); if (append) { strcat(buffer, "/"); strcat(buffer, append); } return buffer; } const char *system_default_directory(void) { static const char *path = NULL; if (!path) path = system_default_path_append(NULL); return path; } const char *system_default_filename(void) { static const char *path = NULL; if (!path) { const char *user = getenv("LOGNAME"); if (empty_string(user)) user = "username"; char *filename = calloc(strlen(user) + 5, 1); strcat(filename, user); strcat(filename, ".xml"); path = system_default_path_append(filename); free(filename); } return path; } int enumerate_devices(device_callback_t callback, void *userdata, unsigned int transport) { int index = -1, entries = 0; DIR *dp = NULL; struct dirent *ep = NULL; size_t i; if (transport & DC_TRANSPORT_SERIAL) { // on Mac we always support FTDI now callback("FTDI", userdata); const char *dirname = "/dev"; const char *patterns[] = { "tty.*", "usbserial", NULL }; dp = opendir(dirname); if (dp == NULL) { return -1; } while ((ep = readdir(dp)) != NULL) { for (i = 0; patterns[i] != NULL; ++i) { if (fnmatch(patterns[i], ep->d_name, 0) == 0) { char filename[1024]; int n = snprintf(filename, sizeof(filename), "%s/%s", dirname, ep->d_name); if (n >= (int)sizeof(filename)) { closedir(dp); return -1; } callback(filename, userdata); if (is_default_dive_computer_device(filename)) index = entries; entries++; break; } } } closedir(dp); } if (transport & DC_TRANSPORT_USBSTORAGE) { const char *dirname = "/Volumes"; int num_uemis = 0; dp = opendir(dirname); if (dp == NULL) { return -1; } while ((ep = readdir(dp)) != NULL) { if (fnmatch("UEMISSDA", ep->d_name, 0) == 0 || fnmatch("GARMIN", ep->d_name, 0) == 0) { char filename[1024]; int n = snprintf(filename, sizeof(filename), "%s/%s", dirname, ep->d_name); if (n >= (int)sizeof(filename)) { closedir(dp); return -1; } callback(filename, userdata); if (is_default_dive_computer_device(filename)) index = entries; entries++; num_uemis++; break; } } closedir(dp); if (num_uemis == 1 && entries == 1) /* if we find exactly one entry and that's a Uemis, select it */ index = 0; } return index; } /* NOP wrappers to comform with windows.c */ int subsurface_rename(const char *path, const char *newpath) { return rename(path, newpath); } int subsurface_open(const char *path, int oflags, mode_t mode) { return open(path, oflags, mode); } FILE *subsurface_fopen(const char *path, const char *mode) { return fopen(path, mode); } void *subsurface_opendir(const char *path) { return (void *)opendir(path); } int subsurface_access(const char *path, int mode) { return access(path, mode); } int subsurface_stat(const char* path, struct stat* buf) { return stat(path, buf); } struct zip *subsurface_zip_open_readonly(const char *path, int flags, int *errorp) { return zip_open(path, flags, errorp); } int subsurface_zip_close(struct zip *zip) { return zip_close(zip); } /* win32 console */ void subsurface_console_init(void) { /* NOP */ } void subsurface_console_exit(void) { /* NOP */ } bool subsurface_user_is_root() { return geteuid() == 0; }
subsurface-for-dirk-master
core/macos.c
// SPDX-License-Identifier: GPL-2.0 /* windows.c */ /* implements Windows specific functions */ #include "ssrf.h" #include <io.h> #include "dive.h" #include "device.h" #include "libdivecomputer.h" #include "file.h" #include "errorhelper.h" #include "subsurfacesysinfo.h" #undef _WIN32_WINNT #define _WIN32_WINNT 0x500 #include <windows.h> #include <shlobj.h> #include <stdio.h> #include <fcntl.h> #include <assert.h> #include <dirent.h> #include <zip.h> #include <lmcons.h> const char non_standard_system_divelist_default_font[] = "Calibri"; const char current_system_divelist_default_font[] = "Segoe UI"; const char *system_divelist_default_font = non_standard_system_divelist_default_font; double system_divelist_default_font_size = -1; void subsurface_OS_pref_setup(void) { if (isWin7Or8()) system_divelist_default_font = current_system_divelist_default_font; } bool subsurface_ignore_font(const char *font) { // if this is running on a recent enough version of Windows and the font // passed in is the pre 4.3 default font, ignore it if (isWin7Or8() && strcmp(font, non_standard_system_divelist_default_font) == 0) return true; return false; } /* this function converts a win32's utf-16 2 byte string to utf-8. * the caller function should manage the allocated memory. */ static char *utf16_to_utf8_fl(const wchar_t *utf16, char *file, int line) { assert(utf16 != NULL); assert(file != NULL); assert(line); /* estimate buffer size */ const int sz = WideCharToMultiByte(CP_UTF8, 0, utf16, -1, NULL, 0, NULL, NULL); if (!sz) { fprintf(stderr, "%s:%d: cannot estimate buffer size\n", file, line); return NULL; } char *utf8 = (char *)malloc(sz); if (!utf8) { fprintf(stderr, "%s:%d: cannot allocate buffer of size: %d\n", file, line, sz); return NULL; } if (WideCharToMultiByte(CP_UTF8, 0, utf16, -1, utf8, sz, NULL, NULL)) { return utf8; } fprintf(stderr, "%s:%d: cannot convert string\n", file, line); free((void *)utf8); return NULL; } #define utf16_to_utf8(s) utf16_to_utf8_fl(s, __FILE__, __LINE__) /* this function converts a utf-8 string to win32's utf-16 2 byte string. * the caller function should manage the allocated memory. */ static wchar_t *utf8_to_utf16_fl(const char *utf8, char *file, int line) { assert(utf8 != NULL); assert(file != NULL); assert(line); /* estimate buffer size */ const int sz = strlen(utf8) + 1; wchar_t *utf16 = (wchar_t *)malloc(sizeof(wchar_t) * sz); if (!utf16) { fprintf(stderr, "%s:%d: cannot allocate buffer of size: %d\n", file, line, sz); return NULL; } if (MultiByteToWideChar(CP_UTF8, 0, utf8, -1, utf16, sz)) return utf16; fprintf(stderr, "%s:%d: cannot convert string\n", file, line); free((void *)utf16); return NULL; } #define utf8_to_utf16(s) utf8_to_utf16_fl(s, __FILE__, __LINE__) /* this function returns the Win32 Roaming path for the current user as UTF-8. * it never returns NULL but fallsback to .\ instead! * the append argument will append a wchar_t string to the end of the path. */ static wchar_t *system_default_path_append(const wchar_t *append) { wchar_t wpath[MAX_PATH] = { 0 }; const char *fname = "system_default_path_append()"; /* obtain the user path via SHGetFolderPathW. * this API is deprecated but still supported on modern Win32. * fallback to .\ if it fails. */ if (!SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_APPDATA, NULL, 0, wpath))) { fprintf(stderr, "%s: cannot obtain path!\n", fname); wpath[0] = L'.'; wpath[1] = L'\0'; } wcscat(wpath, L"\\Subsurface"); if (append) { wcscat(wpath, L"\\"); wcscat(wpath, append); } wchar_t *result = wcsdup(wpath); if (!result) fprintf(stderr, "%s: cannot allocate memory for path!\n", fname); return result; } /* by passing NULL to system_default_path_append() we obtain the pure path. * '\' not included at the end. */ const char *system_default_directory(void) { static const char *path = NULL; if (!path) { wchar_t *wpath = system_default_path_append(NULL); path = utf16_to_utf8(wpath); free((void *)wpath); } return path; } /* obtain the Roaming path and append "\\<USERNAME>.xml" to it. */ const char *system_default_filename(void) { static const char *path = NULL; if (!path) { wchar_t username[UNLEN + 1] = { 0 }; DWORD username_len = UNLEN + 1; GetUserNameW(username, &username_len); wchar_t filename[UNLEN + 5] = { 0 }; wcscat(filename, username); wcscat(filename, L".xml"); wchar_t *wpath = system_default_path_append(filename); path = utf16_to_utf8(wpath); free((void *)wpath); } return path; } int enumerate_devices(device_callback_t callback, void *userdata, unsigned int transport) { int index = -1; DWORD i; if (transport & DC_TRANSPORT_SERIAL) { // Open the registry key. HKEY hKey; LONG rc = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "HARDWARE\\DEVICEMAP\\SERIALCOMM", 0, KEY_QUERY_VALUE, &hKey); if (rc != ERROR_SUCCESS) { return -1; } // Get the number of values. DWORD count = 0; rc = RegQueryInfoKey(hKey, NULL, NULL, NULL, NULL, NULL, NULL, &count, NULL, NULL, NULL, NULL); if (rc != ERROR_SUCCESS) { RegCloseKey(hKey); return -1; } for (i = 0; i < count; ++i) { // Get the value name, data and type. char name[512], data[512]; DWORD name_len = sizeof(name); DWORD data_len = sizeof(data); DWORD type = 0; rc = RegEnumValue(hKey, i, name, &name_len, NULL, &type, (LPBYTE)data, &data_len); if (rc != ERROR_SUCCESS) { RegCloseKey(hKey); return -1; } // Ignore non-string values. if (type != REG_SZ) continue; // Prevent a possible buffer overflow. if (data_len >= sizeof(data)) { RegCloseKey(hKey); return -1; } // Null terminate the string. data[data_len] = 0; callback(data, userdata); index++; if (is_default_dive_computer_device(name)) index = i; } RegCloseKey(hKey); } if (transport & DC_TRANSPORT_USBSTORAGE) { int i; int count_drives = 0; const int bufdef = 512; const char *dlabels[] = {"UEMISSDA", "GARMIN", NULL}; char bufname[bufdef], bufval[bufdef], *p; DWORD bufname_len; /* add drive letters that match labels */ memset(bufname, 0, bufdef); bufname_len = bufdef; if (GetLogicalDriveStringsA(bufname_len, bufname)) { p = bufname; while (*p) { memset(bufval, 0, bufdef); if (GetVolumeInformationA(p, bufval, bufdef, NULL, NULL, NULL, NULL, 0)) { for (i = 0; dlabels[i] != NULL; i++) if (!strcmp(bufval, dlabels[i])) { char data[512]; snprintf(data, sizeof(data), "%s (%s)", p, dlabels[i]); callback(data, userdata); if (is_default_dive_computer_device(p)) index = count_drives; count_drives++; } } p = &p[strlen(p) + 1]; } if (count_drives == 1) /* we found exactly one Uemis "drive" */ index = 0; /* make it the selected "device" */ } } return index; } /* bellow we provide a set of wrappers for some I/O functions to use wchar_t. * on win32 this solves the issue that we need paths to be utf-16 encoded. */ int subsurface_rename(const char *path, const char *newpath) { int ret = -1; if (!path || !newpath) return ret; wchar_t *wpath = utf8_to_utf16(path); wchar_t *wnewpath = utf8_to_utf16(newpath); if (wpath && wnewpath) ret = _wrename(wpath, wnewpath); free((void *)wpath); free((void *)wnewpath); return ret; } // if the QDir based rename fails, we try this one int subsurface_dir_rename(const char *path, const char *newpath) { // check if the folder exists BOOL exists = FALSE; DWORD attrib = GetFileAttributes(path); if (attrib != INVALID_FILE_ATTRIBUTES && attrib & FILE_ATTRIBUTE_DIRECTORY) exists = TRUE; if (!exists && verbose) { fprintf(stderr, "folder not found or path is not a folder: %s\n", path); return EXIT_FAILURE; } // list of error codes: // https://msdn.microsoft.com/en-us/library/windows/desktop/ms681381(v=vs.85).aspx DWORD errorCode; // if this fails something has already obatained (more) exclusive access to the folder HANDLE h = CreateFile(path, GENERIC_WRITE, FILE_SHARE_WRITE | FILE_SHARE_DELETE, 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0); if (h == INVALID_HANDLE_VALUE) { errorCode = GetLastError(); if (verbose) fprintf(stderr, "cannot obtain exclusive write access for folder: %u\n", (unsigned int)errorCode ); return EXIT_FAILURE; } else { if (verbose) fprintf(stderr, "exclusive write access obtained...closing handle!"); CloseHandle(h); // attempt to rename BOOL result = MoveFile(path, newpath); if (!result) { errorCode = GetLastError(); if (verbose) fprintf(stderr, "rename failed: %u\n", (unsigned int)errorCode); return EXIT_FAILURE; } if (verbose > 1) fprintf(stderr, "folder rename success: %s ---> %s\n", path, newpath); } return EXIT_SUCCESS; } int subsurface_open(const char *path, int oflags, mode_t mode) { int ret = -1; if (!path) return ret; wchar_t *wpath = utf8_to_utf16(path); if (wpath) ret = _wopen(wpath, oflags, mode); free((void *)wpath); return ret; } FILE *subsurface_fopen(const char *path, const char *mode) { FILE *ret = NULL; if (!path) return ret; wchar_t *wpath = utf8_to_utf16(path); if (wpath) { const int len = strlen(mode); wchar_t wmode[len + 1]; for (int i = 0; i < len; i++) wmode[i] = (wchar_t)mode[i]; wmode[len] = 0; ret = _wfopen(wpath, wmode); } free((void *)wpath); return ret; } /* here we return a void pointer instead of _WDIR or DIR pointer */ void *subsurface_opendir(const char *path) { _WDIR *ret = NULL; if (!path) return ret; wchar_t *wpath = utf8_to_utf16(path); if (wpath) ret = _wopendir(wpath); free((void *)wpath); return (void *)ret; } int subsurface_access(const char *path, int mode) { int ret = -1; if (!path) return ret; wchar_t *wpath = utf8_to_utf16(path); if (wpath) ret = _waccess(wpath, mode); free((void *)wpath); return ret; } int subsurface_stat(const char* path, struct stat* buf) { int ret = -1; if (!path) return ret; wchar_t *wpath = utf8_to_utf16(path); if (wpath) ret = wstat(wpath, buf); free((void *)wpath); return ret; } #ifndef O_BINARY #define O_BINARY 0 #endif struct zip *subsurface_zip_open_readonly(const char *path, int flags, int *errorp) { #if defined(LIBZIP_VERSION_MAJOR) /* libzip 0.10 has zip_fdopen, let's use it since zip_open doesn't have a * wchar_t version */ int fd = subsurface_open(path, O_RDONLY | O_BINARY, 0); struct zip *ret = zip_fdopen(fd, flags, errorp); if (!ret) close(fd); return ret; #else return zip_open(path, flags, errorp); #endif } int subsurface_zip_close(struct zip *zip) { return zip_close(zip); } /* win32 console */ static struct { bool allocated; UINT cp; FILE *out, *err; } console_desc; void subsurface_console_init(void) { UNUSED(console_desc); /* if this is a console app already, do nothing */ #ifndef WIN32_CONSOLE_APP /* just in case of multiple calls */ memset((void *)&console_desc, 0, sizeof(console_desc)); /* if AttachConsole(ATTACH_PARENT_PROCESS) returns true the parent process * is a terminal. based on the result, either redirect to that terminal or * to log files. */ console_desc.allocated = AttachConsole(ATTACH_PARENT_PROCESS); if (console_desc.allocated) { console_desc.cp = GetConsoleCP(); SetConsoleOutputCP(CP_UTF8); /* make the ouput utf8 */ console_desc.out = freopen("CON", "w", stdout); console_desc.err = freopen("CON", "w", stderr); } else { verbose = 1; /* set the verbose level to '1' */ wchar_t *wpath_out = system_default_path_append(L"subsurface_out.log"); wchar_t *wpath_err = system_default_path_append(L"subsurface_err.log"); if (wpath_out && wpath_err) { console_desc.out = _wfreopen(wpath_out, L"w", stdout); console_desc.err = _wfreopen(wpath_err, L"w", stderr); } free((void *)wpath_out); free((void *)wpath_err); } puts(""); /* add an empty line */ #endif } void subsurface_console_exit(void) { #ifndef WIN32_CONSOLE_APP /* close handles */ if (console_desc.out) fclose(console_desc.out); if (console_desc.err) fclose(console_desc.err); /* reset code page and free */ if (console_desc.allocated) { SetConsoleOutputCP(console_desc.cp); FreeConsole(); } #endif } bool subsurface_user_is_root() { /* FIXME: Detect admin rights */ return false; }
subsurface-for-dirk-master
core/windows.c
// SPDX-License-Identifier: GPL-2.0 #ifdef __clang__ // Clang has a bug on zero-initialization of C structs. #pragma clang diagnostic ignored "-Wmissing-field-initializers" #endif #include <stdarg.h> #include "errorhelper.h" #include "membuffer.h" #include "qthelper.h" #if !defined(Q_OS_ANDROID) && !defined(__ANDROID__) #define LOG_MSG(fmt, ...) fprintf(stderr, fmt, ##__VA_ARGS__) #else #include <android/log.h> #define LOG_MSG(fmt, ...) __android_log_print(ANDROID_LOG_INFO, "Subsurface", fmt, ##__VA_ARGS__); #endif #define VA_BUF(b, fmt) do { va_list args; va_start(args, fmt); put_vformat(b, fmt, args); va_end(args); } while (0) int verbose; void report_info(const char *fmt, ...) { struct membuffer buf = { 0 }; VA_BUF(&buf, fmt); strip_mb(&buf); LOG_MSG("INFO: %s\n", mb_cstring(&buf)); } static void (*error_cb)(char *) = NULL; int report_error(const char *fmt, ...) { struct membuffer buf = { 0 }; VA_BUF(&buf, fmt); strip_mb(&buf); LOG_MSG("ERROR: %s\n", mb_cstring(&buf)); /* if there is no error callback registered, don't produce errors */ if (!error_cb) return -1; error_cb(detach_cstring(&buf)); return -1; } void set_error_cb(void(*cb)(char *)) { error_cb = cb; }
subsurface-for-dirk-master
core/errorhelper.c
// SPDX-License-Identifier: GPL-2.0 /* * uemis-downloader.c * * Copyright (c) Dirk Hohndel <dirk@hohndel.org> * released under GPL2 * * very (VERY) loosely based on the algorithms found in Java code by Fabian Gast <fgast@only640k.net> * which was released under the BSD-STYLE BEER WARE LICENSE * I believe that I only used the information about HOW to do this (download data from the Uemis * Zurich) but did not actually use any of his copyrighted code, therefore the license under which * he released his code does not apply to this new implementation in C * * Modified by Guido Lerch guido.lerch@gmail.com in August 2015 */ #include <fcntl.h> #include <dirent.h> #include <stdio.h> #include <stdarg.h> #include <unistd.h> #include <string.h> #include <errno.h> #include "gettext.h" #include "libdivecomputer.h" #include "uemis.h" #include "divelist.h" #include "divesite.h" #include "errorhelper.h" #include "file.h" #include "tag.h" #include "subsurface-time.h" #include "core/subsurface-string.h" #define ACTION_RECONNECT QT_TRANSLATE_NOOP("gettextFromC", "Disconnect/reconnect the SDA") #define ERR_FS_ALMOST_FULL QT_TRANSLATE_NOOP("gettextFromC", "Uemis Zurich: the file system is almost full.\nDisconnect/reconnect the dive computer\nand click \'Retry\'") #define ERR_FS_FULL QT_TRANSLATE_NOOP("gettextFromC", "Uemis Zurich: the file system is full.\nDisconnect/reconnect the dive computer\nand click Retry") #define ERR_FS_SHORT_WRITE QT_TRANSLATE_NOOP("gettextFromC", "Short write to req.txt file.\nIs the Uemis Zurich plugged in correctly?") #define ERR_NO_FILES QT_TRANSLATE_NOOP("gettextFromC", "No dives to download.") #define BUFLEN 2048 #define BUFLEN 2048 #define NUM_PARAM_BUFS 10 // debugging setup // #define UEMIS_DEBUG 1 + 2 + 4 + 8 + 16 + 32 #define UEMIS_MAX_FILES 4000 #define UEMIS_MEM_FULL 1 #define UEMIS_MEM_OK 0 #define UEMIS_SPOT_BLOCK_SIZE 1 #define UEMIS_DIVE_DETAILS_SIZE 2 #define UEMIS_LOG_BLOCK_SIZE 10 #define UEMIS_CHECK_LOG 1 #define UEMIS_CHECK_DETAILS 2 #define UEMIS_CHECK_SINGLE_DIVE 3 #if UEMIS_DEBUG const char *home, *user, *d_time; static int debug_round = 0; #define debugfile stderr #endif #if UEMIS_DEBUG & 64 /* we are reading from a copy of the filesystem, not the device - no need to wait */ #define UEMIS_TIMEOUT 50 /* 50ns */ #define UEMIS_LONG_TIMEOUT 500 /* 500ns */ #define UEMIS_MAX_TIMEOUT 2000 /* 2ms */ #else #define UEMIS_TIMEOUT 50000 /* 50ms */ #define UEMIS_LONG_TIMEOUT 500000 /* 500ms */ #define UEMIS_MAX_TIMEOUT 2000000 /* 2s */ #endif static char *param_buff[NUM_PARAM_BUFS]; static char *reqtxt_path; static int reqtxt_file; static int filenr; static int number_of_files; static char *mbuf = NULL; static int mbuf_size = 0; static int max_mem_used = -1; static int next_table_index = 0; static int dive_to_read = 0; static uint32_t mindiveid; /* Linked list to remember already executed divespot download requests */ struct divespot_mapping { int divespot_id; struct dive_site *dive_site; struct divespot_mapping *next; }; static struct divespot_mapping *divespot_mapping = NULL; static void erase_divespot_mapping() { struct divespot_mapping *tmp; while (divespot_mapping != NULL) { tmp = divespot_mapping; divespot_mapping = tmp->next; free(tmp); } divespot_mapping = NULL; } static void add_to_divespot_mapping(int divespot_id, struct dive_site *ds) { struct divespot_mapping *ndm = (struct divespot_mapping*)calloc(1, sizeof(struct divespot_mapping)); struct divespot_mapping **pdm = &divespot_mapping; struct divespot_mapping *cdm = *pdm; while (cdm && cdm->next) cdm = cdm->next; ndm->divespot_id = divespot_id; ndm->dive_site = ds; ndm->next = NULL; if (cdm) cdm->next = ndm; else cdm = *pdm = ndm; } static bool is_divespot_mappable(int divespot_id) { struct divespot_mapping *dm = divespot_mapping; while (dm) { if (dm->divespot_id == divespot_id) return true; dm = dm->next; } return false; } static struct dive_site *get_dive_site_by_divespot_id(int divespot_id) { struct divespot_mapping *dm = divespot_mapping; while (dm) { if (dm->divespot_id == divespot_id) return dm->dive_site; dm = dm->next; } return NULL; } /* helper function to parse the Uemis data structures */ static void uemis_ts(char *buffer, void *_when) { struct tm tm; timestamp_t *when = _when; memset(&tm, 0, sizeof(tm)); sscanf(buffer, "%d-%d-%dT%d:%d:%d", &tm.tm_year, &tm.tm_mon, &tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec); tm.tm_mon -= 1; *when = utc_mktime(&tm); } /* float minutes */ static void uemis_duration(char *buffer, duration_t *duration) { duration->seconds = lrint(ascii_strtod(buffer, NULL) * 60); } /* int cm */ static void uemis_depth(char *buffer, depth_t *depth) { depth->mm = atoi(buffer) * 10; } static void uemis_get_index(char *buffer, int *idx) { *idx = atoi(buffer); } /* space separated */ static void uemis_add_string(const char *buffer, char **text, const char *delimit) { /* do nothing if this is an empty buffer (Uemis sometimes returns a single * space for empty buffers) */ if (empty_string(buffer) || (*buffer == ' ' && *(buffer + 1) == '\0')) return; if (!*text) { *text = strdup(buffer); } else { char *buf = malloc(strlen(buffer) + strlen(*text) + 2); strcpy(buf, *text); strcat(buf, delimit); strcat(buf, buffer); free(*text); *text = buf; } } /* still unclear if it ever reports lbs */ static void uemis_get_weight(char *buffer, weightsystem_t *weight, int diveid) { weight->weight.grams = uemis_get_weight_unit(diveid) ? lbs_to_grams(ascii_strtod(buffer, NULL)) : lrint(ascii_strtod(buffer, NULL) * 1000); weight->description = translate("gettextFromC", "unknown"); } static struct dive *uemis_start_dive(uint32_t deviceid) { struct dive *dive = alloc_dive(); dive->dc.model = strdup("Uemis Zurich"); dive->dc.deviceid = deviceid; return dive; } static struct dive *get_dive_by_uemis_diveid(device_data_t *devdata, uint32_t object_id) { for (int i = 0; i < devdata->download_table->nr; i++) { if (object_id == devdata->download_table->dives[i]->dc.diveid) return devdata->download_table->dives[i]; } return NULL; } /* send text to the importer progress bar */ static void uemis_info(const char *fmt, ...) { static char buffer[256]; va_list ap; va_start(ap, fmt); vsnprintf(buffer, sizeof(buffer), fmt, ap); va_end(ap); progress_bar_text = buffer; if (verbose) fprintf(stderr, "Uemis downloader: %s\n", buffer); } static long bytes_available(int file) { long result, r2; long now = lseek(file, 0, SEEK_CUR); if (now == -1) return 0; result = lseek(file, 0, SEEK_END); r2 = lseek(file, now, SEEK_SET); if (now == -1 || result == -1 || r2 == -1) return 0; return result; } static int number_of_file(char *path) { int count = 0; #ifdef WIN32 struct _wdirent *entry; _WDIR *dirp = (_WDIR *)subsurface_opendir(path); #else struct dirent *entry; DIR *dirp = (DIR *)subsurface_opendir(path); #endif while (dirp) { #ifdef WIN32 entry = _wreaddir(dirp); if (!entry) break; #else entry = readdir(dirp); if (!entry) break; if (strstr(entry->d_name, ".TXT") || strstr(entry->d_name, ".txt")) /* If the entry is a regular file */ #endif count++; } #ifdef WIN32 _wclosedir(dirp); #else closedir(dirp); #endif return count; } static char *build_filename(const char *path, const char *name) { int len = strlen(path) + strlen(name) + 2; char *buf = malloc(len); #if WIN32 snprintf(buf, len, "%s\\%s", path, name); #else snprintf(buf, len, "%s/%s", path, name); #endif return buf; } /* Check if there's a req.txt file and get the starting filenr from it. * Test for the maximum number of ANS files (I believe this is always * 4000 but in case there are differences depending on firmware, this * code is easy enough */ static bool uemis_init(const char *path) { char *ans_path; int i; erase_divespot_mapping(); if (!path) return false; /* let's check if this is indeed a Uemis DC */ reqtxt_path = build_filename(path, "req.txt"); reqtxt_file = subsurface_open(reqtxt_path, O_RDONLY | O_CREAT, 0666); if (reqtxt_file < 0) { #if UEMIS_DEBUG & 1 fprintf(debugfile, ":EE req.txt can't be opened\n"); #endif return false; } if (bytes_available(reqtxt_file) > 5) { char tmp[6]; if (read(reqtxt_file, tmp, 5) != 5) return false; tmp[5] = '\0'; #if UEMIS_DEBUG & 2 fprintf(debugfile, "::r req.txt \"%s\"\n", tmp); #endif if (sscanf(tmp + 1, "%d", &filenr) != 1) return false; } else { filenr = 0; #if UEMIS_DEBUG & 2 fprintf(debugfile, "::r req.txt skipped as there were fewer than 5 bytes\n"); #endif } close(reqtxt_file); /* It would be nice if we could simply go back to the first set of * ANS files. But with a FAT filesystem that isn't possible */ ans_path = build_filename(path, "ANS"); number_of_files = number_of_file(ans_path); free(ans_path); /* initialize the array in which we collect the answers */ for (i = 0; i < NUM_PARAM_BUFS; i++) param_buff[i] = ""; return true; } static void str_append_with_delim(char *s, char *t) { int len = strlen(s); snprintf(s + len, BUFLEN - len, "%s{", t); } /* The communication protocol with the DC is truly funky. * After you write your request to the req.txt file you call this function. * It writes the number of the next ANS file at the beginning of the req.txt * file (prefixed by 'n' or 'r') and then again at the very end of it, after * the full request (this time without the prefix). * Then it syncs (not needed on Windows) and closes the file. */ static void trigger_response(int file, char *command, int nr, long tailpos) { char fl[10]; snprintf(fl, 8, "%s%04d", command, nr); #if UEMIS_DEBUG & 4 fprintf(debugfile, ":tr %s (after seeks)\n", fl); #endif if (lseek(file, 0, SEEK_SET) == -1) goto fs_error; if (write(file, fl, strlen(fl)) == -1) goto fs_error; if (lseek(file, tailpos, SEEK_SET) == -1) goto fs_error; if (write(file, fl + 1, strlen(fl + 1)) == -1) goto fs_error; #ifndef WIN32 fsync(file); #endif fs_error: close(file); } static char *next_token(char **buf) { char *q, *p = strchr(*buf, '{'); if (p) *p = '\0'; else p = *buf + strlen(*buf) - 1; q = *buf; *buf = p + 1; return q; } /* poor man's tokenizer that understands a quoted delimiter ('{') */ static char *next_segment(char *buf, int *offset, int size) { int i = *offset; int seg_size; bool done = false; char *segment; while (!done) { if (i < size) { if (i < size - 1 && buf[i] == '\\' && (buf[i + 1] == '\\' || buf[i + 1] == '{')) memcpy(buf + i, buf + i + 1, size - i - 1); else if (buf[i] == '{') done = true; i++; } else { done = true; } } seg_size = i - *offset - 1; if (seg_size < 0) seg_size = 0; segment = malloc(seg_size + 1); memcpy(segment, buf + *offset, seg_size); segment[seg_size] = '\0'; *offset = i; return segment; } /* a dynamically growing buffer to store the potentially massive responses. * The binary data block can be more than 100k in size (base64 encoded) */ static void buffer_add(char **buffer, int *buffer_size, char *buf) { if (!buf) return; if (!*buffer) { *buffer = strdup(buf); *buffer_size = strlen(*buffer) + 1; } else { *buffer_size += strlen(buf); *buffer = realloc(*buffer, *buffer_size); strcat(*buffer, buf); } #if UEMIS_DEBUG & 8 fprintf(debugfile, "added \"%s\" to buffer - new length %d\n", buf, *buffer_size); #endif } /* are there more ANS files we can check? */ static bool next_file(int max) { if (filenr >= max) return false; filenr++; return true; } /* try and do a quick decode - without trying to get to fancy in case the data * straddles a block boundary... * we are parsing something that looks like this: * object_id{int{2{date{ts{2011-04-05T12:38:04{duration{float{12.000... */ static char *first_object_id_val(char *buf) { char *object, *bufend; if (!buf) return NULL; bufend = buf + strlen(buf); object = strstr(buf, "object_id"); if (object && object + 14 < bufend) { /* get the value */ char tmp[36]; char *p = object + 14; char *t = tmp; #if UEMIS_DEBUG & 4 char debugbuf[50]; strncpy(debugbuf, object, 49); debugbuf[49] = '\0'; fprintf(debugfile, "buf |%s|\n", debugbuf); #endif while (p < bufend && *p != '{' && t < tmp + 9) *t++ = *p++; if (*p == '{') { /* found the object_id - let's quickly look for the date */ if (strncmp(p, "{date{ts{", 9) == 0 && strstr(p, "{duration{") != NULL) { /* cool - that was easy */ *t++ = ','; *t++ = ' '; /* skip the 9 characters we just found and take the date, ignoring the seconds * and replace the silly 'T' in the middle with a space */ strncpy(t, p + 9, 16); if (*(t + 10) == 'T') *(t + 10) = ' '; t += 16; } *t = '\0'; return strdup(tmp); } } return NULL; } /* ultra-simplistic; it doesn't deal with the case when the object_id is * split across two chunks. It also doesn't deal with the discrepancy between * object_id and dive number as understood by the dive computer */ static void show_progress(char *buf, const char *what) { char *val = first_object_id_val(buf); if (val) { /* let the user know what we are working on */ #if UEMIS_DEBUG & 8 fprintf(debugfile, "reading %s\n %s\n %s\n", what, val, buf); #endif uemis_info(translate("gettextFromC", "%s %s"), what, val); free(val); } } static void uemis_increased_timeout(int *timeout) { if (*timeout < UEMIS_MAX_TIMEOUT) *timeout += UEMIS_LONG_TIMEOUT; usleep(*timeout); } static char *build_ans_path(const char *path, int filenumber) { char *intermediate, *ans_path, fl[13]; /* Clamp filenumber into the 0..9999 range. This is never necessary, * as filenumber can never go above UEMIS_MAX_FILES, but gcc doesn't * recognize that and produces very noisy warnings. */ filenumber = filenumber < 0 ? 0 : filenumber % 10000; snprintf(fl, 13, "ANS%d.TXT", filenumber); intermediate = build_filename(path, "ANS"); ans_path = build_filename(intermediate, fl); free(intermediate); return ans_path; } /* send a request to the dive computer and collect the answer */ static bool uemis_get_answer(const char *path, char *request, int n_param_in, int n_param_out, const char **error_text) { int i = 0, file_length; char sb[BUFLEN]; char fl[13]; char tmp[101]; const char *what = translate("gettextFromC", "data"); bool searching = true; bool assembling_mbuf = false; bool ismulti = false; bool found_answer = false; bool more_files = true; bool answer_in_mbuf = false; char *ans_path; int ans_file; int timeout = UEMIS_LONG_TIMEOUT; reqtxt_file = subsurface_open(reqtxt_path, O_RDWR | O_CREAT, 0666); if (reqtxt_file < 0) { *error_text = "can't open req.txt"; #ifdef UEMIS_DEBUG fprintf(debugfile, "open %s failed with errno %d\n", reqtxt_path, errno); #endif return false; } snprintf(sb, BUFLEN, "n%04d12345678", filenr); str_append_with_delim(sb, request); for (i = 0; i < n_param_in; i++) str_append_with_delim(sb, param_buff[i]); if (!strcmp(request, "getDivelogs") || !strcmp(request, "getDeviceData") || !strcmp(request, "getDirectory") || !strcmp(request, "getDivespot") || !strcmp(request, "getDive")) { answer_in_mbuf = true; str_append_with_delim(sb, ""); if (!strcmp(request, "getDivelogs")) what = translate("gettextFromC", "dive log #"); else if (!strcmp(request, "getDivespot")) what = translate("gettextFromC", "dive spot #"); else if (!strcmp(request, "getDive")) what = translate("gettextFromC", "details for #"); } str_append_with_delim(sb, ""); file_length = strlen(sb); snprintf(fl, 10, "%08d", file_length - 13); memcpy(sb + 5, fl, strlen(fl)); #if UEMIS_DEBUG & 4 fprintf(debugfile, "::w req.txt \"%s\"\n", sb); #endif int written = write(reqtxt_file, sb, strlen(sb)); if (written == -1 || (size_t)written != strlen(sb)) { *error_text = translate("gettextFromC", ERR_FS_SHORT_WRITE); return false; } if (!next_file(number_of_files)) { *error_text = translate("gettextFromC", ERR_FS_FULL); more_files = false; } trigger_response(reqtxt_file, "n", filenr, file_length); usleep(timeout); free(mbuf); mbuf = NULL; mbuf_size = 0; while (searching || assembling_mbuf) { if (import_thread_cancelled) return false; progress_bar_fraction = filenr / (double)UEMIS_MAX_FILES; ans_path = build_ans_path(path, filenr - 1); ans_file = subsurface_open(ans_path, O_RDONLY, 0666); if (ans_file < 0) { *error_text = "can't open Uemis response file"; #ifdef UEMIS_DEBUG fprintf(debugfile, "open %s failed with errno %d\n", ans_path, errno); #endif free(ans_path); return false; } if (read(ans_file, tmp, 100) < 3) { free(ans_path); close(ans_file); return false; } close(ans_file); #if UEMIS_DEBUG & 8 tmp[100] = '\0'; fprintf(debugfile, "::t %s \"%s\"\n", ans_path, tmp); #elif UEMIS_DEBUG & 4 char pbuf[4]; pbuf[0] = tmp[0]; pbuf[1] = tmp[1]; pbuf[2] = tmp[2]; pbuf[3] = 0; fprintf(debugfile, "::t %s \"%s...\"\n", ans_path, pbuf); #endif free(ans_path); if (tmp[0] == '1') { searching = false; if (tmp[1] == 'm') { assembling_mbuf = true; ismulti = true; } if (tmp[2] == 'e') assembling_mbuf = false; if (assembling_mbuf) { if (!next_file(number_of_files)) { *error_text = translate("gettextFromC", ERR_FS_FULL); more_files = false; assembling_mbuf = false; } reqtxt_file = subsurface_open(reqtxt_path, O_RDWR | O_CREAT, 0666); if (reqtxt_file < 0) { *error_text = "can't open req.txt"; fprintf(stderr, "open %s failed with errno %d\n", reqtxt_path, errno); return false; } trigger_response(reqtxt_file, "n", filenr, file_length); } } else { if (!next_file(number_of_files - 1)) { *error_text = translate("gettextFromC", ERR_FS_FULL); more_files = false; assembling_mbuf = false; searching = false; } reqtxt_file = subsurface_open(reqtxt_path, O_RDWR | O_CREAT, 0666); if (reqtxt_file < 0) { *error_text = "can't open req.txt"; fprintf(stderr, "open %s failed with errno %d\n", reqtxt_path, errno); return false; } trigger_response(reqtxt_file, "r", filenr, file_length); uemis_increased_timeout(&timeout); } if (ismulti && more_files && tmp[0] == '1') { int size; ans_path = build_ans_path(path, assembling_mbuf ? filenr - 2 : filenr - 1); ans_file = subsurface_open(ans_path, O_RDONLY, 0666); if (ans_file < 0) { *error_text = "can't open Uemis response file"; #ifdef UEMIS_DEBUG fprintf(debugfile, "open %s failed with errno %d\n", ans_path, errno); #endif free(ans_path); return false; } free(ans_path); size = bytes_available(ans_file); if (size > 3) { char *buf; int r; if (lseek(ans_file, 3, SEEK_CUR) == -1) goto fs_error; buf = malloc(size - 2); if ((r = read(ans_file, buf, size - 3)) != size - 3) { free(buf); goto fs_error; } buf[r] = '\0'; buffer_add(&mbuf, &mbuf_size, buf); show_progress(buf, what); free(buf); param_buff[3]++; } close(ans_file); timeout = UEMIS_TIMEOUT; usleep(UEMIS_TIMEOUT); } } if (more_files) { int size = 0, j = 0; char *buf = NULL; if (!ismulti) { ans_path = build_ans_path(path, filenr - 1); ans_file = subsurface_open(ans_path, O_RDONLY, 0666); if (ans_file < 0) { *error_text = "can't open Uemis response file"; #ifdef UEMIS_DEBUG fprintf(debugfile, "open %s failed with errno %d\n", ans_path, errno); #endif free(ans_path); return false; } size = bytes_available(ans_file); if (size > 3) { int r; if (lseek(ans_file, 3, SEEK_CUR) == -1) goto fs_error; buf = malloc(size - 2); if ((r = read(ans_file, buf, size - 3)) != size - 3) { free(buf); goto fs_error; } buf[r] = '\0'; buffer_add(&mbuf, &mbuf_size, buf); show_progress(buf, what); #if UEMIS_DEBUG & 8 fprintf(debugfile, "::r %s \"%s\"\n", ans_path, buf); #endif } size -= 3; free(ans_path); close(ans_file); } else { ismulti = false; } #if UEMIS_DEBUG & 8 fprintf(debugfile, ":r: %s\n", buf); #endif if (!answer_in_mbuf) for (i = 0; i < n_param_out && j < size; i++) param_buff[i] = next_segment(buf, &j, size); found_answer = true; free(buf); } #if UEMIS_DEBUG & 1 for (i = 0; i < n_param_out; i++) fprintf(debugfile, "::: %d: %s\n", i, param_buff[i]); #endif return found_answer; fs_error: close(ans_file); return false; } static bool parse_divespot(char *buf) { char *bp = buf + 1; char *tp = next_token(&bp); char *tag, *type, *val; char locationstring[1024] = ""; int divespot, len; double latitude = 0.0, longitude = 0.0; // dive spot got deleted, so fail here if (strstr(bp, "deleted{bool{true")) return false; // not a dive spot, fail here if (strcmp(tp, "divespot")) return false; do tag = next_token(&bp); while (*tag && strcmp(tag, "object_id")); if (!*tag) return false; next_token(&bp); val = next_token(&bp); divespot = atoi(val); do { tag = next_token(&bp); type = next_token(&bp); val = next_token(&bp); if (!strcmp(type, "string") && *val && strcmp(val, " ")) { len = strlen(locationstring); snprintf(locationstring + len, sizeof(locationstring) - len, "%s%s", len ? ", " : "", val); } else if (!strcmp(type, "float")) { if (!strcmp(tag, "longitude")) longitude = ascii_strtod(val, NULL); else if (!strcmp(tag, "latitude")) latitude = ascii_strtod(val, NULL); } } while (tag && *tag); uemis_set_divelocation(divespot, locationstring, longitude, latitude); return true; } static char *suit[] = {"", QT_TRANSLATE_NOOP("gettextFromC", "wetsuit"), QT_TRANSLATE_NOOP("gettextFromC", "semidry"), QT_TRANSLATE_NOOP("gettextFromC", "drysuit")}; static char *suit_type[] = {"", QT_TRANSLATE_NOOP("gettextFromC", "shorty"), QT_TRANSLATE_NOOP("gettextFromC", "vest"), QT_TRANSLATE_NOOP("gettextFromC", "long john"), QT_TRANSLATE_NOOP("gettextFromC", "jacket"), QT_TRANSLATE_NOOP("gettextFromC", "full suit"), QT_TRANSLATE_NOOP("gettextFromC", "2 pcs full suit")}; static char *suit_thickness[] = {"", "0.5-2mm", "2-3mm", "3-5mm", "5-7mm", "8mm+", QT_TRANSLATE_NOOP("gettextFromC", "membrane")}; static void parse_tag(struct dive *dive, char *tag, char *val) { /* we can ignore computer_id, water and gas as those are redundant * with the binary data and would just get overwritten */ #if UEMIS_DEBUG & 4 if (strcmp(tag, "file_content")) fprintf(debugfile, "Adding to dive %d : %s = %s\n", dive->dc.diveid, tag, val); #endif if (!strcmp(tag, "date")) { uemis_ts(val, &dive->when); } else if (!strcmp(tag, "duration")) { uemis_duration(val, &dive->dc.duration); } else if (!strcmp(tag, "depth")) { uemis_depth(val, &dive->dc.maxdepth); } else if (!strcmp(tag, "file_content")) { uemis_parse_divelog_binary(val, dive); } else if (!strcmp(tag, "altitude")) { uemis_get_index(val, &dive->dc.surface_pressure.mbar); } else if (!strcmp(tag, "f32Weight")) { weightsystem_t ws = empty_weightsystem; uemis_get_weight(val, &ws, dive->dc.diveid); add_cloned_weightsystem(&dive->weightsystems, ws); } else if (!strcmp(tag, "notes")) { uemis_add_string(val, &dive->notes, " "); } else if (!strcmp(tag, "u8DiveSuit")) { if (*suit[atoi(val)]) uemis_add_string(translate("gettextFromC", suit[atoi(val)]), &dive->suit, " "); } else if (!strcmp(tag, "u8DiveSuitType")) { if (*suit_type[atoi(val)]) uemis_add_string(translate("gettextFromC", suit_type[atoi(val)]), &dive->suit, " "); } else if (!strcmp(tag, "u8SuitThickness")) { if (*suit_thickness[atoi(val)]) uemis_add_string(translate("gettextFromC", suit_thickness[atoi(val)]), &dive->suit, " "); } else if (!strcmp(tag, "nickname")) { uemis_add_string(val, &dive->buddy, ","); } } static bool uemis_delete_dive(device_data_t *devdata, uint32_t diveid) { struct dive *dive = NULL; if (devdata->download_table->dives[devdata->download_table->nr - 1]->dc.diveid == diveid) { /* we hit the last one in the array */ dive = devdata->download_table->dives[devdata->download_table->nr - 1]; } else { for (int i = 0; i < devdata->download_table->nr - 1; i++) { if (devdata->download_table->dives[i]->dc.diveid == diveid) { dive = devdata->download_table->dives[i]; for (int x = i; x < devdata->download_table->nr - 1; x++) devdata->download_table->dives[i] = devdata->download_table->dives[x + 1]; } } } if (dive) { devdata->download_table->dives[--devdata->download_table->nr] = NULL; free_dive(dive); return true; } return false; } /* This function is called for both dive log and dive information that we get * from the SDA (what an insane design, btw). The object_id in the dive log * matches the logfilenr in the dive information (which has its own, often * different object_id) - we use this as the diveid. * We create the dive when parsing the dive log and then later, when we parse * the dive information we locate the already created dive via its diveid. * Most things just get parsed and converted into our internal data structures, * but the dive location API is even more crazy. We just get an id that is an * index into yet another data store that we read out later. In order to * correctly populate the location and gps data from that we need to remember * the addresses of those fields for every dive that references the dive spot. */ static bool process_raw_buffer(device_data_t *devdata, uint32_t deviceid, char *inbuf, char **max_divenr, int *for_dive) { char *buf = strdup(inbuf); char *tp, *bp, *tag, *type, *val; bool done = false; int inbuflen = strlen(inbuf); char *endptr = buf + inbuflen; bool is_log = false, is_dive = false; char *sections[10]; size_t s, nr_sections = 0; struct dive *dive = NULL; char dive_no[10]; #if UEMIS_DEBUG & 8 fprintf(debugfile, "p_r_b %s\n", inbuf); #endif if (for_dive) *for_dive = -1; bp = buf + 1; tp = next_token(&bp); if (strcmp(tp, "divelog") == 0) { /* this is a dive log */ is_log = true; tp = next_token(&bp); /* is it a valid entry or nothing ? */ if (strcmp(tp, "1.0") != 0 || strstr(inbuf, "divelog{1.0{{{{")) { free(buf); return false; } } else if (strcmp(tp, "dive") == 0) { /* this is dive detail */ is_dive = true; tp = next_token(&bp); if (strcmp(tp, "1.0") != 0) { free(buf); return false; } } else { /* don't understand the buffer */ free(buf); return false; } if (is_log) { dive = uemis_start_dive(deviceid); } else { /* remember, we don't know if this is the right entry, * so first test if this is even a valid entry */ if (strstr(inbuf, "deleted{bool{true")) { #if UEMIS_DEBUG & 2 fprintf(debugfile, "p_r_b entry deleted\n"); #endif /* oops, this one isn't valid, suggest to try the previous one */ free(buf); return false; } /* quickhack and workaround to capture the original dive_no * I am doing this so I don't have to change the original design * but when parsing a dive we never parse the dive number because * at the time it's being read the *dive variable is not set because * the dive_no tag comes before the object_id in the uemis ans file */ dive_no[0] = '\0'; char *dive_no_buf = strdup(inbuf); char *dive_no_ptr = strstr(dive_no_buf, "dive_no{int{") + 12; if (dive_no_ptr) { char *dive_no_end = strstr(dive_no_ptr, "{"); if (dive_no_end) { *dive_no_end = '\0'; strncpy(dive_no, dive_no_ptr, 9); dive_no[9] = '\0'; } } free(dive_no_buf); } while (!done) { /* the valid buffer ends with a series of delimiters */ if (bp >= endptr - 2 || !strcmp(bp, "{{")) break; tag = next_token(&bp); /* we also end if we get an empty tag */ if (*tag == '\0') break; for (s = 0; s < nr_sections; s++) if (!strcmp(tag, sections[s])) { tag = next_token(&bp); break; } type = next_token(&bp); if (!strcmp(type, "1.0")) { /* this tells us the sections that will follow; the tag here * is of the format dive-<section> */ sections[nr_sections] = strchr(tag, '-') + 1; #if UEMIS_DEBUG & 4 fprintf(debugfile, "Expect to find section %s\n", sections[nr_sections]); #endif if (nr_sections < sizeof(sections) / sizeof(*sections) - 1) nr_sections++; continue; } val = next_token(&bp); #if UEMIS_DEBUG & 8 if (strlen(val) < 20) fprintf(debugfile, "Parsed %s, %s, %s\n*************************\n", tag, type, val); #endif if (is_log && strcmp(tag, "object_id") == 0) { free(*max_divenr); *max_divenr = strdup(val); dive->dc.diveid = atoi(val); #if UEMIS_DEBUG % 2 fprintf(debugfile, "Adding new dive from log with object_id %d.\n", atoi(val)); #endif } else if (is_dive && strcmp(tag, "logfilenr") == 0) { /* this one tells us which dive we are adding data to */ dive = get_dive_by_uemis_diveid(devdata, atoi(val)); if (strcmp(dive_no, "0")) dive->number = atoi(dive_no); if (for_dive) *for_dive = atoi(val); } else if (!is_log && dive && !strcmp(tag, "divespot_id")) { int divespot_id = atoi(val); if (divespot_id != -1) { struct dive_site *ds = create_dive_site("from Uemis", devdata->sites); unregister_dive_from_dive_site(dive); add_dive_to_dive_site(dive, ds); uemis_mark_divelocation(dive->dc.diveid, divespot_id, ds); } #if UEMIS_DEBUG & 2 fprintf(debugfile, "Created divesite %d for diveid : %d\n", dive->dive_site->uuid, dive->dc.diveid); #endif } else if (dive) { parse_tag(dive, tag, val); } if (is_log && !strcmp(tag, "file_content")) done = true; /* done with one dive (got the file_content tag), but there could be more: * a '{' indicates the end of the record - but we need to see another "{{" * later in the buffer to know that the next record is complete (it could * be a short read because of some error */ if (done && ++bp < endptr && *bp != '{' && strstr(bp, "{{")) { done = false; record_dive_to_table(dive, devdata->download_table); dive = uemis_start_dive(deviceid); } } if (is_log) { if (dive->dc.diveid) { record_dive_to_table(dive, devdata->download_table); } else { /* partial dive */ free_dive(dive); free(buf); return false; } } free(buf); return true; } static char *uemis_get_divenr(char *deviceidstr, struct dive_table *table, int force) { uint32_t deviceid, maxdiveid = 0; int i; char divenr[10]; deviceid = atoi(deviceidstr); mindiveid = 0xFFFFFFFF; /* * If we are are retrying after a disconnect/reconnect, we * will look up the highest dive number in the dives we * already have. * * Also, if "force_download" is true, do this even if we * don't have any dives (maxdiveid will remain ~0). * * Otherwise, use the global dive table. */ if (!force && !table->nr) table = &dive_table; for (i = 0; i < table->nr; i++) { struct dive *d = table->dives[i]; struct divecomputer *dc; if (!d) continue; for_each_dc (d, dc) { if (dc->model && !strcmp(dc->model, "Uemis Zurich") && (dc->deviceid == 0 || dc->deviceid == 0x7fffffff || dc->deviceid == deviceid)) { if (dc->diveid > maxdiveid) maxdiveid = dc->diveid; if (dc->diveid < mindiveid) mindiveid = dc->diveid; } } } snprintf(divenr, 10, "%d", maxdiveid); return strdup(divenr); } #if UEMIS_DEBUG static int bufCnt = 0; static bool do_dump_buffer_to_file(char *buf, char *prefix) { char path[100]; char date[40]; char obid[40]; bool success; if (!buf) return false; if (strstr(buf, "date{ts{")) strncpy(date, strstr(buf, "date{ts{"), sizeof(date)); else strncpy(date, "date{ts{no-date{", sizeof(date)); if (!strstr(buf, "object_id{int{")) return false; strncpy(obid, strstr(buf, "object_id{int{"), sizeof(obid)); char *ptr1 = strstr(date, "date{ts{"); char *ptr2 = strstr(obid, "object_id{int{"); char *pdate = next_token(&ptr1); pdate = next_token(&ptr1); pdate = next_token(&ptr1); char *pobid = next_token(&ptr2); pobid = next_token(&ptr2); pobid = next_token(&ptr2); snprintf(path, sizeof(path), "/%s/%s/UEMIS Dump/%s_%s_Uemis_dump_%s_in_round_%d_%d.txt", home, user, prefix, pdate, pobid, debug_round, bufCnt); int dumpFile = subsurface_open(path, O_RDWR | O_CREAT, 0666); if (dumpFile == -1) return false; success = write(dumpFile, buf, strlen(buf)) == strlen(buf); close(dumpFile); bufCnt++; return success; } #endif /* do some more sophisticated calculations here to try and predict if the next round of * divelog/divedetail reads will fit into the UEMIS buffer, * filenr holds now the uemis filenr after having read several logs including the dive details, * fCapacity will five us the average number of files needed for all currently loaded data * remember the maximum file usage per dive * return : UEMIS_MEM_OK if there is enough memory for a full round * UEMIS_MEM_CRITICAL if the memory is good for reading the dive logs * UEMIS_MEM_FULL if the memory is exhausted */ static int get_memory(struct dive_table *td, int checkpoint) { if (td->nr <= 0) return UEMIS_MEM_OK; switch (checkpoint) { case UEMIS_CHECK_LOG: if (filenr / td->nr > max_mem_used) max_mem_used = filenr / td->nr; /* check if a full block of dive logs + dive details and dive spot fit into the UEMIS buffer */ #if UEMIS_DEBUG & 4 fprintf(debugfile, "max_mem_used %d (from td->nr %d) * block_size %d > max_files %d - filenr %d?\n", max_mem_used, td->nr, UEMIS_LOG_BLOCK_SIZE, UEMIS_MAX_FILES, filenr); #endif if (max_mem_used * UEMIS_LOG_BLOCK_SIZE > UEMIS_MAX_FILES - filenr) return UEMIS_MEM_FULL; break; case UEMIS_CHECK_DETAILS: /* check if the next set of dive details and dive spot fit into the UEMIS buffer */ if ((UEMIS_DIVE_DETAILS_SIZE + UEMIS_SPOT_BLOCK_SIZE) * UEMIS_LOG_BLOCK_SIZE > UEMIS_MAX_FILES - filenr) return UEMIS_MEM_FULL; break; case UEMIS_CHECK_SINGLE_DIVE: if (UEMIS_DIVE_DETAILS_SIZE + UEMIS_SPOT_BLOCK_SIZE > UEMIS_MAX_FILES - filenr) return UEMIS_MEM_FULL; break; } return UEMIS_MEM_OK; } /* we misuse the hidden_by_filter flag to mark a dive as deleted. * this will be picked up by some cleaning statement later. */ static void do_delete_dives(struct dive_table *td, int idx) { for (int x = idx; x < td->nr; x++) td->dives[x]->hidden_by_filter = true; } static bool load_uemis_divespot(const char *mountpath, int divespot_id) { char divespotnr[32]; snprintf(divespotnr, sizeof(divespotnr), "%d", divespot_id); param_buff[2] = divespotnr; #if UEMIS_DEBUG & 2 fprintf(debugfile, "getDivespot %d\n", divespot_id); #endif bool success = uemis_get_answer(mountpath, "getDivespot", 3, 0, NULL); if (mbuf && success) { #if UEMIS_DEBUG & 16 do_dump_buffer_to_file(mbuf, "Spot"); #endif return parse_divespot(mbuf); } return false; } static void get_uemis_divespot(device_data_t *devdata, const char *mountpath, int divespot_id, struct dive *dive) { struct dive_site *nds = dive->dive_site; if (is_divespot_mappable(divespot_id)) { struct dive_site *ds = get_dive_site_by_divespot_id(divespot_id); unregister_dive_from_dive_site(dive); add_dive_to_dive_site(dive, ds); } else if (nds && nds->name && strstr(nds->name,"from Uemis")) { if (load_uemis_divespot(mountpath, divespot_id)) { /* get the divesite based on the diveid, this should give us * the newly created site */ struct dive_site *ods; /* with the divesite name we got from parse_dive, that is called on load_uemis_divespot * we search all existing divesites if we have one with the same name already. The function * returns the first found which is luckily not the newly created. */ ods = get_dive_site_by_name(nds->name, devdata->sites); if (ods) { /* if the uuid's are the same, the new site is a duplicate and can be deleted */ if (nds->uuid != ods->uuid) { delete_dive_site(nds, devdata->sites); unregister_dive_from_dive_site(dive); add_dive_to_dive_site(dive, ods); } } add_to_divespot_mapping(divespot_id, dive->dive_site); } else { /* if we can't load the dive site details, delete the site we * created in process_raw_buffer */ delete_dive_site(dive->dive_site, devdata->sites); } } } static bool get_matching_dive(int idx, char *newmax, int *uemis_mem_status, device_data_t *data, const char *mountpath, const char deviceidnr) { struct dive *dive = data->download_table->dives[idx]; char log_file_no_to_find[20]; char dive_to_read_buf[10]; bool found = false; bool found_below = false; bool found_above = false; int deleted_files = 0; int fail_count = 0; snprintf(log_file_no_to_find, sizeof(log_file_no_to_find), "logfilenr{int{%d", dive->dc.diveid); #if UEMIS_DEBUG & 2 fprintf(debugfile, "Looking for dive details to go with dive log id %d\n", dive->dc.diveid); #endif while (!found) { if (import_thread_cancelled) break; snprintf(dive_to_read_buf, sizeof(dive_to_read_buf), "%d", dive_to_read); param_buff[2] = dive_to_read_buf; (void)uemis_get_answer(mountpath, "getDive", 3, 0, NULL); #if UEMIS_DEBUG & 16 do_dump_buffer_to_file(mbuf, "Dive"); #endif *uemis_mem_status = get_memory(data->download_table, UEMIS_CHECK_SINGLE_DIVE); if (*uemis_mem_status == UEMIS_MEM_OK) { /* if the memory isn's completely full we can try to read more dive log vs. dive details * UEMIS_MEM_CRITICAL means not enough space for a full round but the dive details * and the dive spots should fit into the UEMIS memory * The match we do here is to map the object_id to the logfilenr, we do this * by iterating through the last set of loaded dive logs and then find the corresponding * dive with the matching logfilenr */ if (mbuf) { if (strstr(mbuf, log_file_no_to_find)) { /* we found the logfilenr that matches our object_id from the dive log we were looking for * we mark the search successful even if the dive has been deleted. */ found = true; if (strstr(mbuf, "deleted{bool{true") == NULL) { process_raw_buffer(data, deviceidnr, mbuf, &newmax, NULL); /* remember the last log file number as it is very likely that subsequent dives * have the same or higher logfile number. * UEMIS unfortunately deletes dives by deleting the dive details and not the logs. */ #if UEMIS_DEBUG & 2 d_time = get_dive_date_c_string(dive->when); fprintf(debugfile, "Matching dive log id %d from %s with dive details %d\n", dive->dc.diveid, d_time, dive_to_read); #endif int divespot_id = uemis_get_divespot_id_by_diveid(dive->dc.diveid); if (divespot_id >= 0) get_uemis_divespot(data, mountpath, divespot_id, dive); } else { /* in this case we found a deleted file, so let's increment */ #if UEMIS_DEBUG & 2 d_time = get_dive_date_c_string(dive->when); fprintf(debugfile, "TRY matching dive log id %d from %s with dive details %d but details are deleted\n", dive->dc.diveid, d_time, dive_to_read); #endif deleted_files++; /* mark this log entry as deleted and cleanup later, otherwise we mess up our array */ dive->hidden_by_filter = true; #if UEMIS_DEBUG & 2 fprintf(debugfile, "Deleted dive from %s, with id %d from table -- newmax is %s\n", d_time, dive->dc.diveid, newmax); #endif } } else { uint32_t nr_found = 0; char *logfilenr = strstr(mbuf, "logfilenr"); if (logfilenr && strstr(mbuf, "act{")) { sscanf(logfilenr, "logfilenr{int{%u", &nr_found); if (nr_found >= dive->dc.diveid || nr_found == 0) { found_above = true; dive_to_read = dive_to_read - 2; } else { found_below = true; } if (dive_to_read < -1) dive_to_read = -1; } else if (!strstr(mbuf, "act{") && ++fail_count == 10) { if (verbose) fprintf(stderr, "Uemis downloader: Cannot access dive details - searching from start\n"); dive_to_read = -1; } } } if (found_above && found_below) break; dive_to_read++; } else { /* At this point the memory of the UEMIS is full, let's cleanup all dive log files were * we could not match the details to. */ do_delete_dives(data->download_table, idx); return false; } } /* decrement iDiveToRead by the amount of deleted entries found to assure * we are not missing any valid matches when processing subsequent logs */ dive_to_read = (dive_to_read - deleted_files > 0 ? dive_to_read - deleted_files : 0); deleted_files = 0; return true; } const char *do_uemis_import(device_data_t *data) { const char *mountpath = data->devname; short force_download = data->force_download; char *newmax = NULL; int first, start, end = -2; uint32_t deviceidnr; char *deviceid = NULL; const char *result = NULL; char *endptr; bool success, once = true; int match_dive_and_log = 0; int dive_offset = 0; int uemis_mem_status = UEMIS_MEM_OK; // To speed up sync you can skip downloading old dives by defining UEMIS_DIVE_OFFSET if (getenv("UEMIS_DIVE_OFFSET")) { dive_offset = atoi(getenv("UEMIS_DIVE_OFFSET")); printf("Uemis: Using dive # offset %d\n", dive_offset); } #if UEMIS_DEBUG home = getenv("HOME"); user = getenv("LOGNAME"); #endif uemis_info(translate("gettextFromC", "Initialise communication")); if (!uemis_init(mountpath)) { free(reqtxt_path); return translate("gettextFromC", "Uemis init failed"); } if (!uemis_get_answer(mountpath, "getDeviceId", 0, 1, &result)) goto bail; deviceid = strdup(param_buff[0]); deviceidnr = atoi(deviceid); /* param_buff[0] is still valid */ if (!uemis_get_answer(mountpath, "initSession", 1, 6, &result)) goto bail; uemis_info(translate("gettextFromC", "Start download")); if (!uemis_get_answer(mountpath, "processSync", 0, 2, &result)) goto bail; /* before starting the long download, check if user pressed cancel */ if (import_thread_cancelled) goto bail; param_buff[1] = "notempty"; newmax = uemis_get_divenr(deviceid, data->download_table, force_download); if (verbose) fprintf(stderr, "Uemis downloader: start looking at dive nr %s\n", newmax); first = start = atoi(newmax); dive_to_read = mindiveid < first ? first - mindiveid : first; if (dive_offset > 0) start += dive_offset; for (;;) { #if UEMIS_DEBUG & 2 debug_round++; #endif #if UEMIS_DEBUG & 4 fprintf(debugfile, "d_u_i inner loop start %d end %d newmax %s\n", start, end, newmax); #endif /* start at the last filled download table index */ match_dive_and_log = data->download_table->nr; sprintf(newmax, "%d", start); param_buff[2] = newmax; param_buff[3] = 0; success = uemis_get_answer(mountpath, "getDivelogs", 3, 0, &result); uemis_mem_status = get_memory(data->download_table, UEMIS_CHECK_DETAILS); /* first, remove any leading garbage... this needs to start with a '{' */ char *realmbuf = mbuf; if (mbuf) realmbuf = strchr(mbuf, '{'); if (success && realmbuf && uemis_mem_status != UEMIS_MEM_FULL) { #if UEMIS_DEBUG & 16 do_dump_buffer_to_file(realmbuf, "Dive logs"); #endif /* process the buffer we have assembled */ if (!process_raw_buffer(data, deviceidnr, realmbuf, &newmax, NULL)) { /* if no dives were downloaded, mark end appropriately */ if (end == -2) end = start - 1; success = false; } if (once) { char *t = first_object_id_val(realmbuf); if (t && atoi(t) > start) start = atoi(t); free(t); once = false; } /* clean up mbuf */ endptr = strstr(realmbuf, "{{{"); if (endptr) *(endptr + 2) = '\0'; /* last object_id we parsed */ sscanf(newmax, "%d", &end); #if UEMIS_DEBUG & 4 fprintf(debugfile, "d_u_i after download and parse start %d end %d newmax %s progress %4.2f\n", start, end, newmax, progress_bar_fraction); #endif /* The way this works is that I am reading the current dive from what has been loaded during the getDiveLogs call to the UEMIS. * As the object_id of the dive log entry and the object_id of the dive details are not necessarily the same, the match needs * to happen based on the logfilenr. * What the following part does is to optimize the mapping by using * dive_to_read = the dive details entry that need to be read using the object_id * logFileNoToFind = map the logfilenr of the dive details with the object_id = diveid from the get dive logs */ for (int i = match_dive_and_log; i < data->download_table->nr; i++) { bool success = get_matching_dive(i, newmax, &uemis_mem_status, data, mountpath, deviceidnr); if (!success) break; if (import_thread_cancelled) break; } start = end; /* Do some memory checking here */ uemis_mem_status = get_memory(data->download_table, UEMIS_CHECK_LOG); if (uemis_mem_status != UEMIS_MEM_OK) { #if UEMIS_DEBUG & 4 fprintf(debugfile, "d_u_i out of memory, bailing\n"); #endif (void)uemis_get_answer(mountpath, "terminateSync", 0, 3, &result); const char *errormsg = translate("gettextFromC", ACTION_RECONNECT); for (int wait=60; wait >=0; wait--){ uemis_info("%s %ds", errormsg, wait); usleep(1000000); } // Resetting to original state filenr = 0; max_mem_used = -1; uemis_mem_status = get_memory(data->download_table, UEMIS_CHECK_DETAILS); if (!uemis_get_answer(mountpath, "getDeviceId", 0, 1, &result)) goto bail; if (strcmp(deviceid, param_buff[0]) != 0) { fprintf(stderr, "Uemis: Device id has changed after reconnect!\n"); goto bail; } param_buff[0] = strdup(deviceid); if (!uemis_get_answer(mountpath, "initSession", 1, 6, &result)) goto bail; uemis_info(translate("gettextFromC", "Start download")); if (!uemis_get_answer(mountpath, "processSync", 0, 2, &result)) goto bail; param_buff[1] = "notempty"; } /* if the user clicked cancel, exit gracefully */ if (import_thread_cancelled) { #if UEMIS_DEBUG & 4 fprintf(debugfile, "d_u_i thread canceled, bailing\n"); #endif break; } /* if we got an error or got nothing back, stop trying */ if (!success || !param_buff[3]) { #if UEMIS_DEBUG & 4 fprintf(debugfile, "d_u_i after download nothing found, giving up\n"); #endif break; } #if UEMIS_DEBUG & 2 if (debug_round != -1) if (debug_round-- == 0) { fprintf(debugfile, "d_u_i debug_round is now 0, bailing\n"); goto bail; } #endif } else { /* some of the loading from the UEMIS failed at the dive log level * if the memory status = full, we can't even load the dive spots and/or buddies. * The loaded block of dive logs is useless and all new loaded dive logs need to * be deleted from the download_table. */ if (uemis_mem_status == UEMIS_MEM_FULL) do_delete_dives(data->download_table, match_dive_and_log); #if UEMIS_DEBUG & 4 fprintf(debugfile, "d_u_i out of memory, bailing instead of processing\n"); #endif break; } } if (end == -2 && sscanf(newmax, "%d", &end) != 1) end = start; #if UEMIS_DEBUG & 2 fprintf(debugfile, "Done: read from object_id %d to %d\n", first, end); #endif /* Regardless on where we are with the memory situation, it's time now * to see if we have to clean some dead bodies from our download table */ next_table_index = 0; while (next_table_index < data->download_table->nr) { if (data->download_table->dives[next_table_index]->hidden_by_filter) uemis_delete_dive(data, data->download_table->dives[next_table_index]->dc.diveid); else next_table_index++; } if (uemis_mem_status != UEMIS_MEM_OK) result = translate("gettextFromC", ERR_FS_ALMOST_FULL); bail: (void)uemis_get_answer(mountpath, "terminateSync", 0, 3, &result); if (!strcmp(param_buff[0], "error")) { if (!strcmp(param_buff[2], "Out of Memory")) result = translate("gettextFromC", ERR_FS_FULL); else result = param_buff[2]; } free(deviceid); free(reqtxt_path); if (!data->download_table->nr) result = translate("gettextFromC", ERR_NO_FILES); return result; }
subsurface-for-dirk-master
core/uemis-downloader.c
// SPDX-License-Identifier: GPL-2.0 #ifdef __clang__ // Clang has a bug on zero-initialization of C structs. #pragma clang diagnostic ignored "-Wmissing-field-initializers" #endif #include "ssrf.h" #include "dive.h" #include "parse.h" #include "sample.h" #include "subsurface-string.h" #include "divelist.h" #include "device.h" #include "membuffer.h" #include "gettext.h" #include "tag.h" #include <stdlib.h> static int dm4_events(void *param, int columns, char **data, char **column) { UNUSED(columns); UNUSED(column); struct parser_state *state = (struct parser_state *)param; event_start(state); if (data[1]) state->cur_event.time.seconds = atoi(data[1]); if (data[2]) { switch (atoi(data[2])) { case 1: /* 1 Mandatory Safety Stop */ strcpy(state->cur_event.name, "safety stop (mandatory)"); break; case 3: /* 3 Deco */ /* What is Subsurface's term for going to * deco? */ strcpy(state->cur_event.name, "deco"); break; case 4: /* 4 Ascent warning */ strcpy(state->cur_event.name, "ascent"); break; case 5: /* 5 Ceiling broken */ strcpy(state->cur_event.name, "violation"); break; case 6: /* 6 Mandatory safety stop ceiling error */ strcpy(state->cur_event.name, "violation"); break; case 7: /* 7 Below deco floor */ strcpy(state->cur_event.name, "below floor"); break; case 8: /* 8 Dive time alarm */ strcpy(state->cur_event.name, "divetime"); break; case 9: /* 9 Depth alarm */ strcpy(state->cur_event.name, "maxdepth"); break; case 10: /* 10 OLF 80% */ case 11: /* 11 OLF 100% */ strcpy(state->cur_event.name, "OLF"); break; case 12: /* 12 High pO₂ */ strcpy(state->cur_event.name, "PO2"); break; case 13: /* 13 Air time */ strcpy(state->cur_event.name, "airtime"); break; case 17: /* 17 Ascent warning */ strcpy(state->cur_event.name, "ascent"); break; case 18: /* 18 Ceiling error */ strcpy(state->cur_event.name, "ceiling"); break; case 19: /* 19 Surfaced */ strcpy(state->cur_event.name, "surface"); break; case 20: /* 20 Deco */ strcpy(state->cur_event.name, "deco"); break; case 22: case 32: /* 22 Mandatory safety stop violation */ /* 32 Deep stop violation */ strcpy(state->cur_event.name, "violation"); break; case 30: /* Tissue level warning */ strcpy(state->cur_event.name, "tissue warning"); break; case 37: /* Tank pressure alarm */ strcpy(state->cur_event.name, "tank pressure"); break; case 257: /* 257 Dive active */ /* This seems to be given after surface when * descending again. */ strcpy(state->cur_event.name, "surface"); break; case 258: /* 258 Bookmark */ if (data[3]) { strcpy(state->cur_event.name, "heading"); state->cur_event.value = atoi(data[3]); } else { strcpy(state->cur_event.name, "bookmark"); } break; case 259: /* Deep stop */ strcpy(state->cur_event.name, "Deep stop"); break; case 260: /* Deep stop */ strcpy(state->cur_event.name, "Deep stop cleared"); break; case 266: /* Mandatory safety stop activated */ strcpy(state->cur_event.name, "safety stop (mandatory)"); break; case 267: /* Mandatory safety stop deactivated */ /* DM5 shows this only on event list, not on the * profile so skipping as well for now */ break; default: strcpy(state->cur_event.name, "unknown"); state->cur_event.value = atoi(data[2]); break; } } event_end(state); return 0; } static int dm4_tags(void *param, int columns, char **data, char **column) { UNUSED(columns); UNUSED(column); struct parser_state *state = (struct parser_state *)param; if (data[0]) taglist_add_tag(&state->cur_dive->tag_list, data[0]); return 0; } static int dm4_dive(void *param, int columns, char **data, char **column) { UNUSED(columns); UNUSED(column); int i; int interval, retval = 0; struct parser_state *state = (struct parser_state *)param; sqlite3 *handle = state->sql_handle; float *profileBlob; unsigned char *tempBlob; int *pressureBlob; char get_events_template[] = "select * from Mark where DiveId = %d"; char get_tags_template[] = "select Text from DiveTag where DiveId = %d"; char get_events[64]; cylinder_t *cyl; dive_start(state); state->cur_dive->number = atoi(data[0]); state->cur_dive->when = (time_t)(atol(data[1])); if (data[2]) utf8_string(data[2], &state->cur_dive->notes); /* * DM4 stores Duration and DiveTime. It looks like DiveTime is * 10 to 60 seconds shorter than Duration. However, I have no * idea what is the difference and which one should be used. * Duration = data[3] * DiveTime = data[15] */ if (data[3]) state->cur_dive->duration.seconds = atoi(data[3]); if (data[15]) state->cur_dive->dc.duration.seconds = atoi(data[15]); /* * TODO: the deviceid hash should be calculated here. */ settings_start(state); dc_settings_start(state); if (data[4]) utf8_string(data[4], &state->cur_settings.dc.serial_nr); if (data[5]) utf8_string(data[5], &state->cur_settings.dc.model); state->cur_settings.dc.deviceid = 0xffffffff; dc_settings_end(state); settings_end(state); if (data[6]) state->cur_dive->dc.maxdepth.mm = lrint(strtod_flags(data[6], NULL, 0) * 1000); if (data[8]) state->cur_dive->dc.airtemp.mkelvin = C_to_mkelvin(atoi(data[8])); if (data[9]) state->cur_dive->dc.watertemp.mkelvin = C_to_mkelvin(atoi(data[9])); /* * TODO: handle multiple cylinders */ cyl = cylinder_start(state); if (data[22] && atoi(data[22]) > 0) cyl->start.mbar = atoi(data[22]); else if (data[10] && atoi(data[10]) > 0) cyl->start.mbar = atoi(data[10]); if (data[23] && atoi(data[23]) > 0) cyl->end.mbar = (atoi(data[23])); if (data[11] && atoi(data[11]) > 0) cyl->end.mbar = (atoi(data[11])); if (data[12]) cyl->type.size.mliter = lrint((strtod_flags(data[12], NULL, 0)) * 1000); if (data[13]) cyl->type.workingpressure.mbar = (atoi(data[13])); if (data[20]) cyl->gasmix.o2.permille = atoi(data[20]) * 10; if (data[21]) cyl->gasmix.he.permille = atoi(data[21]) * 10; cylinder_end(state); if (data[14]) state->cur_dive->dc.surface_pressure.mbar = (atoi(data[14]) * 1000); interval = data[16] ? atoi(data[16]) : 0; profileBlob = (float *)data[17]; tempBlob = (unsigned char *)data[18]; pressureBlob = (int *)data[19]; for (i = 0; interval && i * interval < state->cur_dive->duration.seconds; i++) { sample_start(state); state->cur_sample->time.seconds = i * interval; if (profileBlob) state->cur_sample->depth.mm = lrintf(profileBlob[i] * 1000.0f); else state->cur_sample->depth.mm = state->cur_dive->dc.maxdepth.mm; if (data[18] && data[18][0]) state->cur_sample->temperature.mkelvin = C_to_mkelvin(tempBlob[i]); if (data[19] && data[19][0]) state->cur_sample->pressure[0].mbar = pressureBlob[i]; sample_end(state); } snprintf(get_events, sizeof(get_events) - 1, get_events_template, state->cur_dive->number); retval = sqlite3_exec(handle, get_events, &dm4_events, state, NULL); if (retval != SQLITE_OK) { fprintf(stderr, "%s", "Database query dm4_events failed.\n"); return 1; } snprintf(get_events, sizeof(get_events) - 1, get_tags_template, state->cur_dive->number); retval = sqlite3_exec(handle, get_events, &dm4_tags, state, NULL); if (retval != SQLITE_OK) { fprintf(stderr, "%s", "Database query dm4_tags failed.\n"); return 1; } dive_end(state); /* for (i=0; i<columns;++i) { fprintf(stderr, "%s\t", column[i]); } fprintf(stderr, "\n"); for (i=0; i<columns;++i) { fprintf(stderr, "%s\t", data[i]); } fprintf(stderr, "\n"); //exit(0); */ return SQLITE_OK; } int parse_dm4_buffer(sqlite3 *handle, const char *url, const char *buffer, int size, struct dive_table *table, struct trip_table *trips, struct dive_site_table *sites, struct device_table *devices) { UNUSED(buffer); UNUSED(size); int retval; char *err = NULL; struct parser_state state; init_parser_state(&state); state.target_table = table; state.trips = trips; state.sites = sites; state.devices = devices; state.sql_handle = handle; /* StartTime is converted from Suunto's nano seconds to standard * time. We also need epoch, not seconds since year 1. */ char get_dives[] = "select D.DiveId,StartTime/10000000-62135596800,Note,Duration,SourceSerialNumber,Source,MaxDepth,SampleInterval,StartTemperature,BottomTemperature,D.StartPressure,D.EndPressure,Size,CylinderWorkPressure,SurfacePressure,DiveTime,SampleInterval,ProfileBlob,TemperatureBlob,PressureBlob,Oxygen,Helium,MIX.StartPressure,MIX.EndPressure FROM Dive AS D JOIN DiveMixture AS MIX ON D.DiveId=MIX.DiveId"; retval = sqlite3_exec(handle, get_dives, &dm4_dive, &state, &err); free_parser_state(&state); if (retval != SQLITE_OK) { fprintf(stderr, "Database query failed '%s'.\n", url); return 1; } return 0; } static int dm5_cylinders(void *param, int columns, char **data, char **column) { UNUSED(columns); UNUSED(column); struct parser_state *state = (struct parser_state *)param; cylinder_t *cyl; cyl = cylinder_start(state); if (data[7] && atoi(data[7]) > 0 && atoi(data[7]) < 350000) cyl->start.mbar = atoi(data[7]); if (data[8] && atoi(data[8]) > 0 && atoi(data[8]) < 350000) cyl->end.mbar = (atoi(data[8])); if (data[6]) { /* DM5 shows tank size of 12 liters when the actual * value is 0 (and using metric units). So we just use * the same 12 liters when size is not available */ if (strtod_flags(data[6], NULL, 0) == 0.0 && cyl->start.mbar) cyl->type.size.mliter = 12000; else cyl->type.size.mliter = lrint((strtod_flags(data[6], NULL, 0)) * 1000); } if (data[2]) cyl->gasmix.o2.permille = atoi(data[2]) * 10; if (data[3]) cyl->gasmix.he.permille = atoi(data[3]) * 10; cylinder_end(state); return 0; } static int dm5_gaschange(void *param, int columns, char **data, char **column) { UNUSED(columns); UNUSED(column); struct parser_state *state = (struct parser_state *)param; event_start(state); if (data[0]) state->cur_event.time.seconds = atoi(data[0]); if (data[1]) { strcpy(state->cur_event.name, "gaschange"); state->cur_event.value = lrint(strtod_flags(data[1], NULL, 0)); } /* He part of the mix */ if (data[2]) state->cur_event.value += lrint(strtod_flags(data[2], NULL, 0)) << 16; event_end(state); return 0; } static int dm5_dive(void *param, int columns, char **data, char **column) { UNUSED(columns); UNUSED(column); int i; int tempformat = 0; int interval, retval = 0, block_size; struct parser_state *state = (struct parser_state *)param; sqlite3 *handle = state->sql_handle; unsigned const char *sampleBlob; char get_events_template[] = "select * from Mark where DiveId = %d"; char get_tags_template[] = "select Text from DiveTag where DiveId = %d"; char get_cylinders_template[] = "select * from DiveMixture where DiveId = %d"; char get_gaschange_template[] = "select GasChangeTime,Oxygen,Helium from DiveGasChange join DiveMixture on DiveGasChange.DiveMixtureId=DiveMixture.DiveMixtureId where DiveId = %d"; char get_events[512]; dive_start(state); state->cur_dive->number = atoi(data[0]); state->cur_dive->when = (time_t)(atol(data[1])); if (data[2]) utf8_string(data[2], &state->cur_dive->notes); if (data[3]) state->cur_dive->duration.seconds = atoi(data[3]); if (data[15]) state->cur_dive->dc.duration.seconds = atoi(data[15]); /* * TODO: the deviceid hash should be calculated here. */ settings_start(state); dc_settings_start(state); if (data[4]) { utf8_string(data[4], &state->cur_settings.dc.serial_nr); state->cur_settings.dc.deviceid = atoi(data[4]); } if (data[5]) utf8_string(data[5], &state->cur_settings.dc.model); dc_settings_end(state); settings_end(state); if (data[6]) state->cur_dive->dc.maxdepth.mm = lrint(strtod_flags(data[6], NULL, 0) * 1000); if (data[8]) state->cur_dive->dc.airtemp.mkelvin = C_to_mkelvin(atoi(data[8])); if (data[9]) state->cur_dive->dc.watertemp.mkelvin = C_to_mkelvin(atoi(data[9])); if (data[4]) { state->cur_dive->dc.deviceid = atoi(data[4]); } if (data[5]) utf8_string(data[5], &state->cur_dive->dc.model); if (data[25]) { //enum divemode_t {OC, CCR, PSCR, FREEDIVE, NUM_DIVEMODE, UNDEF_COMP_TYPE}; // Flags (Open-circuit and Closed-circuit-rebreather) for setting dive computer type switch(atoi(data[25])) { case 1: state->cur_dive->dc.divemode = 0; break; case 5: state->cur_dive->dc.divemode = 1; break; default: state->cur_dive->dc.divemode = 0; break; } } snprintf(get_events, sizeof(get_events) - 1, get_cylinders_template, state->cur_dive->number); retval = sqlite3_exec(handle, get_events, &dm5_cylinders, state, NULL); if (retval != SQLITE_OK) { fprintf(stderr, "%s", "Database query dm5_cylinders failed.\n"); return 1; } if (data[14]) state->cur_dive->dc.surface_pressure.mbar = (atoi(data[14]) / 100); interval = data[16] ? atoi(data[16]) : 0; /* * sampleBlob[0] version number, indicates the size of one sample * * Following ones describe single sample, bugs in interpretation of the binary blob are likely: * * sampleBlob[3] depth * sampleBlob[7-9] pressure * sampleBlob[11] temperature - either full Celsius or float, might be different field for some version of DM */ sampleBlob = (unsigned const char *)data[24]; if (sampleBlob) { switch (sampleBlob[0]) { case 1: // Log is converted from DM4 to DM5 block_size = 16; break; case 2: block_size = 19; break; case 3: block_size = 23; break; case 4: // Temperature is stored in float tempformat = 1; block_size = 26; break; case 5: // Temperature is stored in float tempformat = 1; block_size = 30; break; default: block_size = 16; break; } } for (i = 0; interval && sampleBlob && i * interval < state->cur_dive->duration.seconds; i++) { float *depth = (float *)&sampleBlob[i * block_size + 3]; int32_t pressure = (sampleBlob[i * block_size + 9] << 16) + (sampleBlob[i * block_size + 8] << 8) + sampleBlob[i * block_size + 7]; sample_start(state); state->cur_sample->time.seconds = i * interval; state->cur_sample->depth.mm = lrintf(depth[0] * 1000.0f); if (tempformat == 1) { float *temp = (float *)&(sampleBlob[i * block_size + 11]); state->cur_sample->temperature.mkelvin = C_to_mkelvin(*temp); } else { if ((sampleBlob[i * block_size + 11]) != 0x7F) { state->cur_sample->temperature.mkelvin = C_to_mkelvin(sampleBlob[i * block_size + 11]); } } /* * Limit cylinder pressures to somewhat sensible values */ if (pressure >= 0 && pressure < 350000) state->cur_sample->pressure[0].mbar = pressure; sample_end(state); } /* * Log was converted from DM4, thus we need to parse the profile * from DM4 format */ if (i == 0) { float *profileBlob; unsigned char *tempBlob; int *pressureBlob; profileBlob = (float *)data[17]; tempBlob = (unsigned char *)data[18]; pressureBlob = (int *)data[19]; for (i = 0; interval && i * interval < state->cur_dive->duration.seconds; i++) { sample_start(state); state->cur_sample->time.seconds = i * interval; if (profileBlob) state->cur_sample->depth.mm = lrintf(profileBlob[i] * 1000.0f); else state->cur_sample->depth.mm = state->cur_dive->dc.maxdepth.mm; if (data[18] && data[18][0]) state->cur_sample->temperature.mkelvin = C_to_mkelvin(tempBlob[i]); if (data[19] && data[19][0]) state->cur_sample->pressure[0].mbar = pressureBlob[i]; sample_end(state); } } snprintf(get_events, sizeof(get_events) - 1, get_gaschange_template, state->cur_dive->number); retval = sqlite3_exec(handle, get_events, &dm5_gaschange, state, NULL); if (retval != SQLITE_OK) { fprintf(stderr, "%s", "Database query dm5_gaschange failed.\n"); return 1; } snprintf(get_events, sizeof(get_events) - 1, get_events_template, state->cur_dive->number); retval = sqlite3_exec(handle, get_events, &dm4_events, state, NULL); if (retval != SQLITE_OK) { fprintf(stderr, "%s", "Database query dm4_events failed.\n"); return 1; } snprintf(get_events, sizeof(get_events) - 1, get_tags_template, state->cur_dive->number); retval = sqlite3_exec(handle, get_events, &dm4_tags, state, NULL); if (retval != SQLITE_OK) { fprintf(stderr, "%s", "Database query dm4_tags failed.\n"); return 1; } dive_end(state); return SQLITE_OK; } int parse_dm5_buffer(sqlite3 *handle, const char *url, const char *buffer, int size, struct dive_table *table, struct trip_table *trips, struct dive_site_table *sites, struct device_table *devices) { UNUSED(buffer); UNUSED(size); int retval; char *err = NULL; struct parser_state state; init_parser_state(&state); state.target_table = table; state.trips = trips; state.sites = sites; state.devices = devices; state.sql_handle = handle; /* StartTime is converted from Suunto's nano seconds to standard * time. We also need epoch, not seconds since year 1. */ char get_dives[] = "select DiveId,StartTime/10000000-62135596800,Note,Duration,coalesce(SourceSerialNumber,SerialNumber),Source,MaxDepth,SampleInterval,StartTemperature,BottomTemperature,StartPressure,EndPressure,'','',SurfacePressure,DiveTime,SampleInterval,ProfileBlob,TemperatureBlob,PressureBlob,'','','','',SampleBlob,Mode FROM Dive where Deleted is null"; retval = sqlite3_exec(handle, get_dives, &dm5_dive, &state, &err); free_parser_state(&state); if (retval != SQLITE_OK) { fprintf(stderr, "Database query failed '%s'.\n", url); return 1; } return 0; }
subsurface-for-dirk-master
core/import-suunto.c
// SPDX-License-Identifier: GPL-2.0 #ifdef __clang__ // Clang has a bug on zero-initialization of C structs. #pragma clang diagnostic ignored "-Wmissing-field-initializers" #endif #include "save-html.h" #include "dive.h" #include "qthelper.h" #include "gettext.h" #include "divesite.h" #include "errorhelper.h" #include "event.h" #include "file.h" #include "picture.h" #include "sample.h" #include "tag.h" #include "subsurface-time.h" #include "trip.h" #include <stdio.h> #include <string.h> static void write_attribute(struct membuffer *b, const char *att_name, const char *value, const char *separator) { if (!value) value = "--"; put_format(b, "\"%s\":\"", att_name); put_HTML_quoted(b, value); put_format(b, "\"%s", separator); } static void save_photos(struct membuffer *b, const char *photos_dir, struct dive *dive) { if (dive->pictures.nr <= 0) return; char *separator = "\"photos\":["; FOR_EACH_PICTURE(dive) { put_string(b, separator); separator = ", "; char *fname = get_file_name(local_file_path(picture)); put_string(b, "{\"filename\":\""); put_quoted(b, fname, 1, 0); put_string(b, "\"}"); copy_image_and_overwrite(local_file_path(picture), photos_dir, fname); free(fname); } put_string(b, "],"); } static void write_divecomputers(struct membuffer *b, struct dive *dive) { put_string(b, "\"divecomputers\":["); struct divecomputer *dc; char *separator = ""; for_each_dc (dive, dc) { put_string(b, separator); separator = ", "; put_format(b, "{"); write_attribute(b, "model", dc->model, ", "); if (dc->deviceid) put_format(b, "\"deviceid\":\"%08x\", ", dc->deviceid); else put_string(b, "\"deviceid\":\"--\", "); if (dc->diveid) put_format(b, "\"diveid\":\"%08x\" ", dc->diveid); else put_string(b, "\"diveid\":\"--\" "); put_format(b, "}"); } put_string(b, "],"); } static void write_dive_status(struct membuffer *b, struct dive *dive) { put_format(b, "\"sac\":\"%d\",", dive->sac); put_format(b, "\"otu\":\"%d\",", dive->otu); put_format(b, "\"cns\":\"%d\",", dive->cns); } static void put_HTML_bookmarks(struct membuffer *b, struct dive *dive) { struct event *ev = dive->dc.events; if (!ev) return; char *separator = "\"events\":["; do { put_string(b, separator); separator = ", "; put_string(b, "{\"name\":\""); put_quoted(b, ev->name, 1, 0); put_string(b, "\","); put_format(b, "\"value\":\"%d\",", ev->value); put_format(b, "\"type\":\"%d\",", ev->type); put_format(b, "\"time\":\"%d\"}", ev->time.seconds); ev = ev->next; } while (ev); put_string(b, "],"); } static void put_weightsystem_HTML(struct membuffer *b, struct dive *dive) { int i, nr; nr = nr_weightsystems(dive); put_string(b, "\"Weights\":["); char *separator = ""; for (i = 0; i < nr; i++) { weightsystem_t ws = dive->weightsystems.weightsystems[i]; int grams = ws.weight.grams; const char *description = ws.description; put_string(b, separator); separator = ", "; put_string(b, "{"); put_HTML_weight_units(b, grams, "\"weight\":\"", "\","); write_attribute(b, "description", description, " "); put_string(b, "}"); } put_string(b, "],"); } static void put_cylinder_HTML(struct membuffer *b, struct dive *dive) { int i, nr; char *separator = "\"Cylinders\":["; nr = nr_cylinders(dive); if (!nr) put_string(b, separator); for (i = 0; i < nr; i++) { cylinder_t *cylinder = get_cylinder(dive, i); put_format(b, "%s{", separator); separator = ", "; write_attribute(b, "Type", cylinder->type.description, ", "); if (cylinder->type.size.mliter) { int volume = cylinder->type.size.mliter; if (prefs.units.volume == CUFT && cylinder->type.workingpressure.mbar) volume = lrint(volume * bar_to_atm(cylinder->type.workingpressure.mbar / 1000.0)); put_HTML_volume_units(b, volume, "\"Size\":\"", " \", "); } else { write_attribute(b, "Size", "--", ", "); } put_HTML_pressure_units(b, cylinder->type.workingpressure, "\"WPressure\":\"", " \", "); if (cylinder->start.mbar) { put_HTML_pressure_units(b, cylinder->start, "\"SPressure\":\"", " \", "); } else { write_attribute(b, "SPressure", "--", ", "); } if (cylinder->end.mbar) { put_HTML_pressure_units(b, cylinder->end, "\"EPressure\":\"", " \", "); } else { write_attribute(b, "EPressure", "--", ", "); } if (cylinder->gasmix.o2.permille) { put_format(b, "\"O2\":\"%u.%u%%\",", FRACTION(cylinder->gasmix.o2.permille, 10)); put_format(b, "\"He\":\"%u.%u%%\"", FRACTION(cylinder->gasmix.he.permille, 10)); } else { write_attribute(b, "O2", "Air", ""); } put_string(b, "}"); } put_string(b, "],"); } static void put_HTML_samples(struct membuffer *b, struct dive *dive) { int i; put_format(b, "\"maxdepth\":%d,", dive->dc.maxdepth.mm); put_format(b, "\"duration\":%d,", dive->dc.duration.seconds); struct sample *s = dive->dc.sample; if (!dive->dc.samples) return; char *separator = "\"samples\":["; for (i = 0; i < dive->dc.samples; i++) { put_format(b, "%s[%d,%d,%d,%d]", separator, s->time.seconds, s->depth.mm, s->pressure[0].mbar, s->temperature.mkelvin); separator = ", "; s++; } put_string(b, "],"); } static void put_HTML_coordinates(struct membuffer *b, struct dive *dive) { struct dive_site *ds = get_dive_site_for_dive(dive); if (!ds) return; degrees_t latitude = ds->location.lat; degrees_t longitude = ds->location.lon; //don't put coordinates if in (0,0) if (!latitude.udeg && !longitude.udeg) return; put_string(b, "\"coordinates\":{"); put_degrees(b, latitude, "\"lat\":\"", "\","); put_degrees(b, longitude, "\"lon\":\"", "\""); put_string(b, "},"); } void put_HTML_date(struct membuffer *b, struct dive *dive, const char *pre, const char *post) { struct tm tm; utc_mkdate(dive->when, &tm); put_format(b, "%s%04u-%02u-%02u%s", pre, tm.tm_year, tm.tm_mon + 1, tm.tm_mday, post); } void put_HTML_quoted(struct membuffer *b, const char *text) { int is_html = 1, is_attribute = 1; put_quoted(b, text, is_attribute, is_html); } void put_HTML_notes(struct membuffer *b, struct dive *dive, const char *pre, const char *post) { put_string(b, pre); if (dive->notes) { put_HTML_quoted(b, dive->notes); } else { put_string(b, "--"); } put_string(b, post); } void put_HTML_pressure_units(struct membuffer *b, pressure_t pressure, const char *pre, const char *post) { const char *unit; double value; if (!pressure.mbar) { put_format(b, "%s%s", pre, post); return; } value = get_pressure_units(pressure.mbar, &unit); put_format(b, "%s%.1f %s%s", pre, value, unit, post); } void put_HTML_volume_units(struct membuffer *b, unsigned int ml, const char *pre, const char *post) { const char *unit; double value; int frac; value = get_volume_units(ml, &frac, &unit); put_format(b, "%s%.1f %s%s", pre, value, unit, post); } void put_HTML_weight_units(struct membuffer *b, unsigned int grams, const char *pre, const char *post) { const char *unit; double value; int frac; value = get_weight_units(grams, &frac, &unit); put_format(b, "%s%.1f %s%s", pre, value, unit, post); } void put_HTML_time(struct membuffer *b, struct dive *dive, const char *pre, const char *post) { struct tm tm; utc_mkdate(dive->when, &tm); put_format(b, "%s%02u:%02u:%02u%s", pre, tm.tm_hour, tm.tm_min, tm.tm_sec, post); } void put_HTML_depth(struct membuffer *b, struct dive *dive, const char *pre, const char *post) { const char *unit; double value; const struct units *units_p = get_units(); if (!dive->maxdepth.mm) { put_format(b, "%s--%s", pre, post); return; } value = get_depth_units(dive->maxdepth.mm, NULL, &unit); switch (units_p->length) { case METERS: default: put_format(b, "%s%.1f %s%s", pre, value, unit, post); break; case FEET: put_format(b, "%s%.0f %s%s", pre, value, unit, post); break; } } void put_HTML_airtemp(struct membuffer *b, struct dive *dive, const char *pre, const char *post) { const char *unit; double value; if (!dive->airtemp.mkelvin) { put_format(b, "%s--%s", pre, post); return; } value = get_temp_units(dive->airtemp.mkelvin, &unit); put_format(b, "%s%.1f %s%s", pre, value, unit, post); } void put_HTML_watertemp(struct membuffer *b, struct dive *dive, const char *pre, const char *post) { const char *unit; double value; if (!dive->watertemp.mkelvin) { put_format(b, "%s--%s", pre, post); return; } value = get_temp_units(dive->watertemp.mkelvin, &unit); put_format(b, "%s%.1f %s%s", pre, value, unit, post); } static void put_HTML_tags(struct membuffer *b, struct dive *dive, const char *pre, const char *post) { put_string(b, pre); struct tag_entry *tag = dive->tag_list; if (!tag) put_string(b, "[\"--\""); char *separator = "["; while (tag) { put_format(b, "%s\"", separator); separator = ", "; put_HTML_quoted(b, tag->tag->name); put_string(b, "\""); tag = tag->next; } put_string(b, "]"); put_string(b, post); } /* if exporting list_only mode, we neglect exporting the samples, bookmarks and cylinders */ static void write_one_dive(struct membuffer *b, struct dive *dive, const char *photos_dir, int *dive_no, bool list_only) { put_string(b, "{"); put_format(b, "\"number\":%d,", *dive_no); put_format(b, "\"subsurface_number\":%d,", dive->number); put_HTML_date(b, dive, "\"date\":\"", "\","); put_HTML_time(b, dive, "\"time\":\"", "\","); write_attribute(b, "location", get_dive_location(dive), ", "); put_HTML_coordinates(b, dive); put_format(b, "\"rating\":%d,", dive->rating); put_format(b, "\"visibility\":%d,", dive->visibility); put_format(b, "\"current\":%d,", dive->current); put_format(b, "\"wavesize\":%d,", dive->wavesize); put_format(b, "\"surge\":%d,", dive->surge); put_format(b, "\"chill\":%d,", dive->chill); put_format(b, "\"dive_duration\":\"%u:%02u min\",", FRACTION(dive->duration.seconds, 60)); put_string(b, "\"temperature\":{"); put_HTML_airtemp(b, dive, "\"air\":\"", "\","); put_HTML_watertemp(b, dive, "\"water\":\"", "\""); put_string(b, " },"); write_attribute(b, "buddy", dive->buddy, ", "); write_attribute(b, "divemaster", dive->diveguide, ", "); write_attribute(b, "suit", dive->suit, ", "); put_HTML_tags(b, dive, "\"tags\":", ","); if (!list_only) { put_cylinder_HTML(b, dive); put_weightsystem_HTML(b, dive); put_HTML_samples(b, dive); put_HTML_bookmarks(b, dive); write_dive_status(b, dive); if (photos_dir && strcmp(photos_dir, "")) save_photos(b, photos_dir, dive); write_divecomputers(b, dive); } put_HTML_notes(b, dive, "\"notes\":\"", "\""); put_string(b, "}\n"); (*dive_no)++; } static void write_no_trip(struct membuffer *b, int *dive_no, bool selected_only, const char *photos_dir, const bool list_only, char *sep) { int i; struct dive *dive; char *separator = ""; bool found_sel_dive = 0; for_each_dive (i, dive) { // write dive if it doesn't belong to any trip and the dive is selected // or we are in exporting all dives mode. if (!dive->divetrip && (dive->selected || !selected_only)) { if (!found_sel_dive) { put_format(b, "%c{", *sep); (*sep) = ','; put_format(b, "\"name\":\"Other\","); put_format(b, "\"dives\":["); found_sel_dive = 1; } put_string(b, separator); separator = ", "; write_one_dive(b, dive, photos_dir, dive_no, list_only); } } if (found_sel_dive) put_format(b, "]}\n\n"); } static void write_trip(struct membuffer *b, dive_trip_t *trip, int *dive_no, bool selected_only, const char *photos_dir, const bool list_only, char *sep) { struct dive *dive; char *separator = ""; bool found_sel_dive = 0; for (int i = 0; i < trip->dives.nr; i++) { dive = trip->dives.dives[i]; if (!dive->selected && selected_only) continue; // save trip if found at least one selected dive. if (!found_sel_dive) { found_sel_dive = 1; put_format(b, "%c {", *sep); (*sep) = ','; write_attribute(b, "name", trip->location, ", "); put_format(b, "\"dives\":["); } put_string(b, separator); separator = ", "; write_one_dive(b, dive, photos_dir, dive_no, list_only); } // close the trip object if contain dives. if (found_sel_dive) put_format(b, "]}\n\n"); } static void write_trips(struct membuffer *b, const char *photos_dir, bool selected_only, const bool list_only) { int i, dive_no = 0; struct dive *dive; dive_trip_t *trip; char sep_ = ' '; char *sep = &sep_; for (i = 0; i < trip_table.nr; ++i) trip_table.trips[i]->saved = 0; for_each_dive (i, dive) { trip = dive->divetrip; /*Continue if the dive have no trips or we have seen this trip before*/ if (!trip || trip->saved) continue; /* We haven't seen this trip before - save it and all dives */ trip->saved = 1; write_trip(b, trip, &dive_no, selected_only, photos_dir, list_only, sep); } /*Save all remaining trips into Others*/ write_no_trip(b, &dive_no, selected_only, photos_dir, list_only, sep); } void export_list(struct membuffer *b, const char *photos_dir, bool selected_only, const bool list_only) { put_string(b, "trips=["); write_trips(b, photos_dir, selected_only, list_only); put_string(b, "]"); } void export_HTML(const char *file_name, const char *photos_dir, const bool selected_only, const bool list_only) { FILE *f; struct membuffer buf = { 0 }; export_list(&buf, photos_dir, selected_only, list_only); f = subsurface_fopen(file_name, "w+"); if (!f) { report_error(translate("gettextFromC", "Can't open file %s"), file_name); } else { flush_buffer(&buf, f); /*check for writing errors? */ fclose(f); } free_buffer(&buf); } void export_translation(const char *file_name) { FILE *f; struct membuffer buf = { 0 }; struct membuffer *b = &buf; //export translated words here put_format(b, "translate={"); //Dive list view write_attribute(b, "Number", translate("gettextFromC", "Number"), ", "); write_attribute(b, "Date", translate("gettextFromC", "Date"), ", "); write_attribute(b, "Time", translate("gettextFromC", "Time"), ", "); write_attribute(b, "Location", translate("gettextFromC", "Location"), ", "); write_attribute(b, "Air_Temp", translate("gettextFromC", "Air temp."), ", "); write_attribute(b, "Water_Temp", translate("gettextFromC", "Water temp."), ", "); write_attribute(b, "dives", translate("gettextFromC", "Dives"), ", "); write_attribute(b, "Expand_All", translate("gettextFromC", "Expand all"), ", "); write_attribute(b, "Collapse_All", translate("gettextFromC", "Collapse all"), ", "); write_attribute(b, "trips", translate("gettextFromC", "Trips"), ", "); write_attribute(b, "Statistics", translate("gettextFromC", "Statistics"), ", "); write_attribute(b, "Advanced_Search", translate("gettextFromC", "Advanced search"), ", "); //Dive expanded view write_attribute(b, "Rating", translate("gettextFromC", "Rating"), ", "); write_attribute(b, "WaveSize", translate("gettextFromC", "WaveSize"), ", "); write_attribute(b, "Visibility", translate("gettextFromC", "Visibility"), ", "); write_attribute(b, "Current", translate("gettextFromC", "Current"), ", "); write_attribute(b, "Surge", translate("gettextFromC", "Surge"), ", "); write_attribute(b, "Chill", translate("gettextFromC", "Chill"), ", "); write_attribute(b, "Duration", translate("gettextFromC", "Duration"), ", "); write_attribute(b, "DiveGuide", translate("gettextFromC", "Diveguide"), ", "); write_attribute(b, "DiveMaster", translate("gettextFromC", "Divemaster"), ", "); write_attribute(b, "Buddy", translate("gettextFromC", "Buddy"), ", "); write_attribute(b, "Suit", translate("gettextFromC", "Suit"), ", "); write_attribute(b, "Tags", translate("gettextFromC", "Tags"), ", "); write_attribute(b, "Notes", translate("gettextFromC", "Notes"), ", "); write_attribute(b, "Show_more_details", translate("gettextFromC", "Show more details"), ", "); //Yearly statistics view write_attribute(b, "Yearly_statistics", translate("gettextFromC", "Yearly statistics"), ", "); write_attribute(b, "Year", translate("gettextFromC", "Year"), ", "); write_attribute(b, "Total_Time", translate("gettextFromC", "Total time"), ", "); write_attribute(b, "Average_Time", translate("gettextFromC", "Average time"), ", "); write_attribute(b, "Shortest_Time", translate("gettextFromC", "Shortest time"), ", "); write_attribute(b, "Longest_Time", translate("gettextFromC", "Longest time"), ", "); write_attribute(b, "Average_Depth", translate("gettextFromC", "Average depth"), ", "); write_attribute(b, "Min_Depth", translate("gettextFromC", "Min. depth"), ", "); write_attribute(b, "Max_Depth", translate("gettextFromC", "Max. depth"), ", "); write_attribute(b, "Average_SAC", translate("gettextFromC", "Average SAC"), ", "); write_attribute(b, "Min_SAC", translate("gettextFromC", "Min. SAC"), ", "); write_attribute(b, "Max_SAC", translate("gettextFromC", "Max. SAC"), ", "); write_attribute(b, "Average_Temp", translate("gettextFromC", "Average temp."), ", "); write_attribute(b, "Min_Temp", translate("gettextFromC", "Min. temp."), ", "); write_attribute(b, "Max_Temp", translate("gettextFromC", "Max. temp."), ", "); write_attribute(b, "Back_to_List", translate("gettextFromC", "Back to list"), ", "); //dive detailed view write_attribute(b, "Dive_No", translate("gettextFromC", "Dive #"), ", "); write_attribute(b, "Dive_profile", translate("gettextFromC", "Dive profile"), ", "); write_attribute(b, "Dive_information", translate("gettextFromC", "Dive information"), ", "); write_attribute(b, "Dive_equipment", translate("gettextFromC", "Dive equipment"), ", "); write_attribute(b, "Type", translate("gettextFromC", "Type"), ", "); write_attribute(b, "Size", translate("gettextFromC", "Size"), ", "); write_attribute(b, "Work_Pressure", translate("gettextFromC", "Work pressure"), ", "); write_attribute(b, "Start_Pressure", translate("gettextFromC", "Start pressure"), ", "); write_attribute(b, "End_Pressure", translate("gettextFromC", "End pressure"), ", "); write_attribute(b, "Gas", translate("gettextFromC", "Gas"), ", "); write_attribute(b, "Weight", translate("gettextFromC", "Weight"), ", "); write_attribute(b, "Type", translate("gettextFromC", "Type"), ", "); write_attribute(b, "Events", translate("gettextFromC", "Events"), ", "); write_attribute(b, "Name", translate("gettextFromC", "Name"), ", "); write_attribute(b, "Value", translate("gettextFromC", "Value"), ", "); write_attribute(b, "Coordinates", translate("gettextFromC", "Coordinates"), ", "); write_attribute(b, "Dive_Status", translate("gettextFromC", "Dive status"), " "); put_format(b, "}"); f = subsurface_fopen(file_name, "w+"); if (!f) { report_error(translate("gettextFromC", "Can't open file %s"), file_name); } else { flush_buffer(&buf, f); /*check for writing errors? */ fclose(f); } free_buffer(&buf); }
subsurface-for-dirk-master
core/save-html.c
// SPDX-License-Identifier: GPL-2.0 #ifdef __clang__ // Clang has a bug on zero-initialization of C structs. #pragma clang diagnostic ignored "-Wmissing-field-initializers" #endif #include <stdio.h> #include <ctype.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include <fcntl.h> #include "dive.h" #include "divesite.h" #include "errorhelper.h" #include "extradata.h" #include "filterconstraint.h" #include "filterpreset.h" #include "sample.h" #include "subsurface-string.h" #include "subsurface-time.h" #include "trip.h" #include "device.h" #include "event.h" #include "file.h" #include "membuffer.h" #include "picture.h" #include "strndup.h" #include "git-access.h" #include "qthelper.h" #include "gettext.h" #include "tag.h" #include "xmlparams.h" /* * We're outputting utf8 in xml. * We need to quote the characters <, >, &. * * Technically I don't think we'd necessarily need to quote the control * characters, but at least libxml2 doesn't like them. It doesn't even * allow them quoted. So we just skip them and replace them with '?'. * * If we do this for attributes, we need to quote the quotes we use too. */ static void quote(struct membuffer *b, const char *text, int is_attribute) { int is_html = 0; put_quoted(b, text, is_attribute, is_html); } static void show_utf8(struct membuffer *b, const char *text, const char *pre, const char *post, int is_attribute) { int len; char *cleaned; if (!text) return; /* remove leading and trailing space */ /* We need to combine isascii() with isspace(), * because we can only trust isspace() with 7-bit ascii, * on windows for example */ while (isascii(*text) && isspace(*text)) text++; len = strlen(text); if (!len) return; while (len && isascii(text[len - 1]) && isspace(text[len - 1])) len--; cleaned = strndup(text, len); put_string(b, pre); quote(b, cleaned, is_attribute); put_string(b, post); free(cleaned); } static void blankout(char *c) { while(*c) { switch (*c) { case 'A'...'Z': *c = 'X'; break; case 'a'...'z': *c = 'x'; break; default: ; } ++c; } } static void show_utf8_blanked(struct membuffer *b, const char *text, const char *pre, const char *post, int is_attribute, bool anonymize) { if (!text) return; char *copy = strdup(text); if (anonymize) blankout(copy); show_utf8(b, copy, pre, post, is_attribute); free(copy); } static void save_depths(struct membuffer *b, struct divecomputer *dc) { /* What's the point of this dive entry again? */ if (!dc->maxdepth.mm && !dc->meandepth.mm) return; put_string(b, " <depth"); put_depth(b, dc->maxdepth, " max='", " m'"); put_depth(b, dc->meandepth, " mean='", " m'"); put_string(b, " />\n"); } static void save_dive_temperature(struct membuffer *b, struct dive *dive) { if (!dive->airtemp.mkelvin && !dive->watertemp.mkelvin) return; if (dive->airtemp.mkelvin == dc_airtemp(&dive->dc) && dive->watertemp.mkelvin == dc_watertemp(&dive->dc)) return; put_string(b, " <divetemperature"); if (dive->airtemp.mkelvin != dc_airtemp(&dive->dc)) put_temperature(b, dive->airtemp, " air='", " C'"); if (dive->watertemp.mkelvin != dc_watertemp(&dive->dc)) put_temperature(b, dive->watertemp, " water='", " C'"); put_string(b, "/>\n"); } static void save_temperatures(struct membuffer *b, struct divecomputer *dc) { if (!dc->airtemp.mkelvin && !dc->watertemp.mkelvin) return; put_string(b, " <temperature"); put_temperature(b, dc->airtemp, " air='", " C'"); put_temperature(b, dc->watertemp, " water='", " C'"); put_string(b, " />\n"); } static void save_airpressure(struct membuffer *b, struct divecomputer *dc) { if (!dc->surface_pressure.mbar) return; put_string(b, " <surface"); put_pressure(b, dc->surface_pressure, " pressure='", " bar'"); put_string(b, " />\n"); } static void save_salinity(struct membuffer *b, struct divecomputer *dc) { /* only save if we have a value that isn't the default of sea water */ if (!dc->salinity || dc->salinity == SEAWATER_SALINITY) return; put_string(b, " <water"); put_salinity(b, dc->salinity, " salinity='", " g/l'"); put_string(b, " />\n"); } static void save_overview(struct membuffer *b, struct dive *dive, bool anonymize) { show_utf8_blanked(b, dive->diveguide, " <divemaster>", "</divemaster>\n", 0, anonymize); show_utf8_blanked(b, dive->buddy, " <buddy>", "</buddy>\n", 0, anonymize); show_utf8_blanked(b, dive->notes, " <notes>", "</notes>\n", 0, anonymize); show_utf8_blanked(b, dive->suit, " <suit>", "</suit>\n", 0, anonymize); } static void put_gasmix(struct membuffer *b, struct gasmix mix) { int o2 = mix.o2.permille; int he = mix.he.permille; if (o2) { put_format(b, " o2='%u.%u%%'", FRACTION(o2, 10)); if (he) put_format(b, " he='%u.%u%%'", FRACTION(he, 10)); } } static void save_cylinder_info(struct membuffer *b, struct dive *dive) { int i, nr; nr = nr_cylinders(dive); for (i = 0; i < nr; i++) { cylinder_t *cylinder = get_cylinder(dive, i); int volume = cylinder->type.size.mliter; const char *description = cylinder->type.description; int use = cylinder->cylinder_use; put_format(b, " <cylinder"); if (volume) put_milli(b, " size='", volume, " l'"); put_pressure(b, cylinder->type.workingpressure, " workpressure='", " bar'"); show_utf8(b, description, " description='", "'", 1); put_gasmix(b, cylinder->gasmix); put_pressure(b, cylinder->start, " start='", " bar'"); put_pressure(b, cylinder->end, " end='", " bar'"); if (use > OC_GAS && use < NUM_GAS_USE) show_utf8(b, cylinderuse_text[use], " use='", "'", 1); if (cylinder->depth.mm != 0) put_milli(b, " depth='", cylinder->depth.mm, " m'"); put_format(b, " />\n"); } } static void save_weightsystem_info(struct membuffer *b, struct dive *dive) { int i, nr; nr = nr_weightsystems(dive); for (i = 0; i < nr; i++) { weightsystem_t ws = dive->weightsystems.weightsystems[i]; int grams = ws.weight.grams; const char *description = ws.description; put_format(b, " <weightsystem"); put_milli(b, " weight='", grams, " kg'"); show_utf8(b, description, " description='", "'", 1); put_format(b, " />\n"); } } static void show_integer(struct membuffer *b, int value, const char *pre, const char *post) { put_format(b, " %s%d%s", pre, value, post); } static void show_index(struct membuffer *b, int value, const char *pre, const char *post) { if (value) show_integer(b, value, pre, post); } static void save_sample(struct membuffer *b, struct sample *sample, struct sample *old, int o2sensor) { int idx; put_format(b, " <sample time='%u:%02u min'", FRACTION(sample->time.seconds, 60)); put_milli(b, " depth='", sample->depth.mm, " m'"); if (sample->temperature.mkelvin && sample->temperature.mkelvin != old->temperature.mkelvin) { put_temperature(b, sample->temperature, " temp='", " C'"); old->temperature = sample->temperature; } /* * We only show sensor information for samples with pressure, and only if it * changed from the previous sensor we showed. */ for (idx = 0; idx < MAX_SENSORS; idx++) { pressure_t p = sample->pressure[idx]; int sensor = sample->sensor[idx]; if (sensor == NO_SENSOR) continue; if (!p.mbar) continue; /* Legacy o2pressure format? */ if (o2sensor >= 0) { if (sensor == o2sensor) { put_pressure(b, p, " o2pressure='", " bar'"); continue; } put_pressure(b, p, " pressure='", " bar'"); if (sensor != old->sensor[0]) { put_format(b, " sensor='%d'", sensor); old->sensor[0] = sensor; } continue; } /* The new-style format is much simpler: the sensor is always encoded */ put_format(b, " pressure%d=", sensor); put_pressure(b, p, "'", " bar'"); } /* the deco/ndl values are stored whenever they change */ if (sample->ndl.seconds != old->ndl.seconds) { put_format(b, " ndl='%u:%02u min'", FRACTION(sample->ndl.seconds, 60)); old->ndl = sample->ndl; } if (sample->tts.seconds != old->tts.seconds) { put_format(b, " tts='%u:%02u min'", FRACTION(sample->tts.seconds, 60)); old->tts = sample->tts; } if (sample->rbt.seconds != old->rbt.seconds) { put_format(b, " rbt='%u:%02u min'", FRACTION(sample->rbt.seconds, 60)); old->rbt = sample->rbt; } if (sample->in_deco != old->in_deco) { put_format(b, " in_deco='%d'", sample->in_deco ? 1 : 0); old->in_deco = sample->in_deco; } if (sample->stoptime.seconds != old->stoptime.seconds) { put_format(b, " stoptime='%u:%02u min'", FRACTION(sample->stoptime.seconds, 60)); old->stoptime = sample->stoptime; } if (sample->stopdepth.mm != old->stopdepth.mm) { put_milli(b, " stopdepth='", sample->stopdepth.mm, " m'"); old->stopdepth = sample->stopdepth; } if (sample->cns != old->cns) { put_format(b, " cns='%u%%'", sample->cns); old->cns = sample->cns; } if ((sample->o2sensor[0].mbar) && (sample->o2sensor[0].mbar != old->o2sensor[0].mbar)) { put_milli(b, " sensor1='", sample->o2sensor[0].mbar, " bar'"); old->o2sensor[0] = sample->o2sensor[0]; } if ((sample->o2sensor[1].mbar) && (sample->o2sensor[1].mbar != old->o2sensor[1].mbar)) { put_milli(b, " sensor2='", sample->o2sensor[1].mbar, " bar'"); old->o2sensor[1] = sample->o2sensor[1]; } if ((sample->o2sensor[2].mbar) && (sample->o2sensor[2].mbar != old->o2sensor[2].mbar)) { put_milli(b, " sensor3='", sample->o2sensor[2].mbar, " bar'"); old->o2sensor[2] = sample->o2sensor[2]; } if (sample->setpoint.mbar != old->setpoint.mbar) { put_milli(b, " po2='", sample->setpoint.mbar, " bar'"); old->setpoint = sample->setpoint; } if (sample->heartbeat != old->heartbeat) { show_index(b, sample->heartbeat, "heartbeat='", "'"); old->heartbeat = sample->heartbeat; } if (sample->bearing.degrees != old->bearing.degrees) { show_index(b, sample->bearing.degrees, "bearing='", "'"); old->bearing.degrees = sample->bearing.degrees; } put_format(b, " />\n"); } static void save_one_event(struct membuffer *b, struct dive *dive, struct event *ev) { put_format(b, " <event time='%d:%02d min'", FRACTION(ev->time.seconds, 60)); show_index(b, ev->type, "type='", "'"); show_index(b, ev->flags, "flags='", "'"); if (!strcmp(ev->name,"modechange")) show_utf8(b, divemode_text[ev->value], " divemode='", "'",1); else show_index(b, ev->value, "value='", "'"); show_utf8(b, ev->name, " name='", "'", 1); if (event_is_gaschange(ev)) { struct gasmix mix = get_gasmix_from_event(dive, ev); if (ev->gas.index >= 0) show_integer(b, ev->gas.index, "cylinder='", "'"); put_gasmix(b, mix); } put_format(b, " />\n"); } static void save_events(struct membuffer *b, struct dive *dive, struct event *ev) { while (ev) { save_one_event(b, dive, ev); ev = ev->next; } } static void save_tags(struct membuffer *b, struct tag_entry *entry) { if (entry) { const char *sep = " tags='"; do { struct divetag *tag = entry->tag; put_string(b, sep); /* If the tag has been translated, write the source to the xml file */ quote(b, tag->source ?: tag->name, 1); sep = ", "; } while ((entry = entry->next) != NULL); put_string(b, "'"); } } static void save_extra_data(struct membuffer *b, struct extra_data *ed) { while (ed) { if (ed->key && ed->value) { put_string(b, " <extradata"); show_utf8(b, ed->key, " key='", "'", 1); show_utf8(b, ed->value, " value='", "'", 1); put_string(b, " />\n"); } ed = ed->next; } } static void show_date(struct membuffer *b, timestamp_t when) { struct tm tm; utc_mkdate(when, &tm); put_format(b, " date='%04u-%02u-%02u'", tm.tm_year, tm.tm_mon + 1, tm.tm_mday); if (tm.tm_hour || tm.tm_min || tm.tm_sec) put_format(b, " time='%02u:%02u:%02u'", tm.tm_hour, tm.tm_min, tm.tm_sec); } static void save_samples(struct membuffer *b, struct dive *dive, struct divecomputer *dc) { int nr; int o2sensor; struct sample *s; struct sample dummy = { .bearing.degrees = -1, .ndl.seconds = -1 }; /* Set up default pressure sensor indices */ o2sensor = legacy_format_o2pressures(dive, dc); if (o2sensor >= 0) { dummy.sensor[0] = !o2sensor; dummy.sensor[1] = o2sensor; } s = dc->sample; nr = dc->samples; while (--nr >= 0) { save_sample(b, s, &dummy, o2sensor); s++; } } static void save_dc(struct membuffer *b, struct dive *dive, struct divecomputer *dc) { put_format(b, " <divecomputer"); show_utf8(b, dc->model, " model='", "'", 1); if (dc->last_manual_time.seconds) put_duration(b, dc->last_manual_time, " last-manual-time='", " min'"); if (dc->deviceid) put_format(b, " deviceid='%08x'", dc->deviceid); if (dc->diveid) put_format(b, " diveid='%08x'", dc->diveid); if (dc->when && dc->when != dive->when) show_date(b, dc->when); if (dc->duration.seconds && dc->duration.seconds != dive->dc.duration.seconds) put_duration(b, dc->duration, " duration='", " min'"); if (dc->divemode != OC) { for (enum divemode_t i = 0; i < NUM_DIVEMODE; i++) if (dc->divemode == i) show_utf8(b, divemode_text[i], " dctype='", "'", 1); if (dc->no_o2sensors) put_format(b," no_o2sensors='%d'", dc->no_o2sensors); } put_format(b, ">\n"); save_depths(b, dc); save_temperatures(b, dc); save_airpressure(b, dc); save_salinity(b, dc); put_duration(b, dc->surfacetime, " <surfacetime>", " min</surfacetime>\n"); save_extra_data(b, dc->extra_data); save_events(b, dive, dc->events); save_samples(b, dive, dc); put_format(b, " </divecomputer>\n"); } static void save_picture(struct membuffer *b, struct picture *pic) { put_string(b, " <picture filename='"); put_quoted(b, pic->filename, true, false); put_string(b, "'"); if (pic->offset.seconds) { int offset = pic->offset.seconds; char sign = '+'; if (offset < 0) { sign = '-'; offset = -offset; } put_format(b, " offset='%c%u:%02u min'", sign, FRACTION(offset, 60)); } put_location(b, &pic->location, " gps='","'"); put_string(b, "/>\n"); } void save_one_dive_to_mb(struct membuffer *b, struct dive *dive, bool anonymize) { struct divecomputer *dc; pressure_t surface_pressure = un_fixup_surface_pressure(dive); put_string(b, "<dive"); if (dive->number) put_format(b, " number='%d'", dive->number); if (dive->notrip) put_format(b, " tripflag='NOTRIP'"); if (dive->rating) put_format(b, " rating='%d'", dive->rating); if (dive->visibility) put_format(b, " visibility='%d'", dive->visibility); if (dive->wavesize) put_format(b, " wavesize='%d'", dive->wavesize); if (dive->current) put_format(b, " current='%d'", dive->current); if (dive->surge) put_format(b, " surge='%d'", dive->surge); if (dive->chill) put_format(b, " chill='%d'", dive->chill); if (dive->invalid) put_format(b, " invalid='1'"); // These three are calculated, and not read when loading. // But saving them into the XML is useful for data export. if (dive->sac > 100) put_format(b, " sac='%d.%03d l/min'", FRACTION(dive->sac, 1000)); if (dive->otu) put_format(b, " otu='%d'", dive->otu); if (dive->maxcns) put_format(b, " cns='%d%%'", dive->maxcns); save_tags(b, dive->tag_list); if (dive->dive_site) put_format(b, " divesiteid='%8x'", dive->dive_site->uuid); if (dive->user_salinity) put_salinity(b, dive->user_salinity, " watersalinity='", " g/l'"); show_date(b, dive->when); if (surface_pressure.mbar) put_pressure(b, surface_pressure, " airpressure='", " bar'"); if (dive->dc.duration.seconds > 0) put_format(b, " duration='%u:%02u min'>\n", FRACTION(dive->dc.duration.seconds, 60)); else put_format(b, ">\n"); save_overview(b, dive, anonymize); save_cylinder_info(b, dive); save_weightsystem_info(b, dive); save_dive_temperature(b, dive); /* Save the dive computer data */ for_each_dc(dive, dc) save_dc(b, dive, dc); FOR_EACH_PICTURE(dive) save_picture(b, picture); put_format(b, "</dive>\n"); } int save_dive(FILE *f, struct dive *dive, bool anonymize) { struct membuffer buf = { 0 }; save_one_dive_to_mb(&buf, dive, anonymize); flush_buffer(&buf, f); /* Error handling? */ return 0; } static void save_trip(struct membuffer *b, dive_trip_t *trip, bool anonymize) { int i; struct dive *dive; put_format(b, "<trip"); show_date(b, trip_date(trip)); show_utf8(b, trip->location, " location=\'", "\'", 1); put_format(b, ">\n"); show_utf8(b, trip->notes, "<notes>", "</notes>\n", 0); /* * Incredibly cheesy: we want to save the dives sorted, and they * are sorted in the dive array.. So instead of using the dive * list in the trip, we just traverse the global dive array and * check the divetrip pointer.. */ for_each_dive(i, dive) { if (dive->divetrip == trip) save_one_dive_to_mb(b, dive, anonymize); } put_format(b, "</trip>\n"); } static void save_one_device(struct membuffer *b, const struct device *d) { const char *model = device_get_model(d); const char *nickname = device_get_nickname(d); const char *serial_nr = device_get_serial(d); /* Nicknames that are empty or the same as the device model are not interesting */ if (empty_string(nickname) || !strcmp(model, nickname)) nickname = NULL; /* Serial numbers that are empty are not interesting */ if (empty_string(serial_nr)) serial_nr = NULL; /* Do we have anything interesting about this dive computer to save? */ if (!serial_nr || !nickname) return; put_format(b, "<divecomputerid"); show_utf8(b, model, " model='", "'", 1); put_format(b, " deviceid='%08x'", calculate_string_hash(serial_nr)); show_utf8(b, serial_nr, " serial='", "'", 1); show_utf8(b, nickname, " nickname='", "'", 1); put_format(b, "/>\n"); } static void save_one_fingerprint(struct membuffer *b, int i) { const char *data = fp_get_data(&fingerprint_table, i); put_format(b, "<fingerprint model='%08x' serial='%08x' deviceid='%08x' diveid='%08x' data='%s'/>\n", fp_get_model(&fingerprint_table, i), fp_get_serial(&fingerprint_table, i), fp_get_deviceid(&fingerprint_table, i), fp_get_diveid(&fingerprint_table, i), data); free((void *)data); } int save_dives(const char *filename) { return save_dives_logic(filename, false, false); } static void save_filter_presets(struct membuffer *b) { int i; if (filter_presets_count() <= 0) return; put_format(b, "<filterpresets>\n"); for (i = 0; i < filter_presets_count(); i++) { char *name, *fulltext; name = filter_preset_name(i); put_format(b, " <filterpreset"); show_utf8(b, name, " name='", "'", 1); put_format(b, ">\n"); free(name); fulltext = filter_preset_fulltext_query(i); if (!empty_string(fulltext)) { const char *fulltext_mode = filter_preset_fulltext_mode(i); show_utf8(b, fulltext_mode, " <fulltext mode='", "'>", 1); show_utf8(b, fulltext, "", "</fulltext>\n", 0); } free(fulltext); for (int j = 0; j < filter_preset_constraint_count(i); j++) { char *data; const struct filter_constraint *constraint = filter_preset_constraint(i, j); const char *type = filter_constraint_type_to_string(constraint->type); put_format(b, " <constraint"); show_utf8(b, type, " type='", "'", 1); if (filter_constraint_has_string_mode(constraint->type)) { const char *mode = filter_constraint_string_mode_to_string(constraint->string_mode); show_utf8(b, mode, " string_mode='", "'", 1); } if (filter_constraint_has_range_mode(constraint->type)) { const char *mode = filter_constraint_range_mode_to_string(constraint->range_mode); show_utf8(b, mode, " range_mode='", "'", 1); } if (constraint->negate) put_format(b, " negate='1'"); put_format(b, ">"); data = filter_constraint_data_to_string(constraint); show_utf8(b, data, "", "", 0); free(data); put_format(b, "</constraint>\n"); } put_format(b, " </filterpreset>\n"); } put_format(b, "</filterpresets>\n"); } static void save_dives_buffer(struct membuffer *b, bool select_only, bool anonymize) { int i; struct dive *dive; dive_trip_t *trip; put_format(b, "<divelog program='subsurface' version='%d'>\n<settings>\n", DATAFORMAT_VERSION); /* save the dive computer nicknames, if any */ for (int i = 0; i < nr_devices(&device_table); i++) { const struct device *d = get_device(&device_table, i); if (!select_only || device_used_by_selected_dive(d)) save_one_device(b, d); } /* save the fingerprint data */ for (int i = 0; i < nr_fingerprints(&fingerprint_table); i++) save_one_fingerprint(b, i); if (autogroup) put_format(b, " <autogroup state='1' />\n"); put_format(b, "</settings>\n"); /* save the dive sites */ put_format(b, "<divesites>\n"); for (i = 0; i < dive_site_table.nr; i++) { struct dive_site *ds = get_dive_site(i, &dive_site_table); /* Don't export empty dive sites */ if (dive_site_is_empty(ds)) continue; /* Only write used dive sites when exporting selected dives */ if (select_only && !is_dive_site_selected(ds)) continue; put_format(b, "<site uuid='%8x'", ds->uuid); show_utf8_blanked(b, ds->name, " name='", "'", 1, anonymize); put_location(b, &ds->location, " gps='", "'"); show_utf8_blanked(b, ds->description, " description='", "'", 1, anonymize); put_format(b, ">\n"); show_utf8_blanked(b, ds->notes, " <notes>", " </notes>\n", 0, anonymize); if (ds->taxonomy.nr) { for (int j = 0; j < ds->taxonomy.nr; j++) { struct taxonomy *t = &ds->taxonomy.category[j]; if (t->category != TC_NONE && t->value) { put_format(b, " <geo cat='%d'", t->category); put_format(b, " origin='%d'", t->origin); show_utf8_blanked(b, t->value, " value='", "'", 1, anonymize); put_format(b, "/>\n"); } } } put_format(b, "</site>\n"); } put_format(b, "</divesites>\n<dives>\n"); for (i = 0; i < trip_table.nr; ++i) trip_table.trips[i]->saved = 0; /* save the filter presets */ save_filter_presets(b); /* save the dives */ for_each_dive(i, dive) { if (select_only) { if (!dive->selected) continue; save_one_dive_to_mb(b, dive, anonymize); } else { trip = dive->divetrip; /* Bare dive without a trip? */ if (!trip) { save_one_dive_to_mb(b, dive, anonymize); continue; } /* Have we already seen this trip (and thus saved this dive?) */ if (trip->saved) continue; /* We haven't seen this trip before - save it and all dives */ trip->saved = 1; save_trip(b, trip, anonymize); } } put_format(b, "</dives>\n</divelog>\n"); } static void save_backup(const char *name, const char *ext, const char *new_ext) { int len = strlen(name); int a = strlen(ext), b = strlen(new_ext); char *newname; /* len up to and including the final '.' */ len -= a; if (len <= 1) return; if (name[len - 1] != '.') return; /* msvc doesn't have strncasecmp, has _strnicmp instead - crazy */ if (strncasecmp(name + len, ext, a)) return; newname = malloc(len + b + 1); if (!newname) return; memcpy(newname, name, len); memcpy(newname + len, new_ext, b + 1); /* * Ignore errors. Maybe we can't create the backup file, * maybe no old file existed. Regardless, we'll write the * new file. */ (void) subsurface_rename(name, newname); free(newname); } static void try_to_backup(const char *filename) { char extension[][5] = { "xml", "ssrf", "" }; int i = 0; int flen = strlen(filename); /* Maybe we might want to make this configurable? */ while (extension[i][0] != '\0') { int elen = strlen(extension[i]); if (strcasecmp(filename + flen - elen, extension[i]) == 0) { if (last_xml_version < DATAFORMAT_VERSION) { int se_len = strlen(extension[i]) + 5; char *special_ext = malloc(se_len); snprintf(special_ext, se_len, "%s.v%d", extension[i], last_xml_version); save_backup(filename, extension[i], special_ext); free(special_ext); } else { save_backup(filename, extension[i], "bak"); } break; } i++; } } int save_dives_logic(const char *filename, const bool select_only, bool anonymize) { struct membuffer buf = { 0 }; struct git_info info; FILE *f; int error = 0; if (is_git_repository(filename, &info)) { error = git_save_dives(&info, select_only); cleanup_git_info(&info); return error; } save_dives_buffer(&buf, select_only, anonymize); if (same_string(filename, "-")) { f = stdout; } else { try_to_backup(filename); error = -1; f = subsurface_fopen(filename, "w"); } if (f) { flush_buffer(&buf, f); error = fclose(f); } if (error) report_error(translate("gettextFromC", "Failed to save dives to %s (%s)"), filename, strerror(errno)); free_buffer(&buf); return error; } static int export_dives_xslt_doit(const char *filename, struct xml_params *params, bool selected, int units, const char *export_xslt, bool anonymize); int export_dives_xslt(const char *filename, const bool selected, const int units, const char *export_xslt, bool anonymize) { struct xml_params *params = alloc_xml_params(); int ret = export_dives_xslt_doit(filename, params, selected, units, export_xslt, anonymize); free_xml_params(params); return ret; } static int export_dives_xslt_doit(const char *filename, struct xml_params *params, bool selected, int units, const char *export_xslt, bool anonymize) { FILE *f; struct membuffer buf = { 0 }; xmlDoc *doc; xsltStylesheetPtr xslt = NULL; xmlDoc *transformed; int res = 0; if (verbose) fprintf(stderr, "export_dives_xslt with stylesheet %s\n", export_xslt); if (!filename) return report_error("No filename for export"); /* Save XML to file and convert it into a memory buffer */ save_dives_buffer(&buf, selected, anonymize); /* * Parse the memory buffer into XML document and * transform it to selected export format, finally dumping * the XML into a character buffer. */ doc = xmlReadMemory(buf.buffer, buf.len, "divelog", NULL, XML_PARSE_HUGE | XML_PARSE_RECOVER); free_buffer(&buf); if (!doc) return report_error("Failed to read XML memory"); /* Convert to export format */ xslt = get_stylesheet(export_xslt); if (!xslt) return report_error("Failed to open export conversion stylesheet"); xml_params_add_int(params, "units", units); transformed = xsltApplyStylesheet(xslt, doc, xml_params_get(params)); xmlFreeDoc(doc); /* Write the transformed export to file */ f = subsurface_fopen(filename, "w"); if (f) { xsltSaveResultToFile(f, transformed, xslt); fclose(f); /* Check write errors? */ } else { res = report_error("Failed to open %s for writing (%s)", filename, strerror(errno)); } xsltFreeStylesheet(xslt); xmlFreeDoc(transformed); return res; } static void save_dive_sites_buffer(struct membuffer *b, const struct dive_site *sites[], int nr_sites, bool anonymize) { int i; put_format(b, "<divesites program='subsurface' version='%d'>\n", DATAFORMAT_VERSION); /* save the dive sites */ for (i = 0; i < nr_sites; i++) { const struct dive_site *ds = sites[i]; put_format(b, "<site uuid='%8x'", ds->uuid); show_utf8_blanked(b, ds->name, " name='", "'", 1, anonymize); put_location(b, &ds->location, " gps='", "'"); show_utf8_blanked(b, ds->description, " description='", "'", 1, anonymize); put_format(b, ">\n"); show_utf8_blanked(b, ds->notes, " <notes>", " </notes>\n", 0, anonymize); if (ds->taxonomy.nr) { for (int j = 0; j < ds->taxonomy.nr; j++) { struct taxonomy *t = &ds->taxonomy.category[j]; if (t->category != TC_NONE && t->value) { put_format(b, " <geo cat='%d'", t->category); put_format(b, " origin='%d'", t->origin); show_utf8_blanked(b, t->value, " value='", "'", 1, anonymize); put_format(b, "/>\n"); } } } put_format(b, "</site>\n"); } put_format(b, "</divesites>\n"); } int save_dive_sites_logic(const char *filename, const struct dive_site *sites[], int nr_sites, bool anonymize) { struct membuffer buf = { 0 }; FILE *f; int error = 0; save_dive_sites_buffer(&buf, sites, nr_sites, anonymize); if (same_string(filename, "-")) { f = stdout; } else { try_to_backup(filename); error = -1; f = subsurface_fopen(filename, "w"); } if (f) { flush_buffer(&buf, f); error = fclose(f); } if (error) report_error(translate("gettextFromC", "Failed to save divesites to %s (%s)"), filename, strerror(errno)); free_buffer(&buf); return error; }
subsurface-for-dirk-master
core/save-xml.c
// SPDX-License-Identifier: GPL-2.0 /* planner.c * * code that allows us to plan future dives * * (c) Dirk Hohndel 2013 */ #include <assert.h> #include <unistd.h> #include <ctype.h> #include <string.h> #include "ssrf.h" #include "dive.h" #include "divelist.h" // for init_decompression() #include "sample.h" #include "subsurface-string.h" #include "deco.h" #include "errorhelper.h" #include "event.h" #include "interpolate.h" #include "planner.h" #include "subsurface-time.h" #include "gettext.h" #include "libdivecomputer/parser.h" #include "qthelper.h" #include "version.h" #define TIMESTEP 2 /* second */ static int decostoplevels_metric[] = { 0, 3000, 6000, 9000, 12000, 15000, 18000, 21000, 24000, 27000, 30000, 33000, 36000, 39000, 42000, 45000, 48000, 51000, 54000, 57000, 60000, 63000, 66000, 69000, 72000, 75000, 78000, 81000, 84000, 87000, 90000, 100000, 110000, 120000, 130000, 140000, 150000, 160000, 170000, 180000, 190000, 200000, 220000, 240000, 260000, 280000, 300000, 320000, 340000, 360000, 380000 }; static int decostoplevels_imperial[] = { 0, 3048, 6096, 9144, 12192, 15240, 18288, 21336, 24384, 27432, 30480, 33528, 36576, 39624, 42672, 45720, 48768, 51816, 54864, 57912, 60960, 64008, 67056, 70104, 73152, 76200, 79248, 82296, 85344, 88392, 91440, 101600, 111760, 121920, 132080, 142240, 152400, 162560, 172720, 182880, 193040, 203200, 223520, 243840, 264160, 284480, 304800, 325120, 345440, 365760, 386080 }; #if DEBUG_PLAN void dump_plan(struct diveplan *diveplan) { struct divedatapoint *dp; struct tm tm; if (!diveplan) { printf("Diveplan NULL\n"); return; } utc_mkdate(diveplan->when, &tm); printf("\nDiveplan @ %04d-%02d-%02d %02d:%02d:%02d (surfpres %dmbar):\n", tm.tm_year, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, diveplan->surface_pressure); dp = diveplan->dp; while (dp) { printf("\t%3u:%02u: %6dmm cylid: %2d setpoint: %d\n", FRACTION(dp->time, 60), dp->depth, dp->cylinderid, dp->setpoint); dp = dp->next; } } #endif bool diveplan_empty(struct diveplan *diveplan) { struct divedatapoint *dp; if (!diveplan || !diveplan->dp) return true; dp = diveplan->dp; while (dp) { if (dp->time) return false; dp = dp->next; } return true; } /* get the cylinder index at a certain time during the dive */ int get_cylinderid_at_time(struct dive *dive, struct divecomputer *dc, duration_t time) { // we start with the first cylinder unless an event tells us otherwise int cylinder_idx = 0; struct event *event = dc->events; while (event && event->time.seconds <= time.seconds) { if (!strcmp(event->name, "gaschange")) cylinder_idx = get_cylinder_index(dive, event); event = event->next; } return cylinder_idx; } int get_gasidx(struct dive *dive, struct gasmix mix) { return find_best_gasmix_match(mix, &dive->cylinders); } static void interpolate_transition(struct deco_state *ds, struct dive *dive, duration_t t0, duration_t t1, depth_t d0, depth_t d1, struct gasmix gasmix, o2pressure_t po2, enum divemode_t divemode) { int32_t j; for (j = t0.seconds; j < t1.seconds; j++) { int depth = interpolate(d0.mm, d1.mm, j - t0.seconds, t1.seconds - t0.seconds); add_segment(ds, depth_to_bar(depth, dive), gasmix, 1, po2.mbar, divemode, prefs.bottomsac, true); } if (d1.mm > d0.mm) calc_crushing_pressure(ds, depth_to_bar(d1.mm, dive)); } /* returns the tissue tolerance at the end of this (partial) dive */ static int tissue_at_end(struct deco_state *ds, struct dive *dive, struct deco_state **cached_datap) { struct divecomputer *dc; struct sample *sample, *psample; int i; depth_t lastdepth = {}; duration_t t0 = {}, t1 = {}; struct gasmix gas; int surface_interval = 0; if (!dive) return 0; if (*cached_datap) { restore_deco_state(*cached_datap, ds, true); } else { surface_interval = init_decompression(ds, dive, true); cache_deco_state(ds, cached_datap); } dc = &dive->dc; if (!dc->samples) return 0; psample = sample = dc->sample; const struct event *evdm = NULL; enum divemode_t divemode = UNDEF_COMP_TYPE; for (i = 0; i < dc->samples; i++, sample++) { o2pressure_t setpoint; if (i) setpoint = sample[-1].setpoint; else setpoint = sample[0].setpoint; t1 = sample->time; gas = get_gasmix_at_time(dive, dc, t0); if (i > 0) lastdepth = psample->depth; /* The ceiling in the deeper portion of a multilevel dive is sometimes critical for the VPM-B * Boyle's law compensation. We should check the ceiling prior to ascending during the bottom * portion of the dive. The maximum ceiling might be reached while ascending, but testing indicates * that it is only marginally deeper than the ceiling at the start of ascent. * Do not set the first_ceiling_pressure variable (used for the Boyle's law compensation calculation) * at this stage, because it would interfere with calculating the ceiling at the end of the bottom * portion of the dive. * Remember the value for later. */ if ((decoMode(true) == VPMB) && (lastdepth.mm > sample->depth.mm)) { pressure_t ceiling_pressure; nuclear_regeneration(ds, t0.seconds); vpmb_start_gradient(ds); ceiling_pressure.mbar = depth_to_mbar(deco_allowed_depth(tissue_tolerance_calc(ds, dive, depth_to_bar(lastdepth.mm, dive), true), dive->surface_pressure.mbar / 1000.0, dive, 1), dive); if (ceiling_pressure.mbar > ds->max_bottom_ceiling_pressure.mbar) ds->max_bottom_ceiling_pressure.mbar = ceiling_pressure.mbar; } divemode = get_current_divemode(&dive->dc, t0.seconds + 1, &evdm, &divemode); interpolate_transition(ds, dive, t0, t1, lastdepth, sample->depth, gas, setpoint, divemode); psample = sample; t0 = t1; } return surface_interval; } /* calculate the new end pressure of the cylinder, based on its current end pressure and the * latest segment. */ static void update_cylinder_pressure(struct dive *d, int old_depth, int new_depth, int duration, int sac, cylinder_t *cyl, bool in_deco, enum divemode_t divemode) { volume_t gas_used; pressure_t delta_p; depth_t mean_depth; int factor = 1000; if (divemode == PSCR) factor = prefs.pscr_ratio; if (!cyl) return; mean_depth.mm = (old_depth + new_depth) / 2; gas_used.mliter = lrint(depth_to_atm(mean_depth.mm, d) * sac / 60 * duration * factor / 1000); cyl->gas_used.mliter += gas_used.mliter; if (in_deco) cyl->deco_gas_used.mliter += gas_used.mliter; if (cyl->type.size.mliter) { delta_p.mbar = lrint(gas_used.mliter * 1000.0 / cyl->type.size.mliter * gas_compressibility_factor(cyl->gasmix, cyl->end.mbar / 1000.0)); cyl->end.mbar -= delta_p.mbar; } } /* overwrite the data in dive * return false if something goes wrong */ static void create_dive_from_plan(struct diveplan *diveplan, struct dive *dive, bool track_gas) { struct divedatapoint *dp; struct divecomputer *dc; struct sample *sample; struct event *ev; cylinder_t *cyl; int oldpo2 = 0; int lasttime = 0, last_manual_point = 0; depth_t lastdepth = {.mm = 0}; int lastcylid; enum divemode_t type = dive->dc.divemode; if (!diveplan || !diveplan->dp) return; #if DEBUG_PLAN & 4 printf("in create_dive_from_plan\n"); dump_plan(diveplan); #endif dive->salinity = diveplan->salinity; // reset the cylinders and clear out the samples and events of the // dive-to-be-planned so we can restart reset_cylinders(dive, track_gas); dc = &dive->dc; dc->when = dive->when = diveplan->when; dc->surface_pressure.mbar = diveplan->surface_pressure; dc->salinity = diveplan->salinity; free_samples(dc); while ((ev = dc->events)) { dc->events = dc->events->next; free(ev); } dp = diveplan->dp; /* Create first sample at time = 0, not based on dp because * there is no real dp for time = 0, set first cylinder to 0 * O2 setpoint for this sample will be filled later from next dp */ cyl = get_or_create_cylinder(dive, 0); sample = prepare_sample(dc); sample->sac.mliter = prefs.bottomsac; if (track_gas && cyl->type.workingpressure.mbar) sample->pressure[0].mbar = cyl->end.mbar; sample->manually_entered = true; finish_sample(dc); lastcylid = 0; while (dp) { int po2 = dp->setpoint; int time = dp->time; depth_t depth = dp->depth; if (time == 0) { /* special entries that just inform the algorithm about * additional gases that are available */ dp = dp->next; continue; } /* Check for SetPoint change */ if (oldpo2 != po2) { /* this is a bad idea - we should get a different SAMPLE_EVENT type * reserved for this in libdivecomputer... overloading SMAPLE_EVENT_PO2 * with a different meaning will only cause confusion elsewhere in the code */ if (dp->divemode == type) add_event(dc, lasttime, SAMPLE_EVENT_PO2, 0, po2, QT_TRANSLATE_NOOP("gettextFromC", "SP change")); oldpo2 = po2; } /* Make sure we have the new gas, and create a gas change event */ if (dp->cylinderid != lastcylid) { /* need to insert a first sample for the new gas */ add_gas_switch_event(dive, dc, lasttime + 1, dp->cylinderid); cyl = get_cylinder(dive, dp->cylinderid); // FIXME: This actually may get one past the last cylinder for "surface air". if (!cyl) { report_error("Invalid cylinder in create_dive_from_plan(): %d", dp->cylinderid); continue; } sample = prepare_sample(dc); sample[-1].setpoint.mbar = po2; if (po2) sample[-1].o2sensor[0].mbar = po2; sample->time.seconds = lasttime + 1; sample->depth = lastdepth; sample->manually_entered = dp->entered; sample->sac.mliter = dp->entered ? prefs.bottomsac : prefs.decosac; finish_sample(dc); lastcylid = dp->cylinderid; } if (dp->divemode != type) { type = dp->divemode; add_event(dc, lasttime, SAMPLE_EVENT_BOOKMARK, 0, type, "modechange"); } /* Create sample */ sample = prepare_sample(dc); /* set po2 at beginning of this segment */ /* and keep it valid for last sample - where it likely doesn't matter */ sample[-1].setpoint.mbar = po2; sample->setpoint.mbar = po2; sample->time.seconds = lasttime = time; if (dp->entered) last_manual_point = dp->time; sample->depth = lastdepth = depth; sample->manually_entered = dp->entered; sample->sac.mliter = dp->entered ? prefs.bottomsac : prefs.decosac; if (track_gas && !sample[-1].setpoint.mbar) { /* Don't track gas usage for CCR legs of dive */ update_cylinder_pressure(dive, sample[-1].depth.mm, depth.mm, time - sample[-1].time.seconds, dp->entered ? diveplan->bottomsac : diveplan->decosac, cyl, !dp->entered, type); if (cyl->type.workingpressure.mbar) sample->pressure[0].mbar = cyl->end.mbar; } finish_sample(dc); dp = dp->next; } dive->dc.last_manual_time.seconds = last_manual_point; #if DEBUG_PLAN & 32 save_dive(stdout, dive); #endif return; } void free_dps(struct diveplan *diveplan) { if (!diveplan) return; struct divedatapoint *dp = diveplan->dp; while (dp) { struct divedatapoint *ndp = dp->next; free(dp); dp = ndp; } diveplan->dp = NULL; } struct divedatapoint *create_dp(int time_incr, int depth, int cylinderid, int po2) { struct divedatapoint *dp; dp = malloc(sizeof(struct divedatapoint)); dp->time = time_incr; dp->depth.mm = depth; dp->cylinderid = cylinderid; dp->minimum_gas.mbar = 0; dp->setpoint = po2; dp->entered = false; dp->next = NULL; return dp; } static void add_to_end_of_diveplan(struct diveplan *diveplan, struct divedatapoint *dp) { struct divedatapoint **lastdp = &diveplan->dp; struct divedatapoint *ldp = *lastdp; int lasttime = 0; while (*lastdp) { ldp = *lastdp; if (ldp->time > lasttime) lasttime = ldp->time; lastdp = &(*lastdp)->next; } *lastdp = dp; if (ldp) dp->time += lasttime; } struct divedatapoint *plan_add_segment(struct diveplan *diveplan, int duration, int depth, int cylinderid, int po2, bool entered, enum divemode_t divemode) { struct divedatapoint *dp = create_dp(duration, depth, cylinderid, divemode == CCR ? po2 : 0); dp->entered = entered; dp->divemode = divemode; add_to_end_of_diveplan(diveplan, dp); return dp; } struct gaschanges { int depth; int gasidx; }; // Return new setpoint if cylinderi is a setpoint change an 0 if not static int setpoint_change(struct dive *dive, int cylinderid) { cylinder_t *cylinder = get_cylinder(dive, cylinderid); if (!cylinder->type.description) return 0; if (!strncmp(cylinder->type.description, "SP ", 3)) { float sp; sscanf(cylinder->type.description + 3, "%f", &sp); return (int) (sp * 1000); } else { return 0; } } static struct gaschanges *analyze_gaslist(struct diveplan *diveplan, struct dive *dive, int *gaschangenr, int depth, int *asc_cylinder, bool ccr) { int nr = 0; struct gaschanges *gaschanges = NULL; struct divedatapoint *dp = diveplan->dp; int best_depth = get_cylinder(dive, *asc_cylinder)->depth.mm; bool total_time_zero = true; while (dp) { if (dp->time == 0 && total_time_zero && (ccr == (bool) setpoint_change(dive, dp->cylinderid))) { if (dp->depth.mm <= depth) { int i = 0; nr++; gaschanges = realloc(gaschanges, nr * sizeof(struct gaschanges)); while (i < nr - 1) { if (dp->depth.mm < gaschanges[i].depth) { memmove(gaschanges + i + 1, gaschanges + i, (nr - i - 1) * sizeof(struct gaschanges)); break; } i++; } gaschanges[i].depth = dp->depth.mm; gaschanges[i].gasidx = dp->cylinderid; assert(gaschanges[i].gasidx != -1); } else { /* is there a better mix to start deco? */ if (dp->depth.mm < best_depth) { best_depth = dp->depth.mm; *asc_cylinder = dp->cylinderid; } } } else { total_time_zero = false; } dp = dp->next; } *gaschangenr = nr; #if DEBUG_PLAN & 16 for (nr = 0; nr < *gaschangenr; nr++) { int idx = gaschanges[nr].gasidx; printf("gaschange nr %d: @ %5.2lfm gasidx %d (%s)\n", nr, gaschanges[nr].depth / 1000.0, idx, gasname(&get_cylinder(&dive, idx)->gasmix)); } #endif return gaschanges; } /* sort all the stops into one ordered list */ static int *sort_stops(int *dstops, int dnr, struct gaschanges *gstops, int gnr) { int i, gi, di; int total = dnr + gnr; int *stoplevels = malloc(total * sizeof(int)); /* no gaschanges */ if (gnr == 0) { memcpy(stoplevels, dstops, dnr * sizeof(int)); return stoplevels; } i = total - 1; gi = gnr - 1; di = dnr - 1; while (i >= 0) { if (dstops[di] > gstops[gi].depth) { stoplevels[i] = dstops[di]; di--; } else if (dstops[di] == gstops[gi].depth) { stoplevels[i] = dstops[di]; di--; gi--; } else { stoplevels[i] = gstops[gi].depth; gi--; } i--; if (di < 0) { while (gi >= 0) stoplevels[i--] = gstops[gi--].depth; break; } if (gi < 0) { while (di >= 0) stoplevels[i--] = dstops[di--]; break; } } while (i >= 0) stoplevels[i--] = 0; #if DEBUG_PLAN & 16 int k; for (k = gnr + dnr - 1; k >= 0; k--) { printf("stoplevel[%d]: %5.2lfm\n", k, stoplevels[k] / 1000.0); if (stoplevels[k] == 0) break; } #endif return stoplevels; } int ascent_velocity(int depth, int avg_depth, int bottom_time) { UNUSED(bottom_time); /* We need to make this configurable */ /* As an example (and possibly reasonable default) this is the Tech 1 provedure according * to http://www.globalunderwaterexplorers.org/files/Standards_and_Procedures/SOP_Manual_Ver2.0.2.pdf */ if (depth * 4 > avg_depth * 3) { return prefs.ascrate75; } else { if (depth * 2 > avg_depth) { return prefs.ascrate50; } else { if (depth > 6000) return prefs.ascratestops; else return prefs.ascratelast6m; } } } static void track_ascent_gas(int depth, struct dive *dive, int cylinder_id, int avg_depth, int bottom_time, bool safety_stop, enum divemode_t divemode) { cylinder_t *cylinder = get_cylinder(dive, cylinder_id); while (depth > 0) { int deltad = ascent_velocity(depth, avg_depth, bottom_time) * TIMESTEP; if (deltad > depth) deltad = depth; update_cylinder_pressure(dive, depth, depth - deltad, TIMESTEP, prefs.decosac, cylinder, true, divemode); if (depth <= 5000 && depth >= (5000 - deltad) && safety_stop) { update_cylinder_pressure(dive, 5000, 5000, 180, prefs.decosac, cylinder, true, divemode); safety_stop = false; } depth -= deltad; } } // Determine whether ascending to the next stop will break the ceiling. Return true if the ascent is ok, false if it isn't. static bool trial_ascent(struct deco_state *ds, int wait_time, int trial_depth, int stoplevel, int avg_depth, int bottom_time, struct gasmix gasmix, int po2, double surface_pressure, struct dive *dive, enum divemode_t divemode) { bool clear_to_ascend = true; struct deco_state *trial_cache = NULL; // For consistency with other VPM-B implementations, we should not start the ascent while the ceiling is // deeper than the next stop (thus the offgasing during the ascent is ignored). // However, we still need to make sure we don't break the ceiling due to on-gassing during ascent. cache_deco_state(ds, &trial_cache); if (wait_time) add_segment(ds, depth_to_bar(trial_depth, dive), gasmix, wait_time, po2, divemode, prefs.decosac, true); if (decoMode(true) == VPMB) { double tolerance_limit = tissue_tolerance_calc(ds, dive, depth_to_bar(stoplevel, dive), true); update_regression(ds, dive); if (deco_allowed_depth(tolerance_limit, surface_pressure, dive, 1) > stoplevel) { restore_deco_state(trial_cache, ds, false); free(trial_cache); return false; } } while (trial_depth > stoplevel) { double tolerance_limit; int deltad = ascent_velocity(trial_depth, avg_depth, bottom_time) * TIMESTEP; if (deltad > trial_depth) /* don't test against depth above surface */ deltad = trial_depth; add_segment(ds, depth_to_bar(trial_depth, dive), gasmix, TIMESTEP, po2, divemode, prefs.decosac, true); tolerance_limit = tissue_tolerance_calc(ds, dive, depth_to_bar(trial_depth, dive), true); if (decoMode(true) == VPMB) update_regression(ds, dive); if (deco_allowed_depth(tolerance_limit, surface_pressure, dive, 1) > trial_depth - deltad) { /* We should have stopped */ clear_to_ascend = false; break; } trial_depth -= deltad; } restore_deco_state(trial_cache, ds, false); free(trial_cache); return clear_to_ascend; } /* Determine if there is enough gas for the dive. Return true if there is enough. * Also return true if this cannot be calculated because the cylinder doesn't have * size or a starting pressure. */ static bool enough_gas(const struct dive *dive, int current_cylinder) { cylinder_t *cyl; if (current_cylinder < 0 || current_cylinder >= dive->cylinders.nr) return false; cyl = get_cylinder(dive, current_cylinder); if (!cyl->start.mbar) return true; if (cyl->type.size.mliter) return (cyl->end.mbar - prefs.reserve_gas) / 1000.0 * cyl->type.size.mliter > cyl->deco_gas_used.mliter; else return true; } /* Do a binary search for the time the ceiling is clear to ascent to target_depth. * Minimal solution is min + 1, and the solution should be an integer multiple of stepsize. * leap is a guess for the maximum but there is no guarantee that leap is an upper limit. * So we always test at the upper bundary, not in the middle! */ static int wait_until(struct deco_state *ds, struct dive *dive, int clock, int min, int leap, int stepsize, int depth, int target_depth, int avg_depth, int bottom_time, struct gasmix gasmix, int po2, double surface_pressure, enum divemode_t divemode) { // When a deco stop exceeds two days, there is something wrong... if (min >= 48 * 3600) return 50 * 3600; // Round min + leap up to the next multiple of stepsize int upper = min + leap + stepsize - 1 - (min + leap - 1) % stepsize; // Is the upper boundary too small? if (!trial_ascent(ds, upper - clock, depth, target_depth, avg_depth, bottom_time, gasmix, po2, surface_pressure, dive, divemode)) return wait_until(ds, dive, clock, upper, leap, stepsize, depth, target_depth, avg_depth, bottom_time, gasmix, po2, surface_pressure, divemode); if (upper - min <= stepsize) return upper; return wait_until(ds, dive, clock, min, leap / 2, stepsize, depth, target_depth, avg_depth, bottom_time, gasmix, po2, surface_pressure, divemode); } static void average_max_depth(struct diveplan *dive, int *avg_depth, int *max_depth) { int integral = 0; int last_time = 0; int last_depth = 0; struct divedatapoint *dp = dive->dp; *max_depth = 0; while (dp) { if (dp->time) { /* Ignore gas indication samples */ integral += (dp->depth.mm + last_depth) * (dp->time - last_time) / 2; last_time = dp->time; last_depth = dp->depth.mm; if (dp->depth.mm > *max_depth) *max_depth = dp->depth.mm; } dp = dp->next; } if (last_time) *avg_depth = integral / last_time; else *avg_depth = *max_depth = 0; } bool plan(struct deco_state *ds, struct diveplan *diveplan, struct dive *dive, int timestep, struct decostop *decostoptable, struct deco_state **cached_datap, bool is_planner, bool show_disclaimer) { int bottom_depth; int bottom_gi; int bottom_stopidx; bool is_final_plan = true; int bottom_time; int previous_deco_time; struct deco_state *bottom_cache = NULL; struct sample *sample; int po2; int transitiontime, gi; int current_cylinder, stop_cylinder; int stopidx; int depth; struct gaschanges *gaschanges = NULL; int gaschangenr; int *decostoplevels; int decostoplevelcount; int *stoplevels = NULL; bool stopping = false; bool pendinggaschange = false; int clock, previous_point_time; int avg_depth, max_depth; int last_ascend_rate; int best_first_ascend_cylinder; struct gasmix gas, bottom_gas; bool o2break_next = false; int break_cylinder = -1, breakfrom_cylinder = 0; bool last_segment_min_switch = false; int error = 0; bool decodive = false; int first_stop_depth = 0; int laststoptime = timestep; bool o2breaking = false; int decostopcounter = 0; enum divemode_t divemode = dive->dc.divemode; set_gf(diveplan->gflow, diveplan->gfhigh); set_vpmb_conservatism(diveplan->vpmb_conservatism); if (!diveplan->surface_pressure) diveplan->surface_pressure = SURFACE_PRESSURE; dive->surface_pressure.mbar = diveplan->surface_pressure; clear_deco(ds, dive->surface_pressure.mbar / 1000.0, true); ds->max_bottom_ceiling_pressure.mbar = ds->first_ceiling_pressure.mbar = 0; create_dive_from_plan(diveplan, dive, is_planner); // Do we want deco stop array in metres or feet? if (prefs.units.length == METERS ) { decostoplevels = decostoplevels_metric; decostoplevelcount = sizeof(decostoplevels_metric) / sizeof(int); } else { decostoplevels = decostoplevels_imperial; decostoplevelcount = sizeof(decostoplevels_imperial) / sizeof(int); } /* If the user has selected last stop to be at 6m/20', we need to get rid of the 3m/10' stop. * Otherwise reinstate the last stop 3m/10' stop. */ if (prefs.last_stop) *(decostoplevels + 1) = 0; else *(decostoplevels + 1) = M_OR_FT(3,10); /* Let's start at the last 'sample', i.e. the last manually entered waypoint. */ sample = &dive->dc.sample[dive->dc.samples - 1]; /* Keep time during the ascend */ bottom_time = clock = previous_point_time = dive->dc.sample[dive->dc.samples - 1].time.seconds; current_cylinder = get_cylinderid_at_time(dive, &dive->dc, sample->time); // Find the divemode at the end of the dive const struct event *ev = NULL; divemode = UNDEF_COMP_TYPE; divemode = get_current_divemode(&dive->dc, bottom_time, &ev, &divemode); gas = get_cylinder(dive, current_cylinder)->gasmix; po2 = sample->setpoint.mbar; depth = dive->dc.sample[dive->dc.samples - 1].depth.mm; average_max_depth(diveplan, &avg_depth, &max_depth); last_ascend_rate = ascent_velocity(depth, avg_depth, bottom_time); /* if all we wanted was the dive just get us back to the surface */ if (!is_planner) { /* Attn: for manually entered dives, we depend on the last segment having the * same ascent rate as in fake_dc(). If you change it here, also change it there. */ transitiontime = lrint(depth / (double)prefs.ascratelast6m); plan_add_segment(diveplan, transitiontime, 0, current_cylinder, po2, false, divemode); create_dive_from_plan(diveplan, dive, is_planner); return false; } #if DEBUG_PLAN & 4 printf("gas %s\n", gasname(&gas)); printf("depth %5.2lfm \n", depth / 1000.0); printf("current_cylinder %i\n", current_cylinder); #endif best_first_ascend_cylinder = current_cylinder; /* Find the gases available for deco */ gaschanges = analyze_gaslist(diveplan, dive, &gaschangenr, depth, &best_first_ascend_cylinder, divemode == CCR && !prefs.dobailout); /* Find the first potential decostopdepth above current depth */ for (stopidx = 0; stopidx < decostoplevelcount; stopidx++) if (decostoplevels[stopidx] > depth) break; if (stopidx > 0) stopidx--; /* Stoplevels are either depths of gas changes or potential deco stop depths. */ stoplevels = sort_stops(decostoplevels, stopidx + 1, gaschanges, gaschangenr); stopidx += gaschangenr; gi = gaschangenr - 1; /* Set tissue tolerance and initial vpmb gradient at start of ascent phase */ diveplan->surface_interval = tissue_at_end(ds, dive, cached_datap); nuclear_regeneration(ds, clock); vpmb_start_gradient(ds); if (decoMode(true) == RECREATIONAL) { bool safety_stop = prefs.safetystop && max_depth >= 10000; track_ascent_gas(depth, dive, current_cylinder, avg_depth, bottom_time, safety_stop, divemode); // How long can we stay at the current depth and still directly ascent to the surface? do { add_segment(ds, depth_to_bar(depth, dive), get_cylinder(dive, current_cylinder)->gasmix, timestep, po2, divemode, prefs.bottomsac, true); update_cylinder_pressure(dive, depth, depth, timestep, prefs.bottomsac, get_cylinder(dive, current_cylinder), false, divemode); clock += timestep; } while (trial_ascent(ds, 0, depth, 0, avg_depth, bottom_time, get_cylinder(dive, current_cylinder)->gasmix, po2, diveplan->surface_pressure / 1000.0, dive, divemode) && enough_gas(dive, current_cylinder) && clock < 6 * 3600); // We did stay one DECOTIMESTEP too many. // In the best of all worlds, we would roll back also the last add_segment in terms of caching deco state, but // let's ignore that since for the eventual ascent in recreational mode, nobody looks at the ceiling anymore, // so we don't really have to compute the deco state. update_cylinder_pressure(dive, depth, depth, -timestep, prefs.bottomsac, get_cylinder(dive, current_cylinder), false, divemode); clock -= timestep; plan_add_segment(diveplan, clock - previous_point_time, depth, current_cylinder, po2, true, divemode); previous_point_time = clock; do { /* Ascend to surface */ int deltad = ascent_velocity(depth, avg_depth, bottom_time) * TIMESTEP; if (ascent_velocity(depth, avg_depth, bottom_time) != last_ascend_rate) { plan_add_segment(diveplan, clock - previous_point_time, depth, current_cylinder, po2, false, divemode); previous_point_time = clock; last_ascend_rate = ascent_velocity(depth, avg_depth, bottom_time); } if (depth - deltad < 0) deltad = depth; clock += TIMESTEP; depth -= deltad; if (depth <= 5000 && depth >= (5000 - deltad) && safety_stop) { plan_add_segment(diveplan, clock - previous_point_time, 5000, current_cylinder, po2, false, divemode); previous_point_time = clock; clock += 180; plan_add_segment(diveplan, clock - previous_point_time, 5000, current_cylinder, po2, false, divemode); previous_point_time = clock; safety_stop = false; } } while (depth > 0); plan_add_segment(diveplan, clock - previous_point_time, 0, current_cylinder, po2, false, divemode); create_dive_from_plan(diveplan, dive, is_planner); add_plan_to_notes(diveplan, dive, show_disclaimer, error); fixup_dc_duration(&dive->dc); free(stoplevels); free(gaschanges); return false; } if (best_first_ascend_cylinder != current_cylinder) { current_cylinder = best_first_ascend_cylinder; gas = get_cylinder(dive, current_cylinder)->gasmix; #if DEBUG_PLAN & 16 printf("switch to gas %d (%d/%d) @ %5.2lfm\n", best_first_ascend_cylinder, (get_o2(&gas) + 5) / 10, (get_he(&gas) + 5) / 10, gaschanges[best_first_ascend_cylinder].depth / 1000.0); #endif } // VPM-B or Buehlmann Deco tissue_at_end(ds, dive, cached_datap); if ((divemode == CCR || divemode == PSCR) && prefs.dobailout) { divemode = OC; po2 = 0; int bailoutsegment = MAX(prefs.min_switch_duration, 60 * prefs.problemsolvingtime); add_segment(ds, depth_to_bar(depth, dive), get_cylinder(dive, current_cylinder)->gasmix, bailoutsegment, po2, divemode, prefs.bottomsac, true); plan_add_segment(diveplan, bailoutsegment, depth, current_cylinder, po2, false, divemode); bottom_time += bailoutsegment; last_segment_min_switch = true; } previous_deco_time = 100000000; ds->deco_time = 10000000; cache_deco_state(ds, &bottom_cache); // Lets us make several iterations bottom_depth = depth; bottom_gi = gi; bottom_gas = gas; bottom_stopidx = stopidx; //CVA do { decostopcounter = 0; is_final_plan = (decoMode(true) == BUEHLMANN) || (previous_deco_time - ds->deco_time < 10); // CVA time converges if (ds->deco_time != 10000000) vpmb_next_gradient(ds, ds->deco_time, diveplan->surface_pressure / 1000.0, true); previous_deco_time = ds->deco_time; restore_deco_state(bottom_cache, ds, true); depth = bottom_depth; gi = bottom_gi; clock = previous_point_time = bottom_time; gas = bottom_gas; stopping = false; decodive = false; first_stop_depth = 0; stopidx = bottom_stopidx; ds->first_ceiling_pressure.mbar = depth_to_mbar( deco_allowed_depth(tissue_tolerance_calc(ds, dive, depth_to_bar(depth, dive), true), diveplan->surface_pressure / 1000.0, dive, 1), dive); if (ds->max_bottom_ceiling_pressure.mbar > ds->first_ceiling_pressure.mbar) ds->first_ceiling_pressure.mbar = ds->max_bottom_ceiling_pressure.mbar; last_ascend_rate = ascent_velocity(depth, avg_depth, bottom_time); /* Always prefer the best_first_ascend_cylinder if it has the right gasmix. * Otherwise take first cylinder from list with rightgasmix */ if (same_gasmix(gas, get_cylinder(dive, best_first_ascend_cylinder)->gasmix)) current_cylinder = best_first_ascend_cylinder; else current_cylinder = get_gasidx(dive, gas); if (current_cylinder == -1) { report_error(translate("gettextFromC", "Can't find gas %s"), gasname(gas)); current_cylinder = 0; } reset_regression(ds); while (1) { /* We will break out when we hit the surface */ do { /* Ascend to next stop depth */ int deltad = ascent_velocity(depth, avg_depth, bottom_time) * TIMESTEP; if (ascent_velocity(depth, avg_depth, bottom_time) != last_ascend_rate) { if (is_final_plan) plan_add_segment(diveplan, clock - previous_point_time, depth, current_cylinder, po2, false, divemode); previous_point_time = clock; stopping = false; last_ascend_rate = ascent_velocity(depth, avg_depth, bottom_time); } if (depth - deltad < stoplevels[stopidx]) deltad = depth - stoplevels[stopidx]; add_segment(ds, depth_to_bar(depth, dive), get_cylinder(dive, current_cylinder)->gasmix, TIMESTEP, po2, divemode, prefs.decosac, true); last_segment_min_switch = false; clock += TIMESTEP; depth -= deltad; /* Print VPM-Gradient as gradient factor, this has to be done from within deco.c */ if (decodive) ds->plot_depth = depth; } while (depth > 0 && depth > stoplevels[stopidx]); if (depth <= 0) break; /* We are at the surface */ if (gi >= 0 && stoplevels[stopidx] <= gaschanges[gi].depth) { /* We have reached a gas change. * Record this in the dive plan */ /* Check we need to change cylinder. * We might not if the cylinder was chosen by the user * or user has selected only to switch only at required stops. * If current gas is hypoxic, we want to switch asap */ if (current_cylinder != gaschanges[gi].gasidx) { if (!prefs.switch_at_req_stop || !trial_ascent(ds, 0, depth, stoplevels[stopidx - 1], avg_depth, bottom_time, get_cylinder(dive, current_cylinder)->gasmix, po2, diveplan->surface_pressure / 1000.0, dive, divemode) || get_o2(get_cylinder(dive, current_cylinder)->gasmix) < 160) { if (is_final_plan) plan_add_segment(diveplan, clock - previous_point_time, depth, current_cylinder, po2, false, divemode); stopping = true; previous_point_time = clock; current_cylinder = gaschanges[gi].gasidx; gas = get_cylinder(dive, current_cylinder)->gasmix; if (divemode == CCR) po2 = setpoint_change(dive, current_cylinder); #if DEBUG_PLAN & 16 printf("switch to gas %d (%d/%d) @ %5.2lfm\n", gaschanges[gi].gasidx, (get_o2(&gas) + 5) / 10, (get_he(&gas) + 5) / 10, gaschanges[gi].depth / 1000.0); #endif /* Stop for the minimum duration to switch gas unless we switch to o2 */ if (!last_segment_min_switch && get_o2(get_cylinder(dive, current_cylinder)->gasmix) != 1000) { add_segment(ds, depth_to_bar(depth, dive), get_cylinder(dive, current_cylinder)->gasmix, prefs.min_switch_duration, po2, divemode, prefs.decosac, true); clock += prefs.min_switch_duration; last_segment_min_switch = true; } } else { /* The user has selected the option to switch gas only at required stops. * Remember that we are waiting to switch gas */ pendinggaschange = true; } } gi--; } --stopidx; /* Save the current state and try to ascend to the next stopdepth */ while (1) { /* Check if ascending to next stop is clear, go back and wait if we hit the ceiling on the way */ if (trial_ascent(ds, 0, depth, stoplevels[stopidx], avg_depth, bottom_time, get_cylinder(dive, current_cylinder)->gasmix, po2, diveplan->surface_pressure / 1000.0, dive, divemode)) { decostoptable[decostopcounter].depth = depth; decostoptable[decostopcounter].time = 0; decostopcounter++; break; /* We did not hit the ceiling */ } /* Add a minute of deco time and then try again */ if (!decodive) { decodive = true; first_stop_depth = depth; } if (!stopping) { /* The last segment was an ascend segment. * Add a waypoint for start of this deco stop */ if (is_final_plan) plan_add_segment(diveplan, clock - previous_point_time, depth, current_cylinder, po2, false, divemode); previous_point_time = clock; stopping = true; } /* Are we waiting to switch gas? * Occurs when the user has selected the option to switch only at required stops */ if (pendinggaschange) { current_cylinder = gaschanges[gi + 1].gasidx; gas = get_cylinder(dive, current_cylinder)->gasmix; if (divemode == CCR) po2 = setpoint_change(dive, current_cylinder); #if DEBUG_PLAN & 16 printf("switch to gas %d (%d/%d) @ %5.2lfm\n", gaschanges[gi + 1].gasidx, (get_o2(&gas) + 5) / 10, (get_he(&gas) + 5) / 10, gaschanges[gi + 1].depth / 1000.0); #endif /* Stop for the minimum duration to switch gas unless we switch to o2 */ if (!last_segment_min_switch && get_o2(get_cylinder(dive, current_cylinder)->gasmix) != 1000) { add_segment(ds, depth_to_bar(depth, dive), get_cylinder(dive, current_cylinder)->gasmix, prefs.min_switch_duration, po2, divemode, prefs.decosac, true); clock += prefs.min_switch_duration; last_segment_min_switch = true; } pendinggaschange = false; } int new_clock = wait_until(ds, dive, clock, clock, laststoptime * 2 + 1, timestep, depth, stoplevels[stopidx], avg_depth, bottom_time, get_cylinder(dive, current_cylinder)->gasmix, po2, diveplan->surface_pressure / 1000.0, divemode); laststoptime = new_clock - clock; /* Finish infinite deco */ if (laststoptime >= 48 * 3600 && depth >= 6000) { error = LONGDECO; break; } o2breaking = false; stop_cylinder = current_cylinder; if (prefs.doo2breaks && prefs.last_stop) { /* The backgas breaks option limits time on oxygen to 12 minutes, followed by 6 minutes on * backgas. This could be customized if there were demand. */ if (break_cylinder == -1) { if (get_o2(get_cylinder(dive, best_first_ascend_cylinder)->gasmix) <= 320) break_cylinder = best_first_ascend_cylinder; else break_cylinder = 0; } if (get_o2(get_cylinder(dive, current_cylinder)->gasmix) == 1000) { if (laststoptime >= 12 * 60) { laststoptime = 12 * 60; new_clock = clock + laststoptime; o2breaking = true; o2break_next = true; breakfrom_cylinder = current_cylinder; if (is_final_plan) plan_add_segment(diveplan, laststoptime, depth, current_cylinder, po2, false, divemode); previous_point_time = clock + laststoptime; current_cylinder = break_cylinder; gas = get_cylinder(dive, current_cylinder)->gasmix; } } else if (o2break_next) { if (laststoptime >= 6 * 60) { laststoptime = 6 * 60; new_clock = clock + laststoptime; o2breaking = true; o2break_next = false; if (is_final_plan) plan_add_segment(diveplan, laststoptime, depth, current_cylinder, po2, false, divemode); previous_point_time = clock + laststoptime; current_cylinder = breakfrom_cylinder; gas = get_cylinder(dive, current_cylinder)->gasmix; } } } add_segment(ds, depth_to_bar(depth, dive), get_cylinder(dive, stop_cylinder)->gasmix, laststoptime, po2, divemode, prefs.decosac, true); last_segment_min_switch = false; decostoptable[decostopcounter].depth = depth; decostoptable[decostopcounter].time = laststoptime; ++decostopcounter; clock += laststoptime; if (!o2breaking) break; } if (stopping) { /* Next we will ascend again. Add a waypoint if we have spend deco time */ if (is_final_plan) plan_add_segment(diveplan, clock - previous_point_time, depth, current_cylinder, po2, false, divemode); previous_point_time = clock; stopping = false; } } /* When calculating deco_time, we should pretend the final ascent rate is always the same, * otherwise odd things can happen, such as CVA causing the final ascent to start *later* * if the ascent rate is slower, which is completely nonsensical. * Assume final ascent takes 20s, which is the time taken to ascend at 9m/min from 3m */ ds->deco_time = clock - bottom_time - stoplevels[stopidx + 1] / last_ascend_rate + 20; } while (!is_final_plan); decostoptable[decostopcounter].depth = 0; plan_add_segment(diveplan, clock - previous_point_time, 0, current_cylinder, po2, false, divemode); if (decoMode(true) == VPMB) { diveplan->eff_gfhigh = lrint(100.0 * regressionb(ds)); diveplan->eff_gflow = lrint(100.0 * (regressiona(ds) * first_stop_depth + regressionb(ds))); } if (prefs.surface_segment != 0) { // Switch to an empty air cylinder for breathing air at the surface. // FIXME: This is incredibly silly and emulates the old code when // we had a fixed cylinder table: It uses an extra fake cylinder // past the regular cylinder table, which is not visible to the UI. // Fix this as soon as possible! current_cylinder = dive->cylinders.nr; plan_add_segment(diveplan, prefs.surface_segment, 0, current_cylinder, 0, false, OC); } create_dive_from_plan(diveplan, dive, is_planner); add_plan_to_notes(diveplan, dive, show_disclaimer, error); fixup_dc_duration(&dive->dc); free(stoplevels); free(gaschanges); free(bottom_cache); return decodive; } /* * Get a value in tenths (so "10.2" == 102, "9" = 90) * * Return negative for errors. */ static int get_tenths(const char *begin, const char **endp) { char *end; int value = strtol(begin, &end, 10); if (begin == end) return -1; value *= 10; /* Fraction? We only look at the first digit */ if (*end == '.') { end++; if (!isdigit(*end)) return -1; value += *end - '0'; do { end++; } while (isdigit(*end)); } *endp = end; return value; } static int get_permille(const char *begin, const char **end) { int value = get_tenths(begin, end); if (value >= 0) { /* Allow a percentage sign */ if (**end == '%') ++*end; } return value; } int validate_gas(const char *text, struct gasmix *gas) { int o2, he; if (!text) return 0; while (isspace(*text)) text++; if (!*text) return 0; if (!strcasecmp(text, translate("gettextFromC", "air"))) { o2 = O2_IN_AIR; he = 0; text += strlen(translate("gettextFromC", "air")); } else if (!strcasecmp(text, translate("gettextFromC", "oxygen"))) { o2 = 1000; he = 0; text += strlen(translate("gettextFromC", "oxygen")); } else if (!strncasecmp(text, translate("gettextFromC", "ean"), 3)) { o2 = get_permille(text + 3, &text); he = 0; } else { o2 = get_permille(text, &text); he = 0; if (*text == '/') he = get_permille(text + 1, &text); } /* We don't want any extra crud */ while (isspace(*text)) text++; if (*text) return 0; /* Validate the gas mix */ if (*text || o2 < 1 || o2 > 1000 || he < 0 || o2 + he > 1000) return 0; /* Let it rip */ gas->o2.permille = o2; gas->he.permille = he; return 1; } int validate_po2(const char *text, int *mbar_po2) { int po2; if (!text) return 0; po2 = get_tenths(text, &text); if (po2 < 0) return 0; while (isspace(*text)) text++; while (isspace(*text)) text++; if (*text) return 0; *mbar_po2 = po2 * 100; return 1; }
subsurface-for-dirk-master
core/planner.c
// SPDX-License-Identifier: GPL-2.0 /* * An .slg file is composed of a main table (Dives), a bunch of tables directly * linked to Dives by their indices (Site, Suit, Tank, etc) and another group of * independent tables (Activity, Type, Gear, Fish ...) which connect with the dives * via a related group of tables (ActivityRelation, TypeRelation ...) that contain * just the dive index number and the related table index number. * The data stored in the main group of tables are very extensive, going far beyond * the actual scope of Subsurface in most of cases; e.g. Dives table keeps * information which can be directly uploaded to DAN's database of dives, or Buddy * table can include telephones, photo or, even, buddy mother's maiden name. * * Although these funcs are suposed to work in a standalone tool, will also work * on main Subsurface import menu, by simply tweaking file.c and main_window.cpp * to call smartrak_import() */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <mdbtools.h> #include <stdarg.h> #include <locale.h> #if defined(WIN32) || defined(_WIN32) #include <windows.h> #endif #include "core/dive.h" #include "core/subsurface-string.h" #include "core/gettext.h" #include "core/divelist.h" #include "core/event.h" #include "core/libdivecomputer.h" #include "core/divesite.h" #include "core/membuffer.h" #include "core/tag.h" #include "core/device.h" /* SmartTrak version, constant for every single file */ int smtk_version; int tanks; /* Freeing temp char arrays utility */ static void smtk_free(char **array, int count) { int n; for (n = 0; n < count; n++) free(array[n]); array = NULL; } /* * There are AFAIK two versions of Smarttrak. The newer one supports trimix and up * to 10 tanks. The other one just 3 tanks and no trimix but only nitrox. This is a * problem for an automated parser which has to support both formats. * In this solution I made an enum of fields with the same order they would have in * a smarttrak db, and a tiny function which returns the number of the column where * a field is expected to be, taking into account the different db formats . */ enum field_pos {IDX = 0, DIVENUM, _DATE, INTIME, INTVAL, DURATION, OUTTIME, DESATBEFORE, DESATAFTER, NOFLYBEFORE, NOFLYAFTER, NOSTOPDECO, MAXDEPTH, VISIBILITY, WEIGHT, O2FRAC, HEFRAC, PSTART, PEND, AIRTEMP, MINWATERTEMP, MAXWATERTEMP, SECFACT, ALARMS, MODE, REMARKS, DCNUMBER, DCMODEL, DIVETIMECOUNT, LOG, PROFILE, SITEIDX, ALTIDX, SUITIDX, WEATHERIDX, SURFACEIDX, UNDERWATERIDX, TANKIDX}; /* * Returns calculated column number depending on smartrak version, as there are more * tanks (10) in later versions than in older (3). * Older versions also lacks of 3 columns storing he fraction, one for each tank. */ static int coln(enum field_pos pos) { int amnd = (smtk_version < 10213) ? 3 : 0; if (pos <= O2FRAC) return pos; if (pos >= AIRTEMP) { pos += 4 * (tanks - 1) - amnd; return pos; } switch (pos) { case HEFRAC: pos = O2FRAC + tanks; return pos; case PSTART: pos = O2FRAC + 2 * tanks - amnd; return pos; case PEND: pos = O2FRAC + 2 * tanks + 1 - amnd; return pos; } } /* * Fills the date part of a tm structure with the string data obtained * from smartrak in format "DD/MM/YY HH:MM:SS" where time is irrelevant. */ static void smtk_date_to_tm(char *d_buffer, struct tm *tm_date) { int n, d, m, y; if ((d_buffer) && (!empty_string(d_buffer))) { n = sscanf(d_buffer, "%d/%d/%d ", &m, &d, &y); y = (y < 70) ? y + 100 : y; if (n == 3) { tm_date->tm_mday = d; tm_date->tm_mon = m - 1; tm_date->tm_year = y; } else { tm_date->tm_mday = tm_date->tm_mon = tm_date->tm_year = 0; } } else { tm_date->tm_mday = tm_date->tm_mon = tm_date->tm_year = 0; } } /* * Fills the time part of a tm structure with the string data obtained * from smartrak in format "DD/MM/YY HH:MM:SS" where date is irrelevant. */ static void smtk_time_to_tm(char *t_buffer, struct tm *tm_date) { int n, hr, min, sec; if ((t_buffer) && (!empty_string(t_buffer))) { n = sscanf(t_buffer, "%*[0-9/] %d:%d:%d ", &hr, &min, &sec); if (n == 3) { tm_date->tm_hour = hr; tm_date->tm_min = min; tm_date->tm_sec = sec; } else { tm_date->tm_hour = tm_date->tm_min = tm_date->tm_sec = 0; } } else { tm_date->tm_hour = tm_date->tm_min = tm_date->tm_sec = 0; } tm_date->tm_isdst = -1; } /* * Converts to seconds a time lapse returned from smartrak in string format * "DD/MM/YY HH:MM:SS" where date is irrelevant. * TODO: modify to support times > 24h where date means difference in days * from 29/12/99. */ static unsigned int smtk_time_to_secs(char *t_buffer) { int n, hr, min, sec; if (!empty_string(t_buffer)) { n = sscanf(t_buffer, "%*[0-9/] %d:%d:%d ", &hr, &min, &sec); return (n == 3) ? (((hr*60)+min)*60)+sec : 0; } else { return 0; } } /* * Emulate the non portable timegm() function. * Based on timegm man page, changing setenv and unsetenv with putenv, * because of portability issues. */ static time_t smtk_timegm(struct tm *tm) { time_t ret; char *tz, *str; tz = getenv("TZ"); putenv("TZ="); tzset(); ret = mktime(tm); if (tz) { str = calloc(strlen(tz)+4, 1); sprintf(str, "TZ=%s", tz); putenv(str); } else { putenv("TZ"); } tzset(); return ret; } /* * Returns an opened table given its name and mdb. outcol and outbounder have to be allocated * by the caller and are filled here. */ static MdbTableDef *smtk_open_table(MdbHandle *mdb, char *tablename, char **outbounder, int *outlens[]) { MdbCatalogEntry *entry; MdbTableDef *table; int i; entry = mdb_get_catalogentry_by_name(mdb, tablename); if (!entry) return NULL; table = mdb_read_table(entry); if (!table) return NULL; mdb_read_columns(table); for (i = 0; i < table->num_cols; i++) { outbounder[i] = (char *) g_malloc(MDB_BIND_SIZE); if (outlens) { outlens[i] = (int *) g_malloc(sizeof(int)); mdb_bind_column(table, i+1, outbounder[i], outlens[i]); } else { mdb_bind_column(table, i+1, outbounder[i], NULL); } } mdb_rewind_table(table); return table; } /* * Utility function which joins three strings, being the second a separator string, * usually a "\n". The third is a format string with an argument list. * If the original string is NULL, then just returns the third. * This is based in add_to_string() and add_to_string_va(), and, as its parents * frees the original string. */ static char *smtk_concat_str(char *orig, const char *sep, const char *fmt, ...) { char *str; va_list args; struct membuffer out = { 0 }, in = { 0 }; va_start(args, fmt); put_vformat(&in, fmt, args); if (orig != NULL) { put_format(&out, "%s%s%s", orig, sep, mb_cstring(&in)); str = copy_string(mb_cstring(&out)); } else { str = copy_string(mb_cstring(&in)); } va_end(args); free_buffer(&out); free_buffer(&in); free(orig); return str; } /* * A site may be a wreck, which has its own table. * Parse this table referred by the site idx. If found, put the different info items in * Subsurface's dive_site notes. * Wreck format: * | Idx | SiteIdx | Text | Built | Sank | SankTime | Reason | ... | Notes | TrakId | */ static void smtk_wreck_site(MdbHandle *mdb, char *site_idx, struct dive_site *ds) { MdbTableDef *table; char *bound_values[MDB_MAX_COLS]; char *tmp = NULL, *notes = NULL; int rc, i; uint32_t d; const char *wreck_fields[] = {QT_TRANSLATE_NOOP("gettextFromC", "Built"), QT_TRANSLATE_NOOP("gettextFromC", "Sank"), QT_TRANSLATE_NOOP("gettextFromC", "Sank Time"), QT_TRANSLATE_NOOP("gettextFromC", "Reason"), QT_TRANSLATE_NOOP("gettextFromC", "Nationality"), QT_TRANSLATE_NOOP("gettextFromC", "Shipyard"), QT_TRANSLATE_NOOP("gettextFromC", "ShipType"), QT_TRANSLATE_NOOP("gettextFromC", "Length"), QT_TRANSLATE_NOOP("gettextFromC", "Beam"), QT_TRANSLATE_NOOP("gettextFromC", "Draught"), QT_TRANSLATE_NOOP("gettextFromC", "Displacement"), QT_TRANSLATE_NOOP("gettextFromC", "Cargo"), QT_TRANSLATE_NOOP("gettextFromC", "Notes")}; table = smtk_open_table(mdb, "Wreck", bound_values, NULL); /* Sanity check for table, unlikely but ... */ if (!table) return; /* Begin parsing. Write strings to notes only if available.*/ while (mdb_fetch_row(table)) { if (!strcmp(bound_values[1], site_idx)) { notes = smtk_concat_str(notes, "\n", translate("gettextFromC", "Wreck Data")); for (i = 3; i < 16; i++) { switch (i) { case 3: case 4: tmp = copy_string(bound_values[i]); if (tmp) notes = smtk_concat_str(notes, "\n", "%s: %s", wreck_fields[i - 3], strtok(tmp , " ")); free(tmp); break; case 5: tmp = copy_string(bound_values[i]); if (tmp) notes = smtk_concat_str(notes, "\n", "%s: %s", wreck_fields[i - 3], strrchr(tmp, ' ')); free(tmp); break; case 6 ... 9: case 14: case 15: tmp = copy_string(bound_values[i]); if (tmp) notes = smtk_concat_str(notes, "\n", "%s: %s", wreck_fields[i - 3], tmp); free(tmp); break; default: d = lrintl(strtold(bound_values[i], NULL)); if (d) notes = smtk_concat_str(notes, "\n", "%s: %d", wreck_fields[i - 3], d); break; } } ds->notes = smtk_concat_str(ds->notes, "\n", "%s", notes); break; } } /* Clean up and exit */ smtk_free(bound_values, table->num_cols); mdb_free_tabledef(table); free(notes); } /* * Smartrak locations db is quite extensive. This builds a string joining some of * the data in the style: "Country, State, Locality, Site" if this data are * available. Uses two tables, Site and Location. Puts Altitude, Depth and Notes * in Subsurface's dive site structure's notes if they are available. * Site format: * | Idx | Text | LocationIdx | WaterIdx | PlatformIdx | BottomIdx | Latitude | Longitude | Altitude | Depth | Notes | TrakId | * Location format: * | Idx | Text | Province | Country | Depth | */ static void smtk_build_location(MdbHandle *mdb, char *idx, struct dive_site **location) { MdbTableDef *table; MdbColumn *col[MDB_MAX_COLS]; char *bound_values[MDB_MAX_COLS]; int i, rc; uint32_t d; struct dive_site *ds; location_t loc; char *str = NULL, *loc_idx = NULL, *site = NULL, *notes = NULL; const char *site_fields[] = {QT_TRANSLATE_NOOP("gettextFromC", "Altitude"), QT_TRANSLATE_NOOP("gettextFromC", "Depth"), QT_TRANSLATE_NOOP("gettextFromC", "Notes")}; /* Read data from Site table. Format notes for the dive site if any.*/ table = smtk_open_table(mdb, "Site", bound_values, NULL); if (!table) return; do { rc = mdb_fetch_row(table); } while (strcasecmp(bound_values[0], idx) && rc != 0); if (rc == 0) { smtk_free(bound_values, table->num_cols); mdb_free_tabledef(table); return; } loc_idx = copy_string(bound_values[2]); site = copy_string(bound_values[1]); loc = create_location(strtod(bound_values[6], NULL), strtod(bound_values[7], NULL)); for (i = 8; i < 11; i++) { switch (i) { case 8: case 9: d = lrintl(strtold(bound_values[i], NULL)); if (d) notes = smtk_concat_str(notes, "\n", "%s: %d m", site_fields[i - 8], d); break; case 10: if (memcmp(bound_values[i], "\0", 1)) notes = smtk_concat_str(notes, "\n", "%s: %s", site_fields[i - 8], bound_values[i]); break; } } smtk_free(bound_values, table->num_cols); mdb_free_tabledef(table); /* Read data from Location table, linked to Site by loc_idx */ table = smtk_open_table(mdb, "Location", bound_values, NULL); mdb_rewind_table(table); do { rc = mdb_fetch_row(table); } while (strcasecmp(bound_values[0], loc_idx) && rc != 0); if (rc == 0){ smtk_free(bound_values, table->num_cols); mdb_free_tabledef(table); if(notes) free(notes); return; } /* * Create a string for Subsurface's dive site structure with coordinates * if available, if the site's name doesn't previously exists. */ if (memcmp(bound_values[3], "\0", 1)) str = smtk_concat_str(str, ", ", "%s", bound_values[3]); // Country if (memcmp(bound_values[2], "\0", 1)) str = smtk_concat_str(str, ", ", "%s", bound_values[2]); // State - Province if (memcmp(bound_values[1], "\0", 1)) str = smtk_concat_str(str, ", ", "%s", bound_values[1]); // Locality str = smtk_concat_str(str, ", ", "%s", site); ds = get_dive_site_by_name(str, &dive_site_table); if (!ds) { if (!has_location(&loc)) ds = create_dive_site(str, &dive_site_table); else ds = create_dive_site_with_gps(str, &loc, &dive_site_table); } *location = ds; smtk_free(bound_values, table->num_cols); /* Insert site notes */ ds->notes = copy_string(notes); free(notes); /* Check if we have a wreck */ smtk_wreck_site(mdb, idx, ds); /* Clean up and exit */ mdb_free_tabledef(table); free(loc_idx); free(site); free(str); } static void smtk_build_tank_info(MdbHandle *mdb, cylinder_t *tank, char *idx) { MdbTableDef *table; MdbColumn *col[MDB_MAX_COLS]; char *bound_values[MDB_MAX_COLS]; int i; table = smtk_open_table(mdb, "Tank", bound_values, NULL); if (!table) return; for (i = 1; i <= atoi(idx); i++) mdb_fetch_row(table); tank->type.description = copy_string(bound_values[1]); tank->type.size.mliter = lrint(strtod(bound_values[2], NULL) * 1000); tank->type.workingpressure.mbar = lrint(strtod(bound_values[4], NULL) * 1000); smtk_free(bound_values, table->num_cols); mdb_free_tabledef(table); } /* * Under some circustances we can get the same tank from DC and from * the smartrak DB. Will use this utility to check and clean . */ bool is_same_cylinder(cylinder_t *cyl_a, cylinder_t *cyl_b) { // different gasmixes (non zero) if (cyl_a->gasmix.o2.permille - cyl_b->gasmix.o2.permille != 0 && cyl_a->gasmix.o2.permille != 0 && cyl_b->gasmix.o2.permille != 0) return false; // different start pressures (possible error 0.1 bar) if (!(abs(cyl_a->start.mbar - cyl_b->start.mbar) <= 100)) return false; // different end pressures (possible error 0.1 bar) if (!(abs(cyl_a->end.mbar - cyl_b->end.mbar) <= 100)) return false; // different names (none of them null) if (!same_string(cyl_a->type.description, "---") && !same_string(cyl_b->type.description, "---") && !same_string(cyl_a->type.description, cyl_b->type.description)) return false; // Cylinders are most probably the same return true; } /* * Next three functions were removed from dive.c just when I was going to use them * for this import (see 16276faa). Will tweak them a bit and will use for our needs * Macros are copied from dive.c */ #define MERGE_MAX(res, a, b, n) res->n = MAX(a->n, b->n) #define MERGE_MIN(res, a, b, n) res->n = (a->n) ? (b->n) ? MIN(a->n, b->n) : (a->n) : (b->n) static void merge_cylinder_type(cylinder_type_t *src, cylinder_type_t *dst) { if (!dst->size.mliter) dst->size.mliter = src->size.mliter; if (!dst->workingpressure.mbar) dst->workingpressure.mbar = src->workingpressure.mbar; if (!dst->description || same_string(dst->description, "---")) { dst->description = src->description; src->description = NULL; } } static void merge_cylinder_mix(struct gasmix src, struct gasmix *dst) { if (!dst->o2.permille) *dst = src; } static void merge_cylinder_info(cylinder_t *src, cylinder_t *dst) { merge_cylinder_type(&src->type, &dst->type); merge_cylinder_mix(src->gasmix, &dst->gasmix); MERGE_MAX(dst, dst, src, start.mbar); MERGE_MIN(dst, dst, src, end.mbar); if (!dst->cylinder_use) dst->cylinder_use = src->cylinder_use; } /* * Remove unused tanks and merge cylinders if there are signs that * they might be duplicated. Higher numbers are more prone to be unused, * so will make the clean reverse order. * When a used cylinder is found, check against previous one; if they are * both the same, merge and delete the higher number (as lower numbers are * most probably returned by libdivecomputer raw data parse. */ static int smtk_clean_cylinders(struct dive *d) { int i = tanks - 1; cylinder_t *cyl, *base = get_cylinder(d, 0); cyl = base + tanks - 1; while (cyl != base) { if (same_string(cyl->type.description, "---") && cyl->start.mbar == 0 && cyl->end.mbar == 0) remove_cylinder(d, i); else if (is_same_cylinder(cyl, cyl - 1)) { merge_cylinder_info(cyl, cyl - 1); remove_cylinder(d, i); } cyl--; i--; } } /* * List related functions */ struct types_list { int idx; char *text; struct types_list *next; }; /* Head insert types_list items in a list */ static void smtk_head_insert(struct types_list **head, int index, char *txt) { struct types_list *item = (struct types_list *) malloc(sizeof(struct types_list)); item->next = *head; item->idx = index; item->text = txt; *head = item; item = NULL; } /* Clean types_list lists */ static void smtk_list_free(struct types_list *head) { struct types_list *p = head; while (p) { struct types_list *nxt = p->next; free(p->text); free(p); p = nxt; } } /* Return the number of rows in a given table */ static int get_rows_num(MdbHandle *mdb, char *table_name) { MdbTableDef *table; char *bound_values[MDB_MAX_COLS]; int n = 0, i = 0; table = smtk_open_table(mdb, table_name, bound_values, NULL); if (!table) return n; /* We can get an sparse array (less rows in the table than * index). Ensure we allocate as many strings as greater * index, at least */ while (mdb_fetch_row(table)) { i = atoi(bound_values[0]); if (i > n) n = i; } smtk_free(bound_values, table->num_cols); mdb_free_tabledef(table); return n; } /* * Build a list from a given table_name (Type, Gear, etc) * Managed tables formats: Just consider Idx and Text * Type: * | Idx | Text | Default (bool) * Activity: * | Idx | Text | Default (bool) * Gear: * | Idx | Text | Vendor | Type | Typenum | Notes | Default (bool) | TrakId * Fish: * | Idx | Text | Name | Latin name | Typelength | Maxlength | Picture | Default (bool)| TrakId * TODO: Although all divelogs I've seen use *only* the Text field, a concerned diver could * be using some other like Vendor (in Gear) or Latin name (in Fish). I'll take a look at this * in the future, may be something like Buddy table... */ static void smtk_build_list(MdbHandle *mdb, char *table_name, char *array[]) { MdbTableDef *table; char *bound_values[MDB_MAX_COLS], *str; table = smtk_open_table(mdb, table_name, bound_values, NULL); if (!table) return; /* Read the table items into the array */ while (mdb_fetch_row(table)) { str = bound_values[1]; if (str && (!strcmp(str, "---") || !strcmp(str, "--"))) str = NULL; array[atoi(bound_values[0]) - 1] = copy_string(str); } /* clean up and exit */ smtk_free(bound_values, table->num_cols); mdb_free_tabledef(table); } /* * Parses a relation table and returns a list with the relations for a dive idx. * Use types_list items with text set to NULL. * Returns a pointer to the list head. * Table relation format: * | Diveidx | Idx | */ static struct types_list *smtk_index_list(MdbHandle *mdb, char *table_name, char *dive_idx) { MdbTableDef *table; char *bounders[MDB_MAX_COLS]; struct types_list *item, *head = NULL; table = smtk_open_table(mdb, table_name, bounders, NULL); /* Sanity check */ if (!table) return NULL; /* Parse the table searching for dive_idx */ while (mdb_fetch_row(table)) { if (!strcmp(dive_idx, bounders[0])) smtk_head_insert(&head, atoi(bounders[1]), NULL); } /* Clean up and exit */ smtk_free(bounders, table->num_cols); mdb_free_tabledef(table); return head; } /* * "Buddy" is a bit special table that needs some extra work, so we can't just use smtk_build_list. * "Buddy" table is a buddies relation with lots and lots and lots of data (even buddy mother's * maiden name ;-) ) most of them useless for a dive log. Let's just consider the nickname as main * field and the full name if this exists and its construction is different from the nickname. * Buddy table format: * | Idx | Text (nickname) | Name | Firstname | Middlename | Title | Picture | Phone | ... */ static void smtk_build_buddies(MdbHandle *mdb, char *array[]) { MdbTableDef *table; char *bound_values[MDB_MAX_COLS], *fullname = NULL, *str = NULL; table = smtk_open_table(mdb, "Buddy", bound_values, NULL); if (!table) return; while (mdb_fetch_row(table)) { if (!empty_string(bound_values[3])) fullname = smtk_concat_str(fullname, " ", "%s", bound_values[3]); if (!empty_string(bound_values[4])) fullname = smtk_concat_str(fullname, " ", "%s", bound_values[4]); if (!empty_string(bound_values[2])) fullname = smtk_concat_str(fullname, " ", "%s", bound_values[2]); if (fullname && !same_string(bound_values[1], fullname)) array[atoi(bound_values[0]) - 1] = smtk_concat_str(str, "", "%s (%s)", bound_values[1], fullname); else array[atoi(bound_values[0]) - 1] = smtk_concat_str(str, "", "%s", bound_values[1]); free(fullname); fullname = NULL; } free(str); smtk_free(bound_values, table->num_cols); mdb_free_tabledef(table); } /* * Returns string with buddies names as registered in smartrak (may be a nickname). */ static char *smtk_locate_buddy(MdbHandle *mdb, char *dive_idx, char *buddies_list[]) { char *str = NULL; struct types_list *rel, *rel_head; rel_head = smtk_index_list(mdb, "BuddyRelation", dive_idx); if (!rel_head) return str; for (rel = rel_head; rel; rel = rel->next) str = smtk_concat_str(str, ", ", "%s", buddies_list[rel->idx - 1]); /* Clean up and exit */ smtk_list_free(rel_head); return str; } /* Parses the dive_type mdb tables and import the data into dive's * taglist structure or notes. If there are tags that affects dive's dive_mode * (SCR, CCR or so), set the dive mode too. * The "tag" parameter is used to mark if we want this table to be imported * into tags or into notes. */ static void smtk_parse_relations(MdbHandle *mdb, struct dive *dive, char *dive_idx, char *table_name, char *rel_table_name, char *list[], bool tag) { char *tmp = NULL; struct types_list *diverel_head, *d_runner; diverel_head = smtk_index_list(mdb, rel_table_name, dive_idx); if (!diverel_head) return; /* Get the text associated with the relations */ for (d_runner = diverel_head; d_runner; d_runner = d_runner->next) { if (!list[d_runner->idx - 1]) continue; if (tag) taglist_add_tag(&dive->tag_list, list[d_runner->idx - 1]); else tmp = smtk_concat_str(tmp, ", ", "%s", list[d_runner->idx - 1]); if (strstr(list[d_runner->idx - 1], "SCR")) dive->dc.divemode = PSCR; else if (strstr(list[d_runner->idx -1], "CCR")) dive->dc.divemode = CCR; } if (tmp) dive->notes = smtk_concat_str(dive->notes, "\n", "Smartrak %s: %s", table_name, tmp); free(tmp); smtk_list_free(diverel_head); } /* * Add data from tables related in Dives table which are not directly supported * in Subsurface. Write them as tags or dive notes by setting true or false the * boolean parameter "tag". */ static void smtk_parse_other(struct dive *dive, char *list[], char *data_name, char *idx, bool tag) { int i = atoi(idx) - 1; char *str = NULL; str = list[i]; if (str) { if (tag) taglist_add_tag(&dive->tag_list, str); else dive->notes = smtk_concat_str(dive->notes, "\n", "Smartrak %s: %s", data_name, str); } } /* * Returns a pointer to a bookmark event in an event list if it exists for * a given time. Return NULL otherwise. */ static struct event *find_bookmark(struct event *orig, unsigned int t) { struct event *ev = orig; while (ev) { if ((ev->time.seconds == t) && (ev->type == SAMPLE_EVENT_BOOKMARK)) return ev; ev = ev->next; } return NULL; } /* * Marker table is a mix between Type tables and Relations tables. Its format is * | Dive Idx | Idx | Text | Type | XPos | YPos | XConnect | YConnect * Type may be one of 1 = Text; 2 = DC; 3 = Tissue Data; 4 = Photo (0 most of time??) * XPos is time in minutes during the dive (long int) * YPos irelevant * XConnect irelevant * YConnect irelevant */ static void smtk_parse_bookmarks(MdbHandle *mdb, struct dive *d, char *dive_idx) { MdbTableDef *table; char *bound_values[MDB_MAX_COLS], *tmp = NULL; unsigned int time; struct event *ev; table = smtk_open_table(mdb, "Marker", bound_values, NULL); if (!table) { report_error("[smtk-import] Error - Couldn't open table 'Marker', dive %d", d->number); return; } while (mdb_fetch_row(table)) { if (same_string(bound_values[0], dive_idx)) { time = lrint(strtod(bound_values[4], NULL) * 60); tmp = strdup(bound_values[2]); ev = find_bookmark(d->dc.events, time); if (ev) update_event_name(d, 0, ev, tmp); else if (!add_event(&d->dc, time, SAMPLE_EVENT_BOOKMARK, 0, 0, tmp)) report_error("[smtk-import] Error - Couldn't add bookmark, dive %d, Name = %s", d->number, tmp); } } free(tmp); smtk_free(bound_values, table->num_cols); mdb_free_tabledef(table); } /* * Returns a dc_descriptor_t structure based on dc model's number. * This ensures the model pased to libdc_buffer_parser() is a supported model and avoids * problems with shared model num devices by taking the family into account. The family * is estimated elsewhere based in dive header length. */ static dc_descriptor_t *get_data_descriptor(int data_model, dc_family_t data_fam) { dc_descriptor_t *descriptor = NULL, *current = NULL; dc_iterator_t *iterator = NULL; dc_status_t rc; rc = dc_descriptor_iterator(&iterator); if (rc != DC_STATUS_SUCCESS) { report_error("[Error][libdc]\t\t\tCreating the device descriptor iterator.\n"); return current; } while ((dc_iterator_next(iterator, &descriptor)) == DC_STATUS_SUCCESS) { int desc_model = dc_descriptor_get_model(descriptor); dc_family_t desc_fam = dc_descriptor_get_type(descriptor); if (data_fam == DC_FAMILY_UWATEC_ALADIN) { if (data_model == desc_model && data_fam == desc_fam) { current = descriptor; break; } } else if (data_model == desc_model && (desc_fam == DC_FAMILY_UWATEC_SMART || desc_fam == DC_FAMILY_UWATEC_MERIDIAN)) { current = descriptor; break; } dc_descriptor_free(descriptor); } dc_iterator_free(iterator); return current; } /* * Fills a device_data_t structure with known dc data. * Completes a dc_descriptor_t structure with libdc's g_descriptors[] table so * we ensure that data passed for parsing to libdc have a supported and known * DC. dc_family_t is certainly known *only* if it is Aladin/Memomouse family * otherwise it will be known after get_data_descriptor call. */ static int prepare_data(int data_model, char *serial, dc_family_t dc_fam, device_data_t *dev_data) { dev_data->device = NULL; dev_data->context = NULL; if (!data_model){ dev_data->model = copy_string("manually added dive"); dev_data->descriptor = NULL; return DC_STATUS_NODEVICE; } dev_data->descriptor = get_data_descriptor(data_model, dc_fam); if (dev_data->descriptor) { dev_data->vendor = dc_descriptor_get_vendor(dev_data->descriptor); dev_data->product = dc_descriptor_get_product(dev_data->descriptor); dev_data->model = smtk_concat_str(dev_data->model, "", "%s %s", dev_data->vendor, dev_data->product); dev_data->devinfo.serial = (uint32_t) lrint(strtod(serial, NULL)); return DC_STATUS_SUCCESS; } else { dev_data->model = copy_string("unsupported dive computer"); dev_data->devinfo.serial = (uint32_t) lrint(strtod(serial, NULL)); return DC_STATUS_UNSUPPORTED; } } static void device_data_free(device_data_t *dev_data) { free((void *) dev_data->model); dc_descriptor_free(dev_data->descriptor); free(dev_data); } /* * Returns a buffer prepared for libdc parsing. * Aladin and memomouse dives were imported from datatrak, so they lack of a * header. Creates a fake header for them and inserts the dc model where libdc * expects it to be. */ static dc_status_t libdc_buffer_complete(device_data_t *dev_data, unsigned char *hdr_buffer, int hdr_length, unsigned char *prf_buffer, int prf_length, unsigned char *compl_buf) { switch (dc_descriptor_get_type(dev_data->descriptor)) { case DC_FAMILY_UWATEC_ALADIN: case DC_FAMILY_UWATEC_MEMOMOUSE: compl_buf[3] = (unsigned char) dc_descriptor_get_model(dev_data->descriptor); memcpy(compl_buf+hdr_length, prf_buffer, prf_length); break; case DC_FAMILY_UWATEC_SMART: case DC_FAMILY_UWATEC_MERIDIAN: memcpy(compl_buf, hdr_buffer, hdr_length); memcpy(compl_buf+hdr_length, prf_buffer, prf_length); break; default: return -2; } return 0; } /* * Main function. * Two looping levels using a database for the first level ("Dives" table) * and a clone of the first DB for the second level (each dive items). Using * a DB clone is necessary as calling mdb_fetch_row() over different tables in * a single DB breaks binded row data, and so would break the top loop. */ void smartrak_import(const char *file, struct dive_table *divetable) { MdbHandle *mdb, *mdb_clon; MdbTableDef *mdb_table; MdbColumn *col[MDB_MAX_COLS]; char *bound_values[MDB_MAX_COLS]; int i, dc_model, *bound_lens[MDB_MAX_COLS]; struct device_table *devices = alloc_device_table(); // Set an european style locale to work date/time conversion setlocale(LC_TIME, "POSIX"); mdb = mdb_open(file, MDB_NOFLAGS); if (!mdb) { report_error("[Error][smartrak_import]\tFile %s does not seem to be an Access database.", file); return; } if (!mdb_read_catalog(mdb, MDB_TABLE)) { report_error("[Error][smartrak_import]\tFile %s does not seem to be an Access database.", file); return; } mdb_clon = mdb_clone_handle(mdb); mdb_read_catalog(mdb_clon, MDB_TABLE); /* Define arrays for the tables */ int type_num = get_rows_num(mdb_clon, "Type"), activity_num = get_rows_num(mdb_clon, "Activity"), gear_num = get_rows_num(mdb_clon, "Gear"), fish_num = get_rows_num(mdb_clon, "Fish"), suit_num = get_rows_num(mdb_clon, "Suit"), weather_num = get_rows_num(mdb_clon, "Weather"), underwater_num = get_rows_num(mdb_clon, "Underwater"), surface_num = get_rows_num(mdb_clon, "Surface"), buddy_num = get_rows_num(mdb_clon, "Buddy"); char *type_list[type_num], *activity_list[activity_num], *gear_list[gear_num], *fish_list[fish_num], *buddy_list[buddy_num], *suit_list[suit_num], *weather_list[weather_num], *underwater_list[underwater_num], *surface_list[surface_num], *smtk_ver[1]; /* Load auxiliary tables */ smtk_build_list(mdb_clon, "Type", type_list); smtk_build_list(mdb_clon, "Activity", activity_list); smtk_build_list(mdb_clon, "Gear", gear_list); smtk_build_list(mdb_clon, "Fish", fish_list); smtk_build_list(mdb_clon, "SmartTrak", smtk_ver); smtk_build_list(mdb_clon, "Suit", suit_list); smtk_build_list(mdb_clon, "Weather", weather_list); smtk_build_list(mdb_clon, "Underwater", underwater_list); smtk_build_list(mdb_clon, "Surface", surface_list); smtk_build_buddies(mdb_clon, buddy_list); /* Check Smarttrak version (different number of supported tanks, mixes and so) */ smtk_version = atoi(smtk_ver[0]); tanks = (smtk_version < 10213) ? 3 : 10; mdb_table = smtk_open_table(mdb, "Dives", bound_values, bound_lens); if (!mdb_table) { report_error("[Error][smartrak_import]\tFile %s does not seem to be an SmartTrak file.", file); return; } while (mdb_fetch_row(mdb_table)) { device_data_t *devdata = calloc(1, sizeof(device_data_t)); dc_family_t dc_fam = DC_FAMILY_NULL; unsigned char *prf_buffer, *hdr_buffer, *compl_buffer; struct dive *smtkdive = alloc_dive(); struct tm *tm_date = malloc(sizeof(struct tm)); size_t hdr_length, prf_length; dc_status_t rc = 0; for (int j = 0; j < mdb_table->num_cols; j++) col[j] = g_ptr_array_index(mdb_table->columns, j); smtkdive->number = lrint(strtod(bound_values[1], NULL)); /* * If there is a DC model (no zero) try to create a buffer for the * dive and parse it with libdivecomputer */ dc_model = lrint(strtod(bound_values[coln(DCMODEL)], NULL)) & 0xFF; if (*bound_lens[coln(LOG)]) { hdr_buffer = mdb_ole_read_full(mdb, col[coln(LOG)], &hdr_length); if (hdr_length > 0 && hdr_length < 20) // We have a profile but it's imported from datatrak dc_fam = DC_FAMILY_UWATEC_ALADIN; } rc = prepare_data(dc_model, copy_string(col[coln(DCNUMBER)]->bind_ptr), dc_fam, devdata); smtkdive->dc.model = copy_string(devdata->model); if (rc == DC_STATUS_SUCCESS && *bound_lens[coln(PROFILE)]) { prf_buffer = mdb_ole_read_full(mdb, col[coln(PROFILE)], &prf_length); if (prf_length > 0) { if (dc_descriptor_get_type(devdata->descriptor) == DC_FAMILY_UWATEC_ALADIN || dc_descriptor_get_type(devdata->descriptor) == DC_FAMILY_UWATEC_MEMOMOUSE) hdr_length = 18; compl_buffer = calloc(hdr_length+prf_length, sizeof(char)); rc = libdc_buffer_complete(devdata, hdr_buffer, hdr_length, prf_buffer, prf_length, compl_buffer); if (rc != DC_STATUS_SUCCESS) { report_error("[Error][smartrak_import]\t- %s - for dive %d", errmsg(rc), smtkdive->number); } else { rc = libdc_buffer_parser(smtkdive, devdata, compl_buffer, hdr_length + prf_length); if (rc != DC_STATUS_SUCCESS) report_error("[Error][libdc]\t\t- %s - for dive %d", errmsg(rc), smtkdive->number); } free(compl_buffer); } else { /* Dives without profile samples (usual in older aladin series) */ report_error("[Warning][smartrak_import]\t No profile for dive %d", smtkdive->number); smtkdive->dc.duration.seconds = smtkdive->duration.seconds = smtk_time_to_secs(col[coln(DURATION)]->bind_ptr); smtkdive->dc.maxdepth.mm = smtkdive->maxdepth.mm = lrint(strtod(col[coln(MAXDEPTH)]->bind_ptr, NULL) * 1000); } free(hdr_buffer); free(prf_buffer); } else { /* Manual dives or unknown DCs */ report_error("[Warning][smartrak_import]\t Manual or unknown dive computer for dive %d", smtkdive->number); smtkdive->dc.duration.seconds = smtkdive->duration.seconds = smtk_time_to_secs(col[coln(DURATION)]->bind_ptr); smtkdive->dc.maxdepth.mm = smtkdive->maxdepth.mm = lrint(strtod(col[coln(MAXDEPTH)]->bind_ptr, NULL) * 1000); } /* * Cylinder and gasmixes completion. * Revisit data under some circunstances, e.g. a start pressure = 0 may mean * that dc doesn't support gas control, in this situation let's look into mdb data */ int pstartcol = coln(PSTART); int o2fraccol = coln(O2FRAC); int hefraccol = coln(HEFRAC); int tankidxcol = coln(TANKIDX); for (i = 0; i < tanks; i++) { cylinder_t *tmptank = get_or_create_cylinder(smtkdive, i); if (!tmptank) break; if (tmptank->start.mbar == 0) tmptank->start.mbar = lrint(strtod(col[(i * 2) + pstartcol]->bind_ptr, NULL) * 1000); /* * If there is a start pressure ensure that end pressure is not zero as * will be registered in DCs which only keep track of differential pressures, * and collect the data registered by the user in mdb */ if (tmptank->end.mbar == 0 && tmptank->start.mbar != 0) tmptank->end.mbar = lrint(strtod(col[(i * 2) + 1 + pstartcol]->bind_ptr, NULL) * 1000 ? : 1000); if (tmptank->gasmix.o2.permille == 0) tmptank->gasmix.o2.permille = lrint(strtod(col[i + o2fraccol]->bind_ptr, NULL) * 10); if (smtk_version == 10213) { if (tmptank->gasmix.he.permille == 0) tmptank->gasmix.he.permille = lrint(strtod(col[i + hefraccol]->bind_ptr, NULL) * 10); } else { tmptank->gasmix.he.permille = 0; } smtk_build_tank_info(mdb_clon, tmptank, col[i + tankidxcol]->bind_ptr); } /* Check for duplicated cylinders and clean them */ smtk_clean_cylinders(smtkdive); /* Date issues with libdc parser - Take date time from mdb */ smtk_date_to_tm(col[coln(_DATE)]->bind_ptr, tm_date); smtk_time_to_tm(col[coln(INTIME)]->bind_ptr, tm_date); smtkdive->dc.when = smtkdive->when = smtk_timegm(tm_date); free(tm_date); smtkdive->dc.surfacetime.seconds = smtk_time_to_secs(col[coln(INTVAL)]->bind_ptr); /* Data that user may have registered manually if not supported by DC, or not parsed */ if (!smtkdive->airtemp.mkelvin) smtkdive->airtemp.mkelvin = C_to_mkelvin(lrint(strtod(col[coln(AIRTEMP)]->bind_ptr, NULL))); if (!smtkdive->watertemp.mkelvin) smtkdive->watertemp.mkelvin = smtkdive->mintemp.mkelvin = C_to_mkelvin(lrint(strtod(col[coln(MINWATERTEMP)]->bind_ptr, NULL))); if (!smtkdive->maxtemp.mkelvin) smtkdive->maxtemp.mkelvin = C_to_mkelvin(lrint(strtod(col[coln(MAXWATERTEMP)]->bind_ptr, NULL))); /* No DC related data */ smtkdive->visibility = strtod(col[coln(VISIBILITY)]->bind_ptr, NULL) > 25 ? 5 : lrint(strtod(col[13]->bind_ptr, NULL) / 5); weightsystem_t ws = { {lrint(strtod(col[coln(WEIGHT)]->bind_ptr, NULL) * 1000)}, "", false }; add_cloned_weightsystem(&smtkdive->weightsystems, ws); smtkdive->suit = copy_string(suit_list[atoi(col[coln(SUITIDX)]->bind_ptr) - 1]); smtk_build_location(mdb_clon, col[coln(SITEIDX)]->bind_ptr, &smtkdive->dive_site); smtkdive->buddy = smtk_locate_buddy(mdb_clon, col[0]->bind_ptr, buddy_list); smtk_parse_relations(mdb_clon, smtkdive, col[0]->bind_ptr, "Type", "TypeRelation", type_list, true); smtk_parse_relations(mdb_clon, smtkdive, col[0]->bind_ptr, "Activity", "ActivityRelation", activity_list, false); smtk_parse_relations(mdb_clon, smtkdive, col[0]->bind_ptr, "Gear", "GearRelation", gear_list, false); smtk_parse_relations(mdb_clon, smtkdive, col[0]->bind_ptr, "Fish", "FishRelation", fish_list, false); smtk_parse_other(smtkdive, weather_list, "Weather", col[coln(WEATHERIDX)]->bind_ptr, false); smtk_parse_other(smtkdive, underwater_list, "Underwater", col[coln(UNDERWATERIDX)]->bind_ptr, false); smtk_parse_other(smtkdive, surface_list, "Surface", col[coln(SURFACEIDX)]->bind_ptr, false); smtk_parse_bookmarks(mdb_clon, smtkdive, col[0]->bind_ptr); smtkdive->notes = smtk_concat_str(smtkdive->notes, "\n", "%s", col[coln(REMARKS)]->bind_ptr); record_dive_to_table(smtkdive, divetable); device_data_free(devdata); } mdb_free_tabledef(mdb_table); mdb_free_catalog(mdb_clon); mdb->catalog = NULL; mdb_close(mdb_clon); mdb_close(mdb); sort_dive_table(divetable); }
subsurface-for-dirk-master
smtk-import/smartrak.c