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