Ejemplo n.º 1
0
QWhereabouts *NeoGpsPlugin::create(const QString &source)
{
    qLog(Hardware) << __PRETTY_FUNCTION__;
    QString path = source;
    if (path.isEmpty()) {
#ifdef NMEA_GPS_DEVICE
        path = NMEA_GPS_DEVICE;
#endif
        QSettings cfg("Trolltech",  "Whereabouts");
        cfg.beginGroup("Hardware");
        path = cfg.value("Device", path).toString();
    }

    QFile *sourceFile = new QFile(path, this);
    if (!sourceFile->open(QIODevice::ReadOnly)) {
        QMessageBox::warning( 0,tr("Mappingdemo"),tr("Cannot open GPS device at %1").arg(path),
            QMessageBox::Ok,  QMessageBox::Ok);
        qWarning() << "Cannot open GPS device at" << path;
        delete sourceFile;
        return 0;
    }

    QNmeaWhereabouts *whereabouts = new QNmeaWhereabouts(QNmeaWhereabouts::RealTimeMode, this);
    whereabouts->setSourceDevice(sourceFile);

    // QFile does not emit readyRead(), so we must call
    // newDataAvailable() when necessary
    QSocketNotifier *notifier = new QSocketNotifier(sourceFile->handle(), QSocketNotifier::Read, this);
    connect(notifier, SIGNAL(activated(int)),
              whereabouts, SLOT(newDataAvailable()));

    return whereabouts;
}
Ejemplo n.º 2
0
long readContent (const QFile& f, long count, QByteArray& buf)
{
    long result;
    int old_size;

    old_size = buf.size();
    buf.resize(old_size+count);

    result = read (f.handle (), buf.data()+old_size, count);

    if ( result > 0 && result < count )
    {
      buf.resize( old_size + result );
    }
    else if ( result == 0 )
    {
      buf.resize( old_size );
    }
    else if ( result == -1 )
    {
      kdError() << "Could not read the file!" << endl;
    }

    return result;
}
Ejemplo n.º 3
0
QStringList CameraOutV4L2::webcams() const
{
    QDir devicesDir("/dev");

    QStringList devices = devicesDir.entryList(QStringList() << "video*",
                                               QDir::System
                                               | QDir::Readable
                                               | QDir::Writable
                                               | QDir::NoSymLinks
                                               | QDir::NoDotAndDotDot
                                               | QDir::CaseSensitive,
                                               QDir::Name);

    QStringList webcams;
    QFile device;
    v4l2_capability capability;
    memset(&capability, 0, sizeof(v4l2_capability));

    for (const QString &devicePath: devices) {
        device.setFileName(devicesDir.absoluteFilePath(devicePath));

        if (device.open(QIODevice::ReadWrite)) {
            this->xioctl(device.handle(), VIDIOC_QUERYCAP, &capability);

            if (capability.capabilities & V4L2_CAP_VIDEO_OUTPUT)
                webcams << device.fileName();

            device.close();
        }
    }

    return webcams;
}
Ejemplo n.º 4
0
void MainWindow::on_sendBtn_clicked()
{
    QFile *file = new QFile(QFileDialog::getOpenFileName(this, tr("Pick A Song To Send"), 0, tr("Music (*.wav)")));
    if (file->exists())
    {
        file->open(QIODevice::ReadOnly);
        ClientSend((HANDLE) _get_osfhandle(file->handle()));
    }
}
void MImHwKeyboardTrackerPrivate::tryEvdevDevice(const char *device)
{
    QFile *qfile = new QFile(this);
    unsigned char evbits[BITS2BYTES(EV_MAX)];
    int fd;

    qfile->setFileName(device);
    if (!qfile->open(QIODevice::ReadOnly | QIODevice::Unbuffered)) {
        delete qfile;
        return;
    }

    fd = qfile->handle();
    if (fd == -1) {
        delete qfile;
        return;
    }

    if (ioctl(fd, EVIOCGBIT(0, EV_MAX), evbits) < 0) {
        delete qfile;
        return;
    }

    // Check that this input device has switches
    if (!TEST_BIT(EV_SW, evbits)) {
        delete qfile;
        return;
    }

    unsigned char swbit[BITS2BYTES(EV_MAX)];
    if (ioctl(fd, EVIOCGBIT(EV_SW, SW_CNT), swbit) < 0) {
        delete qfile;
        return;
    }

    // Check that there is a tablet mode switch here
    if (!TEST_BIT(SW_TABLET_MODE, swbit)) {
        delete qfile;
        return;
    }

    // Found an appropriate device - start monitoring it
    QSocketNotifier *sn = new QSocketNotifier(fd, QSocketNotifier::Read, qfile);
    sn->setEnabled(true);
    QObject::connect(sn, SIGNAL(activated(int)), this, SLOT(evdevEvent()));

    evdevFile = qfile;
    present = true;

    // Initialise initial tablet mode state
    unsigned long state[BITS2BYTES(SW_MAX)];
    if (ioctl(fd, EVIOCGSW(SW_MAX), state) < 0)
        return;

    evdevTabletMode = TEST_BIT(SW_TABLET_MODE, state);
}
Ejemplo n.º 6
0
void nostderr(QString dir)
{
    // redirect stderr to a file
    QFile *fp = new QFile(QString("%1/goldencheetah.log").arg(dir));
    if (fp->open(QIODevice::WriteOnly|QIODevice::Truncate) == true) {
        close(2);
        if(dup(fp->handle()) == -1) fprintf(stderr, "GoldenCheetah: cannot redirect stderr\n");
    } else {
        fprintf(stderr, "GoldenCheetah: cannot redirect stderr\n");
    }
}
Ejemplo n.º 7
0
ZipReader::ZipReader(QIODevice* device) :
	m_archive(0)
{
	QFile* file = qobject_cast<QFile*>(device);
	if (file) {
		m_archive = zip_fdopen(file->handle(), 0, 0);
		if (m_archive) {
			readFileInfo();
		}
	}
}
Ejemplo n.º 8
0
Archivo: File.cpp Proyecto: Ummon/D-LAN
void File::setFileAsSparse(const QFile& file)
{
   // TODO: Do we need that on linux? see 'fallocate(..)',
   #ifdef Q_OS_WIN32
      DWORD bytesWritten;
      HANDLE hdl = (HANDLE)_get_osfhandle(file.handle());
      // To avoid to initialize all the file, when you seek at the end of a file then you write some data the file will be initialized without this call.
      // File initialization can take several minutes for a large file (> 5 GiB).
      // See : http://msdn.microsoft.com/en-us/library/aa364596%28v=vs.85%29.aspx
      if (!DeviceIoControl(hdl, FSCTL_SET_SPARSE, NULL, 0, NULL, 0, &bytesWritten, NULL))
         L_WARN("DeviceIoControl(..) failed");
   #endif
}
Ejemplo n.º 9
0
    /*!
     Returns true if it's suitable to send colored output to \c stderr.
     */
    inline bool isColoringPossible() const
    {
#           if defined(Q_OS_WIN)
        /* Windows doesn't at all support ANSI escape codes, unless
         * the user install a "device driver". See the Wikipedia links in the
         * class documentation for details. */
        return false;
#           else
        /* We use QFile::handle() to get the file descriptor. It's a bit unsure
         * whether it's 2 on all platforms and in all cases, so hopefully this layer
         * of abstraction helps handle such cases. */
        return isatty(m_out.handle());
#           endif
    }
Ejemplo n.º 10
0
Archivo: io.cpp Proyecto: MUME/MMapper
bool fsync(QFile &file) noexcept(false)
{
    const int handle = file.handle();
#ifdef Q_OS_WIN
    return false;
#elif defined(Q_OS_MAC)
    if (::fcntl(handle, F_FULLFSYNC) == -1) {
        throw IOException::withCurrentErrno();
    }
#else
    if (::fsync(handle) == -1) {
        throw IOException::withCurrentErrno();
    }
#endif
    return true;
}
Ejemplo n.º 11
0
Archivo: log.cpp Proyecto: dosnut/nut
		CLogInit() {
			int fd1 = dup(1), fd2 = dup(2);
			close(fd1); close(fd2);
			if (fd1 == -1 || fd2 == -1) {
				QFile *f = new QFile("/var/log/nuts.log");
				f->open(QIODevice::Append);
				dup2(f->handle(), 2);
				dup2(f->handle(), 1);
				err.setDevice(f);
				log.setDevice(f);
			} else {
				ferr = new QFile(); ferr->open(2, QIODevice::WriteOnly);
				err.setDevice(ferr);
				fout = new QFile(); fout->open(1, QIODevice::WriteOnly);
				log.setDevice(fout);
			}
		}
Ejemplo n.º 12
0
void MainWindow::on_openIncoming_clicked()
{
    if (ClientReceiveSetup() == 0)
    {
        QFile *file = new QFile(QFileDialog::getSaveFileName(this, tr("Save song as"), 0, tr("Music (*.wav)")));
        if (file->fileName() != NULL)
        {
            ui->openIncoming->setEnabled(false);
            ui->disconnectIncoming->setEnabled(true);
            file->open(QIODevice::WriteOnly);
            ClientListen((HANDLE) _get_osfhandle(file->handle()));
        } else
        {
            ClientCleanup();
        }
    }
}
Ejemplo n.º 13
0
QString CameraOutV4L2::description(const QString &webcam) const
{
    if (webcam.isEmpty())
        return QString();

    QFile device;
    v4l2_capability capability;
    memset(&capability, 0, sizeof(v4l2_capability));

    device.setFileName(webcam);

    if (device.open(QIODevice::ReadWrite)) {
        this->xioctl(device.handle(), VIDIOC_QUERYCAP, &capability);

        if (capability.capabilities & V4L2_CAP_VIDEO_OUTPUT)
            return QString(reinterpret_cast<const char *>(capability.card));

        device.close();
    }

    return QString();
}
Ejemplo n.º 14
0
void KConfigINIBackEnd::parseSingleConfigFile(QFile &rFile, KEntryMap *pWriteBackMap, bool bGlobal, bool bDefault)
{
    const char *s;   // May get clobbered by sigsetjump, but we don't use them afterwards.
    const char *eof; // May get clobbered by sigsetjump, but we don't use them afterwards.
    QByteArray data;

    if(!rFile.isOpen()) // come back, if you have real work for us ;->
        return;

    // using kdDebug() here leads to an infinite loop
    // remove this for the release, aleXXX
    // qWarning("Parsing %s, global = %s default = %s",
    //           rFile.name().latin1(), bGlobal ? "true" : "false", bDefault ? "true" : "false");

    QCString aCurrentGroup("<default>");

    unsigned int ll = localeString.length();

#ifdef HAVE_MMAP
    static volatile const char *map;
    map = (const char *)mmap(0, rFile.size(), PROT_READ, MAP_PRIVATE, rFile.handle(), 0);

    if(map != MAP_FAILED)
    {
        s = (const char *)map;
        eof = s + rFile.size();

#ifdef SIGBUS
        struct sigaction act;
        act.sa_handler = mmap_sigbus_handler;
        sigemptyset(&act.sa_mask);
#ifdef SA_ONESHOT
        act.sa_flags = SA_ONESHOT;
#else
        act.sa_flags = SA_RESETHAND;
#endif
        sigaction(SIGBUS, &act, &mmap_old_sigact);

        if(sigsetjmp(mmap_jmpbuf, 1))
        {
            qWarning("SIGBUS while reading %s", rFile.name().latin1());
            munmap((char *)map, rFile.size());
            sigaction(SIGBUS, &mmap_old_sigact, 0);
            return;
        }
#endif
    }
    else
#endif
    {
        rFile.at(0);
        data = rFile.readAll();
        s = data.data();
        eof = s + data.size();
    }

    bool fileOptionImmutable = false;
    bool groupOptionImmutable = false;
    bool groupSkip = false;

    int line = 0;
    for(; s < eof; s++)
    {
        line++;

        while((s < eof) && isspace(*s) && (*s != '\n'))
            s++; // skip leading whitespace, shouldn't happen too often

        // skip empty lines, lines starting with #
        if((s < eof) && ((*s == '\n') || (*s == '#')))
        {
        sktoeol: // skip till end-of-line
            while((s < eof) && (*s != '\n'))
                s++;
            continue; // Empty or comment or no keyword
        }
        const char *startLine = s;

        if(*s == '[') // group
        {
            // In a group [[ and ]] have a special meaning
            while((s < eof) && (*s != '\n'))
            {
                if(*s == ']')
                {
                    if((s + 1 < eof) && (*(s + 1) == ']'))
                        s++; // Skip "]]"
                    else
                        break;
                }

                s++; // Search till end of group
            }
            const char *e = s;
            while((s < eof) && (*s != '\n'))
                s++; // Search till end of line / end of file
            if((e >= eof) || (*e != ']'))
            {
                fprintf(stderr, "Invalid group header at %s:%d\n", rFile.name().latin1(), line);
                continue;
            }
            // group found; get the group name by taking everything in
            // between the brackets
            if((e - startLine == 3) && (startLine[1] == '$') && (startLine[2] == 'i'))
            {
                if(!kde_kiosk_exception)
                    fileOptionImmutable = true;
                continue;
            }

            aCurrentGroup = decodeGroup(startLine + 1, e - startLine);
            // cout<<"found group ["<<aCurrentGroup<<"]"<<endl;

            // Backwards compatibility
            if(aCurrentGroup == "KDE Desktop Entry")
                aCurrentGroup = "Desktop Entry";

            groupOptionImmutable = fileOptionImmutable;

            e++;
            if((e + 2 < eof) && (*e++ == '[') && (*e++ == '$')) // Option follows
            {
                if((*e == 'i') && !kde_kiosk_exception)
                {
                    groupOptionImmutable = true;
                }
            }

            KEntryKey groupKey(aCurrentGroup, 0);
            KEntry entry = pConfig->lookupData(groupKey);
            groupSkip = entry.bImmutable;

            if(groupSkip && !bDefault)
                continue;

            entry.bImmutable |= groupOptionImmutable;
            pConfig->putData(groupKey, entry, false);

            if(pWriteBackMap)
            {
                // add the special group key indicator
                (*pWriteBackMap)[groupKey] = entry;
            }

            continue;
        }
        if(groupSkip && !bDefault)
            goto sktoeol; // Skip entry

        bool optionImmutable = groupOptionImmutable;
        bool optionDeleted = false;
        bool optionExpand = false;
        const char *endOfKey = 0, *locale = 0, *elocale = 0;
        for(; (s < eof) && (*s != '\n'); s++)
        {
            if(*s == '=') // find the equal sign
            {
                if(!endOfKey)
                    endOfKey = s;
                goto haveeq;
            }
            if(*s == '[') // find the locale or options.
            {
                const char *option;
                const char *eoption;
                endOfKey = s;
                option = ++s;
                for(;; s++)
                {
                    if((s >= eof) || (*s == '\n') || (*s == '='))
                    {
                        fprintf(stderr, "Invalid entry (missing ']') at %s:%d\n", rFile.name().latin1(), line);
                        goto sktoeol;
                    }
                    if(*s == ']')
                        break;
                }
                eoption = s;
                if(*option != '$')
                {
                    // Locale
                    if(locale)
                    {
                        fprintf(stderr, "Invalid entry (second locale!?) at %s:%d\n", rFile.name().latin1(), line);
                        goto sktoeol;
                    }
                    locale = option;
                    elocale = eoption;
                }
                else
                {
                    // Option
                    while(option < eoption)
                    {
                        option++;
                        if((*option == 'i') && !kde_kiosk_exception)
                            optionImmutable = true;
                        else if(*option == 'e')
                            optionExpand = true;
                        else if(*option == 'd')
                        {
                            optionDeleted = true;
                            goto haveeq;
                        }
                        else if(*option == ']')
                            break;
                    }
                }
            }
        }
        fprintf(stderr, "Invalid entry (missing '=') at %s:%d\n", rFile.name().latin1(), line);
        continue;

    haveeq:
        for(endOfKey--;; endOfKey--)
        {
            if(endOfKey < startLine)
            {
                fprintf(stderr, "Invalid entry (empty key) at %s:%d\n", rFile.name().latin1(), line);
                goto sktoeol;
            }
            if(!isspace(*endOfKey))
                break;
        }

        const char *st = ++s;
        while((s < eof) && (*s != '\n'))
            s++; // Search till end of line / end of file

        if(locale)
        {
            unsigned int cl = static_cast< unsigned int >(elocale - locale);
            if((ll != cl) || memcmp(locale, localeString.data(), ll))
            {
                // backward compatibility. C == en_US
                if(cl != 1 || ll != 5 || *locale != 'C' || memcmp(localeString.data(), "en_US", 5))
                {
                    // cout<<"mismatched locale '"<<QCString(locale, elocale-locale +1)<<"'"<<endl;
                    // We can ignore this one
                    if(!pWriteBackMap)
                        continue; // We just ignore it
                    // We just store it as is to be able to write it back later.
                    endOfKey = elocale;
                    locale = 0;
                }
            }
        }

        // insert the key/value line
        QCString key(startLine, endOfKey - startLine + 2);
        QCString val = printableToString(st, s - st);
        // qDebug("found key '%s' with value '%s'", key.data(), val.data());

        KEntryKey aEntryKey(aCurrentGroup, decodeKey(key));
        aEntryKey.bLocal = (locale != 0);
        aEntryKey.bDefault = bDefault;

        KEntry aEntry;
        aEntry.mValue = val;
        aEntry.bGlobal = bGlobal;
        aEntry.bImmutable = optionImmutable;
        aEntry.bDeleted = optionDeleted;
        aEntry.bExpand = optionExpand;
        aEntry.bNLS = (locale != 0);

        if(pWriteBackMap)
        {
            // don't insert into the config object but into the temporary
            // scratchpad map
            pWriteBackMap->insert(aEntryKey, aEntry);
        }
        else
        {
            // directly insert value into config object
            // no need to specify localization; if the key we just
            // retrieved was localized already, no need to localize it again.
            pConfig->putData(aEntryKey, aEntry, false);
        }
    }
    if(fileOptionImmutable)
        bFileImmutable = true;

#ifdef HAVE_MMAP
    if(map)
    {
        munmap((char *)map, rFile.size());
#ifdef SIGBUS
        sigaction(SIGBUS, &mmap_old_sigact, 0);
#endif
    }
#endif
}
Ejemplo n.º 15
0
std::ifstream QFileToifstream(QFile & file) {
    Q_ASSERT(file.isReadable());
    return std::ifstream(::_fdopen(file.handle(), "r"));
}
Ejemplo n.º 16
0
void QInputDeviceScanner::scan()
{
    for( int index = 0; index < MAX_INPUT_DEVICES; index++ )
    {
        QString devInput = QString("/dev/input");

        QString devEvent = devInput + "/event" + QString::number(index);

        QFile fileEvent;

        fileEvent.setFileName(devEvent);

        if( fileEvent.open(QIODevice::ReadOnly) )
        {
            char name[256] = "Unknown";
            char phys[256] = "";

            if( ::ioctl(fileEvent.handle(), EVIOCGNAME(sizeof(name)), name) < 0 )
            {
//                qWarning("Cannot get the name of device");
            }

            if( ::ioctl(fileEvent.handle(), EVIOCGPHYS(sizeof(phys)), phys) < 0 )
            {
//                qWarning("Cannot get the physical location");
            }

            QString deviceName = QString(name);
            QString devicePhys = QString(phys);

            if( devicePhys.startsWith("usb-dev") )
            {
                unsigned long evbit[NBITS(EV_MAX + 1)];

                if( ::ioctl(fileEvent.handle(), EVIOCGBIT(0, sizeof(evbit)), evbit) >= 0 )
                {
                    if( IS_BIT_SET(EV_REL, evbit) )
                    {
                        qDebug() << QString("Found Mouse: ") << devEvent;

                        m_listOfMouse.append(devEvent);
                    }
                    else if( IS_BIT_SET(EV_KEY, evbit) &&
                             ! IS_BIT_SET(EV_REL, evbit) &&
                             ! IS_BIT_SET(EV_ABS, evbit) )
                    {
                        qDebug() << QString("Found Keyboard: ") << devEvent;

                        m_listOfKeyboard.append(devEvent);
                    }
                }
            }
            else if(deviceName.contains("M-RCU - Builtin"))
            {
                qDebug() << QString("Found Motion: ") << devEvent;
                m_listOfMotion.append(devEvent);
            }

            fileEvent.close();
        }
    }
}
Ejemplo n.º 17
0
bool TextBuffer::save (const QString &filename)
{
  // codec must be set!
  Q_ASSERT (m_textCodec);

  /**
   * construct correct filter device and try to open
   */
  QIODevice *file = KFilterDev::deviceForFile (filename, m_mimeTypeForFilterDev, false);
  if (!file->open (QIODevice::WriteOnly)) {
    delete file;
    return false;
  }

  /**
   * construct stream + disable Unicode headers
   */
  QTextStream stream (file);
  stream.setCodec (QTextCodec::codecForName("UTF-16"));

  // set the correct codec
  stream.setCodec (m_textCodec);

  // generate byte order mark?
  stream.setGenerateByteOrderMark (generateByteOrderMark());

  // our loved eol string ;)
  QString eol = "\n"; //m_doc->config()->eolString ();
  if (endOfLineMode() == eolDos)
    eol = QString ("\r\n");
  else if (endOfLineMode() == eolMac)
    eol = QString ("\r");

  // just dump the lines out ;)
  for (int i = 0; i < m_lines; ++i)
  {
    // get line to save
    Kate::TextLine textline = line (i);

    // strip trailing spaces
    if (m_removeTrailingSpaces)
    {
      int lastChar = textline->lastChar();
      if (lastChar > -1)
      {
        stream << textline->text().left (lastChar+1);
      }
    }
    else // simple, dump the line
      stream << textline->text();

    // append correct end of line string
    if ((i+1) < m_lines)
      stream << eol;
  }

  // flush stream
  stream.flush ();

  // close and delete file
  file->close ();
  delete file;

#ifndef Q_OS_WIN
  // ensure that the file is written to disk
  // we crete new qfile, as the above might be wrapper around compression
  QFile syncFile (filename);
  syncFile.open (QIODevice::ReadOnly);

#ifdef HAVE_FDATASYNC
  fdatasync (syncFile.handle());
#else
  fsync (syncFile.handle());
#endif
#endif

  // did save work?
  bool ok = stream.status() == QTextStream::Ok;

  // remember this revision as last saved if we had success!
  if (ok)
    m_history.setLastSavedRevision ();

  // report CODEC + ERRORS
  kDebug (13020) << "Saved file " << filename << "with codec" << m_textCodec->name()
    << (ok ? "without" : "with") << "errors";

  // emit signal on success
  if (ok)
    emit saved (filename);

  // return success or not
  return ok;
}
Ejemplo n.º 18
0
bool ConsoleDevice::isConsoleDevice(QIODevice *pDevice)
{
    QFile* file = qobject_cast<QFile*>(pDevice);
    return file && (file->handle() == STDOUT_FILENO || file->handle() == STDERR_FILENO);
}
Ejemplo n.º 19
0
static void writeOutput (const char *type, const char *module, const char *file, int line,
			 const char *className, const char *method, const char *message) {
	
	// Get current time
	tm local;
	time_t timestamp = time (0);
	localtime_r (&timestamp, &local);
	
	// Time string
	char timeString[9]; // 00:00:00
	snprintf (timeString, sizeof(timeString), "%02i:%02i:%02i",
		  local.tm_hour, local.tm_min, local.tm_sec);
	
	// Construct output data
	QByteArray output;
	const char *format = (!g_format) ? FORMAT_STRING : g_format;
	const int *offsets = g_formatOffset;
	
	// Write format
	int pos = 0;
	int i = 0;
	for (; offsets[i + 1] != -1; i++) {
		
		// Is this a identifier?
		int curLen = offsets[i + 1];
		
		if (format[pos] != '%') {
			// No. Copy from 'pos' to 'cur' into output.
			output.append (format + pos, curLen);
		} else if (curLen >= 3) {
			
			// Compare identifiers.
			char a = format[pos + 1];
			char b = format[pos + 2];
			
			if (a == 'D' && b == 'A') { // DATE
				char dateString[11]; // 00/00/0000
				snprintf (dateString, sizeof(dateString), "%02i/%02i/%04i",
					  local.tm_mon + 1, local.tm_mday, local.tm_year + 1900);
				output.append (dateString);
				
			} else if (a == 'T' && b == 'I') { // TIME
				output.append (timeString);
			} else if (a == 'T' && b == 'Y') { // TYPE
				output.append (type);
			} else if (a == 'M' && b == 'O') { // MODULE
				output.append (module);
			} else if (a == 'F' && b == 'I') { // FILE
				output.append (file);
			} else if (a == 'L' && b == 'I') { // LINE
				output.append (QByteArray::number (line));
			} else if (a == 'C' && b == 'L') { // CLASS
				output.append (className);
			} else if (a == 'M' && b == 'E') { // METHOD
				output.append (method);
			} else if (a == 'B' && b == 'O') { // BODY
				output.append (message);
			}
			
		}
		
		// New position
		pos += curLen;
		
	}
	
	// Append "\n" and write output to device
	
	if (!output.isEmpty ()) {
		
		// 
		output.append ('\n');
		
		// Write to device. If we're dealing with a QFile, we use the
		// low-level methods to avoid problems in multi-threaded
		// environments.
		if (g_isFile) {
			QFile *file = static_cast< QFile * > (g_device);
			
			// Use write(3) to output the message and make sure that
			// the data has been written by calling fsync(3).
			int fileno = file->handle ();
			::write (fileno, output.constData (), output.length ());
#ifndef Q_OS_WIN
			::fsync (fileno);
#endif
		
		} else {
			g_device->write (output);
		}
		
	}
	
}
Ejemplo n.º 20
0
/**
\return
**/
void Q19Writer::genera ( BlDbRecordSet  *curcobro, QString fileName , QStringList *idsGenerats)
{
      BL_FUNC_DEBUG
      QString refActual ( "cap rebut" );
      if (fileName.length()==0) {
          fileName = QFileDialog::getSaveFileName ( parentWidget(), _ ( "Fichero de remesa bancaria (Cuaderno 19)" ),
                       "",
                       _ ( "*.q19;;*" ) );
      }

      BlDebug::blDebug ( Q_FUNC_INFO, 0, QString(_("Nombre del fichero: '%1'")).arg(fileName) );

      if (fileName.length()>0) { // else ha apretat cancel?lar
       
	try
	{
		int cobraments=curcobro->numregistros();
		BlDbRecordSet  *curbanc;
		/*
		http://www.cam.es/1/empresas/servicios/pdf/c19.pdf
		"    Dentro de cada Cliente Ordenante, todos los registros individuales debera'n
		figurar en el soporte clasificados ascendentemente por el nu'mero de Entidad-
		Oficina de adeudo, Referencia y Co'digo de dato, terminando con un registro de
		<<Total Ordenante>>. Al final llevara' un registro de <<Total General>>.
		"
		Per'o cada idbanco (de fet cada entitat, per'o no filem tan prim) requereix un
		fitxer, perqu'e no portar'as a un banc els rebuts que vols cobrar per un altre.
		I la data de c'arrec va a la capc,alera d'ordenant, per tant hem d'ordenar primer
		per banc i data i despre's pel que demana als rebuts d'un ordenant. Farem tantes capc,aleres
		d'ordenant com dates encara que sempre sigui el mateix ordenant.

		*/
		bool bancUnic = ( curcobro->value( "idbanco",0 ) == curcobro->value( "idbanco",curcobro->numregistros()-1 ) );
		BlDebug::blDebug ( "bancUnic=",0,bancUnic?"si":"no" );
		QString idbanc ( "" );
		QFile file;
		QTextStream out ( &file );
		/*
		   http://www.cam.es/1/empresas/servicios/pdf/c19.pdf
		   - Codigo ASCII ( en mayusculas) (caracter 165= enye).
		   - Registros de longitud fija (162 bytes).
		   - Formato MS-DOS secuencial tipo texto.
		   En canvi un fitxer de mostra generat amb un programa que do'na el banc
		   te' 162 car'acters + \x0a , que no e's un salt de li'nia MSDOS. Ni se' si
		   un fitxer de registres de longitud fixa necessita  salts de li'nia per a res.
		*/
		out.setCodec ( "Q19" );
		QString sufijo;
		QDate fechaCargo = ( curcobro->eof() ?
		                     QDate()
		                     : QDate::fromString ( curcobro->value( "fechavenccobro" ),"dd/MM/yyyy" ) ) ;
		BlFixed impOrdenante ( 0,2 );
		BlFixed impPresentador ( 0,2 );
		QString resultats ( "" );
		int registrosOrdenante=0;
		int registrosPresentador=0;
		int cobramentsOrdenante=0;
		int cobramentsPresentador=0;
		int ordenants=0;
		int sensebanc=0;
		int sensevenc=0;
		while ( !curcobro->eof() )
		{
			if ( QDate::fromString ( curcobro->value( "fechavenccobro" ),"dd/MM/yyyy" ).isValid() )
			{
				if ( ( !curcobro->value( "idbanco" ).isNull() ) && ( curcobro->value( "idbanco" ).length() >0 ) )
				{

					if ( QDate::fromString ( curcobro->value( "fechavenccobro" ),"dd/MM/yyyy" ) != fechaCargo )
					{
						registrosPresentador++;
						registrosOrdenante++;
						totalOrdenante ( out, sufijo , curbanc, impOrdenante,
						                 cobramentsOrdenante, registrosOrdenante );
						ordenants++;
					}
					if ( curcobro->value( "idbanco" ) != idbanc )
					{
						// canvi de banc on cobrem els rebuts, canvi de fitxer
						idbanc=curcobro->value( "idbanco" );
						if ( file.handle() !=-1 )
						{
							registrosPresentador++;
							totalPresentador ( out, sufijo, curbanc, impPresentador, cobramentsPresentador, registrosPresentador , ordenants );
							resultats += _ ( "\n%3 : %1 recibos, %2 EUR. " ).arg ( cobramentsPresentador ).arg ( impPresentador.toQString() ).arg ( file.fileName() );
							file.close();
							delete curbanc;

						}
						curbanc = m_empresa->loadQuery ( "SELECT * FROM banco WHERE idbanco = $1",1,&idbanc );
                                                sufijo = curbanc->value("sufijobanco");
						if ( bancUnic )
						{
							file.setFileName ( fileName );
							BlDebug::blDebug ( "creare' ",0,fileName );
						}
						else
						{
							QString nomNou = fileName;
							QRegExp ext ( "(\\..*)$" );
							QString extensio ( "" );
							if ( ext.indexIn ( nomNou ) >=0 )
							{
								extensio = ext.cap ( 1 );
							}
							nomNou.replace ( ext,"" );
							nomNou+="_"+curbanc->value( "nombanco" ).replace ( QRegExp ( "[^a-zA-Z0-9_]" ),"-" )
							        +extensio;
							file.setFileName ( nomNou );
							BlDebug::blDebug ( "creare' el nom que m'he muntat: ",0,fileName );
						}
						if ( !file.open ( QIODevice::WriteOnly | QIODevice::Text ) )
							return;
						cabeceraPresentador ( out, sufijo , curbanc );
						cobramentsPresentador=0;
						registrosPresentador=1;
						impPresentador=0;
						ordenants=0;
						fechaCargo=QDate::fromString ( curcobro->value( "fechavenccobro" ),"dd/MM/yyyy" ) ;
					}
					if ( ( QDate::fromString ( curcobro->value( "fechavenccobro" ),"dd/MM/yyyy" ) != fechaCargo ) || ( registrosPresentador==1 ) )
					{
						fechaCargo = QDate::fromString ( curcobro->value( "fechavenccobro" ),"dd/MM/yyyy" );
						registrosPresentador++;
						cabeceraOrdenante ( out, sufijo , curbanc, fechaCargo );
						cobramentsOrdenante=0;
						registrosOrdenante=1;
						impOrdenante=0;
					}

					refActual=curcobro->value( "refcobro" );
					int registres = cobroQ19 ( out, sufijo, curcobro );
                                        if (idsGenerats) 
                                        { 
                                           idsGenerats->append(curcobro->value("idcobro"));
                                        }
					registrosOrdenante+=registres;
					registrosPresentador+=registres;
					cobramentsOrdenante++;
					cobramentsPresentador++;
					impOrdenante=impOrdenante+BlFixed ( curcobro->value( "cantcobro" ) );
					impPresentador=impPresentador+BlFixed ( curcobro->value( "cantcobro" ) );
				}
				else
				{
					sensebanc++;
				}
			}
			else
			{
				sensevenc++;
			}
			curcobro->nextRecord();
		}
		if ( file.handle() !=-1 )
		{
			registrosPresentador++;
			registrosOrdenante++;
			totalOrdenante ( out, sufijo , curbanc, impOrdenante, cobramentsOrdenante, registrosOrdenante );
			ordenants++;
						
			registrosPresentador++;
                        totalPresentador ( out, sufijo, curbanc, impPresentador, cobramentsPresentador, registrosPresentador , ordenants );
			resultats += _ ( "\n%3 : %1 recibos, %2 EUR. " ).arg ( cobramentsPresentador ).arg ( impPresentador.toQString() ).arg ( file.fileName() );
			file.close();
			delete curbanc;

		}
		if ( ( sensevenc>0 ) || ( sensebanc>0 ) )
		{
			QMessageBox::warning ( parentWidget(),_ ( "Remesa parcialmente generada" ),
			                       _ ( "Excluidos %3 de %2 recibos por falta de fecha de vencimiento y otros %1 por falta de banco" ).arg ( sensebanc ).arg ( cobraments ).arg ( sensevenc ) );
		}
		QMessageBox::information ( parentWidget(),_ ( "Fichero(s) generado(s)" ),_ ( "Tiene los siguientes ficheros de recibos para los bancos:\n%1" ).arg ( resultats ) );
	}
	catch ( QString e )
	{
		BlDebug::blDebug ( "Error ",0,refActual+":"+e );
		QMessageBox::critical ( parentWidget(),_ ( "Remesa mal generada" ),_( "%2\n.El fichero de remesa bancaria generado no es aprovechable. Ha fallado la generacion en el recibo con referencia %1" ).arg ( refActual ).arg ( e ) );
                if (idsGenerats) 
                {
                     idsGenerats->clear();
                }
	}
      }
	
}
Ejemplo n.º 21
0
/*!
 * \internal this function locks the lockregistry and checks if there is a collision between the process locks
 * \internal if there is no collision it inserts the lock into the registry and returns
 * \internal return true for success
 */
bool QxtFileLockRegistry::registerLock(QxtFileLock * lock)
{
    QMutexLocker locker(&this->registryMutex);

    QFile *fileToLock = lock ->file();

    if (fileToLock)
    {
        struct stat fileInfo;
        if (fstat(fileToLock->handle(), &fileInfo) < 0)
            return false;

        int newLockStart = lock ->offset();
        int newLockEnd = lock ->offset() + lock ->length();

        QMutableLinkedListIterator< QPointer<QxtFileLock> >iterator(this->procLocks);

        while (iterator.hasNext())
        {
            QPointer<QxtFileLock> currLock = iterator.next();
            if (currLock && currLock->file() && currLock->file()->isOpen())
            {
                struct stat currFileInfo;

                /*first check if the current lock is on the same file*/
                if (fstat(currLock->file()->handle(), &currFileInfo) < 0)
                {
                    /*that should never happen because a closing file should remove all locks*/
                    Q_ASSERT(false);
                    continue;
                }

                if (currFileInfo.st_dev == fileInfo.st_dev && currFileInfo.st_ino == fileInfo.st_ino)
                {
                    /*same file, check if our locks are in conflict*/
                    int currLockStart = currLock->offset();
                    int currLockEnd = currLock->offset() + currLock->length();

                    /*do we have to check for threads here?*/
                    if (newLockEnd >= currLockStart  && newLockStart <= currLockEnd)
                    {
                        //qDebug() << "we may have a collision";
                        //qDebug() << newLockEnd << " >= " << currLockStart << "  &&  " << newLockStart << " <= " << currLockEnd;

                        /*same lock region if one of both locks are exclusive we have a collision*/
                        if (lock ->mode() == QxtFileLock::WriteLockWait || lock ->mode() == QxtFileLock::WriteLock ||
                                currLock->mode() == QxtFileLock::WriteLockWait || currLock->mode() == QxtFileLock::WriteLock)
                        {
                            /*FIXED BUG #6 test rw_same() passes on Unix
                              keeping the old code for a while
                              */
                            return false;
#if 0
                           //qDebug() << "Okay if this is not the same thread using the same handle there is a collision";
                            /*the same thread  can lock the same region with the same handle*/

                            //qDebug() << "! (" << lock ->thread() << " == " << currLock->thread() << " && " << lock ->file()->handle() << " == " << currLock->file()->handle() << ")";

                            if (!(lock ->thread() == currLock->thread() && lock ->file()->handle() == currLock->file()->handle()))
                            {
                                qDebug() << "Collision";
                                return false;
                            }
#endif
                        }
                    }
                }
            }
            else //remove dead locks
                iterator.remove();
        }
        //qDebug() << "The lock is okay";
        /*here we can insert the lock into the list and return*/
        procLocks.append(QPointer<QxtFileLock>(lock));
        return true;

    }

    return false;
}