Show more detailed error messages
[presencevnc] / src / mainwindow.cpp
1 /*
2    Presence VNC
3    Copyright (C) 2010 Christian Pulvermacher
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 2 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License along
16    with this program; if not, write to the Free Software Foundation, Inc.,
17    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18    */
19 #include "connectdialog.h"
20 #include "fullscreenexitbutton.h"
21 #include "keymenu.h"
22 #include "mainwindow.h"
23 #include "preferences.h"
24 #include "scrollarea.h"
25 #include "vncview.h"
26
27 #ifdef Q_WS_MAEMO_5
28 #include <QtMaemo5>
29 #include <QX11Info>
30 #include <QDBusConnection>
31
32 #include <mce/mode-names.h>
33 #include <mce/dbus-names.h>
34
35 #include <X11/Xlib.h>
36 #include <X11/Xatom.h>
37 #endif
38
39
40 MainWindow::MainWindow(QString url, int quality, int listen_port, bool view_only):
41     QMainWindow(0),
42     vnc_view(0),
43     scroll_area(new ScrollArea(0)),
44     input_toolbuttons(new QActionGroup(this)),
45     key_menu(0)
46 {
47     setWindowTitle("Presence VNC");
48 #ifdef Q_WS_MAEMO_5
49     setContextMenuPolicy(Qt::NoContextMenu);
50     setAttribute(Qt::WA_Maemo5StackedWindow);
51 #endif
52
53     migrateConfiguration();
54
55     //set up toolbar
56     toolbar = new QToolBar(0);
57     key_menu_button = input_toolbuttons->addAction(toolbar->addAction(QChar(0x2026), this, SLOT(showKeyMenu()))); //"..." button
58     key_menu_button->setCheckable(true); //used to indicate wether a modifier key is still pressed
59     input_toolbuttons->addAction(toolbar->addAction(tr("Tab"), this, SLOT(sendTab())));
60     input_toolbuttons->addAction(toolbar->addAction(tr("Esc"), this, SLOT(sendEsc())));
61     input_toolbuttons->addAction(toolbar->addAction(tr("PgUp"), this, SLOT(sendPgUp())));
62     input_toolbuttons->addAction(toolbar->addAction(tr("PgDn"), this, SLOT(sendPgDn())));
63 #ifdef Q_WS_MAEMO_5
64     input_toolbuttons->addAction(toolbar->addAction(QIcon("/usr/share/icons/hicolor/48x48/hildon/chat_enter.png"), "", this, SLOT(sendReturn())));
65     input_toolbuttons->addAction(toolbar->addAction(QIcon("/usr/share/icons/hicolor/48x48/hildon/control_keyboard.png"), "", this, SLOT(showInputPanel())));
66 #endif
67
68     QSettings settings;
69     zoom_slider = new QSlider(Qt::Horizontal, 0);
70     zoom_slider->setRange(0, 100);
71     connect(zoom_slider, SIGNAL(valueChanged(int)),
72             this, SLOT(setZoomLevel(int)));
73     connect(zoom_slider, SIGNAL(sliderReleased()),
74             this, SLOT(zoomSliderReleased()));
75     zoom_slider->setValue(settings.value("zoomlevel", 95).toInt());
76     toolbar->addWidget(zoom_slider);
77
78 #ifdef Q_WS_MAEMO_5
79     toolbar->addAction(QIcon("/usr/share/icons/hicolor/48x48/hildon/general_fullsize.png"), "", this, SLOT(toggleFullscreen()));
80 #else
81     toolbar->addAction(tr("Toggle Fullscreen"), this, SLOT(toggleFullscreen()));
82 #endif
83     addToolBar(toolbar);
84     toolbar->setVisible(settings.value("show_toolbar", true).toBool());
85     toolbar->setEnabled(false);
86
87     //set up menu
88     QAction *connect_action = new QAction(tr("Connect"), this);
89     disconnect_action = new QAction(tr("Disconnect"), this);
90     show_toolbar = new QAction(tr("Show toolbar"), this);
91     show_toolbar->setCheckable(true);
92     show_toolbar->setChecked(settings.value("show_toolbar", true).toBool());
93     QAction *pref_action = new QAction(tr("Preferences"), this);
94     QAction *about_action = new QAction(tr("About"), this);
95
96 #ifdef Q_WS_MAEMO_5
97     menuBar()->addAction(connect_action);
98     menuBar()->addAction(disconnect_action);
99     menuBar()->addAction(show_toolbar);
100     menuBar()->addAction(pref_action);
101     menuBar()->addAction(about_action);
102 #else
103     QMenu* session_menu = menuBar()->addMenu(tr("&Session"));
104     session_menu->addAction(connect_action);
105     session_menu->addAction(disconnect_action);
106     session_menu->addSeparator();
107     session_menu->addAction(pref_action);
108     session_menu->addSeparator();
109     session_menu->addAction(tr("&Quit"), this, SLOT(close()));
110
111     QMenu* view_menu = menuBar()->addMenu(tr("&View"));
112     view_menu->addAction(show_toolbar);
113
114     QMenu* help_menu = menuBar()->addMenu(tr("&Help"));
115     help_menu->addAction(about_action);
116 #endif
117
118     connect(about_action, SIGNAL(triggered()),
119             this, SLOT(about()));
120     connect(pref_action, SIGNAL(triggered()),
121             this, SLOT(showPreferences()));
122     connect(connect_action, SIGNAL(triggered()),
123             this, SLOT(showConnectDialog()));
124     connect(disconnect_action, SIGNAL(triggered()),
125             this, SLOT(disconnectFromHost()));
126     connect(show_toolbar, SIGNAL(toggled(bool)),
127             toolbar, SLOT(setVisible(bool)));
128     connect(show_toolbar, SIGNAL(toggled(bool)),
129             this, SLOT(updateScreenSpaceDelayed()));
130 #ifdef Q_WS_MAEMO_5
131     QDBusConnection::systemBus().connect("", MCE_SIGNAL_PATH, MCE_SIGNAL_IF, MCE_DISPLAY_SIG,
132                                          this, SLOT(displayStateChanged(QString)));
133 #endif
134
135     setCentralWidget(scroll_area);
136
137     FullScreenExitButton* fullscreen_exit_button = new FullScreenExitButton(this);
138     connect(fullscreen_exit_button, SIGNAL(clicked()),
139             this, SLOT(toggleFullscreen()));
140
141     grabZoomKeys(true);
142     reloadSettings();
143
144     if(url.isEmpty() and listen_port == 0) {
145         disconnect_action->setEnabled(false);
146         showConnectDialog();
147     } else {
148         connectToHost(url, quality, listen_port, view_only);
149     }
150 }
151
152 void MainWindow::grabZoomKeys(bool grab)
153 {
154 #ifdef Q_WS_MAEMO_5
155     unsigned long val = (grab)?1:0;
156     Atom atom = XInternAtom(QX11Info::display(), "_HILDON_ZOOM_KEY_ATOM", False);
157     if(!atom) {
158         qWarning("Couldn't get zoom key atom");
159         return;
160     }
161     XChangeProperty(QX11Info::display(), winId(), atom, XA_INTEGER,
162                     32, PropModeReplace, reinterpret_cast<unsigned char *>(&val), 1);
163 #endif
164 }
165
166 void MainWindow::closeEvent(QCloseEvent*)
167 {
168     grabZoomKeys(false);
169
170     QSettings settings;
171     settings.setValue("show_toolbar", show_toolbar->isChecked());
172     settings.setValue("zoomlevel", zoom_slider->value());
173     settings.sync();
174
175     hide();
176
177     disconnectFromHost();
178 }
179
180 void MainWindow::about()
181 {
182     QMessageBox::about(this, tr("About Presence VNC"),
183                        tr("<center><h1>Presence VNC 0.8</h1>\
184                 <p>A touchscreen friendly VNC client</p>\
185                 <p><a href=\"http://presencevnc.garage.maemo.org/\">http://presencevnc.garage.maemo.org/</a></p></center>\
186                 <small><p>&copy;2010 Christian Pulvermacher &lt;pulvermacher@gmx.de&gt;<br />\
187                 Based on KRDC, &copy; 2007-2008 Urs Wolfer<br />\
188                 and LibVNCServer, &copy; 2001-2003 Johannes E. Schindelin</p>\
189                 <p>This program is free software; License: <a href=\"http://www.gnu.org/licenses/gpl-2.0.html\">GNU GPL 2</a> or later.</p></small>"));
190 }
191
192 void MainWindow::showConnectDialog()
193 {
194     ConnectDialog *connect_dialog = new ConnectDialog(this);
195     connect(connect_dialog, SIGNAL(connectToHost(QString, int, int, bool)),
196             this, SLOT(connectToHost(QString, int, int, bool)));
197     connect_dialog->exec();
198     //ConnectDialog cleans up after itself
199 }
200
201 void MainWindow::connectToHost(QString url, int quality, int listen_port, bool view_only)
202 {
203     disconnectFromHost();
204
205     vnc_view = new VncView(this, url, RemoteView::Quality(quality), listen_port);
206     vnc_view->setViewOnly(view_only);
207
208     connect(vnc_view, SIGNAL(statusChanged(RemoteView::RemoteStatus)),
209             this, SLOT(statusChanged(RemoteView::RemoteStatus)));
210     connect(vnc_view, SIGNAL(errorMessage(QString, QString)),
211         scroll_area, SLOT(showMessage(QString, QString)));
212     scroll_area->setWidget(vnc_view);
213     vnc_view->start();
214     setWindowTitle(QString("Presence VNC - %1").arg(vnc_view->host()) + (view_only?tr(" [View Only]"):""));
215
216     disconnect_action->setEnabled(true);
217
218     //reset key menu
219     delete key_menu;
220     key_menu = new KeyMenu(this);
221 }
222
223 void MainWindow::disconnectFromHost()
224 {
225     if(!vnc_view)
226         return;
227
228     setWindowTitle("Presence VNC");
229     disconnect_action->setEnabled(false);
230     toolbar->setEnabled(false);
231     scroll_area->setWidget(0);
232
233     delete vnc_view;
234     vnc_view = 0;
235 }
236
237 void MainWindow::statusChanged(RemoteView::RemoteStatus status)
238 {
239     static RemoteView::RemoteStatus old_status = RemoteView::Disconnected;
240
241     switch(status) {
242     case RemoteView::Connecting:
243 #ifdef Q_WS_MAEMO_5
244         setAttribute(Qt::WA_Maemo5ShowProgressIndicator, true);
245 #endif
246         break;
247     case RemoteView::Connected:
248 #ifdef Q_WS_MAEMO_5
249         setAttribute(Qt::WA_Maemo5ShowProgressIndicator, false);
250 #endif
251         toolbar->setEnabled(true);
252
253         //disable key input buttons in view only mode
254         input_toolbuttons->setEnabled(!vnc_view->viewOnly());
255
256         vnc_view->setZoomLevel(zoom_slider->value());
257         vnc_view->useFastTransformations(false);
258         vnc_view->update();
259         break;
260     case RemoteView::Disconnecting:
261         if(old_status == RemoteView::Disconnected) //Disconnecting also occurs while connecting, so check last state
262             break;
263
264         if(disconnect_action->isEnabled()) //don't show when manually disconnecting
265             scroll_area->showMessage(tr("Connection lost"));
266
267         //clean up
268         scroll_area->setWidget(0);
269         vnc_view = 0;
270         setWindowTitle("Presence VNC");
271         disconnect_action->setEnabled(false);
272         toolbar->setEnabled(false);
273
274         //exit fullscreen mode
275         if(windowState() & Qt::WindowFullScreen)
276             setWindowState(windowState() ^ Qt::WindowFullScreen);
277         break;
278     case RemoteView::Disconnected:
279 #ifdef Q_WS_MAEMO_5
280         setAttribute(Qt::WA_Maemo5ShowProgressIndicator, false);
281 #endif
282         if(old_status == RemoteView::Disconnecting) {
283             scroll_area->setWidget(0); //remove widget
284         }
285         break;
286     default: //avoid compiler warnings
287         break;
288     }
289
290     old_status = status;
291 }
292
293 //updates available screen space for current zoom level
294 //necessary when rotating, showing fullscreen, etc.
295 void MainWindow::updateScreenSpace()
296 {
297     if(vnc_view) {
298         vnc_view->setZoomLevel();
299     }
300 }
301
302 void MainWindow::updateScreenSpaceDelayed()
303 {
304     QTimer::singleShot(500, this, SLOT(updateScreenSpace()));
305 }
306
307 void MainWindow::toggleFullscreen()
308 {
309     bool in_fullscreen = windowState() & Qt::WindowFullScreen;
310
311     //hide menu/toolbar in fullscreen (new state is !in_fullscreen)
312     toolbar->setVisible(show_toolbar->isChecked() and in_fullscreen);
313
314 #ifndef Q_WS_MAEMO_5
315     //menu bar is invisible by default on maemo
316     menuBar()->setVisible(in_fullscreen);
317 #endif
318
319     setWindowState(windowState() ^ Qt::WindowFullScreen);
320     updateScreenSpaceDelayed();
321 }
322
323 void MainWindow::showKeyMenu()
324 {
325     key_menu->exec();
326     vnc_view->sendKeySequence(key_menu->getKeySequence());
327     key_menu_button->setChecked(key_menu->isAltChecked() or key_menu->isWinChecked());
328 }
329
330 void MainWindow::showPreferences()
331 {
332     Preferences *p = new Preferences(this);
333     p->exec();
334     delete p;
335
336     reloadSettings();
337 }
338
339 void MainWindow::reloadSettings()
340 {
341     QSettings settings;
342     zoom_to_cursor = settings.value("zoom_to_cursor", true).toBool();
343
344 #ifdef Q_WS_MAEMO_5
345     int rotation = settings.value("screen_rotation", 0).toInt();
346     setAttribute(Qt::WA_Maemo5AutoOrientation, rotation == 0);
347     setAttribute(Qt::WA_Maemo5LandscapeOrientation, rotation == 1);
348     setAttribute(Qt::WA_Maemo5PortraitOrientation, rotation == 2);
349 #endif
350
351     if(vnc_view)
352         vnc_view->reloadSettings();
353 }
354
355 void MainWindow::resizeEvent(QResizeEvent *event)
356 {
357     QMainWindow::resizeEvent(event);
358
359     updateScreenSpace();
360     if(vnc_view)
361         vnc_view->setZoomLevel(zoom_slider->value());
362
363 #ifdef Q_WS_MAEMO_5
364     //hide zoom slider in portrait mode
365     zoom_slider->setVisible(height() < width());
366 #endif
367 }
368
369 void MainWindow::showInputPanel()
370 {
371 #ifdef Q_WS_MAEMO_5
372     //TODO: when hardware keyboard is open, this will only cause the IM to mess up 'real' key events
373     vnc_view->setAttribute(Qt::WA_InputMethodEnabled, true);
374     vnc_view->setInputMethodHints(Qt::ImhNoAutoUppercase); //without this, IM starts with caps lock
375
376     QEvent event(QEvent::RequestSoftwareInputPanel);
377     QApplication::sendEvent(vnc_view, &event);
378 #endif
379 }
380
381 void MainWindow::setZoomLevel(int level)
382 {
383     if(!vnc_view)
384         return;
385
386     const qreal old_factor = vnc_view->zoomFactor();
387     QPoint center = vnc_view->visibleRegion().boundingRect().center();
388
389     vnc_view->setZoomLevel(level);
390
391     const qreal new_factor = vnc_view->zoomFactor();
392
393     //scroll to center, if zoom level actually changed
394     if(old_factor != new_factor) {
395         if(zoom_to_cursor)
396             center = new_factor * vnc_view->cursorPosition();
397         else //zoom to center of visible region
398             center = center * (double(new_factor)/old_factor);
399
400         scroll_area->ensureVisible(center.x(), center.y(),
401                                    vnc_view->visibleRegion().boundingRect().width()/2,
402                                    vnc_view->visibleRegion().boundingRect().height()/2);
403
404         vnc_view->useFastTransformations(zoom_slider->isSliderDown());
405         vnc_view->update();
406
407         scroll_area->showMessage(tr("Zoom: %1\%").arg(qRound(100*new_factor)));
408     }
409 }
410
411 void MainWindow::zoomSliderReleased()
412 {
413     static QTime time;
414     if(!time.isNull() and time.elapsed() < 500) //double clicked
415         zoom_slider->setValue(95); //100%
416
417     time.restart();
418
419     //stopped zooming, reenable high quality
420     vnc_view->useFastTransformations(false);
421 }
422
423 void MainWindow::displayStateChanged(QString state)
424 {
425     const bool display_on = (state != "off");
426     if(vnc_view)
427         vnc_view->setDisplayOff(!display_on);
428 }
429
430 void MainWindow::sendTab() { vnc_view->sendKey(Qt::Key_Tab); }
431 void MainWindow::sendEsc() { vnc_view->sendKey(Qt::Key_Escape); }
432 void MainWindow::sendPgUp() { vnc_view->sendKey(Qt::Key_PageUp); }
433 void MainWindow::sendPgDn() { vnc_view->sendKey(Qt::Key_PageDown); }
434 void MainWindow::sendReturn() { vnc_view->sendKey(Qt::Key_Return); }