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