int main(int argc, char** argv)
{
  //define a matrix;
  Matrix m;

  //parse command line and generate an assignment
  CmdParser parser(argc, argv);
  parser.DisplayInput();

  Assignment as;
  if(parser.GetInputFileName().empty()){
    if(parser.GetSeed())
      as.SetSeed(parser.GetSeed());
    else
      as.SetSeed(time(NULL));
    cout<<endl<<"  *Seed for random generator: "<<as.GetSeed()<<endl;
    m=as.RandomGenerate( parser.GetAssignmentSize(), 
			 parser.GetAssignmentSize(), 
			 MAX_RANDOM, 
			 parser.GetSeed() );
  }
  else{
    ifstream myfile(parser.GetInputFileName().c_str());
    m=as.ImportAssignment(myfile);
  }
  as.DisplayMatrix(m);

  //define a bipartite graph
  BipartiteGraph bg(m);
  
  //run Hungarian method
  Hungarian h(bg);
  h.HungarianAlgo();

  //for testing
  //Test t;
  //t.testHungarian();

  return 0;
}
Exemple #2
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setImgPaths();
    QPixmap bg(path+"/images/dsknight.png");
    QPalette p(palette());
    p.setBrush(QPalette::Background, bg);
    setAutoFillBackground(true);
    setPalette(p);
    mines_left = MINES;

    QWidget::setWindowIcon(QIcon(QString(path+"/images/skull.png")));
    QWidget::setFixedSize(this->size());

    //initialize the high scores
    for(unsigned int i=0; i<10; i++) {
        scores.push_back(9999);
        names.push_back("noname");
    }
    //read in the high scores from the files
    read_in_highscores();
    //construct and display the grid
    prepare_grid(50, 100, GRID_SIZE, this);
    //initialize counter for number of tiles uncovered
    numUncovered = 0;
    //initialize timer
    elapsed_time = 0;
    timer = new QTimer(this);
    timer->start(1000);
    connect (timer, SIGNAL(timeout()), this, SLOT(update_timer()));
    //set the reset button icon
    ui->reset_button->setIcon(QIcon(okay));
    ui->reset_button->setStyleSheet( "background-color: rgba( 50, 50, 50, 60% ); color: white;" );
    ui->label_2->setStyleSheet("color: white;");
    ui->mine_left_label->setStyleSheet("color: white;");
    ui->mines_left_display->setStyleSheet("color: white;");
    ui->timer_label->setStyleSheet("color: white;");
}
Exemple #3
0
void TextRoom::loadStyleSheet(const QString &fcolor, const QString &bcolor, const QString &scolor)
{

	QColor textColor;
	textColor.setNamedColor(fcolor);
	QColor backgroundColor;
	backgroundColor.setNamedColor(bcolor);
	QColor statusbarColor;
	statusbarColor.setNamedColor(scolor);
	QPalette palette;
	palette.setColor(QPalette::Text, textColor);
	palette.setColor(QPalette::Base, QColor(0, 0, 0, 0));
	textEdit->setPalette(palette);

	QPalette bgPalette;
	if ( backgroundImage == 0 )
	{
		bgPalette.setColor(QPalette::Window, backgroundColor);
	}
	else
	{
		QPixmap bgmain;
		bgmain.load( backgroundImage );
		QDesktopWidget* desktopWidget = QApplication::desktop();
		QRect rect = desktopWidget->geometry();
		QSize size(rect.width() , rect.height());
		QPixmap bg(bgmain.scaled(size));
		bgPalette.setBrush(QPalette::Window, bg);
	}
	TextRoom::setPalette(bgPalette);

	QPalette palette2;
	palette2.setColor(QPalette::WindowText, statusbarColor);
	palette2.setColor(QPalette::Window, QColor(0, 0, 0, 0));

	horizontalSlider->setPalette(palette2);
	statsLabel->setPalette(palette2);
	deadlineLabel->setPalette(palette2);
	
}
Exemple #4
0
    bool Socket::connect(SockAddr& remote) {
        _remote = remote;

        _fd = socket(remote.getType(), SOCK_STREAM, 0);
        if ( _fd == INVALID_SOCKET ) {
            LOG(_logLevel) << "ERROR: connect invalid socket " << errnoWithDescription() << endl;
            return false;
        }

        if ( _timeout > 0 ) {
            setTimeout( _timeout );
        }

        ConnectBG bg(_fd, remote);
        bg.go();
        if ( bg.wait(5000) ) {
            if ( bg.inError() ) {
                close();
                return false;
            }
        }
        else {
            // time out the connect
            close();
            bg.wait(); // so bg stays in scope until bg thread terminates
            return false;
        }

        if (remote.getType() != AF_UNIX)
            disableNagle(_fd);

#ifdef SO_NOSIGPIPE
        // ignore SIGPIPE signals on osx, to avoid process exit
        const int one = 1;
        setsockopt( _fd , SOL_SOCKET, SO_NOSIGPIPE, &one, sizeof(int));
#endif

        _fdCreationMicroSec = curTimeMicros64();
        return true;
    }
Exemple #5
0
QwtText ViSpectrumPlotPicker::trackerText(const QPoint &position) const
{
	QColor bg(Qt::white);
	bg.setAlpha(200);
	QPointF point = invTransform(position);

	QString valueX = QString::number(point.x(), 'f', 4);
	QString valueY = QString::number(mPlot->valueAt(point.x()), 'f', 4);
	qint32 stringSizeX = qMax(mLabelX.size(), mLabelY.size()) + 2;
	qint32 stringSizeY = qMax(valueX.size(), valueY.size());

	QString string;
	QTextStream stream(&string);
	stream << qSetFieldWidth(stringSizeX) << left << (mLabelX + ": ") << qSetFieldWidth(stringSizeY) << left << valueX << qSetFieldWidth(0) << left << mUnitX << endl;
	stream << qSetFieldWidth(stringSizeX) << left << (mLabelY + ": ") << qSetFieldWidth(stringSizeY) << right << valueY << qSetFieldWidth(0) << mUnitY;

	QwtText text(string);
	text.setFont(QFont("Courier"));
	text.setBackgroundBrush( QBrush( bg ));

	return text;
}
Exemple #6
0
void FeOverlay::splash_message( const std::string &msg,
				const std::string &rep )
{
	sf::Vector2i size;
	sf::Vector2f text_scale;
	int char_size;
	get_common( size, text_scale, char_size );

	sf::RectangleShape bg( sf::Vector2f( size.x, size.y ) );
	bg.setFillColor( m_bgColour );
	bg.setOutlineColor( m_textColour );
	bg.setOutlineThickness( -2 );

	FeTextPrimative message(
		m_fePresent.get_font(),
		m_textColour,
		sf::Color::Transparent,
		char_size );

	message.setWordWrap( true );
	message.setPosition( 2, 2 );
	message.setSize( size.x - 4, size.y - 4 );
	message.setTextScale( text_scale );

	std::string msg_str;
	m_feSettings.get_resource( msg, rep, msg_str );

	message.setString( msg_str );

	const sf::Transform &t = m_fePresent.get_transform();

	m_fePresent.tick( NULL );

	m_wnd.clear();
	m_wnd.draw( m_fePresent, t );
	m_wnd.draw( bg, t );
	m_wnd.draw( message, t );
	m_wnd.display();
}
Exemple #7
0
static void RunBuiltInCmd(commandT* cmd)
{
  if(strcmp(cmd->argv[0], "cd") == 0) {
    // FILL IN
  } else if(strcmp(cmd->argv[0], "bg") == 0) {
        if (cmd->argc == 2) {
      bg(atoi(cmd->argv[1]));
    } else {
      printf("Invalid number of arguments for bg\n");
      fflush(stdout);
    }
  } else if(strcmp(cmd->argv[0], "fg") == 0) {
    if (cmd->argc == 2) {
      fg(atoi(cmd->argv[1]));
    } else {
      printf("Invalid number of arguments for fg\n");
      fflush(stdout);
    }
  } else if(strcmp(cmd->argv[0], "jobs") == 0) {
      printJobs();
  }  
}
Exemple #8
0
void
draw_conbg (ALLEGRO_BITMAP *bitmap, struct pos *p,
            enum em em, enum vm vm)
{
  switch (bg (p)) {
  case NO_BG:
    if (em == PALACE) draw_bricks_02 (bitmap, p, em, vm);
    break;
  case BRICKS_00: draw_bricks_00 (bitmap, p, em, vm); break;
  case BRICKS_01: draw_bricks_01 (bitmap, p, em, vm); break;
  case BRICKS_02: draw_bricks_02 (bitmap, p, em, vm); break;
  case BRICKS_03: draw_bricks_03 (bitmap, p, em, vm); break;
  case NO_BRICKS: break;
  case TORCH: draw_torch (bitmap, p, em, vm); break;
  case WINDOW: draw_window (bitmap, p, em, vm); break;
  case BALCONY: draw_balcony (bitmap, p, em, vm); break;
  default: assert (false); break;
  }

  if (fake (p) == LEVEL_DOOR)
    draw_level_door (bitmap, p, em, vm);
}
Exemple #9
0
Board::Board(QWidget *parent, const char *name) : 
       QWidget(parent, name, WResizeNoErase), field(0),
       _x_tiles(0), _y_tiles(0),
       _delay(125), paused(false),
       gravity_flag(true), _solvable_flag(true),
	     grav_col_1(-1), grav_col_2(-1), highlighted_tile(-1)
{
	// Randomize
	setShuffle(DEFAULTSHUFFLE);

	random.setSeed(0);
	starttime = time((time_t *)0);

	setDelay(DEFAULTDELAY);
	_redo.setAutoDelete(true);
	_undo.setAutoDelete(true);

	QPixmap bg(KGlobal::dirs()->findResource("appdata", "kshisen_bgnd.png"));
	setBackgroundPixmap(bg);

	loadSettings();
}
Exemple #10
0
int main(int argc, char *argv[])
{
	int fps = 30;
	// get ready the data pools
    AbosPool capture_pool, bg_pool, output_pool;
    capture_pool.clear();   // to make sure it is empty at first
	bg_pool.clear();
	output_pool.clear();
	//init the three modules we wrote
    // image capture
    ImageCapture image_capture( fps );
    image_capture.setDeviceFile("./ftmovie.avi");   // read
    image_capture.setImagePool(&capture_pool);    // write
	//BG averaging
	Background bg(&capture_pool, &bg_pool, 0.025,fps);
	//BG subtraction and thresholding
	BGSubtract bgSub(&capture_pool, &bg_pool, &output_pool, 20,fps);
	// configure main window (QT)
    QVector<AbosThread*> thread_vec;
	QVector<AbosPool*> pool_vec;
	thread_vec.append(&bg);
	thread_vec.append(&bgSub);
	thread_vec.append(&image_capture);
	pool_vec.append(&capture_pool);
	pool_vec.append(&bg_pool);
	pool_vec.append(&output_pool);
    QApplication a(argc, argv);
    MainWindow w(&output_pool, thread_vec, pool_vec, fps);
	w.startThreads(true);
    // start each threads
    w.show();
    // run main event loop of QT
    int ret = a.exec();
    // wait until every thread finish
    while ( image_capture.isRunning() ) { }
	printf("Successfully terminated.\n");
    return ret;
}
Exemple #11
0
void PicContainer::paintEvent(QPaintEvent *e)
{
	QPainter painter(this);
	QBrush bg(QColor(170, 170, 170));

	painter.fillRect(this->rect(), bg);

	if ( m_picPath != "" )
	{
		int border = 20;
		QRect targetRect(border, border, this->width()-2*border, this->height()-2*border);

		double rateW = double(m_pic->width()) / double(targetRect.width());
		double rateH = double(m_pic->height()) / double(targetRect.height());

		QRect realRect;

		if ( rateW > rateH )
		{
			// rateW is right.
			int realH = int(double(m_pic->height()) / rateW);
			realRect.setX(targetRect.x());
			realRect.setY((targetRect.height() - realH)/2 + targetRect.y());
			realRect.setWidth(targetRect.width());
			realRect.setHeight(realH);
		}
		else
		{
			int realW = int(double(m_pic->width()) / rateH);
			realRect.setX((targetRect.width() - realW)/2 + targetRect.x());
			realRect.setY(targetRect.y());
			realRect.setWidth(realW);
			realRect.setHeight(targetRect.height());
		}

		painter.drawPixmap(realRect, *m_pic, m_pic->rect());
	}
}
Exemple #12
0
int builtInCommand(char *argv) {
	if (strcmp(argv, "exit") == 0) {
		exit(EXIT_SUCCESS);
	}
	else if (strncmp(argv, "cd", 2) == 0) {
		return cd(argv);
	}
	else if (strcmp(argv, "jobs") == 0) {
		printJobs();

		return 1;
	}
	else if (strncmp(argv, "bg", 2) == 0) {
		bg(argv);
		return 1;
	}
	else if (strncmp(argv, "fg", 2) == 0) {
		fg(argv);
		return 1;
	}

	return 0;
}
Exemple #13
0
static QIcon codeIcon(const QString& s, QFont f)
      {
      f.setPixelSize(40);
      int w = 40;
      int h = 40;

      QWidget wi;

      QPixmap image(w, h);
      QColor bg(wi.palette().brush(QPalette::Normal, QPalette::Window).color());

      image.fill(QColor(255, 255, 255, 0));
      QPainter painter(&image);
      painter.setRenderHint(QPainter::TextAntialiasing, true);
      painter.setFont(f);

      QPen pen(wi.palette().brush(QPalette::Normal, QPalette::Text).color());

      painter.setPen(pen);
      painter.drawText(0, 0, w, h, Qt::AlignCenter, s);
      painter.end();
      return QIcon(image);
      }
int main(int argc, char *argv[])
{
    cv::Mat frame;
    cv::Mat back;
    cv::Mat fore;
    cv::VideoCapture cap(0);

//    const int history = 5;
//    const int nmixtures =3;
//    const bool bShadowDetection = true;
//    cv::BackgroundSubtractorMOG2 bg(history, nmixtures, bShadowDetection);

    cv::BackgroundSubtractorMOG2 bg;
//    bg.nmixtures = 3;
//    bg.bShadowDetection = false;

    std::vector<std::vector<cv::Point> > contours;

    cv::namedWindow("Frame");
    cv::namedWindow("Background");

    for(;;)
    {
        cap >> frame;
        bg(frame,fore);
//        bg.operator ()(frame,fore);
        bg.getBackgroundImage(back);
        cv::erode(fore,fore,cv::Mat());
        cv::dilate(fore,fore,cv::Mat());
        cv::findContours(fore,contours,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_NONE);
        cv::drawContours(frame,contours,-1,cv::Scalar(0,0,255),2);
        cv::imshow("Frame",frame);
        cv::imshow("Background",back);
        if(cv::waitKey(30) >= 0) break;
    }
    return 0;
}
Exemple #15
0
void TrayButton::drawButton(QPainter *p)
{
    QPixmap bg(size());
    QPainter pbg;

    pbg.begin(&bg);
    if (parentWidget() && parentWidget()->backgroundPixmap())
        pbg.drawTiledPixmap(0, 0, width(), height(), *(parentWidget()->backgroundPixmap()), x(), y());
    else
        pbg.fillRect(rect(), colorGroup().brush(QColorGroup::Background));


    if (isDown() || isOn())
    {
        // Draw shapes to indicate the down state.
        style().drawPrimitive(QStyle::PE_Panel, &pbg, rect(), colorGroup(),
                              QStyle::Style_Sunken);
    }
    pbg.end();

    p->drawPixmap(0,0,bg); // draw the background

    QPixmap pixmap = iconSet()->pixmap(
                         QIconSet::Automatic,
                         isEnabled() ? QIconSet::Normal : QIconSet::Disabled,
                         isOn() ? QIconSet::On : QIconSet::Off);

    // draw icon
    if(!pixmap.isNull())
    {
        QRect br(1, 1, width()-2, height()-2);
        int dx = (br.width() - pixmap.width()) / 2;
        int dy = (br.height() - pixmap.height()) / 2;
        p->drawPixmap(br.x() + dx, br.y() + dy, pixmap);
    }
}
Exemple #16
0
void UserView::paintEmptyArea(QPainter *p, const QRect &r)
{
    if ((r.width() == 0) || (r.height() == 0))
        return;
    QPixmap bg(r.width(), r.height());
    QPainter pp(&bg);
    pp.fillRect(QRect(0, 0, r.width(), r.height()), colorGroup().base());
    PaintView pv;
    pv.p        = &pp;
    pv.pos      = viewport()->mapToParent(r.topLeft());
    pv.size	= r.size();
    pv.win      = this;
    pv.isStatic = false;
    pv.height   = r.height();
    pv.margin   = 0;
    QListViewItem *item = firstChild();
    if (item)
        pv.height = item->height();
    Event e(EventPaintView, &pv);
    e.process();
    pp.end();
    p->drawPixmap(r.topLeft(), bg);
    setStaticBackground(pv.isStatic);
}
void http_cache::get (const std::string& url, int timeout_msec,
                      std::function<void(std::string)> callback) const
{
    auto file (cache_file(url));
    if (fs::exists(file))
    {
        callback(file_contents(url));
        return;
    }

    boost::thread bg ([=]{
        http::client::request rq (url);
        rq << header("Connection", "close");
        http::client temp_client;
        std::string data (http::body(temp_client.get(rq)));

        std::ofstream out (file.string(), std::ios::binary);
        out.write(&data[0], data.size());
        out.close();

        callback(std::move(data));
    });
    bg.detach();
}
void SeqPhraseMatrixView::DrawTopLevelPhrase(	BRect clip,
        BView* view,
        const AmTrack* track,
        const AmPhraseEvent* event,
        AmTime end,
        AmPhraseEvent* topPhrase,
        AmPhraseRendererI* renderer)
{
    ArpASSERT(event && topPhrase);
    if (!event || !event->Phrase() ) return;
    const AmPhrase*		phrase = event->Phrase();
    BRect				entireF(0, clip.top + 3, 0, clip.bottom - 3);
    AmTime				phraseEnd = event->EndTime();
    BString				n = event->Phrase()->Name();
    float				labelH = mCurLabelH + 3;
    bool				drawLabel = mCurLabelH > 0 && labelH < entireF.Height() && n.Length() > 0;

    entireF.left = mMtc.TickToPixel(event->StartTime()) - 2;
    entireF.right = mMtc.TickToPixel(phraseEnd) + 2;
    BRect				labelF = arp_invalid_rect();
    BRect				contentF = arp_invalid_rect();
    if (drawLabel) {
        if (entireF.Height() - 4 > labelH + 4) {
            labelF.Set(entireF.left + 2, entireF.top + 2, entireF.right - 2, entireF.bottom - 2);
            contentF = labelF;
            labelF.bottom = labelF.top + labelH - 1;
            contentF.top = labelF.bottom + 1;
        } else labelF.Set(entireF.left + 2, entireF.top + 2, entireF.right - 2, entireF.bottom - 2);
    } else contentF.Set(entireF.left + 2, entireF.top + 2, entireF.right - 2, entireF.bottom - 2);

    rgb_color			bgC = phrase->Color(phrase->BACKGROUND_C);
    rgb_color			fgC = phrase->Color(phrase->FOREGROUND_C);
    if (mDrawMuted) {
        bgC = shade_color(bgC, MUTE_SHADE);
        fgC = shade_color(fgC, MUTE_SHADE);
    }
    if (arp_is_valid_rect(contentF) ) {
        /* Fill the background.
         */
        if (!mDrawMuted) {
            view->SetHighColor(bgC);
            view->FillRect(contentF);
        }
        /* Draw the measure markers.
         */
        AmTrackMeasureBackground		bg(mSongRef, AmTrackRef(track), mMtc);
        if (mDrawMuted) bg.SetFlag(bg.DRAW_BEATS_FLAG, false);
        else {
            rgb_color	c = weighted_shade(bgC, Prefs().Color(AM_MEASURE_FG_C), 5);
            bg.SetBeatColor(c);
        }
        bg.LockedDraw(view, contentF, track->Signatures() );
    }

    mLines.BeginLineArray();
    if (arp_is_valid_rect(labelF) ) {
        rgb_color	c = weighted_shade(bgC, fgC, 3);
        view->SetHighColor(c);
        view->SetLowColor(c);
        view->FillRect(labelF);
        draw_label_border(view, labelF, c, mLines, mDrawMuted, !arp_is_valid_rect(contentF));
        view->SetHighColor(Prefs().Color(AM_MEASURE_FG_C) );
        BPoint		pt(labelF.left + 2, labelF.bottom - 2);
        if (arp_is_valid_rect(contentF) ) pt.y -= 2;
        view->TruncateString(&n, B_TRUNCATE_END, labelF.Width() );
        view->DrawString(n.String(), pt);
    }

    /* Shade the background.
     */
    rgb_color		c;
    c.red = c.green = c.blue = 0;
    if (mDrawMuted) c = shade_color(c, MUTE_SHADE);
    mLines.AddLine(BPoint(entireF.left + 1, entireF.top), BPoint(entireF.right - 1, entireF.top), c);
    mLines.AddLine(BPoint(entireF.left + 1, entireF.bottom), BPoint(entireF.right - 1, entireF.bottom), c);
    mLines.AddLine(BPoint(entireF.left, entireF.top + 1), BPoint(entireF.left, entireF.bottom - 1), c);
    mLines.AddLine(BPoint(entireF.right, entireF.top + 1), BPoint(entireF.right, entireF.bottom - 1), c);

    if (arp_is_valid_rect(contentF) ) {
        draw_content_border(view, contentF, bgC, mLines, mDrawMuted, !arp_is_valid_rect(labelF));
    }

    c = tint_color(Prefs().Color(AM_DATA_BACKDROP_C), B_DARKEN_1_TINT);
    if (mDrawMuted) c = shade_color(c, MUTE_SHADE);
    if (!gPhraseBg) {
        mLines.AddLine(BPoint(entireF.right + 1, entireF.top + 2), BPoint(entireF.right + 1, entireF.bottom + 0), c);
        mLines.AddLine(BPoint(entireF.left + 2, entireF.bottom + 1), BPoint(entireF.right + 0, entireF.bottom + 1), c);
        mLines.AddLine(BPoint(entireF.right + 0, entireF.bottom + 0), BPoint(entireF.right + 0, entireF.bottom + 0), c);
    }

    /* Indicate if this phrase is linked.
     */
    if (phrase->CountLinks() > 0) {
        view->SetHighColor(bgC);
        view->SetLowColor(0, 0, 0);
        view->StrokeRect(entireF, LINK_PATTERN);
    }

    if (arp_is_valid_rect(contentF) ) {
        /* Draw the events.
         */
        if (renderer) {
            BRect					trackR(clip.left, contentF.top, clip.right, contentF.bottom);
            view->SetHighColor(fgC);
            renderer->BeginTrack(trackR, view, track, mLines);
            renderer->DrawPhrase(contentF, view, track, event, end < phraseEnd ? end : phraseEnd, topPhrase, mLines);
            renderer->EndTrack(trackR, view, track, mLines);
        }
    }
    /* Finish.
     */
    mLines.EndLineArray();
}
Exemple #19
0
//--------------------------------------------------------------
void ofApp::setup(){
    
    //ENVIRONMENT AND MAXIMILIAN
    ofSetFrameRate(60);
    ofSetVerticalSync(true);
    ofEnableAlphaBlending();
    ofEnableSmoothing();
    ofBackground(0,0,0);
    sampleRate 	= 44100; /* Audio sampling rate */
    bufferSize	= 512; /* Audio buffer size */
    ofxMaxiSettings::setup(sampleRate, 2, bufferSize);
    
    ofColor bg(100,100,100,150);
    ofColor fg(255);
    
    //sequencing
    now = ofGetElapsedTimeMillis();
    delay = 1000;
    numSequencerSteps = 16;
    
    //UI positions and dimensions
    padBounds.x = 150;
    padBounds.y = 50;
    padBounds.width = padBounds.height = 625;
    
    sequencerX = padBounds.x+padBounds.width+25;
    sequencerY = padBounds.y;
    sequencerW = 330;
    sequencerToggleH = 100;
    sequencerStepH = 25;
    
    //parameter names
    xParamName = "x";
    yParamName = "y";
    timerParamName = "timer";
    playbackParamName = "playback";
    filterSpeedParamName = "filter speed";
    resetParamName = "reset gesture";
    
    //ZONE SETUP
    //parameters: name, x, y, width, background color, foreground color, sound filename, sound buffer size
    //PAD
    zonePad.setup("padZone", padBounds.x, padBounds.y, padBounds.width, bg,fg, "kick.wav", bufferSize);
    zonePad.addParameterFloat(xParamName, 0.0, 1.0, 0.5);
    zonePad.addParameterFloat(yParamName, 0.0, 1.0, 0.5);
    zonePad.addUI(new ofxAVUIXYPad("Pad", "","", xParamName,yParamName), padBounds.height);
    
    //SEQUENCER
    //kick.wav = https://www.freesound.org/people/DWSD/sounds/171104/
    zoneSequencer.setup("toggleZone", sequencerX, sequencerY, sequencerW, bg, fg, "kick.wav", bufferSize);
    //ZONE UI
    zoneSequencer.addParameterBool(playbackParamName, true);
    zoneSequencer.addUI(new ofxAVUIToggle(playbackParamName,playbackParamName), sequencerToggleH);

    sequencerTogglePrefix = "toggle #";
    for(int i = 0 ; i < numSequencerSteps; i++){
        string toggleParamName = sequencerTogglePrefix + (ofToString(i));
        zoneSequencer.addParameterBool(toggleParamName, false);
        zoneSequencer.addUI(new ofxAVUIToggle(toggleParamName,toggleParamName), sequencerStepH);
    }
    //timer control
    //params
    zoneSequencer.addParameterFloat(timerParamName, 125, 2000, delay);
    zoneSequencer.addParameterBool(resetParamName, false);
    zoneSequencer.addParameterFloat(filterSpeedParamName, 0.010, 0.100, 0.025);
    //ui
    zoneSequencer.addUI(new ofxAVUIEmpty(""), sequencerStepH);
    //slider parameters: caption, trigger (single tap) parameter name, toggle (double tap) parameter name, x parameter name
    zoneSequencer.addUI(new ofxAVUISlider(timerParamName,"","",timerParamName), sequencerStepH);
    zoneSequencer.addUI(new ofxAVUISlider(filterSpeedParamName,"","",filterSpeedParamName), sequencerStepH);
    zoneSequencer.addUI(new ofxAVUIEmpty(""), sequencerStepH);
    zoneSequencer.addUI(new ofxAVUIButton(resetParamName,resetParamName),sequencerStepH);
    //sound FX
    ofxAVUISoundFxFilter *sfx = new ofxAVUISoundFxFilter();
    //sound fx parameters:
    //- filter enabled toggle name (will be linked to any toggle UI with same name), start value
    //- 1st parameter float name (will be linked to any toggle UI with same name), min value, max value, start value
    //- 2nd parameter float name (will be linked to any toggle UI with same name), min value, max value, start value
    sfx->setup("filterToggle", true, "frequency", 200, 15000, 200, "resonance", 1, 100, 10);
    zoneSequencer.addSoundFx(sfx);
    //visual
    zoneSequencer.addVisual(new ofxAVUIVisualBars(numSequencerSteps), ofColor(255, 127));
    //START SOUND
    ofSoundStreamSetup(2,2,this, sampleRate, bufferSize, 4); /* this has to happen at the end of setup*/
    
}
Exemple #20
0
ToolBar::ToolBar(const QString &title, QWidget *parent)
    : QToolBar(parent), spinbox(0), spinboxAction(0)
{
    tip = 0;
    setWindowTitle(title);
    setObjectName(title);

    setIconSize(QSize(32, 32));

    QColor bg(palette().background().color());
    menu = new QMenu("One", this);
    menu->setIcon(genIcon(iconSize(), 1, Qt::black));
    menu->addAction(genIcon(iconSize(), "A", Qt::blue), "A");
    menu->addAction(genIcon(iconSize(), "B", Qt::blue), "B");
    menu->addAction(genIcon(iconSize(), "C", Qt::blue), "C");
    addAction(menu->menuAction());

    QAction *two = addAction(genIcon(iconSize(), 2, Qt::white), "Two");
    QFont boldFont;
    boldFont.setBold(true);
    two->setFont(boldFont);

    addAction(genIcon(iconSize(), 3, Qt::red), "Three");
    addAction(genIcon(iconSize(), 4, Qt::green), "Four");
    addAction(genIcon(iconSize(), 5, Qt::blue), "Five");
    addAction(genIcon(iconSize(), 6, Qt::yellow), "Six");
    orderAction = new QAction(this);
    orderAction->setText(tr("Order Items in Tool Bar"));
    connect(orderAction, SIGNAL(triggered()), SLOT(order()));

    randomizeAction = new QAction(this);
    randomizeAction->setText(tr("Randomize Items in Tool Bar"));
    connect(randomizeAction, SIGNAL(triggered()), SLOT(randomize()));

    addSpinBoxAction = new QAction(this);
    addSpinBoxAction->setText(tr("Add Spin Box"));
    connect(addSpinBoxAction, SIGNAL(triggered()), SLOT(addSpinBox()));

    removeSpinBoxAction = new QAction(this);
    removeSpinBoxAction->setText(tr("Remove Spin Box"));
    removeSpinBoxAction->setEnabled(false);
    connect(removeSpinBoxAction, SIGNAL(triggered()), SLOT(removeSpinBox()));

    movableAction = new QAction(tr("Movable"), this);
    movableAction->setCheckable(true);
    connect(movableAction, SIGNAL(triggered(bool)), SLOT(changeMovable(bool)));

    allowedAreasActions = new QActionGroup(this);
    allowedAreasActions->setExclusive(false);

    allowLeftAction = new QAction(tr("Allow on Left"), this);
    allowLeftAction->setCheckable(true);
    connect(allowLeftAction, SIGNAL(triggered(bool)), SLOT(allowLeft(bool)));

    allowRightAction = new QAction(tr("Allow on Right"), this);
    allowRightAction->setCheckable(true);
    connect(allowRightAction, SIGNAL(triggered(bool)), SLOT(allowRight(bool)));

    allowTopAction = new QAction(tr("Allow on Top"), this);
    allowTopAction->setCheckable(true);
    connect(allowTopAction, SIGNAL(triggered(bool)), SLOT(allowTop(bool)));

    allowBottomAction = new QAction(tr("Allow on Bottom"), this);
    allowBottomAction->setCheckable(true);
    connect(allowBottomAction, SIGNAL(triggered(bool)), SLOT(allowBottom(bool)));

    allowedAreasActions->addAction(allowLeftAction);
    allowedAreasActions->addAction(allowRightAction);
    allowedAreasActions->addAction(allowTopAction);
    allowedAreasActions->addAction(allowBottomAction);

    areaActions = new QActionGroup(this);
    areaActions->setExclusive(true);

    leftAction = new QAction(tr("Place on Left") , this);
    leftAction->setCheckable(true);
    connect(leftAction, SIGNAL(triggered(bool)), SLOT(placeLeft(bool)));

    rightAction = new QAction(tr("Place on Right") , this);
    rightAction->setCheckable(true);
    connect(rightAction, SIGNAL(triggered(bool)), SLOT(placeRight(bool)));

    topAction = new QAction(tr("Place on Top") , this);
    topAction->setCheckable(true);
    connect(topAction, SIGNAL(triggered(bool)), SLOT(placeTop(bool)));

    bottomAction = new QAction(tr("Place on Bottom") , this);
    bottomAction->setCheckable(true);
    connect(bottomAction, SIGNAL(triggered(bool)), SLOT(placeBottom(bool)));

    areaActions->addAction(leftAction);
    areaActions->addAction(rightAction);
    areaActions->addAction(topAction);
    areaActions->addAction(bottomAction);

    toolBarBreakAction = new QAction(tr("Insert break"), this);
    connect(toolBarBreakAction, SIGNAL(triggered(bool)), this, SLOT(insertToolBarBreak()));

    connect(movableAction, SIGNAL(triggered(bool)), areaActions, SLOT(setEnabled(bool)));

    connect(movableAction, SIGNAL(triggered(bool)), allowedAreasActions, SLOT(setEnabled(bool)));

    menu = new QMenu(title, this);
    menu->addAction(toggleViewAction());
    menu->addSeparator();
    menu->addAction(orderAction);
    menu->addAction(randomizeAction);
    menu->addSeparator();
    menu->addAction(addSpinBoxAction);
    menu->addAction(removeSpinBoxAction);
    menu->addSeparator();
    menu->addAction(movableAction);
    menu->addSeparator();
    menu->addActions(allowedAreasActions->actions());
    menu->addSeparator();
    menu->addActions(areaActions->actions());
    menu->addSeparator();
    menu->addAction(toolBarBreakAction);

    connect(menu, SIGNAL(aboutToShow()), this, SLOT(updateMenu()));

    randomize();
}
Exemple #21
0
void OSDWidget::showOSD(const QString &str, OSDUserData *data)
{
    if (isScreenSaverActive()){
        hide();
        return;
    }
    setFont(FontEdit::str2font(data->Font.ptr, baseFont));
    QPainter p(this);
    p.setFont(font());
    unsigned nScreen = data->Screen.value;
    unsigned nScreens = screens();
    if (nScreen >= nScreens)
        nScreen = 0;
    QRect rcScreen = screenGeometry(nScreen);
    rcScreen = QRect(0, 0,
                     rcScreen.width() - SHADOW_OFFS - XOSD_MARGIN * 2 - data->Offset.value,
                     rcScreen.height() - SHADOW_OFFS - XOSD_MARGIN * 2 - data->Offset.value);
    QRect rc = p.boundingRect(rcScreen, AlignLeft | AlignTop | WordBreak, str);
    p.end();
    if (data->EnableMessageShowContent.bValue && data->ContentLines.value){
        QFontMetrics fm(font());
        int maxHeight = fm.height() * (data->ContentLines.value + 1);
        if (rc.height() > maxHeight)
            rc.setHeight(maxHeight);
    }
    int x = rcScreen.left();
    int y = rcScreen.top();
    int w = rc.width() + 1;
    int h = rc.height() + 1;
	int text_y = 0;
    if (data->Background.bValue){
        w += XOSD_MARGIN * 2;
        h += XOSD_MARGIN * 2;
		if (m_button == NULL){
			m_button = new QPushButton("", this);
			m_button->setPixmap(QPixmap((const char **)close_h_xpm)); 
			connect(m_button, SIGNAL(clicked()), this, SLOT(slotCloseClick()));
		}
		QSize s = m_button->sizeHint();
		m_button->resize(s.height() - 4, s.height() - 4);
		m_button->move(w - m_button->width() - 3, 2);
		text_y = m_button->height() + 4;
		h += text_y;
		m_button->show();
	}else{
		if (m_button){
			delete m_button;
			m_button = NULL;
		}
	}
    if (data->Shadow.bValue){
        w += SHADOW_OFFS;
        h += SHADOW_OFFS;
    }
    resize(QSize(w, h));
    switch (data->Position.value){
    case 1:
        move(x + data->Offset.value, y + data->Offset.value);
        break;
    case 2:
        move(x + rcScreen.width() - data->Offset.value - w, y + rcScreen.height() - data->Offset.value - h);
        break;
    case 3:
        move(x + rcScreen.width() - data->Offset.value - w, y + data->Offset.value);
        break;
    case 4:
        move(x + (rcScreen.width() - w) / 2, y + rcScreen.height() - data->Offset.value - h);
        break;
    case 5:
        move(x + (rcScreen.width() - w) / 2, y + data->Offset.value);
        break;
    case 6:
        move(x + (rcScreen.width() - w) / 2, y + (rcScreen.height() - h) /2);
        break;
    default:
        move(x + data->Offset.value, y + rcScreen.height() - data->Offset.value - h);
    }
    if (!data->Background.bValue || data->Shadow.bValue){
        QBitmap mask(w, h);
        p.begin(&mask);
#ifdef WIN32
        QColor bg(255, 255, 255);
        QColor fg(0, 0, 0);
#else
        QColor bg(0, 0, 0);
        QColor fg(255, 255, 255);
#endif
        p.fillRect(0, 0, w, h, bg);
        if (data->Background.bValue){
            p.fillRect(0, 0, w - SHADOW_OFFS, h - SHADOW_OFFS, fg);
            p.fillRect(SHADOW_OFFS, SHADOW_OFFS, w - SHADOW_OFFS, h - SHADOW_OFFS, fg);
        }else{
            p.setPen(fg);
            p.setFont(font());
            if (data->Shadow.bValue){
                rc = QRect(SHADOW_OFFS, SHADOW_OFFS, w - SHADOW_OFFS, h - SHADOW_OFFS);
                p.drawText(rc, AlignLeft | AlignTop | WordBreak, str);
                rc = QRect(0, 0, w - SHADOW_OFFS, h - SHADOW_OFFS);
                p.drawText(rc, AlignLeft | AlignTop | WordBreak, str);
            }else{
                rc = QRect(0, 0, w, h);
                p.drawText(rc, AlignLeft | AlignTop | WordBreak, str);
            }
        }
        p.end();
        setMask(mask);
    }
    qApp->syncX();
    QPixmap pict = QPixmap::grabWindow(QApplication::desktop()->winId(), this->x(), this->y(), width(), height());
    intensity(pict, -0.50f);
    p.begin(&pict);
    rc = QRect(0, 0, w, h);
    if (data->Background.bValue){
        if (data->Shadow.bValue){
            w -= SHADOW_OFFS;
            h -= SHADOW_OFFS;
            rc = QRect(0, 0, w, h);
        }
        QBrush bg(data->BgColor.value);
        p.fillRect(rc, bg);
#if COMPAT_QT_VERSION < 0x030000
        style().drawPopupPanel(&p, 0, 0, w, h, colorGroup(), 2, &bg);
#else
        style().drawPrimitive(QStyle::PE_PanelPopup, &p, rc, colorGroup());
#endif
        rc = QRect(XOSD_MARGIN, XOSD_MARGIN, w - XOSD_MARGIN * 2, h - XOSD_MARGIN * 2);
    }
    p.setFont(font());
    p.setPen(QColor(data->Color.value));
	rc.setTop(text_y);
    p.drawText(rc, AlignLeft | AlignTop | WordBreak, str);
    p.end();
    bgPict = pict;
    QWidget::show();
    raise();
}
Exemple #22
0
bool ScopeASCOM::Connect(void)
{
    bool bError = false;

    try
    {
        Debug.AddLine("Connecting");

        if (IsConnected())
        {
            wxMessageBox("Scope already connected",_("Error"));
            throw ERROR_INFO("ASCOM Scope: Connected - Already Connected");
        }

        DispatchObj pScopeDriver;

        if (!Create(pScopeDriver))
        {
            wxMessageBox(_T("Could not establish instance of ") + m_choice, _("Error"), wxOK | wxICON_ERROR);
            throw ERROR_INFO("ASCOM Scope: Could not establish ASCOM Scope instance");
        }

        // --- get the dispatch IDs we need ...

        // ... get the dispatch ID for the Connected property ...
        if (!pScopeDriver.GetDispatchId(&dispid_connected, L"Connected"))
        {
            wxMessageBox(_T("ASCOM driver problem -- cannot connect"),_("Error"), wxOK | wxICON_ERROR);
            throw ERROR_INFO("ASCOM Scope: Could not get the dispatch id for the Connected property");
        }

        // ... get the dispatch ID for the "IsPulseGuiding" property ....
        m_bCanCheckPulseGuiding = true;
        if (!pScopeDriver.GetDispatchId(&dispid_ispulseguiding, L"IsPulseGuiding"))
        {
            m_bCanCheckPulseGuiding = false;
            Debug.AddLine("cannot get dispid_ispulseguiding");
            // don't fail if we can't get the status on this - can live without it as it's really a safety net for us
        }

        // ... get the dispatch ID for the "Slewing" property ....
        if (!pScopeDriver.GetDispatchId(&dispid_isslewing, L"Slewing"))
        {
            wxMessageBox(_T("ASCOM driver missing the Slewing property"),_("Error"), wxOK | wxICON_ERROR);
            throw ERROR_INFO("ASCOM Scope: Could not get the dispatch id for the Slewing property");
        }

        // ... get the dispatch ID for the "PulseGuide" property ....
        if (!pScopeDriver.GetDispatchId(&dispid_pulseguide, L"PulseGuide"))
        {
            wxMessageBox(_T("ASCOM driver missing the PulseGuide property"),_("Error"), wxOK | wxICON_ERROR);
            throw ERROR_INFO("ASCOM Scope: Could not get the dispatch id for the PulseGuide property");
        }

        // ... get the dispatch ID for the "Declination" property ....
        m_bCanGetCoordinates = true;
        if (!pScopeDriver.GetDispatchId(&dispid_declination, L"Declination"))
        {
            m_bCanGetCoordinates = false;
            Debug.AddLine("cannot get dispid_declination");
        }
        else if (!pScopeDriver.GetDispatchId(&dispid_rightascension, L"RightAscension"))
        {
            Debug.AddLine("cannot get dispid_rightascension");
            m_bCanGetCoordinates = false;
        }
        else if (!pScopeDriver.GetDispatchId(&dispid_siderealtime, L"SiderealTime"))
        {
            Debug.AddLine("cannot get dispid_siderealtime");
            m_bCanGetCoordinates = false;
        }

        if (!pScopeDriver.GetDispatchId(&dispid_sitelatitude, L"SiteLatitude"))
        {
            Debug.AddLine("cannot get dispid_sitelatitude");
        }
        if (!pScopeDriver.GetDispatchId(&dispid_sitelongitude, L"SiteLongitude"))
        {
            Debug.AddLine("cannot get dispid_sitelongitude");
        }

        m_bCanSlew = true;
        if (!pScopeDriver.GetDispatchId(&dispid_slewtocoordinates, L"SlewToCoordinates"))
        {
            m_bCanSlew = false;
            Debug.AddLine("cannot get dispid_slewtocoordinates");
        }

        // ... get the dispatch IDs for the two guide rate properties - if we can't get them, no sweat, doesn't matter for actual guiding
        // Used for things like calibration sanity checking, backlash clearing, etc.
        m_bCanGetGuideRates = true;         // Likely case, required for any ASCOM driver at V2 or later
        if (!pScopeDriver.GetDispatchId(&dispid_decguiderate, L"GuideRateDeclination"))
        {
            Debug.AddLine("cannot get dispid_decguiderate");
            m_bCanGetGuideRates = false;
            // don't throw if we can't get this one
        }
        else if (!pScopeDriver.GetDispatchId(&dispid_raguiderate, L"GuideRateRightAscension"))
        {
            Debug.AddLine("cannot get dispid_raguiderate");
            m_bCanGetGuideRates = false;
            // don't throw if we can't get this one
        }

        if (!pScopeDriver.GetDispatchId(&dispid_sideofpier, L"SideOfPier"))
        {
            Debug.AddLine("cannot get dispid_sideofpier");
            dispid_sideofpier = DISPID_UNKNOWN;
        }

        if (!pScopeDriver.GetDispatchId(&dispid_abortslew, L"AbortSlew"))
        {
            Debug.AddLine("cannot get dispid_abortslew");
            dispid_abortslew = DISPID_UNKNOWN;
        }

        struct ConnectInBg : public ConnectMountInBg
        {
            ScopeASCOM *sa;
            ConnectInBg(ScopeASCOM *sa_) : sa(sa_) { }
            bool Entry()
            {
                GITObjRef scope(sa->m_gitEntry);
                // ... set the Connected property to true....
                if (!scope.PutProp(sa->dispid_connected, true))
                {
                    SetErrorMsg(ExcepMsg(scope.Excep()));
                    return true;
                }
                return false;
            }
        };
        ConnectInBg bg(this);

        // set the Connected property to true in a background thread
        if (bg.Run())
        {
            wxMessageBox(_T("ASCOM driver problem during connection: ") + bg.GetErrorMsg(),
                _("Error"), wxOK | wxICON_ERROR);
            throw ERROR_INFO("ASCOM Scope: Could not set Connected property to true");
        }

        // get the scope name
        Variant vRes;
        if (!pScopeDriver.GetProp(&vRes, L"Name"))
        {
            wxMessageBox(_T("ASCOM driver problem getting Name property"), _("Error"), wxOK | wxICON_ERROR);
            throw ERROR_INFO("ASCOM Scope: Could not get the scope name: " + ExcepMsg(pScopeDriver.Excep()));
        }

        m_Name = vRes.bstrVal;

        Debug.AddLine("Scope reports its name as " + m_Name);

        m_abortSlewWhenGuidingStuck = false;

        if (m_Name == _T("Gemini Telescope .NET"))
        {
            // Gemini2 firmware (2013 Oct 13 version, perhaps others) has been found to contain a
            // bug where a pulse guide command can fail to complete, with the Guiding property
            // returning true forever. The firmware developer suggests that PHD2 should issue an
            // AbortSlew when this condition is detected.
            Debug.AddLine("ASCOM scope: enabling stuck guide pulse workaround");
            m_abortSlewWhenGuidingStuck = true;
        }

        // see if we can pulse guide
        m_bCanPulseGuide = true;
        if (!pScopeDriver.GetProp(&vRes, L"CanPulseGuide") || !vRes.boolVal)
        {
            Debug.AddLine("Connecting to ASCOM scope that does not support PulseGuide");
            m_bCanPulseGuide = false;
        }

        // see if we can slew
        if (m_bCanSlew)
        {
            if (!pScopeDriver.GetProp(&vRes, L"CanSlew"))
            {
                Debug.AddLine("ASCOM scope got error invoking CanSlew: " + ExcepMsg(pScopeDriver.Excep()));
                m_bCanSlew = false;
            }
            else if (!vRes.boolVal)
            {
                Debug.AddLine("ASCOM scope reports CanSlew = false");
                m_bCanSlew = false;
            }
        }

        pFrame->SetStatusText(Name()+_(" connected"));
        Scope::Connect();

        Debug.AddLine("Connect success");
    }
    catch (wxString Msg)
    {
        POSSIBLY_UNUSED(Msg);
        bError = true;
    }

    return bError;
}
Exemple #23
0
/*!
  Here is loaded the configuration of the server.
  The configuration file is a XML file.
  Return nonzero on errors.
 */
int Server::initialize ()
{
  const char *data;
#ifdef WIN32
  envString = GetEnvironmentStrings ();
#endif
  connectionsMutex = new Mutex ();
  threadsMutex = new Mutex ();

  /* Store the default values.  */
  nStaticThreads = 20;
  nMaxThreads = 50;
  currentThreadID = 0;
  freeThreads = 0;
  connectionTimeout = MYSERVER_SEC (180);
  endServer = false;
  purgeThreadsThreshold = 1;
  throttlingRate = 0;
  maxConnections = 0;
  maxConnectionsToAccept = 0;

  if (genMainConf)
    {
      configurationFileManager = genMainConf (this,
                                              mainConfigurationFile.c_str ());
      if (!configurationFileManager)
        {
          log (MYSERVER_LOG_MSG_ERROR,
               _("Error while loading the %s configuration file"),
               mainConfigurationFile.c_str ());
          return -1;
        }

    }
  else
    {
      XmlMainConfiguration *xmlMainConf = new XmlMainConfiguration ();
      if (xmlMainConf->open (mainConfigurationFile.c_str ()))
        {
          log (MYSERVER_LOG_MSG_ERROR,
               _("Error while loading the %s configuration file"),
               mainConfigurationFile.c_str ());
          delete xmlMainConf;
          return -1;
        }
      configurationFileManager = xmlMainConf;
    }

  configurationFileManager->readData (&hashedDataTrees, &hashedData);

  /* Process console colors information.  */
  list<string> levels = logManager->getLoggingLevelsByNames ();
  for (list<string>::iterator it = levels.begin (); it != levels.end (); it++)
    {
      string fg (*it + "_fg");
      string bg (*it + "_bg");

      string fullFg ("log_color." + *it + "_fg");
      string fullBg ("log_color." + *it + "_bg");
      data = getData (fullFg.c_str ());
      if (data)
        consoleColors[fg] = string (data);

      data = getData (fullBg.c_str ());
      if (data)
        consoleColors[bg] = string (data);
    }

  initLogManager ();

  data = getData ("server.buffer_size", "102400");
  if (data)
    buffersize = (atol (data) > 81920) ?  atol (data) :  81920 ;

  data = getData ("connection.timeout");
  if (data)
    connectionTimeout = MYSERVER_SEC ((u_long) atol (data));

  data = getData ("server.static_threads");
  if (data)
    nStaticThreads = atoi (data);

  data = getData ("server.max_threads");
  if (data)
    nMaxThreads = atoi (data);

  /* Get the max connections number to allow.  */
  data = getData ("server.max_connections");
  if (data)
    maxConnections = atoi (data);

  /* Get the max connections number to accept.  */
  data = getData ("server.max_accepted_connections");
  if (data)
    maxConnectionsToAccept = atoi (data);

  data = getData ("server.connections_pool.size");
  if (data)
    connectionsPool.init (atoi (data));

  /* Get the default throttling rate to use on connections.  */
  data = getData ("connection.throttling");
  if (data)
    throttlingRate = (u_long) atoi (data);

  data = getData ("server.max_log_size");
  if (data)
    maxLogFileSize=(u_long) atol (data);

  data = getData ("server.max_files_cache");
  if (data)
    {
      u_long maxSize = (u_long) atol (data);
      cachedFiles.initialize (maxSize);
    }
  else
    cachedFiles.initialize (1 << 23);

  data = getData ("server.temp_directory");
  if (data)
    {
      string tmpPath (data);
      FilesUtility::completePath (tmpPath);
      FilesUtility::setTmpPath (tmpPath);
    }
  else
    FilesUtility::resetTmpPath ();

  data = getData ("server.max_file_cache");
  if (data)
    {
      u_long maxSize = (u_long) atol (data);
      cachedFiles.setMaxSize (maxSize);
    }

  data = getData ("server.min_file_cache");
  if (data)
    {
      u_long minSize = (u_long) atol (data);
      cachedFiles.setMinSize (minSize);
    }

  data = getData ("server.uid");
  if (data)
    uid.assign (data);
  else
    uid.assign ("");

  data = getData ("server.gid");
  if (data)
    gid.assign (data);
  else
    gid.assign ("");

  data = getData ("server.max_servers");
  if (data)
    {
      int maxServersProcesses = atoi (data);
      getProcessServerManager ()->setMaxServers (maxServersProcesses);
    }

  return 0;
}
Exemple #24
0
void ContinuousPanel::paint(const QRect&, QPainter& painter)
      {
      qreal _offsetPanel = 0;
      qreal _y = 0;
      qreal _oldWidth = 0;        // The last final panel width
      qreal _newWidth = 0;        // New panel width
      qreal _height = 0;
      qreal _leftMarginTotal = 0; // Sum of all elments left margin
      qreal _panelRightPadding = 5;  // Extra space for the panel after last element

      Measure* measure = _score->firstMeasure();

      if (!_active || !measure) {
            _visible = false;
            return;
            }

      if (measure->mmRest()) {
            measure = measure->mmRest();
            }

      System* system   = measure->system();
      if (system == 0) {
            _visible = false;
            return;
            }

      Segment* s      = measure->first();
      double _spatium = _score->spatium();
      if (_width <= 0)
            _width  = s->x();

      //
      // Set panel height for whole system
      //
      _height = 6 * _spatium;
      _y = system->staffYpage(0) + system->page()->pos().y();
      double y2 = 0.0;
      for (int i = 0; i < _score->nstaves(); ++i) {
            SysStaff* ss = system->staff(i);
            if (!ss->show() || !_score->staff(i)->show())
                  continue;
            y2 = ss->y() + ss->bbox().height();
            }
      _height += y2 + 6*_spatium;
      _y -= 6 * _spatium;

      //
      // Check elements at current panel position
      //
      _offsetPanel = -(_sv->xoffset()) / _sv->mag();
      _rect        = QRect(_offsetPanel + _width, _y, 1, _height);
      Page* page   = _score->pages().front();
      QList<Element*> el = page->items(_rect);
      if (el.empty()) {
            _visible = false;
            return;
            }
      qStableSort(el.begin(), el.end(), elementLessThan);

      const Measure*_currentMeasure = 0;
      for (const Element* e : el) {
            e->itemDiscovered = 0;
            if (!e->visible() && !_score->showInvisible())
                  continue;

            if (e->isMeasure()) {
                  _currentMeasure = toMeasure(e);
                  break;
                  }
            }
      if (!_currentMeasure)
            return;

      // Don't show panel if staff names are visible
      if (_currentMeasure == _score->firstMeasure() && _sv->toPhysical(_currentMeasure->canvasPos()).x() > 0) {
            _visible = false;
            return;
            }

      qreal _xPosMeasure       = _currentMeasure->canvasX();
      qreal _measureWidth      = _currentMeasure->width();
      int tick                 = _currentMeasure->tick();
      Fraction _currentTimeSig = _currentMeasure->timesig();
      //qDebug() << "_sv->xoffset()=" <<_sv->xoffset() << " _sv->mag()="<< _sv->mag() <<" s->x=" << s->x() << " width=" << _width << " currentMeasure=" << _currentMeasure->x() << " _xPosMeasure=" << _xPosMeasure;

      //---------------------------------------------------------
      //   findElementWidths
      //      determines the max width for each element types
      //---------------------------------------------------------

      // The first pass serves to get the maximum width for each elements

      qreal lineWidthName = 0;
      qreal _widthClef    = 0;
      qreal _widthKeySig  = 0;
      qreal _widthTimeSig = 0;
      qreal _xPosTimeSig  = 0;

      for (const Element* e : el) {
            e->itemDiscovered = 0;
            if (!e->visible() && !_score->showInvisible())
                  continue;

            if (e->isRest() && toRest(e)->isGap())
                  continue;

            if (e->isStaffLines()) {
                  Staff* currentStaff = _score->staff(e->staffIdx());
                  Segment* parent = _score->tick2segment(tick);

                  // Find maximum width for the staff name
                  QList<StaffName>& staffNamesLong = currentStaff->part()->instrument()->longNames();
                  QString staffName = staffNamesLong.isEmpty() ? " " : staffNamesLong[0].name();
                  if (staffName == "") {
                        QList<StaffName>& staffNamesShort = currentStaff->part()->instrument()->shortNames();
                        staffName = staffNamesShort.isEmpty() ? "" : staffNamesShort[0].name();
                        }
                  Text* newName = new Text(_score);
                  newName->setXmlText(staffName);
                  newName->setParent(parent);
                  newName->setTrack(e->track());
                  newName->textStyle().setFamily("FreeSans");
                  newName->textStyle().setSizeIsSpatiumDependent(true);
                  newName->layout();
                  newName->setPlainText(newName->plainText());
                  newName->layout();

                  // Find maximum width for the current Clef
                  Clef* newClef = new Clef(_score);
                  ClefType currentClef = currentStaff->clef(tick);
                  newClef->setClefType(currentClef);
                  newClef->setParent(parent);
                  newClef->setTrack(e->track());
                  newClef->layout();
                  if (newClef->width() > _widthClef)
                        _widthClef = newClef->width();

                  // Find maximum width for the current KeySignature
                  KeySig* newKs = new KeySig(_score);
                  KeySigEvent currentKeySigEvent = currentStaff->keySigEvent(tick);
                  newKs->setKeySigEvent(currentKeySigEvent);
                  // The Parent and the Track must be set to have the key signature layout adjusted to different clefs
                  // This also adds naturals to the key signature (if set in the score style)
                  newKs->setParent(parent);
                  newKs->setTrack(e->track());
                  newKs->setHideNaturals(true);
                  newKs->layout();
                  if (newKs->width() > _widthKeySig)
                        _widthKeySig = newKs->width();

                  // Find maximum width for the current TimeSignature
                  TimeSig* newTs = new TimeSig(_score);

                  // Try to get local time signature, if not, get the current measure one
                  TimeSig* currentTimeSig = currentStaff->timeSig(tick);
                  if (currentTimeSig)
                        newTs->setFrom(currentTimeSig);
                  else
                        newTs->setSig(Fraction(_currentTimeSig.numerator(), _currentTimeSig.denominator()), TimeSigType::NORMAL);
                  newTs->setParent(parent);
                  newTs->setTrack(e->track());
                  newTs->layout();

                  if ((newName->width() > lineWidthName) && (newName->xmlText() != ""))
                        lineWidthName = newName->width();

                  if (newTs->width() > _widthTimeSig)
                        _widthTimeSig = newTs->width();

                  delete newClef;
                  delete newName;
                  delete newKs;
                  delete newTs;
                 }
            }

      _leftMarginTotal = _score->styleP(StyleIdx::clefLeftMargin);
      _leftMarginTotal += _score->styleP(StyleIdx::keysigLeftMargin);
      _leftMarginTotal += _score->styleP(StyleIdx::timesigLeftMargin);

      _newWidth = _widthClef + _widthKeySig + _widthTimeSig + _leftMarginTotal + _panelRightPadding;
      _xPosMeasure -= _offsetPanel;

      lineWidthName += _score->spatium() + _score->styleP(StyleIdx::clefLeftMargin) + _widthClef;
      if (_newWidth < lineWidthName) {
            _newWidth = lineWidthName;
            _oldWidth = 0;
            }
      if (_oldWidth == 0) {
            _oldWidth = _newWidth;
            _width = _newWidth;
            }
      else if (_newWidth > 0) {
            if (_newWidth == _width) {
                  _oldWidth = _width;
                  _width = _newWidth;
                  }
            else if (((_xPosMeasure <= _newWidth) && (_xPosMeasure >= _oldWidth)) ||
                     ((_xPosMeasure >= _newWidth) && (_xPosMeasure <= _oldWidth)))
                        _width = _xPosMeasure;
            else if (((_xPosMeasure+_measureWidth <= _newWidth) && (_xPosMeasure+_measureWidth >= _oldWidth)) ||
                     ((_xPosMeasure+_measureWidth >= _newWidth) && (_xPosMeasure+_measureWidth <= _oldWidth)))
                        _width = _xPosMeasure+_measureWidth;
            else {
                  _oldWidth = _width;
                  _width = _newWidth;
                  }
            }

      _rect = QRect(0, _y, _width, _height);

      //====================

      painter.save();

      // Draw colored rectangle
      painter.setClipping(false);
      QPointF pos(_offsetPanel, 0);

      painter.translate(pos);
      QPen pen;
      pen.setWidthF(0.0);
      pen.setStyle(Qt::NoPen);
      painter.setPen(pen);
      painter.setBrush(preferences.fgColor);
      QRectF bg(_rect);

      bg.setWidth(_widthClef + _widthKeySig + _widthTimeSig + _leftMarginTotal + _panelRightPadding);
      QPixmap* fgPixmap = _sv->fgPixmap();
      if (fgPixmap == 0 || fgPixmap->isNull())
            painter.fillRect(bg, preferences.fgColor);
      else {
            painter.setMatrixEnabled(false);
            painter.drawTiledPixmap(bg, *fgPixmap, bg.topLeft()
               - QPoint(lrint(_sv->matrix().dx()), lrint(_sv->matrix().dy())));
            painter.setMatrixEnabled(true);
            }

      painter.setClipRect(_rect);
      painter.setClipping(true);

      QColor color(MScore::layoutBreakColor);

      // Draw measure text number
      QString text = QString("#%1").arg(_currentMeasure->no()+1);
      Text* newElement = new Text(_score);
      newElement->setTextStyleType(TextStyleType::DEFAULT);
      newElement->setFlag(ElementFlag::MOVABLE, false);
      newElement->setXmlText(text);
      newElement->textStyle().setFamily("FreeSans");
      newElement->textStyle().setSizeIsSpatiumDependent(true);
      newElement->setColor(color);
      newElement->sameLayout();
      pos = QPointF(_score->styleP(StyleIdx::clefLeftMargin) + _widthClef, _y + newElement->height());
      painter.translate(pos);
      newElement->draw(&painter);
      pos += QPointF(_offsetPanel, 0);
      painter.translate(-pos);
      delete newElement;

      // This second pass draws the elements spaced evently using the width of the largest element
      for (const Element* e : el) {
            if (!e->visible() && !_score->showInvisible())
                  continue;

            if (e->isRest() && toRest(e)->isGap())
                  continue;

            if (e->isStaffLines()) {
                  painter.save();
                  Staff* currentStaff = _score->staff(e->staffIdx());
                  Segment* parent = _score->tick2segmentMM(tick);

                  pos = QPointF (_offsetPanel, e->pagePos().y());
                  painter.translate(pos);

                  // Draw staff lines
                  StaffLines newStaffLines(*toStaffLines(e));
                  newStaffLines.setParent(parent);
                  newStaffLines.setTrack(e->track());
                  newStaffLines.layout();
                  newStaffLines.setColor(color);
                  newStaffLines.setWidth(bg.width());
                  newStaffLines.draw(&painter);

                  // Draw barline
                  BarLine barLine(_score);
                  barLine.setBarLineType(BarLineType::NORMAL);
                  barLine.setParent(parent);
                  barLine.setTrack(e->track());
                  barLine.setSpan(currentStaff->barLineSpan());
                  barLine.setSpanFrom(currentStaff->barLineFrom());
                  barLine.setSpanTo(currentStaff->barLineTo());
                  barLine.layout();
                  barLine.setColor(color);
                  barLine.draw(&painter);

                  // Draw the current staff name
                  QList<StaffName>& staffNamesLong = currentStaff->part()->instrument()->longNames();
                  QString staffName = staffNamesLong.isEmpty() ? " " : staffNamesLong[0].name();
                  if (staffName == "") {
                        QList<StaffName>& staffNamesShort = currentStaff->part()->instrument()->shortNames();
                        staffName = staffNamesShort.isEmpty() ? "" : staffNamesShort[0].name();
                        }

                  Text* newName = new Text(_score);
                  newName->setXmlText(staffName);
                  newName->setParent(parent);
                  newName->setTrack(e->track());
                  newName->setColor(color);
                  newName->textStyle().setFamily("FreeSans");
                  newName->textStyle().setSizeIsSpatiumDependent(true);
                  newName->layout();
                  newName->setPlainText(newName->plainText());
                  newName->layout();
                  if (currentStaff->part()->staff(0) == currentStaff) {
                        double _spatium = _score->spatium();
                        pos = QPointF (_score->styleP(StyleIdx::clefLeftMargin) + _widthClef, -_spatium * 2);
                        painter.translate(pos);
                        newName->draw(&painter);
                        painter.translate(-pos);
                        }
                  delete newName;

                  qreal posX = 0.0;

                  // Draw the current Clef
                  Clef clef(_score);
                  clef.setClefType(currentStaff->clef(tick));
                  clef.setParent(parent);
                  clef.setTrack(e->track());
                  clef.setColor(color);
                  clef.layout();
                  posX += _score->styleP(StyleIdx::clefLeftMargin);
                  clef.drawAt(&painter, QPointF(posX, clef.pos().y()));
                  posX += _widthClef;

                  // Draw the current KeySignature
                  KeySig newKs(_score);
                  newKs.setKeySigEvent(currentStaff->keySigEvent(tick));

                  // The Parent and the track must be set to have the key signature layout adjusted to different clefs
                  // This also adds naturals to the key signature (if set in the score style)
                  newKs.setParent(parent);
                  newKs.setTrack(e->track());
                  newKs.setColor(color);
                  newKs.setHideNaturals(true);
                  newKs.layout();
                  posX += _score->styleP(StyleIdx::keysigLeftMargin);
                  newKs.drawAt(&painter, QPointF(posX, 0.0));

                  posX += _widthKeySig + _xPosTimeSig;

                  // Draw the current TimeSignature
                  TimeSig newTs(_score);

                  // Try to get local time signature, if not, get the current measure one
                  TimeSig* currentTimeSig = currentStaff->timeSig(tick);
                  if (currentTimeSig) {
                        newTs.setFrom(currentTimeSig);
                        newTs.setParent(parent);
                        newTs.setTrack(e->track());
                        newTs.setColor(color);
                        newTs.layout();
                        posX += _score->styleP(StyleIdx::timesigLeftMargin);
                        newTs.drawAt(&painter, QPointF(posX, 0.0));
                        }
                  painter.restore();
                  }
            }
      painter.restore();
      _visible = true;
      }
Exemple #25
0
void OSDWidget::showOSD(const QString &str, OSDUserData *data)
{
    setFont(FontEdit::str2font(data->Font.ptr, baseFont));
    QPainter p(this);
    p.setFont(font());
    unsigned nScreen = data->Screen.value;
    unsigned nScreens = screens();
    if (nScreen >= nScreens)
        nScreen = 0;
    QRect rcScreen = screenGeometry(nScreen);
    rcScreen = QRect(0, 0,
                     rcScreen.width() - SHADOW_OFFS - XOSD_MARGIN * 2 - data->Offset.value,
                     rcScreen.height() - SHADOW_OFFS - XOSD_MARGIN * 2 - data->Offset.value);
    QRect rc = p.boundingRect(rcScreen, AlignLeft | AlignTop | WordBreak, str);
    p.end();
    int x = rcScreen.left();
    int y = rcScreen.top();
    int w = rc.width() + 1;
    int h = rc.height() + 1;
    if (data->Shadow.bValue){
        w += SHADOW_OFFS;
        h += SHADOW_OFFS;
    }
    if (data->Background.bValue){
        w += XOSD_MARGIN * 2;
        h += XOSD_MARGIN * 2;
    }
    resize(QSize(w, h));
    switch (data->Position.value){
    case 1:
        move(x + data->Offset.value, y + data->Offset.value);
        break;
    case 2:
        move(x + rcScreen.width() - data->Offset.value - w, y + rcScreen.height() - data->Offset.value - h);
        break;
    case 3:
        move(x + rcScreen.width() - data->Offset.value - w, y + data->Offset.value);
        break;
    case 4:
        move(x + (rcScreen.width() - w) / 2, y + rcScreen.height() - data->Offset.value - h);
        break;
    case 5:
        move(x + (rcScreen.width() - w) / 2, y + data->Offset.value);
        break;
    case 6:
        move(x + (rcScreen.width() - w) / 2, y + (rcScreen.height() - h) /2);
        break;
    default:
        move(x + data->Offset.value, y + rcScreen.height() - data->Offset.value - h);
    }
    if (!data->Background.bValue || data->Shadow.bValue){
        QBitmap mask(w, h);
        p.begin(&mask);
#ifdef WIN32
        QColor bg(255, 255, 255);
        QColor fg(0, 0, 0);
#else
        QColor bg(0, 0, 0);
        QColor fg(255, 255, 255);
#endif
        p.fillRect(0, 0, w, h, bg);
        if (data->Background.bValue){
            p.fillRect(0, 0, w - SHADOW_OFFS, h - SHADOW_OFFS, fg);
            p.fillRect(SHADOW_OFFS, SHADOW_OFFS, w - SHADOW_OFFS, h - SHADOW_OFFS, fg);
        }else{
            p.setPen(fg);
            p.setFont(font());
            if (data->Shadow.bValue){
                rc = QRect(SHADOW_OFFS, SHADOW_OFFS, w - SHADOW_OFFS, h - SHADOW_OFFS);
                p.drawText(rc, AlignLeft | AlignTop | WordBreak, str);
                rc = QRect(0, 0, w - SHADOW_OFFS, h - SHADOW_OFFS);
                p.drawText(rc, AlignLeft | AlignTop | WordBreak, str);
            }else{
                rc = QRect(0, 0, w, h);
                p.drawText(rc, AlignLeft | AlignTop | WordBreak, str);
            }
        }
        p.end();
        setMask(mask);
    }
    qApp->syncX();
    QPixmap pict = QPixmap::grabWindow(QApplication::desktop()->winId(), this->x(), this->y(), width(), height());
    intensity(pict, -0.50f);
    p.begin(&pict);
    rc = QRect(0, 0, w, h);
    if (data->Background.bValue){
        if (data->Shadow.bValue){
            w -= SHADOW_OFFS;
            h -= SHADOW_OFFS;
            rc = QRect(0, 0, w, h);
        }
        QBrush bg(data->BgColor.value);
        p.fillRect(rc, bg);
#if QT_VERSION < 300
        style().drawPopupPanel(&p, 0, 0, w, h, colorGroup(), 2, &bg);
#else
        style().drawPrimitive(QStyle::PE_PanelPopup, &p, rc, colorGroup());
#endif
        rc = QRect(XOSD_MARGIN, XOSD_MARGIN, w - XOSD_MARGIN * 2, h - XOSD_MARGIN * 2);
    }
    p.setFont(font());
    p.setPen(QColor(data->Color.value));
    p.drawText(rc, AlignLeft | AlignTop | WordBreak, str);
    p.end();
    bgPict = pict;
    QWidget::show();
    raise();
}
void QgsGPSInformationWidget::displayGPSInformation( const QgsGPSInformation &info )
{
  QVector<QPointF> data;

  // set validity flag and status from GPS data
  // based on GGA, GSA and RMC sentences - the logic does not require all
  bool validFlag = false; // true if GPS indicates position fix
  FixStatus fixStatus = NoData;

  // no fix if any of the three report bad; default values are invalid values and won't be changed if the corresponding NMEA msg is not received
  if ( info.status == 'V' || info.fixType == NMEA_FIX_BAD || info.quality == 0 ) // some sources say that 'V' indicates position fix, but is below acceptable quality
  {
    fixStatus = NoFix;
  }
  else if ( info.fixType == NMEA_FIX_2D ) // 2D indication (from GGA)
  {
    fixStatus = Fix2D;
    validFlag = true;
  }
  else if ( info.status == 'A' || info.fixType == NMEA_FIX_3D || info.quality > 0 ) // good
  {
    fixStatus = Fix3D;
    validFlag = true;
  }
  else  // unknown status (not likely)
  {
  }

  // set visual status indicator -- do only on change of state
  if ( fixStatus != mLastFixStatus )
  {
    setStatusIndicator( fixStatus );
  }

  if ( mStackedWidget->currentIndex() == 1 && info.satInfoComplete ) //signal
  {
    mpPlot->setAxisScale( QwtPlot::xBottom, 0, info.satellitesInView.size() );
  } //signal
#ifdef WITH_QWTPOLAR
  if ( mStackedWidget->currentIndex() == 2 && info.satInfoComplete ) //satellites
  {
    while ( !mMarkerList.isEmpty() )
    {
      delete mMarkerList.takeFirst();
    }
  } //satellites
#endif
  if ( mStackedWidget->currentIndex() == 4 ) //debug
  {
    mGPSPlainTextEdit->clear();
  } //debug

  for ( int i = 0; i < info.satellitesInView.size(); ++i ) //satellite processing loop
  {
    QgsSatelliteInfo currentInfo = info.satellitesInView.at( i );

    if ( mStackedWidget->currentIndex() == 1 && info.satInfoComplete ) //signal
    {
      data << QPointF( i, 0 );
      data << QPointF( i, currentInfo.signal );
      data << QPointF( i + 1, currentInfo.signal );
      data << QPointF( i + 1, 0 );
    } //signal

    if ( mStackedWidget->currentIndex() == 2 && info.satInfoComplete ) //satellites
    {
      QColor bg( Qt::white ); // moved several items outside of the following if block to minimize loop time
      bg.setAlpha( 200 );
      QColor myColor;

      // Add a marker to the polar plot
      if ( currentInfo.id > 0 )       // don't show satellite if id=0 (no satellite indication)
      {
#ifdef WITH_QWTPOLAR
        QwtPolarMarker *mypMarker = new QwtPolarMarker();
#if (QWT_POLAR_VERSION<0x010000)
        mypMarker->setPosition( QwtPolarPoint( currentInfo.azimuth, currentInfo.elevation ) );
#else
        mypMarker->setPosition( QwtPointPolar( currentInfo.azimuth, currentInfo.elevation ) );
#endif
#endif
        if ( currentInfo.signal < 30 ) //weak signal
        {
          myColor = Qt::red;
        }
        else
        {
          myColor = Qt::black; //strong signal
        }
#ifdef WITH_QWTPOLAR
        QBrush symbolBrush( Qt::black );
        QSize markerSize( 9, 9 );
        QBrush textBgBrush( bg );
#if (QWT_POLAR_VERSION<0x010000)
        mypMarker->setSymbol( QwtSymbol( QwtSymbol::Ellipse,
                                         symbolBrush, QPen( myColor ), markerSize ) );
#else
        mypMarker->setSymbol( new QwtSymbol( QwtSymbol::Ellipse,
                                             symbolBrush, QPen( myColor ), markerSize ) );
#endif

        mypMarker->setLabelAlignment( Qt::AlignHCenter | Qt::AlignTop );
        QwtText text( QString::number( currentInfo.id ) );
        text.setColor( myColor );
        text.setBackgroundBrush( textBgBrush );
        mypMarker->setLabel( text );
        mypMarker->attach( mpSatellitesWidget );
        mMarkerList << mypMarker;
#endif
      } // currentInfo.id > 0
    } //satellites
  } //satellite processing loop

  if ( mStackedWidget->currentIndex() == 1 && info.satInfoComplete ) //signal
  {
    mpCurve->setSamples( data );
    mpPlot->replot();
  } //signal
#ifdef WITH_QWTPOLAR
  if ( mStackedWidget->currentIndex() == 2 && info.satInfoComplete ) //satellites
  {
    mpSatellitesWidget->replot();
  } //satellites
#endif
  if ( validFlag )
  {
    validFlag = info.longitude >= -180.0 && info.longitude <= 180.0 && info.latitude >= -90.0 && info.latitude <= 90.0;
  }

  QgsPointXY myNewCenter;
  if ( validFlag )
  {
    myNewCenter = QgsPointXY( info.longitude, info.latitude );
  }
  else
  {
    myNewCenter = mLastGpsPosition;
  }

  if ( mStackedWidget->currentIndex() == 0 ) //position
  {
    mTxtLatitude->setText( QString::number( info.latitude, 'f', 8 ) );
    mTxtLongitude->setText( QString::number( info.longitude, 'f', 8 ) );
    mTxtAltitude->setText( tr( "%1 m" ).arg( info.elevation, 0, 'f', 1 ) ); // don't know of any GPS receivers that output better than 0.1 m precision
    if ( mDateTimeFormat.isEmpty() )
    {
      mTxtDateTime->setText( info.utcDateTime.toString( Qt::TextDate ) );  // default format
    }
    else
    {
      mTxtDateTime->setText( info.utcDateTime.toString( mDateTimeFormat ) );  //user specified format string for testing the millisecond part of time
    }
    mTxtSpeed->setText( tr( "%1 km/h" ).arg( info.speed, 0, 'f', 1 ) );
    mTxtDirection->setText( QString::number( info.direction, 'f', 1 ) + QStringLiteral( "°" ) );
    mTxtHdop->setText( QString::number( info.hdop, 'f', 1 ) );
    mTxtVdop->setText( QString::number( info.vdop, 'f', 1 ) );
    mTxtPdop->setText( QString::number( info.pdop, 'f', 1 ) );
    mTxtHacc->setText( QString::number( info.hacc, 'f', 1 ) + "m" );
    mTxtVacc->setText( QString::number( info.vacc, 'f', 1 ) + "m" );
    mTxtFixMode->setText( info.fixMode == 'A' ? tr( "Automatic" ) : info.fixMode == 'M' ? tr( "Manual" ) : QLatin1String( "" ) ); // A=automatic 2d/3d, M=manual; allowing for anything else
    mTxtFixType->setText( info.fixType == 3 ? tr( "3D" ) : info.fixType == 2 ? tr( "2D" ) : info.fixType == 1 ? tr( "No fix" ) : QString::number( info.fixType ) ); // 1=no fix, 2=2D, 3=3D; allowing for anything else
    mTxtQuality->setText( info.quality == 2 ? tr( "Differential" ) : info.quality == 1 ? tr( "Non-differential" ) : info.quality == 0 ? tr( "No position" ) : info.quality > 2 ? QString::number( info.quality ) : QLatin1String( "" ) ); // allowing for anything else
    mTxtSatellitesUsed->setText( QString::number( info.satellitesUsed ) );
    mTxtStatus->setText( info.status == 'A' ? tr( "Valid" ) : info.status == 'V' ? tr( "Invalid" ) : QLatin1String( "" ) );
  } //position

  // Avoid refreshing / panning if we haven't moved
  if ( mLastGpsPosition != myNewCenter )
  {
    mLastGpsPosition = myNewCenter;

    // Pan based on user specified behavior
    if ( radRecenterMap->isChecked() || radRecenterWhenNeeded->isChecked() )
    {
      QgsCoordinateReferenceSystem mypSRS = mpCanvas->mapSettings().destinationCrs();
      QgsCoordinateTransform myTransform( mWgs84CRS, mypSRS ); // use existing WGS84 CRS

      QgsPointXY myPoint = myTransform.transform( myNewCenter );
      //keep the extent the same just center the map canvas in the display so our feature is in the middle
      QgsRectangle myRect( myPoint, myPoint );  // empty rect can be used to set new extent that is centered on the point used to construct the rect

      // testing if position is outside some proportion of the map extent
      // this is a user setting - useful range: 5% to 100% (0.05 to 1.0)
      QgsRectangle myExtentLimit( mpCanvas->extent() );
      myExtentLimit.scale( mSpinMapExtentMultiplier->value() * 0.01 );

      // only change the extents if the point is beyond the current extents to minimize repaints
      if ( radRecenterMap->isChecked() ||
           ( radRecenterWhenNeeded->isChecked() && !myExtentLimit.contains( myPoint ) ) )
      {
        mpCanvas->setExtent( myRect );
        mpCanvas->refresh();
      }
    } //otherwise never recenter automatically

    if ( mCbxAutoAddVertices->isChecked() )
    {
      addVertex();
    }
  } // mLastGpsPosition != myNewCenter

  // new marker position after recentering
  if ( mGroupShowMarker->isChecked() ) // show marker
  {
    if ( validFlag ) // update cursor position if valid position
    {
      // initially, cursor isn't drawn until first valid fix; remains visible until GPS disconnect
      if ( ! mpMapMarker )
      {
        mpMapMarker = new QgsGpsMarker( mpCanvas );
      }
      mpMapMarker->setSize( mSliderMarkerSize->value() );
      mpMapMarker->setCenter( myNewCenter );
    }
  }
  else
  {
    if ( mpMapMarker )
    {
      delete mpMapMarker;
      mpMapMarker = nullptr;
    }
  } // show marker
}
Exemple #27
0
wxColour wxSystemSettingsNative::GetColour(wxSystemColour index)
{
    GdkRGBA gdkRGBA = { 0, 0, 0, 1 };
    switch (index)
    {
    case wxSYS_COLOUR_3DLIGHT:
    case wxSYS_COLOUR_ACTIVEBORDER:
    case wxSYS_COLOUR_BTNFACE:
    case wxSYS_COLOUR_DESKTOP:
    case wxSYS_COLOUR_INACTIVEBORDER:
    case wxSYS_COLOUR_INACTIVECAPTION:
    case wxSYS_COLOUR_SCROLLBAR:
    case wxSYS_COLOUR_WINDOWFRAME:
        bg(ButtonWidget(), GTK_STATE_FLAG_NORMAL, gdkRGBA);
        break;
    case wxSYS_COLOUR_BTNHIGHLIGHT:
    case wxSYS_COLOUR_HIGHLIGHT:
        bg(ButtonWidget(), GTK_STATE_FLAG_SELECTED, gdkRGBA);
        break;
    case wxSYS_COLOUR_BTNSHADOW:
        border(ButtonWidget(), GTK_STATE_FLAG_NORMAL, gdkRGBA);
        break;
    case wxSYS_COLOUR_BTNTEXT:
    case wxSYS_COLOUR_WINDOWTEXT:
        fg(ButtonWidget(), GTK_STATE_FLAG_NORMAL, gdkRGBA);
        break;
    case wxSYS_COLOUR_GRAYTEXT:
    case wxSYS_COLOUR_INACTIVECAPTIONTEXT:
        fg(ButtonWidget(), GTK_STATE_FLAG_INSENSITIVE, gdkRGBA);
        break;
    case wxSYS_COLOUR_HIGHLIGHTTEXT:
        fg(ButtonWidget(), GTK_STATE_FLAG_SELECTED, gdkRGBA);
        break;
    case wxSYS_COLOUR_HOTLIGHT:
        {
            static GtkWidget* s_widget;
            if (s_widget == NULL)
            {
                s_widget = gtk_link_button_new("");
                gtk_container_add(ContainerWidget(), s_widget);
            }
            fg(s_widget, GTK_STATE_FLAG_NORMAL, gdkRGBA);
        }
        break;
    case wxSYS_COLOUR_INFOBK:
        bg(ToolTipWidget(), GTK_STATE_FLAG_NORMAL, gdkRGBA);
        break;
    case wxSYS_COLOUR_INFOTEXT:
        fg(ToolTipWidget(), GTK_STATE_FLAG_NORMAL, gdkRGBA);
        break;
    case wxSYS_COLOUR_LISTBOX:
        bg(ListWidget(), GTK_STATE_FLAG_NORMAL, gdkRGBA);
        break;
    case wxSYS_COLOUR_LISTBOXHIGHLIGHTTEXT:
        fg(ListWidget(), GTK_STATE_FLAG_SELECTED, gdkRGBA);
        break;
    case wxSYS_COLOUR_LISTBOXTEXT:
        fg(ListWidget(), GTK_STATE_FLAG_NORMAL, gdkRGBA);
        break;
    case wxSYS_COLOUR_MENU:
        bg(MenuItemWidget(), GTK_STATE_FLAG_NORMAL, gdkRGBA);
        break;
    case wxSYS_COLOUR_MENUBAR:
        bg(MenuBarWidget(), GTK_STATE_FLAG_NORMAL, gdkRGBA);
        break;
    case wxSYS_COLOUR_ACTIVECAPTION:
    case wxSYS_COLOUR_MENUHILIGHT:
        bg(MenuItemWidget(), GTK_STATE_FLAG_PRELIGHT, gdkRGBA);
        break;
    case wxSYS_COLOUR_MENUTEXT:
        fg(MenuItemWidget(), GTK_STATE_FLAG_NORMAL, gdkRGBA);
        break;
    case wxSYS_COLOUR_APPWORKSPACE:
    case wxSYS_COLOUR_WINDOW:
        {
            GtkWidget* widget = TextCtrlWidget();
            GtkStyleContext* sc = gtk_widget_get_style_context(widget);
            gtk_style_context_save(sc);
            gtk_style_context_add_class(sc, GTK_STYLE_CLASS_VIEW);
            bg(widget, GTK_STATE_FLAG_NORMAL, gdkRGBA);
            gtk_style_context_restore(sc);
        }
        break;
    case wxSYS_COLOUR_CAPTIONTEXT:
        {
            GdkRGBA c = { 1, 1, 1, 1 };
            gdkRGBA = c;
        }
        break;
    default:
        wxFAIL_MSG("unknown system colour index");
        // fallthrough
    case wxSYS_COLOUR_3DDKSHADOW:
    case wxSYS_COLOUR_GRADIENTACTIVECAPTION:
    case wxSYS_COLOUR_GRADIENTINACTIVECAPTION:
        // black
        break;
    }
    return wxColour(gdkRGBA);
}
Exemple #28
0
void DocumentManager::delayedNewDocument()
{
    d->document = KisPart::instance()->createDocument();
    d->document->setProgressProxy(d->proxy);
    if (qAppName().contains("sketch")) {
        d->document->setSaveInBatchMode(true);
    }

    if(d->newDocOptions.isEmpty())
    {
        d->document->newImage("New Image", d->newDocWidth, d->newDocHeight, KoColorSpaceRegistry::instance()->rgb8());
        d->document->image()->setResolution(d->newDocResolution, d->newDocResolution);
        d->document->resetURL();
    }
    else if(d->newDocOptions.contains("template")) {
        QUrl url(d->newDocOptions.value("template").toString().remove("template://"));
        bool ok = d->document->loadNativeFormat(url.toLocalFile());
        d->document->setModified(false);
        d->document->undoStack()->clear();

        if (ok) {
            QMimeDatabase db;
            QString mimeType = db.mimeTypeForFile( url.path(), QMimeDatabase::MatchExtension).name();
            // in case this is a open document template remove the -template from the end
            mimeType.remove( QRegExp( "-template$" ) );
            d->document->setMimeTypeAfterLoading(mimeType);
            d->document->resetURL();
            d->document->setEmpty();
        } else {
            d->document->showLoadingErrorDialog();
            d->document->initEmpty();
        }
    }
    else
    {
        QString name = d->newDocOptions.value("name", "New Image").toString();
        int width = d->newDocOptions.value("width").toInt();
        int height = d->newDocOptions.value("height").toInt();
        // internal resolution is pixels per point, not ppi
        float res = d->newDocOptions.value("resolution", 72.0f).toFloat() / 72.0f;

        QString colorModelId = d->newDocOptions.value("colorModelId").toString();
        QString colorDepthId = d->newDocOptions.value("colorDepthId").toString();
        QString colorProfileId = d->newDocOptions.value("colorProfileId").toString();

        const KoColorSpace* profile;
        if(colorModelId.isEmpty() || colorDepthId.isEmpty() || colorProfileId.isEmpty())
        {
            profile = KoColorSpaceRegistry::instance()->rgb8();
        }
        else
        {
            profile = KoColorSpaceRegistry::instance()->colorSpace(colorModelId, colorDepthId, colorProfileId);
        }

        QColor background = d->newDocOptions.value("backgroundColor", QColor("white")).value<QColor>();
        background.setAlphaF(d->newDocOptions.value("backgroundOpacity", 1.0f).toFloat());
        KoColor bg(background, profile);

        d->document->newImage(name, width, height, profile, bg, QString(), res);
        d->document->resetURL();
    }

    KisPart::instance()->addDocument(d->document);

    d->temporaryFile = true;

    emit documentChanged();
}
Exemple #29
0
void XOSD::set(const QString &str, unsigned long _uin)
{
    uin = _uin;
    hide();
    QPainter p(this);
    p.setFont(font());
    QWidget *d = qApp->desktop();
    QRect rc(0, 0,
             d->width() - SHADOW_OFFS - XOSD_MARGIN * 2 - pMain->XOSD_offset(),
             d->height() - SHADOW_OFFS - XOSD_MARGIN * 2 - pMain->XOSD_offset());
    rc = p.boundingRect(rc, AlignLeft | AlignTop | WordBreak, str);
    p.end();
    int w = rc.width();
    int h = rc.height();
    if (pMain->XOSD_Shadow()){
        w += SHADOW_OFFS;
        h += SHADOW_OFFS;
    }
    if (pMain->XOSD_Background()){
        w += XOSD_MARGIN * 2;
        h += XOSD_MARGIN * 2;
    }
    resize(QSize(w, h));
    switch (pMain->XOSD_pos()){
    case 1:
        move(pMain->XOSD_offset(), pMain->XOSD_offset());
        break;
    case 2:
        move(d->width() - pMain->XOSD_offset() - w, d->height() - pMain->XOSD_offset() - h);
        break;
    case 3:
        move(d->width() - pMain->XOSD_offset() - w, pMain->XOSD_offset());
        break;
    case 4:
        move((d->width() - w) / 2, d->height() - pMain->XOSD_offset() - h);
        break;
    case 5:
        move((d->width() - w) / 2, pMain->XOSD_offset());
        break;
    default:
        move(pMain->XOSD_offset(), d->height() - pMain->XOSD_offset() - h);
    }
    if (!pMain->XOSD_Background() || pMain->XOSD_Shadow()){
        QBitmap mask(w, h);
        p.begin(&mask);
#ifdef WIN32
        QColor bg(255, 255, 255);
        QColor fg(0, 0, 0);
#else
        QColor bg(0, 0, 0);
        QColor fg(255, 255, 255);
#endif
        p.fillRect(0, 0, w, h, bg);
        if (pMain->XOSD_Background()){
            p.fillRect(0, 0, w - SHADOW_OFFS, h - SHADOW_OFFS, fg);
            p.fillRect(SHADOW_OFFS, SHADOW_OFFS, w - SHADOW_OFFS, h - SHADOW_OFFS, fg);
        }else{
            p.setPen(fg);
            p.setFont(font());
            if (pMain->XOSD_Shadow()){
                rc = QRect(SHADOW_OFFS, SHADOW_OFFS, w - SHADOW_OFFS, h - SHADOW_OFFS);
                p.drawText(rc, AlignLeft | AlignTop | WordBreak, str);
            }
            rc = QRect(0, 0, w - SHADOW_OFFS, h - SHADOW_OFFS);
            p.drawText(rc, AlignLeft | AlignTop | WordBreak, str);
        }
        p.end();
        setMask(mask);
    }
    qApp->syncX();
    QPixmap pict = QPixmap::grabWindow(QApplication::desktop()->winId(), x(), y(), width(), height());
    intensity(pict, -0.50f);
    p.begin(&pict);
    rc = QRect(0, 0, w, h);
    if (pMain->XOSD_Background()){
        if (pMain->XOSD_Shadow()){
            w -= SHADOW_OFFS;
            h -= SHADOW_OFFS;
            rc = QRect(0, 0, w, h);
        }
        QBrush bg(pMain->XOSD_BgColor());
        p.fillRect(rc, bg);
#if QT_VERSION < 300
        style().drawPopupPanel(&p, 0, 0, w, h, colorGroup(), 2, &bg);
#else
        style().drawPrimitive(QStyle::PE_PanelPopup, &p, rc, colorGroup());
#endif
        rc = QRect(XOSD_MARGIN, XOSD_MARGIN, w - XOSD_MARGIN * 2, h - XOSD_MARGIN * 2);
    }
    p.setFont(font());
    p.setPen(QColor(pMain->XOSD_color()));
    p.drawText(rc, AlignLeft | AlignTop | WordBreak, str);
    p.end();
    bgPict = pict;
    show();
    QTimer::singleShot(pMain->XOSD_timeout() * 1000, this, SLOT(timeout()));
}
void QCallTip::paintEvent(QPaintEvent *e)
{
	Q_UNUSED(e)
	
	QPainter p(this);
	QFontMetrics fm = fontMetrics();
	
	m_up = m_down = QRect();
	
	bool bPrev = m_index, bNext = (m_index + 1) < m_tips.count();
	int offset = 3, whalf = arrowWidth / 2 - 3; //, hhalf = height() / 2;
	
	QRect bg(0, 0, fm.width(m_tips.at(m_index)) + 6, fm.height());
	
	if ( bPrev )
	{
		bg.setWidth(bg.width() + arrowWidth);
	}
	
	if ( bNext )
	{
		bg.setWidth(bg.width() + arrowWidth);
	}
	
	p.fillRect(bg, QColor(0xca, 0xff, 0x70));
	//p.drawRect(bg);
	
	p.save();
	
	p.setPen(QColor(0x00, 0x00, 0x00));
	p.drawLine(0, height() - 1, bg.width() - 1, height() - 1);
	p.drawLine(bg.width() - 1, height() - 1, bg.width() - 1, 0);
	
	p.setPen(QColor(0xc0, 0xc0, 0xc0));
	p.drawLine(0, height() - 1, 0, 0);
	p.drawLine(0, 0, bg.width() - 1, 0);
	
	p.restore();
	
	int top = height() / 3, bottom = height() - height() / 3;
	
	if ( bPrev )
	{
		int x = offset + arrowWidth / 2 - 1;
		
		QPoint pts[] = {
			QPoint(x - whalf, bottom),
			QPoint(x + whalf, bottom),
			QPoint(x, top)
		};
		
		p.drawPolygon(pts, sizeof(pts) / sizeof(QPoint), Qt::WindingFill);
		
		m_up = QRect(offset, 0, offset + arrowWidth, height());
		offset += arrowWidth;
	}
	
	if ( bNext )
	{
		int x = offset + arrowWidth / 2 - 1;
		
		QPoint pts[] = {
			QPoint(x - whalf, top),
			QPoint(x + whalf, top),
			QPoint(x, bottom)
		};
		
		p.drawPolygon(pts, sizeof(pts) / sizeof(QPoint), Qt::WindingFill);
		
		m_down = QRect(offset, 0, offset + arrowWidth, height());
		offset += arrowWidth;
	}
	
	p.drawText(offset, fm.ascent() + 2, m_tips.at(m_index));
	
	setFixedSize(bg.size() + QSize(1, 1));
}