Ejemplo n.º 1
0
TasksDialog::TasksDialog(DialogAction action, ObjectActionList fileNamesActions, QWidget *parent) :
    QDialog(parent),
    m_fileNamesActions(fileNamesActions),
    m_taskListReceived(false),
    m_currentAction(action),
    m_chosenTask(QLatin1String("")),
    ui(new Ui::TasksDialog),
    m_pendingActions(0)
{
    ui->setupUi(this);
    ui->stackedWidget->setCurrentIndex(1);

    connect(this, SIGNAL(setConnectionDialogVisibility(bool)),
            SynergyPlugin::instance(), SLOT(setConnectionDialogVisibilitySlot(bool)));

    connect(ui->cancelButton, SIGNAL(clicked()), this, SLOT(reject()));

    if (m_currentAction == Show || m_currentAction == Indicate)
        connect(ui->okButton, SIGNAL(clicked()), this, SLOT(accept()));
    else
        connect(ui->okButton, SIGNAL(clicked()), this, SLOT(addObjectsToTask()));

    connect(ui->newTaskButton, SIGNAL(clicked()), this, SLOT(startTaskWizard()));

    connect(ui->treeWidget, SIGNAL(customContextMenuRequested(QPoint)),
            this, SLOT(openContextMenu(QPoint)));
    connect(ui->treeWidget, SIGNAL(itemExpanded(QTreeWidgetItem*)),
            this, SLOT(itemExpandedSlot(QTreeWidgetItem*)));
    connect(ui->treeWidget, SIGNAL(itemClicked(QTreeWidgetItem*,int)),
            this, SLOT(itemClicked(QTreeWidgetItem*)));

    // Disable OK button if Action == Indicate
    if (Indicate == m_currentAction)
        ui->okButton->setEnabled(false);

    if (! fileNamesActions.isEmpty())
    {
        const QFileInfo fi(fileNamesActions.first().first);
        m_workingDir = fi.absolutePath();
        setWindowTitle(fi.fileName());
    }
    else
    {
        m_workingDir = QLatin1String("C:\\");
    }

    ui->treeWidget->setContextMenuPolicy(Qt::CustomContextMenu);
    ui->treeWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);
//    ui->treeWidget->setDragEnabled(true);

    emit setConnectionDialogVisibility(true);

    if (!SynergyPlugin::instance()->isSynergyStarted())
    {
        WorkerThreadPair workerThread = SynergyPlugin::instance()->startSynergyAsync(m_workingDir);
        connect(workerThread.first, SIGNAL(resultDownloaded(SynergyResponse)),
                this, SLOT(refreshTaskList()));
    }
    else
    {
        refreshTaskList();
    }
}
Ejemplo n.º 2
0
bool XfigPlug::import(QString fNameIn, const TransactionSettings& trSettings, int flags, bool showProgress)
{
	QString fName = fNameIn;
	bool success = false;
	interactive = (flags & LoadSavePlugin::lfInteractive);
	importerFlags = flags;
	cancel = false;
	double x, y, b, h;
	bool ret = false;
	CustColors.clear();
	importedColors.insert(0, "Black");
	importedColors.insert(1, "Blue");
	importedColors.insert(2, "Green");
	importedColors.insert(3, "Cyan");
	importedColors.insert(4, "Red");
	importedColors.insert(5, "Magenta");
	importedColors.insert(6, "Yellow");
	importedColors.insert(7, "White");
	importedColors.insert(8, "Blue4");
	importedColors.insert(9, "Blue3");
	importedColors.insert(10, "Blue2");
	importedColors.insert(11, "LtBlue");
	importedColors.insert(12, "Green4");
	importedColors.insert(13, "Green3");
	importedColors.insert(14, "Green2");
	importedColors.insert(15, "Cyan4");
	importedColors.insert(16, "Cyan3");
	importedColors.insert(17, "Cyan2");
	importedColors.insert(18, "Red4");
	importedColors.insert(19, "Red3");
	importedColors.insert(20, "Red2");
	importedColors.insert(21, "Magenta4");
	importedColors.insert(22, "Magenta3");
	importedColors.insert(23, "Magenta2");
	importedColors.insert(24, "Brown4");
	importedColors.insert(25, "Brown3");
	importedColors.insert(26, "Brown2");
	importedColors.insert(27, "Pink4");
	importedColors.insert(28, "Pink3");
	importedColors.insert(29, "Pink2");
	importedColors.insert(30, "Pink");
	importedColors.insert(31, "Gold");
	CustColors.insert("Blue", ScColor(255, 0, 0, 0));
	CustColors.insert("Blue4", ScColor(0, 0, 144));
	CustColors.insert("Blue3", ScColor(0, 0, 176));
	CustColors.insert("Blue2", ScColor(0, 0, 208));
	CustColors.insert("LtBlue", ScColor(135, 206, 255));
	CustColors.insert("Cyan", ScColor(255, 0, 0, 0));
	CustColors.insert("Cyan4", ScColor(0, 144, 144));
	CustColors.insert("Cyan3", ScColor(0, 176, 176));
	CustColors.insert("Cyan2", ScColor(0, 208, 208));
	CustColors.insert("Green", ScColor(255, 0, 255, 0));
	CustColors.insert("Green4", ScColor(0, 144, 0));
	CustColors.insert("Green3", ScColor(0, 176, 0));
	CustColors.insert("Green2", ScColor(0, 208, 0));
	CustColors.insert("Red", ScColor(0, 255, 255, 0));
	CustColors.insert("Red4", ScColor(144, 0, 0));
	CustColors.insert("Red3", ScColor(176, 0, 0));
	CustColors.insert("Red2", ScColor(208, 0, 0));
	CustColors.insert("Yellow", ScColor(0, 0, 255, 0));
	CustColors.insert("Magenta", ScColor(0, 255, 0, 0));
	CustColors.insert("Magenta4", ScColor(144, 0, 144));
	CustColors.insert("Magenta3", ScColor(176, 0, 176));
	CustColors.insert("Magenta2", ScColor(208, 0, 208));
	CustColors.insert("Brown4", ScColor(128, 48, 0));
	CustColors.insert("Brown3", ScColor(160, 64, 0));
	CustColors.insert("Brown2", ScColor(192, 96, 0));
	CustColors.insert("Pink4", ScColor(255, 128, 128));
	CustColors.insert("Pink3", ScColor(255, 160, 160));
	CustColors.insert("Pink2", ScColor(255, 192, 192));
	CustColors.insert("Pink", ScColor(255, 224, 224));
	CustColors.insert("Gold", ScColor(255, 215, 0));
	QFileInfo fi = QFileInfo(fName);
	if ( !ScCore->usingGUI() )
	{
		interactive = false;
		showProgress = false;
	}
	baseFile = QDir::cleanPath(QDir::toNativeSeparators(fi.absolutePath()+"/"));
	if ( showProgress )
	{
		ScribusMainWindow* mw=(m_Doc==0) ? ScCore->primaryMainWindow() : m_Doc->scMW();
		progressDialog = new MultiProgressDialog( tr("Importing: %1").arg(fi.fileName()), CommonStrings::tr_Cancel, mw );
		QStringList barNames, barTexts;
		barNames << "GI";
		barTexts << tr("Analyzing File:");
		QList<bool> barsNumeric;
		barsNumeric << false;
		progressDialog->addExtraProgressBars(barNames, barTexts, barsNumeric);
		progressDialog->setOverallTotalSteps(3);
		progressDialog->setOverallProgress(0);
		progressDialog->setProgress("GI", 0);
		progressDialog->show();
		connect(progressDialog, SIGNAL(canceled()), this, SLOT(cancelRequested()));
		qApp->processEvents();
	}
	else
		progressDialog = NULL;
/* Set default Page to size defined in Preferences */
	x = 0.0;
	y = 0.0;
	b = 0.0;
	h = 0.0;
	if (progressDialog)
	{
		progressDialog->setOverallProgress(1);
		qApp->processEvents();
	}
	parseHeader(fName, x, y, b, h);
	docX = x;
	docY = y;
	if (b == 0.0)
		b = PrefsManager::instance()->appPrefs.PageWidth;
	if (h == 0.0)
		h = PrefsManager::instance()->appPrefs.PageHeight;
	docWidth = b - x;
	docHeight = h - y;
	baseX = 0;
	baseY = 0;
	if (!interactive || (flags & LoadSavePlugin::lfInsertPage))
	{
		m_Doc->setPage(b-x, h-y, 0, 0, 0, 0, 0, 0, false, false);
		m_Doc->addPage(0);
		m_Doc->view()->addPage(0, true);
		baseX = 0;
		baseY = 0;
	}
	else
	{
		if (!m_Doc || (flags & LoadSavePlugin::lfCreateDoc))
		{
			m_Doc=ScCore->primaryMainWindow()->doFileNew(b-x, h-y, 0, 0, 0, 0, 0, 0, false, false, 0, false, 0, 1, "Custom", true);
			ScCore->primaryMainWindow()->HaveNewDoc();
			ret = true;
			baseX = 0;
			baseY = 0;
		}
	}
	if (flags & LoadSavePlugin::lfCreateDoc)
	{
		m_Doc->documentInfo.setAuthor(docCreator);
		m_Doc->documentInfo.setPublisher(docOrganisation);
		m_Doc->documentInfo.setTitle(docTitle);
		m_Doc->documentInfo.setDate(docDate+" "+docTime);
	}
	if ((!ret) && (interactive))
	{
		baseX = m_Doc->currentPage()->xOffset();
		baseY = m_Doc->currentPage()->yOffset();
	}
	if ((ret) || (!interactive))
	{
		if (b-x > h-y)
			m_Doc->PageOri = 1;
		else
			m_Doc->PageOri = 0;
		m_Doc->m_pageSize = "Custom";
	}
	Elements.clear();
	FPoint minSize = m_Doc->minCanvasCoordinate;
	FPoint maxSize = m_Doc->maxCanvasCoordinate;
	FPoint cOrigin = m_Doc->view()->canvasOrigin();
	m_Doc->setLoading(true);
	m_Doc->DoDrawing = false;
	m_Doc->view()->updatesOn(false);
	m_Doc->scMW()->ScriptRunning = true;
	qApp->changeOverrideCursor(QCursor(Qt::WaitCursor));
	QString CurDirP = QDir::currentPath();
	QDir::setCurrent(fi.path());
	if (convert(fName))
	{
		tmpSel->clear();
		QDir::setCurrent(CurDirP);
		if ((Elements.count() > 1) && (!(importerFlags & LoadSavePlugin::lfCreateDoc)))
		{
			bool isGroup = true;
			int firstElem = -1;
			if (Elements.at(0)->Groups.count() != 0)
				firstElem = Elements.at(0)->Groups.top();
			for (int bx = 0; bx < Elements.count(); ++bx)
			{
				PageItem* bxi = Elements.at(bx);
				if (bxi->Groups.count() != 0)
				{
					if (bxi->Groups.top() != firstElem)
						isGroup = false;
				}
				else
					isGroup = false;
			}
			if (!isGroup)
			{
				double minx = 99999.9;
				double miny = 99999.9;
				double maxx = -99999.9;
				double maxy = -99999.9;
				uint lowestItem = 999999;
				uint highestItem = 0;
				for (int a = 0; a < Elements.count(); ++a)
				{
					Elements.at(a)->Groups.push(m_Doc->GroupCounter);
					PageItem* currItem = Elements.at(a);
					lowestItem = qMin(lowestItem, currItem->ItemNr);
					highestItem = qMax(highestItem, currItem->ItemNr);
					double x1, x2, y1, y2;
					currItem->getVisualBoundingRect(&x1, &y1, &x2, &y2);
					minx = qMin(minx, x1);
					miny = qMin(miny, y1);
					maxx = qMax(maxx, x2);
					maxy = qMax(maxy, y2);
				}
				double gx = minx;
				double gy = miny;
				double gw = maxx - minx;
				double gh = maxy - miny;
				PageItem *high = m_Doc->Items->at(highestItem);
				int z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Rectangle, gx, gy, gw, gh, 0, m_Doc->toolSettings.dBrush, m_Doc->toolSettings.dPen, true);
				PageItem *neu = m_Doc->Items->takeAt(z);
				m_Doc->Items->insert(lowestItem, neu);
				neu->Groups.push(m_Doc->GroupCounter);
				neu->setItemName( tr("Group%1").arg(neu->Groups.top()));
				neu->AutoName = false;
				neu->isGroupControl = true;
				neu->groupsLastItem = high;
				neu->setTextFlowMode(PageItem::TextFlowDisabled);
				for (int a = 0; a < m_Doc->Items->count(); ++a)
				{
					m_Doc->Items->at(a)->ItemNr = a;
				}
				Elements.prepend(neu);
				m_Doc->GroupCounter++;
			}
		}
		m_Doc->DoDrawing = true;
		m_Doc->scMW()->ScriptRunning = false;
		m_Doc->setLoading(false);
		qApp->changeOverrideCursor(QCursor(Qt::ArrowCursor));
		if ((Elements.count() > 0) && (!ret) && (interactive))
		{
			if (flags & LoadSavePlugin::lfScripted)
			{
				bool loadF = m_Doc->isLoading();
				m_Doc->setLoading(false);
				m_Doc->changed();
				m_Doc->setLoading(loadF);
				m_Doc->m_Selection->delaySignalsOn();
				for (int dre=0; dre<Elements.count(); ++dre)
				{
					m_Doc->m_Selection->addItem(Elements.at(dre), true);
				}
				m_Doc->m_Selection->delaySignalsOff();
				m_Doc->m_Selection->setGroupRect();
				m_Doc->view()->updatesOn(true);
			}
			else
			{
				m_Doc->DragP = true;
				m_Doc->DraggedElem = 0;
				m_Doc->DragElements.clear();
				m_Doc->m_Selection->delaySignalsOn();
				for (int dre=0; dre<Elements.count(); ++dre)
				{
					m_Doc->DragElements.append(Elements.at(dre)->ItemNr);
					tmpSel->addItem(Elements.at(dre), true);
				}
				tmpSel->setGroupRect();
				ScriXmlDoc *ss = new ScriXmlDoc();
				ScElemMimeData* md = new ScElemMimeData();
				md->setScribusElem(ss->WriteElem(m_Doc, m_Doc->view(), tmpSel));
				delete ss;
/*#ifndef Q_WS_MAC*/
// see #2196
				m_Doc->itemSelection_DeleteItem(tmpSel);
/*#else
				qDebug("xfigimport: leaving items on page");
#endif*/
				m_Doc->view()->updatesOn(true);
				m_Doc->m_Selection->delaySignalsOff();
				// We must copy the TransationSettings object as it is owned
				// by handleObjectImport method afterwards
				TransactionSettings* transacSettings = new TransactionSettings(trSettings);
				m_Doc->view()->handleObjectImport(md, transacSettings);
				m_Doc->DragP = false;
				m_Doc->DraggedElem = 0;
				m_Doc->DragElements.clear();
			}
		}
		else
		{
			m_Doc->changed();
			m_Doc->reformPages();
			m_Doc->view()->updatesOn(true);
		}
		success = true;
	}
	else
	{
		QDir::setCurrent(CurDirP);
		m_Doc->DoDrawing = true;
		m_Doc->scMW()->ScriptRunning = false;
		m_Doc->view()->updatesOn(true);
		qApp->changeOverrideCursor(QCursor(Qt::ArrowCursor));
	}
	if (interactive)
		m_Doc->setLoading(false);
	//CB If we have a gui we must refresh it if we have used the progressbar
	if ((showProgress) && (!interactive))
		m_Doc->view()->DrawNew();
	return success;
}
Ejemplo n.º 3
0
void ViewTableListWidget::addViewName(QString str)
{
    qDebug()<<tr("信号发射成功")<<str;
    QDir rootdir("view//");
    rootdir.setFilter(rootdir.filter()|QDir::NoDotAndDotDot);
    QStringList strings;
    strings<<str;
     QFileInfo tempinfo = *(rootdir.entryInfoList(strings).begin());
     qDebug()<<tempinfo.absolutePath();
    this->insertRow(rowCount());
    int temprow = rowCount()-1;
    QTableWidgetItem * item = new QTableWidgetItem(QIcon("images/historicalcurve.jpg"),tempinfo.fileName());
    item->setToolTip(item->text());
    this->setItem(temprow,0,item);
    this->setItem(temprow,1,new QTableWidgetItem(tempinfo.suffix()));
    item = new QTableWidgetItem("0");
    item->setTextAlignment(Qt::AlignCenter);
    this->setItem(temprow,2,item);
    item = new QTableWidgetItem(tempinfo.lastModified().toString("yyyy-MM-dd hh:mm"));
    item->setTextAlignment(Qt::AlignCenter);
    this->setItem(temprow,3,item);
    modifyViewTable();
}
Ejemplo n.º 4
0
static void parse_command(QString cmdline, const QString &id, const QString &whichCommand,
                          QString *command, QStringList *prefix, QStringList *suffix, ArchiveDefinition::ArgumentPassingMethod *method, bool parseFilePlaceholder)
{
    Q_ASSERT(prefix);
    Q_ASSERT(suffix);
    Q_ASSERT(method);

    KShell::Errors errors;
    QStringList l;

    if (cmdline.startsWith(NULL_SEPARATED_STDIN_INDICATOR)) {
        *method = ArchiveDefinition::NullSeparatedInputFile;
        cmdline.remove(0, 2);
    } else if (cmdline.startsWith(NEWLINE_SEPARATED_STDIN_INDICATOR)) {
        *method = ArchiveDefinition::NewlineSeparatedInputFile;
        cmdline.remove(0, 1);
    } else {
        *method = ArchiveDefinition::CommandLine;
    }
    if (*method != ArchiveDefinition::CommandLine && cmdline.contains(FILE_PLACEHOLDER)) {
        throw ArchiveDefinitionError(id, i18n("Cannot use both %f and | in '%1'", whichCommand));
    }
    cmdline.replace(FILE_PLACEHOLDER,        QLatin1String("__files_go_here__"))
    .replace(INSTALLPATH_PLACEHOLDER, QStringLiteral("__path_goes_here__"));
    l = KShell::splitArgs(cmdline, KShell::AbortOnMeta | KShell::TildeExpand, &errors);
    l = l.replaceInStrings(QStringLiteral("__files_go_here__"), FILE_PLACEHOLDER);
    if (l.indexOf(QRegExp(QLatin1String(".*__path_goes_here__.*"))) >= 0) {
        l = l.replaceInStrings(QStringLiteral("__path_goes_here__"), ArchiveDefinition::installPath());
    }
    if (errors == KShell::BadQuoting) {
        throw ArchiveDefinitionError(id, i18n("Quoting error in '%1' entry", whichCommand));
    }
    if (errors == KShell::FoundMeta) {
        throw ArchiveDefinitionError(id, i18n("'%1' too complex (would need shell)", whichCommand));
    }
    qCDebug(KLEOPATRA_LOG) << "ArchiveDefinition[" << id << ']' << l;
    if (l.empty()) {
        throw ArchiveDefinitionError(id, i18n("'%1' entry is empty/missing", whichCommand));
    }
    const QFileInfo fi1(l.front());
    if (fi1.isAbsolute()) {
        *command = try_extensions(l.front());
    } else {
        *command = QStandardPaths::findExecutable(fi1.fileName());
    }
    if (command->isEmpty()) {
        throw ArchiveDefinitionError(id, i18n("'%1' empty or not found", whichCommand));
    }
    if (parseFilePlaceholder) {
        const int idx1 = l.indexOf(FILE_PLACEHOLDER);
        if (idx1 < 0) {
            // none -> append
            *prefix = l.mid(1);
        } else {
            *prefix = l.mid(1, idx1 - 1);
            *suffix = l.mid(idx1 + 1);
        }
    } else {
        *prefix = l.mid(1);
    }
    switch (*method) {
    case ArchiveDefinition::CommandLine:
        qCDebug(KLEOPATRA_LOG) << "ArchiveDefinition[" << id << ']' << *command << *prefix << FILE_PLACEHOLDER << *suffix;
        break;
    case ArchiveDefinition::NewlineSeparatedInputFile:
        qCDebug(KLEOPATRA_LOG) << "ArchiveDefinition[" << id << ']' << "find | " << *command << *prefix;
        break;
    case ArchiveDefinition::NullSeparatedInputFile:
        qCDebug(KLEOPATRA_LOG) << "ArchiveDefinition[" << id << ']' << "find -print0 | " << *command << *prefix;
        break;
    case ArchiveDefinition::NumArgumentPassingMethods:
        Q_ASSERT(!"Should not happen");
        break;
    }
}
Ejemplo n.º 5
0
QString OptionsWindow::getMaskToConfig(int step) {
    QString mask;
    QSettings *GlobalSettings = new QSettings("/root/.WiFiHostapdAP/WiFi_Hostapd_AP.conf",QSettings::NativeFormat); // создание нового объекта
    QDir dir;
    QFileInfoList list;
    QString temp_qstring = "default.conf";
    QString path;

    switch(step) {
    case 0:

        dir.cd("/root");
        if(!dir.cd(".WiFiHostapdAP")) {
            dir.mkdir(QString("%1").arg(".WiFiHostapdAP"));
            dir.cd(".WiFiHostapdAP"); }

        if(!dir.cd("./Mask/")) {
            dir.mkdir(QString("%1").arg("Mask"));
            dir.cd("./Mask/"); }

        if(!dir.cd("./hostapd/")) {
            dir.mkdir(QString("%1").arg("hostapd"));
            dir.cd("./hostapd/"); }

        dir.setFilter(QDir::Files);
        list = dir.entryInfoList();

        if(list.size()==0) {

            QFile new_Default_Mask("/root/.WiFiHostapdAP/Mask/hostapd/default.conf");
            new_Default_Mask.open(QIODevice::Append | QIODevice::Text);
            QTextStream out(&new_Default_Mask);
            out << "#Name:Default\n";
            out << "#Type:Hostapd\n";
            out << "interface=[INTERFACE]\n";
            out << "driver=[DRIVER]\n";
            out << "ssid=[SSID]\n";
            out << "country_code=[COUNTRY_CODE]\n";
            out << "[TYPE_AP]\n";
            out << "channel=[CHANNEL]\n";
            out << "macaddr_acl=0\n";
            out << "[HIDEAP]\n";
            out << "[PROTECT]";
            new_Default_Mask.close();

            list.clear();
            dir.setFilter(QDir::Files);
            list = dir.entryInfoList();
        }
        path = "/root/.WiFiHostapdAP/Mask/hostapd/";

        for (int i = 0; i < list.size(); ++i) {
            QFileInfo fileInfo = list.at(i);
            if(fileInfo.fileName() == GlobalSettings->value("AP/ConfigMask", "default.conf").toString())
                temp_qstring = GlobalSettings->value("AP/ConfigMask", "default.conf").toString();
        }
        path += temp_qstring;

        break;
    case 1:

        dir.cd("/root");
        if(!dir.cd(".WiFiHostapdAP")) {
            dir.mkdir(QString("%1").arg(".WiFiHostapdAP"));
            dir.cd(".WiFiHostapdAP"); }

        if(!dir.cd("./Mask/")) {
            dir.mkdir(QString("%1").arg("Mask"));
            dir.cd("./Mask/"); }

        if(!dir.cd("./dnsmasq/")) {
            dir.mkdir(QString("%1").arg("dnsmasq"));
            dir.cd("./dnsmasq/"); }

        dir.setFilter(QDir::Files);
        list = dir.entryInfoList();

        if(list.size()==0) {
            // Если шаблонов нет, то создаём шаблон по-умолчанию
            QFile new_Default_Mask("/root/.WiFiHostapdAP/Mask/dnsmasq/default.conf");
            new_Default_Mask.open(QIODevice::Append | QIODevice::Text);
            QTextStream out(&new_Default_Mask);
            out << "#Name:Default\n";
            out << "#Type:DNSMASQ\n";
            out << "interface=[INTERFACE]\n";
            out << "dhcp-range=[RANGE_1],[RANGE_2],[IP_TIME];\n";
            out<< "[OpenDNS]";

            new_Default_Mask.close();

            list.clear();
            dir.setFilter(QDir::Files);
            list = dir.entryInfoList();
        }

        path = "/root/.WiFiHostapdAP/Mask/dnsmasq/";
        for (int i = 0; i < list.size(); ++i) {
            QFileInfo fileInfo = list.at(i);
            if(fileInfo.fileName() == GlobalSettings->value("AP/ConfigMask1", "default.conf").toString())
                temp_qstring = GlobalSettings->value("AP/ConfigMask1", "default.conf").toString();
        }
        path += temp_qstring;

        break; }

    QFile file_mask(path);
    file_mask.open(QIODevice::ReadOnly);
    QTextStream in(&file_mask);

    mask = in.read(10240);

    QString temp1 = "";
    // HOSTAPD
    mask.replace("[INTERFACE]", GlobalSettings->value("AP/Iface", "wlan0").toString());
    mask.replace("[DRIVER]", GlobalSettings->value("AP/drive", "nl80211").toString());
    mask.replace("[SSID]", GlobalSettings->value("AP/SSID", "MyWiFI_AP").toString());
    mask.replace("[COUNTRY_CODE]", GlobalSettings->value("AP/CountryCode", "RU").toString());
    mask.replace("[CHANNEL]", GlobalSettings->value("AP/Channels", "7").toString());
    /////////////////////////////////////////////////////////////////////////
    // Тип точки доступа
    /////////////////////////////////////////////////////////////////////////
    if(GlobalSettings->value("AP/TypeAP", "g").toString()=="n")
        temp1 = "hw_mode=g\nwme_enabled=1\nieee80211n=1\nht_capab=[HT40+][SHORT-GI-40][DSSS_CCK-40]";
    else if(GlobalSettings->value("AP/TypeAP", "g").toString()=="g")
        temp1 = "hw_mode=g";
    else
        temp1 = "\n";

    mask.replace("[TYPE_AP]", temp1);
    temp1.clear();

    /////////////////////////////////////////////////////////////////////////
    // Разбираемся с защитой
    /////////////////////////////////////////////////////////////////////////
    if(GlobalSettings->value("AP/Protection", "WPA3").toString()=="WPA3") {
        // Составляем маску для WPA
        temp1 = "wpa=3\nwpa_key_mgmt=WPA-PSK\nwpa_pairwise=TKIP\nwpa_pairwise=CCMP\nwpa_passphrase=";
        temp1.append(GlobalSettings->value("AP/Password", "MyWiFI_AP").toString()); }
    /////////////////////////////////////////////////////////////////////////
    else if(GlobalSettings->value("AP/Protection", "WPA3").toString()=="WEP") {
        // Составляем маску для WPA
        temp1 = "wep_default_key=0\nwep_key_len_broadcast=13\nwep_key_len_unicast=13\nwep_rekey_period=300\nwep_key0=";
        temp1.append(GlobalSettings->value("AP/Password", "MyWiFI_AP").toString());
    }

    else temp1 = "";
    mask.replace("[PROTECT]", temp1);

    if(GlobalSettings->value("AP/ShowSSID", false).toBool())
        mask.replace("[HIDEAP]", "ignore_broadcast_ssid=2");
    else mask.replace("[HIDEAP]", "");
    temp1.clear();

    // DNSMASQ
    mask.replace("[RANGE_1]", GlobalSettings->value("DHCP/IP_CLIENT1", "192.168.0.2").toString());
    mask.replace("[RANGE_2]", GlobalSettings->value("DHCP/IP_CLIENT2", "192.168.0.225").toString());
    mask.replace("[INTERFACE_INTERNET]", GlobalSettings->value("DHCP/Internet_iface", "eth0").toString());

    if(GlobalSettings->value("DHCP/UseOpenDNS", true).toBool())
        mask.replace("[OpenDNS]", "server=/www.google.com/8.8.8.8");
    else
        mask.replace("[OpenDNS]", "");

    switch(GlobalSettings->value("DHCP/IP_time", 2).toInt()) {
    case(0): mask.replace("[IP_TIME]", "10m"); break;
    case(1): mask.replace("[IP_TIME]", "30m"); break;
    case(2): mask.replace("[IP_TIME]", "1h"); break;
    case(3): mask.replace("[IP_TIME]", "2h"); break;
    case(4): mask.replace("[IP_TIME]", "6h"); break;
    case(5): mask.replace("[IP_TIME]", "12h"); break;
    }

    file_mask.close();
    delete GlobalSettings;
    return mask;
}
Ejemplo n.º 6
0
void MegaUploader::upload(QFileInfo info, MegaNode *parent)
{
    QApplication::processEvents();

    MegaNodeList *children =  megaApi->getChildren(parent);
    QByteArray utf8name = info.fileName().toUtf8();
    QString currentPath = QDir::toNativeSeparators(info.absoluteFilePath());
    MegaNode *dupplicate = NULL;
    for (int i = 0; i < children->size(); i++)
    {
        MegaNode *child = children->get(i);
        if (!strcmp(utf8name.constData(), child->getName())
                && ((info.isDir() && (child->getType() == MegaNode::TYPE_FOLDER))
                    || (info.isFile() && (child->getType() == MegaNode::TYPE_FILE)
                        && (info.size() == child->getSize()))))
        {
            dupplicate = child->copy();
            break;
        }
    }
    delete children;

    if (dupplicate)
    {
        if (dupplicate->getType() == MegaNode::TYPE_FILE)
        {
            emit dupplicateUpload(info.absoluteFilePath(), info.fileName(), dupplicate->getHandle());
        }

        if (dupplicate->getType() == MegaNode::TYPE_FOLDER)
        {
            QDir dir(info.absoluteFilePath());
            QFileInfoList entries = dir.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot);
            for (int i = 0; i < entries.size(); i++)
            {
                upload(entries[i], dupplicate);
            }
        }
        delete dupplicate;
        return;
    }

    string localPath = megaApi->getLocalPath(parent);
    if (localPath.size() && megaApi->isSyncable(info.fileName().toUtf8().constData()))
    {
#ifdef WIN32
        QString destPath = QDir::toNativeSeparators(QString::fromWCharArray((const wchar_t *)localPath.data()) + QDir::separator() + info.fileName());
        if (destPath.startsWith(QString::fromAscii("\\\\?\\")))
        {
            destPath = destPath.mid(4);
        }
#else
        QString destPath = QDir::toNativeSeparators(QString::fromUtf8(localPath.data()) + QDir::separator() + info.fileName());
#endif
        megaApi->moveToLocalDebris(destPath.toUtf8().constData());
        QtConcurrent::run(Utilities::copyRecursively, currentPath, destPath);
    }
    else if (info.isFile())
    {
        megaApi->startUpload(currentPath.toUtf8().constData(), parent);
    }
    else if (info.isDir())
    {
        folders.enqueue(info);
        megaApi->createFolder(info.fileName().toUtf8().constData(), parent, delegateListener);
    }
}
Ejemplo n.º 7
0
bool NewMapFile::execute()
{
    PIDGIRL::writeLog("Creating new map file");

    bool ok = false;
    QFileInfo fileInfo = QFileInfo(this->worldModel->filePath(this->index));
    this->dir = fileInfo.dir();

    if(fileInfo.isDir())
    {
        dir.cd(fileInfo.fileName());
    }

    this->file = QInputDialog::getText(0,
                                       tr("New Map..."),
                                       tr("Enter the name of the new map."),
                                       QLineEdit::Normal,
                                       tr("New Map"),
                                       &ok);

    if(!ok)
    {
        PIDGIRL::writeLogDone("[EXIT]");
        return true;
    }

    if(this->file.isEmpty())
    {
        PIDGIRL::writeLogFail("No file was specified. The string, where the path should've been, was empty.");
        return false;
    }

    if(this->file.endsWith(PIDGIRL::MAP_SUFFIX))
    {
        this->file.remove(this->file.size() - PIDGIRL::MAP_SUFFIX.size(), PIDGIRL::MAP_SUFFIX.size());
    }

    int i = 1;
    QString newFile = this->file;
    while(dir.exists(newFile.append(PIDGIRL::MAP_SUFFIX)))
    {
        newFile = this->file;
        newFile = newFile.append(QString::number(i));
        ++i;
    }

    MapModel tempMap;
    QString mapPath = QFileInfo(this->dir, newFile).absoluteFilePath();

    tempMap.setLocalMapPath(this->worldModel->absoluteMapPathToLocalMapPath(mapPath));

    if(!this->fileManager.serialize(&tempMap, mapPath))
    {
        QMessageBox::critical(0, tr("Failed to create a map file..."), tr("Creating a map file has failed."));
        PIDGIRL::writeLogFail("The creating process of the map failed.");
        return false;
    }

    PIDGIRL::writeLogDone();

    return true;
}
Ejemplo n.º 8
0
/*!
  \a fileName is the path of the file to find.

  \a files and \a dirs are the lists where we must find the
  components of \a fileName.
  
  \a location is used for obtaining the file and line numbers
  for report qdoc errors.
 */
QString Config::findFile(const Location& location,
                         const QStringList& files,
                         const QStringList& dirs,
                         const QString& fileName,
                         QString& userFriendlyFilePath)
{
    if (fileName.isEmpty() || fileName.startsWith(QLatin1Char('/'))) {
        userFriendlyFilePath = fileName;
        return fileName;
    }

    QFileInfo fileInfo;
    QStringList components = fileName.split(QLatin1Char('?'));
    QString firstComponent = components.first();

    QStringList::ConstIterator f = files.begin();
    while (f != files.end()) {
	if (*f == firstComponent ||
            (*f).endsWith(QLatin1Char('/') + firstComponent)) {
	    fileInfo.setFile(*f);
	    if (!fileInfo.exists())
		location.fatal(tr("File '%1' does not exist").arg(*f));
	    break;
	}
	++f;
    }

    if (fileInfo.fileName().isEmpty()) {
	QStringList::ConstIterator d = dirs.begin();
	while (d != dirs.end()) {
	    fileInfo.setFile(QDir(*d), firstComponent);
	    if (fileInfo.exists()) {
		break;
            }
	    ++d;
	}
    }

    userFriendlyFilePath = QString();
    if (!fileInfo.exists())
	    return QString();

    QStringList::ConstIterator c = components.begin();
    for (;;) {
	bool isArchive = (c != components.end() - 1);
	QString userFriendly = *c;

	userFriendlyFilePath += userFriendly;

	if (isArchive) {
	    QString extracted = extractedDirs[fileInfo.filePath()];
	    ++c;
	    fileInfo.setFile(QDir(extracted), *c);
	}
        else
	    break;

	userFriendlyFilePath += "?";
    }
    return fileInfo.filePath();
}
Ejemplo n.º 9
0
bool processXmlFile(const QString &xmlFile)
{
    QFile file(xmlFile);
    if (!file.open(QIODevice::ReadOnly))
        return false;

    const QLatin1String tag_app("app");
    const QLatin1String attrib_mainQmlFile("mainqmlfile");
    const QLatin1String attrib_projectPath("projectpath");
    const QLatin1String attrib_projectName("projectname");
    const QLatin1String attrib_screenOrientation("screenorientation");
    const QLatin1String value_screenOrientationLockLandscape("LockLandscape");
    const QLatin1String value_screenOrientationLockPortrait("LockPortrait");
    const QLatin1String attrib_networkAccess("networkaccess");

    static const QString qtDir =
            QLibraryInfo::location(QLibraryInfo::PrefixPath) + QLatin1Char('/');

    QXmlStreamReader reader(&file);
    while (!reader.atEnd()) {
        const QXmlStreamReader::TokenType token = reader.readNext();
        switch (token) {
            case QXmlStreamReader::StartElement:
                if (reader.name() == tag_app) {
                    QtQuickApp app;
                    QFileInfo projectPath;
                    if (!reader.attributes().hasAttribute(attrib_projectPath)) {
                        qDebug() << "Project without path found";
                        continue;
                    }
                    projectPath = qtDir + reader.attributes().value(attrib_projectPath).toString();
                    app.setProjectPath(projectPath.absoluteFilePath());
                    if (reader.attributes().hasAttribute(attrib_mainQmlFile)) {
                        const QFileInfo qmlFileOrigin(
                                qtDir + reader.attributes().value(attrib_mainQmlFile).toString());
                        if (!qmlFileOrigin.exists()) {
                            qDebug() << "Cannot find" <<
                                        QDir::toNativeSeparators(qmlFileOrigin.absoluteFilePath());
                            continue;
                        }
                        const QFileInfo qmlTargetPath(QString(projectPath.absoluteFilePath()
                                                              + QLatin1Char('/') + qmlFileOrigin.baseName()
                                                              + QLatin1String("/qml")));
#ifdef Q_OS_WIN
                        const QString sourcePath =
                                QDir::toNativeSeparators(qmlFileOrigin.canonicalPath() + QLatin1String("/*"));
                        const QString targetPath =
                                QDir::toNativeSeparators(qmlTargetPath.absoluteFilePath() + QLatin1Char('/'));
                        QProcess xcopy;
                        QStringList parameters;
                        parameters << QLatin1String("/E") << sourcePath << targetPath;
                        xcopy.start(QLatin1String("xcopy.exe"), parameters);
                        if (!xcopy.waitForStarted() || !xcopy.waitForFinished()) {
                            qDebug() << "Could not copy" <<
                                        QDir::toNativeSeparators(sourcePath);
                            continue;
                        }
#else // Q_OS_WIN
                        // Implement me!
#endif // Q_OS_WIN
                        app.setMainQmlFile(qmlTargetPath.absoluteFilePath()
                                              + QLatin1Char('/') + qmlFileOrigin.fileName());
                    }
                    app.setProjectName(reader.attributes().hasAttribute(attrib_projectName)
                                            ? reader.attributes().value(attrib_projectName).toString()
                                            : QFileInfo(app.mainQmlFile()).baseName());
                    if (reader.attributes().hasAttribute(attrib_screenOrientation)) {
                        const QStringRef orientation = reader.attributes().value(attrib_screenOrientation);
                        app.setOrientation(orientation == value_screenOrientationLockLandscape ?
                                                AbstractMobileApp::ScreenOrientationLockLandscape
                                              : orientation == value_screenOrientationLockPortrait ?
                                                AbstractMobileApp::ScreenOrientationLockPortrait
                                              : AbstractMobileApp::ScreenOrientationAuto);
                    }
                    if (reader.attributes().hasAttribute(attrib_networkAccess))
                        app.setNetworkEnabled(
                                    reader.attributes().value(attrib_networkAccess).toString() == QLatin1String("true"));
                    if (!app.generateFiles(0))
                        qDebug() << "Unable to generate the files for" << app.projectName();
                }
                break;
            default:
                break;
        }
    }
    return true;
}
void CTile_browser_dlg::RefreshView()
{
	thread_actif = 1;

	//Remove Tiles from the View model
	tileViewModel->removeAllTiles();

	//Add Tiles in the View model
	int listCount = browserModel.GetSize(tileTypeButtonGroup->checkedId());
	tilelist::iterator p = browserModel.GetFirst(tileTypeButtonGroup->checkedId());
	for (p = browserModel.GetFirst(tileTypeButtonGroup->checkedId()); p != browserModel.GetLast(tileTypeButtonGroup->checkedId()); p++)
	{
		std::vector<NLMISC::CBGRA>* bits;
		bool tileLoaded = false;
		std::string tilePath;
		switch(tileTextureButtonGroup->checkedId())
		{
			case Diffuse:
				bits = &p->Bits;
				tileLoaded = p->loaded;
				tilePath = p->path;
				break;

			case Additive:
				bits = &p->nightBits;
				tileLoaded = p->nightLoaded;
				tilePath = p->nightPath;
				break;

			case Alpha:
				bits = &p->alphaBits;
				tileLoaded = p->alphaLoaded;
				tilePath = p->alphaPath;
				break;
		}

		if (tileLoaded)
		{
			int itBufferPixel = 0;
			double bufferWidth = sqrt((double)(*bits).size());
			double bufferHeight = sqrt((double)(*bits).size());

			QImage image(QSize(bufferWidth,bufferHeight), QImage::Format_ARGB32 );
			for(int colIndex = 0;colIndex<bufferHeight;colIndex++)
			{			
				for(int lineIndex = 0;lineIndex<bufferWidth;lineIndex++)
				{
					image.setPixel(lineIndex,colIndex,qRgb((*bits)[itBufferPixel].R
											  ,(*bits)[itBufferPixel].G
											  ,(*bits)[itBufferPixel].B));
					itBufferPixel ++;
				}
			}

			image = image.scaled(tileZoomButtonGroup->checkedId() * (tileTypeButtonGroup->checkedId()==_256x256 ? 2 : 1), tileZoomButtonGroup->checkedId() * (tileTypeButtonGroup->checkedId()==_256x256 ? 2 : 1));

			QString fileInfo = QString::number(p->getId());
			if (tileLabelButtonGroup->checkedId() == CTile_browser_dlg::FileName)
			{
				QFileInfo fi = QFileInfo(QString( tilePath.c_str()));
				fileInfo = fi.fileName();
			}
			QPixmap pixmap = QPixmap::fromImage(image);
			TileModel tile = TileModel(pixmap, fileInfo, p->getId());
			tileViewModel->addTile(tile);

		}
		else
		{
			QString fileInfo;
			if (tileLabelButtonGroup->checkedId() == CTile_browser_dlg::Index)
			{
				fileInfo = QString::number(p->getId());
			}
			TileModel tile = TileModel(tileZoomButtonGroup->checkedId() * (tileTypeButtonGroup->checkedId()==_256x256 ? 2 : 1), fileInfo, p->getId());
			tileViewModel->addTile(tile);
		}

		tileViewModel->sort();

	}

	EnableBrowserInteractions();
	
	thread_actif = 0;
}
Ejemplo n.º 11
0
void WinXP(QString input, QString out)
{
    int per, i, schetchik, k, m, j;
    QString FullPath, buff, Avatars, Thumbnails;

    QDir dirU(input + "/Documents and Settings");
    dirU.setFilter(QDir::NoDotAndDotDot | QDir::Dirs | QDir::Hidden );
    dirU.setSorting(QDir::Name);
    QFileInfoList Uslist = dirU.entryInfoList();
    QString Users[Uslist.size()];
    for (per = 0; per < Uslist.size(); per++)
    {
        QFileInfo fileInfo = Uslist.at(per);
        Users[per] = input + "/Documents and Settings/" + fileInfo.fileName();
    }

    for (i = 0; i < Uslist.size(); i++)
    {
        if ((Users[i] != input + "/Documents and Settings/All Users") && (Users[i] != input + "/Documents and Settings/Default User") && (Users[i] != input + "/Documents and Settings/Public") && (Users[i] != input + "/Documents and Settings/Все пользователи"))
        {
            QDir dirUAR(Users[i] + "/Application Data");
            dirUAR.setFilter(QDir::NoDotAndDotDot | QDir::Dirs | QDir::Hidden );
            dirUAR.setSorting(QDir::Name);
            QFileInfoList Brlist = dirUAR.entryInfoList();
            QString buffRoaming[Brlist.size()];
            schetchik = 0;
            for (per = 0; per < Brlist.size(); per++)
            {
                QFileInfo fileInfo = Brlist.at(per);
                buffRoaming[per] = Users[i] + "/Application Data/" + fileInfo.fileName();
                schetchik++;
            }

            for (k = 0; k < schetchik; k++)
            {
                if (buffRoaming[k] == Users[i] + "/Application Data/ViberPC")
                {

                    QDir dirVib(buffRoaming[k]);
                    dirVib.setFilter(QDir::NoDotAndDotDot | QDir::Dirs | QDir::Hidden );
                    dirVib.setSorting(QDir::Name);
                    QFileInfoList Viblist = dirVib.entryInfoList();
                    QString Vibakk[Viblist.size()];
                    QString KatalogiViber[Viblist.size()];
                    for (m = 0; m < Viblist.size(); m++)
                    {
                        QFileInfo fileInfo = Viblist.at(m);
                        Vibakk[m] = buffRoaming[k] + "/" + fileInfo.fileName();
                        KatalogiViber[m] = fileInfo.fileName();
                    }

                    for (j = 0; j < m; j++)
                    {
                        buff = "";
                        buff = KatalogiViber[j];
                        if ((buff[0] == '7') &&(buff[1] == '9'))
                        {
                            Avatars = Vibakk[j] + "/Avatars";
                            Thumbnails = Vibakk[j] + "/Thumbnails";
                            FullPath = Vibakk[j] + "/" + "viber.db";
                            Viber_XP_7_8_10(FullPath, KatalogiViber[j], out);
                            Viber_Avatars(Avatars, KatalogiViber[j], out);
                            Viber_Thumbnails(Thumbnails, KatalogiViber[j], out);
                        }
                    }
                }
            }
        }
    }
}
Ejemplo n.º 12
0
void Mod::repath(const QFileInfo &file)
{
	m_file = file;
	QString name_base = file.fileName();

	m_type = Mod::MOD_UNKNOWN;

	if (m_file.isDir())
	{
		m_type = MOD_FOLDER;
		m_name = name_base;
		m_mmc_id = name_base;
	}
	else if (m_file.isFile())
	{
		if (name_base.endsWith(".disabled"))
		{
			m_enabled = false;
			name_base.chop(9);
		}
		else
		{
			m_enabled = true;
		}
		m_mmc_id = name_base;
		if (name_base.endsWith(".zip") || name_base.endsWith(".jar"))
		{
			m_type = MOD_ZIPFILE;
			name_base.chop(4);
		}
		else if (name_base.endsWith(".litemod"))
		{
			m_type = MOD_LITEMOD;
			name_base.chop(8);
		}
		else
		{
			m_type = MOD_SINGLEFILE;
		}
		m_name = name_base;
	}

	if (m_type == MOD_ZIPFILE)
	{
		QuaZip zip(m_file.filePath());
		if (!zip.open(QuaZip::mdUnzip))
			return;

		QuaZipFile file(&zip);

		if (zip.setCurrentFile("mcmod.info"))
		{
			if (!file.open(QIODevice::ReadOnly))
			{
				zip.close();
				return;
			}

			ReadMCModInfo(file.readAll());
			file.close();
			zip.close();
			return;
		}
		else if (zip.setCurrentFile("forgeversion.properties"))
		{
			if (!file.open(QIODevice::ReadOnly))
			{
				zip.close();
				return;
			}

			ReadForgeInfo(file.readAll());
			file.close();
			zip.close();
			return;
		}

		zip.close();
	}
	else if (m_type == MOD_FOLDER)
	{
		QFileInfo mcmod_info(PathCombine(m_file.filePath(), "mcmod.info"));
		if (mcmod_info.isFile())
		{
			QFile mcmod(mcmod_info.filePath());
			if (!mcmod.open(QIODevice::ReadOnly))
				return;
			auto data = mcmod.readAll();
			if (data.isEmpty() || data.isNull())
				return;
			ReadMCModInfo(data);
		}
	}
	else if (m_type == MOD_LITEMOD)
	{
		QuaZip zip(m_file.filePath());
		if (!zip.open(QuaZip::mdUnzip))
			return;

		QuaZipFile file(&zip);

		if (zip.setCurrentFile("litemod.json"))
		{
			if (!file.open(QIODevice::ReadOnly))
			{
				zip.close();
				return;
			}

			ReadLiteModInfo(file.readAll());
			file.close();
		}
		zip.close();
	}
}
Ejemplo n.º 13
0
QString MaidFacade::getCapturedFileName(const QFileInfo& saveFile) {

	//if (!viewport)
	//	return saveFile.fileName();

	qDebug() << "saving captured image...";

	//DkImageLoader* loader = viewport->getImageLoader();

	QString selectedFilter;
	QString saveName;
	saveName = saveFile.fileName();

	int filterIdx = -1;

	// do not use the nomacs saveFilters here, the file format is already set
	QStringList sF;
	sF.append("Nikon (*.nef)");
	sF.append("JPEG (*.jpg *.jpeg)");
	//qDebug() << sF;

	QRegExp exp = QRegExp("*." + saveFile.suffix() + "*", Qt::CaseInsensitive);
	exp.setPatternSyntax(QRegExp::Wildcard);
	//qDebug() << "exp: " << exp;

	for (int idx = 0; idx < sF.size(); idx++) {
		if (exp.exactMatch(sF.at(idx))) {
			selectedFilter = sF.at(idx);
			filterIdx = idx;
			break;
		}
	}

	if (filterIdx == -1)
		saveName.remove("." + saveFile.suffix());

	QString fileName;

	//int answer = QDialog::Rejected;

	//if (!selectedFilter.isEmpty() && viewport()->getImageLoader()->isEdited()) {
	//	fileName = loader->getCurrentImage()->file().absoluteFilePath();
	//	DkMessageBox* msg = new DkMessageBox(QMessageBox::Question, tr("Overwrite File"), 
	//		tr("Do you want to overwrite:\n%1?").arg(fileName), 
	//		(QMessageBox::Yes | QMessageBox::No), this);
	//	msg->setObjectName("overwriteDialog");

	//	//msg->show();
	//	answer = msg->exec();

	//}

	//if (answer == QDialog::Rejected || answer == QMessageBox::No) {
		// note: basename removes the whole file name from the first dot...
	if (firstFilename.isEmpty() || !autoSaveNaming) {	
		QString savePath = (!selectedFilter.isEmpty()) ? saveFile.absoluteFilePath() : QFileInfo(saveFile.absoluteDir(), saveName).absoluteFilePath();

		// TODO: set the main window here...
		fileName = QFileDialog::getSaveFileName(dialogParent, tr("Save File %1").arg(saveName),
			savePath, selectedFilter, &selectedFilter);
	}

	return fileName;
}
Ejemplo n.º 14
0
bool MetaEngine::Private::saveOperations(const QFileInfo& finfo, Exiv2::Image::AutoPtr image) const
{
    try
    {
        Exiv2::AccessMode mode;
        bool wroteComment = false, wroteEXIF = false, wroteIPTC = false, wroteXMP = false;

        // We need to load target file metadata to merge with new one. It's mandatory with TIFF format:
        // like all tiff file structure is based on Exif.
        image->readMetadata();

        // Image Comments ---------------------------------

        mode = image->checkMode(Exiv2::mdComment);

        if ((mode == Exiv2::amWrite) || (mode == Exiv2::amReadWrite))
        {
            image->setComment(imageComments());
            wroteComment = true;
        }

        qCDebug(DIGIKAM_METAENGINE_LOG) << "wroteComment: " << wroteComment;

        // Exif metadata ----------------------------------

        mode = image->checkMode(Exiv2::mdExif);

        if ((mode == Exiv2::amWrite) || (mode == Exiv2::amReadWrite))
        {
            if (image->mimeType() == "image/tiff")
            {
                Exiv2::ExifData orgExif = image->exifData();
                Exiv2::ExifData newExif;
                QStringList     untouchedTags;

                // With tiff image we cannot overwrite whole Exif data as well, because
                // image data are stored in Exif container. We need to take a care about
                // to not lost image data.
                untouchedTags << QString::fromLatin1("Exif.Image.ImageWidth");
                untouchedTags << QString::fromLatin1("Exif.Image.ImageLength");
                untouchedTags << QString::fromLatin1("Exif.Image.BitsPerSample");
                untouchedTags << QString::fromLatin1("Exif.Image.Compression");
                untouchedTags << QString::fromLatin1("Exif.Image.PhotometricInterpretation");
                untouchedTags << QString::fromLatin1("Exif.Image.FillOrder");
                untouchedTags << QString::fromLatin1("Exif.Image.SamplesPerPixel");
                untouchedTags << QString::fromLatin1("Exif.Image.StripOffsets");
                untouchedTags << QString::fromLatin1("Exif.Image.RowsPerStrip");
                untouchedTags << QString::fromLatin1("Exif.Image.StripByteCounts");
                untouchedTags << QString::fromLatin1("Exif.Image.XResolution");
                untouchedTags << QString::fromLatin1("Exif.Image.YResolution");
                untouchedTags << QString::fromLatin1("Exif.Image.PlanarConfiguration");
                untouchedTags << QString::fromLatin1("Exif.Image.ResolutionUnit");

                for (Exiv2::ExifData::iterator it = orgExif.begin(); it != orgExif.end(); ++it)
                {
                    if (untouchedTags.contains(QString::fromLatin1(it->key().c_str())))
                    {
                        newExif[it->key().c_str()] = orgExif[it->key().c_str()];
                    }
                }

                Exiv2::ExifData readedExif = exifMetadata();

                for (Exiv2::ExifData::iterator it = readedExif.begin(); it != readedExif.end(); ++it)
                {
                    if (!untouchedTags.contains(QString::fromLatin1(it->key().c_str())))
                    {
                        newExif[it->key().c_str()] = readedExif[it->key().c_str()];
                    }
                }

                image->setExifData(newExif);
            }
            else
            {
                image->setExifData(exifMetadata());
            }

            wroteEXIF = true;
        }

        qCDebug(DIGIKAM_METAENGINE_LOG) << "wroteEXIF: " << wroteEXIF;

        // Iptc metadata ----------------------------------

        mode = image->checkMode(Exiv2::mdIptc);

        if ((mode == Exiv2::amWrite) || (mode == Exiv2::amReadWrite))
        {
            image->setIptcData(iptcMetadata());
            wroteIPTC = true;
        }

        qCDebug(DIGIKAM_METAENGINE_LOG) << "wroteIPTC: " << wroteIPTC;

        // Xmp metadata -----------------------------------

        mode = image->checkMode(Exiv2::mdXmp);

        if ((mode == Exiv2::amWrite) || (mode == Exiv2::amReadWrite))
        {
#ifdef _XMP_SUPPORT_
            image->setXmpData(xmpMetadata());
            wroteXMP = true;
#endif
        }

        qCDebug(DIGIKAM_METAENGINE_LOG) << "wroteXMP: " << wroteXMP;

        if (!wroteComment && !wroteEXIF && !wroteIPTC && !wroteXMP)
        {
            qCDebug(DIGIKAM_METAENGINE_LOG) << "Writing metadata is not supported for file" << finfo.fileName();
            return false;
        }
        else if (!wroteEXIF || !wroteIPTC || !wroteXMP)
        {
            qCDebug(DIGIKAM_METAENGINE_LOG) << "Support for writing metadata is limited for file" << finfo.fileName();
        }

        if (!updateFileTimeStamp)
        {
            // Don't touch access and modification timestamp of file.
            struct stat    st;
            struct utimbuf ut;
            int ret = ::stat(QFile::encodeName(filePath).constData(), &st);

            if (ret == 0)
            {
                ut.modtime = st.st_mtime;
                ut.actime  = st.st_atime;
            }

            image->writeMetadata();

            if (ret == 0)
            {
                ::utime(QFile::encodeName(filePath).constData(), &ut);
            }

            qCDebug(DIGIKAM_METAENGINE_LOG) << "File time stamp restored";
        }
        else
        {
            image->writeMetadata();
        }

        return true;
    }
    catch( Exiv2::Error& e )
    {
        printExiv2ExceptionError(QString::fromLatin1("Cannot save metadata using Exiv2 "), e);
    }
    catch(...)
    {
        qCCritical(DIGIKAM_METAENGINE_LOG) << "Default exception from Exiv2";
    }

    return false;
}
Ejemplo n.º 15
0
bool MetaEngine::Private::saveToFile(const QFileInfo& finfo) const
{
    if (!finfo.isWritable())
    {
        qCDebug(DIGIKAM_METAENGINE_LOG) << "File" << finfo.fileName() << "is read only. Metadata not written.";
        return false;
    }

    QStringList rawTiffBasedSupported, rawTiffBasedNotSupported;

    // Raw files supported by Exiv2 0.21
    rawTiffBasedSupported << QString::fromLatin1("dng")
                          << QString::fromLatin1("nef")
                          << QString::fromLatin1("pef")
                          << QString::fromLatin1("orf")
                          << QString::fromLatin1("srw");

    if (Exiv2::testVersion(0,23,0))
    {
        rawTiffBasedSupported << QString::fromLatin1("cr2");
    }

    // Raw files not supported by Exiv2 0.21
    rawTiffBasedNotSupported << QString::fromLatin1("3fr")
                             << QString::fromLatin1("arw")
                             << QString::fromLatin1("dcr")
                             << QString::fromLatin1("erf")
                             << QString::fromLatin1("k25")
                             << QString::fromLatin1("kdc")
                             << QString::fromLatin1("mos")
                             << QString::fromLatin1("raw")
                             << QString::fromLatin1("sr2")
                             << QString::fromLatin1("srf")
                             << QString::fromLatin1("rw2");

    if (!Exiv2::testVersion(0,23,0))
    {
        rawTiffBasedNotSupported << QString::fromLatin1("cr2");
    }

    QString ext = finfo.suffix().toLower();

    if (!writeRawFiles && (rawTiffBasedSupported.contains(ext) || rawTiffBasedNotSupported.contains(ext)) )
    {
        qCDebug(DIGIKAM_METAENGINE_LOG) << finfo.fileName()
                               << "is a TIFF based RAW file, writing to such a file is disabled by current settings.";
        return false;
    }

/*
    if (rawTiffBasedNotSupported.contains(ext))
    {
        qCDebug(DIGIKAM_METAENGINE_LOG) << finfo.fileName()
                               << "is TIFF based RAW file not yet supported. Metadata not saved.";
        return false;
    }

    if (rawTiffBasedSupported.contains(ext) && !writeRawFiles)
    {
        qCDebug(DIGIKAM_METAENGINE_LOG) << finfo.fileName()
                               << "is TIFF based RAW file supported but writing mode is disabled. "
                               << "Metadata not saved.";
        return false;
    }

    qCDebug(DIGIKAM_METAENGINE_LOG) << "File Extension: " << ext << " is supported for writing mode";

    bool ret = false;
*/

    try
    {
        Exiv2::Image::AutoPtr image;
        image = Exiv2::ImageFactory::open((const char*)(QFile::encodeName(finfo.filePath()).constData()));
        return saveOperations(finfo, image);
    }
    catch( Exiv2::Error& e )
    {
        printExiv2ExceptionError(QString::fromLatin1("Cannot save metadata to image using Exiv2 "), e);
        return false;
    }
    catch(...)
    {
        qCCritical(DIGIKAM_METAENGINE_LOG) << "Default exception from Exiv2";
        return false;
    }
}