]> cloud.milkyroute.net Git - dolphin.git/blob - src/urlnavigator.cpp
* Fixed a bug that caused dolphin to crash when clicking on the "Root" button
[dolphin.git] / src / urlnavigator.cpp
1 /***************************************************************************
2 * Copyright (C) 2006 by Peter Penz (<peter.penz@gmx.at>) *
3 * Copyright (C) 2006 by Aaron J. Seigo (<aseigo@kde.org>) *
4 * Copyright (C) 2006 by Patrice Tremblay *
5 * *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
10 * *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the *
18 * Free Software Foundation, Inc., *
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
20 ***************************************************************************/
21
22 #include "urlnavigator.h"
23
24 #include "bookmarkselector.h"
25 #include "dolphinsettings.h"
26 #include "dolphin_generalsettings.h"
27 #include "protocolcombo.h"
28 #include "urlnavigatorbutton.h"
29
30 #include <assert.h>
31
32 #include <kfileitem.h>
33 #include <kicon.h>
34 #include <klocale.h>
35 #include <kprotocolinfo.h>
36 #include <kurlcombobox.h>
37 #include <kurlcompletion.h>
38
39 #include <QApplication>
40 #include <QClipboard>
41 #include <QDir>
42 #include <QHBoxLayout>
43 #include <QLabel>
44 #include <QLineEdit>
45 #include <QMouseEvent>
46 #include <QToolButton>
47
48 UrlNavigator::HistoryElem::HistoryElem() :
49 m_url(),
50 m_currentFileName(),
51 m_contentsX(0),
52 m_contentsY(0)
53 {
54 }
55
56 UrlNavigator::HistoryElem::HistoryElem(const KUrl& url) :
57 m_url(url),
58 m_currentFileName(),
59 m_contentsX(0),
60 m_contentsY(0)
61 {
62 }
63
64 UrlNavigator::HistoryElem::~HistoryElem()
65 {
66 }
67
68 UrlNavigator::UrlNavigator(const KUrl& url,
69 QWidget* parent) :
70 QWidget(parent),
71 m_active(true),
72 m_showHiddenFiles(false),
73 m_historyIndex(0),
74 m_layout(0),
75 m_protocols(0),
76 m_protocolSeparator(0),
77 m_host(0),
78 m_filler(0)
79 {
80 m_layout = new QHBoxLayout();
81 m_layout->setSpacing(0);
82 m_layout->setMargin(0);
83
84 m_history.prepend(HistoryElem(url));
85
86 QFontMetrics fontMetrics(font());
87 setMinimumHeight(fontMetrics.height() + 10);
88
89 // intialize toggle button which switches between the breadcrumb view
90 // and the traditional view
91 m_toggleButton = new QToolButton();
92 m_toggleButton->setCheckable(true);
93 m_toggleButton->setAutoRaise(true);
94 m_toggleButton->setIcon(KIcon("editinput")); // TODO: is just a placeholder icon (?)
95 m_toggleButton->setFocusPolicy(Qt::NoFocus);
96 m_toggleButton->setMinimumHeight(minimumHeight());
97 connect(m_toggleButton, SIGNAL(clicked()),
98 this, SLOT(switchView()));
99 if (DolphinSettings::instance().generalSettings()->editableUrl()) {
100 m_toggleButton->toggle();
101 }
102
103 // initialize the bookmark selector
104 m_bookmarkSelector = new BookmarkSelector(this);
105 connect(m_bookmarkSelector, SIGNAL(bookmarkActivated(const KUrl&)),
106 this, SLOT(setUrl(const KUrl&)));
107
108 // initialize the path box of the traditional view
109 m_pathBox = new KUrlComboBox(KUrlComboBox::Directories, true, this);
110
111 KUrlCompletion* kurlCompletion = new KUrlCompletion(KUrlCompletion::DirCompletion);
112 m_pathBox->setCompletionObject(kurlCompletion);
113 m_pathBox->setAutoDeleteCompletionObject(true);
114
115 connect(m_pathBox, SIGNAL(returnPressed(const QString&)),
116 this, SLOT(slotReturnPressed(const QString&)));
117 connect(m_pathBox, SIGNAL(urlActivated(const KUrl&)),
118 this, SLOT(slotUrlActivated(const KUrl&)));
119
120 //connect(dolphinView, SIGNAL(redirection(const KUrl&, const KUrl&)),
121 // this, SLOT(slotRedirection(const KUrl&, const KUrl&)));
122
123 // Append a filler widget at the end, which automatically resizes to the
124 // maximum available width. This assures that the URL navigator uses the
125 // whole width, so that the clipboard content can be dropped.
126 m_filler = new QWidget();
127 m_filler->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
128
129 m_layout->addWidget(m_toggleButton);
130 m_layout->addWidget(m_bookmarkSelector);
131 m_layout->addWidget(m_pathBox);
132 m_layout->addWidget(m_filler);
133 setLayout(m_layout);
134
135 updateContent();
136 }
137
138 UrlNavigator::~UrlNavigator()
139 {
140 }
141
142 const KUrl& UrlNavigator::url() const
143 {
144 assert(!m_history.empty());
145 QLinkedList<HistoryElem>::const_iterator it = m_history.begin();
146 it += m_historyIndex;
147 return (*it).url();
148 }
149
150 KUrl UrlNavigator::url(int index) const
151 {
152 assert(index >= 0);
153 // keep scheme, hostname etc. maybe we will need this in the future
154 // for e.g. browsing ftp repositories.
155 QString pre(((QUrl)url()).toString(QUrl::RemovePath));
156 QString path(url().path());
157
158 if (!path.isEmpty()) {
159 if (index == 0) //prevent the last "/" from being stripped
160 path = "/"; //or we end up with an empty path
161 else
162 path = path.section('/', 0, index);
163 }
164
165 return KUrl(pre + path);
166 }
167
168 const QLinkedList<UrlNavigator::HistoryElem>& UrlNavigator::history(int& index) const
169 {
170 index = m_historyIndex;
171 return m_history;
172 }
173
174 void UrlNavigator::goBack()
175 {
176 updateHistoryElem();
177
178 const int count = m_history.count();
179 if (m_historyIndex < count - 1) {
180 ++m_historyIndex;
181 updateContent();
182 emit urlChanged(url());
183 emit historyChanged();
184 }
185 }
186
187 void UrlNavigator::goForward()
188 {
189 if (m_historyIndex > 0) {
190 --m_historyIndex;
191 updateContent();
192 emit urlChanged(url());
193 emit historyChanged();
194 }
195 }
196
197 void UrlNavigator::goUp()
198 {
199 setUrl(url().upUrl());
200 }
201
202 void UrlNavigator::goHome()
203 {
204 setUrl(DolphinSettings::instance().generalSettings()->homeUrl());
205 }
206
207 void UrlNavigator::setUrlEditable(bool editable)
208 {
209 if (isUrlEditable() != editable) {
210 m_toggleButton->toggle();
211 switchView();
212 }
213 }
214
215 bool UrlNavigator::isUrlEditable() const
216 {
217 return m_toggleButton->isChecked();
218 }
219
220 void UrlNavigator::editUrl(bool editOrBrowse)
221 {
222 setUrlEditable(editOrBrowse);
223 if (editOrBrowse) {
224 m_pathBox->setFocus();
225 }
226 }
227
228 void UrlNavigator::setActive(bool active)
229 {
230 if (active != m_active) {
231 m_active = active;
232 update();
233 if (active) {
234 emit activated();
235 }
236 }
237 }
238
239 void UrlNavigator::setShowHiddenFiles( bool show )
240 {
241 m_showHiddenFiles = show;
242 }
243
244 void UrlNavigator::dropUrls(const KUrl::List& urls,
245 const KUrl& destination)
246 {
247 emit urlsDropped(urls, destination);
248 }
249
250 void UrlNavigator::setUrl(const KUrl& url)
251 {
252 QString urlStr(url.pathOrUrl());
253
254 // TODO: a patch has been submitted by Filip Brcic which adjusts
255 // the URL for tar and zip files. See https://bugs.kde.org/show_bug.cgi?id=142781
256 // for details. The URL navigator part of the patch has not been committed yet,
257 // as the URL navigator will be subject of change and
258 // we might think of a more generic approach to check the protocol + MIME type for
259 // this use case.
260
261 //kDebug() << "setUrl(" << url << ")" << endl;
262 if ( urlStr.length() > 0 && urlStr.at(0) == '~') {
263 // replace '~' by the home directory
264 urlStr.remove(0, 1);
265 urlStr.insert(0, QDir::home().path());
266 }
267
268 const KUrl transformedUrl(urlStr);
269
270 if (m_historyIndex > 0) {
271 // Check whether the previous element of the history has the same Url.
272 // If yes, just go forward instead of inserting a duplicate history
273 // element.
274 QLinkedList<HistoryElem>::const_iterator it = m_history.begin();
275 it += m_historyIndex - 1;
276 const KUrl& nextUrl = (*it).url();
277 if (transformedUrl == nextUrl) {
278 goForward();
279 // kDebug() << "goin' forward in history" << endl;
280 return;
281 }
282 }
283
284 QLinkedList<HistoryElem>::iterator it = m_history.begin() + m_historyIndex;
285 const KUrl& currUrl = (*it).url();
286 if (currUrl == transformedUrl) {
287 // don't insert duplicate history elements
288 // kDebug() << "currUrl == transformedUrl" << endl;
289 return;
290 }
291
292 updateHistoryElem();
293 m_history.insert(it, HistoryElem(transformedUrl));
294
295 updateContent();
296
297 emit urlChanged(transformedUrl);
298 emit historyChanged();
299
300 // Prevent an endless growing of the history: remembering
301 // the last 100 Urls should be enough...
302 if (m_historyIndex > 100) {
303 m_history.erase(m_history.begin());
304 --m_historyIndex;
305 }
306
307 /* kDebug() << "history starting ====================" << endl;
308 int i = 0;
309 for (QValueListIterator<UrlNavigator::HistoryElem> it = m_history.begin();
310 it != m_history.end();
311 ++it, ++i)
312 {
313 kDebug() << i << ": " << (*it).url() << endl;
314 }
315 kDebug() << "history done ========================" << endl;*/
316
317 requestActivation();
318 }
319
320 void UrlNavigator::requestActivation()
321 {
322 setActive(true);
323 }
324
325 void UrlNavigator::storeContentsPosition(int x, int y)
326 {
327 QLinkedList<HistoryElem>::iterator it = m_history.begin() + m_historyIndex;
328 (*it).setContentsX(x);
329 (*it).setContentsY(y);
330 }
331
332 void UrlNavigator::keyReleaseEvent(QKeyEvent* event)
333 {
334 QWidget::keyReleaseEvent(event);
335 if (isUrlEditable() && (event->key() == Qt::Key_Escape)) {
336 setUrlEditable(false);
337 }
338 }
339
340 void UrlNavigator::mouseReleaseEvent(QMouseEvent* event)
341 {
342 if (event->button() == Qt::MidButton) {
343 QClipboard* clipboard = QApplication::clipboard();
344 const QMimeData* mimeData = clipboard->mimeData();
345 if (mimeData->hasText()) {
346 const QString text = mimeData->text();
347 setUrl(KUrl(text));
348 }
349 }
350 QWidget::mouseReleaseEvent(event);
351 }
352
353 void UrlNavigator::slotReturnPressed(const QString& text)
354 {
355 // Parts of the following code have been taken
356 // from the class KateFileSelector located in
357 // kate/app/katefileselector.hpp of Kate.
358 // Copyright (C) 2001 Christoph Cullmann <cullmann@kde.org>
359 // Copyright (C) 2001 Joseph Wenninger <jowenn@kde.org>
360 // Copyright (C) 2001 Anders Lund <anders.lund@lund.tdcadsl.dk>
361
362 KUrl typedUrl(text);
363 if (typedUrl.hasPass()) {
364 typedUrl.setPass(QString());
365 }
366
367 QStringList urls = m_pathBox->urls();
368 urls.removeAll(typedUrl.url());
369 urls.prepend(typedUrl.url());
370 m_pathBox->setUrls(urls, KUrlComboBox::RemoveBottom);
371
372 setUrl(typedUrl);
373 // The URL might have been adjusted by UrlNavigator::setUrl(), hence
374 // synchronize the result in the path box.
375 m_pathBox->setUrl(url());
376 }
377
378 void UrlNavigator::slotUrlActivated(const KUrl& url)
379 {
380 setUrl(url);
381 }
382
383 void UrlNavigator::slotRemoteHostActivated()
384 {
385 KUrl u = url();
386
387 QString host = m_host->text();
388 QString user;
389
390 int marker = host.indexOf("@");
391 if (marker != -1)
392 {
393 user = host.left(marker);
394 u.setUser(user);
395 host = host.right(host.length() - marker - 1);
396 }
397
398 marker = host.indexOf("/");
399 if (marker != -1)
400 {
401 u.setPath(host.right(host.length() - marker));
402 host.truncate(marker);
403 }
404 else
405 {
406 u.setPath("");
407 }
408
409 if (m_protocols->currentProtocol() != u.protocol() ||
410 host != u.host() ||
411 user != u.user())
412 {
413 u.setProtocol(m_protocols->currentProtocol());
414 u.setHost(m_host->text());
415
416 //TODO: get rid of this HACK for file:///!
417 if (u.protocol() == "file")
418 {
419 u.setHost("");
420 if (u.path().isEmpty())
421 {
422 u.setPath("/");
423 }
424 }
425
426 setUrl(u);
427 }
428 }
429
430 void UrlNavigator::slotProtocolChanged(const QString& protocol)
431 {
432 KUrl url;
433 url.setProtocol(protocol);
434 //url.setPath(KProtocolInfo::protocolClass(protocol) == ":local" ? "/" : "");
435 url.setPath("/");
436 QLinkedList<UrlNavigatorButton*>::const_iterator it = m_navButtons.begin();
437 const QLinkedList<UrlNavigatorButton*>::const_iterator itEnd = m_navButtons.end();
438 while (it != itEnd) {
439 (*it)->close();
440 (*it)->deleteLater();
441 ++it;
442 }
443 m_navButtons.clear();
444
445 if (KProtocolInfo::protocolClass(protocol) == ":local") {
446 setUrl(url);
447 }
448 else {
449 if (!m_host) {
450 m_protocolSeparator = new QLabel("://", this);
451 appendWidget(m_protocolSeparator);
452 m_host = new QLineEdit(this);
453 appendWidget(m_host);
454
455 connect(m_host, SIGNAL(lostFocus()),
456 this, SLOT(slotRemoteHostActivated()));
457 connect(m_host, SIGNAL(returnPressed()),
458 this, SLOT(slotRemoteHostActivated()));
459 }
460 else {
461 m_host->setText("");
462 }
463 m_protocolSeparator->show();
464 m_host->show();
465 m_host->setFocus();
466 }
467 }
468
469 void UrlNavigator::slotRedirection(const KUrl& oldUrl, const KUrl& newUrl)
470 {
471 // kDebug() << "received redirection to " << newUrl << endl;
472 kDebug() << "received redirection from " << oldUrl << " to " << newUrl << endl;
473 /* UrlStack::iterator it = m_urls.find(oldUrl);
474 if (it != m_urls.end())
475 {
476 m_urls.erase(++it, m_urls.end());
477 }
478
479 m_urls.append(newUrl);*/
480 }
481
482 void UrlNavigator::switchView()
483 {
484 updateContent();
485 if (isUrlEditable()) {
486 m_pathBox->setFocus();
487 }
488 else {
489 setUrl(m_pathBox->currentText());
490 }
491 emit requestActivation();
492 }
493
494 void UrlNavigator::updateHistoryElem()
495 {
496 assert(m_historyIndex >= 0);
497 const KFileItem* item = 0; // TODO: m_dolphinView->currentFileItem();
498 if (item != 0) {
499 QLinkedList<HistoryElem>::iterator it = m_history.begin() + m_historyIndex;
500 (*it).setCurrentFileName(item->name());
501 }
502 }
503
504 void UrlNavigator::updateContent()
505 {
506 m_bookmarkSelector->updateSelection(url());
507
508 m_toggleButton->setToolTip(QString());
509 QString path(url().pathOrUrl());
510
511 // TODO: prevent accessing the DolphinMainWindow out from this scope
512 //const QAction* action = dolphinView()->mainWindow()->actionCollection()->action("editable_location");
513 // TODO: registry of default shortcuts
514 //QString shortcut = action? action->shortcut().toString() : "Ctrl+L";
515 const QString shortcut = "Ctrl+L";
516
517 if (m_toggleButton->isChecked()) {
518 delete m_protocols; m_protocols = 0;
519 delete m_protocolSeparator; m_protocolSeparator = 0;
520 delete m_host; m_host = 0;
521 deleteButtons();
522 m_filler->hide();
523
524 m_toggleButton->setToolTip(i18n("Browse (%1, Escape)", shortcut));
525
526 setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
527 m_pathBox->show();
528 m_pathBox->setUrl(url());
529 }
530 else {
531 m_toggleButton->setToolTip(i18n("Edit location (%1)", shortcut));
532
533 setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
534 m_pathBox->hide();
535 m_filler->show();
536
537 // get the data from the currently selected bookmark
538 KBookmark bookmark = m_bookmarkSelector->selectedBookmark();
539 //int bookmarkIndex = m_bookmarkSelector->selectedIndex();
540
541 QString bookmarkPath;
542 if (bookmark.isNull()) {
543 // No bookmark is a part of the current Url.
544 // The following code tries to guess the bookmark
545 // path. E. g. "fish://root@192.168.0.2/var/lib" writes
546 // "fish://root@192.168.0.2" to 'bookmarkPath', which leads to the
547 // navigation indication 'Custom Path > var > lib".
548 int idx = path.indexOf(QString("//"));
549 idx = path.indexOf("/", (idx < 0) ? 0 : idx + 2);
550 bookmarkPath = (idx < 0) ? path : path.left(idx);
551 }
552 else {
553 bookmarkPath = bookmark.url().pathOrUrl();
554 }
555 const uint len = bookmarkPath.length();
556
557 // calculate the start point for the URL navigator buttons by counting
558 // the slashs inside the bookmark URL
559 int slashCount = 0;
560 for (uint i = 0; i < len; ++i) {
561 if (bookmarkPath.at(i) == QChar('/')) {
562 ++slashCount;
563 }
564 }
565 if ((len > 0) && bookmarkPath.at(len - 1) == QChar('/')) {
566 assert(slashCount > 0);
567 --slashCount;
568 }
569
570 if (!url().isLocalFile() && bookmark.isNull()) {
571 QString protocol = url().protocol();
572 if (!m_protocols) {
573 deleteButtons();
574 m_protocols = new ProtocolCombo(protocol, this);
575 appendWidget(m_protocols);
576 connect(m_protocols, SIGNAL(activated(const QString&)),
577 this, SLOT(slotProtocolChanged(const QString&)));
578 }
579 else {
580 m_protocols->setProtocol(protocol);
581 }
582 m_protocols->show();
583
584 if (KProtocolInfo::protocolClass(protocol) != ":local") {
585 QString hostText = url().host();
586
587 if (!url().user().isEmpty()) {
588 hostText = url().user() + '@' + hostText;
589 }
590
591 if (!m_host) {
592 m_protocolSeparator = new QLabel("://", this);
593 appendWidget(m_protocolSeparator);
594 m_host = new QLineEdit(hostText, this);
595 appendWidget(m_host);
596
597 connect(m_host, SIGNAL(lostFocus()),
598 this, SLOT(slotRemoteHostActivated()));
599 connect(m_host, SIGNAL(returnPressed()),
600 this, SLOT(slotRemoteHostActivated()));
601 }
602 else {
603 m_host->setText(hostText);
604 }
605 m_protocolSeparator->show();
606 m_host->show();
607 }
608 else {
609 delete m_protocolSeparator; m_protocolSeparator = 0;
610 delete m_host; m_host = 0;
611 }
612 }
613 else if (m_protocols) {
614 m_protocols->hide();
615
616 if (m_host) {
617 m_protocolSeparator->hide();
618 m_host->hide();
619 }
620 }
621
622 updateButtons(path, slashCount);
623 }
624 }
625
626 void UrlNavigator::updateButtons(const QString& path, int startIndex)
627 {
628 QLinkedList<UrlNavigatorButton*>::iterator it = m_navButtons.begin();
629 const QLinkedList<UrlNavigatorButton*>::const_iterator itEnd = m_navButtons.end();
630 bool createButton = false;
631
632 int idx = startIndex;
633 bool hasNext = true;
634 do {
635 createButton = (it == itEnd);
636
637 const QString dirName = path.section('/', idx, idx);
638 const bool isFirstButton = (idx == startIndex);
639 hasNext = isFirstButton || !dirName.isEmpty();
640 if (hasNext) {
641 QString text;
642 if (isFirstButton) {
643 // the first URL navigator button should get the name of the
644 // bookmark instead of the directory name
645 const KBookmark bookmark = m_bookmarkSelector->selectedBookmark();
646 text = bookmark.text();
647 if (text.isEmpty()) {
648 if (url().isLocalFile()) {
649 text = i18n("Custom Path");
650 }
651 else {
652 ++idx;
653 continue;
654 }
655 }
656 }
657
658 UrlNavigatorButton* button = 0;
659 if (createButton) {
660 button = new UrlNavigatorButton(idx, this);
661 appendWidget(button);
662 }
663 else {
664 button = *it;
665 button->setIndex(idx);
666 }
667
668 if (isFirstButton) {
669 button->setText(text);
670 }
671
672 if (createButton) {
673 button->show();
674 m_navButtons.append(button);
675 }
676 else {
677 ++it;
678 }
679 ++idx;
680 }
681 } while (hasNext);
682
683 // delete buttons which are not used anymore
684 QLinkedList<UrlNavigatorButton*>::iterator itBegin = it;
685 while (it != itEnd) {
686 (*it)->close();
687 (*it)->deleteLater();
688 ++it;
689 }
690 m_navButtons.erase(itBegin, m_navButtons.end());
691 }
692
693 void UrlNavigator::deleteButtons()
694 {
695 QLinkedList<UrlNavigatorButton*>::iterator itBegin = m_navButtons.begin();
696 QLinkedList<UrlNavigatorButton*>::iterator itEnd = m_navButtons.end();
697 QLinkedList<UrlNavigatorButton*>::iterator it = itBegin;
698 while (it != itEnd) {
699 (*it)->close();
700 (*it)->deleteLater();
701 ++it;
702 }
703 m_navButtons.erase(itBegin, itEnd);
704 }
705
706 void UrlNavigator::appendWidget(QWidget* widget)
707 {
708 m_layout->insertWidget(m_layout->count() - 1, widget);
709 }
710
711 #include "urlnavigator.moc"