int main(int argc, char *argv[]) { struct bogl_font *font; int index_size = 0; int content_size = 0; int i, j, k, cp, n; char buf[MB_LEN_MAX + 1]; setlocale(LC_ALL, ""); /* Check for proper usage. */ if (!argc == 2 ) { fprintf(stderr, "Usage:\n%s font.bdf > font.c\n", argv[0]); return EXIT_FAILURE; } /* Read font file. */ font = bogl_read_bdf(argv[1]); if (!font) { return EXIT_FAILURE; } /* Output header. */ printf("#include \"font.h\"\n"); /* Output offsets, and get index_size and content_size. */ printf("\n/* Offsets into index. */\n"); printf("static int _%s_offset[%d] = {\n", font->name, font->index_mask + 1); for (i = 0; i <= font->index_mask; i++) { printf(" %d, /* (0x%x) */\n", font->offset[i], i); for (j = font->offset[i]; font->index[j] != 0; j += 2) { k = font->index[j + 1] + font->height * (((font->index[j] & font->index_mask) + 31) / 32); if (k > content_size) content_size = k; } if (j > index_size) index_size = j; } ++index_size; printf("};\n"); /* Output index. */ printf("\n/* Index into content data. */\n"); printf("static int _%s_index[%d] = {\n", font->name, index_size); i = 0; while (i < index_size) if (font->index[i] != 0 && i < index_size - 1) { printf(" 0x%x, %d,\n", font->index[i], font->index[i + 1]); i += 2; } else if (font->index[i] == 0) printf(" %d,\n", font->index[i++]); else printf(" %d, /* Hm... */\n", font->index[i++]); printf("};\n"); /* Print out each character's picture and data. */ printf("\n/* Font character content data. */\n"); printf("static u_int32_t _%s_content[] = {\n\n", font->name); cp = 0; while (cp < content_size) { int width = 0; for (i = 0; i <= font->index_mask; i++) for (j = font->offset[i]; font->index[j] != 0; j += 2) if (font->index[j + 1] == cp) { wchar_t wc = (font->index[j] & ~font-> index_mask) | i; int w = font->index[j] & font-> index_mask; if (iswprint(wc)) { wctomb(0, 0); n = wctomb(buf, wc); buf[(n == -1) ? 0 : n] = '\0'; printf ("/* %d: character %s (0x%lx), width %d */\n", cp, buf, (long) wc, w); } else printf ("/* %d: unprintable character 0x%lx, width %d */\n", cp, (long) wc, w); if (w > width) width = w; } if (width && cp + font->height * ((width + 31) / 32) <= content_size) { print_glyph(&font->content[cp], font->height, width); printf("\n"); cp += font->height * ((width + 31) / 32); } else printf("0x%08x,\n", font->content[cp++]); } printf("};\n\n"); /* Print the font structure definition. */ printf("/* Exported structure definition. */\n"); printf("const struct Font %s_font = {\n", font->name); printf(" \"%s\",\n", font->name); printf(" %d,\n", font->height); printf(" 0x%x,\n", font->index_mask); printf(" _%s_offset,\n", font->name); printf(" _%s_index,\n", font->name); printf(" _%s_content,\n", font->name); printf("};\n"); return EXIT_SUCCESS; }
uint32 Editor::onMessage(uint32 message, uint32 wParam, uint32 lParam) { switch (message) { case WM_DESTROY: delete target; target = NULL; break; case WM_SETCURSOR: if (LOWORD(lParam) == HTCLIENT) { POINT pt; GetCursorPos(&pt); ScreenToClient(hWnd, &pt); if (pt.x < LeftMargin()) SetCursor(cursors[cArrow]); else if (selStart != caret) { pt.x = (pt.x - LeftMargin()) / chSize.cx + scrollPos.x; pt.y = pt.y / chSize.cy + scrollPos.y; if (pt.y < 0 || pt.y >= lines.length() || pt.x < 0 || pt.x >= lines[pt.y].text.length()) SetCursor(cursors[cBeam]); else { int offset = fromPoint(pt); int sela = (selStart < caret ? selStart : caret); int selb = (selStart < caret ? caret : selStart); if (offset >= sela && offset < selb) SetCursor(cursors[cArrow]); else SetCursor(cursors[cBeam]); } } else SetCursor(cursors[cBeam]); } else SetCursor(cursors[cArrow]); return TRUE; case WM_ERASEBKGND: return TRUE; case WM_PAINT: paint(); return 0; case WM_SIZE: if (hBitmap) { int wd = LOWORD(lParam); int ht = HIWORD(lParam); if (wd < 10) wd = 10; if (ht < 10) ht = 10; hBitmap = CreateCompatibleBitmap(hDC, wd, ht); SelectObject(hDC, hBitmap); } updateExtent(); return 0; case WM_SETFOCUS: placeCaret(); invalidate(); getParent()->notify(EN_FOCUSED, (uint32) this, 0); return 0; case WM_KILLFOCUS: DestroyCaret(); updateCaret(); invalidate(); return 0; case WM_LBUTTONDBLCLK: { POINT pt = paramToPoint(lParam); fixPoint(pt); int ptStart = wordEnd(lines[pt.y].text.c_str(), pt.x, -1); int ptEnd = wordEnd(lines[pt.y].text.c_str(), pt.x, 1); int offset = fromPoint(pt); selStart = offset - (pt.x - ptStart); caret = offset + (ptEnd - pt.x); updateCaret(); } return 0; case WM_LBUTTONDOWN: if (int(GET_X_LPARAM(lParam)) < int(settings->bpOffset - scrollPos.x * chSize.cx)) { POINT pt = paramToPoint(lParam); toggleBreakpoint(pt.y); } else { POINT pt = paramToPoint(lParam); int offset = fromPoint(pt); int sela = (selStart < caret ? selStart : caret); int selb = (selStart > caret ? selStart : caret); if (offset >= sela && offset < selb) { dragop = 1; uint32 fx = DoDragDropEx(CF_UNICODETEXT, CreateGlobalText(getSelection()), DROPEFFECT_MOVE | DROPEFFECT_COPY, hWnd); if (fx == DROPEFFECT_NONE) dragop = 0; //else if (fx != DROPEFFECT_COPY && dragop != 2) // replace(sela, selb, ""); } else SetCapture(hWnd); if (dragop == 0) { caret = offset; if (!(wParam & MK_SHIFT)) selStart = caret; } dragop = 0; if (GetFocus() != hWnd) SetFocus(hWnd); updateCaret(); } return 0; case WM_RBUTTONDOWN: if (int(GET_X_LPARAM(lParam)) >= int(settings->bpOffset - scrollPos.x * chSize.cx)) { POINT pt = paramToPoint(lParam); int offset = fromPoint(pt); int sela = (selStart < caret ? selStart : caret); int selb = (selStart > caret ? selStart : caret); if (offset < sela || offset >= selb) caret = selStart = offset; if (GetFocus() != hWnd) SetFocus(hWnd); updateCaret(); } return 0; case WM_MOUSEMOVE: if (GetCapture() == hWnd && (wParam & MK_LBUTTON)) { POINT pt = paramToPoint(lParam); caret = fromPoint(pt); updateCaret(); } return 0; case WM_LBUTTONUP: ReleaseCapture(); return 0; case WM_CHAR: if (iswprint(wParam) && (GetAsyncKeyState(VK_CONTROL) & 0x8000) == 0) { if (caret == selStart && !insertMode && caret < getTextLength()) replace(caret, caret + 1, WideString((wchar_t) wParam)); else replace(selStart, caret, WideString((wchar_t) wParam)); } return 0; case WM_VSCROLL: { SCROLLINFO si; memset(&si, 0, sizeof si); si.cbSize = sizeof si; si.fMask = SIF_ALL; GetScrollInfo(hWnd, SB_VERT, &si); switch (LOWORD(wParam)) { case SB_TOP: si.nPos = si.nMin; break; case SB_BOTTOM: si.nPos = si.nMax; break; case SB_LINEUP: si.nPos--; break; case SB_LINEDOWN: si.nPos++; break; case SB_PAGEUP: si.nPos -= si.nPage; break; case SB_PAGEDOWN: si.nPos += si.nPage; break; case SB_THUMBTRACK: si.nPos = si.nTrackPos; break; } doScroll(scrollPos.x, si.nPos); } return 0; case WM_HSCROLL: { SCROLLINFO si; memset(&si, 0, sizeof si); si.cbSize = sizeof si; si.fMask = SIF_ALL; GetScrollInfo(hWnd, SB_HORZ, &si); switch (LOWORD(wParam)) { case SB_LEFT: si.nPos = si.nMin; break; case SB_RIGHT: si.nPos = si.nMax; break; case SB_LINELEFT: si.nPos--; break; case SB_LINERIGHT: si.nPos++; break; case SB_PAGELEFT: si.nPos -= si.nPage; break; case SB_PAGERIGHT: si.nPos += si.nPage; break; case SB_THUMBTRACK: si.nPos = si.nTrackPos; break; } doScroll(si.nPos, scrollPos.y); } return 0; case WM_MOUSEWHEEL: { int step; SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &step, 0); if (step < 0) step = 3; scrollAccum.y += GET_WHEEL_DELTA_WPARAM(wParam) * step; doScroll(scrollPos.x, scrollPos.y - scrollAccum.y / WHEEL_DELTA); scrollAccum.y %= WHEEL_DELTA; } return 0; case WM_MOUSEHWHEEL: { scrollAccum.x += GET_WHEEL_DELTA_WPARAM(wParam) * 4; doScroll(scrollPos.x + scrollAccum.x / WHEEL_DELTA, scrollPos.y); scrollAccum.x %= WHEEL_DELTA; } return 0; case WM_DRAGOVER: { if (running || settings->mode) return TRUE; POINT pt = paramToPoint(lParam); dropPos = fromPoint(pt); RECT rc; GetClientRect(hWnd, &rc); int xto = scrollPos.x; if (pt.x < 10) xto--; else if (pt.x > rc.right - 10) xto++; int yto = scrollPos.y; if (pt.y < 10) yto--; else if (pt.y > rc.bottom - 10) yto++; doScroll(xto, yto); int sela = (selStart < caret ? selStart : caret); int selb = (selStart > caret ? selStart : caret); if (dropPos > sela && dropPos < selb) return TRUE; else { fixPoint(pt); CreateCaret(hWnd, NULL, 2, chSize.cy); SetCaretPos((pt.x - scrollPos.x) * chSize.cx + LeftMargin(), (pt.y - scrollPos.y) * chSize.cy); ShowCaret(hWnd); } } return 0; case WM_DRAGLEAVE: dropPos = 0; updateCaret(); return 0; case WM_DRAGDROP: if (running || settings->mode) return DROPEFFECT_NONE; if (dragop) { dragop = 2; int sela = (selStart < caret ? selStart : caret); int selb = (selStart > caret ? selStart : caret); if (dropPos < sela || dropPos > selb) { WideString text = getSelection(); if (lParam != DROPEFFECT_COPY) { replace(sela, selb, L""); if (dropPos > selb) dropPos -= (selb - sela); caret = replace(dropPos, dropPos, text, NULL, true); } else caret = replace(dropPos, dropPos, text); selStart = dropPos; } } else { caret = replace(dropPos, dropPos, GetGlobalTextWide((HGLOBAL) wParam)); selStart = dropPos; return DROPEFFECT_COPY; } return lParam; case WM_SYSKEYDOWN: case WM_KEYDOWN: onKey(wParam); return 0; case WM_COMMAND: switch (LOWORD(wParam)) { case ID_EDIT_UNDO: { bool glue = true; bool first = true; while (glue && historyPos > 0) { HistoryItem& h = history[--historyPos]; replace(h.begin, h.end, h.text, &h); glue = h.glue; h.glue = !first; first = false; } } break; case ID_EDIT_REDO: { bool glue = true; bool first = true; while (glue && historyPos < history.length()) { HistoryItem& h = history[historyPos++]; replace(h.begin, h.end, h.text, &h); glue = h.glue; h.glue = !first; first = false; } } break; case ID_EDIT_SELECTALL: selStart = 0; caret = getTextLength(); updateCaret(); break; case ID_EDIT_COPY: if (caret != selStart) SetClipboard(CF_UNICODETEXT, CreateGlobalText(getSelection())); else { POINT pt = toPoint(caret); pt.x = 0; int start = fromPoint(pt); if (pt.y < lines.length() - 1) pt.y++; else pt.x = lines[pt.y].text.length(); int end = fromPoint(pt); if (pCopyLine) pCopyLine->Release(); pCopyLine = SetClipboard(CF_UNICODETEXT, CreateGlobalText(substring(start, end))); if (pCopyLine) pCopyLine->AddRef(); } break; case ID_EDIT_CUT: if (caret != selStart) { SetClipboard(CF_UNICODETEXT, CreateGlobalText(getSelection())); replace(selStart, caret, L""); } else { POINT pt = toPoint(caret); POINT save = pt; pt.x = 0; int start = fromPoint(pt); if (pt.y < lines.length() - 1) pt.y++; else pt.x = lines[pt.y].text.length(); int end = fromPoint(pt); if (pCopyLine) pCopyLine->Release(); pCopyLine = SetClipboard(CF_UNICODETEXT, CreateGlobalText(substring(start, end))); if (pCopyLine) pCopyLine->AddRef(); replace(start, end, L""); caret = selStart = fromPoint(save); updateCaret(); } break; case ID_EDIT_PASTE: { ClipboardReader reader(CF_UNICODETEXT); if (reader.getData()) { if (OleIsCurrentClipboard(pCopyLine) == S_OK) { POINT pt = toPoint(caret); pt.x = 0; caret = selStart = fromPoint(pt); } selStart = caret = replace(selStart, caret, GetGlobalTextWide(reader.getData())); updateCaret(); } } break; case ID_DEBUG_BREAKPOINT: { POINT pt = toPoint(caret); toggleBreakpoint(pt.y); } break; default: return M_UNHANDLED; } return 0; } return M_UNHANDLED; }
int iswgraph (wint_t c) { return (iswprint (c) && !iswspace (c)); }
static gboolean _rox_buffer_looks_like_text (const void *data, const size_t len) { gchar *end; if (g_utf8_validate (data, len, (const gchar**)&end)) { /* g_utf8_validate allows control characters */ int i; for (i = 0; i < len; i++) { unsigned char c = ((const guchar *) data)[i]; if (c < 32 && c != '\r' && c != '\n' && c != '\t') return FALSE; } return TRUE; } else { /* Check whether the string was truncated in the middle of * a valid UTF8 char, or if we really have an invalid * UTF8 string */ gint remaining_bytes = len; remaining_bytes -= (end-((gchar*)data)); if (g_utf8_get_char_validated(end, remaining_bytes) == -2) return TRUE; #if defined(HAVE_WCTYPE_H) && defined (HAVE_MBRTOWC) else { size_t wlen; wchar_t wc; gchar *src, *end; mbstate_t state; src = data; end = data+len; memset (&state, 0, sizeof (state)); while (src < end) { /* Don't allow embedded zeros in textfiles */ if (*src == 0) return FALSE; wlen = mbrtowc(&wc, src, end - src, &state); if (wlen == (size_t)(-1)) { /* Illegal mb sequence */ return FALSE; } if (wlen == (size_t)(-2)) { /* No complete mb char before end * Probably a cut off char which is ok */ return TRUE; } if (wlen == 0) { /* Don't allow embedded zeros in textfiles */ return FALSE; } if (!iswspace (wc) && !iswprint(wc)) { /* Not a printable or whitspace * Probably not a text file */ return FALSE; } src += wlen; } return TRUE; } #endif /* defined(HAVE_WCTYPE_H) && defined (HAVE_MBRTOWC) */ } return FALSE; }
static BOOL WriteString(__in FILE *fp, __in_z LPCWSTR szStringW, __in_opt SIZE_T nLength) { SIZE_T i, j, nStart; WCHAR szTempW[32]; if (szStringW == NULL) return S_OK; if (nLength == NKT_SIZE_T_MAX) nLength = wcslen(szStringW); for (i=0; i<nLength; i++) { nStart = i; for (j=0; j<X_ARRAYLEN(szTempW)-1 && i<nLength; j++) { if (iswprint(szStringW[i]) == 0 || szStringW[i] == L'\"' || szStringW[i] == L'\\') break; szTempW[j] = szStringW[i++]; } if (i > nStart) { szTempW[j] = 0; if (fprintf(fp, "%S", szTempW) == 0) return FALSE; } while (i < nLength) { if (iswprint(szStringW[i]) != 0 && szStringW[i] != L'\"' && szStringW[i] != L'\\') break; switch (szStringW[i]) { case L'\"': if (fprintf(fp, "\\\"") == 0) return FALSE; break; case L'\\': if (fprintf(fp, "\\\\") == 0) return FALSE; break; case L'\a': if (fprintf(fp, "\\a") == 0) return FALSE; break; case L'\b': if (fprintf(fp, "\\b") == 0) return FALSE; break; case L'\f': if (fprintf(fp, "\\f") == 0) return FALSE; break; case L'\n': if (fprintf(fp, "\\n") == 0) return FALSE; break; case L'\r': if (fprintf(fp, "\\r") == 0) return FALSE; break; case L'\t': if (fprintf(fp, "\\t") == 0) return FALSE; break; case L'\v': if (fprintf(fp, "\\v") == 0) return FALSE; break; case L'\0': if (fprintf(fp, "\\0") == 0) return FALSE; break; default: if (fprintf(fp, "\\x%02X", szStringW[i]) == 0) return FALSE; break; } i++; } } return TRUE; }
void safe_fprintf(FILE *f, const char *fmt, ...) { char fmtbuff_stack[256]; /* Place to format the printf() string. */ char outbuff[256]; /* Buffer for outgoing characters. */ char *fmtbuff_heap; /* If fmtbuff_stack is too small, we use malloc */ char *fmtbuff; /* Pointer to fmtbuff_stack or fmtbuff_heap. */ int fmtbuff_length; int length, n; va_list ap; const char *p; unsigned i; wchar_t wc; char try_wc; /* Use a stack-allocated buffer if we can, for speed and safety. */ fmtbuff_heap = NULL; fmtbuff_length = sizeof(fmtbuff_stack); fmtbuff = fmtbuff_stack; /* Try formatting into the stack buffer. */ va_start(ap, fmt); length = vsnprintf(fmtbuff, fmtbuff_length, fmt, ap); va_end(ap); /* If the result was too large, allocate a buffer on the heap. */ while (length < 0 || length >= fmtbuff_length) { if (length >= fmtbuff_length) fmtbuff_length = length+1; else if (fmtbuff_length < 8192) fmtbuff_length *= 2; else if (fmtbuff_length < 1000000) fmtbuff_length += fmtbuff_length / 4; else { length = fmtbuff_length; fmtbuff_heap[length-1] = '\0'; break; } free(fmtbuff_heap); fmtbuff_heap = malloc(fmtbuff_length); /* Reformat the result into the heap buffer if we can. */ if (fmtbuff_heap != NULL) { fmtbuff = fmtbuff_heap; va_start(ap, fmt); length = vsnprintf(fmtbuff, fmtbuff_length, fmt, ap); va_end(ap); } else { /* Leave fmtbuff pointing to the truncated * string in fmtbuff_stack. */ length = sizeof(fmtbuff_stack) - 1; break; } } /* Note: mbrtowc() has a cleaner API, but mbtowc() seems a bit * more portable, so we use that here instead. */ if (mbtowc(NULL, NULL, 1) == -1) { /* Reset the shift state. */ /* mbtowc() should never fail in practice, but * handle the theoretical error anyway. */ free(fmtbuff_heap); return; } /* Write data, expanding unprintable characters. */ p = fmtbuff; i = 0; try_wc = 1; while (*p != '\0') { /* Convert to wide char, test if the wide * char is printable in the current locale. */ if (try_wc && (n = mbtowc(&wc, p, length)) != -1) { length -= n; if (iswprint(wc) && wc != L'\\') { /* Printable, copy the bytes through. */ while (n-- > 0) outbuff[i++] = *p++; } else { /* Not printable, format the bytes. */ while (n-- > 0) i += (unsigned)bsdtar_expand_char( outbuff, i, *p++); } } else { /* After any conversion failure, don't bother * trying to convert the rest. */ i += (unsigned)bsdtar_expand_char(outbuff, i, *p++); try_wc = 0; } /* If our output buffer is full, dump it and keep going. */ if (i > (sizeof(outbuff) - 20)) { outbuff[i] = '\0'; fprintf(f, "%s", outbuff); i = 0; } } outbuff[i] = '\0'; fprintf(f, "%s", outbuff); /* If we allocated a heap-based formatting buffer, free it now. */ free(fmtbuff_heap); }
const wchar_t * el_wgets(EditLine *el, int *nread) { int retval; el_action_t cmdnum = 0; int num; /* how many chars we have read at NL */ wchar_t wc; wchar_t ch, *cp; int crlf = 0; int nrb; if (nread == NULL) nread = &nrb; *nread = 0; if (el->el_flags & NO_TTY) { size_t idx; cp = el->el_line.buffer; while ((num = (*el->el_read->read_char)(el, &wc)) == 1) { *cp = wc; /* make sure there is space for next character */ if (cp + 1 >= el->el_line.limit) { idx = (size_t)(cp - el->el_line.buffer); if (!ch_enlargebufs(el, (size_t)2)) break; cp = &el->el_line.buffer[idx]; } cp++; if (el->el_flags & UNBUFFERED) break; if (cp[-1] == '\r' || cp[-1] == '\n') break; } if (num == -1) { if (errno == EINTR) cp = el->el_line.buffer; el->el_errno = errno; } goto noedit; } #ifdef FIONREAD if (el->el_tty.t_mode == EX_IO && el->el_chared.c_macro.level < 0) { int chrs = 0; (void) ioctl(el->el_infd, FIONREAD, &chrs); if (chrs == 0) { if (tty_rawmode(el) < 0) { errno = 0; *nread = 0; return NULL; } } } #endif /* FIONREAD */ if ((el->el_flags & UNBUFFERED) == 0) read_prepare(el); if (el->el_flags & EDIT_DISABLED) { size_t idx; if ((el->el_flags & UNBUFFERED) == 0) cp = el->el_line.buffer; else cp = el->el_line.lastchar; terminal__flush(el); while ((num = (*el->el_read->read_char)(el, &wc)) == 1) { *cp = wc; /* make sure there is space next character */ if (cp + 1 >= el->el_line.limit) { idx = (size_t)(cp - el->el_line.buffer); if (!ch_enlargebufs(el, (size_t)2)) break; cp = &el->el_line.buffer[idx]; } cp++; crlf = cp[-1] == '\r' || cp[-1] == '\n'; if (el->el_flags & UNBUFFERED) break; if (crlf) break; } if (num == -1) { if (errno == EINTR) cp = el->el_line.buffer; el->el_errno = errno; } goto noedit; } for (num = -1; num == -1;) { /* while still editing this line */ #ifdef DEBUG_EDIT read_debug(el); #endif /* DEBUG_EDIT */ /* if EOF or error */ if (read_getcmd(el, &cmdnum, &ch) == -1) { #ifdef DEBUG_READ (void) fprintf(el->el_errfile, "Returning from el_gets\n"); #endif /* DEBUG_READ */ break; } if (el->el_errno == EINTR) { el->el_line.buffer[0] = '\0'; el->el_line.lastchar = el->el_line.cursor = el->el_line.buffer; break; } if ((size_t)cmdnum >= el->el_map.nfunc) { /* BUG CHECK command */ #ifdef DEBUG_EDIT (void) fprintf(el->el_errfile, "ERROR: illegal command from key 0%o\r\n", ch); #endif /* DEBUG_EDIT */ continue; /* try again */ } /* now do the real command */ #ifdef DEBUG_READ { el_bindings_t *b; for (b = el->el_map.help; b->name; b++) if (b->func == cmdnum) break; if (b->name) (void) fprintf(el->el_errfile, "Executing %ls\n", b->name); else (void) fprintf(el->el_errfile, "Error command = %d\n", cmdnum); } #endif /* DEBUG_READ */ /* vi redo needs these way down the levels... */ el->el_state.thiscmd = cmdnum; el->el_state.thisch = ch; if (el->el_map.type == MAP_VI && el->el_map.current == el->el_map.key && el->el_chared.c_redo.pos < el->el_chared.c_redo.lim) { if (cmdnum == VI_DELETE_PREV_CHAR && el->el_chared.c_redo.pos != el->el_chared.c_redo.buf && iswprint(el->el_chared.c_redo.pos[-1])) el->el_chared.c_redo.pos--; else *el->el_chared.c_redo.pos++ = ch; } retval = (*el->el_map.func[cmdnum]) (el, ch); #ifdef DEBUG_READ (void) fprintf(el->el_errfile, "Returned state %d\n", retval ); #endif /* DEBUG_READ */ /* save the last command here */ el->el_state.lastcmd = cmdnum; /* use any return value */ switch (retval) { case CC_CURSOR: re_refresh_cursor(el); break; case CC_REDISPLAY: re_clear_lines(el); re_clear_display(el); /* FALLTHROUGH */ case CC_REFRESH: re_refresh(el); break; case CC_REFRESH_BEEP: re_refresh(el); terminal_beep(el); break; case CC_NORM: /* normal char */ break; case CC_ARGHACK: /* Suggested by Rich Salz */ /* <*****@*****.**> */ continue; /* keep going... */ case CC_EOF: /* end of file typed */ if ((el->el_flags & UNBUFFERED) == 0) num = 0; else if (num == -1) { *el->el_line.lastchar++ = CONTROL('d'); el->el_line.cursor = el->el_line.lastchar; num = 1; } break; case CC_NEWLINE: /* normal end of line */ num = (int)(el->el_line.lastchar - el->el_line.buffer); break; case CC_FATAL: /* fatal error, reset to known state */ #ifdef DEBUG_READ (void) fprintf(el->el_errfile, "*** editor fatal ERROR ***\r\n\n"); #endif /* DEBUG_READ */ /* put (real) cursor in a known place */ re_clear_display(el); /* reset the display stuff */ ch_reset(el, 1); /* reset the input pointers */ re_refresh(el); /* print the prompt again */ break; case CC_ERROR: default: /* functions we don't know about */ #ifdef DEBUG_READ (void) fprintf(el->el_errfile, "*** editor ERROR ***\r\n\n"); #endif /* DEBUG_READ */ terminal_beep(el); terminal__flush(el); break; } el->el_state.argument = 1; el->el_state.doingarg = 0; el->el_chared.c_vcmd.action = NOP; if (el->el_flags & UNBUFFERED) break; } terminal__flush(el); /* flush any buffered output */ /* make sure the tty is set up correctly */ if ((el->el_flags & UNBUFFERED) == 0) { read_finish(el); *nread = num != -1 ? num : 0; } else { *nread = (int)(el->el_line.lastchar - el->el_line.buffer); } goto done; noedit: el->el_line.cursor = el->el_line.lastchar = cp; *cp = '\0'; *nread = (int)(el->el_line.cursor - el->el_line.buffer); done: if (*nread == 0) { if (num == -1) { *nread = -1; errno = el->el_errno; } return NULL; } else return el->el_line.buffer; }
static void chat_onKey(ToxWindow *self, Messenger *m, wint_t key) { ChatContext *ctx = (ChatContext *) self->x; struct tm *timeinfo = get_time(); int x, y, y2, x2; getyx(self->window, y, x); getmaxyx(self->window, y2, x2); /* Add printable chars to buffer and print on input space */ #if HAVE_WIDECHAR if (iswprint(key)) { #else if (isprint(key)) { #endif if (ctx->pos != sizeof(ctx->line) - 1) { mvwaddstr(self->window, y, x, wc_to_char(key)); ctx->line[ctx->pos++] = key; ctx->line[ctx->pos] = L'\0'; } } /* BACKSPACE key: Remove one character from line */ else if (key == 0x107 || key == 0x8 || key == 0x7f) { if (ctx->pos > 0) { ctx->line[--ctx->pos] = L'\0'; if (x == 0) mvwdelch(self->window, y - 1, x2 - 1); else mvwdelch(self->window, y, x - 1); } } /* RETURN key: Execute command or print line */ else if (key == '\n') { char *line = wcs_to_char(ctx->line); wclear(ctx->linewin); wmove(self->window, y2 - CURS_Y_OFFSET, 0); wclrtobot(self->window); if (line[0] == '/') execute(self, ctx, m, line); else { /* make sure the string has at least non-space character */ if (!string_is_empty(line)) { uint8_t selfname[MAX_NAME_LENGTH]; getself_name(m, selfname, sizeof(selfname)); wattron(ctx->history, COLOR_PAIR(2)); wprintw(ctx->history, "[%02d:%02d:%02d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec); wattroff(ctx->history, COLOR_PAIR(2)); wattron(ctx->history, COLOR_PAIR(1)); wprintw(ctx->history, "%s: ", selfname); wattroff(ctx->history, COLOR_PAIR(1)); wprintw(ctx->history, "%s\n", line); if (m_sendmessage(m, ctx->friendnum, (uint8_t *) line, strlen(line) + 1) == 0) { wattron(ctx->history, COLOR_PAIR(3)); wprintw(ctx->history, " * Failed to send message.\n"); wattroff(ctx->history, COLOR_PAIR(3)); } } } ctx->line[0] = L'\0'; ctx->pos = 0; free(line); } } void execute(ToxWindow *self, ChatContext *ctx, Messenger *m, char *cmd) { if (!strcmp(cmd, "/clear") || !strcmp(cmd, "/c")) { wclear(self->window); wclear(ctx->history); int x, y; getmaxyx(self->window, y, x); (void) x; wmove(self->window, y - CURS_Y_OFFSET, 0); } else if (!strcmp(cmd, "/help") || !strcmp(cmd, "/h")) print_help(ctx); else if (!strcmp(cmd, "/quit") || !strcmp(cmd, "/exit") || !strcmp(cmd, "/q")) { endwin(); exit(0); } else if (!strncmp(cmd, "/me ", strlen("/me "))) { struct tm *timeinfo = get_time(); char *action = strchr(cmd, ' '); if (action == NULL) { wprintw(self->window, "Invalid syntax.\n"); return; } action++; wattron(ctx->history, COLOR_PAIR(2)); wprintw(ctx->history, "[%02d:%02d:%02d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec); wattroff(ctx->history, COLOR_PAIR(2)); uint8_t selfname[MAX_NAME_LENGTH]; int len = getself_name(m, selfname, sizeof(selfname)); char msg[MAX_STR_SIZE - len - 4]; snprintf(msg, sizeof(msg), "* %s %s\n", (uint8_t *) selfname, action); wattron(ctx->history, COLOR_PAIR(5)); wprintw(ctx->history, msg); wattroff(ctx->history, COLOR_PAIR(5)); if (m_sendaction(m, ctx->friendnum, (uint8_t *) msg, strlen(msg) + 1) < 0) { wattron(ctx->history, COLOR_PAIR(3)); wprintw(ctx->history, " * Failed to send action\n"); wattroff(ctx->history, COLOR_PAIR(3)); } } else if (!strncmp(cmd, "/status ", strlen("/status "))) { char *status = strchr(cmd, ' '); char *msg; char *status_text; if (status == NULL) { wprintw(ctx->history, "Invalid syntax.\n"); return; } status++; USERSTATUS status_kind; if (!strncmp(status, "online", strlen("online"))) { status_kind = USERSTATUS_NONE; status_text = "ONLINE"; } else if (!strncmp(status, "away", strlen("away"))) { status_kind = USERSTATUS_AWAY; status_text = "AWAY"; } else if (!strncmp(status, "busy", strlen("busy"))) { status_kind = USERSTATUS_BUSY; status_text = "BUSY"; } else { wprintw(ctx->history, "Invalid status.\n"); return; } msg = strchr(status, ' '); if (msg == NULL) { m_set_userstatus(m, status_kind); wprintw(ctx->history, "Status set to: %s\n", status_text); } else { msg++; m_set_userstatus(m, status_kind); m_set_statusmessage(m, ( uint8_t *) msg, strlen(msg) + 1); wprintw(ctx->history, "Status set to: %s, %s\n", status_text, msg); } } else if (!strncmp(cmd, "/nick ", strlen("/nick "))) { char *nick; nick = strchr(cmd, ' '); if (nick == NULL) { wprintw(ctx->history, "Invalid syntax.\n"); return; } nick++; setname(m, (uint8_t *) nick, strlen(nick) + 1); wprintw(ctx->history, "Nickname set to: %s\n", nick); } else if (!strcmp(cmd, "/myid")) { char id[FRIEND_ADDRESS_SIZE * 2 + 1] = {0}; uint8_t address[FRIEND_ADDRESS_SIZE]; size_t i; getaddress(m, address); for (i = 0; i < FRIEND_ADDRESS_SIZE; i++) { char xx[3]; snprintf(xx, sizeof(xx), "%02X", address[i] & 0xff); strcat(id, xx); } wprintw(ctx->history, "%s\n", id); } else if (strcmp(cmd, "/close") == 0) { int f_num = ctx->friendnum; delwin(ctx->linewin); del_window(self); disable_chatwin(f_num); } else wprintw(ctx->history, "Invalid command.\n"); } static void chat_onDraw(ToxWindow *self, Messenger *m) { curs_set(1); int x, y; getmaxyx(self->window, y, x); (void) y; ChatContext *ctx = (ChatContext *) self->x; mvwhline(ctx->linewin, 0, 0, '_', x); wrefresh(self->window); }
static void chat_onKey(ToxWindow *self, Tox *m, wint_t key) { ChatContext *ctx = (ChatContext *) self->x; StatusBar *statusbar = (StatusBar *) self->s; struct tm *timeinfo = get_time(); int x, y, y2, x2; getyx(self->window, y, x); getmaxyx(self->window, y2, x2); /* Add printable chars to buffer and print on input space */ #if HAVE_WIDECHAR if (iswprint(key)) { #else if (isprint(key)) { #endif if (ctx->pos < (MAX_STR_SIZE-1)) { mvwaddstr(self->window, y, x, wc_to_char(key)); ctx->line[ctx->pos++] = key; ctx->line[ctx->pos] = L'\0'; } } /* BACKSPACE key: Remove one character from line */ else if (key == 0x107 || key == 0x8 || key == 0x7f) { if (ctx->pos > 0) { ctx->line[--ctx->pos] = L'\0'; if (x == 0) mvwdelch(self->window, y - 1, x2 - 1); else mvwdelch(self->window, y, x - 1); } } /* RETURN key: Execute command or print line */ else if (key == '\n') { uint8_t *line = wcs_to_char(ctx->line); wclear(ctx->linewin); wmove(self->window, y2 - CURS_Y_OFFSET, 0); wclrtobot(self->window); bool close_win = false; if (line[0] == '/') { if (close_win = !strncmp(line, "/close", strlen("/close"))) { int f_num = self->friendnum; delwin(ctx->linewin); delwin(statusbar->topline); del_window(self); disable_chatwin(f_num); } else execute(self, ctx, statusbar, m, line); } else { /* make sure the string has at least non-space character */ if (!string_is_empty(line)) { uint8_t selfname[TOX_MAX_NAME_LENGTH]; tox_getselfname(m, selfname, TOX_MAX_NAME_LENGTH); wattron(ctx->history, COLOR_PAIR(CYAN)); wprintw(ctx->history, "[%02d:%02d:%02d] ", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec); wattroff(ctx->history, COLOR_PAIR(CYAN)); wattron(ctx->history, COLOR_PAIR(GREEN)); wprintw(ctx->history, "%s: ", selfname); wattroff(ctx->history, COLOR_PAIR(GREEN)); wprintw(ctx->history, "%s\n", line); if (!statusbar->is_online || tox_sendmessage(m, self->friendnum, line, strlen(line) + 1) == 0) { wattron(ctx->history, COLOR_PAIR(RED)); wprintw(ctx->history, " * Failed to send message.\n"); wattroff(ctx->history, COLOR_PAIR(RED)); } } } if (close_win) { free(ctx); free(statusbar); } else { ctx->line[0] = L'\0'; ctx->pos = 0; } free(line); } } static void chat_onDraw(ToxWindow *self, Tox *m) { curs_set(1); int x, y; getmaxyx(self->window, y, x); ChatContext *ctx = (ChatContext *) self->x; /* Draw status bar */ StatusBar *statusbar = (StatusBar *) self->s; mvwhline(statusbar->topline, 1, 0, '-', x); wmove(statusbar->topline, 0, 0); /* Draw name, status and note in statusbar */ if (statusbar->is_online) { char *status_text = "Unknown"; int colour = WHITE; TOX_USERSTATUS status = statusbar->status; switch(status) { case TOX_USERSTATUS_NONE: status_text = "Online"; colour = GREEN; break; case TOX_USERSTATUS_AWAY: status_text = "Away"; colour = YELLOW; break; case TOX_USERSTATUS_BUSY: status_text = "Busy"; colour = RED; break; } wattron(statusbar->topline, A_BOLD); wprintw(statusbar->topline, " %s ", self->name); wattroff(statusbar->topline, A_BOLD); wattron(statusbar->topline, COLOR_PAIR(colour) | A_BOLD); wprintw(statusbar->topline, "[%s]", status_text); wattroff(statusbar->topline, COLOR_PAIR(colour) | A_BOLD); } else { wattron(statusbar->topline, A_BOLD); wprintw(statusbar->topline, " %s ", self->name); wattroff(statusbar->topline, A_BOLD); wprintw(statusbar->topline, "[Offline]"); } /* Truncate note if it doesn't fit in statusbar */ uint16_t maxlen = x - getcurx(statusbar->topline) - 5; if (statusbar->statusmsg_len > maxlen) { statusbar->statusmsg[maxlen] = '\0'; statusbar->statusmsg_len = maxlen; } wattron(statusbar->topline, A_BOLD); wprintw(statusbar->topline, " | %s |", statusbar->statusmsg); wattroff(statusbar->topline, A_BOLD); wprintw(statusbar->topline, "\n"); mvwhline(ctx->linewin, 0, 0, '_', x); wrefresh(self->window); }
void MainCtrl::redraw () { choose_palette (ui::PALETTE_ID_ENTRY); clear (); if (w().entries.empty ()) { put(ui::Size{}, L"No entry yet."); put(ui::Size{0, 1}, L"Press \"a\" to create one; press Esc for the menu."); #ifdef TIARY_USE_MOUSE put(ui::Size{0, 2}, L"You can also use your mouse."); #endif return; } if (w().filtered_entries_ && w().filtered_entries_->empty ()) { put(ui::Size{}, L"This is in filtered mode."); put(ui::Size{0, 1}, L"But no entry satisfies your requirement."); put(ui::Size{0, 2}, L"Press Ctrl-G to modify your filter; or LEFT to see all entries."); return; } unsigned expand_lines = w().global_options.get_num (GLOBAL_OPTION_EXPAND_LINES); scroll_.modify_height(get_size().y - expand_lines + 1); ui::Scroll::Info info = scroll_.get_info(); ui::Size pos{}; std::wstring date_format = w().global_options.get_wstring (GLOBAL_OPTION_DATETIME_FORMAT); // Build a map to get entry ID from pointer std::map <const DiaryEntry *, unsigned> id_map; for (size_t i=0; i<w().entries.size (); ++i) { id_map.insert (std::make_pair (w().entries[i], i+1)); } // Is there a filter? const DiaryEntryList &ent_lst = w().get_current_list (); wchar_t *disp_buffer = new wchar_t [get_size ().x]; for (unsigned i=0; i<info.len; ++i) { choose_palette (i == info.focus_pos ? ui::PALETTE_ID_ENTRY_SELECT : ui::PALETTE_ID_ENTRY); if (i == info.focus_pos) { move_cursor (pos); clear(pos, ui::Size{get_size().x, expand_lines}); } const DiaryEntry &entry = *ent_lst[i+info.first]; // Entry ID pos = put(pos, format(L"%04a "sv, id_map[&entry])); // Date choose_palette (i == info.focus_pos ? ui::PALETTE_ID_ENTRY_DATE_SELECT : ui::PALETTE_ID_ENTRY_DATE); pos = put(pos, entry.local_time.format(date_format)); pos.x++; // Title SplitStringLine split_info; const std::wstring &title = entry.title; choose_palette (i == info.focus_pos ? ui::PALETTE_ID_ENTRY_TITLE_SELECT : ui::PALETTE_ID_ENTRY_TITLE); split_line(&split_info, maxS (0, get_size().x-pos.x), title, 0, SPLIT_NEWLINE_AS_SPACE|SPLIT_CUT_WORD); pos = put (pos, disp_buffer, std::replace_copy_if ( &title[split_info.begin], &title[split_info.begin+split_info.len], disp_buffer, [](auto x) { return !iswprint(x); }, L' ') - disp_buffer); pos.x++; // Labels const DiaryEntry::LabelList &labels = entry.labels; choose_palette (i == info.focus_pos ? ui::PALETTE_ID_ENTRY_LABELS_SELECT : ui::PALETTE_ID_ENTRY_LABELS); int left_wid = get_size().x - pos.x; for (DiaryEntry::LabelList::const_iterator it=labels.begin(); it!=labels.end(); ) { if (left_wid < 3) { break; } unsigned labelwid = ucs_width (*it); if (labelwid + 2 > unsigned (left_wid)) { pos = put (pos, L"...", 3); break; } pos = put (pos, *it); if (++it != labels.end ()) { pos = put (pos, L','); } } pos.x++; choose_palette (i == info.focus_pos ? ui::PALETTE_ID_ENTRY_TEXT_SELECT : ui::PALETTE_ID_ENTRY_TEXT); const std::wstring &text = entry.text; size_t offset = 0; if (i == info.focus_pos && expand_lines >= 2) { // Current entry // [Date] [Title] [Labels] // [...] for (unsigned j=1; j<expand_lines; ++j) { pos = ui::Size{0, pos.y + 1}; offset = split_line(&split_info, get_size().x, text, offset, SPLIT_NEWLINE_AS_SPACE); wchar_t *bufend = std::replace_copy_if ( &text[split_info.begin], &text[split_info.begin+split_info.len], disp_buffer, [](auto x) { return !iswprint(x); }, L' '); pos = put (pos, disp_buffer, bufend-disp_buffer); } } else { // Other entry // [Date] [Title] [Labels] [...] offset = split_line(&split_info, maxS (0, get_size().x - pos.x), text, offset, SPLIT_NEWLINE_AS_SPACE|SPLIT_CUT_WORD); wchar_t *bufend = std::replace_copy_if ( &text[split_info.begin], &text[split_info.begin+split_info.len], disp_buffer, [](auto x) { return !iswprint(x); }, L' '); pos = put (pos, disp_buffer, bufend-disp_buffer); } pos = ui::Size{0, pos.y + 1}; } delete [] disp_buffer; }
int iswprint_l(wint_t c, locale_t) { return iswprint(c); }
static void filtr(struct iblok *f) { wint_t c; char b, *cp; int i, n, w = 0; while((mb_cur_max > 1 ? cp = ib_getw(f, &c, &n) : (b = c = ib_get(f), n = 1, cp = c == (wint_t)EOF ? 0 : &b)), cp != NULL) switch(c) { case '\b': if (col > 0) col--; continue; case '\t': col = (col+8) & ~07; if (col > maxcol) maxcol = col; continue; case '\r': col = 0; continue; case SO: mode |= ALTSET; continue; case SI: mode &= ~ALTSET; continue; case IESC: mb_cur_max > 1 ? cp = ib_getw(f, &c, &n) : (b = c = ib_get(f), n = 1, cp = c == (wint_t)EOF ? 0 : &b); switch (c) { case HREV: if (halfpos == 0) { mode |= SUPERSC; halfpos--; } else if (halfpos > 0) { mode &= ~SUBSC; halfpos--; } else { halfpos = 0; reverse(); } continue; case HFWD: if (halfpos == 0) { mode |= SUBSC; halfpos++; } else if (halfpos < 0) { mode &= ~SUPERSC; halfpos++; } else { halfpos = 0; fwd(); } continue; case FREV: reverse(); continue; default: fprintf(stderr, "Unknown escape sequence in input: %o, %o\n", IESC, cp?*cp:EOF); exit(1); } continue; case '_': obaccs(col); if (obuf[col].c_char) obuf[col].c_mode |= UNDERL | mode; else obuf[col].c_char = '_'; case ' ': col++; if (col > maxcol) maxcol = col; continue; case '\n': flushln(); continue; default: if (mb_cur_max > 1 ? c == WEOF || (w = wcwidth(c)) < 0 || w == 0 && !iswprint(c) : (w = 1, c == (wint_t)EOF || !isprint(c))) /* non printing */ continue; obaccs(col); if (obuf[col].c_char == '\0') { obuf[col].c_char = c; obuf[col].c_mode = mode; } else if (obuf[col].c_char == '_') { obuf[col].c_char = c; obuf[col].c_mode |= UNDERL|mode; } else if (obuf[col].c_char == c) obuf[col].c_mode |= BOLD|mode; else { obuf[col].c_mode = c; obuf[col].c_mode = mode; } obaccs(col+w-1); for (i = 1; i < w; i++) { obuf[col+i].c_mode = obuf[col].c_mode|FILLER; obuf[col+i].c_char = obuf[col].c_char; } col += w; if (col > maxcol) maxcol = col; continue; } if (maxcol) flushln(); }
bool isPrintableChar(UChar c) { return !!iswprint(c); }
/** * @param: the string (at stack -1) * @return: the quoted string (push to stack -1) */ static int l_repr_string(lua_State *L) { size_t size; const char *src = lua_tolstring(L, -1, &size); /* calculate the single-quote vs. double-quote */ size_t single_quote=0, double_quote=0; for (size_t i=0; i<size; i++) { if (src[i] == '"') ++double_quote; if (src[i] == '\'') ++single_quote; } char quote = (double_quote > single_quote) ? '\'' : '"'; wchar_t wstr[size+1]; size_t retsize = mbstowcs(wstr, src, size+1); /* start of luaL_Buffer */ luaL_Buffer b; luaL_buffinit(L, &b); luaL_addchar(&b, quote); /* if not a valid utf-8 string we use isprint() to check printable char */ if (retsize == (size_t)-1) { for (; size--; src++) { switch (*src) { case '\\': luaL_addlstring(&b, "\\\\", 2); break; case '\r': luaL_addlstring(&b, "\\r", 2); break; case '\n': luaL_addlstring(&b, "\\n", 2); break; default: if (*src == quote) { luaL_addchar(&b, '\\'); luaL_addchar(&b, quote); } else if (isprint(*src)) { luaL_addchar(&b, *src); } else { char repr_char[5]; /* forget to cast unsigned leads to segmentation fault */ sprintf(repr_char, "\\%03u", (unsigned char)(*src)); luaL_addlstring(&b, repr_char, 4); } break; } } } else { /* for utf-8 string we use iswprint() */ for (size_t i = 0; i < retsize; i++) { switch (wstr[i]) { case L'\\': luaL_addlstring(&b, "\\\\", 2); break; case L'\r': luaL_addlstring(&b, "\\r", 2); break; case L'\n': luaL_addlstring(&b, "\\n", 2); break; default: if (wstr[i] == (wchar_t)quote) { luaL_addchar(&b, '\\'); luaL_addchar(&b, quote); } else { char utf8str[MB_CUR_MAX]; int wssize = wctomb(utf8str, wstr[i]); /* most utf-8 character should be printable */ if (iswprint(wstr[i])) { luaL_addlstring(&b, utf8str, wssize); } else { char repr_char[wssize*4+1]; for (int j=0; j<wssize; j++) { /* forget to cast unsigned leads to segmentation fault */ sprintf(repr_char, "\\%03u", (unsigned char)utf8str[j]); luaL_addlstring(&b, repr_char, 4); } } } break; } } size_t zs = strlen(src); if (zs != size) { for (; zs<size; zs++) { switch (src[zs]) { case '\\': luaL_addlstring(&b, "\\\\", 2); break; case '\r': luaL_addlstring(&b, "\\r", 2); break; case '\n': luaL_addlstring(&b, "\\n", 2); break; default: if (src[zs] == quote) { luaL_addchar(&b, '\\'); luaL_addchar(&b, quote); } else if (isprint(src[zs])) { luaL_addchar(&b, src[zs]); } else { char repr_char[5]; /* forget to cast unsigned leads to segmentation fault */ sprintf(repr_char, "\\%03u", (unsigned char)(src[zs])); luaL_addlstring(&b, repr_char, 4); } break; } } } } luaL_addchar(&b, quote); luaL_pushresult(&b); /* end of luaL_Buffer */ return 1; }
static int Isprint(int c) { return iswprint(c); }
/* Keys for line input in a text grid window. */ static command_t *commands_textgrid_line(window_textgrid_t *dwin, glui32 key) { static command_t cmdacceptline = { gcmd_grid_accept_line, 0 }; static command_t cmdacceptlineterm = { gcmd_grid_accept_line, -1 }; static command_t cmdinsert = { gcmd_grid_insert_key, -1 }; static command_t cmdmoveleft = { gcmd_grid_move_cursor, gcmd_Left }; static command_t cmdmoveright = { gcmd_grid_move_cursor, gcmd_Right }; static command_t cmdmoveleftend = { gcmd_grid_move_cursor, gcmd_LeftEnd }; static command_t cmdmoverightend = { gcmd_grid_move_cursor, gcmd_RightEnd }; static command_t cmddelete = { gcmd_grid_delete, gcmd_Delete }; static command_t cmddeletenext = { gcmd_grid_delete, gcmd_DeleteNext }; static command_t cmdkillinput = { gcmd_grid_delete, gcmd_KillInput }; static command_t cmdkillline = { gcmd_grid_delete, gcmd_KillLine }; if (key >= 32 && key < 256 && key != 127) return &cmdinsert; switch (key) { case keycode_Return: case '\012': /* ctrl-J */ case '\015': /* ctrl-M */ return &cmdacceptline; case keycode_Left: case '\002': /* ctrl-B */ return &cmdmoveleft; case keycode_Right: case '\006': /* ctrl-F */ return &cmdmoveright; case keycode_Home: case '\001': /* ctrl-A */ return &cmdmoveleftend; case keycode_End: case '\005': /* ctrl-E */ return &cmdmoverightend; case keycode_Delete: case '\177': /* delete */ case '\010': /* backspace */ return &cmddelete; case '\004': /* ctrl-D */ return &cmddeletenext; case '\013': /* ctrl-K */ return &cmdkillline; case '\025': /* ctrl-U */ return &cmdkillinput; case '\033': /* escape */ if (dwin->intermkeys & 0x10000) return &cmdacceptlineterm; break; #ifdef KEY_F case KEY_F(1): if (dwin->intermkeys & (1<<1)) return &cmdacceptlineterm; break; case KEY_F(2): if (dwin->intermkeys & (1<<2)) return &cmdacceptlineterm; break; case KEY_F(3): if (dwin->intermkeys & (1<<3)) return &cmdacceptlineterm; break; case KEY_F(4): if (dwin->intermkeys & (1<<4)) return &cmdacceptlineterm; break; case KEY_F(5): if (dwin->intermkeys & (1<<5)) return &cmdacceptlineterm; break; case KEY_F(6): if (dwin->intermkeys & (1<<6)) return &cmdacceptlineterm; break; case KEY_F(7): if (dwin->intermkeys & (1<<7)) return &cmdacceptlineterm; break; case KEY_F(8): if (dwin->intermkeys & (1<<8)) return &cmdacceptlineterm; break; case KEY_F(9): if (dwin->intermkeys & (1<<9)) return &cmdacceptlineterm; break; case KEY_F(10): if (dwin->intermkeys & (1<<10)) return &cmdacceptlineterm; break; case KEY_F(11): if (dwin->intermkeys & (1<<11)) return &cmdacceptlineterm; break; case KEY_F(12): if (dwin->intermkeys & (1<<12)) return &cmdacceptlineterm; break; #endif /* KEY_F */ } /* Non-Latin1 glyphs valid in this locale */ if ( key > 256 && iswprint (glui32_to_wchar(key)) ) return &cmdinsert; return NULL; }
static void chat_onKey(ToxWindow *self, Tox *m, wint_t key) { ChatContext *ctx = self->chatwin; StatusBar *statusbar = self->stb; int x, y, y2, x2; getyx(self->window, y, x); getmaxyx(self->window, y2, x2); int cur_len = 0; if (key == 0x107 || key == 0x8 || key == 0x7f) { /* BACKSPACE key: Remove character behind pos */ if (ctx->pos > 0) { cur_len = MAX(1, wcwidth(ctx->line[ctx->pos - 1])); del_char_buf_bck(ctx->line, &ctx->pos, &ctx->len); if (x == 0) wmove(self->window, y-1, x2 - cur_len); else wmove(self->window, y, x - cur_len); } else { beep(); } } else if (key == KEY_DC) { /* DEL key: Remove character at pos */ if (ctx->pos != ctx->len) del_char_buf_frnt(ctx->line, &ctx->pos, &ctx->len); else beep(); } else if (key == T_KEY_DISCARD) { /* CTRL-U: Delete entire line behind pos */ if (ctx->pos > 0) { discard_buf(ctx->line, &ctx->pos, &ctx->len); wmove(self->window, y2 - CURS_Y_OFFSET, 0); } else { beep(); } } else if (key == T_KEY_KILL) { /* CTRL-K: Delete entire line in front of pos */ if (ctx->pos != ctx->len) kill_buf(ctx->line, &ctx->pos, &ctx->len); else beep(); } else if (key == KEY_HOME) { /* HOME key: Move cursor to beginning of line */ if (ctx->pos > 0) { ctx->pos = 0; wmove(self->window, y2 - CURS_Y_OFFSET, 0); } } else if (key == KEY_END) { /* END key: move cursor to end of line */ if (ctx->pos != ctx->len) { ctx->pos = ctx->len; mv_curs_end(self->window, MAX(0, wcswidth(ctx->line, (CHATBOX_HEIGHT-1)*x2)), y2, x2); } } else if (key == KEY_LEFT) { if (ctx->pos > 0) { --ctx->pos; cur_len = MAX(1, wcwidth(ctx->line[ctx->pos])); if (x == 0) wmove(self->window, y-1, x2 - cur_len); else wmove(self->window, y, x - cur_len); } else { beep(); } } else if (key == KEY_RIGHT) { if (ctx->pos < ctx->len) { cur_len = MAX(1, wcwidth(ctx->line[ctx->pos])); ++ctx->pos; if (x == x2-1) wmove(self->window, y+1, 0); else wmove(self->window, y, x + cur_len); } else { beep(); } } else if (key == KEY_UP) { /* fetches previous item in history */ fetch_hist_item(ctx->line, &ctx->pos, &ctx->len, ctx->ln_history, ctx->hst_tot, &ctx->hst_pos, LN_HIST_MV_UP); mv_curs_end(self->window, ctx->len, y2, x2); } else if (key == KEY_DOWN) { /* fetches next item in history */ fetch_hist_item(ctx->line, &ctx->pos, &ctx->len, ctx->ln_history, ctx->hst_tot, &ctx->hst_pos, LN_HIST_MV_DWN); mv_curs_end(self->window, ctx->len, y2, x2); } else if (key == '\t') { /* TAB key: completes command */ if (ctx->len > 1 && ctx->line[0] == '/') { int diff = complete_line(ctx->line, &ctx->pos, &ctx->len, chat_cmd_list, AC_NUM_CHAT_COMMANDS, MAX_CMDNAME_SIZE); if (diff != -1) { if (x + diff > x2 - 1) { int ofst = (x + diff - 1) - (x2 - 1); wmove(self->window, y+1, ofst); } else { wmove(self->window, y, x+diff); } } else { beep(); } } else { beep(); } } else #if HAVE_WIDECHAR if (iswprint(key)) #else if (isprint(key)) #endif { /* prevents buffer overflows and strange behaviour when cursor goes past the window */ if ( (ctx->len < MAX_STR_SIZE-1) && (ctx->len < (x2 * (CHATBOX_HEIGHT - 1)-1)) ) { add_char_to_buf(ctx->line, &ctx->pos, &ctx->len, key); if (x == x2-1) wmove(self->window, y+1, 0); else wmove(self->window, y, x + MAX(1, wcwidth(key))); } } /* RETURN key: Execute command or print line */ else if (key == '\n') { uint8_t line[MAX_STR_SIZE]; if (wcs_to_mbs_buf(line, ctx->line, MAX_STR_SIZE) == -1) memset(&line, 0, sizeof(line)); wclear(ctx->linewin); wmove(self->window, y2 - CURS_Y_OFFSET, 0); wclrtobot(self->window); bool close_win = false; if (!string_is_empty(line)) add_line_to_hist(ctx->line, ctx->len, ctx->ln_history, &ctx->hst_tot, &ctx->hst_pos); if (line[0] == '/') { if (close_win = !strcmp(line, "/close")) { int f_num = self->num; delwin(ctx->linewin); delwin(statusbar->topline); del_window(self); disable_chatwin(f_num); } else if (strncmp(line, "/me ", strlen("/me ")) == 0) send_action(self, ctx, m, line + strlen("/me ")); else execute(ctx->history, self, m, line, CHAT_COMMAND_MODE); } else if (!string_is_empty(line)) { uint8_t selfname[TOX_MAX_NAME_LENGTH]; tox_get_self_name(m, selfname, TOX_MAX_NAME_LENGTH); print_time(ctx->history); wattron(ctx->history, COLOR_PAIR(GREEN)); wprintw(ctx->history, "%s: ", selfname); wattroff(ctx->history, COLOR_PAIR(GREEN)); if (line[0] == '>') { wattron(ctx->history, COLOR_PAIR(GREEN)); wprintw(ctx->history, "%s\n", line); wattroff(ctx->history, COLOR_PAIR(GREEN)); } else wprintw(ctx->history, "%s\n", line); if (!statusbar->is_online || tox_send_message(m, self->num, line, strlen(line) + 1) == 0) { wattron(ctx->history, COLOR_PAIR(RED)); wprintw(ctx->history, " * Failed to send message.\n"); wattroff(ctx->history, COLOR_PAIR(RED)); } } if (close_win) { free(ctx); free(statusbar); } else { reset_buf(ctx->line, &ctx->pos, &ctx->len); } } }
void makemsg(char *fname) { int cnt; wchar_t ch; struct tm *lt; struct passwd *pw; struct stat sbuf; time_t now; FILE *fp; int fd; char hostname[MAXHOSTNAMELEN], tmpname[64]; wchar_t *p, *tmp, lbuf[256], codebuf[13]; const char *tty; const char *whom; gid_t egid; (void)snprintf(tmpname, sizeof(tmpname), "%s/wall.XXXXXX", _PATH_TMP); if ((fd = mkstemp(tmpname)) == -1 || !(fp = fdopen(fd, "r+"))) err(1, "can't open temporary file"); (void)unlink(tmpname); if (!nobanner) { tty = ttyname(STDERR_FILENO); if (tty == NULL) tty = "no tty"; if (!(whom = getlogin())) whom = (pw = getpwuid(getuid())) ? pw->pw_name : "???"; (void)gethostname(hostname, sizeof(hostname)); (void)time(&now); lt = localtime(&now); /* * all this stuff is to blank out a square for the message; * we wrap message lines at column 79, not 80, because some * terminals wrap after 79, some do not, and we can't tell. * Which means that we may leave a non-blank character * in column 80, but that can't be helped. */ (void)fwprintf(fp, L"\r%79s\r\n", " "); (void)swprintf(lbuf, sizeof(lbuf)/sizeof(wchar_t), L"Broadcast Message from %s@%s", whom, hostname); (void)fwprintf(fp, L"%-79.79S\007\007\r\n", lbuf); (void)swprintf(lbuf, sizeof(lbuf)/sizeof(wchar_t), L" (%s) at %d:%02d %s...", tty, lt->tm_hour, lt->tm_min, lt->tm_zone); (void)fwprintf(fp, L"%-79.79S\r\n", lbuf); } (void)fwprintf(fp, L"%79s\r\n", " "); if (fname) { egid = getegid(); setegid(getgid()); if (freopen(fname, "r", stdin) == NULL) err(1, "can't read %s", fname); if (setegid(egid) != 0) err(1, "setegid failed"); } cnt = 0; while (fgetws(lbuf, sizeof(lbuf)/sizeof(wchar_t), stdin)) { for (p = lbuf; (ch = *p) != L'\0'; ++p, ++cnt) { if (ch == L'\r') { putwc(L'\r', fp); cnt = 0; continue; } else if (ch == L'\n') { for (; cnt < 79; ++cnt) putwc(L' ', fp); putwc(L'\r', fp); putwc(L'\n', fp); break; } if (cnt == 79) { putwc(L'\r', fp); putwc(L'\n', fp); cnt = 0; } if (iswprint(ch) || iswspace(ch) || ch == L'\a' || ch == L'\b') { putwc(ch, fp); } else { (void)swprintf(codebuf, sizeof(codebuf)/sizeof(wchar_t), L"<0x%X>", ch); for (tmp = codebuf; *tmp != L'\0'; ++tmp) { putwc(*tmp, fp); if (++cnt == 79) { putwc(L'\r', fp); putwc(L'\n', fp); cnt = 0; } } --cnt; } } } (void)fwprintf(fp, L"%79s\r\n", " "); rewind(fp); if (fstat(fd, &sbuf)) err(1, "can't stat temporary file"); mbufsize = sbuf.st_size; if (!(mbuf = malloc((u_int)mbufsize))) err(1, "out of memory"); if ((int)fread(mbuf, sizeof(*mbuf), mbufsize, fp) != mbufsize) err(1, "can't read temporary file"); (void)close(fd); }
/* * string_name(p) returns the pname of extern p */ static char * string_name(at *p) { char *s = ((struct string *) (p->Object))->start; char *name = string_buffer; #if HAVE_MBRTOWC int n = strlen(s); mbstate_t ps; memset(&ps, 0, sizeof(mbstate_t)); *name++ = '\"'; for(;;) { char *ind; int c = *(unsigned char*)s; wchar_t wc = 0; int m; if (name>=string_buffer+STRING_BUFFER-10) break; if (c == 0) break; if ((ind = strchr(special_string, c))) { *name++ = '\\'; *name++ = aspect_string[ind - special_string]; s += 1; continue; } m = (int)mbrtowc(&wc, s, n, &ps); if (m <= 0) { *name++ = '\\'; *name++ = 'x'; *name++ = digit_string[(c >> 4) & 15]; *name++ = digit_string[c & 15]; memset(&ps, 0, sizeof(mbstate_t)); s += 1; continue; } if (iswprint(wc)) { memcpy(name, s, m); name += m; } else if (m==1 && c<=' ') { *name++ = '\\'; *name++ = '^'; *name++ = (char)(c | 0x40); } else { int i; for (i=0; i<m; i++) if (name < string_buffer+STRING_BUFFER-10) { c = *(unsigned char*)(s+i); *name++ = '\\'; *name++ = 'x'; *name++ = digit_string[(c >> 4) & 15]; *name++ = digit_string[c & 15]; } }
const char *file_getbuffer(RMagic *ms) { char *pbuf, *op, *np; size_t psize, len; if (ms->haderr) return NULL; if (ms->flags & R_MAGIC_RAW) return ms->o.buf; if (ms->o.buf == NULL) { eprintf ("ms->o.buf = NULL\n"); return NULL; } /* * 4 is for octal representation, + 1 is for NUL */ len = strlen (ms->o.buf); if (len > (SIZE_MAX - 1) / 4) { file_oomem (ms, len); return NULL; } psize = len * 4 + 1; if ((pbuf = realloc (ms->o.pbuf, psize)) == NULL) { file_oomem (ms, psize); return NULL; } ms->o.pbuf = pbuf; #if 1 //defined(HAVE_WCHAR_H) && defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH) { mbstate_t state; wchar_t nextchar; int mb_conv = 1; size_t bytesconsumed; char *eop; (void)memset(&state, 0, sizeof(mbstate_t)); np = ms->o.pbuf; op = ms->o.buf; eop = op + len; while (op < eop) { bytesconsumed = mbrtowc(&nextchar, op, (size_t)(eop - op), &state); if (bytesconsumed == (size_t)(-1) || bytesconsumed == (size_t)(-2)) { mb_conv = 0; break; } if (iswprint(nextchar)) { (void)memcpy(np, op, bytesconsumed); op += bytesconsumed; np += bytesconsumed; } else { while (bytesconsumed-- > 0) OCTALIFY(np, op); } } *np = '\0'; /* Parsing succeeded as a multi-byte sequence */ if (mb_conv != 0) return ms->o.pbuf; } #endif for (np = ms->o.pbuf, op = ms->o.buf; *op; op++) { if (isprint ((ut8)*op)) { *np++ = *op; } else { OCTALIFY (np, op); } } *np = '\0'; return ms->o.pbuf; }
static NCURSES_INLINE int wadd_wch_nosync(WINDOW *win, cchar_t ch) /* the workhorse function -- add a character to the given window */ { NCURSES_SIZE_T x, y; wchar_t *s; int tabsize = 8; #if USE_REENTRANT SCREEN *sp = _nc_screen_of(win); #endif /* * If we are using the alternate character set, forget about locale. * Otherwise, if the locale * claims the code is printable, treat it that * way. */ if ((AttrOf(ch) & A_ALTCHARSET) || iswprint(CharOf(ch))) return wadd_wch_literal(win, ch); /* * Handle carriage control and other codes that are not printable, or are * known to expand to more than one character according to unctrl(). */ x = win->_curx; y = win->_cury; switch (CharOf(ch)) { case '\t': #if USE_REENTRANT tabsize = *ptrTabsize(sp); #else tabsize = TABSIZE; #endif x += (tabsize - (x % tabsize)); /* * Space-fill the tab on the bottom line so that we'll get the * "correct" cursor position. */ if ((!win->_scroll && (y == win->_regbottom)) || (x <= win->_maxx)) { cchar_t blank = blankchar; AddAttr(blank, AttrOf(ch)); while (win->_curx < x) { if (wadd_wch_literal(win, blank) == ERR) return (ERR); } break; } else { wclrtoeol(win); win->_flags |= _WRAPPED; if (newline_forces_scroll(win, &y)) { x = win->_maxx; if (win->_scroll) { scroll(win); x = 0; } } else { x = 0; } } break; case '\n': wclrtoeol(win); if (newline_forces_scroll(win, &y)) { if (win->_scroll) scroll(win); else return (ERR); } /* FALLTHRU */ case '\r': x = 0; win->_flags &= ~_WRAPPED; break; case '\b': if (x == 0) return (OK); x--; win->_flags &= ~_WRAPPED; break; default: if ((s = wunctrl(&ch)) != 0) { while (*s) { cchar_t sch; SetChar(sch, *s++, AttrOf(ch)); if_EXT_COLORS(SetPair(sch, GetPair(ch))); if (wadd_wch_literal(win, sch) == ERR) return ERR; } return OK; } return ERR; } win->_curx = x; win->_cury = y; return OK; }
bool CharacterFunctions::isPrintable (const juce_wchar character) noexcept { return iswprint ((wint_t) character) != 0; }
int CShellCommandValue::Execute(CConsole &rConsole, CArgumentParser& rArguments) { rArguments.ResetArgumentIteration(); TCHAR *pchCommandItself = rArguments.GetNextArgument(); TCHAR *pchParameter; TCHAR *pchValueFull = NULL; BOOL blnUnicodeDump = FALSE; BOOL blnBadParameter = FALSE; BOOL blnHelp = FALSE; LONG nError; DWORD dwValueSize; DWORD dwType = REG_NONE; BYTE *pDataBuffer = NULL; TCHAR *pchFilename = NULL; if ((_tcsnicmp(pchCommandItself,VALUE_CMD _T(".."),VALUE_CMD_LENGTH+2*sizeof(TCHAR)) == 0)|| (_tcsnicmp(pchCommandItself,VALUE_CMD _T("\\"),VALUE_CMD_LENGTH+1*sizeof(TCHAR)) == 0)) { pchValueFull = pchCommandItself + VALUE_CMD_LENGTH; } else if (_tcsnicmp(pchCommandItself,VALUE_CMD _T("/"),VALUE_CMD_LENGTH+1*sizeof(TCHAR)) == 0) { pchParameter = pchCommandItself + VALUE_CMD_LENGTH; goto CheckValueArgument; } while((pchParameter = rArguments.GetNextArgument()) != NULL) { CheckValueArgument: blnBadParameter = FALSE; if ((_tcsicmp(pchParameter,_T("/?")) == 0) ||(_tcsicmp(pchParameter,_T("-?")) == 0)) { blnHelp = TRUE; break; } else if (_tcsicmp(pchParameter,_T("/u")) == 0) { blnUnicodeDump = TRUE; } else if ((*pchParameter == _T('/'))&&(*(pchParameter+1) == _T('f'))) { pchFilename = pchParameter+2; } else if (!pchValueFull) { pchValueFull = pchParameter; } else { blnBadParameter = TRUE; } if (blnBadParameter) { rConsole.Write(_T("Bad parameter: ")); rConsole.Write(pchParameter); rConsole.Write(_T("\n")); } } CRegistryKey Key; TCHAR *pchValueName; const TCHAR *pszEmpty = _T(""); const TCHAR *pszPath; if (blnHelp) { rConsole.Write(GetHelpString()); if (pDataBuffer) delete pDataBuffer; return 0; } if (pchValueFull) { if (_tcscmp(pchValueFull,_T("\\")) == 0) goto ValueCommandNAonRoot; TCHAR *pchSep = _tcsrchr(pchValueFull,_T('\\')); pchValueName = pchSep?(pchSep+1):(pchValueFull); pszPath = pchSep?pchValueFull:_T("."); //if (_tcsrchr(pchValueName,_T('.'))) //{ // pchValueName = _T(""); // pchPath = pchValueFull; //} //else if (pchSep) *pchSep = 0; } else { pchValueName = (TCHAR*)pszEmpty; pszPath = _T("."); } if (!m_rTree.GetKey(pszPath,KEY_READ,Key)) { rConsole.Write(m_rTree.GetLastErrorDescription()); goto SkipValueCommand; } if (Key.IsRoot()) goto ValueCommandNAonRoot; { rConsole.Write(_T("Value name : \"")); rConsole.Write(_T("\\")); rConsole.Write(Key.GetKeyName()); size_t l = _tcslen(pchValueName); if (l&& (*pchValueName == _T('\"'))&& (pchValueName[l-1] == _T('\"'))) { pchValueName[l-1] = 0; pchValueName++; } rConsole.Write(pchValueName); rConsole.Write(_T("\"\n")); nError = Key.GetValue(pchValueName,NULL,NULL,&dwValueSize); if (nError == ERROR_SUCCESS) { pDataBuffer = new BYTE [dwValueSize]; Key.GetValue(pchValueName,&dwType,pDataBuffer,&dwValueSize); rConsole.Write(_T("Value type : ")); rConsole.Write(CRegistryKey::GetValueTypeName(dwType)); rConsole.Write(_T("\nValue data : ")); switch(dwType) { case REG_DWORD_LITTLE_ENDIAN: { TCHAR Buffer[3]; rConsole.Write(_T("0x")); for (unsigned int i = 0 ; i < dwValueSize ; i++) { _stprintf(Buffer,_T("%02X"),*(pDataBuffer+((dwValueSize-1)-i))); rConsole.Write(Buffer); } } rConsole.Write(_T("\n")); break; case REG_DWORD_BIG_ENDIAN: { TCHAR Buffer[3]; rConsole.Write(_T("0x")); for (unsigned int i = 0 ; i < dwValueSize ; i++) { _stprintf(Buffer,_T("%02X"),*(pDataBuffer+i)); rConsole.Write(Buffer); } } rConsole.Write(_T("\n")); break; case REG_LINK: break; case REG_MULTI_SZ: { TCHAR *pchCurrentString = (TCHAR *)pDataBuffer; rConsole.Write(_T("\n")); while(*pchCurrentString) { rConsole.Write(_T("\"")); rConsole.Write(pchCurrentString); rConsole.Write(_T("\"\n")); pchCurrentString += _tcslen(pchCurrentString)+1; } } break; case REG_RESOURCE_LIST: break; case REG_SZ: case REG_EXPAND_SZ: rConsole.Write(_T("\"")); rConsole.Write((TCHAR *)pDataBuffer); rConsole.Write(_T("\"\n")); break; case REG_BINARY: default: { TCHAR Buffer[256]; DWORD i, j; for (i = 0 ; i < dwValueSize ; i++) { if (i%16 == 0) { // ok this is begining of line rConsole.Write(_T("\n")); // print offset _stprintf(Buffer,_T("0x%08X "),(unsigned int)i); rConsole.Write(Buffer); } else if (i%8 == 0) { // this is the additional space between 7th and 8th byte in current line rConsole.Write(_T(" ")); } // print current byte unsigned int n = *(pDataBuffer+i); _stprintf(Buffer,_T("%02X "),n); rConsole.Write(Buffer); if (i && (i%16 == 15)) { // if this is the last byte in line // Dump text representation for (j = i-15; j <= i; j += blnUnicodeDump?2:1)\ { if ((j%8 == 0)&&(j%16 != 0)) { // this is the additional space between 7th and 8th byte in current line rConsole.Write(_T(" ")); } ASSERT(i-j < 16); // write current char representation if (blnUnicodeDump) { ASSERT(j%2 == 0); wchar_t ch = *(TCHAR *)(pDataBuffer+j); _stprintf(Buffer, #ifdef _UNICODE _T("%c"), #else // g++ may print warnings here (warning: __wchar_t format, different type arg (arg 3)) // %C in format string is a Microsoft extension. _T("%C"), #endif iswprint(ch)?ch:L'.'); } else { unsigned char ch = *(pDataBuffer+j); _stprintf(Buffer, #ifdef _UNICODE // g++ may print warnings here (warning: __wchar_t format, different type arg (arg 3)) // %C in format string is a Microsoft extension. _T("%C"), #else _T("%c"), #endif isprint(ch)?ch:'.'); } rConsole.Write(Buffer); } // for } // if } // for // print text representation of last line if it is not full (it have less than 16 bytes) // k is pseudo offset for (DWORD k = i; k%16 != 0; k++) { if (k%8 == 0) { // this is the additional space between 7th and 8th byte in current line rConsole.Write(_T(" ")); } _tcscpy(Buffer,_T(" ")); // the replacement of two digit of current byte + spacing rConsole.Write(Buffer); if (k && (k%16 == 15)) { // if this is the last byte in line ASSERT((k-15)%16 == 0); // k-15 must point at begin of last line for (j = k-15; j < i; j += blnUnicodeDump?2:1) { if (blnUnicodeDump&&(j+1 >= i)) { // ok, buffer size is odd number, so we don't display last byte. ASSERT(j+1 == i); break; } if ((j%8 == 0)&&(j%16 != 0)) { // this is the additional space between 7th and 8th byte in current line rConsole.Write(_T(" ")); } // write current char representation if (blnUnicodeDump) { ASSERT(j%2 == 0); wchar_t ch = *(TCHAR *)(pDataBuffer+j); _stprintf(Buffer, #ifdef _UNICODE _T("%c"), #else // g++ may print warnings here (warning: __wchar_t format, different type arg (arg 3)) // %C in format string is a Microsoft extension. _T("%C"), #endif iswprint(ch)?ch:L'.'); } else { unsigned char ch = *(pDataBuffer+j); _stprintf(Buffer, #ifdef _UNICODE // g++ may print warnings here (warning: __wchar_t format, different type arg (arg 3)) // %C in format string is a Microsoft extension. _T("%C"), #else _T("%c"), #endif isprint(ch)?ch:'.'); } rConsole.Write(Buffer); } // for } // if } // for } // default: rConsole.Write(_T("\n")); } // switch rConsole.Write(_T("\n")); if (pchFilename) { rConsole.Write(_T("Exporting value data to ")); rConsole.Write(pchFilename); rConsole.Write(_T(" ...\n")); HANDLE hFile = CreateFile(pchFilename,GENERIC_WRITE,0,NULL,CREATE_NEW,FILE_ATTRIBUTE_NORMAL,NULL); if (hFile == INVALID_HANDLE_VALUE) { rConsole.Write(_T("Cannot create new file ")); rConsole.Write(pchFilename); rConsole.Write(_T("\n")); goto SkipValueCommand; } DWORD dwBytesWritten; if (!WriteFile(hFile,pDataBuffer,dwValueSize,&dwBytesWritten,NULL)) { rConsole.Write(_T("Error writting file.\n")); VERIFY(CloseHandle(hFile)); goto SkipValueCommand; } ASSERT(dwBytesWritten == dwValueSize); VERIFY(CloseHandle(hFile)); } } else { rConsole.Write(_T("Error ")); TCHAR Buffer[256]; rConsole.Write(_itoa(nError,Buffer,10)); rConsole.Write(_T("\n")); if (nError == ERROR_FILE_NOT_FOUND) { rConsole.Write(_T("(System cannot find the value specified)\n")); } } } SkipValueCommand: if (pDataBuffer) delete[] pDataBuffer; return 0; ValueCommandNAonRoot: rConsole.Write(VALUE_CMD COMMAND_NA_ON_ROOT); return 0; }
void conv_c(rtems_shell_hexdump_globals* globals, PR *pr, u_char *p, size_t bufsize) { char buf[10]; char const *str; wchar_t wc; size_t clen, oclen; int converr, pad, width; char peekbuf[MB_LEN_MAX]; if (pr->mbleft > 0) { str = "**"; pr->mbleft--; goto strpr; } switch(*p) { case '\0': str = "\\0"; goto strpr; /* case '\a': */ case '\007': str = "\\a"; goto strpr; case '\b': str = "\\b"; goto strpr; case '\f': str = "\\f"; goto strpr; case '\n': str = "\\n"; goto strpr; case '\r': str = "\\r"; goto strpr; case '\t': str = "\\t"; goto strpr; case '\v': str = "\\v"; goto strpr; default: break; } /* * Multibyte characters are disabled for hexdump(1) for backwards * compatibility and consistency (none of its other output formats * recognize them correctly). */ converr = 0; if (odmode && MB_CUR_MAX > 1) { oclen = 0; retry: clen = mbrtowc(&wc, (char*)p, bufsize, &pr->mbstate); if (clen == 0) clen = 1; else if (clen == (size_t)-1 || (clen == (size_t)-2 && buf == peekbuf)) { memset(&pr->mbstate, 0, sizeof(pr->mbstate)); wc = *p; clen = 1; converr = 1; } else if (clen == (size_t)-2) { /* * Incomplete character; peek ahead and see if we * can complete it. */ oclen = bufsize; bufsize = peek(globals, p = (u_char*)peekbuf, MB_CUR_MAX); goto retry; } clen += oclen; } else { wc = *p; clen = 1; } if (!converr && iswprint(wc)) { if (!odmode) { *pr->cchar = 'c'; (void)printf(pr->fmt, (int)wc); } else { *pr->cchar = 'C'; assert(strcmp(pr->fmt, "%3C") == 0); width = wcwidth(wc); assert(width >= 0); pad = 3 - width; if (pad < 0) pad = 0; #if defined(__rtems__) { wchar_t wc_tmp[2] = {0,0}; wc_tmp[0] = wc; (void)printf("%*s%lc", pad, "", wc_tmp); } #else (void)printf("%*s%lc", pad, "", wc); #endif pr->mbleft = clen - 1; } } else { (void)sprintf(buf, "%03o", (int)*p); str = buf; strpr: *pr->cchar = 's'; (void)printf(pr->fmt, str); } }
int mem_callback(CPUState *env, target_ulong pc, target_ulong addr, target_ulong size, void *buf, bool is_write) { string_pos &sp = is_write ? write_text_tracker[pc] : read_text_tracker[pc]; ustring_pos &usp = is_write ? write_utext_tracker[pc] : read_utext_tracker[pc]; // ASCII for (unsigned int i = 0; i < size; i++) { uint8_t val = ((uint8_t *)buf)[i]; if (isprint(val)) { sp.ch[sp.nch++] = val; // If we max out the string, chop it if (sp.nch == MAX_STRLEN - 1) { gzprintf(mem_report, "%.*s\n", sp.nch, sp.ch); sp.nch = 0; } } else { // Don't bother with strings shorter than min if (sp.nch >= min_strlen) { gzprintf(mem_report, "%.*s\n", sp.nch, sp.ch); } sp.nch = 0; } } // Don't consider one-byte reads/writes for UTF-16 if (size < 2) { return 1; } // UTF-16-LE for (unsigned int i = 0; i < size; i+=2) { uint8_t vall = ((uint8_t *)buf)[i]; uint8_t valh = ((uint8_t *)buf)[i+1]; uint16_t val = (valh << 8) | vall; if (iswprint(val)) { usp.ch[usp.nch++] = val; // If we max out the string, chop it if (usp.nch == MAX_STRLEN - 1) { gsize bytes_written = 0; gchar *out_str = g_convert((gchar *)usp.ch, usp.nch*2, "UTF-8", "UTF-16LE", NULL, &bytes_written, NULL); gzprintf(mem_report, "%s\n", out_str); g_free(out_str); usp.nch = 0; } } else { // Don't bother with strings shorter than min if (usp.nch >= min_strlen) { gsize bytes_written = 0; gchar *out_str = g_convert((gchar *)usp.ch, usp.nch*2, "UTF-8", "UTF-16LE", NULL, &bytes_written, NULL); gzprintf(mem_report, "%s\n", out_str); g_free(out_str); } usp.nch = 0; } } return 1; }
int __iswpunct_ascii(wint_t c) { return iswprint (c) && !iswalnum(c) && !iswspace(c); }
int ni_file_write_safe(FILE *fp, const ni_buffer_t *wbuf) { const unsigned char *string = ni_buffer_head(wbuf); unsigned int left = ni_buffer_count(wbuf); mbstate_t mbstate; size_t written = 0; ni_bool_t saw_newline = TRUE; if (left == 0) return 0; memset(&mbstate, 0, sizeof(mbstate)); while (left != 0) { unsigned int nbytes; wchar_t wc; /* Scan until we hit the first non-printable character. * Assume the test node uses the same locale as we do */ for (nbytes = 0; nbytes < left; ) { ssize_t n; saw_newline = FALSE; n = mbrtowc(&wc, (char *) string + nbytes, left - nbytes, &mbstate); if (n < 0) { /* We hit a bad path of string. * If this is preceded by one or more printable * chars, write those out first, then come back here. */ if (nbytes != 0) break; /* write one byte, and try to re-sync */ wc = ((unsigned char *) string)[nbytes++]; if (__ni_file_write_wchar_escaped(fp, wc) < 0) return -1; memset(&mbstate, 0, sizeof(mbstate)); goto consumed_some; } if (!iswprint(wc) && !iswspace(wc)) { /* If this is preceded by one or more printable * chars, write those out first */ if (nbytes != 0) break; if (__ni_file_write_wchar_escaped(fp, wc) < 0) return -1; nbytes += n; goto consumed_some; } if (wc == '\n') saw_newline = TRUE; nbytes += n; } ni_assert(nbytes); if (__ni_file_write_partial(fp, string, nbytes) < 0) return -1; consumed_some: string += nbytes; left -= nbytes; } /* Make sure we're writing a newline at the end of our output */ if (!saw_newline) fputc('\n', fp); fflush(fp); return written; }
static void prompt_onKey(ToxWindow *self, Tox *m, wint_t key) { ChatContext *ctx = self->chatwin; int x, y, y2, x2; getyx(ctx->history, y, x); getmaxyx(ctx->history, y2, x2); /* this is buggy */ //if (key == T_KEY_ESC) { /* ESC key: Toggle history scroll mode */ // bool scroll = ctx->hst->scroll_mode ? false : true; // line_info_toggle_scroll(self, scroll); //} /* If we're in scroll mode ignore rest of function */ if (ctx->hst->scroll_mode) { line_info_onKey(self, key); return; } /* BACKSPACE key: Remove one character from line */ if (key == 0x107 || key == 0x8 || key == 0x7f) { if (ctx->pos > 0) { del_char_buf_bck(ctx->line, &ctx->pos, &ctx->len); wmove(ctx->history, y, x-1); /* not necessary but fixes a display glitch */ } else { beep(); } } else if (key == KEY_DC) { /* DEL key: Remove character at pos */ if (ctx->pos != ctx->len) { del_char_buf_frnt(ctx->line, &ctx->pos, &ctx->len); } else { beep(); } } else if (key == T_KEY_DISCARD) { /* CTRL-U: Delete entire line behind pos */ if (ctx->pos > 0) { wmove(ctx->history, ctx->orig_y, X_OFST); wclrtobot(ctx->history); discard_buf(ctx->line, &ctx->pos, &ctx->len); } else { beep(); } } else if (key == T_KEY_KILL) { /* CTRL-K: Delete entire line in front of pos */ if (ctx->len != ctx->pos) kill_buf(ctx->line, &ctx->pos, &ctx->len); else beep(); } else if (key == KEY_HOME || key == T_KEY_C_A) { /* HOME/C-a key: Move cursor to start of line */ if (ctx->pos != 0) ctx->pos = 0; } else if (key == KEY_END || key == T_KEY_C_E) { /* END/C-e key: move cursor to end of line */ if (ctx->pos != ctx->len) ctx->pos = ctx->len; } else if (key == KEY_LEFT) { if (ctx->pos > 0) --ctx->pos; else beep(); } else if (key == KEY_RIGHT) { if (ctx->pos < ctx->len) ++ctx->pos; else beep(); } else if (key == KEY_UP) { /* fetches previous item in history */ wmove(ctx->history, ctx->orig_y, X_OFST); fetch_hist_item(ctx->line, &ctx->pos, &ctx->len, ctx->ln_history, ctx->hst_tot, &ctx->hst_pos, MOVE_UP); /* adjust line y origin appropriately when window scrolls down */ if (ctx->at_bottom && ctx->len >= x2 - X_OFST) { int px2 = ctx->len >= x2 ? x2 : x2 - X_OFST; int p_ofst = px2 != x2 ? 0 : X_OFST; if (px2 <= 0) return; int k = ctx->orig_y + ((ctx->len + p_ofst) / px2); if (k >= y2) { --ctx->orig_y; } } } else if (key == KEY_DOWN) { /* fetches next item in history */ wmove(ctx->history, ctx->orig_y, X_OFST); fetch_hist_item(ctx->line, &ctx->pos, &ctx->len, ctx->ln_history, ctx->hst_tot, &ctx->hst_pos, MOVE_DOWN); } else if (key == '\t') { /* TAB key: completes command */ if (ctx->len > 1 && ctx->line[0] == '/') { if (complete_line(ctx->line, &ctx->pos, &ctx->len, glob_cmd_list, AC_NUM_GLOB_COMMANDS, MAX_CMDNAME_SIZE) == -1) beep(); } else { beep(); } } else #if HAVE_WIDECHAR if (iswprint(key)) #else if (isprint(key)) #endif { if (ctx->len < (MAX_STR_SIZE-1)) { add_char_to_buf(ctx->line, &ctx->pos, &ctx->len, key); } } /* RETURN key: execute command */ else if (key == '\n') { wprintw(ctx->history, "\n"); uint8_t line[MAX_STR_SIZE] = {0}; if (wcs_to_mbs_buf(line, ctx->line, MAX_STR_SIZE) == -1) memset(&line, 0, sizeof(line)); if (!string_is_empty(line)) add_line_to_hist(ctx->line, ctx->len, ctx->ln_history, &ctx->hst_tot, &ctx->hst_pos); line_info_add(self, NULL, NULL, NULL, line, PROMPT, 0, 0); execute(ctx->history, self, m, line, GLOBAL_COMMAND_MODE); reset_buf(ctx->line, &ctx->pos, &ctx->len); } }
/* * Display a symbol on somebody's window, processing some control * characters while we are at it. */ void display(xwin_t *win, wchar_t *wc) { /* * Alas, can't use variables in C switch statement. * Workaround these 3 cases with goto. */ if (*wc == win->kill) goto kill; else if (*wc == win->cerase) goto cerase; else if (*wc == win->werase) goto werase; switch (*wc) { case L'\n': case L'\r': wadd_wch(win->x_win, makecchar(L'\n')); getyx(win->x_win, win->x_line, win->x_col); wrefresh(win->x_win); return; case 004: if (win == &my_win) { /* Ctrl-D clears the screen. */ werase(my_win.x_win); getyx(my_win.x_win, my_win.x_line, my_win.x_col); wrefresh(my_win.x_win); werase(his_win.x_win); getyx(his_win.x_win, his_win.x_line, his_win.x_col); wrefresh(his_win.x_win); } return; /* Erase character. */ case 010: /* BS */ case 0177: /* DEL */ cerase: wmove(win->x_win, win->x_line, max(--win->x_col, 0)); getyx(win->x_win, win->x_line, win->x_col); waddch(win->x_win, ' '); wmove(win->x_win, win->x_line, win->x_col); getyx(win->x_win, win->x_line, win->x_col); wrefresh(win->x_win); return; case 027: /* ^W */ werase: { /* * On word erase search backwards until we find * the beginning of a word or the beginning of * the line. */ int endcol, xcol, c; endcol = win->x_col; xcol = endcol - 1; while (xcol >= 0) { c = readwin(win->x_win, win->x_line, xcol); if (c != ' ') break; xcol--; } while (xcol >= 0) { c = readwin(win->x_win, win->x_line, xcol); if (c == ' ') break; xcol--; } wmove(win->x_win, win->x_line, xcol + 1); for (int i = xcol + 1; i < endcol; i++) waddch(win->x_win, ' '); wmove(win->x_win, win->x_line, xcol + 1); getyx(win->x_win, win->x_line, win->x_col); wrefresh(win->x_win); return; } case 025: /* ^U */ kill: wmove(win->x_win, win->x_line, 0); wclrtoeol(win->x_win); getyx(win->x_win, win->x_line, win->x_col); wrefresh(win->x_win); return; case L'\f': if (win == &my_win) wrefresh(curscr); return; case L'\7': write(STDOUT_FILENO, wc, sizeof(*wc)); return; } if (iswprint(*wc) || *wc == L'\t') wadd_wch(win->x_win, makecchar(*wc)); else beep(); getyx(win->x_win, win->x_line, win->x_col); wrefresh(win->x_win); }
/* * Print info about the process. */ static int prcom(int found, psinfo_t *psinfo, char *psargs) { char *cp; char *tp; char *psa; long tm; int i, wcnt, length; wchar_t wchar; struct tty *ttyp; /* * If process is zombie, call print routine and return. */ if (psinfo->pr_nlwp == 0) { if (tflg && !found) return (0); else { przom(psinfo); return (1); } } /* * Get current terminal. If none ("?") and 'a' is set, don't print * info. If 't' is set, check if term is in list of desired terminals * and print it if it is. */ i = 0; tp = gettty(psinfo); if (*tp == '?' && !found && !xflg) return (0); if (!(*tp == '?' && aflg) && tflg && !found) { int match = 0; char *other = NULL; for (ttyp = tty; ttyp->tname != NULL; ttyp++) { /* * Look for a name match */ if (strcmp(tp, ttyp->tname) == 0) { match = 1; break; } /* * Look for same device under different names. */ if ((other == NULL) && (psinfo->pr_ttydev == ttyp->tdev)) other = ttyp->tname; } if (!match) { if (other == NULL) return (0); tp = other; } } if (lflg) (void) printf("%2x", psinfo->pr_flag & 0377); if (uflg) { if (!nflg) { struct passwd *pwd; if ((pwd = getpwuid(psinfo->pr_euid)) != NULL) /* USER */ (void) printf("%-8.8s", pwd->pw_name); else /* UID */ (void) printf(" %7.7d", (int)psinfo->pr_euid); } else { (void) printf(" %5d", (int)psinfo->pr_euid); /* UID */ } } else if (lflg) (void) printf(" %5d", (int)psinfo->pr_euid); /* UID */ (void) printf("%*d", pidwidth + 1, (int)psinfo->pr_pid); /* PID */ if (lflg) (void) printf("%*d", pidwidth + 1, (int)psinfo->pr_ppid); /* PPID */ if (lflg) (void) printf("%3d", psinfo->pr_lwp.pr_cpu & 0377); /* CP */ if (uflg) { prtpct(psinfo->pr_pctcpu); /* %CPU */ prtpct(psinfo->pr_pctmem); /* %MEM */ } if (lflg) { (void) printf("%4d", psinfo->pr_lwp.pr_pri); /* PRI */ (void) printf("%3d", psinfo->pr_lwp.pr_nice); /* NICE */ } if (lflg || uflg) { if (psinfo->pr_flag & SSYS) /* SZ */ (void) printf(" 0"); else if (psinfo->pr_size) (void) printf(" %4lu", (ulong_t)psinfo->pr_size); else (void) printf(" ?"); if (psinfo->pr_flag & SSYS) /* RSS */ (void) printf(" 0"); else if (psinfo->pr_rssize) (void) printf(" %4lu", (ulong_t)psinfo->pr_rssize); else (void) printf(" ?"); } if (lflg) { /* WCHAN */ if (psinfo->pr_lwp.pr_sname != 'S') { (void) printf(" "); } else if (psinfo->pr_lwp.pr_wchan) { (void) printf(" %+8.8lx", (ulong_t)psinfo->pr_lwp.pr_wchan); } else { (void) printf(" ?"); } } if ((tplen = strlen(tp)) > 9) maxlen = twidth - tplen + 9; else maxlen = twidth; if (!lflg) (void) printf(" %-8.14s", tp); /* TTY */ (void) printf(" %c", psinfo->pr_lwp.pr_sname); /* STATE */ if (lflg) (void) printf(" %-8.14s", tp); /* TTY */ if (uflg) prtime(psinfo->pr_start); /* START */ /* time just for process */ tm = psinfo->pr_time.tv_sec; if (Sflg) { /* calculate time for process and all reaped children */ tm += psinfo->pr_ctime.tv_sec; if (psinfo->pr_time.tv_nsec + psinfo->pr_ctime.tv_nsec >= 1000000000) tm += 1; } (void) printf(" %2ld:%.2ld", tm / 60, tm % 60); /* TIME */ if (vflg) { if (psinfo->pr_flag & SSYS) /* SZ */ (void) printf(" 0"); else if (psinfo->pr_size) (void) printf("%5lu", (ulong_t)psinfo->pr_size); else (void) printf(" ?"); if (psinfo->pr_flag & SSYS) /* SZ */ (void) printf(" 0"); else if (psinfo->pr_rssize) (void) printf("%5lu", (ulong_t)psinfo->pr_rssize); else (void) printf(" ?"); prtpct(psinfo->pr_pctcpu); /* %CPU */ prtpct(psinfo->pr_pctmem); /* %MEM */ } if (cflg) { /* CMD */ wcnt = namencnt(psinfo->pr_fname, 16, maxlen); (void) printf(" %.*s", wcnt, psinfo->pr_fname); return (1); } /* * PRARGSZ == length of cmd arg string. */ if (psargs == NULL) { psa = &psinfo->pr_psargs[0]; i = PRARGSZ; tp = &psinfo->pr_psargs[PRARGSZ]; } else { psa = psargs; i = strlen(psargs); tp = psa + i; } for (cp = psa; cp < tp; /* empty */) { if (*cp == 0) break; length = mbtowc(&wchar, cp, MB_LEN_MAX); if (length < 0 || !iswprint(wchar)) { (void) printf(" [ %.16s ]", psinfo->pr_fname); return (1); } cp += length; } wcnt = namencnt(psa, i, maxlen); #if 0 /* dumps core on really long strings */ (void) printf(" %.*s", wcnt, psa); #else (void) putchar(' '); (void) fwrite(psa, 1, wcnt, stdout); #endif return (1); }