summaryrefslogtreecommitdiffstats
path: root/konversation/src/topiclabel.cpp
blob: 94c46139a06ded5ea23dc1cf9214bd9f6577b327 (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
/*
  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.
*/

/*
  Copyright (C) 2004 Peter Simonsson <psn@linux.se>
  Copyright (C) 2006-2008 Eike Hein <hein@kde.org>
*/

#include "topiclabel.h"
#include "konversationapplication.h"
#include "connectionmanager.h"
#include "server.h"
#include "common.h"
#include "channel.h"

#include <tqsimplerichtext.h>
#include <tqtooltip.h>
#include <tqclipboard.h>

#include <krun.h>
#include <kprocess.h>
#include <kshell.h>
#include <kurldrag.h>
#include <kstringhandler.h>
#include <tdeglobal.h>
#include <kdebug.h>
#include <tdepopupmenu.h>
#include <kiconloader.h>
#include <kbookmarkmanager.h>
#include <tdeversion.h>


namespace Konversation
{

    TopicLabel::TopicLabel(TQWidget *parent, const char *name)
        : KActiveLabel(parent, name)
    {
        setWrapPolicy(TQTextEdit::AtWordOrDocumentBoundary);
        setFocusPolicy(TQWidget::ClickFocus);

        m_isOnChannel = false;
        m_copyUrlMenu = false;
        mousePressed=false;

        m_popup = new TQPopupMenu(this,"topiclabel_context_menu");
        m_popup->insertItem(SmallIconSet("edit-copy"),i18n("&Copy"),Copy);
        m_popup->insertItem(i18n("Select All"),SelectAll);

        setupChannelPopupMenu();

        connect(this, TQT_SIGNAL(highlighted(const TQString&)), this, TQT_SLOT(highlightedSlot(const TQString&)));
    }

    TopicLabel::~TopicLabel()
    {
    }

    TQSize TopicLabel::minimumSizeHint() const
    {
        int minHeight = fontMetrics().lineSpacing() + fontMetrics().descent();
        return TQSize(0, minHeight);
    }

    TQSize TopicLabel::sizeHint() const
    {
        int minHeight = fontMetrics().lineSpacing() + fontMetrics().descent();
        return TQSize(0, minHeight);
    }

    void TopicLabel::setServer(Server* server)
    {
        m_server = server;
    }

    void TopicLabel::contentsMousePressEvent(TQMouseEvent *e)
    {
        if (e->button()==TQt::LeftButton)
        {
            pressPosition=e->pos();
            urlToDrag = anchorAt(pressPosition);
            // HACK Replace % with \x03 in the url to keep TQt from doing stupid things
            urlToDrag = urlToDrag.replace ('\x03', "%");
            // Hack to counter the fact that we're given an decoded url
            urlToDrag = KURL::fromPathOrURL(urlToDrag).url();
            if (!urlToDrag.isNull())
            {
                mousePressed=true;
                return;
            }
        }
        KActiveLabel::contentsMousePressEvent(e);
    }

    void TopicLabel::contentsMouseReleaseEvent(TQMouseEvent *e)
    {
        if (e->button()==TQt::LeftButton)
        {
            if (mousePressed) openLink(urlToDrag);
            mousePressed=false;
        }
        KActiveLabel::contentsMouseReleaseEvent(e);
    }

    void TopicLabel::contentsMouseMoveEvent(TQMouseEvent *e)
    {
        if (mousePressed && (pressPosition-e->pos()).manhattanLength() > TQApplication::startDragDistance())
        {
            mousePressed=false;
            removeSelection();
            KURL ux = KURL::fromPathOrURL(urlToDrag);
            //FIXME consistent IRC URL serialization
            if (urlToDrag.startsWith("##")) ux=TQString("irc://%1:%2/%3").arg(m_server->getServerName()).
                    arg(m_server->getPort()).arg(urlToDrag.mid(2));
            KURLDrag* u=new KURLDrag(ux,viewport());
            u->drag();
        }
        KActiveLabel::contentsMouseMoveEvent(e);
    }

    void TopicLabel::leaveEvent(TQEvent*)
    {
       emit clearStatusBarTempText();
       m_lastStatusText = TQString();
    }

    void TopicLabel::openLink(const TQString& link)
    {
        if (!link.isEmpty())
        {
            if (link.startsWith("irc://"))
            {
                KonversationApplication* konvApp = static_cast<KonversationApplication*>(kapp);
                konvApp->getConnectionManager()->connectTo(Konversation::SilentlyReuseConnection, link);
            }
            else if (link.startsWith("#") && m_server && m_server->isConnected())
            {
                TQString channel(link);
                channel.replace("##","#");
                m_server->sendJoinCommand(channel);
            }
            // Always use KDE default mailer.
            else if (!Preferences::useCustomBrowser() || link.lower().startsWith("mailto:"))
            {
                new KRun(KURL::fromPathOrURL(link));
            }
            else
            {
                TQString cmd = Preferences::webBrowserCmd();
                cmd.replace("%u",KURL::fromPathOrURL(link).url());
                TDEProcess *proc = new TDEProcess;
                TQStringList cmdAndArgs = KShell::splitArgs(cmd);
                *proc << cmdAndArgs;
                //      This code will also work, but starts an extra shell process.
                //      kdDebug() << "IRCView::linkClickSlot(): cmd = " << cmd << endl;
                //      *proc << cmd;
                //      proc->setUseShell(true);
                proc->start(TDEProcess::DontCare);
                delete proc;
            }
        }
    }

    void TopicLabel::contentsContextMenuEvent(TQContextMenuEvent* ev)
    {
        bool block = contextMenu(ev);

        if(!block)
        {
            KActiveLabel::contentsContextMenuEvent(ev);
        }
    }

    bool TopicLabel::contextMenu(TQContextMenuEvent* ce)
    {
        if (m_isOnChannel)
        {
            m_channelPopup->exec(ce->globalPos());
            m_isOnChannel = false;
        }
        else
        {
            m_popup->setItemEnabled(Copy,(hasSelectedText()));

            int r = m_popup->exec(ce->globalPos());

            switch(r)
            {
                case -1:
                    // dummy. -1 means, no entry selected. we don't want -1to go in default, so
                    // we catch it here
                    break;
                case Copy:
                    copy();
                    break;
                case CopyUrl:
                {
                    TQClipboard *cb = TDEApplication::kApplication()->clipboard();
                    cb->setText(m_urlToCopy,TQClipboard::Selection);
                    cb->setText(m_urlToCopy,TQClipboard::Clipboard);
                    break;
                }
                case SelectAll:
                    selectAll();
                    break;
                case Bookmark:
                {
                    KBookmarkManager* bm = KBookmarkManager::userBookmarksManager();
                    KBookmarkGroup bg = bm->addBookmarkDialog(m_urlToCopy, TQString());
                    bm->save();
                    bm->emitChanged(bg);
                    break;
                }
                default:
                    break;
            }
        }
        return true;
    }

    void TopicLabel::setupChannelPopupMenu()
    {
        m_channelPopup = new TDEPopupMenu(this,"channel_context_menu");
        m_channelPopupId = m_channelPopup->insertTitle(m_currentChannel);
        m_channelPopup->insertItem(i18n("&Join"),Konversation::Join);
        m_channelPopup->insertItem(i18n("Get &user list"),Konversation::Names);
        m_channelPopup->insertItem(i18n("Get &topic"),Konversation::Topic);

        connect(m_channelPopup, TQT_SIGNAL(activated(int)), this, TQT_SIGNAL(popupCommand(int)));
    }

    void TopicLabel::setText(const TQString& text)
    {
        m_fullText = text;
        updateSqueezedText();
    }

    void TopicLabel::updateSqueezedText()
    {
        TQToolTip::remove(this);

        if (m_fullText.isEmpty())
        {
            KActiveLabel::setText(TQString());

            return;
        }

        TQFontMetrics fm(currentFont());
        TQString text = m_fullText;
        // text.replace("&", "&amp;"). Not needed as we do it in tagURLs
        text.replace("<", "\x0blt;"). // tagUrls will replace \x0b with &
            replace(">", "\x0bgt;");
        text = tagURLs(text, "", false);

        if(height() < (fm.lineSpacing() * 2))
        {
            text = rPixelSqueeze(text, visibleWidth() - 10);
            setWordWrap(NoWrap);
            TQToolTip::add(this, "<qt>" + TQStyleSheet::escape(m_fullText) + "</qt>");
        }
        else
        {
            setWordWrap(WidgetWidth);

            if(height() < contentsHeight())
            {
                TQToolTip::add(this, "<qt>" + TQStyleSheet::escape(m_fullText) + "</qt>");
            }
        }

        KActiveLabel::setText("<qt>" + text + "</qt>");
    }

    void TopicLabel::resizeEvent(TQResizeEvent* ev)
    {
        KActiveLabel::resizeEvent(ev);
        updateSqueezedText();
    }

    TQString TopicLabel::rPixelSqueeze(const TQString& text, uint maxPixels)
    {
        TQFontMetrics fm(currentFont());
        uint tw = textWidth(text, fm);

        if(tw > maxPixels)
        {
            TQString tmp = text;
            const uint em = fm.maxWidth();
            maxPixels -= fm.width("...");
            int len, delta;

            while((tw > maxPixels) && !tmp.isEmpty())
            {
                len = tmp.length();
                delta = (tw - maxPixels) / em;
                delta = kClamp(delta, 1, len);

                tmp.remove(len - delta, delta);
                tw = textWidth(tmp, fm);
            }

            return tmp.append("...");
        }

        return text;
    }

    uint TopicLabel::textWidth(const TQString& text, const TQFontMetrics& fm)
    {
        TQSimpleRichText richText("<qt>" + text + "</qt>", currentFont());
        richText.setWidth(fm.width(text));

        return richText.widthUsed();
    }

    void TopicLabel::highlightedSlot(const TQString& _link)
    {
        TQString link = KURL::fromPathOrURL(_link).url();
        //we just saw this a second ago.  no need to reemit.
        if (link == m_lastStatusText && !link.isEmpty())
            return;

        // remember current URL to overcome link clicking problems in TQTextBrowser
        m_highlightedURL = link;

        if (link.isEmpty())
        {
            if (!m_lastStatusText.isEmpty())
            {
                emit clearStatusBarTempText();
                m_lastStatusText = TQString();
            }
        } else {
            m_lastStatusText = link;
        }

        if (!link.startsWith("#"))
        {
            m_isOnChannel = false;

            if (!link.isEmpty()) {
                //link therefore != m_lastStatusText  so emit with this new text
                emit setStatusBarTempText(link);
            }
            if (link.isEmpty() && m_copyUrlMenu)
            {
                m_popup->removeItem(CopyUrl);
                m_popup->removeItem(Bookmark);
                m_copyUrlMenu = false;
            }
            else if (!link.isEmpty() && !m_copyUrlMenu)
            {
                m_popup->insertItem(SmallIcon("edit-copy"), i18n("Copy URL to Clipboard"), CopyUrl, 0);
                m_popup->insertItem(SmallIcon("bookmark"), i18n("Add to Bookmarks"), Bookmark, 1);
                m_copyUrlMenu = true;
                m_urlToCopy = link;
            }
        }
        else if (link.startsWith("##"))
        {
            m_currentChannel = link.mid(1);

            emit currentChannelChanged(m_currentChannel);

            TQString prettyId = m_currentChannel;

            if (prettyId.length()>15)
            {
                prettyId.truncate(15);
                prettyId.append("...");
            }

            m_channelPopup->changeTitle(m_channelPopupId,prettyId);
            m_isOnChannel = true;
            emit setStatusBarTempText(i18n("Join the channel %1").arg(m_currentChannel));
        }
    }
}

#include "topiclabel.moc"