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