예제 #1
0
TQString NoatunSensor::getTitle()
{
    TQByteArray data, replyData;
    TQCString replyType;
    TQString result;
    TQDataStream arg(data, IO_WriteOnly);
    arg << 5;
    if (!client->call( noatunID, "Noatun", "title()",
                       data, replyType, replyData))
    {
        result = "";
        tqDebug("there was some error using DCOP.");
    }
    else
    {
        TQDataStream reply(replyData, IO_ReadOnly);
        if (replyType == TQSTRING_OBJECT_NAME_STRING)
        {
            reply >> result;
            result.replace( TQRegExp("_")," " );
            result.replace( TQRegExp(".mp3$"),"" );

        }
        else
        {
예제 #2
0
void KSim::Sysinfo::clockUptimeUpdate()
{
  TQString time;
  static bool updateDate = true;

  if (m_timeLabel) {
    TQTime now = TQTime::currentTime();
    time = TDEGlobal::locale()->formatTime(now, true);
    if ( now == TQTime(0, 0) )
      updateDate = true;

    m_timeLabel->setText(time);
  }

  // only update the date when necessary
  if (m_dateLabel) {
    if (updateDate) {
      m_dateLabel->setText(TDEGlobal::locale()->formatDate(TQDate::currentDate()));
      updateDate = false;
    }
  }
  else {
    updateDate = true;
  }

  if (m_uptimeLabel) {
    TQString uptime = m_config->uptimeFormat();
    ++m_totalUptime;
    long uptimeDays, uptimeHours, uptimeMins, uptimeSecs;

    uptimeHours = m_totalUptime / 3600;
    uptimeDays = uptimeHours / 24;
    uptimeMins = (m_totalUptime - uptimeHours * 3600) / 60;
    uptimeSecs = m_totalUptime % 60;

    TQString days;
    TQString hours;
    TQString minutes;
    TQString seconds;

    // found days so we have to modify hours
    if (uptime.find(TQRegExp("%d" ), 0) >= 0)
      uptimeHours -= (uptimeDays * 24);

    days.sprintf("%02li", uptimeDays);
    hours.sprintf("%02li", uptimeHours);
    minutes.sprintf("%02li", uptimeMins);
    seconds.sprintf("%02li", uptimeSecs);

    uptime.replace(TQRegExp("%d"), days);
    uptime.replace(TQRegExp("%h"), hours);
    uptime.replace(TQRegExp("%m"), minutes);
    uptime.replace(TQRegExp("%s"), seconds);
    m_uptimeLabel->setText(uptime);
  }
}
예제 #3
0
TQString TDEStorageDevice::friendlyName() {
	// Return the actual storage device name
	TQString devicevendorid = vendorEncoded();
	TQString devicemodelid = modelEncoded();

	devicevendorid.replace("\\x20", " ");
	devicemodelid.replace("\\x20", " ");

	devicevendorid = devicevendorid.stripWhiteSpace();
	devicemodelid = devicemodelid.stripWhiteSpace();
	devicevendorid = devicevendorid.simplifyWhiteSpace();
	devicemodelid = devicemodelid.simplifyWhiteSpace();

	TQString devicename = devicevendorid + " " + devicemodelid;

	devicename = devicename.stripWhiteSpace();
	devicename = devicename.simplifyWhiteSpace();

	if (devicename != "") {
		return devicename;
	}

	if (isDiskOfType(TDEDiskDeviceType::Camera)) {
		return TDEGenericDevice::friendlyName();
	}

	if (isDiskOfType(TDEDiskDeviceType::Floppy)) {
		return friendlyDeviceType();
	}

	TQString label = diskLabel();
	if (label.isNull()) {
		if (deviceSize() > 0) {
			if (checkDiskStatus(TDEDiskDeviceStatus::Hotpluggable)) {
				label = i18n("%1 Removable Device").arg(deviceFriendlySize());
			}
			else {
				label = i18n("%1 Fixed Storage Device").arg(deviceFriendlySize());
			}
		}
	}

	if (!label.isNull()) {
		return label;
	}

	return friendlyDeviceType();
}
예제 #4
0
bool ClickArea::click( TQMouseEvent *e )
{
    if( rect.contains( e->x(), e->y() ) )
    {
        //tqDebug(TQString::number(e->type()));
	//KShellProcess ksp;
        if( e->button() != Qt::LeftButton )
			return false;
	if (!svc_name.isEmpty())
	{
		KService sv(svc_name, svc_onClick, svc_icon);
		KURL::List l;
		KRun::run(sv, l);
		return false;
	}
	else
	{
		TQString program;
		program = onClick;
		program.replace( TQRegExp("%v", false), value );

		if( !program.isEmpty() )
		{
			//tqDebug(program);
			KRun::runCommand(program);
		}
	}
    }
    return false;
}
예제 #5
0
void KwikDisk::toggleMount(int item)
{
   kdDebug() << k_funcinfo << endl;

   DiskEntry *disk = m_diskList.at(item);
   if( disk == 0 )
   {
      return;
   }

   int val = disk->toggleMount();
   if( val != 0 )
   {
      KMessageBox::error(this, disk->lastSysError());
   }
   else if( (m_options.openFileManager() == true) && (disk->mounted() == true ) )
   {
      kdDebug() << "opening filemanager" << endl;
      if( m_options.fileManager().isEmpty() == false )
      {
         TQString cmd = m_options.fileManager();
         int pos = cmd.find("%m");
         if( pos > 0 )
         {
            cmd = cmd.replace( pos, 2, TDEProcess::quote(disk->mountPoint()) ) + " &";
         }
         else
         {
            cmd += " " + TDEProcess::quote(disk->mountPoint()) +" &";
         }
         system( TQFile::encodeName(cmd) );
      }
   }
   m_dirty = TRUE;
}
예제 #6
0
void EvaTextEdit::keyPressEvent(TQKeyEvent *e)
{

    int para;
    int index;	
    getCursorPosition(&para,&index);
    if ( (e->key() == TQt::Key_Enter) || (e->key() == TQt::Key_Return) ) {
	if ( (e->state() & TQt::ControlButton)==TQt::ControlButton)
        {
    	    if ( !isEnterSend )
    	    {
        	emit keyPressed(e);
        	return;
    	    }
    	}
	else if ( (e->state() | TQt::KeyButtonMask) ) {
    	    if (isEnterSend )
    	    {
        	emit keyPressed(e);
        	return;
    	    }
	}
    }
    KTextEdit::keyPressEvent(e);
    if((e->key() == TQt::Key_Enter) || (e->key() == TQt::Key_Return) ){	
        TQString txt = text();
        txt.replace("</p>\n<p>", "<br />");
        setText(txt);
        setCursorPosition(para, index + 1);
    }
    emit keyPressed(e);
}
예제 #7
0
bool ejectDriveUDisks(TDEStorageDevice* sdevice) {
#ifdef WITH_UDISKS
	TQT_DBusConnection dbusConn = TQT_DBusConnection::addConnection(TQT_DBusConnection::SystemBus);
	if (dbusConn.isConnected()) {
		TQString blockDeviceString = sdevice->deviceNode();
		blockDeviceString.replace("/dev/", "");
		blockDeviceString = "/org/freedesktop/UDisks/devices/" + blockDeviceString;

		// Eject the drive!
		TQT_DBusError error;
		TQT_DBusProxy driveControl("org.freedesktop.UDisks", blockDeviceString, "org.freedesktop.UDisks.Device", dbusConn);
		if (driveControl.canSend()) {
			TQValueList<TQT_DBusData> params;
			TQT_DBusDataList options;
			params << TQT_DBusData::fromList(options);
			TQT_DBusMessage reply = driveControl.sendWithReply("DriveEject", params, &error);
			if (error.isValid()) {
				// Error!
				printf("[ERROR][tdehwlib] ejectDriveUDisks: %s\n", error.name().ascii()); fflush(stdout);
				return FALSE;
			}
			else {
				return TRUE;
			}
		}
	}
#endif // WITH_UDISKS
	return FALSE;
}
예제 #8
0
TQString KateSearch::getSearchText()
{
  // SelectionOnly: use selection
  // WordOnly: use word under cursor
  // SelectionWord: use selection if available, else use word under cursor
  // WordSelection: use word if available, else use selection
  TQString str;

  int getFrom = view()->config()->textToSearchMode();
  switch (getFrom)
  {
  case KateViewConfig::SelectionOnly: // (Windows)
    //kdDebug() << "getSearchText(): SelectionOnly" << endl;
    if( m_view->hasSelection() )
      str = m_view->selection();
    break;

  case KateViewConfig::SelectionWord: // (classic Kate behavior)
    //kdDebug() << "getSearchText(): SelectionWord" << endl;
    if( m_view->hasSelection() )
      str = m_view->selection();
    else
      str = view()->currentWord();
    break;

  case KateViewConfig::WordOnly: // (weird?)
    //kdDebug() << "getSearchText(): WordOnly" << endl;
    str = view()->currentWord();
    break;

  case KateViewConfig::WordSelection: // (persistent selection lover)
    //kdDebug() << "getSearchText(): WordSelection" << endl;
    str = view()->currentWord();
    if (str.isEmpty() && m_view->hasSelection() )
      str = m_view->selection();
    break;

  default: // (nowhere)
    //kdDebug() << "getSearchText(): Nowhere" << endl;
    break;
  }

  str.replace( TQRegExp("^\\n"), "" );
  str.replace( TQRegExp("\\n.*"), "" );

  return str;
}
예제 #9
0
TQString TDEStorageDevice::mountPath() {
	// See if this device node is mounted
	// This requires parsing /proc/mounts, looking for deviceNode()

	// The Device Mapper throws a monkey wrench into this
	// It likes to advertise mounts as /dev/mapper/<something>,
	// where <something> is listed in <system path>/dm/name

	// First, ensure that all device information (mainly holders/slaves) is accurate
	TDEGlobal::hardwareDevices()->rescanDeviceInformation(this);

	TQString dmnodename = systemPath();
	dmnodename.append("/dm/name");
	TQFile namefile( dmnodename );
	TQString dmaltname;
	if ( namefile.open( IO_ReadOnly ) ) {
		TQTextStream stream( &namefile );
		dmaltname = stream.readLine();
		namefile.close();
	}
	if (!dmaltname.isNull()) {
		dmaltname.prepend("/dev/mapper/");
	}

	TQStringList lines;
	TQFile file( "/proc/mounts" );
	if ( file.open( IO_ReadOnly ) ) {
		TQTextStream stream( &file );
		TQString line;
		while ( !stream.atEnd() ) {
			line = stream.readLine();
			TQStringList mountInfo = TQStringList::split(" ", line, true);
			TQString testNode = *mountInfo.at(0);
			// Check for match
			if ((testNode == deviceNode()) || (testNode == dmaltname) || (testNode == ("/dev/disk/by-uuid/" + diskUUID()))) {
				TQString ret = *mountInfo.at(1);
				ret.replace("\\040", " ");
				return ret;
			}
			lines += line;
		}
		file.close();
	}

	// While this device is not directly mounted, it could concievably be mounted via the Device Mapper
	// If so, try to retrieve the mount path...
	TQStringList slaveDeviceList = holdingDevices();
	for ( TQStringList::Iterator slavedevit = slaveDeviceList.begin(); slavedevit != slaveDeviceList.end(); ++slavedevit ) {
		// Try to locate this device path in the TDE device tree
		TDEHardwareDevices *hwdevices = TDEGlobal::hardwareDevices();
		TDEGenericDevice *hwdevice = hwdevices->findBySystemPath(*slavedevit);
		if ((hwdevice) && (hwdevice->type() == TDEGenericDeviceType::Disk)) {
			TDEStorageDevice* sdevice = static_cast<TDEStorageDevice*>(hwdevice);
			return sdevice->mountPath();
		}
	}

	return TQString::null;
}
예제 #10
0
bool ApsHandler::completePrinter(KMPrinter *prt, PrintcapEntry *entry, bool shortmode)
{
	if (LprHandler::completePrinter(prt, entry, shortmode))
	{
		if (!shortmode)
		{
			TQMap<TQString,TQString>	opts = loadResources(entry);
			if (opts.contains("PRINTER"))
			{
				prt->setDescription(i18n("APS Driver (%1)").arg(opts["PRINTER"]));
				prt->setDriverInfo(prt->description());
			}
		}
		if (prt->device().isEmpty())
		{
			TQString prot;
			TQString	smbname(sysconfDir() + "/" + prt->printerName() + "/smbclient.conf");
			TQString	ncpname(sysconfDir() + "/" + prt->printerName() + "/netware.conf");
			if (TQFile::exists(smbname))
			{
				TQMap<TQString,TQString>	opts = loadVarFile(smbname);
				if (opts.count() == 0)
					prt->setDevice("smb://<unknown>/<unknown>");
				else
				{
					prt->setDevice(buildSmbURI(
								opts[ "SMB_WORKGROUP" ],
								opts[ "SMB_SERVER" ],
								opts[ "SMB_PRINTER" ],
								opts[ "SMB_USER" ],
								opts[ "SMB_PASSWD" ] ) );
				}
				prot = "smb";
			}
			else if (TQFile::exists(ncpname))
			{
				TQMap<TQString,TQString>	opts = loadVarFile(ncpname);
				if (opts.count() == 0)
					prt->setDevice("ncp://<unknown>/<unknown>");
				else
				{
					TQString uri = buildSmbURI( 
							TQString::null,
							opts[ "NCP_SERVER" ],
							opts[ "NCP_PRINTER" ],
							opts[ "NCP_USER" ],
							opts[ "NCP_PASSWD" ] );
					uri.replace( 0, 3, "ncp" );
					prt->setDevice(uri);
				}
				prot = "ncp";
			}
			if (!prt->device().isEmpty())
				prt->setLocation(i18n("Network printer (%1)").arg(prot));
		}
		return true;
	}
	return false;
}
예제 #11
0
void KSim::Sysinfo::sysUpdate()
{
  const System &system = System::self();
  m_totalUptime = system.uptime();

  if (m_memLabel) {
    TQString memory = m_config->memoryFormat();
    unsigned long total = system.totalRam();
    unsigned long free = system.freeRam();
  unsigned long shared = system.sharedRam();
  unsigned long buffer = system.bufferRam();
  unsigned long cache = system.cacheRam();
  unsigned long used = system.usedRam();
  unsigned long allFree = free + buffer + cache;
  bool all = memory.find( "%F" ) != -1;

  memory.replace(TQRegExp("%s"), TQString::number(System::bytesToMegs(shared)));
  memory.replace(TQRegExp("%b"), TQString::number(System::bytesToMegs(buffer)));
  memory.replace(TQRegExp("%c"), TQString::number(System::bytesToMegs(cache)));
  memory.replace(TQRegExp("%u"), TQString::number(System::bytesToMegs(used)));
  memory.replace(TQRegExp("%t"), TQString::number(System::bytesToMegs(total)));
  memory.replace(TQRegExp("%f"), TQString::number(System::bytesToMegs(free)));
  memory.replace(TQRegExp("%F"), TQString::number(System::bytesToMegs(allFree)));
    kdDebug(2003) << memory << endl;
    m_memLabel->setText("Memory");
    TQToolTip::add(m_memLabel, memory );

    if ( !all )
      m_memLabel->setValue( System::bytesToMegs( total ) - System::bytesToMegs( free ) );
    else
      m_memLabel->setValue( System::bytesToMegs( total ) - System::bytesToMegs( allFree ) );
  }

  if (m_swapLabel) {
    TQString swap = m_config->swapFormat();
    unsigned long total = system.totalSwap();
    unsigned long free = system.freeSwap();
    unsigned long swapUsed = system.usedSwap();
    swap.replace(TQRegExp("%u"), TQString::number(System::bytesToMegs(swapUsed)));
    swap.replace(TQRegExp("%t"), TQString::number(System::bytesToMegs(total)));
    swap.replace(TQRegExp("%f"), TQString::number(System::bytesToMegs(free)));
    m_swapLabel->setText("Swap");
    TQToolTip::add(m_swapLabel, swap);
    m_swapLabel->setValue(System::bytesToMegs(total) - System::bytesToMegs(free));
  }

//  if (m_config->showProcs()) {
//    m_procsLabel->setText(i18n("Procs: %1").arg(sysInfo.procs));
//  }
}
예제 #12
0
void EvaChatView::copy( )
{
    if(hasSelection()) {
        TQString text = selectedText();
        text.replace(TQChar(0xa0), ' ');
        TQApplication::clipboard()->setText( text, TQClipboard::Clipboard );
        TQApplication::clipboard()->setText( text, TQClipboard::Selection );
    }
}
예제 #13
0
//
// Capitalization routines
//
TQString KStringHandler::capwords( const TQString &text )
{
    if ( text.isEmpty() ) {
        return text;
    }

    const TQString strippedText = text.stripWhiteSpace();
    const TQStringList words = capwords( TQStringList::split( ' ', strippedText ) );

    TQString result = text;
    result.replace( strippedText, words.join( " " ) );
    return result;
}
예제 #14
0
void LDAPProtocol::LDAPEntry2UDSEntry( const TQString &dn, UDSEntry &entry, 
  const LDAPUrl &usrc, bool dir )
{
  UDSAtom atom;
  
  int pos;
  entry.clear();
  atom.m_uds = UDS_NAME;
  atom.m_long = 0;
  TQString name = dn;
  if ( (pos = name.find(",")) > 0 )
    name = name.left( pos );
  if ( (pos = name.find("=")) > 0 )
    name.remove( 0, pos+1 );
  name.replace(' ', "_");
  if ( !dir ) name += ".ldif";
  atom.m_str = name;
  entry.append( atom );

  // the file type
  atom.m_uds = UDS_FILE_TYPE;
  atom.m_str = "";
  atom.m_long = dir ? S_IFDIR : S_IFREG;
  entry.append( atom );
  
  // the mimetype
  if (!dir) {
    atom.m_uds = UDS_MIME_TYPE;
    atom.m_long = 0;
    atom.m_str = "text/plain";
    entry.append( atom );
  }

  atom.m_uds = UDS_ACCESS;
  atom.m_long = dir ? 0500 : 0400;
  entry.append( atom );

  // the url
  atom.m_uds = UDS_URL;
  atom.m_long = 0;
  LDAPUrl url;
  url=usrc;

  url.setPath("/"+dn);
  url.setScope( dir ? LDAPUrl::One : LDAPUrl::Base );
  atom.m_str = url.prettyURL();
  entry.append( atom );
}
예제 #15
0
void KBuildSycoca::processGnomeVfs()
{
   TQString file = locate("app-reg", "gnome-vfs.applications");
   if (file.isEmpty())
   {
//      kdDebug(7021) << "gnome-vfs.applications not found." << endl;
      return;
   }

   TQString app;

   char line[1024*64];

   FILE *f = fopen(TQFile::encodeName(file), "r");
   while (!feof(f))
   {
      if (!fgets(line, sizeof(line)-1, f))
      {
        break;
      }

      if (line[0] != '\t')
      {
          app = TQString::fromLatin1(line);
          app.truncate(app.length()-1);
      }
      else if (strncmp(line+1, "mime_types=", 11) == 0)
      {
          TQString mimetypes = TQString::fromLatin1(line+12);
          mimetypes.truncate(mimetypes.length()-1);
          mimetypes.replace(TQRegExp("\\*"), "all");
          KService *s = g_bsf->findServiceByName(app);
          if (!s)
             continue;

          TQStringList &serviceTypes = s->accessServiceTypes();
          if (serviceTypes.count() <= 1)
          {
             serviceTypes += TQStringList::split(',', mimetypes);
//             kdDebug(7021) << "Adding gnome mimetypes for '" << app << "'.\n";
//             kdDebug(7021) << "ServiceTypes=" << s->serviceTypes().join(":") << endl;
          }
      }
   }
   fclose( f );
}
예제 #16
0
int mountDriveUDisks2(TQString deviceNode, TQString fileSystemType, TQString mountOptions, TQString* errStr = NULL) {
#ifdef WITH_UDISKS2
	TQT_DBusConnection dbusConn = TQT_DBusConnection::addConnection(TQT_DBusConnection::SystemBus);
	if (dbusConn.isConnected()) {
		TQString blockDeviceString = deviceNode;
		blockDeviceString.replace("/dev/", "");
		blockDeviceString = "/org/freedesktop/UDisks2/block_devices/" + blockDeviceString;

		// Mount the drive!
		TQT_DBusError error;
		TQT_DBusProxy driveControl("org.freedesktop.UDisks2", blockDeviceString, "org.freedesktop.UDisks2.Filesystem", dbusConn);
		if (driveControl.canSend()) {
			TQValueList<TQT_DBusData> params;
			TQMap<TQString, TQT_DBusData> optionsMap;
			if (fileSystemType != "") {
				optionsMap["fstype"] = convertDBUSDataToVariantData(TQT_DBusData::fromString(fileSystemType));
			}
			optionsMap["options"] = convertDBUSDataToVariantData(TQT_DBusData::fromString(mountOptions));
			params << TQT_DBusData::fromStringKeyMap(TQT_DBusDataMap<TQString>(optionsMap));
			TQT_DBusMessage reply = driveControl.sendWithReply("Mount", params, &error);
			if (error.isValid()) {
				// Error!
				if (error.name() == "org.freedesktop.DBus.Error.ServiceUnknown") {
					// Service not installed or unavailable
					return -2;
				}
				if (errStr) {
					*errStr = error.name() + ": " + error.message();
				}
				else {
					printf("[ERROR][tdehwlib] mountDriveUDisks2: %s\n", error.name().ascii()); fflush(stdout);
				}
				return -1;
			}
			else {
				return 0;
			}
		}
		else {
			return -2;
		}
	}
#endif // WITH_UDISKS2
	return -2;
}
예제 #17
0
void TDELocaleConfigNumber::save()
{
  // temperary use of our locale as the global locale
  TDELocale *lsave = TDEGlobal::_locale;
  TDEGlobal::_locale = m_locale;

  TDEConfig *config = TDEGlobal::config();
  TDEConfigGroupSaver saver(config, "Locale");

  KSimpleConfig ent(locate("locale",
			   TQString::fromLatin1("l10n/%1/entry.desktop")
			   .arg(m_locale->country())), true);
  ent.setGroup("KCM Locale");

  TQString str;

  str = ent.readEntry("DecimalSymbol",
		      TQString::fromLatin1("."));
  config->deleteEntry("DecimalSymbol", false, true);
  if (str != m_locale->decimalSymbol())
    config->writeEntry("DecimalSymbol",
		       m_locale->decimalSymbol(), true, true);

  str = ent.readEntry("ThousandsSeparator",
		      TQString::fromLatin1(","));
  config->deleteEntry("ThousandsSeparator", false, true);
  str.replace(TQString::fromLatin1("$0"), TQString());
  if (str != m_locale->thousandsSeparator())
    config->writeEntry("ThousandsSeparator",
		       TQString::fromLatin1("$0%1$0")
		       .arg(m_locale->thousandsSeparator()), true, true);

  str = ent.readEntry("PositiveSign");
  config->deleteEntry("PositiveSign", false, true);
  if (str != m_locale->positiveSign())
    config->writeEntry("PositiveSign", m_locale->positiveSign(), true, true);

  str = ent.readEntry("NegativeSign", TQString::fromLatin1("-"));
  config->deleteEntry("NegativeSign", false, true);
  if (str != m_locale->negativeSign())
    config->writeEntry("NegativeSign", m_locale->negativeSign(), true, true);

  // restore the old global locale
  TDEGlobal::_locale = lsave;
}
예제 #18
0
int mountDriveUDisks(TQString deviceNode, TQString fileSystemType, TQStringList mountOptions, TQString* errStr = NULL) {
#ifdef WITH_UDISKS
	TQT_DBusConnection dbusConn = TQT_DBusConnection::addConnection(TQT_DBusConnection::SystemBus);
	if (dbusConn.isConnected()) {
		TQString blockDeviceString = deviceNode;
		blockDeviceString.replace("/dev/", "");
		blockDeviceString = "/org/freedesktop/UDisks/devices/" + blockDeviceString;

		// Mount the drive!
		TQT_DBusError error;
		TQT_DBusProxy driveControl("org.freedesktop.UDisks", blockDeviceString, "org.freedesktop.UDisks.Device", dbusConn);
		if (driveControl.canSend()) {
			TQValueList<TQT_DBusData> params;
			params << TQT_DBusData::fromString(fileSystemType);
			params << TQT_DBusData::fromList(TQT_DBusDataList(mountOptions));
			TQT_DBusMessage reply = driveControl.sendWithReply("FilesystemMount", params, &error);
			if (error.isValid()) {
				// Error!
				if (error.name() == "org.freedesktop.DBus.Error.ServiceUnknown") {
					// Service not installed or unavailable
					return -2;
				}
				if (errStr) {
					*errStr = error.name() + ": " + error.message();
				}
				else {
					printf("[ERROR][tdehwlib] mountDriveUDisks: %s\n", error.name().ascii()); fflush(stdout);
				}
				return -1;
			}
			else {
				return 0;
			}
		}
		else {
			return -2;
		}
	}
#endif // WITH_UDISKS
	return -2;
}
예제 #19
0
bool KXSConfigDialog::create()
{
    TQVBoxLayout *topLayout = new TQVBoxLayout(plainPage(), spacingHint());
    TQHBoxLayout *tqlayout = new TQHBoxLayout(topLayout, spacingHint());
    TQVBox *controlLayout = new TQVBox(plainPage());
    controlLayout->setSpacing(spacingHint());
    tqlayout->addWidget(controlLayout);
    ((TQBoxLayout*)controlLayout->tqlayout())->addStrut(120);

    KConfig config(mConfigFile);

    TQString xmlFile = "/doesntexist";
#ifdef XSCREENSAVER_CONFIG_DIR
    xmlFile = XSCREENSAVER_CONFIG_DIR;
#endif

    xmlFile += "/" + mExeName + ".xml";
    if ( TQFile::exists( xmlFile ) ) {
	// We can use the xscreensaver xml config files.
	KXSXml xmlParser(controlLayout);
	xmlParser.parse( xmlFile );
	mConfigItemList = *xmlParser.items();
	TQWidget *spacer = new TQWidget(controlLayout);
	controlLayout->setStretchFactor(spacer, 1 );
	TQString descr = xmlParser.description();
	if ( !descr.isEmpty() ) {
	    descr.replace('\n',' ');
	    descr = descr.simplifyWhiteSpace();
	    TQLabel *l = new TQLabel( i18n( descr.utf8() ), plainPage() );
	    l->tqsetAlignment ( WordBreak );
 	    topLayout->addWidget( l );
 	}
    } else {
        // fall back to KDE's old config files.
	int idx = 0;
	while (true) {
	    TQString group = TQString("Arg%1").tqarg(idx);
	    if (config.hasGroup(group)) {
		config.setGroup(group);
		TQString type = config.readEntry("Type");
		if (type == "Range") {
		    KXSRangeControl *rc = new KXSRangeControl(controlLayout, group, config);
		    mConfigItemList.append(rc);
		} else if (type == "DoubleRange") {
		    KXSDoubleRangeControl *rc =
			new KXSDoubleRangeControl(controlLayout, group, config);
		    mConfigItemList.append(rc);
		} else if (type == "Check") {
		    KXSCheckBoxControl *cc = new KXSCheckBoxControl(controlLayout, group,
			    config);
		    mConfigItemList.append(cc);
		} else if (type == "DropList") {
		    KXSDropListControl *dl = new KXSDropListControl(controlLayout, group,
			    config);
		    mConfigItemList.append(dl);
		}
	    } else {
		break;
	    }
	    idx++;
	}
	if ( idx == 0 )
	    return false;
    }

    TQPtrListIterator<KXSConfigItem> it( mConfigItemList );
    KXSConfigItem *item;
    while ( (item = it.current()) != 0 ) {
	++it;
	item->read( config );
        TQWidget *i = dynamic_cast<TQWidget*>(item);
        if (i) {
            connect( i, TQT_SIGNAL(changed()), TQT_SLOT(slotChanged()) );
        }
    }

    mPreviewProc = new KProcess;
    connect(mPreviewProc, TQT_SIGNAL(processExited(KProcess *)),
	    TQT_SLOT(slotPreviewExited(KProcess *)));

    mPreviewTimer = new TQTimer(this);
    connect(mPreviewTimer, TQT_SIGNAL(timeout()), TQT_SLOT(slotNewPreview()));

    mPreview = new TQWidget(plainPage());
    mPreview->setFixedSize(250, 200);
    //  mPreview->setBackgroundMode(TQWidget::NoBackground);
    mPreview->setBackgroundColor(TQt::black);

    tqlayout->add(mPreview);
    show();

    // So that hacks can XSelectInput ButtonPressMask
    XSelectInput(qt_xdisplay(), mPreview->winId(), widgetEventMask );

    slotPreviewExited(0);
    return true;
}
예제 #20
0
void KateSearch::replaceOne()
{
  TQString replaceWith = m_replacement;
  if ( s.flags.regExp && s.flags.useBackRefs ) {
    // Replace each "\0"..."\9" with the corresponding capture,
    // "\n" and "\t" with newline and tab,
    // "\\" with "\",
    // and remove the "\" for any other sequence.
    TQRegExp br("\\\\(.)");
    int pos = br.search( replaceWith );
    int ncaps = m_re.numCaptures();
    while ( pos >= 0 ) {
      TQString substitute;
      TQChar argument = TQString(br.cap(1)).at(0);
      if ( argument.isDigit() ) {
        // the second character is a digit, this is a backreference
        int ccap = argument.digitValue();
        if (ccap <= ncaps ) {
          substitute = m_re.cap( ccap );
        } else {
          kdDebug()<<"KateSearch::replaceOne(): you don't have "<<ccap<<" backreferences in regexp '"<<TQString(m_re.pattern())<<"'"<<endl;
          break;
        }
      } else if ( argument == 'n' ) {
        substitute = '\n';
      } else if ( argument == 't' ) {
        substitute = '\t';
      } else {
        // handle a validly escaped backslash, or an invalid escape.
        substitute = argument;
      }
      replaceWith.replace( pos, br.matchedLength(), substitute );
      pos = br.search( replaceWith, pos + substitute.length() );
    }
  }

  doc()->editStart();
  doc()->removeText( s.cursor.line(), s.cursor.col(),
      s.cursor.line(), s.cursor.col() + s.matchedLength );
  doc()->insertText( s.cursor.line(), s.cursor.col(), replaceWith );
  doc()->editEnd(),

  replaces++;

  // if we inserted newlines, we better adjust.
  uint newlines = replaceWith.contains('\n');
  if ( newlines )
  {
    if ( ! s.flags.backward )
    {
      s.cursor.setLine( s.cursor.line() + newlines );
      s.cursor.setCol( replaceWith.length() - replaceWith.findRev('\n') );
    }
    // selection?
    if ( s.flags.selected )
      s.selEnd.setLine( s.selEnd.line() + newlines );
  }


  // adjust selection endcursor if needed
  if( s.flags.selected && s.cursor.line() == s.selEnd.line() )
  {
    s.selEnd.setCol(s.selEnd.col() + replaceWith.length() - s.matchedLength );
  }

  // adjust wrap cursor if needed
  if( s.cursor.line() == s.wrappedEnd.line() && s.cursor.col() <= s.wrappedEnd.col())
  {
    s.wrappedEnd.setCol(s.wrappedEnd.col() + replaceWith.length() - s.matchedLength );
  }

  if( !s.flags.backward ) {
    s.cursor.setCol(s.cursor.col() + replaceWith.length());
  } else if( s.cursor.col() > 0 ) {
    s.cursor.setCol(s.cursor.col() - 1);
  } else {
    s.cursor.setLine(s.cursor.line() - 1);
    if( s.cursor.line() >= 0 ) {
      s.cursor.setCol(doc()->lineLength( s.cursor.line() ));
    }
  }
}
예제 #21
0
void NoatunSensor::update()
{
    TQString format;
    SensorParams *sp;
    Meter *meter;
    TQObjectListIt it( *objList );

    TQString title;
    int songLength = 0;
    int currentTime = 0;

    bool running = isRunning();

    if( running )
    {
        title = getTitle();

       if( title.isEmpty() )
            title = "Noatun";
        currentTime = getTime();
        if( currentTime == -1 )
            currentTime = 0;

        songLength = getLength();
        if( songLength == -1 )
            songLength = 0;
    }


    while (it != 0)
    {
        sp = (SensorParams*)(*it);
        meter = sp->getMeter();

        if( running )
        {

            format = sp->getParam("FORMAT");
            if (format.length() == 0 )
            {
                format = "%title %time / %length";
            }

            if( format.lower() == "%ms" )
            {
                meter->setMax( songLength );
                meter->setValue( currentTime );
            }
            else
                if ( format.lower() == "%full" )
                {
                    meter->setValue( 1 );
                }
                else

                {
                   format.replace( TQRegExp("%title", false), title );
		   format.replace( TQRegExp("%id", false), noatunID );

                    format.replace( TQRegExp("%length", false), TQTime( 0,0,0 ).
                                    addMSecs( songLength )
                                    .toString( "h:mm:ss" ) );

                    format.replace( TQRegExp("%time", false), TQTime( 0,0,0 ).
                                    addMSecs( currentTime )
                                    .toString( "h:mm:ss" ) );
                    format.replace( TQRegExp("%remain", false), TQTime( 0,0,0 ).
                                    addMSecs( songLength )
                                    .addMSecs(-currentTime )
                                    .toString( "h:mm:ss" ) );

                    meter->setValue(format);
                }
        }
        else

        {
            meter->setValue("");
        }
        ++it;


    }

}
예제 #22
0
void PreviewJob::startPreview()
{
    // Load the list of plugins to determine which mimetypes are supported
    TDETrader::OfferList plugins = TDETrader::self()->query("ThumbCreator");
    TQMap<TQString, KService::Ptr> mimeMap;

    for (TDETrader::OfferList::ConstIterator it = plugins.begin(); it != plugins.end(); ++it)
        if (!d->enabledPlugins || d->enabledPlugins->contains((*it)->desktopEntryName()))
    {
        TQStringList mimeTypes = (*it)->property("MimeTypes").toStringList();
        for (TQStringList::ConstIterator mt = mimeTypes.begin(); mt != mimeTypes.end(); ++mt)
            mimeMap.insert(*mt, *it);
    }

    // Look for images and store the items in our todo list :)
    bool bNeedCache = false;
    for (KFileItemListIterator it(d->initialItems); it.current(); ++it )
    {
        PreviewItem item;
        item.item = it.current();
        TQMap<TQString, KService::Ptr>::ConstIterator plugin = mimeMap.find(it.current()->mimetype());
        if (plugin == mimeMap.end()
            && (it.current()->mimetype() != "application/x-desktop")
            && (it.current()->mimetype() != "media/builtin-mydocuments")
            && (it.current()->mimetype() != "media/builtin-mycomputer")
            && (it.current()->mimetype() != "media/builtin-mynetworkplaces")
            && (it.current()->mimetype() != "media/builtin-printers")
            && (it.current()->mimetype() != "media/builtin-trash")
            && (it.current()->mimetype() != "media/builtin-webbrowser"))
        {
            TQString mimeType = it.current()->mimetype();
            plugin = mimeMap.find(mimeType.replace(TQRegExp("/.*"), "/*"));

            if (plugin == mimeMap.end())
            {
                // check mime type inheritance
                KMimeType::Ptr mimeInfo = KMimeType::mimeType(it.current()->mimetype());
                TQString parentMimeType = mimeInfo->parentMimeType();
                while (!parentMimeType.isEmpty())
                {
                    plugin = mimeMap.find(parentMimeType);
                    if (plugin != mimeMap.end()) break;

                    KMimeType::Ptr parentMimeInfo = KMimeType::mimeType(parentMimeType);
                    if (!parentMimeInfo) break;

                    parentMimeType = parentMimeInfo->parentMimeType();
                }
            }

            if (plugin == mimeMap.end())
            {
                // check X-TDE-Text property
                KMimeType::Ptr mimeInfo = KMimeType::mimeType(it.current()->mimetype());
                TQVariant textProperty = mimeInfo->property("X-TDE-text");
                if (textProperty.isValid() && textProperty.type() == TQVariant::Bool)
                {
                    if (textProperty.toBool())
                    {
                        plugin = mimeMap.find("text/plain");
                        if (plugin == mimeMap.end())
                        {
                            plugin = mimeMap.find( "text/*" );
                        }
                    }
                }
            }
        }

        if (plugin != mimeMap.end())
        {
            item.plugin = *plugin;
            d->items.append(item);
            if (!bNeedCache && d->bSave &&
                (it.current()->url().protocol() != "file" ||
                 !it.current()->url().directory( false ).startsWith(d->thumbRoot)) &&
                (*plugin)->property("CacheThumbnail").toBool())
                bNeedCache = true;
        }
        else
        {
            emitFailed(it.current());
            if (d->deleteItems)
                delete it.current();
        }
    }

  // Read configuration value for the maximum allowed size
    TDEConfig * config = TDEGlobal::config();
    TDEConfigGroupSaver cgs( config, "PreviewSettings" );
    d->maximumSize = config->readNumEntry( "MaximumSize", 1024*1024 /* 1MB */ );

    if (bNeedCache)
    {
        if (d->width <= 128 && d->height <= 128) d->cacheWidth = d->cacheHeight = 128;
        else d->cacheWidth = d->cacheHeight = 256;
        d->thumbPath = d->thumbRoot + (d->cacheWidth == 128 ? "normal/" : "large/");
        TDEStandardDirs::makeDir(d->thumbPath, 0700);
    }
    else
        d->bSave = false;
    determineNextFile();
}
예제 #23
0
void KWindowListMenu::init()
{
    int i, d;
    i = 0;

    int nd = twin_module->numberOfDesktops();
    int cd = twin_module->currentDesktop();
    WId active_window = twin_module->activeWindow();

    // Make sure the popup is not too wide, otherwise clicking in the middle of kdesktop
    // wouldn't leave any place for the popup, and release would activate some menu entry.    
    int maxwidth = kapp->desktop()->screenGeometry( this ).width() / 2 - 100;

    clear();
    map.clear();

    int unclutter = insertItem( i18n("Unclutter Windows"),
                                this, TQT_SLOT( slotUnclutterWindows() ) );
    int cascade = insertItem( i18n("Cascade Windows"),
                              this, TQT_SLOT( slotCascadeWindows() ) );

    // if we only have one desktop we won't be showing titles, so put a separator in
    if (nd == 1)
    {
        insertSeparator();
    }


    TQValueList<KWin::WindowInfo> windows;
    for (TQValueList<WId>::ConstIterator it = twin_module->windows().begin();
         it != twin_module->windows().end(); ++it) {
         windows.append( KWin::windowInfo( *it, NET::WMDesktop ));
    }
    bool show_all_desktops_group = ( nd > 1 );
    for (d = 1; d <= nd + (show_all_desktops_group ? 1 : 0); d++) {
        bool on_all_desktops = ( d > nd );
	int items = 0;

	if (!active_window && d == cd)
	    setItemChecked(1000 + d, true);

        NameSortedInfoList list;
        list.setAutoDelete(true);

	for (TQValueList<KWin::WindowInfo>::ConstIterator it = windows.begin();
             it != windows.end(); ++it) {
	    if (((*it).desktop() == d) || (on_all_desktops && (*it).onAllDesktops())
                || (!show_all_desktops_group && (*it).onAllDesktops())) {
	        list.inSort(new KWin::WindowInfo( (*it).win(),
                    NET::WMVisibleName | NET::WMState | NET::XAWMState | NET::WMWindowType,
                    NET::WM2GroupLeader | NET::WM2TransientFor ));
            }
        }

        for (KWin::WindowInfo* info = list.first(); info; info = list.next(), ++i)
        {
            TQString itemText = KStringHandler::cPixelSqueeze(info->visibleNameWithState(), fontMetrics(), maxwidth);
            NET::WindowType windowType = info->windowType( NET::NormalMask | NET::DesktopMask
                | NET::DockMask | NET::ToolbarMask | NET::MenuMask | NET::DialogMask
                | NET::OverrideMask | NET::TopMenuMask | NET::UtilityMask | NET::SplashMask );
            if ( (windowType == NET::Normal || windowType == NET::Unknown
                    || (windowType == NET::Dialog && standaloneDialog( info, list )))
                && !(info->state() & NET::SkipTaskbar) ) {
                TQPixmap pm = KWin::icon(info->win(), 16, 16, true );
                items++;

                // ok, we have items on this desktop, let's show the title
                if ( items == 1 && nd > 1 )
                {
                    if( !on_all_desktops )
                        insertTitle(twin_module->desktopName( d ), 1000 + d);
                    else
                        insertTitle(i18n("On All Desktops"), 2000 );
                }

                // Avoid creating unwanted accelerators.
                itemText.replace('&', TQString::fromLatin1("&&"));
                insertItem( pm, itemText, i);
                map.insert(i, info->win());
                if (info->win() == active_window)
                    setItemChecked(i, true);
            }
        }

        if (d == cd)
        {
            setItemEnabled(unclutter, items > 0);
            setItemEnabled(cascade, items > 0);
        }
    }

    // no windows?
    if (i == 0)
    {
        if (nd > 1)
        {
            // because we don't have any titles, nor a separator
            insertSeparator();
        }

        setItemEnabled(insertItem(i18n("No Windows")), false);
    }
}
예제 #24
0
void TDERecentDocument::add(const KURL& url, const TQString& desktopEntryName)
{
	if ( url.isLocalFile() && !TDEGlobal::dirs()->relativeLocation("tmp", url.path()).startsWith("/"))
		return;

    TQString openStr = url.url();
    openStr.replace( TQRegExp("\\$"), "$$" ); // Desktop files with type "Link" are $-variable expanded

    kdDebug(250) << "TDERecentDocument::add for " << openStr << endl;
    TDEConfig *config = TDEGlobal::config();
    TQString oldGrp = config->group();
    config->setGroup(TQString::fromLatin1("RecentDocuments"));
    bool useRecent = config->readBoolEntry(TQString::fromLatin1("UseRecent"), true);
    int maxEntries = config->readNumEntry(TQString::fromLatin1("MaxEntries"), 10);

    config->setGroup(oldGrp);
    if(!useRecent)
        return;

    TQString path = recentDocumentDirectory();

    TQString dStr = path + url.fileName();

    TQString ddesktop = dStr + TQString::fromLatin1(".desktop");

    int i=1;
    // check for duplicates
    while(TQFile::exists(ddesktop)){
        // see if it points to the same file and application
        KSimpleConfig tmp(ddesktop);
        tmp.setDesktopGroup();
        if(tmp.readEntry(TQString::fromLatin1("X-TDE-LastOpenedWith"))
	   == desktopEntryName)
	{
            utime(TQFile::encodeName(ddesktop), NULL);
            return;
        }
        // if not append a (num) to it
        ++i;
        if ( i > maxEntries )
            break;
        ddesktop = dStr + TQString::fromLatin1("[%1].desktop").arg(i);
    }

    TQDir dir(path);
    // check for max entries, delete oldest files if exceeded
    TQStringList list = dir.entryList(TQDir::Files | TQDir::Hidden, TQDir::Time | TQDir::Reversed);
    i = list.count();
    if(i > maxEntries-1){
        TQStringList::Iterator it;
        it = list.begin();
        while(i > maxEntries-1){
            TQFile::remove(dir.absPath() + TQString::fromLatin1("/") + (*it));
            --i, ++it;
        }
    }

    // create the applnk
    KSimpleConfig conf(ddesktop);
    conf.setDesktopGroup();
    conf.writeEntry( TQString::fromLatin1("Type"), TQString::fromLatin1("Link") );
    conf.writePathEntry( TQString::fromLatin1("URL"), openStr );
    // If you change the line below, change the test in the above loop
    conf.writeEntry( TQString::fromLatin1("X-TDE-LastOpenedWith"), desktopEntryName );
    TQString name = url.fileName();
    if (name.isEmpty())
      name = openStr;
    conf.writeEntry( TQString::fromLatin1("Name"), name );
    conf.writeEntry( TQString::fromLatin1("Icon"), KMimeType::iconForURL( url ) );
}
예제 #25
0
bool ejectDriveUDisks2(TDEStorageDevice* sdevice) {
#ifdef WITH_UDISKS2
	TQT_DBusConnection dbusConn = TQT_DBusConnection::addConnection(TQT_DBusConnection::SystemBus);
	if (dbusConn.isConnected()) {
		TQString blockDeviceString = sdevice->deviceNode();
		blockDeviceString.replace("/dev/", "");
		blockDeviceString = "/org/freedesktop/UDisks2/block_devices/" + blockDeviceString;
		TQT_DBusProxy hardwareControl("org.freedesktop.UDisks2", blockDeviceString, "org.freedesktop.DBus.Properties", dbusConn);
		if (hardwareControl.canSend()) {
			// get associated udisks2 drive path
			TQT_DBusError error;
			TQValueList<TQT_DBusData> params;
			params << TQT_DBusData::fromString("org.freedesktop.UDisks2.Block") << TQT_DBusData::fromString("Drive");
			TQT_DBusMessage reply = hardwareControl.sendWithReply("Get", params, &error);
			if (error.isValid()) {
				// Error!
				printf("[ERROR][tdehwlib] ejectDriveUDisks2: %s\n", error.name().ascii()); fflush(stdout);
				return FALSE;
			}
			else {
				if (reply.type() == TQT_DBusMessage::ReplyMessage && reply.count() == 1) {
					TQT_DBusObjectPath driveObjectPath = reply[0].toVariant().value.toObjectPath();
					if (!driveObjectPath.isValid()) {
						return FALSE;
					}

					error = TQT_DBusError();
					TQT_DBusProxy driveInformation("org.freedesktop.UDisks2", driveObjectPath, "org.freedesktop.DBus.Properties", dbusConn);
					// can eject?
					TQValueList<TQT_DBusData> params;
					params << TQT_DBusData::fromString("org.freedesktop.UDisks2.Drive") << TQT_DBusData::fromString("Ejectable");
					TQT_DBusMessage reply = driveInformation.sendWithReply("Get", params, &error);
					if (error.isValid()) {
						// Error!
						printf("[ERROR][tdehwlib] ejectDriveUDisks2: %s\n", error.name().ascii()); fflush(stdout);
						return FALSE;
					}
					if (reply.type() == TQT_DBusMessage::ReplyMessage && reply.count() == 1) {
						bool ejectable = reply[0].toVariant().value.toBool();
						if (!ejectable) {
							return FALSE;
						}

						// Eject the drive!
						TQT_DBusProxy driveControl("org.freedesktop.UDisks2", driveObjectPath, "org.freedesktop.UDisks2.Drive", dbusConn);
						TQValueList<TQT_DBusData> params;
						TQT_DBusDataMap<TQString> options(TQT_DBusData::Variant);
						params << TQT_DBusData::fromStringKeyMap(options);
						TQT_DBusMessage reply = driveControl.sendWithReply("Eject", params, &error);
						if (error.isValid()) {
							// Error!
							printf("[ERROR][tdehwlib] ejectDriveUDisks2: %s\n", error.name().ascii()); fflush(stdout);
							return FALSE;
						}
						else {
							return TRUE;
						}
					}
				}
			}
		}
	}
#endif // WITH_UDISKS2
	return FALSE;
}
예제 #26
0
void DiskSensor::processExited(TDEProcess *)
{
    TQStringList stringList = TQStringList::split('\n',sensorResult);
    sensorResult = "";
    TQStringList::Iterator it = stringList.begin();
    //TQRegExp rx( "^(/dev/).*(/\\S*)$");
    TQRegExp rx( ".*\\s+(/\\S*)$");

    while( it != stringList.end())
    {
        rx.search( *it );
        if ( !rx.cap(0).isEmpty())
        {
            mntMap[rx.cap(1)] = *it;
        }
        it++;
    }
    stringList.clear();

    TQString format;
    TQString mntPt;
    SensorParams *sp;
    Meter *meter;

    TQObjectListIt lit( *objList );
    while (lit != 0)
    {
        sp = (SensorParams*)(*lit);
        meter = sp->getMeter();
        format = sp->getParam("FORMAT");
        mntPt = sp->getParam("MOUNTPOINT");
        if (mntPt.length() == 0)
            mntPt="/";

        if (format.length() == 0 )
        {
            format = "%u";
        }
        format.replace( TQRegExp("%fp", false),TQString::number(getPercentFree(mntPt)));
        format.replace( TQRegExp("%fg",false),
                        TQString::number(getFreeSpace(mntPt)/(1024*1024)));
        format.replace( TQRegExp("%fkb",false),
                        TQString::number(getFreeSpace(mntPt)*8) );
        format.replace( TQRegExp("%fk",false),
                        TQString::number(getFreeSpace(mntPt)) );
        format.replace( TQRegExp("%f", false),TQString::number(getFreeSpace(mntPt)/1024));
        
        format.replace( TQRegExp("%up", false),TQString::number(getPercentUsed(mntPt)));
        format.replace( TQRegExp("%ug",false),
                        TQString::number(getUsedSpace(mntPt)/(1024*1024)));
        format.replace( TQRegExp("%ukb",false),
                        TQString::number(getUsedSpace(mntPt)*8) );
        format.replace( TQRegExp("%uk",false),
                        TQString::number(getUsedSpace(mntPt)) );
        format.replace( TQRegExp("%u", false),TQString::number(getUsedSpace(mntPt)/1024));

        format.replace( TQRegExp("%tg",false),
                        TQString::number(getTotalSpace(mntPt)/(1024*1024)));
        format.replace( TQRegExp("%tkb",false),
                        TQString::number(getTotalSpace(mntPt)*8));
        format.replace( TQRegExp("%tk",false),
                        TQString::number(getTotalSpace(mntPt)));
        format.replace( TQRegExp("%t", false),TQString::number(getTotalSpace(mntPt)/1024));
        meter->setValue(format);
        ++lit;
    }
    if ( init == 1 )
    {
        emit initComplete();
        init = 0;
    }
}
예제 #27
0
TQString TDEStorageDevice::mountDevice(TQString mediaName, TDEStorageMountOptions mountOptions, TQString* errRet, int* retcode) {
	int internal_retcode;
	if (!retcode) {
		retcode = &internal_retcode;
	}

	TQString ret = mountPath();

	// Device is already mounted
	if (!ret.isNull()) {
		return ret;
	}

	TQString command;
	TQString devNode = deviceNode();
	devNode.replace("'", "'\\''");
	mediaName.replace("'", "'\\''");

#if defined(WITH_UDISKS2) || defined(WITH_UDISKS)
	// Prepare filesystem options for mount
	TQStringList udisksOptions;
	TQString optionString;

	if (mountOptions["ro"] == "true") {
		udisksOptions.append("ro");
	}

	if (mountOptions["atime"] != "true") {
		udisksOptions.append("noatime");
	}

	if (mountOptions["sync"] == "true") {
		udisksOptions.append("sync");
	}

	if(  (mountOptions["filesystem"] == "fat")
	  || (mountOptions["filesystem"] == "vfat")
	  || (mountOptions["filesystem"] == "msdos")
	  || (mountOptions["filesystem"] == "umsdos")
	) {
		if (mountOptions.contains("shortname")) {
			udisksOptions.append(TQString("shortname=%1").arg(mountOptions["shortname"]));
		}
	}

	if( (mountOptions["filesystem"] == "jfs")) {
		if (mountOptions["utf8"] == "true") {
			// udisks/udisks2 for now does not support option iocharset= for jfs
			// udisksOptions.append("iocharset=utf8");
		}
	}

	if( (mountOptions["filesystem"] == "ntfs-3g") ) {
		if (mountOptions.contains("locale")) {
			udisksOptions.append(TQString("locale=%1").arg(mountOptions["locale"]));
		}
	}

	if(  (mountOptions["filesystem"] == "ext3")
	  || (mountOptions["filesystem"] == "ext4")
	) {
		if (mountOptions.contains("journaling")) {
			// udisks/udisks2 for now does not support option data= for ext3/ext4
			// udisksOptions.append(TQString("data=%1").arg(mountOptions["journaling"]));
		}
	}

	for (TQStringList::Iterator it = udisksOptions.begin(); it != udisksOptions.end(); ++it) {
		optionString.append(",");
		optionString.append(*it);
	}

	if (!optionString.isEmpty()) {
		optionString.remove(0, 1);
	}
#endif // defined(WITH_UDISKS2) || defined(WITH_UDISKS)

#ifdef WITH_UDISKS2
	if(command.isEmpty()) {
		// Try to use UDISKS v2 via DBUS, if available
		TQString errorString;
		TQString fileSystemType;

		if (mountOptions.contains("filesystem") && !mountOptions["filesystem"].isEmpty()) {
			fileSystemType = mountOptions["filesystem"];
		}

		int uDisks2Ret = mountDriveUDisks2(devNode, fileSystemType, optionString, &errorString);
		if (uDisks2Ret == 0) {
			// Update internal mount data
			TDEGlobal::hardwareDevices()->processModifiedMounts();

			ret = mountPath();
			return ret;
		}
		else if (uDisks2Ret == -1) {
			if (errRet) {
				*errRet = errorString;
			}

			// Update internal mount data
			TDEGlobal::hardwareDevices()->processModifiedMounts();

			ret = mountPath();
			return ret;
		}
		else {
			// The UDISKS v2 DBUS service was either not available or was unusable; try another method...
			command = TQString::null;
		}
	}
#endif // WITH_UDISKS2

#ifdef WITH_UDISKS
	if(command.isEmpty()) {
		// Try to use UDISKS v1 via DBUS, if available
		TQString errorString;
		TQString fileSystemType;

		if (mountOptions.contains("filesystem") && !mountOptions["filesystem"].isEmpty()) {
			fileSystemType = mountOptions["filesystem"];
		}

		int uDisksRet = mountDriveUDisks(devNode, fileSystemType, udisksOptions, &errorString);
		if (uDisksRet == 0) {
			// Update internal mount data
			TDEGlobal::hardwareDevices()->processModifiedMounts();

			ret = mountPath();
			return ret;
		}
		else if (uDisksRet == -1) {
			if (errRet) {
				*errRet = errorString;
			}

			// Update internal mount data
			TDEGlobal::hardwareDevices()->processModifiedMounts();

			ret = mountPath();
			return ret;
		}
		else {
			// The UDISKS v1 DBUS service was either not available or was unusable; try another method...
			command = TQString::null;
		}
	}
#endif // WITH_UDISKS

	if(command.isEmpty()) {
		// Use 'pmount' command, if available
		TQString pmountProg = TDEGlobal::dirs()->findExe("pmount");
		if (!pmountProg.isEmpty()) {
			// Create dummy password file
			KTempFile passwordFile(TQString::null, "tmp", 0600);
			passwordFile.setAutoDelete(true);

			TQString optionString;
			if (mountOptions["ro"] == "true") {
				optionString.append(" -r");
			}

			if (mountOptions["atime"] != "true") {
				optionString.append(" -A");
			}

			if (mountOptions["utf8"] == "true") {
				optionString.append(" -c utf8");
			}

			if (mountOptions["sync"] == "true") {
				optionString.append(" -s");
			}

			if (mountOptions.contains("filesystem") && !mountOptions["filesystem"].isEmpty()) {
				optionString.append(TQString(" -t %1").arg(mountOptions["filesystem"]));
			}

			if (mountOptions.contains("locale")) {
				optionString.append(TQString(" -c %1").arg(mountOptions["locale"]));
			}

			TQString passFileName = passwordFile.name();
			passFileName.replace("'", "'\\''");

			command = TQString("pmount -p '%1' %2 '%3' '%4' 2>&1").arg(passFileName).arg(optionString).arg(devNode).arg(mediaName);
		}
	}

	if(command.isEmpty()) {
		if (errRet) {
			*errRet = i18n("No supported mounting methods were detected on your system");
		}
		return ret;
	}

	FILE *exepipe = popen(command.local8Bit(), "r");
	if (exepipe) {
		TQString mount_output;
		TQTextStream ts(exepipe, IO_ReadOnly);
		mount_output = ts.read();
		*retcode = pclose(exepipe);
		if (errRet) {
			*errRet = mount_output;
		}
	}

	// Update internal mount data
	TDEGlobal::hardwareDevices()->processModifiedMounts();

	ret = mountPath();

	return ret;
}
예제 #28
0
TQString TDEStorageDevice::mountEncryptedDevice(TQString passphrase, TQString mediaName, TDEStorageMountOptions mountOptions, TQString* errRet, int* retcode) {
	int internal_retcode;
	if (!retcode) {
		retcode = &internal_retcode;
	}

	TQString ret = mountPath();

	if (!ret.isNull()) {
		return ret;
	}

	// Create dummy password file
	KTempFile passwordFile(TQString::null, "tmp", 0600);
	passwordFile.setAutoDelete(true);
	TQFile* pwFile = passwordFile.file();
	if (!pwFile) {
		return TQString::null;
	}

	pwFile->writeBlock(passphrase.ascii(), passphrase.length());
	pwFile->flush();

	TQString optionString;
	if (mountOptions["ro"] == "true") {
		optionString.append(" -r");
	}
	
	if (mountOptions["atime"] != "true") {
		optionString.append(" -A");
	}
	
	if (mountOptions["utf8"] == "true") {
		optionString.append(" -c utf8");
	}
	
	if (mountOptions["sync"] == "true") {
		optionString.append(" -s");
	}

	if (mountOptions.contains("filesystem") && !mountOptions["filesystem"].isEmpty()) {
		optionString.append(TQString(" -t %1").arg(mountOptions["filesystem"]));
	}

	if (mountOptions.contains("locale")) {
		optionString.append(TQString(" -c %1").arg(mountOptions["locale"]));
	}

	TQString passFileName = passwordFile.name();
	TQString devNode = deviceNode();
	passFileName.replace("'", "'\\''");
	devNode.replace("'", "'\\''");
	mediaName.replace("'", "'\\''");
	TQString command = TQString("pmount -p '%1' %2 '%3' '%4' 2>&1").arg(passFileName).arg(optionString).arg(devNode).arg(mediaName);

	FILE *exepipe = popen(command.local8Bit(), "r");
	if (exepipe) {
		TQString mount_output;
		TQTextStream ts(exepipe, IO_ReadOnly);
		mount_output = ts.read();
		*retcode = pclose(exepipe);
		if (errRet) {
			*errRet = mount_output;
		}
	}

	// Update internal mount data
	TDEGlobal::hardwareDevices()->processModifiedMounts();

	ret = mountPath();

	return ret;
}
예제 #29
0
void KJavaAppletContext::received( const TQString& cmd, const TQStringList& arg )
{
    kdDebug(6100) << "KJavaAppletContext::received, cmd = >>" << cmd << "<<" << endl;
    kdDebug(6100) << "arg count = " << arg.count() << endl;

    if ( cmd == TQString::fromLatin1("showstatus")
	 && !arg.empty() )
    {
        TQString tmp = arg.first();
        tmp.replace(TQRegExp("[\n\r]"), "");
        kdDebug(6100) << "status message = " << tmp << endl;
        emit showStatus( tmp );
    }
    else if ( cmd == TQString::fromLatin1( "showurlinframe" )
              && arg.count() > 1 )
    {
        kdDebug(6100) << "url = " << arg[0] << ", frame = " << arg[1] << endl;
        emit showDocument( arg[0], arg[1] );
    }
    else if ( cmd == TQString::fromLatin1( "showdocument" )
              && !arg.empty() )
    {
        kdDebug(6100) << "url = " << arg.first() << endl;
        emit showDocument( arg.first(), "_top" );
    }
    else if ( cmd == TQString::fromLatin1( "resizeapplet" )
              && arg.count() > 2 )
    {
        //arg[1] should be appletID
        //arg[2] should be new width
        //arg[3] should be new height
        bool ok;
        const int appletID = arg[0].toInt( &ok );
        const int width = arg[1].toInt( &ok );
        const int height = arg[2].toInt( &ok );

        if( !ok )
        {
            kdError(DEBUGAREA) << "could not parse out parameters for resize" << endl;
        }
        else
        {
            KJavaApplet* const tmp = d->applets[appletID];
            if (tmp)
                tmp->resizeAppletWidget( width, height );
        }
    }
    else if (cmd.startsWith(TQString::fromLatin1("audioclip_"))) {
        kdDebug(DEBUGAREA) << "process Audio command (not yet implemented): " << cmd  << " " << arg[0] << endl;
    }
    else if ( cmd == TQString::fromLatin1( "JS_Event" )
              && arg.count() > 2 )
    {
        bool ok;
        const int appletID = arg.first().toInt(&ok);
        KJavaApplet * applet;
        if (ok && (applet = d->applets[appletID]))
        {
            TQStringList js_args(arg);
            js_args.pop_front();
            applet->jsData(js_args);
        }
        else
            kdError(DEBUGAREA) << "parse JS event " << arg[0] << " " << arg[1] << endl;
    }
    else if ( cmd == TQString::fromLatin1( "AppletStateNotification" ) )
    {
        bool ok;
        const int appletID = arg.first().toInt(&ok);
        if (ok)
        {
            KJavaApplet* const applet = d->applets[appletID];
            if ( applet )
            {
                const int newState   = arg[1].toInt(&ok);
                if (ok)
                {
                    applet->stateChange(newState);
                    if (newState == KJavaApplet::INITIALIZED) {
                        kdDebug(DEBUGAREA) << "emit appletLoaded" << endl;
                        emit appletLoaded();
                    }
                } else
                    kdError(DEBUGAREA) << "AppletStateNotification: status is not numerical" << endl;
            } else
                kdWarning(DEBUGAREA) << "AppletStateNotification:  No such Applet with ID=" << arg[0] << endl;
        } else
            kdError(DEBUGAREA) << "AppletStateNotification: Applet ID is not numerical" << endl;
    }
    else if ( cmd == TQString::fromLatin1( "AppletFailed" ) ) {
        bool ok;
        const int appletID = arg.first().toInt(&ok);
        if (ok)
        {
            KJavaApplet* const applet = d->applets[appletID];
            /*
            TQString errorDetail(arg[1]);
            errorDetail.replace(TQRegExp(":\\s*"), ":\n");
            KMessageBox::detailedError(0L, i18n("Java error while loading applet."), errorDetail);
            */
            if (applet)
                applet->setFailed();
            emit appletLoaded();
        }
    }
}
예제 #30
0
bool TDEStorageDevice::unmountDevice(TQString* errRet, int* retcode) {
	int internal_retcode;
	if (!retcode) {
		retcode = &internal_retcode;
	}

	TQString mountpoint = mountPath();
	TQString devNode = deviceNode();

	if (mountpoint.isNull()) {
		return true;
	}

	mountpoint.replace("'", "'\\''");

	TQString command;

#ifdef WITH_UDISKS2
	if(command.isEmpty()) {
		// Try to use UDISKS v2 via DBUS, if available
		TQString errorString;
		int unMountUDisks2Ret = unMountDriveUDisks2(devNode, TQString::null, &errorString);
		if (unMountUDisks2Ret == 0) {
			// Update internal mount data
			TDEGlobal::hardwareDevices()->processModifiedMounts();

			return true;
		}
		else if (unMountUDisks2Ret == -1) {
			if (errRet) {
				*errRet = errorString;
			}

			// Update internal mount data
			TDEGlobal::hardwareDevices()->processModifiedMounts();

			return false;
		}
		else {
			// The UDISKS v2 DBUS service was either not available or was unusable; try another method...
			command = TQString::null;
		}
	}
#endif // WITH_UDISKS2
#ifdef WITH_UDISKS
	if(command.isEmpty()) {
		// Try to use UDISKS v1 via DBUS, if available
		TQString errorString;
		int unMountUDisksRet = unMountDriveUDisks(devNode, TQStringList(), &errorString);
		if (unMountUDisksRet == 0) {
			// Update internal mount data
			TDEGlobal::hardwareDevices()->processModifiedMounts();

			return true;
		}
		else if (unMountUDisksRet == -1) {
			if (errRet) {
				*errRet = errorString;
			}

			// Update internal mount data
			TDEGlobal::hardwareDevices()->processModifiedMounts();

			return false;
		}
		else {
			// The UDISKS v1 DBUS service was either not available or was unusable; try another method...
			command = TQString::null;
		}
	}
#endif // WITH_UDISKS
	if(command.isEmpty() &&
	   !(TDEGlobal::dirs()->findExe("pumount").isEmpty())) {
		command = TQString("pumount '%1' 2>&1").arg(mountpoint);
	}

	if(command.isEmpty()) {
		if (errRet) {
			*errRet = i18n("No supported unmounting methods were detected on your system");
		}
		return true;
	}

	FILE *exepipe = popen(command.local8Bit(), "r");
	if (exepipe) {
		TQString umount_output;
		TQTextStream ts(exepipe, IO_ReadOnly);
		umount_output = ts.read();
		*retcode = pclose(exepipe);
		if (*retcode == 0) {
			// Update internal mount data
			TDEGlobal::hardwareDevices()->processModifiedMounts();

			return true;
		}
		else {
			if (errRet) {
				*errRet = umount_output;
			}
		}
	}

	// Update internal mount data
	TDEGlobal::hardwareDevices()->processModifiedMounts();

	return false;
}