Esempio n. 1
0
	exit_t main()
	{
		const char *ca_eq =
			"v:=v+(-4*(v>=4))"
			"+(a[-1,0]>=4)+(a[0,-1]>=4)+(a[1,0]>=4)+(a[0,1]>=4)",
			*input_eq = "v:=v+1";

		switch(argc)
		{
			case 3:
				input_eq = argv[2];
			case 2:
				ca_eq = argv[1];
			case 1:
				break;
			default:
				exit_usage();
		}

		std::cerr << "Waiting for a grid as input...\n"
			"If no GUI shows up, you might want to try:\n"
			"  core/create 10 10 0 | gui_qt/gui\n" << std::endl;

		QApplication app(argc, argv);
		MainWindow mainwindow(ca_eq, input_eq);
		mainwindow.show();

		return success(app.exec() == 0);
	}
Esempio n. 2
0
int main(int argc, char *argv[])
{

#if !defined(WIN32)
  //for some reason this does not work with dynamic linking on windows
  //instead we solve the problem by adding a handmade header for the cxResources.qrc file
  Q_INIT_RESOURCE(cxResources);
#endif

  cx::Application app(argc, argv);
  app.setOrganizationName("CustusX");
  app.setOrganizationDomain("www.custusx.org");
  app.setApplicationName("CustusX");
  app.setWindowIcon(QIcon(":/icons/CustusX/CustusX.png"));
  app.setAttribute(Qt::AA_DontShowIconsInMenus, false);

  cx::ApplicationComponentPtr mainwindow(new cx::MainWindowApplicationComponent<cx::MainWindow>());
  cx::LogicManager::initialize(mainwindow);

  int retVal = app.exec();

  cx::LogicManager::shutdown(); // shutdown all global resources, _after_ gui is deleted.

  return retVal;
}
Esempio n. 3
0
int main(int argc, char **argv)
{
	QApplication app(argc, argv);
	MainWindow mainwindow(&app);

	int result = app.exec();
	return result;
}
Esempio n. 4
0
//==============================================================================
/// MAIN
//==============================================================================
int main(int argc, char *argv[])
{
    bool arduinoOnly = false;
#ifdef ARDUINO_ONLY
    arduinoOnly = true;
#endif

#ifdef Q_OS_UNIX
  QApplication::setStyle("cleanlooks");
#endif
  QApplication app( argc, argv);

  QTranslator qt_translator;
  if ( qt_translator.load( ":tr/qt_ru.qm" ))
  { QApplication::installTranslator(&qt_translator);
  }

  Utils::AppInfo::setTitle("MKStudio");

  Console::setMessageTypes( Console::AllTypes );
  Console::setMessageTypes( Console::ModbusPacket, false );

  InitDialog initdialog(0, arduinoOnly);
  if(!initdialog.portsFound())
  { QMessageBox::critical(0, Utils::AppInfo::title(),
                  "В системе не обнаружено последовательных портов ввода-вывода.");
    return 0;
  }
  if( initdialog.exec() != QDialog::Accepted )
      return 0;

  AbstractSerialPortPtr port = initdialog.port();
  if( !port->open() )
  { QMessageBox::critical(0, Utils::AppInfo::title(),
                             "Ошибка открытия порта.\n\n"
                             "Возможно, что порт используется\n"
                             "другим приложением." );
    return 0;
  }

  QString portname = port->name();
  QString portspeed = QString::number(port->speed());
  if(portspeed=="0" ) portspeed.clear();

  Utils::AppInfo::setTitle((QString("%1 %2 - MKStudio")
                      + (arduinoOnly ? "-arduino" : "")).arg(portname).arg(portspeed));

  MBMasterXMLPtr mbmaster(new MBMasterXML);
  mbmaster->setTransport( port );
  mbmaster->setMaximumPacketLength( initdialog.sb_max_len->value() );
  mbmaster->setTransactionDelay( initdialog.sb_tr_delay->value() );
  mbmaster->setCycleTime( initdialog.sb_cycle_time->value() );

  MainWindow mainwindow(mbmaster, arduinoOnly);
  mainwindow.show();

  return QApplication::exec();
}
Esempio n. 5
0
void
qt_tm_widget_rep::set_full_screen(bool flag) {
  full_screen = flag;
  QWidget *win = mainwindow()->window();  
  if (win) {
    if (flag ) {
#ifdef UNIFIED_TOOLBAR
      if (use_unified_toolbar) {
        //HACK: we disable unified toolbar since otherwise
        //  the application will crash when we return to normal mode
        // (bug in Qt? present at least with 4.7.1)
        mainwindow()->setUnifiedTitleAndToolBarOnMac(false);
        mainwindow()->centralWidget()->layout()->setContentsMargins(0,0,0,0);
      }
#endif
//      mainwindow()->window()->setContentsMargins(0,0,0,0);
      //win->showFullScreen();
       win->setWindowState(win->windowState() ^ Qt::WindowFullScreen);
    } else {
      bool cache = visibility[0];
      visibility[0] = false;
      update_visibility();
//      win->showNormal();
      win->setWindowState(win->windowState() ^ Qt::WindowFullScreen);

      visibility[0] = cache;
      update_visibility();
#ifdef UNIFIED_TOOLBAR
      if (use_unified_toolbar) {
        mainwindow()->centralWidget()->layout()->setContentsMargins (0,1,0,0);
        //HACK: we reenable unified toolbar (see above HACK) 
        //  the application will crash when we return to normal mode
        mainwindow()->setUnifiedTitleAndToolBarOnMac(true);
      }
#endif
    }
  }
  
  scrollarea()->setHorizontalScrollBarPolicy(flag ? Qt::ScrollBarAlwaysOff : Qt::ScrollBarAsNeeded);
  scrollarea()->setVerticalScrollBarPolicy(flag ? Qt::ScrollBarAlwaysOff : Qt::ScrollBarAsNeeded);
}
Esempio n. 6
0
File: mapdraw2.c Progetto: rj76/kq
int main (int argc, char *argv[])
{
   setlocale (LC_ALL, "");
   bindtextdomain (PACKAGE, KQ_LOCALE);
   textdomain (PACKAGE);
   
   chdir ("maps");
   install_allegro (SYSTEM_NONE, &errno, atexit);
   if (!startup ()) {
      printf ("wtf?\n");
      return 1;
   }
   mainwindow (&argc, &argv);
   cleanup ();
   allegro_exit ();
   return 0;
}
Esempio n. 7
0
void TestHelpFixture::setupHelpBrowserInsideMainWindow()
{
	cx::DataLocations::setTestMode();

	cx::ApplicationComponentPtr mainwindow(new cx::MainWindowApplicationComponent<cx::MainWindow>());
	cx::LogicManager::initialize(mainwindow);

	mw = dynamic_cast<cx::MainWindowApplicationComponent<cx::MainWindow>*>(mainwindow.get())->mMainWindow;
	REQUIRE(mw!=NULL);

	helpWidget = mw->findChild<cx::HelpWidget*>("help_widget");
	REQUIRE(helpWidget!=NULL);
	helpWidget->forcePrePaint(); // explicitly populate helpWidget

	browser = helpWidget->findChild<QTextBrowser*>();
	REQUIRE(browser!=NULL);
}
Esempio n. 8
0
void
qt_tm_widget_rep::install_main_menu () {
  main_menu_widget = waiting_main_menu_widget;
  QMenu* src = main_menu_widget->get_qmenu();
  if (!src) return;

    // REMARK: We do not want the menubar shared across windows as suggested
    // in http://doc.qt.nokia.com/4.7/qmainwindow.html#menuBar
    // e.g. :
    //
    //     QMenuBar *dest = new QMenuBar(0);
    //     mainwindow()->setMenuBar(dest);
    //
    // as the default behavior on MacOS. The main reason is that in TeXmacs
    // different windows can have different main menus so that it is indeed
    // appropriate to change the main menu as the window focus changes.
    // So we kindly ask to each window to give us its own menu and we install
    // there our actions.
    // So we do:
  
  QMenuBar* dest = mainwindow()->menuBar();
  
    // and everything is fine.
  
    // Also please note that we have to do the replacement and not simply
    // install the menu returned by get_qmenu() since the main menu there
    // could contain some default items appropriate for the given OS (like the
    // service menu on MacOS) which are not present in our menu widget.
    // UPDATE: But replaceActions() *does remove* all actions (!?)
    // It looks more like the reason is that we have to "flatten out" the first
    // level of the QMenu returned... ?
  
  replaceActions (dest, src);
  QList<QAction*> list = dest->actions();
  for (int i = 0; i < list.count(); i++) {
    QAction* a = list[i];
    if (a->menu()) {
      QObject::connect (a->menu(),         SIGNAL (aboutToShow()),
                        the_gui->gui_helper, SLOT (aboutToShowMainMenu()));
      QObject::connect (a->menu(),         SIGNAL (aboutToHide()),
                        the_gui->gui_helper, SLOT (aboutToHideMainMenu()));
    }
  }

}
Esempio n. 9
0
int main (int argc, char *argv[])
{
	QApplication app(argc, argv);
#if 0
	if(argc != 2) 
	{
		qDebug("Usage:example [uifile_name]");
		exit(0);
	}

	QString uifile = argv[1];
	MainWindow mainwindow(uifile);
	mainwindow.show();
#endif
	chdir("/usr/local/opi/bin");
	QWidget *pwidget = new QWidget;
	KSTARMON_UI::KSTARMon form(pwidget);
	return app.exec();
}
Esempio n. 10
0
int main(int argc, char** argv )
{
  const char *file_i  = cimg_option("-image", (char*)0, "Input image");
  const char *file_m  = cimg_option("-mask",  (char*)0, "Mask image");
  const char *file_o  = cimg_option("-out",   (char*)0, "Output mask image");

  if (file_i ==(char*)0) throw CImgException("Please specify input image path");

  //Open input image
  CImg<unsigned char> image(file_i);

  //Open input mask or if not specified create an empty
  CImg<unsigned char> m_image;
  if (file_m!=(char*)0) {
    m_image.assign(file_m);
  } else {
    m_image.assign(image.width(), image.height(), 1,3,255);
  }

  //Create canvas and set background image
  MyImageCanvas<unsigned char> maincanvas(image);
  maincanvas.setImage(image);
  maincanvas.setMask(m_image, blue);
  maincanvas.redraw();

  //Set algorithm
  ThresholdAlg<unsigned char> thresholdAlg;
  thresholdAlg.setParam1(128);
  maincanvas.setProcessingAlgorithm(&thresholdAlg,128);
  
  //Create application window
  MyImageWindow<unsigned char> mainwindow(&maincanvas,"Image viewer (type F1 for help)");
  mainwindow.show();

  if ( file_o != (char*)0 ) {
    CImg<unsigned char> maskresult = maincanvas.getMask();
    maskresult.normalize(0,255).save(file_o);
  }

return 0;
}
Esempio n. 11
0
void
qt_tm_widget_rep::install_main_menu () {
  if (main_menu_widget == waiting_main_menu_widget) return;
  main_menu_widget = waiting_main_menu_widget;
  QList<QAction*>* src = main_menu_widget->get_qactionlist();
  if (!src) return;
  QMenuBar* dest = mainwindow()->menuBar();
  dest->clear();
  for (int i = 0; i < src->count(); i++) {
    QAction* a = (*src)[i];
    if (a->menu()) {
      //TRICK: Mac native QMenuBar accepts only menus which are already populated
      // this will cause a problem for us, since menus are lazy and populated only after triggering
      // this is the reason we add a dummy action before inserting the menu
      a->menu()->addAction("native menubar trick");
      dest->addAction(a->menu()->menuAction());
      QObject::connect (a->menu(),         SIGNAL (aboutToShow()),
                        the_gui->gui_helper, SLOT (aboutToShowMainMenu()));
      QObject::connect (a->menu(),         SIGNAL (aboutToHide()),
                        the_gui->gui_helper, SLOT (aboutToHideMainMenu()));
    }
  }
}
Esempio n. 12
0
	int main(const std::vector<std::string> &args)
	{
		std::string resource_filename("../../Resources/GUIThemeAero/resources.xml");
		std::string theme_filename("../../Resources/GUIThemeAero/theme.css");
		std::string local_theme_filename("theme.css");
		if (!clan::FileHelp::file_exists(resource_filename))
		{
			resource_filename = "../../Resources/GUIThemeBasic/resources.xml";
			std::string theme_filename("../../Resources/GUIThemeBasic/theme.css");
		}

		clan::GUIWindowManagerSystem wm;

		clan::GUIManager gui;
		gui.set_window_manager(wm);
		gui.add_resources("resources.xml");
		gui.add_resources(resource_filename);
		gui.add_theme(theme_filename);
		gui.add_theme(local_theme_filename);

		MainWindow mainwindow(&gui);
		gui.exec();
		return 0;
	}
Esempio n. 13
0
int main(int argc, char*argv[]) { 
  bool timing_mode = 0;
  int i = 1;
  QString scenefile = "scenario.xml";
  Ped::IMPLEMENTATION implementation = Ped::SEQ;
  int number_of_threads = 4;

  // Argument handling
  while(i < argc)
  {
    if(argv[i][0] == '-' && argv[i][1] == '-')
    {
      if(strcmp(&argv[i][2],"timing-mode") == 0)
      {
	cout << "Timing mode on\n";
	timing_mode = true;
      }
      else if (strcmp(&argv[i][2],"threads") == 0)
      {
	implementation = Ped::PTHREAD;
      }
      else if (strcmp(&argv[i][2],"omp") == 0)
      {
	implementation = Ped::OMP;
      }
      else if(strcmp(&argv[i][2],"help") == 0)
      {
	cout << "Usage: " << argv[0] << " [--help] [--timing-mode] [--threads |#threads]] [--omp] [scenario]" << endl;
	return 0;
      }
      else
      {
	cerr << "Unrecognized command: \"" << argv[i] << "\". Ignoring ..." << endl;
      }
    }
    else // Assume it is a path to scenefile or the number of threads to be used
    {
      int old_number_of_threads = number_of_threads;
      number_of_threads = atoi(argv[i]);
      if (number_of_threads == 0) // The argument was not a number
      {
	scenefile = argv[i];
	number_of_threads = old_number_of_threads;
      }
    }
    
    i+=1;
  }

  // Reading the scenario file and setting up the crowd simulation model
  Ped::Model model;
  ParseScenario parser(scenefile);
  model.setup(parser.getAgents(), implementation, number_of_threads);

  // GUI related set ups
  QApplication app(argc, argv);
  MainWindow mainwindow(model);

  // Default number of steps to simulate
  const int maxNumberOfStepsToSimulate = 10000;
  PedSimulation *simulation = new PedSimulation(model, mainwindow);

  cout << "Demo setup complete, running ..." << endl;
  int retval = 0;
  // Timing of simulation
  std::chrono::time_point<std::chrono::system_clock> start,stop;
  start = std::chrono::system_clock::now();

  if(timing_mode)
  {
    // Simulation mode to use when profiling (without any GUI)
    simulation->runSimulationWithoutQt(maxNumberOfStepsToSimulate);
  }
  else
  {
    // Simulation mode to use when visualizing
    mainwindow.show();
    simulation->runSimulationWithQt(maxNumberOfStepsToSimulate);
    retval = app.exec();
  }

  // End timing
  stop = std::chrono::system_clock::now();
  std::chrono::duration<double> elapsed_seconds = stop-start;
  cout << "Time: " << elapsed_seconds.count() << " seconds." << endl;

  cout << "Done" << endl;
  delete (simulation);
  return retval;
}
Esempio n. 14
0
qt_tm_widget_rep::qt_tm_widget_rep(int mask, command _quit)
 : qt_window_widget_rep (new QTMWindow (0), "popup", _quit), helper (this),
   prompt (NULL), full_screen (false)
{
  type = texmacs_widget;

  main_widget = concrete (::glue_widget (true, true, 1, 1));
  
  // decode mask
  visibility[0] = (mask & 1)   == 1;   // header
  visibility[1] = (mask & 2)   == 2;   // main
  visibility[2] = (mask & 4)   == 4;   // mode
  visibility[3] = (mask & 8)   == 8;   // focus
  visibility[4] = (mask & 16)  == 16;  // user
  visibility[5] = (mask & 32)  == 32;  // footer
  visibility[6] = (mask & 64)  == 64;  // side tools #0
  visibility[7] = (mask & 128) == 128; // bottom tools

  // general setup for main window
  
  QMainWindow* mw= mainwindow ();
  mw->setStyle (qtmstyle ());
  mw->menuBar()->setStyle (qtmstyle ());
  
  // there is a bug in the early implementation of toolbars in Qt 4.6
  // which has been fixed in 4.6.2 (at least)
  // this is why we change dimension of icons
  
#if (defined(Q_WS_MAC)&&(QT_VERSION>=QT_VERSION_CHECK(4,6,0))&&(QT_VERSION<QT_VERSION_CHECK(4,6,2)))
  mw->setIconSize (QSize (22, 30));  
#else
  mw->setIconSize (QSize (17, 17));
#endif
  mw->setFocusPolicy (Qt::NoFocus);
  
  // status bar
  
  QStatusBar* bar= new QStatusBar(mw);
  leftLabel= new QLabel (qt_translate ("Welcome to TeXmacs"), mw);
  rightLabel= new QLabel (qt_translate ("Booting"), mw);
  leftLabel->setFrameStyle (QFrame::NoFrame);
  rightLabel->setFrameStyle (QFrame::NoFrame);
  bar->addWidget (leftLabel, 1);
  bar->addPermanentWidget (rightLabel);
  bar->setStyle (qtmstyle ());
  
  // NOTE (mg): the following setMinimumWidth command disable automatic 
  // enlarging of the status bar and consequently of the main window due to 
  // long messages in the left label. I found this strange solution here
  // http://www.archivum.info/[email protected]/2007-05/01453/Re:-QStatusBar-size.html
  // The solution if due to Martin Petricek. He adds:
  //    The docs says: If minimumSize() is set, the minimum size hint will be ignored.
  //    Probably the minimum size hint was size of the lengthy message and
  //    internal layout was enlarging the satusbar and the main window
  //    Maybe the notice about QLayout that is at minimumSizeHint should be
  //    also at minimumSize, didn't notice it first time and spend lot of time
  //    trying to figure this out :)
  
  bar->setMinimumWidth (2);
  mw->setStatusBar (bar);
 
  // toolbars
  
  mainToolBar   = new QToolBar ("main toolbar", mw);
  modeToolBar   = new QToolBar ("mode toolbar", mw);
  focusToolBar  = new QToolBar ("focus toolbar", mw);
  userToolBar   = new QToolBar ("user toolbar", mw);
  
  bottomTools   = new QDockWidget ("bottom tools", mw);
  sideTools     = new QDockWidget ("side tools", 0);
    // HACK: Wrap the dock in a "fake" window widget (last parameter = true) to
    // have clicks report the right position.
  static int cnt=0;
  string dock_name = "dock:" * as_string(cnt++);
  dock_window_widget = tm_new<qt_window_widget_rep> (sideTools, dock_name,
                                                     command(), true);
  
  mainToolBar->setStyle (qtmstyle ());
  modeToolBar->setStyle (qtmstyle ());
  focusToolBar->setStyle (qtmstyle ());
  userToolBar->setStyle (qtmstyle ());
  sideTools->setStyle (qtmstyle ());
  bottomTools->setStyle (qtmstyle ());
  
  {
    // set proper sizes for icons
    QImage *pxm = xpm_image ("tm_new.xpm");
    QSize sz = (pxm ? pxm->size() : QSize (24, 24));
    tweak_iconbar_size (sz);
    mainToolBar->setIconSize (sz);
    pxm = xpm_image ("tm_section.xpm");
    sz = (pxm ? pxm->size() : QSize (20, 20));
    tweak_iconbar_size (sz);
    modeToolBar->setIconSize (sz);
    pxm = xpm_image ("tm_add.xpm");
    sz = (pxm ? pxm->size() : QSize (16, 16));
    tweak_iconbar_size (sz);
    focusToolBar->setIconSize (sz);
  }  
  
  QWidget *cw= new QWidget();
  cw->setObjectName("central widget");  // this is important for styling toolbars.
  
    // The main layout
  
  QVBoxLayout *bl = new QVBoxLayout (cw);
  bl->setContentsMargins (0, 1, 0, 0);
  bl->setSpacing (0);
  cw->setLayout (bl);
  QWidget* q = main_widget->as_qwidget(); // force creation of QWidget
  q->setParent (qwid); // q->layout()->removeWidget(q) will reset the parent to this
  bl->addWidget (q);
  
  mw->setCentralWidget (cw);

#ifdef UNIFIED_TOOLBAR

  mw->setUnifiedTitleAndToolBarOnMac(true);
    
  //WARNING: dumbToolBar is the toolbar installed on the top area of the
  //main widget which is  then unified in the title bar. 
  //to overcome some limitations of the unified toolbar implementation we
  //install the real toolbars as widgets in this toolbar.
  
  dumbToolBar = mw->addToolBar("dumb toolbar");
  dumbToolBar->setMinimumHeight(30);

  //these are the actions related to the various toolbars to be installed in
  //the dumb toolbar.
  
  mainToolBarAction = dumbToolBar->addWidget(mainToolBar);
  modeToolBarAction = NULL;

  
  // A ruler
  rulerWidget = new QWidget(cw);
  rulerWidget->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Fixed);
  rulerWidget->setMinimumHeight(1);
  rulerWidget->setBackgroundRole(QPalette::Mid);
  // FIXME: how to use 112 (active) and 146 (passive)
  rulerWidget->setVisible(false);
  rulerWidget->setAutoFillBackground(true);
  // rulerWidget = new QLabel("pippo", cw);
  
    // A second ruler (this one always visible) to separate from the canvas.
  QWidget* r2 = new QWidget(mw);
  r2->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Fixed);
  r2->setMinimumHeight(1);
  r2->setBackgroundRole(QPalette::Mid);
  r2->setVisible(true);
  r2->setAutoFillBackground(true);

  bl->insertWidget(0, modeToolBar);
  bl->insertWidget(1, rulerWidget);
  bl->insertWidget(2, focusToolBar);
  bl->insertWidget(3, userToolBar);
  bl->insertWidget(5, r2);

    //mw->setContentsMargins (-2, -2, -2, -2);  // Why this?
  bar->setContentsMargins (0, 1, 0, 1);

#else
  mw->addToolBar (mainToolBar);
  mw->addToolBarBreak ();
  mw->addToolBar (modeToolBar);
  mw->addToolBarBreak ();
  mw->addToolBar (focusToolBar);
  mw->addToolBarBreak ();
  mw->addToolBar (userToolBar);
  mw->addToolBarBreak ();
#endif

  sideTools->setAllowedAreas (Qt::AllDockWidgetAreas);
  sideTools->setFeatures (QDockWidget::DockWidgetMovable |
                         QDockWidget::DockWidgetFloatable);
  sideTools->setFloating (false);
  mw->addDockWidget (Qt::RightDockWidgetArea, sideTools);

  bottomTools->setAllowedAreas (Qt::BottomDockWidgetArea);
  bottomTools->setFeatures (QDockWidget::NoDockWidgetFeatures);
  bottomTools->setFloating (false);
  bottomTools->setTitleBarWidget (new QWidget()); // Disables title bar
  bottomTools->setMinimumHeight (10);             // Avoids warning
  bottomTools->setContentsMargins (3, 6, 3, -2);  // Hacks hacks hacks... :(
  mw->addDockWidget (Qt::BottomDockWidgetArea, bottomTools);

  
    // FIXME? add DockWidgetClosable and connect the close signal
    // to the scheme code
    //  QObject::connect(sideDock, SIGNAL(closeEvent()), 
    //                   someHelper, SLOT(call_scheme_hide_side_tools()));  

  
  // handles visibility
  // at this point all the toolbars are empty so we avoid showing them
  // same for the menu bar if we are not on the Mac (where we do not have
  // other options)
  
  mainToolBar->setVisible (false);
  modeToolBar->setVisible (false);
  focusToolBar->setVisible (false);
  userToolBar->setVisible (false);
  sideTools->setVisible (false);
  bottomTools->setVisible (false);
  mainwindow()->statusBar()->setVisible (true);
#ifndef Q_WS_MAC
  mainwindow()->menuBar()->setVisible (false);
#endif  
}
Esempio n. 15
0
blackbox
qt_tm_widget_rep::query (slot s, int type_id) {
  if (DEBUG_QT_WIDGETS)
    debug_widgets << "qt_tm_widget_rep: queried " << slot_name(s)
                  << "\t\tto widget\t" << type_as_string() << LF;
  
  switch (s) {
    case SLOT_SCROLL_POSITION:
    case SLOT_EXTENTS:
    case SLOT_VISIBLE_PART:
    case SLOT_ZOOM_FACTOR:
      return main_widget->query(s, type_id);

    case SLOT_HEADER_VISIBILITY:
      check_type_id<bool> (type_id, s);
      return close_box<bool> (visibility[0]);
      
    case SLOT_MAIN_ICONS_VISIBILITY:
      check_type_id<bool> (type_id, s);
      return close_box<bool> (visibility[1]);
    
    case SLOT_MODE_ICONS_VISIBILITY:
      check_type_id<bool> (type_id, s);
      return close_box<bool> (visibility[2]);

    case SLOT_FOCUS_ICONS_VISIBILITY:
      check_type_id<bool> (type_id, s);
      return close_box<bool> (visibility[3]);      

    case SLOT_USER_ICONS_VISIBILITY:
      check_type_id<bool> (type_id, s);
      return close_box<bool> (visibility[4]);
      
    case SLOT_FOOTER_VISIBILITY:
      check_type_id<bool> (type_id, s);
      return close_box<bool> (visibility[5]);

    case SLOT_SIDE_TOOLS_VISIBILITY:
      check_type_id<bool> (type_id, s);
      return close_box<bool> (visibility[6]);
    case SLOT_BOTTOM_TOOLS_VISIBILITY:
      check_type_id<bool> (type_id, s);
      return close_box<bool> (visibility[7]);
      
    case SLOT_INTERACTIVE_INPUT:
    {
      check_type_id<string> (type_id, s);
      qt_input_text_widget_rep* w = 
        static_cast<qt_input_text_widget_rep*> (int_input.rep);
      if (w->ok)
        return close_box<string> (scm_quote (w->input));
      else
        return close_box<string> ("#f");
    }

    case SLOT_POSITION:
    {
      check_type_id<coord2> (type_id, s);
      return close_box<coord2> (from_qpoint (mainwindow()->pos()));
    }
      
    case SLOT_SIZE:
    {
      check_type_id<coord2> (type_id, s);
      return close_box<coord2> (from_qsize (mainwindow()->size()));
    }

    case SLOT_INTERACTIVE_MODE:
      check_type_id<bool> (type_id, s);
      return close_box<bool> (prompt && prompt->isActive());

    default:
      return qt_window_widget_rep::query (s, type_id);
  }
}
Esempio n. 16
0
void
qt_tm_widget_rep::send (slot s, blackbox val) {
  switch (s) {
    case SLOT_INVALIDATE:
    case SLOT_INVALIDATE_ALL:
    case SLOT_EXTENTS:
    case SLOT_SCROLL_POSITION:
    case SLOT_ZOOM_FACTOR:
    case SLOT_MOUSE_GRAB:
      main_widget->send(s, val);
      return;
    case SLOT_KEYBOARD_FOCUS:
    {
      check_type<bool> (val, s);
      bool focus = open_box<bool> (val);
      if (focus && canvas() && !canvas()->hasFocus())
        canvas()->setFocus (Qt::OtherFocusReason);
    }
      break;
    case SLOT_HEADER_VISIBILITY:
    {
      check_type<bool>(val, s);
      visibility[0] = open_box<bool> (val);
      update_visibility();
    }
      break;
    case SLOT_MAIN_ICONS_VISIBILITY:
    {
      check_type<bool>(val, s);
      visibility[1] = open_box<bool> (val);
      update_visibility();
    }
      break;
    case SLOT_MODE_ICONS_VISIBILITY:
    {
      check_type<bool>(val, s);
      visibility[2] = open_box<bool> (val);
      update_visibility();
    }
      break;
    case SLOT_FOCUS_ICONS_VISIBILITY:
    {
      check_type<bool>(val, s);
      visibility[3] = open_box<bool> (val);
      update_visibility();
    }
      break;
    case SLOT_USER_ICONS_VISIBILITY:
    {
      check_type<bool>(val, s);
      visibility[4] = open_box<bool> (val);
      update_visibility();
    }
      break;

    case SLOT_FOOTER_VISIBILITY:
    {
      check_type<bool>(val, s);
      visibility[5] = open_box<bool> (val);
      update_visibility();
    }
      break;
    case SLOT_SIDE_TOOLS_VISIBILITY:
    {
      check_type<bool>(val, s);
      visibility[6] = open_box<bool> (val);
      update_visibility();
    }
      break;
    case SLOT_BOTTOM_TOOLS_VISIBILITY:
    {
      check_type<bool>(val, s);
      visibility[7] = open_box<bool> (val);
      update_visibility();
    }
      break;

    case SLOT_LEFT_FOOTER:
    {
      check_type<string>(val, s);
      string msg = open_box<string> (val);
      leftLabel->setText (to_qstring (msg));
      leftLabel->update ();
    }
      break;
    case SLOT_RIGHT_FOOTER:
    {
      check_type<string>(val, s);
      string msg= open_box<string> (val);
      rightLabel->setText (to_qstring (msg));
      rightLabel->update ();
    }
      break;
    case SLOT_SCROLLBARS_VISIBILITY:
        // ignore this: qt handles scrollbars independently
        //                send_int (THIS, "scrollbars", val);
      break;
    case SLOT_INTERACTIVE_MODE:
    {
      check_type<bool>(val, s);

      if (open_box<bool> (val) == true) {
        prompt = new QTMInteractivePrompt (int_prompt, int_input);
        mainwindow()->statusBar()->removeWidget (leftLabel);
        mainwindow()->statusBar()->removeWidget (rightLabel);
        mainwindow()->statusBar()->addWidget (prompt, 1);
        prompt->start();
      } else {
        if (prompt) prompt->end();
        mainwindow()->statusBar()->removeWidget (prompt);
        mainwindow()->statusBar()->addWidget (leftLabel);
        mainwindow()->statusBar()->addPermanentWidget (rightLabel);
        leftLabel->show();
        rightLabel->show();
        prompt->deleteLater();
        prompt = NULL;
      }
    }
      break;
    case SLOT_FILE:
    {
      check_type<string>(val, s);
      string file = open_box<string> (val);
      if (DEBUG_QT_WIDGETS) debug_widgets << "\tFile: " << file << LF;
#if (QT_VERSION >= 0x040400)
      mainwindow()->setWindowFilePath (utf8_to_qstring (file));
#endif
    }
      break;
    case SLOT_POSITION:
    {
      check_type<coord2>(val, s);
      coord2 p= open_box<coord2> (val);
      mainwindow()->move (to_qpoint (p));
    }
      break;
    case SLOT_SIZE:
    {
      check_type<coord2>(val, s);
      coord2 p= open_box<coord2> (val);
      mainwindow()->resize (to_qsize (p));
    }
      break;
    case SLOT_DESTROY:
    {
      ASSERT (is_nil (val), "type mismatch");
      if (!is_nil (quit))
        quit ();
      the_gui->need_update ();
    }
      break;
    case SLOT_FULL_SCREEN:
    {
      check_type<bool> (val, s);
      set_full_screen(open_box<bool> (val));
    }
      break;
    default:
      qt_window_widget_rep::send (s, val);
      return;
  }
  
  if (DEBUG_QT_WIDGETS)
    debug_widgets << "qt_tm_widget_rep: sent " << slot_name (s) 
                  << "\t\tto widget\t"      << type_as_string() << LF;
}
Esempio n. 17
0
void
qt_tm_widget_rep::update_visibility () {
#define XOR(exp1,exp2) (((!exp1) && (exp2)) || ((exp1) && (!exp2)))

  bool old_mainVisibility = mainToolBar->isVisible();
  bool old_modeVisibility = modeToolBar->isVisible();
  bool old_focusVisibility = focusToolBar->isVisible();
  bool old_userVisibility = userToolBar->isVisible();
  bool old_sideVisibility = sideTools->isVisible();
  bool old_bottomVisibility = bottomTools->isVisible();
  bool old_statusVisibility = mainwindow()->statusBar()->isVisible();

  bool new_mainVisibility = visibility[1] && visibility[0];
  bool new_modeVisibility = visibility[2] && visibility[0];
  bool new_focusVisibility = visibility[3] && visibility[0];
  bool new_userVisibility = visibility[4] && visibility[0];
  bool new_statusVisibility = visibility[5];
  bool new_sideVisibility = visibility[6];
  bool new_bottomVisibility = visibility[7];
  
  if ( XOR(old_mainVisibility,  new_mainVisibility) )
    mainToolBar->setVisible (new_mainVisibility);
  if ( XOR(old_modeVisibility,  new_modeVisibility) )
    modeToolBar->setVisible (new_modeVisibility);
  if ( XOR(old_focusVisibility,  new_focusVisibility) )
    focusToolBar->setVisible (new_focusVisibility);
  if ( XOR(old_userVisibility,  new_userVisibility) )
    userToolBar->setVisible (new_userVisibility);
  if ( XOR(old_sideVisibility,  new_sideVisibility) )
    sideTools->setVisible (new_sideVisibility);
  if ( XOR(old_bottomVisibility,  new_bottomVisibility) )
    bottomTools->setVisible (new_bottomVisibility);
  if ( XOR(old_statusVisibility,  new_statusVisibility) )
    mainwindow()->statusBar()->setVisible (new_statusVisibility);

#ifndef Q_WS_MAC
  bool old_menuVisibility = mainwindow()->menuBar()->isVisible();
  bool new_menuVisibility = visibility[0];

  if ( XOR(old_menuVisibility,  new_menuVisibility) )
    mainwindow()->menuBar()->setVisible (new_menuVisibility);
#endif

//#if 0
#ifdef UNIFIED_TOOLBAR

  // do modifications only if needed to reduce flicker
  if ( XOR(old_mainVisibility,  new_mainVisibility) ||
      XOR(old_modeVisibility,  new_modeVisibility) )
  {
    // ensure that the topmost visible toolbar is always unified on Mac
    // (actually only for main and mode toolbars, unifying focus is not
    // appropriate)
    
    QBoxLayout *bl = qobject_cast<QBoxLayout*>(mainwindow()->centralWidget()->layout());
    
    if (modeToolBarAction)
      modeToolBarAction->setVisible(modeToolBar->isVisible());
    mainToolBarAction->setVisible(mainToolBar->isVisible());
    
    //WARNING: jugglying around bugs in Qt unified toolbar implementation
    //do not try to change the order of the following operations....
    
    if (mainToolBar->isVisible()) {       
      bool tmp = modeToolBar->isVisible();
      dumbToolBar->removeAction(modeToolBarAction);
      dumbToolBar->addAction(mainToolBarAction);
      bl->insertWidget(0, rulerWidget);
      bl->insertWidget(0, modeToolBar);
      mainToolBarAction->setVisible(true);
      rulerWidget->setVisible(true);
      modeToolBar->setVisible(tmp);
      if (modeToolBarAction)
        modeToolBarAction->setVisible(tmp);
      dumbToolBar->setVisible(true);
    } else { 
      dumbToolBar->removeAction(mainToolBarAction);
      if (modeToolBar->isVisible()) {
        bl->removeWidget(rulerWidget);
        rulerWidget->setVisible(false);
        bl->removeWidget(modeToolBar);
        if (modeToolBarAction == NULL) {
          modeToolBarAction = dumbToolBar->addWidget(modeToolBar);
        } else {
          dumbToolBar->addAction(modeToolBarAction);
        }
        dumbToolBar->setVisible(true);
      } else {
        dumbToolBar->setVisible(false);
        dumbToolBar->removeAction(modeToolBarAction);
      }
    }
  }
#endif // UNIFIED_TOOLBAR
#undef XOR
  {
    QFont f = leftLabel->font();
    int fs = as_int (get_preference ("gui:mini-fontsize", QTM_MINI_FONTSIZE));
    f.setPixelSize (fs > 0 ? fs : QTM_MINI_FONTSIZE);
    leftLabel->setFont(f);
    rightLabel->setFont(f);
  }
}
Esempio n. 18
0
int main(int argc, char *argv[])
{
  Q_INIT_RESOURCE(resource_omedit);
  // read the second argument if specified by user.
  QString fileName = QString();
  // adding style sheet
  argc++;
  argv[(argc - 1)] = "-stylesheet=:/Resources/css/stylesheet.qss";

  QApplication a(argc, argv);
  QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
  QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
  QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
  a.setAttribute(Qt::AA_DontShowIconsInMenus, false);
  // Localization
  //*a.severin/ add localization
  const char *omhome = getenv("OPENMODELICAHOME");
#ifdef WIN32
  if (!omhome) {
    QMessageBox::critical(0, QString(Helper::applicationName).append(" - ").append(Helper::error),
                          GUIMessages::getMessage(GUIMessages::OPENMODELICAHOME_NOT_FOUND), Helper::ok);
    a.quit();
    exit(1);
  }
#else /* unix */
  omhome = omhome ? omhome : CONFIG_DEFAULT_OPENMODELICAHOME;
#endif
  QSettings settings(QSettings::IniFormat, QSettings::UserScope, "openmodelica", "omedit");
  QString language = settings.value("language").toString();
  QString translationDirectory = omhome + QString("/share/omedit/nls");
  QString locale = language.isEmpty() ? QLocale::system().name() : language;
  // install Qt's default translations
  QTranslator qtTranslator;
#ifdef Q_OS_WIN
  qtTranslator.load("qt_" + locale, translationDirectory);
#else
  qtTranslator.load("qt_" + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath));
#endif
  a.installTranslator(&qtTranslator);
  // install application translations
  QTranslator translator;
  translator.load("OMEdit_" + locale, translationDirectory);
  a.installTranslator(&translator);
  // Splash Screen
  QPixmap pixmap(":/Resources/icons/omeditor_splash.png");
  SplashScreen splashScreen(pixmap);
  splashScreen.setMessage();
  splashScreen.show();
  Helper::initHelperVariables();
  // MainWindow Initialization
  MainWindow mainwindow(&splashScreen);
  if (mainwindow.mExitApplication) {        // if there is some issue in running the application.
    a.quit();
    exit(1);
  }
  bool OMCLogger = false;
  // if user has requested to open the file by passing it in argument then,
  if (a.arguments().size() > 1)
  {
    for (int i = 1; i < a.arguments().size(); i++)
    {
      if (strncmp(a.arguments().at(i).toStdString().c_str(), "--OMCLogger=",12) == 0) {
        QString omcLoggerArg = a.arguments().at(i);
        omcLoggerArg.remove("--OMCLogger=");
        if (0 == strcmp("true", omcLoggerArg.toStdString().c_str()))
          OMCLogger = true;
        else if (0 == strcmp("false", omcLoggerArg.toStdString().c_str()))
          OMCLogger = false;
      }
      fileName = a.arguments().at(i);
      if (!fileName.isEmpty())
      {
        // if path is relative make it absolute
        QFileInfo file (fileName);
        if (file.isRelative())
        {
          fileName.prepend(QString(QDir::currentPath()).append("/"));
        }
        mainwindow.mpProjectTabs->openFile(fileName);
      }
    }
  }
  // hide OMCLogger send custom expression feature if OMCLogger is false
  mainwindow.mpOMCProxy->enableCustomExpression(OMCLogger);
  // finally show the main window
  mainwindow.show();
  // hide the splash screen
  splashScreen.finish(&mainwindow);
  return a.exec();
}
void MyImageListWindow<T>::show()
{
  printf("Preparing image viewer ............. \n");

  char title[100];
  int  clicked_x=-1,clicked_y=-1, selection=-1;
  bool redraw_canvas=false, redraw_panel=false, numberOfImagesChanged=false;
  bool algorithmParamChanged=false, numberOfQueryImagesChanged=false;

  CImg<T> selimg, selmsk;

  int size   = listCanvas->getThumbnailSize();
  
  MyImageList<T>* imageList = listCanvas->getImageList();
  float algorithmParam    = imageList->processingAlgorithm->getParam1();
  int numberOfQueryImages = imageList->queryAlgorithm->getNumberOfQueryImages();

  while (!this->is_closed() && this->key()!=cimg::keyESC && this->key()!=cimg::keyQ)
  {
    this->wait();

    if (this->key()) {
      switch (this->key()) {
        case cimg::keyF1:         listCanvas->showHelp(); redraw_canvas=true; break;
        case cimg::keyARROWDOWN:  y_pos-=scroll_step;     redraw_canvas=true; break; //scrool down
        case cimg::keyARROWUP:    y_pos+=scroll_step;     redraw_canvas=true; break; //scrool up
        case cimg::keyARROWLEFT:  size-=size_step;        listCanvas->setThumbnailSize(size); redraw_panel =true;  break; //decrease thumbnail size
        case cimg::keyARROWRIGHT: size+=size_step;        listCanvas->setThumbnailSize(size); redraw_panel =true;  break; //increase thumbnail size

        case cimg::keyM:          imageList->switchLocalMaskVisibility();             redraw_panel =true;  break;

        case cimg::keyR:          imageList->resetOrderList();                        redraw_panel = true;  break;  //reset search result and marker
        case cimg::keyG:          imageList->showInGroups();                          redraw_panel = true;  break;
        case cimg::keyA:          imageList->processAllVisibleImages(algorithmParam); redraw_panel = true;  break;
      }
    }

    //Mouse wheel changed
    if (this->wheel()) {
      if (this->is_keySHIFTLEFT()) {
        algorithmParam+=(this->wheel());
        algorithmParam = algorithmParam<=0?1:algorithmParam;
        algorithmParamChanged=true;
        imageList->processingAlgorithm->setParam1(algorithmParam);
        redraw_panel=true;
        sprintf(title,"Algorithm param: %f",algorithmParam);
        this->set_title(title);
      } else
      if (this->is_keyCTRLLEFT()) {  //change number of query images
        numberOfQueryImages+=(this->wheel());
        numberOfQueryImages = numberOfQueryImages<=0?1:numberOfQueryImages;
        numberOfQueryImagesChanged=true;
        redraw_panel=true;
        sprintf(title,"Number of query images: %d",numberOfQueryImages);
        this->set_title(title);
      } else
    if (this->is_keyCTRLRIGHT()) {   //change thumbnail size
        size+=(this->wheel()*15);  redraw_panel=true;
        listCanvas->setThumbnailSize(size);
      } else {                      //scrool thumbnails panel
        y_pos+=(this->wheel()*15); redraw_canvas=true;
      }
    }

    //Mouse button pressed
    if (this->button()) {
      clicked_x = this->mouse_x();
      clicked_y = this->mouse_y();
      selection = listCanvas->select_image(clicked_x,clicked_y-y_pos);
      redraw_panel=true;
    }

    //Window size changed
    if (this->is_resized()) {
      listCanvas->resize(this->window_width(),this->window_height()); //.fill(fillColor);
      this->resize(false);
      listCanvas->setWidth( this->window_width() );
      redraw_panel=true;
    }
    /*
    if (this->mouse_x>=0 && this->mouse_y>=0) { // Mouse pointer is over the image
      const int x = this->mouse_x, y = this->mouse_y;
    }
    */

    //Right-mouse button pressed
    if (this->button()&2) {
      if (selection>=0) {
        selimg = imageList->at(selection).image;
        selmsk = imageList->at(selection).mask;

        MyImageCanvas<T> maincanvas(selimg);
        maincanvas.setMask(selmsk, red);
        maincanvas.setProcessingAlgorithm(imageList->processingAlgorithm, algorithmParam);
        maincanvas.redraw();
        MyImageWindow<T> mainwindow(&maincanvas,"[Type F1 for help]");
        mainwindow.show();
        if (maincanvas.isMaskChanged()) {
          imageList->at(selection).mask = maincanvas.getMask();
          imageList->at(selection).maskChanged = true;
          if (algorithmParam != maincanvas.getAlgorithmParam()) {
            algorithmParam = maincanvas.getAlgorithmParam();
            algorithmParamChanged = true;
          }
          redraw_panel = true;
        }
      }
    }

    //Middle-mouse button pressed, or number of results changed
    if (this->button()&4 || numberOfQueryImagesChanged || algorithmParamChanged) {
      if (selection>=0) {
        selimg = imageList->at(selection).image;
        if (this->is_keyCTRLLEFT() || numberOfQueryImagesChanged) {
          imageList->orderList = imageList->queryAlgorithm->queryImage(selimg, numberOfQueryImages);
          y_pos=0;
          numberOfQueryImagesChanged=false;
        }
        else {
          imageList->at(selection).mask = imageList->processingAlgorithm->processImage(selimg,algorithmParam );
          imageList->at(selection).maskChanged = true;
        }
        algorithmParamChanged=false;
      }
    }

    //Redraw thumbnail panel and canvas
    if (redraw_panel)
      listCanvas->prepare_image_panel(selection);
    if (redraw_panel || redraw_canvas) {
      listCanvas->redraw(0,y_pos);
      listCanvas->display(*this);
    }

    //Clear temporary settings
    if (redraw_panel || redraw_canvas) {
      redraw_panel  = false;
      redraw_canvas = false;
      this->set_key(0);
      this->set_wheel();
      this->set_button();
    }
  }
}
Esempio n. 20
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;
}
Esempio n. 21
0
int main(int argc, char *argv[])
{
  /* Do not use the signal handler OR exception filter if user is building a debug version. Perhaps the user wants to use gdb. */
  MMC_INIT();

#ifdef QT_NO_DEBUG
#ifdef WIN32
  SetUnhandledExceptionFilter(exceptionFilter);
#else
  /* Abnormal termination (abort) */
  signal(SIGABRT, signalHandler);
  /* Segmentation violation */
  signal(SIGSEGV, signalHandler);
  /* Illegal instruction */
  signal(SIGILL, signalHandler);
  /* Floating point error */
  signal(SIGFPE, signalHandler);
#endif // #ifdef WIN32
#endif // #ifdef QT_NO_DEBUG
  // if user asks for --help
  for(int i = 1; i < argc; i++) {
    if (strcmp(argv[i], "--help") == 0) {
      printOMEditUsage();
      return 0;
    }
  }
  Q_INIT_RESOURCE(resource_omedit);
  QApplication a(argc, argv);
  // set the stylesheet
  a.setStyleSheet("file:///:/Resources/css/stylesheet.qss");
#if !(QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
  QTextCodec::setCodecForTr(QTextCodec::codecForName(Helper::utf8.toLatin1().data()));
  QTextCodec::setCodecForCStrings(QTextCodec::codecForName(Helper::utf8.toLatin1().data()));
#endif
#ifndef WIN32
  QTextCodec::setCodecForLocale(QTextCodec::codecForName(Helper::utf8.toLatin1().data()));
#endif
  a.setAttribute(Qt::AA_DontShowIconsInMenus, false);
  // Localization
  //*a.severin/ add localization
  const char *omhome = getenv("OPENMODELICAHOME");
#ifdef WIN32
  if (!omhome) {
    QMessageBox::critical(0, QString(Helper::applicationName).append(" - ").append(Helper::error),
                          GUIMessages::getMessage(GUIMessages::OPENMODELICAHOME_NOT_FOUND), Helper::ok);
    a.quit();
    exit(1);
  }
#else /* unix */
  omhome = omhome ? omhome : CONFIG_DEFAULT_OPENMODELICAHOME;
#endif
  QSettings *pSettings = OpenModelica::getApplicationSettings();
  QLocale settingsLocale = QLocale(pSettings->value("language").toString());
  settingsLocale = settingsLocale.name() == "C" ? pSettings->value("language").toLocale() : settingsLocale;
  QString locale = settingsLocale.name().isEmpty() ? QLocale::system().name() : settingsLocale.name();
  /* set the default locale of the application so that QSpinBox etc show values according to the locale. */
  QLocale::setDefault(settingsLocale);

  QString translationDirectory = omhome + QString("/share/omedit/nls");
  // install Qt's default translations
  QTranslator qtTranslator;
#ifdef Q_OS_WIN
  qtTranslator.load("qt_" + locale, translationDirectory);
#else
  qtTranslator.load("qt_" + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath));
#endif
  a.installTranslator(&qtTranslator);
  // install application translations
  QTranslator translator;
  translator.load("OMEdit_" + locale, translationDirectory);
  a.installTranslator(&translator);
  // Splash Screen
  QPixmap pixmap(":/Resources/icons/omedit_splashscreen.png");
  QSplashScreen splashScreen(pixmap);
  //splashScreen.setMessage();
  splashScreen.show();
  Helper::initHelperVariables();
  /* Force C-style doubles */
  setlocale(LC_NUMERIC, "C");
  // if user has requested to open the file by passing it in argument then,
  bool OMCLogger = false;
  bool debug = false;
  QString fileName = "";
  QStringList fileNames;
  if (a.arguments().size() > 1) {
    for (int i = 1; i < a.arguments().size(); i++) {
      if (strncmp(a.arguments().at(i).toStdString().c_str(), "--OMCLogger=",12) == 0) {
        QString omcLoggerArg = a.arguments().at(i);
        omcLoggerArg.remove("--OMCLogger=");
        if (0 == strcmp("true", omcLoggerArg.toStdString().c_str())) {
          OMCLogger = true;
        } else {
          OMCLogger = false;
        }
      } else if (strncmp(a.arguments().at(i).toStdString().c_str(), "--Debug=",8) == 0) {
        QString debugArg = a.arguments().at(i);
        debugArg.remove("--Debug=");
        if (0 == strcmp("true", debugArg.toStdString().c_str())) {
          debug = true;
        } else {
          debug = false;
        }
      } else {
        fileName = a.arguments().at(i);
        if (!fileName.isEmpty()) {
          // if path is relative make it absolute
          QFileInfo file (fileName);
          if (file.isRelative()) {
            fileName.prepend(QString(QDir::currentPath()).append("/"));
          }
          fileName = fileName.replace("\\", "/");
          fileNames << fileName;
        }
      }
    }
  }
  // MainWindow Initialization
  MainWindow mainwindow(&splashScreen, debug);
  if (mainwindow.getExitApplicationStatus()) {        // if there is some issue in running the application.
    a.quit();
    exit(1);
  }
  // open the files passed as command line arguments
  foreach (QString fileName, fileNames) {
    mainwindow.getLibraryWidget()->openFile(fileName);
  }