summaryrefslogtreecommitdiffstats
path: root/tdeui/ktip.cpp
blob: 1cc52064014ccfb9af8db7a49bb447936b334ba0 (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
/*****************************************************************

Copyright (c) 2000-2003 Matthias Hoelzer-Kluepfel <mhk@kde.org>
                        Tobias Koenig <tokoe@kde.org>
                        Daniel Molkentin <molkentin@kde.org>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

******************************************************************/

#include <tqcheckbox.h>
#include <tqfile.h>
#include <tqhbox.h>
#include <tqlabel.h>
#include <tqlayout.h>
#include <tqpushbutton.h>
#include <tqregexp.h>
#include <tqtextstream.h>
#include <tqimage.h>

#include <tdeaboutdata.h>
#include <tdeapplication.h>
#include <tdeconfig.h>
#include <kdebug.h>
#include <tdeglobal.h>
#include <kiconloader.h>
#include <tdelocale.h>
#include <kpushbutton.h>
#include <kseparator.h>
#include <kstandarddirs.h>
#include <kstdguiitem.h>
#include <ktextbrowser.h>
#include <kiconeffect.h>
#include <tdeglobalsettings.h>

#ifdef Q_WS_X11
#include <twin.h>
#endif

#include "ktip.h"


KTipDatabase::KTipDatabase(const TQString &_tipFile)
{
    TQString tipFile = _tipFile;
    if (tipFile.isEmpty())
	tipFile = TQString::fromLatin1(TDEGlobal::instance()->aboutData()->appName()) + "/tips";

    loadTips(tipFile);

    if (!mTips.isEmpty())
	mCurrent = kapp->random() % mTips.count();
}


KTipDatabase::KTipDatabase( const TQStringList& tipsFiles )
{
   if ( tipsFiles.isEmpty() || ( ( tipsFiles.count() == 1 ) && tipsFiles.first().isEmpty() ) )
   {
       addTips(TQString::fromLatin1(TDEGlobal::instance()->aboutData()->appName()) + "/tips");
   }
   else
   {
       for (TQStringList::ConstIterator it = tipsFiles.begin(); it != tipsFiles.end(); ++it)
           addTips( *it );
   }
    if (!mTips.isEmpty())
	mCurrent = kapp->random() % mTips.count();

}

void KTipDatabase::loadTips(const TQString &tipFile)
{
    mTips.clear();
    addTips(tipFile);
}

// if you change something here, please update the script
// preparetips, which depends on extracting exactly the same
// text as done here.
void KTipDatabase::addTips(const TQString& tipFile )
{
    TQString fileName = locate("data", tipFile);

    if (fileName.isEmpty())
    {
	kdDebug() << "KTipDatabase::addTips: can't find '" << tipFile << "' in standard dirs" << endl;
        return;
    }

    TQFile file(fileName);
    if (!file.open(IO_ReadOnly))
    {
	kdDebug() << "KTipDatabase::addTips: can't open '" << fileName << "' for reading" << endl;
	return;
    }

    TQByteArray data = file.readAll();
    TQString content = TQString::fromUtf8(data.data(), data.size());
    const TQRegExp rx("\\n+");

    int pos = -1;
    while ((pos = content.find("<html>", pos + 1, false)) != -1)
    {
       // to make translations work, tip extraction here must exactly 
       // match what is done by the preparetips script 
       TQString tip = content 
           .mid(pos + 6, content.find("</html>", pos, false) - pos - 6)
           .replace(rx, "\n");
       if (!tip.endsWith("\n"))
           tip += "\n";
       if (tip.startsWith("\n")) 
            tip = tip.mid(1); 
        if (tip.isEmpty())
        {
            kdDebug() << "Empty tip found! Skipping! " << pos << endl;
            continue;
        }
	mTips.append(tip);
    }

    file.close();

}

void KTipDatabase::nextTip()
{
    if (mTips.isEmpty())
	return ;
    mCurrent += 1;
    if (mCurrent >= (int) mTips.count())
	mCurrent = 0;
}


void KTipDatabase::prevTip()
{
    if (mTips.isEmpty())
	return ;
    mCurrent -= 1;
    if (mCurrent < 0)
	mCurrent = mTips.count() - 1;
}


TQString KTipDatabase::tip() const
{
    if (mTips.isEmpty())
	return TQString::null;
    return mTips[mCurrent];
}

KTipDialog *KTipDialog::mInstance = 0;


KTipDialog::KTipDialog(KTipDatabase *db, TQWidget *parent, const char *name)
  : KDialog(parent, name)
{
    /**
     * Parent is 0L when TipDialog is used as a mainWidget. This should
     * be the case only in ktip, so let's use the ktip layout.
     */
    bool isTipDialog = (parent);

    TQImage img;
    int h,s,v;

    mBlendedColor = TDEGlobalSettings::activeTitleColor();
    mBlendedColor.hsv(&h,&s,&v);
    mBlendedColor.setHsv(h, int(s*(71/76.0)), int(v*(67/93.0)));

    if (!isTipDialog)
    {
	img = TQImage(locate("data", "tdewizard/pics/wizard_small.png"));
	// colorize and check to figure the correct color
	TDEIconEffect::colorize(img, mBlendedColor, 1.0);
	QRgb colPixel( img.pixel(0,0) );

	mBlendedColor = TQColor(tqRed(colPixel),tqGreen(colPixel),tqBlue(colPixel));
    }

    mBaseColor = TDEGlobalSettings::alternateBackgroundColor();
    mBaseColor.hsv(&h,&s,&v);
    mBaseColor.setHsv(h, int(s*(10/6.0)), int(v*(93/99.0)));

    mTextColor = TDEGlobalSettings::textColor();


    mDatabase = db;

    setCaption(i18n("Tip of the Day"));
#ifdef Q_WS_X11
    KWin::setIcons( winId(),
                    TDEGlobal::iconLoader()->loadIcon( "idea", TDEIcon::NoGroup, 32 ),
                    TDEGlobal::iconLoader()->loadIcon( "idea", TDEIcon::NoGroup, 16 ) );
#endif
    TQVBoxLayout *vbox = new TQVBoxLayout(this, marginHint(), spacingHint());

   if (isTipDialog)
    {
	TQHBoxLayout *pl = new TQHBoxLayout(vbox, 0, 0);

	TQLabel *bulb = new TQLabel(this);
	bulb->setPixmap(locate("data", "tdeui/pics/ktip-bulb.png"));
	pl->addWidget(bulb);

	TQLabel *titlePane = new TQLabel(this);
	titlePane->setBackgroundPixmap(locate("data", "tdeui/pics/ktip-background.png"));
	titlePane->setText(i18n("Did you know...?\n"));
	titlePane->setFont(TQFont(TDEGlobalSettings::generalFont().family(), 20, TQFont::Bold));
	titlePane->setAlignment(TQLabel::AlignCenter);
	pl->addWidget(titlePane, 100);
    }

    TQHBox *hbox = new TQHBox(this);
    hbox->setSpacing(0);
    hbox->setFrameStyle(TQFrame::Panel | TQFrame::Sunken);
    vbox->addWidget(hbox);

    TQHBox *tl = new TQHBox(hbox);
    tl->setMargin(7);
    tl->setBackgroundColor(mBlendedColor);

    TQHBox *topLeft = new TQHBox(tl);
    topLeft->setMargin(15);
    topLeft->setBackgroundColor(mBaseColor);

    mTipText = new KTextBrowser(topLeft);

    mTipText->setWrapPolicy( TQTextEdit::AtWordOrDocumentBoundary );
    mTipText->mimeSourceFactory()->addFilePath(
	TDEGlobal::dirs()->findResourceDir("data", "tdewizard/pics")+"tdewizard/pics/");
    mTipText->setFrameStyle(TQFrame::NoFrame | TQFrame::Plain);
    mTipText->setHScrollBarMode(TQScrollView::AlwaysOff);
    mTipText->setLinkUnderline(false);

    TQStyleSheet *sheet = mTipText->styleSheet();
    TQStyleSheetItem *item = sheet->item("a");
    item->setFontWeight(TQFont::Bold);
    mTipText->setStyleSheet(sheet);
    TQPalette pal = mTipText->palette();
    pal.setColor( TQPalette::Active, TQColorGroup::Link, mBlendedColor );
    pal.setColor( TQPalette::Inactive, TQColorGroup::Link, mBlendedColor );
    mTipText->setPalette(pal);

    TQStringList icons = TDEGlobal::dirs()->resourceDirs("icon");
    TQStringList::Iterator it;
    for (it = icons.begin(); it != icons.end(); ++it)
        mTipText->mimeSourceFactory()->addFilePath(*it);

    if (!isTipDialog)
    {
	TQLabel *l = new TQLabel(hbox);
	l->setPixmap(img);
	l->setBackgroundColor(mBlendedColor);
	l->setAlignment(Qt::AlignRight | Qt::AlignBottom);

	resize(550, 230);
        TQSize sh = size();

        TQRect rect = TDEGlobalSettings::splashScreenDesktopGeometry();

        move(rect.x() + (rect.width() - sh.width())/2,
	rect.y() + (rect.height() - sh.height())/2);
    }

    KSeparator* sep = new KSeparator( KSeparator::HLine, this);
    vbox->addWidget(sep);

    TQHBoxLayout *hbox2 = new TQHBoxLayout(vbox, 4);

    mTipOnStart = new TQCheckBox(i18n("&Show tips on startup"), this);
    hbox2->addWidget(mTipOnStart, 1);

    KPushButton *prev = new KPushButton( KStdGuiItem::back(
            KStdGuiItem::UseRTL ), this );
    prev->setText( i18n("&Previous") );
    hbox2->addWidget(prev);

    KPushButton *next = new KPushButton( KStdGuiItem::forward(
            KStdGuiItem::UseRTL ), this );
    next->setText( i18n("Opposite to Previous","&Next") );
    hbox2->addWidget(next);

    KPushButton *ok = new KPushButton(KStdGuiItem::close(), this);
    ok->setDefault(true);
    hbox2->addWidget(ok);

    TDEConfigGroup config(kapp->config(), "TipOfDay");
    mTipOnStart->setChecked(config.readBoolEntry("RunOnStart", true));

    connect(next, TQT_SIGNAL(clicked()), this, TQT_SLOT(nextTip()));
    connect(prev, TQT_SIGNAL(clicked()), this, TQT_SLOT(prevTip()));
    connect(ok, TQT_SIGNAL(clicked()), this, TQT_SLOT(accept()));
    connect(mTipOnStart, TQT_SIGNAL(toggled(bool)), this, TQT_SLOT(showOnStart(bool)));

    ok->setFocus();

    nextTip();
}

KTipDialog::~KTipDialog()
{
    if( mInstance==this )
        mInstance = 0L;
}

void KTipDialog::showTip(const TQString &tipFile, bool force)
{
    showTip(kapp->mainWidget(), tipFile, force);
}

void KTipDialog::showTip(TQWidget *parent, const TQString &tipFile, bool force)
{
  showMultiTip( parent, TQStringList(tipFile), force );
}

void KTipDialog::showMultiTip(TQWidget *parent, const TQStringList &tipFiles, bool force)
{
    TDEConfigGroup configGroup(kapp->config(), "TipOfDay");

    const bool runOnStart = configGroup.readBoolEntry("RunOnStart", true);

    if (!force)
    {
        if (!runOnStart)
	    return;

        bool hasLastShown = configGroup.hasKey("TipLastShown");
        if (hasLastShown)
        {
           const int oneDay = 24*60*60;
           TQDateTime lastShown = configGroup.readDateTimeEntry("TipLastShown");
           // Show tip roughly once a week
           if (lastShown.secsTo(TQDateTime::currentDateTime()) < (oneDay + (kapp->random() % (10*oneDay))))
               return;
        }
        configGroup.writeEntry("TipLastShown", TQDateTime::currentDateTime());
        kapp->config()->sync();
        if (!hasLastShown)
           return; // Don't show tip on first start
    }

    if (!mInstance)
	mInstance = new KTipDialog(new KTipDatabase(tipFiles), parent);
    else
	// The application might have changed the RunOnStart option in its own
	// configuration dialog, so we should update the checkbox.
      mInstance->mTipOnStart->setChecked(runOnStart);

      mInstance->show();
      mInstance->raise();
  }

static TQString fixTip(TQString tip)
{
    TQRegExp iconRegExp("<img src=\"(.*)\">");
    iconRegExp.setMinimal(true);
    if (iconRegExp.search(tip)>-1) {
      TQString iconName = iconRegExp.cap(1);
      if (!iconName.isEmpty())
         if (TDEGlobal::dirs()->findResource("icon", iconName).isEmpty())
           tip.replace("crystalsvg","hicolor");
    }

    return tip;
}

  void KTipDialog::prevTip()
  {
      mDatabase->prevTip();
      TQString currentTip = TQString::fromLatin1(
     "<qt text=\"%1\" bgcolor=\"%2\">%3</qt>")
     .arg(mTextColor.name())
     .arg(mBaseColor.name())
     .arg(i18n(mDatabase->tip().utf8()));


      currentTip = fixTip(currentTip);
      mTipText->setText(currentTip);
      mTipText->setContentsPos(0, 0);
  }

  void KTipDialog::nextTip()
  {
      mDatabase->nextTip();
      TQString currentTip = TQString::fromLatin1(
        "<qt text=\"%1\" bgcolor=\"%2\">%3</qt>")
        .arg(mTextColor.name())
        .arg(mBaseColor.name())
        .arg(i18n(mDatabase->tip().utf8()));


      currentTip = fixTip(currentTip);
      mTipText->setText(currentTip);
      mTipText->setContentsPos(0, 0);
  }

  void KTipDialog::showOnStart(bool on)
  {
      setShowOnStart(on);
  }

  void KTipDialog::setShowOnStart(bool on)
  {
      TDEConfigGroup config(kapp->config(), "TipOfDay");
      config.writeEntry("RunOnStart", on);
      config.sync();
  }

  bool KTipDialog::eventFilter(TQObject *o, TQEvent *e)
  {
    if (TQT_BASE_OBJECT(o) == TQT_BASE_OBJECT(mTipText) && e->type()== TQEvent::KeyPress &&
		(((TQKeyEvent *)e)->key() == Key_Return ||
		((TQKeyEvent *)e)->key() == Key_Space ))
		accept();

	// If the user presses Return or Space, we close the dialog as if the
	// default button was pressed even if the KTextBrowser has the keyboard
	// focus. This could have the bad side-effect that the user cannot use the
	// keyboard to open urls in the KTextBrowser, so we just let it handle
	// the key event _additionally_. (Antonio)

	return TQWidget::eventFilter( o, e );
}

void KTipDialog::virtual_hook( int id, void* data )
{
	KDialog::virtual_hook( id, data );
}

#include "ktip.moc"