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