boinctui-2.7.1/src/0000775000175000017500000000000014536642777012007 5ustar ssssboinctui-2.7.1/src/nstatictext.cpp0000664000175000017500000000403014536642777015062 0ustar ssss// =============================================================================
// This file is part of boinctui.
// http://boinctui.googlecode.com
// Copyright (C) 2012,2013 Sergey Suslov
//
// boinctui is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// boinctui is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details
// .
// =============================================================================
#include "nstatictext.h"
#include "kclog.h"
void NStaticText::appendstring(int attr, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
content->vappend(attr, fmt, args);
va_end(args);
needrefresh = true;
this->refresh();
}
void NStaticText::setstring(int attr, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
delete content;
content = new NColorString(attr,fmt,args);
va_end(args);
needrefresh = true;
this->refresh();
}
void NStaticText::refresh()
{
wbkgd(win,bgcolor);
std::list::iterator it;
werase(win);
wmove(win,0,0);
if (align == 1) //центрирование
{
wmove(win,0,(getwidth()/2)-(content->getlen()+1)/2);
}
if (align == 2) //правое
{
wmove(win,0,getwidth()-content->getlen()/*+1*/);
}
for (it = content->parts.begin(); it != content->parts.end(); it++) //цикл по частям тек строки
{
NColorStringPart* part = *it;
//kLogPrintf("[%d] %s\n", part->attr, part->s.c_str());
wattrset(win,part->attr);
wprintw(win,"%s",part->s.c_str());
//wattrset(win,0);
}
wbkgdset(win,bgcolor);
wclrtoeol(win); //очищаем до конца строки
NView::refresh();
}
boinctui-2.7.1/src/resultparse.cpp0000664000175000017500000001201314536642777015061 0ustar ssss// =============================================================================
// This file is part of boinctui.
// http://boinctui.googlecode.com
// Copyright (C) 2012,2013 Sergey Suslov
//
// boinctui is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// boinctui is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details
// .
// =============================================================================
#include
#include
#include
#include
#include "resultparse.h"
#include "kclog.h"
std::stack- curitem; //на верху стека указатель на текущий заполняемый эл-т а голова это вершина дерева
void callbackStartElement(void* userdata, const char* name, const char** atts); //колбэк начала эл-та
void callbackEndElement(void* userdata, const char* name); //коллбэк завершения эл-та
void callbackData(void *userdata, const char *content, int len); //коллбэк значения эл-та
char* stripinvalidtag(char* xml, int len) //ГРЯЗНЫЙ ХАК нужен чтобы до парсинга удалить кривые теги
//в сообщениях вида иначе будет ошибка парсинга
{
const char* teg1 = "";
const char* teg2 = "";
//int bytesdone = 0; //просмотрено байт
char* pos = (char*)xml;
while (pos < xml + len)
{
char* x1 = strstr(pos, teg1);
char* x2 = strstr(pos, teg2);
if ((x1 != NULL)&&(x2 != NULL))
{
for(char* p = x1 + strlen(teg1); p < x2; p++)
{
if ((*p == '<')||(*p == '>')) //убираем html теги
*p = ' ';
}
pos = (x1>x2)? x1:x2; //берем наибольшую
pos++;
}
else
break;
}
return xml;
}
Item* xmlparse(const char* xml, int len, std::string& errmsg) //xml строка с xml len ее размер в байтах
{
XML_Parser parser;
void* ret;
parser = XML_ParserCreate(NULL/*"UTF-8"*/);
XML_SetUserData(parser, (void*) &ret);
XML_SetElementHandler(parser, callbackStartElement, callbackEndElement); //устанавливаем колбэки
XML_SetCharacterDataHandler(parser, callbackData);
Item* roottree = new Item(""); //создаем корневой эл-т дерева
curitem.push(roottree); //и делаем его текущим
int retcode = XML_Parse(parser, xml, len, XML_TRUE); //собственно парсинг
if (retcode == XML_STATUS_ERROR)
{
kLogPrintf("XML Error: %s\n", XML_ErrorString(XML_GetErrorCode(parser)));
errmsg = std::string("XML error:") + std::string(XML_ErrorString(XML_GetErrorCode(parser)));
}
XML_ParserFree(parser);
while (!curitem.empty())
curitem.pop(); //очищаем стек
return roottree; //возвращаем постороенное дерево
}
void callbackStartElement(void* userdata, const char* name, const char** atts)
{
//kLogPrintf("\t+ %s\n",name);
//аттрибуты тегов типа
//length=4 это атрибут (в boinc таких тегов нет?)
/*
for(int i = 0; atts[i]; i += 2)
printf(" %s= '%s'", atts[i], atts[i + 1]);
printf("\n");
*/
//создаем новый эл-т дерева
Item* pitem = new Item(name);
//добавляем созданный эл-т в вышестоящий (если он есть)
if (!curitem.empty())
{
Item* parentitem = curitem.top(); //владелец всегда на верху стека
parentitem->addsubitem(pitem);
}
//делаем созданный эл-т текущим (кладем в стек)
curitem.push(pitem);
}
void callbackEndElement(void* userdata, const char* name)
{
//kLogPrintf("\t- %s\n",name);
//удаляем текущий эл-т из стека (текущим становится его родитель)
curitem.pop();
}
void callbackData(void *userdata, const char *content, int len)
{
char *tmp = (char*)malloc(len+1);
strncpy(tmp, content, len);
tmp[len] = '\0';
//data = (void *) tmp;
//kLogPrintf("\ncallbackData()-->[%s]<-- len=%d\n",tmp,len);
//заносим значение в текущий эл-т
bool empty = true;
for (unsigned int i = 0; i < strlen(tmp); i++)
{
if (tmp[i] != ' ')
{
empty = false;
break;
}
}
if ( (!empty) && (strcmp(tmp,"\n") != 0) ) //пропускаем пустые строки
{
Item* pitem = curitem.top(); //текущий на верху стека
pitem->appendvalue(tmp);
}
free(tmp);
}
boinctui-2.7.1/src/cfgform.h0000664000175000017500000000306614536642777013610 0ustar ssss// =============================================================================
// This file is part of boinctui.
// http://boinctui.googlecode.com
// Copyright (C) 2012,2013 Sergey Suslov
//
// boinctui is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// boinctui is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details
// .
// =============================================================================
#ifndef CFGFORM_H
#define CFGFORM_H
#include
#include
#include "nform.h"
#include "cfg.h"
#include "nstatictext.h"
class CfgForm : public NForm
{
public:
CfgForm(int lines, int rows/*, Config* cfg*/);
void genfields(bool extfields); //создаст массив полей (extfields если нужно добавить хост)
virtual void eventhandle(NEvent* ev); //обработчик событий
protected:
void updatecfg(); //сохраняет данные из формы в cfg
//Config* cfg;
bool extfields; //true если поле для доп хоста видимо
int nhost; //макс номер хоста с 0го (включаа дополнительный если есть)
};
#endif //CFGFORM_Hboinctui-2.7.1/src/nhline.cpp0000664000175000017500000000205114536642777013766 0ustar ssss// =============================================================================
// This file is part of boinctui.
// http://boinctui.googlecode.com
// Copyright (C) 2012,2013 Sergey Suslov
//
// boinctui is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// boinctui is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details
// .
// =============================================================================
#include "nhline.h"
void NHLine::refresh()
{
wbkgd(win,bgcolor);
wattrset(win,getcolorpair(COLOR_WHITE,getbgcolor()));
if ( asciilinedraw == 1)
whline(win, '-', getwidth()-0);
else
whline(win, ACS_HLINE, getwidth()-0);
NView::refresh();
};boinctui-2.7.1/src/kclog.cpp0000664000175000017500000000555714536642777013626 0ustar ssss// =============================================================================
// This file is part of boinctui.
// http://boinctui.googlecode.com
// Copyright (C) 2012,2013 Sergey Suslov
//
// boinctui is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// boinctui is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details
// .
// =============================================================================
// * для ведения логов
#ifdef LINUX
#include
#endif
#include
#include
#include
#include "kclog.h"
#define K_NO_THREAD_COLOR_LOG //отключаем раскраску тредов ибо в этом проекте нахрен не нужно
#ifdef DEBUG
FILE* kLog = NULL;
/// ANSI цвета
const char* colors[7] = {"\033[0;0;31m","\033[0;0;32m","\033[0;0;33m","\033[0;0;34m","\033[0;0;35m","\033[0;0;36m","\033[0;0;37m"};
#endif
/// открывает лог файл на запись
void kLogOpen(const char* filename)
{
#ifdef DEBUG
if (filename == NULL)
{
kLog = stdout;
}
else
{
char* tmpfile = (char*) malloc(256);
#ifdef WIN32
sprintf(tmpfile,"%s/%s",getenv("TEMP"),filename); //для win32 используем юзерский temp
//const char* tmpdir = getenv("TEMP");
#else //для линукса используем фиксированный путь
sprintf(tmpfile,"/tmp/%s",filename);
#endif
if ((kLog = fopen(tmpfile,"a")) == NULL)
{
//kLogPrintf("ERROR: can't create log file %s\n",tmpfile.c_str());
}
else
{
kLogPrintf("\nINFO: log opened success\n");
}
free(tmpfile);
}
#endif
}
/// закрывает лог файл
void kLogClose()
{
#ifdef DEBUG
kLogPrintf("\nINFO: log close\n");
fclose(kLog);
#endif
}
/// вывести информацию в лог заданным цветом
void kCLogPrintf(char* color, char* fmt, ...)
{
#ifdef DEBUG
if (kLog == NULL)
kLogOpen();
fprintf(kLog,"%s",color);
va_list args;
va_start(args, fmt);
vfprintf(kLog, fmt, args);
va_end(args);
fprintf(kLog,"\033[0m");
fflush(kLog);
#endif
}
/// вывести информацию в лог
void kLogPrintf(const char* fmt, ...)
{
#ifdef DEBUG
if (kLog == NULL)
kLogOpen();
#ifndef K_NO_THREAD_COLOR_LOG
fprintf(kLog,"%s",colors[pthread_self() % (sizeof(colors)/sizeof(colors[0]))]);
#endif
va_list args;
va_start(args, fmt);
vfprintf(kLog, fmt, args);
va_end(args);
#ifndef K_NO_THREAD_COLOR_LOG
fprintf(kLog,"\033[0m");
#endif
fflush(kLog);
#endif
}
boinctui-2.7.1/src/nmessagebox.cpp0000664000175000017500000001313414536642777015030 0ustar ssss// =============================================================================
// This file is part of boinctui.
// http://boinctui.googlecode.com
// Copyright (C) 2012,2013 Sergey Suslov
//
// boinctui is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// boinctui is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details
// .
// =============================================================================
#include
#include
#include "kclog.h"
#include "nmessagebox.h"
// =============================================================================
NMButton::NMButton(const char* text, NEvent* pevent, ...) : NStaticText(NRect(3, 20, getmaxy(stdscr)/2-3/2,getmaxx(stdscr)/2-20/2))
{
appendstring(getcolorpair(COLOR_WHITE, COLOR_CYAN)," ");
appendstring(getcolorpair(COLOR_WHITE, COLOR_CYAN) | A_BOLD ,text);
appendstring(getcolorpair(COLOR_WHITE, COLOR_CYAN)," ");
this->pevent = pevent;
//размер кнопки
resize(1, mbstrlen(text) + 2);
//список клавиш на которые реагирует эта кнопка
va_list pk;
va_start(pk, pevent);
int ch = va_arg(pk, int);
while ( ch != 0)
{
keys.push_back((char)ch);
ch = va_arg(pk, int); //следующий ключ
}
va_end(pk);
}
void NMButton::eventhandle(NEvent* ev) //обработчик событий
{
NStaticText::eventhandle(ev); //предок
if ( ev->done )
return;
//одиночный или двойной клик
NMouseEvent* mevent = (NMouseEvent*)ev;
if (( ev->type == NEvent::evMOUSE ) && (mevent->cmdcode & (BUTTON1_CLICKED | BUTTON1_DOUBLE_CLICKED)))
{
if (isinside(mevent->row, mevent->col))
{
ev->done = true;
NEvent* tmp = pevent;
pevent = NULL;
putevent(tmp); //активируем событие связанное с этой кнопкой
}
}
//клавиатура
if ( ev->type == NEvent::evKB )
{
if ( keys.end() != std::find(keys.begin(), keys.end(), ev->cmdcode) )
{
kLogPrintf("NMButton::eventhandle() got '%c' key\n", ev->cmdcode);
if (pevent)
{
ev->done = true;
NEvent* tmp = pevent;
pevent = NULL;
putevent(tmp); //активируем событие связанное с этой кнопкой
}
}
}
}
// =============================================================================
NMessageBox::NMessageBox(const char* text) : NGroup(NRect(3, 40, 1, 1))
{
//расчитать сколько строк нужно для отображения контента
int contentheight = 0;
int bsize = strlen(text); //количество байт
int result = 0; //подсчитанное кол-во символов
int nbytes = 0; //просмотренное кол-во байтов
//int nlines = 0; //количество экранных строк
int col = getwidth() - 4;
const char* p = text;
do
{
col++;
if ((col >= getwidth() - 4)||(*p == '\n'))
{
if (*p == '\n')
col = 0;
else
col = 1;
contentheight++; //след строка
}
int symlen = mblen(p,bsize-nbytes);
nbytes = nbytes + symlen;
result++;
p = p + symlen; //адрес начала след символа
}
while ( (*p != 0)&&(nbytes < bsize) ); //дошли до конца
//заполняем содержимое
content = new NStaticText(NRect(contentheight, getwidth()-4, 2, 2));
content->setbgcolor(getcolorpair(COLOR_WHITE, getbgcolor()));
insert(content);
content->appendstring(getcolorpair(COLOR_WHITE, getbgcolor()) | A_BOLD, text);
modalflag = true;
resize(contentheight + 6,getwidth());
wattrset(win,getcolorpair(COLOR_WHITE, getbgcolor()) | A_BOLD);
if(asciilinedraw == 1)
wborder(win, '|', '|', '-', '-', '+', '+', '+', '+');
else
box(win,0,0);
//content->setalign(1);
move(getmaxy(stdscr)/2-getheight()/2,getmaxx(stdscr)/2-getwidth()/2); //центрируем
}
void NMessageBox::addbutton(NMButton* button) //добавить кнопку
{
insert(button);
std::list::iterator it;
int w = 0; //суммарная ширина всех кнопок
for (it = ++items.begin(); it != items.end(); it++) // ++ пропустить content
{
w = w + (*it)->getwidth() + 2; // +2 промежутки между кнопками
}
int row = getheight() - 3;
int col = (getwidth() - w) / 2 + 2;
for (it = ++items.begin(); it != items.end(); it++)
{
(*it)->move(row, col);
col = col + (*it)->getwidth() + 2;
}
}
void NMessageBox::eventhandle(NEvent* ev) //обработчик событий
{
NGroup::eventhandle(ev); //предок
if ( ev->done )
return;
//одиночный или двойной клик
//NMouseEvent* mevent = (NMouseEvent*)ev;
if (/*(*/ ev->type == NEvent::evMOUSE /*) && (mevent->cmdcode & (BUTTON1_CLICKED | BUTTON1_DOUBLE_CLICKED))*/)
{
//блокируем все мышиные мнутри окна
// if (isinside(mevent->row, mevent->col))
ev->done = true;
}
//клавиатура
if (ev->type == NEvent::evKB )
{
//блокировать все клавиатурные кроме кода закрытия формы
if (ev->keycode != 27)
ev->done = true;
}
}
boinctui-2.7.1/src/ngroup.cpp0000664000175000017500000000742514536642777014035 0ustar ssss// =============================================================================
// This file is part of boinctui.
// http://boinctui.googlecode.com
// Copyright (C) 2012,2013 Sergey Suslov
//
// boinctui is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// boinctui is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details
// .
// =============================================================================
#include
#include "ngroup.h"
NGroup::~NGroup()
{
std::list::iterator it;
for(it = items.begin(); it != items.end(); it++)
{
delete (*it);
}
}
NView* NGroup::getitembyid(const char* id) //получить эл-т зная id его класса
{
NView* result = NULL;
std::list::iterator it;
for(it = items.begin(); it != items.end(); it++)
{
if (strcmp((*it)->getid(), id) == 0)
{
result = (*it);
break;
}
}
return result;
}
bool NGroup::destroybyid(const char* id) //удалить (с деструкцией) эл-т зная id его класса
{
bool result = false;
NView* item = getitembyid(id);
if (item != NULL)
{
remove(item);
delete(item);
result = true;
}
return result;
}
void NGroup::setneedrefresh()
{
NView::setneedrefresh();
std::list::iterator it;
for(it = items.begin(); it != items.end(); it++) //перерисовать все подэлементы
{
(*it)->setneedrefresh();
}
}
void NGroup::refresh()
{
NView::refresh(); //предок
std::list::iterator it;
for(it = items.begin(); it != items.end(); it++) //перерисовать все подэлементы
{
(*it)->refresh();
}
}
void NGroup::move(int begrow, int begcol)
{
//перемещаем само окно
NView::move(begrow, begcol); //предок
//перемещаем содержимое (относительно этого окна)
std::list::iterator it;
for(it = items.begin(); it != items.end(); it++) //перместить все подэлементы
{
(*it)->move((*it)->getbegrow(),(*it)->getbegcol());
}
}
void NGroup::centermodalitems(int maxy, int maxx) //центрировать все модальные эл-ты (maxy,maxx -размер экрана)
{
std::list::iterator it;
for(it = items.begin(); it != items.end(); it++) //ищем модальные подэлементы
{
if ((*it)->ismodal())
(*it)->move(maxy/2-(*it)->getheight()/2,maxx/2-(*it)->getwidth()/2);
}
}
void NGroup::eventhandle(NEvent* ev) //обработчик событий
{
//если событие уже кем-то обработано, то просто выходим
if (ev->done)
return;
//посылаем событие всем своим подэлементам (последние вставленные
//получат первыми. Если один из подэл-тов обработал, то выходим
std::list::reverse_iterator rit;
for(rit = items.rbegin(); rit != items.rend(); rit++) //отправить всем подэлементам
{
(*rit)->eventhandle(ev);
if (ev->done)
return; //прекращаем если событие обработано
}
//раз подэл-ты не обработали пытаемся обработать самостоятельно
NView::eventhandle(ev); //предок
}
boinctui-2.7.1/src/nselectlist.h0000664000175000017500000000465414536642777014522 0ustar ssss// =============================================================================
// This file is part of boinctui.
// http://boinctui.googlecode.com
// Copyright (C) 2012,2013 Sergey Suslov
//
// boinctui is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// boinctui is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details
// .
// =============================================================================
#ifndef NSELECTLIST_H
#define NSELECTLIST_H
#include "nscrollview.h"
class NSelectList : public NScrollView //список со скроллингом и селектором
{
public:
NSelectList(NRect rect) : NScrollView(rect) { selectedindex = -1; setselectorenable(true); setselectorbgcolor(COLOR_WHITE); };
void addstring(void* userobj, int attr, const char* fmt, ...); //userobj произвольные данные связанные со строкой
void addstring(void* userobj, NColorString* sctring);
virtual void drawcontent();
virtual void refresh();
virtual void selectorup();
virtual void selectordown();
virtual void setselectorpos(int n) { selectedindex = n; needrefresh = true; }; //передвинуть селектор на строку n
void* getselectedobj(); //вернет указатель или NULL
void setselectorbgcolor(short color) { selectorbgcolor = color; };
//virtual bool objcmpeqv(void* obj1, void* obj2) { return obj1==obj2; };
void setselectorenable(bool b) { selectorenable = b; }; //изменить видимость селектора
protected:
//void* selectedobj; //выделенный объект
int selectedindex; //номер выделенной строки
bool selectorenable; //true если видимость селектора разрешена (не значит что он видим)
std::vector objects; //объекты, ассоциированные с визуальными строками
short selectorbgcolor; //номер цвета фона выделеной строки
};
#endif //NSELECTLIST_Hboinctui-2.7.1/src/nmenu.h0000664000175000017500000000473014536642777013306 0ustar ssss// =============================================================================
// This file is part of boinctui.
// http://boinctui.googlecode.com
// Copyright (C) 2012,2013 Sergey Suslov
//
// boinctui is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// boinctui is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details
// .
// =============================================================================
#ifndef NMENU_H
#define NMENU_H
#if HAVE_LIBNCURSESW == 1 && NCURSESW_HAVE_SUBDIR == 1
#include
#else
#include
#endif
#include
#include "ngroup.h"
#include "nscrollbar.h"
class NMenu : public NGroup
{
public:
NMenu(NRect rect, bool horis = false);
virtual ~NMenu();
virtual void refresh();
void additem(const char* name, const char* comment); //добавить эл-т в меню
virtual void eventhandle(NEvent* ev); //обработчик событий
void setbackground(int attr) { set_menu_back(menu, attr); wattrset(win, attr); bgattr = attr; wbkgdset(win,attr); };
void setforeground(int attr) { set_menu_fore(menu, attr); fgattr = attr; };
void postmenu() { if (!posted) {post_menu(menu); posted = true;} };
void unpostmenu() { if (posted) {unpost_menu(menu); posted = false;} };
virtual bool createsubmenu() { return false; }; //открыть субменю
virtual void destroysubmenu(); //закрыть субменю
virtual bool action() { return false; }; //вызывается при нажатии Enter
protected:
MENU* menu;
ITEM** mitems; //масив элементов
std::list itemnames; //имена эл-тов меню
std::list itemcomments; //комментарии к эл-там меню
int bgattr; //цвет текста и фона невыделенного эл-та
int fgattr; //цвет текста и фона выделенного эл-та
bool ishoris;//true если меню горизонтальное
private:
bool posted; //true после post_menu()
NScrollBar* scrollbar;
};
#endif //NMENU_Hboinctui-2.7.1/src/net.h0000664000175000017500000000344514536642777012754 0ustar ssss// =============================================================================
// This file is part of boinctui.
// http://boinctui.googlecode.com
// Copyright (C) 2012,2013 Sergey Suslov
//
// boinctui is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// boinctui is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details
// .
// =============================================================================
#ifndef NET_H
#define NET_H
#include
#include
class TConnect //информация о соединении с boinc сервером
{
public:
TConnect(const char* shost, const char* sport) { this->shost = strdup(shost); this->sport = strdup(sport); hsock = -1; };
virtual ~TConnect() { disconnect(); free(shost); free(sport); };
int getsock() {return hsock;};
void sendreq(const char* fmt, va_list vl); //отправить запрос на сервер
void sendreq(const char* fmt, ...); //отправить запрос на сервер
char* waitresult(); //получить ответ на запрос
char* gethost() { return shost; };
char* getport() { return sport; };
bool isconnected() { return (hsock != -1); };
protected:
virtual void createconnect (/*const char* shost, const char* sport*/);
virtual void disconnect();
int hsock; //дескриптор сокета
char* shost;
char* sport;
};
#endif // NET_H
boinctui-2.7.1/src/nscrollbar.cpp0000664000175000017500000001021014536642777014646 0ustar ssss// =============================================================================
// This file is part of boinctui.
// http://boinctui.googlecode.com
// Copyright (C) 2012,2013,2014 Sergey Suslov
//
// boinctui is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// boinctui is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details
// .
// =============================================================================
#include
#include "nscrollbar.h"
#include "kclog.h"
NScrollBar::NScrollBar(NRect rect, chtype chtop, chtype chbottom, chtype chinactive) : NView(rect)
{
bgcolor = 0;
this->chtop = chtop;
this->chbottom = chbottom;
this->chinactive = chinactive;
setvisible(true);
}
void NScrollBar::setpos(int vmin, int vmax, int vpos1, int vpos2)
{
//если видимая часть больше или равна контенту то выключаем
setvisible(!((vpos1<=vmin)&&(vpos2>=vmax)));
if ((this->vmin!=vmin)||(this->vmax!=vmax)||(this->vpos1!=vpos1)||(this->vpos2!=vpos2))
{
this->vmin=vmin;
this->vmax=vmax;
this->vpos1=vpos1;
this->vpos2=vpos2;
if (vmin>vmax)
vmax = vmin;
if (vpos1 > vpos2)
vpos2 = vpos1;
if (vpos1 < vmin)
vpos1 = vmin;
if (vpos2 > vmax)
vpos2 = vmax;
//kLogPrintf("NScrollBar::setpos(vmin=%d, vmax=%d, vpos1=%d, vpos2=%d)\n",vmin, vmax, vpos1, vpos2);
refresh();
}
}
void NScrollBar::refresh()
{
wbkgd(win,bgcolor);
wattrset(win,getcolorpair(COLOR_WHITE,getbgcolor()));
chtype topsymbol = asciilinedraw ? '+'| (chtop & A_BOLD) : chtop;
chtype bottomsymbol = asciilinedraw ? '+' | (chbottom & A_BOLD) : chbottom;
chtype bodysymbol = asciilinedraw ? 'X' : ACS_CKBOARD;
if (!visible)
bodysymbol = asciilinedraw ? '|' | (chinactive & A_BOLD) : chinactive;
int rowmin = 0; //строка с которой начинаем рисовать фон
int rowmax = getheight() - 1; //строка до которой рисуем фон включительно
if (chtop != 0) //верхний концевой символ есть
{
mvwaddch(win,0,0,topsymbol);
rowmin = 1;
}
if (chbottom != 0)//нижний концевой символ есть
{
mvwaddch(win,getheight()-1,0,bottomsymbol);
rowmax--; //укорачиваем
}
//фоновый заполнитель
int len = rowmax - rowmin + 1; //высота заполнителя в символах
mvwvline(win, rowmin, 0, bodysymbol, len);
if (visible)
{
//отрисовка позиции
if ((vpos2>vpos1)&&(vmax>vmin))
{
double scale = double(len-1)/(vmax-vmin); //сколько единиц на экранную строку
int len2 = round(scale * (vpos2-vpos1)); //число выделенных строк
int rowpos1 = rowmin + round(scale * (vpos1-vmin)); //строка начала выделения
if (len2<1) //len2 всегда 1 и более
len2=1;
//подпорки с краем диапазона чтобы были видны малые фрагменты
//в начале и в конце
if ((rowpos1==rowmin)&&(vpos1>vmin))
{
if (rowpos1=rowmax)&&(vpos2rowmin)
rowpos1--; //слегка приподнять вверх чтобы показать что это не конец
}
if (vpos2==vmax)
len2=len-rowpos1+1;
//kLogPrintf("len=%d vmin=%d vmax=%d vpos1=%d vpos2=%d scale=%f rowmin=%d rowmax=%d rowpos1=%d len2=%d\n",len, vmin,vmax,vpos1,vpos2,scale,rowmin,rowmax,rowpos1,len2);
//рисуем выделение
mvwvline(win,rowpos1,0,' ' | getcolorpair(COLOR_CYAN,COLOR_WHITE), len2);
}
}
NView::refresh();
}
boinctui-2.7.1/src/mainprog.cpp0000664000175000017500000004660714536642777014344 0ustar ssss// =============================================================================
// This file is part of boinctui.
// http://boinctui.googlecode.com
// Copyright (C) 2012,2013 Sergey Suslov
//
// boinctui is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// boinctui is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details
// .
// =============================================================================
#include
#include
#include
#include "kclog.h"
#include "mainprog.h"
#include "tuievent.h"
#include "nmessagebox.h"
#include "statwin.h"
MainProg::MainProg()
{
uistate = 0;
done = false;
gsrvlist = new SrvList();
evtimertime = 0; //запускаем таймер с нуля
//основное окно
wmain = new MainWin(NRect(getmaxy(stdscr)-2, getmaxx(stdscr), 1, 0)); //создаем основное окно
insert(wmain);
wmain->setserver(gsrvlist->getcursrv()); //отображать первый в списке сервер
menu = new TopMenu();
menu->setserver(gsrvlist->getcursrv()); //отображать первый в списке сервер
insert(menu);
wmain->updatecaption();
//статус строка
wstatus = new NStaticText(NRect(1, getmaxx(stdscr), getmaxy(stdscr)-1, 0)); //создаем окно статуса
insert(wstatus);
wstatus->setbgcolor(getcolorpair(COLOR_WHITE,COLOR_GREEN));
updatestatuslinecontent();
}
MainProg::~MainProg()
{
kLogPrintf("MainProg::~MainProg()\n");
gCfg->save();
delete gsrvlist;
}
void MainProg::smartresize()
{
if (!MainProg::needresize)
return;
struct winsize size;
ioctl(fileno(stdout), TIOCGWINSZ, (char *) &size);
resizeterm(size.ws_row, size.ws_col);
menu->resize(1, getmaxx(stdscr)); //ширина верхнего меню
wmain->resize(getmaxy(stdscr)-2, getmaxx(stdscr));
wstatus->resize(1, getmaxx(stdscr)); //ширина статус строки
wstatus->move(getmaxy(stdscr)-1,0); //позиция статус строки
centermodalitems(getmaxy(stdscr),getmaxx(stdscr)); //центрировать модальные формы (если есть)
MainProg::needresize = false;
}
void MainProg::updatestatuslinecontent()
{
int attrYG = A_BOLD | getcolorpair(COLOR_YELLOW,COLOR_GREEN);
int attrWG = A_BOLD | getcolorpair(COLOR_WHITE,COLOR_GREEN);
int attrBG = A_BOLD | getcolorpair(COLOR_BLACK,COLOR_GREEN) | A_BOLD;
if (uistate & stUIMODALFORM)
{
wstatus->setstring(attrYG, " Esc");
wstatus->appendstring(attrWG, " Cancel");
}
if (uistate & stUISTATWIN)
{
wstatus->setstring(attrYG, " Esc");
wstatus->appendstring(attrWG, " Cancel");
wstatus->appendstring(attrWG, " |");
wstatus->appendstring(attrYG, " PgUp/PgDn");
wstatus->appendstring(attrWG, " V.Scroll");
wstatus->appendstring(attrWG, " |");
wstatus->appendstring(attrYG, " Left/Right");
wstatus->appendstring(attrWG, " H.Scroll");
wstatus->appendstring(attrWG, " |");
wstatus->appendstring(attrYG, " U");
wstatus->appendstring(attrWG, " Host/User score");
}
if (uistate & stUITASKINFO)
{
wstatus->setstring(attrYG, " Esc");
wstatus->appendstring(attrWG, " Cancel");
wstatus->appendstring(attrWG, " |");
wstatus->appendstring(attrYG, " PgUp/PgDn");
wstatus->appendstring(attrWG, " Scroll ");
}
if ( (uistate == 0)||(uistate == stUISELECTOR) )
{
wstatus->setstring(attrYG, " PgUp/PgDn");
wstatus->appendstring(attrWG, " Scroll Msg |");
wstatus->appendstring(attrYG, " +/-");
wstatus->appendstring(attrWG, " Resize Msg |");
wstatus->appendstring(attrYG, " Up/Dn");
wstatus->appendstring(attrWG, " Select |");
if (uistate & stUISELECTOR)
{
wstatus->appendstring(attrYG, " S");
wstatus->appendstring(attrWG, "uspend");
wstatus->appendstring(attrWG, " |");
wstatus->appendstring(attrYG, " R");
wstatus->appendstring(attrWG, "esume |");
wstatus->appendstring(attrYG, " Enter");
wstatus->appendstring(attrWG, " Info");
}
else
{
wstatus->appendstring(attrBG, " Suspend");
wstatus->appendstring(attrWG, " |");
wstatus->appendstring(attrBG, " Resume");
wstatus->appendstring(attrWG, " |");
wstatus->appendstring(attrBG, " Enter Info");
}
wstatus->appendstring(attrWG, " |");
wstatus->appendstring(attrYG, " F9/M");
wstatus->appendstring(attrWG, " Menu |");
wstatus->appendstring(attrYG, " V");
wstatus->appendstring(attrWG, " Statistics |");
}
}
void MainProg::eventhandle(NEvent* ev) //обработчик событий КОРНЕВОЙ!
{
NProgram::eventhandle(ev);
if (ev->done) //если событие не обработано обработать здесь
return;
if (ev->type == NEvent::evKB) //клавиатурные
{
switch(ev->keycode)
{
case 'q':
case 'Q':
done = true; //выходим
break;
case 'n':
case 'N':
menu->disable();
if (gsrvlist->getcursrv())
{
gsrvlist->nextserver();
wmain->setserver(gsrvlist->getcursrv());
menu->setserver(gsrvlist->getcursrv());
evtimertime = 0; //для перезапуска таймера для форсированонй перерисовки
wmain->updatecaption();
}
break;
case 'p':
case 'P':
menu->disable();
if (gsrvlist->getcursrv())
{
gsrvlist->prevserver();
wmain->setserver(gsrvlist->getcursrv());
menu->setserver(gsrvlist->getcursrv());
evtimertime = 0;
wmain->updatecaption();
}
break;
case 'c':
case 'C':
if (getitembyid(typeid(CfgForm).name()) == NULL)
{
menu->disable();
CfgForm* cfgform = new CfgForm(15,76/*,cfg*/);
insert(cfgform);
cfgform->settitle("Configuration");
cfgform->refresh();
uistate = uistate | stUIMODALFORM;
updatestatuslinecontent();
}
break;
case 'S':
case 's':
{
TaskInfo* tinfo = (TaskInfo*)wmain->wtask->getselectedobj();
if (tinfo) //только если есть выделенный эл-т
gsrvlist->getcursrv()->optask(tinfo->projecturl.c_str(), tinfo->taskname.c_str(),"suspend_result");
break;
}
case 'V':
case 'v':
{
if (!destroybyid(typeid(StatWin).name()))
{
menu->disable();
StatWin* statwin = new StatWin(gsrvlist->getcursrv());
insert(statwin);
statwin->move(getmaxy(stdscr)/2-statwin->getheight()/2,getmaxx(stdscr)/2-statwin->getwidth()/2); //центрируем
uistate = uistate | stUISTATWIN;
}
else
uistate = uistate & ~stUISTATWIN;
updatestatuslinecontent();
break;
}
case 'R':
case 'r':
{
TaskInfo* tinfo = (TaskInfo*)wmain->wtask->getselectedobj();
if (tinfo) //только если есть выделенный эл-т
gsrvlist->getcursrv()->optask(tinfo->projecturl.c_str(), tinfo->taskname.c_str(),"resume_result");
break;
}
case 'A':
case 'a':
{
TaskInfo* tinfo = (TaskInfo*)wmain->wtask->getselectedobj();
if (tinfo) //только если есть выделенный эл-т
{
TuiEvent* ev = new TuiEvent(evABORTRES);
ev->bdata1 = false;
putevent(ev); //создаем событие с кодом 2 "abort_result"
}
break;
}
case 27:
menu->disable();
//деструктим все какие есть модельные окна
destroybyid(typeid(CfgForm).name()); //деструктим форму
destroybyid(typeid(NMessageBox).name()); //деструктим форму
if (destroybyid(typeid(StatWin).name())) //деструктим форму
uistate = uistate & ~stUISTATWIN;
if (destroybyid(typeid(TaskInfoWin).name())) //деструктим форму
{
wmain->wtask->setselectorenable(true);
uistate = uistate & ~stUITASKINFO;
}
uistate = uistate & ~stUIMODALFORM;
updatestatuslinecontent();
break;
case 'M':
case 'm':
case KEY_F(9):
if (!menu->isenable())
{
menu->enable();
menu->action();
}
else
menu->disable();
break;
default:
kLogPrintf("KEYCODE=%d\n", ev->keycode);
break;
} //switch
}
if (ev->type == NEvent::evPROG) //прграммные
{
switch(ev->cmdcode)
{
case evCFGCH: //событие при изменении конфига
{
menu->disable();
destroybyid(typeid(CfgForm).name()); //деструктим форму
//реакция на изменение конфига
gsrvlist->refreshcfg();
wmain->setserver(gsrvlist->getcursrv()); //отображать первый в списке сервер
menu->setserver(gsrvlist->getcursrv()); //отображать первый в списке сервер
wmain->updatecaption();
evtimertime = 0; //для перезапуска таймера для форсированонй перерисовки
break;
}
case evABOUT: //событие About win
{
if (!destroybyid(typeid(AboutWin).name()))
{
AboutWin* about = new AboutWin(2,40);
insert(about);
about->move(getmaxy(stdscr)/2-about->getheight()/2,getmaxx(stdscr)/2-about->getwidth()/2); //центрируем
uistate = uistate | stUIMODALFORM;
}
else
uistate = uistate & ~stUIMODALFORM;
updatestatuslinecontent();
break;
}
case evPOPUPMSG:
{
TuiEvent* ev1 = (TuiEvent*)ev;
NMessageBox* mbox = new NMessageBox((ev1->sdata1 + "\n" + ev1->sdata2).c_str());
NEvent* buttonNev = new NEvent(NEvent::evKB, 27); //событие для кнопки Ok
mbox->addbutton(new NMButton("Ok",buttonNev, 'O','o',27,'\n',0));
insert(mbox);
uistate = uistate | stUIMODALFORM;
break;
}
case evKEYBIND: //событие KeyBinding win
{
if (!destroybyid(typeid(HelpWin).name()))
{
HelpWin* help = new HelpWin(2,40);
insert(help);
help->move(getmaxy(stdscr)/2-help->getheight()/2,getmaxx(stdscr)/2-help->getwidth()/2); //центрируем
uistate = uistate | stUIMODALFORM;
}
else
uistate = uistate & ~stUIMODALFORM;
updatestatuslinecontent();
break;
}
case evBENCHMARK: //запустить бенчмарк
{
Srv* srv = gsrvlist->getcursrv();
if (srv != NULL)
srv->runbenchmarks();
break;
}
case evADDPROJECT: //добавить проект
{
if (!destroybyid(typeid(AddProjectForm).name()))
{
TuiEvent* ev1 = (TuiEvent*)ev;
//Srv* srv = gsrvlist->getcursrv();
if (ev1->srv != NULL)
{
AddProjectForm* addform = new AddProjectForm(30,65,ev1->srv,ev1->sdata1.c_str(),ev1->bdata1, ev1->bdata2);
insert(addform);
addform->move(getmaxy(stdscr)/2-addform->getheight()/2,getmaxx(stdscr)/2-addform->getwidth()/2); //центрируем
uistate = uistate | stUIMODALFORM;
}
}
else
uistate = uistate & ~stUIMODALFORM;
updatestatuslinecontent();
break;
}
case evADDACCMGR: //добавить акк менеджер
{
if (!destroybyid(typeid(AddAccMgrForm).name()))
{
TuiEvent* ev1 = (TuiEvent*)ev;
//Srv* srv = gsrvlist->getcursrv();
if (ev1->srv != NULL)
{
AddAccMgrForm* addmgrform = new AddAccMgrForm(30,65,ev1->srv,ev1->sdata1.c_str());
insert(addmgrform);
addmgrform->move(getmaxy(stdscr)/2-addmgrform->getheight()/2,getmaxx(stdscr)/2-addmgrform->getwidth()/2); //центрируем
uistate = uistate | stUIMODALFORM;
}
}
else
uistate = uistate & ~stUIMODALFORM;
updatestatuslinecontent();
break;
}
case evPROJECTOP: //операции над проектом
{
TuiEvent* ev1 = (TuiEvent*)ev;
const char* projname = ev1->sdata1.c_str();
const char* projop = ev1->sdata2.c_str();
if (!ev1->bdata1) //если нет флага подтвержденного события, то не выполняем а спрашиваем юзера
{
menu->disable(); //выключаем меню
//создаем окно сообщения с подтверждением
std::stringstream s;
s << "Please Confirm\n\n" << "Project : "<< projname << "\nOperation : " << projop;
NMessageBox* mbox = new NMessageBox(s.str().c_str());
TuiEvent* buttonYev = new TuiEvent(evPROJECTOP, ev1->srv, projname, projop); //событие для кнопки Y
buttonYev->bdata1 = true; //флаг подтвержденности
mbox->addbutton(new NMButton("Yes",buttonYev, 'Y','y',0));
NEvent* buttonNev = new NEvent(NEvent::evKB, 27); //событие для кнопки N
mbox->addbutton(new NMButton("No",buttonNev, 'N','n',27,0));
insert(mbox);
uistate = uistate | stUIMODALFORM;
}
else
{
kLogPrintf("evPROJECT confirmed event detected\n");
ev1->srv->opproject(projname, projop); //выполняем действие
if (destroybyid(typeid(NMessageBox).name())) //удаляем окно подтверждения (если есть)
uistate = uistate & ~stUIMODALFORM;
}
updatestatuslinecontent();
break;
}
case evABORTRES: //событие действий над проектами "abort_result" и.т.д.
{
TaskInfo* tinfo = (TaskInfo*)wmain->wtask->getselectedobj();
if (tinfo) //только если есть выделенный эл-т
{
TuiEvent* ev1 = (TuiEvent*)ev;
if (!ev1->bdata1) //если нет флага подтвержденного события, то не выполняем а спрашиваем юзера
{
menu->disable(); //выключаем меню
//создаем окно сообщения с подтверждением
std::stringstream s;
s << "Please Confirm\n\n" << "Task : " << tinfo->taskname << "\nOperation : " << "Abort";
NMessageBox* mbox = new NMessageBox(s.str().c_str());
TuiEvent* buttonYev = new TuiEvent(evABORTRES); //событие для кнопки Y
buttonYev->bdata1 = true; //флаг подтвержденности
mbox->addbutton(new NMButton("Yes",buttonYev, 'Y','y',0));
NEvent* buttonNev = new NEvent(NEvent::evKB, 27); //событие для кнопки N
mbox->addbutton(new NMButton("No",buttonNev, 'N','n',27,0));
insert(mbox);
uistate = uistate | stUIMODALFORM;
}
else
{
kLogPrintf("evABORTRES confirmed event detected\n");
Srv* srv = gsrvlist->getcursrv();
srv->optask(tinfo->projecturl.c_str(), tinfo->taskname.c_str(),"abort_result"); //выполняем действие
if (destroybyid(typeid(NMessageBox).name())) //удаляем окно подтверждения (если есть)
uistate = uistate & ~stUIMODALFORM;
}
updatestatuslinecontent();
break;
}
}
case evTASKSELECTORON:
{
uistate = uistate | stUISELECTOR;
updatestatuslinecontent();
break;
}
case evTASKSELECTOROFF:
{
uistate = uistate & ~stUISELECTOR;
updatestatuslinecontent();
break;
}
case evTASKINFO:
{
TaskInfo* tinfo = (TaskInfo*)wmain->wtask->getselectedobj();
if (tinfo) //только если есть выделенный эл-т
{
wmain->wtask->setselectorenable(false);
TaskInfoWin* taskinfowin = new TaskInfoWin("Task Info Raw View", gsrvlist->getcursrv(), tinfo->projecturl.c_str(), tinfo->taskname.c_str());
insert(taskinfowin);
taskinfowin->move(getmaxy(stdscr)/2-taskinfowin->getheight()/2,getmaxx(stdscr)/2-taskinfowin->getwidth()/2); //центрируем
uistate = uistate | stUITASKINFO;
updatestatuslinecontent();
}
}
case evASCIIMODECHANGE:
{
gCfg->setivalue("line_draw_mode",asciilinedraw);
refresh();
break;
}
case evTRANSPARENTBGMODECHANGE:
{
gCfg->setivalue("transparent_background",(transparentbg==0)?1:0);
//transparentbg = (transparentbg==0)?1:0;
//refresh();
menu->disable(); //выключаем меню
//создаем окно сообщения с подтверждением
NMessageBox* mbox = new NMessageBox("Need restart boinctui");
NEvent* buttonNev = new NEvent(NEvent::evKB, 27); //событие для кнопки N
mbox->addbutton(new NMButton("Yes",buttonNev, 'Y','y','\n',27,0));
insert(mbox);
uistate = uistate | stUIMODALFORM;
break;
}
} //switch
}
}
bool MainProg::mainloop() //основной цикл порождающий события
{
sigset_t newset;
sigemptyset(&newset);
sigaddset(&newset, SIGWINCH); //маска для сигнала
if (!gCfg->errmsg.empty())
putevent(new TuiEvent(evPOPUPMSG, "Config error:", gCfg->errmsg.c_str()));
else
{
if (gCfg->isdefault) //если конфига нет то открыть форму
putevent(new NEvent(NEvent::evKB, 'C')); //создаем событие иммитирующее нажатие 'C'
}
do
{
//блокировка сигнала изменения окна SIGWINCH на время отрисовки (из-за нереентерабельности курсес)
sigprocmask(SIG_BLOCK, &newset, 0);
//если нужен ресайз - перерисовать полностью
if (MainProg::needresize)
{
smartresize();
refresh();
menu->refresh();
//wmain->erase();
wstatus->erase();
wmain->refresh();
wstatus->refresh();
}
#ifndef EVENTTHREAD
//если настало время посылаем evTIMER
if (time(NULL) - evtimertime > EVTIMERINTERVAL)
{
NEvent* event = new NEvent(NEvent::evTIMER, 0); //создаем событие таймера
putevent(event); //отправить в очередь
time(&evtimertime);
}
//есть символ в буфере -> нужно создать событие
int ic;
if ( (ic = getch()) != ERR ) //символ(ы) есть?
{
NEvent* event = NULL;
if (KEY_MOUSE == ic)
{
// mouse event
MEVENT mevent;
if (OK == getmouse(&mevent))
event = new NMouseEvent(mevent.bstate, mevent.y, mevent.x); //создаем мышиное событие
else
kLogPrintf("getmouse() err\n");
}
else // keyboard event
event = new NEvent(NEvent::evKB, ic); //создаем клавиатурное событие
if (event != NULL)
putevent(event); //отправить в очередь
}
#endif
//есть события в очереди - выполняем
while(!evqueueempty())
{
NEvent* event = popevent(); //получить первое событие из очереди
this->eventhandle(event); //отправить событие обработчику
#ifdef DEBUG
if ((event->type != NEvent::evTIMER)&&(!event->done))
kLogPrintf("WARNING! lost event %s\n", event->tostring().c_str());
#endif
delete event; //удаляем отработанное событие
//обновляем экран
update_panels();
doupdate(); //физически выполняет перерисовку
}
//разблокируем SIGWINCH
sigprocmask(SIG_UNBLOCK, &newset, 0);
#ifdef EVENTTHREAD
usleep(10000); //10 milisec
#endif
}
while(!done);
return true;
}
boinctui-2.7.1/src/nview.cpp0000664000175000017500000001057514536642777013653 0ustar ssss// =============================================================================
// This file is part of boinctui.
// http://boinctui.googlecode.com
// Copyright (C) 2012,2013 Sergey Suslov
//
// boinctui is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// boinctui is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details
// .
// =============================================================================
#include "nview.h"
#include "ngroup.h"
#include "kclog.h"
#include иначе будет ошибка парсинга
#endif // RESULTPARSE_H
boinctui-2.7.1/src/cfg.h0000664000175000017500000000431414536642777012721 0ustar ssss// =============================================================================
// This file is part of boinctui.
// http://boinctui.googlecode.com
// Copyright (C) 2012,2013 Sergey Suslov
//
// boinctui is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// boinctui is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details
// .
// =============================================================================
#ifndef CFG_H
#define CFG_H
#include "resultdom.h"
#include "nview.h"
class Config
{
public:
Config(const char* filename);
~Config();
void load();
void save();
void generatedefault();
Item* getcfgptr() { if ( root!= NULL) return root->findItem("boinctui_cfg"); else return NULL; };
int getivalue(Item* node, const char* name); //ищет name начиная с node
int getivalue(const char* name) { return getivalue(getcfgptr(), name); }; //ищет name начиная с корня
void setivalue(Item* node, const char* name, int value); //создаст в node подэл-т name со значением value
void setivalue(const char* name, int value) { setivalue(getcfgptr(), name, value); }; //создаст в корне подэл-т name со значением value
void addhost(const char* host, const char* port, const char* pwd, const char* hostid);
bool isdefault; //true если конфиг не найден и создан дефолтный
std::string errmsg; //строка ошибки возникшей при загрузке файла конфига
std::string cmdlinehost="";
std::string cmdlineport="31416";
std::string cmdlinepwd="";
bool cmdlocalhost=false;
protected:
char* fullname; //полное имя файла
Item* root; //корень дерева конфига
};
extern Config* gCfg;
#endif //CFG_H
boinctui-2.7.1/src/ncolorstring.cpp0000664000175000017500000000555414536642777015247 0ustar ssss// =============================================================================
// This file is part of boinctui.
// http://boinctui.googlecode.com
// Copyright (C) 2012,2013 Sergey Suslov
//
// boinctui is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// boinctui is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details
// .
// =============================================================================
#include
#include "ncolorstring.h"
NColorStringPart::NColorStringPart(int attr, const char* fmt, va_list vl)
{
char buf[1024];
vsnprintf(buf, sizeof(buf), fmt, vl);
this->s = buf;
this->attr = attr;
}
NColorString::NColorString(int attr, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
vappend(attr,fmt,args);
va_end(args);
}
NColorString::NColorString(int attr, const char* fmt, va_list vl)
{
vappend(attr,fmt,vl);
}
NColorString::~NColorString()
{
std::list::iterator it;
for (it = parts.begin(); it != parts.end(); it++)
{
delete (*it);
}
}
void NColorString::append(int attr, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
NColorStringPart* part = new NColorStringPart(attr, fmt, args);
va_end(args);
append(part);
}
void NColorString::vappend(int attr, const char* fmt, va_list vl)
{
NColorStringPart* part = new NColorStringPart(attr, fmt, vl);
append(part);
}
int NColorString::getlen() //вернет длинну в ЭКРАННЫХ СИМВОЛАХ
{
int result = 0;
std::list::iterator it;
for (it = parts.begin(); it != parts.end(); it++)
{
result = result + (*it)->getlen();
}
return result;
}
NColorString& NColorString::operator=(const NColorString& v)
{
clear();
std::list::const_iterator it;
for ( it = v.parts.begin(); it != v.parts.end(); it++ )
{
append((*it)->attr, (*it)->s.c_str());
}
return *this;
}
bool NColorString::operator==(const NColorString& v)
{
bool result = true;
if (v.parts.size() != parts.size())
return false; //различается кол-во эл-тов
//сравниваем поэлементно
std::list::const_iterator it1;
std::list::const_iterator it2;
it2 = v.parts.begin();
for ( it1 = parts.begin(); it1 != parts.end(); it1++ )
{
if (*(*it1) == *(*it2))
it2++;
else
return false; //часть отличается
}
return result;
}
boinctui-2.7.1/src/tui-main.cpp0000664000175000017500000001242314536642777014240 0ustar ssss// =============================================================================
// This file is part of boinctui.
// http://boinctui.googlecode.com
// Copyright (C) 2012,2013 Sergey Suslov
//
// boinctui is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// boinctui is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details
// .
// =============================================================================
#include
#include
#include
#if HAVE_LIBNCURSESW == 1 && NCURSESW_HAVE_SUBDIR == 1
#include
#else
#include
#endif
#include
#include
#include "kclog.h"
#include "mainprog.h"
std::string locale;
void initcurses()
{
locale = setlocale(LC_ALL, NULL);
setlocale(LC_ALL, "");
setlocale(LC_MESSAGES, "");
initscr();
noecho();
curs_set(0);
keypad(stdscr,true); //разрешаем стрелки и т.п.
#ifdef ENABLEMOUSE
mousemask(ALL_MOUSE_EVENTS, NULL); // Report all mouse events
#endif
timeout(100); //ожидание для getch() 100 милисекунд
use_default_colors();
start_color();
}
void donecurses()
{
clear();
refresh();
endwin();
setlocale(LC_ALL, locale.c_str());
}
void printhelp()
{
printf
(
"\n\nusage: \n"
" boinctui [--help] [--boinchost=:] [--pwd=]\n\n"
" -b, --boinchost ip address and port of boinc server host\n"
" -p, --pwd boinc password\n"
" -h, --help print this help and exit\n"
"\nexamples: \n"
" boinctui --boinchost=192.168.1.123 --pwd=my_password -default port 31416 is used\n"
" boinctui --boinchost=192.168.1.123:31416 -connect with empty password\n"
" boinctui --boinchost=localhost -connect to localhost with defaul port and\n"
" password from /var/lib/boinc-client/gui_rpc_auth.cfg\n"
"\n"
);
}
std::string hostname2ip(std::string& hostname)
{
std::string result="";
struct hostent *he;
struct in_addr **addr_list;
if ((he=gethostbyname(hostname.c_str()))==NULL)
{
printf("cat't resolve gethostbyname");
return result;
}
addr_list = (struct in_addr **) he->h_addr_list;
for(int i=0; addr_list[i]!=NULL; i++)
{
char ip[100];
strcpy(ip,inet_ntoa(*addr_list[i]));
if(i>0)
result+=",";
result+=ip;
}
return result;
}
bool parseargs(int argc, char ** argv)
{
bool result=true;
int c;
while (1)
{
static struct option long_options[] =
{
{"help", no_argument, 0, 'h'},
{"boinchost", required_argument, 0, 'b'},
{"pwd", required_argument, 0, 'p'},
{0, 0, 0, 0}
};
int option_index = 0;
c = getopt_long (argc, argv, "hb:p:",long_options, &option_index);
if (c == -1)
break;
switch (c)
{
case 0:
if (long_options[option_index].flag != 0)
break;
printf ("option %s", long_options[option_index].name);
if (optarg)
printf (" with arg %s", optarg);
printf ("\n");
break;
case 'h':
printhelp();
result=false;
break;
case 'b':
{
gCfg->cmdlinehost=optarg;
int pos=gCfg->cmdlinehost.find_last_of(":");
if(pos!=std::string::npos)
{
gCfg->cmdlineport=gCfg->cmdlinehost.substr(pos+1);
gCfg->cmdlinehost.resize(pos);
}
char ip[100];
std::string hostip=hostname2ip(gCfg->cmdlinehost);
gCfg->cmdlocalhost=(hostip.find("127.0.0.1")!=std::string::npos);
printf ("boinc server '%s' %s %s\n"
, gCfg->cmdlinehost.c_str()
,(gCfg->cmdlinehost!=hostip)?hostip.c_str():""
,(gCfg->cmdlocalhost)?"(local host)":""
);
printf ("boinc server TCP port '%s'\n", gCfg->cmdlineport.c_str());
break;
}
case 'p':
gCfg->cmdlinepwd=optarg;
break;
case '?':
result=false;
break;
default:
break;
}
}
return result;
}
int main(int argc, char ** argv)
{
MainProg* mainprog;
kLogOpen("boinctui.log");
#ifdef DEBUG
struct mallinfo minf1 = mallinfo();
#endif
gCfg = new Config(".boinctui.cfg");
if(parseargs(argc,argv))
{
initcurses();
mainprog = new MainProg();
mainprog->refresh();
mainprog->mainloop(); //запускаем осн. цикл событий
delete mainprog;
donecurses();
}
#ifdef DEBUG
struct mallinfo minf2 = mallinfo();
kLogPrintf("mallinfo.uordblks= %d-%d = %d (bytes leak)\n",minf1.uordblks,minf2.uordblks, minf2.uordblks-minf1.uordblks);
//malloc_stats();
#endif
kLogClose();
exit(EXIT_SUCCESS);
}
boinctui-2.7.1/src/nview.h0000664000175000017500000000677414536642777013326 0ustar ssss// =============================================================================
// This file is part of boinctui.
// http://boinctui.googlecode.com
// Copyright (C) 2012,2013 Sergey Suslov
//
// boinctui is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// boinctui is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details
// .
// =============================================================================
#ifndef NVIEW_H
#define NVIEW_H
#include
#if HAVE_LIBNCURSESW == 1 && NCURSESW_HAVE_SUBDIR == 1
#include
#else
#include
#endif
#include "nrect.h"
#include "nevent.h"
class NGroup;
void initcolorpairs();
int getcolorpair(int fcolor, int bcolor); //получить пару для комбинации цветов
int getbgcolor(); //вернет цвет бакграунда (в зависимости от настройки transparentbg)
extern int asciilinedraw; //1-рисовать рамки символами +----+
extern int transparentbg; //1-прозрачный бэкграунд
class NView //базовый визуальный класс
{
public:
NView(NRect rect);
virtual ~NView() { del_panel(pan); delwin(win); };
//virtual void draw() {};
virtual void resize(int rows, int cols);
virtual void move(int begrow, int begcol);
PANEL* getpan() { return pan; }; //!!!!!!!!!!!!!!!!!!!!
int getwidth() { return rect.cols; }; //ширина в символах
int getheight() { return rect.rows; }; //высота в строках
int getbegrow() { return rect.begrow; }; //начальная строка
int getbegcol() { return rect.begcol; }; //начальный столбец
void erase() { werase(win); }; //очистить
bool isinside(int row, int col); //true если координаты внутри окна (row col абсолютные!)
virtual void refresh(); //перерисовать
virtual void setneedrefresh() { needrefresh = true; };
virtual void eventhandle(NEvent* ev) {/*EMPTY*/}; //обработчик событий
virtual void putevent(NEvent* ev); //отправить событие по цепочке владельцев в очередь
void setowner(NGroup* owner);
virtual const char* getid() { return typeid(*this).name(); }; //возвращает имя класса
virtual bool ismodal() { return modalflag; };
protected:
NGroup* owner; //владелец эл-та
WINDOW* win; //окно curses
PANEL* pan; //панель curses на основе окна win
bool needrefresh; //устанавливается в true когда нужна перерисовка
#ifdef DEBUG
int refreshcount; //счетчик обновлений
#endif
bool modalflag; //true если этот эл-т модальный
int getabsbegrow(); //получить начальную строку (абсолютную на экране)
int getabsbegcol(); //получить начальный столбец (абсолютный на экране)
private:
NRect rect; //координаты и размер
};
#endif //NVIEW_Hboinctui-2.7.1/src/about.h0000664000175000017500000000216214536642777013273 0ustar ssss// =============================================================================
// This file is part of boinctui.
// http://boinctui.googlecode.com
// Copyright (C) 2012,2013 Sergey Suslov
//
// boinctui is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// boinctui is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details
// .
// =============================================================================
#ifndef ABOUT_H
#define ABOUT_H
#include "ngroup.h"
class AboutWin : public NGroup
{
public:
AboutWin(int rows, int cols);
~AboutWin() { delete caption; };
virtual void eventhandle(NEvent* ev); //обработчик событий
protected:
char* caption; //строка заголовка
};
#endif //ABOUT_Hboinctui-2.7.1/src/helpwin.h0000664000175000017500000000224714536642777013633 0ustar ssss// =============================================================================
// This file is part of boinctui.
// http://boinctui.googlecode.com
// Copyright (C) 2012,2013 Sergey Suslov
//
// boinctui is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// boinctui is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details
// .
// =============================================================================
#ifndef HELPWIN_H
#define HELPWIN_H
#include "ngroup.h"
#include "nstatictext.h"
class HelpWin : public NGroup
{
public:
HelpWin(int rows, int cols);
~HelpWin() { delete caption; };
virtual void eventhandle(NEvent* ev); //обработчик событий
protected:
char* caption; //строка заголовка
NStaticText* text1;
};
#endif //HELPWIN_Hboinctui-2.7.1/src/nscrollview.cpp0000664000175000017500000001602714536642777015070 0ustar ssss// =============================================================================
// This file is part of boinctui.
// http://boinctui.googlecode.com
// Copyright (C) 2012,2013 Sergey Suslov
//
// boinctui is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// boinctui is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details
// .
// =============================================================================
#include "nscrollview.h"
NScrollView::~NScrollView()
{
clearcontent();
}
void NScrollView::addstring(int attr, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
NColorString* cs = new NColorString(attr, fmt, args);
va_end(args);
addstring(cs);
}
void NScrollView::clearcontent()
{
std::vector::iterator it;
for (it = content.begin(); it != content.end(); it++)
{
delete (*it);
}
content.clear();
startindex=0;
needrefresh = true;
}
void NScrollView::drawcontent() //отрисовывает буфер строк
{
//выводим строки начиная со startindex
for (int line = 0; line < getheight(); line++) //цикл по экранным строкам
{
if (startindex+line < (int)content.size())
{
NColorString* cstring = content[startindex + line];
std::list::iterator it;
wmove(win,line,0);
for (it = cstring->parts.begin(); it != cstring->parts.end(); it++) //цикл по частям тек строки
{
NColorStringPart* part = *it;
wattrset(win,part->attr); //включаем атрибут
wprintw(win,"%s",part->s.c_str());
// wattrset(win,0); //отключаем атрибут
}
wclrtoeol(win); //очищаем до конца строки
}
else //очищаем нижнюю незанятую часть окна (если есть)
{
wmove(win,line,0);
wclrtoeol(win); //очищаем до конца строки
}
}
if (scrollbar) //если есть связанный скроллбар то обновляем его
{
scrollbar->setpos(0,content.size(),startindex, startindex+getheight());
}
}
void NScrollView::refresh()
{
if (needrefresh)
{
drawcontent();
NView::refresh();
}
}
void NScrollView::resize(int rows, int cols)
{
NView::resize(rows, cols);
if (autoscroll)
{
setautoscroll(true); //костыль чтобы при ресайзе переустановилась позиция при автоскроле
}
}
void NScrollView::scrollto(int delta)//сдвинуть отображение на drlta строк вверх или вниз
{
if ((int)content.size()>getheight())
{
//kLogPrintf("NScrollView::scrollto(%d) startindex=%d content.size()=%d getheight()=%d\n",delta, startindex, content.size(), getheight());
int oldstartindex = startindex;
startindex = startindex + delta;
if ( startindex < 0 )
startindex = 0;
if ( startindex > (int)content.size()-getheight() )
startindex = content.size()-getheight()/* + 1*/; //+1 чтобы оставлять пустую строку
if (oldstartindex != startindex) //позиция изменилась нужно перерисовываться
needrefresh = true;
}
};
void NScrollView::setautoscroll(bool b) //true чтобы включить автоскроллинг
{
int oldstartindex = startindex;
autoscroll = b;
if (b)
{
startindex = content.size()-getheight();
if ( startindex < 0 )
startindex = 0;
}
if (oldstartindex != startindex) //позиция изменилась нужно перерисовываться
needrefresh = true;
};
void NScrollView::setstartindex(int n) //установить отображение со строки n
{
if (((int)content.size()-n) < getheight()) //последняя строка видимая на экране
{
startindex = content.size()-getheight(); //поднять вверх
if (startindex < 0) //но не выше нулевой
startindex = 0;
}
else
startindex = n;
}
int NScrollView::getmaxcontentwidth() //вернет максимальную длину строки (в экранных символях) в content
{
int result = 0;
std::vector::iterator it;
for(it = content.begin(); it != content.end(); it++)
{
if (result < (*it)->getlen())
{
result = (*it)->getlen();
}
}
return result;
}
void NScrollView::eventhandle(NEvent* ev) //обработчик событий
{
NView::eventhandle(ev); //предок
if ( ev->done )
return;
//реакция на мышь
NMouseEvent* mevent = (NMouseEvent*)ev;
if ( ev->type == NEvent::evMOUSE )
{
//скроллинг по колесу
if (isinside(mevent->row, mevent->col))
{
//колесо вверх
#if NCURSES_MOUSE_VERSION > 1
if (mevent->cmdcode & BUTTON4_PRESSED) //NOT TESTED
#else
if (mevent->cmdcode & BUTTON4_PRESSED)
#endif
{
scrollto(-getheight()/2); //вверх на полокна
setautoscroll(false);
ev->done = true;
}
//колесо вниз
#if NCURSES_MOUSE_VERSION > 1
if (mevent->cmdcode & BUTTON5_PRESSED) //NOT TESTED
#else
if ( mevent->cmdcode & (BUTTON2_PRESSED | REPORT_MOUSE_POSITION)) //REPORT_MOUSE_POSITION подпорка иначе теряет эвенты при быстрой прокрутке вниз
#endif
{
if (!getautoscroll())
{
int oldpos = getstartindex();
scrollto(getheight()/2); //вниз на пол окна
if ( oldpos == getstartindex()) //позиция не изменилась (уже достигли конца)
setautoscroll(true); //включаем автоскроллинг
ev->done = true;
}
}
}
}
//клавиатура
/*
if ( ev->type == NEvent::evKB )
{
ev->done = true;
switch(ev->keycode)
{
case KEY_PPAGE:
content->scrollto(-getheight()/2); //вверх на полокна
content->setautoscroll(false);
break;
case KEY_NPAGE:
if (!content->getautoscroll())
{
int oldpos = content->getstartindex();
content->scrollto(getheight()/2); //вниз на пол окна
if ( oldpos == content->getstartindex()) //позиция не изменилась (уже достигли конца)
content->setautoscroll(true); //включаем автоскроллинг
}
break;
default:
//блокировать все клавиатурные кроме кода закрытия формы
if (ev->keycode == 27)
ev->done = false;
} //switch
}
*/
if (ev->done) //если обработали, то нужно перерисоваться
refresh();
}
boinctui-2.7.1/src/nevent.h0000664000175000017500000000471514536642777013466 0ustar ssss// =============================================================================
// This file is part of boinctui.
// http://boinctui.googlecode.com
// Copyright (C) 2012,2013 Sergey Suslov
//
// boinctui is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// boinctui is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details
// .
// =============================================================================
#ifndef NEVENT_H
#define NEVENT_H
#ifdef DEBUG
#include
#include
#endif
//#include "kclog.h"
class NEvent //класс описывающий событие создаваемое например при нажатии клавиш
{
public:
enum Type { evKB, evMOUSE, evPROG, evTIMER }; //evPROG событие генерируемое самой прораммой
NEvent(NEvent::Type type, int keycode) { this->type = type; this->done = false; this->keycode = keycode;};
virtual ~NEvent() { /*kLogPrintf("~NEvent()\n");*/ };
NEvent::Type type;
bool done; //true если обработано
union
{
int keycode; //код клавиатуры
int cmdcode; //произвольный код команды
};
#ifdef DEBUG
virtual std::string tostring()
{
std::stringstream s;
s << this << " " << type << "(";
switch (type)
{
case evKB:
s << "evKB keycode=" << keycode;
break;
case evMOUSE:
s << "evMOUSE";
break;
case evPROG:
s << "evPROG";
break;
case evTIMER:
s << "evTIMER";
break;
};
s << ")";
return s.str();
};
#endif
};
class NMouseEvent : public NEvent
{
public:
NMouseEvent(int bstate, int row, int col) : NEvent(evMOUSE, bstate) //bstate (see mmask_t ncurses.h)
{
this->col = col;
this->row = row;
};
virtual ~NMouseEvent() { /*kLogPrintf("~NMouseEvent()\n");*/ };
int row;
int col;
#ifdef DEBUG
virtual std::string tostring()
{
std::stringstream s;
s << NEvent::tostring() << "{row=" << row << ",col=" << col << ",bstate=" << std::hex << cmdcode;
s << "}";
return s.str();
};
#endif
};
#endif //NEVENT_Hboinctui-2.7.1/src/nrect.h0000664000175000017500000000241214536642777013272 0ustar ssss// =============================================================================
// This file is part of boinctui.
// http://boinctui.googlecode.com
// Copyright (C) 2012,2013 Sergey Suslov
//
// boinctui is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// boinctui is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details
// .
// =============================================================================
#ifndef NRECT_H
#define NRECT_H
class NRect //прямоугольная область //нумерация строк и столбцов идет от 0
{
public:
NRect() {};
NRect(int rows, int cols, int begrow, int begcol) {this->begrow = begrow; this->begcol = begcol; this->rows = rows; this->cols = cols;};
int begrow;
int begcol;
int rows; //высота (число строк)
int cols; //ширина (число колонок)
};
#endif //NRECT_Hboinctui-2.7.1/src/nmessagebox.h0000664000175000017500000000331614536642777014476 0ustar ssss// =============================================================================
// This file is part of boinctui.
// http://boinctui.googlecode.com
// Copyright (C) 2012,2013 Sergey Suslov
//
// boinctui is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// boinctui is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details
// .
// =============================================================================
#ifndef NMESSAGEBOX_H
#define NMESSAGEBOX_H
#include
#include "ngroup.h"
#include "nstatictext.h"
#include "tuievent.h"
class NMButton : public NStaticText //кнопка внутри NMessageBox
{
public:
NMButton(const char* text, NEvent* pevent, ...);
~NMButton() { if (pevent) delete pevent; };
void eventhandle(NEvent* ev); //обработчик событий
private:
NEvent* pevent; //евент генерируемый кнопкой при нажатии
std::list keys; //на какие коды она реагирует
};
class NMessageBox : public NGroup //стандартный диалог вида Ok/Cancel или Yes/No
{
public:
NMessageBox(const char* text);
void eventhandle(NEvent* ev); //обработчик событий
void addbutton(NMButton* button); //добавить кнопку
private:
NStaticText* content;
};
#endif //NMESSAGEBOX_Hboinctui-2.7.1/src/nselectlist.cpp0000664000175000017500000001115014536642777015042 0ustar ssss// =============================================================================
// This file is part of boinctui.
// http://boinctui.googlecode.com
// Copyright (C) 2012,2013 Sergey Suslov
//
// boinctui is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// boinctui is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details
// .
// =============================================================================
#include
#include
#include "nselectlist.h"
#include "kclog.h"
void NSelectList::addstring(void* userobj, int attr, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
NColorString* cs = new NColorString(attr, fmt, args);
va_end(args);
NScrollView::addstring(cs);
objects.push_back(userobj);
}
void NSelectList::addstring(void* userobj, NColorString* cstring)
{
NScrollView::addstring(cstring);
objects.push_back(userobj);
}
void NSelectList::drawcontent() //отрисовывает буфер строк
{
//выводим строки начиная со startindex
for (int line = 0; line < getheight(); line++) //цикл по экранным строкам
{
if (startindex+line < (int)content.size()) //цикл по строкам
{
NColorString* cstring = content[startindex + line];
std::list::iterator it;
wmove(win,line,0);
for (it = cstring->parts.begin(); it != cstring->parts.end(); it++) //цикл по частям тек строки
{
NColorStringPart* part = *it;
if ((!selectorenable)||(startindex + line != selectedindex)) //эта строка не выделена или селектор выключен
wattrset(win,part->attr); //включаем атрибут
else
{
//получаем из атрибута цвета для текста и фона
short f,b;
f = b = 0;
unsigned int a = 0;
a = a | (part->attr & A_BOLD); //нужен-ли аттрибут
pair_content(PAIR_NUMBER(part->attr),&f,&b); //цвета тек куска для пары с номером PAIR_NUMBER(part->attr)
//kLogPrintf("part->attr=%X PAIR_NUMBER(%X) -> #%d f=%x b=%x attr=%x\n",part->attr, part->attr,PAIR_NUMBER(part->attr),f,b,a);
//kLogPrintf("A_BOLD=%X\n",A_BOLD);
wattrset(win, getcolorpair(f, selectorbgcolor) | a); //включаем новый цвет и атрибут
}
wprintw(win,"%s",part->s.c_str());
} //цикл частей одной строки
//wattrset(win,0); //отключаем атрибут
//очищаем до конца строки
if ((!selectorenable)||(startindex + line != selectedindex))
wclrtoeol(win);
else
{
wbkgdset(win,getcolorpair(COLOR_WHITE,selectorbgcolor));
wclrtoeol(win); //очищаем до конца строки
wbkgdset(win,getcolorpair(COLOR_WHITE, getbgcolor()));
}
}
else //очищаем нижнюю незанятую часть окна (если есть)
{
wmove(win,line,0);
wclrtoeol(win); //очищаем до конца строки
}
}
if (scrollbar) //если есть связанный скроллбар то обновляем его
{
scrollbar->setpos(0,content.size(),startindex, startindex+getheight());
}
}
void NSelectList::refresh()
{
if (needrefresh)
{
drawcontent();
NView::refresh(); //Именно так!!!
}
}
void* NSelectList::getselectedobj()
{
if ((selectedindex >= 0)&&(selectedindex < (int)objects.size()))
{
return objects[selectedindex];
}
else
return NULL;
}
void NSelectList::selectorup()
{
if (selectedindex >= 0)
{
selectedindex--;
needrefresh = true;
//проверяем не нужно ли скролить
if (selectedindex - startindex < 4) //видимых строк выше серлектора осталось
{
scrollto(-1);
}
}
}
void NSelectList::selectordown()
{
if (selectedindex < (int)content.size())
{
selectedindex++;
needrefresh = true;
//проверяем не нужно ли скролить
if ((startindex + getheight() < (int)content.size())&&(startindex + getheight() - selectedindex < 4)) //видимых строк ниже серлектора осталось
{
scrollto(1);
}
}
}
boinctui-2.7.1/src/nwin.h0000664000175000017500000000152214536642777013133 0ustar ssss// =============================================================================
// This file is part of boinctui.
// http://boinctui.googlecode.com
// Copyright (C) 2012,2013 Sergey Suslov
//
// boinctui is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// boinctui is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details
// .
// =============================================================================
#ifndef NWIN_H
#define NWIN_H
#endif //NWIN_Hboinctui-2.7.1/src/statwin.cpp0000664000175000017500000002360714536642777014214 0ustar ssss// =============================================================================
// This file is part of boinctui.
// http://boinctui.googlecode.com
// Copyright (C) 2012-2014 Sergey Suslov
//
// boinctui is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// boinctui is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details
// .
// =============================================================================
#include
#include
#include