int vnode_parsemsg(vnode_msg_t *msg, void *data, const vnode_tlvhandler_t tlvhandler[VNODE_TLV_MAX]) { size_t offset = 0; vnode_tlv_t *tlv; vnode_tlvhandler_t tlvhandlefn; int tmp = -1; while (offset < msg->hdr.datalen) { tlv = (void *)msg->data + offset; offset += sizeof(*tlv) + tlv->vallen; if (tlv->vallen == 0 || offset > msg->hdr.datalen) { WARNX("invalid value length: %u", tlv->vallen); continue; } if ((tlvhandlefn = tlvhandler[tlv->type]) == NULL) { WARNX("unknown tlv type: %u", tlv->type); continue; } if ((tmp = tlvhandlefn(tlv, data))) break; } return tmp; }
int vnode_connect(const char *name) { int fd; struct sockaddr_un addr; #ifdef DEBUG WARNX("opening '%s'", name); #endif if (strlen(name) > sizeof(addr.sun_path) - 1) { WARNX("name too long: '%s'", name); return -1; } if ((fd = socket(AF_UNIX, SOCK_SEQPACKET, 0)) < 0) { WARN("socket() failed"); return -1; } addr.sun_family = AF_UNIX; strcpy(addr.sun_path, name); if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { WARN("connect() failed for '%s'", name); close(fd); return -1; } if (set_nonblock(fd)) WARN("set_nonblock() failed for fd %d", fd); return fd; }
static void vnode_msg_cb(struct ev_loop *loop, ev_io *w, int revents) { vnode_msgio_t *msgio = w->data; ssize_t tmp; vnode_msghandler_t msghandlefn; #ifdef DEBUG WARNX("new message on fd %d", msgio->fd); #endif assert(msgio); tmp = vnode_recvmsg(msgio); if (tmp == 0) return; else if (tmp < 0) { ev_io_stop(loop, w); if (msgio->ioerror) msgio->ioerror(msgio); return; } msghandlefn = msgio->msghandler[msgio->msgbuf.msg->hdr.type]; if (!msghandlefn) { WARNX("no handler found for msg type %u from fd %d", msgio->msgbuf.msg->hdr.type, msgio->fd); return; } msghandlefn(msgio); return; }
int vnode_listen(const char *name) { int fd; struct sockaddr_un addr; #ifdef DEBUG WARNX("opening '%s'", name); #endif if (strlen(name) > sizeof(addr.sun_path) - 1) { WARNX("name too long: '%s'", name); return -1; } if ((fd = socket(AF_UNIX, SOCK_SEQPACKET, 0)) < 0) { WARN("socket() failed"); return -1; } unlink(name); addr.sun_family = AF_UNIX; strcpy(addr.sun_path, name); if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { WARN("bind() failed for '%s'", name); close(fd); return -1; } /* to override umask */ if (chmod(name, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) WARN("fchmod() failed for '%s'", name); if (listen(fd, 5) < 0) { WARN("listen() failed"); close(fd); return -1; } if (set_nonblock(fd)) WARN("set_nonblock() failed for fd %d", fd); return fd; }
bool readFITS(char *filename, IMAGE **fits){ FNAME(); bool ret = TRUE; fitsfile *fp; // float nullval = 0., imBits, bZero = 0., bScale = 1.; int i, j, hdunum, hdutype, nkeys, keypos; int naxis; long naxes[2]; char card[FLEN_CARD]; IMAGE *img = MALLOC(IMAGE, 1); TRYFITS(fits_open_file, &fp, filename, READONLY); FITSFUN(fits_get_num_hdus, fp, &hdunum); if(hdunum < 1){ WARNX(_("Can't read HDU")); ret = FALSE; goto returning; } // get image dimensions TRYFITS(fits_get_img_param, fp, 2, &img->dtype, &naxis, naxes); if(naxis > 2){ WARNX(_("Images with > 2 dimensions are not supported")); ret = FALSE; goto returning; } img->width = naxes[0]; img->height = naxes[1]; DBG("got image %ldx%ld pix, bitpix=%d", naxes[0], naxes[1], img->dtype); // loop through all HDUs for(i = 1; !(fits_movabs_hdu(fp, i, &hdutype, &fitsstatus)); ++i){ TRYFITS(fits_get_hdrpos, fp, &nkeys, &keypos); int oldnkeys = img->keynum; img->keynum += nkeys; if(!(img->keylist = realloc(img->keylist, sizeof(char*) * img->keynum))){ ERR(_("Can't realloc")); } char **currec = &(img->keylist[oldnkeys]); DBG("HDU # %d of %d keys", i, nkeys); for(j = 1; j <= nkeys; ++j){ FITSFUN(fits_read_record, fp, j, card); if(!fitsstatus){ *currec = MALLOC(char, FLEN_CARD); memcpy(*currec, card, FLEN_CARD); DBG("key %d: %s", oldnkeys + j, *currec); ++currec; } } }
void signals(int sig){ if(sig > 0) WARNX(_("Get signal %d, quit.\n"), sig); unlink(PIDFILE); stop_motor(); exit(sig); }
/** * Mmap file to a memory area * * @param filename (i) - name of file to mmap * @return stuct with mmap'ed file or die */ mmapbuf *My_mmap(char *filename){ int fd; char *ptr; size_t Mlen; struct stat statbuf; /// "Не задано имя файла!" if(!filename){ WARNX(_("No filename given!")); return NULL; } if((fd = open(filename, O_RDONLY)) < 0){ /// "Не могу открыть %s для чтения" WARN(_("Can't open %s for reading"), filename); return NULL; } if(fstat (fd, &statbuf) < 0){ /// "Не могу выполнить stat %s" WARN(_("Can't stat %s"), filename); close(fd); return NULL; } Mlen = statbuf.st_size; if((ptr = mmap (0, Mlen, PROT_READ, MAP_PRIVATE, fd, 0)) == MAP_FAILED){ /// "Ошибка mmap" WARN(_("Mmap error for input")); close(fd); return NULL; } /// "Не могу закрыть mmap'нутый файл" if(close(fd)) WARN(_("Can't close mmap'ed file")); mmapbuf *ret = MALLOC(mmapbuf, 1); ret->data = ptr; ret->len = Mlen; return ret; }
// /// Creates a TFont object from the given LOGFONT. // TFont::TFont(const LOGFONT& logFont) { Handle = ::CreateFontIndirect(&logFont); WARNX(OwlGDI, !Handle, 0, "Cannot create TFont from logfont @" << static_cast<const void*>(&logFont)); CheckValid(); RefAdd(Handle, Font); }
// /// Overrides TWindow's virtual PerformCreate function. Creates the interface /// element associated with the MDI frame window. /// // TWindow::TPerformCreateReturnType TMdiFrame::PerformCreate(int arg) { PRECONDITIONX(!(OWL_STRICT && arg), _T("The deprecated argument to PerformCreate is disallowed.")); InUse(arg); PRECONDITION(GetModule()); // // An MDI frame must have a menu. Give it an empty one if none is supplied. // Use RAII to ensure the menu is released in case of failure. // struct TMenuGuard { HMENU m; TMenuGuard(HMENU m_) : m(m_) {} ~TMenuGuard() {if (m) DestroyMenu(m);} operator HMENU() {return m;} HMENU RelinquishOwnership() {HMENU tmp = m; m = 0; return m;} } menu(Attr.Menu ? LoadMenu(Attr.Menu) : CreateMenu()); WARNX(OwlWin, !menu, 0, _T("Unable to load menu: ") << Attr.Menu << _T(" from ") << *GetModule()); THandle h = CreateWindowEx( Attr.ExStyle, GetClassName(), Title, Attr.Style, Attr.X, Attr.Y, Attr.W, Attr.H, Parent ? Parent->GetHandle() : 0, menu, *GetModule(), Attr.Param ); if (h) menu.RelinquishOwnership(); // The menu belongs to the window now. OWL_SET_OR_RETURN_HANDLE(h); }
void vnode_close_clientcmdio(vnode_client_cmdio_t *clientcmdio) { switch (clientcmdio->iotype) { case VCMD_IO_NONE: case VCMD_IO_FD: break; case VCMD_IO_PIPE: close_stdio_pipe(&clientcmdio->stdiopipe); break; case VCMD_IO_PTY: close_stdio_pty(&clientcmdio->stdiopty); break; default: WARNX("unknown i/o type: %u", clientcmdio->iotype); break; } memset(clientcmdio, 0, sizeof(*clientcmdio)); free(clientcmdio); return; }
/** * save all tables of given image into file */ void table_write(IMAGE *img, fitsfile *fp){ FNAME(); if(!img->tables || img->tables->amount == 0) return; size_t N = img->tables->amount, i; for(i = 0; i < N; ++i){ FITStable *tbl = img->tables->tables[i]; size_t c, cols = tbl->ncols; /*int hdutype; TRYFITS(fits_movabs_hdu, fp, ++img->lasthdu, &hdutype); if(fitsstatus){ WARNX(_("Can't write table %s - cannot move to HDU #%d!"), tbl->tabname, img->lasthdu); continue; }*/ char **columns = MALLOC(char*, cols); char **formats = MALLOC(char*, cols); char **units = MALLOC(char*, cols); table_column *col = tbl->columns; for(c = 0; c < cols; ++c, ++col){ columns[c] = col->colname; formats[c] = col->format; units[c] = col->unit; DBG("col: %s, form: %s, unit: %s", columns[c], formats[c], units[c]); } FITSFUN(fits_create_tbl, fp, BINARY_TBL, tbl->nrows, cols, columns, formats, units, tbl->tabname); FREE(columns); FREE(formats); FREE(units); if(fitsstatus){ WARNX(_("Can't write table %s!"), tbl->tabname); continue; } col = tbl->columns; for(c = 0; c < cols; ++c, ++col){ DBG("write column %zd", c); TRYFITS(fits_write_col, fp, col->coltype, c+1, 1, 1, col->repeat, col->contents); if(fitsstatus){ WARNX(_("Can't write column %s!"), col->colname); continue; } } /*int hdutype; TRYFITS(fits_movabs_hdu, fp, ++img->lasthdu, &hdutype); if(fitsstatus){ WARNX(_("Can't write table %s - cannot move to HDU #%d!"), tbl->tabname, img->lasthdu); continue; }*/ } }
// /// Create a view on a given document using the given tempalte, or document's /// template if none given, and then initialize the view. Return the view if /// all was OK, or 0 if something failed. // TView* TDocManager::CreateView(TDocument& doc, TDocTemplate* tpl) { // Default to the document's template if none provided // if (!tpl) tpl = doc.GetTemplate(); CHECK(tpl); TView* view = tpl->ConstructView(doc); WARNX(OwlDocView, !view, 0, _T("CreateView(): ConstructView call failed")); view = doc.InitView(view); WARNX(OwlDocView, !view, 0, _T("CreateView(): InitView call failed")); return view; }
/** * get mirror temperature over network * @return 0 if succeed */ int get_mirT(double *T){ int sockfd = 0; char recvBuff[64]; memset(recvBuff, 0, sizeof(recvBuff)); struct addrinfo h, *r, *p; memset(&h, 0, sizeof(h)); h.ai_family = AF_INET; h.ai_socktype = SOCK_STREAM; h.ai_flags = AI_CANONNAME; char *host = HOST; char *port = PORT; if(getaddrinfo(host, port, &h, &r)) WARNX("getaddrinfo()"); for(p = r; p; p = p->ai_next){ if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { WARN("socket()"); continue; } if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); WARN("connect()"); continue; } break; // if we get here, we must have connected successfully } if(p == NULL){ WARNX("failed to connect"); return 1; } freeaddrinfo(r); if(send(sockfd, RESOURCE, sizeof(RESOURCE), 0) != sizeof(RESOURCE)){ WARN("send()"); return 1; } ssize_t rd = read(sockfd, recvBuff, sizeof(recvBuff)-1); if(rd < 0){ WARN("read()"); return 1; }else recvBuff[rd] = 0; close(sockfd); char *eptr; *T = strtod(recvBuff, &eptr); if(eptr == recvBuff) return 1; return 0; }
// /// Creates a TFont object from the given LOGFONT. /// This overload is deprecated; use the overload for a LOGFONT reference instead. // TFont::TFont(const LOGFONT * logFont) { PRECONDITION(logFont); Handle = ::CreateFontIndirect((LPLOGFONT)logFont); // API typecast WARNX(OwlGDI, !Handle, 0, _T("Cannot create TFont from logfont @") << hex << uint32(LPVOID(logFont))); CheckValid(); RefAdd(Handle, Font); }
// /// Creates a bitmap object for the given application instance from the given /// resource. // TBitmap::TBitmap(HINSTANCE instance, TResId resId) { Handle = ::LoadBitmap(instance, resId); WARNX(OwlGDI, !Handle, 0, "Cannot load bitmap " << resId << " from " << hex << (uint)instance); CheckValid(); RefAdd(Handle, Bitmap); TRACEX(OwlGDI, OWL_CDLEVEL, "TBitmap constructed from resource @" << (void*)this << "."); }
// /// Creates a bitmap object with the values found in the given bitmap structure. // TBitmap::TBitmap(const BITMAP& bitmap) { Handle = ::CreateBitmapIndirect(&bitmap); WARNX(OwlGDI, !Handle, 0, "Cannot create bitmap from BITMAP @" << static_cast<const void*>(&bitmap)); CheckValid(); RefAdd(Handle, Bitmap); TRACEX(OwlGDI, OWL_CDLEVEL, "TBitmap constructed @" << static_cast<void*>(this) << " from BITMAP @" << static_cast<const void*>(&bitmap) << "."); }
// /// Creates a bitmap object from bitCount bits in the bits buffer with the given /// width, height, and planes argument values. // TBitmap::TBitmap(int width, int height, uint8 planes, uint8 bitCount, const void * bits) { Handle = ::CreateBitmap(width, height, planes, bitCount, bits); WARNX(OwlGDI, !Handle, 0, "Cannot create bitmap (" << width << "x" << height << "x" << planes << ")"); CheckValid(); RefAdd(Handle, Bitmap); TRACEX(OwlGDI, OWL_CDLEVEL, "TBitmap constructed @" << (void*)this << " using parameters (" << dec << width << "x" << height << "x" << planes << ")." << hex); }
// /// Creates a bitmap object with the values found in the given bitmap structure. /// This overload is deprecated. Use the overload that takes a reference instead. // TBitmap::TBitmap(const BITMAP * bitmap) { PRECONDITION(bitmap); Handle = ::CreateBitmapIndirect((LPBITMAP)bitmap); // API cast WARNX(OwlGDI, !Handle, 0, "Cannot create bitmap from BITMAP @" << hex << (void*)bitmap); CheckValid(); RefAdd(Handle, Bitmap); TRACEX(OwlGDI, OWL_CDLEVEL, "TBitmap constructed @" << (void*)this << " from BITMAP @" << (void*)bitmap << "."); }
// /// If the document can be closed it is closed. // void TDocManager::FileClose() { TDocument* doc = GetCurrentDoc(); if (doc && doc->CanClose()) { // normally calls back to FlushDoc() if (!doc->Close()) PostDocError(*doc, IDS_UNABLECLOSE); else delete doc; } WARNX(OwlDocView, !doc, 0, _T("FileClose invoked with no current doc")); }
// /// Saves the current data to storage. When a file is closed, the document manager /// calls either Commit or Revert. If force is true, all data is written to storage. /// Commit checks any child documents and commits their changes to storage also. /// Before the current data is saved, all child documents must return true. If all /// child documents return true, Commit flushes the views for operations that /// occurred since the last time the view was checked. After all data for the /// document is updated and saved, Commit returns true. // bool TDocument::Commit(bool force) { TDocument* pdoc = 0; while ((pdoc = ChildDoc.Next(pdoc)) != 0) { if (!pdoc->Commit(force)) return false; } WARNX(OwlDocView, !DocPath, 0, _T("Commit(): 0 DocPath!")); return NotifyViews(vnCommit, force); }
static void vcmd_cmddonecb(int32_t cmdid, pid_t pid, int status, void *data) { vcmd_t *vcmd = data; if (vcmd->cmdio->iotype == VCMD_IO_PTY) { ev_io_stop(vcmd->client->loop, &vcmd->stdin_watcher); ev_io_stop(vcmd->client->loop, &vcmd->ptymaster_watcher); /* drain command output */ for (;;) { char buf[BUFSIZ]; ssize_t rcount, wcount; rcount = read(vcmd->ptymaster_watcher.fd, buf, sizeof(buf)); if (rcount <= 0) break; wcount = write(STDOUT_FILENO, buf, rcount); if (wcount != rcount) WARN("write() error: %d of %d bytes", wcount, rcount); } } vnode_close_clientcmdio(vcmd->cmdio); #ifdef DEBUG WARNX("cmdid %u; pid %d; status: 0x%x", cmdid, pid, status); #endif if (WIFEXITED(status)) /* normal terminataion */ vcmd->cmdstatus = WEXITSTATUS(status); else if (WIFSIGNALED(status)) { if (verbose) INFO("command %u terminated by signal: %d", cmdid, WTERMSIG(status)); vcmd->cmdstatus = 255; } else { INFO("unexpected termination status for command %u: 0x%x", cmdid, status); vcmd->cmdstatus = 255; } vcmd->cmdid = -1; ev_unloop(vcmd->client->loop, EVUNLOOP_ALL); return; }
/** * Safely convert data from string to double * * @param num (o) - double number read from string * @param str (i) - input string * @return 1 if success, 0 if fails */ int str2double(double *num, const char *str){ double res; char *endptr; if(!str) return 0; res = strtod(str, &endptr); if(endptr == str || *str == '\0' || *endptr != '\0'){ /// "Неправильный формат числа double!" WARNX("Wrong double number format!"); return FALSE; } if(num) *num = res; // you may run it like myatod(NULL, str) to test wether str is double number return TRUE; }
static void vcmd_ioerrorcb(vnode_client_t *client) { vcmd_t *vcmd = client->data; WARNX("i/o error"); vnode_delclient(client); vcmd->client = NULL; exit(1); return; }
/** * Try to open log file * if failed show warning message */ void openlogfile(char *name){ if(!name){ WARNX(_("Need filename")); return; } green(_("Try to open log file %s in append mode\n"), name); if(!(Flog = fopen(name, "a"))){ WARN(_("Can't open log file")); return; } log_open_time = time(NULL); logname = name; }
// /// Creates a document view based on the directory path and specified template. The /// parameter flags, one of the document template constants, determines how the /// document template is created. /// /// Create (Construct and Init) a view from registered templates supporting /// a given doc. /// /// This implementation allows user intervention if there is more than one /// template available, by calling SelectViewType() // TView* TDocManager::CreateAnyView(TDocument& doc, long /*flags*/) { int tplCount = GetTemplateCount(&doc); // Abort if there are no usable templates // if (!tplCount) { WARNX(OwlDocView, !tplCount, 0, _T("CreateAnyView(): no usable template")); return 0; } // Allocate memory for templates and get 'em // TDocTemplatePtr* tplList = new TDocTemplatePtr[tplCount]; TAPointer<TDocTemplatePtr> _clnObj(tplList); tplCount = GetViewTemplates(tplList, tplCount, doc); int index; if (tplCount > 1) index = SelectViewType(tplList, tplCount); else index = tplCount; if (index <= 0) { WARNX(OwlDocView, !tplCount, 0, _T("CreateAnyView(): no usable template")); WARNX(OwlDocView, tplCount, 0, _T("CreateAnyView(): invalid template index")); return 0; } CHECK(index > 0); //CHECK(index < tplCount);//????????? CHECK(index <= tplCount); // Now create the view on the document using the selected template // return CreateView(doc, tplList[index-1]); }
static void vcmd_cmdreqcb(struct ev_loop *loop, ev_timer *w, int revents) { vcmd_t *vcmd = w->data; #ifdef DEBUG WARNX("sending command request: serverfd %d; vcmd %p", vcmd->client->serverfd, vcmd); #endif if (vcmd->cmdio->iotype == VCMD_IO_PTY) { /* setup forwarding i/o */ vcmd->stdin_fwdfd = vcmd->cmdio->stdiopty.masterfd; vcmd->stdin_watcher.data = &vcmd->stdin_fwdfd; ev_io_init(&vcmd->stdin_watcher, vcmd_rwcb, STDIN_FILENO, EV_READ); ev_io_start(loop, &vcmd->stdin_watcher); vcmd->ptymaster_fwdfd = STDOUT_FILENO; vcmd->ptymaster_watcher.data = &vcmd->ptymaster_fwdfd; ev_io_init(&vcmd->ptymaster_watcher, vcmd_rwcb, vcmd->cmdio->stdiopty.masterfd, EV_READ); ev_io_start(loop, &vcmd->ptymaster_watcher); } vcmd->cmdid = vnode_client_cmdreq(vcmd->client, vcmd->cmdio, vcmd_cmddonecb, vcmd, vcmd->argc, vcmd->argv); if (vcmd->cmdid < 0) { WARNX("vnode_client_cmdreq() failed"); vnode_delclient(vcmd->client); vcmd->client = NULL; exit(255); } return; }
// /// Constructs a wrapper for the current drag imagelist and specifies the location /// and hotspot of the imagelist. // TImageList::TImageList(TPoint& pt, TPoint& hotspot) { Bitmap = 0; Handle = TCommCtrl::Dll()->ImageList_GetDragImage(&pt, &hotspot); if (Handle) { int x, y; bool r = TCommCtrl::Dll()->ImageList_GetIconSize(Handle, &x, &y); CHECK(r); InUse(r); ImageSize = TSize(x, y); } CheckValid(); WARNX(OwlCommCtrl, !Handle, 0, "Cannot create ImageList"); }
// /// Constructs an empty ImageList of a given size. /// The `imageSize` is the individual image size, not the total size of the list. /// The `initCapacity` parameter describes the initial capacity of the list, i.e. /// how many images it can hold before it needs to grow (perform a reallocation). /// Note that the list remains empty after construction, regardless of capacity. /// The `growBy` parameter specifies how much the capacity will grow when needed. // TImageList::TImageList(const TSize& imageSize, uint flags, int initCapacity, int growBy) { if (!TCommCtrl::IsAvailable()) TXCommCtrl::Raise(); if (!initCapacity) initCapacity = 1; ImageSize = TSize(imageSize.cx, imageSize.cy); Bitmap = 0; Handle = TCommCtrl::Dll()->ImageList_Create(imageSize.cx, imageSize.cy, flags, initCapacity, growBy); CheckValid(); WARNX(OwlCommCtrl, !Handle, 0, "Cannot create ImageList"); }
static void sighandler(int signum) { if (!vcmd.client || vcmd.cmdid < 0) return; #ifdef DEBUG WARNX("sending command signal: serverfd %d; cmdid %u; signum: %d", vcmd.client->serverfd, vcmd.cmdid, signum); #endif if (vnode_send_cmdsignal(vcmd.client->serverfd, vcmd.cmdid, signum)) WARN("vnode_send_cmdsignal() failed"); return; }
// /// The TFont copy constructor. // TFont::TFont(const TFont& src) { #if !defined(NO_GDI_SHARE_HANDLES) Handle = src.Handle; RefAdd(Handle, Font); #else LOGFONT logFont; src.GetObject(logFont); Handle = ::CreateFontIndirect(&logFont); WARNX(OwlGDI, !Handle, 0, _T("Cannot create TFont from TFont @") << hex << uint32(LPVOID(&src))); CheckValid(); RefAdd(Handle, Font); #endif }