Ejemplo n.º 1
0
void MergeCmappedDialog::accept() {
  m_levelPath = TFilePath(QString(m_saveInFileFld->getPath() + "\\" +
                                  m_fileNameFld->text() + ".tlv")
                              .toStdString());
  TFilePath fp =
      TApp::instance()->getCurrentScene()->getScene()->decodeFilePath(
          m_levelPath);

  if (TSystem::doesExistFileOrLevel(fp)) {
    if (DVGui::MsgBox(
            QObject::tr("Level ") +
                QString::fromStdWString(m_levelPath.getWideString()) +
                QObject::tr(
                    " already exists! Are you sure you want to overwrite it?"),
            tr("Ok"), tr("Cancel")) != 1)
      return;
    else {
      TSystem::removeFileOrLevel(fp);
      TSystem::removeFileOrLevel(fp.withType("tpl"));
    }
  }

  Dialog::accept();
}
Ejemplo n.º 2
0
void SceneLevel::save()
{
	TFilePath fp = m_oldPath;
	SceneResource::updatePath(fp);
	TFilePath actualFp = m_scene->decodeFilePath(fp);
	actualFp = restorePsdPath(actualFp);
	TFilePath oldActualPath = restorePsdPath(m_oldActualPath);
	assert(actualFp.getWideString() == L"" || actualFp.getWideString()[0] != L'+');
	if (actualFp != oldActualPath || !TSystem::doesExistFileOrLevel(oldActualPath) || m_sl->getProperties()->getDirtyFlag() || (m_sl->getPalette() && m_sl->getPalette()->getDirtyFlag())) {
		try {
			TSystem::touchParentDir(actualFp);
			if (actualFp != oldActualPath &&
				TSystem::doesExistFileOrLevel(oldActualPath) &&
				m_sl->getProperties()->getDirtyFlag() == false &&
				(!m_sl->getPalette() || (m_sl->getPalette() && m_sl->getPalette()->getDirtyFlag() == false))) {
				try {
					TXshSimpleLevel::copyFiles(actualFp, oldActualPath);
				} catch (...) {
				}
				//Must NOT KEEP FRAMES, it generate a level frames bind necessary to imageBuilder path refresh.
				m_sl->setPath(fp, false);
			} else {
				m_sl->save(actualFp, oldActualPath);

				if ((actualFp.getType() == "tlv" || actualFp.getType() == "pli") &&
					actualFp != oldActualPath &&
					m_oldRefImgPath != TFilePath()) {
					//Devo preoccuparmi dell'eventuale livello colormodel
					TFilePath actualRefImagPath = m_scene->decodeFilePath(m_oldRefImgPath);
					TFilePath actualRefImagPathTpl = actualRefImagPath.withType("tpl");
					TFilePath oldRefImagPathTpl = m_oldActualRefImgPath.withType("tpl");
					TSystem::copyFile(actualRefImagPath, m_oldActualRefImgPath);
					if (actualRefImagPath.getType() == "tlv")
						TSystem::copyFile(actualRefImagPathTpl, oldRefImagPathTpl);
				}

				if (actualFp.getType() == "tif" || actualFp.getType() == "tiff" || actualFp.getType() == "tga" || actualFp.getType() == "tzi") {
					TFilePath clnin = oldActualPath.withNoFrame().withType("cln");
					if (TSystem::doesExistFileOrLevel(clnin))
						TSystem::copyFile(actualFp.withNoFrame().withType("cln"), clnin);
				}
			}
			//Se il livello e' tlv verifico se esiste il corrispondente unpainted ed in caso affermativo lo copio.
			//Questo controllo viene fatto qui e non nella copia o nel salvataggio del livello perche' in generale
			//non si vuole che il livello unpainted venga copiato con il livello.
			if (actualFp.getType() == "tlv") {
				TFilePath oldUnpaintedLevelPath = oldActualPath.getParentDir() + TFilePath(oldActualPath.getName() + "-unpainted." + oldActualPath.getType());
				TFilePath unpaintedLevelPath = actualFp.getParentDir() + TFilePath(actualFp.getName() + "-unpainted." + actualFp.getType());
				if (TSystem::doesExistFileOrLevel(oldUnpaintedLevelPath) && !TSystem::doesExistFileOrLevel(unpaintedLevelPath))
					TSystem::copyFile(unpaintedLevelPath, oldUnpaintedLevelPath);
				TFilePath oldUnpaintedPalettePath = oldUnpaintedLevelPath.withType("tpl");
				TFilePath unpaintedPalettePath = unpaintedLevelPath.withType("tpl");
				if (TSystem::doesExistFileOrLevel(oldUnpaintedPalettePath) && !TSystem::doesExistFileOrLevel(unpaintedPalettePath))
					TSystem::copyFile(unpaintedPalettePath, oldUnpaintedPalettePath);
			}
		} catch (...) {
		}
	}
	fp = m_oldScannedPath;
	if (fp != TFilePath()) {
		SceneResource::updatePath(fp);
		actualFp = m_scene->decodeFilePath(fp);
		if (actualFp != m_oldActualScannedPath &&
			TSystem::doesExistFileOrLevel(m_oldActualScannedPath)) {
			try {
				TSystem::touchParentDir(actualFp);
				TSystem::copyFileOrLevel_throw(actualFp, m_oldActualScannedPath);
				m_sl->clearFrames();
				m_sl->load();
			} catch (...) {
			}
		}
	}
}
Ejemplo n.º 3
0
void TExternalProgramFx::doCompute(TTile &tile, double frame,
                                   const TRenderSettings &ri) {
  TRaster32P ras = tile.getRaster();
  if (!ras) return;
  std::string args           = m_args;
  std::string executablePath = ::to_string(m_executablePath);
  std::map<std::string, TFilePath> tmpFiles;  // portname --> file
  TFilePath outputTmpFile;

  std::map<std::string, Port>::const_iterator portIt;
  for (portIt = m_ports.begin(); portIt != m_ports.end(); ++portIt) {
    TFilePath fp            = TSystem::getUniqueFile("externfx");
    fp                      = fp.withType(portIt->second.m_ext);
    tmpFiles[portIt->first] = fp;
    if (portIt->second.m_port == 0)  // solo una porta e' di output
      outputTmpFile = fp;
    else {
      TRasterFxPort *tmp;
      tmp = portIt->second.m_port;
      if (tmp->isConnected()) {
        (*tmp)->compute(tile, frame, ri);
        TImageWriter::save(fp, ras);
      }
    }
  }

  // args e' della forma "$src $ctrl -o $out -v $value"
  // sostituisco le variabili
  int i = 0;
  for (;;) {
    i = args.find('$', i);
    if (i == (int)std::string::npos) break;
    int j   = i + 1;
    int len = args.length();
    while (j < len && isalnum(args[j])) j++;
    // un '$' non seguito da caratteri alfanumerici va ignorato
    if (j == i + 1) {
      // la sequenza '$$' diventa '$'
      if (j < len && args[j] == '$') args.replace(i, 2, "$");
      i++;
      continue;
    }
    // ho trovato una variabile
    int m            = j - i - 1;
    std::string name = args.substr(i + 1, m);
    // calcolo il valore.
    std::string value;

    std::map<std::string, TFilePath>::const_iterator it;
    it = tmpFiles.find(name);
    if (it != tmpFiles.end()) {
      // e' una porta. il valore e' il nome del
      // file temporaneo
      value = "\"" + ::to_string(it->second.getWideString()) + "\"";
    } else {
      // e' un parametro
      // se il nome non viene riconosciuto sostituisco la stringa nulla
      TDoubleParamP param = TParamP(getParams()->getParam(name));
      if (param) value    = std::to_string(param->getValue(frame));
    }

    args.replace(i, m + 1, value);
  }
  args = " " + args;  // aggiungo uno spazio per sicurezza
  // ofstream os("C:\\temp\\butta.txt");
  // os << args << endl;

  // bisognerebbe calcolare le immagini dalla/e porta/e di input
  // scrivere il/i valore/i nei files temporanei/o
  // chiamare "m_executablePath args"
  // e leggere l'immagine scritta in outputTmpFile
  // poi cancellare tutto
  std::string expandedargs;
  char buffer[1024];
#ifdef _WIN32
  ExpandEnvironmentStrings(args.c_str(), buffer, 1024);

  STARTUPINFO si;
  PROCESS_INFORMATION pinfo;

  GetStartupInfo(&si);

  BOOL ret = CreateProcess(
      (char *)executablePath.c_str(),           // name of executable module
      buffer,                                   // command line string
      NULL,                                     // SD
      NULL,                                     // SD
      TRUE,                                     // handle inheritance option
      CREATE_NO_WINDOW, /*CREATE_NEW_CONSOLE*/  // creation flags
      NULL,                                     // new environment block
      NULL,                                     // current directory name
      &si,                                      // startup information
      &pinfo                                    // process information
      );

  if (!ret) DWORD err = GetLastError();

  // aspetta che il processo termini
  WaitForSingleObject(pinfo.hProcess, INFINITE);

  DWORD exitCode;
  ret = GetExitCodeProcess(pinfo.hProcess,  // handle to the process
                           &exitCode);      // termination status

#else
  std::string cmdline = executablePath + buffer;
  //    int exitCode =
  system(cmdline.c_str());
#endif
  /*
string name = m_executablePath.getName();
TPixel32 color;
if(name == "saturate") color = TPixel32::Magenta;
else if(name == "over") color = TPixel32::Green;
else color = TPixel32::Red;
for(int iy=0;iy<ras->getLy();iy++)
{
TPixel32 *pix = ras->pixels(iy);
TPixel32 *endPix = pix + ras->getLx();
double x = tile.m_pos.x;
double y = tile.m_pos.y + iy;
while(pix<endPix)
 {
  if(x*x+y*y<900) *pix = color;
  else *pix = TPixel32(0,0,0,0);
  ++pix;
  x+=1.0;
 }
}
*/

  try {
    TRasterP ras = tile.getRaster();
    TImageReader::load(outputTmpFile, ras);
  } catch (...) {
  }

  // butto i file temporanei creati
  std::map<std::string, TFilePath>::const_iterator fileIt;
  for (fileIt = tmpFiles.begin(); fileIt != tmpFiles.end(); ++fileIt) {
    if (TFileStatus(fileIt->second).doesExist() == true) try {
        TSystem::deleteFile(fileIt->second);
      } catch (...) {
      }
  }
  if (TFileStatus(outputTmpFile).doesExist() == true) try {
      TSystem::deleteFile(outputTmpFile);
    } catch (...) {
    }
}
Ejemplo n.º 4
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;
}