void CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_vfprintf_32_bad()
{
    wchar_t * data;
    wchar_t * *dataPtr1 = &data;
    wchar_t * *dataPtr2 = &data;
    wchar_t dataBuffer[100] = L"";
    data = dataBuffer;
    {
        wchar_t * data = *dataPtr1;
        {
#ifdef _WIN32
            WSADATA wsaData;
            int wsaDataInit = 0;
#endif
            int recvResult;
            struct sockaddr_in service;
            wchar_t *replace;
            SOCKET connectSocket = INVALID_SOCKET;
            size_t dataLen = wcslen(data);
            do
            {
#ifdef _WIN32
                if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
                {
                    break;
                }
                wsaDataInit = 1;
#endif
                /* POTENTIAL FLAW: Read data using a connect socket */
                connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
                if (connectSocket == INVALID_SOCKET)
                {
                    break;
                }
                memset(&service, 0, sizeof(service));
                service.sin_family = AF_INET;
                service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
                service.sin_port = htons(TCP_PORT);
                if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
                {
                    break;
                }
                /* Abort on error or the connection was closed, make sure to recv one
                 * less char than is in the recv_buf in order to append a terminator */
                /* Abort on error or the connection was closed */
                recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(wchar_t) * (100 - dataLen - 1), 0);
                if (recvResult == SOCKET_ERROR || recvResult == 0)
                {
                    break;
                }
                /* Append null terminator */
                data[dataLen + recvResult / sizeof(wchar_t)] = L'\0';
                /* Eliminate CRLF */
                replace = wcschr(data, L'\r');
                if (replace)
                {
                    *replace = L'\0';
                }
                replace = wcschr(data, L'\n');
                if (replace)
                {
                    *replace = L'\0';
                }
            }
            while (0);
            if (connectSocket != INVALID_SOCKET)
            {
                CLOSE_SOCKET(connectSocket);
            }
#ifdef _WIN32
            if (wsaDataInit)
            {
                WSACleanup();
            }
#endif
        }
        *dataPtr1 = data;
    }
    {
        wchar_t * data = *dataPtr2;
        badVaSink(data, data);
    }
}
Esempio n. 2
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    // Setup this MainWindow with the parameters mainwindow.ui:
    // Definition of size, creation of widgets inside etc..
    ui->setupUi(this);

    // Retrieve pointers of widgets already created by the up operation
    // Those who will be used again outside the creator are saved at class variables
    QMenuBar * menuBar = ui->menuBar;
    QSlider *slider_color = ui->verticalSlider;
    QSlider *slider_style = ui->verticalSlider_2;
    QToolBar * toolbar = ui->toolBar;
    mydrawzone = ui->widget;

    // Declaration of menus and adition inside menubar
    QMenu * openMenu = menuBar->addMenu( tr("&Open"));
    QMenu * saveMenu = menuBar->addMenu( tr("&Save"));
    QMenu * quitMenu = menuBar->addMenu( tr("&Quit"));
    QMenu * penMenu = menuBar->addMenu( tr("&Pen Settings"));
    QMenu * colorMenu = menuBar->addMenu( tr("&Color Settings"));
    QMenu * styleMenu = menuBar->addMenu( tr("&Style Settings"));
    QMenu * formMenu = menuBar->addMenu( tr("&Form Settings"));

    // Declaration of principal actions
    // Those that will be shown at the toolbar
    QAction * openAction = new QAction( QIcon(":/icons/open.png"), tr("&Open"), this);
    QAction * saveAction = new QAction( QIcon(":/icons/save.png"), tr("&Save"), this);
    QAction * quitAction = new QAction( QIcon(":/icons/quit.png"), tr("&Quit"), this);
    QAction * paintAction = new QAction( QIcon(":/icons/paint.png"), tr("&Paint"), this);
    QAction * editAction = new QAction( QIcon(":/icons/edit.png"), tr("&Edit"), this);
    QAction * moveAction = new QAction( QIcon(":/icons/move.png"), tr("&Edit"), this);

    // Declaration of some other actions
    // Those that will have shortcuts as well but wont be shown in the toolbar
    QAction *set_pen_color =new QAction(tr("Alternate Color Pen"), this);
    QAction *set_pen_width_larger =new QAction(tr("&Pen Width +"), this);
    QAction *set_pen_width_shorter =new QAction(tr("&Pen Width -"), this);
    QAction *set_pen_style =new QAction(tr("&Alternate Style Pen"), this);
    QAction *set_figure_form =new QAction(tr("&Alternate Figure Form"), this);
    QAction *undo =new QAction(tr("&Undo"), this);

    // Declaration of action groups
    // The pointers for the actions are saved inside class variables
    // to be used outside the class creator
    QActionGroup *action_group_color = new QActionGroup(this);
    color0 = action_group_color->addAction(tr("Black Pen"));
    color1 = action_group_color->addAction(tr("White Pen"));
    color2 = action_group_color->addAction(tr("Dark Gray Pen"));
    color3 = action_group_color->addAction(tr("Gray Pen"));
    color4 = action_group_color->addAction(tr("Light Gray Pen"));
    color5 = action_group_color->addAction(tr("Red Pen"));
    color6 = action_group_color->addAction(tr("Green Pen"));
    color7 = action_group_color->addAction(tr("Blue Pen"));
    color8 = action_group_color->addAction(tr("Cyan Pen"));
    color9 = action_group_color->addAction(tr("Magenta Pen"));
    color10 = action_group_color->addAction(tr("Yellow Pen"));
    color11 = action_group_color->addAction(tr("Dark Red Pen"));
    color12 = action_group_color->addAction(tr("Dark Green Pen"));
    color13 = action_group_color->addAction(tr("Dark Blue Pen"));
    color14 = action_group_color->addAction(tr("Dark Cyan Pen"));
    color15 = action_group_color->addAction(tr("Dark Magenta Pen"));
    color16 = action_group_color->addAction(tr("Dark Yellow Pen"));
    color17 = action_group_color->addAction(tr("Transparent"));

    QActionGroup *action_group_style = new QActionGroup(this);
    style0 = action_group_style->addAction(tr("Solid Pen"));
    style1 = action_group_style->addAction(tr("Dash Line Pen"));
    style2 = action_group_style->addAction(tr("Dot Line Pen"));
    style3 = action_group_style->addAction(tr("Dash dot Line Pen"));
    style4 = action_group_style->addAction(tr("Dash Dot Dot Line Pen"));
    style5 = action_group_style->addAction(tr("Custom Dash Line Pen"));

    QActionGroup *action_group_form = new QActionGroup(this);
    form0 = action_group_form->addAction(tr("Line Form"));
    form1 = action_group_form->addAction(tr("Rectangle Form"));
    form2 = action_group_form->addAction(tr("Elipse Form"));

    // Adition of shortcuts for principal actions
    openAction->setShortcut( tr("Ctrl+O"));
    saveAction->setShortcut( tr("Ctrl+S"));
    quitAction->setShortcut( tr("Ctrl+Q"));
    paintAction->setShortcut( tr("Ctrl+P"));
    editAction->setShortcut( tr("Ctrl+E"));
    moveAction->setShortcut( tr("Ctrl+M"));

    // Adition of shortcuts for those other actions
    set_pen_color->setShortcut( tr("Ctrl+C"));
    set_pen_style->setShortcut( tr("Ctrl+Space"));
    set_pen_width_larger->setShortcut( tr("Ctrl++"));
    set_pen_width_shorter->setShortcut( tr("Ctrl+-"));
    set_figure_form->setShortcut( tr("Ctrl+F"));
    undo->setShortcut(tr ("Ctrl+Z"));

    // Adition of tool tips for principal actions
    openAction->setToolTip( tr("Open file"));
    saveAction->setToolTip( tr("Save file"));
    quitAction->setToolTip( tr("Quit file"));

    // Adition of status tips for principal actions
    openAction->setStatusTip( tr("Open file"));
    saveAction->setStatusTip( tr("Save file"));
    quitAction->setStatusTip( tr("Quit file"));

    // Adition of actions to menus
    openMenu->addAction(openAction);
    saveMenu->addAction(saveAction);
    quitMenu->addAction(quitAction);

    penMenu->addAction(set_pen_width_larger);
    penMenu->addAction(set_pen_width_shorter);
    penMenu->addAction(undo);

    colorMenu->addAction(set_pen_color);
    colorMenu->addActions(action_group_color->actions());

    styleMenu->addAction(set_pen_style);
    styleMenu->addActions(action_group_style->actions());

    formMenu->addAction(set_figure_form);
    formMenu->addActions(action_group_form->actions());

    // Adition of principal actions to toolbar
    toolbar->addAction(openAction);
    toolbar->addAction(saveAction);
    toolbar->addAction(quitAction);
    toolbar->addAction(paintAction);
    toolbar->addAction(editAction);
    toolbar->addAction(moveAction);

    // Set some parameters to the sliders
    slider_color->setTickPosition(QSlider::TicksBothSides);
    slider_color->setMinimum(0);
    slider_color->setMaximum(17);
    slider_color->setSingleStep(1);

    slider_style->setTickPosition(QSlider::TicksBothSides);
    slider_style->setMinimum(0);
    slider_style->setMaximum(5);
    slider_style->setSingleStep(1);

    // Link actions and signals to slots
    connect(openAction, SIGNAL(triggered( )), this, SLOT(openFile()));
    connect(saveAction, SIGNAL(triggered( )), this, SLOT(saveFile()));
    connect(quitAction, SIGNAL(triggered( )), this, SLOT(quitApp()));

    connect(paintAction, SIGNAL(triggered( )), mydrawzone, SLOT(set_draw_mode_paint()));
    connect(editAction, SIGNAL(triggered( )), mydrawzone, SLOT(set_draw_mode_edit()));
    connect(moveAction, SIGNAL(triggered( )), mydrawzone, SLOT(set_draw_mode_move()));
    connect(set_pen_width_larger, SIGNAL(triggered( )), mydrawzone, SLOT(set_pen_width_larger()));
    connect(set_pen_width_shorter, SIGNAL(triggered( )), mydrawzone, SLOT(set_pen_width_shorter()));
    connect(undo, SIGNAL(triggered( )), mydrawzone, SLOT(undo()));

    connect(set_pen_color, SIGNAL(triggered( )), mydrawzone, SLOT(set_pen_color()));
    connect(action_group_color, SIGNAL(triggered(QAction *)), this, SLOT(doIt(QAction *)));
    connect(this, SIGNAL(color_pen_changed(int)), mydrawzone, SLOT(set_pen_color(int)));

    connect(set_pen_style, SIGNAL(triggered( )), mydrawzone, SLOT(set_pen_style()));
    connect(action_group_style, SIGNAL(triggered(QAction *)), this, SLOT(doIt2(QAction *)));
    connect(this, SIGNAL(style_pen_changed(int)), mydrawzone, SLOT(set_pen_style(int)));

    connect(set_figure_form, SIGNAL(triggered( )), mydrawzone, SLOT(set_figure_form()));
    connect(action_group_form, SIGNAL(triggered(QAction *)), this, SLOT(doIt3(QAction *)));
    connect(this, SIGNAL(form_painter_changed(int)), mydrawzone, SLOT(set_figure_form(int)));

    connect(slider_color, SIGNAL(valueChanged(int)), this, SLOT(slide_color_pen_changed(int)));
    connect(slider_style, SIGNAL(valueChanged(int)), this, SLOT(slide_style_pen_changed(int)));
}
Esempio n. 3
0
File: ftp.c Progetto: maplefish/MICO
// Analyze FTP server response and take some action
// Server response is in recvBuf
//--------------------------
static void response( void )
{
  if (!(status & FTP_CONNECTED)) return;
  if (recvBuf == NULL) return;

  uint16_t cmd = 0;
  
  if (*(recvBuf+3) != ' ') {
    _setResponse(cmd);
    return;
  }
  *(recvBuf+3) = '\0';
  cmd = atoi(recvBuf);
  if (cmd == 0) {
    _setResponse(cmd);
    return;
  }
  recvLen -= 4;
  memmove(recvBuf, (recvBuf+4), recvLen);
  *(recvBuf+recvLen) = '\0';
  
  
  if (cmd == 220) {
    ftp_log("[FTP cmd] Send user: %s\r\n",ftpuser);
    char tmps[100];
    sprintf(tmps,"USER %s\r\n",ftpuser);
    _send(&tmps[0], strlen(ftpuser)+7);
  }
  else if (cmd == 331) {
    ftp_log("[FTP cmd] Send pass: %s\r\n",ftppass);
    char tmps[100];
    sprintf(tmps,"PASS %s\r\n", ftppass);
    _send(&tmps[0], strlen(ftppass)+7);
  }
  else if (cmd == 230) {
    if (ftppass != NULL) {
      free(ftppass);
      ftppass = NULL;
    }
    if (ftpuser != NULL) {
      free(ftpuser);
      ftpuser = NULL;
    }
    _send("TYPE I\r\n", 8);

    ftp_log("[FTP cmd] Login OK.\r\n");
    status |= FTP_LOGGED;
    ftpCmdSocket->clientFlag = REQ_ACTION_LOGGED;
  }
  else if (cmd == 530) {
    ftp_log("[FTP cmd] Login authentication failed\r\n");
    ftpCmdSocket->clientFlag = REQ_ACTION_QUIT;
  }
  else if (cmd == 221) {
    ftp_log("[FTP cmd] Request Logout\r\n");
    ftpCmdSocket->clientFlag = REQ_ACTION_DISCONNECT;
  }
  else if (cmd == 226) {
    // Closing data connection
    _setResponse(cmd);
  }
  else if (cmd == 250) {
    // Requested file action okay, completed
    _setResponse(cmd);
  }
  else if (cmd == 257) {
    // Pathname
    _setResponse(cmd);
    if (ftpresponse != NULL) {
      uint16_t i;
      for (i = 0; i<strlen(ftpresponse); i++) {
        if (*(recvBuf+i) == '"') break;
      }
      if (i<strlen(ftpresponse)) {
        memmove(ftpresponse, ftpresponse+i+1, strlen(ftpresponse)-i);
        for (i=strlen(ftpresponse)-1; i>0; i--) {
          if (*(ftpresponse+i) == '"') *(ftpresponse+i) = '\0';
        }
      }
    }
  }
  else if ((cmd == 150) || (cmd == 125)) {
    // mark: Accepted data connection
    if ((ftpfile != NULL) && ftpDataSocket != NULL) {
      status |= FTP_SENDING;
      if ((send_type & SEND_STRING)) {
        ftp_log("[FTP dta] Sending string to %s (%d)\r\n", ftpfile, file_size);
      }
      else {
        ftp_log("[FTP dta] Sending file %s (%d)\r\n", ftpfile, file_size);
      }
    }
    else _setResponse(cmd);
  }
  else if (cmd == 227) {
    // entering passive mod
    char *tStr = strtok(recvBuf, "(,");
    uint8_t array_pasv[6];
    for ( int i = 0; i < 6; i++) {
      tStr = strtok(NULL, "(,");
      if (tStr != NULL) {
        array_pasv[i] = atoi(tStr);
      }
      else {
        array_pasv[i] = 0;
      }
    }
    uint32_t dataPort, dataServ;
    dataPort = (uint32_t)((array_pasv[4] << 8) + (array_pasv[5] & 255));
    dataServ = (uint32_t)((array_pasv[0] << 24) + (array_pasv[1] << 16) + (array_pasv[2] << 8) + (array_pasv[3] & 255));

    if ((dataServ != 0) && (dataPort != 0)) {
      // connect data socket
      if (_openDataSocket() >= 0) {
        ftpDataSocket->addr.s_ip = dataServ;
        ftpDataSocket->addr.s_port = dataPort;

        char ip[17]; memset(ip, 0x00, 17);
        inet_ntoa(ip, ftpDataSocket->addr.s_ip);
        ftp_log("[FTP dta] Opening data connection to: %s:%d\r\n", ip, ftpDataSocket->addr.s_port);

        struct sockaddr_t *paddr = &(ftpDataSocket->addr);
        int slen = sizeof(ftpDataSocket->addr);
      
        //_micoNotify will be called if connected
        int stat = connect(ftpDataSocket->socket, paddr, slen);
        if (stat < 0) {
          ftp_log("[FTP dta] Data connection error: %d\r\n", stat);
          ftpCmdSocket->clientFlag = NO_ACTION;
          ftpCmdSocket->clientLastFlag = NO_ACTION;
          data_done = 1;
          file_status = -9;
          closeDataSocket();
        }
        else {
          // Data socket connected, initialize action
          if (ftpCmdSocket->clientLastFlag == REQ_ACTION_LIST) {
            ftpCmdSocket->clientLastFlag = NO_ACTION;
            ftpCmdSocket->clientFlag = REQ_ACTION_DOLIST;
          }
          else if (ftpCmdSocket->clientLastFlag == REQ_ACTION_RECV) {
            ftpCmdSocket->clientLastFlag = NO_ACTION;
            ftpCmdSocket->clientFlag = REQ_ACTION_DORECV;
          }
          else if (ftpCmdSocket->clientLastFlag == REQ_ACTION_SEND) {
            ftpCmdSocket->clientLastFlag = NO_ACTION;
            ftpCmdSocket->clientFlag = REQ_ACTION_DOSEND;
          }
        }
      }
    }
    else {
      ftp_log("[FTP dta] Wrong pasv address:port received!\r\n");
      ftpCmdSocket->clientFlag = REQ_ACTION_DISCONNECT;
    }
  }
  else _setResponse(cmd);
}
Esempio n. 4
0
long tcp_connect(bmdnet_handler_ptr handler,char*host,long port)
{
	long status;
#ifndef _WIN32
	char aux[256];
	struct sockaddr_in serv_addr;
	struct hostent hostinfo_buf;
	struct hostent *hostinfo=&hostinfo_buf;
	long one = 1;
	int si_temp; /* to musi byc int - nie zmieniac !!!! */
#else
	struct addrinfo *result = NULL, hints;
	char * portstr=NULL;
#endif
	if (host == NULL || port == 0 || port > 65535)
	{
		return(-1);
	}

	handler->s = (long)socket(AF_INET, SOCK_STREAM,IPPROTO_TCP);
	if (handler->s <= 0)
		return -1;

#ifndef WIN32
	if (setsockopt(handler->s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
	{
		return ERR(ERR_net, "Cannot set SO_REUSEADDR flag on socket", "LK");
	}
	memset(&serv_addr, 0, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons((short)port);

	if( gethostbyname_r(host, &hostinfo_buf, aux, sizeof(aux), &hostinfo, &si_temp) != 0 )
	{
		PRINT_ERROR("gethostbyname_r failed.\n");
		return(-1);
	}
	if (hostinfo==NULL) {
		PRINT_ERROR("Hostname not found.\n");
		return(-1);
	}
	serv_addr.sin_addr=*(struct in_addr *)hostinfo->h_addr;
	status = connect(handler->s, (const struct sockaddr *)&serv_addr,sizeof(serv_addr));
	if (status)
	{
		PRINT_ERROR("Cannot connect to host.\n");
		return(-1);
	}
#else
	ZeroMemory( &hints, sizeof(hints) );
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;
	portstr = calloc(6,sizeof(char));
	_itoa_s(port, portstr, 6,10);
	status = getaddrinfo(host, portstr, &hints, &result);
	if( status == WSAHOST_NOT_FOUND )
	{
		BMD_FOK(BMD_ERR_NET_RESOLV);
	}
	else
		if( status != 0 )
		{
			BMD_FOK(BMD_ERR_OP_FAILED);
		}
	if (result == NULL)
	{
		BMD_FOK(BMD_ERR_OP_FAILED);
	}
	status = connect(handler->s, result->ai_addr,(long)result->ai_addrlen);
	if (status)
	{
		PRINT_ERROR("Cannot connect to host.\n");
		return(-1);
	}
#endif

	return BMD_OK;
};
Esempio n. 5
0
void MainWindow::setupConnections()
{
    // Importing
    connect(importButton, SIGNAL(clicked()), this, SLOT(launchImageImport()));
    connect(filedata, SIGNAL(imagesImported()), aListWidget, SLOT(populate()));
    connect(filedata, SIGNAL(imagesImported()), bListWidget, SLOT(populate()));
    connect(filedata, SIGNAL(imagesImported()), vectorListWidget, SLOT(populate()));
    connect(filedata, SIGNAL(imagesImported()), this, SLOT(notifyFolderChange()));
    connect(filedata, SIGNAL(vectorListUpdated()), vectorListWidget, SLOT(update()));

    // Image selection
    connect(aListWidget, SIGNAL(fileClicked(int)), this, SLOT(pivAclicked(int)));
    connect(bListWidget, SIGNAL(fileClicked(int)), this, SLOT(pivBclicked(int)));
    connect(vectorListWidget, SIGNAL(fileClicked(int)), this, SLOT(vectorClicked(int)));
    connect(forwardButton, SIGNAL(clicked()), this, SLOT(forwardOne()));
    connect(backButton, SIGNAL(clicked()), this, SLOT(backwardOne()));

    // Image/vector viewing
    connect(zoomInButton, SIGNAL(clicked()), pivDisplay, SLOT(zoomIn()));
    connect(zoomOutButton, SIGNAL(clicked()), pivDisplay, SLOT(zoomOut()));
    connect(zoomFitButton, SIGNAL(clicked()), pivDisplay, SLOT(zoomFit()));
    // The following should be moved into settings
    connect(vectorToggle, SIGNAL(toggled(bool)), pivDisplay, SLOT(vectorsToggled(bool)));
    //
    connect(colourButtonFiltered, SIGNAL(clicked()), this, SLOT(chooseFilteredColour()));
    connect(colourButtonUnfiltered, SIGNAL(clicked()), this, SLOT(chooseUnfilteredColour()));
    connect(scaleSpin, SIGNAL(valueChanged(double)), settings, SLOT(setVectorScale(double)));
    connect(subSpin, SIGNAL(valueChanged(double)), settings, SLOT(setVectorSub(double)));
    connect(settings, SIGNAL(vectorSettingChanged()), pivDisplay, SLOT(vectorsChanged()));

    // Masking
    connect(maskButton, SIGNAL(clicked()), maskButton, SLOT(showMenu()));
    connect(filedata,SIGNAL(imagesImported()), maskDropDown, SLOT(imageLoaded()));
    connect(maskDropDown, SIGNAL(importMaskClicked()), filedata, SLOT(importMask()));
    connect(filedata, SIGNAL(maskLoaded()), maskDropDown, SLOT(maskLoaded()));
    connect(maskDropDown, SIGNAL(gridToggled(bool)), pivDisplay, SLOT(maskToggled(bool)));
    connect(maskDropDown, SIGNAL(clearMask(bool)), settings, SLOT(setIsMask(bool)));

    // Process tab
    connect(hSizeCombo, SIGNAL(activated(int)), settings, SLOT(setIntLengthX(int)));
    connect(vSizeCombo, SIGNAL(activated(int)), settings, SLOT(setIntLengthY(int)));
    connect(hSpaceSpin, SIGNAL(valueChanged(int)), settings, SLOT(setDeltaX(int)));
    connect(vSpaceSpin, SIGNAL(valueChanged(int)), settings, SLOT(setDeltaY(int)));

    // Filter tab
    connect(globalRangeCheck, SIGNAL(toggled(bool)), this, SLOT(filterChanged()));
    connect(minUedit, SIGNAL(textChanged(QString)), this, SLOT(setFilterValues()));
    connect(maxUedit, SIGNAL(textChanged(QString)), this, SLOT(setFilterValues()));
    connect(minVedit, SIGNAL(textChanged(QString)), this, SLOT(setFilterValues()));
    connect(maxVedit, SIGNAL(textChanged(QString)), this, SLOT(setFilterValues()));
    connect(globalStDevCheck, SIGNAL(toggled(bool)), this, SLOT(filterChanged()));
    connect(nStdDevSpin, SIGNAL(valueChanged(double)), this, SLOT(setFilterValues()));

    connect(localCheck, SIGNAL(toggled(bool)), this, SLOT(filterChanged()));
    connect(localMethodCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(setFilterValues()));
    connect(localNxNCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(setFilterValues()));
    connect(localUedit, SIGNAL(textChanged(QString)), this, SLOT(setFilterValues()));
    connect(localVedit, SIGNAL(textChanged(QString)), this, SLOT(setFilterValues()));

    connect(interpolateCheck, SIGNAL(toggled(bool)), this, SLOT(filterChanged()));
    connect(interpolateMethodCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(setFilterValues()));
    connect(interpolateNxNCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(setFilterValues()));

    connect(smoothCheck, SIGNAL(toggled(bool)), this, SLOT(filterChanged()));
    connect(smoothRadiusEdit, SIGNAL(textChanged(QString)), this, SLOT(setFilterValues()));
    connect(smoothNxNCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(setFilterValues()));

    // DoingPIV
    connect(outputFolderEdit, SIGNAL(textEdited(QString)), this, SLOT(setOutput()));
    connect(outputFolderButton, SIGNAL(clicked()), this, SLOT(chooseOutputFolder()));
    connect(outputFormatCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(setOutput()));
    connect(correlateButton, SIGNAL(clicked()), process, SLOT(processCurrentImagePair()));
    connect(process, SIGNAL(currentProcessed()), pivDisplay, SLOT(displayCurrent()));
    connect(process, SIGNAL(currentProcessed()), output, SLOT(outputCurrent()));
    connect(filterButton, SIGNAL(clicked()), analysis, SLOT(filterCurrent()));
    connect(analysis, SIGNAL(currentFiltered()), pivDisplay, SLOT(displayCurrent()));
    connect(analysis, SIGNAL(currentFiltered()), output, SLOT(outputCurrent()));
    connect(batchButton, SIGNAL(clicked()), process, SLOT(launchBatchWindow()));
    connect(process, SIGNAL(batchProcessed()), this, SLOT(batchDone()));
    connect(pivDisplay, SIGNAL(mouseMoved(QPointF)), this, SLOT(updatePositionLabel(QPointF)));

    // Data Quality
    connect(filterSNRCheck, SIGNAL(toggled(bool)), this, SLOT(qualityChanged()));
    connect(snrEdit, SIGNAL(textEdited(QString)), this, SLOT(qualityChanged()));
    connect(filterIntCheck, SIGNAL(toggled(bool)), this, SLOT(qualityChanged()));
    connect(intensityEdit, SIGNAL(textEdited(QString)), this, SLOT(qualityChanged()));
}
Esempio n. 6
0
void make_tunnel(int rsock, const char *remote)
{
	char buf[4096], *outbuf = NULL, *inbuf = NULL;
	int sock = -1, outlen = 0, inlen = 0;
	struct sockaddr *sa = NULL;
	const char *source;

	if (map_list) {
		if (!(source = map_find(remote))) {
			debug("<%d> connection from unmapped address (%s), disconnecting\n", rsock, remote);
			goto cleanup;
		}

		debug("<%d> mapped to %s\n", rsock, source);
	} else
		source = source_host;

	if (ircpass) {
		int i, ret;

		for (i = 0; i < sizeof(buf) - 1; i++) {
			if ((ret = read(rsock, buf + i, 1)) < 1)
				goto cleanup;
			if (buf[i] == '\n')
				break;
		}

		buf[i] = 0;
		
		if (i > 0 && buf[i - 1] == '\r')
			buf[i - 1] = 0;

		if (i == 4095 || strncasecmp(buf, "PASS ", 5)) {
			char *tmp;

			debug("<%d> irc proxy auth failed - junk\n", rsock);

			tmp = "ERROR :Closing link: Make your client send password first\r\n";
			if (write(rsock, tmp, strlen(tmp)) != strlen(tmp)) {
				// Do nothing. We're failing anyway.
			}
				
			goto cleanup;
		}

		if (strcmp(buf + 5, ircpass)) {
			char *tmp;

			debug("<%d> irc proxy auth failed - password incorrect\n", rsock);
			tmp = ":6tunnel 464 * :Password incorrect\r\nERROR :Closing link: Password incorrect\r\n";
			if (write(rsock, tmp, strlen(tmp)) != strlen(tmp)) {
				// Do nothing. We're failing anyway.
			}
			
			goto cleanup;
		}
		
		debug("<%d> irc proxy auth succeded\n", rsock);
	}
  
	if (!(sa = resolve_host(remote_host, remote_hint))) {
		debug("<%d> unable to resolve %s\n", rsock, remote_host);
		goto cleanup;
	}

	if ((sock = socket(sa->sa_family, SOCK_STREAM, 0)) == -1) {
		debug("<%d> unable to create socket (%s)\n", rsock, strerror(errno));
		goto cleanup;
	}

	free(sa);
	sa = NULL;

	if (source) {
		if (!(sa = resolve_host(source, local_hint))) {
			debug("<%d> unable to resolve source host (%s)\n", rsock, source);
			goto cleanup;
		}

		if (bind(sock, sa, (local_hint == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6))) {
			debug("<%d> unable to bind to source host (%s)\n", rsock, source);
			goto cleanup;
		}

		free(sa);
		sa = NULL;
	}

	sa = resolve_host(remote_host, remote_hint);

	((struct sockaddr_in*) sa)->sin_port = htons(remote_port);

	if (connect(sock, sa, (sa->sa_family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6))) {
		debug("<%d> connection refused (%s,%d)\n", rsock, remote_host, remote_port);
		goto cleanup;
	}

	free(sa);
	sa = NULL;

	debug("<%d> connected to %s,%d\n", rsock, remote_host, remote_port);

	if (ircsendpass) {
		snprintf(buf, 4096, "PASS %s\r\n", ircsendpass);
		if (write(sock, buf, strlen(buf)) != strlen(buf))
			goto cleanup;
	}

	for (;;) {
		fd_set rds, wds;
		int ret, sent;

		FD_ZERO(&rds);
		FD_SET(sock, &rds);
		FD_SET(rsock, &rds);

		FD_ZERO(&wds);
		if (outbuf && outlen)
			FD_SET(rsock, &wds);
		if (inbuf && inlen)
			FD_SET(sock, &wds);
    
		ret = select((sock > rsock) ? (sock + 1) : (rsock + 1), &rds, &wds, NULL, NULL);

		if (FD_ISSET(rsock, &wds)) {
			sent = write(rsock, outbuf, outlen);

			if (sent < 1)
				goto cleanup;

			if (sent == outlen) {
				free(outbuf);
				outbuf = NULL;
				outlen = 0;
			} else {
				memmove(outbuf, outbuf + sent, outlen - sent);
				outlen -= sent;
			}
		}

		if (FD_ISSET(sock, &wds)) {
			sent = write(sock, inbuf, inlen);

			if (sent < 1)
				goto cleanup;

			if (sent == inlen) {
				free(inbuf);
				inbuf = NULL;
				inlen = 0;
			} else {
				memmove(inbuf, inbuf + sent, inlen - sent);
				inlen -= sent;
			}
		}

		if (FD_ISSET(sock, &rds)) {
			if ((ret = read(sock, buf, 4096)) < 1)
				goto cleanup;

			if (hexdump) {
				printf("<%d> recvfrom %s,%d\n", rsock, remote_host, remote_port);
				print_hexdump(buf, ret);
			}
			
			sent = write(rsock, buf, ret);

			if (sent < 1)
				goto cleanup;
			
			if (sent < ret) {
				outbuf = xrealloc(outbuf, outlen + ret - sent);
				memcpy(outbuf + outlen, buf + sent, ret - sent);
				outlen = ret - sent;
			}
		}

		if (FD_ISSET(rsock, &rds)) {
			if ((ret = read(rsock, buf, 4096)) < 1)
				goto cleanup;

			if (hexdump) {
				printf("<%d> sendto %s,%d\n", rsock, remote_host, remote_port);
				print_hexdump(buf, ret);
			}

			sent = write(sock, buf, ret);

			if (sent < 1)
				goto cleanup;

			if (sent < ret) {
				inbuf = xrealloc(inbuf, inlen + ret - sent);
				memcpy(inbuf + inlen, buf + sent, ret - sent);
				inlen = ret - sent;
			}
		}
	}


cleanup:
	if (sa)
		free(sa);

	close(rsock);

	if (sock != -1)
		close(sock);
}
Esempio n. 7
0
ModulesDialog::ModulesDialog(QWidget *parent)
	: QWidget(parent, Qt::Window),
	lv_modules(0), l_moduleinfo(0)
{
	kdebugf();
	setWindowTitle(tr("Manage Modules"));
	setAttribute(Qt::WA_DeleteOnClose);

	// create main QLabel widgets (icon and app info)
	QWidget *left = new QWidget(this);
	QVBoxLayout *leftLayout = new QVBoxLayout(left);
	leftLayout->setMargin(10);
	leftLayout->setSpacing(10);

	QLabel *l_icon = new QLabel(left);

	leftLayout->addWidget(l_icon);
	leftLayout->addStretch();

	QWidget *center = new QWidget(this);
	QVBoxLayout *centerLayout = new QVBoxLayout(center);
	centerLayout->setMargin(10);
	centerLayout->setSpacing(10);

	QLabel *l_info = new QLabel(center);
	l_icon->setPixmap(IconsManager::instance()->loadPixmap("ManageModulesWindowIcon"));
	l_info->setText(tr("This dialog box allows you to manage installed modules. Modules are responsible "
			"for numerous vital features like playing sounds or message encryption.\n"
			"You can load (or unload) them by double-clicking on their names."));
	l_info->setWordWrap(true);
#ifndef	Q_OS_MAC
	l_info->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum));
#endif
	// end create main QLabel widgets (icon and app info)

	// our QListView
	lv_modules = new QTreeWidget(center);
	QStringList headers;
	headers << tr("Module name") << tr("Version") << tr("Module type") << tr("State");
	lv_modules->setHeaderLabels(headers);
	lv_modules->setSortingEnabled(true);
	lv_modules->setAllColumnsShowFocus(true);
	lv_modules->setIndentation(false);
	lv_modules->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum));

	
	// end our QListView

	//our QVGroupBox
	QGroupBox *vgb_info = new QGroupBox(center);
	QVBoxLayout *infoLayout = new QVBoxLayout(vgb_info);
	vgb_info->setTitle(tr("Info"));
	//end our QGroupBox

	l_moduleinfo = new QLabel(vgb_info);
	l_moduleinfo->setText(tr("<b>Module:</b><br/><b>Depends on:</b><br/><b>Conflicts with:</b><br/><b>Provides:</b><br/><b>Author:</b><br/><b>Version:</b><br/><b>Description:</b>"));
#ifndef	Q_OS_MAC
	l_moduleinfo->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum));
#endif
	l_moduleinfo->setWordWrap(true);

	infoLayout->addWidget(l_moduleinfo);

	// buttons
	QWidget *bottom = new QWidget(center);
	QHBoxLayout *bottomLayout = new QHBoxLayout(bottom);
	bottomLayout->setSpacing(5);

	hideBaseModules = new QCheckBox(tr("Hide base modules"), bottom);
	hideBaseModules->setChecked(config_file.readBoolEntry("General", "HideBaseModules"));
	connect(hideBaseModules, SIGNAL(clicked()), this, SLOT(refreshList()));
	QPushButton *pb_close = new QPushButton(IconsManager::instance()->loadIcon("CloseWindow"), tr("&Close"), bottom);

	bottomLayout->addWidget(hideBaseModules);
	bottomLayout->addStretch();
	bottomLayout->addWidget(pb_close);
#ifdef Q_OS_MAC
	bottom->setMaximumHeight(pb_close->height() + 5);
#endif
	// end buttons

	centerLayout->addWidget(l_info);
	centerLayout->addWidget(lv_modules);
	centerLayout->addWidget(vgb_info);
	centerLayout->addWidget(bottom);

	QHBoxLayout *layout = new QHBoxLayout(this);
	layout->addWidget(left);
	layout->addWidget(center);

	connect(pb_close, SIGNAL(clicked()), this, SLOT(close()));
	connect(lv_modules, SIGNAL(itemSelectionChanged()), this, SLOT(itemsChanging()));
	connect(lv_modules, SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)), this, SLOT(moduleAction(QTreeWidgetItem *)));

	loadWindowGeometry(this, "General", "ModulesDialogGeometry", 0, 50, 600, 620);
	refreshList();
	lv_modules->sortByColumn(0, Qt::AscendingOrder);
	kdebugf2();
}
/*!
  \class RWidgetResizer
  Create a new RReportWidget resize manager. A resize manager show 8 circle on
  widget that user can drag them to resize the widget
*/
QReportWidgetResizer::QReportWidgetResizer(QGraphicsScene *parent) :
    QObject(),
    parentScene(parent),
    //_parent( 0 ),
    m_scale(1)
{
    resizerTL = new QReportResizeHandle(0, 0, CIRCLER);
    resizerT  = new QReportResizeHandle(0, 0, CIRCLER);
    resizerTR = new QReportResizeHandle(0, 0, CIRCLER);
    resizerL  = new QReportResizeHandle(0, 0, CIRCLER);
    resizerR  = new QReportResizeHandle(0, 0, CIRCLER);
    resizerBL = new QReportResizeHandle(0, 0, CIRCLER);
    resizerB  = new QReportResizeHandle(0, 0, CIRCLER);
    resizerBR = new QReportResizeHandle(0, 0, CIRCLER);

    /*parent->addItem( resizerTL );
    parent->addItem( resizerT  );
    parent->addItem( resizerTR );
    parent->addItem( resizerL  );
    parent->addItem( resizerR  );
    parent->addItem( resizerBL );
    parent->addItem( resizerB  );
    parent->addItem( resizerBR );*/

    handles.append(resizerTL);
    handles.append(resizerT);
    handles.append(resizerTR);
    handles.append(resizerL);
    handles.append(resizerR);
    handles.append(resizerBL);
    handles.append(resizerB);
    handles.append(resizerBR);

    resizerTL->setPen(QPen(Qt::black));

    setVisible(false);

    resizerTL->setCursor(Qt::SizeFDiagCursor);
    resizerT->setCursor(Qt::SizeVerCursor);
    resizerTR->setCursor(Qt::SizeBDiagCursor);
    resizerL->setCursor(Qt::SizeHorCursor);
    resizerR->setCursor(Qt::SizeHorCursor);
    resizerBL->setCursor(Qt::SizeBDiagCursor);
    resizerB->setCursor(Qt::SizeVerCursor);
    resizerBR->setCursor(Qt::SizeFDiagCursor);

    resizerT->setResizeDirection(::Top);
    resizerL->setResizeDirection(::Left);
    resizerR->setResizeDirection(::Right);
    resizerB->setResizeDirection(::Bottom);

    resizerTR->setResizeDirection(::Top    | ::Right);
    resizerTL->setResizeDirection(::Top    | ::Left);
    resizerBR->setResizeDirection(::Bottom | ::Right);
    resizerBL->setResizeDirection(::Bottom | ::Left);

    for (int i = 0; i < handles.count(); i++) {
        /*QRadialGradient gradient( CIRCLER, CIRCLER, 270);
        gradient.setColorAt(0, QColor::fromRgb(128, 128, 255) );
        gradient.setColorAt(1, QColor::fromRgb(255, 255, 255) );
        handles.at( i )->setBrush( QBrush(gradient) );*/

        handles.at(i)->setBrush(QBrush(Qt::white));
        parent->addItem(handles.at(i));

        connect(handles.at(i), SIGNAL(moving(QPointF)),
                this,          SLOT(handleMoving(QPointF)));

        connect(handles.at(i), SIGNAL(moved()),
                this,          SIGNAL(resized()));

    }//for
}
Esempio n. 9
0
int main(int argc, char** argv)
{
	 int val=30;	
	 //playc.flagc1=1;
	//playc.flagc2=1;
	//playc.flagc3 =1;
	playc. flags1=0;
//	playc.flags2=0;
//	playc.flags3=0;
	playc.a_rchar[0]='$';
	playc.a_rchar[1]='O';
	playc.v_score=0;
	playc.v_rscore=0;
	playc.v_total=0;
	playc.v_life=3;
	playc.ack=1;
        int sockfd, n,len,portno;
        char buff[100];
	int buffi[5];
        struct sockaddr_in serv;
        struct hostent *server;
	/*if(argc < 3){
	printf(stderr,"using %s hostname port \n",argv[0]);
	exit(0);
	}*/
	
	//portno=atoi(argv[2]);
		if( (sockfd=socket(AF_INET,SOCK_STREAM,0)) < 0 )
        {
                printf("\nError! Socket not created...\n");
                exit(0);
        }
        //server=gethostbyname(argv[1]);
	if(server == NULL){
		fprintf(stderr,"ERROR, no such host\n");
		exit(0);
	}
	bzero(&serv,sizeof(serv));
        serv.sin_family=AF_INET;
        serv.sin_port=htons(60607);
        
        if(inet_pton(AF_INET,"127.0.0.1", &serv.sin_addr) < 0)
        {
        
	 printf("\nError in conversion of IP address from string to num\n");
                exit(0);
        }

        if( connect(sockfd,(struct sockaddr*)&serv, sizeof(serv)) <0)
        {
                printf("\nError! Conx not established...\n");
                exit(0);
        }

        printf("\n Connected.... \n");
	//sleep(5);
	//write(sockfd,&flag1,sizeof(flag1));
	//write(sockfd,&flagc1,sizeof(flagc1));
//	write(sockfd,&val,sizeof(val));
	//write(sockfd,&playc,sizeof(playc));
//	cout<<"\nSize of play"<<sizeof(playc);
	playc.flags1=1;
	write(sockfd,&playc.flags1,sizeof(playc.flags1));
	playc.f_Init();
	write(sockfd,&playc.v_opt,sizeof(playc.v_opt));
//	read(sockfd,&playc,sizeof(playc));
//	cout<<"\n"<<n;
//	playc.f_Number();
//	sleep(3);
//	playc.v_opt=1;
//	system("clear");
//	cout<<playc.v_opt;
	
//	write(sockfd,&playc.v_opt,sizeof(playc.v_opt));
	while(1)
	{
		if((len =read(sockfd,&playc.a_a,sizeof(playc.a_a))) > 0)
		{
	    //    cout<<"length is :"<<len;
	//sleep(2);
	//	cout<<"hererasdfsdf"<<len;
		playc.f_Display();
		playc.f_Print();
		playc.f_Msleep(250);
	//	sleep(10);
		if(playc.f_Kbhit())
		{
		//	 playc.flags1=2;
                  //      write(sockfd,&playc.flags1,sizeof(playc.flags1));
                    //   write(sockfd,&playc.a_a,sizeof(playc.a_a));

		   	//system("stty raw");

			playc.flags1=3;

		 	playc.v_ch=getchar();

			write(sockfd,&playc.flags1,sizeof(playc.flags1));
                	write(sockfd,&playc.v_ch,sizeof(playc.v_ch));

			//playc.f_Display1();
			//playc.f_Print();
		 	//system("stty cooked");


			//playc.flags1=3;
		//	playc.f_Msleep(500);
//			write(sockfd,&playc,sizeof(playc));
			//write(sockfd,&playc.flags1,sizeof(playc.flags1));
			//write(sockfd,&playc,sizeof(playc));
		//	playc.flags1=2;
	          //      write(sockfd,&playc.flags1,sizeof(playc.flags1));
        	    //    write(sockfd,&playc.a_a,sizeof(playc.a_a));

		}
		//playc.f_Msleep(600);
		playc.flags1=2;
		write(sockfd,&playc.flags1,sizeof(playc.flags1));	
		write(sockfd,&playc.a_a,sizeof(playc.a_a));
		}    
	}
        close(sockfd);
	  printf("\n");
//	  return 0;


}	
Esempio n. 10
0
creatordialog::creatordialog(QString main_table,QWidget *parent) :
    QDialog(parent),
    ui(new Ui::creatordialog)
{
    ui->setupUi(this);
    level=0;

    path=dir.absolutePath();

    relation=false;
    count=false;
    ui->pushButton_add->setVisible(false);
    ui->pushButton_delete->setVisible(false);

    table_constructor=main_table;
    this->setWindowTitle("Kreator relacji");
    ui->stackedWidget->setCurrentIndex(0);

    QImage image(path + "/obrazy/sigma_LOGO_3D.png");
    ui->logo_label->setPixmap(QPixmap::fromImage(image.scaled(200,200,Qt::KeepAspectRatio,Qt::FastTransformation)));

    ui->pushButton->setIcon(QIcon(path + "/obrazy/arrow_right.png"));
    ui->pushButton->setIconSize(QSize(40, 40));

    ui->pushButton_delete->setIcon(QIcon(path + "/obrazy/delete_row.png"));
    ui->pushButton_delete->setIconSize(QSize(20, 20));

    ui->pushButton_add->setIcon(QIcon(path + "/obrazy/add_row.png"));
    ui->pushButton_add->setIconSize(QSize(20, 20));

    ui->checkBox_2->setVisible(true);
    relational_table="";
    relational_table_2="";

    table=main_table;

    if(main_table=="Daneosobowe") {
        ui->checkBox->setText("Maszyny");
        ui->checkBox_2->setVisible(false);
    }
    else if(main_table=="Czesci") {
        ui->checkBox->setText("Maszyny");
        ui->checkBox_2->setVisible(false);
    }
    else if(main_table=="Maszyny") {
        ui->checkBox->setText("Części");
        ui->checkBox_2->setText("Dane osobowe");
    }

    else if(main_table=="Maszyny_has_Daneosobowe") {
        relation=true;
        relational_table_2=main_table;
        on_pushButton_clicked();
    }
    else if(main_table=="Maszyny_has_Czesci") {
        relation=true;
        relational_table_2=main_table;
        on_pushButton_clicked();
    }

    if(relation) {
        ui->pushButton_add->setVisible(true);
        ui->pushButton_delete->setVisible(true);
    }

    connect(this, SIGNAL(rejected()), this, SLOT(closing_creator_dialog()));
}
Esempio n. 11
0
void wgt_base::connect_to_signal_mapper(QPushButton *button, int i, QSignalMapper *signalMapper)
{
	signalMapper->setMapping(button, i);
	connect(button, SIGNAL(clicked()), signalMapper, SLOT(map()));
}
Server_ProtocolHandler::Server_ProtocolHandler(Server *_server, QObject *parent)
	: QObject(parent), server(_server), authState(PasswordWrong), acceptsUserListChanges(false), acceptsRoomListChanges(false), userInfo(0), lastCommandTime(QDateTime::currentDateTime())
{
	connect(server, SIGNAL(pingClockTimeout()), this, SLOT(pingClockTimeout()));
}
Esempio n. 13
0
void VNewFileDialog::setupUI(const QString &p_title,
                             const QString &p_info,
                             const QString &p_defaultName)
{
    QLabel *infoLabel = NULL;
    if (!p_info.isEmpty()) {
        infoLabel = new QLabel(p_info);
    }

    // Name.
    m_nameEdit = new VMetaWordLineEdit(p_defaultName);
    QValidator *validator = new QRegExpValidator(QRegExp(VUtils::c_fileNameRegExp),
                                                 m_nameEdit);
    m_nameEdit->setValidator(validator);
    int dotIndex = p_defaultName.lastIndexOf('.');
    m_nameEdit->setSelection(0, (dotIndex == -1) ? p_defaultName.size() : dotIndex);

    // Template.
    m_templateCB = VUtils::getComboBox();
    m_templateCB->setToolTip(tr("Choose a template (magic word supported)"));
    m_templateCB->setSizeAdjustPolicy(QComboBox::AdjustToContents);

    QPushButton *templateBtn = new QPushButton(VIconUtils::buttonIcon(":/resources/icons/manage_template.svg"),
                                               "");
    templateBtn->setToolTip(tr("Manage Templates"));
    templateBtn->setProperty("FlatBtn", true);
    connect(templateBtn, &QPushButton::clicked,
            this, [this]() {
                QUrl url = QUrl::fromLocalFile(g_config->getTemplateConfigFolder());
                QDesktopServices::openUrl(url);
            });

    QHBoxLayout *tempBtnLayout = new QHBoxLayout();
    tempBtnLayout->addWidget(m_templateCB);
    tempBtnLayout->addWidget(templateBtn);
    tempBtnLayout->addStretch();

    m_templateEdit = new QTextEdit();
    m_templateEdit->setReadOnly(true);

    QVBoxLayout *templateLayout = new QVBoxLayout();
    templateLayout->addLayout(tempBtnLayout);
    templateLayout->addWidget(m_templateEdit);

    m_templateEdit->hide();

    // InsertTitle.
    m_insertTitleCB = new QCheckBox(tr("Insert note name as title (for Markdown only)"));
    m_insertTitleCB->setToolTip(tr("Insert note name into the new note as a title"));
    m_insertTitleCB->setChecked(g_config->getInsertTitleFromNoteName());
    connect(m_insertTitleCB, &QCheckBox::stateChanged,
            this, [this](int p_state) {
                g_config->setInsertTitleFromNoteName(p_state == Qt::Checked);
            });

    QFormLayout *topLayout = new QFormLayout();
    topLayout->addRow(tr("Note &name:"), m_nameEdit);
    topLayout->addWidget(m_insertTitleCB);
    topLayout->addRow(tr("Template:"), templateLayout);

    m_nameEdit->setMinimumWidth(m_insertTitleCB->sizeHint().width());

    m_warnLabel = new QLabel();
    m_warnLabel->setWordWrap(true);
    m_warnLabel->hide();

    // Ok is the default button.
    m_btnBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
    connect(m_btnBox, &QDialogButtonBox::accepted,
            this, [this]() {
                s_lastTemplateFile = m_templateCB->currentData().toString();
                QDialog::accept();
            });
    connect(m_btnBox, &QDialogButtonBox::rejected, this, &QDialog::reject);

    QPushButton *okBtn = m_btnBox->button(QDialogButtonBox::Ok);
    okBtn->setProperty("SpecialBtn", true);
    m_templateCB->setMaximumWidth(okBtn->sizeHint().width() * 4);

    QVBoxLayout *mainLayout = new QVBoxLayout();
    if (infoLabel) {
        mainLayout->addWidget(infoLabel);
    }

    mainLayout->addLayout(topLayout);
    mainLayout->addWidget(m_warnLabel);
    mainLayout->addWidget(m_btnBox);
    mainLayout->setSizeConstraint(QLayout::SetFixedSize);
    setLayout(mainLayout);

    setWindowTitle(p_title);
}
Esempio n. 14
0
MntConfigWidget::MntConfigWidget(TQWidget *parent, const char *name, bool init)
  : TQWidget(parent, name)
{
  mInitializing = false;

  GUI = !init;
  if (GUI)
  {
    //tabList fillup waits until disklist.readDF() is done...
    mDiskList.readFSTAB();
    mDiskList.readDF();
    mInitializing = true;
    connect( &mDiskList,TQT_SIGNAL(readDFDone()),this,TQT_SLOT(readDFDone()));

    TQString text;
    TQVBoxLayout *topLayout = new TQVBoxLayout( this, 0, KDialog::spacingHint());

    mList = new CListView( this, "list", 8 );
    mList->setAllColumnsShowFocus( true );
    mList->addColumn( i18n("Icon") );
    mList->addColumn( i18n("Device") );
    mList->addColumn( i18n("Mount Point") );
    mList->addColumn( i18n("Mount Command") );
    mList->addColumn( i18n("Unmount Command") );
    mList->setFrameStyle( TQFrame::WinPanel + TQFrame::Sunken );
    connect( mList, TQT_SIGNAL(selectionChanged(TQListViewItem *)),
	     this, TQT_SLOT(clicked(TQListViewItem *)));

    topLayout->addWidget( mList );

    text = TQString("%1: %2  %3: %4").
      arg(mList->header()->label(DEVCOL)).
      arg(i18n("None")).
      arg(mList->header()->label(MNTPNTCOL)).
      arg(i18n("None"));
    mGroupBox = new TQGroupBox( text, this );
    TQ_CHECK_PTR(mGroupBox);
    topLayout->addWidget(mGroupBox);

    TQGridLayout *gl = new TQGridLayout(mGroupBox, 3, 4, KDialog::spacingHint());
    if( gl == 0 ) { return; }
    gl->addRowSpacing( 0, fontMetrics().lineSpacing() );

    mIconLineEdit = new TQLineEdit(mGroupBox);
    TQ_CHECK_PTR(mIconLineEdit);
    mIconLineEdit->setMinimumWidth( fontMetrics().maxWidth()*10 );
    connect( mIconLineEdit, TQT_SIGNAL(textChanged(const TQString&)),
	     this,TQT_SLOT(iconChanged(const TQString&)));
    connect( mIconLineEdit, TQT_SIGNAL(textChanged(const TQString&)),
	     this,TQT_SLOT(slotChanged()));
    gl->addWidget( mIconLineEdit, 2, 0 );

    mIconButton = new TDEIconButton(mGroupBox);
    mIconButton->setIconType(TDEIcon::Small, TDEIcon::Device);
    TQ_CHECK_PTR(mIconButton);
    mIconButton->setFixedWidth( mIconButton->sizeHint().height() );
    connect(mIconButton,TQT_SIGNAL(iconChanged(TQString)),this,TQT_SLOT(iconChangedButton(TQString)));
    gl->addWidget( mIconButton, 2, 1 );

    //Mount
    mMountButton = new TQPushButton( i18n("Get Mount Command"), mGroupBox );
    TQ_CHECK_PTR(mMountButton);
    connect(mMountButton,TQT_SIGNAL(clicked()),this,TQT_SLOT(selectMntFile()));
    gl->addWidget( mMountButton, 1, 2 );

    mMountLineEdit = new TQLineEdit(mGroupBox);
    TQ_CHECK_PTR(mMountLineEdit);
    mMountLineEdit->setMinimumWidth( fontMetrics().maxWidth()*10 );
    connect(mMountLineEdit,TQT_SIGNAL(textChanged(const TQString&)),
	    this,TQT_SLOT(mntCmdChanged(const TQString&)));
    connect( mMountLineEdit, TQT_SIGNAL(textChanged(const TQString&)),
	     this,TQT_SLOT(slotChanged()));
    gl->addWidget( mMountLineEdit, 1, 3 );

    //Umount
    mUmountButton = new TQPushButton(i18n("Get Unmount Command"), mGroupBox );
    TQ_CHECK_PTR( mUmountButton );
    connect(mUmountButton,TQT_SIGNAL(clicked()),this,TQT_SLOT(selectUmntFile()));
    gl->addWidget( mUmountButton, 2, 2 );

    mUmountLineEdit=new TQLineEdit(mGroupBox);
    TQ_CHECK_PTR(mUmountLineEdit);
    mUmountLineEdit->setMinimumWidth( fontMetrics().maxWidth()*10 );
    connect(mUmountLineEdit,TQT_SIGNAL(textChanged(const TQString&)),
	    this,TQT_SLOT(umntCmdChanged(const TQString&)));
    connect( mUmountLineEdit, TQT_SIGNAL(textChanged(const TQString&)),
	     this,TQT_SLOT(slotChanged()));
    gl->addWidget( mUmountLineEdit, 2, 3 );

  }

  loadSettings();
  if(init)
  {
    applySettings();
    mDiskLookup.resize(0);
  }

  mGroupBox->setEnabled( false );
}
Esempio n. 15
0
void MainWindow::showContextMenu( QTableWidgetItem * item,bool itemClicked )
{
	QMenu m ;

	m.setFont( this->font() ) ;

	QString mt = m_ui->tableWidget->item( item->row(),1 )->text() ;
	QString type = m_ui->tableWidget->item( item->row(),2 )->text() ;

	if( mt == QString( "Nil" ) ){
		connect( m.addAction( tr( "mount" ) ),SIGNAL( triggered() ),this,SLOT( slotMount() ) ) ;
	}else{
		QString mp = QString( "/run/media/private/%1/" ).arg( utility::userName() ) ;
		QString mp_1 = QString( "/home/%1/" ).arg( utility::userName() ) ;
		if( mt.startsWith( mp ) || mt.startsWith( mp_1 ) ){
			connect( m.addAction( tr( "unmount" ) ),SIGNAL( triggered() ),this,SLOT( pbUmount() ) ) ;
			m.addSeparator() ;
			connect( m.addAction( tr( "properties" ) ),SIGNAL( triggered() ),this,SLOT( volumeProperties() ) ) ;
			m.addSeparator() ;
			m_sharedFolderPath = utility::sharedMountPointPath( mt ) ;
			if( m_sharedFolderPath.isEmpty() ){
				connect( m.addAction( tr( "open folder" ) ),SIGNAL( triggered() ),
					 this,SLOT( slotOpenFolder() ) ) ;
			}else{
				connect( m.addAction( tr( "open private folder" ) ),SIGNAL( triggered() ),
					 this,SLOT( slotOpenFolder() ) ) ;
				connect( m.addAction( tr( "open shared folder" ) ),SIGNAL( triggered() ),
					 this,SLOT( slotOpenSharedFolder() ) ) ;
			}
		}else{
			m_sharedFolderPath = utility::sharedMountPointPath( mt ) ;
			if( m_sharedFolderPath.isEmpty() ){
				if( utility::pathIsReadable( mt ) ){
					connect( m.addAction( tr( "properties" ) ),SIGNAL( triggered() ),this,SLOT( volumeProperties() ) ) ;
					m.addSeparator() ;
					connect( m.addAction( tr( "open folder" ) ),SIGNAL( triggered() ),
						 this,SLOT( slotOpenFolder() ) ) ;
				}else{
					connect( m.addAction( tr( "properties" ) ),SIGNAL( triggered() ),this,SLOT( volumeProperties() ) ) ;
				}
			}else{
				connect( m.addAction( tr( "properties" ) ),SIGNAL( triggered() ),this,SLOT( volumeProperties() ) ) ;
				m.addSeparator() ;
				connect( m.addAction( tr( "open shared folder" ) ),SIGNAL( triggered() ),
					 this,SLOT( slotOpenSharedFolder() ) ) ;
			}
		}
	}

	m.addSeparator() ;
	m.addAction( tr( "close menu" ) ) ;

	if( itemClicked ){
		m.exec( QCursor::pos() ) ;
	}else{
		QPoint p = this->pos() ;
		int x = p.x() + 100 + m_ui->tableWidget->columnWidth( 0 ) ;
		int y = p.y() + 50 + m_ui->tableWidget->rowHeight( 0 ) * item->row() ;
		p.setX( x ) ;
		p.setY( y ) ;
		m.exec( p ) ;
	}
}
Esempio n. 16
0
MissionWidget::MissionWidget(QWidget *parent, QString mName, JoystickWidget *joystick,  Ui::NautilusCommander *gui, SendAction *sa) :
    QWidget(parent)
{
     this->missionName=mName;
     this->ui=gui;

     m_sSettingsFile = QString("%1/%2/settings.ini").arg(createPath("Missions")).arg(missionName);
     loadSettings();

     //Create Mission Folder.
     QString missionFolder=QString("%1/%2").arg(createPath("Missions")).arg(missionName);
     if(!QDir(missionFolder).exists()){
         QDir().mkdir(missionFolder);
     }

    lblLightsOff=ui->label_switchOff;
    lblLightsOn=ui->label_switchOn;
    lblLightsOn->setVisible(false);
    islightsOn=false;

    righLeft=-1;
    upDown=-1;

    statusVideoOff=ui->statusVideoOff;
    statusVideoOff->setVisible(true);
    isRecording=false;

    lblScreenShot=ui->label_toastSS;
    lblScreenShot->setVisible(false);


    missionNameLabel=ui->lblMissionName;
    missionNameLabel->setText(missionName);

    batteryROVPB=ui->progressBattRov;
    panCamera=ui->panCamera;
    tiltCamera=ui->tiltCamera;

    statusErrorBox=ui->statusErrorBox;
    statusErrorBox->setVisible(false);
    lblError=ui->lblError;


    sendAction=sa;
    connect(this->sendAction,SIGNAL(offline()),this,SLOT(robotDisconnected()));
    status=checkStatus();

    if(status!=-1)
    sendAction->sendComando(START_ROBOT);  //ReEnable the robot


    /********************************  Joystick *****************************************************/
    this->joystick=joystick;
    connect(joystick,SIGNAL(updateStatus(bool)),this,SLOT(updateControlStatus(bool)));
    connect(this->joystick,SIGNAL(joystickAxisEvent(QString,int)),this,SLOT(axisEvent(QString,int)));
    connect(this->joystick,SIGNAL(joystickButtonEvent(QString, QGameControllerButtonEvent*)),this,SLOT(buttonEvent(QString,QGameControllerButtonEvent*)));

    rtsp=new openRTSP(0,missionName,numVideos);
    connect(this,SIGNAL(saveVideo()),rtsp,SLOT(saveVideo()));


    dataThread=new DataThread(ui->progressBattControl, ui->progressBattRov,ui->labelDepthValue);
    dataThread->start();



    mplayer=ui->mplayerWG;    
    //connect(mplayer,SIGNAL(stateChanged(int)),this,SLOT(updatePlayerStatus(int)));
    mplayer->start();    
    mplayer->load("rtsp://*****:*****@10.5.5.110:554");
    mplayer->setVisible(true);


    isCameraOnline=true;

    speedDial=ui->dial;
    speedDial->setNotchesVisible(false);

    speeds[0][0]=3;speeds[0][1]=10;speeds[0][2]=14;speeds[0][3]=20;//speeds[0][4]=13;//speeds[0][5]=15;speeds[0][6]=18;speeds[0][7]=22;
    speeds[1][0]=1580;speeds[1][1]=1610;speeds[1][2]=1640;speeds[1][3]=1670;//speeds[1][4]=1670;
    speeds[2][0]=1420;speeds[2][1]=1390;speeds[2][2]=1360;speeds[2][3]=1330;//speeds[2][4]=1330; y = 3000-x
    dialIndex=0;
    lastCommand="";
    speedDial->setValue(speeds[0][0]);

}
Esempio n. 17
0
void MainWindow::setUpApp()
{
	this->setLocalizationLanguage() ;
	m_ui = new Ui::MainWindow ;
	m_ui->setupUi( this ) ;

	this->setFixedSize( this->size() ) ;

	m_ui->tableWidget->setColumnWidth( 0,225 ) ;
	m_ui->tableWidget->setColumnWidth( 1,320 ) ;
	m_ui->tableWidget->setColumnWidth( 2,105 ) ;
	m_ui->tableWidget->hideColumn( 3 ) ;
	m_ui->tableWidget->setColumnWidth( 4,87 ) ;
	m_ui->tableWidget->setColumnWidth( 5,87 ) ;

#if QT_VERSION < QT_VERSION_CHECK( 5,0,0 )
	m_ui->tableWidget->verticalHeader()->setResizeMode( QHeaderView::ResizeToContents ) ;
#else
	m_ui->tableWidget->verticalHeader()->setSectionResizeMode( QHeaderView::ResizeToContents ) ;
#endif
	m_ui->tableWidget->verticalHeader()->setMinimumSectionSize( 30 ) ;

	this->setAcceptDrops( true ) ;
	this->setWindowIcon( QIcon( QString( ":/zuluMount.png" ) ) ) ;

	m_ui->tableWidget->setMouseTracking( true ) ;

	connect( m_ui->tableWidget,SIGNAL( itemEntered( QTableWidgetItem * ) ),this,SLOT( itemEntered( QTableWidgetItem * ) ) ) ;
	connect( m_ui->tableWidget,SIGNAL( currentItemChanged( QTableWidgetItem *,QTableWidgetItem * ) ),
		 this,SLOT( slotCurrentItemChanged( QTableWidgetItem *,QTableWidgetItem * ) ) ) ;
	connect( m_ui->pbmount,SIGNAL( clicked() ),this,SLOT( pbMount() ) ) ;
	connect( m_ui->pbupdate,SIGNAL( clicked()),this,SLOT(pbUpdate() ) ) ;
	connect( m_ui->pbclose,SIGNAL( clicked() ),this,SLOT( pbClose() ) ) ;
	connect( m_ui->tableWidget,SIGNAL( itemClicked( QTableWidgetItem * ) ),this,SLOT( itemClicked( QTableWidgetItem * ) ) ) ;

	this->setUpShortCuts() ;

	this->setUpFont() ;

	m_trayIcon = new QSystemTrayIcon( this ) ;
	m_trayIcon->setIcon( QIcon( QString( ":/zuluMount.png" ) ) ) ;

	QMenu * trayMenu = new QMenu( this ) ;

	m_autoMountAction = new QAction( this ) ;
	m_autoMount = this->autoMount() ;
	m_autoMountAction->setCheckable( true ) ;
	m_autoMountAction->setChecked( m_autoMount ) ;

	m_autoMountAction->setText( tr( "automount volumes" ) ) ;

	connect( m_autoMountAction,SIGNAL( toggled( bool ) ),this,SLOT( autoMountToggled( bool ) ) ) ;

	trayMenu->addAction( m_autoMountAction ) ;

	QAction * autoOpenFolderOnMount = new QAction( this ) ;
	autoOpenFolderOnMount->setCheckable( true ) ;
	m_autoOpenFolderOnMount = this->autoOpenFolderOnMount() ;
	autoOpenFolderOnMount->setChecked( m_autoOpenFolderOnMount ) ;
	autoOpenFolderOnMount->setText( tr( "auto open mount point" ) ) ;
	connect( autoOpenFolderOnMount,SIGNAL( toggled( bool ) ),this,SLOT( autoOpenFolderOnMount( bool ) ) ) ;

	trayMenu->addAction( autoOpenFolderOnMount ) ;

	trayMenu->addAction( tr( "quit" ),this,SLOT( pbClose() ) ) ;
	m_trayIcon->setContextMenu( trayMenu ) ;

	connect( m_trayIcon,SIGNAL( activated( QSystemTrayIcon::ActivationReason ) ),
		 this,SLOT( slotTrayClicked( QSystemTrayIcon::ActivationReason ) ) ) ;

	m_trayIcon->show() ;

	QString dirPath = QDir::homePath() + QString( "/.zuluCrypt/" ) ;
	QDir dir( dirPath ) ;

	if( !dir.exists() ){
		dir.mkdir( dirPath ) ;
	}

	Task * t = new Task() ;

	this->disableAll() ;

	connect( t,SIGNAL( signalMountedList( QStringList,QStringList ) ),
		 this,SLOT( slotMountedList( QStringList,QStringList ) ) ) ;
	connect( t,SIGNAL( done() ),this,SLOT( openVolumeFromArgumentList() ) ) ;
	connect( t,SIGNAL( done() ),this,SLOT( started() ) ) ;

	t->start( Task::Update ) ;

	this->startAutoMonitor() ;
}
Esempio n. 18
0
QColorButton::QColorButton( QWidget *parent, const char *name )
        : QPushButton( parent, name )
{
    connect (this, SIGNAL(clicked()), this, SLOT(chooseColor()));
}
Esempio n. 19
0
/*!
    Constructs a new QxtSpanSlider with \a orientation and \a parent.
 */
QxtSpanSlider::QxtSpanSlider(Qt::Orientation orientation, QWidget* parent) : QSlider(orientation, parent)
{
    QXT_INIT_PRIVATE(QxtSpanSlider);
    connect(this, SIGNAL(rangeChanged(int, int)), &qxt_d(), SLOT(updateRange(int, int)));
    connect(this, SIGNAL(sliderReleased()), &qxt_d(), SLOT(movePressedHandle()));
}
SQLConfigWindow::SQLConfigWindow()
{
    setAttribute(Qt::WA_DeleteOnClose, true);

    QVBoxLayout *v = new QVBoxLayout(this);

    QLabel *desc = new QLabel(tr("<b><span style='color:red'>Don't touch anything if you've no clue what SQL is!</span></b><br /><br />For any change to have effect, you need to restart the server."
                                 "<br />If you change the settings without knowledge of what you are doing, you'll probably end up without any users stored anymore.<br/><br/>SQLite is the "
                                 "only system fully supported by default. PostGreSQL needs an external installation, and you then just have to put the .dlls in that are located in PostGreSQL's bin folder in the server folder. "
                                 "MySQL needs the user to get the right DLLs, the MySQL driver and to install a MySQL database too (it is advised to be on linux to do this as this is far less complicated)."));
    desc->setWordWrap(true);
    v->addWidget(desc);

    QSettings s("config", QSettings::IniFormat);

    b = new QComboBox();
    b->addItem("SQLite");
    b->addItem("PostGreSQL");
    b->addItem("MySQL");
    v->addLayout(new QSideBySide(new QLabel(tr("SQL Database type: ")), b));
    if (s.value("sql_driver").toInt() == SQLCreator::PostGreSQL) {
        b->setCurrentIndex(1);
    } else if (s.value("sql_driver").toInt() == SQLCreator::MySQL) {
        b->setCurrentIndex(2);
    }

    name = new QLineEdit();
    name->setText(s.value("sql_db_name").toString());
    v->addLayout(new QSideBySide(new QLabel(tr("Database name: ")), name));
    
    schema = new QLineEdit();
    schema->setText(s.value("sql_db_schema", "").toString());
    v->addLayout(new QSideBySide(new QLabel(tr("Schema: ")), schema));

    user = new QLineEdit();
    user->setText(s.value("sql_db_user").toString());
    v->addLayout(new QSideBySide(new QLabel(tr("User: "******"sql_db_pass").toString());
    v->addLayout(new QSideBySide(new QLabel(tr("Password: "******"sql_db_host").toString());
    v->addLayout(new QSideBySide(new QLabel(tr("Host: ")), host));

    port = new QSpinBox();
    port->setRange(0, 65535);
    port->setValue(s.value("sql_db_port").toInt());
    v->addLayout(new QSideBySide(new QLabel(tr("Port: ")), port));

    doVacuum = new QCheckBox("Do VACUUM on start if possible (recommended).");
    doVacuum->setChecked(s.value("sql_do_vacuum", true).toBool());
    v->addWidget(doVacuum);

    QPushButton *exporting = new QPushButton(tr("&Export"));
    connect(exporting, SIGNAL(clicked()), SLOT(exportDatabase()));

    QPushButton *apply = new QPushButton(tr("&Apply"));
    connect(apply, SIGNAL(clicked()), this, SLOT(apply()));

    v->addLayout(new QSideBySide(exporting, apply));

    connect(b, SIGNAL(activated(int)), SLOT(changeEnabled()));
    changeEnabled();
}
void CWE190_Integer_Overflow__int_connect_socket_square_66_bad()
{
    int data;
    int dataArray[5];
    /* Initialize data */
    data = 0;
    {
#ifdef _WIN32
        WSADATA wsaData;
        int wsaDataInit = 0;
#endif
        int recvResult;
        struct sockaddr_in service;
        SOCKET connectSocket = INVALID_SOCKET;
        char inputBuffer[CHAR_ARRAY_SIZE];
        do
        {
#ifdef _WIN32
            if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
            {
                break;
            }
            wsaDataInit = 1;
#endif
            /* POTENTIAL FLAW: Read data using a connect socket */
            connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
            if (connectSocket == INVALID_SOCKET)
            {
                break;
            }
            memset(&service, 0, sizeof(service));
            service.sin_family = AF_INET;
            service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
            service.sin_port = htons(TCP_PORT);
            if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
            {
                break;
            }
            /* Abort on error or the connection was closed, make sure to recv one
             * less char than is in the recv_buf in order to append a terminator */
            recvResult = recv(connectSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0);
            if (recvResult == SOCKET_ERROR || recvResult == 0)
            {
                break;
            }
            /* NUL-terminate the string */
            inputBuffer[recvResult] = '\0';
            /* Convert to int */
            data = atoi(inputBuffer);
        }
        while (0);
        if (connectSocket != INVALID_SOCKET)
        {
            CLOSE_SOCKET(connectSocket);
        }
#ifdef _WIN32
        if (wsaDataInit)
        {
            WSACleanup();
        }
#endif
    }
    /* put data in array */
    dataArray[2] = data;
    CWE190_Integer_Overflow__int_connect_socket_square_66b_badSink(dataArray);
}
SetColValuesDialog::SetColValuesDialog( ScriptingEnv *env, QWidget* parent, Qt::WFlags fl )
    : QDialog( parent, fl ), scripted(env)
{
    setName( "SetColValuesDialog" );
	setWindowTitle( tr( "QtiPlot - Set column values" ) );
	setSizeGripEnabled(true);
    setAttribute(Qt::WA_DeleteOnClose);

	QHBoxLayout *hbox1 = new QHBoxLayout();
	hbox1->addWidget(new QLabel(tr("For row (i)")));
	start = new QSpinBox();
	start->setMinValue(1);
    start->setMaxValue(INT_MAX);
	hbox1->addWidget(start);

	hbox1->addWidget(new QLabel(tr("to")));

	end = new QSpinBox();
	end->setMinValue(1);
    end->setMaxValue(INT_MAX);
	hbox1->addWidget(end);

	QGridLayout *gl1 = new QGridLayout();
	functions = new QComboBox(false);
	gl1->addWidget(functions, 0, 0);
	btnAddFunction = new QPushButton(tr( "Add function" ));
	gl1->addWidget(btnAddFunction, 0, 1);
	boxColumn = new QComboBox(false);
	gl1->addWidget(boxColumn, 1, 0);
	btnAddCol = new QPushButton(tr( "Add column" ));
	gl1->addWidget(btnAddCol, 1, 1);

	QHBoxLayout *hbox3 = new QHBoxLayout();
	hbox3->addStretch();
	buttonPrev = new QPushButton("&<<");
	hbox3->addWidget(buttonPrev);
	buttonNext = new QPushButton("&>>");
	hbox3->addWidget(buttonNext);
	gl1->addLayout(hbox3, 2, 0);
	addCellButton = new QPushButton(tr( "Add cell" ));
	gl1->addWidget(addCellButton, 2, 1);

	QGroupBox *gb = new QGroupBox();
	QVBoxLayout *vbox1 = new QVBoxLayout();
	vbox1->addLayout(hbox1);
	vbox1->addLayout(gl1);
	gb->setLayout(vbox1);
	gb->setSizePolicy(QSizePolicy (QSizePolicy::Preferred, QSizePolicy::Preferred));

	explain = new QTextEdit();
	explain->setReadOnly (true);
	explain->setSizePolicy(QSizePolicy (QSizePolicy::Preferred, QSizePolicy::Preferred));
	QPalette palette = explain->palette();
	palette.setColor(QPalette::Active, QPalette::Base, Qt::lightGray);
	explain->setPalette(palette);

	QHBoxLayout *hbox2 = new QHBoxLayout();
	hbox2->addWidget(explain);
	hbox2->addWidget(gb);

	commands = new ScriptEdit( scriptEnv);

	QVBoxLayout *vbox2 = new QVBoxLayout();
	btnApply = new QPushButton(tr( "&Apply" ));
	vbox2->addWidget(btnApply);
	btnCancel = new QPushButton(tr( "&Close" ));
	vbox2->addWidget(btnCancel);
	vbox2->addStretch();

	QHBoxLayout *hbox4 = new QHBoxLayout();
	hbox4->addWidget(commands);
	hbox4->addLayout(vbox2);

	QVBoxLayout* vbox3 = new QVBoxLayout();
	vbox3->addLayout(hbox2);
#ifdef SCRIPTING_PYTHON
	boxMuParser = NULL;
	if (env->name() != QString("muParser")){
		boxMuParser = new QCheckBox(tr("Use built-in muParser (much faster)"));
		boxMuParser->setChecked(true);
		vbox3->addWidget(boxMuParser);
	}
#endif

	colNameLabel = new QLabel();
	vbox3->addWidget(colNameLabel);
	vbox3->addLayout(hbox4);

	setLayout(vbox3);
	setFocusProxy (commands);
	commands->setFocus();

	functions->insertStringList(scriptEnv->mathFunctions(), -1);
	if (functions->count() > 0)
		insertExplain(0);

	connect(btnAddFunction, SIGNAL(clicked()),this, SLOT(insertFunction()));
	connect(btnAddCol, SIGNAL(clicked()),this, SLOT(insertCol()));
	connect(addCellButton, SIGNAL(clicked()),this, SLOT(insertCell()));
	connect(btnApply, SIGNAL(clicked()),this, SLOT(apply()));
	connect(btnCancel, SIGNAL(clicked()),this, SLOT(close()));
	connect(functions, SIGNAL(activated(int)),this, SLOT(insertExplain(int)));
	connect(buttonPrev, SIGNAL(clicked()), this, SLOT(prevColumn()));
	connect(buttonNext, SIGNAL(clicked()), this, SLOT(nextColumn()));
}
Esempio n. 23
0
void material::makeStatus(const QString text){
    ui.label_status->setText(text);
    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), ui.label_status, SLOT(clear()));
    timer->start(10000);
}
enum pbpal_resolv_n_connect_result pbpal_resolv_and_connect(pubnub_t *pb)
{
    int error;
    char const* origin = PUBNUB_ORIGIN_SETTABLE ? pb->origin : PUBNUB_ORIGIN;

    PUBNUB_ASSERT(pb_valid_ctx_ptr(pb));
    PUBNUB_ASSERT_OPT((pb->state == PBS_READY) || (pb->state == PBS_WAIT_DNS_SEND)  || (pb->state == PBS_WAIT_DNS_RCV));

    if (PUBNUB_USE_ADNS) {
        struct sockaddr_in dest;
        int skt = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

        if (SOCKET_INVALID == skt) {
            return pbpal_resolv_resource_failure;
        }
        pb->options.use_blocking_io = false;
        pbpal_set_blocking_io(pb);
        dest.sin_family = AF_INET;
        dest.sin_port = htons(DNS_PORT);
        inet_pton(AF_INET, "8.8.8.8", &dest.sin_addr.s_addr);
        error = send_dns_query(skt, (struct sockaddr*)&dest, (unsigned char*)origin);
        if (error < 0) {
            socket_close(skt);
            return pbpal_resolv_failed_send;
        }
        else if (error > 0) {
            return pbpal_resolv_send_wouldblock;
        }
        pb->pal.socket = skt;
        return pbpal_resolv_sent;
    }
    else {
        struct addrinfo *result;
        struct addrinfo *it;
        struct addrinfo hint;

        hint.ai_socktype = SOCK_STREAM;
        hint.ai_family = AF_UNSPEC;
        hint.ai_protocol = hint.ai_flags = hint.ai_addrlen = 0;
        hint.ai_addr = NULL;
        hint.ai_canonname = NULL;
        hint.ai_next = NULL;
        error = getaddrinfo(origin, HTTP_PORT_STRING, &hint, &result);
        if (error != 0) {
            return pbpal_resolv_failed_processing;
        }

        for (it = result; it != NULL; it = it->ai_next) {
            pb->pal.socket = socket(it->ai_family, it->ai_socktype, it->ai_protocol);
            if (pb->pal.socket == SOCKET_INVALID) {
                continue;
            }
            pbpal_set_blocking_io(pb);
            if (connect(pb->pal.socket, it->ai_addr, it->ai_addrlen) == SOCKET_ERROR) {
                if (socket_would_block()) {
                    error = 1;
                    break;
                }
                else {
                    PUBNUB_LOG_WARNING("socket connect() failed, will try another IP address, if available\n");
                    socket_close(pb->pal.socket);
                    pb->pal.socket = SOCKET_INVALID;
                    continue;
                }
            }
            break;
        }
        freeaddrinfo(result);

        if (NULL == it) {
            return pbpal_connect_failed;
        }

        socket_set_rcv_timeout(pb->pal.socket, pb->transaction_timeout_ms);

        return error ? pbpal_connect_wouldblock : pbpal_connect_success;
    }
}
QSharedItemSelectionModel::QSharedItemSelectionModel(QAbstractItemModel *model, QItemSelectionModel *shared, QObject *parent) :
    QItemSelectionModel(model, parent), d(new QSharedItemSelectionModelPrivate(this))
{
    d->shared = shared;
    connect(d->shared, SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(sharedSelectionChanged(QItemSelection,QItemSelection)));
}
Esempio n. 26
0
void InputWindowAction::common()
{
 pref = (UserPreferencesManager*)InstanceManager::getDefault("UserPreferencesManager");
 connect(this, SIGNAL(triggered()), this, SLOT(actionPerformed()));
}
Esempio n. 27
0
TopWidget::TopWidget(MainWindow * parent) : QWidget(parent)
{
	this->parent = parent;
	setMinimumWidth(300);
	setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);

	stopButton = new QToolButton();
	stopButton->setIcon(QIcon(DATAPATH "stop.png"));
	pauseButton = new QToolButton();
	pauseButton->setIcon(QIcon(DATAPATH "pause.png"));
	playButton = new QToolButton();
	playButton->setIcon(QIcon(DATAPATH "play.png"));
	prevButton = new QToolButton();
	prevButton->setIcon(QIcon(DATAPATH "prev.png"));
	nextButton = new QToolButton();
	nextButton->setIcon(QIcon(DATAPATH "next.png"));
	randomButton = new QToolButton();
	randomButton->setIcon(QIcon(DATAPATH "random.png"));
	libraryButton = new QToolButton();
	if(Settings::getLibraryFolded())
		libraryButton->setIcon(QIcon(DATAPATH "unfold.png"));
	else
		libraryButton->setIcon(QIcon(DATAPATH "fold.png"));

	trackBar = new Slider(parent);
	volumeBar = new Slider(parent);
	volumeBar->setMaximumWidth(70);
	volumeBar->setValue(100);
	volumeBar->style = 2;

	playModeBox = new QComboBox();
	playModeBox->setMaximumWidth(150);
	playModeBox->addItem("Normal");
	playModeBox->addItem("Loop All");
	playModeBox->addItem("Loop Track");
	playModeBox->addItem("Shuffle");

	grid = new QGridLayout();
	grid->addWidget(stopButton, 0, 0);
	grid->addWidget(pauseButton, 0, 1);
	grid->addWidget(playButton, 0, 2);
	grid->addWidget(prevButton, 0, 3);
	grid->addWidget(nextButton, 0, 4);
	grid->addWidget(randomButton, 0, 5);
	grid->addWidget(trackBar, 0, 6);
	grid->addWidget(playModeBox, 0, 7);
	grid->addWidget(volumeBar, 0, 8);
	grid->addWidget(libraryButton, 0, 9);
	grid->setContentsMargins(4, 4, 4, 4);

	connect(trackBar, SIGNAL(changed()), this, SLOT(onTrackBarChanged()));
	connect(volumeBar, SIGNAL(step()), this, SLOT(onVolumeBarChanged()));
	connect(pauseButton, SIGNAL(clicked()), this, SLOT(onPauseClick()));
	connect(playButton, SIGNAL(clicked()), this, SLOT(onPlayClick()));
	connect(stopButton, SIGNAL(clicked()), this, SLOT(onStopClick()));
	connect(prevButton, SIGNAL(clicked()), this, SLOT(onPrevClick()));
	connect(nextButton, SIGNAL(clicked()), this, SLOT(onNextClick()));
	connect(libraryButton, SIGNAL(clicked()), this, SLOT(onLibraryClick()));
	setLayout(grid);

	//Library View
	libraryWidget = new QWidget();
	libraryGrid = new QGridLayout();
	artistLabel = new QLabel("Artists: ");
	artistListWidget = new QListView();
	artistListWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
	artistModel = new QStringListModel();
	albumLabel = new QLabel("Albums: ");
	albumListWidget = new QListView();
	albumListWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
	albumModel = new QStringListModel();
	libraryGrid->addWidget(artistLabel, 1, 0);
	libraryGrid->addWidget(artistListWidget, 2, 0);
	libraryGrid->addWidget(albumLabel, 1, 1);
	libraryGrid->addWidget(albumListWidget, 2, 1);
	libraryGrid->setContentsMargins(0, 0, 0, 0);
	libraryWidget->setLayout(libraryGrid);
	if(Settings::getLibraryFolded())
		foldLibrary();
	else
		unfoldLibrary();

	artistList << "(Any)";
	mpdconfirm(mpd_search_db_tags(mpd, MPD_TAG_ARTIST));
	mpd_search_commit(mpd);
	mpd_pair * mp;
	while((mp = mpd_recv_pair_tag(mpd, MPD_TAG_ARTIST)) != NULL)
	{
		const QString artist = mp->value;
		if (artist != "")
			artistList << artist;
		mpd_return_pair(mpd, mp);
	}
	artistListWidget->setModel(artistModel);
	artistModel->setStringList(artistList);

	albumListWidget->setModel(albumModel);
	albumModel->setStringList(albumList);

	connect(artistListWidget->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this, SLOT(onArtistSelectionChanged(QItemSelection)));
	connect(albumListWidget->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this, SLOT(onAlbumSelectionChanged(QItemSelection)));

	artistListWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
	albumListWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
	selectedArtist = "(Any)";

}
Esempio n. 28
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow) {
    ui->setupUi(this);

    backlightIsAvailable =  false;
    backlightBrightness = new QFile("/sys/class/backlight/backlight/brightness");
    if (backlightBrightness && backlightBrightness->exists()) {
        backlightIsAvailable = backlightBrightness->open(QIODevice::ReadWrite);
        if (backlightIsAvailable) {
            backlightBrightness->write("6");
            backlightBrightness->flush();
        }
    }

    fbBlankIsAvailable =  false;
    fbBlank = new QFile("/sys/class/graphics/fb0/blank");
    if (fbBlank && fbBlank->exists()) {
        fbBlankIsAvailable = fbBlank->open(QIODevice::ReadWrite);
        if (fbBlankIsAvailable) {
            fbBlank->write("0");
            fbBlank->flush();
        }
    }

    // screen saver
    screensaverOn = false;
    scrTimer = new QTimer(this);
    connect(scrTimer, SIGNAL(timeout()), this, SLOT(scrTimerEvent()));
    scrTimer->setSingleShot(true);
    scrTimer->start(60000);

    // cyclic timer for measurement display
    roomTemperature = new QFile("/sys/class/hwmon/hwmon2/temp1_input");
    if (roomTemperature && roomTemperature->exists()) {
        roomTemperatureIsAvailable = true;
        roomTemperatureStr = new QString();
    } else {
        roomTemperatureIsAvailable = false;
    }

    roomHumidity = new QFile("/sys/class/hwmon/hwmon3/humidity1_input");
    if (roomHumidity && roomHumidity->exists()) {
        roomHumidityIsAvailable = true;
        roomHumidityStr = new QString();
    } else {
        roomHumidityIsAvailable = false;
    }

    statusLed = new statusled(this);
    statusLed->set_state(statusled::eOff);

    cycTimer = new QTimer(this);
    connect(cycTimer, SIGNAL(timeout()), this, SLOT(cycTimerEvent()));
    cycTimer->start(5000);

    qApp->installEventFilter(this);

    io = new ioState;

    meventmon = new eventmonitor;
    connect(meventmon, SIGNAL(busEvent(struct eventmonitor::event *)), this, SLOT(onBusEvent(struct eventmonitor::event *)));

    mservice = new moduleservice;

    uiEg = new egwindow(this, io);
    uiOg = new ogwindow(this, io);
    uiUg = new ugwindow(this, io);
    uiKueche = new kuechewindow(this, io);
    uiGarage = new garagewindow(this, io);
    uiSetup = new setupwindow(this, io);
}
Esempio n. 29
0
File: ftp.c Progetto: maplefish/MICO
// ======= FTP thread handler =========
static void _thread_ftp(void*inContext)
{
  (void)inContext;

  fd_set readset, wrset;
  struct timeval_t t_val;
  int k;
  uint32_t timeout = 0;
  uint8_t recv_tmo = 0;

  t_val.tv_sec = 0;
  t_val.tv_usec = 5000;

  timeout = mico_get_time();
  ftp_log("\r\n[FTP trd] FTP THREAD STARTED\r\n");
  
  // *** First we have to get IP address and connect the cmd socket
  char pIPstr[16]={0};
  int err;
  k = 3;
  do {
    err = gethostbyname((char *)pDomain4Dns, (uint8_t *)pIPstr, 16);
    if (err != kNoErr) {
      k--;
      mico_thread_msleep(50);
    }
  }while ((err != kNoErr) && (k > 0));
  
  if ((err == kNoErr) && (ftpCmdSocket != NULL)) {
    ftpCmdSocket->addr.s_ip = inet_addr(pIPstr);
    ftpCmdSocket->clientFlag = NO_ACTION;

    free(pDomain4Dns);
    pDomain4Dns=NULL;

    // Connect socket!
    char ip[17];
    memset(ip, 0x00, 17);
    inet_ntoa(ip, ftpCmdSocket->addr.s_ip);
    ftp_log("[FTP cmd] Got IP: %s, connecting...\r\n", ip);

    struct sockaddr_t *paddr = &(ftpCmdSocket->addr);
    int slen = sizeof(ftpCmdSocket->addr);
    // _micoNotify will be called if connected
    connect(ftpCmdSocket->socket, paddr, slen);
  }
  else {
    ftp_log("[FTP dns] Get IP error\r\n");
    goto terminate;
  }

  if (recvBuf == NULL) {
    recvBuf = malloc(MAX_RECV_LEN+4);
    memset(recvBuf, 0, MAX_RECV_LEN+4);
  }
  recvLen = 0;

  // ===========================================================================
  // Main Thread loop
  while (1) {
    mico_thread_msleep(5);
        
    if (ftpCmdSocket == NULL) goto terminate;

    if ( ((mico_get_time() - timeout) > MAX_FTP_TIMEOUT) ||
         (((mico_get_time() - timeout) > 8000) && (!(status & FTP_LOGGED))) ) {
      // ** TIMEOUT **
      ftp_log("[FTP trd] Timeout\r\n");
      timeout = mico_get_time();
      
      if ((status & FTP_LOGGED))
        ftpCmdSocket->clientFlag = REQ_ACTION_QUIT;
      else
        ftpCmdSocket->clientFlag = REQ_ACTION_DISCONNECT;
    }

    // ========== stage #1, Check cmd socket action requests ===================
    
    //REQ_ACTION_DISCONNECT
    if (ftpCmdSocket->clientFlag == REQ_ACTION_DISCONNECT) {
      ftpCmdSocket->clientFlag = NO_ACTION;
      
      closeDataSocket();
      
      ftp_log("[FTP cmd] Socket disconnected\r\n");
      if (ftpCmdSocket->disconnect_cb != LUA_NOREF) {
        queue_msg_t msg;
        msg.L = gL;
        msg.source = onFTP;
        msg.para1 = 0;
        msg.para2 = ftpCmdSocket->disconnect_cb;
        mico_rtos_push_to_queue( &os_queue, &msg, 0);
      }
      closeCmdSocket(0);
      continue;
    }
    //REQ_ACTION_QUIT
    if (ftpCmdSocket->clientFlag == REQ_ACTION_QUIT) {
      if ((status & FTP_LOGGED)) {
        ftpCmdSocket->clientFlag = NO_ACTION;
        ftp_log("[FTP cmd] Quit command\r\n");
        if (_send("QUIT\r\n", 6) <= 0) {
          ftpCmdSocket->clientFlag = REQ_ACTION_DISCONNECT;
        }
      }
      else ftpCmdSocket->clientFlag = REQ_ACTION_DISCONNECT;
      continue;
    }

    if (!(status & FTP_CONNECTED)) continue;
    //--------------------------------------

    //REQ_ACTION_LIST, REQ_ACTION_RECV, REQ_ACTION_SEND
    else if ((ftpCmdSocket->clientFlag == REQ_ACTION_LIST) ||
             (ftpCmdSocket->clientFlag == REQ_ACTION_RECV) ||
             (ftpCmdSocket->clientFlag == REQ_ACTION_SEND)) {
      ftpCmdSocket->clientLastFlag = ftpCmdSocket->clientFlag;
      ftpCmdSocket->clientFlag = NO_ACTION;

      _send("PASV\r\n", 6);
    }
    //REQ_ACTION_DOLIST
    else if (ftpCmdSocket->clientFlag == REQ_ACTION_DOLIST) {
      ftpCmdSocket->clientFlag = NO_ACTION;

      int res;
      if (ftpfile != NULL) {
        char tmps[100];
        if (list_type == 1) sprintf(tmps,"NLST %s\r\n", ftpfile);
        else sprintf(tmps,"LIST %s\r\n", ftpfile);
        res = _send(&tmps[0], strlen(ftpfile)+7);
        free(ftpfile);
        ftpfile = NULL;
      }
      else {
        if (list_type == 1) res = _send("NLST\r\n", 6);
        else res = _send("LIST\r\n", 6);
      }
      if (res > 0) status |= FTP_LISTING;
      else {
        ftp_log("[FTP cmd] LIST command failed.\r\n");
      }
    }
    //REQ_ACTION_DORECV
    else if (ftpCmdSocket->clientFlag == REQ_ACTION_DORECV) {
      ftpCmdSocket->clientFlag = NO_ACTION;

      char tmps[100];
      sprintf(tmps,"RETR %s\r\n", ftpfile);
      int res = _send(&tmps[0], strlen(ftpfile)+7);
      if (res > 0) {
        status |= FTP_RECEIVING;
        file_status = 0;
      }
      else {
        ftp_log("[FTP cmd] RETR command failed.\r\n");
        file_status = -4;
      }
    }
    //REQ_ACTION_DOSEND
    else if (ftpCmdSocket->clientFlag == REQ_ACTION_DOSEND) {
      ftpCmdSocket->clientFlag = NO_ACTION;

      char tmps[100];
      if ((send_type & SEND_APPEND)) sprintf(tmps,"APPE %s\r\n", ftpfile);
      else sprintf(tmps,"STOR %s\r\n", ftpfile);
      int res = _send(&tmps[0], strlen(ftpfile)+7);
      if (res > 0) {
        file_status = 0;
      }
      else {
        ftp_log("[FTP cmd] STOR/APPE command failed.\r\n");
        file_status = -4;
      }
    }
    //REQ_ACTION_CHDIR
    else if (ftpCmdSocket->clientFlag == REQ_ACTION_CHDIR) {
      ftpCmdSocket->clientFlag = NO_ACTION;

      if (ftpfile != NULL) {
        char tmps[100];
        sprintf(tmps,"CWD %s\r\n", ftpfile);
        _send(&tmps[0], strlen(ftpfile)+6);
        free(ftpfile);
        ftpfile = NULL;
      }
      else {
        _send("PWD\r\n", 5);
      }
    }
    //REQ_ACTION_LOGGED
    else if (ftpCmdSocket->clientFlag == REQ_ACTION_LOGGED) {
      ftpCmdSocket->clientFlag=NO_ACTION;
      if (ftpCmdSocket->logon_cb != LUA_NOREF) {
        queue_msg_t msg;
        msg.L = gL;
        msg.source = onFTP;
        msg.para1 = 1;
        msg.para3 = NULL;
        msg.para2 = ftpCmdSocket->logon_cb;
        mico_rtos_push_to_queue( &os_queue, &msg, 0);
      }
    }
    //REQ_ACTION_LIST_RECEIVED
    else if (ftpCmdSocket->clientFlag == REQ_ACTION_LIST_RECEIVED) {
      ftpCmdSocket->clientFlag=NO_ACTION;
      if (ftpCmdSocket->list_cb != LUA_NOREF) {
        queue_msg_t msg;
        msg.L = gL;
        msg.source = onFTP;
        msg.para1 = recvDataLen;
        msg.para2 = ftpCmdSocket->list_cb;
        msg.para3 = (uint8_t*)malloc(recvDataLen+4);
        if (msg.para3 != NULL) memcpy((char*)msg.para3, recvDataBuf, recvDataLen);

        mico_rtos_push_to_queue( &os_queue, &msg, 0);
      }
    }
    //REQ_ACTION_RECEIVED
    else if (ftpCmdSocket->clientFlag == REQ_ACTION_RECEIVED) {
      ftpCmdSocket->clientFlag=NO_ACTION;
      if (ftpCmdSocket->received_cb != LUA_NOREF) {
        queue_msg_t msg;
        msg.L = gL;
        msg.source = onFTP;
        msg.para1 = file_status;
        msg.para3 = NULL;
        if (recv_type == RECV_TOSTRING) {
          msg.para3 = (uint8_t*)malloc(recvDataLen+4);
          if (msg.para3 != NULL) memcpy((char*)msg.para3, recvDataBuf, recvDataLen);
        }
        msg.para2 = ftpCmdSocket->received_cb;

        mico_rtos_push_to_queue( &os_queue, &msg, 0);
      }
    }
    //REQ_ACTION_SENT
    else if (ftpCmdSocket->clientFlag == REQ_ACTION_SENT) {
      ftpCmdSocket->clientFlag=NO_ACTION;
      if (ftpCmdSocket->sent_cb != LUA_NOREF) {
        queue_msg_t msg;
        msg.L = gL;
        msg.source = onFTP;
        msg.para1 = file_status;
        msg.para3 = NULL;
        msg.para2 = ftpCmdSocket->sent_cb;

        mico_rtos_push_to_queue( &os_queue, &msg, 0);
      }
    }

    // ========== stage 2, check data send =====================================
    if ((ftpDataSocket != NULL) && ((status & FTP_SENDING))) {
      FD_ZERO(&wrset);
      FD_SET(ftpDataSocket->socket, &wrset);
      // check socket state
      select(ftpDataSocket->socket+1, NULL, &wrset, NULL, &t_val);
      
      if (FD_ISSET(ftpDataSocket->socket, &wrset)) {
        int err;
        if ((send_type & SEND_STRING)) err = _sendString();
        else err = _sendFile();
        if (err != 0) {
          closeDataSocket();
          // close file;
          if (file_fd != FILE_NOT_OPENED) {
            SPIFFS_close(&fs,file_fd);
            file_fd = FILE_NOT_OPENED;
            ftp_log("\r\n[FTP dta] Data file closed\r\n");
          }
          data_done = 1;
          status &= ~FTP_SENDING;
          ftpCmdSocket->clientFlag = REQ_ACTION_SENT;
        }
        continue;
      }
    }

    // ========== stage 3, check receive&disconnect ============================
    FD_ZERO(&readset);
    // ** select sockets to monitor for receive or disconnect
    int maxfd = ftpCmdSocket->socket;
    FD_SET(ftpCmdSocket->socket, &readset);
    if ( (ftpDataSocket != NULL) && ((status & FTP_DATACONNECTED)) ) {
      if (ftpDataSocket->socket > maxfd) maxfd = ftpDataSocket->socket;
      FD_SET(ftpDataSocket->socket, &readset);
    }
    // ** check sockets state
    select(maxfd+1, &readset, NULL, NULL, &t_val);

    // ** Check COMMAND socket
    if (FD_ISSET(ftpCmdSocket->socket, &readset)) {
      // read received data to buffer
      int rcv_len;
      if ((MAX_RECV_LEN-recvLen) > 1) {
        rcv_len = recv(ftpCmdSocket->socket, (recvBuf+recvLen), MAX_RECV_LEN-recvLen-1, 0);
      }
      else { // buffer full, ignore received bytes
        char tmpb[16];
        rcv_len = recv(ftpCmdSocket->socket, &tmpb[0], 16, 0);
      }
      
      if (rcv_len <= 0) { // failed
        ftp_log("\r\n[FTP cmd] Disconnect!\r\n");
        ftpCmdSocket->clientFlag = REQ_ACTION_DISCONNECT;
        continue;
      }
      
      recvLen += rcv_len;
      _checkCmdResponse(); // leave only the last line in buffer
      timeout = mico_get_time();
      recv_tmo = 0;
    }

    // ** Check DATA socket
    if ( (ftpDataSocket != NULL) && ((status & FTP_DATACONNECTED)) ) {
      if (FD_ISSET(ftpDataSocket->socket, &readset)) {
        // read received data to buffer
        int rcv_len = recv(ftpDataSocket->socket, (recvDataBuf+recvDataLen), max_recv_datalen-recvDataLen-1, 0);

        if (rcv_len <= 0) { // failed
          if (!(status & (FTP_RECEIVING | FTP_LISTING))) {
            ftp_log("\r\n[FTP dta] Disconnect!\r\n");
            closeDataSocket();
            file_status = -9;
            data_done = 1;
          }
          continue;
        }
        else {
          if ((status & FTP_RECEIVING) && (recv_type == RECV_TOFILE)) {
            // === write received data to file ===
            recvDataLen = rcv_len;
            _saveData(0);
            recvDataLen = 0;
          }
          else if ((status & FTP_LISTING) || ((status & FTP_RECEIVING) && (recv_type == RECV_TOSTRING))) {
            if ((recvDataLen + rcv_len) < (max_recv_datalen-16)) recvDataLen += rcv_len;
            else recvDataLen = max_recv_datalen-16;
            *(recvDataBuf + recvDataLen) = '\0';
          }
        }
        timeout = mico_get_time();
        recv_tmo = 0;
      }
    }

    // ===== nothing received ==================================================
    recv_tmo++;
    if (recv_tmo < 10) continue;
    
    recv_tmo = 0;

    // == Check if something was received from Command socket ==
    if (recvLen > 0) {
      // == Analize response ===
      response();
      recvLen = 0;
      memset(recvBuf, 0, MAX_RECV_LEN);
    }

    // == Check if Data socket was receiving ==
    if ((status & (FTP_RECEIVING | FTP_LISTING))) {
      // Finish all operattions on data socket
      if ((status & FTP_RECEIVING) && (recv_type == RECV_TOFILE)) {
        _saveData(1);
        recvDataLen = 0;
      }
      else {
        if ((status & FTP_RECEIVING) && (recv_type == RECV_TOSTRING)) {
          file_status = recvDataLen;
        }
        ftp_log("[FTP dta] Data received (%d)\r\n", recvDataLen);
      }
      
      if ((status & FTP_LISTING)) {
        status &= ~FTP_LISTING;
        ftpCmdSocket->clientFlag = REQ_ACTION_LIST_RECEIVED;
      }
      if ((status & FTP_RECEIVING)) {
        status &= ~FTP_RECEIVING;
        ftpCmdSocket->clientFlag = REQ_ACTION_RECEIVED;
      }

      // Close data socket
      closeDataSocket();
      data_done = 1;
    }
  } // while

terminate:
  _ftp_deinit(0);
  ftp_log("\r\n[FTP trd] FTP THREAD TERMINATED\r\n");
  ftp_thread_is_started = false;
  mico_rtos_delete_thread( NULL );
}
QgsGeometryCheckerSetupTab::QgsGeometryCheckerSetupTab( QgisInterface *iface, QDialog *checkerDialog, QWidget *parent )
  : QWidget( parent )
  , mIface( iface )
  , mCheckerDialog( checkerDialog )

{
  ui.setupUi( this );
  ui.progressBar->hide();
  ui.labelStatus->hide();
  mRunButton = ui.buttonBox->addButton( tr( "Run" ), QDialogButtonBox::ActionRole );
  mAbortButton = new QPushButton( tr( "Abort" ) );
  mRunButton->setEnabled( false );

  const auto drivers = QgsVectorFileWriter::ogrDriverList( QgsVectorFileWriter::SortRecommended | QgsVectorFileWriter::SkipNonSpatialFormats );
  for ( const QgsVectorFileWriter::DriverDetails &driver : drivers )
  {
    ui.comboBoxOutputFormat->addItem( driver.longName, driver.driverName );
  }
  ui.listWidgetInputLayers->setIconSize( QSize( 16, 16 ) );

  ui.lineEditFilenamePrefix->setText( QSettings().value( "/geometry_checker/previous_values/filename_prefix", tr( "checked_" ) ).toString() );

  connect( mRunButton, &QAbstractButton::clicked, this, &QgsGeometryCheckerSetupTab::runChecks );
  connect( ui.listWidgetInputLayers, &QListWidget::itemChanged, this, &QgsGeometryCheckerSetupTab::validateInput );
  connect( QgsProject::instance(), &QgsProject::layersAdded, this, &QgsGeometryCheckerSetupTab::updateLayers );
  connect( QgsProject::instance(), static_cast<void ( QgsProject::* )( const QStringList & )>( &QgsProject::layersRemoved ), this, &QgsGeometryCheckerSetupTab::updateLayers );
  connect( ui.radioButtonOutputNew, &QAbstractButton::toggled, ui.frameOutput, &QWidget::setEnabled );
  connect( ui.buttonGroupOutput, static_cast<void ( QButtonGroup::* )( int )>( &QButtonGroup::buttonClicked ), this, &QgsGeometryCheckerSetupTab::validateInput );
  connect( ui.pushButtonOutputDirectory, &QAbstractButton::clicked, this, &QgsGeometryCheckerSetupTab::selectOutputDirectory );
  connect( ui.lineEditOutputDirectory, &QLineEdit::textChanged, this, &QgsGeometryCheckerSetupTab::validateInput );
  connect( ui.checkBoxSliverPolygons, &QAbstractButton::toggled, ui.widgetSliverThreshold, &QWidget::setEnabled );
  connect( ui.checkBoxSliverArea, &QAbstractButton::toggled, ui.doubleSpinBoxSliverArea, &QWidget::setEnabled );
  connect( ui.checkLineLayerIntersection, &QAbstractButton::toggled, ui.comboLineLayerIntersection, &QComboBox::setEnabled );
  connect( ui.checkBoxFollowBoundaries, &QAbstractButton::toggled, ui.comboBoxFollowBoundaries, &QComboBox::setEnabled );

  for ( const QgsGeometryCheckFactory *factory : QgsGeometryCheckFactoryRegistry::getCheckFactories() )
  {
    factory->restorePrevious( ui );
  }
  updateLayers();
}