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