示例#1
0
void DocumentWatcher::processUpdates()
{
	while (!m_updates.isEmpty()) {
		QString path = m_updates.takeFirst();
		QString filename = "<i>" + QFileInfo(path).fileName() + "</i>";

		// Show document
		Document* document = m_paths.value(path);
		if (!document) {
			continue;
		}
		emit showDocument(document);

		if (QFile::exists(path)) {
			// Process changed file
			QMessageBox mbox(document->window());
			mbox.setIcon(QMessageBox::Warning);
			mbox.setWindowTitle(tr("File Changed"));
			mbox.setText(tr("The file %1 was changed by another program.").arg(filename));
			mbox.setInformativeText(tr("Do you want to reload the file?"));

			QPushButton* reload_button = mbox.addButton(tr("Reload"), QMessageBox::AcceptRole);
			if (reload_button->style()->styleHint(QStyle::SH_DialogButtonBox_ButtonsHaveIcons)) {
				reload_button->setIcon(reload_button->style()->standardIcon(QStyle::SP_BrowserReload));
			}
			QPushButton* ignore_button = mbox.addButton(QMessageBox::Cancel);
			ignore_button->setText(tr("Ignore"));
			mbox.setDefaultButton(reload_button);

			mbox.exec();
			if (mbox.clickedButton() == reload_button) {
				document->reload(false);
			}
		} else  {
			// Process deleted file
			QMessageBox mbox(document->window());
			mbox.setIcon(QMessageBox::Warning);
			mbox.setWindowTitle(tr("File Deleted"));
			mbox.setText(tr("The file %1 was deleted by another program.").arg(filename));
			mbox.setInformativeText(tr("Do you want to save or close the file?"));

			mbox.setStandardButtons(QMessageBox::Save | QMessageBox::Close);
			mbox.setDefaultButton(QMessageBox::Save);

			if (mbox.exec() == QMessageBox::Save) {
				document->save();
			} else {
				emit closeDocument(document);
			}
		}
	}
}
示例#2
0
static void mail_func_delete(t_connection * c, std::istream& istr)
{
	if (!c) {
		ERROR0("got NULL connection");
		return;
	}

	std::string token;
	istr >> token;

	if (token.empty()) {
		message_send_text(c,message_type_error,c,"Please specify which message to delete. Use the following syntax: /mail delete {<index>|all} .");
		return;
	}

	t_account * user = conn_get_account(c);
	Mailbox mbox(account_get_uid(user));

	if (token == "all") {
		mbox.clear();
		message_send_text(c, message_type_info, c, "Successfully deleted messages.");
	} else {
		if (std::find_if(token.begin(), token.end(), NonNumericChar) != token.end()) {
			message_send_text(c,message_type_error,c,"Invalid index. Please use /mail delete {<index>|all} where <index> is a number.");
			return;
		}

		mbox.erase(std::atoi(token.c_str()));
		message_send_text(c,message_type_info,c, "Succesfully deleted message.");
	}
}
示例#3
0
文件: files.cpp 项目: cpavlina/kicad
bool GERBVIEW_FRAME::LoadZipArchiveFile( const wxString& aFullFileName )
{
#define ZipFileExtension "zip"

    wxFileName filename = aFullFileName;
    wxString currentPath;

    if( !filename.IsOk() )
    {
        // Use the current working directory if the file name path does not exist.
        if( filename.DirExists() )
            currentPath = filename.GetPath();
        else
            currentPath = m_mruPath;

        wxFileDialog dlg( this,
                          _( "Open Zip File" ),
                          currentPath,
                          filename.GetFullName(),
                          ZipFileWildcard(),
                          wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_CHANGE_DIR );

        if( dlg.ShowModal() == wxID_CANCEL )
            return false;

        filename = dlg.GetPath();
        currentPath = wxGetCwd();
        m_mruPath = currentPath;
    }
    else
    {
        currentPath = filename.GetPath();
        m_mruPath = currentPath;
    }

    wxString msg;
    WX_STRING_REPORTER reporter( &msg );

    if( filename.IsOk() )
        unarchiveFiles( filename.GetFullPath(), &reporter );

    Zoom_Automatique( false );

    // Synchronize layers tools with actual active layer:
    ReFillLayerWidget();
    SetActiveLayer( GetActiveLayer() );
    m_LayersManager->UpdateLayerIcons();
    syncLayerBox();

    if( !msg.IsEmpty() )
    {
        wxSafeYield();  // Allows slice of time to redraw the screen
                        // to refresh widgets, before displaying messages
        HTML_MESSAGE_BOX mbox( this, _( "Messages" ) );
        mbox.ListSet( msg );
        mbox.ShowModal();
    }

    return true;
}
示例#4
0
void Document::reload(bool prompt)
{
	// Abort if there is no file to reload
	if (m_index) {
		return;
	}

	// Confirm that they do want to reload
	if (prompt) {
		QMessageBox mbox(window());
		mbox.setIcon(QMessageBox::Question);
		mbox.setWindowTitle(tr("Reload File"));
		mbox.setText(tr("Reload the file %1 from disk?").arg("<i>" + QFileInfo(m_filename).fileName() + "</i>"));
		mbox.setInformativeText(tr("All unsaved changes will be lost."));

		QPushButton* reload_button = mbox.addButton(tr("Reload"), QMessageBox::AcceptRole);
		if (reload_button->style()->styleHint(QStyle::SH_DialogButtonBox_ButtonsHaveIcons)) {
			reload_button->setIcon(reload_button->style()->standardIcon(QStyle::SP_BrowserReload));
		}
		mbox.addButton(QMessageBox::Cancel);
		mbox.setDefaultButton(reload_button);

		if (mbox.exec() == QMessageBox::Cancel) {
			return;
		}
	}

	// Reload file
	emit loadStarted(Window::tr("Opening %1").arg(QDir::toNativeSeparators(m_filename)));
	m_text->setReadOnly(true);
	disconnect(m_text->document(), SIGNAL(contentsChange(int,int,int)), this, SLOT(updateWordCount(int,int,int)));
	disconnect(m_text->document(), SIGNAL(undoCommandAdded()), this, SLOT(undoCommandAdded()));
	loadFile(m_filename, -1);
	emit loadFinished();
}
示例#5
0
void MBoxProtocol::listDir(const QUrl &url)
{
    m_errorState = false;

    KIO::UDSEntry entry;
    UrlInfo info(url, UrlInfo::directory);
    ReadMBox mbox(&info, this, hasMetaData(QStringLiteral("onlynew")), hasMetaData(QStringLiteral("savetime")));

    if (m_errorState) {
        return;
    }

    if (info.type() != UrlInfo::directory) {
        error(KIO::ERR_DOES_NOT_EXIST, info.url());
        return;
    }

    while (!mbox.atEnd() && !m_errorState) {
        entry = Stat::stat(mbox, info);
        if (mbox.inListing()) {
            listEntry(entry);
        }
    }

    finished();
}
示例#6
0
void MBoxProtocol::get(const QUrl &url)
{
    m_errorState = false;

    UrlInfo info(url, UrlInfo::message);
    QString line;
    QByteArray ba_line;

    if (info.type() == UrlInfo::invalid && !m_errorState) {
        error(KIO::ERR_DOES_NOT_EXIST, info.url());
        return;
    }

    ReadMBox mbox(&info, this);

    while (!mbox.atEnd() && !m_errorState) {
        line = mbox.currentLine();
        line += QLatin1Char('\n');
        ba_line = QByteArray(line.toUtf8());
        ba_line.truncate(ba_line.size() - 1);   //Removing training '\0'
        data(ba_line);
        mbox.nextLine();
    };

    if (!m_errorState) {
        data(QByteArray());
        finished();
    }
}
bool OutputCalibrationPage::checkAlarms()
{
    ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
    UAVObjectManager *uavObjectManager = pm->getObject<UAVObjectManager>();

    Q_ASSERT(uavObjectManager);
    SystemAlarms *systemAlarms    = SystemAlarms::GetInstance(uavObjectManager);
    Q_ASSERT(systemAlarms);
    SystemAlarms::DataFields data = systemAlarms->getData();

    if (data.Alarm[SystemAlarms::ALARM_ACTUATOR] != SystemAlarms::ALARM_OK) {
        QMessageBox mbox(this);
        mbox.setText(QString(tr("The actuator module is in an error state.\n\n"
                                "Please make sure the correct firmware version is used then "
                                "restart the wizard and try again. If the problem persists please "
                                "consult the openpilot.org support forum.")));
        mbox.setStandardButtons(QMessageBox::Ok);
        mbox.setIcon(QMessageBox::Critical);

        getWizard()->setWindowFlags(getWizard()->windowFlags() & ~Qt::WindowStaysOnTopHint);

        mbox.exec();

        getWizard()->setWindowFlags(getWizard()->windowFlags() | Qt::WindowStaysOnTopHint);
        getWizard()->setWindowIcon(qApp->windowIcon());
        getWizard()->show();
        return false;
    }
    return true;
}
//**************************************************************************
// AServerWindow :: addDone(..)
//**************************************************************************
bool AServerWindow::addDone(char * newDone)
{
  doneList.addAsLast(newDone);          //Add new done item
  try
  {
    unsigned long index=                //Locate this item in the work list
      workList.locateText(newDone);
    workList.remove(index);             //Remove from work list
  }
  catch (IException& exc)               //Catch Error
  {                                     //
    IMessageBox mbox(this);             //Create Message Box
    mbox.show(exc);                     //
    return false;                       //Return error
  }                                     //
  updateStatus();                       //Update status
  if (hot)                              //Is hot link active?
  {
    log( MI_HOTLINKUPDATE_HOTWORK );
    server.hotLinkUpdate( resLib.loadString( MI_HOTWORK ));  //Update work hot link
    log( MI_HOTLINKUPDATE_HOTDONE );
    server.hotLinkUpdate( resLib.loadString( MI_HOTDONE ));  //Update done hot link
  } /* endif */
  return true;
} /* end AServerWindow :: addDone(..) */
示例#9
0
static void fileError(int err,QString file){
    QMessageBox mbox(QMessageBox::Critical,
                     "Cannot open file",
                     QString("File : "+file+"\nError code: ")+QString::number(err),
                     QMessageBox::Ok
                     );
    mbox.exec();
    
}
示例#10
0
void execWindow::on_pushButton_2_clicked()
{
    QMessageBox mbox(QMessageBox::Question,tr("Abort"),tr("Abort action?"),QMessageBox::Yes|QMessageBox::No,this);
    if(mbox.exec()==QMessageBox::No)
    {
        m_ui->plainTextEdit->ensureCursorVisible();
        return;
    }

    if(m_proc && m_proc->state()!=QProcess::NotRunning)
        m_proc->kill();
}
示例#11
0
/*
 * 1. copy old config file to backup
 * 2. save boards to new config file
 * 3. then copy new to old config file
 */
void Hardware::saveBoards()
{
    QString back = +".backup";
    QMessageBox mbox(QMessageBox::Critical,tr("xBasic.cfg File Error"),"", QMessageBox::Ok);
    QFile file;
    if(!file.exists(xBasicCfgFile)) {
        mbox.setInformativeText(tr("Can't find file: ")+xBasicCfgFile);
        mbox.exec();
        return;
    }
    QFile cfg(xBasicCfgFile);
/*
    QFile bup(this->xBasicCfgFile+back);
    if(bup.exists()) bup.remove();
    if(!cfg.copy(this->xBasicCfgFile+back)) {
        mbox.setInformativeText(tr("Can't backup file: ")+xBasicCfgFile);
        mbox.exec();
        return;
    }
*/
    QByteArray barry = "";
    QString currentName = ui->comboBoxBoard->currentText().toUpper();
    XBasicBoard *board = xBasicConfig->getBoardByName(currentName);
    if(board == NULL)
        ui->comboBoxBoard->addItem(currentName);
    for(int n = 0; n < ui->comboBoxBoard->count(); n++)
    {
        QString name = ui->comboBoxBoard->itemText(n);
        XBasicBoard *board = xBasicConfig->getBoardByName(name);
        if(board == NULL && name == currentName)
            board = xBasicConfig->newBoard(name);
        if(name == currentName)
            setBoardInfo(board);
        QString ba = board->getFormattedConfig();
        qDebug() << ba;
        barry.append(ba);
    }


    QMessageBox sbox(QMessageBox::Question,tr("Saving xBasic.cfg File"),"",
                     QMessageBox::Save | QMessageBox::Cancel);

    sbox.setInformativeText(tr("Save new ")+xBasicCfgFile+tr("?"));

    if(sbox.exec() == QMessageBox::Save) {
        if(cfg.open(QIODevice::WriteOnly | QFile::Text)) {
            cfg.write(barry);
            cfg.flush();
            cfg.close();
        }
    }
}
示例#12
0
void handle_missing_pdf_viewer() {

    QMessageBox mbox(QMessageBox::Critical, "Error",
                     "Error: failed to find the application that could open pdf files!\n"
                     "Try to download such an application now?",
                     QMessageBox::Yes | QMessageBox::No);

    int ret = mbox.exec();

    if (ret==QMessageBox::Yes) {

        openWithDefaultApp("http://get.adobe.com/reader/");
    }
}
示例#13
0
void AnotherMainWindow::on_CreateFileDialog_accepted()
{

    if(_createFileParams->IsFileOpenError)
    {
        QMessageBox mbox(QMessageBox::Warning, "Error", _createFileParams->FileOpenError + ".");
        mbox.exec();
        return;
    }
    ui->DurationBox->setText(QString::number(_createFileParams->LastOperationDuration));
    _openedFiles.append(_createFileParams);
    QMessageBox::information(0, "Информация", "Операция создания/открытия файла успешно завершена.");
    ui->OpenedFilesList->addItem(_createFileParams->FileName);
}
示例#14
0
void MainWindow::onActionOpenMeshFileObjTriggered()
{
    ///QString filename = QFileDialog::getOpenFileName(this,"Open file...","","Wavefront object mesh (*.obj);;");
    QString filename("/home/carlo/workspace/cncsvisioncmake/data/objmodels/face.obj");
    if (filename.isEmpty())
    {
        QMessageBox mbox(this);
        mbox.setIcon(QMessageBox::Critical);
        mbox.setText("You must select a valid file.Now exiting!");
        mbox.setStandardButtons(QMessageBox::Close);
        mbox.show();
        mbox.exec();
        exit(0);
    }
    QFileInfo info(filename);
    if (!info.exists())
    {
        QMessageBox mbox(this);
        mbox.setIcon(QMessageBox::Critical);
        mbox.setText("File does not exist!");
        //  mbox.setWindowModality(Qt::WindowModal);
        mbox.setStandardButtons(QMessageBox::Close);
        mbox.show();
        mbox.exec();
    }
    else
    {
        ui->glWidgetGeometry->loadMesh(filename);
        ui->glWidgetGeometry->computeProjectionsBackward();
        ui->glWidgetGeometry->repaint();
    }
    ui->spinBoxRayIndex->setRange(0,ui->glWidgetGeometry->getParameters()->meshVertices-1);

    QObject::connect(ui->glWidgetGeometry,SIGNAL(verticesChanged(GLfloat*,unsigned int)),ui->glShaderWidget,SLOT(setVertices(GLfloat*,unsigned int)));
    ui->glShaderWidget->setParameters( ui->glWidgetGeometry->getParameters());
}
// Show error with option to open settings.
static inline void showGraphicalShellError(QWidget *parent,
                                           const QString &app,
                                           const QString &error)
{
    const QString title = FolderNavigationWidget::tr("Launching a file browser failed");
    const QString msg = FolderNavigationWidget::tr("Unable to start the file manager:\n\n%1\n\n").arg(app);
    QMessageBox mbox(QMessageBox::Warning, title, msg, QMessageBox::Close, parent);
    if (!error.isEmpty())
        mbox.setDetailedText(FolderNavigationWidget::tr("'%1' returned the following error:\n\n%2").arg(app, error));
    QAbstractButton *settingsButton = mbox.addButton(FolderNavigationWidget::tr("Settings..."), QMessageBox::ActionRole);
    mbox.exec();
    if (mbox.clickedButton() == settingsButton)
        Core::ICore::instance()->showOptionsDialog(QLatin1String(Core::Constants::SETTINGS_CATEGORY_CORE),
                                                   QLatin1String(Core::Constants::SETTINGS_ID_ENVIRONMENT));
}
示例#16
0
void SectionSetupForm::errorMessage(const char* err_text) {

    //---(*)---Zuskin---15/02/2012---
    //QMessageBox::critical(this, toForm("Ошибка"), toForm(err_text) );
    QMessageBox mbox(this);
    mbox.setIcon(QMessageBox::Critical);
    mbox.setWindowTitle(toForm("Ошибка"));
    mbox.setText(toForm(err_text));
    mbox.addButton(QMessageBox::Ok);
    
    if (this->isActiveWindow()==false) {
        mbox.setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, this->size(), qApp->desktop()->availableGeometry()));
    }
    mbox.exec();
    //-------------------------------
}
示例#17
0
// Show error with option to open settings.
static void showGraphicalShellError(QWidget *parent, const QString &app, const QString &error)
{
    const QString title = QApplication::translate("Core::Internal",
                                                  "Launching a file browser failed");
    const QString msg = QApplication::translate("Core::Internal",
                                                "Unable to start the file manager:\n\n%1\n\n").arg(app);
    QMessageBox mbox(QMessageBox::Warning, title, msg, QMessageBox::Close, parent);
    if (!error.isEmpty())
        mbox.setDetailedText(QApplication::translate("Core::Internal",
                                                     "'%1' returned the following error:\n\n%2").arg(app, error));
    QAbstractButton *settingsButton = mbox.addButton(QApplication::translate("Core::Internal", "Settings..."),
                                                     QMessageBox::ActionRole);
    mbox.exec();
    if (mbox.clickedButton() == settingsButton)
        ICore::showOptionsDialog(Constants::SETTINGS_CATEGORY_CORE, Constants::SETTINGS_ID_ENVIRONMENT);
}
示例#18
0
void handle_missing_spreadsheet_editor() {

    // TODO Try to resolve it on loading the applicaton,
    // somewhat ugly that it occurs later on demand

    QMessageBox mbox(QMessageBox::Critical, "Error",
                     "Error: failed to find the application that could open spreadsheet documents!\n"
                     "Try to download such an application now?",
                     QMessageBox::Yes | QMessageBox::No);

    int ret = mbox.exec();

    if (ret==QMessageBox::Yes) {

        openWithDefaultApp("http://www.openoffice.org/download/");
    }
}
示例#19
0
		static void mail_func_send(t_connection * c, std::istream& istr)
		{
			if (!c) {
				ERROR0("got NULL connection");
				return;
			}

			std::string dest;
			istr >> dest;
			if (dest.empty()) {
				message_send_text(c, message_type_error, c, "You must specify the receiver");
				message_send_text(c, message_type_error, c, "Syntax: /mail send <receiver> <message>");
				return;
			}

			std::string message;
			std::getline(istr, message);
			std::string::size_type pos(message.find_first_not_of(" \t"));
			if (pos == std::string::npos) {
				message_send_text(c, message_type_error, c, "Your message is empty!");
				message_send_text(c, message_type_error, c, "Syntax: /mail send <receiver> <message>");
				return;
			}

			t_account * recv = accountlist_find_account(dest.c_str());
			if (!recv) {
				message_send_text(c, message_type_error, c, "Receiver UNKNOWN!");
				return;
			}

			Mailbox mbox(account_get_uid(recv));
			if (get_mail_quota(recv) <= mbox.size()) {
				message_send_text(c, message_type_error, c, "Receiver has reached his mail quota. Your message will NOT be sent.");
				return;
			}

			try {
				mbox.deliver(conn_get_username(c), message.substr(pos));
				message_send_text(c, message_type_info, c, "Your mail has been sent successfully.");
			}
			catch (const Mailbox::DeliverError&) {
				message_send_text(c, message_type_error, c, "There was an error completing your request!");
			}
		}
示例#20
0
		static transform_indicator_t< SOURCE >
		limit_then_transform(
			unsigned int limit,
			LAMBDA transformator )
			{
				ensure_signal< SOURCE >();

				action_t act = [transformator]( const overlimit_context_t & ctx ) {
						// Service request cannot be transformed.
						// So ensure that is event, not service request.
						impl::ensure_event_transform_reaction( ctx );

						auto r = transformator();
						impl::transform_reaction(
								ctx, r.mbox(), r.msg_type(), r.message() );
					};

				return transform_indicator_t< SOURCE >{ limit, std::move( act ) };
			}
示例#21
0
		static transform_indicator_t< ARG >
		limit_then_transform(
			unsigned int limit,
			LAMBDA transformator )
			{
				ensure_not_signal< ARG >();

				action_t act = [transformator]( const overlimit_context_t & ctx ) {
						// Service request cannot be transformed.
						// So ensure that is event, not service request.
						impl::ensure_event_transform_reaction( ctx );

						const ARG & msg = dynamic_cast< const ARG & >(
								*ctx.m_message.get() );
						auto r = transformator( msg );
						impl::transform_reaction(
								ctx, r.mbox(), r.msg_type(), r.message() );
					};

				return transform_indicator_t< ARG >{ limit, std::move( act ) };
			}
示例#22
0
	void testWhitespaceMBox()
	{
		// Space MUST be encoded inside a word
		vmime::mailbox mbox(vmime::text("Achim Br\xc3\xa4ndt", vmime::charsets::UTF_8), "*****@*****.**");
		VASSERT_EQ("generate1", "=?us-ascii?Q?Achim_?= =?utf-8?Q?Br=C3=A4ndt?= <*****@*****.**>", mbox.generate());

		vmime::text txt;
		txt.appendWord(vmime::create <vmime::word>("Achim ", "us-ascii"));
		txt.appendWord(vmime::create <vmime::word>("Br\xc3\xa4ndt", "utf-8"));
		mbox = vmime::mailbox(txt, "*****@*****.**");
		VASSERT_EQ("generate2", "=?us-ascii?Q?Achim_?= =?utf-8?Q?Br=C3=A4ndt?= <*****@*****.**>", mbox.generate());

		mbox.parse("=?us-ascii?Q?Achim?= =?utf-8?Q?Br=C3=A4ndt?= <*****@*****.**>");
		VASSERT_EQ("parse.name.count", 2, mbox.getName().getWordCount());
		VASSERT_EQ("parse.name.word1.buffer", "Achim", mbox.getName().getWordAt(0)->getBuffer());
		VASSERT_EQ("parse.name.word1.charset", "us-ascii", mbox.getName().getWordAt(0)->getCharset());
		VASSERT_EQ("parse.name.word2.buffer", "Br\xc3\xa4ndt", mbox.getName().getWordAt(1)->getBuffer());
		VASSERT_EQ("parse.name.word2.charset", "utf-8", mbox.getName().getWordAt(1)->getCharset());

		VASSERT_EQ("parse.email", "*****@*****.**", mbox.getEmail());
	}
示例#23
0
void cClientWidget::show_clientInfo()
{
    QMessageBox mbox(this);
    mbox.setText(m_client->info());
    mbox.exec();
}
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
void CIpsSosAOImapAgent::PopulateAllL()
    {
    FUNC_LOG;
    TImImap4GetPartialMailInfo info;
    //<QMail>
    CIpsSosAOSettingsHandler* settings = 
             CIpsSosAOSettingsHandler::NewL(iSession, iServiceId);
     CleanupStack::PushL(settings);
     settings->ConstructImapPartialFetchInfo( info, *iImapSettings );
     CleanupStack::PopAndDestroy(settings);	
	//</QMail>
    
    if ( !IsConnected() )
        {
        SignalSyncCompleted( iServiceId, iError );
        CancelAllAndDisconnectL();
        }
	//<QMail>
    else if ( iFoldersArray.Count() > 0 && info.iTotalSizeLimit 
            != KIpsSetDataHeadersOnly )
	//</QMail>
         {

         // only inbox is set, do we have to populate other folders also
         TMsvId id = iFoldersArray[0];
         CMsvEntry* cEntry = iSession.GetEntryL( id );
         CleanupStack::PushL( cEntry );
         CMsvEntrySelection* sel = cEntry->ChildrenWithTypeL( 
                 KUidMsvMessageEntry ); 
         CleanupStack::PushL( sel );
         
         info.iDestinationFolder = iFoldersArray[0];
         
         CIpsPlgTimerOperation* dummy = NULL;
         iImapClientMtm->SwitchCurrentEntryL( iServiceId );
         TFSMailMsgId mbox( KIpsPlgImap4PluginUidValue, iServiceId );
         iStatus = KRequestPending;
		 //<Qmail>
         iOngoingOp = CIpsPlgImap4PopulateOp::NewL(
                 iSession,
                 this->iStatus,
                 iServiceId,
                 *dummy,
                 info,
                 *sel,
                 mbox,
                 this,
                 0,
                 NULL );
         //</Qmail>
         iFoldersArray.Remove( 0 );
         SetActive();
         iState = EStatePopulateAll;
         CleanupStack::PopAndDestroy( 2, cEntry );
         
         }
     else
         {
         iState = EStateDisconnect;
         SignalSyncStarted( iServiceId );
         SetActiveAndCompleteThis();
         }
    }
示例#25
0
int KMailBox::countMail()
{
	QFile mbox(_file);
	char *buffer = new char[MAXSTR];
	int count=0, msgCount=0;
	bool inHeader = false;
	bool hasContentLen = false;
	bool msgRead = false;
	long contentLength=0;

	if( isLocked() ){
//		debug("countMail: locked. returning.");
		delete[] buffer;
		return _numMessages;
	}

	if(!mbox.open(IO_ReadOnly)) {
		warning(i18n("countMail: file open error"));
		emit fileError();
		delete[]buffer;
		return 0;
	}

	buffer[MAXSTR-1] = 0;

	while(mbox.readLine(buffer, MAXSTR-2) > 0) {

		if( !strchr(buffer, '\n') && !mbox.atEnd() ){
			int c;

			while( (c=mbox.getch()) >=0 && c !='\n' )
				;
		}

		if( !inHeader && realfrom(buffer) ) {
			hasContentLen = false;
			inHeader = true;
			msgRead = false;
		}
		else if ( inHeader ){
			if (compareHeader(buffer, "Content-Length")){
				hasContentLen = true;
				contentLength = atol(buffer+15);
			}

			if (compareHeader(buffer, "Status")) {
				const char *field = buffer;
				field += 7;
				while(field && (*field== ' '||*field == '\t'))
					field++;

				if ( *field == 'N' || *field == 'U' )
					msgRead = false;
				else
					msgRead = true;
			}
			else if (buffer[0] == '\n' ) {
				if( hasContentLen )
					mbox.at( mbox.at() + contentLength);

				inHeader = false;

				if ( !msgRead )
					count++;
			} 
		}//in header

		if(++msgCount >= 100 ) {
			qApp->processEvents();
			msgCount = 0;
		}
	}//while

	mbox.close();

	delete[] buffer;
	return count;

}//countMail
示例#26
0
static void mail_func_read(t_connection * c, std::istream& istr)
{
	if (!c) {
		ERROR0("got NULL connection");
		return;
	}

	std::string token;
	istr >> token;

	t_account * user = conn_get_account(c);
	Mailbox mbox(account_get_uid(user));

	if (token.empty()) { /* user wants to see the mail summary */
		if (mbox.empty()) {
			message_send_text(c,message_type_info,c,"You have no mail.");
			return;
		}

		MailList mlist;
		mbox.readAll(mlist);

		std::ostringstream ostr;
		ostr << "You have " << mbox.size() << " messages. Your mail quote is set to " << get_mail_quota(user) << '.';
		message_send_text(c, message_type_info, c, ostr.str().c_str());
		message_send_text(c, message_type_info, c, "ID    Sender          Date");
		message_send_text(c, message_type_info, c, "-------------------------------------");

		for(MailList::const_iterator it(mlist.begin()); it != mlist.end(); ++it) {
			ostr.str("");
			ostr << std::setfill('0') << std::setw(2) << std::right << (it - mlist.begin()) << "    "
			     << std::setfill(' ') << std::setw(14) << std::left << it->sender() << ' ';
			char buff[128];
			std::strftime(buff, sizeof(buff), "%a %b %d %H:%M:%S %Y", std::localtime(&it->timestamp()));
			ostr << buff;
			message_send_text(c, message_type_info, c, ostr.str().c_str());
		}

		message_send_text(c,message_type_info,c,"Use /mail read <ID> to read the content of any message");
	} else { /* user wants to read a message */
		if (std::find_if(token.begin(), token.end(), NonNumericChar) != token.end()) {
			message_send_text(c,message_type_error,c,"Invalid index. Please use /mail read <index> where <index> is a number.");
			return;
		}

		try {
			unsigned idx = std::atoi(token.c_str());
			Mail mail(mbox.read(idx));

			std::ostringstream ostr;
			ostr << "Message #" << idx << " from " << mail.sender() << " on ";
			char buff[128];
			std::strftime(buff, sizeof(buff), "%a %b %d %H:%M:%S %Y", std::localtime(&mail.timestamp()));
			ostr << buff << ':';
			message_send_text(c, message_type_info, c, ostr.str().c_str());
			message_send_text(c, message_type_info, c, mail.message().c_str());
		} catch (const Mailbox::ReadError&) {
			message_send_text(c,message_type_error,c,"There was an error completing your request.");
		}
	}
}
void DocumentWatcher::processUpdates()
{
	while (!m_updates.isEmpty()) {
		QString path = m_updates.takeFirst();
		QFileInfo info(path);
		QString filename = info.fileName();

		// Find document
		Document* document = m_paths.value(path);
		if (!document) {
			continue;
		}
		const Details& details = m_documents[document];
		if (details.ignored) {
			continue;
		}

		// Ignore unchanged documents
		if (info.exists() && (details.modified == info.lastModified()) && (details.permissions == info.permissions())) {
			continue;
		}

		// Show document
		emit showDocument(document);

		if (info.exists()) {
			// Process changed file
			QMessageBox mbox(document->window());
			mbox.setIcon(QMessageBox::Warning);
			mbox.setWindowTitle(tr("File Changed"));
			mbox.setText(tr("The file '%1' was changed by another program.").arg(filename));
			mbox.setInformativeText(tr("Do you want to reload the file?"));

			QPushButton* reload_button = mbox.addButton(tr("Reload"), QMessageBox::AcceptRole);
			if (reload_button->style()->styleHint(QStyle::SH_DialogButtonBox_ButtonsHaveIcons)) {
				reload_button->setIcon(reload_button->style()->standardIcon(QStyle::SP_BrowserReload));
			}
			QPushButton* ignore_button = mbox.addButton(QMessageBox::Cancel);
			ignore_button->setText(tr("Ignore"));
			mbox.setDefaultButton(reload_button);

			mbox.exec();
			if (mbox.clickedButton() == reload_button) {
				document->reload(false);
			}
		} else  {
			// Process deleted file
			QMessageBox mbox(document->window());
			mbox.setIcon(QMessageBox::Warning);
			mbox.setWindowTitle(tr("File Deleted"));
			mbox.setText(tr("The file %1 was deleted by another program.").arg(filename));
			mbox.setInformativeText(tr("Do you want to save or close the file?"));

			mbox.setStandardButtons(QMessageBox::Save | QMessageBox::Close | QMessageBox::Ignore);
			mbox.setDefaultButton(QMessageBox::Save);

			QAbstractButton* save_button = mbox.button(QMessageBox::Save);

			QAbstractButton* ignore_button = mbox.button(QMessageBox::Ignore);
			if (ignore_button->icon().isNull() && ignore_button->style()->styleHint(QStyle::SH_DialogButtonBox_ButtonsHaveIcons)) {
				ignore_button->setIcon(ignore_button->style()->standardIcon(QStyle::SP_MessageBoxWarning));
			}

			mbox.exec();
			if (mbox.clickedButton() == save_button) {
				document->save();
			} else if (mbox.clickedButton() == ignore_button) {
				document->setModified(true);
			} else {
				emit closeDocument(document);
			}
		}
	}
}
示例#28
0
int main( int argc, char **argv )
{
    QApplication::setColorSpec( QApplication::CustomColor );
    QApplication * a = new QApplication( argc, argv );
    
    QString appname( "xpracman" );
    QString applabel( "XpracMan" );
    ::XpracManDir = getenv("PRAC_DIR");
    if ( !XpracManDir.length() )
        XpracManDir = QMVAPPLICATIONDIR;
    
    QString dbname = getenv( "PGDATABASE" );
    QString dbaccessname = getenv( "MARVINACCESS" );
    QString dbhost = getenv( "PGHOST" );
    QString dbport = getenv( "PGPORT" );
    
    int debug = 0;
    int wapp = 800;
    int happ = 600;
    bool maximize = false;
    
    for ( int i = 1; i < a->argc(); i++ )
    {
        if ( QString( a->argv()[i] ) == "--debug" )
        {
            debug = 1;
            continue;
        }
        if ( QString( a->argv()[i] ) == "--maximize" )
        {
            maximize = true;
            continue;
        }
        qDebug( "main: argument # %d <%s>", i, a->argv()[i] );
        if ( QString( a->argv()[i] ) == "--pracdir" )
        {
            ++i;
            XpracManDir = QString( a->argv()[i] );
            continue;
        }
        if ( QString( a->argv()[i] ) == "--database" )
        {
            ++i;
            dbname = QString( a->argv()[i] );
            continue;
        }
        if ( QString( a->argv()[i] ) == "--database-host" )
        {
            ++i;
            dbhost = QString( a->argv()[i] );
            continue;
        }
        if ( QString( a->argv()[i] ) == "--database-port" )
        {
            ++i;
            dbport = QString( a->argv()[i] );
            continue;
        }
        if ( QString( a->argv()[i] ) == "--accessdb" )
        {
            ++i;
            dbaccessname = QString( a->argv()[i] );
            continue;
        }
        if ( QString( a->argv()[i] ) == "--applabel" )
        {
            ++i;
            applabel = QString( a->argv()[i] );
            continue;
        }
        
        QMessageBox::critical( 0, QString( "%1: Illegal argument:fatal" ).arg( appname ),
                               QString( "An unknown argument was detected.\n\n %1\n\n"
                                        "This application will now exit." )
                               .arg( QString( a->argv()[i] ) ) );
        exit(1);
        
    }

        // Start a splash screen asap
    
    QProgressDialog splash( QString("Starting %1...").arg(applabel), "Abort", 100, 0, "progress", TRUE );
    splash.setProgress( 10 );
    qApp->processEvents();
    if ( splash.wasCancelled() )
        exit(1);
    
    if ( !debug )
        qInstallMsgHandler( messageHandler );

        // ------------------------------------------------------------
        // Settle on an access database name
        // ------------------------------------------------------------
    if ( dbaccessname.isNull() || dbaccessname.length() < 1 )
        if ( dbname.isNull() || dbname.length() < 1 )
            dbaccessname = QString("marvin_access");
        else
            dbaccessname = dbname;

        // ------------------------------------------------------------
        // Create a QmvAccess object
        // ------------------------------------------------------------
    splash.setProgress( 20 );
    splash.setLabelText("Checking access rights...");
    qApp->processEvents();
    if ( splash.wasCancelled() )
        exit(1);
    
    QmvAccess * dbaccess;
    try {
        dbaccess = new QmvAccess( QString("%1:%2:%3").arg(dbaccessname).arg(dbhost).arg(dbport), 0, "db-access" );
    }
    catch ( QmvException * exception )
    {
        splash.cancel();
        QMessageBox::Icon icon;
        switch ( exception->eStatus() )
        {
            case QmvException::Critical:
                icon = QMessageBox::Critical;
                break;
            case QmvException::Warning:
                icon = QMessageBox::Warning;
                break;
            case QmvException::Information:
            default:
                icon = QMessageBox::Information;
                break;
        }
        QMessageBox mbox( QString( "%1: Fatal Error - No Access Service available" ).arg( appname ),
                          exception->eMessage(),
                          icon,
                          QMessageBox::Ok,
                          QMessageBox::NoButton,
                          QMessageBox::NoButton);
        mbox.exec();
        delete exception;
        exit(1);
    }
    

        // ------------------------------------------------------------
        // Create a QmvApplication object
        // ------------------------------------------------------------
    splash.setProgress( 40 );
    splash.setLabelText("Connecting to database...");
    qApp->processEvents();
    if ( splash.wasCancelled() )
        exit(1);
    
    QString dbtitle;
    if ( dbname.isNull() || dbname.length() < 1 )
        if ( dbaccess->dbTitleList().count() > 0 )
                // take the first database in list
            dbtitle = *(dbaccess->dbTitleList().begin());
        else
        {
            splash.cancel();
            QMessageBox mbox( QString( "%1: Fatal Error - Database not found" ).arg( appname ),
                              QString( "Unable to determine the name of the database.\n\n"
                                       " You need to either set PGDATABASE,\\"
                                       " or use the command-line argument < --database NAME >"),
                              QMessageBox::Critical,
                              QMessageBox::Ok,
                              QMessageBox::NoButton,
                              QMessageBox::NoButton);
            mbox.exec();
            exit(1);
        }
    else
    {
        dbtitle = dbaccess->dbTitleByName( dbname );
        if ( dbtitle.isNull() || dbtitle.length() < 1 )
        {
            splash.cancel();
            QMessageBox mbox( QString( "%1: Fatal Error -  Database not accessible (title)" ).arg( appname ),
                              QString( "Unable to determine details of the database <b>\"%1\"</b>.<BR><BR>"
                                       " It may be that you do not have access to this database."
                                       " Check with your administrator.").arg( dbname),
                              QMessageBox::Critical,
                              QMessageBox::Ok,
                              QMessageBox::NoButton,
                              QMessageBox::NoButton);
            mbox.exec();
            exit(1);
        }
    }

        // ------------------------------------------------------------
        // manage a pid file
        // ------------------------------------------------------------

    QString homeappdir = QString( "%1/.%2" ).arg( getenv("HOME")).arg(appname);
    QDir dir_homeappdir( homeappdir ); 
    if ( !dir_homeappdir.exists() )
    {
        if ( !dir_homeappdir.mkdir( homeappdir ) )
        {
            splash.cancel();
            QMessageBox mbox( QString( "%1: Fatal Error - configuration" ).arg( appname ),
                              QString( "Could not create the directory:<br>%1").arg(homeappdir),
                              QMessageBox::Critical,
                              QMessageBox::Ok,
                              QMessageBox::NoButton,
                              QMessageBox::NoButton);
            mbox.exec();
            exit(1);
        }
    }
        // look for existing pid file.
    QString pidfile = QString("%1/%2-%3.pid")
        .arg(homeappdir).arg(dbname).arg( getenv("DISPLAY"));
    QFile f_pidfile( pidfile);
    if ( f_pidfile.open(IO_ReadOnly) )
    {  
        QTextStream t_pidfile( &f_pidfile);
        int pid = -1;
        t_pidfile >> pid;
        int k = kill(pid, 0);
        qDebug("pid=%d, kill=%d, errno = %d", pid, k, errno);
        
        if ( pid > 0 && !(kill(pid, 0) == -1 && errno == ESRCH) )
        {
            splash.cancel();
            QMessageBox mbox( QString( "%1: Fatal Error - startup" ).arg( appname ),
                              QString( "%1 is already running(pid=%2).").arg( appname ).arg(pid),
                              QMessageBox::Critical,
                              QMessageBox::Ok,
                              QMessageBox::NoButton,
                              QMessageBox::NoButton);
            mbox.exec();
            exit(1);
        }
        f_pidfile.close();
    }
示例#29
0
文件: files.cpp 项目: cpavlina/kicad
bool GERBVIEW_FRAME::LoadGerberFiles( const wxString& aFullFileName )
{
    wxString   filetypes;
    wxArrayString filenamesList;
    wxFileName filename = aFullFileName;
    wxString currentPath;

    if( !filename.IsOk() )
    {
        /* Standard gerber filetypes
         * (See http://en.wikipedia.org/wiki/Gerber_File)
         * the .gbr (.pho in legacy files) extension is the default used in Pcbnew
         * However there are a lot of other extensions used for gerber files
         * Because the first letter is usually g, we accept g* as extension
         * (Mainly internal copper layers do not have specific extension,
         *  and filenames are like *.g1, *.g2 *.gb1 ...).
         * Now (2014) Ucamco (the company which manages the Gerber format) encourages
         * use of .gbr only and the Gerber X2 file format.
         */
        filetypes = _( "Gerber files (.g* .lgr .pho)" );
        filetypes << wxT("|");
        filetypes += wxT("*.g*;*.G*;*.pho;*.PHO" );
        filetypes << wxT("|");

        /* Special gerber filetypes */
        filetypes += _( "Top layer (*.GTL)|*.GTL;*.gtl|" );
        filetypes += _( "Bottom layer (*.GBL)|*.GBL;*.gbl|" );
        filetypes += _( "Bottom solder resist (*.GBS)|*.GBS;*.gbs|" );
        filetypes += _( "Top solder resist (*.GTS)|*.GTS;*.gts|" );
        filetypes += _( "Bottom overlay (*.GBO)|*.GBO;*.gbo|" );
        filetypes += _( "Top overlay (*.GTO)|*.GTO;*.gto|" );
        filetypes += _( "Bottom paste (*.GBP)|*.GBP;*.gbp|" );
        filetypes += _( "Top paste (*.GTP)|*.GTP;*.gtp|" );
        filetypes += _( "Keep-out layer (*.GKO)|*.GKO;*.gko|" );
        filetypes += _( "Mechanical layers (*.GMx)|*.GM1;*.gm1;*.GM2;*.gm2;*.GM3;*.gm3|" );
        filetypes += _( "Top Pad Master (*.GPT)|*.GPT;*.gpt|" );
        filetypes += _( "Bottom Pad Master (*.GPB)|*.GPB;*.gpb|" );

        // All filetypes
        filetypes += AllFilesWildcard;

        // Use the current working directory if the file name path does not exist.
        if( filename.DirExists() )
            currentPath = filename.GetPath();
        else
        {
            currentPath = m_mruPath;

            // On wxWidgets 3.1 (bug?) the path in wxFileDialog is ignored when
            // finishing by the dir separator. Remove it if any:
            if( currentPath.EndsWith( '\\' ) || currentPath.EndsWith( '/' ) )
                currentPath.RemoveLast();
        }

        wxFileDialog dlg( this, _( "Open Gerber File" ),
                          currentPath,
                          filename.GetFullName(),
                          filetypes,
                          wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_MULTIPLE | wxFD_CHANGE_DIR );

        if( dlg.ShowModal() == wxID_CANCEL )
            return false;

        dlg.GetPaths( filenamesList );

        // @todo Take a closer look at the CWD switching here.  The current working directory
        // gets changed by wxFileDialog because the wxFD_CHANGE_DIR flag is set.  Is this the
        // appropriate behavior?  The current working directory is not returned to the previous
        // value so this may be an issue elsewhere.
        currentPath = wxGetCwd();
        m_mruPath = currentPath;
    }
    else
    {
        filenamesList.Add( aFullFileName );
        currentPath = filename.GetPath();
        m_mruPath = currentPath;
    }

    // Set the busy cursor
    wxBusyCursor wait;

    // Read gerber files: each file is loaded on a new GerbView layer
    bool success = true;
    int layer = GetActiveLayer();

    // Manage errors when loading files
    wxString msg;
    WX_STRING_REPORTER reporter( &msg );

    for( unsigned ii = 0; ii < filenamesList.GetCount(); ii++ )
    {
        filename = filenamesList[ii];

        if( !filename.IsAbsolute() )
            filename.SetPath( currentPath );

        m_lastFileName = filename.GetFullPath();

        SetActiveLayer( layer, false );

        if( Read_GERBER_File( filename.GetFullPath() ) )
        {
            UpdateFileHistory( m_lastFileName );

            layer = getNextAvailableLayer( layer );

            if( layer == NO_AVAILABLE_LAYERS && ii < filenamesList.GetCount()-1 )
            {
                success = false;
                reporter.Report( MSG_NO_MORE_LAYER, REPORTER::RPT_ERROR );

                // Report the name of not loaded files:
                ii += 1;
                while( ii < filenamesList.GetCount() )
                {
                    filename = filenamesList[ii++];
                    wxString txt;
                    txt.Printf( MSG_NOT_LOADED,
                                GetChars( filename.GetFullName() ) );
                    reporter.Report( txt, REPORTER::RPT_ERROR );
                }
                break;
            }

            SetActiveLayer( layer, false );
        }
    }

    if( !success )
    {
        HTML_MESSAGE_BOX mbox( this, _( "Errors" ) );
        mbox.ListSet( msg );
        mbox.ShowModal();
    }

    Zoom_Automatique( false );

    // Synchronize layers tools with actual active layer:
    ReFillLayerWidget();
    SetActiveLayer( GetActiveLayer() );
    m_LayersManager->UpdateLayerIcons();
    syncLayerBox();
    return success;
}
示例#30
0
文件: files.cpp 项目: cpavlina/kicad
bool GERBVIEW_FRAME::LoadExcellonFiles( const wxString& aFullFileName )
{
    wxString   filetypes;
    wxArrayString filenamesList;
    wxFileName filename = aFullFileName;
    wxString currentPath;

    if( !filename.IsOk() )
    {
        filetypes = DrillFileWildcard();
        filetypes << wxT( "|" );

        /* All filetypes */
        filetypes += wxGetTranslation( AllFilesWildcard );

        /* Use the current working directory if the file name path does not exist. */
        if( filename.DirExists() )
            currentPath = filename.GetPath();
        else
            currentPath = m_mruPath;

        wxFileDialog dlg( this, _( "Open Drill File" ),
                          currentPath, filename.GetFullName(), filetypes,
                          wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_MULTIPLE | wxFD_CHANGE_DIR );

        if( dlg.ShowModal() == wxID_CANCEL )
            return false;

        dlg.GetPaths( filenamesList );
        currentPath = wxGetCwd();
        m_mruPath = currentPath;
    }
    else
    {
        filenamesList.Add( aFullFileName );
        currentPath = filename.GetPath();
        m_mruPath = currentPath;
    }

    // Read Excellon drill files: each file is loaded on a new GerbView layer
    bool success = true;
    int layer = GetActiveLayer();

    // Manage errors when loading files
    wxString msg;
    WX_STRING_REPORTER reporter( &msg );

    for( unsigned ii = 0; ii < filenamesList.GetCount(); ii++ )
    {
        filename = filenamesList[ii];

        if( !filename.IsAbsolute() )
            filename.SetPath( currentPath );

        m_lastFileName = filename.GetFullPath();

        SetActiveLayer( layer, false );

        if( Read_EXCELLON_File( filename.GetFullPath() ) )
        {
            // Update the list of recent drill files.
            UpdateFileHistory( filename.GetFullPath(),  &m_drillFileHistory );

            layer = getNextAvailableLayer( layer );

            if( layer == NO_AVAILABLE_LAYERS && ii < filenamesList.GetCount()-1 )
            {
                success = false;
                reporter.Report( MSG_NO_MORE_LAYER, REPORTER::RPT_ERROR );

                // Report the name of not loaded files:
                ii += 1;
                while( ii < filenamesList.GetCount() )
                {
                    filename = filenamesList[ii++];
                    wxString txt;
                    txt.Printf( MSG_NOT_LOADED,
                                GetChars( filename.GetFullName() ) );
                    reporter.Report( txt, REPORTER::RPT_ERROR );
                }
                break;
            }

            SetActiveLayer( layer, false );
        }
    }

    if( !success )
    {
        HTML_MESSAGE_BOX mbox( this, _( "Errors" ) );
        mbox.ListSet( msg );
        mbox.ShowModal();
    }

    Zoom_Automatique( false );

    // Synchronize layers tools with actual active layer:
    ReFillLayerWidget();
    SetActiveLayer( GetActiveLayer() );
    m_LayersManager->UpdateLayerIcons();
    syncLayerBox();

    return success;
}