]> git.lyx.org Git - lyx.git/blob - src/insets/InsetHyperlink.cpp
Fix IM window position for a new window (#13094)
[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 "LyX.h"
21 #include "output_docbook.h"
22 #include "output_xhtml.h"
23 #include "Statistics.h"
24 #include "texstream.h"
25 #include "xml.h"
26
27 #include "support/debug.h"
28 #include "support/docstream.h"
29 #include "support/FileName.h"
30 #include "support/filetools.h"
31 #include "support/gettext.h"
32 #include "support/lstrings.h"
33 #include "support/qstring_helpers.h"
34
35 #include "frontends/alert.h"
36
37 #include <QtGui/QDesktopServices>
38 #include <QUrl>
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         // Ctrl + click: open hyperlink
97         if (cmd.action() == LFUN_MOUSE_RELEASE && cmd.modifier() == ControlModifier) {
98                 lyx::dispatch(FuncRequest(LFUN_INSET_EDIT));
99                 return;
100         }
101
102         switch (cmd.action()) {
103
104         case LFUN_INSET_EDIT:
105                 viewTarget();
106                 break;
107
108         default:
109                 InsetCommand::doDispatch(cur, cmd);
110                 break;
111         }
112 }
113
114
115 bool InsetHyperlink::getStatus(Cursor & cur, FuncRequest const & cmd,
116                 FuncStatus & flag) const
117 {
118         switch (cmd.action()) {
119         case LFUN_INSET_EDIT: {
120                 docstring const & utype = getParam("type");
121                 QUrl url(toqstr(getParam("target")),QUrl::StrictMode);
122                 bool url_valid = utype.empty() && url.isValid();
123                 flag.setEnabled(url_valid || utype == "file:");
124                 return true;
125                 }
126
127         default:
128                 return InsetCommand::getStatus(cur, cmd, flag);
129         }
130 }
131
132
133 void InsetHyperlink::viewTarget() const
134 {
135         if (getParam("type").empty()) { //==Web
136                 QUrl url(toqstr(getParam("target")),QUrl::StrictMode);
137                 if (!QDesktopServices::openUrl(url))
138                         LYXERR0("Unable to open URL!");
139         } else if (getParam("type") == "file:") {
140                 FileName url = makeAbsPath(to_utf8(getParam("target")), buffer().filePath());
141                 string const format = theFormats().getFormatFromFile(url);
142                 theFormats().view(buffer(), url, format);
143         }
144 }
145
146
147 docstring makeURL(docstring const & url, docstring const & type) {
148         if (type == "other" ||
149                         (!type.empty() && url.find(type) == 0))
150                 return url;
151         return type + url;
152 }
153
154
155 void InsetHyperlink::latex(otexstream & os,
156                            OutputParams const & runparams) const
157 {
158         docstring url   = getParam("target");
159         docstring name  = getParam("name");
160         docstring const & utype = getParam("type");
161         static char_type const chars_url[2] = {'%', '#'};
162
163         // For the case there is no name given, the target is set as name.
164         // Do this before !url.empty() and !name.empty() to handle characters
165         // such as % correctly.
166         if (name.empty())
167                 name = url;
168
169         if (!url.empty()) {
170                 // Use URI/URL-style percent-encoded string (hexadecimal).
171                 // We exclude some characters that must not be transformed
172                 // in hrefs: % # / : ? = & ! * ' ( ) ; @ + $ , [ ]
173                 // or that we need to treat manually: \.
174                 url = to_percent_encoding(url, from_ascii("%#\\/:?=&!*'();@+$,[]"));
175                 // We handle \ manually since \\ is valid
176                 for (size_t i = 0, pos;
177                         (pos = url.find('\\', i)) != string::npos;
178                         i = pos + 2) {
179                         if (url[pos + 1] != '\\')
180                                 url.replace(pos, 1, from_ascii("%5C"));
181                 }
182
183                 // The characters in chars_url[] need to be escaped in the url
184                 // field because otherwise LaTeX will fail when the hyperlink is
185                 // within an argument of another command, e.g. in a \footnote. It
186                 // is important that they are escaped as "\#" and not as "\#{}".
187                 // FIXME this is not necessary in outside of commands.
188                 for (int k = 0; k < 2; k++)
189                         for (size_t i = 0, pos;
190                                 (pos = url.find(chars_url[k], i)) != string::npos;
191                                 i = pos + 2)
192                                 url.replace(pos, 1, from_ascii("\\") + chars_url[k]);
193
194                 // add "http://" when the type is web (type = empty)
195                 // and no "://" is given
196                 if (url.find(from_ascii("://")) == string::npos
197                         && utype.empty())
198                         url = from_ascii("http://") + url;
199
200         } // end if (!url.empty())
201
202         if (!name.empty()) {
203                 name = params().prepareCommand(runparams, name,
204                                         ParamInfo::HANDLING_LATEXIFY);
205                 // replace the tilde by the \sim character as suggested in the
206                 // LaTeX FAQ for URLs
207                 if (getParam("literal") != "true") {
208                         docstring const sim = from_ascii("$\\sim$");
209                         for (size_t i = 0, pos;
210                                 (pos = name.find('~', i)) != string::npos;
211                                 i = pos + 1)
212                                 name.replace(pos, 1, sim);
213                 }
214         }
215
216         if (runparams.moving_arg)
217                 os << "\\protect";
218
219         // output the ready \href command
220         os << "\\href{" << makeURL(url, utype) << "}{" << name << '}';
221 }
222
223
224 int InsetHyperlink::plaintext(odocstringstream & os,
225         OutputParams const &, size_t) const
226 {
227         odocstringstream oss;
228
229         oss << '[' << getParam("target");
230         if (getParam("name").empty())
231                 oss << ']';
232         else
233                 oss << "||" << getParam("name") << ']';
234
235         docstring const str = oss.str();
236         os << str;
237         return str.size();
238 }
239
240
241 void InsetHyperlink::docbook(XMLStream & xs, OutputParams const &) const
242 {
243         docstring target = subst(getParam("target"), from_ascii("&"), from_ascii("&amp;")) ;
244         xs << xml::StartTag("link", "xlink:href=\"" + makeURL(target, getParam("type")) + "\"");
245         xs << xml::escapeString(getParam("name"));
246         xs << xml::EndTag("link");
247 }
248
249
250 docstring InsetHyperlink::xhtml(XMLStream & xs, OutputParams const &) const
251 {
252         docstring const & target =
253                 xml::escapeString(getParam("target"), XMLStream::ESCAPE_AND);
254         docstring const & name = getParam("name");
255         xs << xml::StartTag("a", to_utf8("href=\"" + makeURL(target, getParam("type")) + "\""));
256         xs << (name.empty() ? target : name);
257         xs << xml::EndTag("a");
258         return docstring();
259 }
260
261
262 void InsetHyperlink::toString(odocstream & os) const
263 {
264         odocstringstream ods;
265         plaintext(ods, OutputParams(0), INT_MAX);
266         os << ods.str();
267 }
268
269
270 void InsetHyperlink::forOutliner(docstring & os, size_t const, bool const) const
271 {
272         docstring const & n = getParam("name");
273         if (!n.empty()) {
274                 os += n;
275                 return;
276         }
277         os += getParam("target");
278 }
279
280
281 docstring InsetHyperlink::toolTip(BufferView const & /*bv*/, int /*x*/, int /*y*/) const
282 {
283         docstring const & url = getParam("target");
284         docstring const & type = getParam("type");
285         docstring guitype = _("www");
286         if (type == "mailto:")
287                 guitype = _("email");
288         else if (type == "file:")
289                 guitype = _("file");
290         else if (type == "other")
291                 guitype = _("other[[Hyperlink Type]]");
292         return bformat(_("Hyperlink (%1$s) to %2$s"), guitype, url);
293 }
294
295
296 void InsetHyperlink::validate(LaTeXFeatures & features) const
297 {
298         features.require("hyperref");
299         InsetCommand::validate(features);
300 }
301
302
303 void InsetHyperlink::updateStatistics(Statistics & stats) const
304 {
305         stats.update(getParam("name"));
306 }
307
308
309 string InsetHyperlink::contextMenuName() const
310 {
311         return "context-hyperlink";
312 }
313
314
315 } // namespace lyx