summaryrefslogtreecommitdiffstats
path: root/tdecore/tdeuniqueapplication.cpp
blob: 7db9f528e55779e2fb857eb1293b0df9ca0c5a10 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
/* This file is part of the KDE libraries
    Copyright (c) 1999 Preston Brown <pbrown@kde.org>

    $Id$

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include <config.h>

#include <sys/types.h>
#include <sys/wait.h>

#include <assert.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>

#include <tqfile.h>
#include <tqptrlist.h>
#include <tqtimer.h>

#include <dcopclient.h>
#include <tdecmdlineargs.h>
#include <kstandarddirs.h>
#include <tdeaboutdata.h>

#if defined TQ_WS_X11
#include <twin.h> 
#include <tdestartupinfo.h> 
#endif

#include <tdeconfig.h>
#include "kdebug.h"
#include "tdeuniqueapplication.h"

#if defined TQ_WS_X11
#include <netwm.h> 
#include <X11/Xlib.h> 
#define DISPLAY "DISPLAY"
#else
#  ifdef TQ_WS_QWS
#    define DISPLAY "QWS_DISPLAY"
#  else
#    define DISPLAY "DISPLAY"
#  endif
#endif

bool TDEUniqueApplication::s_nofork = false;
bool TDEUniqueApplication::s_multipleInstances = false;
bool TDEUniqueApplication::s_uniqueTestDone = false;
bool TDEUniqueApplication::s_handleAutoStarted = false;

static TDECmdLineOptions tdeunique_options[] =
{
  { "nofork", "Don't run in the background.", 0 },
  TDECmdLineLastOption
};

struct DCOPRequest {
   TQCString fun;
   TQByteArray data;
   DCOPClientTransaction *transaction;
};

class TDEUniqueApplicationPrivate {
public:
   TQPtrList <DCOPRequest> requestList;
   bool processingRequest;
   bool firstInstance;
};

void
TDEUniqueApplication::addCmdLineOptions()
{
  TDECmdLineArgs::addCmdLineOptions(tdeunique_options, 0, "tdeuniqueapp", "tde" );
}

bool
TDEUniqueApplication::start()
{
  if( s_uniqueTestDone )
    return true;
  s_uniqueTestDone = true;
  addCmdLineOptions(); // Make sure to add cmd line options
#ifdef TQ_WS_WIN
  s_nofork = true;
#else
  TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs("tdeuniqueapp");
  s_nofork = !args->isSet("fork");
  delete args;
#endif

  TQCString appName = TDECmdLineArgs::about->appName();

  if (s_nofork)
  {
     if (s_multipleInstances)
     {
        TQCString pid;
        pid.setNum(getpid());
        appName = appName + "-" + pid;
     }

     // Check to make sure that we're actually able to register with the DCOP
     // server.

#ifndef TQ_WS_WIN //TODO
     if(dcopClient()->registerAs(appName, false).isEmpty()) {
        startKdeinit();
        if(dcopClient()->registerAs(appName, false).isEmpty()) {
           kdError() << "TDEUniqueApplication: Can't setup DCOP communication." << endl;
           ::exit(255);
        }           
     }
#endif

     // We'll call newInstance in the constructor. Do nothing here.
     return true;
  }
  DCOPClient *dc;
  int fd[2];
  signed char result;
  if (0 > pipe(fd))
  {
     kdError() << "TDEUniqueApplication: pipe() failed!" << endl;
     ::exit(255);
  }
  int fork_result = fork();
  switch(fork_result) {
  case -1:
     kdError() << "TDEUniqueApplication: fork() failed!" << endl;
     ::exit(255);
     break;
  case 0:
     // Child
     ::close(fd[0]);
     if (s_multipleInstances)
        appName.append("-").append(TQCString().setNum(getpid()));
     dc = dcopClient();
     {
        TQCString regName = dc->registerAs(appName, false);
        if (regName.isEmpty())
        {
           // Check DISPLAY
           if (TQCString(getenv(DISPLAY)).isEmpty())
           {
              kdError() << "TDEUniqueApplication: Can't determine DISPLAY. Aborting." << endl;
              result = -1; // Error
              ::write(fd[1], &result, 1);
              ::exit(255);
           }

           // Try to launch tdeinit.
           startKdeinit();
           regName = dc->registerAs(appName, false);
           if (regName.isEmpty())
           {
              kdError() << "TDEUniqueApplication: Can't setup DCOP communication." << endl;
              result = -1;
              delete dc;	// Clean up DCOP commmunication
              ::write(fd[1], &result, 1);
              ::exit(255);
           }
        }
        if (regName != appName)
        {
           // Already running. Ok.
           result = 0;
           delete dc;	// Clean up DCOP commmunication
           ::write(fd[1], &result, 1);
           ::close(fd[1]);
#if 0
#ifdef TQ_WS_X11
           // say we're up and running ( probably no new window will appear )
           TDEStartupInfoId id;
           if( kapp != NULL ) // TDEApplication constructor unsets the env. variable
               id.initId( kapp->startupId());
           else
               id = TDEStartupInfo::currentStartupIdEnv();
           if( !id.none())
           {
               Display* disp = XOpenDisplay( NULL );
               if( disp != NULL ) // use extra X connection
               {
                   TDEStartupInfo::sendFinishX( disp, id );
                   XCloseDisplay( disp );
               }
           }
#else //FIXME(E): implement
#endif
#endif
           return false;
        }
        dc->setPriorityCall(true);
     }

     {
#ifdef TQ_WS_X11
         TDEStartupInfoId id;
         if( kapp != NULL ) // TDEApplication constructor unsets the env. variable
             id.initId( kapp->startupId());
         else
             id = TDEStartupInfo::currentStartupIdEnv();
         if( !id.none())
         { // notice about pid change
            Display* disp = XOpenDisplay( NULL );
            if( disp != NULL ) // use extra X connection
               {
               TDEStartupInfoData data;
               data.addPid( getpid());
               TDEStartupInfo::sendChangeX( disp, id, data );
               XCloseDisplay( disp );
               }
         }
#else //FIXME(E): Implement
#endif
     }
     result = 0;
     ::write(fd[1], &result, 1);
     ::close(fd[1]);
     return true; // Finished.
  default:
     // Parent
//     DCOPClient::emergencyClose();
//     dcopClient()->detach();
     if (s_multipleInstances)
        appName.append("-").append(TQCString().setNum(fork_result));
     ::close(fd[1]);
     for(;;)
     {
       int n = ::read(fd[0], &result, 1);
       if (n == 1) break;
       if (n == 0)
       {
          kdError() << "TDEUniqueApplication: Pipe closed unexpectedly." << endl;
          ::exit(255);
       }
       if (errno != EINTR)
       {
          kdError() << "TDEUniqueApplication: Error reading from pipe." << endl;
          ::exit(255);
       }
     }
     ::close(fd[0]);

     if (result != 0)
        ::exit(result); // Error occurred in child.

     dc = new DCOPClient();
     if (!dc->attach())
     {
        kdError() << "TDEUniqueApplication: Parent process can't attach to DCOP." << endl;
        delete dc;	// Clean up DCOP commmunication
        ::exit(255);
     }
     if (!dc->isApplicationRegistered(appName)) {
        kdError() << "TDEUniqueApplication: Registering failed!" << endl;
     }

     TQCString new_asn_id;
#if defined TQ_WS_X11
     TDEStartupInfoId id;
     if( kapp != NULL ) // TDEApplication constructor unsets the env. variable
         id.initId( kapp->startupId());
     else
         id = TDEStartupInfo::currentStartupIdEnv();
     if( !id.none())
         new_asn_id = id.id();
#endif
     
     TQByteArray data, reply;
     TQDataStream ds(data, IO_WriteOnly);

     TDECmdLineArgs::saveAppArgs(ds);
     ds << new_asn_id;

     dc->setPriorityCall(true);
     TQCString replyType;
     if (!dc->call(appName, TDECmdLineArgs::about->appName(), "newInstance()", data, replyType, reply))
     {
        kdError() << "Communication problem with " << TDECmdLineArgs::about->appName() << ", it probably crashed." << endl;
        delete dc;	// Clean up DCOP commmunication
        ::exit(255);
     }
     dc->setPriorityCall(false);
     if (replyType != "int")
     {
        kdError() << "TDEUniqueApplication: DCOP communication error!" << endl;
        delete dc;	// Clean up DCOP commmunication
        ::exit(255);
     }
     TQDataStream rs(reply, IO_ReadOnly);
     int exitCode;
     rs >> exitCode;
     delete dc;	// Clean up DCOP commmunication
     ::exit(exitCode);
     break;
  }
  return false; // make insure++ happy
}


TDEUniqueApplication::TDEUniqueApplication(bool allowStyles, bool GUIenabled, bool configUnique)
  : TDEApplication( allowStyles, GUIenabled, initHack( configUnique )),
    DCOPObject(TDECmdLineArgs::about->appName())
{
  d = new TDEUniqueApplicationPrivate;
  d->processingRequest = false;
  d->firstInstance = true;

  if (s_nofork) {
    // Can't call newInstance directly from the constructor since it's virtual...
    TQTimer::singleShot( 0, this, TQ_SLOT(newInstanceNoFork()) );
  }
  else {
    // Force to handle DCOP requests (newInstance call)
    TQTimer::singleShot( 0, this, TQ_SLOT(processDelayed()));
  }
}


#ifdef TQ_WS_X11
TDEUniqueApplication::TDEUniqueApplication(Display *display, TQt::HANDLE visual,
		TQt::HANDLE colormap, bool allowStyles, bool configUnique)
  : TDEApplication( display, visual, colormap, allowStyles, initHack( configUnique )),
    DCOPObject(TDECmdLineArgs::about->appName())
{
  d = new TDEUniqueApplicationPrivate;
  d->processingRequest = false;
  d->firstInstance = true;

  if (s_nofork) {
    // Can't call newInstance directly from the constructor since it's virtual...
    TQTimer::singleShot( 0, this, TQ_SLOT(newInstanceNoFork()) );
  }
  else {
    // Force to handle DCOP requests (newInstance call)
    TQTimer::singleShot( 0, this, TQ_SLOT(processDelayed()));
  }
}
#endif


TDEUniqueApplication::~TDEUniqueApplication()
{
  delete d;
}

// this gets called before even entering TQApplication::TQApplication()
TDEInstance* TDEUniqueApplication::initHack( bool configUnique )
{
  TDEInstance* inst = new TDEInstance( TDECmdLineArgs::about );
  if (configUnique)
  {
    TDEConfigGroupSaver saver( inst->config(), "KDE" );
    s_multipleInstances = inst->config()->readBoolEntry("MultipleInstances", false);
  }
  if( !start())
         // Already running
      ::exit( 0 );
  return inst;
}

void TDEUniqueApplication::newInstanceNoFork()
{
  if (dcopClient()->isSuspended())
  {
    // Try again later.
    TQTimer::singleShot( 200, this, TQ_SLOT(newInstanceNoFork()) );
    return;
  }
  
  s_handleAutoStarted = false;
  newInstance();
  d->firstInstance = false;
#if defined TQ_WS_X11
  // KDE4 remove
  // A hack to make startup notification stop for apps which override newInstance()
  // and reuse an already existing window there, but use KWin::activateWindow()
  // instead of TDEStartupInfo::setNewStartupId(). Therefore KWin::activateWindow()
  // for now sets this flag. Automatically ending startup notification always
  // would cause problem if the new window would show up with a small delay.
  if( s_handleAutoStarted )
      TDEStartupInfo::handleAutoAppStartedSending();
#endif
  // What to do with the return value ?
}

bool TDEUniqueApplication::process(const TQCString &fun, const TQByteArray &data,
				 TQCString &replyType, TQByteArray &replyData)
{
  if (fun == "newInstance()")
  {
    delayRequest(fun, data);
    return true;
  } else
    return DCOPObject::process(fun, data, replyType, replyData);
}

void
TDEUniqueApplication::delayRequest(const TQCString &fun, const TQByteArray &data)
{
  DCOPRequest *request = new DCOPRequest;
  request->fun = fun;
  request->data = data;
  request->transaction = dcopClient()->beginTransaction();
  d->requestList.append(request);
  if (!d->processingRequest)
  {
     TQTimer::singleShot(0, this, TQ_SLOT(processDelayed()));
  }
}

void
TDEUniqueApplication::processDelayed()
{
  if (dcopClient()->isSuspended())
  {
    // Try again later.
    TQTimer::singleShot( 200, this, TQ_SLOT(processDelayed()));
    return;
  }
  d->processingRequest = true;
  while( !d->requestList.isEmpty() )
  {
     DCOPRequest *request = d->requestList.take(0);
     TQByteArray replyData;
     TQCString replyType;
     if (request->fun == "newInstance()") {
       dcopClient()->setPriorityCall(false);
       TQDataStream ds(request->data, IO_ReadOnly);
       TDECmdLineArgs::loadAppArgs(ds);
       if( !ds.atEnd()) // backwards compatibility
       {
           TQCString asn_id;
           ds >> asn_id;
           setStartupId( asn_id );
       }
       s_handleAutoStarted = false;
       int exitCode = newInstance();
       d->firstInstance = false;
#if defined TQ_WS_X11
       if( s_handleAutoStarted )
           TDEStartupInfo::handleAutoAppStartedSending(); // KDE4 remove?
#endif
       TQDataStream rs(replyData, IO_WriteOnly);
       rs << exitCode;
       replyType = "int";
     }
     dcopClient()->endTransaction( request->transaction, replyType, replyData);
     delete request;
  }

  d->processingRequest = false;
}

bool TDEUniqueApplication::restoringSession()
{
  return d->firstInstance && isRestored();
}

int TDEUniqueApplication::newInstance()
{
  if (!d->firstInstance)
  {
    
    if ( mainWidget() )
    {
      mainWidget()->show();
#if defined TQ_WS_X11
    // This is the line that handles window activation if necessary,
    // and what's important, it does it properly. If you reimplement newInstance(),
    // and don't call the inherited one, use this (but NOT when newInstance()
    // is called for the first time, like here).
      TDEStartupInfo::setNewStartupId( mainWidget(), kapp->startupId());
#endif
    }
  }
  return 0; // do nothing in default implementation
}

void TDEUniqueApplication::setHandleAutoStarted()
{
    s_handleAutoStarted = false;
}

void TDEUniqueApplication::virtual_hook( int id, void* data )
{ TDEApplication::virtual_hook( id, data );
  DCOPObject::virtual_hook( id, data ); }

#include "tdeuniqueapplication.moc"