Debian Codegraph @

src/GUI/gui_funcs.cxx

raw symbols SCIP
1 /**************************************************************************
2 * gui_funcs.cxx
3 *
4 * Based on gui.cxx and renamed on 2002/08/13 by Erik Hofman.
5 *
6 * Written 1998 by Durk Talsma, started Juni, 1998. For the flight gear
7 * project.
8 *
9 * Additional mouse supported added by David Megginson, 1999.
10 *
11 * This program is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU General Public License as
13 * published by the Free Software Foundation; either version 2 of the
14 * License, or (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful, but
17 * WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
24 *
25 * $Id$
26 **************************************************************************/
27
28
29 #include "MouseCursor.hxx"
30 #ifdef HAVE_CONFIG_H
31 # include <config.h>
32 #endif
33
34 #ifdef HAVE_WINDOWS_H
35 #include <windows.h>
36 #endif
37
38 #include <simgear/compiler.h>
39
40 #include <fstream>
41 #include <string>
42 #include <cstring>
43 #include <sstream>
44
45 #include <stdlib.h>
46
47 #include <simgear/debug/logstream.hxx>
48 #include <simgear/misc/sg_path.hxx>
49 #include <simgear/screen/screen-dump.hxx>
50 #include <simgear/structure/event_mgr.hxx>
51 #include <simgear/props/props_io.hxx>
52
53 #include <Cockpit/panel.hxx>
54 #include <Main/globals.hxx>
55 #include <Main/fg_props.hxx>
56 #include <Main/fg_os.hxx>
57 #include <Viewer/renderer.hxx>
58 #include <Viewer/viewmgr.hxx>
59 #include <Viewer/WindowSystemAdapter.hxx>
60 #include <Viewer/CameraGroup.hxx>
61 #include <GUI/new_gui.hxx>
62
63
64 #ifdef _WIN32
65 # include <shellapi.h>
66 #endif
67
68 #if defined(SG_MAC)
69 # include <GUI/CocoaHelpers.h> // for cocoaOpenUrl
70 #endif
71
72 #include "gui.h"
73
74 using std::string;
75
76
77 #if defined( TR_HIRES_SNAP)
78 #include <simgear/screen/tr.h>
79 extern void fgUpdateHUD( GLfloat x_start, GLfloat y_start,
80 GLfloat x_end, GLfloat y_end );
81 #endif
82
83
84 const __fg_gui_fn_t __fg_gui_fn[] = {
85 #ifdef TR_HIRES_SNAP
86 {"dumpHiResSnapShot", fgHiResDumpWrapper},
87 #endif
88 {"dumpSnapShot", fgDumpSnapShotWrapper},
89 // Help
90 {"helpCb", helpCb},
91
92 // Structure termination
93 {"", NULL}
94 };
95
96
97 /* ================ General Purpose Functions ================ */
98
99 // General Purpose Message Box. Makes sure no more than 5 different
100 // messages are displayed at the same time, and none of them are
101 // duplicates. (5 is a *lot*, but this will hardly ever be reached
102 // and we don't want to miss any, either.)
103 void mkDialog (const char *txt)
104 {
105 auto gui = globals->get_subsystem<NewGUI>();
106 if (!gui)
107 return;
108 SGPropertyNode *master = gui->getDialogProperties("message");
109 if (!master)
110 return;
111
112 const int maxdialogs = 5;
113 string name;
114 SGPropertyNode *msg = fgGetNode("/sim/gui/dialogs", true);
115 int i;
116 for (i = 0; i < maxdialogs; i++) {
117 std::ostringstream s;
118 s << "message-" << i;
119 name = s.str();
120
121 if (!msg->getNode(name.c_str(), false))
122 break;
123
124 if (!strcmp(txt, msg->getNode(name.c_str())->getStringValue("message").c_str())) {
125 SG_LOG(SG_GENERAL, SG_WARN, "mkDialog(): duplicate of message " << txt);
126 return;
127 }
128 }
129 if (i == maxdialogs)
130 return;
131 msg = msg->getNode(name.c_str(), true);
132 msg->setStringValue("message", txt);
133 msg = msg->getNode("dialog", true);
134 copyProperties(master, msg);
135 msg->setStringValue("name", name.c_str());
136 gui->newDialog(msg);
137 gui->showDialog(name.c_str());
138 }
139
140 // Message Box to report an error.
141 void guiErrorMessage (const char *txt)
142 {
143 SG_LOG(SG_GENERAL, SG_ALERT, txt);
144 mkDialog(txt);
145 }
146
147 // Message Box to report a throwable (usually an exception).
148 void guiErrorMessage (const char *txt, const sg_throwable &throwable)
149 {
150 string msg = txt;
151 msg += '\n';
152 msg += throwable.getFormattedMessage();
153 if (std::strlen(throwable.getOrigin()) != 0) {
154 msg += "\n (reported by ";
155 msg += throwable.getOrigin();
156 msg += ')';
157 }
158 SG_LOG(SG_GENERAL, SG_ALERT, msg);
159 mkDialog(msg.c_str());
160 }
161
162
163
164 /* -----------------------------------------------------------------------
165 the Gui callback functions
166 ____________________________________________________________________*/
167
168 void helpCb()
169 {
170 openBrowser( "Docs/index.html" );
171 }
172
173 bool openBrowser(const std::string& aAddress)
174 {
175 bool ok = true;
176 string address(aAddress);
177
178 // do not resolve addresses with given protocol, i.e. "http://...", "ftp://..."
179 if (address.find("://")==string::npos)
180 {
181 // resolve local file path
182 SGPath path(address);
183 path = globals->resolve_maybe_aircraft_path(address);
184 if (!path.isNull()) {
185 address = "file://" + path.local8BitStr();
186 } else {
187 mkDialog ("Sorry, file not found!");
188 SG_LOG(SG_GENERAL, SG_ALERT, "openBrowser: Cannot find requested file '"
189 << address << "'.");
190 return false;
191 }
192 }
193
194 #ifdef SG_MAC
195 cocoaOpenUrl(address);
196 #elif defined _WIN32
197
198 // Look for favorite browser
199 char win32_name[1024];
200 # ifdef __CYGWIN__
201 cygwin32_conv_to_full_win32_path(address.c_str(),win32_name);
202 # else
203 strncpy(win32_name,address.c_str(), 1024);
204 # endif
205 ShellExecuteA(NULL, "open", win32_name, NULL, NULL,
206 SW_SHOWNORMAL);
207 #else
208 // Linux, BSD, SGI etc
209 string command = globals->get_browser();
210 string::size_type pos;
211 if ((pos = command.find("%u", 0)) != string::npos)
212 command.replace(pos, 2, address);
213 else
214 command += " \"" + address +"\"";
215
216 command += " &";
217 ok = (system( command.c_str() ) == 0);
218 #endif
219
220 if( fgGetBool("/sim/gui/show-browser-open-hint", true) )
221 mkDialog("The file is shown in your web browser window.");
222
223 return ok;
224 }
225
226 #if defined( TR_HIRES_SNAP)
227 void fgHiResDump()
228 {
229 FILE *f;
230 string message;
231 bool menu_status = fgGetBool("/sim/menubar/visibility");
232 char *filename = new char [24];
233 static unsigned short count = 1;
234
235 SGPropertyNode *master_freeze = fgGetNode("/sim/freeze/master");
236
237 bool freeze = master_freeze->getBoolValue();
238 if ( !freeze ) {
239 master_freeze->setBoolValue(true);
240 }
241
242 fgSetBool("/sim/menubar/visibility", false);
243 const auto mouse = fgGetMouseCursor();
244 fgSetMouseCursor(FGMouseCursor::CURSOR_NONE);
245
246 FGRenderer *renderer = globals->get_renderer();
247 // renderer->init();
248 renderer->resize( fgGetInt("/sim/startup/xsize"),
249 fgGetInt("/sim/startup/ysize") );
250
251 // we need two render frames here to clear the menu and cursor
252 // ... not sure why but doing an extra fgRenderFrame() shouldn't
253 // hurt anything
254 //renderer->update( true );
255 //renderer->update( true );
256
257 // This ImageSize stuff is a temporary hack
258 // should probably use 128x128 tile size and
259 // support any image size
260
261 // This should be a requester to get multiplier from user
262 int multiplier = fgGetInt("/sim/startup/hires-multiplier", 3);
263 int width = fgGetInt("/sim/startup/xsize");
264 int height = fgGetInt("/sim/startup/ysize");
265
266 /* allocate buffer large enough to store one tile */
267 GLubyte *tile = (GLubyte *)malloc(width * height * 3 * sizeof(GLubyte));
268 if (!tile) {
269 delete [] filename;
270 printf("Malloc of tile buffer failed!\n");
271 return;
272 }
273
274 int imageWidth = multiplier*width;
275 int imageHeight = multiplier*height;
276
277 /* allocate buffer to hold a row of tiles */
278 GLubyte *buffer
279 = (GLubyte *)malloc(imageWidth * height * 3 * sizeof(GLubyte));
280 if (!buffer) {
281 delete [] filename;
282 free(tile);
283 printf("Malloc of tile row buffer failed!\n");
284 return;
285 }
286 TRcontext *tr = trNew();
287 trTileSize(tr, width, height, 0);
288 trTileBuffer(tr, GL_RGB, GL_UNSIGNED_BYTE, tile);
289 trImageSize(tr, imageWidth, imageHeight);
290 trRowOrder(tr, TR_TOP_TO_BOTTOM);
291 // OSGFIXME
292 // sgFrustum *frustum = ssgGetFrustum();
293 // trFrustum(tr,
294 // frustum->getLeft(), frustum->getRight(),
295 // frustum->getBot(), frustum->getTop(),
296 // frustum->getNear(), frustum->getFar());
297
298 /* Prepare ppm output file */
299 while (count < 1000) {
300 snprintf(filename, 24, "fgfs-screen-%03d.ppm", count++);
301 if ( (f = fopen(filename, "r")) == NULL )
302 break;
303 fclose(f);
304 }
305 f = fopen(filename, "wb");
306 if (!f) {
307 printf("Couldn't open image file: %s\n", filename);
308 delete [] filename;
309 free(buffer);
310 free(tile);
311 return;
312 }
313 fprintf(f,"P6\n");
314 fprintf(f,"# ppm-file created by %s\n", "trdemo2");
315 fprintf(f,"%i %i\n", imageWidth, imageHeight);
316 fprintf(f,"255\n");
317
318 /* just to be safe... */
319 glPixelStorei(GL_PACK_ALIGNMENT, 1);
320
321 // OSGFIXME
322 #if 0
323 /* Because the HUD and Panel change the ViewPort we will
324 * need to handle some lowlevel stuff ourselves */
325 int ncols = trGet(tr, TR_COLUMNS);
326 int nrows = trGet(tr, TR_ROWS);
327
328 bool do_hud = fgGetBool("/sim/hud/visibility");
329 GLfloat hud_col_step = 640.0 / ncols;
330 GLfloat hud_row_step = 480.0 / nrows;
331
332 bool do_panel = fgPanelVisible();
333 GLfloat panel_col_step = globals->get_current_panel()->getWidth() / ncols;
334 GLfloat panel_row_step = globals->get_current_panel()->getHeight() / nrows;
335 #endif
336 glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
337 glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST);
338 glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
339 glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);
340 glHint(GL_FOG_HINT, GL_NICEST);
341
342 /* Draw tiles */
343 int more = 1;
344 while (more) {
345 trBeginTile(tr);
346 int curColumn = trGet(tr, TR_CURRENT_COLUMN);
347 // int curRow = trGet(tr, TR_CURRENT_ROW);
348
349 renderer->update();
350 // OSGFIXME
351 // if ( do_hud )
352 // fgUpdateHUD( curColumn*hud_col_step, curRow*hud_row_step,
353 // (curColumn+1)*hud_col_step, (curRow+1)*hud_row_step );
354 // OSGFIXME
355 // if (do_panel)
356 // globals->get_current_panel()->update(
357 // curColumn*panel_col_step, panel_col_step,
358 // curRow*panel_row_step, panel_row_step );
359 more = trEndTile(tr);
360
361 /* save tile into tile row buffer*/
362 int curTileWidth = trGet(tr, TR_CURRENT_TILE_WIDTH);
363 int bytesPerImageRow = imageWidth * 3*sizeof(GLubyte);
364 int bytesPerTileRow = (width) * 3*sizeof(GLubyte);
365 int xOffset = curColumn * bytesPerTileRow;
366 int bytesPerCurrentTileRow = (curTileWidth) * 3*sizeof(GLubyte);
367 int i;
368 for (i=0;i<height;i++) {
369 memcpy(buffer + i*bytesPerImageRow + xOffset, /* Dest */
370 tile + i*bytesPerTileRow, /* Src */
371 bytesPerCurrentTileRow); /* Byte count*/
372 }
373
374 if (curColumn == trGet(tr, TR_COLUMNS)-1) {
375 /* write this buffered row of tiles to the file */
376 int curTileHeight = trGet(tr, TR_CURRENT_TILE_HEIGHT);
377 int bytesPerImageRow = imageWidth * 3*sizeof(GLubyte);
378 int i;
379 for (i=0;i<curTileHeight;i++) {
380 /* Remember, OpenGL images are bottom to top. Have to reverse. */
381 GLubyte *rowPtr = buffer + (curTileHeight-1-i) * bytesPerImageRow;
382 fwrite(rowPtr, 1, imageWidth*3, f);
383 }
384 }
385
386 }
387
388 renderer->resize( width, height );
389
390 trDelete(tr);
391
392 glHint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
393 glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
394 glHint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
395 glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
396 if ( fgGetString("/sim/rendering/fog") == "disabled" ||
397 (!fgGetBool("/sim/rendering/shading"))) {
398 // if fastest fog requested, or if flat shading force fastest
399 glHint ( GL_FOG_HINT, GL_FASTEST );
400 } else if ( fgGetString("/sim/rendering/fog") == "nicest" ) {
401 glHint ( GL_FOG_HINT, GL_DONT_CARE );
402 }
403
404 fclose(f);
405
406 message = "Snapshot saved to \"";
407 message += filename;
408 message += "\".";
409 mkDialog (message.c_str());
410
411 free(tile);
412 free(buffer);
413
414 delete [] filename;
415
416 fgSetMouseCursor(mouse);
417 fgSetBool("/sim/menubar/visibility", menu_status);
418
419 if ( !freeze ) {
420 master_freeze->setBoolValue(false);
421 }
422 }
423 #endif // #if defined( TR_HIRES_SNAP)
424
425 void fgDumpSnapShotWrapper () {
426 fgDumpSnapShot();
427 }
428
429
430 void fgHiResDumpWrapper () {
431 fgHiResDump();
432 }
433
434 namespace
435 {
436 using namespace flightgear;
437
438 SGPath nextScreenshotPath(const SGPath& screenshotDir)
439 {
440 char filename[60];
441 int count = 0;
442 while (count < 100) { // 100 per second should be more than enough.
443 char time_str[20];
444 time_t calendar_time = time(NULL);
445 struct tm *tmUTC;
446 tmUTC = gmtime(&calendar_time);
447 strftime(time_str, sizeof(time_str), "%Y%m%d%H%M%S", tmUTC);
448
449 if (count)
450 snprintf(filename, 32, "fgfs-%s-%d.png", time_str, count++);
451 else
452 snprintf(filename, 32, "fgfs-%s.png", time_str);
453
454 SGPath p = screenshotDir / filename;
455 if (!p.exists()) {
456 return p;
457 }
458 }
459
460 return SGPath();
461 }
462
463 class GUISnapShotOperation :
464 public GraphicsContextOperation
465 {
466 public:
467
468 // start new snap shot
469 static bool start()
470 {
471 // allow only one snapshot at a time
472 if (_snapShotOp.valid())
473 return false;
474 _snapShotOp = new GUISnapShotOperation();
475 /* register with graphics context so actual snap shot is done
476 * in the graphics context (thread) */
477 osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
478 WindowSystemAdapter* wsa = WindowSystemAdapter::getWSA();
479 osg::GraphicsContext* gc = 0;
480 if (guiCamera)
481 gc = guiCamera->getGraphicsContext();
482 if (gc) {
483 gc->add(_snapShotOp.get());
484 } else {
485 wsa->windows[0]->gc->add(_snapShotOp.get());
486 }
487 return true;
488 }
489
490 static void cancel()
491 {
492 _snapShotOp = nullptr;
493 }
494
495 private:
496 // constructor to be executed in main loop's thread
497 GUISnapShotOperation() :
498 flightgear::GraphicsContextOperation(std::string("GUI snap shot")),
499 _master_freeze(fgGetNode("/sim/freeze/master", true)),
500 _freeze(_master_freeze->getBoolValue()),
501 _result(false),
502 _mouse(fgGetMouseCursor())
503 {
504 if (!_freeze)
505 _master_freeze->setBoolValue(true);
506
507 fgSetMouseCursor(FGMouseCursor::CURSOR_NONE);
508
509 SGPath dir = SGPath::fromUtf8(fgGetString("/sim/paths/screenshot-dir"));
510 if (dir.isNull())
511 dir = SGPath::desktop();
512
513 if (!dir.exists() && dir.create_dir( 0755 )) {
514 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot create screenshot directory '"
515 << dir << "'. Trying home directory.");
516 dir = globals->get_fg_home();
517 }
518
519 _path = nextScreenshotPath(dir);
520 _xsize = fgGetInt("/sim/startup/xsize");
521 _ysize = fgGetInt("/sim/startup/ysize");
522
523 FGRenderer *renderer = globals->get_renderer();
524 renderer->resize(_xsize, _ysize);
525 globals->get_event_mgr()->addTask("SnapShotTimer",
526 [this](){ this->timerExpired(); },
527 0.1, false);
528 }
529
530 // to be executed in graphics context (maybe separate thread)
531 void run(osg::GraphicsContext* gc)
532 {
533 std::string ps = _path.local8BitStr();
534 _result = sg_glDumpWindow(ps.c_str(),
535 _xsize,
536 _ysize);
537 }
538
539 // timer method, to be executed in main loop's thread
540 virtual void timerExpired()
541 {
542 if (isFinished())
543 {
544 globals->get_event_mgr()->removeTask("SnapShotTimer");
545
546 fgSetString("/sim/paths/screenshot-last", _path.utf8Str());
547 fgSetBool("/sim/signals/screenshot", _result);
548
549 fgSetMouseCursor(_mouse);
550
551 if ( !_freeze )
552 _master_freeze->setBoolValue(false);
553
554 _snapShotOp = 0;
555 }
556 }
557
558 static osg::ref_ptr<GUISnapShotOperation> _snapShotOp;
559 SGPropertyNode_ptr _master_freeze;
560 bool _freeze;
561 bool _result;
562 FGMouseCursor::Cursor _mouse;
563 int _xsize, _ysize;
564 SGPath _path;
565 };
566
567 } // of anonymous namespace
568
569 osg::ref_ptr<GUISnapShotOperation> GUISnapShotOperation::_snapShotOp;
570
571 // do a screen snap shot
572 bool fgDumpSnapShot ()
573 {
574 // start snap shot operation, while needs to be executed in
575 // graphics context
576 return GUISnapShotOperation::start();
577 }
578
579 void fgCancelSnapShot()
580 {
581 GUISnapShotOperation::cancel();
582 }
583
584 // do an entire scenegraph dump
585 void fgDumpSceneGraph()
586 {
587 char *filename = new char [24];
588 string message;
589 static unsigned short count = 1;
590
591 SGPropertyNode *master_freeze = fgGetNode("/sim/freeze/master");
592
593 bool freeze = master_freeze->getBoolValue();
594 if ( !freeze ) {
595 master_freeze->setBoolValue(true);
596 }
597
598 while (count < 1000) {
599 FILE *fp;
600 snprintf(filename, 24, "fgfs-graph-%03d.osg", count++);
601 if ( (fp = fopen(filename, "r")) == NULL )
602 break;
603 fclose(fp);
604 }
605
606 if ( fgDumpSceneGraphToFile(filename)) {
607 message = "Entire scene graph saved to \"";
608 message += filename;
609 message += "\".";
610 } else {
611 message = "Failed to save to \"";
612 message += filename;
613 message += "\".";
614 }
615
616 mkDialog (message.c_str());
617
618 delete [] filename;
619
620 if ( !freeze ) {
621 master_freeze->setBoolValue(false);
622 }
623 }
624
625
626 // do an terrain branch dump
627 void fgDumpTerrainBranch()
628 {
629 char *filename = new char [24];
630 string message;
631 static unsigned short count = 1;
632
633 SGPropertyNode *master_freeze = fgGetNode("/sim/freeze/master");
634
635 bool freeze = master_freeze->getBoolValue();
636 if ( !freeze ) {
637 master_freeze->setBoolValue(true);
638 }
639
640 while (count < 1000) {
641 FILE *fp;
642 snprintf(filename, 24, "fgfs-graph-%03d.osg", count++);
643 if ( (fp = fopen(filename, "r")) == NULL )
644 break;
645 fclose(fp);
646 }
647
648 if ( fgDumpTerrainBranchToFile(filename)) {
649 message = "Terrain graph saved to \"";
650 message += filename;
651 message += "\".";
652 } else {
653 message = "Failed to save to \"";
654 message += filename;
655 message += "\".";
656 }
657
658 mkDialog (message.c_str());
659
660 delete [] filename;
661
662 if ( !freeze ) {
663 master_freeze->setBoolValue(false);
664 }
665 }
666
667 void fgPrintVisibleSceneInfoCommand()
668 {
669 SGPropertyNode *master_freeze = fgGetNode("/sim/freeze/master");
670
671 bool freeze = master_freeze->getBoolValue();
672 if ( !freeze ) {
673 master_freeze->setBoolValue(true);
674 }
675
676 flightgear::printVisibleSceneInfo(globals->get_renderer());
677
678 if ( !freeze ) {
679 master_freeze->setBoolValue(false);
680 }
681 }