Ejemplo n.º 1
0
ArthurFrame::ArthurFrame(QWidget *parent)
    : QWidget(parent)
    , m_prefer_image(false)
{
#ifdef QT_OPENGL_SUPPORT
    glw = 0;
    m_use_opengl = false;
    QGLFormat f = QGLFormat::defaultFormat();
    f.setSampleBuffers(true);
    f.setStencil(true);
    f.setAlpha(true);
    f.setAlphaBufferSize(8);
    QGLFormat::setDefaultFormat(f);
#endif
    m_document = 0;
    m_show_doc = false;

    m_tile = QPixmap(128, 128);
    m_tile.fill(Qt::white);
    QPainter pt(&m_tile);
    QColor color(230, 230, 230);
    pt.fillRect(0, 0, 64, 64, color);
    pt.fillRect(64, 64, 64, 64, color);
    pt.end();

//     QPalette pal = palette();
//     pal.setBrush(backgroundRole(), m_tile);
//     setPalette(pal);

#ifdef Q_WS_X11
    QPixmap xRenderPixmap(1, 1);
    m_prefer_image = xRenderPixmap.pixmapData()->classId() == QPixmapData::X11Class && !xRenderPixmap.x11PictureHandle();
#endif
}
Ejemplo n.º 2
0
QT_BEGIN_NAMESPACE

QGLFormat QGLFormat::fromPlatformWindowFormat(const QPlatformWindowFormat &format)
{
    QGLFormat retFormat;
    retFormat.setAccum(format.accum());
    if (format.accumBufferSize() >= 0)
        retFormat.setAccumBufferSize(format.accumBufferSize());
    retFormat.setAlpha(format.alpha());
    if (format.alphaBufferSize() >= 0)
        retFormat.setAlphaBufferSize(format.alphaBufferSize());
    if (format.blueBufferSize() >= 0)
        retFormat.setBlueBufferSize(format.blueBufferSize());
    retFormat.setDepth(format.depth());
    if (format.depthBufferSize() >= 0)
        retFormat.setDepthBufferSize(format.depthBufferSize());
    retFormat.setDirectRendering(format.directRendering());
    retFormat.setDoubleBuffer(format.doubleBuffer());
    if (format.greenBufferSize() >= 0)
        retFormat.setGreenBufferSize(format.greenBufferSize());
    if (format.redBufferSize() >= 0)
        retFormat.setRedBufferSize(format.redBufferSize());
    retFormat.setRgba(format.rgba());
    retFormat.setSampleBuffers(format.sampleBuffers());
    retFormat.setSamples(format.sampleBuffers());
    retFormat.setStencil(format.stencil());
    if (format.stencilBufferSize() >= 0)
        retFormat.setStencilBufferSize(format.stencilBufferSize());
    retFormat.setStereo(format.stereo());
    retFormat.setSwapInterval(format.swapInterval());
    return retFormat;
}
Ejemplo n.º 3
0
int main(int argc, char** argv)
{
    // sets the paths
    QApplication::setColorSpec(QApplication::ManyColor);
    QApplication *app = new QApplication(argc, argv);
    Q_INIT_RESOURCE(freestyle);

    Config::Path pathconfig;

    QGLFormat myformat;
    myformat.setAlpha(true);
    QGLFormat::setDefaultFormat( myformat );

    AppMainWindow mainWindow(NULL, "Freestyle");

    g_pController = new Controller;
    g_pController->SetMainWindow(&mainWindow);
    g_pController->SetView(mainWindow.pQGLWidget);

    mainWindow.show();

    int res = app->exec();

    delete g_pController;

    return res;
}
Ejemplo n.º 4
0
PixmapRenderer::PixmapRenderer(int width, int height, QGLWidget *shareWidget)
	: width_(width), height_(height), shareWidget_(shareWidget)
{
	QGLFormat fmt = QGLFormat::defaultFormat();
	fmt.setAlpha(true);
	fmt.setSampleBuffers(true);

	if (!QGLPixelBuffer::hasOpenGLPbuffers()) {
		throw std::runtime_error("OpenGL Pbuffer extension required.");
	}
	
	buffer_ = new QGLPixelBuffer(width_, height_, fmt, shareWidget_);
	buffer_->makeCurrent();	
	
	// Initialize GL
#ifndef KONSTRUKTOR_DB_UPDATER
	params_ = new ldraw_renderer::parameters(*Application::self()->renderer_params());
#else
	params_ = new ldraw_renderer::parameters();
	params_->set_stud_rendering_mode(ldraw_renderer::parameters::stud_regular);
#endif
	
	ldraw_renderer::renderer_opengl_factory ro(params_, ldraw_renderer::renderer_opengl_factory::mode_vbo);
	renderer_ = ro.create_renderer();
	renderer_->set_base_color(ldraw::color(7));
	renderer_->setup();
	
	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
	glClearDepth(1.0f);
	
	glMatrixMode(GL_PROJECTION);
	glViewport(0, 0, width_, height_);
	
	buffer_->doneCurrent();
}
Ejemplo n.º 5
0
int main(int argc, char** argv)
{
  char *flnm;

  QApplication application(argc,argv);
  
  QGLFormat glFormat;
  glFormat.setSampleBuffers(true);
  glFormat.setDoubleBuffer(true);
  glFormat.setRgba(true);
  glFormat.setAlpha(true);

//  //-----------------------------
//  // did not work - still getting 8bit buffers
//  glFormat.setAlphaBufferSize(16);
//  glFormat.setRedBufferSize(16);
//  glFormat.setGreenBufferSize(16);
//  glFormat.setBlueBufferSize(16);
//  //-----------------------------

  flnm = argv[1];
  if (QString::compare(argv[1], "-stereo", Qt::CaseInsensitive) == 0)
    {
      flnm = argv[2];
      glFormat.setStereo(true);
    }
  QGLFormat::setDefaultFormat(glFormat);

  MainWindow mainwindow;
  mainwindow.show();
  
  // Run main loop.
  return application.exec();
}
Ejemplo n.º 6
0
ArthurFrame::ArthurFrame(QWidget *parent)
    : QWidget(parent)
    , m_prefer_image(false)
{
#ifdef QT_OPENGL_SUPPORT
  std::cout << "Using Open GL" << std::endl;
    glw = 0;
    m_use_opengl = false;
    QGLFormat f = QGLFormat::defaultFormat();
    f.setSampleBuffers(true);
    f.setStencil(true);
    f.setAlpha(true);
    f.setAlphaBufferSize(8);
    QGLFormat::setDefaultFormat(f);
#endif
    m_document = 0;
    m_show_doc = false;

    m_tile = QPixmap(100, 100);
    m_tile.fill(Qt::white);
    QPainter pt(&m_tile);
    QColor color(240, 240, 240);
    pt.fillRect(0, 0, 50, 50, color);
    pt.fillRect(50, 50, 50, 50, color);
    pt.end();

//     QPalette pal = palette();
//     pal.setBrush(backgroundRole(), m_tile);
//     setPalette(pal);

#ifdef Q_WS_X11
    QPixmap xRenderPixmap(1, 1);
    m_prefer_image = !xRenderPixmap.x11PictureHandle();
#endif
}
Ejemplo n.º 7
0
/*===========================================================================*/
void ScreenBase::create()
{
    KVS_ASSERT( m_id == -1 );

    // Initialize display mode.
    QGLFormat f = QGLFormat::defaultFormat();
    f.setDoubleBuffer( displayFormat().doubleBuffer() );
    f.setRgba( displayFormat().colorBuffer() );
    f.setDepth( displayFormat().depthBuffer() );
    f.setAccum( displayFormat().accumulationBuffer() );
    f.setStencil( displayFormat().stencilBuffer() );
    f.setStereo( displayFormat().stereoBuffer() );
    f.setSampleBuffers( displayFormat().multisampleBuffer() );
    f.setAlpha( displayFormat().alphaChannel() );
    QGLFormat::setDefaultFormat( f );

    // Set screen geometry.
    QWidget::setGeometry( BaseClass::x(), BaseClass::y(), BaseClass::width(), BaseClass::height() );

    QGLWidget::makeCurrent();

    // Initialize GLEW.
    GLenum result = glewInit();
    if ( result != GLEW_OK )
    {
        const GLubyte* message = glewGetErrorString( result );
        kvsMessageError( "GLEW initialization failed: %s.", message );
    }

    // Create window.
    static int counter = 0;
    m_id = counter++;
}
Ejemplo n.º 8
0
	bool wzMainScreenSetup(int antialiasing, bool fullscreen, bool vsync)
	{
		debug(LOG_MAIN, "Qt initialization");
		//QGL::setPreferredPaintEngine(QPaintEngine::OpenGL); // Workaround for incorrect text rendering on many platforms, doesn't exist in Qt5…

		// Setting up OpenGL
		QGLFormat format;
		format.setDoubleBuffer(true);
		format.setAlpha(true);
		int w = pie_GetVideoBufferWidth();
		int h = pie_GetVideoBufferHeight();

		if (antialiasing)
		{
			format.setSampleBuffers(true);
			format.setSamples(antialiasing);
		}
		mainWindowPtr = new WzMainWindow(QSize(w, h), format);
		WzMainWindow &mainwindow = *mainWindowPtr;
		mainwindow.setMinimumResolution(QSize(800, 600));
		if (!mainwindow.context()->isValid())
		{
			QMessageBox::critical(NULL, "Oops!", "Warzone2100 failed to create an OpenGL context. This probably means that your graphics drivers are out of date. Try updating them!");
			return false;
		}

		screenWidth = w;
		screenHeight = h;
		if (fullscreen)
		{
			mainwindow.resize(w, h);
			mainwindow.showFullScreen();
			if (w > mainwindow.width())
			{
				w = mainwindow.width();
			}
			if (h > mainwindow.height())
			{
				h = mainwindow.height();
			}
			pie_SetVideoBufferWidth(w);
			pie_SetVideoBufferHeight(h);
		}
		else
		{
			mainwindow.show();
			mainwindow.setMinimumSize(w, h);
			mainwindow.setMaximumSize(w, h);
		}

		mainwindow.setSwapInterval(vsync);
		mainwindow.setReadyToPaint();

		return true;
	}
Ejemplo n.º 9
0
void *QGLContext::chooseVisual()
{
    static int bufDepths[] = { 8, 4, 2, 1 };	// Try 16, 12 also?
    //todo: if pixmap, also make sure that vi->depth == pixmap->depth
    void* vis = 0;
    int i = 0;
    bool fail = FALSE;
    QGLFormat fmt = format();
    bool tryDouble = !fmt.doubleBuffer();  // Some GL impl's only have double
    bool triedDouble = FALSE;
    while( !fail && !( vis = tryVisual( fmt, bufDepths[i] ) ) ) {
	if ( !fmt.rgba() && bufDepths[i] > 1 ) {
	    i++;
	    continue;
	}
	if ( tryDouble ) {
	    fmt.setDoubleBuffer( TRUE );
	    tryDouble = FALSE;
	    triedDouble = TRUE;
	    continue;
	}
	else if ( triedDouble ) {
	    fmt.setDoubleBuffer( FALSE );
	    triedDouble = FALSE;
	}
	if ( fmt.stereo() ) {
	    fmt.setStereo( FALSE );
	    continue;
	}
	if ( fmt.accum() ) {
	    fmt.setAccum( FALSE );
	    continue;
	}
	if ( fmt.stencil() ) {
	    fmt.setStencil( FALSE );
	    continue;
	}
	if ( fmt.alpha() ) {
	    fmt.setAlpha( FALSE );
	    continue;
	}
	if ( fmt.depth() ) {
	    fmt.setDepth( FALSE );
	    continue;
	}
	if ( fmt.doubleBuffer() ) {
	    fmt.setDoubleBuffer( FALSE );
	    continue;
	}
	fail = TRUE;
    }
    glFormat = fmt;
    return vis;
}
QGLFormat QtCanvas::getQGLFormat(const Buffers buffers) {
    QGLFormat format = QGLFormat();
    format.setAlpha(buffers & GLCanvas::ALPHA_BUFFER);
    format.setDepth(buffers & GLCanvas::DEPTH_BUFFER);
    format.setDoubleBuffer(buffers & GLCanvas::DOUBLE_BUFFER);
    format.setStencil(buffers & GLCanvas::STENCIL_BUFFER);
    format.setAccum(buffers & GLCanvas::ACCUM_BUFFER);
    format.setStereo(buffers & GLCanvas::STEREO_VIEWING);
    format.setSampleBuffers(buffers & GLCanvas::MULTISAMPLING);

    return format;
}
Ejemplo n.º 11
0
Archivo: main.cpp Proyecto: akva2/BSGUI
int main(int argc, char **argv)
{
    QGLFormat fmt;
    fmt.setRgba(true);
    fmt.setAlpha(true);
    fmt.setDepth(true);
    fmt.setDoubleBuffer(true);
    QGLFormat::setDefaultFormat(fmt);

    QApplication app(argc, argv);

    MainWindow window;
    window.showMaximized();

    for (int i = 1; i < argc; i++)
        window.objectSet()->loadFile(argv[i]);

    return app.exec();
}
Ejemplo n.º 12
0
TwoDFrame::TwoDFrame( QWidget * parent, Qt::WFlags f ) :
	QFrame(parent, f) {
	
	setFocusPolicy(Qt::StrongFocus);
	 // Create our OpenGL widget.  
	QGLFormat fmt;
	fmt.setAlpha(true);
	fmt.setRgba(true);
	fmt.setDoubleBuffer(true);
	fmt.setDirectRendering(true);
    glTwoDWindow = new GLTwoDWindow(fmt, this, "gltwoDwindow", this);
	if (!(fmt.directRendering() && fmt.rgba() && fmt.alpha() && fmt.doubleBuffer())){
		Params::BailOut("Unable to obtain required OpenGL rendering format",__FILE__,__LINE__);	
	}
	QHBoxLayout* flayout = new QHBoxLayout( this);
    flayout->addWidget( glTwoDWindow, 1 );
	twoDParams = 0;
	isDataWindow = true;

}
Ejemplo n.º 13
0
    void GridsPlugin::initDockWidget()
    {
        // create and add doc widget
        _dock_widget = new QDockWidget(QObject::tr("Grid Viewer"));
        _dock_widget->setAllowedAreas(Qt::RightDockWidgetArea);
        _dock_widget->setObjectName("gridViewerDock");

        QGLFormat format;
        format.setVersion(2, 1);
        format.setDoubleBuffer(true);
        format.setDepth(true);
        format.setRgba(true);
        format.setAlpha(false);
        format.setAccum(false);
        format.setStencil(false);
        format.setStereo(false);
        format.setDirectRendering(true);
        format.setOverlay(false);

        _viewer = new GridViewer(format);
        _viewer->setMinimumSize(250, 0);
        _viewer->setObjectName("gridViewer");

        QVBoxLayout *layout = new QVBoxLayout();
        layout->addWidget(_viewer);

        QWidget *widget = new QWidget();
        widget->setLayout(layout);

        _dock_widget->setWidget(widget);

        NeuroGui::MainWindow::instance()->addDockWidget(Qt::RightDockWidgetArea, _dock_widget);

        // add to view menu
        NeuroGui::MainWindow::instance()->toolBarsMenu()->addAction(_dock_widget->toggleViewAction());
    }
Ejemplo n.º 14
0
MainWindow::MainWindow()
: QMainWindow()
{
    _scene.reset();

    if (!QGLFormat::hasOpenGL()) {
        QMessageBox::critical(this,
                "No OpenGL Support",
                "This system does not appear to support OpenGL.\n\n"
                "The Tungsten scene editor requires OpenGL "
                "to work properly. The editor will now terminate.\n\n"
                "Please install any available updates for your graphics card driver and try again");
        std::exit(0);
    }

    QGLFormat qglFormat;
    qglFormat.setVersion(3, 2);
    qglFormat.setProfile(QGLFormat::CoreProfile);
    qglFormat.setAlpha(true);
    qglFormat.setSampleBuffers(true);
    qglFormat.setSamples(16);

    _windowSplit = new QSplitter(this);
    _stackWidget = new QStackedWidget(_windowSplit);

      _renderWindow = new   RenderWindow(_stackWidget, this);
     _previewWindow = new  PreviewWindow(_stackWidget, this, qglFormat);
    _propertyWindow = new PropertyWindow(_windowSplit, this);

    _stackWidget->addWidget(_renderWindow);
    _stackWidget->addWidget(_previewWindow);

    _windowSplit->addWidget(_stackWidget);
    _windowSplit->addWidget(_propertyWindow);
    _windowSplit->setStretchFactor(0, 1);
    _windowSplit->setStretchFactor(1, 0);

    setCentralWidget(_windowSplit);

    _previewWindow->addStatusWidgets(statusBar());
     _renderWindow->addStatusWidgets(statusBar());

    connect(this, SIGNAL(sceneChanged()),  _previewWindow, SLOT(sceneChanged()));
    connect(this, SIGNAL(sceneChanged()),   _renderWindow, SLOT(sceneChanged()));
    connect(this, SIGNAL(sceneChanged()), _propertyWindow, SLOT(sceneChanged()));

    connect( _previewWindow, SIGNAL(primitiveListChanged()), _propertyWindow, SLOT(primitiveListChanged()));
    connect( _previewWindow, SIGNAL(selectionChanged()), _propertyWindow, SLOT(changeSelection()));
    connect(_propertyWindow, SIGNAL(selectionChanged()),  _previewWindow, SLOT(changeSelection()));

    showPreview(true);

    QMenu *fileMenu = new QMenu("&File");
    fileMenu->addAction("New",          this, SLOT(newScene()),  QKeySequence("Ctrl+N"));
    fileMenu->addAction("Open File...", this, SLOT(openScene()), QKeySequence("Ctrl+O"));
    fileMenu->addAction("Reload File...", this, SLOT(reloadScene()), QKeySequence("Shift+R"));
    fileMenu->addSeparator();
    fileMenu->addAction("Close", this, SLOT(closeScene()), QKeySequence("Ctrl+W"));
    fileMenu->addSeparator();
    fileMenu->addAction("Save",       this, SLOT(saveScene()),   QKeySequence("Ctrl+S"));
    fileMenu->addAction("Save as...", this, SLOT(saveSceneAs()), QKeySequence("Ctrl+Shift+S"));
    fileMenu->addSeparator();
    fileMenu->addAction("Exit", this, SLOT(close()));

    QMenuBar *menuBar = new QMenuBar();
    menuBar->addMenu(fileMenu);

    setMenuBar(menuBar);

    newScene();
}
Ejemplo n.º 15
0
QGLGraphicsSystem::QGLGraphicsSystem(bool useX11GL)
    : QGraphicsSystem(), m_useX11GL(useX11GL)
{
#if defined(Q_WS_X11) && !defined(QT_OPENGL_ES)
    // only override the system defaults if the user hasn't already
    // picked a visual
    if (X11->visual == 0 && X11->visual_id == -1 && X11->visual_class == -1) {
        // find a double buffered, RGBA visual that supports OpenGL
        // and set that as the default visual for windows in Qt
        int i = 0;
        int spec[16];
        spec[i++] = GLX_RGBA;
        spec[i++] = GLX_DOUBLEBUFFER;

        if (!qgetenv("QT_GL_SWAPBUFFER_PRESERVE").isNull()) {
            spec[i++] = GLX_DEPTH_SIZE;
            spec[i++] = 8;
            spec[i++] = GLX_STENCIL_SIZE;
            spec[i++] = 8;
            spec[i++] = GLX_SAMPLE_BUFFERS_ARB;
            spec[i++] = 1;
            spec[i++] = GLX_SAMPLES_ARB;
            spec[i++] = 4;
        }

        spec[i++] = XNone;

        XVisualInfo *vi = glXChooseVisual(X11->display, X11->defaultScreen, spec);
        if (vi) {
            X11->visual_id = vi->visualid;
            X11->visual_class = vi->c_class;

            QGLFormat format;
            int res;
            glXGetConfig(X11->display, vi, GLX_LEVEL, &res);
            format.setPlane(res);
            glXGetConfig(X11->display, vi, GLX_DOUBLEBUFFER, &res);
            format.setDoubleBuffer(res);
            glXGetConfig(X11->display, vi, GLX_DEPTH_SIZE, &res);
            format.setDepth(res);
            if (format.depth())
                format.setDepthBufferSize(res);
            glXGetConfig(X11->display, vi, GLX_RGBA, &res);
            format.setRgba(res);
            glXGetConfig(X11->display, vi, GLX_RED_SIZE, &res);
            format.setRedBufferSize(res);
            glXGetConfig(X11->display, vi, GLX_GREEN_SIZE, &res);
            format.setGreenBufferSize(res);
            glXGetConfig(X11->display, vi, GLX_BLUE_SIZE, &res);
            format.setBlueBufferSize(res);
            glXGetConfig(X11->display, vi, GLX_ALPHA_SIZE, &res);
            format.setAlpha(res);
            if (format.alpha())
                format.setAlphaBufferSize(res);
            glXGetConfig(X11->display, vi, GLX_ACCUM_RED_SIZE, &res);
            format.setAccum(res);
            if (format.accum())
                format.setAccumBufferSize(res);
            glXGetConfig(X11->display, vi, GLX_STENCIL_SIZE, &res);
            format.setStencil(res);
            if (format.stencil())
                format.setStencilBufferSize(res);
            glXGetConfig(X11->display, vi, GLX_STEREO, &res);
            format.setStereo(res);
            glXGetConfig(X11->display, vi, GLX_SAMPLE_BUFFERS_ARB, &res);
            format.setSampleBuffers(res);
            if (format.sampleBuffers()) {
                glXGetConfig(X11->display, vi, GLX_SAMPLES_ARB, &res);
                format.setSamples(res);
            }

            QGLWindowSurface::surfaceFormat = format;
            XFree(vi);

            printf("using visual class %x, id %x\n", X11->visual_class, X11->visual_id);
        }
    }
#elif defined(Q_WS_WIN)
    QGLWindowSurface::surfaceFormat.setDoubleBuffer(true);

    qt_win_owndc_required = true;
#endif
}
Ejemplo n.º 16
0
CubeWidget::CubeWidget(const QString &name, int pos)
        : ModuleWidget(name, pos)
{
    m_active = false;
    m_varsCount = 0;
    m_cube = Kernel::instance()->getCube();

    // OpenGL format
    QGLFormat fmt;
    fmt.setDepth(true);
    fmt.setAlpha(true);

    // drawer
    m_drawer = new CubeGLDrawer(fmt);
    m_gm = GUIManager::instance();
    // changing one term in drawer
    connect(m_drawer, SIGNAL(cubeChanged(int, OutputValue &)),
            m_gm, SLOT(setTerm(int, OutputValue &)));
    // minimizing formula from drawer
    connect(m_drawer, SIGNAL(minRequested()), m_gm, SLOT(minimizeFormula()));

    // creating new formula
    connect(m_gm, SIGNAL(formulaChanged()), m_drawer, SLOT(reloadCube()));
    connect(m_gm, SIGNAL(formulaChanged()), this, SLOT(updateData()));
    connect(m_gm, SIGNAL(minimalFormulaChanged()), this, SLOT(updateData()));
    connect(m_gm, SIGNAL(minimalFormulaChanged()), m_drawer, SLOT(reloadCube()));
    // request for minimizing cube
    connect(m_gm, SIGNAL(formulaMinimized()), m_drawer, SLOT(minimizeCube()));
    // request for invalidating cube
    connect(m_gm, SIGNAL(formulaInvalidated()), m_drawer, SLOT(invalidateCube()));
    connect(m_gm, SIGNAL(formulaInvalidated()), this, SLOT(invalidateData()));
    // formula representation changed
    connect(m_gm, SIGNAL(repreChanged(bool)), this, SLOT(setRepre(bool)));
    // setting drawer activity
    connect(this, SIGNAL(activated(bool)), m_drawer, SLOT(setActivity(bool)));

    QHBoxLayout *glLayout = new QHBoxLayout;
    glLayout->setMargin(0);
    glLayout->addWidget(m_drawer);

    BorderWidget *borderWidget = new BorderWidget;
    borderWidget->setLayout(glLayout);
    BorderWidget *error1Widget = new BorderWidget(tr("No logic function for Cube."));
    BorderWidget *error2Widget = new BorderWidget(tr("Too many variables (max 3 variables)."));
    m_stack = new QStackedLayout;
    m_stack->addWidget(borderWidget);
    m_stack->addWidget(error1Widget);
    m_stack->addWidget(error2Widget);
    m_stack->setCurrentIndex(1);

    // terms
    m_termsModel = new TermsModel;
    m_termsView = new QTableView;
    m_termsView->setModel(m_termsModel);
    m_termsView->setShowGrid(false);
    m_termsView->horizontalHeader()->hide();
    m_termsView->setMaximumWidth(SIDEBAR_SIZE);
    m_mintermsStr = tr("Minterms");
    m_maxtermsStr = tr("Maxterms");
    m_termsLabel = new QLabel(m_gm->isSoP()? m_mintermsStr: m_maxtermsStr);
    m_termsLabel->setContentsMargins(3, 5, 5, 0);
    m_termsLabel->setBuddy(m_termsView);

    // covers
    m_coversModel = new CoversModel;
    m_coversView = new QTableView;
    m_coversView->setModel(m_coversModel);
    m_coversView->setShowGrid(false);
    m_coversView->horizontalHeader()->hide();
    m_coversView->verticalHeader()->hide();
    m_coversView->setMaximumWidth(SIDEBAR_SIZE);
    m_coversCheckBox = new QCheckBox(tr("Show covers"));
    m_coversCheckBox->setChecked(Constants::CUBE_COVERS_DEFAULT);
    m_drawer->showCovers(Constants::CUBE_COVERS_DEFAULT);
    connect(m_coversCheckBox, SIGNAL(toggled(bool)), this, SLOT(enableCovers(bool)));
    connect(m_coversCheckBox, SIGNAL(toggled(bool)), m_drawer, SLOT(showCovers(bool)));
    connect(m_drawer, SIGNAL(showingCoversChanged(bool)), m_coversCheckBox, SLOT(setChecked(bool)));
    connect(m_termsView->selectionModel(),
            SIGNAL(selectionChanged(QItemSelection, QItemSelection)),
            this, SLOT(selectTerms(QItemSelection, QItemSelection)));
    connect(m_coversView->selectionModel(),
            SIGNAL(selectionChanged(QItemSelection, QItemSelection)),
            this, SLOT(selectCovers(QItemSelection, QItemSelection)));

#if CUBE_TEXTURES
    // covers tour
    m_tourPos = -1;
    QGroupBox *tourGroupBox = new QGroupBox(tr("Covers tour"));
    m_tourStartStr = tr("Start tour");
    m_tourStopStr = tr("Stop tour");
    m_tourBtn = new QPushButton(m_tourStartStr);
    m_tourBtn->setEnabled(false);
    m_tourPrevBtn = new QPushButton(tr("Prev"));
    m_tourPrevBtn->setEnabled(false);
    m_tourNextBtn = new QPushButton(tr("Next"));
    m_tourNextBtn->setEnabled(false);
    QHBoxLayout *tourShiftLayout = new QHBoxLayout;
    tourShiftLayout->setMargin(0);
    tourShiftLayout->addWidget(m_tourPrevBtn);
    tourShiftLayout->addWidget(m_tourNextBtn);
    QVBoxLayout *tourMainLayout = new QVBoxLayout;
    tourMainLayout->setMargin(0);
    tourMainLayout->addWidget(m_tourBtn);
    tourMainLayout->addLayout(tourShiftLayout);
    tourGroupBox->setLayout(tourMainLayout);
    // tour connections with drawer
    connect(m_tourBtn, SIGNAL(clicked()), m_drawer, SLOT(toggleMin()));
    connect(m_tourNextBtn, SIGNAL(clicked()), m_drawer, SLOT(nextMin()));
    connect(m_tourPrevBtn, SIGNAL(clicked()), m_drawer, SLOT(prevMin()));
    connect(m_drawer, SIGNAL(minStarted(int)), this, SLOT(startTour(int)));
    connect(m_drawer, SIGNAL(minStopped()), this, SLOT(stopTour()));
    connect(m_drawer, SIGNAL(minShifted(int)), this, SLOT(shiftTour(int)));
#endif

    // espresso
    EspressoWidget *espressoWidget = new EspressoWidget(CubeGLDrawer::MAX_N);

    QVBoxLayout *sideLayout = new QVBoxLayout;
    sideLayout->addWidget(m_termsLabel);
    sideLayout->addWidget(m_termsView);
    sideLayout->addWidget(m_coversCheckBox);
    sideLayout->addWidget(m_coversView);
#if CUBE_TEXTURES
    sideLayout->addWidget(tourGroupBox);
#endif
    sideLayout->addWidget(espressoWidget);
    sideLayout->setStretchFactor(m_termsView, 5);
    sideLayout->setStretchFactor(m_coversView, 3);

    QHBoxLayout *mainLayout = new QHBoxLayout;
    mainLayout->setMargin(0);
    //mainLayout->addWidget(borderWidget);
    mainLayout->addLayout(m_stack);
    mainLayout->addLayout(sideLayout);

    setLayout(mainLayout);

    setFocusPolicy(Qt::StrongFocus);
}
Ejemplo n.º 17
0
int main(int argc, char *argv[])
{
    int i;
    const char *resPath = 0;
    char    override_base_file[MAX_STR_LEN] = "";
    int     override_local_port = 0;
    char    override_remote_host[MAX_STR_LEN] = "";
    int     override_remote_port = 0;
    char    configfile[MAX_STR_LEN] = "mume.ini";
    int     default_local_port = 3000;
    int     default_remote_port = 4242;
    int     mud_emulation = 0;

#ifdef Q_OS_MACX
    CFURLRef pluginRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());
    CFStringRef macPath = CFURLCopyFileSystemPath(pluginRef,
						  kCFURLPOSIXPathStyle);
    const char *appPath = CFStringGetCStringPtr(macPath,
						CFStringGetSystemEncoding());
    resPath = (char *)malloc(strlen(appPath)+25);
    strcpy(resPath, appPath);
    strcat(resPath, "/Contents/Resources/");

    char    default_base_file[MAX_STR_LEN] = "mume.pmf";
    char    default_remote_host[MAX_STR_LEN] = "";
    strcpy(configfile, "configs/default.conf");

    CFRelease(pluginRef);
    CFRelease(macPath);

#else
    resPath = "";
    char    default_base_file[MAX_STR_LEN] = "mume.pmf";
    char    default_remote_host[MAX_STR_LEN] = "129.241.210.221";
#endif
    QApplication::setColorSpec( QApplication::CustomColor );
    QApplication app( argc, argv );

    QPixmap pixmap("images/logo.png");
    QSplashScreen *splash = new QSplashScreen(pixmap);
    splash->show();

    splash->showMessage("Loading configuration and database...");

    for (i=1; i < argc; i++) {

      if ((strcmp(argv[i], "--config") == 0) || ( strcmp(argv[i], "-c") == 0))
      {
        if (i == argc) {
          printf("Too few arguments. Missing config file name.\r\n");
          print_usage();
          exit(1);
        }
        i++;

        strcpy(configfile, argv[i]);
	resPath = ""; // obviously the user has an own config file - including the path
      }

      if ((strcmp(argv[i], "--emulate") == 0) || ( strcmp(argv[i], "-e") == 0))
      {
        printf("Pandora: Starting in MUD emulation mode.\r\n");
        mud_emulation = 1;
      }

      if ((strcmp(argv[i], "--base") == 0) || ( strcmp(argv[i], "-b") == 0))
      {
        if (i == argc) {
          printf("Too few arguments. Missing database.\r\n");
          print_usage();
          exit(1);
        }
        i++;
        strcpy(override_base_file, argv[i]); // overriding the database file is possible even with default config file
      }

      if ((strcmp(argv[i], "--hostname") == 0) || ( strcmp(argv[i], "-hn") == 0))
      {
        if (i == argc) {
          printf("Too few arguments. Wrong hostname given.\r\n");
          print_usage();
          exit(1);
        }
        i++;
        strcpy(override_remote_host, argv[i]);
      }

      if ((strcmp(argv[i], "--localport") == 0) || ( strcmp(argv[i], "-lp") == 0))
      {
        if (i == argc) {
          printf("Too few arguments. Missing localport.\r\n");
          print_usage();
          exit(1);
        }
        i++;
        override_local_port = atoi(argv[i]);
      }

      if ((strcmp(argv[i], "--remoteport") == 0) || ( strcmp(argv[i], "-rp") == 0))
      {
        if (i == argc) {
          printf("Too few arguments. Missing targetport.\r\n");
          print_usage();
          exit(1);
        }
        i++;
        override_remote_port = atoi(argv[i]);
      }


      if ((strcmp(argv[i], "--help") == 0) || ( strcmp(argv[i], "-h") == 0))
      {
        print_usage();
        exit(1);
      }

    }


    /* set analyzer engine defaults */
    //engine_init();
    splash->showMessage(QString("Loading the configuration ") + configfile);
    conf = new Cconfigurator();
    conf->loadConfig(resPath, configfile);
    print_debug(DEBUG_SYSTEM, "starting up...");


    if (override_base_file[0] != 0) {
      conf->setBaseFile(override_base_file);
    } else if ( conf->getBaseFile() == "") {
      conf->setBaseFile(default_base_file);
    }
    print_debug(DEBUG_SYSTEM, "Using database file : %s.", (const char*) conf->getBaseFile() );

    if (override_remote_host[0] != 0) {
      conf->setRemoteHost(override_remote_host);
    } else if ( conf->getRemoteHost().isEmpty() ) {
      conf->setRemoteHost(default_remote_host);
    }
    print_debug(DEBUG_SYSTEM, "Using target hostname : %s.", (const char*) conf->getRemoteHost() );

    if (override_local_port != 0) {
      conf->setLocalPort(override_local_port);
    } else if ( conf->getLocalPort() == 0) {
      conf->setLocalPort(default_local_port);
    }
    print_debug(DEBUG_SYSTEM, "Using local port : %i.", conf->getLocalPort());

    if (override_remote_port != 0) {
      conf->setRemotePort(override_remote_port);
    } else if (conf->getRemotePort() == 0) {
      conf->setRemotePort(default_remote_port);
    }
    print_debug(DEBUG_SYSTEM, "Using target port : %i.", conf->getRemotePort());

    conf->setConfigModified( false );

    splash->showMessage("Starting Analyzer and Proxy...");

    engine = new CEngine(new CRoomManager());
    proxy = new Proxy();

    /* special init for the mud emulation */
    if (mud_emulation) {
        print_debug(DEBUG_SYSTEM, "Starting in MUD emulation mode...");
        engine->initEmulationMode();
    }

    proxy->setMudEmulation( mud_emulation );


    print_debug(DEBUG_SYSTEM, "Starting renderer ...\n");

    if ( !QGLFormat::hasOpenGL() ) {
        qWarning( "This system has no OpenGL support. Quiting." );
        return -1;
    }

    QRect rect = app.desktop()->availableGeometry(-1);
    if (conf->getWindowRect().x() == 0 || conf->getWindowRect().x() >= rect.width() ||
        conf->getWindowRect().y() >= rect.height() ) {
        print_debug(DEBUG_SYSTEM && DEBUG_INTERFACE, "Autosettings for window size and position");
        int x, y, height, width;

        x = rect.width() / 3 * 2;
        y = 0;
        height = rect.height() / 3;
        width = rect.width() - x;

        conf->setWindowRect( x, y, width, height);
    }


    QGLFormat f = QGLFormat::defaultFormat();
    f.setDoubleBuffer( true );
    f.setDirectRendering( true );
    f.setRgba( true );
    f.setDepth( true );
    f.setAlpha( true );

    if (conf->getMultisampling())
   	f.setSampleBuffers( true );
    //f.setSamples(4);

    QGLFormat::setDefaultFormat( f );

    renderer_window = new CMainWindow;

    renderer_window->show();

    splash->finish(renderer_window);
    delete splash;

    proxy->start();
    QObject::connect(proxy, SIGNAL(startEngine()), engine, SLOT(slotRunEngine()), Qt::QueuedConnection );
    QObject::connect(proxy, SIGNAL(startRenderer()), renderer_window->renderer, SLOT(display()), Qt::QueuedConnection);

    // this will be done via mainwindow itself
    //userland_parser->parse_user_input_line("mload");

    return app.exec();
}
Ejemplo n.º 18
0
/*
  See qgl.cpp for qdoc comment.
 */
void *QGLContext::chooseVisual()
{
    Q_D(QGLContext);
    static const int bufDepths[] = { 8, 4, 2, 1 };        // Try 16, 12 also?
    //todo: if pixmap, also make sure that vi->depth == pixmap->depth
    void* vis = 0;
    int i = 0;
    bool fail = false;
    QGLFormat fmt = format();
    bool tryDouble = !fmt.doubleBuffer();  // Some GL impl's only have double
    bool triedDouble = false;
    bool triedSample = false;
    if (fmt.sampleBuffers())
        fmt.setSampleBuffers(QGLExtensions::glExtensions & QGLExtensions::SampleBuffers);
    while(!fail && !(vis = tryVisual(fmt, bufDepths[i]))) {
        if (!fmt.rgba() && bufDepths[i] > 1) {
            i++;
            continue;
        }
        if (tryDouble) {
            fmt.setDoubleBuffer(true);
            tryDouble = false;
            triedDouble = true;
            continue;
        } else if (triedDouble) {
            fmt.setDoubleBuffer(false);
            triedDouble = false;
        }
        if (!triedSample && fmt.sampleBuffers()) {
            fmt.setSampleBuffers(false);
            triedSample = true;
            continue;
        }
        if (fmt.stereo()) {
            fmt.setStereo(false);
            continue;
        }
        if (fmt.accum()) {
            fmt.setAccum(false);
            continue;
        }
        if (fmt.stencil()) {
            fmt.setStencil(false);
            continue;
        }
        if (fmt.alpha()) {
            fmt.setAlpha(false);
            continue;
        }
        if (fmt.depth()) {
            fmt.setDepth(false);
            continue;
        }
        if (fmt.doubleBuffer()) {
            fmt.setDoubleBuffer(false);
            continue;
        }
        fail = true;
    }
    d->glFormat = fmt;
    return vis;
}
Ejemplo n.º 19
0
int main(int argc, char *argv[])
{
#ifdef Q_OS_WIN
	//  Enable standard input/output on Windows Platform for debug
	BOOL consoleAttached = ::AttachConsole(ATTACH_PARENT_PROCESS);
	if (consoleAttached) {
		freopen("CON", "r", stdin);
		freopen("CON", "w", stdout);
		freopen("CON", "w", stderr);
	}
#endif

	/*-- "-layout [レイアウト設定ファイル名]" で、必要なモジュールのPageだけのレイアウトで起動することを可能にする --*/
	QString argumentLayoutFileName = "";
	TFilePath loadScenePath;
	if (argc > 1) {
		for (int a = 1; a < argc; a++) {
			if (QString(argv[a]) == "-layout") {
				argumentLayoutFileName = QString(argv[a + 1]);
				a++;
			} else
				loadScenePath = TFilePath(argv[a]);
		}
	}

	QApplication a(argc, argv);

#ifdef Q_OS_WIN
	//	Since currently OpenToonz does not work with OpenGL of software or angle,
	//	force Qt to use desktop OpenGL
	a.setAttribute(Qt::AA_UseDesktopOpenGL, true);
#endif

	// Some Qt objects are destroyed badly withouth a living qApp. So, we must enforce a way to either
	// postpone the application destruction until the very end, OR ensure that sensible objects are
	// destroyed before.

	// Using a static QApplication only worked on Windows, and in any case C++ respects the statics destruction
	// order ONLY within the same library. On MAC, it made the app crash on exit o_o. So, nope.

	std::auto_ptr<QObject> mainScope(new QObject(&a)); // A QObject destroyed before the qApp is therefore explicitly
	mainScope->setObjectName("mainScope");			   // provided. It can be accessed by looking in the qApp's children.

#ifdef _WIN32
#ifndef x64
	//Store the floating point control word. It will be re-set before Toonz initialization
	//has ended.
	unsigned int fpWord = 0;
	_controlfp_s(&fpWord, 0, 0);
#endif
#endif

#ifdef _WIN32
	//At least on windows, Qt's 4.5.2 native windows feature tend to create
	//weird flickering effects when dragging panel separators.
	a.setAttribute(Qt::AA_DontCreateNativeWidgetSiblings);
#endif

	//Set the app's locale for numeric stuff to standard C. This is important for atof() and similar
	//calls that are locale-dependant.
	setlocale(LC_NUMERIC, "C");

// Set current directory to the bundle/application path - this is needed to have correct relative paths
#ifdef MACOSX
	{
		QDir appDir(QApplication::applicationDirPath());
		appDir.cdUp(), appDir.cdUp(), appDir.cdUp();

		bool ret = QDir::setCurrent(appDir.absolutePath());
		assert(ret);
	}
#endif

	// splash screen
	QPixmap splashPixmap(":Resources/splash.png");
#ifdef _WIN32
	a.setFont(QFont("Arial", 10));
#else
	a.setFont(QFont("Helvetica", 10));
#endif

	QString offsetStr("\n\n\n\n\n\n\n\n");

	TSystem::hasMainLoop(true);

	TMessageRepository::instance();

	QSplashScreen splash(splashPixmap);
	splash.show();
	a.processEvents();

	splash.showMessage(offsetStr + "Initializing QGLFormat...", Qt::AlignCenter, Qt::white);
	a.processEvents();

	// OpenGL
	QGLFormat fmt;
	fmt.setAlpha(true);
	fmt.setStencil(true);
	QGLFormat::setDefaultFormat(fmt);

#ifdef LINUX
	glutInit(&argc, argv);
#endif

	splash.showMessage(offsetStr + "Initializing Toonz environment ...", Qt::AlignCenter, Qt::white);
	a.processEvents();

	//Install run out of contiguous memory callback
	TBigMemoryManager::instance()->setRunOutOfContiguousMemoryHandler(&toonzRunOutOfContMemHandler);

	// Toonz environment
	initToonzEnv();

	// Initialize thread components
	TThread::init();

	TProjectManager *projectManager = TProjectManager::instance();
	if (Preferences::instance()->isSVNEnabled()) {
		// Read Version Control repositories and add it to project manager as "special" svn project root
		VersionControl::instance()->init();
		QList<SVNRepository> repositories = VersionControl::instance()->getRepositories();
		int count = repositories.size();
		for (int i = 0; i < count; i++) {
			SVNRepository r = repositories.at(i);

			TFilePath localPath(r.m_localPath.toStdWString());
			if (!TFileStatus(localPath).doesExist()) {
				try {
					TSystem::mkDir(localPath);
				} catch (TException &e) {
					fatalError(QString::fromStdWString(e.getMessage()));
				}
			}
			projectManager->addSVNProjectsRoot(localPath);
		}
	}

#if defined(MACOSX) && defined(__LP64__)

	//Load the shared memory settings
	int shmmax = Preferences::instance()->getShmMax();
	int shmseg = Preferences::instance()->getShmSeg();
	int shmall = Preferences::instance()->getShmAll();
	int shmmni = Preferences::instance()->getShmMni();

	if (shmall < 0) //Make sure that at least 100 MB of shared memory are available
		shmall = (tipc::shm_maxSharedPages() < (100 << 8)) ? (100 << 8) : -1;

	tipc::shm_set(shmmax, shmseg, shmall, shmmni);

#endif

	// DVDirModel must be instantiated after Version Control initialization...
	FolderListenerManager::instance()->addListener(DvDirModel::instance());

	splash.showMessage(offsetStr + "Loading Translator ...", Qt::AlignCenter, Qt::white);
	a.processEvents();

	// Carico la traduzione contenuta in toonz.qm (se � presente)
	QString languagePathString = QString::fromStdString(toString(TEnv::getConfigDir() + "loc"));
#ifndef WIN32
	//the merge of menu on osx can cause problems with different languages with the Preferences menu
	//qt_mac_set_menubar_merge(false);
	languagePathString += "/" + Preferences::instance()->getCurrentLanguage();
#else
	languagePathString += "\\" + Preferences::instance()->getCurrentLanguage();
#endif
	QTranslator translator;
#ifdef LINETEST
	translator.load("linetest", languagePathString);
#else
	translator.load("toonz", languagePathString);
#endif

	// La installo
	a.installTranslator(&translator);

	// Carico la traduzione contenuta in toonzqt.qm (se e' presente)
	QTranslator translator2;
	translator2.load("toonzqt", languagePathString);
	a.installTranslator(&translator2);

	// Carico la traduzione contenuta in tnzcore.qm (se e' presente)
	QTranslator tnzcoreTranslator;
	tnzcoreTranslator.load("tnzcore", languagePathString);
	qApp->installTranslator(&tnzcoreTranslator);

	// Carico la traduzione contenuta in toonzlib.qm (se e' presente)
	QTranslator toonzlibTranslator;
	toonzlibTranslator.load("toonzlib", languagePathString);
	qApp->installTranslator(&toonzlibTranslator);

	// Carico la traduzione contenuta in colorfx.qm (se e' presente)
	QTranslator colorfxTranslator;
	colorfxTranslator.load("colorfx", languagePathString);
	qApp->installTranslator(&colorfxTranslator);

	// Carico la traduzione contenuta in tools.qm
	QTranslator toolTranslator;
	toolTranslator.load("tnztools", languagePathString);
	qApp->installTranslator(&toolTranslator);

	// Aggiorno la traduzione delle properties di tutti i tools
	TTool::updateToolsPropertiesTranslation();

	splash.showMessage(offsetStr + "Loading styles ...", Qt::AlignCenter, Qt::white);
	a.processEvents();

	// stile
	QApplication::setStyle("windows");

	IconGenerator::setFilmstripIconSize(Preferences::instance()->getIconSize());

	splash.showMessage(offsetStr + "Loading shaders ...", Qt::AlignCenter, Qt::white);
	a.processEvents();

	loadShaderInterfaces(ToonzFolder::getLibraryFolder() + TFilePath("shaders"));

	splash.showMessage(offsetStr + "Initializing Toonz application ...", Qt::AlignCenter, Qt::white);
	a.processEvents();

	TTool::setApplication(TApp::instance());
	TApp::instance()->init();

//iwsw commented out temporarily
#if 0 
  QStringList monitorNames;
  /*-- 接続モニタがPVM-2541の場合のみLUTを読み込む --*/
  if (Preferences::instance()->isDoColorCorrectionByUsing3DLutEnabled())
  {
	  /*-- 接続モニタがPVM-2541の場合のみLUTを読み込む --*/
	  monitorNames = Ghibli3DLutUtil::getMonitorName();
	  if (monitorNames.contains(QString::fromStdWString(L"PVM-2541")))
		  /*-- 3DLUTファイルを読み込む --*/
		  Ghibli3DLutUtil::loadLutFile(Preferences::instance()->get3DLutPath());
  }
  /*-- 接続モニタをスプラッシュ画面にも表示 --*/
  if (!monitorNames.isEmpty())
  {
	  lastUpdateStr += QString("Monitor Name : ");
	  for (int mn = 0; mn < monitorNames.size(); mn++)
	  {
		  if (mn != 0)
			  lastUpdateStr += QString(", ");
		  lastUpdateStr += monitorNames.at(mn);
	  }
	  lastUpdateStr += QString("\n");
  }
#endif

	splash.showMessage(offsetStr + "Loading Plugins...", Qt::AlignCenter, Qt::white);
	a.processEvents();
	/* poll the thread ends: 
	 絶対に必要なわけではないが PluginLoader は中で setup ハンドラが常に固有のスレッドで呼ばれるよう main thread queue の blocking をしているので
	 processEvents を行う必要がある
   */
	while (!PluginLoader::load_entries("")) {
		a.processEvents();
	}

	splash.showMessage(offsetStr + "Creating main window ...", Qt::AlignCenter, Qt::white);
	a.processEvents();

	/*-- Layoutファイル名をMainWindowのctorに渡す --*/
	MainWindow w(argumentLayoutFileName);

	splash.showMessage(offsetStr + "Loading style sheet ...", Qt::AlignCenter, Qt::white);
	a.processEvents();

	// Carico lo styleSheet
	QString currentStyle = Preferences::instance()->getCurrentStyleSheet();
	a.setStyleSheet(currentStyle);

	TApp::instance()->setMainWindow(&w);
	w.setWindowTitle(applicationFullName);

	splash.showMessage(offsetStr + "Starting main window ...", Qt::AlignCenter, Qt::white);
	a.processEvents();

	TFilePath fp = ToonzFolder::getModuleFile("mainwindow.ini");
	QSettings settings(toQString(fp), QSettings::IniFormat);
	w.restoreGeometry(settings.value("MainWindowGeometry").toByteArray());

#ifndef MACOSX
	//Workaround for the maximized window case: Qt delivers two resize events, one in the normal geometry, before
	//maximizing (why!?), the second afterwards - all inside the following show() call. This makes troublesome for
	//the docking system to correctly restore the saved geometry. Fortunately, MainWindow::showEvent(..) gets called
	//just between the two, so we can disable the currentRoom layout right before showing and re-enable it after
	//the normal resize has happened.
	if (w.isMaximized())
		w.getCurrentRoom()->layout()->setEnabled(false);
#endif

	QRect splashGeometry = splash.geometry();
	splash.finish(&w);

	a.setQuitOnLastWindowClosed(false);
// a.connect(&a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()));
	w.checkForUpdates();

	w.show();

	//Show floating panels only after the main window has been shown
	w.startupFloatingPanels();

	CommandManager::instance()->execute(T_Hand);
	if (!loadScenePath.isEmpty()) {
		splash.showMessage(QString("Loading file '") + loadScenePath.getQString() + "'...", Qt::AlignCenter, Qt::white);

		loadScenePath = loadScenePath.withType("tnz");
		if (TFileStatus(loadScenePath).doesExist())
			IoCmd::loadScene(loadScenePath);
	}

	QFont *myFont;

	std::string family = EnvSoftwareCurrentFont;
	myFont = new QFont(QString(family.c_str()));

	myFont->setPixelSize(EnvSoftwareCurrentFontSize);
	/*-- フォントのBoldの指定 --*/
	std::string weight = EnvSoftwareCurrentFontWeight;
	if (strcmp(weight.c_str(), "Yes") == 0)
		myFont->setBold(true);
	else
		myFont->setBold(false);
	a.setFont(*myFont);

	QAction *action = CommandManager::instance()->getAction("MI_OpenTMessage");
	if (action)
		QObject::connect(TMessageRepository::instance(), SIGNAL(openMessageCenter()), action, SLOT(trigger()));

	QObject::connect(
		TUndoManager::manager(), SIGNAL(somethingChanged()),
		TApp::instance()->getCurrentScene(), SLOT(setDirtyFlag()));

#ifdef _WIN32
#ifndef x64
	//On 32-bit architecture, there could be cases in which initialization could alter the
	//FPU floating point control word. I've seen this happen when loading some AVI coded (VFAPI),
	//where 80-bit internal precision was used instead of the standard 64-bit (much faster and
	//sufficient - especially considering that x86 truncates to 64-bit representation anyway).
	//IN ANY CASE, revert to the original control word.
	//In the x64 case these precision changes simply should not take place up to _controlfp_s
	//documentation.
	_controlfp_s(0, fpWord, -1);
#endif
#endif

	a.installEventFilter(TApp::instance());

	int ret = a.exec();

	TUndoManager::manager()->reset();
	PreviewFxManager::instance()->reset();

#ifdef _WIN32
	if (consoleAttached) {
		::FreeConsole();
	}
#endif

	return ret;
}
Ejemplo n.º 20
0
void System::initializeGL()
{
	// We will destroy and rebuild it with the chosen OpenGL format in the end, but we need to have a valid current OpenGL
	// context for calling some of the methods below.
	//sharedWidget = new QGLWidget;
	//sharedWidget->makeCurrent();

	struct _GLVersion
	{
		unsigned int majorVer;
		unsigned int minorVer;
	};

	// Array of all the OpenGL versions that gtatools-gui might work with. We will try to build a context with the first entry
	// in this array, and if that fails, we go on trying the next one and so on.
	_GLVersion glVersionsToTry[] = {
			{ 4, 3 },
			{ 4, 2 },
			{ 4, 1 },
			{ 4, 0 },
			{ 3, 3 },
			{ 3, 2 },
			{ 3, 1 },
			{ 3, 0 }
	};

	QGLFormat::OpenGLVersionFlags vflags = QGLFormat::openGLVersionFlags();

	QGLFormat defaultGlFormat;
	defaultGlFormat.setDoubleBuffer(true);
	defaultGlFormat.setDirectRendering(true);
	defaultGlFormat.setDepth(true);
	defaultGlFormat.setAlpha(true);

	// NOTE: This line is VERY important. GLEW (tested with version 1.11) does not work with OpenGL 3.2+ Core Contexts,
	// apparently because it calls glGetString(GL_EXTENSIONS), which is deprecated and therefore returns an error on the
	// Core profile, which makes GLEW fail at basically everything.
	// This issue is described in http://www.opengl.org/wiki/OpenGL_Loading_Library. Quote:
	//
	// 		"GLEW has a problem with core contexts. It calls glGetString(GL_EXTENSIONS), which causes GL_INVALID_ENUM on GL
	//		 3.2+ core context as soon as glewInit() is called. It also doesn't fetch the function pointers. The solution
	//		 is for GLEW to use glGetStringi instead. The current version of GLEW is 1.10.0 but they still haven't corrected
	// 		 it. The only fix is to use glewExperimental for now"
	//
	// Instead of using glewExperimental, we simply use the compatibility profile (which is probably a good idea in general,
	// god knows how many "deprecated" (-> compatibility!) features I use in libgta that might fail with a core context...
	defaultGlFormat.setProfile(QGLFormat::CompatibilityProfile);

	int majorVer = 0;
	int minorVer = 0;
	bool foundMatching = false;

	for (size_t i = 0 ; i < sizeof(glVersionsToTry)/sizeof(_GLVersion) ; i++) {
		_GLVersion ver = glVersionsToTry[i];

		defaultGlFormat.setVersion(ver.majorVer, ver.minorVer);

		sharedWidget = new QGLWidget(defaultGlFormat);
		sharedWidget->makeCurrent();

		majorVer = sharedWidget->format().majorVersion();
		minorVer = sharedWidget->format().minorVersion();

		if (majorVer > ver.majorVer  ||  (majorVer == ver.majorVer  &&  minorVer >= ver.minorVer)) {
			foundMatching = true;
			break;
		} else {
			delete sharedWidget;
		}
	}

	if (!foundMatching) {
		fprintf(stderr, "ERROR: OpenGL >= 3.0 seems to be unsupported on the system. gtatools-gui will need at least OpenGL "
				"3.0 to work correctly!\n");
	}

	printf("Using OpenGL version %d.%d\n", majorVer, minorVer);

	QGLFormat::setDefaultFormat(defaultGlFormat);
}
Ejemplo n.º 21
0
int main(int argc,char* argv[]) {

    qRegisterMetaType<medDataIndex>("medDataIndex");

    // this needs to be done before creating the QApplication object, as per the
    // Qt doc, otherwise there are some edge cases where the style is not fully applied
    QApplication::setStyle("plastique");
    medApplication application(argc,argv);
    medSplashScreen splash(QPixmap(":/pixmaps/medInria-splash.png"));
    setlocale(LC_NUMERIC, "C");

    if (dtkApplicationArgumentsContain(&application, "-h") || dtkApplicationArgumentsContain(&application, "--help")) {
        qDebug() << "Usage: medInria [--fullscreen|--no-fullscreen] [--stereo] "
        #ifdef ACTIVATE_WALL_OPTION
        "[--wall] [--tracker=URL] "
        #endif
        "[--view] [files]]";
        return 1;
    }

    // Do not show the splash screen in debug builds because it hogs the
    // foreground, hiding all other windows. This makes debugging the startup
    // operations difficult.

    #if !defined(_DEBUG)
    bool show_splash = true;
    #else
    bool show_splash = false;
    #endif

    medSettingsManager* mnger = medSettingsManager::instance();

    QStringList posargs;
    for (int i=1;i<application.argc();++i) {
        const QString arg = application.argv()[i];
        if (arg.startsWith("--")) {
            bool valid_option = false;
            const QStringList options = (QStringList()
                    << "--fullscreen"
                    << "--no-fullscreen"
                    << "--wall" 
                    << "--tracker" 
                    << "--stereo"
                    << "--view");
            for (QStringList::const_iterator opt=options.constBegin();opt!=options.constEnd();++opt)
                if (arg.startsWith(*opt))
                    valid_option = true;
            if (!valid_option) { qDebug() << "Ignoring unknown option " << arg; }
            continue;
        }
        posargs.append(arg);
    }

    const bool DirectView = dtkApplicationArgumentsContain(&application,"--view") || posargs.size()!=0;
    int runningMedInria = 0;
    if (DirectView) {
        show_splash = false;
        for (QStringList::const_iterator i=posargs.constBegin();i!=posargs.constEnd();++i) {
            const QString& message = QString("/open ")+*i;
            runningMedInria = application.sendMessage(message);
        }
    } else {
        runningMedInria = application.sendMessage("");
    }

    if (runningMedInria)
        return 0;

    if (show_splash) {

        QObject::connect(medDatabaseController::instance().data(),
                         SIGNAL(copyMessage(QString,int,QColor)),
                         &splash,SLOT(showMessage(QString,int, QColor)));

        application.setMsgColor(Qt::white);
        application.setMsgAlignment(Qt::AlignLeft|Qt::AlignBottom);

        QObject::connect(medPluginManager::instance(),SIGNAL(loadError(const QString&)),
                         &application,SLOT(redirectMessageToSplash(const QString&)) );
        QObject::connect(medPluginManager::instance(),SIGNAL(loaded(QString)),
                         &application,SLOT(redirectMessageToSplash(QString)) );
        QObject::connect(&application,SIGNAL(showMessage(const QString&, int, const QColor&)),
                         &splash,SLOT(showMessage(const QString&, int, const QColor&)) );
        splash.show();
        splash.showMessage("Loading plugins...",Qt::AlignLeft|Qt::AlignBottom,Qt::white);
    }

    //  DATABASE INITIALISATION.
    //  First compare the current with the new data location

    QString currentLocation = medStorage::dataLocation();

    //  If the user configured a new location for the database in the settings editor, we'll need to move it

    QString newLocation = mnger->value("medDatabaseSettingsWidget", "new_database_location").toString();
    if (!newLocation.isEmpty()) {

        //  If the locations are different we need to move the db to the new location

        if (currentLocation.compare(newLocation)!=0) {
            if (!medDatabaseController::instance()->moveDatabase(newLocation)) {
                qDebug() << "Failed to move the database from " << currentLocation << " to " << newLocation;
                //  The new location is invalid so set it to zero
                newLocation = "";
            }
            mnger->setValue("medDatabaseSettingsWidget", "actual_database_location",newLocation);

            //  We need to reset the new Location to prevent doing it all the time

            mnger->setValue("medDatabaseSettingsWidget", "new_database_location","");
        }
    }
    // END OF DATABASE INITIALISATION

    medPluginManager::instance()->initialize();

    medMainWindow mainwindow;
    if (DirectView)
        mainwindow.setStartup(medMainWindow::WorkSpace,posargs);

    forceShow(mainwindow);

    bool fullScreen = medSettingsManager::instance()->value("startup", "fullscreen", false).toBool();

    const bool hasFullScreenArg   = application.arguments().contains("--fullscreen");
    const bool hasNoFullScreenArg = application.arguments().contains("--no-fullscreen");
    const bool hasWallArg         = application.arguments().contains("--wall");

    const int conflict = static_cast<int>(hasFullScreenArg)+static_cast<int>(hasNoFullScreenArg)+ static_cast<int>(hasWallArg);

    if (conflict>1)
        dtkWarn() << "Conflicting command line parameters between --fullscreen, --no-fullscreen and -wall. Ignoring.";
    else {
        if (hasWallArg) {
            mainwindow.setWallScreen(true);
            fullScreen = false;
        }

        if (hasFullScreenArg)
            fullScreen = true;

        if (hasNoFullScreenArg)
            fullScreen = false;
    }

    mainwindow.setFullScreen(fullScreen);


    if(application.arguments().contains("--stereo")) {
       QGLFormat format;
       format.setAlpha(true);
       format.setDoubleBuffer(true);
       format.setStereo(true);
       format.setDirectRendering(true);
       QGLFormat::setDefaultFormat(format);
    }

    if (show_splash)
        splash.finish(&mainwindow);

    if (medPluginManager::instance()->plugins().isEmpty()) {
        QMessageBox::warning(&mainwindow,
                             QObject::tr("No plugin loaded"),
                             QObject::tr("Warning : no plugin loaded successfully."));
    }

    //  Handle signals for multiple medInria instances.

    QObject::connect(&application,SIGNAL(messageReceived(const QString&)),
                     &mainwindow,SLOT(onNewInstance(const QString&)));

    application.setActivationWindow(&mainwindow);
    application.setMainWindow(&mainwindow);

    //  Start main loop.

    const int status = application.exec();

    medPluginManager::instance()->uninitialize();

    return status;
}
Ejemplo n.º 22
0
int main(int argc, char *argv[])
{
	QApplication app(argc, argv);
	int utfargc = argc;
	const char** utfargv = (const char**)argv;

#ifdef WZ_OS_MAC
	cocoaInit();
#endif

	debug_init();
	debug_register_callback( debug_callback_stderr, NULL, NULL, NULL );
#if defined(WZ_OS_WIN) && defined(DEBUG_INSANE)
	debug_register_callback( debug_callback_win32debug, NULL, NULL, NULL );
#endif // WZ_OS_WIN && DEBUG_INSANE

	// *****
	// NOTE: Try *NOT* to use debug() output routines without some other method of informing the user.  All this output is sent to /dev/nul at this point on some platforms!
	// *****
	if (!getUTF8CmdLine(&utfargc, &utfargv))
	{
		return EXIT_FAILURE;
	}
	QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));	// make Qt treat all C strings in Warzone as UTF-8

	setupExceptionHandler(utfargc, utfargv, version_getFormattedVersionString());

	/*** Initialize PhysicsFS ***/
	initialize_PhysicsFS(utfargv[0]);

	/*** Initialize translations ***/
	initI18n();

	// find early boot info
	if (!ParseCommandLineEarly(utfargc, utfargv))
	{
		return EXIT_FAILURE;
	}

	/* Initialize the write/config directory for PhysicsFS.
	 * This needs to be done __after__ the early commandline parsing,
	 * because the user might tell us to use an alternative configuration
	 * directory.
	 */
	initialize_ConfigDir();

	/*** Initialize directory structure ***/
	make_dir(ScreenDumpPath, "screenshots", NULL);
	make_dir(SaveGamePath, "savegames", NULL);
	make_dir(MultiCustomMapsPath, "maps", NULL); // MUST have this to prevent crashes when getting map
	PHYSFS_mkdir("music");
	PHYSFS_mkdir("logs");		// a place to hold our netplay, mingw crash reports & WZ logs
	make_dir(MultiPlayersPath, "multiplay", NULL);
	make_dir(MultiPlayersPath, "multiplay", "players");

	if (!customDebugfile)
	{
		// there was no custom debug file specified  (--debug-file=blah)
		// so we use our write directory to store our logs.
		time_t aclock;
		struct tm *newtime;
		char buf[PATH_MAX];

		time( &aclock );					// Get time in seconds
		newtime = localtime( &aclock );		// Convert time to struct
		// Note: We are using fopen(), and not physfs routines to open the file
		// log name is logs/(or \)WZlog-MMDD_HHMMSS.txt
		snprintf(buf, sizeof(buf), "%slogs%sWZlog-%02d%02d_%02d%02d%02d.txt", PHYSFS_getWriteDir(), PHYSFS_getDirSeparator(),
			newtime->tm_mon, newtime->tm_mday, newtime->tm_hour, newtime->tm_min, newtime->tm_sec );
		debug_register_callback( debug_callback_file, debug_callback_file_init, debug_callback_file_exit, buf );
	}

	// NOTE: it is now safe to use debug() calls to make sure output gets captured.
	check_Physfs();
	debug(LOG_WZ, "Warzone 2100 - %s", version_getFormattedVersionString());
	debug(LOG_WZ, "Using language: %s", getLanguage());
	debug(LOG_MEMORY, "sizeof: SIMPLE_OBJECT=%ld, BASE_OBJECT=%ld, DROID=%ld, STRUCTURE=%ld, FEATURE=%ld, PROJECTILE=%ld",
	      (long)sizeof(SIMPLE_OBJECT), (long)sizeof(BASE_OBJECT), (long)sizeof(DROID), (long)sizeof(STRUCTURE), (long)sizeof(FEATURE), (long)sizeof(PROJECTILE));


	/* Put in the writedir root */
	sstrcpy(KeyMapPath, "keymap.map");

	// initialise all the command line states
	war_SetDefaultStates();

	debug(LOG_MAIN, "initializing");

	PhysicsEngineHandler engine;	// register abstract physfs filesystem

	loadConfig();

	// parse the command line
	if (!ParseCommandLine(utfargc, utfargv))
	{
		return EXIT_FAILURE;
	}

	// Save new (commandline) settings
	saveConfig();

	// Find out where to find the data
	scanDataDirs();

	// This needs to be done after "scanDataDirs"
	// for the root cert from cacert.
	NETinit(true);

	// Must be run before OpenGL driver is properly initialized due to
	// strange conflicts - Per
	if (selfTest)
	{
		memset(enabled_debug, 0, sizeof(*enabled_debug) * LOG_LAST);
		fprintf(stdout, "Carrying out self-test:\n");
		playListTest();
		audioTest();
		soundTest();
	}

	// Now we check the mods to see if they exist or not (specified on the command line)
	// They are all capped at 100 mods max(see clparse.c)
	// FIX ME: I know this is a bit hackish, but better than nothing for now?
	{
		char *modname;
		char modtocheck[256];
		int i = 0;
		int result = 0;

		// check global mods
		for(i=0; i < 100; i++)
		{
			modname = global_mods[i];
			if (modname == NULL)
			{
				break;
			}
			ssprintf(modtocheck, "mods/global/%s", modname);
			result = PHYSFS_exists(modtocheck);
			result |= PHYSFS_isDirectory(modtocheck);
			if (!result)
			{
				debug(LOG_ERROR, "The (global) mod (%s) you have specified doesn't exist!", modname);
			}
			else
			{
				info("(global) mod (%s) is enabled", modname);
			}
		}
		// check campaign mods
		for(i=0; i < 100; i++)
		{
			modname = campaign_mods[i];
			if (modname == NULL)
			{
				break;
			}
			ssprintf(modtocheck, "mods/campaign/%s", modname);
			result = PHYSFS_exists(modtocheck);
			result |= PHYSFS_isDirectory(modtocheck);
			if (!result)
			{
				debug(LOG_ERROR, "The mod_ca (%s) you have specified doesn't exist!", modname);
			}
			else
			{
				info("mod_ca (%s) is enabled", modname);
			}
		}
		// check multiplay mods
		for(i=0; i < 100; i++)
		{
			modname = multiplay_mods[i];
			if (modname == NULL)
			{
				break;
			}
			ssprintf(modtocheck, "mods/multiplay/%s", modname);
			result = PHYSFS_exists(modtocheck);
			result |= PHYSFS_isDirectory(modtocheck);
			if (!result)
			{
				debug(LOG_ERROR, "The mod_mp (%s) you have specified doesn't exist!", modname);
			}
			else
			{
				info("mod_mp (%s) is enabled", modname);
			}
		}
	}

	debug(LOG_MAIN, "Qt initialization");
	QGL::setPreferredPaintEngine(QPaintEngine::OpenGL); // Workaround for incorrect text rendering on nany platforms.

	// Setting up OpenGL
	QGLFormat format;
	format.setDoubleBuffer(true);
	format.setAlpha(true);
	int w = pie_GetVideoBufferWidth();
	int h = pie_GetVideoBufferHeight();

	if (war_getFSAA())
	{
		format.setSampleBuffers(true);
		format.setSamples(war_getFSAA());
	}
	WzMainWindow mainwindow(QSize(w, h), format);
	mainwindow.setMinimumResolution(QSize(800, 600));
	if (!mainwindow.context()->isValid())
	{
		QMessageBox::critical(NULL, "Oops!", "Warzone2100 failed to create an OpenGL context. This probably means that your graphics drivers are out of date. Try updating them!");
		return EXIT_FAILURE;
	}

	screenWidth = w;
	screenHeight = h;
	if (war_getFullscreen())
	{
		mainwindow.resize(w,h);
		mainwindow.showFullScreen();
		if(w>mainwindow.width()) {
			w = mainwindow.width();
		}
		if(h>mainwindow.height()) {
			h = mainwindow.height();
		}
		pie_SetVideoBufferWidth(w);
		pie_SetVideoBufferHeight(h);
	}
	else
	{
		mainwindow.show();
		mainwindow.setMinimumSize(w, h);
		mainwindow.setMaximumSize(w, h);
	}

	mainwindow.setSwapInterval(war_GetVsync());
	war_SetVsync(mainwindow.swapInterval() > 0);

	mainwindow.setReadyToPaint();

	char buf[256];
	ssprintf(buf, "Video Mode %d x %d (%s)", w, h, war_getFullscreen() ? "fullscreen" : "window");
	addDumpInfo(buf);

	debug(LOG_MAIN, "Final initialization");
	if (!frameInitialise())
	{
		return EXIT_FAILURE;
	}
	war_SetWidth(pie_GetVideoBufferWidth());
	war_SetHeight(pie_GetVideoBufferHeight());

	pie_SetFogStatus(false);
	pie_ScreenFlip(CLEAR_BLACK);

	pal_Init();

	pie_LoadBackDrop(SCREEN_RANDOMBDROP);
	pie_SetFogStatus(false);
	pie_ScreenFlip(CLEAR_BLACK);

	if (!systemInitialise())
	{
		return EXIT_FAILURE;
	}

	//set all the pause states to false
	setAllPauseStates(false);

	/* Runtime unit testing */
	if (selfTest)
	{
		parseTest();
		levTest();
		mapTest();
		fprintf(stdout, "All tests PASSED!\n");
		exit(0);
	}

	// Copy this info to be used by the crash handler for the dump file
	ssprintf(buf,"Using language: %s", getLanguageName());
	addDumpInfo(buf);

	// Do the game mode specific initialisation.
	switch(GetGameMode())
	{
		case GS_TITLE_SCREEN:
			startTitleLoop();
			break;
		case GS_SAVEGAMELOAD:
			initSaveGameLoad();
			break;
		case GS_NORMAL:
			startGameLoop();
			break;
		default:
			debug(LOG_ERROR, "Weirdy game status, I'm afraid!!");
			break;
	}

#if defined(WZ_CC_MSVC) && defined(DEBUG)
	debug_MEMSTATS();
#endif
	debug(LOG_MAIN, "Entering main loop");
	app.exec();
	saveConfig();
	systemShutdown();
	debug(LOG_MAIN, "Completed shutting down Warzone 2100");
	return EXIT_SUCCESS;
}
Ejemplo n.º 23
0
int main(int argc, char **argv)
{
#ifdef CONSOLE_APPLICATION
    QApplication app(argc, argv, QApplication::Tty);
#else
    QApplication app(argc, argv);
#endif
#ifdef DO_QWS_DEBUGGING
    qt_show_painter_debug_output = false;
#endif

    DeviceType type = WidgetType;
    bool checkers_background = true;

    QImage::Format imageFormat = QImage::Format_ARGB32_Premultiplied;

    QLocale::setDefault(QLocale::c());

    QStringList files;

    bool interactive = false;
    bool printdlg = false;
    bool highres = false;
    bool show_cmp = false;
    int width = 800, height = 800;
    bool verboseMode = false;

#ifndef QT_NO_OPENGL
    QGLFormat f = QGLFormat::defaultFormat();
    f.setSampleBuffers(true);
    f.setStencil(true);
    f.setAlpha(true);
    f.setAlphaBufferSize(8);
    QGLFormat::setDefaultFormat(f);
#endif

    char *arg;
    for (int i=1; i<argc; ++i) {
        arg = argv[i];
        if (*arg == '-') {
            QString option = QString(arg + 1).toLower();
            if (option == "widget")
                type = WidgetType;
            else if (option == "bitmap")
                type = BitmapType;
            else if (option == "pixmap")
                type = PixmapType;
            else if (option == "image")
                type = ImageType;
            else if (option == "imageformat") {
                Q_ASSERT_X(i + 1 < argc, "main", "-imageformat must be followed by a value");
                QString format = QString(argv[++i]).toLower();

                imageFormat = QImage::Format_Invalid;
                static const unsigned int formatCount =
                    sizeof(imageFormats) / sizeof(imageFormats[0]);
                for (int ff = 0; ff < formatCount; ++ff) {
                    if (QLatin1String(imageFormats[ff].name) == format) {
                        imageFormat = imageFormats[ff].format;
                        break;
                    }
                }

                if (imageFormat == QImage::Format_Invalid) {
                    printf("Invalid image format.  Available formats are:\n");
                    for (int ff = 0; ff < formatCount; ++ff) 
                        printf("\t%s\n", imageFormats[ff].name);
                    return -1;
                }
            } else if (option == "imagemono")
                type = ImageMonoType;
            else if (option == "imagewidget")
                type = ImageWidgetType;
#ifndef QT_NO_OPENGL
            else if (option == "opengl")
                type = OpenGLType;
            else if (option == "pbuffer")
                type = OpenGLPBufferType;
#endif
#ifdef USE_CUSTOM_DEVICE
            else if (option == "customdevice")
                type = CustomDeviceType;
            else if (option == "customwidget")
                type = CustomWidgetType;
#endif
            else if (option == "pdf")
                type = PdfType;
            else if (option == "ps")
                type = PsType;
            else if (option == "picture")
                type = PictureType;
            else if (option == "printer")
                type = PrinterType;
            else if (option == "highres") {
                type = PrinterType;
                highres = true;
            } else if (option == "printdialog") {
                type = PrinterType;
                printdlg = true;
            }
            else if (option == "grab")
                type = GrabType;
            else if (option == "i")
                interactive = true;
            else if (option == "v")
                verboseMode = true;
            else if (option == "commands") {
                displayCommands();
                return 0;
            } else if (option == "w") {
                Q_ASSERT_X(i + 1 < argc, "main", "-w must be followed by a value");
                width = atoi(argv[++i]);
            } else if (option == "h") {
                Q_ASSERT_X(i + 1 < argc, "main", "-h must be followed by a value");
                height = atoi(argv[++i]);
            } else if (option == "cmp") {
                show_cmp = true;
            } else if (option == "bg-white") {
                checkers_background = false;
            }
        } else {
#if defined (Q_WS_WIN)
            QString input = QString::fromLocal8Bit(argv[i]);
            if (input.indexOf('*') >= 0) {
                QFileInfo info(input);
                QDir dir = info.dir();
                QFileInfoList infos = dir.entryInfoList(QStringList(info.fileName()));
                for (int ii=0; ii<infos.size(); ++ii)
                    files.append(infos.at(ii).absoluteFilePath());
            } else {
                files.append(input);
            }
#else
            files.append(QString(argv[i]));
#endif
        }
    }

    PaintCommands pcmd(QStringList(), 800, 800);
    pcmd.setVerboseMode(verboseMode);
    pcmd.setType(type);
    pcmd.setCheckersBackground(checkers_background);

    QWidget *activeWidget = 0;

    if (interactive) {
        runInteractive();
        if (!files.isEmpty())
            interactive_widget->load(files.at(0));
    } else if (files.isEmpty()) {
        printHelp();
        return 0;
    } else {
        for (int j=0; j<files.size(); ++j) {
            const QString &fileName = files.at(j);
            QStringList content;

            QFile file(fileName);
            QFileInfo fileinfo(file);
            if (file.open(QIODevice::ReadOnly)) {
                QTextStream textFile(&file);
                QString script = textFile.readAll();
                content = script.split("\n", QString::SkipEmptyParts);
            } else {
                printf("failed to read file: '%s'\n", qPrintable(fileName));
                continue;
            }
            pcmd.setContents(content);

            if (show_cmp) {
                QString pmFile = QString(files.at(j)).replace(".qps", "_qps") + ".png";
                qDebug() << pmFile << QFileInfo(pmFile).exists();
                QPixmap pixmap(pmFile);
                if (!pixmap.isNull()) {
                    QLabel *label = createLabel();
                    label->setWindowTitle("VERIFY: " + pmFile);
                    label->setPixmap(pixmap);
                    label->show();
                }
            }

            switch (type) {

            case WidgetType:
            {
                OnScreenWidget<QWidget> *qWidget =
                    new OnScreenWidget<QWidget>;
                qWidget->setVerboseMode(verboseMode);
                qWidget->setType(type);
                qWidget->setCheckersBackground(checkers_background);
                qWidget->m_filename = files.at(j);
                qWidget->setWindowTitle(fileinfo.filePath());
                qWidget->m_commands = content;
                qWidget->resize(width, height);
                qWidget->show();
                activeWidget = qWidget;
                break;
            }

            case ImageWidgetType:
            {
                OnScreenWidget<QWidget> *qWidget = new OnScreenWidget<QWidget>;
                qWidget->setVerboseMode(verboseMode);
                qWidget->setType(type);
                qWidget->setCheckersBackground(checkers_background);
                qWidget->m_filename = files.at(j);
                qWidget->setWindowTitle(fileinfo.filePath());
                qWidget->m_commands = content;
                qWidget->resize(width, height);
                qWidget->show();
                activeWidget = qWidget;
                break;

            }
#ifndef QT_NO_OPENGL
            case OpenGLPBufferType:
            {
                QGLPixelBuffer pbuffer(QSize(width, height));
                QPainter pt(&pbuffer);
                pcmd.setPainter(&pt);
                pcmd.setFilePath(fileinfo.absolutePath());
                pcmd.runCommands();
                pt.end();

                QImage image = pbuffer.toImage();

                QLabel *label = createLabel();
                label->setPixmap(QPixmap::fromImage(image));
                label->resize(label->sizeHint());
                label->show();
                activeWidget = label;
                break;
            }
            case OpenGLType:
            {
                OnScreenWidget<QGLWidget> *qGLWidget = new OnScreenWidget<QGLWidget>;
                qGLWidget->setVerboseMode(verboseMode);
                qGLWidget->setType(type);
                qGLWidget->setCheckersBackground(checkers_background);
                qGLWidget->m_filename = files.at(j);
                qGLWidget->setWindowTitle(fileinfo.filePath());
                qGLWidget->m_commands = content;
                qGLWidget->resize(width, height);
                qGLWidget->show();
                activeWidget = qGLWidget;
                break;
            }
#else
            case OpenGLType:
                printf("OpenGL type not supported in this Qt build\n");
                break;
#endif
#ifdef USE_CUSTOM_DEVICE
            case CustomDeviceType:
            {
                CustomPaintDevice custom(width, height);
                QPainter pt;
                pt.begin(&custom);
                pcmd.setPainter(&pt);
                pcmd.setFilePath(fileinfo.absolutePath());
                pcmd.runCommands();
                pt.end();
                QImage *img = custom.image();
                if (img) {
                    QLabel *label = createLabel();
                    label->setPixmap(QPixmap::fromImage(*img));
                    label->resize(label->sizeHint());
                    label->show();
                    activeWidget = label;
                    img->save("custom_output_pixmap.png", "PNG");
                } else {
                    custom.save("custom_output_pixmap.png", "PNG");
                }
                break;
            }
            case CustomWidgetType:
            {
                OnScreenWidget<CustomWidget> *cWidget = new OnScreenWidget<CustomWidget>;
                cWidget->setVerboseMode(verboseMode);
                cWidget->setType(type);
                cWidget->setCheckersBackground(checkers_background);
                cWidget->m_filename = files.at(j);
                cWidget->setWindowTitle(fileinfo.filePath());
                cWidget->m_commands = content;
                cWidget->resize(width, height);
                cWidget->show();
                activeWidget = cWidget;
                break;
            }
#endif
            case PixmapType:
            {
                QPixmap pixmap(width, height);
                pixmap.fill(Qt::white);
                QPainter pt(&pixmap);
                pcmd.setPainter(&pt);
                pcmd.setFilePath(fileinfo.absolutePath());
                pcmd.runCommands();
                pt.end();
                pixmap.save("output_pixmap.png", "PNG");
                break;
            }

            case BitmapType:
            {
                QBitmap bitmap(width, height);
                QPainter pt(&bitmap);
                pcmd.setPainter(&pt);
                pcmd.setFilePath(fileinfo.absolutePath());
                pcmd.runCommands();
                pt.end();
                bitmap.save("output_bitmap.png", "PNG");

                QLabel *label = createLabel();
                label->setPixmap(bitmap);
                label->resize(label->sizeHint());
                label->show();
                activeWidget = label;
                break;
            }

            case ImageMonoType:
            case ImageType:
            {
                qDebug() << "Creating image";
                QImage image(width, height, type == ImageMonoType
                             ? QImage::Format_MonoLSB
                             : imageFormat);
                image.fill(0);
                QPainter pt(&image);
                pcmd.setPainter(&pt);
                pcmd.setFilePath(fileinfo.absolutePath());
                pcmd.runCommands();
                pt.end();
                image.convertToFormat(QImage::Format_ARGB32).save("output_image.png", "PNG");
#ifndef CONSOLE_APPLICATION
                QLabel *label = createLabel();
                label->setPixmap(QPixmap::fromImage(image));
                label->resize(label->sizeHint());
                label->show();
                activeWidget = label;
#endif
                break;
            }

            case PictureType:
            {
                QPicture pic;
                QPainter pt(&pic);
                pcmd.setPainter(&pt);
                pcmd.setFilePath(fileinfo.absolutePath());
                pcmd.runCommands();
                pt.end();

                QImage image(width, height, QImage::Format_ARGB32_Premultiplied);
                image.fill(0);
                pt.begin(&image);
                pt.drawPicture(0, 0, pic);
                pt.end();
                QLabel *label = createLabel();
                label->setWindowTitle(fileinfo.absolutePath());
                label->setPixmap(QPixmap::fromImage(image));
                label->resize(label->sizeHint());
                label->show();
                activeWidget = label;
                break;
            }

            case PrinterType:
            {
                PaintCommands pcmd(QStringList(), 800, 800);
                pcmd.setVerboseMode(verboseMode);
                pcmd.setType(type);
                pcmd.setCheckersBackground(checkers_background);
                pcmd.setContents(content);
                QString file = QString(files.at(j)).replace(".", "_") + ".ps";

                QPrinter p(highres ? QPrinter::HighResolution : QPrinter::ScreenResolution);
                if (printdlg) {
                    QPrintDialog printDialog(&p, 0);
                    if (printDialog.exec() != QDialog::Accepted)
                        break;
                } else {
                    p.setOutputFileName(file);
                }

                QPainter pt(&p);
                pcmd.setPainter(&pt);
                pcmd.setFilePath(fileinfo.absolutePath());
                pcmd.runCommands();
                pt.end();

                if (!printdlg) {
                    printf("wrote file: %s\n", qPrintable(file));
                }

                Q_ASSERT(!p.paintingActive());
                break;
            }
            case PsType:
            case PdfType:
            {
                PaintCommands pcmd(QStringList(), 800, 800);
                pcmd.setVerboseMode(verboseMode);
                pcmd.setType(type);
                pcmd.setCheckersBackground(checkers_background);
                pcmd.setContents(content);
                bool ps = type == PsType;
                QPrinter p(highres ? QPrinter::HighResolution : QPrinter::ScreenResolution);
                QFileInfo input(files.at(j));
                QString file = QString("%1_%2.%3")
                               .arg(input.baseName())
                               .arg(input.suffix())
                               .arg(ps ? "ps" : "pdf");
                p.setOutputFormat(ps ? QPrinter::PdfFormat : QPrinter::PostScriptFormat);
                p.setOutputFileName(file);
                p.setPageSize(QPrinter::A4);
                QPainter pt(&p);
                pcmd.setPainter(&pt);
                pcmd.setFilePath(fileinfo.absolutePath());
                pcmd.runCommands();
                pt.end();

                printf("write file: %s\n", qPrintable(file));
                break;
            }
            case GrabType:
            {
                QImage image(width, height, QImage::Format_ARGB32_Premultiplied);
                image.fill(QColor(Qt::white).rgb());
                QPainter pt(&image);
                pcmd.setPainter(&pt);
                pcmd.setFilePath(fileinfo.absolutePath());
                pcmd.runCommands();
                pt.end();
                QImage image1(width, height, QImage::Format_RGB32);
                image1.fill(QColor(Qt::white).rgb());
                QPainter pt1(&image1);
                pt1.drawImage(QPointF(0, 0), image);
                pt1.end();

                QString filename = QString(files.at(j)).replace(".qps", "_qps") + ".png";
                image1.save(filename, "PNG");
                printf("%s grabbed to %s\n", qPrintable(files.at(j)), qPrintable(filename));
                break;
            }

            default:
                break;
            }
        }
    }
#ifndef CONSOLE_APPLICATION
    if (activeWidget || interactive) {
        QObject::connect(&app, SIGNAL(lastWindowClosed()), &app, SLOT(quit()));
        app.exec();
    }

    delete activeWidget;
#endif
    return 0;
}