Beispiel #1
0
bool MidiInstrument::fileSave()/*{{{*/
{
    if(_filePath.isEmpty())
        return false;
    // Do not allow a direct overwrite of a 'built-in' los instrument.
    QFileInfo qfi(_filePath);
    if (qfi.absolutePath() == losInstruments)
    {
        return false;
    }
    FILE* f = fopen(_filePath.toUtf8().constData(), "w");
    if (f == 0)
    {
        return false;
    }

    Xml xml(f);

    write(0, xml);

    // Now signal the rest of the app so stuff can change...
    song->update(SC_CONFIG | SC_MIDI_CONTROLLER);

    if (fclose(f) != 0)
    {
        return false;
    }
    return true;
}/*}}}*/
QString LibrariesInfo::resolveLibraryPath(const QString &library, const LibSearchInfo &info)
{
    if (cache.contains(library))
        return cache[library]->path;

    // Create search path
    QStringList paths;

    // RPATH was set, RUNPATH was not, look in RPATH first.
    if(info.runPath.isEmpty() && !info.rPath.isEmpty())
        paths << info.rPath.split(":");

    if (elfClass == ELF64)
        paths << envPaths64;
    else
        paths << envPaths32;

    if(!info.runPath.isEmpty())
        paths << info.runPath.split(":");

    if (elfClass == ELF64)
        paths << basePaths64;
    else
        paths << basePaths32;
    paths << "/lib" << "/usr/lib";

    foreach(QString path, paths) {
        QFileInfo qfi(path + "/" + library);
        if (qfi.exists()) {
            // Resolve symlink.
            cache[library] = Lib::create(qfi.canonicalFilePath());

            return qfi.canonicalFilePath();
        }
    }
Beispiel #3
0
/**
 * \return "" when fail, out file name when successful
 */
QString saveLDRImage(const QString initialFileName, const QImage* image, bool batchMode) {
	QString outfname = QDir(settings.value(KEY_RECENT_PATH_SAVE_LDR,QDir::currentPath()).toString()).filePath(initialFileName);
	if (!batchMode) {
		QString filetypes = QObject::tr("All LDR formats (*.jpg *.jpeg *.png *.ppm *.pbm *.bmp);;");
		filetypes += "JPEG (*.jpg *.jpeg);;" ;
		filetypes += "PNG (*.png);;" ;
		filetypes += "PPM PBM (*.ppm *.pbm);;";
		filetypes += "BMP (*.bmp)";

		outfname = QFileDialog::getSaveFileName(
				0,
				QObject::tr("Save the LDR to..."),
				QDir(settings.value(KEY_RECENT_PATH_SAVE_LDR,QDir::currentPath()).toString()).filePath(initialFileName),
				filetypes
		);
	}

	if(!outfname.isEmpty()) {
		QFileInfo qfi(outfname);
		//save settings
		settings.setValue(KEY_RECENT_PATH_SAVE_LDR, qfi.path());
		QString format=qfi.suffix();
		if (qfi.suffix().isEmpty()) {
			// default as png
			format="png";
			outfname+=".png";
		}
		if(!(image->save(outfname,format.toAscii().constData(),100))) {
			QMessageBox::warning(0,"",QObject::tr("Failed to save <b>") + outfname + "</b>", QMessageBox::Ok, QMessageBox::NoButton);
			return "";
		}
	} //if(!outfname.isEmpty())
	return outfname;
}
Beispiel #4
0
StateDiff Repo::detectChanges() const
{
    State* state = m_logger->state();
    StateDiff diff;
    QStringList found_files = readFilePaths();

    // checking for known files
    // known_file_paths will hold a list of all file_paths in the store and the state
    QStringList known_file_paths = state->knownFilePaths(found_files);

    // checking for files which are unrecognised
    // an unknown file is on the disk but not in the collection
    QStringList unknown_file_paths = state->unknownFilePaths(found_files);

    // a missing file is in the state but not in the repo
    // check for files which have gone missing
    QStringList missing_file_paths = state->missingFilePaths(found_files);


    // scanning known files for modifications
    QString file_path;
    foreach(file_path, known_file_paths){
        QCoreApplication::processEvents();
        // check if that file has been modified
        // to save effort we dont call newFileInfo as that reads the sha1
        // and we only want to read the sha1 if the mtime has changed
        FileInfo stored_fi = state->fileInfoByFilePath(file_path);
        QFileInfo qfi(m_path+'/'+file_path);
        if (!stored_fi.sameModifiedAtAndSize(qfi.lastModified(), qfi.size())){
            // file has changed on disk but filename is the same.
            // record the new values for the file
            diff.modifyFile(file_path, qfi.size(), qfi.lastModified(),
                                readFingerPrint(file_path));
        }
    }
Beispiel #5
0
void TimeLapseWidget::setDirectory()
{
    QFileDialog::Options options = QFileDialog::DontResolveSymlinks | QFileDialog::ShowDirsOnly;
    QString directory =
            QFileDialog::getExistingDirectory(this,
                                              tr("Save pictures..."),
                                              saveDirectory->text(),
                                              options);
    if(  !directory.isEmpty() )
    {
        QFileInfo qfi(directory);

         if ( qfi.exists() && qfi.isWritable() )
         {
             saveDirectory->setText( directory );
             if( attachedCameras->currentText().compare( "No camera detected" ) != 0 )
             {
                 startButton->setDisabled( false );
             }
         }
         else
         {
             QMessageBox::critical( this, tr("Error"),tr("Please select a writable directory") );
             saveDirectory->clear();
             startButton->setDisabled( true );
             stopButton->setDisabled( true );
         }
     }
}
Beispiel #6
0
void MainWindow::do_load_dataset() {
        tty->append("Loading dataset...");

        QString rand_img = QFileDialog::getOpenFileName(this,
                tr("Pick one image from the data set."), QDir::homePath(),
                tr("Scan Data (*.pgm *.bmp)"));
                
        if (rand_img != "") {
                tty->append("-->" + rand_img);
        } else {
                tty->append("--> Error: No base image selected.");
                return;
        }             
        
        QFileInfo qfi(rand_img);
        img_type = QString(qfi.suffix());
        fprefix = rand_img;
        fprefix.chop(7);
        dataset_path_edit->setText(fprefix);
        
        // num_imgs = slices_spin->value();        
        QDir dir(qfi.dir());
        QStringList filters;
        QString ifilt = "*." + img_type;
		filters << ifilt;
		dir.setNameFilters(filters);
        num_imgs = dir.count();
        slices_spin->setValue(num_imgs);
        
        tty->append("--> fprefix: " + fprefix);
        tty->append("--> Note: You may want to modify the slice/spacing parameters using the controls above.");
        
        has_dataset = true;
}
Beispiel #7
0
  void LocalProcess::processError(QProcess::ProcessError t_e)
  {
    m_fileCheckTimer.stop();
    QFileInfo qfi(toQString(m_tool.localBinPath));
    QFileInfo outdirfi(toQString(m_outdir));
    LOG(Error, "LocalProcess processError: " << t_e 
        << " exe: " << toString(m_tool.localBinPath)
        << " workingdir: " << toString(m_outdir)
        << " fileexists: " << qfi.isFile()
        << " fileexecutable: " << qfi.isExecutable()
        << " ErrorValue: " << t_e
        << " outdirexists: " << outdirfi.isFile()
        << " outdirisdirectory: " << outdirfi.isDir());

    QCoreApplication::processEvents();
    directoryChanged(openstudio::toQString(m_outdir));

    QProcess::ProcessState state = m_process.state();

    if (state != QProcess::Running
        && t_e == QProcess::WriteError)
    {
      LOG(Info, "WriteError occured when process was not running, ignoring it");
    } else {
      //directoryChanged(openstudio::toQString(m_outdir));
      emit error(t_e);
    }

 }
Beispiel #8
0
QString Util::findBinaryInPath(QString binary) {
  initialiseEnvironment();

  QString ret = "";

  binary.prepend(QDir::separator());

  if (_env.contains("PATH")) {
    QString path = _env.value("PATH");

    QStringList entries;
#ifndef Q_OS_WIN
    entries = path.split(':');
    if (entries.length() < 2) {
#endif
      entries = path.split(';');
#ifndef Q_OS_WIN
    }
#endif

    foreach(QString entry, entries) {
      QScopedPointer<QFileInfo> qfi(new QFileInfo(entry.append(binary)));
#ifdef Q_OS_WIN
      if (!qfi->exists())
        qfi.reset(new QFileInfo(entry.append(".exe")));

#endif
      qDebug() << entry;
      if (!qfi->isExecutable())
        continue;

      ret = qfi->absoluteFilePath();
      break;
    }
Beispiel #9
0
static QFile* getHTMLFilename(QFile *file){
    QFileInfo qfi(*file);
    QString htmlFilename = qfi.path() + "/";
    if(qfi.suffix() == "md" || qfi.suffix() == "mkd"){
        htmlFilename +=  qfi.baseName() + ".html";
    }
    else {
        htmlFilename +=  qfi.fileName() + ".html";
    }
    return new QFile(htmlFilename);
}
Beispiel #10
0
void GlobalConfigWidget::selectFile()
{
   QFileDialog fileDialog( this );

   fileDialog.setFileMode( QFileDialog::ExistingFile );
   QFileInfo qfi( mpStyleSheetFileName->text() );
   fileDialog.setDirectory( qfi.absolutePath() );
   fileDialog.setFilter("Playlists (*.qss)");
   fileDialog.setReadOnly( true );
   if( fileDialog.exec() )
   {
      mpStyleSheetFileName->setText( fileDialog.selectedFiles().at(0) );
   }
}
Beispiel #11
0
void TimeLapseWidget::saveDirectoryUpdated()
{
    QFileInfo qfi(saveDirectory->text());

    if( qfi.exists() && qfi.isDir()
        && qfi.isWritable()
        && attachedCameras->currentText().compare( "No camera detected" ) != 0 )
    {
        startButton->setDisabled( false );
    }
    else
    {
        startButton->setDisabled( true );
    }
}
void HdrCreationManager::newResult(int index, float expotime, QString newfname) {
	runningThreads--;
	processedFiles++;

	//update filesToRemove
	if ( fileList.at(index) != newfname )
		filesToRemove.append(newfname);

	//update expotimes[i]
	expotimes[index]=expotime;

	QFileInfo qfi(fileList[index]);
	//check for invalid exif: update list that will be sent once all is over.
	if (expotimes[index]==-1) {
		filesLackingExif << "<li>"+qfi.fileName()+"</li>";
		//qDebug("HCM: new invalid exif. elements: %d", filesLackingExif.size());
	}

	emit fileLoaded(index,fileList[index],expotimes[index]);
}
Beispiel #13
0
    bool ImageLoader::makeFilePaths(const QString & p)
    {
        QFileInfo qfi(p);
        QSettings ss;

        if(qfi.exists() == false || qfi.isReadable() == false ||is_quitted)
            return false;

        if(qfi.isDir() && (p == path_to_load || recurse))
        {
            QDir the_dir(p);
            QStringList files, filters;

            filters << "*";
            the_dir.setNameFilters(ss.value("files/types_filter", filters).toStringList());

            files = the_dir.entryList(QDir::AllDirs|QDir::Files|QDir::NoDotAndDotDot|QDir::Readable, QDir::Name|QDir::IgnoreCase|QDir::LocaleAware);
            foreach(const QString &path, files)
            {
                makeFilePaths(the_dir.absoluteFilePath(path));
                if(is_quitted)
                    break;
            }
Beispiel #14
0
/**
 * Get real name for file.
 */
int
getNames(const QString &full, QCString &zname, QCString &sname, ZEntry **buf)
{
    QString zip_name, suname;
    int prev_type = QZF_NONE;

    if (QFile::exists(full)) {
        QFileInfo       qfi(full);
        if (qfi.isDir())
          return QZF_DIR;
        if (qfi.isFile()) {
          prev_type = QZF_FILE;
        } else {
          return QZF_NONE;
        }
    }
    //printf("File[%s] does not exist!\n", (const char*)full);

    /* finding zip file name */
    int idx;
    idx = full.length();
    zip_name = full;
    while(idx>=0) {
        if (QFile::exists(zip_name))
            break;

        idx = full.findRev('/', idx);
        if (idx<0)
            return prev_type;
        zip_name = full.left(idx);
        idx--;
    }
    if (toMB(sname, full.mid(idx+1), "euc-kr")<0)
      sname = full.mid(idx+1);
    QFileInfo   zdir(zip_name);
    zip_name = zdir.absFilePath();

    ZRootEntry *root = ZDirEntry::getEntry(zip_name.utf8());
    if (root==NULL) {
      if (zdir.extension(false)=="dz") {
        zname = zip_name.utf8();
        sname = NULL;
        return QZF_DZ|QZF_FILE;
      }
      return prev_type;
    }

    ZEntry *entry = root->findByName(sname);
    if (entry==NULL) {
      return prev_type;
    }

    zname = zip_name.utf8();

    if (buf) *buf = entry;
    if (entry->isDir()) {
      return QZF_ZIP|QZF_DIR;
    } else {
      return QZF_ZIP|QZF_FILE;
    }
}
Beispiel #15
0
FileInfo LocalDiskRepo::readFileInfoCheap(QString filePath) const
{
    QFileInfo qfi(m_path+"/"+filePath);
    return FileInfo(filePath, qfi.size(), qfi.lastModified(), "");
}
Beispiel #16
0
void MainGui::fileSaveAs()
{
	if (currenthdr==NULL)
		return;

	QString filetypes = tr("All Hdr formats ");
	filetypes += "(*.exr *.hdr *.pic *.tiff *.tif *.pfs);;" ;
	filetypes += "OpenEXR (*.exr);;" ;
	filetypes += "Radiance RGBE (*.hdr *.pic);;";
	filetypes += "HDR TIFF (*.tiff *.tif);;";
	filetypes += "PFS Stream (*.pfs)";

	QString fname = QFileDialog::getSaveFileName(
			this,
			tr("Save the HDR..."),
			RecentDirHDRSetting,
			filetypes
	);

	if(!fname.isEmpty()) {
		QFileInfo qfi(fname);
		QString absoluteFileName=qfi.absoluteFilePath();
		char* encodedName=strdup(QFile::encodeName(absoluteFileName).constData());
		// if the new dir, the one just chosen by the user, is different from the one stored in the settings, update the settings.
		if (RecentDirHDRSetting != qfi.path() )
			// update internal field variable
			updateRecentDirHDRSetting(qfi.path());

		if (qfi.suffix().toUpper()=="EXR") {
			writeEXRfile  (currenthdr->getHDRPfsFrame(),encodedName);
		} else if (qfi.suffix().toUpper()=="HDR") {
			writeRGBEfile (currenthdr->getHDRPfsFrame(), encodedName);
		} else if (qfi.suffix().toUpper().startsWith("TIF")) {
			TiffWriter tiffwriter(encodedName, currenthdr->getHDRPfsFrame());
			if (qtpfsgui_options->saveLogLuvTiff)
				tiffwriter.writeLogLuvTiff();
			else
				tiffwriter.writeFloatTiff();
		} else if (qfi.suffix().toUpper()=="PFS") {
			pfs::DOMIO pfsio;
			(currenthdr->getHDRPfsFrame())->convertRGBChannelsToXYZ();
			pfsio.writeFrame(currenthdr->getHDRPfsFrame(),encodedName);
			(currenthdr->getHDRPfsFrame())->convertXYZChannelsToRGB();
		} else {
			// TODO: [QT 4.5] This is not needed for windows (bug will be fixed in QT 4.5..?)

			// Default as EXR
			free(encodedName);
			absoluteFileName = absoluteFileName + ".exr";
			encodedName = strdup(QFile::encodeName(absoluteFileName).constData());
			writeEXRfile  (currenthdr->getHDRPfsFrame(),encodedName);
//			QMessageBox::warning(this,tr("Aborting..."), tr("Qtpfsgui supports only the following formats: <br>Radiance RGBE (hdr), PFS, tiff-hdr and OpenEXR."),
//			QMessageBox::Ok,QMessageBox::NoButton);
//			return;
		}
		free(encodedName);
		setCurrentFile(absoluteFileName);
		currenthdr->NeedsSaving=false;
		currenthdr->filename=absoluteFileName;
		currenthdr->setWindowTitle(absoluteFileName);
	}
}
Beispiel #17
0
int Controller::LoadMesh(Render *re, SceneRenderLayer *srl)
{
	BlenderFileLoader loader(re, srl);

	loader.setRenderMonitor(_pRenderMonitor);

	_Chrono.start();

	NodeGroup *blenderScene = loader.Load();

	if (blenderScene == NULL) {
		if (G.debug & G_DEBUG_FREESTYLE) {
			cout << "Cannot load scene" << endl;
		}
		return 1;
	}

	if (blenderScene->numberOfChildren() < 1) {
		if (G.debug & G_DEBUG_FREESTYLE) {
			cout << "Empty scene" << endl;
		}
		blenderScene->destroy();
		delete blenderScene;
		return 1;
	}

	real duration = _Chrono.stop();
	if (G.debug & G_DEBUG_FREESTYLE) {
		cout << "Scene loaded" << endl;
		printf("Mesh cleaning    : %lf\n", duration);
		printf("View map cache   : %s\n", _EnableViewMapCache ? "enabled" : "disabled");
	}
	_SceneNumFaces += loader.numFacesRead();

#if 0
	if (loader.minEdgeSize() < _minEdgeSize) {
		_minEdgeSize = loader.minEdgeSize();
	}
#endif

#if 0  // DEBUG
	ScenePrettyPrinter spp;
	blenderScene->accept(spp);
#endif

	_RootNode->AddChild(blenderScene);
	_RootNode->UpdateBBox(); // FIXME: Correct that by making a Renderer to compute the bbox

	_pView->setModel(_RootNode);
	//_pView->FitBBox();

	if (_pRenderMonitor->testBreak())
		return 0;

	if (_EnableViewMapCache) {

		NodeCamera *cam;
		if (g_freestyle.proj[3][3] != 0.0)
			cam = new NodeOrthographicCamera;
		else
			cam = new NodePerspectiveCamera;
		double proj[16];
		for (int i = 0; i < 4; i++) {
			for (int j = 0; j < 4; j++) {
				proj[i * 4 + j] = g_freestyle.proj[i][j];
			}
		}
		cam->setProjectionMatrix(proj);
		_RootNode->AddChild(cam);
		_RootNode->AddChild(new NodeSceneRenderLayer(*re->scene, *srl));

		sceneHashFunc.reset();
		//blenderScene->accept(sceneHashFunc);
		_RootNode->accept(sceneHashFunc);
		if (G.debug & G_DEBUG_FREESTYLE) {
			cout << "Scene hash       : " << sceneHashFunc.toString() << endl;
		}
		if (hitViewMapCache()) {
			ClearRootNode();
			return 0;
		}
		else {
			delete _ViewMap;
			_ViewMap = NULL;
		}
	}

	_Chrono.start();

	WXEdgeBuilder wx_builder;
	wx_builder.setRenderMonitor(_pRenderMonitor);
	blenderScene->accept(wx_builder);
	_winged_edge = wx_builder.getWingedEdge();

	duration = _Chrono.stop();
	if (G.debug & G_DEBUG_FREESTYLE) {
		printf("WEdge building   : %lf\n", duration);
	}

#if 0
	_pView->setDebug(_DebugNode);

	// delete stuff
	if (0 != ws_builder) {
		delete ws_builder;
		ws_builder = 0;
	}

	soc QFileInfo qfi(iFileName);
	soc string basename((const char*)qfi.fileName().toAscii().data());
	char cleaned[FILE_MAX];
	BLI_strncpy(cleaned, iFileName, FILE_MAX);
	BLI_cleanup_file(NULL, cleaned);
	string basename = string(cleaned);
#endif

	_ListOfModels.push_back("Blender_models");

	_Scene3dBBox = _RootNode->bbox();

	_bboxDiag = (_RootNode->bbox().getMax() - _RootNode->bbox().getMin()).norm();
	if (G.debug & G_DEBUG_FREESTYLE) {
		cout << "Triangles nb     : " << _SceneNumFaces << " imported, " <<
		        _winged_edge->getNumFaces() << " retained" << endl;
		cout << "Bounding Box     : " << _bboxDiag << endl;
	}

	ClearRootNode();

	_SceneNumFaces = _winged_edge->getNumFaces();
	if (_SceneNumFaces == 0) {
		DeleteWingedEdge();
		return 1;
	}

	return 0;
}
bool ScImgDataLoader_JPEG::loadPicture(const QString& fn, int /*page*/, int res, bool thumbnail)
{
	bool isCMYK = false;
	bool fromPS = false;
	float xres = 72.0, yres = 72.0;
	if (!QFile::exists(fn))
		return false;
	ExifData ExifInf;
	struct jpeg_decompress_struct cinfo;
	struct my_error_mgr         jerr;
	FILE     *infile;
	cinfo.err = jpeg_std_error (&jerr.pub);
	jerr.pub.error_exit = my_error_exit;
	infile = NULL;

	initialize();
	m_imageInfoRecord.type = ImageTypeJPG;
	m_imageInfoRecord.exifInfo.thumbnail = QImage();
	if (setjmp (jerr.setjmp_buffer))
	{
		jpeg_destroy_decompress (&cinfo);
		if (infile)
			fclose (infile);
		return false;
	}
	jpeg_create_decompress (&cinfo);
	if ((infile = fopen (fn.toLocal8Bit(), "rb")) == NULL)
		return false;
	jpeg_stdio_src(&cinfo, infile);
	jpeg_save_markers(&cinfo, ICC_MARKER, 0xFFFF);
	jpeg_save_markers(&cinfo, PHOTOSHOP_MARKER, 0xFFFF);
	jpeg_read_header(&cinfo, true);
	jpeg_start_decompress(&cinfo);
	bool exi = ExifInf.scan(fn);
	if ((exi) && (ExifInf.exifDataValid))
	{
		if (cinfo.output_components == 4)
			m_imageInfoRecord.colorspace = ColorSpaceCMYK;
		else if (cinfo.output_components == 3)
			m_imageInfoRecord.colorspace = ColorSpaceRGB;
		else if (cinfo.output_components == 1)
			m_imageInfoRecord.colorspace = ColorSpaceGray;
		if ((!ExifInf.Thumbnail.isNull()) && thumbnail)
		{
			m_image = ExifInf.getThumbnail();
			m_imageInfoRecord.exifInfo.thumbnail = ExifInf.getThumbnail();
			if (cinfo.output_components == 4)
			{
				QRgb *s;
				unsigned char cc, cm, cy, ck;
				for( int yit=0; yit < m_image.height(); ++yit )
				{
					s = (QRgb*)(m_image.scanLine( yit ));
					for(int xit=0; xit < m_image.width(); ++xit )
					{
						cc = 255 - qRed(*s);
						cm = 255 - qGreen(*s);
						cy = 255 - qBlue(*s);
						ck = qMin(qMin(cc, cm), cy);
						*s = qRgba(cc-ck,cm-ck,cy-ck,ck);
						s++;
					}
				}
			}
		}
		else
			m_imageInfoRecord.exifInfo.thumbnail = QImage();
		m_imageInfoRecord.exifInfo.cameraName = ExifInf.getCameraModel();
		m_imageInfoRecord.exifInfo.cameraVendor = ExifInf.getCameraMake();
		m_imageInfoRecord.exifInfo.comment = ExifInf.getComment();
		m_imageInfoRecord.exifInfo.width = ExifInf.getWidth();
		m_imageInfoRecord.exifInfo.height = ExifInf.getHeight();
		m_imageInfoRecord.exifInfo.userComment = ExifInf.getUserComment();
		m_imageInfoRecord.exifInfo.dateTime = ExifInf.getDateTime();
		m_imageInfoRecord.exifInfo.ApertureFNumber = ExifInf.getApertureFNumber();
		m_imageInfoRecord.exifInfo.ExposureTime = ExifInf.getExposureTime();
		m_imageInfoRecord.exifInfo.ISOequivalent = ExifInf.getISOequivalent();
		m_imageInfoRecord.exifDataValid = true;
		if (cinfo.density_unit == 0)
		{
			xres = 72;
			yres = 72;
		}
		else if ( cinfo.density_unit == 1 )
		{
			xres = cinfo.X_density;
			yres = cinfo.Y_density;
		}
		else if ( cinfo.density_unit == 2 )
		{
			xres = cinfo.X_density * 2.54;
			yres = cinfo.Y_density * 2.54;
		}
		if( xres <= 1.0 || yres <= 1.0 || xres > 3000.0 || yres > 3000.0 )
		{
			xres = yres = 72.0;
			QFileInfo qfi(fn);
			m_message = QObject::tr("%1 may be corrupted : missing or wrong resolution tags").arg(qfi.fileName());
			m_msgType = warningMsg;
		}
		m_imageInfoRecord.xres = qRound(xres);
		m_imageInfoRecord.yres = qRound(yres);
		m_imageInfoRecord.progressive = jpeg_has_multiple_scans(&cinfo);
		if ((!ExifInf.Thumbnail.isNull()) && thumbnail)
		{
			jpeg_destroy_decompress(&cinfo);
			fclose(infile);
			return true;
		}
	}
	else
		m_imageInfoRecord.exifDataValid = false;
	m_imageInfoRecord.exifInfo.thumbnail = QImage();
	unsigned int EmbedLen = 0;
	unsigned char* EmbedBuffer;
	if (read_jpeg_marker(ICC_MARKER,&cinfo, &EmbedBuffer, &EmbedLen))
	{
		QByteArray profArray = QByteArray((const char*) EmbedBuffer, EmbedLen);
		ScColorProfile prof = ScColorMgmtEngine::openProfileFromMem(profArray);
		m_embeddedProfile   = profArray;
		m_imageInfoRecord.profileName = prof.productDescription();
		m_imageInfoRecord.isEmbedded  = true;
		free(EmbedBuffer);
	}
	else
	{
		m_imageInfoRecord.isEmbedded = false;
		m_imageInfoRecord.profileName = "";
	}
	unsigned int PhotoshopLen = 0;
	unsigned char * PhotoshopBuffer;
	if (cinfo.density_unit == 0)
	{
		xres = 72;
		yres = 72;
		m_image.setDotsPerMeterX(2834);
		m_image.setDotsPerMeterY(2834);
	}
	else if ( cinfo.density_unit == 1 )
	{
		xres = cinfo.X_density;
		yres = cinfo.Y_density;
		m_image.setDotsPerMeterX( int(100. * cinfo.X_density / 2.54) );
		m_image.setDotsPerMeterY( int(100. * cinfo.Y_density / 2.54) );
	}
	else if ( cinfo.density_unit == 2 )
	{
		xres = cinfo.X_density * 2.54;
		yres = cinfo.Y_density * 2.54;
		m_image.setDotsPerMeterX( int(100. * cinfo.X_density) );
		m_image.setDotsPerMeterY( int(100. * cinfo.Y_density) );
	}
	if( xres <= 1.0 || yres <= 1.0 || xres > 3000.0 || yres > 3000.0 )
	{
		xres = yres = 72.0;
		m_image.setDotsPerMeterX(2834);
		m_image.setDotsPerMeterY(2834);
		QFileInfo qfi(fn);
		m_message = QObject::tr("%1 may be corrupted : missing or wrong resolution tags").arg(qfi.fileName());
		m_msgType = warningMsg;
	}
	m_imageInfoRecord.xres = qRound(xres);
	m_imageInfoRecord.yres = qRound(yres);
	if (cinfo.output_components == 4)
	{
		isCMYK = true;
		m_imageInfoRecord.colorspace = ColorSpaceCMYK;
	}
	else if (cinfo.output_components == 3)
		m_imageInfoRecord.colorspace = ColorSpaceRGB;
	else if (cinfo.output_components == 1)
		m_imageInfoRecord.colorspace = ColorSpaceGray;
	m_imageInfoRecord.progressive = jpeg_has_multiple_scans(&cinfo);

	if (read_jpeg_marker(PHOTOSHOP_MARKER,&cinfo, &PhotoshopBuffer, &PhotoshopLen) )
	{
		if (PhotoshopLen != 0)
		{
			bool savEx = m_imageInfoRecord.exifDataValid;
			QByteArray arrayPhot(PhotoshopLen, ' ');
			arrayPhot = QByteArray::fromRawData((const char*)PhotoshopBuffer,PhotoshopLen);
			QDataStream strPhot(&arrayPhot,QIODevice::ReadOnly);
			strPhot.setByteOrder( QDataStream::BigEndian );
			PSDHeader fakeHeader;
			fakeHeader.width = cinfo.output_width;
			fakeHeader.height = cinfo.output_height;
			if (cinfo.output_components == 4)
				m_imageInfoRecord.colorspace = ColorSpaceCMYK;
			else if (cinfo.output_components == 3)
				m_imageInfoRecord.colorspace = ColorSpaceRGB;
			else if (cinfo.output_components == 1)
				m_imageInfoRecord.colorspace = ColorSpaceGray;
			m_imageInfoRecord.progressive = jpeg_has_multiple_scans(&cinfo);
			parseRessourceData(strPhot, fakeHeader, PhotoshopLen);
			// Photoshop resolution is more accurate than jpeg header resolution
			xres = m_imageInfoRecord.xres;
			yres = m_imageInfoRecord.yres;
			m_image.setDotsPerMeterX( int(100. * m_imageInfoRecord.xres / 2.54) );
			m_image.setDotsPerMeterY( int(100. * m_imageInfoRecord.yres / 2.54) );
			if( xres <= 1.0 || yres <= 1.0 || xres > 3000.0 || yres > 3000.0 )
			{
				xres = yres = 72.0;
				m_imageInfoRecord.xres = qRound(xres);
				m_imageInfoRecord.yres = qRound(yres);
				m_image.setDotsPerMeterX(2834);
				m_image.setDotsPerMeterY(2834);
				QFileInfo qfi(fn);
				m_message = QObject::tr("%1 may be corrupted : missing or wrong resolution tags").arg(qfi.fileName());
				m_msgType = warningMsg;
			}
			if (m_imageInfoRecord.exifDataValid && !m_imageInfoRecord.exifInfo.thumbnail.isNull() && thumbnail)
			{
				m_image = QImage(m_imageInfoRecord.exifInfo.width, m_imageInfoRecord.exifInfo.height, QImage::Format_ARGB32 );
				m_imageInfoRecord.exifInfo.width = cinfo.output_width;
				m_imageInfoRecord.exifInfo.height = cinfo.output_height;
				if (cinfo.output_components == 4)
				{
					QRgb *d;
					QRgb *s;
					unsigned char cc, cm, cy, ck;
					for( int yit=0; yit < m_image.height(); ++yit )
					{
						d = (QRgb*)(m_image.scanLine( yit ));
						s = (QRgb*)(m_imageInfoRecord.exifInfo.thumbnail.scanLine( yit ));
						for(int xit=0; xit < m_image.width(); ++xit )
						{
							cc = 255 - qRed(*s);
							cm = 255 - qGreen(*s);
							cy = 255 - qBlue(*s);
							ck = qMin(qMin(cc, cm), cy);
							*d = qRgba(cc-ck,cm-ck,cy-ck,ck);
							s++;
							d++;
						}
					}
				}
				else
					m_image = m_imageInfoRecord.exifInfo.thumbnail.copy();
			}
			m_imageInfoRecord.valid = (m_imageInfoRecord.PDSpathData.size())>0?true:false; // The only interest is vectormask
			arrayPhot.clear();
			free( PhotoshopBuffer );
			if (m_imageInfoRecord.exifDataValid && !m_imageInfoRecord.exifInfo.thumbnail.isNull() && thumbnail)
			{
				jpeg_destroy_decompress(&cinfo);
				fclose(infile);
				return true;
			}
			m_imageInfoRecord.exifInfo.thumbnail = QImage();
			m_imageInfoRecord.exifDataValid = savEx;
			fromPS = true;
		}
	}
	if ( cinfo.output_components == 3 || cinfo.output_components == 4)
		m_image = QImage( cinfo.output_width, cinfo.output_height, QImage::Format_ARGB32 );
	else if ( cinfo.output_components == 1 )
	{
		m_image = QImage( cinfo.output_width, cinfo.output_height, QImage::Format_Indexed8 );
		m_image.setNumColors(256);
		for (int i=0; i<256; i++)
			m_image.setColor(i, qRgb(i,i,i));
	}
	if (!m_image.isNull())
	{
		uchar* data = m_image.bits();
		int bpl = m_image.bytesPerLine();
		while (cinfo.output_scanline < cinfo.output_height)
		{
			uchar *d = data + cinfo.output_scanline * bpl;
			(void) jpeg_read_scanlines(&cinfo, &d, 1);
		}
		if ( cinfo.output_components == 3 )
		{
			uchar *in;
			QRgb *out;
			for (uint j=0; j<cinfo.output_height; j++)
			{
				in = m_image.scanLine(j) + cinfo.output_width * 3;
				out = (QRgb*) m_image.scanLine(j);
				for (uint i=cinfo.output_width; i--; )
				{
					in -= 3;
					out[i] = qRgb(in[0], in[1], in[2]);
				}
			}
		}
		if ( cinfo.output_components == 4 )
		{
			int method = 0;
			if (cinfo.jpeg_color_space == JCS_YCCK)
				method = 1;
			else if (fromPS)
			{
				if ((cinfo.jpeg_color_space == JCS_CMYK) && (cinfo.saw_Adobe_marker) && (cinfo.Adobe_transform == 0))
					method = 2;
			}
			else if ((cinfo.jpeg_color_space == JCS_CMYK) && (cinfo.saw_Adobe_marker))
				method = 1;
			QRgb *ptr;
			unsigned char c, m, y ,k;
			unsigned char *p;
			for (int i = 0; i < m_image.height(); i++)
			{
				ptr = (QRgb*)  m_image.scanLine(i);
				if (method == 1)
				{
					for (int j = 0; j <  m_image.width(); j++)
					{
						p = (unsigned char *) ptr;
						c = p[0];
						m = p[1];
						y =  p[2];
						k =  p[3];
						*ptr = qRgba(255 - c, 255 - m, 255 - y, 255 - k);
						ptr++;
					}
				}
				else if (method == 2)
				{
					for (int j = 0; j <  m_image.width(); j++)
					{
						p = (unsigned char *) ptr;
						c = p[0];
						m = p[1];
						y =  p[2];
						k =  p[3];
						*ptr = qRgba(255 - c, 255 - m, 255 - y, k);
						ptr++;
					}
				}
				else
				{
					for (int j = 0; j <  m_image.width(); j++)
					{
						p = (unsigned char *) ptr;
						c = p[0];
						m = p[1];
						y =  p[2];
						k =  p[3];
						*ptr = qRgba(y, m, c, k);
						ptr++;
					}
				}
			}
			isCMYK = true;
		}
		else
			isCMYK = false;
		if ( cinfo.output_components == 1 )
		{
			QImage tmpImg = m_image.convertToFormat(QImage::Format_ARGB32);
			m_image = QImage( cinfo.output_width, cinfo.output_height, QImage::Format_ARGB32 );
			QRgb *s;
			QRgb *d;
			for( int yi=0; yi < tmpImg.height(); ++yi )
			{
				s = (QRgb*)(tmpImg.scanLine( yi ));
				d = (QRgb*)(m_image.scanLine( yi ));
				for(int xi=0; xi < tmpImg.width(); ++xi )
				{
					(*d) = (*s);
					s++;
					d++;
				}
			}
		}
	}
	(void) jpeg_finish_decompress(&cinfo);
	fclose (infile);
	jpeg_destroy_decompress (&cinfo);
	m_imageInfoRecord.layerInfo.clear();
	m_imageInfoRecord.BBoxX = 0;
	m_imageInfoRecord.BBoxH = m_image.height();
	return (!m_image.isNull());
}
Beispiel #19
0
int Controller::LoadMesh(Render *re, SceneRenderLayer *srl)
{
	BlenderFileLoader loader(re, srl);

	loader.setRenderMonitor(_pRenderMonitor);

	_Chrono.start();

	NodeGroup *blenderScene = loader.Load();

	if (blenderScene == NULL) {
		if (G.debug & G_DEBUG_FREESTYLE) {
			cout << "Cannot load scene" << endl;
		}
		return 1;
	}

	if (blenderScene->numberOfChildren() < 1) {
		if (G.debug & G_DEBUG_FREESTYLE) {
			cout << "Empty scene" << endl;
		}
		blenderScene->destroy();
		delete blenderScene;
		return 1;
	}

	real duration = _Chrono.stop();
	if (G.debug & G_DEBUG_FREESTYLE) {
		cout << "Scene loaded" << endl;
		printf("Mesh cleaning    : %lf\n", duration);
	}
	_SceneNumFaces += loader.numFacesRead();

	if (loader.minEdgeSize() < _minEdgeSize) {
		_minEdgeSize = loader.minEdgeSize();
	}

#if 0  // DEBUG
	ScenePrettyPrinter spp;
	blenderScene->accept(spp);
#endif

	_RootNode->AddChild(blenderScene);
	_RootNode->UpdateBBox(); // FIXME: Correct that by making a Renderer to compute the bbox

	_pView->setModel(_RootNode);
	//_pView->FitBBox();

	if (_pRenderMonitor->testBreak())
		return 0;

	_Chrono.start();

	WXEdgeBuilder wx_builder;
	wx_builder.setRenderMonitor(_pRenderMonitor);
	blenderScene->accept(wx_builder);
	_winged_edge = wx_builder.getWingedEdge();

	duration = _Chrono.stop();
	if (G.debug & G_DEBUG_FREESTYLE) {
		printf("WEdge building   : %lf\n", duration);
	}

#if 0
	_pView->setDebug(_DebugNode);

	// delete stuff
	if (0 != ws_builder) {
		delete ws_builder;
		ws_builder = 0;
	}

	soc QFileInfo qfi(iFileName);
	soc string basename((const char*)qfi.fileName().toAscii().data());
	char cleaned[FILE_MAX];
	BLI_strncpy(cleaned, iFileName, FILE_MAX);
	BLI_cleanup_file(NULL, cleaned);
	string basename = string(cleaned);
#endif

	_ListOfModels.push_back("Blender_models");

	_Scene3dBBox = _RootNode->bbox();

	_bboxDiag = (_RootNode->bbox().getMax() - _RootNode->bbox().getMin()).norm();
	if (G.debug & G_DEBUG_FREESTYLE) {
		cout << "Triangles nb     : " << _SceneNumFaces << endl;
		cout << "Bounding Box     : " << _bboxDiag << endl;
	}

	ClearRootNode();

	return 0;
}
Beispiel #20
0
void ControlWidget::handleSatellite( const QByteArray &msg )
{
   QStringList src( Satellite::split( msg ) );

   if( src.size() > 0 )
   {
      if( src.at(0) == "P0Q" )
      {
         QStringList dest;

         /* convert from url to filename if necessary */
         for( int i = 1; i < src.size(); i++ )
         {
            QFileInfo qfi( src.at(i) );
            if( qfi.isFile() )
            {
               dest << qfi.absoluteFilePath();
            }
         }

         if( dest.size() > 0 )
         {
            emit requestAddToPlaylist( dest, false );
         }
      }

      else if( src.at(0) == "P0A" )
      {
         if( mConnected )
         {
            if( mPaused || !mKioskMode )
            {
               handlePause();
            }
         }
         else
         {
            initConnect();
         }
      }

      else if( src.at(0) == "P0N" )
      {
         handleSkipTrack();
      }

      else if( src.at(0) == "P0S" )
      {
         if( !mKioskMode )
         {
            initDisconnect();
         }
      }

      else if( src.at(0) == "P0R" )
      {
         if( mpSatellite && !mLastP0p.isEmpty() )
         {
            mpSatellite->send( mLastP0p );
         }
      }

      else if( src.at(0) == "P0C" )
      {
         bool favorite = false;
         bool unwanted = false;
         if( src.size() > 1 )
         {
            switch( src.at(1).toUInt() )
            {
               case 1:
                  favorite = true;
                  break;
               case 2:
                  unwanted = true;
                  break;
               default:
                  break;
            }
            mpPlaylist->setTrackInfoFavoriteUnwanted( favorite, unwanted );
         }
      }

      else if( src.at(0) == "P0T" )
      {
         if( src.size() > 1 )
         {
            emit requestTab( src.at(1) );
         }
      }

      else if( (src.at(0) == "k0u") ||
               (src.at(0) == "r0u") )
      {
         emit trackUpdate();
      }

      else if( src.at(0) == "u0p" )
      {
         if( Settings::value( Settings::PartymanStopOnUnderpassStart ) && !mKioskMode )
         {
            initDisconnect();
         }
      }
   }
}
// void test() {
//  
//     aligned_buffer<short> a(16);
//     aligned_buffer<short> b(16);
//     aligned_buffer<short> c(16);
//     
//     std::fill( a.begin(), a.end(), 1 );
//     std::fill( b.begin(), b.end(), 2 );
//     a.m_ptr[0] = 2;
//     
//     typedef vector_unit<short,16> vu;
//     
//     vu::vec_t av = vu::load(a.m_ptr);
//     vu::vec_t bv = vu::load(b.m_ptr);
//     
//     vu::store( vu::cmp_lt(av,bv), c.m_ptr );
//     
//     for( int i = 0; i < c.size(); i++ ) {
//      
//         std::cout << i << ": " << c.m_ptr[i] << "\n";
//     }
//     
// }
int main( int argc, char *argv[] ) {
//     test();
//     return 0;
    
    
    seqs sq;
    seqs sd;
    
   // typedef mapped_file file_input;
    typedef std::ifstream file_input;
    
    if( argc != 6 ) {
     
        throw std::runtime_error( "missing parameters. expect: <open> <ext> <query.fa> <db.fa> <matrix>" );
        
    }
    
    const int gap_open = atoi( argv[1] );
    const int gap_extend = atoi( argv[2] );
    
    //std::cout << "gap: " <<

    std::ifstream ism( argv[5] );
    scoring_matrix sm( ism );
    
    file_input qfi( argv[3] );
    inc_fasta<file_input, scoring_matrix> qfasta( qfi, sm );
    
    file_input dfi( argv[4] );
    inc_fasta<file_input, scoring_matrix> dfasta( dfi, sm );
        
        
    
    
    
    
//     for( int i = 0 ; i < sd.names.size(); i++ ) {
//         int sc = align<int>( sd.data[i], sq.data[0], sm );
//         std::cout << sc << "\t" << sd.names[i] << "\n";
//     }
    
    
#if 0
    const int W = 8;
    typedef short score_t;
    typedef short sscore_t;
#else
    const int W = 16;
    typedef unsigned char score_t;
    typedef char sscore_t;
#endif
    persistent_state<score_t> ps;
//     size_t db_size = (sd.names.size() / W ) * W;
    
#ifndef LOCAL_ALIGN
#define PAD_FRONT  
#endif
    
    typedef uint8_t seq_char_t;
    
    std::string dname[W];
    std::vector<seq_char_t> ddata[W];
//     size_t dpad[W];
    aligned_buffer<seq_char_t> ddata_int;
    
//     std::vector<score_t> dmask[W];
    
    std::string qname;
    std::vector<seq_char_t> qdata;
    
    bool have_input = true;
    size_t n_qseq = 0;
    size_t n_qchar = 0;
    
    size_t n_dseq = 0;
    size_t n_dchar = 0;
    
    bool first_block = true;
    while( have_input ) {
        
        size_t maxlen = 0;
        
        int lj = -1;
        
        // determine db sequences for the current block
        
        for( int j = 0; j < W; j++ ) {
            dname[j].resize(0);
            ddata[j].resize(0);
            have_input = dfasta.next_seq( dname[j], ddata[j] );
            
            
            // if there aren't enough db sequences left to fill the block, pad with last db sequence
            if( !have_input ) {
                
                // break immediately if there are no db sequences left (means #db-seqs % W == 0, or otherwise have_input would have been == false from last iteration)
                if( j == 0 ) {
                    break;
                } else {
                    dname[j] = dname[lj];
                    ddata[j] = ddata[lj];
                }
            } else {
                n_dseq++;
                n_dchar += ddata[j].size();
                lj = j; // store largest valid 'j'
                
//                 for( int i = 0; i < ddata[j].length(); i++ ) {
//                         
//                     ddata[j][i] = sm.state_backmap(ddata[j][i]);
//                 }
            }
            
//             dmask[j].clear();
//             dmask[j].resize(ddata[j].length(), 0xffff );
            
            
            maxlen = std::max( maxlen, ddata[j].size() );
        }
        
        // jf == -1 at this point means that the block is empty (#db-seqs % W == 0)
        if( lj == -1 ) {
            break;
        }
        
        
        // WARNING: front-padding is currently defunct
#ifdef PAD_FRONT
        for( int j = 0; j < W; j++ ) {
            dpad[j] = maxlen - ddata[j].size();
        }
#endif

        // lj == -1 means that there are no remaining sequences
        
        
        
//         std::cout << "sdis: " << sdi.size() << "\n";
        aligned_buffer<sscore_t> qprofile( maxlen * W * sm.num_states());
        aligned_buffer<sscore_t>::iterator qpi = qprofile.begin();
#if 0
        for( int j = 0; j < sm.num_states(); j++ ) {
            const int jstate = sm.get_state(j);
//             const scoring_matrix::score_t *slice = sm.get_slice(jstate);
            const scoring_matrix::score_t *cslice = sm.get_cslice(j);
            for( int k = 0; k < maxlen; k++ ) {
                for( int l = 0; l < W; l++ ) {
                    
                    
                    std::vector<seq_char_t> &sdi = ddata[l];
                    
                    
#ifdef PAD_FRONT
                    const size_t frontpad = dpad[l];//maxlen - sdi.size();

                    //if( k < sdi.size() ) {
                    if( k >= frontpad )  {
                        //*qpi = sm.get_score( sdi[k], jstate);
                        *qpi = cslice[sdi[k - frontpad]];
#else
                    if( k < sdi.size() ) {
//                         *qpi = slice[sdi[k]];
                        
                        *qpi = cslice[sdi[k]];
#endif
                    } else {
                        *qpi = 0;   
                    }
//                     std::cout << "prof: " << (qpi - qprofile.begin() ) << " " << *qpi << " " << int(j) << " " << char(sm.get_state(j)) << " " << sdi[k] << "\n";
                    qpi++;
                }
            }
        }
#else
        // setup the qprofile (= lookup table for match penalties along the db-sequences in the current block)
        // this is the faster (at least on core i5) two-step version, using interleaved db-sequences
        
        // setup buffer for interleaved db sequences
        if( ddata_int.size() < maxlen * W ) {
            ddata_int.resize(maxlen * W);
        }
 
        // copy individual db sequences into interleaved buffer (padding the shorter sequnences 
        aligned_buffer<seq_char_t>::iterator dint_iter = ddata_int.begin();
        const int zero_state = sm.get_zero_state();
        for( size_t i = 0; i < maxlen; i++ ) {
            for( int j = 0; j < W; j++ ) {
                std::vector<seq_char_t> &sdi = ddata[j];
                if( i < sdi.size() ) {
                    *dint_iter = sdi[i];

                } else {
                    *dint_iter = zero_state;   
                }
                ++dint_iter;
            }
        }
        for( size_t j = 0; j < sm.num_states(); j++ ) {
            dint_iter = ddata_int.begin();
            const char *cslice = sm.get_cslice(j);
            for( size_t k = 0; k < maxlen; k++ ) {
                for( int l = 0; l < W; l++ ) {
//                     if( *dint_iter == zero_state ) {
//                         std::cout << int(cslice[*dint_iter]) << "\n";
//                        
//                     }
                    
                    *qpi = cslice[*dint_iter];
                    ++dint_iter;
                    ++qpi;
                }
            }
        }
#endif
//         std::cout << "sdis2: " << sdi.size() << std::endl;
//         aligned_buffer<short> dv(sdi.size() * W);
//         short *dv_iter = dv.begin();
//         
//         for( int j = 0; j < sdi.size(); j++ ) {
//                 
//             for( int k = 0; k < W; k++ ) {
//                 *dv_iter = sdi[j];
//                 dv_iter++;
//             }
//             
//         }
        
        
//         aligned_buffer<score_t> len(W);
//         for( int j = 0; j < W; j++ ) {
//             len.m_ptr[j] = sd.data[i + j].size();
//         }
        
        std::vector<int> out(W);
        
        qfasta.reset();
        
        while( qfasta.next_seq( qname, qdata )) {
            if( first_block ) {
                n_qseq++;
                n_qchar+=qdata.size();
            }
            
            align_vec<score_t,sscore_t,W>( ps, maxlen, qdata, sm, qprofile, gap_open, gap_extend, out );
        
            for( int j = 0; j <= lj; j++ ) {
//                 std::cout << out[j] << "\t" << dname[j] << " " << qname << " " << ddata[j].size() << "\n";
                std::cout << out[j] << "\t" << dname[j] << "\n";
            }
            qname.resize(0);
            qdata.resize(0);
            
        }
        first_block = false;
    }
    
    std::cerr << n_qseq << "[" << n_qchar << "] x " << n_dseq << "[" << n_dchar << "]\n";
}
Beispiel #22
0
int
main( int argc, char** argv )
{
	QApplication app( argc, argv );
	QTranslator qtr( 0 );
	QTranslator qtr2( 0 );

	// Set our working directory

#ifdef _WIN32
	QString datadir = QString::fromLocal8Bit(qgetenv("APPDATA").constData());
	QDir dir(datadir);
	dir.mkdir("Image Splitter");
	datadir = MakePath(datadir, "Image Splitter");
	gDataDir = datadir;
#ifdef _DEBUG
	WString wdatadir(datadir);
	qDebug("Data directory: %ls", wdatadir.getBuffer());
#endif
	gAppDir = QDir::toNativeSeparators(app.applicationDirPath());
	// Set our working directory
	QDir::setCurrent(datadir);
#endif

	// Load language file
	QString langfile;
#ifndef _WIN32
	langfile = "isplitter.lng";
	// Set our working directory
	SetWorkingDirectory(argv[0]);
	gAppDir = QDir::currentPath();
#else
	langfile = MakePath(gDataDir, "isplitter.lng");
#endif
	QFile lang(langfile);
	QString lfile;
	QString ldir = MakePath(gAppDir, "translations");
	QDir ld(ldir);
	// Try to find directory containing translation files
	if (!ld.exists())
	{
		ld.cdUp();
		// If there is no "translations" sub-directory, check the directory containing the executable
		if (ld.exists("isplitter_en.qm"))
		{
			ldir = gAppDir;
		}
		else
		{
			// ... then try its parent directory, for example if we are running from Visual Studio
			ld.cdUp();
			if (ld.exists("isplitter_en.qm"))
			{
				ldir = QDir::toNativeSeparators(ld.absolutePath());
			}
		}
	}

	if (!lang.exists())
	{
NoTranslation:
		lfile = QFileDialog::getOpenFileName(NULL, app.translate("main", "Open translation file..."), ldir, "isplitter_*.qm");
		// Save selected language's translator filename
		if (!lfile.isEmpty() && lang.open(QIODevice::WriteOnly) )
		{
			QByteArray clang = lfile.toUtf8();
			lang.write(clang);
			lang.close();
		}
	}

	// (Re-)load translator filename
	if ( lang.open(QIODevice::ReadOnly) )
	{
		// file opened successfully
		QByteArray plang = lang.readLine();
		lfile = QString::fromUtf8(plang);
		lang.close();
	}

	// Install translator ;)
	if (!lfile.isEmpty() && QFile::exists(lfile) && qtr.load(lfile))
		app.installTranslator(&qtr);
	else
		goto NoTranslation;

	// Qt's own translator file
	QFileInfo qfi(lfile);
	QString qt_lang = QString::null;
	QString qtdir = QString::fromLocal8Bit(qgetenv("QTDIR").constData());
	langfile = qfi.fileName().replace(QRegExp("isplitter"), "qt");

	if (qtdir != QString::null)
	{
		QString tr_dir = MakePath(qtdir, "translations");
		qt_lang = MakePath(tr_dir, langfile);
		if (!QFile::exists(qt_lang))
			qt_lang = QString::null;
	}

	// Try using same directory as Image Splitter's translations
	if (qt_lang == QString::null)
	{
		qt_lang = MakePath(qfi.absolutePath(), langfile);
	}

	if (QFile::exists(qt_lang) && qtr2.load(qt_lang))
	{
		app.installTranslator( &qtr2 );
	}

	ImageSplitter * window = new ImageSplitter(NULL);
	Q_CHECK_PTR(window);

	window->show();

	if (app.arguments().count() > 1)
		window->Load(app.arguments().at(1));

	return app.exec();
}