]> git.lyx.org Git - lyx.git/blob - src/insets/InsetHyperlink.cpp
66bfa6d18460462b5dd977d518f2588fb0dab71c
[lyx.git] / src / insets / InsetHyperlink.cpp
1 /**
2  * \file InsetHyperlink.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author José Matos
7  * \author Uwe Stöhr
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13 #include "InsetHyperlink.h"
14
15 #include "Buffer.h"
16 #include "Format.h"
17 #include "FuncRequest.h"
18 #include "FuncStatus.h"
19 #include "LaTeXFeatures.h"
20 #include "OutputParams.h"
21 #include "output_docbook.h"
22 #include "output_xhtml.h"
23 #include "xml.h"
24 #include "texstream.h"
25
26 #include "support/debug.h"
27 #include "support/docstream.h"
28 #include "support/FileName.h"
29 #include "support/filetools.h"
30 #include "support/gettext.h"
31 #include "support/lstrings.h"
32 #include "support/qstring_helpers.h"
33
34 #include "frontends/alert.h"
35
36 #include <QtGui/QDesktopServices>
37 #include <QUrl>
38
39 using namespace std;
40 using namespace lyx::support;
41
42 namespace lyx {
43
44
45 InsetHyperlink::InsetHyperlink(Buffer * buf, InsetCommandParams const & p)
46         : InsetCommand(buf, p)
47 {}
48
49
50 ParamInfo const & InsetHyperlink::findInfo(string const & /* cmdName */)
51 {
52         static ParamInfo param_info_;
53         if (param_info_.empty()) {
54                 param_info_.add("name", ParamInfo::LATEX_OPTIONAL,
55                                 ParamInfo::HANDLING_LATEXIFY);
56                 param_info_.add("target", ParamInfo::LATEX_REQUIRED);
57                 param_info_.add("type", ParamInfo::LATEX_REQUIRED);
58                 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
59         }
60         return param_info_;
61 }
62
63
64 docstring InsetHyperlink::screenLabel() const
65 {
66         // TODO: replace with unicode hyperlink character = U+1F517
67         docstring const temp = _("Hyperlink: ");
68
69         docstring url;
70
71         url += getParam("name");
72         if (url.empty()) {
73                 url += getParam("target");
74
75                 // elide if long and no name was provided
76                 if (url.length() > 30) {
77                         docstring end = url.substr(url.length() - 17, url.length());
78                         support::truncateWithEllipsis(url, 13);
79                         url += end;
80                 }
81         } else {
82                 // elide if long (approx number of chars in line of article class)
83                 if (url.length() > 80) {
84                         docstring end = url.substr(url.length() - 67, url.length());
85                         support::truncateWithEllipsis(url, 13);
86                         url += end;
87                 }
88         }
89         return temp + url;
90 }
91
92
93 void InsetHyperlink::doDispatch(Cursor & cur, FuncRequest & cmd)
94 {
95         switch (cmd.action()) {
96
97         case LFUN_INSET_EDIT:
98                 viewTarget();
99                 break;
100
101         default:
102                 InsetCommand::doDispatch(cur, cmd);
103                 break;
104         }
105 }
106
107
108 bool InsetHyperlink::getStatus(Cursor & cur, FuncRequest const & cmd,
109                 FuncStatus & flag) const
110 {
111         switch (cmd.action()) {
112         case LFUN_INSET_EDIT: {
113                 QUrl url(toqstr(getParam("target")),QUrl::StrictMode);
114                 bool url_valid = getParam("type").empty() && url.isValid();
115
116                 flag.setEnabled(url_valid || getParam("type") == "file:");
117                 return true;
118                 }
119
120         default:
121                 return InsetCommand::getStatus(cur, cmd, flag);
122         }
123 }
124
125
126 void InsetHyperlink::viewTarget() const
127 {
128         if (getParam("type").empty()) { //==Web
129                 QUrl url(toqstr(getParam("target")),QUrl::StrictMode);
130                 if (!QDesktopServices::openUrl(url))
131                         LYXERR0("Unable to open URL!");
132
133         } else if (getParam("type") == "file:") {
134                 FileName url = makeAbsPath(to_utf8(getParam("target")), buffer().filePath());
135                 string const format = theFormats().getFormatFromFile(url);
136                 theFormats().view(buffer(), url, format);
137         }
138 }
139
140
141 void InsetHyperlink::latex(otexstream & os,
142                            OutputParams const & runparams) const
143 {
144         docstring url = getParam("target");
145         docstring name = getParam("name");
146         static char_type const chars_url[2] = {'%', '#'};
147
148         // For the case there is no name given, the target is set as name.
149         // Do this before !url.empty() and !name.empty() to handle characters
150         // such as % correctly.
151         if (name.empty())
152                 name = url;
153
154         if (!url.empty()) {
155                 // Use URI/URL-style percent-encoded string (hexadecimal).
156                 // We exclude some characters that must not be transformed
157                 // in hrefs: % # / : ? = & ! * ' ( ) ; @ + $ , [ ]
158                 // or that we need to treat manually: \.
159                 url = to_percent_encoding(url, from_ascii("%#\\/:?=&!*'();@+$,[]"));
160                 // We handle \ manually since \\ is valid
161                 for (size_t i = 0, pos;
162                         (pos = url.find('\\', i)) != string::npos;
163                         i = pos + 2) {
164                         if (url[pos + 1] != '\\')
165                                 url.replace(pos, 1, from_ascii("%5C"));
166                 }
167
168                 // The characters in chars_url[] need to be escaped in the url
169                 // field because otherwise LaTeX will fail when the hyperlink is
170                 // within an argument of another command, e.g. in a \footnote. It
171                 // is important that they are escaped as "\#" and not as "\#{}".
172                 // FIXME this is not necessary in outside of commands.
173                 for (int k = 0; k < 2; k++)
174                         for (size_t i = 0, pos;
175                                 (pos = url.find(chars_url[k], i)) != string::npos;
176                                 i = pos + 2)
177                                 url.replace(pos, 1, from_ascii("\\") + chars_url[k]);
178
179                 // add "http://" when the type is web (type = empty)
180                 // and no "://" or "run:" is given
181                 docstring type = getParam("type");
182                 if (url.find(from_ascii("://")) == string::npos
183                         && url.find(from_ascii("run:")) == string::npos
184                         && type.empty())
185                         url = from_ascii("http://") + url;
186
187         } // end if (!url.empty())
188
189         if (!name.empty()) {
190                 name = params().prepareCommand(runparams, name,
191                                         ParamInfo::HANDLING_LATEXIFY);
192                 // replace the tilde by the \sim character as suggested in the
193                 // LaTeX FAQ for URLs
194                 if (getParam("literal") != from_ascii("true")) {
195                         docstring const sim = from_ascii("$\\sim$");
196                         for (size_t i = 0, pos;
197                                 (pos = name.find('~', i)) != string::npos;
198                                 i = pos + 1)
199                                 name.replace(pos, 1, sim);
200                 }
201         }
202
203         if (runparams.moving_arg)
204                 os << "\\protect";
205
206         // output the ready \href command
207         os << "\\href{" << getParam("type") << url << "}{" << name << '}';
208 }
209
210
211 int InsetHyperlink::plaintext(odocstringstream & os,
212         OutputParams const &, size_t) const
213 {
214         odocstringstream oss;
215
216         oss << '[' << getParam("target");
217         if (getParam("name").empty())
218                 oss << ']';
219         else
220                 oss << "||" << getParam("name") << ']';
221
222         docstring const str = oss.str();
223         os << str;
224         return str.size();
225 }
226
227
228 void InsetHyperlink::docbook(XMLStream & xs, OutputParams const &) const
229 {
230         xs << xml::StartTag("link", "xlink:href=\"" + subst(getParam("target"), from_ascii("&"), from_ascii("&amp;")) + "\"");
231         xs << xml::escapeString(getParam("name"));
232         xs << xml::EndTag("link");
233 }
234
235
236 docstring InsetHyperlink::xhtml(XMLStream & xs, OutputParams const &) const
237 {
238         docstring const & target =
239                 xml::escapeString(getParam("target"), XMLStream::ESCAPE_AND);
240         docstring const & name   = getParam("name");
241         xs << xml::StartTag("a", to_utf8("href=\"" + target + "\""));
242         xs << (name.empty() ? target : name);
243         xs << xml::EndTag("a");
244         return docstring();
245 }
246
247
248 void InsetHyperlink::toString(odocstream & os) const
249 {
250         odocstringstream ods;
251         plaintext(ods, OutputParams(0), INT_MAX);
252         os << ods.str();
253 }
254
255
256 void InsetHyperlink::forOutliner(docstring & os, size_t const, bool const) const
257 {
258         docstring const & n = getParam("name");
259         if (!n.empty()) {
260                 os += n;
261                 return;
262         }
263         os += getParam("target");
264 }
265
266
267 docstring InsetHyperlink::toolTip(BufferView const & /*bv*/, int /*x*/, int /*y*/) const
268 {
269         docstring url = getParam("target");
270         docstring type = getParam("type");
271         docstring guitype = _("www");
272         if (type == "mailto:")
273                 guitype = _("email");
274         else if (type == "file:")
275                 guitype = _("file");
276         return bformat(_("Hyperlink (%1$s) to %2$s"), guitype, url);
277 }
278
279
280 void InsetHyperlink::validate(LaTeXFeatures & features) const
281 {
282         features.require("hyperref");
283         InsetCommand::validate(features);
284 }
285
286
287 string InsetHyperlink::contextMenuName() const
288 {
289         return "context-hyperlink";
290 }
291
292
293 } // namespace lyx