• Skip to content
  • Skip to link menu
Trinity API Reference
  • Trinity API Reference
  • tdeio/tdeio
 

tdeio/tdeio

  • tdeio
  • tdeio
krun.cpp
1 /* This file is part of the KDE libraries
2  Copyright (C) 2000 Torben Weis <weis@kde.org>
3  Copyright (C) 2006 David Faure <faure@kde.org>
4 
5  This library is free software; you can redistribute it and/or
6  modify it under the terms of the GNU Library General Public
7  License as published by the Free Software Foundation; either
8  version 2 of the License, or (at your option) any later version.
9 
10  This library is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13  Library General Public License for more details.
14 
15  You should have received a copy of the GNU Library General Public License
16  along with this library; see the file COPYING.LIB. If not, write to
17  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18  Boston, MA 02110-1301, USA.
19 */
20 
21 #include "krun.h"
22 
23 #include <assert.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <typeinfo>
28 
29 #include <tqwidget.h>
30 #include <tqguardedptr.h>
31 
32 #include "kuserprofile.h"
33 #include "kmimetype.h"
34 #include "kmimemagic.h"
35 #include "tdeio/job.h"
36 #include "tdeio/global.h"
37 #include "tdeio/scheduler.h"
38 #include "tdeio/netaccess.h"
39 #include "tdefile/kopenwith.h"
40 #include "tdefile/tderecentdocument.h"
41 
42 #include <kdatastream.h>
43 #include <kmessageboxwrapper.h>
44 #include <kurl.h>
45 #include <tdeapplication.h>
46 #include <kdebug.h>
47 #include <tdelocale.h>
48 #include <kprotocolinfo.h>
49 #include <kstandarddirs.h>
50 #include <kprocess.h>
51 #include <dcopclient.h>
52 #include <tqfile.h>
53 #include <tqfileinfo.h>
54 #include <tqtextstream.h>
55 #include <tqdatetime.h>
56 #include <tqregexp.h>
57 #include <kdesktopfile.h>
58 #include <tdestartupinfo.h>
59 #include <kmacroexpander.h>
60 #include <kshell.h>
61 #include <kde_file.h>
62 #include <kstringhandler.h>
63 
64 #ifdef Q_WS_X11
65 #include <twin.h>
66 #endif
67 
68 class KRun::KRunPrivate
69 {
70 public:
71  KRunPrivate() { m_showingError = false; }
72 
73  bool m_showingError;
74  bool m_runExecutables;
75 
76  TQString m_preferredService;
77  TQString m_externalBrowser;
78  TQString m_localPath;
79  TQString m_suggestedFileName;
80  TQGuardedPtr <TQWidget> m_window;
81  TQCString m_asn;
82 };
83 
84 pid_t KRun::runURL( const KURL& u, const TQString& _mimetype )
85 {
86  return runURL( u, _mimetype, false, true, TQString::null );
87 }
88 
89 pid_t KRun::runURL( const KURL& u, const TQString& _mimetype, bool tempFile )
90 {
91  return runURL( u, _mimetype, tempFile, true, TQString::null );
92 }
93 
94 pid_t KRun::runURL( const KURL& u, const TQString& _mimetype, bool tempFile, bool runExecutables )
95 {
96  return runURL( u, _mimetype, tempFile, runExecutables, TQString::null );
97 }
98 
99 bool KRun::isExecutableFile( const KURL& url, const TQString &mimetype )
100 {
101  if ( !url.isLocalFile() )
102  return false;
103  TQFileInfo file( url.path() );
104  if ( file.isExecutable() ) // Got a prospective file to run
105  {
106  KMimeType::Ptr mimeType = KMimeType::mimeType( mimetype );
107 
108  if ( mimeType->is("application/x-executable") || mimeType->is("application/x-executable-script") )
109  return true;
110  }
111  return false;
112 }
113 
114 pid_t KRun::runURL( const KURL& u, const TQString& _mimetype, bool tempFile, bool runExecutables, const TQString& suggestedFileName )
115 {
116  return runURL( u, _mimetype, NULL, "", tempFile, runExecutables, suggestedFileName );
117 }
118 
119 // This is called by foundMimeType, since it knows the mimetype of the URL
120 pid_t KRun::runURL( const KURL& u, const TQString& _mimetype, TQWidget* window, const TQCString& asn,
121  bool tempFile, bool runExecutables, const TQString& suggestedFileName )
122 {
123  bool noRun = false;
124  bool noAuth = false;
125  if ( _mimetype == "inode/directory-locked" )
126  {
127  KMessageBoxWrapper::error( window,
128  i18n("<qt>Unable to enter <b>%1</b>.\nYou do not have access rights to this location.</qt>").arg(u.htmlURL()) );
129  return 0;
130  }
131  else if ( (_mimetype == "application/x-desktop") ||
132  (_mimetype == "media/builtin-mydocuments") ||
133  (_mimetype == "media/builtin-mycomputer") ||
134  (_mimetype == "media/builtin-mynetworkplaces") ||
135  (_mimetype == "media/builtin-printers") ||
136  (_mimetype == "media/builtin-trash") ||
137  (_mimetype == "media/builtin-webbrowser") )
138  {
139  if ( u.isLocalFile() && runExecutables )
140  return KDEDesktopMimeType::run( u, true );
141  }
142  else if ( isExecutableFile(u, _mimetype) )
143  {
144  if ( u.isLocalFile() && runExecutables)
145  {
146  if (kapp->authorize("shell_access"))
147  {
148  TQString path = u.path();
149  shellQuote( path );
150  return (KRun::runCommand(path, TQString::null, TQString::null, window, asn)); // just execute the url as a command
151  // ## TODO implement deleting the file if tempFile==true
152  }
153  else
154  {
155  noAuth = true;
156  }
157  }
158  else if (_mimetype == "application/x-executable" || _mimetype == "application/x-pie-executable")
159  {
160  noRun = true;
161  }
162  }
163  else if ( isExecutable(_mimetype) )
164  {
165  if (!runExecutables)
166  noRun = true;
167 
168  if (!kapp->authorize("shell_access"))
169  noAuth = true;
170  }
171 
172  if ( noRun )
173  {
174  KMessageBox::sorry( window,
175  i18n("<qt>The file <b>%1</b> is an executable program. "
176  "For safety it will not be started.</qt>").arg(u.htmlURL()));
177  return 0;
178  }
179  if ( noAuth )
180  {
181  KMessageBoxWrapper::error( window,
182  i18n("<qt>You do not have permission to run <b>%1</b>.</qt>").arg(u.htmlURL()) );
183  return 0;
184  }
185 
186  KURL::List lst;
187  lst.append( u );
188 
189  static const TQString& app_str = TDEGlobal::staticQString("Application");
190 
191  KService::Ptr offer = KServiceTypeProfile::preferredService( _mimetype, app_str );
192 
193  if ( !offer )
194  {
195  // Open-with dialog
196  // TODO : pass the mimetype as a parameter, to show it (comment field) in the dialog !
197  // Hmm, in fact KOpenWithDlg::setServiceType already guesses the mimetype from the first URL of the list...
198  return displayOpenWithDialog( lst, tempFile, suggestedFileName );
199  }
200 
201  return KRun::run( *offer, lst, window, asn, tempFile, suggestedFileName );
202 }
203 
204 bool KRun::displayOpenWithDialog( const KURL::List& lst )
205 {
206  return displayOpenWithDialog( lst, false, TQString::null );
207 }
208 
209 bool KRun::displayOpenWithDialog( const KURL::List& lst, bool tempFiles )
210 {
211  return displayOpenWithDialog( lst, tempFiles, TQString::null );
212 }
213 
214 bool KRun::displayOpenWithDialog( const KURL::List& lst, bool tempFiles, const TQString& suggestedFileName )
215 {
216  if (kapp && !kapp->authorizeTDEAction("openwith"))
217  {
218  // TODO: Better message, i18n freeze :-(
219  KMessageBox::sorry(0L, i18n("You are not authorized to open this file."));
220  return false;
221  }
222 
223  KOpenWithDlg l( lst, i18n("Open with:"), TQString::null, 0L );
224  if ( l.exec() )
225  {
226  KService::Ptr service = l.service();
227  if ( !!service )
228  return KRun::run( *service, lst, 0 /*window*/, tempFiles, suggestedFileName );
229 
230  kdDebug(7010) << "No service set, running " << l.text() << endl;
231  return KRun::run( l.text(), lst, suggestedFileName ); // TODO handle tempFiles
232  }
233  return false;
234 }
235 
236 void KRun::shellQuote( TQString &_str )
237 {
238  // Credits to Walter, says Bernd G. :)
239  if (_str.isEmpty()) // Don't create an explicit empty parameter
240  return;
241  TQChar q('\'');
242  _str.replace(q, "'\\''").prepend(q).append(q);
243 }
244 
245 
246 class KRunMX1 : public KMacroExpanderBase {
247 public:
248  KRunMX1( const KService &_service ) :
249  KMacroExpanderBase( '%' ), hasUrls( false ), hasSpec( false ), service( _service ) {}
250  bool hasUrls:1, hasSpec:1;
251 
252 protected:
253  virtual int expandEscapedMacro( const TQString &str, uint pos, TQStringList &ret );
254 
255 private:
256  const KService &service;
257 };
258 
259 int
260 KRunMX1::expandEscapedMacro( const TQString &str, uint pos, TQStringList &ret )
261 {
262  uint option = str[pos + 1];
263  switch( option ) {
264  case 'c':
265  ret << service.name().replace( '%', "%%" );
266  break;
267  case 'k':
268  ret << service.desktopEntryPath().replace( '%', "%%" );
269  break;
270  case 'i':
271  ret << "-icon" << service.icon().replace( '%', "%%" );
272  break;
273  case 'm':
274  ret << "-miniicon" << service.icon().replace( '%', "%%" );
275  break;
276  case 'u':
277  case 'U':
278  hasUrls = true;
279  /* fallthrough */
280  case 'f':
281  case 'F':
282  case 'n':
283  case 'N':
284  case 'd':
285  case 'D':
286  case 'v':
287  hasSpec = true;
288  /* fallthrough */
289  default:
290  return -2; // subst with same and skip
291  }
292  return 2;
293 }
294 
295 class KRunMX2 : public KMacroExpanderBase {
296 public:
297  KRunMX2( const KURL::List &_urls ) :
298  KMacroExpanderBase( '%' ), ignFile( false ), urls( _urls ) {}
299  bool ignFile:1;
300 
301 protected:
302  virtual int expandEscapedMacro( const TQString &str, uint pos, TQStringList &ret );
303 
304 private:
305  void subst( int option, const KURL &url, TQStringList &ret );
306 
307  const KURL::List &urls;
308 };
309 
310 void
311 KRunMX2::subst( int option, const KURL &url, TQStringList &ret )
312 {
313  switch( option ) {
314  case 'u':
315  ret << url.pathOrURL();
316  break;
317  case 'd':
318  ret << url.directory();
319  break;
320  case 'f':
321  ret << url.path();
322  break;
323  case 'n':
324  ret << url.fileName();
325  break;
326  case 'v':
327  if (url.isLocalFile() && TQFile::exists( url.path() ) )
328  ret << KDesktopFile( url.path(), true ).readEntry( "Dev" );
329  break;
330  }
331  return;
332 }
333 
334 int
335 KRunMX2::expandEscapedMacro( const TQString &str, uint pos, TQStringList &ret )
336 {
337  uint option = str[pos + 1];
338  switch( option ) {
339  case 'f':
340  case 'u':
341  case 'n':
342  case 'd':
343  case 'v':
344  if( urls.isEmpty() ) {
345  if (!ignFile)
346  kdDebug() << "KRun::processDesktopExec: No URLs supplied to single-URL service " << str << endl;
347  } else if( urls.count() > 1 )
348  kdWarning() << "KRun::processDesktopExec: " << urls.count() << " URLs supplied to single-URL service " << str << endl;
349  else
350  subst( option, urls.first(), ret );
351  break;
352  case 'F':
353  case 'U':
354  case 'N':
355  case 'D':
356  option += 'a' - 'A';
357  for( KURL::List::ConstIterator it = urls.begin(); it != urls.end(); ++it )
358  subst( option, *it, ret );
359  break;
360  case '%':
361  ret = "%";
362  break;
363  default:
364  return -2; // subst with same and skip
365  }
366  return 2;
367 }
368 
369 // BIC: merge methods below
370 TQStringList KRun::processDesktopExec(const KService &_service, const KURL::List& _urls, bool has_shell) {
371  return processDesktopExec( _service, _urls, has_shell, false, TQString::null );
372 }
373 
374 TQStringList KRun::processDesktopExec(const KService &_service, const KURL::List& _urls, bool has_shell /* KDE4: remove */, bool tempFiles)
375 {
376  return processDesktopExec( _service, _urls, has_shell, tempFiles, TQString::null );
377 }
378 
379 TQStringList KRun::processDesktopExec(const KService &_service, const KURL::List& _urls, bool has_shell /* KDE4: remove */, bool tempFiles, const TQString& suggestedFileName)
380 {
381  TQString exec = _service.exec();
382  TQStringList result;
383  bool appHasTempFileOption;
384 
385  KRunMX1 mx1( _service );
386  KRunMX2 mx2( _urls );
387 
389  TQRegExp re("^\\s*(?:/bin/)?sh\\s+-c\\s+(.*)$");
390  if (!re.search( exec )) {
391  exec = TQString(re.cap( 1 )).stripWhiteSpace();
392  for (uint pos = 0; pos < exec.length(); ) {
393  TQChar c = exec.unicode()[pos];
394  if (c != '\'' && c != '"')
395  goto synerr; // what else can we do? after normal parsing the substs would be insecure
396  int pos2 = exec.find( c, pos + 1 ) - 1;
397  if (pos2 < 0)
398  goto synerr; // quoting error
399  memcpy( (void *)(exec.unicode() + pos), exec.unicode() + pos + 1, (pos2 - pos) * sizeof(TQChar));
400  pos = pos2;
401  exec.remove( pos, 2 );
402  }
403  }
404 
405  if( !mx1.expandMacrosShellQuote( exec ) )
406  goto synerr; // error in shell syntax
407 
408  // FIXME: the current way of invoking tdeioexec disables term and su use
409 
410  // Check if we need "tempexec" (tdeioexec in fact)
411  appHasTempFileOption = tempFiles && _service.property("X-TDE-HasTempFileOption").toBool();
412  if( tempFiles && !appHasTempFileOption && _urls.size() ) {
413  result << "tdeioexec" << "--tempfiles" << exec;
414  result += _urls.toStringList();
415  if (has_shell)
416  result = KShell::joinArgs( result );
417  return result;
418  }
419 
420  // Check if we need tdeioexec
421  if( !mx1.hasUrls ) {
422  for( KURL::List::ConstIterator it = _urls.begin(); it != _urls.end(); ++it )
423  if ( !(*it).isLocalFile() && !KProtocolInfo::isHelperProtocol(*it) ) {
424  // We need to run the app through tdeioexec
425  result << "tdeioexec";
426  if ( tempFiles )
427  result << "--tempfiles";
428  if ( !suggestedFileName.isEmpty() ) {
429  result << "--suggestedfilename";
430  result << suggestedFileName;
431  }
432  result << exec;
433  result += _urls.toStringList();
434  if (has_shell)
435  result = KShell::joinArgs( result );
436  return result;
437  }
438  }
439 
440  if ( appHasTempFileOption )
441  exec += " --tempfile";
442 
443  // Did the user forget to append something like '%f'?
444  // If so, then assume that '%f' is the right choice => the application
445  // accepts only local files.
446  if( !mx1.hasSpec ) {
447  exec += " %f";
448  mx2.ignFile = true;
449  }
450 
451  mx2.expandMacrosShellQuote( exec ); // syntax was already checked, so don't check return value
452 
453 /*
454  1 = need_shell, 2 = terminal, 4 = su, 8 = has_shell
455 
456  0 << split(cmd)
457  1 << "sh" << "-c" << cmd
458  2 << split(term) << "-e" << split(cmd)
459  3 << split(term) << "-e" << "sh" << "-c" << cmd
460 
461  4 << "tdesu" << "-u" << user << "-c" << cmd
462  5 << "tdesu" << "-u" << user << "-c" << ("sh -c " + quote(cmd))
463  6 << split(term) << "-e" << "su" << user << "-c" << cmd
464  7 << split(term) << "-e" << "su" << user << "-c" << ("sh -c " + quote(cmd))
465 
466  8 << cmd
467  9 << cmd
468  a << term << "-e" << cmd
469  b << term << "-e" << ("sh -c " + quote(cmd))
470 
471  c << "tdesu" << "-u" << user << "-c" << quote(cmd)
472  d << "tdesu" << "-u" << user << "-c" << quote("sh -c " + quote(cmd))
473  e << term << "-e" << "su" << user << "-c" << quote(cmd)
474  f << term << "-e" << "su" << user << "-c" << quote("sh -c " + quote(cmd))
475 
476  "sh -c" is needed in the "su" case, too, as su uses the user's login shell, not sh.
477  this could be optimized with the -s switch of some su versions (e.g., debian linux).
478 */
479 
480  if (_service.terminal()) {
481  TDEConfigGroupSaver gs(TDEGlobal::config(), "General");
482  TQString terminal = TDEGlobal::config()->readPathEntry("TerminalApplication", "konsole");
483  if (terminal == "konsole")
484  terminal += " -caption=%c %i %m";
485  terminal += " ";
486  terminal += _service.terminalOptions();
487  if( !mx1.expandMacrosShellQuote( terminal ) ) {
488  kdWarning() << "KRun: syntax error in command `" << terminal << "', service `" << _service.name() << "'" << endl;
489  return TQStringList();
490  }
491  mx2.expandMacrosShellQuote( terminal );
492  if (has_shell)
493  result << terminal;
494  else
495  result = KShell::splitArgs( terminal ); // assuming that the term spec never needs a shell!
496  result << "-e";
497  }
498 
499  int err;
500  if (_service.substituteUid()) {
501  if (_service.terminal())
502  result << "su";
503  else
504  result << "tdesu" << "-u";
505  result << _service.username() << "-c";
506  KShell::splitArgs(exec, KShell::AbortOnMeta | KShell::TildeExpand, &err);
507  if (err == KShell::FoundMeta) {
508  shellQuote( exec );
509  exec.prepend( "/bin/sh -c " );
510  } else if (err != KShell::NoError)
511  goto synerr;
512  if (has_shell)
513  shellQuote( exec );
514  result << exec;
515  } else {
516  if (has_shell) {
517  if (_service.terminal()) {
518  KShell::splitArgs(exec, KShell::AbortOnMeta | KShell::TildeExpand, &err);
519  if (err == KShell::FoundMeta) {
520  shellQuote( exec );
521  exec.prepend( "/bin/sh -c " );
522  } else if (err != KShell::NoError)
523  goto synerr;
524  }
525  result << exec;
526  } else {
527  result += KShell::splitArgs(exec, KShell::AbortOnMeta | KShell::TildeExpand, &err);
528  if (err == KShell::FoundMeta)
529  result << "/bin/sh" << "-c" << exec;
530  else if (err != KShell::NoError)
531  goto synerr;
532  }
533  }
534 
535  return result;
536 
537  synerr:
538  kdWarning() << "KRun: syntax error in command `" << _service.exec() << "', service `" << _service.name() << "'" << endl;
539  return TQStringList();
540 }
541 
542 //static
543 TQString KRun::binaryName( const TQString & execLine, bool removePath )
544 {
545  // Remove parameters and/or trailing spaces.
546  TQStringList args = KShell::splitArgs( execLine );
547  for (TQStringList::ConstIterator it = args.begin(); it != args.end(); ++it)
548  if (!(*it).contains('='))
549  // Remove path if wanted
550  return removePath ? (*it).mid(TQString(*it).findRev('/') + 1) : *it;
551  return TQString();
552 }
553 
554 static pid_t runCommandInternal( TDEProcess* proc, const KService* service, const TQString& binName,
555  const TQString &execName, const TQString & iconName, TQWidget* window, TQCString asn )
556 {
557  if (service && !service->desktopEntryPath().isEmpty()
558  && !KDesktopFile::isAuthorizedDesktopFile( service->desktopEntryPath() ))
559  {
560  kdWarning() << "No authorization to execute " << service->desktopEntryPath() << endl;
561  KMessageBox::sorry(window, i18n("You are not authorized to execute this file."));
562  return 0;
563  }
564  TQString bin = KRun::binaryName( binName, true );
565 #ifdef Q_WS_X11 // Startup notification doesn't work with QT/E, service isn't needed without Startup notification
566  bool silent;
567  TQCString wmclass;
568  TDEStartupInfoId id;
569  bool startup_notify = ( asn != "0" && KRun::checkStartupNotify( binName, service, &silent, &wmclass ));
570  if( startup_notify )
571  {
572  id.initId( asn );
573  id.setupStartupEnv();
574  TDEStartupInfoData data;
575  data.setHostname();
576  data.setBin( bin );
577  if( !execName.isEmpty())
578  data.setName( execName );
579  else if( service && !service->name().isEmpty())
580  data.setName( service->name());
581  data.setDescription( i18n( "Launching %1" ).arg( data.name()));
582  if( !iconName.isEmpty())
583  data.setIcon( iconName );
584  else if( service && !service->icon().isEmpty())
585  data.setIcon( service->icon());
586  if( !wmclass.isEmpty())
587  data.setWMClass( wmclass );
588  if( silent )
589  data.setSilent( TDEStartupInfoData::Yes );
590  data.setDesktop( KWin::currentDesktop());
591  if( window )
592  data.setLaunchedBy( window->winId());
593  TDEStartupInfo::sendStartup( id, data );
594  }
595  pid_t pid = TDEProcessRunner::run( proc, binName, id );
596  if( startup_notify && pid )
597  {
598  TDEStartupInfoData data;
599  data.addPid( pid );
600  TDEStartupInfo::sendChange( id, data );
601  TDEStartupInfo::resetStartupEnv();
602  }
603  return pid;
604 #else
605  Q_UNUSED( execName );
606  Q_UNUSED( iconName );
607  return TDEProcessRunner::run( proc, bin );
608 #endif
609 }
610 
611 // This code is also used in tdelauncher.
612 bool KRun::checkStartupNotify( const TQString& /*binName*/, const KService* service, bool* silent_arg, TQCString* wmclass_arg )
613 {
614  bool silent = false;
615  TQCString wmclass;
616  if( service && service->property( "StartupNotify" ).isValid())
617  {
618  silent = !service->property( "StartupNotify" ).toBool();
619  wmclass = service->property( "StartupWMClass" ).toString().latin1();
620  }
621  else if( service && service->property( "X-TDE-StartupNotify" ).isValid())
622  {
623  silent = !service->property( "X-TDE-StartupNotify" ).toBool();
624  wmclass = service->property( "X-TDE-WMClass" ).toString().latin1();
625  }
626  else // non-compliant app
627  {
628  if( service )
629  {
630  if( service->type() == "Application" )
631  wmclass = "0"; // doesn't have .desktop entries needed, start as non-compliant
632  else
633  return false; // no startup notification at all
634  }
635  else
636  {
637 #if 0
638  // Create startup notification even for apps for which there shouldn't be any,
639  // just without any visual feedback. This will ensure they'll be positioned on the proper
640  // virtual desktop, and will get user timestamp from the ASN ID.
641  wmclass = "0";
642  silent = true;
643 #else // That unfortunately doesn't work, when the launched non-compliant application
644  // launches another one that is compliant and there is any delay inbetween (bnc:#343359)
645  return false;
646 #endif
647  }
648  }
649  if( silent_arg != NULL )
650  *silent_arg = silent;
651  if( wmclass_arg != NULL )
652  *wmclass_arg = wmclass;
653  return true;
654 }
655 
656 static pid_t runTempService( const KService& _service, const KURL::List& _urls, TQWidget* window,
657  const TQCString& asn, bool tempFiles, const TQString& suggestedFileName )
658 {
659  if (!_urls.isEmpty()) {
660  kdDebug(7010) << "runTempService: first url " << _urls.first().url() << endl;
661  }
662 
663  TQStringList args;
664  if ((_urls.count() > 1) && !_service.allowMultipleFiles())
665  {
666  // We need to launch the application N times. That sucks.
667  // We ignore the result for application 2 to N.
668  // For the first file we launch the application in the
669  // usual way. The reported result is based on this
670  // application.
671  KURL::List::ConstIterator it = _urls.begin();
672  while(++it != _urls.end())
673  {
674  KURL::List singleUrl;
675  singleUrl.append(*it);
676  runTempService( _service, singleUrl, window, "", tempFiles, suggestedFileName );
677  }
678  KURL::List singleUrl;
679  singleUrl.append(_urls.first());
680  args = KRun::processDesktopExec(_service, singleUrl, false, tempFiles, suggestedFileName);
681  }
682  else
683  {
684  args = KRun::processDesktopExec(_service, _urls, false, tempFiles, suggestedFileName);
685  }
686  kdDebug(7010) << "runTempService: TDEProcess args=" << args << endl;
687 
688  TDEProcess * proc = new TDEProcess;
689  *proc << args;
690 
691  if (!_service.path().isEmpty())
692  proc->setWorkingDirectory(_service.path());
693 
694  return runCommandInternal( proc, &_service, KRun::binaryName( _service.exec(), false ),
695  _service.name(), _service.icon(), window, asn );
696 }
697 
698 // WARNING: don't call this from processDesktopExec, since tdelauncher uses that too...
699 static KURL::List resolveURLs( const KURL::List& _urls, const KService& _service )
700 {
701  // Check which protocols the application supports.
702  // This can be a list of actual protocol names, or just TDEIO for KDE apps.
703  TQStringList supportedProtocols = _service.property("X-TDE-Protocols").toStringList();
704  KRunMX1 mx1( _service );
705  TQString exec = _service.exec();
706  if ( mx1.expandMacrosShellQuote( exec ) && !mx1.hasUrls ) {
707  Q_ASSERT( supportedProtocols.isEmpty() ); // huh? If you support protocols you need %u or %U...
708  } else {
709  if ( supportedProtocols.isEmpty() )
710  {
711  // compat mode: assume TDEIO if not set and it's a KDE app
712  TQStringList categories = _service.property("Categories").toStringList();
713  if (( categories.find("TDE") != categories.end() ) && ( categories.find("KDE") != categories.end() ))
714  supportedProtocols.append( "TDEIO" );
715  else { // if no KDE app, be a bit over-generic
716  supportedProtocols.append( "http");
717  supportedProtocols.append( "ftp");
718  }
719  }
720  }
721  kdDebug(7010) << "supportedProtocols:" << supportedProtocols << endl;
722 
723  KURL::List urls( _urls );
724  if ( supportedProtocols.find( "TDEIO" ) == supportedProtocols.end() ) {
725  for( KURL::List::Iterator it = urls.begin(); it != urls.end(); ++it ) {
726  const KURL url = *it;
727  bool supported = url.isLocalFile() || supportedProtocols.find( url.protocol().lower() ) != supportedProtocols.end();
728  kdDebug(7010) << "Looking at url=" << url << " supported=" << supported << endl;
729  if ( !supported && KProtocolInfo::protocolClass(url.protocol()) == ":local" &&
730  !url.url().startsWith("media:/") && !url.url().startsWith("system:/media"))
731  {
732  // Maybe we can resolve to a local URL?
733  KURL localURL = TDEIO::NetAccess::mostLocalURL( url, 0 );
734  if ( localURL != url ) {
735  *it = localURL;
736  kdDebug(7010) << "Changed to " << localURL << endl;
737  }
738  }
739  }
740  }
741  return urls;
742 }
743 
744 // BIC merge methods below
745 pid_t KRun::run( const KService& _service, const KURL::List& _urls )
746 {
747  return run( _service, _urls, 0, false, TQString::null );
748 }
749 
750 pid_t KRun::run( const KService& _service, const KURL::List& _urls, bool tempFiles )
751 {
752  return run( _service, _urls, 0, tempFiles, TQString::null );
753 }
754 
755 pid_t KRun::run( const KService& _service, const KURL::List& _urls, TQWidget* window, bool tempFiles )
756 {
757  return run( _service, _urls, window, "", tempFiles, TQString::null );
758 }
759 
760 pid_t KRun::run( const KService& _service, const KURL::List& _urls, TQWidget* window, const TQCString& asn, bool tempFiles )
761 {
762  return run( _service, _urls, window, asn, tempFiles, TQString::null );
763 }
764 
765 pid_t KRun::run( const KService& _service, const KURL::List& _urls, TQWidget* window, bool tempFiles, const TQString& suggestedFileName )
766 {
767  return run( _service, _urls, window, "", tempFiles, suggestedFileName );
768 }
769 
770 pid_t KRun::run( const KService& _service, const KURL::List& _urls, TQWidget* window, const TQCString& asn,
771  bool tempFiles, const TQString& suggestedFileName )
772 {
773  if (!_service.desktopEntryPath().isEmpty() &&
774  !KDesktopFile::isAuthorizedDesktopFile( _service.desktopEntryPath()))
775  {
776  kdWarning() << "No authorization to execute " << _service.desktopEntryPath() << endl;
777  KMessageBox::sorry(window, i18n("You are not authorized to execute this service."));
778  return 0;
779  }
780 
781  if ( !tempFiles )
782  {
783  // Remember we opened those urls, for the "recent documents" menu in kicker
784  KURL::List::ConstIterator it = _urls.begin();
785  for(; it != _urls.end(); ++it) {
786  //kdDebug(7010) << "TDERecentDocument::adding " << (*it).url() << endl;
787  TDERecentDocument::add( *it, _service.desktopEntryName() );
788  }
789  }
790 
791  if ( tempFiles || _service.desktopEntryPath().isEmpty() || !suggestedFileName.isEmpty() )
792  {
793  return runTempService(_service, _urls, window, asn, tempFiles, suggestedFileName);
794  }
795 
796  kdDebug(7010) << "KRun::run " << _service.desktopEntryPath() << endl;
797 
798  if (!_urls.isEmpty()) {
799  kdDebug(7010) << "First url " << _urls.first().url() << endl;
800  }
801 
802  // Resolve urls if needed, depending on what the app supports
803  const KURL::List urls = resolveURLs( _urls, _service );
804 
805  TQString error;
806  int pid = 0;
807 
808  TQCString myasn = asn;
809  // startServiceByDesktopPath() doesn't take TQWidget*, add it to the startup info now
810  if( window != NULL )
811  {
812  if( myasn.isEmpty())
813  myasn = TDEStartupInfo::createNewStartupId();
814  if( myasn != "0" )
815  {
816  TDEStartupInfoId id;
817  id.initId( myasn );
818  TDEStartupInfoData data;
819  data.setLaunchedBy( window->winId());
820  TDEStartupInfo::sendChange( id, data );
821  }
822  }
823 
824  int i = TDEApplication::startServiceByDesktopPath(
825  _service.desktopEntryPath(), urls.toStringList(), &error, 0L, &pid, myasn
826  );
827 
828  if (i != 0)
829  {
830  kdDebug(7010) << error << endl;
831  KMessageBox::sorry( window, error );
832  return 0;
833  }
834 
835  kdDebug(7010) << "startServiceByDesktopPath worked fine" << endl;
836  return (pid_t) pid;
837 }
838 
839 
840 pid_t KRun::run( const TQString& _exec, const KURL::List& _urls, const TQString& _name,
841  const TQString& _icon, const TQString&, const TQString&)
842 {
843  KService::Ptr service = new KService(_name, _exec, _icon);
844 
845  return run(*service, _urls);
846 }
847 
848 pid_t KRun::runCommand( TQString cmd )
849 {
850  return KRun::runCommand( cmd, TQString::null, TQString::null, NULL, "" );
851 }
852 
853 pid_t KRun::runCommand( const TQString& cmd, const TQString &execName, const TQString & iconName )
854 {
855  return KRun::runCommand( cmd, execName, iconName, NULL, "" );
856 }
857 
858 pid_t KRun::runCommand( const TQString& cmd, const TQString &execName, const TQString & iconName,
859  TQWidget* window, const TQCString& asn )
860 {
861  kdDebug(7010) << "runCommand " << cmd << "," << execName << endl;
862  TDEProcess * proc = new TDEProcess;
863  proc->setUseShell(true);
864  *proc << cmd;
865  KService::Ptr service = KService::serviceByDesktopName( binaryName( execName, true ) );
866  TQString bin = binaryName( cmd, false );
867  int pos = bin.findRev( '/' );
868  if (pos != -1) {
869  proc->setWorkingDirectory( bin.mid(0, pos) );
870  }
871  return runCommandInternal( proc, service.data(), binaryName( execName, false ), execName, iconName, window, asn );
872 }
873 
874 KRun::KRun( const KURL& url, mode_t mode, bool isLocalFile, bool showProgressInfo )
875  :m_timer(0,"KRun::timer")
876 {
877  init (url, 0, "", mode, isLocalFile, showProgressInfo);
878 }
879 
880 KRun::KRun( const KURL& url, TQWidget* window, mode_t mode, bool isLocalFile,
881  bool showProgressInfo )
882  :m_timer(0,"KRun::timer")
883 {
884  init (url, window, "", mode, isLocalFile, showProgressInfo);
885 }
886 
887 KRun::KRun( const KURL& url, TQWidget* window, const TQCString& asn, mode_t mode, bool isLocalFile,
888  bool showProgressInfo )
889  :m_timer(0,"KRun::timer")
890 {
891  init (url, window, asn, mode, isLocalFile, showProgressInfo);
892 }
893 
894 void KRun::init ( const KURL& url, TQWidget* window, const TQCString& asn, mode_t mode, bool isLocalFile,
895  bool showProgressInfo )
896 {
897  m_bFault = false;
898  m_bAutoDelete = true;
899  m_bProgressInfo = showProgressInfo;
900  m_bFinished = false;
901  m_job = 0L;
902  m_strURL = url;
903  m_bScanFile = false;
904  m_bIsDirectory = false;
905  m_bIsLocalFile = isLocalFile;
906  m_mode = mode;
907  d = new KRunPrivate;
908  d->m_runExecutables = true;
909  d->m_window = window;
910  d->m_asn = asn;
911  setEnableExternalBrowser(true);
912 
913  // Start the timer. This means we will return to the event
914  // loop and do initialization afterwards.
915  // Reason: We must complete the constructor before we do anything else.
916  m_bInit = true;
917  connect( &m_timer, TQT_SIGNAL( timeout() ), this, TQT_SLOT( slotTimeout() ) );
918  m_timer.start( 0, true );
919  kdDebug(7010) << " new KRun " << this << " " << url.prettyURL() << " timer=" << &m_timer << endl;
920 
921  kapp->ref();
922 }
923 
924 void KRun::init()
925 {
926  kdDebug(7010) << "INIT called" << endl;
927 
928  bool bypassErrorMessage = false;
929 
930  if (m_strURL.url().startsWith("$(")) {
931  // check for environment variables and make necessary translations
932  TQString aValue = m_strURL.url();
933  int nDollarPos = aValue.find( '$' );
934 
935  while( nDollarPos != -1 && nDollarPos+1 < static_cast<int>(aValue.length())) {
936  // there is at least one $
937  if( (aValue)[nDollarPos+1] != '$' ) {
938  uint nEndPos = nDollarPos+1;
939  // the next character is no $
940  TQString aVarName;
941  if (aValue[nEndPos]=='{')
942  {
943  while ( (nEndPos <= aValue.length()) && (aValue[nEndPos]!='}') )
944  nEndPos++;
945  nEndPos++;
946  aVarName = aValue.mid( nDollarPos+2, nEndPos-nDollarPos-3 );
947  }
948  else
949  {
950  while ( nEndPos <= aValue.length() && (aValue[nEndPos].isNumber()
951  || aValue[nEndPos].isLetter() || aValue[nEndPos]=='_' ) )
952  nEndPos++;
953  aVarName = aValue.mid( nDollarPos+1, nEndPos-nDollarPos-1 );
954  }
955  const char* pEnv = 0;
956  if (!aVarName.isEmpty())
957  pEnv = getenv( aVarName.ascii() );
958  if( pEnv ) {
959  // !!! Sergey A. Sukiyazov <corwin@micom.don.ru> !!!
960  // A environment variables may contain values in 8bit
961  // locale cpecified encoding or in UTF8 encoding.
962  aValue.replace( nDollarPos, nEndPos-nDollarPos, KStringHandler::from8Bit( pEnv ) );
963  } else
964  aValue.remove( nDollarPos, nEndPos-nDollarPos );
965  } else {
966  // remove one of the dollar signs
967  aValue.remove( nDollarPos, 1 );
968  nDollarPos++;
969  }
970  nDollarPos = aValue.find( '$', nDollarPos );
971  }
972  m_strURL = KURL(aValue);
973  bypassErrorMessage = true;
974  }
975 
976  if ( !m_strURL.isValid() )
977  {
978  if (bypassErrorMessage == false) {
979  d->m_showingError = true;
980  KMessageBoxWrapper::error( d->m_window, i18n( "Malformed URL\n%1" ).arg( m_strURL.url() ) );
981  d->m_showingError = false;
982  }
983  m_bFault = true;
984  m_bFinished = true;
985  m_timer.start( 0, true );
986  return;
987  }
988  if ( !kapp->authorizeURLAction( "open", KURL(), m_strURL))
989  {
990  TQString msg = TDEIO::buildErrorString(TDEIO::ERR_ACCESS_DENIED, m_strURL.prettyURL());
991  d->m_showingError = true;
992  KMessageBoxWrapper::error( d->m_window, msg );
993  d->m_showingError = false;
994  m_bFault = true;
995  m_bFinished = true;
996  m_timer.start( 0, true );
997  return;
998  }
999 
1000  if ( !m_bIsLocalFile && m_strURL.isLocalFile() )
1001  m_bIsLocalFile = true;
1002 
1003  TQString exec;
1004  if (m_strURL.protocol().startsWith("http"))
1005  {
1006  exec = d->m_externalBrowser;
1007  }
1008 
1009  if ( m_bIsLocalFile )
1010  {
1011  if ( m_mode == 0 )
1012  {
1013  KDE_struct_stat buff;
1014  if ( KDE_stat( TQFile::encodeName(m_strURL.path()), &buff ) == -1 )
1015  {
1016  d->m_showingError = true;
1017  KMessageBoxWrapper::error( d->m_window, i18n( "<qt>Unable to run the command specified. The file or folder <b>%1</b> does not exist.</qt>" ).arg( m_strURL.htmlURL() ) );
1018  d->m_showingError = false;
1019  m_bFault = true;
1020  m_bFinished = true;
1021  m_timer.start( 0, true );
1022  return;
1023  }
1024  m_mode = buff.st_mode;
1025  }
1026 
1027  KMimeType::Ptr mime = KMimeType::findByURL( m_strURL, m_mode, m_bIsLocalFile );
1028  assert( mime != 0L );
1029  kdDebug(7010) << "MIME TYPE is " << mime->name() << endl;
1030  foundMimeType( mime->name() );
1031  return;
1032  }
1033  else if ( !exec.isEmpty() || KProtocolInfo::isHelperProtocol( m_strURL ) ) {
1034  kdDebug(7010) << "Helper protocol" << endl;
1035 
1036  bool ok = false;
1037  KURL::List urls;
1038  if (!((m_strURL.protocol().startsWith("http")) && (m_strURL.url() == "http://default.browser")))
1039  urls.append( m_strURL );
1040  if (exec.isEmpty())
1041  {
1042  exec = KProtocolInfo::exec( m_strURL.protocol() );
1043  if (exec.isEmpty())
1044  {
1045  foundMimeType(KProtocolInfo::defaultMimetype(m_strURL));
1046  return;
1047  }
1048  run( exec, urls );
1049  ok = true;
1050  }
1051  else if (exec.startsWith("!"))
1052  {
1053  exec = exec.mid(1); // Literal command
1054  exec += " %u";
1055  run( exec, urls );
1056  ok = true;
1057  }
1058  else
1059  {
1060  KService::Ptr service = KService::serviceByStorageId( exec );
1061  if (service)
1062  {
1063  run( *service, urls, d->m_window, d->m_asn );
1064  ok = true;
1065  }
1066  }
1067 
1068  if (ok)
1069  {
1070  m_bFinished = true;
1071  // will emit the error and autodelete this
1072  m_timer.start( 0, true );
1073  return;
1074  }
1075  }
1076 
1077  if ((m_strURL.protocol().startsWith("http")) && (m_strURL.url() == "http://default.browser")) {
1078  KURL::List urls;
1079  run( "kfmclient openProfile webbrowsing", urls );
1080  m_bFinished = true;
1081  // will emit the error and autodelete this
1082  m_timer.start( 0, true );
1083  return;
1084  }
1085 
1086  // Did we already get the information that it is a directory ?
1087  if ( S_ISDIR( m_mode ) )
1088  {
1089  foundMimeType( "inode/directory" );
1090  return;
1091  }
1092 
1093  // Let's see whether it is a directory
1094 
1095  if ( !KProtocolInfo::supportsListing( m_strURL ) )
1096  {
1097  //kdDebug(7010) << "Protocol has no support for listing" << endl;
1098  // No support for listing => it can't be a directory (example: http)
1099  scanFile();
1100  return;
1101  }
1102 
1103  kdDebug(7010) << "Testing directory (stating)" << endl;
1104 
1105  // It may be a directory or a file, let's stat
1106  TDEIO::StatJob *job = TDEIO::stat( m_strURL, true, 0 /* no details */, m_bProgressInfo );
1107  job->setWindow (d->m_window);
1108  connect( job, TQT_SIGNAL( result( TDEIO::Job * ) ),
1109  this, TQT_SLOT( slotStatResult( TDEIO::Job * ) ) );
1110  m_job = job;
1111  kdDebug(7010) << " Job " << job << " is about stating " << m_strURL.url() << endl;
1112 }
1113 
1114 KRun::~KRun()
1115 {
1116  kdDebug(7010) << "KRun::~KRun() " << this << endl;
1117  m_timer.stop();
1118  killJob();
1119  kapp->deref();
1120  kdDebug(7010) << "KRun::~KRun() done " << this << endl;
1121  delete d;
1122 }
1123 
1124 void KRun::scanFile()
1125 {
1126  kdDebug(7010) << "###### KRun::scanFile " << m_strURL.url() << endl;
1127  // First, let's check for well-known extensions
1128  // Not when there is a query in the URL, in any case.
1129  if ( m_strURL.query().isEmpty() )
1130  {
1131  KMimeType::Ptr mime = KMimeType::findByURL( m_strURL );
1132  assert( mime != 0L );
1133  if ( mime->name() != "application/octet-stream" || m_bIsLocalFile )
1134  {
1135  kdDebug(7010) << "Scanfile: MIME TYPE is " << mime->name() << endl;
1136  foundMimeType( mime->name() );
1137  return;
1138  }
1139  }
1140 
1141  // No mimetype found, and the URL is not local (or fast mode not allowed).
1142  // We need to apply the 'TDEIO' method, i.e. either asking the server or
1143  // getting some data out of the file, to know what mimetype it is.
1144 
1145  if ( !KProtocolInfo::supportsReading( m_strURL ) )
1146  {
1147  kdError(7010) << "#### NO SUPPORT FOR READING!" << endl;
1148  m_bFault = true;
1149  m_bFinished = true;
1150  m_timer.start( 0, true );
1151  return;
1152  }
1153  kdDebug(7010) << this << " Scanning file " << m_strURL.url() << endl;
1154 
1155  TDEIO::TransferJob *job = TDEIO::get( m_strURL, false /*reload*/, m_bProgressInfo );
1156  job->setWindow (d->m_window);
1157  connect(job, TQT_SIGNAL( result(TDEIO::Job *)),
1158  this, TQT_SLOT( slotScanFinished(TDEIO::Job *)));
1159  connect(job, TQT_SIGNAL( mimetype(TDEIO::Job *, const TQString &)),
1160  this, TQT_SLOT( slotScanMimeType(TDEIO::Job *, const TQString &)));
1161  m_job = job;
1162  kdDebug(7010) << " Job " << job << " is about getting from " << m_strURL.url() << endl;
1163 }
1164 
1165 void KRun::slotTimeout()
1166 {
1167  kdDebug(7010) << this << " slotTimeout called" << endl;
1168  if ( m_bInit )
1169  {
1170  m_bInit = false;
1171  init();
1172  return;
1173  }
1174 
1175  if ( m_bFault ) {
1176  emit error();
1177  }
1178  if ( m_bFinished ) {
1179  emit finished();
1180  }
1181  else
1182  {
1183  if ( m_bScanFile )
1184  {
1185  m_bScanFile = false;
1186  scanFile();
1187  return;
1188  }
1189  else if ( m_bIsDirectory )
1190  {
1191  m_bIsDirectory = false;
1192  foundMimeType( "inode/directory" );
1193  return;
1194  }
1195  }
1196 
1197  if ( m_bAutoDelete )
1198  {
1199  delete this;
1200  return;
1201  }
1202 }
1203 
1204 void KRun::slotStatResult( TDEIO::Job * job )
1205 {
1206  m_job = 0L;
1207  if (job->error())
1208  {
1209  d->m_showingError = true;
1210  kdError(7010) << this << " ERROR " << job->error() << " " << job->errorString() << endl;
1211  job->showErrorDialog();
1212  //kdDebug(7010) << this << " KRun returning from showErrorDialog, starting timer to delete us" << endl;
1213  d->m_showingError = false;
1214 
1215  m_bFault = true;
1216  m_bFinished = true;
1217 
1218  // will emit the error and autodelete this
1219  m_timer.start( 0, true );
1220 
1221  } else {
1222 
1223  kdDebug(7010) << "Finished" << endl;
1224  if(!dynamic_cast<TDEIO::StatJob*>(job))
1225  kdFatal() << "job is a " << typeid(*job).name() << " should be a StatJob" << endl;
1226 
1227  TQString knownMimeType;
1228  TDEIO::UDSEntry entry = ((TDEIO::StatJob*)job)->statResult();
1229  TDEIO::UDSEntry::ConstIterator it = entry.begin();
1230  for( ; it != entry.end(); it++ ) {
1231  switch( (*it).m_uds ) {
1232  case TDEIO::UDS_FILE_TYPE:
1233  if ( S_ISDIR( (mode_t)((*it).m_long) ) )
1234  m_bIsDirectory = true; // it's a dir
1235  else
1236  m_bScanFile = true; // it's a file
1237  break;
1238  case TDEIO::UDS_MIME_TYPE: // mimetype already known? (e.g. print:/manager)
1239  knownMimeType = (*it).m_str;
1240  break;
1241  case TDEIO::UDS_LOCAL_PATH:
1242  d->m_localPath = (*it).m_str;
1243  break;
1244  default:
1245  break;
1246  }
1247  }
1248  if ( !knownMimeType.isEmpty() )
1249  {
1250  foundMimeType( knownMimeType );
1251  m_bFinished = true;
1252  }
1253 
1254  // We should have found something
1255  assert ( m_bScanFile || m_bIsDirectory );
1256 
1257  // Start the timer. Once we get the timer event this
1258  // protocol server is back in the pool and we can reuse it.
1259  // This gives better performance than starting a new slave
1260  m_timer.start( 0, true );
1261  }
1262 }
1263 
1264 void KRun::slotScanMimeType( TDEIO::Job *, const TQString &mimetype )
1265 {
1266  if ( mimetype.isEmpty() )
1267  kdWarning(7010) << "KRun::slotScanFinished : MimetypeJob didn't find a mimetype! Probably a tdeioslave bug." << endl;
1268  foundMimeType( mimetype );
1269  m_job = 0;
1270 }
1271 
1272 void KRun::slotScanFinished( TDEIO::Job *job )
1273 {
1274  m_job = 0;
1275  if (job->error())
1276  {
1277  d->m_showingError = true;
1278  kdError(7010) << this << " ERROR (stat) : " << job->error() << " " << job->errorString() << endl;
1279  job->showErrorDialog();
1280  //kdDebug(7010) << this << " KRun returning from showErrorDialog, starting timer to delete us" << endl;
1281  d->m_showingError = false;
1282 
1283  m_bFault = true;
1284  m_bFinished = true;
1285 
1286  // will emit the error and autodelete this
1287  m_timer.start( 0, true );
1288  }
1289 }
1290 
1291 void KRun::foundMimeType( const TQString& type )
1292 {
1293  kdDebug(7010) << "Resulting mime type is " << type << endl;
1294 
1295 /*
1296  // Automatically unzip stuff
1297 
1298  // Disabled since the new TDEIO doesn't have filters yet.
1299 
1300  if ( type == "application/x-gzip" ||
1301  type == "application/x-bzip" ||
1302  type == "application/x-bzip2" )
1303  {
1304  KURL::List lst = KURL::split( m_strURL );
1305  if ( lst.isEmpty() )
1306  {
1307  TQString tmp = i18n( "Malformed URL" );
1308  tmp += "\n";
1309  tmp += m_strURL.url();
1310  KMessageBoxWrapper::error( 0L, tmp );
1311  return;
1312  }
1313 
1314  if ( type == "application/x-gzip" )
1315  lst.prepend( KURL( "gzip:/decompress" ) );
1316  else if ( type == "application/x-bzip" )
1317  lst.prepend( KURL( "bzip:/decompress" ) );
1318  else if ( type == "application/x-bzip2" )
1319  lst.prepend( KURL( "bzip2:/decompress" ) );
1320  else if ( type == "application/x-tar" )
1321  lst.prepend( KURL( "tar:/" ) );
1322 
1323  // Move the HTML style reference to the leftmost URL
1324  KURL::List::Iterator it = lst.begin();
1325  ++it;
1326  (*lst.begin()).setRef( (*it).ref() );
1327  (*it).setRef( TQString::null );
1328 
1329  // Create the new URL
1330  m_strURL = KURL::join( lst );
1331 
1332  kdDebug(7010) << "Now trying with " << debugString(m_strURL.url()) << endl;
1333 
1334  killJob();
1335 
1336  // We don't know if this is a file or a directory. Let's test this first.
1337  // (For instance a tar.gz is a directory contained inside a file)
1338  // It may be a directory or a file, let's stat
1339  TDEIO::StatJob *job = TDEIO::stat( m_strURL, m_bProgressInfo );
1340  connect( job, TQT_SIGNAL( result( TDEIO::Job * ) ),
1341  this, TQT_SLOT( slotStatResult( TDEIO::Job * ) ) );
1342  m_job = job;
1343 
1344  return;
1345  }
1346 */
1347  TDEIO::TransferJob *job = ::tqqt_cast<TDEIO::TransferJob *>( m_job );
1348  if ( job )
1349  {
1350  job->putOnHold();
1351  TDEIO::Scheduler::publishSlaveOnHold();
1352  m_job = 0;
1353  }
1354 
1355  Q_ASSERT( !m_bFinished );
1356 
1357  // Suport for preferred service setting, see setPreferredService
1358  if ( !d->m_preferredService.isEmpty() ) {
1359  kdDebug(7010) << "Attempting to open with preferred service: " << d->m_preferredService << endl;
1360  KService::Ptr serv = KService::serviceByDesktopName( d->m_preferredService );
1361  if ( serv && serv->hasServiceType( type ) )
1362  {
1363  KURL::List lst;
1364  lst.append( m_strURL );
1365  m_bFinished = KRun::run( *serv, lst, d->m_window, d->m_asn );
1370  }
1371  }
1372 
1373  // Resolve .desktop files from media:/, remote:/, applications:/ etc.
1374  if ( ((type == "application/x-desktop") ||
1375  (type == "media/builtin-mydocuments") ||
1376  (type == "media/builtin-mycomputer") ||
1377  (type == "media/builtin-mynetworkplaces") ||
1378  (type == "media/builtin-printers") ||
1379  (type == "media/builtin-trash") ||
1380  (type == "media/builtin-webbrowser")) /* or inheriting? */ && (!d->m_localPath.isEmpty()) )
1381  {
1382  m_strURL = KURL();
1383  m_strURL.setPath( d->m_localPath );
1384  }
1385 
1386  if (!m_bFinished && KRun::runURL( m_strURL, type, d->m_window, d->m_asn, false, d->m_runExecutables, d->m_suggestedFileName )){
1387  m_bFinished = true;
1388  }
1389  else{
1390  m_bFinished = true;
1391  m_bFault = true;
1392  }
1393 
1394  m_timer.start( 0, true );
1395 }
1396 
1397 void KRun::killJob()
1398 {
1399  if ( m_job )
1400  {
1401  kdDebug(7010) << "KRun::killJob run=" << this << " m_job=" << m_job << endl;
1402  m_job->kill();
1403  m_job = 0L;
1404  }
1405 }
1406 
1407 void KRun::abort()
1408 {
1409  kdDebug(7010) << "KRun::abort " << this << " m_showingError=" << d->m_showingError << endl;
1410  killJob();
1411  // If we're showing an error message box, the rest will be done
1412  // after closing the msgbox -> don't autodelete nor emit signals now.
1413  if ( d->m_showingError )
1414  return;
1415  m_bFault = true;
1416  m_bFinished = true;
1417  m_bInit = false;
1418  m_bScanFile = false;
1419 
1420  // will emit the error and autodelete this
1421  m_timer.start( 0, true );
1422 }
1423 
1424 void KRun::setEnableExternalBrowser(bool b)
1425 {
1426  if (b)
1427  d->m_externalBrowser = TDEConfigGroup(TDEGlobal::config(), "General").readEntry("BrowserApplication");
1428  else
1429  d->m_externalBrowser = TQString::null;
1430 }
1431 
1432 void KRun::setPreferredService( const TQString& desktopEntryName )
1433 {
1434  d->m_preferredService = desktopEntryName;
1435 }
1436 
1437 void KRun::setRunExecutables(bool b)
1438 {
1439  d->m_runExecutables = b;
1440 }
1441 
1442 void KRun::setSuggestedFileName( const TQString& fileName )
1443 {
1444  d->m_suggestedFileName = fileName;
1445 }
1446 
1447 bool KRun::isExecutable( const TQString& serviceType )
1448 {
1449  return ( serviceType == "application/x-desktop" ||
1450  serviceType == "media/builtin-mydocuments" ||
1451  serviceType == "media/builtin-mycomputer" ||
1452  serviceType == "media/builtin-mynetworkplaces" ||
1453  serviceType == "media/builtin-printers" ||
1454  serviceType == "media/builtin-trash" ||
1455  serviceType == "media/builtin-webbrowser" ||
1456  serviceType == "application/x-executable" ||
1457  serviceType == "application/x-pie-executable" ||
1458  serviceType == "application/x-msdos-program" ||
1459  serviceType == "application/x-shellscript" );
1460 }
1461 
1462 /****************/
1463 
1464 pid_t
1465 TDEProcessRunner::run(TDEProcess * p, const TQString & binName)
1466 {
1467  return (new TDEProcessRunner(p, binName))->pid();
1468 }
1469 
1470 #ifdef Q_WS_X11
1471 pid_t
1472 TDEProcessRunner::run(TDEProcess * p, const TQString & binName, const TDEStartupInfoId& id )
1473 {
1474  return (new TDEProcessRunner(p, binName, id))->pid();
1475 }
1476 #endif
1477 
1478 TDEProcessRunner::TDEProcessRunner(TDEProcess * p, const TQString & _binName )
1479  : TQObject(),
1480  process_(p),
1481  binName( _binName )
1482 {
1483  TQObject::connect(
1484  process_, TQT_SIGNAL(processExited(TDEProcess *)),
1485  this, TQT_SLOT(slotProcessExited(TDEProcess *)));
1486 
1487  process_->start();
1488  if ( !process_->pid() )
1489  slotProcessExited( process_ );
1490 }
1491 
1492 #ifdef Q_WS_X11
1493 TDEProcessRunner::TDEProcessRunner(TDEProcess * p, const TQString & _binName, const TDEStartupInfoId& id )
1494  : TQObject(),
1495  process_(p),
1496  binName( _binName ),
1497  id_( id )
1498 {
1499  TQObject::connect(
1500  process_, TQT_SIGNAL(processExited(TDEProcess *)),
1501  this, TQT_SLOT(slotProcessExited(TDEProcess *)));
1502 
1503  process_->start();
1504  if ( !process_->pid() )
1505  slotProcessExited( process_ );
1506 }
1507 #endif
1508 
1509 TDEProcessRunner::~TDEProcessRunner()
1510 {
1511  delete process_;
1512 }
1513 
1514  pid_t
1515 TDEProcessRunner::pid() const
1516 {
1517  return process_->pid();
1518 }
1519 
1520  void
1521 TDEProcessRunner::slotProcessExited(TDEProcess * p)
1522 {
1523  if (p != process_)
1524  return; // Eh ?
1525 
1526  kdDebug(7010) << "slotProcessExited " << binName << endl;
1527  kdDebug(7010) << "normalExit " << process_->normalExit() << endl;
1528  kdDebug(7010) << "exitStatus " << process_->exitStatus() << endl;
1529  bool showErr = process_->normalExit()
1530  && ( process_->exitStatus() == 127 || process_->exitStatus() == 1 );
1531  if ( !binName.isEmpty() && ( showErr || process_->pid() == 0 ) )
1532  {
1533  // Often we get 1 (zsh, csh) or 127 (ksh, bash) because the binary doesn't exist.
1534  // We can't just rely on that, but it's a good hint.
1535  // Before assuming its really so, we'll try to find the binName
1536  // relatively to current directory, and then in the PATH.
1537  if ( !TQFile( binName ).exists() && TDEStandardDirs::findExe( binName ).isEmpty() )
1538  {
1539  kapp->ref();
1540  KMessageBox::sorry( 0L, i18n("Could not find the program '%1'").arg( binName ) );
1541  kapp->deref();
1542  }
1543  }
1544 #ifdef Q_WS_X11
1545  if( !id_.none())
1546  {
1547  TDEStartupInfoData data;
1548  data.addPid( pid()); // announce this pid for the startup notification has finished
1549  data.setHostname();
1550  TDEStartupInfo::sendFinish( id_, data );
1551  }
1552 #endif
1553  deleteLater();
1554 }
1555 
1556 void KRun::virtual_hook( int, void* )
1557 { /*BASE::virtual_hook( id, data );*/ }
1558 
1559 #include "krun.moc"
TDEIO::UDS_LOCAL_PATH
A local file path if the ioslave display files sitting on the local filesystem (but in another hierar...
Definition: global.h:338
KRun::setEnableExternalBrowser
void setEnableExternalBrowser(bool b)
Sets whether the external webbrowser setting should be honoured.
Definition: krun.cpp:1424
TDEIO::UDSEntry
TQValueList< UDSAtom > UDSEntry
An entry is the list of atoms containing all the information for a file or URL.
Definition: global.h:507
TDEIO::NetAccess::mostLocalURL
static KURL mostLocalURL(const KURL &url, TQWidget *window)
Tries to map a local URL for the given URL.
Definition: netaccess.cpp:213
KRun::abort
void abort()
Abort this KRun.
Definition: krun.cpp:1407
KRun::runURL
static pid_t runURL(const KURL &_url, const TQString &_mimetype, bool tempFile, bool runExecutables)
Open the given URL.
Definition: krun.cpp:94
KService::terminalOptions
TQString terminalOptions() const
Returns any options associated with the terminal the service runs in, if it requires a terminal...
Definition: kservice.h:147
KService::desktopEntryName
TQString desktopEntryName() const
Returns the filename of the service desktop entry without any extension.
Definition: kservice.h:182
KService::serviceByStorageId
static Ptr serviceByStorageId(const TQString &_storageId)
Find a service by its storage-id or desktop-file path.
Definition: kservice.cpp:694
KRun::setSuggestedFileName
void setSuggestedFileName(const TQString &fileName)
Sets the file name to use in the case of downloading the file to a tempfile in order to give to a non...
Definition: krun.cpp:1442
KService::property
virtual TQVariant property(const TQString &_name) const
Returns the requested property.
Definition: kservice.cpp:528
KRun::setRunExecutables
void setRunExecutables(bool b)
Sets whether executables, .desktop files or shell scripts should be run by KRun.
Definition: krun.cpp:1437
KService
Represent a service, i.e.
Definition: kservice.h:48
TDEIO::Job::errorString
TQString errorString() const
Converts an error code and a non-i18n error message into an error message in the current language...
Definition: global.cpp:225
KRun::setPreferredService
void setPreferredService(const TQString &desktopEntryName)
Set the preferred service for opening this URL, after its mimetype will have been found by KRun...
Definition: krun.cpp:1432
KService::substituteUid
bool substituteUid() const
Checks whether the service runs with a different user id.
Definition: kservice.cpp:726
KMimeType::mimeType
static Ptr mimeType(const TQString &_name)
Retrieve a pointer to the mime type _name or a pointer to the default mime type "application/octet-st...
Definition: kmimetype.cpp:141
KProtocolInfo::supportsReading
static bool supportsReading(const KURL &url)
Returns whether the protocol can retrieve data from URLs.
Definition: kprotocolinfo.cpp:139
KService::username
TQString username() const
Returns the user name, if the service runs with a different user id.
Definition: kservice.cpp:740
KRun::run
static pid_t run(const KService &_service, const KURL::List &_urls, TQWidget *window, bool tempFiles=false)
Open a list of URLs with a certain service (application).
Definition: krun.cpp:755
TDEIO::Job
The base class for all jobs.
Definition: jobclasses.h:67
TDEIO::StatJob
A TDEIO job that retrieves information about a file or directory.
Definition: jobclasses.h:687
KRun::binaryName
static TQString binaryName(const TQString &execLine, bool removePath)
Given a full command line (e.g.
Definition: krun.cpp:543
KProtocolInfo::exec
static TQString exec(const TQString &protocol)
Returns the library / executable to open for the protocol protocol Example : "tdeio_ftp", meaning either the executable "tdeio_ftp" or the library "tdeio_ftp.la" (recommended), whichever is available.
KService::type
virtual TQString type() const
Returns the type of the service.
Definition: kservice.h:92
TDEIO::Job::setWindow
void setWindow(TQWidget *window)
Associate this job with a window given by window.
Definition: job.cpp:352
KRun::finished
void finished()
Emitted when the operation finished.
KRun::processDesktopExec
static TQStringList processDesktopExec(const KService &_service, const KURL::List &_urls, bool has_shell, bool tempFiles)
Processes a Exec= line as found in .desktop files.
Definition: krun.cpp:374
TDEIO::Job::kill
virtual void kill(bool quietly=true)
Abort this job.
Definition: job.cpp:239
TDEIO::localURL
TDEIO_EXPORT LocalURLJob * localURL(const KURL &remoteUrl)
Retrieve local URL if available.
Definition: job.cpp:841
TDEIO::Job::error
int error() const
Returns the error code, if there has been an error.
Definition: jobclasses.h:94
KProtocolInfo::supportsListing
static bool supportsListing(const KURL &url)
Returns whether the protocol can list files/objects.
Definition: kprotocolinfo.cpp:121
KService::path
TQString path() const
Returns the working directory to run the program in.
Definition: kservice.h:226
TDEIO::stat
TDEIO_EXPORT StatJob * stat(const KURL &url, bool showProgressInfo=true)
Find all details for one file or directory.
Definition: job.cpp:921
TDEIO::UDS_MIME_TYPE
A mime type; prevents guessing.
Definition: global.h:373
KRun::KRun
KRun(const KURL &url, mode_t mode=0, bool isLocalFile=false, bool showProgressInfo=true)
Create a KRun object to run the preferred application for a file/URL.
Definition: krun.cpp:874
TDEIO::mimetype
TDEIO_EXPORT MimetypeJob * mimetype(const KURL &url, bool showProgressInfo=true)
Find mimetype for one file or directory.
Definition: job.cpp:1544
TDEIO::get
TDEIO_EXPORT TransferJob * get(const KURL &url, bool reload=false, bool showProgressInfo=true)
Get (a.k.a.
Definition: job.cpp:1255
KMimeType::findByURL
static Ptr findByURL(const KURL &_url, mode_t _mode=0, bool _is_local_file=false, bool _fast_mode=false)
Finds a KMimeType with the given _url.
Definition: kmimetype.cpp:165
KProtocolInfo::protocolClass
static TQString protocolClass(const TQString &protocol)
Returns the protocol class for the specified protocol.
KService::exec
TQString exec() const
Returns the executable.
Definition: kservice.h:104
TDEIO::Scheduler::publishSlaveOnHold
static void publishSlaveOnHold()
Send the slave that was put on hold back to TDELauncher.
Definition: scheduler.h:181
KService::desktopEntryPath
TQString desktopEntryPath() const
Returns the path to the location where the service desktop entry is stored.
Definition: kservice.h:174
KService::allowMultipleFiles
bool allowMultipleFiles() const
Checks whether this service can handle several files as startup arguments.
Definition: kservice.cpp:824
KService::terminal
bool terminal() const
Checks whethe the service should be run in a terminal.
Definition: kservice.h:138
KRun::isExecutable
static bool isExecutable(const TQString &serviceType)
Returns whether serviceType refers to an executable program instead of a data file.
Definition: krun.cpp:1447
KRun::isExecutableFile
static bool isExecutableFile(const KURL &url, const TQString &mimetype)
Returns wether the url of mimetype is executable.
Definition: krun.cpp:99
TDEIO::Job::showErrorDialog
void showErrorDialog(TQWidget *parent=0L)
Display a dialog box to inform the user of the error given by this job.
Definition: job.cpp:294
TDEIO::UDS_FILE_TYPE
File type, part of the mode returned by stat (for a link, this returns the file type of the pointed i...
Definition: global.h:366
KDEDesktopMimeType::run
static pid_t run(const KURL &_url, bool _is_local)
Invokes the default action for the desktop entry.
Definition: kmimetype.cpp:790
KService::name
virtual TQString name() const
Returns the name of the service.
Definition: kservice.h:98
KService::serviceByDesktopName
static Ptr serviceByDesktopName(const TQString &_name)
Find a service by the name of its desktop file, not depending on its actual location (as long as it's...
Definition: kservice.cpp:680
KRun::error
void error()
Emitted when the operation had an error.
KRun::m_bScanFile
bool m_bScanFile
Used to indicate that the next action is to scan the file.
Definition: krun.h:434
KRun::runCommand
static pid_t runCommand(TQString cmd)
Run the given shell command and notifies kicker of the starting of the application.
Definition: krun.cpp:848
KProtocolInfo::isHelperProtocol
static bool isHelperProtocol(const KURL &url)
Returns whether the protocol can act as a helper protocol.
Definition: kprotocolinfo.cpp:94
KServiceTypeProfile::preferredService
static KService::Ptr preferredService(const TQString &serviceType, const TQString &genericServiceType)
Returns the preferred service for _serviceType and _genericServiceType ("Application", type of component, or null).
Definition: kuserprofile.cpp:303
TDEIO::buildErrorString
TDEIO_EXPORT TQString buildErrorString(int errorCode, const TQString &errorText)
Returns a translated error message for errorCode using the additional error information provided by e...
Definition: global.cpp:230
KRun::~KRun
virtual ~KRun()
Destructor.
Definition: krun.cpp:1114
TDEIO::TransferJob
The transfer job pumps data into and/or out of a Slave.
Definition: jobclasses.h:874
KRun::displayOpenWithDialog
static bool displayOpenWithDialog(const KURL::List &lst, bool tempFiles)
Display the Open-With dialog for those URLs, and run the chosen application.
Definition: krun.cpp:209
KRun::foundMimeType
virtual void foundMimeType(const TQString &_type)
Called if the mimetype has been detected.
Definition: krun.cpp:1291
KRun::shellQuote
static void shellQuote(TQString &_str)
Quotes a string for the shell.
Definition: krun.cpp:236
KProtocolInfo::defaultMimetype
static TQString defaultMimetype(const KURL &url)
Returns default mimetype for this URL based on the protocol.
Definition: kprotocolinfo.cpp:249
KRun::m_bInit
bool m_bInit
USed to indicate that the next action is to initialize.
Definition: krun.h:441
TDEIO::SimpleJob::putOnHold
virtual void putOnHold()
Abort job.
Definition: job.cpp:464
KService::icon
TQString icon() const
Returns the name of the icon.
Definition: kservice.h:125

tdeio/tdeio

Skip menu "tdeio/tdeio"
  • Main Page
  • Modules
  • Namespace List
  • Class Hierarchy
  • Alphabetical List
  • Class List
  • File List
  • Namespace Members
  • Class Members
  • Related Pages

tdeio/tdeio

Skip menu "tdeio/tdeio"
  • arts
  • dcop
  • dnssd
  • interfaces
  •   kspeech
  •     interface
  •     library
  •   tdetexteditor
  • kate
  • kded
  • kdoctools
  • kimgio
  • kjs
  • libtdemid
  • libtdescreensaver
  •     tdecore
  • tdeabc
  • tdecmshell
  • tdecore
  • tdefx
  • tdehtml
  • tdeinit
  • tdeio
  •   bookmarks
  •   httpfilter
  •   kpasswdserver
  •   kssl
  • tdeioslave
  •   http
  •   tdefile
  •   tdeio
  •   tdeioexec
  • tdemdi
  •   tdemdi
  • tdenewstuff
  • tdeparts
  • tdeprint
  • tderandr
  • tderesources
  • tdespell2
  • tdesu
  • tdeui
  • tdeunittest
  • tdeutils
  • tdewallet
Generated for tdeio/tdeio by doxygen 1.8.8
This website is maintained by Timothy Pearson.